/** * Upload an object * * @param upload The upload object */ public void upload(final Upload upload) { // Check associations if (!uploaderAssociations.containsKey(upload.getClass())) { icon.displayMessage( Language.getString("noUploaderTitle"), Language.getString("noUploader", upload.getClass().getName()), TrayIcon.MessageType.ERROR); return; } uploadService.execute( new Runnable() { @Override public void run() { icon.setImage(Resources.ICON_BUSY_IMAGE); executeUpload(upload); icon.setImage(Resources.ICON_IMAGE); } }); }
/** Upload a file to the file service by selecting in another window */ public void selectFile() { final JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); final int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = chooser.getSelectedFile(); final int confirm = JOptionPane.showConfirmDialog( null, Language.getString("uploadConfirm", file.getName()), Language.getString("uploadConfirmTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (confirm == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog( null, Language.getString("fileUploading"), Language.getString("fileUploadTitle"), JOptionPane.INFORMATION_MESSAGE); upload(new FileUpload(file.getAbsoluteFile())); } else { JOptionPane.showMessageDialog( null, Language.getString("fileUploadCanceled"), Language.getString("fileUploadTitle"), JOptionPane.INFORMATION_MESSAGE); } } }
/** Upload content from the clipboard */ public void clipboard() { try { final Object clipboard = ClipboardUtil.getClipboardContents(); if (clipboard == null) { icon.displayMessage( Language.getString("invalidClipboard"), Language.getString("invalidClipboardTitle"), TrayIcon.MessageType.WARNING); return; } if (clipboard instanceof BufferedImage) { upload(new ImageUpload((BufferedImage) clipboard)); } else if (clipboard instanceof File) { final File file = (File) clipboard; final String mime = FileUtils.getMimeType(file.getAbsolutePath()); // A better way to upload images, it'll check the mime type! if (mime.startsWith("image")) { upload(new ImageUpload(ImageIO.read(file))); } else if (mime.startsWith("text") && configuration.getBoolean("plainTextUpload")) { upload(new TextUpload(FileUtils.readFile(file))); } else { upload(new FileUpload(file)); } } else if (clipboard instanceof String) { final String string = clipboard.toString(); if (string.matches("((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)")) { upload(new URLUpload(clipboard.toString())); } else { upload(new TextUpload(string)); } } } catch (final ClipboardException e) { logger.log(Level.SEVERE, "Unable to get clipboard contents", e); showException(e); } catch (final IOException e) { e.printStackTrace(); } }
/** Prompt the user for a configuration reset */ public void promptConfigurationReset() { final int option = JOptionPane.showConfirmDialog( null, Language.getString("settingsCorrupted"), Language.getString("errorLoadingSettings"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (option == JOptionPane.YES_OPTION) { try { loadSettings(true); } catch (final Exception e) { logger.log(Level.SEVERE, "Unable to load default settings!", e); } } else if (option == JOptionPane.NO_OPTION) { // If no, let them set the configuration themselves.. openSettings(); } else if (option == JOptionPane.CANCEL_OPTION) { // Exit, they don't want anything to do with it. System.exit(0); } }
/** * Load upload filters * * @throws Exception If an error occurred while loading */ private void loadFilters() throws Exception { // Register any filters // PNG Compression will always be done last. registerFilter(new PNGCompressionFilter(this)); // Watermarks will be done after everything else too. registerFilter(new WatermarkFilter()); // Load custom filters final File dir = new File(Util.getWorkingDirectory(), "plugins/filters"); if (!dir.exists()) { dir.mkdirs(); } final ClassLoader loader = new URLClassLoader(new URL[] {dir.toURI().toURL()}); for (final File f : dir.listFiles()) { // TODO jar files. final String name = f.getName(); if (name.endsWith(".class") && !name.contains("$")) { try { final Class<?> c = loader.loadClass(f.getName().replaceAll(".class", "")); final UploadFilter<?> uploader = (UploadFilter<?>) c.newInstance(); if (uploader == null) { throw new Exception(); } registerFilter(uploader); } catch (final Exception e) { JOptionPane.showMessageDialog( null, Language.getString("loadingError", name, e), Language.getString("filterLoadError", e), JOptionPane.ERROR_MESSAGE); } } } }
/** Initialize the tray menu */ private void initializeTray() { // Add uploaders from the list we loaded earlier final PopupMenu tray = new PopupMenu(); // Add the action menu tray.add(new ActionMenuItem(Language.getString("cropupload"), ScreenshotAction.CROP)); tray.add(new ActionMenuItem(Language.getString("fullupload"), ScreenshotAction.FULL)); if (Platform.isWindows() || Platform.isLinux()) { tray.add(new ActionMenuItem(Language.getString("activeupload"), ScreenshotAction.ACTIVE)); } tray.addSeparator(); tray.add(new ActionMenuItem(Language.getString("clipboardupload"), ScreenshotAction.CLIPBOARD)); tray.add(new ActionMenuItem(Language.getString("fileupload"), ScreenshotAction.FILE)); tray.addSeparator(); final MenuItem settings = new MenuItem(Language.getString("options")); settings.addActionListener( new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (!openSettings()) { icon.displayMessage( Language.getString("error"), Language.getString("optionsOpenError"), TrayIcon.MessageType.ERROR); } } }); tray.add(settings); final MenuItem exit = new MenuItem(Language.getString("exit")); exit.addActionListener( new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { shutdown(); } }); tray.add(exit); icon = new TrayIcon( Toolkit.getDefaultToolkit().getImage(Resources.ICON), Application.NAME + " v" + Version.getVersionString()); icon.setPopupMenu(tray); icon.addActionListener( new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (lastUrl != null) { try { Util.openURL(new URL(lastUrl)); } catch (final Exception e1) { showException(e1, "Unable to open URL"); } } } }); try { SystemTray.getSystemTray().add(icon); } catch (final AWTException e1) { this.showException(e1); } }
/** * Initialize the program * * @param map Flag to reset configuration */ private void initialize(final Map<String, Object> map) { // Check for a configuration option if (map.containsKey("dir")) { final File file = new File(map.get("dir").toString()); if (!file.exists()) { file.mkdirs(); } Util.setWorkingDirectory(file); } // Verify the directory final File local = Util.getWorkingDirectory(); if (!local.exists()) { local.mkdirs(); } // Load the Release info final URL releaseUrl = Util.getResourceByName("/org/sleeksnap/release.json"); JSONObject releaseInfo = new JSONObject(); if (releaseUrl != null) { try { releaseInfo = new JSONObject(new JSONTokener(releaseUrl.openStream())); } catch (final IOException e) { e.printStackTrace(); } } // Set the UI skin try { UIManager.setLookAndFeel( releaseInfo.getString("uiClass", UIManager.getSystemLookAndFeelClassName())); } catch (final Exception e) { e.printStackTrace(); } // Then start try { LoggingManager.configure(); } catch (final IOException e) { logger.log( Level.WARNING, "Unable to configure logger, file logging and logging panel will not work.", e); JOptionPane.showMessageDialog( null, "Unable to configure logger, file logging and logging panel will not work.", "Error", JOptionPane.ERROR_MESSAGE); } logger.info("Loading plugins..."); try { loadUploaders(); loadFilters(); } catch (final Exception e) { logger.log(Level.SEVERE, "Failed to load plugins!", e); } // Load the settings logger.info("Loading settings..."); try { loadSettings(map.containsKey("resetconfig")); } catch (final Exception e) { logger.log(Level.SEVERE, "Failed to load settings!", e); } // Load the selected language try { Language.load( map.containsKey("language") ? map.get("language").toString() : configuration.getString("language", Constants.Configuration.DEFAULT_LANGUAGE)); } catch (final IOException e) { logger.log(Level.SEVERE, "Failed to load language file!", e); } // Check the update mode final UpdaterMode mode = configuration.getEnumValue("updateMode", UpdaterMode.class); if (mode != UpdaterMode.MANUAL) { final UpdaterReleaseType type = configuration.getEnumValue("updateReleaseType", UpdaterReleaseType.class); final Updater updater = new Updater(); if (updater.checkUpdate(type, mode == UpdaterMode.PROMPT)) { return; } } // Load the history logger.info("Loading history..."); final File historyFile = new File(local, "history.json"); history = new History(historyFile); if (historyFile.exists()) { logger.info("Using existing history file."); try { history.load(); } catch (final Exception e) { logger.log(Level.WARNING, "Failed to load history", e); } } else { logger.info("Using new history file."); } // Validate settings if (!configuration.contains("hotkeys") || !configuration.contains("uploaders")) { promptConfigurationReset(); } // Register the hotkeys logger.info("Registering keys..."); keyManager = new HotkeyManager(this); keyManager.initializeInput(); logger.info("Opening tray icon..."); initializeTray(); logger.info("Ready."); }
/** * Execute an upload * * @param object The object to upload */ @SuppressWarnings({"rawtypes", "unchecked"}) public void executeUpload(Upload object) { // Run the object through the filters if (filters.containsKey(object.getClass())) { for (final UploadFilter filter : filters.get(object.getClass())) { try { object = filter.filter(object); } catch (final FilterException e) { // FilterExceptions when thrown should interrupt the upload. showException(e, e.getErrorMessage()); return; } } } // Then upload it final Uploader uploader = uploaderAssociations.get(object.getClass()); if (uploader != null) { try { String url = uploader.upload(object); if (url != null) { if (configuration.getBoolean("shortenurls")) { final Uploader shortener = uploaderAssociations.get(URL.class); if (shortener != null) { url = shortener.upload(new URLUpload(url)); } } if (object instanceof ImageUpload) { if (configuration.getBoolean("savelocal") && !(uploader instanceof ImageLocalFileUploader)) { final FileOutputStream output = new FileOutputStream(getLocalFile(DateUtil.getCurrentDate() + ".png")); try { ImageIO.write(((ImageUpload) object).getImage(), "png", output); } finally { output.close(); } } ((ImageUpload) object).getImage().flush(); ((ImageUpload) object).setImage(null); } url = url.trim(); retries = 0; ClipboardUtil.setClipboard(url); lastUrl = url; history.addEntry(new HistoryEntry(url, uploader.getName())); icon.displayMessage( Language.getString("uploadComplete"), Language.getString("uploadedTo", url), TrayIcon.MessageType.INFO); logger.info("Upload completed, url: " + url); } else { icon.displayMessage( Language.getString("uploadFailed"), Language.getString("uploadFailedError"), TrayIcon.MessageType.ERROR); logger.severe("Upload failed to execute due to an unknown error"); } } catch (final UploaderConfigurationException e) { icon.displayMessage( Language.getString("uploaderConfigError"), Language.getString("uploaderConfigErrorMessage"), TrayIcon.MessageType.ERROR); logger.log(Level.SEVERE, "Upload failed to execute", e); } catch (final Exception e) { // Retry until retries > max final StringBuilder msg = new StringBuilder("The upload failed to execute: "); msg.append(e.getMessage()); final int max = configuration.getInteger("max_retries", Constants.Configuration.DEFAULT_MAX_RETRIES); if (retries++ < max) { logger.info("Retrying upload (" + retries + " of " + max + " retries)..."); msg.append("\nRetrying..."); upload(object); } else { msg.append("\nReached retry limit, upload aborted."); logger.log(Level.SEVERE, "Upload failed to execute, retries: " + retries, e); retries = 0; } icon.displayMessage( Language.getString("uploadFailed"), msg.toString(), TrayIcon.MessageType.ERROR); } } }
/** * Show a TrayIcon message for an exception * * @param e The exception */ public void showException(final Exception e, final String errorMessage) { icon.displayMessage( Language.getString("error"), Language.getString("exceptionCauseWithMessage", errorMessage, e.getMessage()), MessageType.ERROR); }