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