You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UpdateChecker.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*
  2. * Copyright (c) 2006-2011 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.updater;
  23. import com.dmdirc.Precondition;
  24. import com.dmdirc.config.ConfigManager;
  25. import com.dmdirc.config.IdentityManager;
  26. import com.dmdirc.logger.ErrorLevel;
  27. import com.dmdirc.logger.Logger;
  28. import com.dmdirc.updater.components.ClientComponent;
  29. import com.dmdirc.updater.components.DefaultsComponent;
  30. import com.dmdirc.updater.components.ModeAliasesComponent;
  31. import com.dmdirc.util.Downloader;
  32. import com.dmdirc.util.ListenerList;
  33. import java.io.IOException;
  34. import java.net.MalformedURLException;
  35. import java.util.ArrayList;
  36. import java.util.Date;
  37. import java.util.List;
  38. import java.util.Timer;
  39. import java.util.TimerTask;
  40. import java.util.concurrent.Semaphore;
  41. /**
  42. * The update checker contacts the DMDirc website to check to see if there
  43. * are any updates available.
  44. */
  45. public final class UpdateChecker implements Runnable {
  46. /** The possible states for the checker. */
  47. public static enum STATE {
  48. /** Nothing's happening. */
  49. IDLE,
  50. /** Currently checking for updates. */
  51. CHECKING,
  52. /** Currently updating. */
  53. UPDATING,
  54. /** New updates are available. */
  55. UPDATES_AVAILABLE,
  56. /** Updates installed but restart needed. */
  57. RESTART_REQUIRED,
  58. }
  59. /** The domain to use for updater settings. */
  60. private static final String DOMAIN = "updater";
  61. /** Semaphore used to prevent multiple invocations. */
  62. private static final Semaphore MUTEX = new Semaphore(1);
  63. /** A list of components that we're to check. */
  64. private static final List<UpdateComponent> COMPONENTS
  65. = new ArrayList<UpdateComponent>();
  66. /** Our timer. */
  67. private static Timer timer = new Timer("Update Checker Timer");
  68. /** The list of updates that are available. */
  69. private static final List<Update> UPDATES = new ArrayList<Update>();
  70. /** A list of our listeners. */
  71. private static final ListenerList LISTENERS = new ListenerList();
  72. /** Our current state. */
  73. private static STATE status = STATE.IDLE;
  74. /** A reference to the listener we use for update status changes. */
  75. private static final UpdateListener LISTENER = new UpdateListener() {
  76. @Override
  77. public void updateStatusChange(final Update update, final UpdateStatus status) {
  78. if (status == UpdateStatus.INSTALLED
  79. || status == UpdateStatus.ERROR) {
  80. removeUpdate(update);
  81. } else if (status == UpdateStatus.RESTART_NEEDED && UpdateChecker.status
  82. == STATE.UPDATING) {
  83. doNextUpdate();
  84. }
  85. }
  86. @Override
  87. public void updateProgressChange(final Update update, final float progress) {
  88. // Don't care
  89. }
  90. };
  91. static {
  92. COMPONENTS.add(new ClientComponent());
  93. COMPONENTS.add(new ModeAliasesComponent());
  94. COMPONENTS.add(new DefaultsComponent());
  95. }
  96. /** {@inheritDoc} */
  97. @Override
  98. public void run() {
  99. if (!MUTEX.tryAcquire()) {
  100. // Duplicate invocation
  101. return;
  102. }
  103. final ConfigManager config = IdentityManager.getGlobalConfig();
  104. if (!config.getOptionBool(DOMAIN, "enable")
  105. || status == STATE.UPDATING) {
  106. IdentityManager.getConfigIdentity().setOption(DOMAIN,
  107. "lastcheck", String.valueOf((int) (new Date().getTime() / 1000)));
  108. MUTEX.release();
  109. initTimer();
  110. return;
  111. }
  112. setStatus(STATE.CHECKING);
  113. // Remove any existing update that isn't waiting for a restart.
  114. for (Update update : new ArrayList<Update>(UPDATES)) {
  115. if (update.getStatus() != UpdateStatus.RESTART_NEEDED) {
  116. UPDATES.remove(update);
  117. }
  118. }
  119. final StringBuilder data = new StringBuilder();
  120. final String updateChannel = config.getOption(DOMAIN, "channel");
  121. // Build the data string to send to the server
  122. for (UpdateComponent component : COMPONENTS) {
  123. if (isEnabled(component)) {
  124. data.append(component.getName());
  125. data.append(',');
  126. data.append(updateChannel);
  127. data.append(',');
  128. data.append(component.getVersion());
  129. data.append(';');
  130. }
  131. }
  132. // If we actually have components to check
  133. if (data.length() > 0) {
  134. try {
  135. final List<String> response
  136. = Downloader.getPage("http://updates.dmdirc.com/", "data=" + data);
  137. for (String line : response) {
  138. checkLine(line);
  139. }
  140. } catch (MalformedURLException ex) {
  141. Logger.appError(ErrorLevel.LOW, "Error when checking for updates", ex);
  142. } catch (IOException ex) {
  143. Logger.userError(ErrorLevel.LOW,
  144. "I/O error when checking for updates: " + ex.getMessage());
  145. }
  146. }
  147. if (UPDATES.isEmpty()) {
  148. setStatus(STATE.IDLE);
  149. } else {
  150. boolean available = false;
  151. // Check to see if the updates are outstanding or just waiting for
  152. // a restart
  153. for (Update update : UPDATES) {
  154. if (update.getStatus() == UpdateStatus.PENDING) {
  155. available = true;
  156. }
  157. }
  158. setStatus(available ? STATE.UPDATES_AVAILABLE : STATE.RESTART_REQUIRED);
  159. }
  160. updateCachedUpdates();
  161. MUTEX.release();
  162. IdentityManager.getConfigIdentity().setOption(DOMAIN,
  163. "lastcheck", String.valueOf((int) (new Date().getTime() / 1000)));
  164. UpdateChecker.initTimer();
  165. if (config.getOptionBool(DOMAIN, "autoupdate")) {
  166. applyUpdates();
  167. }
  168. }
  169. /**
  170. * Updates the cache of pending updates in the configuration file.
  171. *
  172. * @since 0.6.5
  173. */
  174. private static void updateCachedUpdates() {
  175. final List<String> stringCopies = new ArrayList<String>();
  176. for (Update update : UPDATES) {
  177. // Only include outstanding updates
  178. if (update.getStatus() == UpdateStatus.PENDING
  179. || update.getStatus() == UpdateStatus.ERROR) {
  180. stringCopies.add(update.getStringRepresentation());
  181. }
  182. }
  183. IdentityManager.getConfigIdentity().setOption(DOMAIN, "updates", stringCopies);
  184. }
  185. /**
  186. * Checks the specified line to determine the message from the update server.
  187. *
  188. * @param line The line to be checked
  189. */
  190. private static void checkLine(final String line) {
  191. if (line.startsWith("outofdate")) {
  192. doUpdateAvailable(line);
  193. } else if (line.startsWith("error")) {
  194. String errorMessage = "Error when checking for updates: " + line.substring(6);
  195. final String[] bits = line.split(" ");
  196. if (bits.length > 2) {
  197. final UpdateComponent thisComponent = findComponent(bits[2]);
  198. if (thisComponent instanceof FileComponent) {
  199. errorMessage = errorMessage + " (" + ((FileComponent) thisComponent)
  200. .getFileName() + ")";
  201. }
  202. }
  203. Logger.userError(ErrorLevel.LOW, errorMessage);
  204. } else if (!line.startsWith("uptodate")) {
  205. Logger.userError(ErrorLevel.LOW, "Unknown update line received from server: "
  206. + line);
  207. }
  208. }
  209. /**
  210. * Informs the user that there's an update available.
  211. *
  212. * @param line The line that was received from the update server
  213. */
  214. private static void doUpdateAvailable(final String line) {
  215. final Update update = new Update(line);
  216. if (update.getUrl() != null) {
  217. UPDATES.add(update);
  218. update.addUpdateListener(LISTENER);
  219. }
  220. }
  221. /**
  222. * Initialises the update checker. Sets a timer to check based on the
  223. * frequency specified in the config.
  224. */
  225. public static void init() {
  226. for (String update : IdentityManager.getGlobalConfig().getOptionList(DOMAIN, "updates")) {
  227. checkLine(update);
  228. }
  229. if (!UPDATES.isEmpty()) {
  230. setStatus(STATE.UPDATES_AVAILABLE);
  231. }
  232. initTimer();
  233. }
  234. /**
  235. * Initialises the timer to check for updates.
  236. *
  237. * @since 0.6.5
  238. */
  239. protected static void initTimer() {
  240. final int last = IdentityManager.getGlobalConfig()
  241. .getOptionInt(DOMAIN, "lastcheck");
  242. final int freq = IdentityManager.getGlobalConfig()
  243. .getOptionInt(DOMAIN, "frequency");
  244. final int timestamp = (int) (new Date().getTime() / 1000);
  245. int time = 0;
  246. if (last + freq > timestamp) {
  247. time = last + freq - timestamp;
  248. }
  249. if (time > freq || time < 0) {
  250. Logger.userError(ErrorLevel.LOW, "Attempted to schedule update check "
  251. + (time < 0 ? "in the past" : "too far in the future")
  252. + ", rescheduling.");
  253. time = 1;
  254. }
  255. timer.cancel();
  256. timer = new Timer("Update Checker Timer");
  257. timer.schedule(new TimerTask() {
  258. /** {@inheritDoc} */
  259. @Override
  260. public void run() {
  261. checkNow();
  262. }
  263. }, time * 1000);
  264. }
  265. /**
  266. * Checks for updates now.
  267. */
  268. public static void checkNow() {
  269. new Thread(new UpdateChecker(), "Update Checker thread").start();
  270. }
  271. /**
  272. * Registers an update component.
  273. *
  274. * @param component The component to be registered
  275. */
  276. public static void registerComponent(final UpdateComponent component) {
  277. COMPONENTS.add(component);
  278. }
  279. /**
  280. * Unregisters an update component with the specified name.
  281. *
  282. * @param name The name of the component to be removed
  283. */
  284. public static void removeComponent(final String name) {
  285. UpdateComponent target = null;
  286. for (UpdateComponent component : COMPONENTS) {
  287. if (name.equals(component.getName())) {
  288. target = component;
  289. }
  290. }
  291. if (target != null) {
  292. COMPONENTS.remove(target);
  293. }
  294. }
  295. /**
  296. * Finds and returns the component with the specified name.
  297. *
  298. * @param name The name of the component that we're looking for
  299. * @return The corresponding UpdateComponent, or null if it's not found
  300. */
  301. @Precondition("The specified name is not null")
  302. public static UpdateComponent findComponent(final String name) {
  303. assert name != null;
  304. for (UpdateComponent component : COMPONENTS) {
  305. if (name.equals(component.getName())) {
  306. return component;
  307. }
  308. }
  309. return null;
  310. }
  311. /**
  312. * Removes the specified update from the list. This should be called when
  313. * the update has finished, has encountered an error, or the user does not
  314. * want the update to be performed.
  315. *
  316. * @param update The update to be removed
  317. */
  318. public static void removeUpdate(final Update update) {
  319. update.removeUpdateListener(LISTENER);
  320. UPDATES.remove(update);
  321. if (UPDATES.isEmpty()) {
  322. setStatus(STATE.IDLE);
  323. updateCachedUpdates();
  324. } else if (status == STATE.UPDATING) {
  325. doNextUpdate();
  326. }
  327. }
  328. /**
  329. * Downloads and installs all known updates.
  330. */
  331. public static void applyUpdates() {
  332. if (!UPDATES.isEmpty()) {
  333. setStatus(STATE.UPDATING);
  334. doNextUpdate();
  335. }
  336. }
  337. /**
  338. * Finds and applies the next pending update, or sets the state to idle
  339. * / restart needed if appropriate.
  340. */
  341. private static void doNextUpdate() {
  342. boolean restart = false;
  343. for (Update update : UPDATES) {
  344. if (update.getStatus() == UpdateStatus.PENDING) {
  345. update.doUpdate();
  346. return;
  347. } else if (update.getStatus() == UpdateStatus.RESTART_NEEDED) {
  348. restart = true;
  349. }
  350. }
  351. setStatus(restart ? STATE.RESTART_REQUIRED : STATE.IDLE);
  352. updateCachedUpdates();
  353. }
  354. /**
  355. * Retrieves a list of components registered with the checker.
  356. *
  357. * @return A list of registered components
  358. */
  359. public static List<UpdateComponent> getComponents() {
  360. return COMPONENTS;
  361. }
  362. /**
  363. * Retrives a list of available updates from the checker.
  364. *
  365. * @return A list of available updates
  366. */
  367. public static List<Update> getAvailableUpdates() {
  368. return UPDATES;
  369. }
  370. /**
  371. * Adds a new status listener to the update checker.
  372. *
  373. * @param listener The listener to be added
  374. */
  375. public static void addListener(final UpdateCheckerListener listener) {
  376. LISTENERS.add(UpdateCheckerListener.class, listener);
  377. }
  378. /**
  379. * Removes a status listener from the update checker.
  380. *
  381. * @param listener The listener to be removed
  382. */
  383. public static void removeListener(final UpdateCheckerListener listener) {
  384. LISTENERS.remove(UpdateCheckerListener.class, listener);
  385. }
  386. /**
  387. * Retrieves the current status of the update checker.
  388. *
  389. * @return The update checker's current status
  390. */
  391. public static STATE getStatus() {
  392. return status;
  393. }
  394. /**
  395. * Sets the status of the update checker to the specified new status.
  396. *
  397. * @param newStatus The new status of this checker
  398. */
  399. private static void setStatus(final STATE newStatus) {
  400. status = newStatus;
  401. for (UpdateCheckerListener myListener : LISTENERS.get(UpdateCheckerListener.class)) {
  402. myListener.statusChanged(newStatus);
  403. }
  404. }
  405. /**
  406. * Checks is a specified component is enabled.
  407. *
  408. * @param component Update component to check state
  409. * @return true iif the update component is enabled
  410. */
  411. public static boolean isEnabled(final UpdateComponent component) {
  412. return !IdentityManager.getGlobalConfig().hasOptionBool(DOMAIN,
  413. "enable-" + component.getName()) || IdentityManager.getGlobalConfig()
  414. .getOptionBool(DOMAIN, "enable-" + component.getName());
  415. }
  416. }