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