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.

TransferContainer.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (c) 2006-2017 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  5. * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  7. * permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  10. * Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  13. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  14. * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  16. */
  17. package com.dmdirc.addons.dcc;
  18. import com.dmdirc.FrameContainer;
  19. import com.dmdirc.ServerState;
  20. import com.dmdirc.addons.dcc.events.DccSendDatatransferedEvent;
  21. import com.dmdirc.addons.dcc.events.DccSendSocketclosedEvent;
  22. import com.dmdirc.addons.dcc.events.DccSendSocketopenedEvent;
  23. import com.dmdirc.addons.dcc.io.DCC;
  24. import com.dmdirc.addons.dcc.io.DCCTransfer;
  25. import com.dmdirc.interfaces.Connection;
  26. import com.dmdirc.interfaces.EventBus;
  27. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  28. import com.dmdirc.parser.events.SocketCloseEvent;
  29. import com.dmdirc.parser.interfaces.Parser;
  30. import com.dmdirc.ui.messages.BackBufferFactory;
  31. import java.awt.Desktop;
  32. import java.io.File;
  33. import java.util.Arrays;
  34. import java.util.Optional;
  35. import javax.annotation.Nullable;
  36. import javax.swing.JOptionPane;
  37. import net.engio.mbassy.listener.Handler;
  38. /**
  39. * This class links DCC Send objects to a window.
  40. */
  41. public class TransferContainer extends FrameContainer implements
  42. DCCTransferHandler {
  43. /** The dcc plugin that owns this frame */
  44. protected final DCCManager plugin;
  45. /** Config manager. */
  46. private final AggregateConfigProvider config;
  47. /** The Window we're using. */
  48. private boolean windowClosing = false;
  49. /** The DCCSend object we are a window for */
  50. private final DCCTransfer dcc;
  51. /** Other Nickname */
  52. private final String otherNickname;
  53. /** Total data transferred */
  54. private volatile long transferCount = 0;
  55. /** Time Started */
  56. private long timeStarted = 0;
  57. /** Plugin that this send belongs to. */
  58. private final DCCManager myPlugin;
  59. /** IRC Parser that caused this send */
  60. @Nullable
  61. private Parser parser;
  62. /** Connection the send was initiated on. */
  63. @Nullable
  64. private final Connection connection;
  65. /** Show open button. */
  66. private final boolean showOpen = Desktop.isDesktopSupported()
  67. && Desktop.getDesktop().isSupported(Desktop.Action.OPEN);
  68. /** Event bus to post events on. */
  69. private final EventBus eventBus;
  70. /**
  71. * Creates a new instance of DCCTransferWindow with a given DCCTransfer object.
  72. */
  73. public TransferContainer(final DCCManager plugin, final DCCTransfer dcc,
  74. final AggregateConfigProvider config,
  75. final BackBufferFactory backBufferFactory, final String title,
  76. final String targetNick, @Nullable final Connection connection,
  77. final EventBus eventBus) {
  78. super(dcc.getType() == DCCTransfer.TransferType.SEND
  79. ? "dcc-send-inactive" : "dcc-receive-inactive",
  80. title, title, config, backBufferFactory, eventBus,
  81. Arrays.asList("com.dmdirc.addons.dcc.ui.TransferPanel"));
  82. this.plugin = plugin;
  83. this.dcc = dcc;
  84. this.connection = connection;
  85. this.config = config;
  86. parser = Optional.ofNullable(connection).flatMap(Connection::getParser).orElse(null);
  87. myPlugin = plugin;
  88. if (parser != null) {
  89. parser.getCallbackManager().subscribe(this);
  90. }
  91. dcc.addHandler(this);
  92. otherNickname = targetNick;
  93. this.eventBus = eventBus;
  94. initBackBuffer();
  95. }
  96. @Handler
  97. public void onSocketClosed(final SocketCloseEvent event) {
  98. // Remove our reference to the parser (and its reference to us)
  99. parser.getCallbackManager().unsubscribe(this);
  100. this.parser = null;
  101. }
  102. /**
  103. * Get the DCCSend Object associated with this window
  104. *
  105. * @return The DCCSend Object associated with this window
  106. */
  107. public DCCTransfer getDCC() {
  108. return dcc;
  109. }
  110. /**
  111. * Retrieves the nickname of the other party involved in this transfer.
  112. *
  113. * @return The other party's nickname
  114. *
  115. * @since 0.6.4
  116. */
  117. public String getOtherNickname() {
  118. return otherNickname;
  119. }
  120. /**
  121. * Called when data is sent/received
  122. *
  123. * @param dcc The DCCSend that this message is from
  124. * @param bytes The number of new bytes that were transferred
  125. */
  126. @Override
  127. public void dataTransferred(final DCCTransfer dcc, final int bytes) {
  128. final double percent;
  129. synchronized (this) {
  130. transferCount += bytes;
  131. percent = getPercent();
  132. }
  133. final boolean percentageInTitle = config.getOptionBool(
  134. plugin.getDomain(), "general.percentageInTitle");
  135. if (percentageInTitle) {
  136. final StringBuilder title = new StringBuilder();
  137. if (dcc.isListenSocket()) {
  138. title.append('*');
  139. }
  140. title.append(dcc.getType() == DCCTransfer.TransferType.SEND
  141. ? "Sending: " : "Receiving: ");
  142. title.append(otherNickname);
  143. title.append(" (")
  144. .append(String.format("%.0f", Math.floor(percent)))
  145. .append("%)");
  146. setName(title.toString());
  147. setTitle(title.toString());
  148. }
  149. eventBus.publish(new DccSendDatatransferedEvent(this, bytes));
  150. }
  151. /**
  152. * Retrieves the current percentage progress of this transfer.
  153. *
  154. * @since 0.6.4
  155. * @return The percentage of this transfer that has been completed
  156. */
  157. public double getPercent() {
  158. return 100.00 / dcc.getFileSize() * (transferCount
  159. + dcc.getFileStart());
  160. }
  161. /**
  162. * Retrieves the current transfer speed of this transfer.
  163. *
  164. * @since 0.6.4
  165. * @return The speed of this transfer in Bytes/Sec
  166. */
  167. public double getBytesPerSecond() {
  168. final long time = getElapsedTime();
  169. synchronized (this) {
  170. return time > 0 ? (double) transferCount / time : transferCount;
  171. }
  172. }
  173. /**
  174. * Retrieves the estimated time remaining for this transfer.
  175. *
  176. * @since 0.6.4
  177. * @return The number of seconds estimated for this transfer to complete
  178. */
  179. public double getRemainingTime() {
  180. final double bytesPerSecond = getBytesPerSecond();
  181. final long remainingBytes;
  182. synchronized (this) {
  183. remainingBytes = dcc.getFileSize() - dcc.getFileStart()
  184. - transferCount;
  185. }
  186. return bytesPerSecond > 0 ? remainingBytes / bytesPerSecond : 1;
  187. }
  188. /**
  189. * Retrieves the timestamp at which this transfer started.
  190. *
  191. * @since 0.6.4
  192. * @return The timestamp (milliseconds since 01/01/1970) at which this transfer started.
  193. */
  194. public long getStartTime() {
  195. return timeStarted;
  196. }
  197. /**
  198. * Retrieves the number of seconds that this transfer has been running for.
  199. *
  200. * @since 0.6.4
  201. * @return The number of seconds elapsed since this transfer started
  202. */
  203. public long getElapsedTime() {
  204. return (System.currentTimeMillis() - timeStarted) / 1000;
  205. }
  206. /**
  207. * Determines whether this transfer is complete or not.
  208. *
  209. * @since 0.6.4
  210. * @return True if the transfer is complete, false otherwise
  211. */
  212. public boolean isComplete() {
  213. return transferCount == dcc.getFileSize() - dcc.getFileStart();
  214. }
  215. /**
  216. * Determines whether the "Open" button should be displayed for this transfer.
  217. *
  218. * @since 0.6.4
  219. * @return True if the open button should be displayed, false otherwise
  220. */
  221. public boolean shouldShowOpenButton() {
  222. return showOpen && dcc.getType() == DCCTransfer.TransferType.RECEIVE;
  223. }
  224. /**
  225. * Called when the socket is closed
  226. *
  227. * @param dcc The DCCSend that this message is from
  228. */
  229. @Override
  230. public void socketClosed(final DCCTransfer dcc) {
  231. eventBus.publish(new DccSendSocketclosedEvent(this));
  232. if (!windowClosing) {
  233. synchronized (this) {
  234. if (transferCount == dcc.getFileSize() - dcc.getFileStart()) {
  235. setIcon(dcc.getType() == DCCTransfer.TransferType.SEND
  236. ? "dcc-send-done" : "dcc-receive-done");
  237. } else {
  238. setIcon(dcc.getType() == DCCTransfer.TransferType.SEND
  239. ? "dcc-send-failed" : "dcc-receive-failed");
  240. }
  241. }
  242. }
  243. }
  244. /**
  245. * Called when the socket is opened
  246. *
  247. * @param dcc The DCCSend that this message is from
  248. */
  249. @Override
  250. public void socketOpened(final DCCTransfer dcc) {
  251. eventBus.publish(new DccSendSocketopenedEvent(this));
  252. timeStarted = System.currentTimeMillis();
  253. setIcon(dcc.getType() == DCCTransfer.TransferType.SEND
  254. ? "dcc-send-active" : "dcc-receive-active");
  255. }
  256. /**
  257. * Attempts to resend the transfer.
  258. *
  259. * @since 0.6.4
  260. * @return True if the transfer could be resent, false otherwise
  261. */
  262. public boolean resend() {
  263. synchronized (this) {
  264. transferCount = 0;
  265. }
  266. dcc.reset();
  267. if (connection != null && connection.getState() == ServerState.CONNECTED) {
  268. final String myNickname = connection.getParser().get().getLocalClient()
  269. .getNickname();
  270. // Check again in case we have changed nickname to the same nickname
  271. //that this send is for.
  272. if (connection.getParser().get().getStringConverter().equalsIgnoreCase(
  273. otherNickname, myNickname)) {
  274. final Thread errorThread = new Thread(() -> JOptionPane.showMessageDialog(null,
  275. "You can't DCC yourself.", "DCC Error",
  276. JOptionPane.ERROR_MESSAGE), "DCC-Error-Message");
  277. errorThread.start();
  278. } else {
  279. if (config.getOptionBool(plugin.getDomain(), "send.reverse")) {
  280. parser.sendCTCP(otherNickname, "DCC", "SEND \"" + new File(dcc.getFileName()).
  281. getName() + "\" "
  282. + DCC.ipToLong(myPlugin.getListenIP(parser))
  283. + " 0 " + dcc.getFileSize() + " " + dcc.makeToken()
  284. + ((dcc.isTurbo()) ? " T" : ""));
  285. } else if (plugin.listen(dcc)) {
  286. parser.sendCTCP(otherNickname, "DCC", "SEND \""
  287. + new File(dcc.getFileName()).getName() + "\" "
  288. + DCC.ipToLong(myPlugin.getListenIP(parser)) + " "
  289. + dcc.getPort() + " " + dcc.getFileSize()
  290. + ((dcc.isTurbo()) ? " T" : ""));
  291. }
  292. }
  293. return true;
  294. }
  295. return false;
  296. }
  297. /**
  298. * Closes this container (and it's associated frame).
  299. */
  300. @Override
  301. public void close() {
  302. windowClosing = true;
  303. super.close();
  304. dcc.removeFromTransfers();
  305. }
  306. @Override
  307. public Optional<Connection> getConnection() {
  308. return Optional.empty();
  309. }
  310. }