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

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