Пример #1
0
def CAT_LIST(force=False):
  if force==False:
    if not os.path.isfile(SETTINGS.CHAN_LIST):
      addon_log('channels first download')
      Downloader(SETTINGS.CHAN_LIST_URL, SETTINGS.CHAN_LIST, addon.getLocalizedString(30053), addon.getLocalizedString(30054))  #Downloading Channel list
      parse_ch_data()
    else:
      now_time = time.mktime(datetime.now().timetuple())
      time_created = os.stat(SETTINGS.CHAN_LIST)[8]  # get local play list modified date
      if SETTINGS.CHAN_LIST_EXPIRE>0 and now_time - time_created > SETTINGS.CHAN_LIST_EXPIRE:
        addon_log('channels update')
        Downloader(SETTINGS.CHAN_LIST_URL, SETTINGS.CHAN_LIST, addon.getLocalizedString(30053), addon.getLocalizedString(30054)) #Downloading Channel list
        parse_ch_data()
  else:
    Downloader(SETTINGS.CHAN_LIST_URL, SETTINGS.CHAN_LIST, addon.getLocalizedString(30053), addon.getLocalizedString(30054)) #Downloading Channel list
    parse_ch_data()

  try:
    sql = "SELECT id, name \
           FROM categories"
    db_cursor.execute(sql)
    rec=db_cursor.fetchall()
  except Exception as inst:
    #addon_log(inst)
    #cannot parse the channel list
    xbmcgui.Dialog().ok(addon.getLocalizedString(30300), addon.getLocalizedString(30301), str(inst))  #Cannot parse channel list !

  if len(rec)>0:
    for id, name in rec:
      addDir(name, str(id), SETTINGS.CHAN_LIST, 1)

  #xbmc.executebuiltin("Container.SetViewMode(500)")
  xbmc.executebuiltin("Container.SetViewMode(51)")
Пример #2
0
def addLink(ch_id, name_formatted, name, url, protocol, schedule_ch_id,
            cat_name, cat_id, mode, iconimage, plot, totalitems):
    name = name.encode('utf8')
    cat_name = cat_name.encode('utf8')
    ok = True
    contextMenuItems = []

    if SETTINGS.DISABLE_SCHEDULE != 'true':
        u = sys.argv[0] + "?mode=3&name=" + urllib.quote_plus(name)
        if schedule_ch_id != "0":
            u += "&sch_ch_id=" + urllib.quote_plus(schedule_ch_id)
        contextMenuItems.append((
            addon.getLocalizedString(30050),
            "XBMC.RunPlugin(" + u + ")",
        ))  #Refresh Schedule

        u = sys.argv[0] + "?mode=5&name=" + urllib.quote_plus(
            cat_name) + "&cat_id=" + cat_id
        contextMenuItems.append((
            addon.getLocalizedString(30051),
            "XBMC.RunPlugin(" + u + ")",
        ))  #Refresh All Schedules

        #u=sys.argv[0]+"?mode=6"
        #contextMenuItems.append(( 'EPG', "XBMC.RunPlugin("+u+")", )) #EPG

    u = sys.argv[0] + "?mode=4"
    contextMenuItems.append((
        addon.getLocalizedString(30052),
        "XBMC.RunPlugin(" + u + ")",
    ))  #Refresh Channel List

    liz = xbmcgui.ListItem(name_formatted,
                           iconImage="DefaultVideo.png",
                           thumbnailImage=iconimage)
    liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": plot})

    u=sys.argv[0]+"?"+"url="+urllib.quote_plus(url)+"&mode="+str(mode)+\
                           "&name="+urllib.quote_plus(name)+\
                           "&iconimage="+urllib.quote_plus(iconimage)+\
                           "&cat_id="+cat_id+"&protocol="+protocol+\
                           "&ch_id="+str(ch_id)
    if schedule_ch_id != "0":
        u += "&sch_ch_id=" + urllib.quote_plus(schedule_ch_id)

    liz.addContextMenuItems(contextMenuItems)

    ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                     url=u,
                                     listitem=liz,
                                     isFolder=False)
    return ok
Пример #3
0
def addLink(name_formatted, name, url, schedule_ch_id, cat_name, cat_id, mode, iconimage, plot, totalitems):
  ok = True
  contextMenuItems = []
  
  if DISABLE_SCHEDULE != 'true':
    u=sys.argv[0]+"?mode=3&name="+urllib.quote_plus(name.decode('utf8').encode('utf8'))
    if schedule_ch_id != "0":
      u+="&sch_ch_id="+urllib.quote_plus(schedule_ch_id)
    contextMenuItems.append(( addon.getLocalizedString(30050), "XBMC.RunPlugin("+u+")", )) #Refresh Schedule
    
    u=sys.argv[0]+"?mode=5&name="+urllib.quote_plus(cat_name.decode('utf8').encode('utf8'))+"&cat_id="+cat_id
    contextMenuItems.append(( addon.getLocalizedString(30051), "XBMC.RunPlugin("+u+")", )) #Refresh All Schedules
    
    #u=sys.argv[0]+"?mode=6"
    #contextMenuItems.append(( 'EPG', "XBMC.RunPlugin("+u+")", )) #EPG
    
  u=sys.argv[0]+"?mode=4"
  contextMenuItems.append(( addon.getLocalizedString(30052), "XBMC.RunPlugin("+u+")", )) #Refresh Channel List
  
  liz = xbmcgui.ListItem(name_formatted, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
  liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": plot} )
  #if url[0:6]=="sop://":
    #u=sys.argv[0]+"?sop="+urllib.quote_plus(url)+"&mode=3&name="+urllib.quote_plus(name.decode('utf8').encode('utf8'))+"&iconimage="+urllib.quote_plus(iconimage)
    #contextMenuItems.append(( 'Refresh', "XBMC.RunPlugin("+u+")", ))
    
    #if CHAN_LIST == os.path.join(ADDON_PATH,"channel_guide.xml"):
    #    u=sys.argv[0]+"?sop="+urllib.quote_plus(url)+"&mode=4&name="+urllib.quote_plus(name.decode('utf8').encode('utf8'))+"&iconimage="+urllib.quote_plus(iconimage)
    #    contextMenuItems.append(( 'Remove channel', "XBMC.RunPlugin("+u+")", ))
    #channel_guide_xml=ElementTree.parse(os.path.join(ADDON_PATH,"channel_guide.xml"))
    #channel_guide_data = channel_guide_xml.find("./group/channel/.[@id='"+urlparse(url).path.strip("/")+"']")
    #if channel_guide_data:
    #    u=sys.argv[0]+"?sop="+urllib.quote_plus(url)+"&mode=5&name="+urllib.quote_plus(name.decode('utf8').encode('utf8'))+"&iconimage="+urllib.quote_plus(iconimage)
    #    contextMenuItems.append(( 'Update EPG', "XBMC.RunPlugin("+u+")", ))
  
  u=sys.argv[0]+"?"+"url="+urllib.quote_plus(url)+"&mode="+str(mode)+\
                         "&name="+urllib.quote_plus(name.decode('utf8').encode('utf8'))+\
                         "&iconimage="+urllib.quote_plus(iconimage.decode('utf8').encode('utf8'))+\
                         "&cat_id="+cat_id
  if schedule_ch_id != "0":
    u+="&sch_ch_id="+urllib.quote_plus(schedule_ch_id)
  #else:
    #u=url
    #liz.setProperty('IsPlayable', 'true')

  liz.addContextMenuItems(contextMenuItems)
  
  ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
  return ok
Пример #4
0
def grab_vk_stream(name, url):
  temp = os.path.join(ADDON_PATH,"temp.htm")
  Downloader(url, temp, addon.getLocalizedString(30065), name)  #Downloading page for parsing stream url
  f = open(temp)
  source_txt = f.read()
  f.close()
  os.remove(temp)
  
  #addon_log(source_txt)
  match=re.compile('url720=(http:\/\/[\w\W]+?.mp4)&').search(source_txt)
  if match:
    stream_url = match.group(1)
    addon_log('720 = '+stream_url)  
    return stream_url
  
  match=re.compile('url480=(http:\/\/[\w\W]+?.mp4)&').search(source_txt)
  if match:
    stream_url = match.group(1)
    addon_log('480 = '+stream_url)  
    return stream_url
  
  match=re.compile('url360=(http:\/\/[\w\W]+?.mp4)&').search(source_txt)
  if match:
    stream_url = match.group(1)
    addon_log('360 = '+stream_url)  
    return stream_url
    
  match=re.compile('url240=(http:\/\/[\w\W]+?.mp4)&').search(source_txt)
  if match:
    stream_url = match.group(1)
    addon_log('240 = '+stream_url)  
    return stream_url

  return None
Пример #5
0
    def onPlayBackStopped(self):
        addon_log('----------------------->STOP')
        addon_log(self.stream_online)

        #xbmc.executebuiltin('Container.Refresh()')
        addon_log(self.callback)
        try:
            if (self.callback != None):
                self.callback()
        except:
            pass

        #online notif
        if (self.stream_online != True):
            mark = mark_stream(ch_id=self.ch_id)
            mark.mark_offline()
            self.stream_online = False
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            if SETTINGS.NOTIFY_OFFLINE == "true":
                xbmc.executebuiltin("Notification(%s,%s,%i)" %
                                    (addon.getLocalizedString(30057), "",
                                     1))  #Channel is offline

        #addon.setSetting('player_status', 'stop')
        self.player_status = 'stop'
Пример #6
0
def grab_vk_stream(name, url):
    temp = os.path.join(ADDON_PATH, "temp.htm")
    Downloader(url, temp, addon.getLocalizedString(30065),
               name)  #Downloading page for parsing stream url
    f = open(temp)
    source_txt = f.read()
    f.close()
    os.remove(temp)

    #addon_log(source_txt)
    match = re.compile('url720=(http:\/\/[\w\W]+?.mp4)&').search(source_txt)
    if match:
        stream_url = match.group(1)
        addon_log('720 = ' + stream_url)
        return stream_url

    match = re.compile('url480=(http:\/\/[\w\W]+?.mp4)&').search(source_txt)
    if match:
        stream_url = match.group(1)
        addon_log('480 = ' + stream_url)
        return stream_url

    match = re.compile('url360=(http:\/\/[\w\W]+?.mp4)&').search(source_txt)
    if match:
        stream_url = match.group(1)
        addon_log('360 = ' + stream_url)
        return stream_url

    match = re.compile('url240=(http:\/\/[\w\W]+?.mp4)&').search(source_txt)
    if match:
        stream_url = match.group(1)
        addon_log('240 = ' + stream_url)
        return stream_url

    return None
Пример #7
0
def CAT_LIST(force=False):
    if force == False:
        if not os.path.isfile(CHAN_LIST):
            addon_log('channels first download')
            Downloader(
                CHAN_LIST_URL, CHAN_LIST, addon.getLocalizedString(30053),
                addon.getLocalizedString(30054))  #Downloading Channel list
            parse_ch_data()
        else:
            now_time = time.mktime(datetime.now().timetuple())
            time_created = os.stat(CHAN_LIST)[
                8]  # get local play list modified date
            if CHAN_LIST_EXPIRE > 0 and now_time - time_created > CHAN_LIST_EXPIRE:
                addon_log('channels update')
                Downloader(
                    CHAN_LIST_URL, CHAN_LIST, addon.getLocalizedString(30053),
                    addon.getLocalizedString(30054))  #Downloading Channel list
                parse_ch_data()
    else:
        Downloader(CHAN_LIST_URL, CHAN_LIST, addon.getLocalizedString(30053),
                   addon.getLocalizedString(30054))  #Downloading Channel list
        parse_ch_data()

    #try:
    #  parse_ch_data()
    #except Exception as inst:
    #  addon_log(inst)
    #  pass

    try:
        sql = "SELECT id, name \
           FROM categories"

        db_cursor.execute(sql)
        rec = db_cursor.fetchall()
    except Exception as inst:
        #addon_log(inst)
        #cannot parse the channel list
        xbmcgui.Dialog().ok(addon.getLocalizedString(30300),
                            addon.getLocalizedString(30301),
                            str(inst))  #Cannot parse channel list !

    if len(rec) > 0:
        for id, name in rec:
            addDir(name, str(id), CHAN_LIST, 1)

    #xbmc.executebuiltin("Container.SetViewMode(500)")
    xbmc.executebuiltin("Container.SetViewMode(51)")
Пример #8
0
def addLink(ch_id, name_formatted, name, url, protocol, schedule_ch_id, cat_name, cat_id, mode, iconimage, plot, totalitems):
  name = name.encode('utf8')
  cat_name = cat_name.encode('utf8')
  ok = True
  contextMenuItems = []

  if SETTINGS.DISABLE_SCHEDULE != 'true':
    u=sys.argv[0]+"?mode=3&name="+urllib.quote_plus(name)
    if schedule_ch_id != "0":
      u+="&sch_ch_id="+urllib.quote_plus(schedule_ch_id)
    contextMenuItems.append(( addon.getLocalizedString(30050), "XBMC.RunPlugin("+u+")", )) #Refresh Schedule

    u=sys.argv[0]+"?mode=5&name="+urllib.quote_plus(cat_name)+"&cat_id="+cat_id
    contextMenuItems.append(( addon.getLocalizedString(30051), "XBMC.RunPlugin("+u+")", )) #Refresh All Schedules

    #u=sys.argv[0]+"?mode=6"
    #contextMenuItems.append(( 'EPG', "XBMC.RunPlugin("+u+")", )) #EPG

  u=sys.argv[0]+"?mode=4"
  contextMenuItems.append(( addon.getLocalizedString(30052), "XBMC.RunPlugin("+u+")", )) #Refresh Channel List

  liz = xbmcgui.ListItem(name_formatted, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
  liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": plot} )

  u=sys.argv[0]+"?"+"url="+urllib.quote_plus(url)+"&mode="+str(mode)+\
                         "&name="+urllib.quote_plus(name)+\
                         "&iconimage="+urllib.quote_plus(iconimage)+\
                         "&cat_id="+cat_id+"&protocol="+protocol+\
                         "&ch_id="+str(ch_id)
  if schedule_ch_id != "0":
    u+="&sch_ch_id="+urllib.quote_plus(schedule_ch_id)

  liz.addContextMenuItems(contextMenuItems)

  ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
  return ok
Пример #9
0
def STREAM(name, iconimage, url, protocol, sch_ch_id, ch_id):
    if (url == None):
        try:
            xbmc.executebuiltin("Dialog.Close(all,true)")
        except:
            pass
        return False

    if (sch_ch_id != None) and (SETTINGS.DISABLE_SCHEDULE != 'true'):
        grab_schedule(sch_ch_id, name)

    #addon_log(name)
    #addon_log(iconimage)

    if not iconimage or iconimage == "": iconimage = "DefaultVideo.png"
    listitem = xbmcgui.ListItem(name,
                                iconImage="DefaultVideo.png",
                                thumbnailImage=iconimage)
    #listitem.setLabel(name)
    listitem.setInfo('video', {'Title': name})

    player = streamplayer(xbmc.PLAYER_CORE_AUTO,
                          name=name,
                          protocol=protocol,
                          ch_id=ch_id)

    #play sopcast stream
    if protocol == "sop":
        sop = sopcast(player=player, url=url, listitem=listitem)
        sop.start()

    #play acestream
    elif protocol == 'acestream':
        ace = acestream(player=player, url=url, listitem=listitem)
        ace.engine_connect()

    #play direct stream
    else:
        try:
            player.play(url, listitem)
        except Exception as inst:
            xbmcgui.Dialog().ok(addon.getLocalizedString(30060),
                                str(type(inst)), str(inst), "")
            try:
                xbmc.executebuiltin("Dialog.Close(all,true)")
            except:
                pass
def grab_fu_stream(name, url):
  temp = os.path.join(ADDON_PATH,"temp.htm")
  Downloader(url, temp, addon.getLocalizedString(30065), name)  #Downloading page for parsing stream url
  f = open(temp)
  source_txt = f.read()
  f.close()
  os.remove(temp)
  
  #addon_log(url)
  #addon_log(source_txt)
  
  match=re.compile('\'file\':\s*\'(http:\/\/[\w\W]+?\.flv)\'').search(source_txt)
  if match:
    stream_url = match.group(1)
    addon_log(stream_url)  
    return stream_url
  
  return None
Пример #11
0
def grab_fu_stream(name, url):
    temp = os.path.join(ADDON_PATH, "temp.htm")
    Downloader(url, temp, addon.getLocalizedString(30065),
               name)  #Downloading page for parsing stream url
    f = open(temp)
    source_txt = f.read()
    f.close()
    os.remove(temp)

    #addon_log(url)
    #addon_log(source_txt)

    match = re.compile('\'file\':\s*\'(http:\/\/[\w\W]+?\.flv)\'').search(
        source_txt)
    if match:
        stream_url = match.group(1)
        addon_log(stream_url)
        return stream_url

    return None
Пример #12
0
def load_schedule(name):
    addon_log('load schedule ' + name)
    schedule = []

    db_connection = sqlite3.connect(SCHEDULE_PATH)
    db_cursor = db_connection.cursor()

    table_name = name.replace(' ', '_').lower()

    now_utc = datetime.now(timezone('UTC'))
    tz_ro = timezone('Europe/Bucharest')
    dt_ro = tz_ro.normalize(now_utc.astimezone(tz_ro))

    try:
        active_event = load_active_event(name)
        if active_event:
            schedule.append(active_event)

        sql="SELECT event_time, title FROM `%s` WHERE event_time > ? ORDER BY event_time ASC LIMIT 10" % \
             (table_name,)
        #addon_log(sql)
        db_cursor.execute(sql, (time.mktime(dt_ro.timetuple()), ))
        rec = db_cursor.fetchall()

        if len(rec) > 0:
            for event_time, title in rec:
                event = add_event(event_time, title)
                schedule.append(event)

    except Exception as inst:
        addon_log(inst)
        #pass

    if len(schedule) >= 2:
        schedule_txt = ' - '.join(schedule)
    else:
        schedule_txt = '( [I]' + addon.getLocalizedString(30064) + '[/I] )'
    #addon_log(schedule_txt)

    return schedule_txt
Пример #13
0
def load_schedule(name):
  addon_log('load schedule ' + name)
  schedule = []
  
  db_connection=sqlite3.connect(SCHEDULE_PATH)
  db_cursor=db_connection.cursor()
  
  table_name = name.replace(' ', '_').lower()
  
  now_utc = datetime.now(timezone('UTC'))
  tz_ro = timezone('Europe/Bucharest')
  dt_ro = tz_ro.normalize(now_utc.astimezone(tz_ro))
  
  try:
    active_event = load_active_event(name)
    if active_event:
      schedule.append(active_event)
    
    sql="SELECT event_time, title FROM `%s` WHERE event_time > ? ORDER BY event_time ASC LIMIT 10" % \
         (table_name,)
    #addon_log(sql)
    db_cursor.execute(sql, (time.mktime(dt_ro.timetuple()),) )
    rec=db_cursor.fetchall()
          
    if len(rec)>0:
      for event_time, title in rec:
        event = add_event(event_time, title)
        schedule.append(event)
      
  except Exception as inst:
    addon_log(inst)
    #pass
  
  if len(schedule)>=2:
    schedule_txt = ' - '.join(schedule)
  else:
    schedule_txt = '( [I]'+addon.getLocalizedString(30064)+'[/I] )'
  #addon_log(schedule_txt)
  
  return schedule_txt
Пример #14
0
def STREAM(name, iconimage, url, protocol, sch_ch_id, ch_id):
  if(url == None):
    try: xbmc.executebuiltin("Dialog.Close(all,true)")
    except: pass
    return False

  if (sch_ch_id != None) and (SETTINGS.DISABLE_SCHEDULE != 'true'):
    grab_schedule(sch_ch_id, name)

  #addon_log(name)
  #addon_log(iconimage)

  if not iconimage or iconimage == "": iconimage="DefaultVideo.png"
  listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
  #listitem.setLabel(name)
  listitem.setInfo('video', {'Title': name})

  player = streamplayer(xbmc.PLAYER_CORE_AUTO, name=name, protocol=protocol, ch_id=ch_id)

  #play sopcast stream
  if protocol == "sop":
    sop = sopcast(player=player, url=url, listitem=listitem)
    sop.start()

  #play acestream
  elif protocol=='acestream':
    ace = acestream(player=player, url=url, listitem=listitem)
    ace.engine_connect()

  #play direct stream
  else:
    try:
      player.play(url, listitem)
    except Exception as inst:
      xbmcgui.Dialog().ok(addon.getLocalizedString(30060), str(type(inst)),str(inst),"")
      try: xbmc.executebuiltin("Dialog.Close(all,true)")
      except: pass
Пример #15
0
def CHANNEL_LIST(name, cat_id, schedule=False):
  addon_log(name);
  try:
    db_cursor.execute( 'SELECT id, name, country, language, status, \
                        video_resolution, video_aspect, audio_codec, video_codec, \
                        address, thumbnail, protocol, \
                        schedule_id \
                        FROM channels \
                        WHERE id_cat = ?', \
                        (cat_id,) )
    rec=db_cursor.fetchall()
  except Exception as inst:
    addon_log(inst)
    xbmcgui.Dialog().ok(addon.getLocalizedString(30300), addon.getLocalizedString(30301), str(inst))  #Cannot parse channel list !

  if len(rec)>0:
    for id, name, country, language, status, \
        video_resolution, video_aspect, audio_codec, video_codec, \
        address, thumbnail, protocol, \
        schedule_id in rec:

      #filter by country and language
      #if( (((country != '') and (addon.getSetting('country_'+country) == 'true')) or
           #((country == '') and (addon.getSetting('country_none') == 'true')) ) and
           #(((language != '') and (addon.getSetting('lang_'+language) == 'true')) or
           #((language == '') and (addon.getSetting('lang_none') == 'true')) )
        #):

      chan_name = name
      chan_url = address.strip()

      protocol = protocol.strip()
      if protocol=='sop':
        protocol_color = '[COLOR lightgreen]'+protocol+'[/COLOR]'
      else:
        protocol_color = '[COLOR yellow]'+protocol+'[/COLOR]'
      chan_thumb = thumbnail.strip()
      #addon_log(chan_thumb)
      chan_status = status

      if (((SETTINGS.SHOW_OFFLINE_CH=='true') and (int(chan_status)==1)) or (int(chan_status)!=1)): #if we show or not offline channels based on settings
        logo_name = chan_name.replace(' ', '').lower()
        logo_name = logo_name.encode('utf8')

        chan_name_formatted ="[B][COLOR blue]"+chan_name+"[/COLOR][/B]"
        chan_name_formatted += " ("+protocol_color
        if(video_codec != ''):
          chan_name_formatted += " "+video_codec
        chan_name_formatted += ")"
        if int(chan_status)==1: chan_name_formatted += " [COLOR red]"+addon.getLocalizedString(30063)+"[/COLOR]"  #Offline

        thumb_path=""
        if chan_thumb and chan_thumb != "":
          fileName, fileExtension = os.path.splitext(chan_thumb)
          fileName=fileName.split("/")[-1]
          if fileName != "":
            #thumb_path=os.path.join(ADDON_PATH,"logos",fileName+fileExtension)
            fileExtension = fileExtension.encode('utf8')
            thumb_path=os.path.join(SETTINGS.ADDON_PATH,"logos",logo_name+fileExtension)

          if not os.path.isfile(thumb_path):
            if fileName != "":
              try:
                Downloader(chan_thumb, thumb_path, fileName+fileExtension, addon.getLocalizedString(30055)) #Downloading Channel Logo
              except Exception as inst:
                pass;

        #schedule
        if (schedule_id != 0) and \
            (schedule or (addon.getSetting('schedule_ch_list') == 'true')) \
            and (SETTINGS.DISABLE_SCHEDULE != 'true'):
          if (schedule): #update all by context menu
            update_all = True
          elif(addon.getSetting('schedule_ch_list') == 'true'): #update all when we display channel list
            update_all = False
          grab_schedule(schedule_id, chan_name, update_all=update_all)

        if (SETTINGS.DISABLE_SCHEDULE != 'true') and (int(cat_id) < 200):
          schedule_txt = load_schedule(chan_name)
          chan_name_formatted += "   " + schedule_txt

        addLink(id, chan_name_formatted, chan_name, chan_url, protocol, str(schedule_id),
                name, cat_id, 2, thumb_path, "", len(rec))

  xbmc.executebuiltin("Container.SetViewMode(51)")
Пример #16
0
def grab_schedule(id_channel_port, name, force=False, update_all=False):
    addon_log('grab schedule')

    nr_days = 5

    db_connection = sqlite3.connect(SCHEDULE_PATH)
    db_cursor = db_connection.cursor()

    table_name = name.replace(' ', '_').lower()
    sql = "CREATE TABLE IF NOT EXISTS `%s` (event_time REAL, title TEXT)" % \
          (table_name)
    db_cursor.execute(sql)

    now_utc = datetime.now(timezone('UTC'))
    tz_ro = timezone('Europe/Bucharest')
    dt_ro = tz_ro.normalize(now_utc.astimezone(tz_ro))

    if force == False:
        sql="SELECT event_time FROM `%s` ORDER BY event_time ASC LIMIT 1" % \
            (table_name)
        db_cursor.execute(sql)
        rec = db_cursor.fetchone()
        if rec:
            #addon_log(rec[0]);
            #addon_log(time.mktime(dt_ro.timetuple()));
            if ((time.mktime(dt_ro.timetuple()) - rec[0]) <
                (60 * 60 * 24 *
                 2)):  #update only if schedule is older than 2 days
                addon_log('schedule is up to date')
                if update_all:
                    xbmc.executebuiltin("Notification(%s,%s,%i)" %
                                        (name, addon.getLocalizedString(30056),
                                         1000))  #Schedule is up to date
                return True

    addon_log('update schedule')

    sql="DELETE FROM `%s`" % \
         (table_name)
    db_cursor.execute(sql)

    month_name_to_no = {
        "Ianuarie": "01",
        "Februarie": "02",
        "Martie": "03",
        "Aprilie": "04",
        "Mai": "05",
        "Iunie": "06",
        "Iulie": "07",
        "August": "08",
        "Septembrie": "09",
        "Octombrie": "10",
        "Noiembrie": "11",
        "Decembrie": "12"
    }

    #event_year = dt_ro.year
    start_date = dt_ro
    url = "http://port.ro/pls/w/tv.channel?i_xday=" + str(
        nr_days) + "&i_date=%i-%02i-%02i&i_ch=%s" % (
            start_date.year, start_date.month, start_date.day, id_channel_port)

    addon_log(url)

    temp = os.path.join(ADDON_PATH, "temp.htm")
    try:
        Downloader(url, temp, addon.getLocalizedString(30061),
                   addon.getLocalizedString(30062) + " " +
                   name)  #Downloading Schedule
        f = open(temp)
        schedule_txt = f.read()
        f.close()
        os.remove(temp)
    except Exception as inst:
        schedule_txt = ""

    #addon_log(schedule_txt)

    match = re.compile(r'class="begin_time">(?P<time>.*?)</p>').search(
        schedule_txt)
    if match:
        now_time = match.group('time')
    else:
        now_time = ""
    #addon_log(now_time)

    next_year = None

    match_days = re.compile(
        '<td style="vertical-align:top;text-align:center">\n*\s*<p class="date_box" style="margin-bottom:0px">\n*\s*<span>\n(?P<date>.*?)\n*\s*</span><br/>(?P<content>.*?)\n*\s*</table>\n*\s*</td>',
        re.DOTALL).findall(schedule_txt)
    if match_days:
        i = 1
        prev_event_day = None
        prev_event_month = None
        for date, content in match_days:
            date_obj = re.match('.*? \((.*) (.*)\)', date)

            event_day = date_obj.group(1).zfill(2)
            event_month = month_name_to_no[date_obj.group(2)]
            event_year = dt_ro.year

            if (event_day == '01') and (event_month == '01') and ((
                (i > 1) and (i < nr_days)) or (i > nr_days + 1)):
                next_year = event_year + 1
            elif i == (nr_days + 1):
                next_year = None

            if next_year != None:
                event_year = next_year

            #addon_log(event_day + " " + event_month)

            if content:
                match_events_re = re.compile(
                    'btxt\" style=\"width:40px;margin:0px;padding:0px\">(?P<event_time>.*?)<.*?btxt\">(?P<event_title>.*?)</(?P<event_details>.*?)</td></tr>',
                    re.DOTALL)
                match_events = match_events_re.findall(content)
            else:
                return False

            prev_event_hour = None
            if match_events:
                for event_time, event_title, event_details in match_events:
                    if event_time == '':
                        event_time = now_time

                    event_hour = event_time.split(":")[0].zfill(2)
                    event_minutes = event_time.split(":")[1]

                    if (event_hour < prev_event_hour
                        ):  #what is after midnight is moved to the next day
                        next_day = datetime(int(event_year), int(event_month),
                                            int(event_day)) + timedelta(days=1)
                        #addon_log(next_day)
                        prev_event_day = event_day
                        prev_event_month = event_month
                        event_day = next_day.strftime('%d')
                        event_month = next_day.strftime('%m')

                    #addon_log(event_day+" "+event_month+" "+str(prev_event_day)+" "+str(prev_event_month))
                    if (event_day == '01') and (event_month == '01') and (
                            prev_event_day
                            == '31') and (prev_event_month
                                          == '12') and (event_year
                                                        == dt_ro.year):
                        event_year += 1
                        prev_event_day = None
                        prev_event_month = None

                    event_timestamp = time.mktime(
                        time.strptime(
                            event_day + "-" + event_month + "-" +
                            str(event_year) + " " + event_hour + ":" +
                            event_minutes, "%d-%m-%Y %H:%M"))

                    #addon_log(event_time)
                    #addon_log(event_day+" "+event_month+" "+str(event_year)+" "+event_hour+":"+event_minutes + " " + event_title)
                    #addon_log(event_time + "  " + str(event_timestamp) + " " + event_title)

                    sql="INSERT INTO `%s` VALUES (?, ?)" % \
                         (table_name)
                    st = db_cursor.execute(
                        sql,
                        (event_timestamp,
                         unicode(event_title.replace("'", ""), 'iso-8859-2')))
                    #addon_log(sql)

                    prev_event_hour = event_hour

            prev_event_day = event_day
            prev_event_month = event_month

            i += 1

    db_connection.commit()
    db_connection.close()
Пример #17
0
def grab_schedule(id_channel_port, name, force=False, update_all=False):
    addon_log("grab schedule")

    nr_days = 5

    db_connection = sqlite3.connect(SETTINGS.SCHEDULE_PATH)
    db_cursor = db_connection.cursor()

    table_name = name.replace(" ", "_").lower()
    sql = "CREATE TABLE IF NOT EXISTS `%s` (event_time REAL, title TEXT)" % (table_name)
    db_cursor.execute(sql)

    now_utc = datetime.now(timezone("UTC"))
    tz_ro = timezone("Europe/Bucharest")
    dt_ro = tz_ro.normalize(now_utc.astimezone(tz_ro))

    if force == False:
        sql = "SELECT event_time FROM `%s` ORDER BY event_time ASC LIMIT 1" % (table_name)
        db_cursor.execute(sql)
        rec = db_cursor.fetchone()
        if rec:
            # addon_log(rec[0]);
            # addon_log(time.mktime(dt_ro.timetuple()));
            if (time.mktime(dt_ro.timetuple()) - rec[0]) < (
                60 * 60 * 24 * 2
            ):  # update only if schedule is older than 2 days
                addon_log("schedule is up to date")
                if update_all:
                    xbmc.executebuiltin(
                        "Notification(%s,%s,%i)" % (name, addon.getLocalizedString(30056), 1000)
                    )  # Schedule is up to date
                return True

    addon_log("update schedule")

    sql = "DELETE FROM `%s`" % (table_name)
    db_cursor.execute(sql)

    month_name_to_no = {
        "Ianuarie": "01",
        "Februarie": "02",
        "Martie": "03",
        "Aprilie": "04",
        "Mai": "05",
        "Iunie": "06",
        "Iulie": "07",
        "August": "08",
        "Septembrie": "09",
        "Octombrie": "10",
        "Noiembrie": "11",
        "Decembrie": "12",
    }

    # event_year = dt_ro.year
    start_date = dt_ro
    url = (
        "http://port.ro/pls/w/tv.channel?i_xday="
        + str(nr_days)
        + "&i_date=%i-%02i-%02i&i_ch=%s" % (start_date.year, start_date.month, start_date.day, id_channel_port)
    )

    addon_log(url)

    temp = os.path.join(SETTINGS.ADDON_PATH, "temp.htm")
    try:
        Downloader(
            url, temp, addon.getLocalizedString(30061), addon.getLocalizedString(30062) + " " + name
        )  # Downloading Schedule
        f = open(temp)
        schedule_txt = f.read()
        f.close()
        os.remove(temp)
    except Exception as inst:
        schedule_txt = ""

    # addon_log(schedule_txt)

    match = re.compile(r'class="begin_time">(?P<time>.*?)</p>').search(schedule_txt)
    if match:
        now_time = match.group("time")
    else:
        now_time = ""
    # addon_log(now_time)

    next_year = None

    match_days = re.compile(
        '<td style="vertical-align:top;text-align:center">\n*\s*<p class="date_box" style="margin-bottom:0px">\n*\s*<span>\n(?P<date>.*?)\n*\s*</span><br/>(?P<content>.*?)\n*\s*</table>\n*\s*</td>',
        re.DOTALL,
    ).findall(schedule_txt)
    if match_days:
        i = 1
        prev_event_day = None
        prev_event_month = None
        for date, content in match_days:
            date_obj = re.match(".*? \((.*) (.*)\)", date)

            event_day = date_obj.group(1).zfill(2)
            event_month = month_name_to_no[date_obj.group(2)]
            event_year = dt_ro.year

            if (event_day == "01") and (event_month == "01") and (((i > 1) and (i < nr_days)) or (i > nr_days + 1)):
                next_year = event_year + 1
            elif i == (nr_days + 1):
                next_year = None

            if next_year != None:
                event_year = next_year

            # addon_log(event_day + " " + event_month)

            if content:
                match_events_re = re.compile(
                    'btxt" style="width:40px;margin:0px;padding:0px">(?P<event_time>.*?)<.*?btxt">(?P<event_title>.*?)</(?P<event_details>.*?)</td></tr>',
                    re.DOTALL,
                )
                match_events = match_events_re.findall(content)
            else:
                return False

            prev_event_hour = None
            if match_events:
                for event_time, event_title, event_details in match_events:
                    if event_time == "":
                        event_time = now_time

                    event_hour = event_time.split(":")[0].zfill(2)
                    event_minutes = event_time.split(":")[1]

                    if event_hour < prev_event_hour:  # what is after midnight is moved to the next day
                        next_day = datetime(int(event_year), int(event_month), int(event_day)) + timedelta(days=1)
                        # addon_log(next_day)
                        prev_event_day = event_day
                        prev_event_month = event_month
                        event_day = next_day.strftime("%d")
                        event_month = next_day.strftime("%m")

                    # addon_log(event_day+" "+event_month+" "+str(prev_event_day)+" "+str(prev_event_month))
                    if (
                        (event_day == "01")
                        and (event_month == "01")
                        and (prev_event_day == "31")
                        and (prev_event_month == "12")
                        and (event_year == dt_ro.year)
                    ):
                        event_year += 1
                        prev_event_day = None
                        prev_event_month = None

                    event_timestamp = time.mktime(
                        time.strptime(
                            event_day
                            + "-"
                            + event_month
                            + "-"
                            + str(event_year)
                            + " "
                            + event_hour
                            + ":"
                            + event_minutes,
                            "%d-%m-%Y %H:%M",
                        )
                    )

                    # addon_log(event_time)
                    # addon_log(event_day+" "+event_month+" "+str(event_year)+" "+event_hour+":"+event_minutes + " " + event_title)
                    # addon_log(event_time + "  " + str(event_timestamp) + " " + event_title)

                    sql = "INSERT INTO `%s` VALUES (?, ?)" % (table_name)
                    st = db_cursor.execute(sql, (event_timestamp, unicode(event_title.replace("'", ""), "iso-8859-2")))
                    # addon_log(sql)

                    prev_event_hour = event_hour

            prev_event_day = event_day
            prev_event_month = event_month

            i += 1

    db_connection.commit()
    db_connection.close()
Пример #18
0
def CHANNEL_LIST(name, cat_id, schedule=False):
    addon_log(name)
    try:
        db_cursor.execute( 'SELECT id, name, country, language, status, \
                        video_resolution, video_aspect, audio_codec, video_codec, \
                        address, thumbnail, protocol, \
                        schedule_id \
                        FROM channels \
                        WHERE id_cat = ?'                                             , \
                            (cat_id,) )
        rec = db_cursor.fetchall()
    except Exception as inst:
        addon_log(inst)
        xbmcgui.Dialog().ok(addon.getLocalizedString(30300),
                            addon.getLocalizedString(30301),
                            str(inst))  #Cannot parse channel list !

    if len(rec) > 0:
        for id, name, country, language, status, \
            video_resolution, video_aspect, audio_codec, video_codec, \
            address, thumbnail, protocol, \
            schedule_id in rec:

            #filter by country and language
            #if( (((country != '') and (addon.getSetting('country_'+country) == 'true')) or
            #((country == '') and (addon.getSetting('country_none') == 'true')) ) and
            #(((language != '') and (addon.getSetting('lang_'+language) == 'true')) or
            #((language == '') and (addon.getSetting('lang_none') == 'true')) )
            #):

            chan_name = name
            chan_url = address.strip()

            protocol = protocol.strip()
            if protocol == 'sop':
                protocol_color = '[COLOR lightgreen]' + protocol + '[/COLOR]'
            else:
                protocol_color = '[COLOR yellow]' + protocol + '[/COLOR]'
            chan_thumb = thumbnail.strip()
            #addon_log(chan_thumb)
            chan_status = status

            if (((SETTINGS.SHOW_OFFLINE_CH == 'true') and
                 (int(chan_status) == 1)) or
                (int(chan_status) !=
                 1)):  #if we show or not offline channels based on settings
                logo_name = chan_name.replace(' ', '').lower()
                logo_name = logo_name.encode('utf8')

                chan_name_formatted = "[B][COLOR blue]" + chan_name + "[/COLOR][/B]"
                chan_name_formatted += " (" + protocol_color
                if (video_codec != ''):
                    chan_name_formatted += " " + video_codec
                chan_name_formatted += ")"
                if int(chan_status) == 1:
                    chan_name_formatted += " [COLOR red]" + addon.getLocalizedString(
                        30063) + "[/COLOR]"  #Offline

                thumb_path = ""
                if chan_thumb and chan_thumb != "":
                    fileName, fileExtension = os.path.splitext(chan_thumb)
                    fileName = fileName.split("/")[-1]
                    if fileName != "":
                        #thumb_path=os.path.join(ADDON_PATH,"logos",fileName+fileExtension)
                        fileExtension = fileExtension.encode('utf8')
                        thumb_path = os.path.join(SETTINGS.ADDON_PATH, "logos",
                                                  logo_name + fileExtension)

                    if not os.path.isfile(thumb_path):
                        if fileName != "":
                            try:
                                Downloader(
                                    chan_thumb, thumb_path,
                                    fileName + fileExtension,
                                    addon.getLocalizedString(
                                        30055))  #Downloading Channel Logo
                            except Exception as inst:
                                pass

                #schedule
                if (schedule_id != 0) and \
                    (schedule or (addon.getSetting('schedule_ch_list') == 'true')) \
                    and (SETTINGS.DISABLE_SCHEDULE != 'true'):
                    if (schedule):  #update all by context menu
                        update_all = True
                    elif (addon.getSetting('schedule_ch_list') == 'true'
                          ):  #update all when we display channel list
                        update_all = False
                    grab_schedule(schedule_id,
                                  chan_name,
                                  update_all=update_all)

                if (SETTINGS.DISABLE_SCHEDULE != 'true') and (int(cat_id) <
                                                              200):
                    schedule_txt = load_schedule(chan_name)
                    chan_name_formatted += "   " + schedule_txt

                addLink(id, chan_name_formatted, chan_name, chan_url, protocol,
                        str(schedule_id), name, cat_id, 2, thumb_path, "",
                        len(rec))

    xbmc.executebuiltin("Container.SetViewMode(51)")
Пример #19
0
import xbmc, xbmcgui
import os, os.path, re
import glob
from glob import addon_log, Downloader, message, addon
from datetime import datetime, timedelta

from settings import SETTINGS

try:
    import pytz
    from pytz import timezone
except ImportError as err:
    addon_log(str(err))
    message(addon.getLocalizedString(30300), str(err) + "\n" + addon.getLocalizedString(30302))

import time
import sys
import sqlite3

# import random

# reload(sys)
# sys.setdefaultencoding('utf-8')


def grab_schedule(id_channel_port, name, force=False, update_all=False):
    addon_log("grab schedule")

    nr_days = 5

    db_connection = sqlite3.connect(SETTINGS.SCHEDULE_PATH)
Пример #20
0
  def ace_read(self):
    for line in self.read_lines(self.sock):

      if ((self.start_time!=None) and ((time.time() - self.start_time) > self.timeout)):
        self.shutdown()
        xbmc.executebuiltin("Notification(%s,%s,%i)" % (addon.getLocalizedString(30057), "", 10000))

      addon_log(line)
      if line.startswith("HELLOTS"):
        self.auth(line)
      elif line.startswith("AUTH"):
        self.request_id = self.ch_open()
      elif line.startswith("LOADRESP"):
        response = line.split()[2:]
        response = ' '.join(response)
        response = json.loads(response)

        infohash = response.get('infohash')
        #self.sock.send('GETADURL width = 1328 height = 474 infohash = ' + infohash + ' action = load'+"\r\n")
        #self.sock.send('GETADURL width = 1328 height = 474 infohash = ' + infohash + ' action = pause'+"\r\n")

        if response.get('status') == 100:
          addon_log("LOADASYNC returned error with message: %s" % response.get('message'))
        else:
          #self.filename = urllib2.unquote(response.get('files')[0][0])
          self.filename = urllib.unquote(response.get('files')[0][0].encode('ascii')).decode('utf-8')
          addon_log(self.filename)
          self.ch_start()

      elif line.startswith("START"):
        self.start_time = None

        try: xbmc.executebuiltin("Dialog.Close(all,true)")
        except: pass

        try:
          player_url = line.split()[1]
          addon_log (player_url)
          self.player.callback = self.shutdown
          self.listitem.setInfo('video', {'Title': self.filename})
          self.player.play(player_url, self.listitem)
          self.player_started = True
        except IndexError as e:
          player_url = None

        #p = re.compile('(http://)[\w\W]+?(\:[0-9]+/)')
        #player_url = url
        #player_url = p.sub(r"\1" + self.ace_host + r"\2", url)
        #addon_log (player_url)
        #self.player.play(player_url, self.listitem)

        #self.sock.send("PAUSE"+"\r\n")
        #self.sock.send("RESUME"+"\r\n")
        #self.sock.send("STOP"+"\r\n")
        #self.sock.send("SHUTDOWN"+"\r\n")

      elif line.startswith("SHUTDOWN"):
        self.sock.close()

        #offline notif
        #if player was not started
        #addon_log('player_started=');
        #addon_log(self.player_started);
        if(self.player_started != True):
          mark = mark_stream(ch_id=self.player.ch_id)
          mark.mark_offline()

        break

      #INFO 1;Cannot find active peers
      elif line.startswith("INFO"):
        tmp = line.split(';')
        info_status = tmp[0].split()[1]
        if(info_status == '1'): #INFO 1;Cannot find active peers
          info_msg = tmp[1]
          self.shutdown()
          xbmc.executebuiltin("Notification(%s,%s,%i)" % (info_msg, "", 10000))

      elif line.startswith("EVENT"):
        #print line
        pass
Пример #21
0
  def start( self ):
    try:
      if(SETTINGS.ARM):
        self.spsc = subprocess.Popen(self.cmd, shell=False, bufsize=SETTINGS.BUFER_SIZE, stdin=None, stdout=None, stderr=None)
      else:
        env = os.environ
        env['LD_LIBRARY_PATH'] = SETTINGS.SPSC_LIB
        self.spsc = subprocess.Popen(self.cmd, shell=False, bufsize=SETTINGS.BUFER_SIZE, stdin=None, stdout=None, stderr=None, env=env)

      self.spsc_pid = self.spsc.pid

      xbmc.sleep(int(addon.getSetting('wait_time')))

      res=False
      counter=50
      #while counter > 0 and os.path.exists("/proc/"+str(spsc.pid)):
      while counter > 0 and self.sop_pid_exists():
        xbmc.executebuiltin( "ActivateWindow(busydialog)" )
        xbmc.sleep(400)
        counter -= 1
        try:
          addon_log(SETTINGS.LOCAL_URL);
          urllib2.urlopen(SETTINGS.LOCAL_URL)
          counter=0
          res=self.sop_sleep(200)
          break
        except Exception as inst:
          addon_log(inst)

      addon_log(res)
      offline = None
      if res:

        #START PLAY
        self.player.callback = self.stop_spsc
        self.player.play(SETTINGS.LOCAL_URL, self.listitem)

      elif not self.sop_pid_exists():
        try: xbmc.executebuiltin("Dialog.Close(all,true)")
        except: pass
        try:
          urllib2.urlopen(SETTINGS.TEST_URL)
          if SETTINGS.NOTIFY_OFFLINE == "true": xbmc.executebuiltin("Notification(%s,%s,%i)" % (addon.getLocalizedString(30057), "",1))  #Channel is offline
          offline = True
        except:
          if SETTINGS.NOTIFY_OFFLINE == "true": xbmc.executebuiltin("Notification(%s,%s,%i)" % (addon.getLocalizedString(30058), "",1)) #Network is offline
      elif SETTINGS.NOTIFY_OFFLINE == "true":
        try: xbmc.executebuiltin("Dialog.Close(all,true)")
        except: pass
        xbmc.executebuiltin("Notification(%s,%s,%i)" % (addon.getLocalizedString(30059), "", 1)) #Channel initialization failed
        offline = True
        try: self.stop_spsc()
        except: pass
      
      if offline:
        mark = mark_stream(ch_id=self.player.ch_id)
        mark.mark_offline()

    except Exception as inst:
      xbmcgui.Dialog().ok(addon.getLocalizedString(30060), str(type(inst)),str(inst),"")
      addon_log(str(inst))
      try:
        stop_spsc()
      except: pass
      try: xbmc.executebuiltin("Dialog.Close(all,true)")
      except: pass
Пример #22
0
def addLink(name_formatted, name, url, schedule_ch_id, cat_name, cat_id, mode,
            iconimage, plot, totalitems):
    ok = True
    contextMenuItems = []

    if DISABLE_SCHEDULE != 'true':
        u = sys.argv[0] + "?mode=3&name=" + urllib.quote_plus(
            name.decode('utf8').encode('utf8'))
        if schedule_ch_id != "0":
            u += "&sch_ch_id=" + urllib.quote_plus(schedule_ch_id)
        contextMenuItems.append((
            addon.getLocalizedString(30050),
            "XBMC.RunPlugin(" + u + ")",
        ))  #Refresh Schedule

        u = sys.argv[0] + "?mode=5&name=" + urllib.quote_plus(
            cat_name.decode('utf8').encode('utf8')) + "&cat_id=" + cat_id
        contextMenuItems.append((
            addon.getLocalizedString(30051),
            "XBMC.RunPlugin(" + u + ")",
        ))  #Refresh All Schedules

        #u=sys.argv[0]+"?mode=6"
        #contextMenuItems.append(( 'EPG', "XBMC.RunPlugin("+u+")", )) #EPG

    u = sys.argv[0] + "?mode=4"
    contextMenuItems.append((
        addon.getLocalizedString(30052),
        "XBMC.RunPlugin(" + u + ")",
    ))  #Refresh Channel List

    liz = xbmcgui.ListItem(name_formatted,
                           iconImage="DefaultVideo.png",
                           thumbnailImage=iconimage)
    liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": plot})
    #if url[0:6]=="sop://":
    #u=sys.argv[0]+"?sop="+urllib.quote_plus(url)+"&mode=3&name="+urllib.quote_plus(name.decode('utf8').encode('utf8'))+"&iconimage="+urllib.quote_plus(iconimage)
    #contextMenuItems.append(( 'Refresh', "XBMC.RunPlugin("+u+")", ))

    #if CHAN_LIST == os.path.join(ADDON_PATH,"channel_guide.xml"):
    #    u=sys.argv[0]+"?sop="+urllib.quote_plus(url)+"&mode=4&name="+urllib.quote_plus(name.decode('utf8').encode('utf8'))+"&iconimage="+urllib.quote_plus(iconimage)
    #    contextMenuItems.append(( 'Remove channel', "XBMC.RunPlugin("+u+")", ))
    #channel_guide_xml=ElementTree.parse(os.path.join(ADDON_PATH,"channel_guide.xml"))
    #channel_guide_data = channel_guide_xml.find("./group/channel/.[@id='"+urlparse(url).path.strip("/")+"']")
    #if channel_guide_data:
    #    u=sys.argv[0]+"?sop="+urllib.quote_plus(url)+"&mode=5&name="+urllib.quote_plus(name.decode('utf8').encode('utf8'))+"&iconimage="+urllib.quote_plus(iconimage)
    #    contextMenuItems.append(( 'Update EPG', "XBMC.RunPlugin("+u+")", ))

    u=sys.argv[0]+"?"+"url="+urllib.quote_plus(url)+"&mode="+str(mode)+\
                           "&name="+urllib.quote_plus(name.decode('utf8').encode('utf8'))+\
                           "&iconimage="+urllib.quote_plus(iconimage.decode('utf8').encode('utf8'))+\
                           "&cat_id="+cat_id
    if schedule_ch_id != "0":
        u += "&sch_ch_id=" + urllib.quote_plus(schedule_ch_id)
    #else:
    #u=url
    #liz.setProperty('IsPlayable', 'true')

    liz.addContextMenuItems(contextMenuItems)

    ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                     url=u,
                                     listitem=liz,
                                     isFolder=False)
    return ok
Пример #23
0
def STREAM(name, iconimage, url, sch_ch_id):
    if (url == None):
        try:
            xbmc.executebuiltin("Dialog.Close(all,true)")
        except:
            pass
        return False

    if (sch_ch_id != None) and (DISABLE_SCHEDULE != 'true'):
        grab_schedule(sch_ch_id, name)

    #addon_log(name)
    #addon_log(iconimage)

    if not iconimage or iconimage == "": iconimage = "DefaultVideo.png"
    listitem = xbmcgui.ListItem(name,
                                iconImage="DefaultVideo.png",
                                thumbnailImage=iconimage)
    listitem.setLabel(name)
    listitem.setInfo('video', {'Title': name})

    if url[0:6] == "sop://":  #play sopcast stream
        try:
            cmd = [
                SPSC, url,
                str(LOCAL_PORT),
                str(VIDEO_PORT), "> /dev/null &"
            ]
            if (ARM):
                cmd = QEMU_SPSC + cmd
            #addon_log(cmd)
            spsc = subprocess.Popen(cmd,
                                    shell=False,
                                    bufsize=BUFER_SIZE,
                                    stdin=None,
                                    stdout=None,
                                    stderr=None)

            xbmc.sleep(int(addon.getSetting('wait_time')))

            res = False
            counter = 50
            #while counter > 0 and os.path.exists("/proc/"+str(spsc.pid)):
            while counter > 0 and sop_pid_exists(spsc.pid):
                xbmc.executebuiltin("ActivateWindow(busydialog)")
                xbmc.sleep(400)
                counter -= 1
                try:
                    addon_log(LOCAL_URL)
                    urllib2.urlopen(LOCAL_URL)
                    counter = 0
                    res = sop_sleep(200, spsc.pid)
                    break
                except:
                    pass

            addon_log(res)

            if res:
                player = streamplayer(xbmc.PLAYER_CORE_AUTO,
                                      spsc_pid=spsc.pid,
                                      name=name)
                addon.setSetting('player_status', 'play')
                player.play(LOCAL_URL, listitem)

                keep_allive(player)

                #watching sop process and restarting the player if it dies
                #watch_sop_thread(spsc.pid, name, listitem)

            #elif not os.path.exists("/proc/"+str(spsc.pid)):
            elif not sop_pid_exists(spsc.pid):
                try:
                    xbmc.executebuiltin("Dialog.Close(all,true)")
                except:
                    pass
                try:
                    urllib2.urlopen("http://www.google.com")
                    if NOTIFY_OFFLINE == "true":
                        xbmc.executebuiltin("Notification(%s,%s,%i)" %
                                            (addon.getLocalizedString(30057),
                                             "", 1))  #Channel is offline
                except:
                    if NOTIFY_OFFLINE == "true":
                        xbmc.executebuiltin("Notification(%s,%s,%i)" %
                                            (addon.getLocalizedString(30058),
                                             "", 1))  #Network is offline
            elif NOTIFY_OFFLINE == "true":
                try:
                    xbmc.executebuiltin("Dialog.Close(all,true)")
                except:
                    pass
                xbmc.executebuiltin("Notification(%s,%s,%i)" %
                                    (addon.getLocalizedString(30059), "",
                                     1))  #Channel initialization failed
                try:
                    stop_spsc(spsc.pid)
                except:
                    pass

        except Exception as inst:
            xbmcgui.Dialog().ok(addon.getLocalizedString(30060),
                                str(type(inst)), str(inst), "")
            addon_log(str(inst))
            try:
                stop_spsc()
            except:
                pass
            try:
                xbmc.executebuiltin("Dialog.Close(all,true)")
            except:
                pass

    else:  #play direct stream
        try:
            player = streamplayer(xbmc.PLAYER_CORE_AUTO, name=name)
            addon.setSetting('player_status', 'play')
            player.play(url, listitem)
            keep_allive(player)

        except Exception as inst:
            xbmcgui.Dialog().ok(addon.getLocalizedString(30060),
                                str(type(inst)), str(inst), "")
            try:
                xbmc.executebuiltin("Dialog.Close(all,true)")
            except:
                pass
Пример #24
0
    def ace_read(self):
        for line in self.read_lines(self.sock):

            if ((self.start_time != None)
                    and ((time.time() - self.start_time) > self.timeout)):
                self.shutdown()
                xbmc.executebuiltin(
                    "Notification(%s,%s,%i)" %
                    (addon.getLocalizedString(30057), "", 10000))

            addon_log(line)
            if line.startswith("HELLOTS"):
                self.auth(line)
            elif line.startswith("AUTH"):
                self.request_id = self.ch_open()
            elif line.startswith("LOADRESP"):
                response = line.split()[2:]
                response = ' '.join(response)
                response = json.loads(response)

                infohash = response.get('infohash')
                #self.sock.send('GETADURL width = 1328 height = 474 infohash = ' + infohash + ' action = load'+"\r\n")
                #self.sock.send('GETADURL width = 1328 height = 474 infohash = ' + infohash + ' action = pause'+"\r\n")

                if response.get('status') == 100:
                    addon_log("LOADASYNC returned error with message: %s" %
                              response.get('message'))
                else:
                    #self.filename = urllib2.unquote(response.get('files')[0][0])
                    self.filename = urllib.unquote(
                        response.get('files')[0][0].encode('ascii')).decode(
                            'utf-8')
                    addon_log(self.filename)
                    self.ch_start()

            elif line.startswith("START"):
                self.start_time = None

                try:
                    xbmc.executebuiltin("Dialog.Close(all,true)")
                except:
                    pass

                try:
                    player_url = line.split()[1]
                    addon_log(player_url)
                    self.player.callback = self.shutdown
                    self.listitem.setInfo('video', {'Title': self.filename})
                    self.player.play(player_url, self.listitem)
                    self.player_started = True
                except IndexError as e:
                    player_url = None

                #p = re.compile('(http://)[\w\W]+?(\:[0-9]+/)')
                #player_url = url
                #player_url = p.sub(r"\1" + self.ace_host + r"\2", url)
                #addon_log (player_url)
                #self.player.play(player_url, self.listitem)

                #self.sock.send("PAUSE"+"\r\n")
                #self.sock.send("RESUME"+"\r\n")
                #self.sock.send("STOP"+"\r\n")
                #self.sock.send("SHUTDOWN"+"\r\n")

            elif line.startswith("SHUTDOWN"):
                self.sock.close()

                #offline notif
                #if player was not started
                #addon_log('player_started=');
                #addon_log(self.player_started);
                if (self.player_started != True):
                    mark = mark_stream(ch_id=self.player.ch_id)
                    mark.mark_offline()

                break

            #INFO 1;Cannot find active peers
            elif line.startswith("INFO"):
                tmp = line.split(';')
                info_status = tmp[0].split()[1]
                if (info_status == '1'):  #INFO 1;Cannot find active peers
                    info_msg = tmp[1]
                    self.shutdown()
                    xbmc.executebuiltin("Notification(%s,%s,%i)" %
                                        (info_msg, "", 10000))

            elif line.startswith("EVENT"):
                #print line
                pass
Пример #25
0
def STREAM(name, iconimage, url, sch_ch_id):
  if(url == None):
    try: xbmc.executebuiltin("Dialog.Close(all,true)")
    except: pass
    return False
  
  if (sch_ch_id != None) and (DISABLE_SCHEDULE != 'true'):
    grab_schedule(sch_ch_id, name)
    
  #addon_log(name)
  #addon_log(iconimage)
  
  if not iconimage or iconimage == "": iconimage="DefaultVideo.png"
  listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
  listitem.setLabel(name)
  listitem.setInfo('video', {'Title': name})
  
  if url[0:6]=="sop://": #play sopcast stream
    try:
      cmd = [SPSC, url, str(LOCAL_PORT), str(VIDEO_PORT), "> /dev/null &"]
      if(ARM):
        cmd = QEMU_SPSC + cmd
      #addon_log(cmd)
      spsc = subprocess.Popen(cmd, shell=False, bufsize=BUFER_SIZE, stdin=None, stdout=None, stderr=None)
      
      xbmc.sleep(int(addon.getSetting('wait_time')))
      
      res=False
      counter=50
      #while counter > 0 and os.path.exists("/proc/"+str(spsc.pid)):
      while counter > 0 and sop_pid_exists(spsc.pid):
        xbmc.executebuiltin( "ActivateWindow(busydialog)" )
        xbmc.sleep(400)
        counter -= 1
        try:
          addon_log(LOCAL_URL);
          urllib2.urlopen(LOCAL_URL)
          counter=0
          res=sop_sleep(200 , spsc.pid)
          break
        except:pass
      
      addon_log(res)
        
      if res:
        player = streamplayer(xbmc.PLAYER_CORE_AUTO , spsc_pid=spsc.pid, name=name)
        addon.setSetting('player_status', 'play')
        player.play(LOCAL_URL, listitem)
        
        keep_allive(player)
        
        #watching sop process and restarting the player if it dies
        #watch_sop_thread(spsc.pid, name, listitem)
        
      #elif not os.path.exists("/proc/"+str(spsc.pid)):
      elif not sop_pid_exists(spsc.pid):
        try: xbmc.executebuiltin("Dialog.Close(all,true)")
        except: pass
        try:
          urllib2.urlopen("http://www.google.com")
          if NOTIFY_OFFLINE == "true": xbmc.executebuiltin("Notification(%s,%s,%i)" % (addon.getLocalizedString(30057), "",1))  #Channel is offline
        except:
          if NOTIFY_OFFLINE == "true": xbmc.executebuiltin("Notification(%s,%s,%i)" % (addon.getLocalizedString(30058), "",1)) #Network is offline
      elif NOTIFY_OFFLINE == "true": 
        try: xbmc.executebuiltin("Dialog.Close(all,true)")
        except: pass
        xbmc.executebuiltin("Notification(%s,%s,%i)" % (addon.getLocalizedString(30059), "", 1)) #Channel initialization failed
        try: stop_spsc(spsc.pid)
        except: pass
    
    except Exception as inst:
      xbmcgui.Dialog().ok(addon.getLocalizedString(30060), str(type(inst)),str(inst),"")
      addon_log(str(inst))
      try:
        stop_spsc()
      except: pass
      try: xbmc.executebuiltin("Dialog.Close(all,true)")
      except: pass
      
  else: #play direct stream
    try:
      player = streamplayer(xbmc.PLAYER_CORE_AUTO, name=name)
      addon.setSetting('player_status', 'play')
      player.play(url, listitem)
      keep_allive(player)
      
    except Exception as inst:
      xbmcgui.Dialog().ok(addon.getLocalizedString(30060), str(type(inst)),str(inst),"")
      try: xbmc.executebuiltin("Dialog.Close(all,true)")
      except: pass
Пример #26
0
  def onPlayBackStopped(self):
    addon_log('----------------------->STOP')
    addon_log(self.stream_online);

    #xbmc.executebuiltin('Container.Refresh()')
    addon_log(self.callback)
    try:
      if(self.callback != None):
        self.callback()
    except: pass

    #online notif
    if(self.stream_online!=True) :
      mark = mark_stream(ch_id=self.ch_id)
      mark.mark_offline()
      self.stream_online = False
      xbmc.executebuiltin( "Dialog.Close(busydialog)" )
      if SETTINGS.NOTIFY_OFFLINE == "true": xbmc.executebuiltin("Notification(%s,%s,%i)" % (addon.getLocalizedString(30057), "",1))  #Channel is offline

    #addon.setSetting('player_status', 'stop')
    self.player_status = 'stop';
Пример #27
0
import xbmc, xbmcgui
import os, os.path, re
import glob
from glob import addon_log, ADDON_PATH, Downloader, message, addon
from datetime import datetime, timedelta

try:
    import pytz
    from pytz import timezone
except ImportError as err:
    addon_log(str(err))
    message(addon.getLocalizedString(30300),
            str(err) + "\n" + addon.getLocalizedString(30302))

import time
import sys
import sqlite3
#import random

reload(sys)
sys.setdefaultencoding('utf-8')

SCHEDULE_PATH = os.path.join(ADDON_PATH, 'schedule.sqlite')


def grab_schedule(id_channel_port, name, force=False, update_all=False):
    addon_log('grab schedule')

    nr_days = 5

    db_connection = sqlite3.connect(SCHEDULE_PATH)