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