Merge branch 'partial-rewrite' into less-critical
[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.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Set;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ScheduledExecutorService;
36 import java.util.concurrent.TimeUnit;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
39
40 import net.pterodactylus.sone.core.Options.DefaultOption;
41 import net.pterodactylus.sone.core.Options.Option;
42 import net.pterodactylus.sone.core.Options.OptionWatcher;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneLockedEvent;
53 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostReply;
60 import net.pterodactylus.sone.data.Profile;
61 import net.pterodactylus.sone.data.Profile.Field;
62 import net.pterodactylus.sone.data.Reply;
63 import net.pterodactylus.sone.data.Sone;
64 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
65 import net.pterodactylus.sone.data.Sone.SoneStatus;
66 import net.pterodactylus.sone.database.PostBuilder;
67 import net.pterodactylus.sone.database.PostBuilderFactory;
68 import net.pterodactylus.sone.database.PostProvider;
69 import net.pterodactylus.sone.database.PostReplyBuilder;
70 import net.pterodactylus.sone.database.PostReplyBuilderFactory;
71 import net.pterodactylus.sone.database.PostReplyProvider;
72 import net.pterodactylus.sone.database.SoneProvider;
73 import net.pterodactylus.sone.data.TemporaryImage;
74 import net.pterodactylus.sone.fcp.FcpInterface;
75 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
76 import net.pterodactylus.sone.freenet.wot.Identity;
77 import net.pterodactylus.sone.freenet.wot.IdentityManager;
78 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
84 import net.pterodactylus.sone.main.SonePlugin;
85 import net.pterodactylus.sone.utils.IntegerRangePredicate;
86 import net.pterodactylus.util.config.Configuration;
87 import net.pterodactylus.util.config.ConfigurationException;
88 import net.pterodactylus.util.logging.Logging;
89 import net.pterodactylus.util.number.Numbers;
90 import net.pterodactylus.util.service.AbstractService;
91 import net.pterodactylus.util.thread.NamedThreadFactory;
92
93 import com.google.common.base.Function;
94 import com.google.common.base.Optional;
95 import com.google.common.base.Predicate;
96 import com.google.common.base.Predicates;
97 import com.google.common.collect.Collections2;
98 import com.google.common.collect.FluentIterable;
99 import com.google.common.collect.Ordering;
100 import com.google.common.eventbus.EventBus;
101 import com.google.common.eventbus.Subscribe;
102 import com.google.inject.Inject;
103
104 import freenet.keys.FreenetURI;
105
106 /**
107  * The Sone core.
108  *
109  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
110  */
111 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
112
113         /** The logger. */
114         private static final Logger logger = Logging.getLogger(Core.class);
115
116         /** The start time. */
117         private final long startupTime = System.currentTimeMillis();
118
119         /** The options. */
120         private final Options options = new Options();
121
122         /** The preferences. */
123         private final Preferences preferences = new Preferences(options);
124
125         /** The event bus. */
126         private final EventBus eventBus;
127
128         /** The configuration. */
129         private Configuration configuration;
130
131         /** Whether we’re currently saving the configuration. */
132         private boolean storingConfiguration = false;
133
134         /** The identity manager. */
135         private final IdentityManager identityManager;
136
137         /** Interface to freenet. */
138         private final FreenetInterface freenetInterface;
139
140         /** The Sone downloader. */
141         private final SoneDownloader soneDownloader;
142
143         /** The image inserter. */
144         private final ImageInserter imageInserter;
145
146         /** Sone downloader thread-pool. */
147         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
148
149         /** The update checker. */
150         private final UpdateChecker updateChecker;
151
152         /** The trust updater. */
153         private final WebOfTrustUpdater webOfTrustUpdater;
154
155         /** The FCP interface. */
156         private volatile FcpInterface fcpInterface;
157
158         /** The times Sones were followed. */
159         private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
160
161         /** Locked local Sones. */
162         /* synchronize on itself. */
163         private final Set<Sone> lockedSones = new HashSet<Sone>();
164
165         /** Sone inserters. */
166         /* synchronize access on this on sones. */
167         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
168
169         /** Sone rescuers. */
170         /* synchronize access on this on sones. */
171         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
172
173         /** All Sones. */
174         /* synchronize access on this on itself. */
175         private final Map<String, Sone> sones = new HashMap<String, Sone>();
176
177         /** All known Sones. */
178         private final Set<String> knownSones = new HashSet<String>();
179
180         /** The post builder. */
181         private final PostBuilderFactory postBuilderFactory;
182
183         /** All posts. */
184         private final Map<String, Post> posts = new HashMap<String, Post>();
185
186         /** All known posts. */
187         private final Set<String> knownPosts = new HashSet<String>();
188
189         /** The post reply builder factory. */
190         private final PostReplyBuilderFactory postReplyBuilderFactory;
191
192         /** All replies. */
193         private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
194
195         /** All known replies. */
196         private final Set<String> knownReplies = new HashSet<String>();
197
198         /** All bookmarked posts. */
199         /* synchronize access on itself. */
200         private final Set<String> bookmarkedPosts = new HashSet<String>();
201
202         /** Trusted identities, sorted by own identities. */
203         private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
204
205         /** All known albums. */
206         private final Map<String, Album> albums = new HashMap<String, Album>();
207
208         /** All known images. */
209         private final Map<String, Image> images = new HashMap<String, Image>();
210
211         /** All temporary images. */
212         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
213
214         /** Ticker for threads that mark own elements as known. */
215         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
216
217         /** The time the configuration was last touched. */
218         private volatile long lastConfigurationUpdate;
219
220         /**
221          * Creates a new core.
222          *
223          * @param configuration
224          *            The configuration of the core
225          * @param freenetInterface
226          *            The freenet interface
227          * @param identityManager
228          *            The identity manager
229          * @param webOfTrustUpdater
230          *            The WebOfTrust updater
231          * @param eventBus
232          *            The event bus
233          * @param postBuilderFactory
234          *            The post builder
235          * @param postReplyBuilderFactory
236          *            The post reply builder factory
237          */
238         @Inject
239         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory, PostReplyBuilderFactory postReplyBuilderFactory) {
240                 super("Sone Core");
241                 this.configuration = configuration;
242                 this.freenetInterface = freenetInterface;
243                 this.identityManager = identityManager;
244                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
245                 this.imageInserter = new ImageInserter(freenetInterface);
246                 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
247                 this.webOfTrustUpdater = webOfTrustUpdater;
248                 this.eventBus = eventBus;
249                 this.postBuilderFactory = postBuilderFactory;
250                 this.postReplyBuilderFactory = postReplyBuilderFactory;
251         }
252
253         //
254         // ACCESSORS
255         //
256
257         /**
258          * Returns the time Sone was started.
259          *
260          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
261          */
262         public long getStartupTime() {
263                 return startupTime;
264         }
265
266         /**
267          * Sets the configuration to use. This will automatically save the current
268          * configuration to the given configuration.
269          *
270          * @param configuration
271          *            The new configuration to use
272          */
273         public void setConfiguration(Configuration configuration) {
274                 this.configuration = configuration;
275                 touchConfiguration();
276         }
277
278         /**
279          * Returns the options used by the core.
280          *
281          * @return The options of the core
282          */
283         public Preferences getPreferences() {
284                 return preferences;
285         }
286
287         /**
288          * Returns the identity manager used by the core.
289          *
290          * @return The identity manager
291          */
292         public IdentityManager getIdentityManager() {
293                 return identityManager;
294         }
295
296         /**
297          * Returns the update checker.
298          *
299          * @return The update checker
300          */
301         public UpdateChecker getUpdateChecker() {
302                 return updateChecker;
303         }
304
305         /**
306          * Sets the FCP interface to use.
307          *
308          * @param fcpInterface
309          *            The FCP interface to use
310          */
311         public void setFcpInterface(FcpInterface fcpInterface) {
312                 this.fcpInterface = fcpInterface;
313         }
314
315         /**
316          * Returns the Sone rescuer for the given local Sone.
317          *
318          * @param sone
319          *            The local Sone to get the rescuer for
320          * @return The Sone rescuer for the given Sone
321          */
322         public SoneRescuer getSoneRescuer(Sone sone) {
323                 checkNotNull(sone, "sone must not be null");
324                 checkArgument(sone.isLocal(), "sone must be local");
325                 synchronized (sones) {
326                         SoneRescuer soneRescuer = soneRescuers.get(sone);
327                         if (soneRescuer == null) {
328                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
329                                 soneRescuers.put(sone, soneRescuer);
330                                 soneRescuer.start();
331                         }
332                         return soneRescuer;
333                 }
334         }
335
336         /**
337          * Returns whether the given Sone is currently locked.
338          *
339          * @param sone
340          *            The sone to check
341          * @return {@code true} if the Sone is locked, {@code false} if it is not
342          */
343         public boolean isLocked(Sone sone) {
344                 synchronized (lockedSones) {
345                         return lockedSones.contains(sone);
346                 }
347         }
348
349         /**
350          * Returns all Sones, remote and local.
351          *
352          * @return All Sones
353          */
354         public Set<Sone> getSones() {
355                 return new HashSet<Sone>(sones.values());
356         }
357
358         /**
359          * Returns the Sone with the given ID, regardless whether it’s local or
360          * remote.
361          *
362          * @param id
363          *            The ID of the Sone to get
364          * @return The Sone with the given ID, or {@code null} if there is no such
365          *         Sone
366          */
367         @Override
368         public Sone getSone(String id) {
369                 synchronized (sones) {
370                         return sones.get(id);
371                 }
372         }
373
374         /**
375          * Checks whether the core knows a Sone with the given ID.
376          *
377          * @param id
378          *            The ID of the Sone
379          * @return {@code true} if there is a Sone with the given ID, {@code false}
380          *         otherwise
381          */
382         public boolean hasSone(String id) {
383                 synchronized (sones) {
384                         return sones.containsKey(id);
385                 }
386         }
387
388         /**
389          * Returns all local Sones.
390          *
391          * @return All local Sones
392          */
393         public Collection<Sone> getLocalSones() {
394                 synchronized (sones) {
395                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
396
397                                 @Override
398                                 public boolean apply(Sone sone) {
399                                         return sone.isLocal();
400                                 }
401                         });
402                 }
403         }
404
405         /**
406          * Returns the local Sone with the given ID, optionally creating a new Sone.
407          *
408          * @param id
409          *            The ID of the Sone
410          * @param create
411          *            {@code true} to create a new Sone if none exists,
412          *            {@code false} to return null if none exists
413          * @return The Sone with the given ID, or {@code null}
414          */
415         public Sone getLocalSone(String id, boolean create) {
416                 synchronized (sones) {
417                         Sone sone = sones.get(id);
418                         if ((sone == null) && create) {
419                                 sone = new Sone(id, true);
420                                 sones.put(id, sone);
421                         }
422                         if ((sone != null) && !sone.isLocal()) {
423                                 sone = new Sone(id, true);
424                                 sones.put(id, sone);
425                         }
426                         return sone;
427                 }
428         }
429
430         /**
431          * Returns all remote Sones.
432          *
433          * @return All remote Sones
434          */
435         public Collection<Sone> getRemoteSones() {
436                 synchronized (sones) {
437                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
438
439                                 @Override
440                                 public boolean apply(Sone sone) {
441                                         return !sone.isLocal();
442                                 }
443                         });
444                 }
445         }
446
447         /**
448          * Returns the remote Sone with the given ID.
449          *
450          * @param id
451          *            The ID of the remote Sone to get
452          * @param create
453          *            {@code true} to always create a Sone, {@code false} to return
454          *            {@code null} if no Sone with the given ID exists
455          * @return The Sone with the given ID
456          */
457         public Sone getRemoteSone(String id, boolean create) {
458                 synchronized (sones) {
459                         Sone sone = sones.get(id);
460                         if ((sone == null) && create && (id != null) && (id.length() == 43)) {
461                                 sone = new Sone(id, false);
462                                 sones.put(id, sone);
463                         }
464                         return sone;
465                 }
466         }
467
468         /**
469          * Returns whether the given Sone has been modified.
470          *
471          * @param sone
472          *            The Sone to check for modifications
473          * @return {@code true} if a modification has been detected in the Sone,
474          *         {@code false} otherwise
475          */
476         public boolean isModifiedSone(Sone sone) {
477                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
478         }
479
480         /**
481          * Returns the time when the given was first followed by any local Sone.
482          *
483          * @param sone
484          *            The Sone to get the time for
485          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
486          *         been followed, or {@link Long#MAX_VALUE}
487          */
488         public long getSoneFollowingTime(Sone sone) {
489                 synchronized (soneFollowingTimes) {
490                         return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
491                 }
492         }
493
494         /**
495          * Returns whether the target Sone is trusted by the origin Sone.
496          *
497          * @param origin
498          *            The origin Sone
499          * @param target
500          *            The target Sone
501          * @return {@code true} if the target Sone is trusted by the origin Sone
502          */
503         public boolean isSoneTrusted(Sone origin, Sone target) {
504                 checkNotNull(origin, "origin must not be null");
505                 checkNotNull(target, "target must not be null");
506                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
507                 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
508         }
509
510         /**
511          * Returns a post builder.
512          *
513          * @return A new post builder
514          */
515         public PostBuilder postBuilder() {
516                 return postBuilderFactory.newPostBuilder();
517         }
518
519         /**
520          * {@inheritDoc}
521          */
522         @Override
523         public Optional<Post> getPost(String postId) {
524                 synchronized (posts) {
525                         return Optional.fromNullable(posts.get(postId));
526                 }
527         }
528
529         /**
530          * {@inheritDoc}
531          */
532         @Override
533         public Collection<Post> getDirectedPosts(final String recipientId) {
534                 checkNotNull(recipientId, "recipient must not be null");
535                 synchronized (posts) {
536                         return Collections2.filter(posts.values(), new Predicate<Post>() {
537
538                                 @Override
539                                 public boolean apply(Post post) {
540                                         return (post.getRecipient() != null) && (post.getRecipient().getId().equals(recipientId));
541                                 }
542                         });
543                 }
544         }
545         /**
546          * Returns a post reply builder.
547          *
548          * @return A new post reply builder
549          */
550         public PostReplyBuilder postReplyBuilder() {
551                 return postReplyBuilderFactory.newPostReplyBuilder();
552         }
553
554         /**
555          * {@inheritDoc}
556          */
557         @Override
558         public Optional<PostReply> getPostReply(String replyId) {
559                 synchronized (replies) {
560                         return Optional.fromNullable(replies.get(replyId));
561                 }
562         }
563
564         /**
565          * {@inheritDoc}
566          */
567         @Override
568         public List<PostReply> getReplies(final Post post) {
569                 return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(FluentIterable.from(getSones()).transformAndConcat(new Function<Sone, Iterable<PostReply>>() {
570
571                         @Override
572                         public Iterable<PostReply> apply(Sone sone) {
573                                 return sone.getReplies();
574                         }
575                 }).filter(new Predicate<PostReply>() {
576
577                         @Override
578                         public boolean apply(PostReply reply) {
579                                 return post.getId().equals(reply.getPostId());
580                         }
581                 }));
582         }
583
584         /**
585          * Returns all Sones that have liked the given post.
586          *
587          * @param post
588          *            The post to get the liking Sones for
589          * @return The Sones that like the given post
590          */
591         public Set<Sone> getLikes(Post post) {
592                 Set<Sone> sones = new HashSet<Sone>();
593                 for (Sone sone : getSones()) {
594                         if (sone.getLikedPostIds().contains(post.getId())) {
595                                 sones.add(sone);
596                         }
597                 }
598                 return sones;
599         }
600
601         /**
602          * Returns all Sones that have liked the given reply.
603          *
604          * @param reply
605          *            The reply to get the liking Sones for
606          * @return The Sones that like the given reply
607          */
608         public Set<Sone> getLikes(PostReply reply) {
609                 Set<Sone> sones = new HashSet<Sone>();
610                 for (Sone sone : getSones()) {
611                         if (sone.getLikedReplyIds().contains(reply.getId())) {
612                                 sones.add(sone);
613                         }
614                 }
615                 return sones;
616         }
617
618         /**
619          * Returns whether the given post is bookmarked.
620          *
621          * @param post
622          *            The post to check
623          * @return {@code true} if the given post is bookmarked, {@code false}
624          *         otherwise
625          */
626         public boolean isBookmarked(Post post) {
627                 return isPostBookmarked(post.getId());
628         }
629
630         /**
631          * Returns whether the post with the given ID is bookmarked.
632          *
633          * @param id
634          *            The ID of the post to check
635          * @return {@code true} if the post with the given ID is bookmarked,
636          *         {@code false} otherwise
637          */
638         public boolean isPostBookmarked(String id) {
639                 synchronized (bookmarkedPosts) {
640                         return bookmarkedPosts.contains(id);
641                 }
642         }
643
644         /**
645          * Returns all currently known bookmarked posts.
646          *
647          * @return All bookmarked posts
648          */
649         public Set<Post> getBookmarkedPosts() {
650                 Set<Post> posts = new HashSet<Post>();
651                 synchronized (bookmarkedPosts) {
652                         for (String bookmarkedPostId : bookmarkedPosts) {
653                                 Optional<Post> post = getPost(bookmarkedPostId);
654                                 if (!post.isPresent()) {
655                                         posts.add(post.get());
656                                 }
657                         }
658                 }
659                 return posts;
660         }
661
662         /**
663          * Returns the album with the given ID, creating a new album if no album
664          * with the given ID can be found.
665          *
666          * @param albumId
667          *            The ID of the album
668          * @return The album with the given ID
669          */
670         public Album getAlbum(String albumId) {
671                 return getAlbum(albumId, true);
672         }
673
674         /**
675          * Returns the album with the given ID, optionally creating a new album if
676          * an album with the given ID can not be found.
677          *
678          * @param albumId
679          *            The ID of the album
680          * @param create
681          *            {@code true} to create a new album if none exists for the
682          *            given ID
683          * @return The album with the given ID, or {@code null} if no album with the
684          *         given ID exists and {@code create} is {@code false}
685          */
686         public Album getAlbum(String albumId, boolean create) {
687                 synchronized (albums) {
688                         Album album = albums.get(albumId);
689                         if (create && (album == null)) {
690                                 album = new Album(albumId);
691                                 albums.put(albumId, album);
692                         }
693                         return album;
694                 }
695         }
696
697         /**
698          * Returns the image with the given ID, creating it if necessary.
699          *
700          * @param imageId
701          *            The ID of the image
702          * @return The image with the given ID
703          */
704         public Image getImage(String imageId) {
705                 return getImage(imageId, true);
706         }
707
708         /**
709          * Returns the image with the given ID, optionally creating it if it does
710          * not exist.
711          *
712          * @param imageId
713          *            The ID of the image
714          * @param create
715          *            {@code true} to create an image if none exists with the given
716          *            ID
717          * @return The image with the given ID, or {@code null} if none exists and
718          *         none was created
719          */
720         public Image getImage(String imageId, boolean create) {
721                 synchronized (images) {
722                         Image image = images.get(imageId);
723                         if (create && (image == null)) {
724                                 image = new Image(imageId);
725                                 images.put(imageId, image);
726                         }
727                         return image;
728                 }
729         }
730
731         /**
732          * Returns the temporary image with the given ID.
733          *
734          * @param imageId
735          *            The ID of the temporary image
736          * @return The temporary image, or {@code null} if there is no temporary
737          *         image with the given ID
738          */
739         public TemporaryImage getTemporaryImage(String imageId) {
740                 synchronized (temporaryImages) {
741                         return temporaryImages.get(imageId);
742                 }
743         }
744
745         //
746         // ACTIONS
747         //
748
749         /**
750          * Locks the given Sone. A locked Sone will not be inserted by
751          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
752          * again.
753          *
754          * @param sone
755          *            The sone to lock
756          */
757         public void lockSone(Sone sone) {
758                 synchronized (lockedSones) {
759                         if (lockedSones.add(sone)) {
760                                 eventBus.post(new SoneLockedEvent(sone));
761                         }
762                 }
763         }
764
765         /**
766          * Unlocks the given Sone.
767          *
768          * @see #lockSone(Sone)
769          * @param sone
770          *            The sone to unlock
771          */
772         public void unlockSone(Sone sone) {
773                 synchronized (lockedSones) {
774                         if (lockedSones.remove(sone)) {
775                                 eventBus.post(new SoneUnlockedEvent(sone));
776                         }
777                 }
778         }
779
780         /**
781          * Adds a local Sone from the given own identity.
782          *
783          * @param ownIdentity
784          *            The own identity to create a Sone from
785          * @return The added (or already existing) Sone
786          */
787         public Sone addLocalSone(OwnIdentity ownIdentity) {
788                 if (ownIdentity == null) {
789                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
790                         return null;
791                 }
792                 synchronized (sones) {
793                         final Sone sone;
794                         try {
795                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
796                         } catch (MalformedURLException mue1) {
797                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
798                                 return null;
799                         }
800                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
801                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
802                         sone.setKnown(true);
803                         /* TODO - load posts ’n stuff */
804                         sones.put(ownIdentity.getId(), sone);
805                         final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
806                         soneInserters.put(sone, soneInserter);
807                         sone.setStatus(SoneStatus.idle);
808                         loadSone(sone);
809                         soneInserter.start();
810                         return sone;
811                 }
812         }
813
814         /**
815          * Creates a new Sone for the given own identity.
816          *
817          * @param ownIdentity
818          *            The own identity to create a Sone for
819          * @return The created Sone
820          */
821         public Sone createSone(OwnIdentity ownIdentity) {
822                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
823                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
824                         return null;
825                 }
826                 Sone sone = addLocalSone(ownIdentity);
827                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
828                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
829                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
830                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
831                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
832                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
833
834                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
835                 touchConfiguration();
836                 return sone;
837         }
838
839         /**
840          * Adds the Sone of the given identity.
841          *
842          * @param identity
843          *            The identity whose Sone to add
844          * @return The added or already existing Sone
845          */
846         public Sone addRemoteSone(Identity identity) {
847                 if (identity == null) {
848                         logger.log(Level.WARNING, "Given Identity is null!");
849                         return null;
850                 }
851                 synchronized (sones) {
852                         final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
853                         boolean newSone = sone.getRequestUri() == null;
854                         sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
855                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
856                         if (newSone) {
857                                 synchronized (knownSones) {
858                                         newSone = !knownSones.contains(sone.getId());
859                                 }
860                                 sone.setKnown(!newSone);
861                                 if (newSone) {
862                                         eventBus.post(new NewSoneFoundEvent(sone));
863                                         for (Sone localSone : getLocalSones()) {
864                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
865                                                         followSone(localSone, sone.getId());
866                                                 }
867                                         }
868                                 }
869                         }
870                         soneDownloader.addSone(sone);
871                         soneDownloaders.execute(new Runnable() {
872
873                                 @Override
874                                 @SuppressWarnings("synthetic-access")
875                                 public void run() {
876                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
877                                 }
878
879                         });
880                         return sone;
881                 }
882         }
883
884         /**
885          * Lets the given local Sone follow the Sone with the given ID.
886          *
887          * @param sone
888          *            The local Sone that should follow another Sone
889          * @param soneId
890          *            The ID of the Sone to follow
891          */
892         public void followSone(Sone sone, String soneId) {
893                 checkNotNull(sone, "sone must not be null");
894                 checkNotNull(soneId, "soneId must not be null");
895                 sone.addFriend(soneId);
896                 synchronized (soneFollowingTimes) {
897                         if (!soneFollowingTimes.containsKey(soneId)) {
898                                 long now = System.currentTimeMillis();
899                                 soneFollowingTimes.put(soneId, now);
900                                 Sone followedSone = getSone(soneId);
901                                 if (followedSone == null) {
902                                         return;
903                                 }
904                                 for (Post post : followedSone.getPosts()) {
905                                         if (post.getTime() < now) {
906                                                 markPostKnown(post);
907                                         }
908                                 }
909                                 for (PostReply reply : followedSone.getReplies()) {
910                                         if (reply.getTime() < now) {
911                                                 markReplyKnown(reply);
912                                         }
913                                 }
914                         }
915                 }
916                 touchConfiguration();
917         }
918
919         /**
920          * Lets the given local Sone unfollow the Sone with the given ID.
921          *
922          * @param sone
923          *            The local Sone that should unfollow another Sone
924          * @param soneId
925          *            The ID of the Sone being unfollowed
926          */
927         public void unfollowSone(Sone sone, String soneId) {
928                 checkNotNull(sone, "sone must not be null");
929                 checkNotNull(soneId, "soneId must not be null");
930                 sone.removeFriend(soneId);
931                 boolean unfollowedSoneStillFollowed = false;
932                 for (Sone localSone : getLocalSones()) {
933                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
934                 }
935                 if (!unfollowedSoneStillFollowed) {
936                         synchronized (soneFollowingTimes) {
937                                 soneFollowingTimes.remove(soneId);
938                         }
939                 }
940                 touchConfiguration();
941         }
942
943         /**
944          * Sets the trust value of the given origin Sone for the target Sone.
945          *
946          * @param origin
947          *            The origin Sone
948          * @param target
949          *            The target Sone
950          * @param trustValue
951          *            The trust value (from {@code -100} to {@code 100})
952          */
953         public void setTrust(Sone origin, Sone target, int trustValue) {
954                 checkNotNull(origin, "origin must not be null");
955                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
956                 checkNotNull(target, "target must not be null");
957                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
958                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
959         }
960
961         /**
962          * Removes any trust assignment for the given target Sone.
963          *
964          * @param origin
965          *            The trust origin
966          * @param target
967          *            The trust target
968          */
969         public void removeTrust(Sone origin, Sone target) {
970                 checkNotNull(origin, "origin must not be null");
971                 checkNotNull(target, "target must not be null");
972                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
973                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
974         }
975
976         /**
977          * Assigns the configured positive trust value for the given target.
978          *
979          * @param origin
980          *            The trust origin
981          * @param target
982          *            The trust target
983          */
984         public void trustSone(Sone origin, Sone target) {
985                 setTrust(origin, target, preferences.getPositiveTrust());
986         }
987
988         /**
989          * Assigns the configured negative trust value for the given target.
990          *
991          * @param origin
992          *            The trust origin
993          * @param target
994          *            The trust target
995          */
996         public void distrustSone(Sone origin, Sone target) {
997                 setTrust(origin, target, preferences.getNegativeTrust());
998         }
999
1000         /**
1001          * Removes the trust assignment for the given target.
1002          *
1003          * @param origin
1004          *            The trust origin
1005          * @param target
1006          *            The trust target
1007          */
1008         public void untrustSone(Sone origin, Sone target) {
1009                 removeTrust(origin, target);
1010         }
1011
1012         /**
1013          * Updates the stored Sone with the given Sone.
1014          *
1015          * @param sone
1016          *            The updated Sone
1017          */
1018         public void updateSone(Sone sone) {
1019                 updateSone(sone, false);
1020         }
1021
1022         /**
1023          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1024          * {@code true}, an older Sone than the current Sone can be given to restore
1025          * an old state.
1026          *
1027          * @param sone
1028          *            The Sone to update
1029          * @param soneRescueMode
1030          *            {@code true} if the stored Sone should be updated regardless
1031          *            of the age of the given Sone
1032          */
1033         public void updateSone(Sone sone, boolean soneRescueMode) {
1034                 if (hasSone(sone.getId())) {
1035                         Sone storedSone = getSone(sone.getId());
1036                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1037                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1038                                 return;
1039                         }
1040                         synchronized (posts) {
1041                                 if (!soneRescueMode) {
1042                                         for (Post post : storedSone.getPosts()) {
1043                                                 posts.remove(post.getId());
1044                                                 if (!sone.getPosts().contains(post)) {
1045                                                         eventBus.post(new PostRemovedEvent(post));
1046                                                 }
1047                                         }
1048                                 }
1049                                 List<Post> storedPosts = storedSone.getPosts();
1050                                 synchronized (knownPosts) {
1051                                         for (Post post : sone.getPosts()) {
1052                                                 post.setKnown(knownPosts.contains(post.getId()));
1053                                                 if (!storedPosts.contains(post)) {
1054                                                         if (post.getTime() < getSoneFollowingTime(sone)) {
1055                                                                 knownPosts.add(post.getId());
1056                                                                 post.setKnown(true);
1057                                                         } else if (!knownPosts.contains(post.getId())) {
1058                                                                 eventBus.post(new NewPostFoundEvent(post));
1059                                                         }
1060                                                 }
1061                                                 posts.put(post.getId(), post);
1062                                         }
1063                                 }
1064                         }
1065                         synchronized (replies) {
1066                                 if (!soneRescueMode) {
1067                                         for (PostReply reply : storedSone.getReplies()) {
1068                                                 replies.remove(reply.getId());
1069                                                 if (!sone.getReplies().contains(reply)) {
1070                                                         eventBus.post(new PostReplyRemovedEvent(reply));
1071                                                 }
1072                                         }
1073                                 }
1074                                 Set<PostReply> storedReplies = storedSone.getReplies();
1075                                 synchronized (knownReplies) {
1076                                         for (PostReply reply : sone.getReplies()) {
1077                                                 reply.setKnown(knownReplies.contains(reply.getId()));
1078                                                 if (!storedReplies.contains(reply)) {
1079                                                         if (reply.getTime() < getSoneFollowingTime(sone)) {
1080                                                                 knownReplies.add(reply.getId());
1081                                                                 reply.setKnown(true);
1082                                                         } else if (!knownReplies.contains(reply.getId())) {
1083                                                                 eventBus.post(new NewPostReplyFoundEvent(reply));
1084                                                         }
1085                                                 }
1086                                                 replies.put(reply.getId(), reply);
1087                                         }
1088                                 }
1089                         }
1090                         synchronized (albums) {
1091                                 synchronized (images) {
1092                                         for (Album album : storedSone.getAlbums()) {
1093                                                 albums.remove(album.getId());
1094                                                 for (Image image : album.getImages()) {
1095                                                         images.remove(image.getId());
1096                                                 }
1097                                         }
1098                                         for (Album album : sone.getAlbums()) {
1099                                                 albums.put(album.getId(), album);
1100                                                 for (Image image : album.getImages()) {
1101                                                         images.put(image.getId(), image);
1102                                                 }
1103                                         }
1104                                 }
1105                         }
1106                         synchronized (sones) {
1107                                 sones.put(sone.getId(), sone);
1108                         }
1109                 }
1110         }
1111
1112         /**
1113          * Deletes the given Sone. This will remove the Sone from the
1114          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1115          * remove the context from its identity.
1116          *
1117          * @param sone
1118          *            The Sone to delete
1119          */
1120         public void deleteSone(Sone sone) {
1121                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1122                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1123                         return;
1124                 }
1125                 synchronized (sones) {
1126                         if (!getLocalSones().contains(sone)) {
1127                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1128                                 return;
1129                         }
1130                         sones.remove(sone.getId());
1131                         SoneInserter soneInserter = soneInserters.remove(sone);
1132                         soneInserter.stop();
1133                 }
1134                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1135                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1136                 try {
1137                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1138                 } catch (ConfigurationException ce1) {
1139                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1140                 }
1141         }
1142
1143         /**
1144          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1145          * known} before, a {@link MarkSoneKnownEvent} is fired.
1146          *
1147          * @param sone
1148          *            The Sone to mark as known
1149          */
1150         public void markSoneKnown(Sone sone) {
1151                 if (!sone.isKnown()) {
1152                         sone.setKnown(true);
1153                         synchronized (knownSones) {
1154                                 knownSones.add(sone.getId());
1155                         }
1156                         eventBus.post(new MarkSoneKnownEvent(sone));
1157                         touchConfiguration();
1158                 }
1159         }
1160
1161         /**
1162          * Loads and updates the given Sone from the configuration. If any error is
1163          * encountered, loading is aborted and the given Sone is not changed.
1164          *
1165          * @param sone
1166          *            The Sone to load and update
1167          */
1168         public void loadSone(Sone sone) {
1169                 if (!sone.isLocal()) {
1170                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1171                         return;
1172                 }
1173
1174                 /* initialize options. */
1175                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1176                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1177                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1178                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1179                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1180                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1181
1182                 /* load Sone. */
1183                 String sonePrefix = "Sone/" + sone.getId();
1184                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1185                 if (soneTime == null) {
1186                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1187                         return;
1188                 }
1189                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1190
1191                 /* load profile. */
1192                 Profile profile = new Profile(sone);
1193                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1194                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1195                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1196                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1197                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1198                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1199
1200                 /* load profile fields. */
1201                 while (true) {
1202                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1203                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1204                         if (fieldName == null) {
1205                                 break;
1206                         }
1207                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1208                         profile.addField(fieldName).setValue(fieldValue);
1209                 }
1210
1211                 /* load posts. */
1212                 Set<Post> posts = new HashSet<Post>();
1213                 while (true) {
1214                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1215                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1216                         if (postId == null) {
1217                                 break;
1218                         }
1219                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1220                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1221                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1222                         if ((postTime == 0) || (postText == null)) {
1223                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1224                                 return;
1225                         }
1226                         PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1227                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1228                                 postBuilder.to(postRecipientId);
1229                         }
1230                         posts.add(postBuilder.build());
1231                 }
1232
1233                 /* load replies. */
1234                 Set<PostReply> replies = new HashSet<PostReply>();
1235                 while (true) {
1236                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1237                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1238                         if (replyId == null) {
1239                                 break;
1240                         }
1241                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1242                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1243                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1244                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1245                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1246                                 return;
1247                         }
1248                         PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1249                         postReplyBuilder.withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1250                         replies.add(postReplyBuilder.build());
1251                 }
1252
1253                 /* load post likes. */
1254                 Set<String> likedPostIds = new HashSet<String>();
1255                 while (true) {
1256                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1257                         if (likedPostId == null) {
1258                                 break;
1259                         }
1260                         likedPostIds.add(likedPostId);
1261                 }
1262
1263                 /* load reply likes. */
1264                 Set<String> likedReplyIds = new HashSet<String>();
1265                 while (true) {
1266                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1267                         if (likedReplyId == null) {
1268                                 break;
1269                         }
1270                         likedReplyIds.add(likedReplyId);
1271                 }
1272
1273                 /* load friends. */
1274                 Set<String> friends = new HashSet<String>();
1275                 while (true) {
1276                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1277                         if (friendId == null) {
1278                                 break;
1279                         }
1280                         friends.add(friendId);
1281                 }
1282
1283                 /* load albums. */
1284                 List<Album> topLevelAlbums = new ArrayList<Album>();
1285                 int albumCounter = 0;
1286                 while (true) {
1287                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1288                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1289                         if (albumId == null) {
1290                                 break;
1291                         }
1292                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1293                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1294                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1295                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1296                         if ((albumTitle == null) || (albumDescription == null)) {
1297                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1298                                 return;
1299                         }
1300                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1301                         if (albumParentId != null) {
1302                                 Album parentAlbum = getAlbum(albumParentId, false);
1303                                 if (parentAlbum == null) {
1304                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1305                                         return;
1306                                 }
1307                                 parentAlbum.addAlbum(album);
1308                         } else {
1309                                 if (!topLevelAlbums.contains(album)) {
1310                                         topLevelAlbums.add(album);
1311                                 }
1312                         }
1313                 }
1314
1315                 /* load images. */
1316                 int imageCounter = 0;
1317                 while (true) {
1318                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1319                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1320                         if (imageId == null) {
1321                                 break;
1322                         }
1323                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1324                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1325                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1326                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1327                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1328                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1329                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1330                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1331                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1332                                 return;
1333                         }
1334                         Album album = getAlbum(albumId, false);
1335                         if (album == null) {
1336                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1337                                 return;
1338                         }
1339                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1340                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1341                         album.addImage(image);
1342                 }
1343
1344                 /* load avatar. */
1345                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1346                 if (avatarId != null) {
1347                         profile.setAvatar(getImage(avatarId, false));
1348                 }
1349
1350                 /* load options. */
1351                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1352                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1353                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1354                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1355                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1356                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1357
1358                 /* if we’re still here, Sone was loaded successfully. */
1359                 synchronized (sone) {
1360                         sone.setTime(soneTime);
1361                         sone.setProfile(profile);
1362                         sone.setPosts(posts);
1363                         sone.setReplies(replies);
1364                         sone.setLikePostIds(likedPostIds);
1365                         sone.setLikeReplyIds(likedReplyIds);
1366                         for (String friendId : friends) {
1367                                 followSone(sone, friendId);
1368                         }
1369                         sone.setAlbums(topLevelAlbums);
1370                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1371                 }
1372                 synchronized (knownSones) {
1373                         for (String friend : friends) {
1374                                 knownSones.add(friend);
1375                         }
1376                 }
1377                 synchronized (knownPosts) {
1378                         for (Post post : posts) {
1379                                 knownPosts.add(post.getId());
1380                         }
1381                 }
1382                 synchronized (knownReplies) {
1383                         for (PostReply reply : replies) {
1384                                 knownReplies.add(reply.getId());
1385                         }
1386                 }
1387         }
1388
1389         /**
1390          * Creates a new post.
1391          *
1392          * @param sone
1393          *            The Sone that creates the post
1394          * @param text
1395          *            The text of the post
1396          * @return The created post
1397          */
1398         public Post createPost(Sone sone, String text) {
1399                 return createPost(sone, System.currentTimeMillis(), text);
1400         }
1401
1402         /**
1403          * Creates a new post.
1404          *
1405          * @param sone
1406          *            The Sone that creates the post
1407          * @param time
1408          *            The time of the post
1409          * @param text
1410          *            The text of the post
1411          * @return The created post
1412          */
1413         public Post createPost(Sone sone, long time, String text) {
1414                 return createPost(sone, null, time, text);
1415         }
1416
1417         /**
1418          * Creates a new post.
1419          *
1420          * @param sone
1421          *            The Sone that creates the post
1422          * @param recipient
1423          *            The recipient Sone, or {@code null} if this post does not have
1424          *            a recipient
1425          * @param text
1426          *            The text of the post
1427          * @return The created post
1428          */
1429         public Post createPost(Sone sone, Sone recipient, String text) {
1430                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1431         }
1432
1433         /**
1434          * Creates a new post.
1435          *
1436          * @param sone
1437          *            The Sone that creates the post
1438          * @param recipient
1439          *            The recipient Sone, or {@code null} if this post does not have
1440          *            a recipient
1441          * @param time
1442          *            The time of the post
1443          * @param text
1444          *            The text of the post
1445          * @return The created post
1446          */
1447         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1448                 checkNotNull(text, "text must not be null");
1449                 checkArgument(text.trim().length() > 0, "text must not be empty");
1450                 if (!sone.isLocal()) {
1451                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1452                         return null;
1453                 }
1454                 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1455                 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1456                 if (recipient != null) {
1457                         postBuilder.to(recipient.getId());
1458                 }
1459                 final Post post = postBuilder.build();
1460                 synchronized (posts) {
1461                         posts.put(post.getId(), post);
1462                 }
1463                 eventBus.post(new NewPostFoundEvent(post));
1464                 sone.addPost(post);
1465                 touchConfiguration();
1466                 localElementTicker.schedule(new Runnable() {
1467
1468                         /**
1469                          * {@inheritDoc}
1470                          */
1471                         @Override
1472                         public void run() {
1473                                 markPostKnown(post);
1474                         }
1475                 }, 10, TimeUnit.SECONDS);
1476                 return post;
1477         }
1478
1479         /**
1480          * Deletes the given post.
1481          *
1482          * @param post
1483          *            The post to delete
1484          */
1485         public void deletePost(Post post) {
1486                 if (!post.getSone().isLocal()) {
1487                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1488                         return;
1489                 }
1490                 post.getSone().removePost(post);
1491                 synchronized (posts) {
1492                         posts.remove(post.getId());
1493                 }
1494                 eventBus.post(new PostRemovedEvent(post));
1495                 markPostKnown(post);
1496                 touchConfiguration();
1497         }
1498
1499         /**
1500          * Marks the given post as known, if it is currently not a known post
1501          * (according to {@link Post#isKnown()}).
1502          *
1503          * @param post
1504          *            The post to mark as known
1505          */
1506         public void markPostKnown(Post post) {
1507                 post.setKnown(true);
1508                 synchronized (knownPosts) {
1509                         eventBus.post(new MarkPostKnownEvent(post));
1510                         if (knownPosts.add(post.getId())) {
1511                                 touchConfiguration();
1512                         }
1513                 }
1514                 for (PostReply reply : getReplies(post)) {
1515                         markReplyKnown(reply);
1516                 }
1517         }
1518
1519         /**
1520          * Bookmarks the given post.
1521          *
1522          * @param post
1523          *            The post to bookmark
1524          */
1525         public void bookmark(Post post) {
1526                 bookmarkPost(post.getId());
1527         }
1528
1529         /**
1530          * Bookmarks the post with the given ID.
1531          *
1532          * @param id
1533          *            The ID of the post to bookmark
1534          */
1535         public void bookmarkPost(String id) {
1536                 synchronized (bookmarkedPosts) {
1537                         bookmarkedPosts.add(id);
1538                 }
1539         }
1540
1541         /**
1542          * Removes the given post from the bookmarks.
1543          *
1544          * @param post
1545          *            The post to unbookmark
1546          */
1547         public void unbookmark(Post post) {
1548                 unbookmarkPost(post.getId());
1549         }
1550
1551         /**
1552          * Removes the post with the given ID from the bookmarks.
1553          *
1554          * @param id
1555          *            The ID of the post to unbookmark
1556          */
1557         public void unbookmarkPost(String id) {
1558                 synchronized (bookmarkedPosts) {
1559                         bookmarkedPosts.remove(id);
1560                 }
1561         }
1562
1563         /**
1564          * Creates a new reply.
1565          *
1566          * @param sone
1567          *            The Sone that creates the reply
1568          * @param post
1569          *            The post that this reply refers to
1570          * @param text
1571          *            The text of the reply
1572          * @return The created reply
1573          */
1574         public PostReply createReply(Sone sone, Post post, String text) {
1575                 checkNotNull(text, "text must not be null");
1576                 checkArgument(text.trim().length() > 0, "text must not be empty");
1577                 if (!sone.isLocal()) {
1578                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1579                         return null;
1580                 }
1581                 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1582                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1583                 final PostReply reply = postReplyBuilder.build();
1584                 synchronized (replies) {
1585                         replies.put(reply.getId(), reply);
1586                 }
1587                 synchronized (knownReplies) {
1588                         eventBus.post(new NewPostReplyFoundEvent(reply));
1589                 }
1590                 sone.addReply(reply);
1591                 touchConfiguration();
1592                 localElementTicker.schedule(new Runnable() {
1593
1594                         /**
1595                          * {@inheritDoc}
1596                          */
1597                         @Override
1598                         public void run() {
1599                                 markReplyKnown(reply);
1600                         }
1601                 }, 10, TimeUnit.SECONDS);
1602                 return reply;
1603         }
1604
1605         /**
1606          * Deletes the given reply.
1607          *
1608          * @param reply
1609          *            The reply to delete
1610          */
1611         public void deleteReply(PostReply reply) {
1612                 Sone sone = reply.getSone();
1613                 if (!sone.isLocal()) {
1614                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1615                         return;
1616                 }
1617                 synchronized (replies) {
1618                         replies.remove(reply.getId());
1619                 }
1620                 synchronized (knownReplies) {
1621                         markReplyKnown(reply);
1622                         knownReplies.remove(reply.getId());
1623                 }
1624                 sone.removeReply(reply);
1625                 touchConfiguration();
1626         }
1627
1628         /**
1629          * Marks the given reply as known, if it is currently not a known reply
1630          * (according to {@link Reply#isKnown()}).
1631          *
1632          * @param reply
1633          *            The reply to mark as known
1634          */
1635         public void markReplyKnown(PostReply reply) {
1636                 reply.setKnown(true);
1637                 synchronized (knownReplies) {
1638                         eventBus.post(new MarkPostReplyKnownEvent(reply));
1639                         if (knownReplies.add(reply.getId())) {
1640                                 touchConfiguration();
1641                         }
1642                 }
1643         }
1644
1645         /**
1646          * Creates a new top-level album for the given Sone.
1647          *
1648          * @param sone
1649          *            The Sone to create the album for
1650          * @return The new album
1651          */
1652         public Album createAlbum(Sone sone) {
1653                 return createAlbum(sone, null);
1654         }
1655
1656         /**
1657          * Creates a new album for the given Sone.
1658          *
1659          * @param sone
1660          *            The Sone to create the album for
1661          * @param parent
1662          *            The parent of the album (may be {@code null} to create a
1663          *            top-level album)
1664          * @return The new album
1665          */
1666         public Album createAlbum(Sone sone, Album parent) {
1667                 Album album = new Album();
1668                 synchronized (albums) {
1669                         albums.put(album.getId(), album);
1670                 }
1671                 album.setSone(sone);
1672                 if (parent != null) {
1673                         parent.addAlbum(album);
1674                 } else {
1675                         sone.addAlbum(album);
1676                 }
1677                 return album;
1678         }
1679
1680         /**
1681          * Deletes the given album. The owner of the album has to be a local Sone,
1682          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1683          *
1684          * @param album
1685          *            The album to remove
1686          */
1687         public void deleteAlbum(Album album) {
1688                 checkNotNull(album, "album must not be null");
1689                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1690                 if (!album.isEmpty()) {
1691                         return;
1692                 }
1693                 if (album.getParent() == null) {
1694                         album.getSone().removeAlbum(album);
1695                 } else {
1696                         album.getParent().removeAlbum(album);
1697                 }
1698                 synchronized (albums) {
1699                         albums.remove(album.getId());
1700                 }
1701                 touchConfiguration();
1702         }
1703
1704         /**
1705          * Creates a new image.
1706          *
1707          * @param sone
1708          *            The Sone creating the image
1709          * @param album
1710          *            The album the image will be inserted into
1711          * @param temporaryImage
1712          *            The temporary image to create the image from
1713          * @return The newly created image
1714          */
1715         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1716                 checkNotNull(sone, "sone must not be null");
1717                 checkNotNull(album, "album must not be null");
1718                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1719                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1720                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1721                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1722                 album.addImage(image);
1723                 synchronized (images) {
1724                         images.put(image.getId(), image);
1725                 }
1726                 imageInserter.insertImage(temporaryImage, image);
1727                 return image;
1728         }
1729
1730         /**
1731          * Deletes the given image. This method will also delete a matching
1732          * temporary image.
1733          *
1734          * @see #deleteTemporaryImage(TemporaryImage)
1735          * @param image
1736          *            The image to delete
1737          */
1738         public void deleteImage(Image image) {
1739                 checkNotNull(image, "image must not be null");
1740                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1741                 deleteTemporaryImage(image.getId());
1742                 image.getAlbum().removeImage(image);
1743                 synchronized (images) {
1744                         images.remove(image.getId());
1745                 }
1746                 touchConfiguration();
1747         }
1748
1749         /**
1750          * Creates a new temporary image.
1751          *
1752          * @param mimeType
1753          *            The MIME type of the temporary image
1754          * @param imageData
1755          *            The encoded data of the image
1756          * @return The temporary image
1757          */
1758         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1759                 TemporaryImage temporaryImage = new TemporaryImage();
1760                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1761                 synchronized (temporaryImages) {
1762                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1763                 }
1764                 return temporaryImage;
1765         }
1766
1767         /**
1768          * Deletes the given temporary image.
1769          *
1770          * @param temporaryImage
1771          *            The temporary image to delete
1772          */
1773         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1774                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1775                 deleteTemporaryImage(temporaryImage.getId());
1776         }
1777
1778         /**
1779          * Deletes the temporary image with the given ID.
1780          *
1781          * @param imageId
1782          *            The ID of the temporary image to delete
1783          */
1784         public void deleteTemporaryImage(String imageId) {
1785                 checkNotNull(imageId, "imageId must not be null");
1786                 synchronized (temporaryImages) {
1787                         temporaryImages.remove(imageId);
1788                 }
1789                 Image image = getImage(imageId, false);
1790                 if (image != null) {
1791                         imageInserter.cancelImageInsert(image);
1792                 }
1793         }
1794
1795         /**
1796          * Notifies the core that the configuration, either of the core or of a
1797          * single local Sone, has changed, and that the configuration should be
1798          * saved.
1799          */
1800         public void touchConfiguration() {
1801                 lastConfigurationUpdate = System.currentTimeMillis();
1802         }
1803
1804         //
1805         // SERVICE METHODS
1806         //
1807
1808         /**
1809          * Starts the core.
1810          */
1811         @Override
1812         public void serviceStart() {
1813                 loadConfiguration();
1814                 updateChecker.start();
1815                 identityManager.start();
1816                 webOfTrustUpdater.init();
1817                 webOfTrustUpdater.start();
1818         }
1819
1820         /**
1821          * {@inheritDoc}
1822          */
1823         @Override
1824         public void serviceRun() {
1825                 long lastSaved = System.currentTimeMillis();
1826                 while (!shouldStop()) {
1827                         sleep(1000);
1828                         long now = System.currentTimeMillis();
1829                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1830                                 for (Sone localSone : getLocalSones()) {
1831                                         saveSone(localSone);
1832                                 }
1833                                 saveConfiguration();
1834                                 lastSaved = now;
1835                         }
1836                 }
1837         }
1838
1839         /**
1840          * Stops the core.
1841          */
1842         @Override
1843         public void serviceStop() {
1844                 localElementTicker.shutdownNow();
1845                 synchronized (sones) {
1846                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1847                                 soneInserter.getValue().stop();
1848                                 saveSone(soneInserter.getKey());
1849                         }
1850                 }
1851                 saveConfiguration();
1852                 webOfTrustUpdater.stop();
1853                 updateChecker.stop();
1854                 soneDownloader.stop();
1855                 soneDownloaders.shutdown();
1856                 identityManager.stop();
1857         }
1858
1859         //
1860         // PRIVATE METHODS
1861         //
1862
1863         /**
1864          * Saves the given Sone. This will persist all local settings for the given
1865          * Sone, such as the friends list and similar, private options.
1866          *
1867          * @param sone
1868          *            The Sone to save
1869          */
1870         private synchronized void saveSone(Sone sone) {
1871                 if (!sone.isLocal()) {
1872                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1873                         return;
1874                 }
1875                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1876                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1877                         return;
1878                 }
1879
1880                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1881                 try {
1882                         /* save Sone into configuration. */
1883                         String sonePrefix = "Sone/" + sone.getId();
1884                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1885                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1886
1887                         /* save profile. */
1888                         Profile profile = sone.getProfile();
1889                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1890                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1891                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1892                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1893                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1894                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1895                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1896
1897                         /* save profile fields. */
1898                         int fieldCounter = 0;
1899                         for (Field profileField : profile.getFields()) {
1900                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1901                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1902                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1903                         }
1904                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1905
1906                         /* save posts. */
1907                         int postCounter = 0;
1908                         for (Post post : sone.getPosts()) {
1909                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1910                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1911                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1912                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1913                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1914                         }
1915                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1916
1917                         /* save replies. */
1918                         int replyCounter = 0;
1919                         for (PostReply reply : sone.getReplies()) {
1920                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1921                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1922                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1923                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1924                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1925                         }
1926                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1927
1928                         /* save post likes. */
1929                         int postLikeCounter = 0;
1930                         for (String postId : sone.getLikedPostIds()) {
1931                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1932                         }
1933                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1934
1935                         /* save reply likes. */
1936                         int replyLikeCounter = 0;
1937                         for (String replyId : sone.getLikedReplyIds()) {
1938                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1939                         }
1940                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1941
1942                         /* save friends. */
1943                         int friendCounter = 0;
1944                         for (String friendId : sone.getFriends()) {
1945                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1946                         }
1947                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1948
1949                         /* save albums. first, collect in a flat structure, top-level first. */
1950                         List<Album> albums = sone.getAllAlbums();
1951
1952                         int albumCounter = 0;
1953                         for (Album album : albums) {
1954                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1955                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1956                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1957                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1958                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1959                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1960                         }
1961                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1962
1963                         /* save images. */
1964                         int imageCounter = 0;
1965                         for (Album album : albums) {
1966                                 for (Image image : album.getImages()) {
1967                                         if (!image.isInserted()) {
1968                                                 continue;
1969                                         }
1970                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1971                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1972                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1973                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1974                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1975                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1976                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1977                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1978                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1979                                 }
1980                         }
1981                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1982
1983                         /* save options. */
1984                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1985                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1986                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1987                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1988                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1989                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1990
1991                         configuration.save();
1992
1993                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1994
1995                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1996                 } catch (ConfigurationException ce1) {
1997                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1998                 }
1999         }
2000
2001         /**
2002          * Saves the current options.
2003          */
2004         private void saveConfiguration() {
2005                 synchronized (configuration) {
2006                         if (storingConfiguration) {
2007                                 logger.log(Level.FINE, "Already storing configuration…");
2008                                 return;
2009                         }
2010                         storingConfiguration = true;
2011                 }
2012
2013                 /* store the options first. */
2014                 try {
2015                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2016                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2017                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2018                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2019                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2020                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2021                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2022                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2023                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2024                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2025                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2026                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2027
2028                         /* save known Sones. */
2029                         int soneCounter = 0;
2030                         synchronized (knownSones) {
2031                                 for (String knownSoneId : knownSones) {
2032                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2033                                 }
2034                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2035                         }
2036
2037                         /* save Sone following times. */
2038                         soneCounter = 0;
2039                         synchronized (soneFollowingTimes) {
2040                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2041                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
2042                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2043                                         ++soneCounter;
2044                                 }
2045                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2046                         }
2047
2048                         /* save known posts. */
2049                         int postCounter = 0;
2050                         synchronized (knownPosts) {
2051                                 for (String knownPostId : knownPosts) {
2052                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2053                                 }
2054                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2055                         }
2056
2057                         /* save known replies. */
2058                         int replyCounter = 0;
2059                         synchronized (knownReplies) {
2060                                 for (String knownReplyId : knownReplies) {
2061                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2062                                 }
2063                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2064                         }
2065
2066                         /* save bookmarked posts. */
2067                         int bookmarkedPostCounter = 0;
2068                         synchronized (bookmarkedPosts) {
2069                                 for (String bookmarkedPostId : bookmarkedPosts) {
2070                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2071                                 }
2072                         }
2073                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2074
2075                         /* now save it. */
2076                         configuration.save();
2077
2078                 } catch (ConfigurationException ce1) {
2079                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2080                 } finally {
2081                         synchronized (configuration) {
2082                                 storingConfiguration = false;
2083                         }
2084                 }
2085         }
2086
2087         /**
2088          * Loads the configuration.
2089          */
2090         @SuppressWarnings("unchecked")
2091         private void loadConfiguration() {
2092                 /* create options. */
2093                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2094
2095                         @Override
2096                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2097                                 SoneInserter.setInsertionDelay(newValue);
2098                         }
2099
2100                 }));
2101                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2102                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2103                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2104                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2105                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2106                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2107                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2108                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2109                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2110
2111                         @Override
2112                         @SuppressWarnings("synthetic-access")
2113                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2114                                 fcpInterface.setActive(newValue);
2115                         }
2116                 }));
2117                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2118
2119                         @Override
2120                         @SuppressWarnings("synthetic-access")
2121                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2122                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2123                         }
2124
2125                 }));
2126
2127                 loadConfigurationValue("InsertionDelay");
2128                 loadConfigurationValue("PostsPerPage");
2129                 loadConfigurationValue("ImagesPerPage");
2130                 loadConfigurationValue("CharactersPerPost");
2131                 loadConfigurationValue("PostCutOffLength");
2132                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2133                 loadConfigurationValue("PositiveTrust");
2134                 loadConfigurationValue("NegativeTrust");
2135                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2136                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2137                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2138
2139                 /* load known Sones. */
2140                 int soneCounter = 0;
2141                 while (true) {
2142                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2143                         if (knownSoneId == null) {
2144                                 break;
2145                         }
2146                         synchronized (knownSones) {
2147                                 knownSones.add(knownSoneId);
2148                         }
2149                 }
2150
2151                 /* load Sone following times. */
2152                 soneCounter = 0;
2153                 while (true) {
2154                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2155                         if (soneId == null) {
2156                                 break;
2157                         }
2158                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2159                         Sone followedSone = getSone(soneId);
2160                         if (followedSone == null) {
2161                                 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2162                         } else {
2163                                 synchronized (soneFollowingTimes) {
2164                                         soneFollowingTimes.put(soneId, time);
2165                                 }
2166                         }
2167                         ++soneCounter;
2168                 }
2169
2170                 /* load known posts. */
2171                 int postCounter = 0;
2172                 while (true) {
2173                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2174                         if (knownPostId == null) {
2175                                 break;
2176                         }
2177                         synchronized (knownPosts) {
2178                                 knownPosts.add(knownPostId);
2179                         }
2180                 }
2181
2182                 /* load known replies. */
2183                 int replyCounter = 0;
2184                 while (true) {
2185                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2186                         if (knownReplyId == null) {
2187                                 break;
2188                         }
2189                         synchronized (knownReplies) {
2190                                 knownReplies.add(knownReplyId);
2191                         }
2192                 }
2193
2194                 /* load bookmarked posts. */
2195                 int bookmarkedPostCounter = 0;
2196                 while (true) {
2197                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2198                         if (bookmarkedPostId == null) {
2199                                 break;
2200                         }
2201                         synchronized (bookmarkedPosts) {
2202                                 bookmarkedPosts.add(bookmarkedPostId);
2203                         }
2204                 }
2205
2206         }
2207
2208         /**
2209          * Loads an {@link Integer} configuration value for the option with the
2210          * given name, logging validation failures.
2211          *
2212          * @param optionName
2213          *            The name of the option to load
2214          */
2215         private void loadConfigurationValue(String optionName) {
2216                 try {
2217                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2218                 } catch (IllegalArgumentException iae1) {
2219                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2220                 }
2221         }
2222
2223         /**
2224          * Notifies the core that a new {@link OwnIdentity} was added.
2225          *
2226          * @param ownIdentityAddedEvent
2227          *            The event
2228          */
2229         @Subscribe
2230         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2231                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2232                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2233                 if (ownIdentity.hasContext("Sone")) {
2234                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2235                         addLocalSone(ownIdentity);
2236                 }
2237         }
2238
2239         /**
2240          * Notifies the core that an {@link OwnIdentity} was removed.
2241          *
2242          * @param ownIdentityRemovedEvent
2243          *            The event
2244          */
2245         @Subscribe
2246         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2247                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2248                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2249                 trustedIdentities.remove(ownIdentity);
2250         }
2251
2252         /**
2253          * Notifies the core that a new {@link Identity} was added.
2254          *
2255          * @param identityAddedEvent
2256          *            The event
2257          */
2258         @Subscribe
2259         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2260                 Identity identity = identityAddedEvent.identity();
2261                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2262                 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2263                 addRemoteSone(identity);
2264         }
2265
2266         /**
2267          * Notifies the core that an {@link Identity} was updated.
2268          *
2269          * @param identityUpdatedEvent
2270          *            The event
2271          */
2272         @Subscribe
2273         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2274                 final Identity identity = identityUpdatedEvent.identity();
2275                 soneDownloaders.execute(new Runnable() {
2276
2277                         @Override
2278                         @SuppressWarnings("synthetic-access")
2279                         public void run() {
2280                                 Sone sone = getRemoteSone(identity.getId(), false);
2281                                 sone.setIdentity(identity);
2282                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2283                                 soneDownloader.addSone(sone);
2284                                 soneDownloader.fetchSone(sone);
2285                         }
2286                 });
2287         }
2288
2289         /**
2290          * Notifies the core that an {@link Identity} was removed.
2291          *
2292          * @param identityRemovedEvent
2293          *            The event
2294          */
2295         @Subscribe
2296         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2297                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2298                 Identity identity = identityRemovedEvent.identity();
2299                 trustedIdentities.get(ownIdentity).remove(identity);
2300                 boolean foundIdentity = false;
2301                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2302                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2303                                 continue;
2304                         }
2305                         if (trustedIdentity.getValue().contains(identity)) {
2306                                 foundIdentity = true;
2307                         }
2308                 }
2309                 if (foundIdentity) {
2310                         /* some local identity still trusts this identity, don’t remove. */
2311                         return;
2312                 }
2313                 Sone sone = getSone(identity.getId());
2314                 if (sone == null) {
2315                         /* TODO - we don’t have the Sone anymore. should this happen? */
2316                         return;
2317                 }
2318                 synchronized (posts) {
2319                         synchronized (knownPosts) {
2320                                 for (Post post : sone.getPosts()) {
2321                                         posts.remove(post.getId());
2322                                         eventBus.post(new PostRemovedEvent(post));
2323                                 }
2324                         }
2325                 }
2326                 synchronized (replies) {
2327                         synchronized (knownReplies) {
2328                                 for (PostReply reply : sone.getReplies()) {
2329                                         replies.remove(reply.getId());
2330                                         eventBus.post(new PostReplyRemovedEvent(reply));
2331                                 }
2332                         }
2333                 }
2334                 synchronized (sones) {
2335                         sones.remove(identity.getId());
2336                 }
2337                 eventBus.post(new SoneRemovedEvent(sone));
2338         }
2339
2340         /**
2341          * Deletes the temporary image.
2342          *
2343          * @param imageInsertFinishedEvent
2344          *            The event
2345          */
2346         @Subscribe
2347         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2348                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2349                 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2350                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2351                 touchConfiguration();
2352         }
2353
2354 }