CIS: transfer in, transcode, and thumbnail extraction bugs solved
[living-lab-site.git] / cis / api / file_transfer.py
1 #!/usr/bin/env python
2
3 """
4 Classes that facilitate file transfer (between Web Server and CIS).
5
6 They may extend BaseFileTransferer class.
7 """
8
9 import sys
10 import ftplib
11 import base
12 import ftp_config
13 import socket
14 import api_exceptions
15 import os
16
17
18 class FTPFileTransferer(base.BaseFileTransferer):
19     """
20     FTPS implementation for file transfering between Web Server and CIS.
21     """
22
23     ftp = None
24
25     def __init__(self, local_path='', remote_path=''):
26         base.BaseFileTransferer.__init__(self, local_path, remote_path)
27
28         self.ftp = ftplib.FTP_TLS(ftp_config.FTP_HOST, ftp_config.FTP_USER,
29                 ftp_config.FTP_PASSWD, ftp_config.FTP_ACCT)
30         self.ftp.set_pasv(True)
31
32     def get(self, files):
33         for crt_fn in files:
34             local_fn = os.path.join(self.local_path, crt_fn)
35             remote_fn = os.path.join(self.remote_path, crt_fn)
36             try:
37                 file_local = open(local_fn, 'wb')
38             except IOError as e:
39                 raise api_exceptions.FileTransferException( \
40                         "Could not open local file '%s' for writing: %s" \
41                         % (local_fn, repr(e)))
42
43             try:
44                 self.ftp.cwd(self.remote_path)
45                 self.ftp.retrbinary('RETR %s' % crt_fn, file_local.write)
46                 file_local.close()
47             except ftplib.error_perm as e:
48                 raise api_exceptions.FileTransferException( \
49                         "Could not get file '%s' from Web Server: %s" \
50                         % (remote_fn, repr(e)))
51
52     def put(self, files):
53         for crt_fn in files:
54             local_fn = os.path.join(self.local_path, crt_fn)
55             remote_fn = os.path.join(self.local_path, crt_fn)
56
57             try:
58                 file_local = open(local_fn, 'rb')
59             except IOError as e:
60                 raise api_exceptions.FileTransferException( \
61                         "Could not open local file '%s' for reading: %s" \
62                         % (local_fn, repr(e)))
63                 
64             try:
65                 self.ftp.cwd(self.remote_path)
66                 self.ftp.storbinary('STOR %s' % crt_fn, file_local)
67                 file_local.close()
68             except ftplib.error_perm as e:
69                 raise api_exceptions.FileTransferException( \
70                         "Could not get file '%s' from Web Server: %s" \
71                         % (remote_fn, repr(e)))
72
73     def close(self):
74         if self.ftp is not None:
75             try:
76                 self.ftp.quit()
77             except:
78                 pass