Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/examples/copy_async.py
blob: 602ef4785881680d04a579a0740f4633dc9465b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import tempfile

from gi.repository import GObject
from gi.repository import Gio
from gi.repository import GLib

# Avoid "Fatal Python error: GC object already tracked"
# http://stackoverflow.com/questions/7496629/gstreamer-appsrc-causes-random-crashes
GObject.threads_init()


class FileTransfer(GObject.GObject):
    _CHUNK_SIZE = 10240

    def __init__(self, input_stream, output_stream):
        GObject.GObject.__init__(self)

        self._input_stream = input_stream
        self._output_stream = output_stream
        self._buffer = GLib.Bytes.new([])
        self._buffer = GLib.ByteArray()

    def start(self):
        self._input_stream.read_bytes_async(
            self._CHUNK_SIZE, GLib.PRIORITY_LOW,
            None, self.__read_async_cb, None)

    def __read_async_cb(self, input_stream, result, user_data=None):
        data = input_stream.read_bytes_finish(result)
        print 'Read Size:', data, 'Type:', type(data)
        print 'Result:', result, 'Propagate ERROR:', result.propagate_error()

        if data is None:
            # TODO: an error occured. Report something
            print 'An error occured'
        elif data.get_size() == 0:
            # We read the file completely
            print 'Closing the File.'
            self._input_stream.close(None)
        else:
            self._input_stream.read_bytes_async(
                self._CHUNK_SIZE, GLib.PRIORITY_LOW,
                None, self.__read_async_cb, None)
            self._write_next_buffer(data)

    def __write_async_cb(self, output_stream, result, user_data=None):
        self._output_stream.write_bytes_finish(result)

        if not self._output_stream.has_pending() and \
                not self._input_stream.has_pending():
            output_stream.close(None)
            print 'DONE'
            loop.quit()
        else:
            self._write_next_buffer()

    def _write_next_buffer(self, data):

        if not self._output_stream.has_pending():
            self._output_stream.write_bytes_async(
                data, GLib.PRIORITY_LOW, None, self.__write_async_cb,
                None)


test_file_name = '/home/humitos/test.py'
test_input_stream = Gio.File.new_for_path(test_file_name).read(None)
PATH = tempfile.mkstemp()[1]
print PATH

test_output_stream = Gio.File.new_for_path(PATH)\
    .append_to(Gio.FileCreateFlags.PRIVATE, None)

splicer = FileTransfer(test_input_stream, test_output_stream)
splicer.start()

loop = GObject.MainLoop()
loop.run()