mojo_client.dart 3.84 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

9 10 11
import 'package:flutter/src/services/shell.dart';
import 'package:mojo_services/mojo/network_service.mojom.dart' as mojo;
import 'package:mojo_services/mojo/url_loader.mojom.dart' as mojo;
12 13 14
import 'package:mojo/core.dart' as mojo;
import 'package:mojo/mojo/url_request.mojom.dart' as mojo;
import 'package:mojo/mojo/url_response.mojom.dart' as mojo;
15
import 'package:mojo/mojo/http_header.mojom.dart' as mojo;
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

import 'response.dart';

/// A `mojo`-based HTTP client
class MojoClient {

  Future<Response> head(url, {Map<String, String> headers}) =>
    _send("HEAD", url, headers);

  Future<Response> get(url, {Map<String, String> headers}) =>
    _send("GET", url, headers);

  Future<Response> post(url, {Map<String, String> headers, body,
      Encoding encoding}) =>
    _send("POST", url, headers, body, encoding);

  Future<Response> put(url, {Map<String, String> headers, body,
      Encoding encoding}) =>
    _send("PUT", url, headers, body, encoding);

  Future<Response> patch(url, {Map<String, String> headers, body,
      Encoding encoding}) =>
    _send("PATCH", url, headers, body, encoding);

  Future<Response> delete(url, {Map<String, String> headers}) =>
    _send("DELETE", url, headers);

  Future<String> read(url, {Map<String, String> headers}) {
    return get(url, headers: headers).then((response) {
      _checkResponseSuccess(url, response);
      return response.body;
    });
  }

  Future<Uint8List> readBytes(url, {Map<String, String> headers}) {
51
    return get(url, headers: headers).then((Response response) {
52 53 54 55 56 57 58 59
      _checkResponseSuccess(url, response);
      return response.bodyBytes;
    });
  }

  Future<Response> _send(String method, url,
      Map<String, String> headers, [body, Encoding encoding]) async {
    mojo.UrlLoaderProxy loader = new mojo.UrlLoaderProxy.unbound();
60
    List<mojo.HttpHeader> mojoHeaders = <mojo.HttpHeader>[];
61
    headers?.forEach((String name, String value) {
62 63 64 65 66
      mojo.HttpHeader header = new mojo.HttpHeader()
        ..name = name
        ..value = value;
      mojoHeaders.add(header);
    });
67 68
    mojo.UrlRequest request = new mojo.UrlRequest()
      ..url = url.toString()
69
      ..headers = mojoHeaders
70 71 72 73
      ..method = method;
    if (body != null) {
      mojo.MojoDataPipe pipe = new mojo.MojoDataPipe();
      request.body = <mojo.MojoDataPipeConsumer>[pipe.consumer];
74 75
      Uint8List encodedBody = UTF8.encode(body);
      ByteData data = new ByteData.view(encodedBody.buffer);
76 77
      mojo.DataPipeFiller.fillHandle(pipe.producer, data);
    }
78
    try {
79
      networkService.ptr.createUrlLoader(loader);
80 81
      mojo.UrlResponse response = (await loader.ptr.start(request)).response;
      ByteData data = await mojo.DataPipeDrainer.drainHandle(response.body);
82
      Uint8List bodyBytes = new Uint8List.view(data.buffer);
83 84
      String bodyString = new String.fromCharCodes(bodyBytes);
      return new Response(body: bodyString, bodyBytes: bodyBytes, statusCode: response.statusCode);
85 86
    } catch (e) {
      print("NetworkService unavailable $e");
87
      return new Response(statusCode: 500);
88 89 90 91 92 93
    } finally {
      loader.close();
    }
  }

  void _checkResponseSuccess(url, Response response) {
94 95 96
    if (response.statusCode < 400)
      return;
    throw new Exception("Request to $url failed with status ${response.statusCode}.");
97 98 99
  }

  void close() {}
100 101 102 103 104 105 106 107

  static mojo.NetworkServiceProxy _initNetworkService() {
    mojo.NetworkServiceProxy proxy = new mojo.NetworkServiceProxy.unbound();
    shell.connectToService("mojo:authenticated_network_service", proxy);
    return proxy;
  }

  static final mojo.NetworkServiceProxy networkService = _initNetworkService();
108
}