Declare update checker to be a singleton
[Sone.git] / src / main / java / net / pterodactylus / sone / core / UpdateChecker.java
1 /*
2  * Sone - UpdateChecker.java - Copyright © 2011–2015 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;
67
68         /** The current latest known version. */
69         private Version currentLatestVersion = SonePlugin.VERSION;
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) {
84                 this.eventBus = eventBus;
85                 this.freenetInterface = freenetInterface;
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(SonePlugin.VERSION) > 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                         logger.log(Level.INFO, String.format("Found new version: %s (%tc)", version, new Date(releaseTime)));
225                         eventBus.post(new UpdateFoundEvent(version, releaseTime, edition));
226                 }
227         }
228
229 }