In case of a permanent redirect, follow.
[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.HashMap;
22 import java.util.Map;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25
26 import net.pterodactylus.sone.data.Sone;
27 import net.pterodactylus.util.logging.Logging;
28 import net.pterodactylus.util.service.AbstractService;
29
30 import com.db4o.ObjectContainer;
31
32 import freenet.client.FetchException;
33 import freenet.client.FetchResult;
34 import freenet.client.HighLevelSimpleClient;
35 import freenet.client.HighLevelSimpleClientImpl;
36 import freenet.client.InsertException;
37 import freenet.client.async.ClientContext;
38 import freenet.client.async.USKCallback;
39 import freenet.keys.FreenetURI;
40 import freenet.keys.USK;
41 import freenet.node.Node;
42 import freenet.node.RequestStarter;
43
44 /**
45  * Contains all necessary functionality for interacting with the Freenet node.
46  *
47  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48  */
49 public class FreenetInterface extends AbstractService {
50
51         /** The logger. */
52         private static final Logger logger = Logging.getLogger(FreenetInterface.class);
53
54         /** The node to interact with. */
55         private final Node node;
56
57         /** The high-level client to use for requests. */
58         private final HighLevelSimpleClient client;
59
60         /** The USK callbacks. */
61         private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
62
63         /**
64          * Creates a new Freenet interface.
65          *
66          * @param node
67          *            The node to interact with
68          * @param client
69          *            The high-level client
70          */
71         public FreenetInterface(Node node, HighLevelSimpleClient client) {
72                 super("Sone Freenet Interface");
73                 this.node = node;
74                 this.client = client;
75         }
76
77         //
78         // ACTIONS
79         //
80
81         /**
82          * Fetches the given URI.
83          *
84          * @param uri
85          *            The URI to fetch
86          * @return The result of the fetch, or {@code null} if an error occured
87          */
88         public FetchResult fetchUri(FreenetURI uri) {
89                 FetchResult fetchResult = null;
90                 FreenetURI currentUri = new FreenetURI(uri);
91                 while (true) {
92                         try {
93                                 fetchResult = client.fetch(currentUri);
94                                 return fetchResult;
95                         } catch (FetchException fe1) {
96                                 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
97                                         currentUri = fe1.newURI;
98                                         continue;
99                                 }
100                                 logger.log(Level.WARNING, "Could not fetch “" + uri + "”!", fe1);
101                                 return null;
102                         }
103                 }
104         }
105
106         /**
107          * Creates a key pair.
108          *
109          * @return The request key at index 0, the insert key at index 1
110          */
111         public String[] generateKeyPair() {
112                 FreenetURI[] keyPair = client.generateKeyPair("");
113                 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
114         }
115
116         /**
117          * Inserts a directory into Freenet.
118          *
119          * @param insertUri
120          *            The insert URI
121          * @param manifestEntries
122          *            The directory entries
123          * @param defaultFile
124          *            The name of the default file
125          * @return The generated URI
126          * @throws SoneException
127          *             if an insert error occurs
128          */
129         public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
130                 try {
131                         return client.insertManifest(insertUri, manifestEntries, defaultFile);
132                 } catch (InsertException ie1) {
133                         throw new SoneException(null, ie1);
134                 }
135         }
136
137         /**
138          * Registers the USK for the given Sone and notifies the given
139          * {@link SoneDownloader} if an update was found.
140          *
141          * @param sone
142          *            The Sone to watch
143          * @param soneDownloader
144          *            The Sone download to notify on updates
145          */
146         public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
147                 try {
148                         logger.log(Level.FINE, "Registering Sone “%s” for USK updates at %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
149                         USKCallback uskCallback = new USKCallback() {
150
151                                 @Override
152                                 @SuppressWarnings("synthetic-access")
153                                 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
154                                         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 });
155                                         if (newKnownGood) {
156                                                 sone.updateUris(key.getURI());
157                                                 soneDownloader.fetchSone(sone);
158                                         }
159                                 }
160
161                                 @Override
162                                 public short getPollingPriorityProgress() {
163                                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
164                                 }
165
166                                 @Override
167                                 public short getPollingPriorityNormal() {
168                                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
169                                 }
170                         };
171                         soneUskCallbacks.put(sone.getId(), uskCallback);
172                         node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, true, (HighLevelSimpleClientImpl) client);
173                 } catch (MalformedURLException mue1) {
174                         logger.log(Level.WARNING, "Could not subscribe USK “" + sone.getRequestUri() + "”!", mue1);
175                 }
176         }
177
178         /**
179          * Unsubscribes the request URI of the given Sone.
180          *
181          * @param sone
182          *            The Sone to unregister
183          */
184         public void unregisterUsk(Sone sone) {
185                 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
186                 if (uskCallback == null) {
187                         return;
188                 }
189                 try {
190                         logger.log(Level.FINEST, "Unsubscribing from USK for %s…", new Object[] { sone });
191                         node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
192                 } catch (MalformedURLException mue1) {
193                         logger.log(Level.FINE, "Could not unsubscribe USK “" + sone.getRequestUri() + "”!", mue1);
194                 }
195         }
196
197 }