Don't like ads? PRO users don't see any ads ;-)
Guest

Etvnet

By: a guest on May 2nd, 2012  |  syntax: Python  |  size: 9.87 KB  |  hits: 46  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. # -*- coding: utf-8 -*-
  2. TITLE    = "EtvNet3"
  3. PREFIX   = "/video/EtvNet3"
  4. ICON_SEARCH = "icon-search.png"
  5. ART  = "art-default.jpg"
  6. ICON = "icon-default.png"
  7. API_URL = "http://etvnet.com/api/v2.0/"
  8. BASE_URL = "http://etvnet.com/"
  9. LOGGEDIN = False
  10. sessionid = ""
  11. SORT_VALUES = ["on_air","production_year","name","mark_total"]
  12. DIR_VALUES  = ["desc","asc"]
  13. PERPAGE = "10"
  14. TRANSLIT = False
  15. USEDETAILS = False
  16.  
  17. import translit
  18.  
  19. ###################################################################################################
  20.  
  21. def Start():
  22.  
  23.   # Initialize the plug-in
  24.   Plugin.AddViewGroup("Details", viewMode="InfoList", mediaType="items")
  25.   Plugin.AddViewGroup("List", viewMode="List", mediaType="items")
  26.  
  27.   # Setup the default attributes for the ObjectContainer
  28.   ObjectContainer.title1 = TITLE
  29.   ObjectContainer.view_group = "List"
  30.   ObjectContainer.art = R(ART)
  31.  
  32.   # Setup the default attributes for the other objects
  33.   DirectoryObject.thumb = R(ICON)
  34.   DirectoryObject.art = R(ART)
  35.   VideoClipObject.thumb = R(ICON)
  36.   VideoClipObject.art = R(ART)
  37.  
  38. ###################################################################################################
  39.  
  40. @handler("/video/etvnet3", TITLE)
  41. def MainMenu():
  42.  
  43.   LOGGEDIN = Login()
  44.   oc = ObjectContainer()
  45.  
  46.   oc.add(DirectoryObject(
  47.     key = Callback(GetChannels),
  48.     title = TXT("Каналы")))
  49.  
  50.   oc.add(PrefsObject(title = "Login Info", thumb=R(ICON)))
  51.    
  52. #    Log("MyLog> url %s" % (url))
  53.    
  54.   return oc
  55.  
  56. #####################################################################
  57. def Thumb(url):
  58.   try:
  59.     data = HTTP.Request(url, cacheTime = CACHE_1MONTH).content
  60.     return DataObject(data, "image/jpeg")
  61.   except:
  62.     return Redirect(R(ICON))
  63.  
  64. ####################################################################################################
  65. def GetChannels():
  66.     oc = ObjectContainer()
  67.     url = API_URL + "channel_list.json"
  68.     obj = JSON.ObjectFromURL(url, encoding="utf-8")
  69.     sortby=""
  70.     sortdir=""
  71.     index = 0
  72.     sortby = SORT_VALUES[index]
  73.     sortdir = DIR_VALUES[index]
  74.  
  75.     for item in obj:
  76.         slug=item["slug"]
  77.         link="channel/"+str(slug)+".json?"
  78.         title = TXT(item["name"])
  79.         oc.add(DirectoryObject(
  80.             key = Callback(GetCategories, link = link, page = 1, chslug = slug),
  81.             title = title))
  82.  
  83.     return oc
  84.  
  85. ####################################################################################################
  86. def stub():
  87.     oc = ObjectContainer()
  88.     return oc
  89.  
  90. ####################################################################################################
  91. def GetCategories(link = "catalog.json?", page = 1, chslug=""):
  92.     Log(">>GetCategories called link:'%s' page:%d chslug:'%s'" % (link, page, chslug))
  93.     oc = ObjectContainer()
  94.     sortby = ""
  95.     sortdir = ""
  96.     index = 0
  97.     #index = SORT_NAMES.index(Prefs["sort"])
  98.     sortby = SORT_VALUES[index]
  99.     #index = DIR_NAMES.index(Prefs["direction"])
  100.     sortdir = DIR_VALUES[index]
  101.     thumb = ""
  102.     url = API_URL + link + "per_page=" + PERPAGE + "&sort=" + sortby + "&dir=" + sortdir
  103.     if (page > 0):
  104.         url = url + "&page="+str(page)
  105.  
  106.     obj = JSON.ObjectFromURL(url)
  107.     st = JSON.StringFromObject(obj)
  108.     #title = title + " "+str(currpage)+"/"+str(totpages)
  109.     if (obj["header"].has_key("categories")):
  110.         Log("----> Categories count=\"%d\"" % len(obj["header"]["categories"]))
  111.         for item in obj["header"]["categories"]:
  112.             url = "catalog/" + str(item["slug"])+".json?"
  113.            
  114.             if (chslug != ""):
  115.                 url = "channel/"+chslug+"/"+str(item["slug"])+".json?"
  116.  
  117.             count = item["count"]
  118.             title = TXT(item["name"]);
  119.             Log(">> Category=\"%s\"" % title)
  120.             oc.add(DirectoryObject(
  121.                 key = Callback(GetCategories, link = url, page = 1, chslug = chslug),
  122.                 title = title))
  123.  
  124.     if (len(obj["header"]["categories"]) == 0 and obj.has_key("results")):
  125.         for item in obj["results"]:
  126.             id = item["id"]
  127.             try:
  128.                 originally_available_at = Datetime.ParseDate(item["on_air"]).date()
  129.             except:
  130.                 originally_available_at = None
  131.  
  132.             if (item["class"] == "Container"):
  133.                 rating_key = id
  134.                 oc.add(TVShowObject(
  135.                     key = Callback(GetEpisodes, id = id),
  136.                     rating_key = id,
  137.                     title = TXT(item["name"]),
  138.                     rating = float(item["mark_total"]),
  139.                     originally_available_at = originally_available_at,
  140.                     episode_count = int(item["children_count"])))
  141.             else:
  142.                     oc.add(GetEpisodeOrSeason(id = id));
  143.         if (obj["header"]["page_info"]["current"] != obj["header"]["page_info"]["total"]):
  144.             oc.add(DirectoryObject(
  145.                 key = Callback(GetCategories, link = link, page = page + 1, chslug = chslug),
  146.                 title = TXT(" >> Страница ") + str(page + 1),
  147.                 thumb = R("next.png")))
  148.     return oc
  149.  
  150. ####################################################################################################
  151. def GetEpisodes(id, page = 1):
  152.     Log(">> GetEpisodes id:%s" % id)
  153.     sortby = SORT_VALUES[0]
  154.     sortdir = DIR_VALUES[0]
  155.  
  156.     oc = ObjectContainer()
  157.     url = API_URL +"media/details/"+str(id) + ".json?" + "per_page=" + PERPAGE + "&sort=" + sortby + "&dir=" + sortdir
  158.     if (page > 1):
  159.         url = url + "&page=" + str(page)
  160.  
  161.     objMedia = JSON.ObjectFromURL(url)
  162.    
  163.     for item in objMedia["children"]:
  164.         eps = GetEpisodeOrSeason(id = item["id"])
  165.         if not eps == None:
  166.             oc.add(eps);
  167.  
  168.     if (objMedia["media"]["children_page_info"]["current"] != objMedia["media"]["children_page_info"]["total"]):
  169.         oc.add(DirectoryObject(
  170.             key = Callback(GetEpisodes, id = id, page = page + 1),
  171.             title = objMedia["media"]["name"] + TXT(" -> Страница ") + str(page + 1),
  172.             thumb = R("next.png")))
  173.  
  174.     return oc
  175.  
  176. ####################################################################################################
  177. def GetEpisodeOrSeason(id):
  178.     url = API_URL +"media/details/"+str(id) + ".json?"
  179.     Log(">> Making episode")
  180.     #eps = EpisodeObject(url = url, title = TXT(item["name"]))
  181.     #oc.add(eps)
  182.     try:
  183.         objMedia = JSON.ObjectFromURL(url)
  184.     except:
  185.         return None
  186.     try:
  187.         originally_available_at = Datetime.ParseDate(objMedia['media']["on_air"]).date()
  188.     except:
  189.         originally_available_at = None
  190.     bitrates = objMedia['media']['bitrates']
  191.     duration = objMedia['media']['duration']
  192.     eps = VideoClipObject(
  193.         title = TXT(objMedia['media']["name"]),
  194.         rating = float(objMedia['media']["mark_total"]),
  195.         key = id,
  196.         summary = TXT(objMedia['media']['description']),
  197.         thumb=objMedia['media']['screenshots_path']+'b01.jpg',
  198.         originally_available_at = originally_available_at,
  199.         rating_key = id
  200.     )
  201.     for item in bitrates:
  202.         eps.add(MediaObject(
  203.         bitrate = int(item),
  204.         protocol = Protocol.WebKit,
  205.         duration = duration,
  206.         video_resolution = item,
  207.         optimized_for_streaming = True,
  208.         parts = [PartObject(key = Callback(PlayMedia, id = id, bitrate = item) , duration = duration)],
  209.         ))
  210.     return eps
  211.  
  212. ####################################################################################################
  213. def PlayMedia(id, bitrate):
  214.     url = API_URL +"media/watch/" + str(id) + "/" + str(bitrate) +".json?is_preview=0&other_server=0"
  215.     viewObj = JSON.ObjectFromURL(url)
  216.  
  217.     if (viewObj.has_key('status') and viewObj['status']=='ok'):
  218.         vurl = WindowsMediaVideoURL(viewObj['url'])
  219.     Log(">> Playing Video:%s" % viewObj['url'])
  220.     return Redirect(vurl)
  221.  
  222. ####################################################################################################
  223. def TXT(text):
  224.     if text == None:
  225.         return None
  226.     if TRANSLIT:
  227.         return translit.translify(text)
  228.     return text.decode("utf-8")
  229.  
  230. ####################################################################################################
  231. def ValidatePrefs():
  232.     u = Prefs["username"]
  233.     p = Prefs["password"]
  234.     ## do some checks and return a
  235.     ## message container
  236.     if( u and p ):
  237.         LOGGEDIN = Login()
  238.         if LOGGEDIN == False:
  239.             return MessageContainer(
  240.                 "Success",
  241.                 "User and password provided ok"
  242.         )
  243.     else:
  244.         return MessageContainer(
  245.             "Error",
  246.             "You need to provide both a user and password"
  247.         )
  248.  
  249. ####################################################################################################
  250. def Login():
  251.     global LOGGEDIN, sessionid
  252.     if (LOGGEDIN):
  253.         return True
  254.     elif (not Prefs["username"] and not Prefs["password"]):
  255.         return False
  256.     else:
  257.         #initiate = HTTP.Request(BASE_URL+"/login/", encoding="iso-8859-1", cacheTime=1)
  258.         values = {
  259.             "username" : Prefs["username"],
  260.             "password" : Prefs["password"]
  261.         }
  262.         url = API_URL + "session.json"
  263.         try:
  264.             obj = JSON.ObjectFromURL(url, values=values, encoding="utf-8", cacheTime=1)
  265.         except:
  266.             obj=[]
  267.             Log("----> Someting Bad\"%s\"" % (values))
  268.             LOGGEDIN = False
  269.             return False    
  270.         sessionid = obj["sessid"]
  271.         if (len(sessionid) > 0):
  272.             LOGGEDIN = True
  273.             Log(" --> Login successful! %s SSID=\"%s\"" % (LOGGEDIN, sessionid))
  274.             return True
  275.         else:
  276.             LOGGEDIN = False
  277.             Log(" --> Username/password incorrect!")
  278.             return False
  279.  
  280. ####################################################################################################