Note: In order to use this module, run nimble install asyncftpclient.

This module implements an asynchronous FTP client. It allows you to connect to an FTP server and perform operations on it such as for example:

  • The upload of new files.
  • The removal of existing files.
  • Download of files.
  • Changing of files’ permissions.
  • Navigation through the FTP server’s directories.

Connecting to an FTP server

In order to begin any sort of transfer of files you must first connect to an FTP server. You can do so with the connect procedure.

  1. import std/asyncdispatch
  2. import pkg/asyncftpclient
  3. proc main() {.async.} =
  4. var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
  5. await ftp.connect()
  6. echo("Connected")
  7. waitFor(main())

A new main async procedure must be declared to allow the use of the await keyword. The connection will complete asynchronously and the client will be connected after the await ftp.connect() call.

Uploading a new file

After a connection is made you can use the store procedure to upload a new file to the FTP server. Make sure to check you are in the correct working directory before you do so with the pwd procedure, you can also instead specify an absolute path.

  1. import std/asyncdispatch
  2. import pkg/asyncftpclient
  3. proc main() {.async.} =
  4. var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
  5. await ftp.connect()
  6. let currentDir = await ftp.pwd()
  7. assert currentDir == "/home/user/"
  8. await ftp.store("file.txt", "file.txt")
  9. echo("File finished uploading")
  10. waitFor(main())

Checking the progress of a file transfer

The progress of either a file upload or a file download can be checked by specifying a onProgressChanged procedure to the store or retrFile procedures.

Procs that take an onProgressChanged callback will call this every progressInterval milliseconds.

  1. import std/asyncdispatch
  2. import pkg/asyncftpclient
  3. proc onProgressChanged(total, progress: BiggestInt,
  4. speed: float) {.async.} =
  5. echo("Uploaded ", progress, " of ", total, " bytes")
  6. echo("Current speed: ", speed, " kb/s")
  7. proc main() {.async.} =
  8. var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test", progressInterval = 500)
  9. await ftp.connect()
  10. await ftp.store("file.txt", "/home/user/file.txt", onProgressChanged)
  11. echo("File finished uploading")
  12. waitFor(main())

Types

  1. AsyncFtpClient = ref object
  2. csock*: AsyncSocket
  3. dsock*: AsyncSocket
  4. user*, pass*: string
  5. address*: string
  6. port*: Port
  7. jobInProgress*: bool
  8. job*: FtpJob
  9. dsockConnected*: bool
  10. when defined(ssl):
  1. FtpEvent = object
  2. filename*: string
  3. case typ*: FtpEventType
  4. of EvLines:
  5. lines*: string ## Lines that have been transferred.
  6. of EvRetr, EvStore: ## Retr/Store operation finished.
  7. nil
  8. of EvTransferProgress:
  9. bytesTotal*: BiggestInt ## Bytes total.
  10. bytesFinished*: BiggestInt ## Bytes transferred.
  11. speed*: BiggestInt ## Speed in bytes/s
  12. currentJob*: FtpJobType ## The current job being performed.

Event

  1. FtpEventType = enum
  2. EvTransferProgress, EvLines, EvRetr, EvStore
  1. FtpJobType = enum
  2. JRetrText, JRetr, JStore
  1. ProgressChangedProc = proc (total, progress: BiggestInt; speed: float): Future[
  2. void] {.closure, ...gcsafe.}
  1. ReplyError = object of IOError

Procs

  1. proc cd(ftp: AsyncFtpClient; dir: string): owned(Future[void]) {.
  2. ...stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}

Changes the current directory on the remote FTP server to dir.

  1. proc cdup(ftp: AsyncFtpClient): owned(Future[void]) {....stackTrace: false,
  2. raises: [Exception], tags: [RootEffect], forbids: [].}

Changes the current directory to the parent of the current directory.

  1. proc chmod(ftp: AsyncFtpClient; path: string; permissions: set[FilePermission]): owned(
  2. Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
  3. forbids: [].}

Changes permission of path to permissions.

  1. proc connect(ftp: AsyncFtpClient): owned(Future[void]) {....stackTrace: false,
  2. raises: [Exception], tags: [RootEffect], forbids: [].}

Connect to the FTP server specified by ftp.

  1. proc createDir(ftp: AsyncFtpClient; dir: string; recursive = false): owned(
  2. Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
  3. forbids: [].}

Creates a directory dir. If recursive is true, the topmost subdirectory of dir will be created first, following the secondmost… etc. this allows you to give a full path as the dir without worrying about subdirectories not existing.

  1. proc defaultOnProgressChanged(total, progress: BiggestInt; speed: float): Future[
  2. void] {.nimcall, ...gcsafe, raises: [Exception], tags: [RootEffect],
  3. forbids: [].}

Default FTP onProgressChanged handler. Does nothing.

  1. proc fileExists(ftp: AsyncFtpClient; file: string): Future[bool] {.
  2. ...stackTrace: false, raises: [Exception, ValueError], tags: [RootEffect],
  3. forbids: [].}

Determines whether file exists.

  1. proc list(ftp: AsyncFtpClient; dir = ""): Future[string] {....stackTrace: false,
  2. raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}

Lists all files in dir. If dir is “”, uses the current working directory.

  1. proc listDirs(ftp: AsyncFtpClient; dir = ""): Future[seq[string]] {.
  2. ...stackTrace: false, raises: [Exception, ValueError], tags: [RootEffect],
  3. forbids: [].}

Returns a list of filenames in the given directory. If dir is “”, the current directory is used. If async is true, this function will return immediately and it will be your job to use asyncdispatch’s poll to progress this operation.

  1. proc newAsyncFtpClient(address: string; port = Port(21); user, pass = "";
  2. progressInterval: int = 1000; useTls = false;
  3. sslContext: SslContext = nil): AsyncFtpClient {.
  4. ...raises: [OSError], tags: [], forbids: [].}

Creates a new AsyncFtpClient object.

  1. proc pwd(ftp: AsyncFtpClient): Future[string] {....stackTrace: false,
  2. raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}

Returns the current working directory.

  1. proc removeDir(ftp: AsyncFtpClient; dir: string): owned(Future[void]) {.
  2. ...stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}

Delete a directory dir on the remote FTP server

  1. proc removeFile(ftp: AsyncFtpClient; filename: string): owned(Future[void]) {.
  2. ...stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}

Delete a file filename on the remote FTP server

  1. proc rename(ftp: AsyncFtpClient; nameFrom: string; nameTo: string): owned(
  2. Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
  3. forbids: [].}

Rename a file or directory on the remote FTP Server from current name name_from to new name name_to

  1. proc retrFile(ftp: AsyncFtpClient; file, dest: string;
  2. onProgressChanged: ProgressChangedProc = defaultOnProgressChanged): owned(
  3. Future[void]) {....stackTrace: false, raises: [Exception],
  4. tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}

Downloads file and saves it to dest. The EvRetr event is passed to the specified handleEvent function when the download is finished. The event’s filename field will be equal to file.

  1. proc retrText(ftp: AsyncFtpClient; file: string): Future[string] {.
  2. ...stackTrace: false, raises: [Exception, ValueError], tags: [RootEffect],
  3. forbids: [].}

Retrieves file. File must be ASCII text.

  1. proc send(ftp: AsyncFtpClient; m: string): Future[string] {....stackTrace: false,
  2. raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}

Send a message to the server, and wait for a primary reply. \c\L is added for you.

You need to make sure that the message m doesn’t contain any newline characters. Failing to do so will raise AssertionDefect.

Note: The server may return multiple lines of coded replies.

  1. proc store(ftp: AsyncFtpClient; file, dest: string;
  2. onProgressChanged: ProgressChangedProc = defaultOnProgressChanged): owned(
  3. Future[void]) {....stackTrace: false, raises: [Exception],
  4. tags: [RootEffect, ReadIOEffect, TimeEffect], forbids: [].}

Uploads file to dest on the remote FTP server. Usage of this function asynchronously is recommended to view the progress of the download. The EvStore event is passed to the specified handleEvent function when the upload is finished, and the filename field will be equal to file.