Set local Sones in posts deliverd by AJAX.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / UpdateChecker.java
1 /*
2  * Sone - UpdateChecker.java - Copyright © 2011 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.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.net.MalformedURLException;
24 import java.util.Date;
25 import java.util.Properties;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.main.SonePlugin;
30 import net.pterodactylus.util.collection.Pair;
31 import net.pterodactylus.util.io.Closer;
32 import net.pterodactylus.util.logging.Logging;
33 import net.pterodactylus.util.version.Version;
34 import freenet.client.FetchResult;
35 import freenet.keys.FreenetURI;
36 import freenet.support.api.Bucket;
37
38 /**
39  * Watches the official Sone homepage for new releases.
40  *
41  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
42  */
43 public class UpdateChecker {
44
45         /** The logger. */
46         private static final Logger logger = Logging.getLogger(UpdateChecker.class);
47
48         /** The key of the Sone homepage. */
49         private static final String SONE_HOMEPAGE = "USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/";
50
51         /** The current latest known edition. */
52         private static final int LATEST_EDITION = 25;
53
54         /** The Freenet interface. */
55         private final FreenetInterface freenetInterface;
56
57         /** The update listener manager. */
58         private final UpdateListenerManager updateListenerManager = new UpdateListenerManager();
59
60         /** The current URI of the homepage. */
61         private FreenetURI currentUri;
62
63         /** The latest known edition. */
64         private long latestEdition;
65
66         /** The current latest known version. */
67         private Version currentLatestVersion = SonePlugin.VERSION;
68
69         /** The release date of the latest version. */
70         private long latestVersionDate;
71
72         /**
73          * Creates a new update checker.
74          *
75          * @param freenetInterface
76          *            The freenet interface to use
77          */
78         public UpdateChecker(FreenetInterface freenetInterface) {
79                 this.freenetInterface = freenetInterface;
80         }
81
82         //
83         // EVENT LISTENER MANAGEMENT
84         //
85
86         /**
87          * Adds the given listener to the list of registered listeners.
88          *
89          * @param updateListener
90          *            The listener to add
91          */
92         public void addUpdateListener(UpdateListener updateListener) {
93                 updateListenerManager.addListener(updateListener);
94         }
95
96         /**
97          * Removes the given listener from the list of registered listeners.
98          *
99          * @param updateListener
100          *            The listener to remove
101          */
102         public void removeUpdateListener(UpdateListener updateListener) {
103                 updateListenerManager.removeListener(updateListener);
104         }
105
106         //
107         // ACCESSORS
108         //
109
110         /**
111          * Returns whether a version that is later than the currently running
112          * version has been found.
113          *
114          * @return {@code true} if a new version was found
115          */
116         public boolean hasLatestVersion() {
117                 return currentLatestVersion.compareTo(SonePlugin.VERSION) > 0;
118         }
119
120         /**
121          * Returns the latest version. If no new latest version has been found, the
122          * current version is returned.
123          *
124          * @return The latest known version
125          */
126         public Version getLatestVersion() {
127                 return currentLatestVersion;
128         }
129
130         /**
131          * Returns the release time of the latest version. If no new latest version
132          * has been found, the returned value is undefined.
133          *
134          * @return The release time of the latest version, if a new version was
135          *         found
136          */
137         public long getLatestVersionDate() {
138                 return latestVersionDate;
139         }
140
141         /**
142          * Returns the latest known edition of the Sone homepage.
143          *
144          * @return The latest edition of the Sone homepage
145          */
146         public long getLatestEdition() {
147                 return latestEdition;
148         }
149
150         //
151         // ACTIONS
152         //
153
154         /**
155          * Starts the update checker.
156          */
157         public void start() {
158                 try {
159                         currentUri = new FreenetURI(SONE_HOMEPAGE + LATEST_EDITION);
160                 } catch (MalformedURLException mue1) {
161                         /* this can not really happen unless I screw up. */
162                         logger.log(Level.SEVERE, "Sone Homepage URI invalid!", mue1);
163                 }
164                 freenetInterface.registerUsk(currentUri, new FreenetInterface.Callback() {
165
166                         @Override
167                         @SuppressWarnings("synthetic-access")
168                         public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot) {
169                                 logger.log(Level.FINEST, "Found update for %s: %d, %s, %s", new Object[] { uri, edition, newKnownGood, newSlot });
170                                 if (newKnownGood || newSlot) {
171                                         Pair<FreenetURI, FetchResult> uriResult = freenetInterface.fetchUri(uri.setMetaString(new String[] { "sone.properties" }));
172                                         if (uriResult == null) {
173                                                 logger.log(Level.WARNING, "Could not fetch properties of latest homepage: %s", uri);
174                                                 return;
175                                         }
176                                         Bucket resultBucket = uriResult.getRight().asBucket();
177                                         try {
178                                                 parseProperties(resultBucket.getInputStream(), edition);
179                                                 latestEdition = edition;
180                                         } catch (IOException ioe1) {
181                                                 logger.log(Level.WARNING, "Could not parse sone.properties of " + uri, ioe1);
182                                         } finally {
183                                                 resultBucket.free();
184                                         }
185                                 }
186                         }
187                 });
188         }
189
190         /**
191          * Stops the update checker.
192          */
193         public void stop() {
194                 freenetInterface.unregisterUsk(currentUri);
195         }
196
197         //
198         // PRIVATE ACTIONS
199         //
200
201         /**
202          * Parses the properties of the latest version and fires events, if
203          * necessary.
204          *
205          * @see UpdateListener#updateFound(Version, long, long)
206          * @see UpdateListenerManager#fireUpdateFound(Version, long, long)
207          * @param propertiesInputStream
208          *            The input stream to parse
209          * @param edition
210          *            The latest edition of the Sone homepage
211          * @throws IOException
212          *             if an I/O error occured
213          */
214         private void parseProperties(InputStream propertiesInputStream, long edition) throws IOException {
215                 Properties properties = new Properties();
216                 InputStreamReader inputStreamReader = null;
217                 try {
218                         inputStreamReader = new InputStreamReader(propertiesInputStream, "UTF-8");
219                         properties.load(inputStreamReader);
220                 } finally {
221                         Closer.close(inputStreamReader);
222                 }
223                 String versionString = properties.getProperty("CurrentVersion/Version");
224                 String releaseTimeString = properties.getProperty("CurrentVersion/ReleaseTime");
225                 if ((versionString == null) || (releaseTimeString == null)) {
226                         logger.log(Level.INFO, "Invalid data parsed from properties.");
227                         return;
228                 }
229                 Version version = Version.parse(versionString);
230                 long releaseTime = 0;
231                 try {
232                         releaseTime = Long.parseLong(releaseTimeString);
233                 } catch (NumberFormatException nfe1) {
234                         /* ignore. */
235                 }
236                 if ((version == null) || (releaseTime == 0)) {
237                         logger.log(Level.INFO, "Could not parse data from properties.");
238                         return;
239                 }
240                 if (version.compareTo(currentLatestVersion) > 0) {
241                         currentLatestVersion = version;
242                         latestVersionDate = releaseTime;
243                         logger.log(Level.INFO, "Found new version: %s (%tc)", new Object[] { version, new Date(releaseTime) });
244                         updateListenerManager.fireUpdateFound(version, releaseTime, edition);
245                 }
246         }
247
248 }