from gi.repository import Soup, Gio, GLib, GObject, Gtk

session = Soup.Session.new()
ua_string = "Minimal test case"
session.set_properties(user_agent=ua_string, timeout=15)

def download(msg, implicit=True):
    def spliced(ostream, task, istream):
        try:
            ostream.splice_finish(task)
            print('finished')
        except GLib.GError as e:
            print(e, '; stream closed?', istream.is_closed())
            if not implicit:
                istream.close(None)  # might not be closed

    def _sent(session, task, data):
        istream = session.send_finish(task)
        if implicit:
            print('sent, closed implicitly')
            flags = Gio.OutputStreamSpliceFlags.CLOSE_SOURCE  # BUG HERE
        else:
            print('sent')
            flags = Gio.OutputStreamSpliceFlags.NONE
        ostream = Gio.MemoryOutputStream.new_resizable()
        ostream.splice_async(istream, flags,
                             GLib.PRIORITY_DEFAULT,
                             cancellable, spliced, istream)
        # hehe?
        cancellable.cancel()


    cancellable = Gio.Cancellable.new()
    session.send_async(msg, cancellable, _sent, None)


msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, False)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, False)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, False)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, False)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, False)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, False)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, True)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, True)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, True)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, True)
msg = Soup.Message.new('GET', 'http://kazlauskas.me')
download(msg, True)

while True: Gtk.main_iteration()
