Remove core listener.
[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.data.Post;
30 import net.pterodactylus.sone.data.Reply;
31 import net.pterodactylus.sone.data.Sone;
32 import net.pterodactylus.sone.data.Sone.SoneStatus;
33 import net.pterodactylus.sone.freenet.StringBucket;
34 import net.pterodactylus.sone.main.SonePlugin;
35 import net.pterodactylus.util.io.Closer;
36 import net.pterodactylus.util.logging.Logging;
37 import net.pterodactylus.util.service.AbstractService;
38 import net.pterodactylus.util.template.HtmlFilter;
39 import net.pterodactylus.util.template.ReflectionAccessor;
40 import net.pterodactylus.util.template.Template;
41 import net.pterodactylus.util.template.TemplateContext;
42 import net.pterodactylus.util.template.TemplateContextFactory;
43 import net.pterodactylus.util.template.TemplateException;
44 import net.pterodactylus.util.template.TemplateParser;
45 import net.pterodactylus.util.template.XmlFilter;
46
47 import com.google.common.collect.Ordering;
48
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 lastInsertedFingerprint = lastInsertFingerprint;
193                 String lastFingerprint = "";
194                 while (!shouldStop()) { try {
195                         /* check every seconds. */
196                         sleep(1000);
197
198                         /* don’t insert locked Sones. */
199                         if (core.isLocked(sone)) {
200                                 /* trigger redetection when the Sone is unlocked. */
201                                 synchronized (sone) {
202                                         modified = !sone.getFingerprint().equals(lastInsertedFingerprint);
203                                 }
204                                 lastFingerprint = "";
205                                 lastModificationTime = 0;
206                                 continue;
207                         }
208
209                         InsertInformation insertInformation = null;
210                         synchronized (sone) {
211                                 String fingerprint = sone.getFingerprint();
212                                 if (!fingerprint.equals(lastFingerprint)) {
213                                         if (fingerprint.equals(lastInsertedFingerprint)) {
214                                                 modified = false;
215                                                 lastModificationTime = 0;
216                                                 logger.log(Level.FINE, String.format("Sone %s has been reverted to last insert state.", sone));
217                                         } else {
218                                                 lastModificationTime = System.currentTimeMillis();
219                                                 modified = true;
220                                                 logger.log(Level.FINE, String.format("Sone %s has been modified, waiting %d seconds before inserting.", sone.getName(), insertionDelay));
221                                         }
222                                         lastFingerprint = fingerprint;
223                                 }
224                                 if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
225                                         lastInsertedFingerprint = fingerprint;
226                                         insertInformation = new InsertInformation(sone);
227                                 }
228                         }
229
230                         if (insertInformation != null) {
231                                 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
232
233                                 boolean success = false;
234                                 try {
235                                         sone.setStatus(SoneStatus.inserting);
236                                         long insertTime = System.currentTimeMillis();
237                                         insertInformation.setTime(insertTime);
238                                         soneInsertListenerManager.fireInsertStarted();
239                                         FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
240                                         soneInsertListenerManager.fireInsertFinished(System.currentTimeMillis() - insertTime);
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                                         soneInsertListenerManager.fireInsertAborted(se1);
253                                         logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
254                                 } finally {
255                                         sone.setStatus(SoneStatus.idle);
256                                 }
257
258                                 /*
259                                  * reset modification counter if Sone has not been modified
260                                  * while it was inserted.
261                                  */
262                                 if (success) {
263                                         synchronized (sone) {
264                                                 if (lastInsertedFingerprint.equals(sone.getFingerprint())) {
265                                                         logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
266                                                         lastModificationTime = 0;
267                                                         lastInsertFingerprint = lastInsertedFingerprint;
268                                                         core.touchConfiguration();
269                                                         modified = false;
270                                                 }
271                                         }
272                                 }
273                         }
274                 } catch (Throwable t1) {
275                         logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
276                 }}
277         }
278
279         /**
280          * Container for information that are required to insert a Sone. This
281          * container merely exists to copy all relevant data without holding a lock
282          * on the {@link Sone} object for too long.
283          *
284          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
285          */
286         private class InsertInformation {
287
288                 /** All properties of the Sone, copied for thread safety. */
289                 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
290
291                 /**
292                  * Creates a new insert information container.
293                  *
294                  * @param sone
295                  *            The sone to insert
296                  */
297                 public InsertInformation(Sone sone) {
298                         soneProperties.put("id", sone.getId());
299                         soneProperties.put("name", sone.getName());
300                         soneProperties.put("time", sone.getTime());
301                         soneProperties.put("requestUri", sone.getRequestUri());
302                         soneProperties.put("insertUri", sone.getInsertUri());
303                         soneProperties.put("profile", sone.getProfile());
304                         soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
305                         soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
306                         soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
307                         soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
308                         soneProperties.put("albums", sone.getAllAlbums());
309                 }
310
311                 //
312                 // ACCESSORS
313                 //
314
315                 /**
316                  * Returns the insert URI of the Sone.
317                  *
318                  * @return The insert URI of the Sone
319                  */
320                 public FreenetURI getInsertUri() {
321                         return (FreenetURI) soneProperties.get("insertUri");
322                 }
323
324                 /**
325                  * Sets the time of the Sone at the time of the insert.
326                  *
327                  * @param time
328                  *            The time of the Sone
329                  */
330                 public void setTime(long time) {
331                         soneProperties.put("time", time);
332                 }
333
334                 //
335                 // ACTIONS
336                 //
337
338                 /**
339                  * Generates all manifest entries required to insert this Sone.
340                  *
341                  * @return The manifest entries for the Sone insert
342                  */
343                 public HashMap<String, Object> generateManifestEntries() {
344                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
345
346                         /* first, create an index.html. */
347                         manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
348
349                         /* now, store the sone. */
350                         manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
351
352                         return manifestEntries;
353                 }
354
355                 //
356                 // PRIVATE METHODS
357                 //
358
359                 /**
360                  * Creates a new manifest element.
361                  *
362                  * @param name
363                  *            The name of the file
364                  * @param contentType
365                  *            The content type of the file
366                  * @param templateName
367                  *            The name of the template to render
368                  * @return The manifest element
369                  */
370                 @SuppressWarnings("synthetic-access")
371                 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
372                         InputStreamReader templateInputStreamReader = null;
373                         Template template;
374                         try {
375                                 templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset);
376                                 template = TemplateParser.parse(templateInputStreamReader);
377                         } catch (TemplateException te1) {
378                                 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
379                                 return null;
380                         } finally {
381                                 Closer.close(templateInputStreamReader);
382                         }
383
384                         TemplateContext templateContext = templateContextFactory.createTemplateContext();
385                         templateContext.set("core", core);
386                         templateContext.set("currentSone", soneProperties);
387                         templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
388                         templateContext.set("version", SonePlugin.VERSION);
389                         StringWriter writer = new StringWriter();
390                         StringBucket bucket = null;
391                         try {
392                                 template.render(templateContext, writer);
393                                 bucket = new StringBucket(writer.toString(), utf8Charset);
394                                 return new ManifestElement(name, bucket, contentType, bucket.size());
395                         } catch (TemplateException te1) {
396                                 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
397                                 return null;
398                         } finally {
399                                 Closer.close(writer);
400                                 if (bucket != null) {
401                                         bucket.free();
402                                 }
403                         }
404                 }
405
406         }
407
408 }