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