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