Use dependency injection to create Sone instance.
[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.collection.Pair;
33 import net.pterodactylus.util.logging.Logging;
34
35 import com.db4o.ObjectContainer;
36 import com.google.inject.Inject;
37
38 import freenet.client.ClientMetadata;
39 import freenet.client.FetchException;
40 import freenet.client.FetchResult;
41 import freenet.client.HighLevelSimpleClient;
42 import freenet.client.HighLevelSimpleClientImpl;
43 import freenet.client.InsertBlock;
44 import freenet.client.InsertContext;
45 import freenet.client.InsertException;
46 import freenet.client.async.BaseClientPutter;
47 import freenet.client.async.ClientContext;
48 import freenet.client.async.ClientPutCallback;
49 import freenet.client.async.ClientPutter;
50 import freenet.client.async.USKCallback;
51 import freenet.keys.FreenetURI;
52 import freenet.keys.InsertableClientSSK;
53 import freenet.keys.USK;
54 import freenet.node.Node;
55 import freenet.node.RequestStarter;
56 import freenet.support.api.Bucket;
57 import freenet.support.io.ArrayBucket;
58
59 /**
60  * Contains all necessary functionality for interacting with the Freenet node.
61  *
62  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
63  */
64 public class FreenetInterface {
65
66         /** The logger. */
67         private static final Logger logger = Logging.getLogger(FreenetInterface.class);
68
69         /** The node to interact with. */
70         private final Node node;
71
72         /** The high-level client to use for requests. */
73         private final HighLevelSimpleClient client;
74
75         /** The USK callbacks. */
76         private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
77
78         /** The not-Sone-related USK callbacks. */
79         private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
80
81         /**
82          * Creates a new Freenet interface.
83          *
84          * @param node
85          *            The node to interact with
86          */
87         @Inject
88         public FreenetInterface(Node node) {
89                 this.node = node;
90                 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
91         }
92
93         //
94         // ACTIONS
95         //
96
97         /**
98          * Fetches the given URI.
99          *
100          * @param uri
101          *            The URI to fetch
102          * @return The result of the fetch, or {@code null} if an error occured
103          */
104         public Pair<FreenetURI, FetchResult> fetchUri(FreenetURI uri) {
105                 FetchResult fetchResult = null;
106                 FreenetURI currentUri = new FreenetURI(uri);
107                 while (true) {
108                         try {
109                                 fetchResult = client.fetch(currentUri);
110                                 return new Pair<FreenetURI, FetchResult>(currentUri, fetchResult);
111                         } catch (FetchException fe1) {
112                                 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
113                                         currentUri = fe1.newURI;
114                                         continue;
115                                 }
116                                 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
117                                 return null;
118                         }
119                 }
120         }
121
122         /**
123          * Creates a key pair.
124          *
125          * @return The request key at index 0, the insert key at index 1
126          */
127         public String[] generateKeyPair() {
128                 FreenetURI[] keyPair = client.generateKeyPair("");
129                 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
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                         node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, (System.currentTimeMillis() - sone.getTime()) < 7 * 24 * 60 * 60 * 1000, (HighLevelSimpleClientImpl) client);
225                 } catch (MalformedURLException mue1) {
226                         logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), mue1);
227                 }
228         }
229
230         /**
231          * Unsubscribes the request URI of the given Sone.
232          *
233          * @param sone
234          *            The Sone to unregister
235          */
236         public void unregisterUsk(Sone sone) {
237                 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
238                 if (uskCallback == null) {
239                         return;
240                 }
241                 try {
242                         logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
243                         node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
244                 } catch (MalformedURLException mue1) {
245                         logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
246                 }
247         }
248
249         /**
250          * Registers an arbitrary URI and calls the given callback if a new edition
251          * is found.
252          *
253          * @param uri
254          *            The URI to watch
255          * @param callback
256          *            The callback to call
257          */
258         public void registerUsk(FreenetURI uri, final Callback callback) {
259                 USKCallback uskCallback = new USKCallback() {
260
261                         @Override
262                         public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
263                                 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
264                         }
265
266                         @Override
267                         public short getPollingPriorityNormal() {
268                                 return RequestStarter.PREFETCH_PRIORITY_CLASS;
269                         }
270
271                         @Override
272                         public short getPollingPriorityProgress() {
273                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
274                         }
275
276                 };
277                 try {
278                         node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (HighLevelSimpleClientImpl) client);
279                         uriUskCallbacks.put(uri, uskCallback);
280                 } catch (MalformedURLException mue1) {
281                         logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
282                 }
283         }
284
285         /**
286          * Unregisters the USK watcher for the given URI.
287          *
288          * @param uri
289          *            The URI to unregister the USK watcher for
290          */
291         public void unregisterUsk(FreenetURI uri) {
292                 USKCallback uskCallback = uriUskCallbacks.remove(uri);
293                 if (uskCallback == null) {
294                         logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
295                         return;
296                 }
297                 try {
298                         node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
299                 } catch (MalformedURLException mue1) {
300                         logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
301                 }
302         }
303
304         /**
305          * Callback for USK watcher events.
306          *
307          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
308          */
309         public static interface Callback {
310
311                 /**
312                  * Notifies a listener that a new edition was found for a URI.
313                  *
314                  * @param uri
315                  *            The URI that a new edition was found for
316                  * @param edition
317                  *            The found edition
318                  * @param newKnownGood
319                  *            Whether the found edition was actually fetched
320                  * @param newSlot
321                  *            Whether the found edition is higher than all previously
322                  *            found editions
323                  */
324                 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
325
326         }
327
328         /**
329          * Insert token that can be used to add {@link ImageInsertListener}s and
330          * cancel a running insert.
331          *
332          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
333          */
334         public class InsertToken implements ClientPutCallback {
335
336                 /** The image being inserted. */
337                 private final Image image;
338
339                 /** The list of registered image insert listeners. */
340                 private final List<ImageInsertListener> imageInsertListeners = Collections.synchronizedList(new ArrayList<ImageInsertListener>());
341
342                 /** The client putter. */
343                 private ClientPutter clientPutter;
344
345                 /** The final URI. */
346                 private volatile FreenetURI resultingUri;
347
348                 /**
349                  * Creates a new insert token for the given image.
350                  *
351                  * @param image
352                  *            The image being inserted
353                  */
354                 public InsertToken(Image image) {
355                         this.image = image;
356                 }
357
358                 //
359                 // LISTENER MANAGEMENT
360                 //
361
362                 /**
363                  * Adds the given listener to the list of registered listener.
364                  *
365                  * @param imageInsertListener
366                  *            The listener to add
367                  */
368                 public void addImageInsertListener(ImageInsertListener imageInsertListener) {
369                         imageInsertListeners.add(imageInsertListener);
370                 }
371
372                 /**
373                  * Removes the given listener from the list of registered listener.
374                  *
375                  * @param imageInsertListener
376                  *            The listener to remove
377                  */
378                 public void removeImageInsertListener(ImageInsertListener imageInsertListener) {
379                         imageInsertListeners.remove(imageInsertListener);
380                 }
381
382                 //
383                 // ACCESSORS
384                 //
385
386                 /**
387                  * Sets the client putter that is inserting the image. This will also
388                  * signal all registered listeners that the image has started.
389                  *
390                  * @see ImageInsertListener#imageInsertStarted(Image)
391                  * @param clientPutter
392                  *            The client putter
393                  */
394                 public void setClientPutter(ClientPutter clientPutter) {
395                         this.clientPutter = clientPutter;
396                         for (ImageInsertListener imageInsertListener : imageInsertListeners) {
397                                 imageInsertListener.imageInsertStarted(image);
398                         }
399                 }
400
401                 //
402                 // ACTIONS
403                 //
404
405                 /**
406                  * Cancels the running insert.
407                  *
408                  * @see ImageInsertListener#imageInsertAborted(Image)
409                  */
410                 @SuppressWarnings("synthetic-access")
411                 public void cancel() {
412                         clientPutter.cancel(null, node.clientCore.clientContext);
413                         for (ImageInsertListener imageInsertListener : imageInsertListeners) {
414                                 imageInsertListener.imageInsertAborted(image);
415                         }
416                 }
417
418                 //
419                 // INTERFACE ClientPutCallback
420                 //
421
422                 /**
423                  * {@inheritDoc}
424                  */
425                 @Override
426                 public void onMajorProgress(ObjectContainer objectContainer) {
427                         /* ignore, we don’t care. */
428                 }
429
430                 /**
431                  * {@inheritDoc}
432                  */
433                 @Override
434                 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
435                         for (ImageInsertListener imageInsertListener : imageInsertListeners) {
436                                 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
437                                         imageInsertListener.imageInsertAborted(image);
438                                 } else {
439                                         imageInsertListener.imageInsertFailed(image, insertException);
440                                 }
441                         }
442                 }
443
444                 /**
445                  * {@inheritDoc}
446                  */
447                 @Override
448                 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
449                         /* ignore, we don’t care. */
450                 }
451
452                 /**
453                  * {@inheritDoc}
454                  */
455                 @Override
456                 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
457                         /* ignore, we don’t care. */
458                 }
459
460                 /**
461                  * {@inheritDoc}
462                  */
463                 @Override
464                 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
465                         resultingUri = generatedUri;
466                 }
467
468                 /**
469                  * {@inheritDoc}
470                  */
471                 @Override
472                 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
473                         for (ImageInsertListener imageInsertListener : imageInsertListeners) {
474                                 imageInsertListener.imageInsertFinished(image, resultingUri);
475                         }
476                 }
477
478         }
479
480 }