9ccf5fc0bc1ff6515da4adb459be185368507184
[Sone.git] / src / main / java / net / pterodactylus / sone / core / FreenetInterface.java
1 /*
2  * Sone - FreenetInterface.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 java.net.MalformedURLException;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.concurrent.TimeUnit;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
28 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
29 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
30 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
31 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
32 import net.pterodactylus.sone.data.Image;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.data.TemporaryImage;
35 import net.pterodactylus.util.logging.Logging;
36
37 import com.db4o.ObjectContainer;
38
39 import com.google.common.base.Function;
40 import com.google.common.eventbus.EventBus;
41 import com.google.inject.Inject;
42
43 import freenet.client.ClientMetadata;
44 import freenet.client.FetchException;
45 import freenet.client.FetchResult;
46 import freenet.client.HighLevelSimpleClient;
47 import freenet.client.InsertBlock;
48 import freenet.client.InsertContext;
49 import freenet.client.InsertException;
50 import freenet.client.async.BaseClientPutter;
51 import freenet.client.async.ClientContext;
52 import freenet.client.async.ClientPutCallback;
53 import freenet.client.async.ClientPutter;
54 import freenet.client.async.USKCallback;
55 import freenet.keys.FreenetURI;
56 import freenet.keys.InsertableClientSSK;
57 import freenet.keys.USK;
58 import freenet.node.Node;
59 import freenet.node.RequestClient;
60 import freenet.node.RequestStarter;
61 import freenet.support.api.Bucket;
62 import freenet.support.io.ArrayBucket;
63
64 /**
65  * Contains all necessary functionality for interacting with the Freenet node.
66  *
67  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
68  */
69 public class FreenetInterface {
70
71         /** The logger. */
72         private static final Logger logger = Logging.getLogger(FreenetInterface.class);
73
74         /** The event bus. */
75         private final EventBus eventBus;
76
77         /** The node to interact with. */
78         private final Node node;
79
80         /** The high-level client to use for requests. */
81         private final HighLevelSimpleClient client;
82
83         /** The USK callbacks. */
84         private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
85
86         /** The not-Sone-related USK callbacks. */
87         private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
88
89         /**
90          * Creates a new Freenet interface.
91          *
92          * @param eventBus
93          *            The event bus
94          * @param node
95          *            The node to interact with
96          */
97         @Inject
98         public FreenetInterface(EventBus eventBus, Node node) {
99                 this.eventBus = eventBus;
100                 this.node = node;
101                 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
102         }
103
104         //
105         // ACTIONS
106         //
107
108         /**
109          * Fetches the given URI.
110          *
111          * @param uri
112          *            The URI to fetch
113          * @return The result of the fetch, or {@code null} if an error occured
114          */
115         public Fetched fetchUri(FreenetURI uri) {
116                 FreenetURI currentUri = new FreenetURI(uri);
117                 while (true) {
118                         try {
119                                 FetchResult fetchResult = client.fetch(currentUri);
120                                 return new Fetched(currentUri, fetchResult);
121                         } catch (FetchException fe1) {
122                                 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
123                                         currentUri = fe1.newURI;
124                                         continue;
125                                 }
126                                 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
127                                 return null;
128                         }
129                 }
130         }
131
132         /**
133          * Inserts the image data of the given {@link TemporaryImage} and returns
134          * the given insert token that can be used to add listeners or cancel the
135          * insert.
136          *
137          * @param temporaryImage
138          *            The temporary image data
139          * @param image
140          *            The image
141          * @param insertToken
142          *            The insert token
143          * @throws SoneException
144          *             if the insert could not be started
145          */
146         public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
147                 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
148                 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
149                 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
150                 InsertContext insertContext = client.getInsertContext(true);
151                 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
152                 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
153                 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
154                 try {
155                         ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
156                         insertToken.setClientPutter(clientPutter);
157                 } catch (InsertException ie1) {
158                         throw new SoneInsertException("Could not start image insert.", ie1);
159                 }
160         }
161
162         /**
163          * Inserts a directory into Freenet.
164          *
165          * @param insertUri
166          *            The insert URI
167          * @param manifestEntries
168          *            The directory entries
169          * @param defaultFile
170          *            The name of the default file
171          * @return The generated URI
172          * @throws SoneException
173          *             if an insert error occurs
174          */
175         public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
176                 try {
177                         return client.insertManifest(insertUri, manifestEntries, defaultFile);
178                 } catch (InsertException ie1) {
179                         throw new SoneException(ie1);
180                 }
181         }
182
183         /**
184          * Registers the USK for the given Sone and notifies the given
185          * {@link SoneDownloader} if an update was found.
186          *
187          * @param sone
188          *            The Sone to watch
189          * @param soneDownloader
190          *            The Sone download to notify on updates
191          */
192         public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
193                 try {
194                         logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" })));
195                         USKCallback uskCallback = new USKCallback() {
196
197                                 @Override
198                                 @SuppressWarnings("synthetic-access")
199                                 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
200                                         logger.log(Level.FINE, String.format("Found USK update for Sone “%s” at %s, new known good: %s, new slot too: %s.", sone, key, newKnownGood, newSlotToo));
201                                         if (edition > sone.getLatestEdition()) {
202                                                 sone.setLatestEdition(edition);
203                                                 new Thread(new Runnable() {
204
205                                                         @Override
206                                                         public void run() {
207                                                                 soneDownloader.fetchSone(sone);
208                                                         }
209                                                 }, "Sone Downloader").start();
210                                         }
211                                 }
212
213                                 @Override
214                                 public short getPollingPriorityProgress() {
215                                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
216                                 }
217
218                                 @Override
219                                 public short getPollingPriorityNormal() {
220                                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
221                                 }
222                         };
223                         soneUskCallbacks.put(sone.getId(), uskCallback);
224                         boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
225                         node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, runBackgroundFetch, (RequestClient) client);
226                 } catch (MalformedURLException mue1) {
227                         logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), mue1);
228                 }
229         }
230
231         /**
232          * Unsubscribes the request URI of the given Sone.
233          *
234          * @param sone
235          *            The Sone to unregister
236          */
237         public void unregisterUsk(Sone sone) {
238                 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
239                 if (uskCallback == null) {
240                         return;
241                 }
242                 try {
243                         logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
244                         node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
245                 } catch (MalformedURLException mue1) {
246                         logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
247                 }
248         }
249
250         /**
251          * Registers an arbitrary URI and calls the given callback if a new edition
252          * is found.
253          *
254          * @param uri
255          *            The URI to watch
256          * @param callback
257          *            The callback to call
258          */
259         public void registerUsk(FreenetURI uri, final Callback callback) {
260                 USKCallback uskCallback = new USKCallback() {
261
262                         @Override
263                         public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
264                                 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
265                         }
266
267                         @Override
268                         public short getPollingPriorityNormal() {
269                                 return RequestStarter.PREFETCH_PRIORITY_CLASS;
270                         }
271
272                         @Override
273                         public short getPollingPriorityProgress() {
274                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
275                         }
276
277                 };
278                 try {
279                         node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
280                         uriUskCallbacks.put(uri, uskCallback);
281                 } catch (MalformedURLException mue1) {
282                         logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
283                 }
284         }
285
286         /**
287          * Unregisters the USK watcher for the given URI.
288          *
289          * @param uri
290          *            The URI to unregister the USK watcher for
291          */
292         public void unregisterUsk(FreenetURI uri) {
293                 USKCallback uskCallback = uriUskCallbacks.remove(uri);
294                 if (uskCallback == null) {
295                         logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
296                         return;
297                 }
298                 try {
299                         node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
300                 } catch (MalformedURLException mue1) {
301                         logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
302                 }
303         }
304
305         /**
306          * Container for a fetched URI and the {@link FetchResult}.
307          *
308          * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
309          */
310         public static class Fetched {
311
312                 /** The fetched URI. */
313                 private final FreenetURI freenetUri;
314
315                 /** The fetch result. */
316                 private final FetchResult fetchResult;
317
318                 /**
319                  * Creates a new fetched URI.
320                  *
321                  * @param freenetUri
322                  *            The URI that was fetched
323                  * @param fetchResult
324                  *            The fetch result
325                  */
326                 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
327                         this.freenetUri = freenetUri;
328                         this.fetchResult = fetchResult;
329                 }
330
331                 //
332                 // ACCESSORS
333                 //
334
335                 /**
336                  * Returns the fetched URI.
337                  *
338                  * @return The fetched URI
339                  */
340                 public FreenetURI getFreenetUri() {
341                         return freenetUri;
342                 }
343
344                 /**
345                  * Returns the fetch result.
346                  *
347                  * @return The fetch result
348                  */
349                 public FetchResult getFetchResult() {
350                         return fetchResult;
351                 }
352
353         }
354
355         /**
356          * Callback for USK watcher events.
357          *
358          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
359          */
360         public static interface Callback {
361
362                 /**
363                  * Notifies a listener that a new edition was found for a URI.
364                  *
365                  * @param uri
366                  *            The URI that a new edition was found for
367                  * @param edition
368                  *            The found edition
369                  * @param newKnownGood
370                  *            Whether the found edition was actually fetched
371                  * @param newSlot
372                  *            Whether the found edition is higher than all previously
373                  *            found editions
374                  */
375                 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
376
377         }
378
379         /**
380          * Insert token that can cancel a running insert and sends events.
381          *
382          * @see ImageInsertAbortedEvent
383          * @see ImageInsertStartedEvent
384          * @see ImageInsertFailedEvent
385          * @see ImageInsertFinishedEvent
386          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
387          */
388         public class InsertToken implements ClientPutCallback {
389
390                 /** The image being inserted. */
391                 private final Image image;
392
393                 /** The client putter. */
394                 private ClientPutter clientPutter;
395
396                 /** The final URI. */
397                 private volatile FreenetURI resultingUri;
398
399                 /**
400                  * Creates a new insert token for the given image.
401                  *
402                  * @param image
403                  *            The image being inserted
404                  */
405                 public InsertToken(Image image) {
406                         this.image = image;
407                 }
408
409                 //
410                 // ACCESSORS
411                 //
412
413                 /**
414                  * Sets the client putter that is inserting the image. This will also
415                  * signal all registered listeners that the image has started.
416                  *
417                  * @param clientPutter
418                  *            The client putter
419                  */
420                 @SuppressWarnings("synthetic-access")
421                 public void setClientPutter(ClientPutter clientPutter) {
422                         this.clientPutter = clientPutter;
423                         eventBus.post(new ImageInsertStartedEvent(image));
424                 }
425
426                 //
427                 // ACTIONS
428                 //
429
430                 /**
431                  * Cancels the running insert.
432                  */
433                 @SuppressWarnings("synthetic-access")
434                 public void cancel() {
435                         clientPutter.cancel(null, node.clientCore.clientContext);
436                         eventBus.post(new ImageInsertAbortedEvent(image));
437                 }
438
439                 //
440                 // INTERFACE ClientPutCallback
441                 //
442
443                 /**
444                  * {@inheritDoc}
445                  */
446                 @Override
447                 public void onMajorProgress(ObjectContainer objectContainer) {
448                         /* ignore, we don’t care. */
449                 }
450
451                 /**
452                  * {@inheritDoc}
453                  */
454                 @Override
455                 @SuppressWarnings("synthetic-access")
456                 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
457                         if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
458                                 eventBus.post(new ImageInsertAbortedEvent(image));
459                         } else {
460                                 eventBus.post(new ImageInsertFailedEvent(image, insertException));
461                         }
462                 }
463
464                 /**
465                  * {@inheritDoc}
466                  */
467                 @Override
468                 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
469                         /* ignore, we don’t care. */
470                 }
471
472                 /**
473                  * {@inheritDoc}
474                  */
475                 @Override
476                 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
477                         /* ignore, we don’t care. */
478                 }
479
480                 /**
481                  * {@inheritDoc}
482                  */
483                 @Override
484                 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
485                         resultingUri = generatedUri;
486                 }
487
488                 /**
489                  * {@inheritDoc}
490                  */
491                 @Override
492                 @SuppressWarnings("synthetic-access")
493                 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
494                         eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
495                 }
496
497         }
498
499         public class InsertTokenSupplier implements Function<Image, InsertToken> {
500
501                 @Override
502                 public InsertToken apply(Image image) {
503                         return new InsertToken(image);
504                 }
505
506         }
507
508 }