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