Rename fetch action methods
[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.FreenetInterface.Fetched;
34 import net.pterodactylus.sone.core.event.UpdateFoundEvent;
35 import net.pterodactylus.sone.main.SonePlugin;
36 import net.pterodactylus.util.io.Closer;
37 import net.pterodactylus.util.version.Version;
38
39 import com.google.common.eventbus.EventBus;
40 import com.google.inject.Inject;
41
42 import freenet.keys.FreenetURI;
43 import freenet.support.api.Bucket;
44
45 /**
46  * Watches the official Sone homepage for new releases.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 @Singleton
51 public class UpdateChecker {
52
53         /** The logger. */
54         private static final Logger logger = getLogger(UpdateChecker.class.getName());
55
56         /** The event bus. */
57         private final EventBus eventBus;
58
59         /** The Freenet interface. */
60         private final FreenetInterface freenetInterface;
61
62         /** The current URI of the homepage. */
63         private FreenetURI currentUri;
64
65         /** The latest known edition. */
66         private long latestEdition = SonePlugin.getLatestEdition();
67
68         /** The current latest known version. */
69         private Version currentLatestVersion;
70         private final Version currentRunningVersion;
71
72         /** The release date of the latest version. */
73         private long latestVersionDate;
74
75         /**
76          * Creates a new update checker.
77          *
78          * @param eventBus
79          *            The event bus
80          * @param freenetInterface
81          *            The freenet interface to use
82          */
83         @Inject
84         public UpdateChecker(EventBus eventBus, FreenetInterface freenetInterface, Version currentVersion) {
85                 this.eventBus = eventBus;
86                 this.freenetInterface = freenetInterface;
87                 this.currentRunningVersion = currentVersion;
88                 this.currentLatestVersion = currentVersion;
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(currentRunningVersion) > 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(SonePlugin.getHomepage());
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                         boolean disruptive = disruptiveVersionBetweenCurrentAndFound(properties);
228                         logger.log(Level.INFO, String.format("Found new version: %s (%tc%s)", version, new Date(releaseTime), disruptive ? ", disruptive" : ""));
229                         eventBus.post(new UpdateFoundEvent(version, releaseTime, edition, disruptive));
230                 }
231         }
232
233         private boolean disruptiveVersionBetweenCurrentAndFound(Properties properties) {
234                 for (String key : properties.stringPropertyNames()) {
235                         if (key.startsWith("DisruptiveVersion/")) {
236                                 Version disruptiveVersion = Version.parse(key.substring("DisruptiveVersion/".length()));
237                                 if (disruptiveVersion.compareTo(currentRunningVersion) > 0) {
238                                         return true;
239                                 }
240                         }
241                 }
242                 return false;
243         }
244
245 }