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