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.

LoggingManager.java 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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.addons.logging;
  23. import com.dmdirc.ClientModule.GlobalConfig;
  24. import com.dmdirc.DMDircMBassador;
  25. import com.dmdirc.FrameContainer;
  26. import com.dmdirc.Query;
  27. import com.dmdirc.commandline.CommandLineOptionsModule.Directory;
  28. import com.dmdirc.config.prefs.PluginPreferencesCategory;
  29. import com.dmdirc.config.prefs.PreferencesCategory;
  30. import com.dmdirc.config.prefs.PreferencesDialogModel;
  31. import com.dmdirc.config.prefs.PreferencesSetting;
  32. import com.dmdirc.config.prefs.PreferencesType;
  33. import com.dmdirc.events.BaseChannelActionEvent;
  34. import com.dmdirc.events.BaseChannelMessageEvent;
  35. import com.dmdirc.events.BaseQueryActionEvent;
  36. import com.dmdirc.events.BaseQueryMessageEvent;
  37. import com.dmdirc.events.ChannelClosedEvent;
  38. import com.dmdirc.events.ChannelGotTopicEvent;
  39. import com.dmdirc.events.ChannelJoinEvent;
  40. import com.dmdirc.events.ChannelKickEvent;
  41. import com.dmdirc.events.ChannelModeChangeEvent;
  42. import com.dmdirc.events.ChannelNickChangeEvent;
  43. import com.dmdirc.events.ChannelOpenedEvent;
  44. import com.dmdirc.events.ChannelPartEvent;
  45. import com.dmdirc.events.ChannelQuitEvent;
  46. import com.dmdirc.events.ChannelTopicChangeEvent;
  47. import com.dmdirc.events.ClientPrefsOpenedEvent;
  48. import com.dmdirc.events.QueryClosedEvent;
  49. import com.dmdirc.events.QueryOpenedEvent;
  50. import com.dmdirc.events.UserErrorEvent;
  51. import com.dmdirc.interfaces.GroupChat;
  52. import com.dmdirc.interfaces.GroupChatUser;
  53. import com.dmdirc.interfaces.PrivateChat;
  54. import com.dmdirc.interfaces.User;
  55. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  56. import com.dmdirc.interfaces.config.ConfigChangeListener;
  57. import com.dmdirc.logger.ErrorLevel;
  58. import com.dmdirc.plugins.PluginDomain;
  59. import com.dmdirc.plugins.PluginInfo;
  60. import com.dmdirc.ui.WindowManager;
  61. import com.dmdirc.ui.messages.BackBufferFactory;
  62. import com.dmdirc.ui.messages.Styliser;
  63. import com.dmdirc.util.io.ReverseFileReader;
  64. import com.dmdirc.util.io.StreamUtils;
  65. import java.awt.Color;
  66. import java.io.BufferedWriter;
  67. import java.io.File;
  68. import java.io.FileWriter;
  69. import java.io.IOException;
  70. import java.nio.file.Files;
  71. import java.nio.file.Path;
  72. import java.nio.file.Paths;
  73. import java.text.DateFormat;
  74. import java.text.SimpleDateFormat;
  75. import java.util.ArrayList;
  76. import java.util.Collection;
  77. import java.util.Collections;
  78. import java.util.Date;
  79. import java.util.HashMap;
  80. import java.util.Map;
  81. import java.util.Stack;
  82. import java.util.Timer;
  83. import java.util.TimerTask;
  84. import javax.inject.Inject;
  85. import javax.inject.Provider;
  86. import javax.inject.Singleton;
  87. import net.engio.mbassy.listener.Handler;
  88. /**
  89. * Manages logging activities.
  90. */
  91. @Singleton
  92. public class LoggingManager implements ConfigChangeListener {
  93. /** Date format used for "File Opened At" log. */
  94. private static final DateFormat OPENED_AT_FORMAT = new SimpleDateFormat(
  95. "EEEE MMMM dd, yyyy - HH:mm:ss");
  96. /** Object for synchronising access to the date forma.t */
  97. private static final Object FORMAT_LOCK = new Object();
  98. /** This plugin's plugin info. */
  99. private final String domain;
  100. private final PluginInfo pluginInfo;
  101. /** Global config. */
  102. private final AggregateConfigProvider config;
  103. /** The manager to add history windows to. */
  104. private final WindowManager windowManager;
  105. /** Map of open files. */
  106. private final Map<String, OpenFile> openFiles = Collections.synchronizedMap(
  107. new HashMap<>());
  108. private final DMDircMBassador eventBus;
  109. private final Provider<String> directoryProvider;
  110. private final BackBufferFactory backBufferFactory;
  111. private final LogFileLocator locator;
  112. /** Timer used to close idle files. */
  113. private Timer idleFileTimer;
  114. /** Cached boolean settings. */
  115. private boolean addtime;
  116. private boolean stripcodes;
  117. private boolean channelmodeprefix;
  118. private boolean autobackbuffer;
  119. private boolean backbufferTimestamp;
  120. /** Cached string settings. */
  121. private String timestamp;
  122. private String colour;
  123. /** Cached int settings. */
  124. private int historyLines;
  125. private int backbufferLines;
  126. @Inject
  127. public LoggingManager(@PluginDomain(LoggingPlugin.class) final String domain,
  128. @PluginDomain(LoggingPlugin.class) final PluginInfo pluginInfo,
  129. @GlobalConfig final AggregateConfigProvider globalConfig,
  130. final WindowManager windowManager, final DMDircMBassador eventBus,
  131. @Directory(LoggingModule.LOGS_DIRECTORY) final Provider<String> directoryProvider,
  132. final BackBufferFactory backBufferFactory,
  133. final LogFileLocator locator) {
  134. this.domain = domain;
  135. this.pluginInfo = pluginInfo;
  136. this.config = globalConfig;
  137. this.windowManager = windowManager;
  138. this.eventBus = eventBus;
  139. this.directoryProvider = directoryProvider;
  140. this.backBufferFactory = backBufferFactory;
  141. this.locator = locator;
  142. }
  143. public void load() {
  144. setCachedSettings();
  145. final File dir = new File(directoryProvider.get());
  146. if (dir.exists()) {
  147. if (!dir.isDirectory()) {
  148. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null,
  149. "Unable to create logging dir (file exists instead)", ""));
  150. }
  151. } else {
  152. if (!dir.mkdirs()) {
  153. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null,
  154. "Unable to create logging dir", ""));
  155. }
  156. }
  157. config.addChangeListener(domain, this);
  158. // Close idle files every hour.
  159. idleFileTimer = new Timer("LoggingPlugin Timer");
  160. idleFileTimer.schedule(new TimerTask() {
  161. @Override
  162. public void run() {
  163. timerTask();
  164. }
  165. }, 3600000);
  166. eventBus.subscribe(this);
  167. }
  168. public void unload() {
  169. if (idleFileTimer != null) {
  170. idleFileTimer.cancel();
  171. idleFileTimer.purge();
  172. }
  173. synchronized (openFiles) {
  174. for (OpenFile file : openFiles.values()) {
  175. StreamUtils.close(file.writer);
  176. }
  177. openFiles.clear();
  178. }
  179. eventBus.unsubscribe(this);
  180. }
  181. /**
  182. * What to do every hour when the timer fires.
  183. */
  184. protected void timerTask() {
  185. // Oldest time to allow
  186. final long oldestTime = System.currentTimeMillis() - 3480000;
  187. synchronized (openFiles) {
  188. final Collection<String> old = new ArrayList<>(openFiles.size());
  189. for (Map.Entry<String, OpenFile> entry : openFiles.entrySet()) {
  190. if (entry.getValue().lastUsedTime < oldestTime) {
  191. StreamUtils.close(entry.getValue().writer);
  192. old.add(entry.getKey());
  193. }
  194. }
  195. openFiles.keySet().removeAll(old);
  196. }
  197. }
  198. @Handler
  199. public void handleQueryOpened(final QueryOpenedEvent event) {
  200. final String filename = locator.getLogFile(event.getQuery().getUser());
  201. if (autobackbuffer) {
  202. showBackBuffer(event.getQuery(), filename);
  203. }
  204. synchronized (FORMAT_LOCK) {
  205. appendLine(filename, "*** Query opened at: %s", OPENED_AT_FORMAT.format(new Date()));
  206. appendLine(filename, "*** Query with User: %s", event.getQuery().getHost());
  207. appendLine(filename, "");
  208. }
  209. }
  210. @Handler
  211. public void handleQueryClosed(final QueryClosedEvent event) {
  212. final String filename = locator.getLogFile(event.getQuery().getUser());
  213. synchronized (FORMAT_LOCK) {
  214. appendLine(filename, "*** Query closed at: %s", OPENED_AT_FORMAT.format(new Date()));
  215. }
  216. if (openFiles.containsKey(filename)) {
  217. StreamUtils.close(openFiles.get(filename).writer);
  218. openFiles.remove(filename);
  219. }
  220. }
  221. @Handler
  222. public void handleQueryActions(final BaseQueryActionEvent event) {
  223. final User user = event.getUser();
  224. final String filename = locator.getLogFile(user);
  225. appendLine(filename, "* %s %s", user.getNickname(), event.getMessage());
  226. }
  227. @Handler
  228. public void handleQueryMessages(final BaseQueryMessageEvent event) {
  229. final User user = event.getUser();
  230. final String filename = locator.getLogFile(user);
  231. appendLine(filename, "<%s> %s", user.getNickname(), event.getMessage());
  232. }
  233. @Handler
  234. public void handleChannelMessage(final BaseChannelMessageEvent event) {
  235. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  236. appendLine(filename, "<%s> %s", getDisplayName(event.getClient()), event.getMessage());
  237. }
  238. @Handler
  239. public void handleChannelAction(final BaseChannelActionEvent event) {
  240. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  241. appendLine(filename, "* %s %s", getDisplayName(event.getClient()), event.getMessage());
  242. }
  243. @Handler
  244. public void handleChannelGotTopic(final ChannelGotTopicEvent event) {
  245. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  246. final DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
  247. final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
  248. appendLine(filename, "*** Topic is: %s", event.getTopic().getTopic());
  249. appendLine(filename, "*** Set at: %s on %s by %s",
  250. timeFormat.format(1000 * event.getTopic().getTime()),
  251. dateFormat.format(1000 * event.getTopic().getTime()),
  252. event.getTopic().getClient()
  253. .map(GroupChatUser::getNickname).orElse("Unknown"));
  254. }
  255. @Handler
  256. public void handleChannelTopicChange(final ChannelTopicChangeEvent event) {
  257. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  258. appendLine(filename, "*** %s Changed the topic to: %s",
  259. event.getTopic().getClient().map(this::getDisplayName).orElse(""), event.getTopic());
  260. }
  261. @Handler
  262. public void handleChannelJoin(final ChannelJoinEvent event) {
  263. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  264. final GroupChatUser channelClient = event.getClient();
  265. appendLine(filename, "*** %s (%s) joined the channel", getDisplayName(channelClient),
  266. channelClient.getNickname());
  267. }
  268. @Handler
  269. public void handleChannelPart(final ChannelPartEvent event) {
  270. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  271. final String message = event.getMessage();
  272. final GroupChatUser channelClient = event.getClient();
  273. if (message.isEmpty()) {
  274. appendLine(filename, "*** %s (%s) left the channel", getDisplayName(channelClient),
  275. channelClient.getNickname());
  276. } else {
  277. appendLine(filename, "*** %s (%s) left the channel (%s)",
  278. getDisplayName(channelClient), channelClient.getNickname(), message);
  279. }
  280. }
  281. @Handler
  282. public void handleChannelQuit(final ChannelQuitEvent event) {
  283. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  284. final String reason = event.getMessage();
  285. final GroupChatUser channelClient = event.getClient();
  286. if (reason.isEmpty()) {
  287. appendLine(filename, "*** %s (%s) Quit IRC",
  288. getDisplayName(channelClient), channelClient.getNickname());
  289. } else {
  290. appendLine(filename, "*** %s (%s) Quit IRC (%s)",
  291. getDisplayName(channelClient), channelClient.getNickname(), reason);
  292. }
  293. }
  294. @Handler
  295. public void handleChannelKick(final ChannelKickEvent event) {
  296. final GroupChatUser victim = event.getVictim();
  297. final GroupChatUser perpetrator = event.getClient();
  298. final String reason = event.getReason();
  299. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  300. if (reason.isEmpty()) {
  301. appendLine(filename, "*** %s was kicked by %s",
  302. getDisplayName(victim), getDisplayName(perpetrator));
  303. } else {
  304. appendLine(filename, "*** %s was kicked by %s (%s)",
  305. getDisplayName(victim), getDisplayName(perpetrator), reason);
  306. }
  307. }
  308. @Handler
  309. public void handleNickChange(final ChannelNickChangeEvent event) {
  310. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  311. appendLine(filename, "*** %s is now %s", getDisplayName(event.getClient(),
  312. event.getOldNick()), getDisplayName(event.getClient()));
  313. }
  314. @Handler
  315. public void handleModeChange(final ChannelModeChangeEvent event) {
  316. final String filename = locator.getLogFile(event.getChannel().getChannelInfo());
  317. if (event.getClient().getNickname().isEmpty()) {
  318. appendLine(filename, "*** Channel modes are: %s", event.getModes());
  319. } else {
  320. appendLine(filename, "*** %s set modes: %s",
  321. getDisplayName(event.getClient()), event.getModes());
  322. }
  323. }
  324. @Override
  325. public void configChanged(final String domain, final String key) {
  326. setCachedSettings();
  327. }
  328. @Handler
  329. public void handleChannelOpened(final ChannelOpenedEvent event) {
  330. final String filename = locator.getLogFile(event.getChannel().getName());
  331. if (autobackbuffer) {
  332. showBackBuffer(event.getChannel(), filename);
  333. }
  334. synchronized (FORMAT_LOCK) {
  335. appendLine(filename, "*** Channel opened at: %s", OPENED_AT_FORMAT.format(new Date()));
  336. appendLine(filename, "");
  337. }
  338. }
  339. @Handler
  340. public void handleChannelClosed(final ChannelClosedEvent event) {
  341. final String filename = locator.getLogFile(event.getChannel().getName());
  342. synchronized (FORMAT_LOCK) {
  343. appendLine(filename, "*** Channel closed at: %s", OPENED_AT_FORMAT.format(new Date()));
  344. }
  345. if (openFiles.containsKey(filename)) {
  346. StreamUtils.close(openFiles.get(filename).writer);
  347. openFiles.remove(filename);
  348. }
  349. }
  350. /**
  351. * Add a backbuffer to a frame.
  352. *
  353. * @param frame The frame to add the backbuffer lines to
  354. * @param filename File to get backbuffer from
  355. */
  356. protected void showBackBuffer(final FrameContainer frame, final String filename) {
  357. if (frame == null) {
  358. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null, "Given a null frame", ""));
  359. return;
  360. }
  361. final Path testFile = Paths.get(filename);
  362. if (Files.exists(testFile)) {
  363. try {
  364. final ReverseFileReader file = new ReverseFileReader(testFile);
  365. // Because the file includes a newline char at the end, an empty line
  366. // is returned by getLines. To counter this, we call getLines(1) and do
  367. // nothing with the output.
  368. file.getLines(1);
  369. final Stack<String> lines = file.getLines(backbufferLines);
  370. while (!lines.empty()) {
  371. frame.addLine(getColouredString(colour, lines.pop()), backbufferTimestamp);
  372. }
  373. file.close();
  374. frame.addLine(getColouredString(colour, "--- End of backbuffer\n"),
  375. backbufferTimestamp);
  376. } catch (IOException | SecurityException e) {
  377. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, e,
  378. "Unable to show backbuffer (Filename: " + filename + "): " + e.getMessage(),
  379. ""));
  380. }
  381. }
  382. }
  383. /**
  384. * Get a coloured String. If colour is invalid, IRC Colour 14 will be used.
  385. *
  386. * @param colour The colour the string should be (IRC Colour or 6-digit hex colour)
  387. * @param line the line to colour
  388. *
  389. * @return The given line with the appropriate irc codes appended/prepended to colour it.
  390. */
  391. protected static String getColouredString(final String colour, final String line) {
  392. String res = null;
  393. if (colour.length() < 3) {
  394. int num;
  395. try {
  396. num = Integer.parseInt(colour);
  397. } catch (NumberFormatException ex) {
  398. num = -1;
  399. }
  400. if (num >= 0 && num <= 15) {
  401. res = String.format("%c%02d%s%1$c", Styliser.CODE_COLOUR, num, line);
  402. }
  403. } else if (colour.length() == 6) {
  404. try {
  405. Color.decode('#' + colour);
  406. res = String.format("%c%s%s%1$c", Styliser.CODE_HEXCOLOUR, colour, line);
  407. } catch (NumberFormatException ex) { /* Do Nothing */ }
  408. }
  409. if (res == null) {
  410. res = String.format("%c%02d%s%1$c", Styliser.CODE_COLOUR, 14, line);
  411. }
  412. return res;
  413. }
  414. /**
  415. * Add a line to a file.
  416. *
  417. * @param filename Name of file to write to
  418. * @param format Format of line to add. (NewLine will be added Automatically)
  419. * @param args Arguments for format
  420. *
  421. * @return true on success, else false.
  422. */
  423. protected boolean appendLine(final String filename, final String format, final Object... args) {
  424. return appendLine(filename, String.format(format, args));
  425. }
  426. /**
  427. * Add a line to a file.
  428. *
  429. * @param filename Name of file to write to
  430. * @param line Line to add. (NewLine will be added Automatically)
  431. *
  432. * @return true on success, else false.
  433. */
  434. protected boolean appendLine(final String filename, final String line) {
  435. final StringBuilder finalLine = new StringBuilder();
  436. if (addtime) {
  437. String dateString;
  438. try {
  439. final DateFormat dateFormat = new SimpleDateFormat(timestamp);
  440. dateString = dateFormat.format(new Date()).trim();
  441. } catch (IllegalArgumentException iae) {
  442. // Default to known good format
  443. final DateFormat dateFormat = new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]");
  444. dateString = dateFormat.format(new Date()).trim();
  445. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, iae,
  446. "Dateformat String '" + timestamp + "' is invalid. For more information: "
  447. + "http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html",
  448. ""));
  449. }
  450. finalLine.append(dateString);
  451. finalLine.append(' ');
  452. }
  453. if (stripcodes) {
  454. finalLine.append(Styliser.stipControlCodes(line));
  455. } else {
  456. finalLine.append(line);
  457. }
  458. try {
  459. final BufferedWriter out;
  460. if (openFiles.containsKey(filename)) {
  461. final OpenFile of = openFiles.get(filename);
  462. of.lastUsedTime = System.currentTimeMillis();
  463. out = of.writer;
  464. } else {
  465. out = new BufferedWriter(new FileWriter(filename, true));
  466. openFiles.put(filename, new OpenFile(out));
  467. }
  468. out.write(finalLine.toString());
  469. out.newLine();
  470. out.flush();
  471. return true;
  472. } catch (IOException e) {
  473. /*
  474. * Do Nothing
  475. *
  476. * Makes no sense to keep adding errors to the logger when we can't write to the file,
  477. * as chances are it will happen on every incomming line.
  478. */
  479. }
  480. return false;
  481. }
  482. /**
  483. * Get name to display for channelClient (Taking into account the channelmodeprefix setting).
  484. *
  485. * @param channelClient The client to get the display name for
  486. *
  487. * @return name to display
  488. */
  489. protected String getDisplayName(final GroupChatUser channelClient) {
  490. return getDisplayName(channelClient, "");
  491. }
  492. /**
  493. * Get name to display for channelClient (Taking into account the channelmodeprefix setting).
  494. *
  495. * @param channelClient The client to get the display name for
  496. * @param overrideNick Nickname to display instead of real nickname
  497. *
  498. * @return name to display
  499. */
  500. protected String getDisplayName(final GroupChatUser channelClient, final String overrideNick) {
  501. if (channelClient == null) {
  502. return overrideNick.isEmpty() ? "Unknown Client" : overrideNick;
  503. } else if (overrideNick.isEmpty()) {
  504. return channelmodeprefix ? channelClient.toString() : channelClient.getNickname();
  505. } else {
  506. return channelmodeprefix ? channelClient.getImportantMode() + overrideNick :
  507. overrideNick;
  508. }
  509. }
  510. /**
  511. * Shows the history window for the specified target, if available.
  512. *
  513. * @param target The window whose history we're trying to open
  514. *
  515. * @return True if the history is available, false otherwise
  516. */
  517. protected boolean showHistory(final FrameContainer target) {
  518. final String descriptor;
  519. if (target instanceof GroupChat) {
  520. descriptor = target.getName();
  521. } else if (target instanceof Query) {
  522. descriptor = ((PrivateChat) target).getNickname();
  523. } else {
  524. // Unknown component
  525. return false;
  526. }
  527. final Path log = Paths.get(locator.getLogFile(descriptor));
  528. if (!Files.exists(log)) {
  529. // File doesn't exist
  530. return false;
  531. }
  532. windowManager.addWindow(target, new HistoryWindow("History", log, target,
  533. eventBus, backBufferFactory, historyLines));
  534. return true;
  535. }
  536. /** Updates cached settings. */
  537. public void setCachedSettings() {
  538. addtime = config.getOptionBool(domain, "general.addtime");
  539. stripcodes = config.getOptionBool(domain, "general.stripcodes");
  540. channelmodeprefix = config.getOptionBool(domain, "general.channelmodeprefix");
  541. autobackbuffer = config.getOptionBool(domain, "backbuffer.autobackbuffer");
  542. backbufferTimestamp = config.getOptionBool(domain, "backbuffer.timestamp");
  543. timestamp = config.getOption(domain, "general.timestamp");
  544. historyLines = config.getOptionInt(domain, "history.lines");
  545. colour = config.getOption(domain, "backbuffer.colour");
  546. backbufferLines = config.getOptionInt(domain, "backbuffer.lines");
  547. }
  548. @Handler
  549. public void showConfig(final ClientPrefsOpenedEvent event) {
  550. final PreferencesDialogModel manager = event.getModel();
  551. final PreferencesCategory general = new PluginPreferencesCategory(
  552. pluginInfo, "Logging", "General configuration for Logging plugin.");
  553. final PreferencesCategory backbuffer = new PluginPreferencesCategory(
  554. pluginInfo, "Back Buffer", "Options related to the automatic backbuffer");
  555. final PreferencesCategory advanced = new PluginPreferencesCategory(
  556. pluginInfo, "Advanced",
  557. "Advanced configuration for Logging plugin. You shouldn't need to edit this unless you know what you are doing.");
  558. general.addSetting(new PreferencesSetting(PreferencesType.DIRECTORY,
  559. pluginInfo.getDomain(), "general.directory", "Directory",
  560. "Directory for log files", manager.getConfigManager(),
  561. manager.getIdentity()));
  562. general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  563. pluginInfo.getDomain(), "general.networkfolders",
  564. "Separate logs by network",
  565. "Should the files be stored in a sub-dir with the networks name?",
  566. manager.getConfigManager(), manager.getIdentity()));
  567. general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  568. pluginInfo.getDomain(), "general.addtime", "Timestamp logs",
  569. "Should a timestamp be added to the log files?",
  570. manager.getConfigManager(), manager.getIdentity()));
  571. general.addSetting(new PreferencesSetting(PreferencesType.TEXT,
  572. pluginInfo.getDomain(), "general.timestamp", "Timestamp format",
  573. "The String to pass to 'SimpleDateFormat' to format the timestamp",
  574. manager.getConfigManager(), manager.getIdentity()));
  575. general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  576. pluginInfo.getDomain(), "general.stripcodes", "Strip Control Codes",
  577. "Remove known irc control codes from lines before saving?",
  578. manager.getConfigManager(), manager.getIdentity()));
  579. general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  580. pluginInfo.getDomain(), "general.channelmodeprefix",
  581. "Show channel mode prefix", "Show the @,+ etc next to nicknames",
  582. manager.getConfigManager(), manager.getIdentity()));
  583. backbuffer.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  584. pluginInfo.getDomain(), "backbuffer.autobackbuffer", "Automatically display",
  585. "Automatically display the backbuffer when a channel is joined",
  586. manager.getConfigManager(), manager.getIdentity()));
  587. backbuffer.addSetting(new PreferencesSetting(PreferencesType.COLOUR,
  588. pluginInfo.getDomain(), "backbuffer.colour", "Colour to use for display",
  589. "Colour used when displaying the backbuffer",
  590. manager.getConfigManager(), manager.getIdentity()));
  591. backbuffer.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
  592. pluginInfo.getDomain(), "backbuffer.lines", "Number of lines to show",
  593. "Number of lines used when displaying backbuffer",
  594. manager.getConfigManager(), manager.getIdentity()));
  595. backbuffer.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  596. pluginInfo.getDomain(), "backbuffer.timestamp", "Show Formatter-Timestamp",
  597. "Should the line be added to the frame with the timestamp from "
  598. + "the formatter aswell as the file contents",
  599. manager.getConfigManager(), manager.getIdentity()));
  600. advanced.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  601. pluginInfo.getDomain(), "advanced.filenamehash", "Add Filename hash",
  602. "Add the MD5 hash of the channel/client name to the filename. "
  603. + "(This is used to allow channels with similar names "
  604. + "(ie a _ not a -) to be logged separately)",
  605. manager.getConfigManager(), manager.getIdentity()));
  606. advanced.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  607. pluginInfo.getDomain(), "advanced.usedate", "Use Date directories",
  608. "Should the log files be in separate directories based on the date?",
  609. manager.getConfigManager(), manager.getIdentity()));
  610. advanced.addSetting(new PreferencesSetting(PreferencesType.TEXT,
  611. pluginInfo.getDomain(), "advanced.usedateformat", "Archive format",
  612. "The String to pass to 'SimpleDateFormat' to format the "
  613. + "directory name(s) for archiving",
  614. manager.getConfigManager(), manager.getIdentity()));
  615. general.addSubCategory(backbuffer.setInline());
  616. general.addSubCategory(advanced.setInline());
  617. manager.getCategory("Plugins").addSubCategory(general.setInlineAfter());
  618. }
  619. /** Open File. */
  620. private static class OpenFile {
  621. /** Last used time. */
  622. public long lastUsedTime = System.currentTimeMillis();
  623. /** Open file's writer. */
  624. public final BufferedWriter writer;
  625. /**
  626. * Creates a new open file.
  627. *
  628. * @param writer Writer that has file open
  629. */
  630. protected OpenFile(final BufferedWriter writer) {
  631. this.writer = writer;
  632. }
  633. }
  634. }