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