private int getFiles(DirectoryHandle preDir) { int files = 0; try { files = preDir.getFilesUnchecked().size(); for (DirectoryHandle dir : preDir.getDirectoriesUnchecked()) { files += getFiles(dir); } } catch (FileNotFoundException e) { logger.warn("FileNotFoundException ", e); } return files; }
private static void recursiveRemoveOwnership(DirectoryHandle dir, long lastModified) { try { dir.setUsername("drftpd"); dir.setGroup("drftpd"); dir.setLastModified(lastModified); for (InodeHandle file : dir.getInodeHandlesUnchecked()) { file.setUsername("drftpd"); file.setGroup("drftpd"); file.setLastModified(lastModified); if (file.isDirectory()) recursiveRemoveOwnership((DirectoryHandle) file, lastModified); } } catch (FileNotFoundException e) { logger.warn("FileNotFoundException on recursiveRemoveOwnership()", e); } }
/** * Method called whenever an inode is created. Spawns a {@link TvMazeThread} if all criteria are * met to not stall running thread while getting the info from TvMaze. Depends on {@link * VirtualFileSystemInodeCreatedEvent} <code>type</code> property. * * @param event */ @EventSubscriber public void inodeCreated(VirtualFileSystemInodeCreatedEvent event) { if (!event.getInode().isFile()) return; String fileName = event.getInode().getName().toLowerCase(); if (!fileName.endsWith(".nfo") || fileName.endsWith("imdb.nfo")) return; DirectoryHandle parentDir = event.getInode().getParent(); SectionInterface sec = GlobalContext.getGlobalContext().getSectionManager().lookup(parentDir); if (!IMDBUtils.containSection(sec, getRaceSections())) return; if (parentDir.getName().matches(getExclude())) return; logger.debug("Dir added to process queue for IMDB data: " + parentDir.getPath()); // Add dir to process queue addDirToProcessQueue(parentDir); }
private void preAwardCredits(DirectoryHandle preDir, HashMap<User, Long> awards) { try { for (InodeHandle file : preDir.getInodeHandlesUnchecked()) { if (file.isFile()) { User owner; try { owner = GlobalContext.getGlobalContext() .getUserManager() .getUserByNameUnchecked(file.getUsername()); } catch (NoSuchUserException e) { logger.warn("PRE: Cannot award credits to non-existing user", e); continue; } catch (UserFileException e) { logger.warn("", e); continue; } catch (FileNotFoundException e) { logger.warn("", e); continue; } Long total = awards.get(owner); if (total == null) { total = 0L; } total = (total + (long) (file.getSize() * owner.getKeyedMap().getObjectFloat(UserManagement.RATIO))); awards.put(owner, total); } if (file.isDirectory()) { preAwardCredits((DirectoryHandle) file, awards); } } } catch (FileNotFoundException e) { logger.warn("FileNotFoundException on preAwardCredits()", e); } }
/** * USAGE: site nuke <directory> <multiplier> <message> Nuke a directory * * <p>ex. site nuke shit 2 CRAP * * <p>This will nuke the directory 'shit' and remove x2 credits with the comment 'CRAP'. * * <p>NOTE: You can enclose the directory in braces if you have spaces in the name ex. site NUKE * {My directory name} 1 because_i_dont_like_it * * <p>Q) What does the multiplier in 'site nuke' do? A) Multiplier is a penalty measure. If it is * 0, the user doesn't lose any credits for the stuff being nuked. If it is 1, user only loses the * amount of credits he gained by uploading the files (which is calculated by multiplying total * size of file by his/her ratio). If multiplier is more than 1, the user loses the credits he/she * gained by uploading, PLUS some extra credits. The formula is this: size * ratio + size * * (multiplier - 1). This way, multiplier of 2 causes user to lose size * ratio + size * 1, so the * additional penalty in this case is the size of nuked files. If the multiplier is 3, user loses * size * ratio + size * 2, etc. * * @throws ImproperUsageException */ public CommandResponse doSITE_NUKE(CommandRequest request) throws ImproperUsageException { if (!request.hasArgument()) { throw new ImproperUsageException(); } StringTokenizer st = new StringTokenizer(request.getArgument()); if (!st.hasMoreTokens()) { throw new ImproperUsageException(); } Session session = request.getSession(); int multiplier; DirectoryHandle currentDir = request.getCurrentDirectory(); String nukeDirName = st.nextToken(); User requestUser = session.getUserNull(request.getUser()); String nukeDirPath = VirtualFileSystem.fixPath(nukeDirName); if (!(nukeDirPath.startsWith(VirtualFileSystem.separator))) { // Not a full path, let's make it one if (request.getCurrentDirectory().isRoot()) { boolean searchIndex = request.getProperties().getProperty("search", "true").equalsIgnoreCase("true"); if (searchIndex) { // Get dirs from index system ArrayList<DirectoryHandle> dirsToNuke; try { dirsToNuke = NukeUtils.findNukeDirs(currentDir, requestUser, nukeDirPath); } catch (FileNotFoundException e) { logger.warn(e); return new CommandResponse(550, e.getMessage()); } ReplacerEnvironment env = new ReplacerEnvironment(); if (dirsToNuke.isEmpty()) { env.add("searchstr", nukeDirPath); return new CommandResponse( 550, session.jprintf(_bundle, _keyPrefix + "nuke.search.empty", env, requestUser)); } else if (dirsToNuke.size() == 1) { nukeDirPath = dirsToNuke.get(0).getPath(); } else { CommandResponse response = new CommandResponse(200); for (DirectoryHandle nukeDir : dirsToNuke) { try { env.add("name", nukeDir.getName()); env.add("path", nukeDir.getPath()); env.add("owner", nukeDir.getUsername()); env.add("group", nukeDir.getGroup()); env.add("size", Bytes.formatBytes(nukeDir.getSize())); response.addComment( session.jprintf(_bundle, _keyPrefix + "nuke.search.item", env, requestUser)); } catch (FileNotFoundException e) { logger.warn( "Dir deleted after index search?, skip and continue: " + nukeDir.getPath()); } } response.addComment( session.jprintf(_bundle, _keyPrefix + "nuke.search.end", env, requestUser)); // Return matching dirs and let user decide what to nuke return response; } } else { nukeDirPath = VirtualFileSystem.separator + nukeDirPath; } } else { nukeDirPath = request.getCurrentDirectory().getPath() + VirtualFileSystem.separator + nukeDirPath; } } DirectoryHandle nukeDir; try { nukeDir = request.getCurrentDirectory().getDirectory(nukeDirPath, requestUser); } catch (FileNotFoundException e) { return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN"); } catch (ObjectNotValidException e) { return new CommandResponse(550, nukeDirPath + " is not a directory"); } nukeDirName = nukeDir.getName(); if (!st.hasMoreTokens()) { throw new ImproperUsageException(); } try { multiplier = Integer.parseInt(st.nextToken()); } catch (NumberFormatException ex) { logger.warn(ex, ex); return new CommandResponse(501, "Invalid multiplier: " + ex.getMessage()); } String reason = ""; if (st.hasMoreTokens()) { reason = st.nextToken("").trim(); } NukeData nd; try { nd = NukeUtils.nuke(nukeDir, multiplier, reason, requestUser); } catch (NukeException e) { return new CommandResponse(500, "Nuke failed: " + e.getMessage()); } CommandResponse response = new CommandResponse(200, "Nuke succeeded"); GlobalContext.getEventService().publishAsync(new NukeEvent(requestUser, "NUKE", nd)); ReplacerEnvironment env = new ReplacerEnvironment(); String section = GlobalContext.getGlobalContext().getSectionManager().lookup(nukeDir).getName(); env.add("section", section); env.add("dir", nukeDirName); env.add("path", nukeDirPath); env.add("relpath", nukeDirPath.replaceAll("/.*?" + section + "/", "")); env.add("multiplier", multiplier); env.add("nukedamount", Bytes.formatBytes(nd.getAmount())); env.add("reason", reason); env.add("size", Bytes.formatBytes(nd.getSize())); if (session instanceof BaseFtpConnection) { response.addComment(session.jprintf(_bundle, _keyPrefix + "nuke", env, requestUser)); for (NukedUser nukeeObj : NukeBeans.getNukeeList(nd)) { ReplacerEnvironment nukeeenv = new ReplacerEnvironment(); User nukee; try { nukee = GlobalContext.getGlobalContext() .getUserManager() .getUserByName(nukeeObj.getUsername()); } catch (NoSuchUserException e1) { // Unable to get user, does not exist.. skip announce for this user continue; } catch (UserFileException e1) { // Error in user file.. skip announce for this user continue; } long debt = NukeUtils.calculateNukedAmount( nukeeObj.getAmount(), nukee.getKeyedMap().getObjectFloat(UserManagement.RATIO), multiplier); nukeeenv.add("nukedamount", Bytes.formatBytes(debt)); response.addComment(session.jprintf(_bundle, _keyPrefix + "nuke.nukees", nukeeenv, nukee)); } } return response; }
/** * USAGE: site unnuke <directory> <message> Unnuke a directory. * * <p>ex. site unnuke shit NOT CRAP * * <p>This will unnuke the directory 'shit' with the comment 'NOT CRAP'. * * <p>NOTE: You can enclose the directory in braces if you have spaces in the name ex. site unnuke * {My directory name} justcause * * <p>You need to configure glftpd to keep nuked files if you want to unnuke. See the section * about glftpd.conf. * * @throws ImproperUsageException */ public CommandResponse doSITE_UNNUKE(CommandRequest request) throws ImproperUsageException { if (!request.hasArgument()) { throw new ImproperUsageException(); } StringTokenizer st = new StringTokenizer(request.getArgument()); Session session = request.getSession(); DirectoryHandle currentDir = request.getCurrentDirectory(); User user = session.getUserNull(request.getUser()); String toName = st.nextToken(); String toDir; String nukeName; if (!toName.startsWith(VirtualFileSystem.separator)) { // Not a full path, let's make it one and append [NUKED]- if needed. if (toName.startsWith("[NUKED]-")) { nukeName = toName; toName = toName.substring(8); } else { nukeName = "[NUKED]-" + toName; } if (request.getCurrentDirectory().isRoot()) { boolean searchIndex = request.getProperties().getProperty("search", "true").equalsIgnoreCase("true"); if (searchIndex) { // Get dirs from index system ArrayList<DirectoryHandle> dirsToUnNuke; try { dirsToUnNuke = NukeUtils.findNukeDirs(currentDir, user, nukeName); } catch (FileNotFoundException e) { logger.warn(e); return new CommandResponse(550, e.getMessage()); } ReplacerEnvironment env = new ReplacerEnvironment(); if (dirsToUnNuke.isEmpty()) { env.add("searchstr", nukeName); return new CommandResponse( 550, session.jprintf(_bundle, _keyPrefix + "unnuke.search.empty", env, user)); } else if (dirsToUnNuke.size() == 1) { toDir = dirsToUnNuke.get(0).getParent().getPath() + VirtualFileSystem.separator; } else { CommandResponse response = new CommandResponse(200); for (DirectoryHandle nukeDir : dirsToUnNuke) { try { env.add("name", nukeDir.getName()); env.add("path", nukeDir.getPath()); env.add("owner", nukeDir.getUsername()); env.add("group", nukeDir.getGroup()); env.add("size", Bytes.formatBytes(nukeDir.getSize())); response.addComment( session.jprintf(_bundle, _keyPrefix + "unnuke.search.item", env, user)); } catch (FileNotFoundException e) { logger.warn( "Dir deleted after index search?, skip and continue: " + nukeDir.getPath()); } } response.addComment( session.jprintf(_bundle, _keyPrefix + "unnuke.search.end", env, user)); // Return matching dirs and let user decide what to unnuke return response; } } else { toDir = VirtualFileSystem.separator; } } else { toDir = currentDir.getPath() + VirtualFileSystem.separator; } } else { // Full path to Nuked dir provided, append [NUKED]- if needed. toDir = VirtualFileSystem.fixPath(toName); toName = toDir.substring(toDir.lastIndexOf(VirtualFileSystem.separator) + 1); toDir = toDir.substring(0, toDir.lastIndexOf(VirtualFileSystem.separator) + 1); if (toName.startsWith("[NUKED]-")) { nukeName = toName; toName = toName.substring(8); } else { nukeName = "[NUKED]-" + toName; } } String reason; if (st.hasMoreTokens()) { reason = st.nextToken("").trim(); } else { reason = ""; } DirectoryHandle nukeDir; try { nukeDir = currentDir.getDirectory(toDir + nukeName, user); } catch (FileNotFoundException e) { // Maybe dir was deleted/wiped, lets remove it from nukelog. try { NukeBeans.getNukeBeans().remove(toDir + toName); } catch (ObjectNotFoundException ex) { return new CommandResponse( 500, toDir + nukeName + " doesnt exist and no nukelog for this path was found."); } return new CommandResponse( 200, toDir + nukeName + " doesnt exist, removed nuke from nukelog."); } catch (ObjectNotValidException e) { return new CommandResponse(550, toDir + nukeName + " is not a directory"); } NukeData nd; try { nd = NukeUtils.unnuke(nukeDir, reason); } catch (NukeException e) { return new CommandResponse(500, "Unnuke failed: " + e.getMessage()); } CommandResponse response = new CommandResponse(200, "Unnuke succeeded"); NukeEvent nukeEvent = new NukeEvent(session.getUserNull(request.getUser()), "UNNUKE", nd); GlobalContext.getEventService().publishAsync(nukeEvent); ReplacerEnvironment env = new ReplacerEnvironment(); String section = GlobalContext.getGlobalContext().getSectionManager().lookup(nukeDir).getName(); env.add("section", section); env.add("dir", nukeDir.getName()); env.add("path", nukeDir.getPath()); env.add("relpath", nukeDir.getPath().replaceAll("/" + section + "/", "")); env.add("multiplier", nd.getMultiplier()); env.add("nukedamount", Bytes.formatBytes(nd.getAmount())); env.add("reason", reason); env.add("size", Bytes.formatBytes(nd.getSize())); if (session instanceof BaseFtpConnection) { response.addComment(session.jprintf(_bundle, _keyPrefix + "unnuke", env, user)); for (NukedUser nukeeObj : NukeBeans.getNukeeList(nd)) { ReplacerEnvironment nukeeenv = new ReplacerEnvironment(); User nukee; try { nukee = GlobalContext.getGlobalContext() .getUserManager() .getUserByName(nukeeObj.getUsername()); } catch (NoSuchUserException e1) { // Unable to get user, does not exist.. skip announce for this user continue; } catch (UserFileException e1) { // Error in user file.. skip announce for this user continue; } long debt = NukeUtils.calculateNukedAmount( nukeeObj.getAmount(), nukee.getKeyedMap().getObjectFloat(UserManagement.RATIO), nd.getMultiplier()); nukeeenv.add("nukedamount", Bytes.formatBytes(debt)); response.addComment( session.jprintf(_bundle, _keyPrefix + "unnuke.nukees", nukeeenv, nukee)); } } return response; }
public CommandResponse doSITE_PRE(CommandRequest request) throws ImproperUsageException { if (!request.hasArgument()) { throw new ImproperUsageException(); } String[] args = request.getArgument().split(" "); if (args.length != 2) { return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR"); } SectionInterface section = GlobalContext.getGlobalContext().getSectionManager().getSection(args[1]); if (section.getName().equals("")) { return new CommandResponse( 500, "Invalid section, see SITE SECTIONS for a list of available sections"); } User user = request.getSession().getUserNull(request.getUser()); DirectoryHandle preDir; String path = VirtualFileSystem.fixPath(args[0]); if (!(path.startsWith(VirtualFileSystem.separator))) { // Not a full path, let's make it one if (request.getCurrentDirectory().isRoot()) { path = VirtualFileSystem.separator + path; } else { path = request.getCurrentDirectory().getPath() + VirtualFileSystem.separator + path; } } try { preDir = request.getCurrentDirectory().getDirectory(path, user); } catch (FileNotFoundException e) { return StandardCommandManager.genericResponse("RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN"); } catch (ObjectNotValidException e) { return StandardCommandManager.genericResponse( "RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS"); } ConfigInterface config = GlobalContext.getConfig(); if (!config.checkPathPermission("pre", user, preDir)) { return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED"); } DirectoryHandle toInode = new DirectoryHandle( section.getCurrentDirectory().getPath() + VirtualFileSystem.separator + preDir.getName()); if (toInode.exists()) { return new CommandResponse(500, "Directory already exist in target section"); } CommandResponse response = new CommandResponse(250, request.getCommand().toUpperCase() + " command successful."); // AWARD CREDITS HashMap<User, Long> awards = new HashMap<User, Long>(); preAwardCredits(preDir, awards); for (Map.Entry<User, Long> entry : awards.entrySet()) { User owner = entry.getKey(); if (StatsManager.getStatsManager().getCreditCheckRatio(preDir, owner) == 0) { Long award = entry.getValue(); owner.updateCredits(award); response.addComment("Awarded " + Bytes.formatBytes(award) + " to " + owner.getName()); } } recursiveRemoveOwnership(preDir, System.currentTimeMillis()); int files = getFiles(preDir); long bytes = 0; try { bytes = preDir.getSize(); } catch (FileNotFoundException e) { logger.warn("FileNotFoundException ", e); } try { preDir.renameToUnchecked(toInode); } catch (FileNotFoundException e) { logger.warn("FileNotFoundException on renameTo()", e); return new CommandResponse(500, "FileNotFound - " + e.getMessage()); } catch (IOException e) { logger.warn("IOException on renameTo()", e); return new CommandResponse(500, "IOException - " + e.getMessage()); } preDir = toInode; GlobalContext.getEventService() .publishAsync( new PreEvent(preDir, section, Integer.toString(files), Bytes.formatBytes(bytes))); response.setObject(PREDIR, preDir); return response; }