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