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