Only store the post ID in the reply.
[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 java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.net.MalformedURLException;
24 import java.util.Date;
25 import java.util.Properties;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
30 import net.pterodactylus.sone.core.event.UpdateFoundEvent;
31 import net.pterodactylus.sone.main.SonePlugin;
32 import net.pterodactylus.util.io.Closer;
33 import net.pterodactylus.util.logging.Logging;
34 import net.pterodactylus.util.version.Version;
35
36 import com.google.common.eventbus.EventBus;
37 import com.google.inject.Inject;
38
39 import freenet.keys.FreenetURI;
40 import freenet.support.api.Bucket;
41
42 /**
43  * Watches the official Sone homepage for new releases.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public class UpdateChecker {
48
49         /** The logger. */
50         private static final Logger logger = Logging.getLogger(UpdateChecker.class);
51
52         /** The key of the Sone homepage. */
53         private static final String SONE_HOMEPAGE = "USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/";
54
55         /** The current latest known edition. */
56         private static final int LATEST_EDITION = 55;
57
58         /** The event bus. */
59         private final EventBus eventBus;
60
61         /** The Freenet interface. */
62         private final FreenetInterface freenetInterface;
63
64         /** The current URI of the homepage. */
65         private FreenetURI currentUri;
66
67         /** The latest known edition. */
68         private long latestEdition;
69
70         /** The current latest known version. */
71         private Version currentLatestVersion = SonePlugin.VERSION;
72
73         /** The release date of the latest version. */
74         private long latestVersionDate;
75
76         /**
77          * Creates a new update checker.
78          *
79          * @param eventBus
80          *            The event bus
81          * @param freenetInterface
82          *            The freenet interface to use
83          */
84         @Inject
85         public UpdateChecker(EventBus eventBus, FreenetInterface freenetInterface) {
86                 this.eventBus = eventBus;
87                 this.freenetInterface = freenetInterface;
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(SonePlugin.VERSION) > 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(SONE_HOMEPAGE + LATEST_EDITION);
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                         logger.log(Level.INFO, String.format("Found new version: %s (%tc)", version, new Date(releaseTime)));
227                         eventBus.post(new UpdateFoundEvent(version, releaseTime, edition));
228                 }
229         }
230
231 }