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