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