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