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