serveDirectory method

Future<bool> serveDirectory(
  1. Directory directory,
  2. String relative,
  3. FileStat stat,
  4. RequestContext req,
  5. ResponseContext res,
)

Serves the index file of a directory, if it exists.

Implementation

Future<bool> serveDirectory(Directory directory, String relative,
    FileStat stat, RequestContext req, ResponseContext res) async {
  for (var indexFileName in indexFileNames) {
    final index =
        fileSystem.file(directory.absolute.uri.resolve(indexFileName));
    if (await index.exists()) {
      return await serveFile(index, stat, req, res);
    }
  }

  if (allowDirectoryListing == true) {
    res.contentType = MediaType('text', 'html');
    res
      ..write('<!DOCTYPE html>')
      ..write('<html>')
      ..write(
          '<head><meta name="viewport" content="width=device-width,initial-scale=1">')
      ..write('<style>ul { list-style-type: none; }</style>')
      ..write('</head><body>');

    res.write('<li><a href="..">..</a></li>');

    var entities = await directory
        .list(followLinks: false)
        .toList()
        .then((l) => List.from(l));
    entities.sort((a, b) {
      if (a is Directory) {
        if (b is Directory) {
          return a.path.compareTo(b.path);
        }
        return -1;
      } else if (a is File) {
        if (b is Directory) {
          return 1;
        } else if (b is File) {
          return a.path.compareTo(b.path);
        }
        return -1;
      } else if (a is Link) {
        if (b is Directory) {
          return 1;
        } else if (b is Link) {
          return a.path.compareTo(b.path);
        }
        return -1;
      }

      return 1;
    });

    for (var entity in entities) {
      String stub;
      String type;

      if (entity is File) {
        type = '[File]';
        stub = p.basename(entity.path);
      } else if (entity is Directory) {
        type = '[Directory]';
        stub = p.basename(entity.path);
      } else if (entity is Link) {
        type = '[Link]';
        stub = p.basename(entity.path);
      } else {
        _log.severe('Unknown file entity. Not a file, directory or link.');
        type = '[]';
        stub = '';
      }
      var href = stub;

      if (relative.isNotEmpty) {
        href = '/$relative/$stub';
      }

      if (entity is Directory) {
        if (href == '') {
          href = '/';
        } else {
          href += '/';
        }
      }
      href = Uri.encodeFull(href);

      res.write('<li><a href="$href">$type $stub</a></li>');
    }

    res.write('</body></html>');
    return false;
  }

  return true;
}