info view: get information about file or directory
[qcg-portal.git] / filex / ftp.py
1 from datetime import datetime
2 from Queue import Queue, Empty
3 import os
4 import re
5 from threading import Event
6 from urlparse import urlparse
7
8 from django.utils.timezone import localtime, UTC
9 from gridftp import FTPClient, Buffer, HandleAttr, OperationAttr
10
11
12 class FTPException(Exception):
13     pass
14
15
16 class FTPOperation:
17     def __init__(self, proxy=None, buffer_size=4096):
18         self._end = Event()
19         self._error = None
20         self._buffer = Buffer(buffer_size)
21
22         self.attr = HandleAttr()
23         self.op_attr = OperationAttr()
24
25         if proxy is not None:
26             self.op_attr.set_authorization(proxy)
27
28         self.cli = FTPClient(self.attr)
29
30         # limit size of a queue to 4 MB
31         self.stream = Queue((4 * 2**20) / buffer_size or 1)
32
33     def __del__(self):
34         self.attr.destroy()
35         self.op_attr.destroy()
36         self.cli.destroy()
37
38     def _read(self, arg, handle, error, buff, length, offset, eof):
39         if not error:
40             self.stream.put(str(buff))
41
42             if not eof:
43                 self.cli.register_read(self._buffer, self._read, None)
44
45     def _write(self, arg, handle, error, buff, length, offset, eof):
46         if eof or error:
47             return
48
49         chunk = self.stream.get()
50
51         if chunk is None:
52             size = 0
53             eof = True
54         else:
55             size = len(chunk)
56             self._buffer.fill(chunk)
57
58         self.cli.register_write(self._buffer, size, offset, eof, self._write, None)
59
60     def _done(self, arg, handle, error):
61         self._error = error
62         self._end.set()
63
64     def wait(self):
65         self._end.wait()
66         self._end.clear()
67
68         if self._error is not None:
69             match = re.search(r'A system call failed: (.*)$', self._error.replace('\r\n', '\n'), re.MULTILINE)
70
71             msg = match.groups()[0] if match else "Unknown error"
72
73             raise FTPException(msg)
74
75     def listing(self, url):
76         self.cli.verbose_list(url, self._done, None, self.op_attr)
77         self.cli.register_read(self._buffer, self._read, None)
78
79         self.wait()
80
81         result = ''
82         while not self.stream.empty():
83             result += self.stream.get()
84
85         return self._parse_mlst(result)
86
87     @staticmethod
88     def _parse_mlst(listing):
89         for item in listing.strip().splitlines():
90             # we may receive empty string when there are multiple consecutive newlines in listing
91             if item:
92                 attrs, name = item.split(' ', 1)
93
94                 attrs_dict = {}
95                 for attr in attrs.split(';'):
96                     try:
97                         key, value = attr.split('=', 1)
98                         attrs_dict[key] = value
99                     except ValueError:
100                         pass
101
102                 yield {
103                     'name': name,
104                     'type': 'directory' if attrs_dict['Type'] == 'dir' else 'file',
105                     'size': int(attrs_dict['Size']),
106                     'date': localtime(datetime.strptime(attrs_dict['Modify'], "%Y%m%d%H%M%S").replace(tzinfo=UTC())),
107                 }
108
109     def get(self, url):
110         self.cli.get(url, self._done, None, self.op_attr)
111         self.cli.register_read(self._buffer, self._read, None)
112
113         while True:
114             try:
115                 yield self.stream.get(timeout=0.1)
116             except Empty:
117                 if self._end.wait(0):
118                     break
119
120         self.wait()
121
122     def put(self, url):
123         self.cli.put(url, self._done, None, self.op_attr)
124         self.cli.register_write(self._buffer, 0, 0, False, self._write, None)
125
126     def move(self, src, dst):
127         self.cli.move(src, dst, self._done, None, self.op_attr)
128
129         self.wait()
130
131     def info(self, url):
132         data = self.listing(url).next()
133
134         if data['name'] == '.':
135             data['name'] = os.path.basename(urlparse(url).path.rstrip('/')) or u'/'
136
137         return data