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