Remove updated time setter from Sone, store update time in database.
[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.util.logging.Logger.getLogger;
25
26 import java.util.ArrayList;
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.SoneChangeDetector.PostProcessor;
42 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
53 import net.pterodactylus.sone.core.event.SoneLockedEvent;
54 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
55 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
56 import net.pterodactylus.sone.data.Album;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.LocalSone;
59 import net.pterodactylus.sone.data.Post;
60 import net.pterodactylus.sone.data.PostReply;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.SoneStatus;
64 import net.pterodactylus.sone.data.TemporaryImage;
65 import net.pterodactylus.sone.database.AlbumBuilder;
66 import net.pterodactylus.sone.database.Database;
67 import net.pterodactylus.sone.database.DatabaseException;
68 import net.pterodactylus.sone.database.ImageBuilder;
69 import net.pterodactylus.sone.database.PostBuilder;
70 import net.pterodactylus.sone.database.PostProvider;
71 import net.pterodactylus.sone.database.PostReplyBuilder;
72 import net.pterodactylus.sone.database.PostReplyProvider;
73 import net.pterodactylus.sone.database.SoneBuilder;
74 import net.pterodactylus.sone.database.SoneProvider;
75 import net.pterodactylus.sone.freenet.wot.Identity;
76 import net.pterodactylus.sone.freenet.wot.IdentityManager;
77 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
83 import net.pterodactylus.util.config.Configuration;
84 import net.pterodactylus.util.config.ConfigurationException;
85 import net.pterodactylus.util.service.AbstractService;
86 import net.pterodactylus.util.thread.NamedThreadFactory;
87
88 import com.google.common.annotations.VisibleForTesting;
89 import com.google.common.base.Function;
90 import com.google.common.base.Optional;
91 import com.google.common.collect.HashMultimap;
92 import com.google.common.collect.Multimap;
93 import com.google.common.collect.Multimaps;
94 import com.google.common.eventbus.EventBus;
95 import com.google.common.eventbus.Subscribe;
96 import com.google.inject.Inject;
97 import com.google.inject.Singleton;
98
99 /**
100  * The Sone core.
101  *
102  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
103  */
104 @Singleton
105 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
106
107         /** The logger. */
108         private static final Logger logger = getLogger("Sone.Core");
109
110         /** The start time. */
111         private final long startupTime = System.currentTimeMillis();
112
113         /** The preferences. */
114         private final Preferences preferences;
115
116         /** The event bus. */
117         private final EventBus eventBus;
118
119         /** The configuration. */
120         private final Configuration configuration;
121
122         /** Whether we’re currently saving the configuration. */
123         private boolean storingConfiguration = false;
124
125         /** The identity manager. */
126         private final IdentityManager identityManager;
127
128         /** Interface to freenet. */
129         private final FreenetInterface freenetInterface;
130
131         /** The Sone downloader. */
132         private final SoneDownloader soneDownloader;
133
134         /** The image inserter. */
135         private final ImageInserter imageInserter;
136
137         /** Sone downloader thread-pool. */
138         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
139
140         /** The update checker. */
141         private final UpdateChecker updateChecker;
142
143         /** The trust updater. */
144         private final WebOfTrustUpdater webOfTrustUpdater;
145
146         /** Locked local Sones. */
147         /* synchronize on itself. */
148         private final Set<LocalSone> lockedSones = new HashSet<LocalSone>();
149
150         /** Sone inserters. */
151         /* synchronize access on this on sones. */
152         private final Map<LocalSone, SoneInserter> soneInserters = new HashMap<LocalSone, SoneInserter>();
153
154         /** Sone rescuers. */
155         /* synchronize access on this on sones. */
156         private final Map<LocalSone, SoneRescuer> soneRescuers = new HashMap<LocalSone, SoneRescuer>();
157
158         /** The post database. */
159         private final Database database;
160
161         /** Trusted identities, sorted by own identities. */
162         private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
163
164         /** All temporary images. */
165         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
166
167         /** Ticker for threads that mark own elements as known. */
168         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
169
170         /** The time the configuration was last touched. */
171         private volatile long lastConfigurationUpdate;
172
173         /**
174          * Creates a new core.
175          *
176          * @param configuration
177          *            The configuration of the core
178          * @param freenetInterface
179          *            The freenet interface
180          * @param identityManager
181          *            The identity manager
182          * @param webOfTrustUpdater
183          *            The WebOfTrust updater
184          * @param eventBus
185          *            The event bus
186          * @param database
187          *            The database
188          */
189         @Inject
190         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
191                 super("Sone Core");
192                 this.configuration = configuration;
193                 this.freenetInterface = freenetInterface;
194                 this.identityManager = identityManager;
195                 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
196                 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
197                 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
198                 this.webOfTrustUpdater = webOfTrustUpdater;
199                 this.eventBus = eventBus;
200                 this.database = database;
201                 preferences = new Preferences(eventBus);
202         }
203
204         @VisibleForTesting
205         protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
206                 super("Sone Core");
207                 this.configuration = configuration;
208                 this.freenetInterface = freenetInterface;
209                 this.identityManager = identityManager;
210                 this.soneDownloader = soneDownloader;
211                 this.imageInserter = imageInserter;
212                 this.updateChecker = updateChecker;
213                 this.webOfTrustUpdater = webOfTrustUpdater;
214                 this.eventBus = eventBus;
215                 this.database = database;
216                 preferences = new Preferences(eventBus);
217         }
218
219         //
220         // ACCESSORS
221         //
222
223         /**
224          * Returns the time Sone was started.
225          *
226          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
227          */
228         public long getStartupTime() {
229                 return startupTime;
230         }
231
232         /**
233          * Returns the options used by the core.
234          *
235          * @return The options of the core
236          */
237         public Preferences getPreferences() {
238                 return preferences;
239         }
240
241         /**
242          * Returns the identity manager used by the core.
243          *
244          * @return The identity manager
245          */
246         public IdentityManager getIdentityManager() {
247                 return identityManager;
248         }
249
250         /**
251          * Returns the update checker.
252          *
253          * @return The update checker
254          */
255         public UpdateChecker getUpdateChecker() {
256                 return updateChecker;
257         }
258
259         /**
260          * Returns the Sone rescuer for the given local Sone.
261          *
262          * @param sone
263          *            The local Sone to get the rescuer for
264          * @return The Sone rescuer for the given Sone
265          */
266         public SoneRescuer getSoneRescuer(LocalSone sone) {
267                 checkNotNull(sone, "sone must not be null");
268                 synchronized (soneRescuers) {
269                         SoneRescuer soneRescuer = soneRescuers.get(sone);
270                         if (soneRescuer == null) {
271                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
272                                 soneRescuers.put(sone, soneRescuer);
273                                 soneRescuer.start();
274                         }
275                         return soneRescuer;
276                 }
277         }
278
279         /**
280          * Returns whether the given Sone is currently locked.
281          *
282          * @param sone
283          *            The sone to check
284          * @return {@code true} if the Sone is locked, {@code false} if it is not
285          */
286         public boolean isLocked(LocalSone sone) {
287                 synchronized (lockedSones) {
288                         return lockedSones.contains(sone);
289                 }
290         }
291
292         public SoneBuilder soneBuilder() {
293                 return database.newSoneBuilder();
294         }
295
296         /**
297          * {@inheritDocs}
298          */
299         @Override
300         public Collection<Sone> getSones() {
301                 return database.getSones();
302         }
303
304         @Override
305         public Function<String, Optional<Sone>> soneLoader() {
306                 return database.soneLoader();
307         }
308
309         /**
310          * Returns the Sone with the given ID, regardless whether it’s local or
311          * remote.
312          *
313          * @param id
314          *            The ID of the Sone to get
315          * @return The Sone with the given ID, or {@code null} if there is no such
316          *         Sone
317          */
318         @Override
319         public Optional<Sone> getSone(String id) {
320                 return database.getSone(id);
321         }
322
323         @Override
324         public Collection<LocalSone> getLocalSones() {
325                 return database.getLocalSones();
326         }
327
328         public Optional<LocalSone> getLocalSone(String id) {
329                 return database.getLocalSone(id);
330         }
331
332         /**
333          * {@inheritDocs}
334          */
335         @Override
336         public Collection<Sone> getRemoteSones() {
337                 return database.getRemoteSones();
338         }
339
340         /**
341          * Returns the remote Sone with the given ID.
342          *
343          *
344          * @param id
345          *            The ID of the remote Sone to get
346          * @return The Sone with the given ID
347          */
348         public Sone getRemoteSone(String id) {
349                 return database.getSone(id).orNull();
350         }
351
352         /**
353          * Returns whether the given Sone has been modified.
354          *
355          * @param sone
356          *            The Sone to check for modifications
357          * @return {@code true} if a modification has been detected in the Sone,
358          *         {@code false} otherwise
359          */
360         public boolean isModifiedSone(LocalSone sone) {
361                 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
362         }
363
364         /**
365          * Returns the time when the given was first followed by any local Sone.
366          *
367          * @param sone
368          *            The Sone to get the time for
369          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
370          *         been followed, or {@link Long#MAX_VALUE}
371          */
372         public long getSoneFollowingTime(Sone sone) {
373                 return database.getSoneFollowingTime(sone.getId()).or(Long.MAX_VALUE);
374         }
375
376         /**
377          * Returns a post builder.
378          *
379          * @return A new post builder
380          */
381         public PostBuilder postBuilder() {
382                 return database.newPostBuilder();
383         }
384
385         /**
386          * {@inheritDoc}
387          */
388         @Override
389         public Optional<Post> getPost(String postId) {
390                 return database.getPost(postId);
391         }
392
393         /**
394          * {@inheritDocs}
395          */
396         @Override
397         public Collection<Post> getPosts(String soneId) {
398                 return database.getPosts(soneId);
399         }
400
401         /**
402          * {@inheritDoc}
403          */
404         @Override
405         public Collection<Post> getDirectedPosts(final String recipientId) {
406                 checkNotNull(recipientId, "recipient must not be null");
407                 return database.getDirectedPosts(recipientId);
408         }
409
410         /**
411          * Returns a post reply builder.
412          *
413          * @return A new post reply builder
414          */
415         public PostReplyBuilder postReplyBuilder() {
416                 return database.newPostReplyBuilder();
417         }
418
419         /**
420          * {@inheritDoc}
421          */
422         @Override
423         public Optional<PostReply> getPostReply(String replyId) {
424                 return database.getPostReply(replyId);
425         }
426
427         /**
428          * {@inheritDoc}
429          */
430         @Override
431         public List<PostReply> getReplies(final String postId) {
432                 return database.getReplies(postId);
433         }
434
435         /**
436          * Returns all Sones that have liked the given post.
437          *
438          * @param post
439          *            The post to get the liking Sones for
440          * @return The Sones that like the given post
441          */
442         public Set<Sone> getLikes(Post post) {
443                 Set<Sone> sones = new HashSet<Sone>();
444                 for (Sone sone : getSones()) {
445                         if (sone.getLikedPostIds().contains(post.getId())) {
446                                 sones.add(sone);
447                         }
448                 }
449                 return sones;
450         }
451
452         /**
453          * Returns all Sones that have liked the given reply.
454          *
455          * @param reply
456          *            The reply to get the liking Sones for
457          * @return The Sones that like the given reply
458          */
459         public Set<Sone> getLikes(PostReply reply) {
460                 Set<Sone> sones = new HashSet<Sone>();
461                 for (Sone sone : getSones()) {
462                         if (sone.getLikedReplyIds().contains(reply.getId())) {
463                                 sones.add(sone);
464                         }
465                 }
466                 return sones;
467         }
468
469         /**
470          * Returns whether the given post is bookmarked.
471          *
472          * @param post
473          *            The post to check
474          * @return {@code true} if the given post is bookmarked, {@code false}
475          *         otherwise
476          */
477         public boolean isBookmarked(Post post) {
478                 return database.isPostBookmarked(post);
479         }
480
481         /**
482          * Returns all currently known bookmarked posts.
483          *
484          * @return All bookmarked posts
485          */
486         public Set<Post> getBookmarkedPosts() {
487                 return database.getBookmarkedPosts();
488         }
489
490         public AlbumBuilder albumBuilder() {
491                 return database.newAlbumBuilder();
492         }
493
494         /**
495          * Returns the album with the given ID, optionally creating a new album if
496          * an album with the given ID can not be found.
497          *
498          * @param albumId
499          *            The ID of the album
500          * @return The album with the given ID, or {@code null} if no album with the
501          *         given ID exists
502          */
503         public Album getAlbum(String albumId) {
504                 return database.getAlbum(albumId).orNull();
505         }
506
507         public ImageBuilder imageBuilder() {
508                 return database.newImageBuilder();
509         }
510
511         /**
512          * Returns the image with the given ID, creating it if necessary.
513          *
514          * @param imageId
515          *            The ID of the image
516          * @return The image with the given ID
517          */
518         public Image getImage(String imageId) {
519                 return getImage(imageId, true);
520         }
521
522         /**
523          * Returns the image with the given ID, optionally creating it if it does
524          * not exist.
525          *
526          * @param imageId
527          *            The ID of the image
528          * @param create
529          *            {@code true} to create an image if none exists with the given
530          *            ID
531          * @return The image with the given ID, or {@code null} if none exists and
532          *         none was created
533          */
534         public Image getImage(String imageId, boolean create) {
535                 Optional<Image> image = database.getImage(imageId);
536                 if (image.isPresent()) {
537                         return image.get();
538                 }
539                 if (!create) {
540                         return null;
541                 }
542                 Image newImage = database.newImageBuilder().withId(imageId).build();
543                 database.storeImage(newImage);
544                 return newImage;
545         }
546
547         /**
548          * Returns the temporary image with the given ID.
549          *
550          * @param imageId
551          *            The ID of the temporary image
552          * @return The temporary image, or {@code null} if there is no temporary
553          *         image with the given ID
554          */
555         public TemporaryImage getTemporaryImage(String imageId) {
556                 synchronized (temporaryImages) {
557                         return temporaryImages.get(imageId);
558                 }
559         }
560
561         //
562         // ACTIONS
563         //
564
565         /**
566          * Locks the given Sone. A locked Sone will not be inserted by
567          * {@link SoneInserter} until it is {@link #unlockSone(LocalSone) unlocked}
568          * again.
569          *
570          * @param sone
571          *            The sone to lock
572          */
573         public void lockSone(LocalSone sone) {
574                 synchronized (lockedSones) {
575                         if (lockedSones.add(sone)) {
576                                 eventBus.post(new SoneLockedEvent(sone));
577                         }
578                 }
579         }
580
581         /**
582          * Unlocks the given Sone.
583          *
584          * @see #lockSone(LocalSone)
585          * @param sone
586          *            The sone to unlock
587          */
588         public void unlockSone(LocalSone sone) {
589                 synchronized (lockedSones) {
590                         if (lockedSones.remove(sone)) {
591                                 eventBus.post(new SoneUnlockedEvent(sone));
592                         }
593                 }
594         }
595
596         /**
597          * Adds a local Sone from the given own identity.
598          *
599          * @param ownIdentity
600          *            The own identity to create a Sone from
601          * @return The added (or already existing) Sone
602          */
603         public LocalSone addLocalSone(OwnIdentity ownIdentity) {
604                 if (ownIdentity == null) {
605                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
606                         return null;
607                 }
608                 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
609                 LocalSone sone = database.registerLocalSone(ownIdentity);
610                 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, database, ownIdentity.getId());
611                 eventBus.register(soneInserter);
612                 synchronized (soneInserters) {
613                         soneInserters.put(sone, soneInserter);
614                 }
615                 synchronized (soneInserters) {
616                         soneInserters.get(sone).setLastInsertFingerprint(database.getLastInsertFingerprint(sone));
617                 }
618                 sone.setStatus(SoneStatus.idle);
619                 soneInserter.start();
620                 return sone;
621         }
622
623         /**
624          * Creates a new Sone for the given own identity.
625          *
626          * @param ownIdentity
627          *            The own identity to create a Sone for
628          * @return The created Sone
629          */
630         public Sone createSone(OwnIdentity ownIdentity) {
631                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
632                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
633                         return null;
634                 }
635                 LocalSone sone = addLocalSone(ownIdentity);
636
637                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
638                 touchConfiguration();
639                 return sone;
640         }
641
642         /**
643          * Adds the Sone of the given identity.
644          *
645          * @param identity
646          *            The identity whose Sone to add
647          * @return The added or already existing Sone
648          */
649         public Sone addRemoteSone(Identity identity) {
650                 if (identity == null) {
651                         logger.log(Level.WARNING, "Given Identity is null!");
652                         return null;
653                 }
654                 final Long latestEdition = tryParse(fromNullable(
655                                 identity.getProperty("Sone.LatestEdition")).or("0"));
656                 Optional<Sone> existingSone = getSone(identity.getId());
657                 if (existingSone.isPresent() && existingSone.get().isLocal()) {
658                         return existingSone.get();
659                 }
660                 boolean newSone = !existingSone.isPresent();
661                 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
662                 sone.setLatestEdition(latestEdition);
663                 if (newSone) {
664                         newSone = !database.isSoneKnown(sone);
665                         sone.setKnown(!newSone);
666                         if (newSone) {
667                                 eventBus.post(new NewSoneFoundEvent(sone));
668                                 for (LocalSone localSone : getLocalSones()) {
669                                         if (localSone.getOptions().isAutoFollow()) {
670                                                 followSone(localSone, sone.getId());
671                                         }
672                                 }
673                         }
674                 }
675                 database.storeSone(sone);
676                 soneDownloader.addSone(sone);
677                 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
678                 return sone;
679         }
680
681         /**
682          * Lets the given local Sone follow the Sone with the given ID.
683          *
684          * @param sone
685          *            The local Sone that should follow another Sone
686          * @param soneId
687          *            The ID of the Sone to follow
688          */
689         public void followSone(LocalSone sone, String soneId) {
690                 checkNotNull(sone, "sone must not be null");
691                 checkNotNull(soneId, "soneId must not be null");
692                 boolean newFriend = !database.getSoneFollowingTime(soneId).isPresent();
693                 database.addFriend(sone, soneId);
694                 if (newFriend) {
695                         long now = System.currentTimeMillis();
696                         Optional<Sone> followedSone = getSone(soneId);
697                         if (!followedSone.isPresent()) {
698                                 return;
699                         }
700                         for (Post post : followedSone.get().getPosts()) {
701                                 if (post.getTime() < now) {
702                                         markPostKnown(post);
703                                 }
704                         }
705                         for (PostReply reply : followedSone.get().getReplies()) {
706                                 if (reply.getTime() < now) {
707                                         markReplyKnown(reply);
708                                 }
709                         }
710                 }
711         }
712
713         /**
714          * Lets the given local Sone unfollow the Sone with the given ID.
715          *
716          * @param sone
717          *            The local Sone that should unfollow another Sone
718          * @param soneId
719          *            The ID of the Sone being unfollowed
720          */
721         public void unfollowSone(LocalSone sone, String soneId) {
722                 checkNotNull(sone, "sone must not be null");
723                 checkNotNull(soneId, "soneId must not be null");
724                 database.removeFriend(sone, soneId);
725         }
726
727         /**
728          * Sets the trust value of the given origin Sone for the target Sone.
729          *
730          * @param origin
731          *            The origin Sone
732          * @param target
733          *            The target Sone
734          * @param trustValue
735          *            The trust value (from {@code -100} to {@code 100})
736          */
737         public void setTrust(Sone origin, Sone target, int trustValue) {
738                 checkNotNull(origin, "origin must not be null");
739                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
740                 checkNotNull(target, "target must not be null");
741                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
742                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
743         }
744
745         /**
746          * Removes any trust assignment for the given target Sone.
747          *
748          * @param origin
749          *            The trust origin
750          * @param target
751          *            The trust target
752          */
753         public void removeTrust(Sone origin, Sone target) {
754                 checkNotNull(origin, "origin must not be null");
755                 checkNotNull(target, "target must not be null");
756                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
757                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
758         }
759
760         /**
761          * Assigns the configured positive trust value for the given target.
762          *
763          * @param origin
764          *            The trust origin
765          * @param target
766          *            The trust target
767          */
768         public void trustSone(Sone origin, Sone target) {
769                 setTrust(origin, target, preferences.getPositiveTrust());
770         }
771
772         /**
773          * Assigns the configured negative trust value for the given target.
774          *
775          * @param origin
776          *            The trust origin
777          * @param target
778          *            The trust target
779          */
780         public void distrustSone(Sone origin, Sone target) {
781                 setTrust(origin, target, preferences.getNegativeTrust());
782         }
783
784         /**
785          * Removes the trust assignment for the given target.
786          *
787          * @param origin
788          *            The trust origin
789          * @param target
790          *            The trust target
791          */
792         public void untrustSone(Sone origin, Sone target) {
793                 removeTrust(origin, target);
794         }
795
796         /**
797          * Updates the stored Sone with the given Sone.
798          *
799          * @param sone
800          *            The updated Sone
801          */
802         public void updateSone(Sone sone) {
803                 updateSone(sone, false);
804         }
805
806         /**
807          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
808          * {@code true}, an older Sone than the current Sone can be given to restore
809          * an old state.
810          *
811          * @param sone
812          *            The Sone to update
813          * @param soneRescueMode
814          *            {@code true} if the stored Sone should be updated regardless
815          *            of the age of the given Sone
816          */
817         public void updateSone(final Sone sone, boolean soneRescueMode) {
818                 Optional<Sone> storedSone = getSone(sone.getId());
819                 if (storedSone.isPresent()) {
820                         if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
821                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
822                                 return;
823                         }
824                         List<Object> events =
825                                         collectEventsForChangesInSone(storedSone.get(), sone);
826                         database.storeSone(sone);
827                         for (Object event : events) {
828                                 eventBus.post(event);
829                         }
830                         sone.setOptions(storedSone.get().getOptions());
831                         sone.setKnown(storedSone.get().isKnown());
832                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
833                         if (sone.isLocal()) {
834                                 touchConfiguration();
835                         }
836                 }
837         }
838
839         private List<Object> collectEventsForChangesInSone(Sone oldSone,
840                         final Sone newSone) {
841                 final List<Object> events = new ArrayList<Object>();
842                 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
843                                 oldSone);
844                 soneChangeDetector.onNewPosts(new PostProcessor() {
845                         @Override
846                         public void processPost(Post post) {
847                                 if (post.getTime() < getSoneFollowingTime(newSone)) {
848                                         post.setKnown(true);
849                                 } else if (!post.isKnown()) {
850                                         events.add(new NewPostFoundEvent(post));
851                                 }
852                         }
853                 });
854                 soneChangeDetector.onRemovedPosts(new PostProcessor() {
855                         @Override
856                         public void processPost(Post post) {
857                                 events.add(new PostRemovedEvent(post));
858                         }
859                 });
860                 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
861                         @Override
862                         public void processPostReply(PostReply postReply) {
863                                 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
864                                         postReply.setKnown(true);
865                                 } else if (!postReply.isKnown()) {
866                                         events.add(new NewPostReplyFoundEvent(postReply));
867                                 }
868                         }
869                 });
870                 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
871                         @Override
872                         public void processPostReply(PostReply postReply) {
873                                 events.add(new PostReplyRemovedEvent(postReply));
874                         }
875                 });
876                 soneChangeDetector.detectChanges(newSone);
877                 return events;
878         }
879
880         /**
881          * Deletes the given Sone. This will remove the Sone from the
882          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
883          * remove the context from its identity.
884          *
885          * @param sone
886          *            The Sone to delete
887          */
888         public void deleteSone(Sone sone) {
889                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
890                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
891                         return;
892                 }
893                 if (!getLocalSones().contains(sone)) {
894                         logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
895                         return;
896                 }
897                 SoneInserter soneInserter = soneInserters.remove(sone);
898                 soneInserter.stop();
899                 database.removeSone(sone);
900                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
901                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
902                 try {
903                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
904                 } catch (ConfigurationException ce1) {
905                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
906                 }
907         }
908
909         /**
910          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
911          * known} before, a {@link MarkSoneKnownEvent} is fired.
912          *
913          * @param sone
914          *            The Sone to mark as known
915          */
916         public void markSoneKnown(Sone sone) {
917                 if (!sone.isKnown()) {
918                         sone.setKnown(true);
919                         database.setSoneKnown(sone);
920                         eventBus.post(new MarkSoneKnownEvent(sone));
921                         touchConfiguration();
922                 }
923         }
924
925         /**
926          * Creates a new post.
927          *
928          * @param sone
929          *            The Sone that creates the post
930          * @param recipient
931          *            The recipient Sone, or {@code null} if this post does not have
932          *            a recipient
933          * @param text
934          *            The text of the post
935          * @return The created post
936          */
937         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
938                 checkNotNull(text, "text must not be null");
939                 checkArgument(text.trim().length() > 0, "text must not be empty");
940                 if (!sone.isLocal()) {
941                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
942                         return null;
943                 }
944                 PostBuilder postBuilder = database.newPostBuilder();
945                 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
946                 if (recipient.isPresent()) {
947                         postBuilder.to(recipient.get().getId());
948                 }
949                 final Post post = postBuilder.build();
950                 database.storePost(post);
951                 eventBus.post(new NewPostFoundEvent(post));
952                 sone.addPost(post);
953                 touchConfiguration();
954                 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
955                 return post;
956         }
957
958         /**
959          * Deletes the given post.
960          *
961          * @param post
962          *            The post to delete
963          */
964         public void deletePost(Post post) {
965                 if (!post.getSone().isLocal()) {
966                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
967                         return;
968                 }
969                 database.removePost(post);
970                 eventBus.post(new PostRemovedEvent(post));
971                 markPostKnown(post);
972                 touchConfiguration();
973         }
974
975         /**
976          * Marks the given post as known, if it is currently not a known post
977          * (according to {@link Post#isKnown()}).
978          *
979          * @param post
980          *            The post to mark as known
981          */
982         public void markPostKnown(Post post) {
983                 post.setKnown(true);
984                 eventBus.post(new MarkPostKnownEvent(post));
985                 touchConfiguration();
986                 for (PostReply reply : getReplies(post.getId())) {
987                         markReplyKnown(reply);
988                 }
989         }
990
991         public void bookmarkPost(Post post) {
992                 database.bookmarkPost(post);
993         }
994
995         /**
996          * Removes the given post from the bookmarks.
997          *
998          * @param post
999          *            The post to unbookmark
1000          */
1001         public void unbookmarkPost(Post post) {
1002                 database.unbookmarkPost(post);
1003         }
1004
1005         /**
1006          * Creates a new reply.
1007          *
1008          * @param sone
1009          *            The Sone that creates the reply
1010          * @param post
1011          *            The post that this reply refers to
1012          * @param text
1013          *            The text of the reply
1014          * @return The created reply
1015          */
1016         public PostReply createReply(Sone sone, Post post, String text) {
1017                 checkNotNull(text, "text must not be null");
1018                 checkArgument(text.trim().length() > 0, "text must not be empty");
1019                 if (!sone.isLocal()) {
1020                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1021                         return null;
1022                 }
1023                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1024                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1025                 final PostReply reply = postReplyBuilder.build();
1026                 database.storePostReply(reply);
1027                 eventBus.post(new NewPostReplyFoundEvent(reply));
1028                 sone.addReply(reply);
1029                 touchConfiguration();
1030                 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1031                 return reply;
1032         }
1033
1034         /**
1035          * Deletes the given reply.
1036          *
1037          * @param reply
1038          *            The reply to delete
1039          */
1040         public void deleteReply(PostReply reply) {
1041                 Sone sone = reply.getSone();
1042                 if (!sone.isLocal()) {
1043                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1044                         return;
1045                 }
1046                 database.removePostReply(reply);
1047                 markReplyKnown(reply);
1048                 sone.removeReply(reply);
1049                 touchConfiguration();
1050         }
1051
1052         /**
1053          * Marks the given reply as known, if it is currently not a known reply
1054          * (according to {@link Reply#isKnown()}).
1055          *
1056          * @param reply
1057          *            The reply to mark as known
1058          */
1059         public void markReplyKnown(PostReply reply) {
1060                 boolean previouslyKnown = reply.isKnown();
1061                 reply.setKnown(true);
1062                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1063                 if (!previouslyKnown) {
1064                         touchConfiguration();
1065                 }
1066         }
1067
1068         /**
1069          * Creates a new album for the given Sone.
1070          *
1071          * @param sone
1072          *            The Sone to create the album for
1073          * @param parent
1074          *            The parent of the album (may be {@code null} to create a
1075          *            top-level album)
1076          * @return The new album
1077          */
1078         public Album createAlbum(Sone sone, Album parent) {
1079                 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1080                 database.storeAlbum(album);
1081                 parent.addAlbum(album);
1082                 return album;
1083         }
1084
1085         /**
1086          * Deletes the given album. The owner of the album has to be a local Sone,
1087          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1088          *
1089          * @param album
1090          *            The album to remove
1091          */
1092         public void deleteAlbum(Album album) {
1093                 checkNotNull(album, "album must not be null");
1094                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1095                 if (!album.isEmpty()) {
1096                         return;
1097                 }
1098                 album.getParent().removeAlbum(album);
1099                 database.removeAlbum(album);
1100                 touchConfiguration();
1101         }
1102
1103         /**
1104          * Creates a new image.
1105          *
1106          * @param sone
1107          *            The Sone creating the image
1108          * @param album
1109          *            The album the image will be inserted into
1110          * @param temporaryImage
1111          *            The temporary image to create the image from
1112          * @return The newly created image
1113          */
1114         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1115                 checkNotNull(sone, "sone must not be null");
1116                 checkNotNull(album, "album must not be null");
1117                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1118                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1119                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1120                 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1121                 album.addImage(image);
1122                 database.storeImage(image);
1123                 imageInserter.insertImage(temporaryImage, image);
1124                 return image;
1125         }
1126
1127         /**
1128          * Deletes the given image. This method will also delete a matching
1129          * temporary image.
1130          *
1131          * @see #deleteTemporaryImage(String)
1132          * @param image
1133          *            The image to delete
1134          */
1135         public void deleteImage(Image image) {
1136                 checkNotNull(image, "image must not be null");
1137                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1138                 deleteTemporaryImage(image.getId());
1139                 image.getAlbum().removeImage(image);
1140                 database.removeImage(image);
1141                 touchConfiguration();
1142         }
1143
1144         /**
1145          * Creates a new temporary image.
1146          *
1147          * @param mimeType
1148          *            The MIME type of the temporary image
1149          * @param imageData
1150          *            The encoded data of the image
1151          * @return The temporary image
1152          */
1153         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1154                 TemporaryImage temporaryImage = new TemporaryImage();
1155                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1156                 synchronized (temporaryImages) {
1157                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1158                 }
1159                 return temporaryImage;
1160         }
1161
1162         /**
1163          * Deletes the temporary image with the given ID.
1164          *
1165          * @param imageId
1166          *            The ID of the temporary image to delete
1167          */
1168         public void deleteTemporaryImage(String imageId) {
1169                 checkNotNull(imageId, "imageId must not be null");
1170                 synchronized (temporaryImages) {
1171                         temporaryImages.remove(imageId);
1172                 }
1173                 Image image = getImage(imageId, false);
1174                 if (image != null) {
1175                         imageInserter.cancelImageInsert(image);
1176                 }
1177         }
1178
1179         /**
1180          * Notifies the core that the configuration, either of the core or of a
1181          * single local Sone, has changed, and that the configuration should be
1182          * saved.
1183          */
1184         public void touchConfiguration() {
1185                 lastConfigurationUpdate = System.currentTimeMillis();
1186         }
1187
1188         //
1189         // SERVICE METHODS
1190         //
1191
1192         /**
1193          * Starts the core.
1194          */
1195         @Override
1196         public void serviceStart() {
1197                 loadConfiguration();
1198                 updateChecker.start();
1199                 identityManager.start();
1200                 webOfTrustUpdater.init();
1201                 webOfTrustUpdater.start();
1202                 database.start();
1203         }
1204
1205         /**
1206          * {@inheritDoc}
1207          */
1208         @Override
1209         public void serviceRun() {
1210                 long lastSaved = System.currentTimeMillis();
1211                 while (!shouldStop()) {
1212                         sleep(1000);
1213                         long now = System.currentTimeMillis();
1214                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1215                                 saveConfiguration();
1216                                 lastSaved = now;
1217                         }
1218                 }
1219         }
1220
1221         /**
1222          * Stops the core.
1223          */
1224         @Override
1225         public void serviceStop() {
1226                 localElementTicker.shutdownNow();
1227                 synchronized (soneInserters) {
1228                         for (Entry<LocalSone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1229                                 soneInserter.getValue().stop();
1230                         }
1231                 }
1232                 database.stop();
1233                 saveConfiguration();
1234                 webOfTrustUpdater.stop();
1235                 updateChecker.stop();
1236                 soneDownloader.stop();
1237                 soneDownloaders.shutdown();
1238                 identityManager.stop();
1239         }
1240
1241         //
1242         // PRIVATE METHODS
1243         //
1244
1245         /**
1246          * Saves the current options.
1247          */
1248         private void saveConfiguration() {
1249                 synchronized (configuration) {
1250                         if (storingConfiguration) {
1251                                 logger.log(Level.FINE, "Already storing configuration…");
1252                                 return;
1253                         }
1254                         storingConfiguration = true;
1255                 }
1256
1257                 /* store the options first. */
1258                 try {
1259                         preferences.saveTo(configuration);
1260
1261                         /* save known posts. */
1262                         database.save();
1263
1264                         /* now save it. */
1265                         configuration.save();
1266
1267                 } catch (ConfigurationException ce1) {
1268                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1269                 } catch (DatabaseException de1) {
1270                         logger.log(Level.SEVERE, "Could not save database!", de1);
1271                 } finally {
1272                         synchronized (configuration) {
1273                                 storingConfiguration = false;
1274                         }
1275                 }
1276         }
1277
1278         /**
1279          * Loads the configuration.
1280          */
1281         private void loadConfiguration() {
1282                 new PreferencesLoader(preferences).loadFrom(configuration);
1283         }
1284
1285         /**
1286          * Notifies the core that a new {@link OwnIdentity} was added.
1287          *
1288          * @param ownIdentityAddedEvent
1289          *            The event
1290          */
1291         @Subscribe
1292         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1293                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1294                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1295                 if (ownIdentity.hasContext("Sone")) {
1296                         addLocalSone(ownIdentity);
1297                 }
1298         }
1299
1300         /**
1301          * Notifies the core that an {@link OwnIdentity} was removed.
1302          *
1303          * @param ownIdentityRemovedEvent
1304          *            The event
1305          */
1306         @Subscribe
1307         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1308                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1309                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1310                 trustedIdentities.removeAll(ownIdentity);
1311         }
1312
1313         /**
1314          * Notifies the core that a new {@link Identity} was added.
1315          *
1316          * @param identityAddedEvent
1317          *            The event
1318          */
1319         @Subscribe
1320         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1321                 Identity identity = identityAddedEvent.identity();
1322                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1323                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1324                 addRemoteSone(identity);
1325         }
1326
1327         /**
1328          * Notifies the core that an {@link Identity} was updated.
1329          *
1330          * @param identityUpdatedEvent
1331          *            The event
1332          */
1333         @Subscribe
1334         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1335                 Identity identity = identityUpdatedEvent.identity();
1336                 final Sone sone = getRemoteSone(identity.getId());
1337                 if (sone.isLocal()) {
1338                         return;
1339                 }
1340                 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1341                 soneDownloader.addSone(sone);
1342                 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1343         }
1344
1345         /**
1346          * Notifies the core that an {@link Identity} was removed.
1347          *
1348          * @param identityRemovedEvent
1349          *            The event
1350          */
1351         @Subscribe
1352         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1353                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1354                 Identity identity = identityRemovedEvent.identity();
1355                 trustedIdentities.remove(ownIdentity, identity);
1356                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1357                         if (trustedIdentity.getKey().equals(ownIdentity)) {
1358                                 continue;
1359                         }
1360                         if (trustedIdentity.getValue().contains(identity)) {
1361                                 return;
1362                         }
1363                 }
1364                 Optional<Sone> sone = getSone(identity.getId());
1365                 if (!sone.isPresent()) {
1366                         /* TODO - we don’t have the Sone anymore. should this happen? */
1367                         return;
1368                 }
1369                 database.removeSone(sone.get());
1370                 eventBus.post(new SoneRemovedEvent(sone.get()));
1371         }
1372
1373         @Subscribe
1374         public void soneInserted(SoneInsertedEvent soneInsertedEvent) {
1375                 Sone sone = soneInsertedEvent.sone();
1376                 database.setLastInsertFingerprint(sone, soneInsertedEvent.insertFingerprint());
1377                 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(
1378                                 sone.getLatestEdition()));
1379         }
1380
1381         /**
1382          * Deletes the temporary image.
1383          *
1384          * @param imageInsertFinishedEvent
1385          *            The event
1386          */
1387         @Subscribe
1388         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1389                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1390                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1391                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1392                 touchConfiguration();
1393         }
1394
1395         @VisibleForTesting
1396         class MarkPostKnown implements Runnable {
1397
1398                 private final Post post;
1399
1400                 public MarkPostKnown(Post post) {
1401                         this.post = post;
1402                 }
1403
1404                 @Override
1405                 public void run() {
1406                         markPostKnown(post);
1407                 }
1408
1409         }
1410
1411         @VisibleForTesting
1412         class MarkReplyKnown implements Runnable {
1413
1414                 private final PostReply postReply;
1415
1416                 public MarkReplyKnown(PostReply postReply) {
1417                         this.postReply = postReply;
1418                 }
1419
1420                 @Override
1421                 public void run() {
1422                         markReplyKnown(postReply);
1423                 }
1424
1425         }
1426
1427 }