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