@@ -0,0 +1,2488 @@
+package peergos.server;%0A%0Aimport peergos.shared.*;%0Aimport peergos.shared.crypto.random.*;%0Aimport peergos.shared.user.*;%0Aimport peergos.shared.user.fs.*;%0A%0Aimport java.io.*;%0Aimport java.net.*;%0Aimport java.nio.file.*;%0Aimport java.util.*;%0A%0Apublic class Downloader %7B%0A%0A    public static void main(String%5B%5D args) throws Exception %7B%0A        Crypto crypto = Crypto.initJava();%0A        NetworkAccess network = NetworkAccess.buildJava(new URL(%22https://demo.peergos.net%22)).get();%0A        String username = args%5B0%5D;%0A        String password = args%5B1%5D;%0A        String fromPath = args%5B2%5D;%0A        String toPath = args%5B3%5D;%0A        UserContext context = UserContext.signIn(username, password, network, crypto).get();%0A        downloadTo(context, fromPath, Paths.get(toPath));%0A    %7D%0A%0A    public static void downloadTo(UserContext source, String origin, Path targetDir) throws Exception %7B%0A        if (! targetDir.toFile().exists() && ! targetDir.toFile().mkdirs())%0A            throw new IllegalStateException(%22Couldn't create %22 + targetDir);%0A        Optional%3CFileTreeNode%3E file = source.getByPath(origin).get();%0A        file.ifPresent(f -%3E downloadTo(f, targetDir, source.network, source.crypto.random));%0A    %7D%0A%0A    public static void downloadTo(FileTreeNode source, Path target, NetworkAccess network, SafeRandom random) %7B%0A        try %7B%0A            Path us = target.resolve(source.getName());%0A            if (source.isDirectory()) %7B%0A                Set%3CFileTreeNode%3E children = source.getChildren(network).get();%0A                if (!us.toFile().mkdir())%0A                    throw new IllegalStateException(%22Couldn't create directory: %22 + us);%0A                children.forEach(child -%3E downloadTo(child, us, network, random));%0A            %7D else %7B%0A                try (FileOutputStream fout = new FileOutputStream(us.toFile());) %7B%0A                    AsyncReader reader = source.getInputStream(network, random, count -%3E %7B%7D).get();%0A                    long size = source.getSize();%0A                    long offset = 0;%0A                    byte%5B%5D buf = new byte%5B5 * 1024 * 1024%5D;%0A                    while (offset %3C size) %7B%0A                        int count = Math.min(buf.length, (int) (size - offset));%0A                        reader.readIntoArray(buf, 0, count).get();%0A                        fout.write(buf, 0, count);%0A                        offset += count;%0A                    %7D%0A                %7D%0A            %7D%0A        %7D catch (Exception e) %7B%0A            throw new RuntimeException(e);%0A        %7D%0A    %7D%0A%7D%0A

Create downloader util to optimally download entire subtrees