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