Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

UpdateChecker.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /*
  2. * Copyright (c) 2006-2010 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. /** 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. /**
  97. * Instantiates an Updatechecker.
  98. */
  99. public UpdateChecker() {
  100. //Ignore
  101. }
  102. /** {@inheritDoc} */
  103. @Override
  104. public void run() {
  105. if (!mutex.tryAcquire()) {
  106. // Duplicate invocation
  107. return;
  108. }
  109. final ConfigManager config = IdentityManager.getGlobalConfig();
  110. if (!config.getOptionBool("updater", "enable")
  111. || status == STATE.UPDATING) {
  112. IdentityManager.getConfigIdentity().setOption("updater",
  113. "lastcheck", String.valueOf((int) (new Date().getTime() / 1000)));
  114. mutex.release();
  115. init();
  116. return;
  117. }
  118. setStatus(STATE.CHECKING);
  119. // Remove any existing update that isn't waiting for a restart.
  120. for (Update update : new ArrayList<Update>(updates)) {
  121. if (update.getStatus() != UpdateStatus.RESTART_NEEDED) {
  122. updates.remove(update);
  123. }
  124. }
  125. final StringBuilder data = new StringBuilder();
  126. final String updateChannel = config.getOption("updater", "channel");
  127. // Build the data string to send to the server
  128. for (UpdateComponent component : components) {
  129. if (isEnabled(component)) {
  130. data.append(component.getName());
  131. data.append(',');
  132. data.append(updateChannel);
  133. data.append(',');
  134. data.append(component.getVersion());
  135. data.append(';');
  136. }
  137. }
  138. // If we actually have components to check
  139. if (data.length() > 0) {
  140. try {
  141. final List<String> response
  142. = Downloader.getPage("http://updates.dmdirc.com/", "data=" + data);
  143. for (String line : response) {
  144. checkLine(line);
  145. }
  146. } catch (MalformedURLException ex) {
  147. Logger.appError(ErrorLevel.LOW, "Error when checking for updates", ex);
  148. } catch (IOException ex) {
  149. Logger.userError(ErrorLevel.LOW,
  150. "I/O error when checking for updates: " + ex.getMessage());
  151. }
  152. }
  153. if (updates.isEmpty()) {
  154. setStatus(STATE.IDLE);
  155. } else {
  156. boolean available = false;
  157. // Check to see if the updates are outstanding or just waiting for
  158. // a restart
  159. for (Update update : updates) {
  160. if (update.getStatus() == UpdateStatus.PENDING) {
  161. available = true;
  162. }
  163. }
  164. setStatus(available ? STATE.UPDATES_AVAILABLE : STATE.RESTART_REQUIRED);
  165. }
  166. mutex.release();
  167. IdentityManager.getConfigIdentity().setOption("updater",
  168. "lastcheck", String.valueOf((int) (new Date().getTime() / 1000)));
  169. UpdateChecker.init();
  170. if (config.getOptionBool("updater", "autoupdate")) {
  171. applyUpdates();
  172. }
  173. }
  174. /**
  175. * Checks the specified line to determine the message from the update server.
  176. *
  177. * @param line The line to be checked
  178. */
  179. private void checkLine(final String line) {
  180. if (line.startsWith("outofdate")) {
  181. doUpdateAvailable(line);
  182. } else if (line.startsWith("error")) {
  183. String errorMessage = "Error when checking for updates: " + line.substring(6);
  184. final String[] bits = line.split(" ");
  185. if (bits.length > 2) {
  186. final UpdateComponent thisComponent = findComponent(bits[2]);
  187. if (thisComponent != null) {
  188. if (thisComponent instanceof FileComponent) {
  189. errorMessage = errorMessage + " (" + ((FileComponent)thisComponent).getFileName() + ")";
  190. }
  191. }
  192. }
  193. Logger.userError(ErrorLevel.LOW, errorMessage);
  194. } else if (!line.startsWith("uptodate")) {
  195. Logger.userError(ErrorLevel.LOW, "Unknown update line received from server: "
  196. + line);
  197. }
  198. }
  199. /**
  200. * Informs the user that there's an update available.
  201. *
  202. * @param line The line that was received from the update server
  203. */
  204. private void doUpdateAvailable(final String line) {
  205. final Update update = new Update(line);
  206. if (update.getUrl() != null) {
  207. updates.add(update);
  208. update.addUpdateListener(listener);
  209. }
  210. }
  211. /**
  212. * Initialises the update checker. Sets a timer to check based on the
  213. * frequency specified in the config.
  214. */
  215. public static void init() {
  216. final int last = IdentityManager.getGlobalConfig()
  217. .getOptionInt("updater", "lastcheck");
  218. final int freq = IdentityManager.getGlobalConfig()
  219. .getOptionInt("updater", "frequency");
  220. final int timestamp = (int) (new Date().getTime() / 1000);
  221. int time = 0;
  222. if (last + freq > timestamp) {
  223. time = last + freq - timestamp;
  224. }
  225. if (time > freq || time < 0) {
  226. Logger.userError(ErrorLevel.LOW, "Attempted to schedule update check "
  227. + (time < 0 ? "in the past" : "too far in the future")
  228. + ", rescheduling.");
  229. time = 1;
  230. }
  231. timer.cancel();
  232. timer = new Timer("Update Checker Timer");
  233. timer.schedule(new TimerTask() {
  234. /** {@inheritDoc} */
  235. @Override
  236. public void run() {
  237. checkNow();
  238. }
  239. }, time * 1000);
  240. }
  241. /**
  242. * Checks for updates now.
  243. */
  244. public static void checkNow() {
  245. new Thread(new UpdateChecker(), "Update Checker thread").start();
  246. }
  247. /**
  248. * Registers an update component.
  249. *
  250. * @param component The component to be registered
  251. */
  252. public static void registerComponent(final UpdateComponent component) {
  253. components.add(component);
  254. }
  255. /**
  256. * Unregisters an update component with the specified name.
  257. *
  258. * @param name The name of the component to be removed
  259. */
  260. public static void removeComponent(final String name) {
  261. UpdateComponent target = null;
  262. for (UpdateComponent component : components) {
  263. if (name.equals(component.getName())) {
  264. target = component;
  265. }
  266. }
  267. if (target != null) {
  268. components.remove(target);
  269. }
  270. }
  271. /**
  272. * Finds and returns the component with the specified name.
  273. *
  274. * @param name The name of the component that we're looking for
  275. * @return The corresponding UpdateComponent, or null if it's not found
  276. */
  277. @Precondition("The specified name is not null")
  278. public static UpdateComponent findComponent(final String name) {
  279. assert(name != null);
  280. for (UpdateComponent component : components) {
  281. if (name.equals(component.getName())) {
  282. return component;
  283. }
  284. }
  285. return null;
  286. }
  287. /**
  288. * Removes the specified update from the list. This should be called when
  289. * the update has finished, has encountered an error, or the user does not
  290. * want the update to be performed.
  291. *
  292. * @param update The update to be removed
  293. */
  294. public static void removeUpdate(final Update update) {
  295. update.removeUpdateListener(listener);
  296. updates.remove(update);
  297. if (updates.isEmpty()) {
  298. setStatus(STATE.IDLE);
  299. } else if (status == STATE.UPDATING) {
  300. doNextUpdate();
  301. }
  302. }
  303. /**
  304. * Downloads and installs all known updates.
  305. */
  306. public static void applyUpdates() {
  307. if (!updates.isEmpty()) {
  308. setStatus(STATE.UPDATING);
  309. doNextUpdate();
  310. }
  311. }
  312. /**
  313. * Finds and applies the next pending update, or sets the state to idle
  314. * / restart needed if appropriate.
  315. */
  316. private static void doNextUpdate() {
  317. boolean restart = false;
  318. for (Update update : updates) {
  319. if (update.getStatus() == UpdateStatus.PENDING) {
  320. update.doUpdate();
  321. return;
  322. } else if (update.getStatus() == UpdateStatus.RESTART_NEEDED) {
  323. restart = true;
  324. }
  325. }
  326. setStatus(restart ? STATE.RESTART_REQUIRED : STATE.IDLE);
  327. }
  328. /**
  329. * Retrieves a list of components registered with the checker.
  330. *
  331. * @return A list of registered components
  332. */
  333. public static List<UpdateComponent> getComponents() {
  334. return components;
  335. }
  336. /**
  337. * Retrives a list of available updates from the checker.
  338. *
  339. * @return A list of available updates
  340. */
  341. public static List<Update> getAvailableUpdates() {
  342. return updates;
  343. }
  344. /**
  345. * Adds a new status listener to the update checker.
  346. *
  347. * @param listener The listener to be added
  348. */
  349. public static void addListener(final UpdateCheckerListener listener) {
  350. listeners.add(UpdateCheckerListener.class, listener);
  351. }
  352. /**
  353. * Removes a status listener from the update checker.
  354. *
  355. * @param listener The listener to be removed
  356. */
  357. public static void removeListener(final UpdateCheckerListener listener) {
  358. listeners.remove(UpdateCheckerListener.class, listener);
  359. }
  360. /**
  361. * Retrieves the current status of the update checker.
  362. *
  363. * @return The update checker's current status
  364. */
  365. public static STATE getStatus() {
  366. return status;
  367. }
  368. /**
  369. * Sets the status of the update checker to the specified new status.
  370. *
  371. * @param newStatus The new status of this checker
  372. */
  373. private static void setStatus(final STATE newStatus) {
  374. status = newStatus;
  375. for (UpdateCheckerListener myListener : listeners.get(UpdateCheckerListener.class)) {
  376. myListener.statusChanged(newStatus);
  377. }
  378. }
  379. /**
  380. * Checks is a specified component is enabled.
  381. *
  382. * @param component Update component to check state
  383. * @return true iif the update component is enabled
  384. */
  385. public static boolean isEnabled(final UpdateComponent component) {
  386. return !IdentityManager.getGlobalConfig().hasOptionBool("updater",
  387. "enable-" + component.getName()) || IdentityManager.getGlobalConfig()
  388. .getOptionBool("updater", "enable-" + component.getName());
  389. }
  390. }