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