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