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