Add Sone downloader.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * FreenetSone - Core.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.HashSet;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.UUID;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.sone.core.SoneException.Type;
31 import net.pterodactylus.sone.data.Post;
32 import net.pterodactylus.sone.data.PostShell;
33 import net.pterodactylus.sone.data.Profile;
34 import net.pterodactylus.sone.data.Reply;
35 import net.pterodactylus.sone.data.ReplyShell;
36 import net.pterodactylus.sone.data.Shell;
37 import net.pterodactylus.sone.data.ShellCache;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.data.SoneShell;
40 import net.pterodactylus.util.config.Configuration;
41 import net.pterodactylus.util.config.ConfigurationException;
42 import net.pterodactylus.util.logging.Logging;
43 import net.pterodactylus.util.service.AbstractService;
44 import freenet.keys.FreenetURI;
45
46 /**
47  * The Sone core.
48  *
49  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50  */
51 public class Core extends AbstractService {
52
53         /** The logger. */
54         private static final Logger logger = Logging.getLogger(Core.class);
55
56         /** The configuration. */
57         private Configuration configuration;
58
59         /** Interface to freenet. */
60         private FreenetInterface freenetInterface;
61
62         /** The Sone downloader. */
63         private SoneDownloader soneDownloader;
64
65         /** The local Sones. */
66         private final Set<Sone> localSones = new HashSet<Sone>();
67
68         /** Sone inserters. */
69         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
70
71         /* various caches follow here. */
72
73         /** Cache for all known Sones. */
74         private final ShellCache<Sone> soneCache = new ShellCache<Sone>(SoneShell.creator);
75
76         /** Cache for all known posts. */
77         private final ShellCache<Post> postCache = new ShellCache<Post>(PostShell.creator);
78
79         /** Cache for all known replies. */
80         private final ShellCache<Reply> replyCache = new ShellCache<Reply>(ReplyShell.creator);
81
82         /**
83          * Creates a new core.
84          */
85         public Core() {
86                 super("Sone Core");
87         }
88
89         //
90         // ACCESSORS
91         //
92
93         /**
94          * Sets the configuration of the core.
95          *
96          * @param configuration
97          *            The configuration of the core
98          * @return This core (for method chaining)
99          */
100         public Core configuration(Configuration configuration) {
101                 this.configuration = configuration;
102                 return this;
103         }
104
105         /**
106          * Sets the Freenet interface to use.
107          *
108          * @param freenetInterface
109          *            The Freenet interface to use
110          * @return This core (for method chaining)
111          */
112         public Core freenetInterface(FreenetInterface freenetInterface) {
113                 this.freenetInterface = freenetInterface;
114                 soneDownloader = new SoneDownloader(freenetInterface);
115                 return this;
116         }
117
118         /**
119          * Returns the local Sones.
120          *
121          * @return The local Sones
122          */
123         public Set<Sone> getSones() {
124                 return Collections.unmodifiableSet(localSones);
125         }
126
127         /**
128          * Returns a Sone or a {@link Shell} around one for the given ID.
129          *
130          * @param soneId
131          *            The ID of the Sone
132          * @return The Sone, or a {@link Shell} around one
133          */
134         public Sone getSone(String soneId) {
135                 Sone sone = soneCache.get(soneId);
136                 if (sone instanceof SoneShell) {
137                         soneCache.put(soneId, sone = ((SoneShell) sone).getShelled());
138                 }
139                 return sone;
140         }
141
142         //
143         // ACTIONS
144         //
145
146         /**
147          * Adds the given Sone.
148          *
149          * @param sone
150          *            The Sone to add
151          */
152         public void addSone(Sone sone) {
153                 if (localSones.add(sone)) {
154                         soneCache.put(sone.getId(), sone);
155                         SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
156                         soneInserter.start();
157                         soneDownloader.addSone(sone);
158                         soneInserters.put(sone, soneInserter);
159                 }
160         }
161
162         /**
163          * Creates a new Sone at a random location.
164          *
165          * @param name
166          *            The name of the Sone
167          * @return The created Sone
168          * @throws SoneException
169          *             if a Sone error occurs
170          */
171         public Sone createSone(String name) throws SoneException {
172                 return createSone(name, null, null);
173         }
174
175         /**
176          * Creates a new Sone at the given location. If one of {@code requestUri} or
177          * {@code insertUrI} is {@code null}, the Sone is created at a random
178          * location.
179          *
180          * @param name
181          *            The name of the Sone
182          * @param requestUri
183          *            The request URI of the Sone, or {@link NullPointerException}
184          *            to create a Sone at a random location
185          * @param insertUri
186          *            The insert URI of the Sone, or {@code null} to create a Sone
187          *            at a random location
188          * @return The created Sone
189          * @throws SoneException
190          *             if a Sone error occurs
191          */
192         public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
193                 if ((name == null) || (name.trim().length() == 0)) {
194                         throw new SoneException(Type.INVALID_SONE_NAME);
195                 }
196                 String finalRequestUri;
197                 String finalInsertUri;
198                 if ((requestUri == null) || (insertUri == null)) {
199                         String[] keyPair = freenetInterface.generateKeyPair();
200                         finalRequestUri = keyPair[0];
201                         finalInsertUri = keyPair[1];
202                 } else {
203                         finalRequestUri = requestUri;
204                         finalInsertUri = insertUri;
205                 }
206                 Sone sone;
207                 try {
208                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
209                         sone = new Sone(UUID.randomUUID(), name, new FreenetURI(finalRequestUri).setKeyType("USK").setDocName("Sone-" + name), new FreenetURI(finalInsertUri).setKeyType("USK").setDocName("Sone-" + name));
210                         sone.setProfile(new Profile());
211                         /* set modification counter to 1 so it is inserted immediately. */
212                         sone.setModificationCounter(1);
213                         addSone(sone);
214                 } catch (MalformedURLException mue1) {
215                         throw new SoneException(Type.INVALID_URI);
216                 }
217                 return sone;
218         }
219
220         /**
221          * Deletes the given Sone from this plugin instance.
222          *
223          * @param sone
224          *            The sone to delete
225          */
226         public void deleteSone(Sone sone) {
227                 SoneInserter soneInserter = soneInserters.remove(sone);
228                 soneInserter.stop();
229                 localSones.remove(sone);
230         }
231
232         //
233         // SERVICE METHODS
234         //
235
236         /**
237          * {@inheritDoc}
238          */
239         @Override
240         protected void serviceStart() {
241                 loadConfiguration();
242         }
243
244         /**
245          * {@inheritDoc}
246          */
247         @Override
248         protected void serviceStop() {
249                 soneDownloader.stop();
250                 /* stop all Sone inserters. */
251                 for (SoneInserter soneInserter : soneInserters.values()) {
252                         soneInserter.stop();
253                 }
254                 saveConfiguration();
255         }
256
257         //
258         // PRIVATE METHODS
259         //
260
261         /**
262          * Loads the configuration.
263          */
264         private void loadConfiguration() {
265                 logger.entering(Core.class.getName(), "loadConfiguration()");
266
267                 /* parse local Sones. */
268                 logger.log(Level.INFO, "Loading Sones…");
269                 int soneId = 0;
270                 do {
271                         String sonePrefix = "Sone/Sone." + soneId++;
272                         String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
273                         if (id == null) {
274                                 break;
275                         }
276                         String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
277                         String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
278                         String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
279                         long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
280                         String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
281                         String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
282                         String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
283                         try {
284                                 Profile profile = new Profile();
285                                 profile.setFirstName(firstName);
286                                 profile.setMiddleName(middleName);
287                                 profile.setLastName(lastName);
288                                 Sone sone = new Sone(UUID.fromString(id), name, new FreenetURI(requestUri), new FreenetURI(insertUri));
289                                 soneCache.put(id, sone);
290                                 sone.setProfile(profile);
291                                 int postId = 0;
292                                 do {
293                                         String postPrefix = sonePrefix + "/Post." + postId++;
294                                         id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
295                                         if (id == null) {
296                                                 break;
297                                         }
298                                         long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
299                                         String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
300                                         Post post = new Post(UUID.fromString(id), sone, time, text);
301                                         postCache.put(id, post);
302                                         sone.addPost(post);
303                                 } while (true);
304                                 int replyCounter = 0;
305                                 do {
306                                         String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
307                                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
308                                         if (replyId == null) {
309                                                 break;
310                                         }
311                                         Sone replySone = soneCache.get(configuration.getStringValue(replyPrefix + "/Sone/ID").getValue(null));
312                                         String replySoneKey = configuration.getStringValue(replyPrefix + "/Sone/Key").getValue(null);
313                                         String replySoneName = configuration.getStringValue(replyPrefix + "/Sone/Name").getValue(null);
314                                         if (replySone instanceof SoneShell) {
315                                                 ((SoneShell) replySone).setRequestUri(new FreenetURI(replySoneKey)).setName(replySoneName);
316                                         }
317                                         Post replyPost = postCache.get(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
318                                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
319                                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
320                                         Reply reply = new ReplyShell().setSone(replySone).setPost(replyPost).setTime(replyTime).setText(replyText).getShelled();
321                                         replyCache.put(replyId, reply);
322                                 } while (true);
323                                 sone.setModificationCounter(modificationCounter);
324                                 addSone(sone);
325                         } catch (MalformedURLException mue1) {
326                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
327                         }
328                 } while (true);
329                 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
330
331                 logger.exiting(Core.class.getName(), "loadConfiguration()");
332         }
333
334         /**
335          * Saves the configuraiton.
336          */
337         private void saveConfiguration() {
338                 Set<Sone> sones = getSones();
339                 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
340                 try {
341                         /* store all Sones. */
342                         int soneId = 0;
343                         for (Sone sone : localSones) {
344                                 String sonePrefix = "Sone/Sone." + soneId++;
345                                 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
346                                 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
347                                 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
348                                 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
349                                 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
350                                 Profile profile = sone.getProfile();
351                                 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
352                                 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
353                                 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
354                                 int postId = 0;
355                                 for (Post post : sone.getPosts()) {
356                                         String postPrefix = sonePrefix + "/Post." + postId++;
357                                         configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
358                                         configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
359                                         configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
360                                 }
361                                 /* write null ID as terminator. */
362                                 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
363
364                                 int replyId = 0;
365                                 for (Reply reply : sone.getReplies()) {
366                                         String replyPrefix = sonePrefix + "/Reply." + replyId++;
367                                         configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
368                                         configuration.getStringValue(replyPrefix + "/Sone/ID").setValue(reply.getSone().getId());
369                                         configuration.getStringValue(replyPrefix + "/Sone/Key").setValue(reply.getSone().getRequestUri().toString());
370                                         configuration.getStringValue(replyPrefix + "/Sone/Name").setValue(reply.getSone().getName());
371                                         configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
372                                         configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
373                                         configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
374                                 }
375                                 /* write null ID as terminator. */
376                                 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
377                         }
378                         /* write null ID as terminator. */
379                         configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
380
381                 } catch (ConfigurationException ce1) {
382                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
383                 }
384         }
385
386 }