|
| 1 | +part of github.common; |
| 2 | + |
| 3 | +class EventPoller { |
| 4 | + final GitHub github; |
| 5 | + final String path; |
| 6 | + |
| 7 | + Timer _timer; |
| 8 | + StreamController _controller; |
| 9 | + |
| 10 | + String _lastFetch; |
| 11 | + |
| 12 | + EventPoller(this.github, this.path); |
| 13 | + |
| 14 | + Stream<Event> start() { |
| 15 | + if (_timer != null) { |
| 16 | + throw new Exception("Polling already started."); |
| 17 | + } |
| 18 | + |
| 19 | + _controller = new StreamController(); |
| 20 | + |
| 21 | + int interval; |
| 22 | + |
| 23 | + void handleEvent(http.Response response) { |
| 24 | + if (interval == null) { |
| 25 | + interval = int.parse(response.headers['x-poll-interval']); |
| 26 | + } |
| 27 | + |
| 28 | + if (response.statusCode == 304) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + var json = JSON.decode(response.body); |
| 33 | + |
| 34 | + for (var item in json) { |
| 35 | + var event = Event.fromJSON(github, item); |
| 36 | + _controller.add(event); |
| 37 | + } |
| 38 | + |
| 39 | + if (_timer == null) { |
| 40 | + _timer = new Timer.periodic(new Duration(seconds: interval), (timer) { |
| 41 | + var headers = {}; |
| 42 | + |
| 43 | + if (_lastFetch != null) { |
| 44 | + headers['If-None-Match'] = _lastFetch; |
| 45 | + } |
| 46 | + |
| 47 | + github.request("GET", path, headers: headers).then(handleEvent); |
| 48 | + }); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + var headers = {}; |
| 53 | + |
| 54 | + if (_lastFetch != null) { |
| 55 | + headers['If-None-Match'] = _lastFetch; |
| 56 | + } |
| 57 | + |
| 58 | + github.request("GET", path, headers: headers).then(handleEvent); |
| 59 | + |
| 60 | + return _controller.stream; |
| 61 | + } |
| 62 | + |
| 63 | + Future stop() { |
| 64 | + if (_timer == null) { |
| 65 | + throw new Exception("Polling not started."); |
| 66 | + } |
| 67 | + |
| 68 | + _timer.cancel(); |
| 69 | + var future = _controller.close(); |
| 70 | + |
| 71 | + _timer = null; |
| 72 | + _controller = null; |
| 73 | + |
| 74 | + return future; |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +class Event { |
| 79 | + final GitHub github; |
| 80 | + |
| 81 | + Repository repo; |
| 82 | + User actor; |
| 83 | + Organization org; |
| 84 | + |
| 85 | + @ApiName("created_at") |
| 86 | + DateTime createdAt; |
| 87 | + |
| 88 | + String id; |
| 89 | + |
| 90 | + Map<String, dynamic> payload; |
| 91 | + |
| 92 | + Event(this.github); |
| 93 | + |
| 94 | + static Event fromJSON(GitHub github, input) { |
| 95 | + var event = new Event(github); |
| 96 | + |
| 97 | + event |
| 98 | + ..repo = Repository.fromJSON(github, input['repo']) |
| 99 | + ..org = Organization.fromJSON(github, input['org']) |
| 100 | + ..createdAt = parseDateTime(input['created_at']) |
| 101 | + ..id = input['id'] |
| 102 | + ..actor = User.fromJSON(github, input['actor']) |
| 103 | + ..payload = input['payload']; |
| 104 | + |
| 105 | + return event; |
| 106 | + } |
| 107 | +} |
0 commit comments