10

最初のjavascriptGTKアプリから始めて、ファイルをダウンロードして、Gtk.ProgressBarで進行状況を追跡したいと思います。httpリクエストについて私が見つけることができる唯一のドキュメントはここにいくつかのサンプルコードです:

http://developer.gnome.org/gnome-devel-demos/unstable/weatherGeonames.js.html.en

そして、ここでいくつかの紛らわしいスープのリファレンス:

http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Soup.SessionAsync.html

私が集めることができるものから、私はこのようなことをすることができます:

const Soup = imports.gi.Soup;

var _httpSession = new Soup.SessionAsync();
Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());

var request = Soup.Message.new('GET', url);
_httpSession.queue_message(request, function(_httpSession, message) {
  print('download is done');
}

ダウンロードが完了したときのコールバックがあるようで、データイベントのコールバック関数を設定する方法が見つかりません。これどうやってするの?

これはnode.jsでは本当に簡単です:

var req = http.request(url, function(res){
  console.log('download starting');
  res.on('data', function(chunk) {
    console.log('got a chunk of '+chunk.length+' bytes');
  }); 
});
req.end();
4

1 に答える 1

8

javascript-list@gnome.orgの助けを借りて、私はそれを理解しました。Soup.Messageには、got_chunkと呼ばれるイベントやgot_headersと呼ばれるイベントなど、バインドできるイベントが含まれていることがわかります。

const Soup = imports.gi.Soup;
const Lang = imports.lang;

var _httpSession = new Soup.SessionAsync();
Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());

// variables for the progress bar
var total_size;
var bytes_so_far = 0;

// create an http message
var request = Soup.Message.new('GET', url);

// got_headers event
request.connect('got_headers', Lang.bind(this, function(message){
  total_size = message.response_headers.get_content_length()
}));

// got_chunk event
request.connect('got_chunk', Lang.bind(this, function(message, chunk){
  bytes_so_far += chunk.length;

  if(total_size) {
    let fraction = bytes_so_far / total_size;
    let percent = Math.floor(fraction * 100);
    print("Download "+percent+"% done ("+bytes_so_far+" / "+total_size+" bytes)");
  }
}));

// queue the http request
_httpSession.queue_message(request, function(_httpSession, message) {
  print('Download is done');
});
于 2013-02-11T19:38:21.727 に答える