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

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