*
* @return list of file moves performed
*/
public static List<FileMove> runRules(User user) {
List<FileMove> fileMoves = Lists.newArrayList();
ApiClient client = ApiClientFactory.create(user);
try {
Set<String> files = client.listDir(user.sortingFolder);
if (files.isEmpty()) {
Logger.info("Ran rules for %s, no files to process.", user);
return fileMoves;
}
user.updateLastSyncDate();
List<Rule> rules = Rule.findByUserId(user.getKey());
Logger.info("Running rules for %s with files %s", user, files);
for (String file : files) {
String base = basename(file);
for (Rule r : rules) {
if (r.matches(base)) {
Logger.info("Moving file '%s' to '%s'. Rule id: %s",
file, r.dest, r.id);
boolean hasCollision = false;
String resolvedName = null;
for (int tries = 0; tries < MAX_TRIES; tries++) {
try {
String suffix = null;
if (hasCollision) {
suffix = " conflict"
+ (tries > 1 ? " " + tries : "");
}
resolvedName = removeInvalidChars(insertIntoName(base, suffix));
String dest = r.dest +
(r.dest.endsWith("/") ? "" : "/") +
resolvedName;
client.move(file, dest);
break;
} catch (FileMoveCollisionException e) {
hasCollision = true;
resolvedName = null;
}