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