♻️ Use Sone’s identity to create insert URI
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneInserter.java
1 /*
2  * Sone - SoneInserter.java - Copyright © 2010–2020 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 java.lang.String.format;
21 import static java.lang.System.currentTimeMillis;
22 import static java.util.concurrent.TimeUnit.*;
23 import static java.util.logging.Logger.getLogger;
24 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
25
26 import java.io.Closeable;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.StringWriter;
30 import java.net.MalformedURLException;
31 import java.nio.charset.Charset;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.concurrent.atomic.AtomicInteger;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
39
40 import com.codahale.metrics.*;
41 import com.google.common.base.*;
42 import net.pterodactylus.sone.core.SoneModificationDetector.LockableFingerprintProvider;
43 import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
44 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
45 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
46 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
47 import net.pterodactylus.sone.data.Album;
48 import net.pterodactylus.sone.data.Post;
49 import net.pterodactylus.sone.data.Reply;
50 import net.pterodactylus.sone.data.Sone;
51 import net.pterodactylus.sone.data.Sone.SoneStatus;
52 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
53 import net.pterodactylus.sone.main.SonePlugin;
54 import net.pterodactylus.util.io.Closer;
55 import net.pterodactylus.util.service.AbstractService;
56 import net.pterodactylus.util.template.HtmlFilter;
57 import net.pterodactylus.util.template.ReflectionAccessor;
58 import net.pterodactylus.util.template.Template;
59 import net.pterodactylus.util.template.TemplateContext;
60 import net.pterodactylus.util.template.TemplateContextFactory;
61 import net.pterodactylus.util.template.TemplateException;
62 import net.pterodactylus.util.template.TemplateParser;
63 import net.pterodactylus.util.template.XmlFilter;
64
65 import com.google.common.annotations.VisibleForTesting;
66 import com.google.common.collect.FluentIterable;
67 import com.google.common.collect.Ordering;
68 import com.google.common.eventbus.EventBus;
69 import com.google.common.eventbus.Subscribe;
70
71 import freenet.keys.FreenetURI;
72 import freenet.support.api.Bucket;
73 import freenet.support.api.ManifestElement;
74 import freenet.support.api.RandomAccessBucket;
75 import freenet.support.io.ArrayBucket;
76
77 /**
78  * A Sone inserter is responsible for inserting a Sone if it has changed.
79  */
80 public class SoneInserter extends AbstractService {
81
82         /** The logger. */
83         private static final Logger logger = getLogger(SoneInserter.class.getName());
84
85         /** The insertion delay (in seconds). */
86         private static final AtomicInteger insertionDelay = new AtomicInteger(60);
87
88         /** The template factory used to create the templates. */
89         private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
90
91         static {
92                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
93                 templateContextFactory.addFilter("xml", new XmlFilter());
94                 templateContextFactory.addFilter("html", new HtmlFilter());
95         }
96
97         /** The UTF-8 charset. */
98         private static final Charset utf8Charset = Charset.forName("UTF-8");
99
100         /** The core. */
101         private final Core core;
102
103         /** The event bus. */
104         private final EventBus eventBus;
105
106         /** The Freenet interface. */
107         private final FreenetInterface freenetInterface;
108
109         private final SoneModificationDetector soneModificationDetector;
110         private final long delay;
111         private final String soneId;
112         private final Histogram soneInsertDurationHistogram;
113         private final Meter soneInsertErrorMeter;
114
115         /**
116          * Creates a new Sone inserter.
117          *
118          * @param core
119          *            The core
120          * @param eventBus
121          *            The event bus
122          * @param freenetInterface
123          *            The freenet interface
124          * @param soneId
125          *            The ID of the Sone to insert
126          */
127         public SoneInserter(final Core core, EventBus eventBus, FreenetInterface freenetInterface, MetricRegistry metricRegistry, final String soneId) {
128                 this(core, eventBus, freenetInterface, metricRegistry, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
129                         @Override
130                         public boolean isLocked() {
131                                 Sone sone = core.getSone(soneId);
132                                 if (sone == null) {
133                                         return false;
134                                 }
135                                 return core.isLocked(sone);
136                         }
137
138                         @Override
139                         public String getFingerprint() {
140                                 Sone sone = core.getSone(soneId);
141                                 if (sone == null) {
142                                         return null;
143                                 }
144                                 return sone.getFingerprint();
145                         }
146                 }, insertionDelay), 1000);
147         }
148
149         @VisibleForTesting
150         SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, MetricRegistry metricRegistry, String soneId, SoneModificationDetector soneModificationDetector, long delay) {
151                 super("Sone Inserter for “" + soneId + "”", false);
152                 this.core = core;
153                 this.eventBus = eventBus;
154                 this.freenetInterface = freenetInterface;
155                 this.soneInsertDurationHistogram = metricRegistry.histogram("sone.insert.duration", () -> new Histogram(new ExponentiallyDecayingReservoir(3000, 0)));
156                 this.soneInsertErrorMeter = metricRegistry.meter("sone.insert.errors");
157                 this.soneId = soneId;
158                 this.soneModificationDetector = soneModificationDetector;
159                 this.delay = delay;
160         }
161
162         //
163         // ACCESSORS
164         //
165
166         @VisibleForTesting
167         static AtomicInteger getInsertionDelay() {
168                 return insertionDelay;
169         }
170
171         /**
172          * Changes the insertion delay, i.e. the time the Sone inserter waits after it
173          * has noticed a Sone modification before it starts the insert.
174          *
175          * @param insertionDelay
176          *            The insertion delay (in seconds)
177          */
178         private static void setInsertionDelay(int insertionDelay) {
179                 SoneInserter.insertionDelay.set(insertionDelay);
180         }
181
182         /**
183          * Returns the fingerprint of the last insert.
184          *
185          * @return The fingerprint of the last insert
186          */
187         public String getLastInsertFingerprint() {
188                 return soneModificationDetector.getLastInsertFingerprint();
189         }
190
191         /**
192          * Sets the fingerprint of the last insert.
193          *
194          * @param lastInsertFingerprint
195          *            The fingerprint of the last insert
196          */
197         public void setLastInsertFingerprint(String lastInsertFingerprint) {
198                 soneModificationDetector.setFingerprint(lastInsertFingerprint);
199         }
200
201         /**
202          * Returns whether the Sone inserter has detected a modification of the
203          * Sone.
204          *
205          * @return {@code true} if the Sone has been modified, {@code false}
206          *         otherwise
207          */
208         public boolean isModified() {
209                 return soneModificationDetector.isModified();
210         }
211
212         //
213         // SERVICE METHODS
214         //
215
216         /**
217          * {@inheritDoc}
218          */
219         @Override
220         protected void serviceRun() {
221                 while (!shouldStop()) {
222                         try {
223                                 /* check every second. */
224                                 sleep(delay);
225
226                                 if (soneModificationDetector.isEligibleForInsert()) {
227                                         Sone sone = core.getSone(soneId);
228                                         if (sone == null) {
229                                                 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
230                                                 return;
231                                         }
232                                         InsertInformation insertInformation = new InsertInformation(sone);
233                                         logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
234
235                                         boolean success = false;
236                                         try {
237                                                 sone.setStatus(SoneStatus.inserting);
238                                                 long insertTime = currentTimeMillis();
239                                                 eventBus.post(new SoneInsertingEvent(sone));
240                                                 Stopwatch stopwatch = Stopwatch.createStarted();
241                                                 FreenetURI finalUri = freenetInterface.insertDirectory(getSoneInsertUri(sone), insertInformation.generateManifestEntries(), "index.html");
242                                                 stopwatch.stop();
243                                                 soneInsertDurationHistogram.update(stopwatch.elapsed(MICROSECONDS));
244                                                 eventBus.post(new SoneInsertedEvent(sone, stopwatch.elapsed(MILLISECONDS), insertInformation.getFingerprint()));
245                                                 /* at this point we might already be stopped. */
246                                                 if (shouldStop()) {
247                                                         /* if so, bail out, don’t change anything. */
248                                                         break;
249                                                 }
250                                                 sone.setTime(insertTime);
251                                                 sone.setLatestEdition(finalUri.getEdition());
252                                                 core.touchConfiguration();
253                                                 success = true;
254                                                 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
255                                         } catch (SoneException se1) {
256                                                 soneInsertErrorMeter.mark();
257                                                 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
258                                                 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
259                                         } finally {
260                                                 insertInformation.close();
261                                                 sone.setStatus(SoneStatus.idle);
262                                         }
263
264                                         /*
265                                          * reset modification counter if Sone has not been modified
266                                          * while it was inserted.
267                                          */
268                                         if (success) {
269                                                 synchronized (sone) {
270                                                         if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
271                                                                 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
272                                                                 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
273                                                                 core.touchConfiguration();
274                                                         }
275                                                 }
276                                         }
277                                 }
278                         } catch (Throwable t1) {
279                                 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
280                         }
281                 }
282         }
283
284         @Subscribe
285         public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
286                 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
287         }
288
289         private FreenetURI getSoneInsertUri(Sone sone) throws MalformedURLException {
290                 return new FreenetURI(((OwnIdentity) sone.getIdentity()).getInsertUri())
291                                 .setKeyType("USK")
292                                 .setDocName("Sone")
293                                 .setMetaString(new String[0])
294                                 .setSuggestedEdition(sone.getLatestEdition());
295         }
296
297         /**
298          * Container for information that are required to insert a Sone. This
299          * container merely exists to copy all relevant data without holding a lock
300          * on the {@link Sone} object for too long.
301          */
302         @VisibleForTesting
303         class InsertInformation implements Closeable {
304
305                 /** All properties of the Sone, copied for thread safety. */
306                 private final Map<String, Object> soneProperties = new HashMap<>();
307                 private final String fingerprint;
308                 private final ManifestCreator manifestCreator;
309
310                 /**
311                  * Creates a new insert information container.
312                  *
313                  * @param sone
314                  *            The sone to insert
315                  */
316                 public InsertInformation(Sone sone) {
317                         this.fingerprint = sone.getFingerprint();
318                         Map<String, Object> soneProperties = new HashMap<>();
319                         soneProperties.put("id", sone.getId());
320                         soneProperties.put("name", sone.getName());
321                         soneProperties.put("time", currentTimeMillis());
322                         soneProperties.put("requestUri", sone.getRequestUri());
323                         soneProperties.put("profile", sone.getProfile());
324                         soneProperties.put("posts", Ordering.from(Post.NEWEST_FIRST).sortedCopy(sone.getPosts()));
325                         soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
326                         soneProperties.put("likedPostIds", new HashSet<>(sone.getLikedPostIds()));
327                         soneProperties.put("likedReplyIds", new HashSet<>(sone.getLikedReplyIds()));
328                         soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
329                         manifestCreator = new ManifestCreator(core, soneProperties);
330                 }
331
332                 //
333                 // ACCESSORS
334                 //
335
336                 @VisibleForTesting
337                 String getFingerprint() {
338                         return fingerprint;
339                 }
340
341                 //
342                 // ACTIONS
343                 //
344
345                 /**
346                  * Generates all manifest entries required to insert this Sone.
347                  *
348                  * @return The manifest entries for the Sone insert
349                  */
350                 public HashMap<String, Object> generateManifestEntries() {
351                         HashMap<String, Object> manifestEntries = new HashMap<>();
352
353                         /* first, create an index.html. */
354                         manifestEntries.put("index.html", manifestCreator.createManifestElement(
355                                         "index.html", "text/html; charset=utf-8",
356                                         "/templates/insert/index.html"));
357
358                         /* now, store the sone. */
359                         manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
360                                         "sone.xml", "text/xml; charset=utf-8",
361                                         "/templates/insert/sone.xml"));
362
363                         return manifestEntries;
364                 }
365
366                 @Override
367                 public void close() {
368                         manifestCreator.close();
369                 }
370
371         }
372
373         /**
374          * Creates manifest elements for an insert by rendering a template.
375          */
376         @VisibleForTesting
377         static class ManifestCreator implements Closeable {
378
379                 private final Core core;
380                 private final Map<String, Object> soneProperties;
381                 private final Set<Bucket> buckets = new HashSet<>();
382
383                 ManifestCreator(Core core, Map<String, Object> soneProperties) {
384                         this.core = core;
385                         this.soneProperties = soneProperties;
386                 }
387
388                 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
389                         InputStreamReader templateInputStreamReader = null;
390                         InputStream templateInputStream = null;
391                         Template template;
392                         try {
393                                 templateInputStream = getClass().getResourceAsStream(templateName);
394                                 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
395                                 template = TemplateParser.parse(templateInputStreamReader);
396                         } catch (TemplateException te1) {
397                                 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
398                                 return null;
399                         } finally {
400                                 Closer.close(templateInputStreamReader);
401                                 Closer.close(templateInputStream);
402                         }
403
404                         TemplateContext templateContext = templateContextFactory.createTemplateContext();
405                         templateContext.set("core", core);
406                         templateContext.set("currentSone", soneProperties);
407                         templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
408                         templateContext.set("version", SonePlugin.getPluginVersion());
409                         StringWriter writer = new StringWriter();
410                         try {
411                                 template.render(templateContext, writer);
412                                 RandomAccessBucket bucket = new ArrayBucket(writer.toString().getBytes(Charsets.UTF_8));
413                                 buckets.add(bucket);
414                                 return new ManifestElement(name, bucket, contentType, bucket.size());
415                         } catch (TemplateException te1) {
416                                 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
417                                 return null;
418                         } finally {
419                                 Closer.close(writer);
420                         }
421                 }
422
423                 public void close() {
424                         for (Bucket bucket : buckets) {
425                                 bucket.free();
426                         }
427                 }
428
429         }
430
431 }