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.

LoggingPlugin.java 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. /*
  2. * Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
  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.Main;
  25. import com.dmdirc.Query;
  26. import com.dmdirc.Server;
  27. import com.dmdirc.actions.ActionManager;
  28. import com.dmdirc.actions.CoreActionType;
  29. import com.dmdirc.actions.interfaces.ActionType;
  30. import com.dmdirc.commandparser.CommandManager;
  31. import com.dmdirc.config.IdentityManager;
  32. import com.dmdirc.config.prefs.PreferencesCategory;
  33. import com.dmdirc.config.prefs.PreferencesManager;
  34. import com.dmdirc.config.prefs.PreferencesSetting;
  35. import com.dmdirc.config.prefs.PreferencesType;
  36. import com.dmdirc.interfaces.ActionListener;
  37. import com.dmdirc.logger.ErrorLevel;
  38. import com.dmdirc.logger.Logger;
  39. import com.dmdirc.parser.interfaces.ChannelInfo;
  40. import com.dmdirc.parser.interfaces.ClientInfo;
  41. import com.dmdirc.parser.interfaces.Parser;
  42. import com.dmdirc.parser.irc.ChannelClientInfo;
  43. import com.dmdirc.plugins.Plugin;
  44. import com.dmdirc.ui.interfaces.InputWindow;
  45. import com.dmdirc.ui.interfaces.Window;
  46. import com.dmdirc.ui.messages.Styliser;
  47. import java.awt.Color;
  48. import java.io.BufferedWriter;
  49. import java.io.File;
  50. import java.io.FileNotFoundException;
  51. import java.io.FileWriter;
  52. import java.io.IOException;
  53. import java.math.BigInteger;
  54. import java.security.MessageDigest;
  55. import java.security.NoSuchAlgorithmException;
  56. import java.text.DateFormat;
  57. import java.text.SimpleDateFormat;
  58. import java.util.Date;
  59. import java.util.Hashtable;
  60. import java.util.Map;
  61. import java.util.Stack;
  62. import java.util.Timer;
  63. import java.util.TimerTask;
  64. /**
  65. * Adds logging facility to client.
  66. *
  67. * @author Shane 'Dataforce' McCormack
  68. */
  69. public class LoggingPlugin extends Plugin implements ActionListener {
  70. /** The command we registered. */
  71. private LoggingCommand command;
  72. /** Open File */
  73. protected class OpenFile {
  74. public long lastUsedTime = System.currentTimeMillis();
  75. public BufferedWriter writer = null;
  76. public OpenFile(final BufferedWriter writer) {
  77. this.writer = writer;
  78. }
  79. }
  80. /** Timer used to close idle files */
  81. protected Timer idleFileTimer;
  82. /** Hashtable of open files. */
  83. protected final Map<String, OpenFile> openFiles = new Hashtable<String, OpenFile>();
  84. /** Date format used for "File Opened At" log. */
  85. final DateFormat openedAtFormat = new SimpleDateFormat("EEEE MMMM dd, yyyy - HH:mm:ss");
  86. /**
  87. * Creates a new instance of the Logging Plugin.
  88. */
  89. public LoggingPlugin() { super(); }
  90. /** {@inheritDoc} */
  91. @Override
  92. public void domainUpdated() {
  93. IdentityManager.getAddonIdentity().setOption(getDomain(),
  94. "general.directory", Main.getConfigDir() + "logs"
  95. + System.getProperty("file.separator"));
  96. }
  97. /**
  98. * Called when the plugin is loaded.
  99. */
  100. @Override
  101. public void onLoad() {
  102. final File dir = new File(IdentityManager.getGlobalConfig().getOption(getDomain(), "general.directory"));
  103. if (dir.exists()) {
  104. if (!dir.isDirectory()) {
  105. Logger.userError(ErrorLevel.LOW, "Unable to create logging dir (file exists instead)");
  106. }
  107. } else {
  108. if (!dir.mkdirs()) {
  109. Logger.userError(ErrorLevel.LOW, "Unable to create logging dir");
  110. }
  111. }
  112. command = new LoggingCommand();
  113. ActionManager.addListener(this,
  114. CoreActionType.CHANNEL_OPENED,
  115. CoreActionType.CHANNEL_CLOSED,
  116. CoreActionType.CHANNEL_MESSAGE,
  117. CoreActionType.CHANNEL_SELF_MESSAGE,
  118. CoreActionType.CHANNEL_ACTION,
  119. CoreActionType.CHANNEL_SELF_ACTION,
  120. CoreActionType.CHANNEL_GOTTOPIC,
  121. CoreActionType.CHANNEL_TOPICCHANGE,
  122. CoreActionType.CHANNEL_JOIN,
  123. CoreActionType.CHANNEL_PART,
  124. CoreActionType.CHANNEL_QUIT,
  125. CoreActionType.CHANNEL_KICK,
  126. CoreActionType.CHANNEL_NICKCHANGE,
  127. CoreActionType.CHANNEL_MODECHANGE,
  128. CoreActionType.QUERY_OPENED,
  129. CoreActionType.QUERY_CLOSED,
  130. CoreActionType.QUERY_MESSAGE,
  131. CoreActionType.QUERY_SELF_MESSAGE,
  132. CoreActionType.QUERY_ACTION,
  133. CoreActionType.QUERY_SELF_ACTION);
  134. // Close idle files every hour.
  135. idleFileTimer = new Timer("LoggingPlugin Timer");
  136. idleFileTimer.schedule(new TimerTask(){
  137. /** {@inheritDoc} */
  138. @Override
  139. public void run() {
  140. timerTask();
  141. }
  142. }, 3600000);
  143. }
  144. /**
  145. * What to do every hour when the timer fires.
  146. */
  147. protected void timerTask() {
  148. // Oldest time to allow
  149. final long oldestTime = System.currentTimeMillis() - 3480000;
  150. synchronized (openFiles) {
  151. for (String filename : (new Hashtable<String, OpenFile>(openFiles)).keySet()) {
  152. OpenFile file = openFiles.get(filename);
  153. if (file.lastUsedTime < oldestTime) {
  154. try {
  155. file.writer.close();
  156. openFiles.remove(filename);
  157. } catch (IOException e) {
  158. Logger.userError(ErrorLevel.LOW, "Unable to close idle file (File: "+filename+")");
  159. }
  160. }
  161. }
  162. }
  163. }
  164. /**
  165. * Called when this plugin is unloaded.
  166. */
  167. @Override
  168. public void onUnload() {
  169. idleFileTimer.cancel();
  170. idleFileTimer.purge();
  171. CommandManager.unregisterCommand(command);
  172. ActionManager.removeListener(this);
  173. synchronized (openFiles) {
  174. for (String filename : openFiles.keySet()) {
  175. OpenFile file = openFiles.get(filename);
  176. try {
  177. file.writer.close();
  178. } catch (IOException e) {
  179. Logger.userError(ErrorLevel.LOW, "Unable to close file (File: "+filename+")");
  180. }
  181. }
  182. openFiles.clear();
  183. }
  184. }
  185. /** {@inheritDoc} */
  186. @Override
  187. public void showConfig(final PreferencesManager manager) {
  188. final PreferencesCategory general = new PreferencesCategory("Logging", "General configuration for Logging plugin.");
  189. final PreferencesCategory backbuffer = new PreferencesCategory("Back Buffer", "Options related to the automatic backbuffer");
  190. final PreferencesCategory advanced = new PreferencesCategory("Advanced", "Advanced configuration for Logging plugin. You shouldn't need to edit this unless you know what you are doing.");
  191. general.addSetting(new PreferencesSetting(PreferencesType.TEXT, getDomain(), "general.directory", "Directory", "Directory for log files"));
  192. general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, getDomain(), "general.networkfolders", "Separate logs by network", "Should the files be stored in a sub-dir with the networks name?"));
  193. general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, getDomain(), "general.addtime", "Timestamp logs", "Should a timestamp be added to the log files?"));
  194. general.addSetting(new PreferencesSetting(PreferencesType.TEXT, getDomain(), "general.timestamp", "Timestamp format", "The String to pass to 'SimpleDateFormat' to format the timestamp"));
  195. general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, getDomain(), "general.stripcodes", "Strip Control Codes", "Remove known irc control codes from lines before saving?"));
  196. general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, getDomain(), "general.channelmodeprefix", "Show channel mode prefix", "Show the @,+ etc next to nicknames"));
  197. backbuffer.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, getDomain(), "backbuffer.autobackbuffer", "Automatically display", "Automatically display the backbuffer when a channel is joined"));
  198. backbuffer.addSetting(new PreferencesSetting(PreferencesType.COLOUR, getDomain(), "backbuffer.colour", "Colour to use for display", "Colour used when displaying the backbuffer"));
  199. backbuffer.addSetting(new PreferencesSetting(PreferencesType.INTEGER, getDomain(), "backbuffer.lines", "Number of lines to show", "Number of lines used when displaying backbuffer"));
  200. backbuffer.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, getDomain(), "backbuffer.timestamp", "Show Formatter-Timestamp", "Should the line be added to the frame with the timestamp from the formatter aswell as the file contents"));
  201. advanced.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, getDomain(), "advanced.filenamehash", "Add Filename hash", "Add the MD5 hash of the channel/client name to the filename. (This is used to allow channels with similar names (ie a _ not a -) to be logged separately)"));
  202. advanced.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, getDomain(), "advanced.usedate", "Use Date directories", "Should the log files be in separate directories based on the date?"));
  203. advanced.addSetting(new PreferencesSetting(PreferencesType.TEXT, getDomain(), "advanced.usedateformat", "Archive format", "The String to pass to 'SimpleDateFormat' to format the directory name(s) for archiving"));
  204. general.addSubCategory(backbuffer.setInline());
  205. general.addSubCategory(advanced.setInline());
  206. manager.getCategory("Plugins").addSubCategory(general.setInlineAfter());
  207. }
  208. /**
  209. * Log a query-related event
  210. *
  211. * @param type The type of the event to process
  212. * @param format Format of messages that are about to be sent. (May be null)
  213. * @param arguments The arguments for the event
  214. */
  215. protected void handleQueryEvent(final CoreActionType type, final StringBuffer format, final Object... arguments) {
  216. final Query query = (Query)arguments[0];
  217. if (query.getServer() == null) {
  218. Logger.appError(ErrorLevel.MEDIUM, "Query object has no server ("+type.toString()+")", new Exception("Query object has no server ("+type.toString()+")"));
  219. return;
  220. }
  221. final Parser parser = query.getServer().getParser();
  222. ClientInfo client;
  223. if (parser == null) {
  224. // Without a parser object, we might not be able to find the file to log this to.
  225. if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "general.networkfolders")) {
  226. // We *wont* be able to, so rather than logging to an incorrect file we just won't log.
  227. return;
  228. }
  229. client = null;
  230. } else {
  231. client = parser.getClientInfo(query.getHost());
  232. if (client == null) {
  233. client = new IRCClientInfo(parser, query.getHost()).setFake(true);
  234. }
  235. }
  236. final String filename = getLogFile(client);
  237. switch (type) {
  238. case QUERY_OPENED:
  239. if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "backbuffer.autobackbuffer")) {
  240. showBackBuffer(query.getFrame(), filename);
  241. }
  242. appendLine(filename, "*** Query opened at: %s", openedAtFormat.format(new Date()));
  243. appendLine(filename, "*** Query with User: %s", query.getHost());
  244. appendLine(filename, "");
  245. break;
  246. case QUERY_CLOSED:
  247. appendLine(filename, "*** Query closed at: %s", openedAtFormat.format(new Date()));
  248. if (openFiles.containsKey(filename)) {
  249. final BufferedWriter file = openFiles.get(filename).writer;
  250. try {
  251. file.close();
  252. } catch (IOException e) {
  253. Logger.userError(ErrorLevel.LOW, "Unable to close file (Filename: "+filename+")");
  254. }
  255. openFiles.remove(filename);
  256. }
  257. break;
  258. case QUERY_MESSAGE:
  259. case QUERY_SELF_MESSAGE:
  260. case QUERY_ACTION:
  261. case QUERY_SELF_ACTION:
  262. final boolean isME = (type == CoreActionType.QUERY_SELF_MESSAGE || type == CoreActionType.QUERY_SELF_ACTION);
  263. final String overrideNick = (isME) ? getDisplayName(parser.getMyself()) : "";
  264. if (type == CoreActionType.QUERY_MESSAGE || type == CoreActionType.QUERY_SELF_MESSAGE) {
  265. appendLine(filename, "<%s> %s", getDisplayName(client, overrideNick), (String)arguments[1]);
  266. } else {
  267. appendLine(filename, "* %s %s", getDisplayName(client, overrideNick), (String)arguments[1]);
  268. }
  269. break;
  270. }
  271. }
  272. /**
  273. * Log a channel-related event
  274. *
  275. * @param type The type of the event to process
  276. * @param format Format of messages that are about to be sent. (May be null)
  277. * @param arguments The arguments for the event
  278. */
  279. protected void handleChannelEvent(final CoreActionType type, final StringBuffer format, final Object... arguments) {
  280. final Channel chan = ((Channel)arguments[0]);
  281. final ChannelInfo channel = chan.getChannelInfo();
  282. final String filename = getLogFile(channel);
  283. final ChannelClientInfo channelClient = (arguments.length > 1 && arguments[1] instanceof ChannelClientInfo) ? (ChannelClientInfo)arguments[1] : null;
  284. final ClientInfo client = (channelClient != null) ? channelClient.getClient() : null;
  285. final String message = (arguments.length > 2 && arguments[2] instanceof String) ? (String)arguments[2] : null;
  286. switch (type) {
  287. case CHANNEL_OPENED:
  288. if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "backbuffer.autobackbuffer")) {
  289. showBackBuffer(chan.getFrame(), filename);
  290. }
  291. appendLine(filename, "*** Channel opened at: %s", openedAtFormat.format(new Date()));
  292. appendLine(filename, "");
  293. break;
  294. case CHANNEL_CLOSED:
  295. appendLine(filename, "*** Channel closed at: %s", openedAtFormat.format(new Date()));
  296. if (openFiles.containsKey(filename)) {
  297. final BufferedWriter file = openFiles.get(filename).writer;
  298. try {
  299. file.close();
  300. } catch (IOException e) {
  301. Logger.userError(ErrorLevel.LOW, "Unable to close file (Filename: "+filename+")");
  302. }
  303. openFiles.remove(filename);
  304. }
  305. break;
  306. case CHANNEL_MESSAGE:
  307. case CHANNEL_SELF_MESSAGE:
  308. case CHANNEL_ACTION:
  309. case CHANNEL_SELF_ACTION:
  310. if (type == CoreActionType.CHANNEL_MESSAGE || type == CoreActionType.CHANNEL_SELF_MESSAGE) {
  311. appendLine(filename, "<%s> %s", getDisplayName(client), message);
  312. } else {
  313. appendLine(filename, "* %s %s", getDisplayName(client), message);
  314. }
  315. break;
  316. case CHANNEL_GOTTOPIC:
  317. // ActionManager.processEvent(CoreActionType.CHANNEL_GOTTOPIC, this);
  318. final DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
  319. final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
  320. appendLine(filename, "*** Topic is: %s", channel.getTopic());
  321. appendLine(filename, "*** Set at: %s on %s by %s", timeFormat.format(1000 * channel.getTopicTime()), dateFormat.format(1000 * channel.getTopicTime()), channel.getTopicUser());
  322. break;
  323. case CHANNEL_TOPICCHANGE:
  324. appendLine(filename, "*** %s Changed the topic to: %s", getDisplayName(channelClient), message);
  325. break;
  326. case CHANNEL_JOIN:
  327. appendLine(filename, "*** %s (%s) joined the channel", getDisplayName(channelClient), client.toString());
  328. break;
  329. case CHANNEL_PART:
  330. if (message.isEmpty()) {
  331. appendLine(filename, "*** %s (%s) left the channel", getDisplayName(channelClient), client.toString());
  332. } else {
  333. appendLine(filename, "*** %s (%s) left the channel (%s)", getDisplayName(channelClient), client.toString(), message);
  334. }
  335. break;
  336. case CHANNEL_QUIT:
  337. if (message.isEmpty()) {
  338. appendLine(filename, "*** %s (%s) Quit IRC", getDisplayName(channelClient), client.toString());
  339. } else {
  340. appendLine(filename, "*** %s (%s) Quit IRC (%s)", getDisplayName(channelClient), client.toString(), message);
  341. }
  342. break;
  343. case CHANNEL_KICK:
  344. final String kickReason = (String)arguments[3];
  345. final ChannelClientInfo kickedClient = (ChannelClientInfo)arguments[2];
  346. if (kickReason.isEmpty()) {
  347. appendLine(filename, "*** %s was kicked by %s", getDisplayName(kickedClient), getDisplayName(channelClient));
  348. } else {
  349. appendLine(filename, "*** %s was kicked by %s (%s)", getDisplayName(kickedClient), getDisplayName(channelClient), kickReason);
  350. }
  351. break;
  352. case CHANNEL_NICKCHANGE:
  353. appendLine(filename, "*** %s is now %s", getDisplayName(channelClient, message), getDisplayName(channelClient));
  354. break;
  355. case CHANNEL_MODECHANGE:
  356. if (channelClient.getNickname().isEmpty()) {
  357. appendLine(filename, "*** Channel modes are: %s", message);
  358. } else {
  359. appendLine(filename, "*** %s set modes: %s", getDisplayName(channelClient), message);
  360. }
  361. break;
  362. }
  363. }
  364. /**
  365. * Process an event of the specified type.
  366. *
  367. * @param type The type of the event to process
  368. * @param format Format of messages that are about to be sent. (May be null)
  369. * @param arguments The arguments for the event
  370. */
  371. @Override
  372. public void processEvent(final ActionType type, final StringBuffer format, final Object ... arguments) {
  373. if (type instanceof CoreActionType) {
  374. final CoreActionType thisType = (CoreActionType) type;
  375. switch (thisType) {
  376. case CHANNEL_OPENED:
  377. case CHANNEL_CLOSED:
  378. case CHANNEL_MESSAGE:
  379. case CHANNEL_SELF_MESSAGE:
  380. case CHANNEL_ACTION:
  381. case CHANNEL_SELF_ACTION:
  382. case CHANNEL_GOTTOPIC:
  383. case CHANNEL_TOPICCHANGE:
  384. case CHANNEL_JOIN:
  385. case CHANNEL_PART:
  386. case CHANNEL_QUIT:
  387. case CHANNEL_KICK:
  388. case CHANNEL_NICKCHANGE:
  389. case CHANNEL_MODECHANGE:
  390. handleChannelEvent(thisType, format, arguments);
  391. break;
  392. case QUERY_OPENED:
  393. case QUERY_CLOSED:
  394. case QUERY_MESSAGE:
  395. case QUERY_SELF_MESSAGE:
  396. case QUERY_ACTION:
  397. case QUERY_SELF_ACTION:
  398. handleQueryEvent(thisType, format, arguments);
  399. break;
  400. default:
  401. break;
  402. }
  403. }
  404. }
  405. /**
  406. * Add a backbuffer to a frame.
  407. *
  408. * @param frame The frame to add the backbuffer lines to
  409. * @param filename File to get backbuffer from
  410. */
  411. protected void showBackBuffer(final Window frame, final String filename) {
  412. final int numLines = IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "backbuffer.lines");
  413. final String colour = IdentityManager.getGlobalConfig().getOption(getDomain(), "backbuffer.colour");
  414. final boolean showTimestamp = IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "backbuffer.timestamp");
  415. if (frame == null) {
  416. Logger.userError(ErrorLevel.LOW, "Given a null frame");
  417. return;
  418. }
  419. final File testFile = new File(filename);
  420. if (testFile.exists()) {
  421. try {
  422. final ReverseFileReader file = new ReverseFileReader(testFile);
  423. // Because the file includes a newline char at the end, an empty line
  424. // is returned by getLines. To counter this, we call getLines(1) and do
  425. // nothing with the output.
  426. file.getLines(1);
  427. final Stack<String> lines = file.getLines(numLines);
  428. while (!lines.empty()) {
  429. frame.addLine(getColouredString(colour,lines.pop()), showTimestamp);
  430. }
  431. file.close();
  432. frame.addLine(getColouredString(colour,"--- End of backbuffer\n"), showTimestamp);
  433. } catch (FileNotFoundException e) {
  434. Logger.userError(ErrorLevel.LOW, "Unable to show backbuffer (Filename: "+filename+"): " + e.getMessage());
  435. } catch (IOException e) {
  436. Logger.userError(ErrorLevel.LOW, "Unable to show backbuffer (Filename: "+filename+"): " + e.getMessage());
  437. } catch (SecurityException e) {
  438. Logger.userError(ErrorLevel.LOW, "Unable to show backbuffer (Filename: "+filename+"): " + e.getMessage());
  439. }
  440. }
  441. }
  442. /**
  443. * Get a coloured String.
  444. * If colour is invalid, IRC Colour 14 will be used.
  445. *
  446. * @param colour The colour the string should be (IRC Colour or 6-digit hex colour)
  447. * @param line the line to colour
  448. * @return The given line with the appropriate irc codes appended/prepended to colour it.
  449. */
  450. protected static String getColouredString(final String colour, final String line) {
  451. String res = null;
  452. if (colour.length() < 3) {
  453. int num;
  454. try {
  455. num = Integer.parseInt(colour);
  456. } catch (NumberFormatException ex) {
  457. num = -1;
  458. }
  459. if (num >= 0 && num <= 15) {
  460. res = String.format("%c%02d%s%1$c", Styliser.CODE_COLOUR, num, line);
  461. }
  462. } else if (colour.length() == 6) {
  463. try {
  464. Color.decode("#" + colour);
  465. res = String.format("%c%s%s%1$c", Styliser.CODE_HEXCOLOUR, colour, line);
  466. } catch (NumberFormatException ex) { /* Do Nothing */ }
  467. }
  468. if (res == null) {
  469. res = String.format("%c%02d%s%1$c", Styliser.CODE_COLOUR, 14, line);
  470. }
  471. return res;
  472. }
  473. /**
  474. * Add a line to a file.
  475. *
  476. * @param filename Name of file to write to
  477. * @param format Format of line to add. (NewLine will be added Automatically)
  478. * @param args Arguments for format
  479. * @return true on success, else false.
  480. */
  481. protected boolean appendLine(final String filename, final String format, final Object... args) {
  482. return appendLine(filename, String.format(format, args));
  483. }
  484. /**
  485. * Add a line to a file.
  486. *
  487. * @param filename Name of file to write to
  488. * @param line Line to add. (NewLine will be added Automatically)
  489. * @return true on success, else false.
  490. */
  491. protected boolean appendLine(final String filename, final String line) {
  492. final StringBuffer finalLine = new StringBuffer();
  493. if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "general.addtime")) {
  494. String dateString;
  495. final String dateFormatString = IdentityManager.getGlobalConfig().getOption(getDomain(), "general.timestamp");
  496. try {
  497. final DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
  498. dateString = dateFormat.format(new Date()).trim();
  499. } catch (IllegalArgumentException iae) {
  500. // Default to known good format
  501. final DateFormat dateFormat = new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]");
  502. dateString = dateFormat.format(new Date()).trim();
  503. Logger.userError(ErrorLevel.LOW, "Dateformat String '"+dateFormatString+"' is invalid. For more information: http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html");
  504. }
  505. finalLine.append(dateString);
  506. finalLine.append(" ");
  507. }
  508. if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "general.stripcodes")) {
  509. finalLine.append(Styliser.stipControlCodes(line));
  510. } else {
  511. finalLine.append(line);
  512. }
  513. //System.out.println("[Adding] "+filename+" => "+finalLine);
  514. BufferedWriter out = null;
  515. try {
  516. if (openFiles.containsKey(filename)) {
  517. OpenFile of = openFiles.get(filename);
  518. of.lastUsedTime = System.currentTimeMillis();
  519. out = of.writer;
  520. } else {
  521. out = new BufferedWriter(new FileWriter(filename, true));
  522. openFiles.put(filename, new OpenFile(out));
  523. }
  524. out.write(finalLine.toString());
  525. out.newLine();
  526. out.flush();
  527. return true;
  528. } catch (IOException e) {
  529. /*
  530. * Do Nothing
  531. *
  532. * Makes no sense to keep adding errors to the logger when we can't
  533. * write to the file, as chances are it will happen on every incomming
  534. * line.
  535. */
  536. }
  537. return false;
  538. }
  539. /**
  540. * Get the name of the log file for a specific object.
  541. *
  542. * @param obj Object to get name for
  543. * @return the name of the log file to use for this object.
  544. */
  545. protected String getLogFile(final Object obj) {
  546. final StringBuffer directory = new StringBuffer();
  547. final StringBuffer file = new StringBuffer();
  548. String md5String = "";
  549. directory.append(IdentityManager.getGlobalConfig().getOption(getDomain(), "general.directory"));
  550. if (directory.charAt(directory.length()-1) != File.separatorChar) {
  551. directory.append(File.separatorChar);
  552. }
  553. if (obj == null) {
  554. file.append("null.log");
  555. } else if (obj instanceof ChannelInfo) {
  556. final ChannelInfo channel = (ChannelInfo) obj;
  557. if (channel.getParser() != null) {
  558. addNetworkDir(directory, file, channel.getParser().getNetworkName());
  559. }
  560. file.append(sanitise(channel.getName().toLowerCase()));
  561. md5String = channel.getName();
  562. } else if (obj instanceof ClientInfo) {
  563. final ClientInfo client = (ClientInfo) obj;
  564. if (client.getParser() != null) {
  565. addNetworkDir(directory, file, client.getParser().getNetworkName());
  566. }
  567. file.append(sanitise(client.getNickname().toLowerCase()));
  568. md5String = client.getNickname();
  569. } else {
  570. file.append(sanitise(obj.toString().toLowerCase()));
  571. md5String = obj.toString();
  572. }
  573. if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "advanced.usedate")) {
  574. final String dateFormat = IdentityManager.getGlobalConfig().getOption(getDomain(), "advanced.usedateformat");
  575. final String dateDir = (new SimpleDateFormat(dateFormat)).format(new Date());
  576. directory.append(dateDir);
  577. if (directory.charAt(directory.length()-1) != File.separatorChar) {
  578. directory.append(File.separatorChar);
  579. }
  580. if (!new File(directory.toString()).exists() && !(new File(directory.toString())).mkdirs()) {
  581. Logger.userError(ErrorLevel.LOW, "Unable to create date dirs");
  582. }
  583. }
  584. if (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "advanced.filenamehash")) {
  585. file.append('.');
  586. file.append(md5(md5String));
  587. }
  588. file.append(".log");
  589. return directory.toString() + file.toString();
  590. }
  591. /**
  592. * This function adds the networkName to the log file.
  593. * It first tries to create a directory for each network, if that fails
  594. * it will prepend the networkName to the filename instead.
  595. *
  596. * @param directory Current directory name
  597. * @param file Current file name
  598. * @param networkName Name of network
  599. */
  600. protected void addNetworkDir(final StringBuffer directory, final StringBuffer file, final String networkName) {
  601. if (!IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "general.networkfolders")) {
  602. return;
  603. }
  604. final String network = sanitise(networkName.toLowerCase());
  605. boolean prependNetwork = false;
  606. // Check dir exists
  607. final File dir = new File(directory.toString()+network+System.getProperty("file.separator"));
  608. if (dir.exists() && !dir.isDirectory()) {
  609. Logger.userError(ErrorLevel.LOW, "Unable to create networkfolders dir (file exists instead)");
  610. // Prepend network name to file instead.
  611. prependNetwork = true;
  612. } else if (!dir.exists() && !dir.mkdirs()) {
  613. Logger.userError(ErrorLevel.LOW, "Unable to create networkfolders dir");
  614. prependNetwork = true;
  615. }
  616. if (prependNetwork) {
  617. file.insert(0, " -- ");
  618. file.insert(0, network);
  619. } else {
  620. directory.append(network);
  621. directory.append(System.getProperty("file.separator"));
  622. }
  623. }
  624. /**
  625. * Sanitise a string to be used as a filename.
  626. *
  627. * @param name String to sanitise
  628. * @return Sanitised version of name that can be used as a filename.
  629. */
  630. protected static String sanitise(final String name) {
  631. // Replace illegal chars with
  632. return name.replaceAll("[^\\w\\.\\s\\-\\#\\&\\_]", "_");
  633. }
  634. /**
  635. * Get the md5 hash of a string.
  636. *
  637. * @param string String to hash
  638. * @return md5 hash of given string
  639. */
  640. protected static String md5(final String string) {
  641. try {
  642. final MessageDigest m = MessageDigest.getInstance("MD5");
  643. m.update(string.getBytes(), 0, string.length());
  644. return new BigInteger(1, m.digest()).toString(16);
  645. } catch (NoSuchAlgorithmException e) {
  646. return "";
  647. }
  648. }
  649. /**
  650. * Get name to display for client.
  651. *
  652. * @param client The client to get the display name for
  653. * @return name to display
  654. */
  655. protected String getDisplayName(final ClientInfo client) {
  656. return getDisplayName(client, "");
  657. }
  658. /**
  659. * Get name to display for client.
  660. *
  661. * @param client The client to get the display name for
  662. * @param overrideNick Nickname to display instead of real nickname
  663. * @return name to display
  664. */
  665. protected String getDisplayName(final ClientInfo client, final String overrideNick) {
  666. if (overrideNick.isEmpty()) {
  667. return (client == null) ? "Unknown Client" : client.getNickname() ;
  668. } else {
  669. return overrideNick;
  670. }
  671. }
  672. /**
  673. * Get name to display for channelClient (Taking into account the channelmodeprefix setting).
  674. *
  675. * @param channelClient The client to get the display name for
  676. * @return name to display
  677. */
  678. protected String getDisplayName(final ChannelClientInfo channelClient) {
  679. return getDisplayName(channelClient, "");
  680. }
  681. /**
  682. * Get name to display for channelClient (Taking into account the channelmodeprefix setting).
  683. *
  684. * @param channelClient The client to get the display name for
  685. * @param overrideNick Nickname to display instead of real nickname
  686. * @return name to display
  687. */
  688. protected String getDisplayName(final ChannelClientInfo channelClient, final String overrideNick) {
  689. final boolean addModePrefix = (IdentityManager.getGlobalConfig().getOptionBool(getDomain(), "general.channelmodeprefix"));
  690. if (channelClient == null) {
  691. return (overrideNick.isEmpty()) ? "Unknown Client" : overrideNick;
  692. } else if (overrideNick.isEmpty()) {
  693. return (addModePrefix) ? channelClient.toString() : channelClient.getNickname();
  694. } else {
  695. return (addModePrefix) ? channelClient.getImportantModePrefix() + overrideNick : overrideNick;
  696. }
  697. }
  698. /**
  699. * Shows the history window for the specified target, if available.
  700. *
  701. * @param target The window whose history we're trying to open
  702. * @return True if the history is available, false otherwise
  703. */
  704. protected boolean showHistory(final InputWindow target) {
  705. Object component;
  706. if (target.getContainer() instanceof Channel) {
  707. component = ((Channel) target.getContainer()).getChannelInfo();
  708. } else if (target.getContainer() instanceof Query) {
  709. final Parser parser = ((Query) target.getContainer()).getServer().getParser();
  710. component = parser.getClientInfo(((Query) target.getContainer()).getHost());
  711. if (component == null) {
  712. component = new IRCClientInfo(parser, ((Query) target.getContainer()).getHost()).setFake(true);
  713. }
  714. } else if (target.getContainer() instanceof Server) {
  715. component = target.getContainer().getServer().getParser();
  716. } else {
  717. // Unknown component
  718. return false;
  719. }
  720. final String log = getLogFile(component);
  721. if (!new File(log).exists()) {
  722. // File doesn't exist
  723. return false;
  724. }
  725. ReverseFileReader reader;
  726. try {
  727. reader = new ReverseFileReader(log);
  728. } catch (FileNotFoundException ex) {
  729. return false;
  730. } catch (IOException ex) {
  731. return false;
  732. } catch (SecurityException ex) {
  733. return false;
  734. }
  735. new HistoryWindow("History", reader, target,
  736. IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "history.lines"));
  737. return true;
  738. }
  739. }