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 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. /*
  2. * Copyright (c) 2006-2014 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.Channel;
  24. import com.dmdirc.ClientModule.GlobalConfig;
  25. import com.dmdirc.DMDircMBassador;
  26. import com.dmdirc.FrameContainer;
  27. import com.dmdirc.Query;
  28. import com.dmdirc.commandline.CommandLineOptionsModule.Directory;
  29. import com.dmdirc.events.BaseChannelActionEvent;
  30. import com.dmdirc.events.BaseChannelMessageEvent;
  31. import com.dmdirc.events.BaseQueryActionEvent;
  32. import com.dmdirc.events.BaseQueryMessageEvent;
  33. import com.dmdirc.events.ChannelClosedEvent;
  34. import com.dmdirc.events.ChannelGottopicEvent;
  35. import com.dmdirc.events.ChannelJoinEvent;
  36. import com.dmdirc.events.ChannelKickEvent;
  37. import com.dmdirc.events.ChannelModechangeEvent;
  38. import com.dmdirc.events.ChannelNickchangeEvent;
  39. import com.dmdirc.events.ChannelOpenedEvent;
  40. import com.dmdirc.events.ChannelPartEvent;
  41. import com.dmdirc.events.ChannelQuitEvent;
  42. import com.dmdirc.events.ChannelTopicChangeEvent;
  43. import com.dmdirc.events.QueryClosedEvent;
  44. import com.dmdirc.events.QueryOpenedEvent;
  45. import com.dmdirc.events.UserErrorEvent;
  46. import com.dmdirc.interfaces.PrivateChat;
  47. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  48. import com.dmdirc.interfaces.config.ConfigChangeListener;
  49. import com.dmdirc.logger.ErrorLevel;
  50. import com.dmdirc.parser.interfaces.ChannelClientInfo;
  51. import com.dmdirc.parser.interfaces.ChannelInfo;
  52. import com.dmdirc.parser.interfaces.ClientInfo;
  53. import com.dmdirc.parser.interfaces.Parser;
  54. import com.dmdirc.plugins.PluginDomain;
  55. import com.dmdirc.ui.WindowManager;
  56. import com.dmdirc.ui.messages.ColourManagerFactory;
  57. import com.dmdirc.ui.messages.Styliser;
  58. import com.dmdirc.util.URLBuilder;
  59. import com.dmdirc.util.io.ReverseFileReader;
  60. import com.dmdirc.util.io.StreamUtils;
  61. import java.awt.Color;
  62. import java.io.BufferedWriter;
  63. import java.io.File;
  64. import java.io.FileWriter;
  65. import java.io.IOException;
  66. import java.math.BigInteger;
  67. import java.security.MessageDigest;
  68. import java.security.NoSuchAlgorithmException;
  69. import java.text.DateFormat;
  70. import java.text.SimpleDateFormat;
  71. import java.util.ArrayList;
  72. import java.util.Collection;
  73. import java.util.Collections;
  74. import java.util.Date;
  75. import java.util.HashMap;
  76. import java.util.Map;
  77. import java.util.Stack;
  78. import java.util.Timer;
  79. import java.util.TimerTask;
  80. import javax.annotation.Nullable;
  81. import javax.inject.Inject;
  82. import javax.inject.Provider;
  83. import javax.inject.Singleton;
  84. import net.engio.mbassy.listener.Handler;
  85. /**
  86. * Manages logging activities.
  87. */
  88. @Singleton
  89. public class LoggingManager implements ConfigChangeListener {
  90. /** Date format used for "File Opened At" log. */
  91. private static final DateFormat OPENED_AT_FORMAT = new SimpleDateFormat(
  92. "EEEE MMMM dd, yyyy - HH:mm:ss");
  93. /** This plugin's plugin info. */
  94. private final String domain;
  95. /** Global config. */
  96. private final AggregateConfigProvider config;
  97. /** The manager to add history windows to. */
  98. private final WindowManager windowManager;
  99. /** Map of open files. */
  100. private final Map<String, OpenFile> openFiles = Collections.synchronizedMap(
  101. new HashMap<String, OpenFile>());
  102. private final URLBuilder urlBuilder;
  103. private final DMDircMBassador eventBus;
  104. private final Provider<String> directoryProvider;
  105. private final ColourManagerFactory colourManagerFactory;
  106. /** Timer used to close idle files. */
  107. private Timer idleFileTimer;
  108. /** Cached boolean settings. */
  109. private boolean networkfolders;
  110. private boolean filenamehash;
  111. private boolean addtime;
  112. private boolean stripcodes;
  113. private boolean channelmodeprefix;
  114. private boolean autobackbuffer;
  115. private boolean backbufferTimestamp;
  116. private boolean usedate;
  117. /** Cached string settings. */
  118. private String timestamp;
  119. private String usedateformat;
  120. private String colour;
  121. /** Cached int settings. */
  122. private int historyLines;
  123. private int backbufferLines;
  124. @Inject
  125. public LoggingManager(@PluginDomain(LoggingPlugin.class) final String domain,
  126. @GlobalConfig final AggregateConfigProvider globalConfig,
  127. final WindowManager windowManager, final URLBuilder urlBuilder, final DMDircMBassador eventBus,
  128. @Directory(LoggingModule.LOGS_DIRECTORY) final Provider<String> directoryProvider,
  129. final ColourManagerFactory colourManagerFactory) {
  130. this.domain = domain;
  131. this.config = globalConfig;
  132. this.windowManager = windowManager;
  133. this.urlBuilder = urlBuilder;
  134. this.eventBus = eventBus;
  135. this.directoryProvider = directoryProvider;
  136. this.colourManagerFactory = colourManagerFactory;
  137. }
  138. public void load() {
  139. setCachedSettings();
  140. final File dir = new File(directoryProvider.get());
  141. if (dir.exists()) {
  142. if (!dir.isDirectory()) {
  143. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null,
  144. "Unable to create logging dir (file exists instead)", ""));
  145. }
  146. } else {
  147. if (!dir.mkdirs()) {
  148. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null,
  149. "Unable to create logging dir", ""));
  150. }
  151. }
  152. config.addChangeListener(domain, this);
  153. // Close idle files every hour.
  154. idleFileTimer = new Timer("LoggingPlugin Timer");
  155. idleFileTimer.schedule(new TimerTask() {
  156. @Override
  157. public void run() {
  158. timerTask();
  159. }
  160. }, 3600000);
  161. eventBus.subscribe(this);
  162. }
  163. public void unload() {
  164. if (idleFileTimer != null) {
  165. idleFileTimer.cancel();
  166. idleFileTimer.purge();
  167. }
  168. synchronized (openFiles) {
  169. for (OpenFile file : openFiles.values()) {
  170. StreamUtils.close(file.writer);
  171. }
  172. openFiles.clear();
  173. }
  174. eventBus.unsubscribe(this);
  175. }
  176. /**
  177. * What to do every hour when the timer fires.
  178. */
  179. protected void timerTask() {
  180. // Oldest time to allow
  181. final long oldestTime = System.currentTimeMillis() - 3480000;
  182. synchronized (openFiles) {
  183. final Collection<String> old = new ArrayList<>(openFiles.size());
  184. for (Map.Entry<String, OpenFile> entry : openFiles.entrySet()) {
  185. if (entry.getValue().lastUsedTime < oldestTime) {
  186. StreamUtils.close(entry.getValue().writer);
  187. old.add(entry.getKey());
  188. }
  189. }
  190. openFiles.keySet().removeAll(old);
  191. }
  192. }
  193. @Handler
  194. public void handleQueryOpened(final QueryOpenedEvent event) {
  195. final Parser parser = event.getQuery().getConnection().getParser();
  196. final ClientInfo client = parser.getClient(event.getQuery().getHost());
  197. final String filename = getLogFile(client);
  198. if (autobackbuffer) {
  199. showBackBuffer(event.getQuery(), filename);
  200. }
  201. appendLine(filename, "*** Query opened at: %s", OPENED_AT_FORMAT.format(new Date()));
  202. appendLine(filename, "*** Query with User: %s", event.getQuery().getHost());
  203. appendLine(filename, "");
  204. }
  205. @Handler
  206. public void handleQueryClosed(final QueryClosedEvent event) {
  207. final Parser parser = event.getQuery().getConnection().getParser();
  208. final ClientInfo client = parser.getClient(event.getQuery().getHost());
  209. final String filename = getLogFile(client);
  210. appendLine(filename, "*** Query closed at: %s", OPENED_AT_FORMAT.format(new Date()));
  211. if (openFiles.containsKey(filename)) {
  212. StreamUtils.close(openFiles.get(filename).writer);
  213. openFiles.remove(filename);
  214. }
  215. }
  216. @Handler
  217. public void handleQueryActions(final BaseQueryActionEvent event) {
  218. final ClientInfo client = event.getClient();
  219. final String filename = getLogFile(client);
  220. appendLine(filename, "* %s %s", client.getNickname(), event.getMessage());
  221. }
  222. @Handler
  223. public void handleQueryMessages(final BaseQueryMessageEvent event) {
  224. final ClientInfo client = event.getClient();
  225. final String filename = getLogFile(client);
  226. appendLine(filename, "<%s> %s", client.getNickname(), event.getMessage());
  227. }
  228. @Handler
  229. public void handleChannelMessage(final BaseChannelMessageEvent event) {
  230. final String filename = getLogFile(event.getChannel().getChannelInfo());
  231. appendLine(filename, "<%s> %s", getDisplayName(event.getClient()), event.getMessage());
  232. }
  233. @Handler
  234. public void handleChannelAction(final BaseChannelActionEvent event) {
  235. final String filename = getLogFile(event.getChannel().getChannelInfo());
  236. appendLine(filename, "* %s %s", getDisplayName(event.getClient()), event.getMessage());
  237. }
  238. @Handler
  239. public void handleChannelGotTopic(final ChannelGottopicEvent event) {
  240. final String filename = getLogFile(event.getChannel().getChannelInfo());
  241. final ChannelInfo channel = event.getChannel().getChannelInfo();
  242. final DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
  243. final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
  244. appendLine(filename, "*** Topic is: %s", channel.getTopic());
  245. appendLine(filename, "*** Set at: %s on %s by %s", timeFormat.format(1000 * channel.
  246. getTopicTime()), dateFormat.format(1000 * channel.getTopicTime()), channel.
  247. getTopicSetter());
  248. }
  249. @Handler
  250. public void handleChannelTopicChange(final ChannelTopicChangeEvent event) {
  251. final String filename = getLogFile(event.getChannel().getChannelInfo());
  252. final ChannelClientInfo channelClient = event.getClient();
  253. appendLine(filename, "*** %s Changed the topic to: %s",
  254. getDisplayName(channelClient), event.getTopic());
  255. }
  256. @Handler
  257. public void handleChannelJoin(final ChannelJoinEvent event) {
  258. final String filename = getLogFile(event.getChannel().getChannelInfo());
  259. final ChannelClientInfo channelClient = event.getClient();
  260. final ClientInfo client = channelClient.getClient();
  261. appendLine(filename, "*** %s (%s) joined the channel",
  262. getDisplayName(channelClient), client.toString());
  263. }
  264. @Handler
  265. public void handleChannelPart(final ChannelPartEvent event) {
  266. final String filename = getLogFile(event.getChannel().getChannelInfo());
  267. final String message = event.getMessage();
  268. final ChannelClientInfo channelClient = event.getClient();
  269. final ClientInfo client = channelClient.getClient();
  270. if (message.isEmpty()) {
  271. appendLine(filename, "*** %s (%s) left the channel",
  272. getDisplayName(channelClient), client.toString());
  273. } else {
  274. appendLine(filename, "*** %s (%s) left the channel (%s)",
  275. getDisplayName(channelClient), client.toString(), message);
  276. }
  277. }
  278. @Handler
  279. public void handleChannelQuit(final ChannelQuitEvent event) {
  280. final String filename = getLogFile(event.getChannel().getChannelInfo());
  281. final String reason = event.getMessage();
  282. final ChannelClientInfo channelClient = event.getClient();
  283. final ClientInfo client = channelClient.getClient();
  284. if (reason.isEmpty()) {
  285. appendLine(filename, "*** %s (%s) Quit IRC",
  286. getDisplayName(channelClient), client.toString());
  287. } else {
  288. appendLine(filename, "*** %s (%s) Quit IRC (%s)",
  289. getDisplayName(channelClient), client.toString(), reason);
  290. }
  291. }
  292. @Handler
  293. public void handleChannelKick(final ChannelKickEvent event) {
  294. final ChannelClientInfo victim = event.getVictim();
  295. final ChannelClientInfo perpetrator = event.getClient();
  296. final String reason = event.getReason();
  297. final String filename = getLogFile(event.getChannel().getChannelInfo());
  298. if (reason.isEmpty()) {
  299. appendLine(filename, "*** %s was kicked by %s",
  300. getDisplayName(victim), getDisplayName(perpetrator));
  301. } else {
  302. appendLine(filename, "*** %s was kicked by %s (%s)",
  303. getDisplayName(victim), getDisplayName(perpetrator), reason);
  304. }
  305. }
  306. @Handler
  307. public void handleNickChange(final ChannelNickchangeEvent event) {
  308. final String filename = getLogFile(event.getChannel().getChannelInfo());
  309. appendLine(filename, "*** %s is now %s", getDisplayName(event.getClient(),
  310. event.getOldNick()), getDisplayName(event.getClient()));
  311. }
  312. @Handler
  313. public void handleModeChange(final ChannelModechangeEvent event) {
  314. final String filename = getLogFile(event.getChannel().getChannelInfo());
  315. if (event.getClient().getClient().getNickname().isEmpty()) {
  316. appendLine(filename, "*** Channel modes are: %s", event.getModes());
  317. } else {
  318. appendLine(filename, "*** %s set modes: %s",
  319. getDisplayName(event.getClient()), event.getModes());
  320. }
  321. }
  322. @Override
  323. public void configChanged(final String domain, final String key) {
  324. setCachedSettings();
  325. }
  326. @Handler
  327. public void handleChannelOpened(final ChannelOpenedEvent event) {
  328. final String filename = getLogFile(event.getChannel().getName());
  329. if (autobackbuffer) {
  330. showBackBuffer(event.getChannel(), filename);
  331. }
  332. appendLine(filename, "*** Channel opened at: %s", OPENED_AT_FORMAT.format(new Date()));
  333. appendLine(filename, "");
  334. }
  335. @Handler
  336. public void handleChannelClosed(final ChannelClosedEvent event) {
  337. final String filename = getLogFile(event.getChannel().getName());
  338. appendLine(filename, "*** Channel closed at: %s", OPENED_AT_FORMAT.format(new Date()));
  339. if (openFiles.containsKey(filename)) {
  340. StreamUtils.close(openFiles.get(filename).writer);
  341. openFiles.remove(filename);
  342. }
  343. }
  344. /**
  345. * Add a backbuffer to a frame.
  346. *
  347. * @param frame The frame to add the backbuffer lines to
  348. * @param filename File to get backbuffer from
  349. */
  350. protected void showBackBuffer(final FrameContainer frame, final String filename) {
  351. if (frame == null) {
  352. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null, "Given a null frame", ""));
  353. return;
  354. }
  355. final File testFile = new File(filename);
  356. if (testFile.exists()) {
  357. try {
  358. final ReverseFileReader file = new ReverseFileReader(testFile);
  359. // Because the file includes a newline char at the end, an empty line
  360. // is returned by getLines. To counter this, we call getLines(1) and do
  361. // nothing with the output.
  362. file.getLines(1);
  363. final Stack<String> lines = file.getLines(backbufferLines);
  364. while (!lines.empty()) {
  365. frame.addLine(getColouredString(colour, lines.pop()), backbufferTimestamp);
  366. }
  367. file.close();
  368. frame.addLine(getColouredString(colour, "--- End of backbuffer\n"),
  369. backbufferTimestamp);
  370. } catch (IOException | SecurityException e) {
  371. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, e,
  372. "Unable to show backbuffer (Filename: " + filename + "): " + e.getMessage(),
  373. ""));
  374. }
  375. }
  376. }
  377. /**
  378. * Get a coloured String. If colour is invalid, IRC Colour 14 will be used.
  379. *
  380. * @param colour The colour the string should be (IRC Colour or 6-digit hex colour)
  381. * @param line the line to colour
  382. *
  383. * @return The given line with the appropriate irc codes appended/prepended to colour it.
  384. */
  385. protected static String getColouredString(final String colour, final String line) {
  386. String res = null;
  387. if (colour.length() < 3) {
  388. int num;
  389. try {
  390. num = Integer.parseInt(colour);
  391. } catch (NumberFormatException ex) {
  392. num = -1;
  393. }
  394. if (num >= 0 && num <= 15) {
  395. res = String.format("%c%02d%s%1$c", Styliser.CODE_COLOUR, num, line);
  396. }
  397. } else if (colour.length() == 6) {
  398. try {
  399. Color.decode('#' + colour);
  400. res = String.format("%c%s%s%1$c", Styliser.CODE_HEXCOLOUR, colour, line);
  401. } catch (NumberFormatException ex) { /* Do Nothing */ }
  402. }
  403. if (res == null) {
  404. res = String.format("%c%02d%s%1$c", Styliser.CODE_COLOUR, 14, line);
  405. }
  406. return res;
  407. }
  408. /**
  409. * Add a line to a file.
  410. *
  411. * @param filename Name of file to write to
  412. * @param format Format of line to add. (NewLine will be added Automatically)
  413. * @param args Arguments for format
  414. *
  415. * @return true on success, else false.
  416. */
  417. protected boolean appendLine(final String filename, final String format, final Object... args) {
  418. return appendLine(filename, String.format(format, args));
  419. }
  420. /**
  421. * Add a line to a file.
  422. *
  423. * @param filename Name of file to write to
  424. * @param line Line to add. (NewLine will be added Automatically)
  425. *
  426. * @return true on success, else false.
  427. */
  428. protected boolean appendLine(final String filename, final String line) {
  429. final StringBuilder finalLine = new StringBuilder();
  430. if (addtime) {
  431. String dateString;
  432. try {
  433. final DateFormat dateFormat = new SimpleDateFormat(timestamp);
  434. dateString = dateFormat.format(new Date()).trim();
  435. } catch (IllegalArgumentException iae) {
  436. // Default to known good format
  437. final DateFormat dateFormat = new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]");
  438. dateString = dateFormat.format(new Date()).trim();
  439. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, iae,
  440. "Dateformat String '" + timestamp + "' is invalid. For more information: "
  441. + "http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html",
  442. ""));
  443. }
  444. finalLine.append(dateString);
  445. finalLine.append(' ');
  446. }
  447. if (stripcodes) {
  448. finalLine.append(Styliser.stipControlCodes(line));
  449. } else {
  450. finalLine.append(line);
  451. }
  452. try {
  453. final BufferedWriter out;
  454. if (openFiles.containsKey(filename)) {
  455. final OpenFile of = openFiles.get(filename);
  456. of.lastUsedTime = System.currentTimeMillis();
  457. out = of.writer;
  458. } else {
  459. out = new BufferedWriter(new FileWriter(filename, true));
  460. openFiles.put(filename, new OpenFile(out));
  461. }
  462. out.write(finalLine.toString());
  463. out.newLine();
  464. out.flush();
  465. return true;
  466. } catch (IOException e) {
  467. /*
  468. * Do Nothing
  469. *
  470. * Makes no sense to keep adding errors to the logger when we can't write to the file,
  471. * as chances are it will happen on every incomming line.
  472. */
  473. }
  474. return false;
  475. }
  476. /**
  477. * Get the name of the log file for a specific object.
  478. *
  479. * @param channel Channel to get the name for
  480. *
  481. * @return the name of the log file to use for this object.
  482. */
  483. protected String getLogFile(final ChannelInfo channel) {
  484. final StringBuffer directory = getLogDirectory();
  485. final StringBuffer file = new StringBuffer();
  486. if (channel.getParser() != null) {
  487. addNetworkDir(directory, file, channel.getParser().getNetworkName());
  488. }
  489. file.append(sanitise(channel.getName().toLowerCase()));
  490. return getPath(directory, file, channel.getName());
  491. }
  492. /**
  493. * Get the name of the log file for a specific object.
  494. *
  495. * @param client Client to get the name for
  496. *
  497. * @return the name of the log file to use for this object.
  498. */
  499. protected String getLogFile(final ClientInfo client) {
  500. final StringBuffer directory = getLogDirectory();
  501. final StringBuffer file = new StringBuffer();
  502. if (client.getParser() != null) {
  503. addNetworkDir(directory, file, client.getParser().getNetworkName());
  504. }
  505. file.append(sanitise(client.getNickname().toLowerCase()));
  506. return getPath(directory, file, client.getNickname());
  507. }
  508. /**
  509. * Get the name of the log file for a specific object.
  510. *
  511. * @param descriptor Description of the object to get a log file for.
  512. *
  513. * @return the name of the log file to use for this object.
  514. */
  515. protected String getLogFile(@Nullable final String descriptor) {
  516. final StringBuffer directory = getLogDirectory();
  517. final StringBuffer file = new StringBuffer();
  518. final String md5String;
  519. if (descriptor == null) {
  520. file.append("null.log");
  521. md5String = "";
  522. } else {
  523. file.append(sanitise(descriptor.toLowerCase()));
  524. md5String = descriptor;
  525. }
  526. return getPath(directory, file, md5String);
  527. }
  528. /**
  529. * Gets the path for the given file and directory. Only intended to be used from getLogFile
  530. * methods.
  531. *
  532. * @param directory Log file directory
  533. * @param file Log file path
  534. * @param md5String Log file object MD5 hash
  535. *
  536. * @return Name of the log file
  537. */
  538. protected String getPath(final StringBuffer directory, final StringBuffer file,
  539. final String md5String) {
  540. if (usedate) {
  541. final String dateFormat = usedateformat;
  542. final String dateDir = new SimpleDateFormat(dateFormat).format(new Date());
  543. directory.append(dateDir);
  544. if (directory.charAt(directory.length() - 1) != File.separatorChar) {
  545. directory.append(File.separatorChar);
  546. }
  547. if (!new File(directory.toString()).exists()
  548. && !new File(directory.toString()).mkdirs()) {
  549. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null,
  550. "Unable to create date dirs", ""));
  551. }
  552. }
  553. if (filenamehash) {
  554. file.append('.');
  555. file.append(md5(md5String));
  556. }
  557. file.append(".log");
  558. return directory + file.toString();
  559. }
  560. /**
  561. * Sanitises the log file directory.
  562. *
  563. * @return Log directory
  564. */
  565. private StringBuffer getLogDirectory() {
  566. final StringBuffer directory = new StringBuffer();
  567. directory.append(directoryProvider.get());
  568. if (directory.charAt(directory.length() - 1) != File.separatorChar) {
  569. directory.append(File.separatorChar);
  570. }
  571. return directory;
  572. }
  573. /**
  574. * This function adds the networkName to the log file. It first tries to create a directory for
  575. * each network, if that fails it will prepend the networkName to the filename instead.
  576. *
  577. * @param directory Current directory name
  578. * @param file Current file name
  579. * @param networkName Name of network
  580. */
  581. protected void addNetworkDir(final StringBuffer directory, final StringBuffer file,
  582. final String networkName) {
  583. if (!networkfolders) {
  584. return;
  585. }
  586. final String network = sanitise(networkName.toLowerCase());
  587. boolean prependNetwork = false;
  588. // Check dir exists
  589. final File dir = new File(directory + network + System.getProperty(
  590. "file.separator"));
  591. if (dir.exists() && !dir.isDirectory()) {
  592. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null,
  593. "Unable to create networkfolders dir (file exists instead)", ""));
  594. // Prepend network name to file instead.
  595. prependNetwork = true;
  596. } else if (!dir.exists() && !dir.mkdirs()) {
  597. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null,
  598. "Unable to create networkfolders dir", ""));
  599. prependNetwork = true;
  600. }
  601. if (prependNetwork) {
  602. file.insert(0, " -- ");
  603. file.insert(0, network);
  604. } else {
  605. directory.append(network);
  606. directory.append(System.getProperty("file.separator"));
  607. }
  608. }
  609. /**
  610. * Sanitise a string to be used as a filename.
  611. *
  612. * @param name String to sanitise
  613. *
  614. * @return Sanitised version of name that can be used as a filename.
  615. */
  616. protected static String sanitise(final String name) {
  617. // Replace illegal chars with
  618. return name.replaceAll("[^\\w\\.\\s\\-#&_]", "_");
  619. }
  620. /**
  621. * Get the md5 hash of a string.
  622. *
  623. * @param string String to hash
  624. *
  625. * @return md5 hash of given string
  626. */
  627. protected static String md5(final String string) {
  628. try {
  629. final MessageDigest m = MessageDigest.getInstance("MD5");
  630. m.update(string.getBytes(), 0, string.length());
  631. return new BigInteger(1, m.digest()).toString(16);
  632. } catch (NoSuchAlgorithmException e) {
  633. return "";
  634. }
  635. }
  636. /**
  637. * Get name to display for channelClient (Taking into account the channelmodeprefix setting).
  638. *
  639. * @param channelClient The client to get the display name for
  640. *
  641. * @return name to display
  642. */
  643. protected String getDisplayName(final ChannelClientInfo channelClient) {
  644. return getDisplayName(channelClient, "");
  645. }
  646. /**
  647. * Get name to display for channelClient (Taking into account the channelmodeprefix setting).
  648. *
  649. * @param channelClient The client to get the display name for
  650. * @param overrideNick Nickname to display instead of real nickname
  651. *
  652. * @return name to display
  653. */
  654. protected String getDisplayName(final ChannelClientInfo channelClient, final String overrideNick) {
  655. if (channelClient == null) {
  656. return overrideNick.isEmpty() ? "Unknown Client" : overrideNick;
  657. } else if (overrideNick.isEmpty()) {
  658. return channelmodeprefix ? channelClient.toString() : channelClient.getClient().
  659. getNickname();
  660. } else {
  661. return channelmodeprefix ? channelClient.getImportantModePrefix() + overrideNick
  662. : overrideNick;
  663. }
  664. }
  665. /**
  666. * Shows the history window for the specified target, if available.
  667. *
  668. * @param target The window whose history we're trying to open
  669. *
  670. * @return True if the history is available, false otherwise
  671. */
  672. protected boolean showHistory(final FrameContainer target) {
  673. final String descriptor;
  674. if (target instanceof Channel) {
  675. descriptor = target.getName();
  676. } else if (target instanceof Query) {
  677. final Parser parser = target.getConnection().getParser();
  678. descriptor = parser.getClient(((PrivateChat) target).getHost()).getNickname();
  679. } else {
  680. // Unknown component
  681. return false;
  682. }
  683. final String log = getLogFile(descriptor);
  684. if (!new File(log).exists()) {
  685. // File doesn't exist
  686. return false;
  687. }
  688. final ReverseFileReader reader;
  689. try {
  690. reader = new ReverseFileReader(log);
  691. } catch (IOException | SecurityException ex) {
  692. return false;
  693. }
  694. final HistoryWindow window = new HistoryWindow("History", reader, target, urlBuilder,
  695. eventBus, colourManagerFactory, historyLines);
  696. windowManager.addWindow(target, window);
  697. return true;
  698. }
  699. /** Updates cached settings. */
  700. public void setCachedSettings() {
  701. networkfolders = config.getOptionBool(domain, "general.networkfolders");
  702. filenamehash = config.getOptionBool(domain, "advanced.filenamehash");
  703. addtime = config.getOptionBool(domain, "general.addtime");
  704. stripcodes = config.getOptionBool(domain, "general.stripcodes");
  705. channelmodeprefix = config.getOptionBool(domain, "general.channelmodeprefix");
  706. autobackbuffer = config.getOptionBool(domain, "backbuffer.autobackbuffer");
  707. backbufferTimestamp = config.getOptionBool(domain, "backbuffer.timestamp");
  708. usedate = config.getOptionBool(domain, "advanced.usedate");
  709. timestamp = config.getOption(domain, "general.timestamp");
  710. usedateformat = config.getOption(domain, "advanced.usedateformat");
  711. historyLines = config.getOptionInt(domain, "history.lines");
  712. colour = config.getOption(domain, "backbuffer.colour");
  713. backbufferLines = config.getOptionInt(domain, "backbuffer.lines");
  714. }
  715. /** Open File. */
  716. private static class OpenFile {
  717. /** Last used time. */
  718. public long lastUsedTime = System.currentTimeMillis();
  719. /** Open file's writer. */
  720. public final BufferedWriter writer;
  721. /**
  722. * Creates a new open file.
  723. *
  724. * @param writer Writer that has file open
  725. */
  726. protected OpenFile(final BufferedWriter writer) {
  727. this.writer = writer;
  728. }
  729. }
  730. }