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