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.

Channel.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * Copyright (c) 2006-2015 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;
  23. import com.dmdirc.commandparser.CommandType;
  24. import com.dmdirc.commandparser.parsers.ChannelCommandParser;
  25. import com.dmdirc.config.ConfigBinding;
  26. import com.dmdirc.events.ChannelClosedEvent;
  27. import com.dmdirc.events.ChannelSelfActionEvent;
  28. import com.dmdirc.events.ChannelSelfJoinEvent;
  29. import com.dmdirc.events.ChannelSelfMessageEvent;
  30. import com.dmdirc.events.DisplayProperty;
  31. import com.dmdirc.events.NickListClientAddedEvent;
  32. import com.dmdirc.events.NickListClientRemovedEvent;
  33. import com.dmdirc.events.NickListClientsChangedEvent;
  34. import com.dmdirc.events.NickListUpdatedEvent;
  35. import com.dmdirc.interfaces.CommandController;
  36. import com.dmdirc.interfaces.Connection;
  37. import com.dmdirc.interfaces.GroupChat;
  38. import com.dmdirc.interfaces.GroupChatUser;
  39. import com.dmdirc.interfaces.User;
  40. import com.dmdirc.interfaces.config.ConfigProviderMigrator;
  41. import com.dmdirc.parser.interfaces.ChannelClientInfo;
  42. import com.dmdirc.parser.interfaces.ChannelInfo;
  43. import com.dmdirc.parser.interfaces.Parser;
  44. import com.dmdirc.ui.core.components.WindowComponent;
  45. import com.dmdirc.ui.input.TabCompleterFactory;
  46. import com.dmdirc.ui.input.TabCompletionType;
  47. import com.dmdirc.ui.messages.BackBufferFactory;
  48. import com.dmdirc.ui.messages.Styliser;
  49. import com.dmdirc.ui.messages.sink.MessageSinkManager;
  50. import com.dmdirc.util.URLBuilder;
  51. import com.dmdirc.util.collections.RollingList;
  52. import com.dmdirc.util.colours.Colour;
  53. import com.dmdirc.util.colours.ColourUtils;
  54. import java.util.ArrayList;
  55. import java.util.Arrays;
  56. import java.util.Collection;
  57. import java.util.Collections;
  58. import java.util.List;
  59. import java.util.Optional;
  60. import java.util.stream.Collectors;
  61. /**
  62. * The Channel class represents the client's view of the channel. It handles callbacks for channel
  63. * events from the parser, maintains the corresponding ChannelWindow, and handles user input for the
  64. * channel.
  65. */
  66. public class Channel extends MessageTarget implements GroupChat {
  67. /** The parser's pChannel class. */
  68. private ChannelInfo channelInfo;
  69. /** The server this channel is on. */
  70. private final Server server;
  71. /** A list of previous topics we've seen. */
  72. private final RollingList<Topic> topics;
  73. /** Our event handler. */
  74. private final ChannelEventHandler eventHandler;
  75. /** The migrator to use to migrate our config provider. */
  76. private final ConfigProviderMigrator configMigrator;
  77. /** Manager used to retrieve {@link GroupChatUser}s */
  78. private final GroupChatUserManager groupChatUserManager;
  79. /** Whether we're in this channel or not. */
  80. private boolean isOnChannel;
  81. /** Whether we should send WHO requests for this channel. */
  82. @ConfigBinding(domain = "channel", key = "sendwho")
  83. private volatile boolean sendWho;
  84. /** Whether we should show mode prefixes in text. */
  85. @ConfigBinding(domain = "channel", key = "showmodeprefix")
  86. private volatile boolean showModePrefix;
  87. /** Whether we should show colours in nicks. */
  88. @ConfigBinding(domain = "ui", key = "shownickcoloursintext")
  89. private volatile boolean showColours;
  90. /**
  91. * Creates a new instance of Channel.
  92. *
  93. * @param newServer The server object that this channel belongs to
  94. * @param newChannelInfo The parser's channel object that corresponds to this channel
  95. * @param configMigrator The config migrator which provides the config for this channel.
  96. * @param tabCompleterFactory The factory to use to create tab completers.
  97. * @param commandController The controller to load commands from.
  98. * @param messageSinkManager The sink manager to use to despatch messages.
  99. * @param urlBuilder The URL builder to use when finding icons.
  100. * @param eventBus The bus to despatch events onto.
  101. */
  102. public Channel(
  103. final Server newServer,
  104. final ChannelInfo newChannelInfo,
  105. final ConfigProviderMigrator configMigrator,
  106. final TabCompleterFactory tabCompleterFactory,
  107. final CommandController commandController,
  108. final MessageSinkManager messageSinkManager,
  109. final URLBuilder urlBuilder,
  110. final DMDircMBassador eventBus,
  111. final BackBufferFactory backBufferFactory,
  112. final GroupChatUserManager groupChatUserManager) {
  113. super(newServer, "channel-inactive", newChannelInfo.getName(),
  114. Styliser.stipControlCodes(newChannelInfo.getName()),
  115. configMigrator.getConfigProvider(),
  116. backBufferFactory,
  117. new ChannelCommandParser(newServer, commandController, eventBus),
  118. tabCompleterFactory.getTabCompleter(newServer.getTabCompleter(),
  119. configMigrator.getConfigProvider(), CommandType.TYPE_CHANNEL,
  120. CommandType.TYPE_CHAT),
  121. messageSinkManager,
  122. urlBuilder,
  123. newServer.getEventBus(),
  124. Arrays.asList(WindowComponent.TEXTAREA.getIdentifier(),
  125. WindowComponent.INPUTFIELD.getIdentifier(),
  126. WindowComponent.TOPICBAR.getIdentifier(),
  127. WindowComponent.USERLIST.getIdentifier()));
  128. this.configMigrator = configMigrator;
  129. this.channelInfo = newChannelInfo;
  130. this.server = newServer;
  131. this.groupChatUserManager = groupChatUserManager;
  132. getConfigManager().getBinder().bind(this, Channel.class);
  133. topics = new RollingList<>(getConfigManager().getOptionInt("channel", "topichistorysize"));
  134. eventHandler = new ChannelEventHandler(this, getEventBus(), groupChatUserManager);
  135. registerCallbacks();
  136. updateTitle();
  137. selfJoin();
  138. }
  139. public ChannelInfo getChannelInfo() {
  140. return channelInfo;
  141. }
  142. @Override
  143. public boolean isOnChannel() {
  144. return isOnChannel;
  145. }
  146. /**
  147. * Registers callbacks with the parser for this channel.
  148. */
  149. private void registerCallbacks() {
  150. eventHandler.registerCallbacks();
  151. configMigrator.migrate(server.getProtocol(), server.getIrcd(),
  152. server.getNetwork(), server.getAddress(), channelInfo.getName());
  153. }
  154. @Override
  155. public void sendLine(final String line) {
  156. if (server.getState() != ServerState.CONNECTED
  157. || server.getParser().get().getChannel(channelInfo.getName()) == null) {
  158. // We're not in the channel/connected to the server
  159. return;
  160. }
  161. final GroupChatUser me = getUser(server.getLocalUser().get()).get();
  162. splitLine(line).stream().filter(part -> !part.isEmpty()).forEach(part -> {
  163. getEventBus().publishAsync(new ChannelSelfMessageEvent(this, me, part));
  164. channelInfo.sendMessage(part);
  165. });
  166. }
  167. @Override
  168. public int getMaxLineLength() {
  169. return server.getState() == ServerState.CONNECTED
  170. ? server.getParser().get().getMaxLength("PRIVMSG", getChannelInfo().getName())
  171. : -1;
  172. }
  173. @Override
  174. public void sendAction(final String action) {
  175. if (server.getState() != ServerState.CONNECTED
  176. || server.getParser().get().getChannel(channelInfo.getName()) == null) {
  177. // We're not on the server/channel
  178. return;
  179. }
  180. if (server.getParser().get().getMaxLength("PRIVMSG", getChannelInfo().getName())
  181. <= action.length()) {
  182. addLine("actionTooLong", action.length());
  183. } else {
  184. final GroupChatUser me = getUser(server.getLocalUser().get()).get();
  185. getEventBus().publishAsync(new ChannelSelfActionEvent(this, me, action));
  186. channelInfo.sendAction(action);
  187. }
  188. }
  189. /**
  190. * Sets this object's ChannelInfo reference to the one supplied. This only needs to be done if
  191. * the channel window (and hence this channel object) has stayed open while the user has been
  192. * out of the channel.
  193. *
  194. * @param newChannelInfo The new ChannelInfo object
  195. */
  196. public void setChannelInfo(final ChannelInfo newChannelInfo) {
  197. channelInfo = newChannelInfo;
  198. registerCallbacks();
  199. }
  200. /**
  201. * Called when we join this channel. Just needs to output a message.
  202. */
  203. public void selfJoin() {
  204. isOnChannel = true;
  205. final User me = server.getLocalUser().get();
  206. getEventBus().publishAsync(new ChannelSelfJoinEvent(this, me));
  207. checkWho();
  208. setIcon("channel");
  209. server.removeInvites(channelInfo.getName());
  210. }
  211. /**
  212. * Updates the title of the channel window, and of the main window if appropriate.
  213. */
  214. private void updateTitle() {
  215. String temp = Styliser.stipControlCodes(channelInfo.getName());
  216. if (!channelInfo.getTopic().isEmpty()) {
  217. temp += " - " + Styliser.stipControlCodes(channelInfo.getTopic());
  218. }
  219. setTitle(temp);
  220. }
  221. @Override
  222. public void join() {
  223. server.getParser().get().joinChannel(channelInfo.getName());
  224. }
  225. @Override
  226. public void part(final String reason) {
  227. channelInfo.part(reason);
  228. resetWindow();
  229. }
  230. @Override
  231. public void retrieveListModes() {
  232. channelInfo.requestListModes();
  233. }
  234. /**
  235. * Resets the window state after the client has left a channel.
  236. */
  237. public void resetWindow() {
  238. isOnChannel = false;
  239. setIcon("channel-inactive");
  240. getEventBus().publishAsync(new NickListClientsChangedEvent(this,
  241. Collections.<GroupChatUser>emptyList()));
  242. }
  243. @Override
  244. public void close() {
  245. super.close();
  246. // Remove any callbacks or listeners
  247. eventHandler.unregisterCallbacks();
  248. getConfigManager().getBinder().unbind(this);
  249. server.getParser().map(Parser::getCallbackManager)
  250. .ifPresent(cm -> cm.delAllCallback(eventHandler));
  251. // Trigger any actions neccessary
  252. if (isOnChannel && server.getState() != ServerState.CLOSING) {
  253. part(getConfigManager().getOption("general", "partmessage"));
  254. }
  255. // Trigger action for the window closing
  256. getEventBus().publish(new ChannelClosedEvent(this));
  257. // Inform any parents that the window is closing
  258. server.delChannel(channelInfo.getName());
  259. }
  260. /**
  261. * Called every {general.whotime} seconds to check if the channel needs to send a who request.
  262. */
  263. public void checkWho() {
  264. if (isOnChannel && sendWho) {
  265. channelInfo.sendWho();
  266. }
  267. }
  268. /**
  269. * Adds a ChannelClient to this Channel.
  270. *
  271. * @param client The client to be added
  272. */
  273. public void addClient(final GroupChatUser client) {
  274. getEventBus().publishAsync(new NickListClientAddedEvent(this, client));
  275. getTabCompleter().addEntry(TabCompletionType.CHANNEL_NICK, client.getNickname());
  276. }
  277. /**
  278. * Removes the specified ChannelClient from this channel.
  279. *
  280. * @param client The client to be removed
  281. */
  282. public void removeClient(final GroupChatUser client) {
  283. getEventBus().publishAsync(new NickListClientRemovedEvent(this, client));
  284. getTabCompleter().removeEntry(TabCompletionType.CHANNEL_NICK,
  285. client.getNickname());
  286. if (client.getUser().equals(server.getLocalUser())) {
  287. resetWindow();
  288. }
  289. }
  290. /**
  291. * Replaces the list of known clients on this channel with the specified one.
  292. *
  293. * @param clients The list of clients to use
  294. */
  295. public void setClients(final Collection<GroupChatUser> clients) {
  296. getEventBus().publishAsync(new NickListClientsChangedEvent(this, clients));
  297. getTabCompleter().clear(TabCompletionType.CHANNEL_NICK);
  298. getTabCompleter().addEntries(TabCompletionType.CHANNEL_NICK,
  299. clients.stream().map(GroupChatUser::getNickname).collect(Collectors.toList()));
  300. }
  301. /**
  302. * Renames a client that is in this channel.
  303. *
  304. * @param oldName The old nickname of the client
  305. * @param newName The new nickname of the client
  306. */
  307. public void renameClient(final String oldName, final String newName) {
  308. getTabCompleter().removeEntry(TabCompletionType.CHANNEL_NICK, oldName);
  309. getTabCompleter().addEntry(TabCompletionType.CHANNEL_NICK, newName);
  310. refreshClients();
  311. }
  312. /**
  313. * Refreshes the list of clients stored by this channel. Should be called when (visible) user
  314. * modes or nicknames change.
  315. */
  316. public void refreshClients() {
  317. if (!isOnChannel) {
  318. return;
  319. }
  320. getEventBus().publishAsync(new NickListUpdatedEvent(this));
  321. }
  322. /**
  323. * Returns a string containing the most important mode for the specified client.
  324. *
  325. * @param user The channel client to check.
  326. *
  327. * @return A string containing the most important mode, or an empty string if there are no
  328. * (known) modes.
  329. */
  330. private String getModes(final GroupChatUser user) {
  331. if (user == null || !showModePrefix) {
  332. return "";
  333. } else {
  334. return user.getImportantMode();
  335. }
  336. }
  337. /**
  338. * Returns a string[] containing the nickname/ident/host of a channel client.
  339. *
  340. *
  341. *
  342. * @param client The channel client to check
  343. *
  344. * @return A string[] containing displayable components
  345. * 0 - mode
  346. * 1 - nickname
  347. * 2 - ident
  348. * 3 - hostname
  349. */
  350. private String[] getDetails(final GroupChatUser client) {
  351. if (client == null) {
  352. // WTF?
  353. throw new UnsupportedOperationException("getDetails called with"
  354. + " null ChannelClientInfo");
  355. }
  356. final String[] res = {
  357. getModes(client),
  358. Styliser.CODE_NICKNAME + client.getNickname() + Styliser.CODE_NICKNAME,
  359. client.getUsername().orElse(""),
  360. client.getHostname().orElse(""),};
  361. if (showColours) {
  362. final Optional<Colour> foreground
  363. = client.getDisplayProperty(DisplayProperty.FOREGROUND_COLOUR);
  364. final Optional<Colour> background
  365. = client.getDisplayProperty(DisplayProperty.BACKGROUND_COLOUR);
  366. if (foreground.isPresent()) {
  367. String prefix = Styliser.CODE_HEXCOLOUR + ColourUtils.getHex(foreground.get());
  368. if (background.isPresent()) {
  369. prefix += ',' + ColourUtils.getHex(background.get());
  370. }
  371. res[1] = prefix + res[1] + Styliser.CODE_HEXCOLOUR;
  372. }
  373. }
  374. return res;
  375. }
  376. @Override
  377. protected boolean processNotificationArg(final Object arg, final List<Object> args) {
  378. if (arg instanceof User) {
  379. final User clientInfo = (User) arg;
  380. args.add(clientInfo.getNickname());
  381. args.add(clientInfo.getUsername());
  382. args.add(clientInfo.getHostname());
  383. return true;
  384. } else if (arg instanceof GroupChatUser) {
  385. final GroupChatUser clientInfo = (GroupChatUser) arg;
  386. args.addAll(Arrays.asList(getDetails(clientInfo)));
  387. return true;
  388. } else if (arg instanceof Topic) {
  389. // Format topics
  390. final Topic topic = (Topic) arg;
  391. args.add("");
  392. args.add(topic.getClient().map(GroupChatUser::getNickname).orElse("Unknown"));
  393. args.add(topic.getClient().flatMap(GroupChatUser::getUsername).orElse(""));
  394. args.add(topic.getClient().flatMap(GroupChatUser::getHostname).orElse(""));
  395. args.add(topic.getTopic());
  396. args.add(topic.getTime() * 1000);
  397. return true;
  398. } else {
  399. // Everything else - default formatting
  400. return super.processNotificationArg(arg, args);
  401. }
  402. }
  403. @Override
  404. protected void modifyNotificationArgs(final List<Object> actionArgs,
  405. final List<Object> messageArgs) {
  406. messageArgs.add(channelInfo.getName());
  407. }
  408. // ---------------------------------------------------- TOPIC HANDLING -----
  409. /**
  410. * Adds the specified topic to this channel's topic list.
  411. *
  412. * @param topic The topic to be added.
  413. */
  414. public void addTopic(final Topic topic) {
  415. synchronized (topics) {
  416. topics.add(topic);
  417. }
  418. updateTitle();
  419. }
  420. @Override
  421. public List<Topic> getTopics() {
  422. synchronized (topics) {
  423. return new ArrayList<>(topics.getList());
  424. }
  425. }
  426. @Override
  427. public Optional<Topic> getCurrentTopic() {
  428. synchronized (topics) {
  429. if (topics.getList().isEmpty()) {
  430. return Optional.empty();
  431. } else {
  432. return Optional.of(topics.get(topics.getList().size() - 1));
  433. }
  434. }
  435. }
  436. // ------------------------------------------ PARSER METHOD DELEGATION -----
  437. @Override
  438. public void setTopic(final String topic) {
  439. channelInfo.setTopic(topic);
  440. }
  441. @Override
  442. public int getMaxTopicLength() {
  443. return server.getParser().get().getMaxTopicLength();
  444. }
  445. @Override
  446. public Optional<Connection> getConnection() {
  447. return Optional.of(server);
  448. }
  449. @Override
  450. public Optional<GroupChatUser> getUser(final User user) {
  451. final ChannelClientInfo ci = channelInfo.getChannelClient(((Client) user).getClientInfo());
  452. if (ci == null) {
  453. return Optional.empty();
  454. }
  455. return Optional.of(groupChatUserManager.getUserFromClient(ci, user, this));
  456. }
  457. @Override
  458. public Collection<GroupChatUser> getUsers() {
  459. return channelInfo.getChannelClients().stream()
  460. .map(client -> groupChatUserManager.getUserFromClient(client, this))
  461. .collect(Collectors.toList());
  462. }
  463. @Override
  464. public FrameContainer getWindowModel() {
  465. return this;
  466. }
  467. @Override
  468. public void kick(final GroupChatUser user, final Optional<String> reason) {
  469. ((ChannelClient) user).getClientInfo().kick(
  470. reason.orElse(getConfigManager().getOption("general", "kickmessage")));
  471. }
  472. }