Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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