2 * Sone - SoneInserter.java - Copyright © 2010–2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.core;
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;
24 import java.io.InputStreamReader;
25 import java.io.StringWriter;
26 import java.nio.charset.Charset;
27 import java.util.HashMap;
28 import java.util.HashSet;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
33 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
34 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
35 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
36 import net.pterodactylus.sone.data.Album;
37 import net.pterodactylus.sone.data.Post;
38 import net.pterodactylus.sone.data.Reply;
39 import net.pterodactylus.sone.data.Sone;
40 import net.pterodactylus.sone.data.Sone.SoneStatus;
41 import net.pterodactylus.sone.freenet.StringBucket;
42 import net.pterodactylus.sone.main.SonePlugin;
43 import net.pterodactylus.util.io.Closer;
44 import net.pterodactylus.util.logging.Logging;
45 import net.pterodactylus.util.service.AbstractService;
46 import net.pterodactylus.util.template.HtmlFilter;
47 import net.pterodactylus.util.template.ReflectionAccessor;
48 import net.pterodactylus.util.template.Template;
49 import net.pterodactylus.util.template.TemplateContext;
50 import net.pterodactylus.util.template.TemplateContextFactory;
51 import net.pterodactylus.util.template.TemplateException;
52 import net.pterodactylus.util.template.TemplateParser;
53 import net.pterodactylus.util.template.XmlFilter;
55 import freenet.client.async.ManifestElement;
56 import freenet.keys.FreenetURI;
58 import com.google.common.collect.FluentIterable;
59 import com.google.common.collect.Ordering;
60 import com.google.common.eventbus.EventBus;
63 * A Sone inserter is responsible for inserting a Sone if it has changed.
65 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
67 public class SoneInserter extends AbstractService {
70 private static final Logger logger = Logging.getLogger(SoneInserter.class);
72 /** The insertion delay (in seconds). */
73 private static volatile int insertionDelay = 60;
75 /** The template factory used to create the templates. */
76 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
79 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
80 templateContextFactory.addFilter("xml", new XmlFilter());
81 templateContextFactory.addFilter("html", new HtmlFilter());
84 /** The UTF-8 charset. */
85 private static final Charset utf8Charset = Charset.forName("UTF-8");
88 private final Core core;
91 private final EventBus eventBus;
93 /** The Freenet interface. */
94 private final FreenetInterface freenetInterface;
96 /** The Sone to insert. */
97 private volatile Sone sone;
99 /** Whether a modification has been detected. */
100 private volatile boolean modified = false;
102 /** The fingerprint of the last insert. */
103 private volatile String lastInsertFingerprint;
106 * Creates a new Sone inserter.
112 * @param freenetInterface
113 * The freenet interface
117 public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
118 super("Sone Inserter for “" + sone.getName() + "”", false);
120 this.eventBus = eventBus;
121 this.freenetInterface = freenetInterface;
130 * Sets the Sone to insert.
134 * @return This Sone inserter
136 public SoneInserter setSone(Sone sone) {
137 checkArgument((this.sone == null) || sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
143 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
144 * has noticed a Sone modification before it starts the insert.
146 * @param insertionDelay
147 * The insertion delay (in seconds)
149 public static void setInsertionDelay(int insertionDelay) {
150 SoneInserter.insertionDelay = insertionDelay;
154 * Returns the fingerprint of the last insert.
156 * @return The fingerprint of the last insert
158 public String getLastInsertFingerprint() {
159 return lastInsertFingerprint;
163 * Sets the fingerprint of the last insert.
165 * @param lastInsertFingerprint
166 * The fingerprint of the last insert
168 public void setLastInsertFingerprint(String lastInsertFingerprint) {
169 this.lastInsertFingerprint = lastInsertFingerprint;
173 * Returns whether the Sone inserter has detected a modification of the
176 * @return {@code true} if the Sone has been modified, {@code false}
179 public boolean isModified() {
188 protected void serviceRun() {
189 long lastModificationTime = 0;
190 String lastInsertedFingerprint = lastInsertFingerprint;
191 String lastFingerprint = "";
193 while (!shouldStop()) {
195 /* check every seconds. */
198 /* don’t insert locked Sones. */
200 if (core.isLocked(sone)) {
201 /* trigger redetection when the Sone is unlocked. */
202 synchronized (sone) {
203 modified = !sone.getFingerprint().equals(lastInsertedFingerprint);
205 lastFingerprint = "";
206 lastModificationTime = 0;
210 InsertInformation insertInformation = null;
211 synchronized (sone) {
212 String fingerprint = sone.getFingerprint();
213 if (!fingerprint.equals(lastFingerprint)) {
214 if (fingerprint.equals(lastInsertedFingerprint)) {
216 lastModificationTime = 0;
217 logger.log(Level.FINE, String.format("Sone %s has been reverted to last insert state.", sone));
219 lastModificationTime = System.currentTimeMillis();
221 logger.log(Level.FINE, String.format("Sone %s has been modified, waiting %d seconds before inserting.", sone.getName(), insertionDelay));
223 lastFingerprint = fingerprint;
225 if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
226 lastInsertedFingerprint = fingerprint;
227 insertInformation = new InsertInformation(sone);
231 if (insertInformation != null) {
232 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
234 boolean success = false;
236 sone.setStatus(SoneStatus.inserting);
237 long insertTime = System.currentTimeMillis();
238 insertInformation.setTime(insertTime);
239 eventBus.post(new SoneInsertingEvent(sone));
240 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
241 eventBus.post(new SoneInsertedEvent(sone, System.currentTimeMillis() - insertTime));
242 /* at this point we might already be stopped. */
244 /* if so, bail out, don’t change anything. */
247 sone.setTime(insertTime);
248 sone.modify().setLatestEdition(finalUri.getEdition()).update();
249 core.touchConfiguration();
251 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
252 } catch (SoneException se1) {
253 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
254 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
256 sone.setStatus(SoneStatus.idle);
260 * reset modification counter if Sone has not been modified
261 * while it was inserted.
264 synchronized (sone) {
265 if (lastInsertedFingerprint.equals(sone.getFingerprint())) {
266 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
267 lastModificationTime = 0;
268 lastInsertFingerprint = lastInsertedFingerprint;
269 core.touchConfiguration();
275 } catch (Throwable t1) {
276 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
282 * Container for information that are required to insert a Sone. This
283 * container merely exists to copy all relevant data without holding a lock
284 * on the {@link Sone} object for too long.
286 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
288 private class InsertInformation {
290 /** All properties of the Sone, copied for thread safety. */
291 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
294 * Creates a new insert information container.
299 public InsertInformation(Sone sone) {
300 soneProperties.put("id", sone.getId());
301 soneProperties.put("name", sone.getName());
302 soneProperties.put("time", sone.getTime());
303 soneProperties.put("requestUri", TO_FREENET_URI.apply(sone));
304 soneProperties.put("profile", sone.getProfile());
305 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
306 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
307 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
308 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
309 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
317 * Returns the insert URI of the Sone.
319 * @return The insert URI of the Sone
321 public FreenetURI getInsertUri() {
322 return (FreenetURI) soneProperties.get("insertUri");
326 * Sets the time of the Sone at the time of the insert.
329 * The time of the Sone
331 public void setTime(long time) {
332 soneProperties.put("time", time);
340 * Generates all manifest entries required to insert this Sone.
342 * @return The manifest entries for the Sone insert
344 public HashMap<String, Object> generateManifestEntries() {
345 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
347 /* first, create an index.html. */
348 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
350 /* now, store the sone. */
351 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
353 return manifestEntries;
361 * Creates a new manifest element.
364 * The name of the file
366 * The content type of the file
367 * @param templateName
368 * The name of the template to render
369 * @return The manifest element
371 @SuppressWarnings("synthetic-access")
372 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
373 InputStreamReader templateInputStreamReader = null;
376 templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset);
377 template = TemplateParser.parse(templateInputStreamReader);
378 } catch (TemplateException te1) {
379 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
382 Closer.close(templateInputStreamReader);
385 TemplateContext templateContext = templateContextFactory.createTemplateContext();
386 templateContext.set("core", core);
387 templateContext.set("currentSone", soneProperties);
388 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
389 templateContext.set("version", SonePlugin.VERSION);
390 StringWriter writer = new StringWriter();
391 StringBucket bucket = null;
393 template.render(templateContext, writer);
394 bucket = new StringBucket(writer.toString(), utf8Charset);
395 return new ManifestElement(name, bucket, contentType, bucket.size());
396 } catch (TemplateException te1) {
397 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
400 Closer.close(writer);
401 if (bucket != null) {