PageRenderTime 69ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/apps/tv/libs/ba.py

https://github.com/barttenbrinke/Bartsidee-Repository
Python | 328 lines | 305 code | 3 blank | 20 comment | 0 complexity | b7dcc7969f396ef3477610bf4f9e9da6 MD5 | raw file
  1. #===============================================================================
  2. # LICENSE Bartsidee Framework - CC BY-NC-ND
  3. #===============================================================================
  4. # This work is licenced under the Creative Commons
  5. # Attribution-Non-Commercial-No Derivative Works 3.0 Unported License. To view a
  6. # copy of this licence, visit http://creativecommons.org/licenses/by-nc-nd/3.0/
  7. # or send a letter to Creative Commons, 171 Second Street, Suite 300,
  8. # San Francisco, California 94105, USA.
  9. #===============================================================================
  10. import mc, bz2, binascii, os
  11. from time import time
  12. from django import encoding
  13. import cPickle as pickle
  14. from beautifulsoup.BeautifulSoup import BeautifulSoup
  15. #===============================================================================
  16. # Global Variables
  17. #===============================================================================
  18. http = mc.Http()
  19. http.SetUserAgent("Mozilla/5.0 (Windows; U; Windows NT 6.1; nl; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13")
  20. http.SetHttpHeader('Accept', 'text/javascript, text/html, application/xml, text/xml, */*')
  21. config = mc.GetApp().GetLocalConfig()
  22. #===============================================================================
  23. # Function to Retrieve and Cache a Http request
  24. # Input:
  25. # url - reqest url
  26. # cacheTime - amount of time to keep the http result in the cache (seconds)
  27. # xhr - make a xhr ajax request (boolean)
  28. # params - parameters to POST if empty a GET request is executed
  29. #===============================================================================
  30. def FetchUrl(url, cacheTime=0, xhr=False, params="", cookie=""):
  31. dbid = "cache_" + url
  32. if Cache(dbid+'{0}', cacheTime): return bz2.decompress(binascii.unhexlify(config.GetValue(dbid+'{1}')))
  33. if xhr: http.SetHttpHeader('X-Requested-With', 'XMLHttpRequest')
  34. if cookie: http.SetHttpHeader('Cookie', cookie)
  35. if params: data = http.Post(url, params)
  36. else: data = http.Get(url)
  37. if cacheTime != 0:
  38. config.Reset(dbid)
  39. config.Reset(dbid)
  40. config.PushBackValue(dbid, str(time()).split('.')[0])
  41. config.PushBackValue(dbid, binascii.hexlify(bz2.compress(data)))
  42. return data
  43. #===============================================================================
  44. # Function to determine if a cache is expired, returns a boolean
  45. # Input:
  46. # var - user agent variable as string
  47. #===============================================================================
  48. def UserAgent(var):
  49. http.SetUserAgent(var)
  50. #===============================================================================
  51. # Function to determine if a cache is expired, returns a boolean
  52. # Input:
  53. # dbid - variable ame id in database to check
  54. # cacheTime - amount of time to keep the variable in the cache (seconds)
  55. #===============================================================================
  56. def Cache(dbid, cacheTime):
  57. if cacheTime == 0: return False
  58. urltime = config.GetValue(dbid)
  59. if urltime == "": urltime = 0
  60. expiresAt = int(urltime) + int(cacheTime)
  61. if time() < expiresAt:
  62. return True
  63. else:
  64. return False
  65. #===============================================================================
  66. # Function to clean the app database: speeds it up and saves storage space
  67. # Input:
  68. # interval - amount of time before a new cleanup (seconds)
  69. # save - array containing the variable names to exclude from deleting
  70. #===============================================================================
  71. def CleanDb(interval, save=[]):
  72. latest = config.GetValue('clean')
  73. if latest == "": latest = 0
  74. expiresAt = int(latest) + int(interval)
  75. if time() > expiresAt:
  76. var_save = []
  77. for i in range(len(save)):
  78. var_save.append(config.GetValue(save[i]))
  79. config.ResetAll()
  80. config.SetValue('clean', str(time()).split('.')[0])
  81. for i in range(len(save)):
  82. config.SetValue(str(save[i]), str(var_save[i]))
  83. #===============================================================================
  84. # Function to convert special characters to regular unicode characters (python 2.4)
  85. # Input:
  86. # string - string to check
  87. # codec - codec to encodie the string in
  88. #===============================================================================
  89. def ConvertASCII(x):
  90. return encoding.smart_str(x, encoding='ascii', errors='ignore')
  91. #===============================================================================
  92. # Serialize an objetc/array/dictonary into a string
  93. # Input:
  94. # obj - object/dictonary element
  95. #===============================================================================
  96. def Serialize(obj):
  97. return pickle.dumps(obj)
  98. #return marshal.dumps(obj)
  99. #===============================================================================
  100. # Deserialize a string into an object/array/dictonary
  101. # Input:
  102. # obj - object/dictonary element
  103. #===============================================================================
  104. def Deserialize(obj):
  105. return pickle.loads(obj)
  106. #return marshal.loads(zstr)
  107. #===============================================================================
  108. # Get SAMI subtitle from string and converts it a tmp srt file, returning the path
  109. # Input:
  110. # data - string containing sami subtitle data
  111. #===============================================================================
  112. def ConvertSami(samiurl):
  113. data = FetchUrl(samiurl, 0)
  114. soup = BeautifulSoup(data, convertEntities="xml", smartQuotesTo="xml")
  115. i = 1
  116. sync = ''
  117. temp = ''
  118. for info in soup.findAll("sync"):
  119. if info.find(attrs={"class" : "ENUSCC"}):
  120. sync += str(i) + '\n'
  121. temp = info.find(attrs={"class" : "ENUSCC"}).contents[0]
  122. timemsec = str(info['start'])[-3:]
  123. timesec = int(str(info['start']))/1000
  124. hour = timesec / 3600
  125. minute = (timesec - (hour*3600)) / 60
  126. sec = timesec - (hour*3600) - (minute*60)
  127. srttime = str(hour) + ':' + str(minute) + ':' + str(sec) + ',' + str(timemsec)
  128. sync += str(srttime)
  129. i += 1
  130. else:
  131. timemsec = str(info['start'])[-3:]
  132. timesec = int(str(info['start']))/1000
  133. hour = timesec / 3600
  134. minute = (timesec - (hour*3600)) / 60
  135. sec = timesec - (hour*3600) - (minute*60)
  136. srttime = str(hour) + ':' + str(minute) + ':' + str(sec) + ',' + str(timemsec)
  137. sync += ' --> ' + str(srttime) + '\n'
  138. sync += str(temp) + '\n' + '\n'
  139. tmpPath = mc.GetTempDir()
  140. subFilePath = tmpPath+os.sep+'subcache.srt'
  141. f = open(subFilePath, "w")
  142. f.write(sync)
  143. f.close()
  144. return subFilePath
  145. #===============================================================================
  146. # Get SAMI subtitle from string and converts it a tmp srt file, returning the path
  147. # Input:
  148. # data - string containing sami subtitle data
  149. #===============================================================================
  150. def ConvertFlashXML(path):
  151. data = FetchUrl(path)
  152. soup = BeautifulSoup(data, convertEntities="xml", smartQuotesTo="xml")
  153. i = 1
  154. add = 1
  155. sync = ''
  156. tmp = False
  157. for info in soup.findAll("p"):
  158. sync += str(i) + '\n'
  159. timesec1 = str(info['begin'])
  160. timesec1 = timesec1.split('.')
  161. timesec2 = str(info['end'])
  162. timesec2 = timesec2.split('.')
  163. for tt in [timesec1,timesec2]:
  164. if not tmp: tmp = True
  165. else: tmp = False
  166. hour = (int(tt[0])+add) / 3600
  167. minute = ((int(tt[0])+add) - (hour*3600)) / 60
  168. sec = (int(tt[0])+add) - (hour*3600) - (minute*60)
  169. sync += str(hour) + ':' + str(minute) + ':' + str(sec) + ',' + str(tt[1])
  170. if tmp: sync += ' --> '
  171. else: sync += '\n'
  172. sync += ConvertASCII(info.renderContents()).replace('\n','').replace('\t','').replace('<br />','\n')
  173. sync += '\n' + '\n'
  174. i += 1
  175. tmpPath = mc.GetTempDir()
  176. subFilePath = tmpPath+os.sep+'subcache.srt'
  177. f = open(subFilePath, "w")
  178. f.write(sync)
  179. f.close()
  180. return subFilePath
  181. #===============================================================================
  182. # Variable Objects
  183. #===============================================================================
  184. class CreateStream:
  185. def __init__(self):
  186. self.name = ''
  187. self.id = ''
  188. self.episode = ''
  189. def SetName(self, var=''):
  190. self.name = var
  191. def SetId(self, var=''):
  192. self.id = var
  193. def SetEpisode(self, var=''):
  194. self.episode = var
  195. class CreateEpisode:
  196. def __init__(self):
  197. self.name = ''
  198. self.id = ''
  199. self.description = ''
  200. self.thumbnails = ''
  201. self.date = ''
  202. self.filter = ''
  203. self.page = ''
  204. self.totalpage = ''
  205. self.episode = ''
  206. def SetName(self, var=''):
  207. self.name = var
  208. def SetId(self, var=''):
  209. self.id = var
  210. def SetDescription(self, var=''):
  211. self.description = var
  212. def SetThumbnails(self, var=''):
  213. self.thumbnails = var
  214. def SetDate(self, var=''):
  215. self.date = var
  216. def SetFilter(self, var=''):
  217. self.filter = var
  218. def SetPage(self, var=''):
  219. self.page = var
  220. def SetTotalpage(self, var=''):
  221. self.totalpage = var
  222. def SetEpisode(self, var=''):
  223. self.episode = var
  224. class CreatePlay:
  225. def __init__(self):
  226. self.path = ''
  227. self.subtitle = ''
  228. self.subtitle_type = ''
  229. self.domain = ''
  230. self.jsactions = ''
  231. self.content_type = ''
  232. self.rtmpurl = ''
  233. self.rtmpdomain = ''
  234. self.rtmpauth = ''
  235. self.rtmpswf = ''
  236. def SetPath(self, var=''):
  237. self.path = var
  238. def SetDomain(self, var=''):
  239. self.domain = var
  240. def SetJSactions(self, var=''):
  241. self.jsactions = var
  242. def SetSubtitle(self, var=''):
  243. self.subtitle = var
  244. def SetSubtitle_type(self, var=''):
  245. self.subtitle_type = var
  246. def SetContent_type(self, var=''):
  247. self.content_type = var
  248. def SetRTMPPath(self, var=''):
  249. self.rtmppath = var
  250. def SetRTMPDomain(self, var=''):
  251. self.rtmpdomain = var
  252. def SetRTMPAuth(self, var=''):
  253. self.rtmpauth = var
  254. def SetRTMPSwf(self, var=''):
  255. self.rtmpswf = var
  256. class SearchData:
  257. def __init__(self):
  258. self.module = {}
  259. self.type = ''
  260. self.name = ''
  261. self.id = ''
  262. self.label = ''
  263. self.episode = ''
  264. def SetModule(self, var=''):
  265. self.module = var
  266. def SetType(self, var=''):
  267. self.type = var
  268. def SetLabel(self, var=''):
  269. self.label = var
  270. def SetName(self, var=''):
  271. self.name = var
  272. def SetId(self, var=''):
  273. self.id = var
  274. def SetEpisode(self, var=''):
  275. self.episode = var