Merge branch 'release-0.4.2'
[Sone.git] / src / main / java / net / pterodactylus / sone / core / FreenetInterface.java
1 /*
2  * FreenetSone - FreenetInterface.java - Copyright © 2010 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.data.Sone;
28 import net.pterodactylus.util.collection.Pair;
29 import net.pterodactylus.util.logging.Logging;
30
31 import com.db4o.ObjectContainer;
32
33 import freenet.client.FetchException;
34 import freenet.client.FetchResult;
35 import freenet.client.HighLevelSimpleClient;
36 import freenet.client.HighLevelSimpleClientImpl;
37 import freenet.client.InsertException;
38 import freenet.client.async.ClientContext;
39 import freenet.client.async.USKCallback;
40 import freenet.keys.FreenetURI;
41 import freenet.keys.USK;
42 import freenet.node.Node;
43 import freenet.node.RequestStarter;
44
45 /**
46  * Contains all necessary functionality for interacting with the Freenet node.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class FreenetInterface {
51
52         /** The logger. */
53         private static final Logger logger = Logging.getLogger(FreenetInterface.class);
54
55         /** The node to interact with. */
56         private final Node node;
57
58         /** The high-level client to use for requests. */
59         private final HighLevelSimpleClient client;
60
61         /** The USK callbacks. */
62         private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
63
64         /** The not-Sone-related USK callbacks. */
65         private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
66
67         /**
68          * Creates a new Freenet interface.
69          *
70          * @param node
71          *            The node to interact with
72          */
73         public FreenetInterface(Node node) {
74                 this.node = node;
75                 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
76         }
77
78         //
79         // ACTIONS
80         //
81
82         /**
83          * Fetches the given URI.
84          *
85          * @param uri
86          *            The URI to fetch
87          * @return The result of the fetch, or {@code null} if an error occured
88          */
89         public Pair<FreenetURI, FetchResult> fetchUri(FreenetURI uri) {
90                 FetchResult fetchResult = null;
91                 FreenetURI currentUri = new FreenetURI(uri);
92                 while (true) {
93                         try {
94                                 fetchResult = client.fetch(currentUri);
95                                 return new Pair<FreenetURI, FetchResult>(currentUri, fetchResult);
96                         } catch (FetchException fe1) {
97                                 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
98                                         currentUri = fe1.newURI;
99                                         continue;
100                                 }
101                                 logger.log(Level.WARNING, "Could not fetch “" + uri + "”!", fe1);
102                                 return null;
103                         }
104                 }
105         }
106
107         /**
108          * Creates a key pair.
109          *
110          * @return The request key at index 0, the insert key at index 1
111          */
112         public String[] generateKeyPair() {
113                 FreenetURI[] keyPair = client.generateKeyPair("");
114                 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
115         }
116
117         /**
118          * Inserts a directory into Freenet.
119          *
120          * @param insertUri
121          *            The insert URI
122          * @param manifestEntries
123          *            The directory entries
124          * @param defaultFile
125          *            The name of the default file
126          * @return The generated URI
127          * @throws SoneException
128          *             if an insert error occurs
129          */
130         public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
131                 try {
132                         return client.insertManifest(insertUri, manifestEntries, defaultFile);
133                 } catch (InsertException ie1) {
134                         throw new SoneException(null, ie1);
135                 }
136         }
137
138         /**
139          * Registers the USK for the given Sone and notifies the given
140          * {@link SoneDownloader} if an update was found.
141          *
142          * @param sone
143          *            The Sone to watch
144          * @param soneDownloader
145          *            The Sone download to notify on updates
146          */
147         public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
148                 try {
149                         logger.log(Level.FINE, "Registering Sone “%s” for USK updates at %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
150                         USKCallback uskCallback = new USKCallback() {
151
152                                 @Override
153                                 @SuppressWarnings("synthetic-access")
154                                 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
155                                         logger.log(Level.FINE, "Found USK update for Sone “%s” at %s, new known good: %s, new slot too: %s.", new Object[] { sone, key, newKnownGood, newSlotToo });
156                                         if (edition > sone.getLatestEdition()) {
157                                                 sone.setLatestEdition(edition);
158                                                 new Thread(new Runnable() {
159
160                                                         @Override
161                                                         public void run() {
162                                                                 soneDownloader.fetchSone(sone);
163                                                         }
164                                                 }, "Sone Downloader").start();
165                                         }
166                                 }
167
168                                 @Override
169                                 public short getPollingPriorityProgress() {
170                                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
171                                 }
172
173                                 @Override
174                                 public short getPollingPriorityNormal() {
175                                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
176                                 }
177                         };
178                         soneUskCallbacks.put(sone.getId(), uskCallback);
179                         node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, true, (HighLevelSimpleClientImpl) client);
180                 } catch (MalformedURLException mue1) {
181                         logger.log(Level.WARNING, "Could not subscribe USK “" + sone.getRequestUri() + "”!", mue1);
182                 }
183         }
184
185         /**
186          * Unsubscribes the request URI of the given Sone.
187          *
188          * @param sone
189          *            The Sone to unregister
190          */
191         public void unregisterUsk(Sone sone) {
192                 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
193                 if (uskCallback == null) {
194                         return;
195                 }
196                 try {
197                         logger.log(Level.FINEST, "Unsubscribing from USK for %s…", new Object[] { sone });
198                         node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
199                 } catch (MalformedURLException mue1) {
200                         logger.log(Level.FINE, "Could not unsubscribe USK “" + sone.getRequestUri() + "”!", mue1);
201                 }
202         }
203
204         /**
205          * Registers an arbitrary URI and calls the given callback if a new edition
206          * is found.
207          *
208          * @param uri
209          *            The URI to watch
210          * @param callback
211          *            The callback to call
212          */
213         public void registerUsk(FreenetURI uri, final Callback callback) {
214                 USKCallback uskCallback = new USKCallback() {
215
216                         @Override
217                         public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
218                                 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
219                         }
220
221                         @Override
222                         public short getPollingPriorityNormal() {
223                                 return RequestStarter.PREFETCH_PRIORITY_CLASS;
224                         }
225
226                         @Override
227                         public short getPollingPriorityProgress() {
228                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
229                         }
230
231                 };
232                 try {
233                         node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (HighLevelSimpleClientImpl) client);
234                         uriUskCallbacks.put(uri, uskCallback);
235                 } catch (MalformedURLException mue1) {
236                         logger.log(Level.WARNING, "Could not subscribe to USK: " + uri, uri);
237                 }
238         }
239
240         /**
241          * Unregisters the USK watcher for the given URI.
242          *
243          * @param uri
244          *            The URI to unregister the USK watcher for
245          */
246         public void unregisterUsk(FreenetURI uri) {
247                 USKCallback uskCallback = uriUskCallbacks.remove(uri);
248                 if (uskCallback == null) {
249                         logger.log(Level.INFO, "Could not unregister unknown USK: " + uri);
250                         return;
251                 }
252                 try {
253                         node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
254                 } catch (MalformedURLException mue1) {
255                         logger.log(Level.INFO, "Could not unregister invalid USK: " + uri);
256                 }
257         }
258
259         /**
260          * Callback for USK watcher events.
261          *
262          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
263          */
264         public static interface Callback {
265
266                 /**
267                  * Notifies a listener that a new edition was found for a URI.
268                  *
269                  * @param uri
270                  *            The URI that a new edition was found for
271                  * @param edition
272                  *            The found edition
273                  * @param newKnownGood
274                  *            Whether the found edition was actually fetched
275                  * @param newSlot
276                  *            Whether the found edition is higher than all previously
277                  *            found editions
278                  */
279                 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
280
281         }
282
283 }