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