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