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