Python module (submodule repositary), which provides content (video streams) from various online stream sources to corresponding Enigma2, Kodi, Plex plugins

file.py 7.5KB

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