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