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