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