Ivars 6 years ago
parent
commit
346b41307b
1 changed files with 244 additions and 0 deletions
  1. 244
    0
      file.py

+ 244
- 0
file.py View File

@@ -0,0 +1,244 @@
1
+# -*- coding: utf-8 -*-
2
+
3
+# Server agnostic file operation similar to local files
4
+# Currently supported - local, ftp, http
5
+
6
+import os, sys, re
7
+import urllib2, ftplib
8
+
9
+def parse_url(url):
10
+    #logger.info("Url: %s" % url)
11
+    url = url.strip()
12
+    import re
13
+    m = re.search(r"^(?P<protocol>\w+)://(?:(?P<domain>[^;]+);)?(?:(?P<user>[^:@]+)[:|@])?(?:(?P<password>[^@]+)@)?(?P<host>[^/^:]+)?(?::(?P<port>[^/]+))?(?P<path>[/]?.*?)$", url, re.DOTALL | re.MULTILINE)
14
+    if m:
15
+        res = m.groupdict()
16
+    else:
17
+        res = {"domain": None, "host": None, "password": None, "path": url, "port": None, "protocol": "file", "user": None}
18
+    return res
19
+
20
+
21
+class FileObject(object):
22
+
23
+    def __init__(self, url, mode="r", encoding=""):
24
+        self.url = url
25
+        self.mode = mode
26
+        self.encoding = encoding
27
+        self.file = None
28
+        p = parse_url(url)
29
+        self.p = p
30
+        if p["protocol"] == "file":
31
+            self.file = __builtins__["open"](p["path"], mode)
32
+        elif p["protocol"] == "ftp":
33
+            import ftplib, urllib2
34
+            if "w" in mode or "a" in mode:
35
+                self.file = ftplib.FTP(p["host"], p["user"], p["password"])
36
+            elif "r" in mode:
37
+                self.file = urllib2.urlopen(url)
38
+        elif p["protocol"] in ["http", "https"]:
39
+            self.file = urllib2.urlopen(url)
40
+        else:
41
+            raise Exception("Not valid protocol")
42
+        self.first = True
43
+
44
+    def read(self, bytes=None):
45
+        if self.p["protocol"] == "file":
46
+            return self.file.read(bytes)
47
+        elif self.p["protocol"] == "ftp":
48
+            return self.file.read(bytes)
49
+        elif self.p["protocol"] in ("http", "https"):
50
+            return self.file.read(bytes)
51
+
52
+    def write(self, data, bytes=None):
53
+        if self.p["protocol"] == "file":
54
+            return self.file.write(data)
55
+        elif self.p["protocol"] == "ftp":
56
+            from StringIO import StringIO
57
+            if "w" in self.mode and self.first:
58
+                cmd = "STOR "
59
+            elif "a" in self.mode or "w" in self.mode:
60
+                cmd = "APPE "
61
+            else:
62
+                raise Exception("Can not write in r mode")
63
+            if "b" in self.mode:
64
+                self.file.storbinary(cmd + self.p["path"], StringIO(data))
65
+            else:
66
+                self.file.storlines(cmd + self.p["path"], StringIO(data))
67
+            self.first = False
68
+        elif self.p["protocol"] in ("http", "https"):
69
+            raise Exception("Write not allowed for http")
70
+        else:
71
+            raise Exception("Not valid protocol")
72
+
73
+    def close(self):
74
+        if self.p["protocol"] == "file":
75
+            self.file.close()
76
+        elif self.p["protocol"] == "ftp":
77
+            if "w" in self.mode or "a" in self.mode:
78
+                self.file.close()
79
+        elif self.p["protocol"] in ("http", "https"):
80
+            pass
81
+        else:
82
+            raise Exception("Not valid protocol")
83
+
84
+def open(url, mode="r", encoding=""):
85
+    return FileObject(url, mode, encoding)
86
+
87
+def exists(url):
88
+    p = parse_url(url)
89
+    if p["protocol"] == "file":
90
+        return os.path.exists(url)
91
+    elif p["protocol"] in ("ftp", "http", "https"):
92
+        try:
93
+            f = urllib2.urlopen(url)
94
+            del f
95
+            return True
96
+        except:
97
+            return False
98
+    else:
99
+        raise Exception("Not valid protocol")
100
+
101
+def isdir(url):
102
+    p = parse_url(url)
103
+    if p["protocol"] == "file":
104
+        return os.path.isdir(url)
105
+    elif p["protocol"] in ("ftp"):
106
+        file = ftplib.FTP(p["host"], p["user"], p["password"])
107
+        cmd = "MLSD "+p["path"]
108
+        lines = []
109
+        file.retrbinary(cmd, lines.append)
110
+        file.close()
111
+        return False if "No such file or directory" in lines[0] else True
112
+    else:
113
+        raise Exception("Not valid protocol")
114
+
115
+def mkdir(url):
116
+    p = parse_url(url)
117
+    if p["protocol"] == "file":
118
+        os.mkdir(url)
119
+    elif p["protocol"] in ("ftp"):
120
+        file = ftplib.FTP(p["host"], p["user"], p["password"])
121
+        file.mkd(p["path"])
122
+        file.close()
123
+    else:
124
+        raise Exception("Not valid protocol")
125
+
126
+def rmdir(url):
127
+    p = parse_url(url)
128
+    if p["protocol"] == "file":
129
+        os.rmdir(url)
130
+    elif p["protocol"] in ("ftp"):
131
+        file = ftplib.FTP(p["host"], p["user"], p["password"])
132
+        file.rmd(p["path"])
133
+        file.close()
134
+    else:
135
+        raise Exception("Not valid protocol")
136
+
137
+def remove(url):
138
+    p = parse_url(url)
139
+    if p["protocol"] == "file":
140
+        os.remove(url)
141
+    elif p["protocol"] in ("ftp"):
142
+        file = ftplib.FTP(p["host"], p["user"], p["password"])
143
+        file.delete(p["path"])
144
+        file.close()
145
+    else:
146
+        raise Exception("Not valid protocol")
147
+
148
+def rename(url, url2):
149
+    p = parse_url(url)
150
+    p2 = parse_url(url2)
151
+    if p["protocol"] == "file":
152
+        os.rename(url, url2)
153
+    elif p["protocol"] in ("ftp"):
154
+        file = ftplib.FTP(p["host"], p["user"], p["password"])
155
+        file.rename(p["path"], p2["path"])
156
+        file.close()
157
+    else:
158
+        raise Exception("Not valid protocol")
159
+
160
+def listdir(url):
161
+    p = parse_url(url)
162
+    if p["protocol"] == "file":
163
+        return os.listdir(url)
164
+    elif p["protocol"] in ("ftp"):
165
+        cmd = "MLSD "+p["path"]
166
+        file = ftplib.FTP(p["host"], p["user"], p["password"])
167
+        lines = []
168
+        file.retrlines(cmd, lines.append)
169
+        file.close()
170
+        return lines
171
+    else:
172
+        raise Exception("Not valid protocol")
173
+
174
+def join(*arg):
175
+    n = len(arg)
176
+    if n == 0:
177
+        return ""
178
+    elif n == 1:
179
+        return arg[0]
180
+    p = parse_url(arg[0])
181
+    sep = os.path.sep if p["protocol"] == "file" else "/"
182
+    if "/" in arg[0]:
183
+        sep = "/"
184
+    elif "\\" in arg[0]:
185
+        sep = "\\"
186
+    path = arg[0]
187
+    for i in xrange(1, n):
188
+        if arg[i-1][-1] == sep:
189
+            path = path + arg[i]
190
+        else:
191
+            path = path + sep + arg[i]
192
+    return path
193
+
194
+def encoding(url):
195
+    p = parse_url(url)
196
+    if p["protocol"] == "file":
197
+        return sys.getfilesystemencoding()
198
+    else:
199
+        return "utf8"
200
+
201
+def make_fname(name):
202
+    #"\[.+?\]" "[/\n\r\t,:]"
203
+    name = name.strip()
204
+    name = re.sub(r"[/\n\r\t,:/\\]", " ", name)
205
+    name = re.sub("['""\?\*<>]","", name)
206
+    name = name.replace("&quot;","")
207
+    return name
208
+
209
+
210
+def encode(url):
211
+    if not isinstance(url, unicode):
212
+        url = url.decode("utf8")
213
+    return url.encode(encoding(url))
214
+
215
+if __name__ == "__main__":
216
+    res = join("aaa", "bbb")
217
+    #url = "smb://user:Kaskade7@192.168.77.197/hdd/test"
218
+    url = "ftp://user:Kaskade7@home.blue.lv:21/hdd/test"
219
+    url = "ftp://user:Kaskade7@192.168.77.197:21/hdd/test"
220
+
221
+    mkdir("ftp://user:Kaskade7@192.168.77.197:21/hdd/movie/AAA")
222
+    res = listdir("ftp://user:Kaskade7@home.blue.lv/hdd/movie/")
223
+    print res
224
+    rmdir("ftp://user:Kaskade7@192.168.77.197:21/hdd/movie/AAA")
225
+    rename("ftp://user:Kaskade7@192.168.77.197:21/hdd/test", "ftp://user:Kaskade7@192.168.77.197:21/hdd/test2")
226
+    remove("ftp://user:Kaskade7@192.168.77.197:21/hdd/test2")
227
+    e = isdir("ftp://user:Kaskade7@192.168.77.197:21/hdd/movies/TV2")
228
+    print e
229
+
230
+    f = open(url, "wb")
231
+    f.write("6.rinda\n")
232
+    f.write("7.rinda\n")
233
+    f.close()
234
+    f = open(url, "rb")
235
+    res = f.read()
236
+    print res
237
+    f.close()
238
+    e = exists(url)
239
+    print e
240
+    e = exists(url+"2")
241
+    print e
242
+
243
+
244
+