Пример #1
0
def ask_search_term():
    kb = xbmc.Keyboard('', 'Enter a search term')
    kb.doModal()

    if kb.isConfirmed():
        return kb.getText()
Пример #2
0
 def keyboard( self, default="", heading=LangXBMC( 528 ) ):
     kb = xbmc.Keyboard( default, heading )
     kb.doModal()
     if kb.isConfirmed():
         return kb.getText()
Пример #3
0
    if json_return['status'] != 'ok':
        raise Exception('api error')

    return json_return['params']


if ADDON.getSetting('user') == '':
    dialog = xbmcgui.Dialog()
    if dialog.yesno("IPTVMANIA",
                    "If you dont already have an account, please sign up at:",
                    "[COLOR royalblue]http://iptvmania.tv/en[/COLOR]", "",
                    "Exit", "Continue"):

        dialog.ok("IPTVMANIA", "Please provide your email")
        keyboard = xbmc.Keyboard("", "IPTVMANIA - Please provide your email")
        keyboard.doModal()
        if keyboard.isConfirmed():
            user_input = keyboard.getText()
        ADDON.setSetting('user', user_input)

        dialog.ok("IPTVMANIA", "Please provide your password")
        keyboard = xbmc.Keyboard("",
                                 "IPTVMANIA - Please provide your password")
        keyboard.doModal()
        if keyboard.isConfirmed():
            pwd_input = keyboard.getText()
        ADDON.setSetting('pass', pwd_input)
    else:
        Exit()
Пример #4
0
def GetKeyboardText(title="", defaultText=""):
    keyboard = xbmc.Keyboard(defaultText, title)
    keyboard.doModal()
    text = "" if not keyboard.isConfirmed() else keyboard.getText()
    return text
Пример #5
0
 def GetEnteredText(self, deftext='', heading='', hidden=False):
     keyboard = xbmc.Keyboard(deftext, heading, 1 if hidden else 0)
     keyboard.doModal()
     if keyboard.isConfirmed():
         return keyboard.getText()
     return deftext
Пример #6
0
def checkServer(force=False, change_user=False, notify=False):
    log.debug("checkServer Called")

    settings = xbmcaddon.Addon()
    server_url = ""
    something_changed = False
    du = DownloadUtils()

    if force is False:
        # if not forcing use server details from settings
        svr = du.getServer()
        if svr is not None:
            server_url = svr

    # if the server is not set then try to detect it
    if server_url == "":

        # scan for local server
        server_info = getServerDetails()

        addon = xbmcaddon.Addon()
        server_icon = addon.getAddonInfo('icon')

        server_list = []
        for server in server_info:
            server_item = xbmcgui.ListItem(
                server.get("Name", string_load(30063)))
            sub_line = server.get("Address")
            server_item.setLabel2(sub_line)
            server_item.setProperty("address", server.get("Address"))
            art = {"Thumb": server_icon}
            server_item.setArt(art)
            server_list.append(server_item)

        if len(server_list) > 0:
            return_index = xbmcgui.Dialog().select(__addon_name__ + " : " +
                                                   string_load(30166),
                                                   server_list,
                                                   useDetails=True)
            if return_index != -1:
                server_url = server_info[return_index]["Address"]

        if not server_url:
            return_index = xbmcgui.Dialog().yesno(__addon_name__,
                                                  string_load(30282),
                                                  string_load(30370))
            if not return_index:
                xbmc.executebuiltin("ActivateWindow(Home)")
                return

            while True:
                kb = xbmc.Keyboard()
                kb.setHeading(string_load(30372))
                if server_url:
                    kb.setDefault(server_url)
                else:
                    kb.setDefault("http://<server address>:8096")
                kb.doModal()
                if kb.isConfirmed():
                    server_url = kb.getText()
                else:
                    xbmc.executebuiltin("ActivateWindow(Home)")
                    return

                url_bits = urlparse(server_url)
                server_address = url_bits.hostname
                server_port = str(url_bits.port)
                server_protocol = url_bits.scheme
                user_name = url_bits.username
                user_password = url_bits.password

                if user_name and user_password:
                    temp_url = "%s://%s:%s@%s:%s/emby/Users/Public?format=json" % (
                        server_protocol, user_name, user_password,
                        server_address, server_port)
                else:
                    temp_url = "%s://%s:%s/emby/Users/Public?format=json" % (
                        server_protocol, server_address, server_port)

                log.debug("Testing_Url: {0}", temp_url)
                progress = xbmcgui.DialogProgress()
                progress.create(__addon_name__ + " : " + string_load(30376))
                progress.update(0, string_load(30377))
                json_data = du.downloadUrl(temp_url, authenticate=False)
                progress.close()

                result = json.loads(json_data)
                if result is not None:
                    xbmcgui.Dialog().ok(
                        __addon_name__ + " : " + string_load(30167),
                        "%s://%s:%s/" %
                        (server_protocol, server_address, server_port))
                    break
                else:
                    return_index = xbmcgui.Dialog().yesno(
                        __addon_name__ + " : " + string_load(30135),
                        server_url, string_load(30371))
                    if not return_index:
                        xbmc.executebuiltin("ActivateWindow(Home)")
                        return

        log.debug("Selected server: {0}", server_url)

        # parse the url
        url_bits = urlparse(server_url)
        server_address = url_bits.hostname
        server_port = str(url_bits.port)
        server_protocol = url_bits.scheme
        user_name = url_bits.username
        user_password = url_bits.password
        log.debug("Detected server info {0} - {1} - {2}", server_protocol,
                  server_address, server_port)

        # save the server info
        settings.setSetting("port", server_port)

        if user_name and user_password:
            server_address = "%s:%s@%s" % (url_bits.username,
                                           url_bits.password, server_address)

        settings.setSetting("ipaddress", server_address)

        if server_protocol == "https":
            settings.setSetting("protocol", "1")
        else:
            settings.setSetting("protocol", "0")

        something_changed = True

    # do we need to change the user
    user_details = load_user_details(settings)
    current_username = user_details.get("username", "")
    current_username = unicode(current_username, "utf-8")

    # if asked or we have no current user then show user selection screen
    if something_changed or change_user or len(current_username) == 0:

        # stop playback when switching users
        xbmc.Player().stop()
        du = DownloadUtils()

        # get a list of users
        log.debug("Getting user list")
        json_data = du.downloadUrl(server_url +
                                   "/emby/Users/Public?format=json",
                                   authenticate=False)

        log.debug("jsonData: {0}", json_data)
        try:
            result = json.loads(json_data)
        except:
            result = None

        if result is None:
            xbmcgui.Dialog().ok(string_load(30135), string_load(30201),
                                string_load(30169) + server_url)

        else:
            selected_id = -1
            users = []
            for user in result:
                config = user.get("Configuration")
                if config is not None:
                    if config.get("IsHidden", False) is False:
                        name = user.get("Name")
                        admin = user.get("Policy",
                                         {}).get("IsAdministrator", False)

                        time_ago = ""
                        last_active = user.get("LastActivityDate")
                        if last_active:
                            last_active_date = datetime_from_string(
                                last_active)
                            log.debug("LastActivityDate: {0}",
                                      last_active_date)
                            ago = datetime.now() - last_active_date
                            log.debug("LastActivityDate: {0}", ago)
                            days = divmod(ago.seconds, 86400)
                            hours = divmod(days[1], 3600)
                            minutes = divmod(hours[1], 60)
                            log.debug("LastActivityDate: {0} {1} {2}", days[0],
                                      hours[0], minutes[0])
                            if days[0]:
                                time_ago += " %sd" % days[0]
                            if hours[0]:
                                time_ago += " %sh" % hours[0]
                            if minutes[0]:
                                time_ago += " %sm" % minutes[0]
                            time_ago = time_ago.strip()
                            if not time_ago:
                                time_ago = "Active: now"
                            else:
                                time_ago = "Active: %s ago" % time_ago
                            log.debug("LastActivityDate: {0}", time_ago)

                        user_item = xbmcgui.ListItem(name)
                        user_image = du.get_user_artwork(user, 'Primary')
                        if not user_image:
                            user_image = "DefaultUser.png"
                        art = {"Thumb": user_image}
                        user_item.setArt(art)
                        user_item.setLabel2("TEST")

                        sub_line = time_ago

                        if user.get("HasPassword", False) is True:
                            sub_line += ", Password"
                            user_item.setProperty("secure", "true")

                            m = hashlib.md5()
                            m.update(name)
                            hashed_username = m.hexdigest()
                            saved_password = settings.getSetting(
                                "saved_user_password_" + hashed_username)
                            if saved_password:
                                sub_line += ": Saved"

                        else:
                            user_item.setProperty("secure", "false")

                        if admin:
                            sub_line += ", Admin"
                        else:
                            sub_line += ", User"

                        user_item.setProperty("manual", "false")
                        user_item.setLabel2(sub_line)
                        users.append(user_item)

                        if current_username == name:
                            selected_id = len(users) - 1

            if current_username:
                selection_title = string_load(
                    30180) + " (" + current_username + ")"
            else:
                selection_title = string_load(30180)

            # add manual login
            user_item = xbmcgui.ListItem(string_load(30365))
            art = {"Thumb": "DefaultUser.png"}
            user_item.setArt(art)
            user_item.setLabel2(string_load(30366))
            user_item.setProperty("secure", "true")
            user_item.setProperty("manual", "true")
            users.append(user_item)

            return_value = xbmcgui.Dialog().select(selection_title,
                                                   users,
                                                   preselect=selected_id,
                                                   autoclose=20000,
                                                   useDetails=True)

            if return_value > -1 and return_value != selected_id:

                something_changed = True
                selected_user = users[return_value]
                secured = selected_user.getProperty("secure") == "true"
                manual = selected_user.getProperty("manual") == "true"
                selected_user_name = selected_user.getLabel()

                log.debug("Selected User Name: {0} : {1}", return_value,
                          selected_user_name)

                if manual:
                    kb = xbmc.Keyboard()
                    kb.setHeading(string_load(30005))
                    if current_username:
                        kb.setDefault(current_username)
                    kb.doModal()
                    if kb.isConfirmed():
                        selected_user_name = kb.getText()
                        log.debug("Manual entered username: {0}",
                                  selected_user_name)
                    else:
                        return

                if secured:
                    # we need a password, check the settings first
                    m = hashlib.md5()
                    m.update(selected_user_name)
                    hashed_username = m.hexdigest()
                    saved_password = settings.getSetting(
                        "saved_user_password_" + hashed_username)
                    allow_password_saving = settings.getSetting(
                        "allow_password_saving") == "true"

                    # if not saving passwords but have a saved ask to clear it
                    if not allow_password_saving and saved_password:
                        clear_password = xbmcgui.Dialog().yesno(
                            string_load(30368), string_load(30369))
                        if clear_password:
                            settings.setSetting(
                                "saved_user_password_" + hashed_username, "")

                    if saved_password:
                        log.debug("Saving username and password: {0}",
                                  selected_user_name)
                        log.debug("Using stored password for user: {0}",
                                  hashed_username)
                        save_user_details(settings, selected_user_name,
                                          saved_password)

                    else:
                        kb = xbmc.Keyboard()
                        kb.setHeading(string_load(30006))
                        kb.setHiddenInput(True)
                        kb.doModal()
                        if kb.isConfirmed():
                            log.debug("Saving username and password: {0}",
                                      selected_user_name)
                            save_user_details(settings, selected_user_name,
                                              kb.getText())

                            # should we save the password
                            if allow_password_saving:
                                save_password = xbmcgui.Dialog().yesno(
                                    string_load(30363), string_load(30364))
                                if save_password:
                                    log.debug(
                                        "Saving password for fast user switching: {0}",
                                        hashed_username)
                                    settings.setSetting(
                                        "saved_user_password_" +
                                        hashed_username, kb.getText())
                else:
                    log.debug("Saving username with no password: {0}",
                              selected_user_name)
                    save_user_details(settings, selected_user_name, "")

        if something_changed:
            home_window = HomeWindow()
            home_window.clearProperty("userid")
            home_window.clearProperty("AccessToken")
            home_window.clearProperty("userimage")
            home_window.setProperty("embycon_widget_reload", str(time.time()))
            du = DownloadUtils()
            du.authenticate()
            du.getUserId()
            xbmc.executebuiltin("ActivateWindow(Home)")
            xbmc.executebuiltin("ReloadSkin()")
Пример #7
0
def Movie_Search(params):
    #-- get filter parameters
    par = Get_Parameters(params)

    # show search dialog
    if par.search == 'Y':
        skbd = xbmc.Keyboard()
        skbd.setHeading('Поиск фильмов.')
        skbd.doModal()
        if skbd.isConfirmed():
            SearchStr = skbd.getText().split(':')
            par.search = SearchStr[0]
        else:
            return False
    #-- get search url
    url = 'http://v720.ru/index.php?do=search'
    #-- serach parameters ---------
    values = {
        'beforeafter': 'after',
        #'catlist[]'	        :   0,
        'do': 'search',
        'full_search': 1,
        'replyless': 0,
        'replylimit': 0,
        'resorder': 'asc',
        'result_from': 1,
        'result_num': 200,
        'search_start': 1,
        'searchdate': 0,
        'searchuser': '',
        'showposts': 0,
        'sortby': 'title',
        'story': par.search.decode('utf-8').encode('cp1251'),
        'subaction': 'search',
        'titleonly': 3
    }

    post = urllib.urlencode(values)

    #== get movie list =====================================================
    html = get_HTML(url, post).replace(
        '<div id="sort">', '<div id="MOVIE"><div id="sort">').replace(
            '<div class="bottom_content">',
            '</div><div class="bottom_content">').replace('<br />', '|')
    # -- parsing web page ------------------------------------------------------
    soup = BeautifulSoup(html, fromEncoding="windows-1251")

    for rec in soup.findAll('div', {'class': 'middle_content'}):
        if rec.find('form'):
            s = rec.text.replace(u'По Вашему запросу найдено',
                                 '##').replace(u'ответов', '##')
            try:
                par.count = int(re.compile('## (.+?) ##').findall(s)[0])
            except:
                pass

    # -- add header info
    Get_Header(par)

    for rec in soup.findAll('div', {'id': 'MOVIE'}):
        try:
            #--
            mi.url = rec.find('div', {'id': 'sort'}).find('a')['href']
            name_year = rec.find('div', {
                'id': 'sort'
            }).find('a').text.encode('utf-8')
            mi.title = name_year.split('(')[0]
            mi.year = int(name_year.split('(')[1].replace(')', ''))
            #--
            mi.img = 'http://v720.ru/' + rec.find('td', {
                'class': 'short-story_img'
            }).find('img')['src']
            #--
            for r in rec.find('td', {
                    'class': 'short-story_text'
            }).text.split('|'):
                if r.split(':', 1)[0] == u'Оригинальное название':
                    mi.orig = r.split(':', 1)[1].encode('utf-8')
                elif r.split(':')[0] == u'Страна':
                    mi.country = r.split(':')[1].encode('utf-8')
                elif r.split(':')[0] == u'Жанр':
                    mi.genre = r.split(':')[1].encode('utf-8')
                elif r.split(':', 1)[0] == u'В главных ролях':
                    mi.artist = r.split(':', 1)[1].encode('utf-8').split(',')
                elif r.split(':')[0] == u'Режиссер':
                    mi.director = r.split(':')[1].encode('utf-8')
                elif r.split(':', 1)[0] == u'О фильме':
                    mi.text = r.split(':', 1)[1].encode('utf-8')
            #--
            i = xbmcgui.ListItem(mi.title,
                                 iconImage=mi.img,
                                 thumbnailImage=mi.img)
            u = sys.argv[0] + '?mode=SOURCE'
            u += '&name=%s' % urllib.quote_plus(mi.title)
            u += '&url=%s' % urllib.quote_plus(mi.url)
            u += '&img=%s' % urllib.quote_plus(mi.img)
            i.setInfo(type='video',
                      infoLabels={
                          'title': mi.title,
                          'originaltitle': mi.orig,
                          'year': mi.year,
                          'director': mi.director,
                          'artist': mi.artist,
                          'plot': mi.text,
                          'country': mi.country,
                          'genre': mi.genre
                      })
            #i.setProperty('fanart_image', mi.img)
            xbmcplugin.addDirectoryItem(h, u, i, True)
        except:
            pass

    xbmcplugin.endOfDirectory(h)
Пример #8
0
def add_new_parser(url):
	if not url:
		opcao= xbmcgui.Dialog().yesno(translate(40000),translate(400012),"","",translate(40124),translate(40125))
		if opcao:
			dialog = xbmcgui.Dialog()
			parser_tball = dialog.browse(int(1), translate(400013), 'myprograms','.tar.gz')
			if '.tar.gz' in parser_tball:
				parser_name = parser_tball.split('/')
				if len(parser_name) == 1: parser_name = parser_tball.split('\\')
				parser_name=parser_name[-1].replace('.tar.gz','')	
				print("the list is: " + parser_tball,parser_name)
				future_parser_tball = os.path.join(parser_folder,parser_name+'.tar.gz')
				xbmcvfs.copy(parser_tball,future_parser_tball)
				if not xbmcvfs.exists(os.path.join(pastaperfil,"parser-packages")): xbmcvfs.mkdir(os.path.join(pastaperfil,"parser-packages"))
				parser_package_directory_file = os.path.join(pastaperfil,"parser-packages",parser_name+'.tar.gz')
				xbmcvfs.copy(future_parser_tball,parser_package_directory_file)
				import tarfile
				if tarfile.is_tarfile(future_parser_tball):
					download_tools().extract(future_parser_tball,parser_core_folder)
					xbmc.sleep(500)
					download_tools().remove(future_parser_tball)
				module_file = os.path.join(parser_folder,parser_name + '.txt')
				text = str({})
				save(module_file,str(text))
				xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000), translate(400014),1,addonpath+"/icon.png"))
				xbmc.executebuiltin("Container.Refresh")
			else:
				mensagemok(translate(40000),translate(400015))
				sys.exit(0) 			
		else:
			keyb = xbmc.Keyboard("", translate(400016))
			keyb.doModal()
			if (keyb.isConfirmed()):
				search = keyb.getText()
				if search=='': sys.exit(0)
				if '.tar.gz' not in search: mensagemok(translate(40000),translate(400017)); sys.exit(0)
				else: 
					md5checksum = search.replace('.tar.gz','.md5')
					modulename = search.split('/')[-1].replace('.tar.gz','').replace('?raw=true','').replace('?dl=1','')
					md5_up=url_isup(md5checksum)
					module_up=url_isup(search)
					if not xbmcvfs.exists(parser_folder): xbmcvfs.mkdir(parser_folder)
					text = {}
					if module_up: text['url'] = search
					if md5_up: text['md5'] = get_page_source(md5checksum)
					if text:
						try:
							module_file = os.path.join(parser_folder,modulename + '.txt')
							module_tar_location = os.path.join(parser_core_folder,modulename+'tar.gz')
							save(module_file,str(text))
							download_tools().Downloader(search,module_tar_location,translate(400018),translate(40000))
							import tarfile            
							if tarfile.is_tarfile(module_tar_location):
								download_tools().extract(module_tar_location,parser_core_folder)
								xbmc.sleep(500)
								download_tools().remove(module_tar_location)
							xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000),translate(400014),1,addonpath+"/icon.png"))
							xbmc.executebuiltin("Container.Refresh")
						except: mensagemok(translate(40000),translate(400024))
					else:
						mensagemok(translate(40000),translate(400015))
						sys.exit(0)
	else:
		modulename = url.split('/')[-1].replace('.tar.gz','').replace('?raw=true','').replace('?dl=1','')
		if not xbmcvfs.exists(parser_folder): xbmcvfs.mkdir(parser_folder)
		if not xbmcvfs.exists(parser_packages_folder): xbmcvfs.mkdir(parser_packages_folder)
		if xbmcvfs.exists(os.path.join(parser_folder,modulename + '.txt')):
			texto = readfile(os.path.join(parser_folder,modulename + '.txt'))
			texto = eval(texto)
			if type(texto) == dict:
				if 'md5_url' in texto.keys(): md5checksum = texto['md5_url']
				else: md5checksum = url.replace('.tar.gz','.md5')
			else: md5checksum = url.replace('.tar.gz','.md5')		
		else: md5checksum = url.replace('.tar.gz','.md5')
		md5_up=url_isup(md5checksum)
		module_up=url_isup(url)
		text = {}
		if module_up: text['url'] = url
		if md5_up: 
			text['md5'] = get_page_source(md5checksum)
			text['md5_url'] = md5checksum
		if text:
			module_file = os.path.join(parser_folder,modulename + '.txt')
			module_tar_location = os.path.join(parser_core_folder,modulename+'.tar.gz')
			module_parser_backup = os.path.join(parser_packages_folder,modulename+'.tar.gz')
			save(module_file,str(text))
			download_tools().Downloader(url,module_tar_location,translate(400018),translate(40000))
			import tarfile 
			if tarfile.is_tarfile(module_tar_location):
				download_tools().extract(module_tar_location,parser_core_folder)
				shutil.copyfile(module_tar_location, module_parser_backup)
				xbmc.sleep(500)
				download_tools().remove(module_tar_location)
				print(str(modulename) + " : Module installed sucessfully")
				return
Пример #9
0
 def onClick(self, controlID):
     list = self.getControl(120)
     if (controlID == 111):
         # Add torrent
         engines = [
             (_(32200), None),
             (_(32202), search.TPB),
             (_(32203), search.Mininova),
             (_(32204), search.Kickass),
         ]
         selected = xbmcgui.Dialog().select(_(32000),
                                            [i[0] for i in engines])
         if selected < 0:
             return
         engine = engines[selected][1]
         if not engine:
             filename = xbmcgui.Dialog().browse(1, _(32000), 'files',
                                                '.torrent')
             try:
                 f = open(filename, 'r')
                 data = base64.b64encode(f.read())
                 self.transmission.add(data)
             except:
                 pass
         else:
             kb = xbmc.Keyboard('', engines[selected][0])
             kb.doModal()
             if not kb.isConfirmed():
                 return
             terms = kb.getText()
             p = xbmcgui.DialogProgress()
             p.create(_(32000), _(32290))
             try:
                 results = engine().search(terms)
             except:
                 p.close()
                 xbmcgui.Dialog().ok(_(32000), _(32292))
                 return
             p.close()
             if not results:
                 xbmcgui.Dialog().ok(_(32000), _(32291))
                 return
             selected = xbmcgui.Dialog().select(_(32000), [
                 '[S:%d L:%d] %s' % (t['seeds'], t['leechers'], t['name'])
                 for t in results
             ])
             if selected < 0:
                 return
             try:
                 self.transmission.add_torrent(results[selected]['url'])
             except:
                 xbmcgui.Dialog().ok(_(32000), _(32293))
                 return
     if (controlID == 112):
         # Remove selected torrent
         item = list.getSelectedItem()
         if item and xbmcgui.Dialog().yesno(
                 _(32000), 'Remove \'%s\'?' %
                 self.torrents[int(item.getProperty('TorrentID'))].name):
             remove_data = xbmcgui.Dialog().yesno(_(32000),
                                                  'Remove data as well?')
             self.transmission.remove(int(item.getProperty('TorrentID')),
                                      remove_data)
     if (controlID == 113):
         # Stop selected torrent
         item = list.getSelectedItem()
         if item:
             self.transmission.stop(int(item.getProperty('TorrentID')))
     if (controlID == 114):
         # Start selected torrent
         item = list.getSelectedItem()
         if item:
             self.transmission.start(int(item.getProperty('TorrentID')))
     if (controlID == 115):
         # Stop all torrents
         self.transmission.stop(self.torrents.keys())
     if (controlID == 116):
         # Start all torrents
         self.transmission.start(self.torrents.keys())
     if (controlID == 117):
         # Exit button
         self.close()
     if (controlID == 118):
         # Settings button
         prev_settings = common.get_settings()
         __settings__.openSettings()
         p = xbmcgui.DialogProgress()
         p.create(_(32000),
                  _(32001))  # 'Transmission', 'Connecting to Transmission'
         try:
             self.transmission = common.get_rpc_client()
             self.updateTorrents()
             p.close()
         except:
             p.close()
             xbmcgui.Dialog().ok(_(32002), _(32901))
             # restore settings
             self.set_settings(prev_settings)
             try:
                 self.transmission = common.get_rpc_client()
             except err:
                 xbmcgui.Dialog().ok(_(32002), _(32901))
                 self.close()
     if (controlID == 120):
         # A torrent was chosen, show details
         item = list.getSelectedItem()
         w = TorrentInfoGUI("script-Transmission-details.xml",
                            __settings__.getAddonInfo('path'), "Default")
         w.setTorrent(self.transmission, int(item.getProperty('TorrentID')))
         w.doModal()
         del w
Пример #10
0
def handle_captchas(url, html, data, dialog):

    headers = {'Referer': url}

    puzzle_img = os.path.join(datapath, "solve_puzzle.png")

    #Check for type of captcha used
    solvemedia = re.search('<iframe src="(http://api.solvemedia.com.+?)"',
                           html)
    recaptcha = re.search(
        '<script type="text/javascript" src="(http://www.google.com.+?)">',
        html)
    numeric_captcha = re.compile(
        "left:(\d+)px;padding-top:\d+px;'>&#(.+?);<").findall(html)

    #SolveMedia captcha
    if solvemedia:
        dialog.close()
        html = net.http_GET(solvemedia.group(1), headers=headers).content

        for match in re.finditer(
                r'type=hidden.*?name="([^"]+)".*?value="([^"]+)', html):
            name, value = match.groups()
            data[name] = value

        #Check for alternate puzzle type - stored in a div
        alt_frame = re.search('<div><iframe src="(/papi/media[^"]+)', html)
        if alt_frame:
            html = net.http_GET("http://api.solvemedia.com%s" %
                                alt_frame.group(1)).content
            alt_puzzle = re.search(
                '<div\s+id="typein">\s*<img\s+src="data:image/png;base64,([^"]+)',
                html, re.DOTALL)
            if alt_puzzle:
                open(puzzle_img,
                     'wb').write(alt_puzzle.group(1).decode('base64'))
        else:
            open(puzzle_img, 'wb').write(
                net.http_GET("http://api.solvemedia.com%s" % re.search(
                    '<img src="(/papi/media[^"]+)"', html).group(1)).content)

        img = xbmcgui.ControlImage(450, 15, 400, 130, puzzle_img)
        wdlg = xbmcgui.WindowDialog()
        wdlg.addControl(img)
        wdlg.show()

        xbmc.sleep(3000)

        kb = xbmc.Keyboard('', 'Type the letters in the image', False)
        kb.doModal()
        capcode = kb.getText()

        if (kb.isConfirmed()):
            userInput = kb.getText()
            if userInput != '':
                solution = kb.getText()
            elif userInput == '':
                raise Exception(
                    'You must enter text in the image to access video')
                wdlg.close()
        else:
            wdlg.close()
            raise Exception('Captcha Error')
        wdlg.close()
        data['adcopy_response'] = solution
        html = net.http_POST('http://api.solvemedia.com/papi/verify.noscript',
                             data)
        data.update({
            'adcopy_challenge': data['adcopy_challenge'],
            'adcopy_response': 'manual_challenge'
        })

    #Google Recaptcha
    elif recaptcha:
        dialog.close()
        html = net.http_GET(recaptcha.group(1), headers=headers).content
        part = re.search("challenge \: \\'(.+?)\\'", html)
        captchaimg = 'http://www.google.com/recaptcha/api/image?c=' + part.group(
            1)
        img = xbmcgui.ControlImage(450, 15, 400, 130, captchaimg)
        wdlg = xbmcgui.WindowDialog()
        wdlg.addControl(img)
        wdlg.show()

        xbmc.sleep(3000)

        kb = xbmc.Keyboard('', 'Type the letters in the image', False)
        kb.doModal()
        capcode = kb.getText()

        if (kb.isConfirmed()):
            userInput = kb.getText()
            if userInput != '':
                solution = kb.getText()
            elif userInput == '':
                raise Exception(
                    'You must enter text in the image to access video')
                wdlg.close()
        else:
            wdlg.close()
            raise Exception('Captcha Error')
        wdlg.close()
        data.update({
            'recaptcha_challenge_field': part.group(1),
            'recaptcha_response_field': solution
        })

    #Numeric captcha - we can programmatically figure this out
    elif numeric_captcha:
        result = sorted(numeric_captcha, key=lambda ltr: int(ltr[0]))
        solution = ''.join(str(int(num[1]) - 48) for num in result)
        data.update({'code': solution})

    return data
Пример #11
0
#########################################################

if mode is None:
    Main_addDir()

###############GAMATOKIDS#################
elif mode == 3:
    get_gam_genres(url)
elif mode == 4:
    gamato_kids(url)
elif mode == 12:
    get_links(name, url, iconimage, description)
    # gamato_links(url, name, iconimage)
elif mode == 18:
    keyb = xbmc.Keyboard('', Lang(32002))
    keyb.doModal()
    if keyb.isConfirmed():
        search = quote_plus(keyb.getText())
        url = GAMATO + "?s={}".format(search)
        Search_gamato(url)
    else:
        pass
elif mode == 20:
    gamatokids()
elif mode == 21:
    gamatokids_top(url)

##########################################

###############METAGLOTISMENO#################
Пример #12
0
    api_return = urlopen(request).read()
    print api_return
    import json
    json_return = json.loads(api_return)
    
    if json_return['status'] != 'ok':
        raise Exception('api error')
    
    return json_return['params']

if ADDON.getSetting('user')=='':
    dialog = xbmcgui.Dialog()
    if dialog.yesno("Husahm.iptv", "If you dont already have an account, please sign up at:", "[COLOR royalblue]http://IPTV.HUSHAM.COM[/COLOR]", "", "Exit", "Continue"):
        
        dialog.ok("Husahm.iptv", "Please provide your email")
        keyboard = xbmc.Keyboard("", "Husahm.iptv - Please provide your email")
        keyboard.doModal()
        if keyboard.isConfirmed():
            user_input = keyboard.getText() 
        ADDON.setSetting('user',user_input)
        
        dialog.ok("Husahm.iptv", "Please provide your password")
        keyboard = xbmc.Keyboard("", "Husahm.iptv - Please provide your password")
        keyboard.doModal()
        if keyboard.isConfirmed():
            pwd_input = keyboard.getText() 
        ADDON.setSetting('pass',pwd_input)
    else:
        Exit()

user = ADDON.getSetting('user')
Пример #13
0
def MFACheck(br, email, soup):
    Log('MFA, DCQ or Captcha form')
    uni_soup = soup.__unicode__()
    if 'signIn' in [i.name for i in br.forms()]:
        br.select_form(name='signIn')
    else:
        br.select_form(nr=0)

    if 'auth-mfa-form' in uni_soup:
        msg = soup.find('form', attrs={'id': 'auth-mfa-form'})
        msgtxt = msg.p.renderContents().strip()
        kb = xbmc.Keyboard('', msgtxt)
        kb.doModal()
        if kb.isConfirmed() and kb.getText():
            br['otpCode'] = kb.getText()
        else:
            return False
    elif 'ap_dcq_form' in uni_soup:
        msg = soup.find('div', attrs={'id': 'message_warning'})
        Dialog.ok(pluginname, msg.p.contents[0].strip())
        dcq = soup.find('div', attrs={'id': 'ap_dcq1a_pagelet'})
        dcq_title = dcq.find('div', attrs={
            'id': 'ap_dcq1a_pagelet_title'
        }).h1.contents[0].strip()
        q_title = []
        q_id = []
        for q in dcq.findAll('div', attrs={'class': 'dcq_question'}):
            if q.span.label:
                label = q.span.label.renderContents().strip().replace(
                    '  ', '').replace('\n', '')
                if q.span.label.span:
                    label = label.replace(str(q.span.label.span),
                                          q.span.label.span.text)
                q_title.append(insertLF(label))
                q_id.append(q.input['id'])

        sel = Dialog.select(insertLF(dcq_title, 60),
                            q_title) if len(q_title) > 1 else 0
        if sel < 0:
            return False

        ret = Dialog.input(q_title[sel])
        if ret:
            br[q_id[sel]] = ret
        else:
            return False
    elif ('ap_captcha_img_label'
          in uni_soup) or ('auth-captcha-image-container' in uni_soup):
        wnd = Captcha((getString(30008).split('.')[0]), soup, email)
        wnd.doModal()
        if wnd.email and wnd.cap and wnd.pwd:
            br['email'] = wnd.email
            br['password'] = wnd.pwd
            br['guess'] = wnd.cap
        else:
            return False
        del wnd
    elif 'claimspicker' in uni_soup:
        msg = soup.find('form', attrs={'name': 'claimspicker'})
        cs_title = msg.find('div', attrs={'class': 'a-row a-spacing-small'})
        cs_title = cs_title.h1.contents[0].strip()
        cs_quest = msg.find('label', attrs={'class': 'a-form-label'})
        cs_hint = msg.find('div', attrs={'class': 'a-row'}).contents[0].strip()
        choices = []
        if cs_quest:
            for c in soup.findAll('div', attrs={'data-a-input-name':
                                                'option'}):
                choices.append((c.span.contents[0].strip(), c.input['name'],
                                c.input['value']))
            sel = Dialog.select(
                '%s - %s' % (cs_title, cs_quest.contents[0].strip()),
                [k[0] for k in choices])
        else:
            sel = 100 if Dialog.ok(cs_title, cs_hint) else -1

        if sel > -1:
            if sel < 100:
                br[choices[sel][1]] = [choices[sel][2]]
        else:
            return False
    elif 'fwcim-form' in uni_soup:
        msg = soup.find('div',
                        attrs={
                            'class':
                            'a-row a-spacing-micro cvf-widget-input-code-label'
                        }).contents[0].strip()
        ret = Dialog.input(msg)
        if ret:
            br['code'] = ret
        else:
            return False
    return br
Пример #14
0
def LogIn(ask):
    user = loadUser()
    email = user['email']
    password = decode(user['password'])
    savelogin = var.addon.getSetting('save_login') == 'true'
    useMFA = False
    if ask and var.multiuser:
        email = ''

    if ask:
        keyboard = xbmc.Keyboard(email, getString(30002))
        keyboard.doModal()
        if keyboard.isConfirmed() and keyboard.getText():
            email = keyboard.getText()
            password = setLoginPW()
    else:
        if not email or not password:
            Dialog.notification(getString(30200), getString(30216))
            xbmc.executebuiltin('Addon.OpenSettings(%s)' %
                                var.addon.getAddonInfo('id'))
            return False

    if password:
        cj = requests.cookies.RequestsCookieJar()
        br = mechanize.Browser()
        br.set_handle_robots(False)
        br.set_cookiejar(cj)
        br.set_handle_gzip(True)
        caperr = -5
        while caperr:
            Log('Connect to SignIn Page %s attempts left' % -caperr)
            br.addheaders = [('User-Agent', getConfig('UserAgent'))]
            br.open(BaseUrl + '/gp/aw/si.html')
            response = br.response().read()
            if 'signIn' not in [i.name for i in br.forms()]:
                getUA(True)
                caperr += 1
                WriteLog(response, 'login-si')
                xbmc.sleep(randint(750, 1500))
            else:
                break
        else:
            Dialog.ok(getString(30200), getString(30213))
            return False

        br.select_form(name='signIn')
        br['email'] = email
        br['password'] = password
        br.addheaders = [(
            'Accept',
            'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        ), ('Accept-Encoding', 'gzip, deflate'),
                         ('Accept-Language', 'de,en-US;q=0.8,en;q=0.6'),
                         ('Cache-Control', 'max-age=0'),
                         ('Connection', 'keep-alive'),
                         ('Content-Type', 'application/x-www-form-urlencoded'),
                         ('Host', BaseUrl.split('//')[1]), ('Origin', BaseUrl),
                         ('User-Agent', getConfig('UserAgent')),
                         ('Upgrade-Insecure-Requests', '1')]
        br.submit()
        response, soup = parseHTML(br)
        WriteLog(response, 'login')

        while any(s in response for s in [
                'auth-mfa-form', 'ap_dcq_form', 'ap_captcha_img_label',
                'claimspicker', 'fwcim-form', 'auth-captcha-image-container'
        ]):
            br = MFACheck(br, email, soup)
            if not br:
                return False
            useMFA = 'otpCode' in str(list(br.forms())[0])
            br.submit()
            response, soup = parseHTML(br)
            WriteLog(response, 'login-mfa')

        if 'action=sign-out' in response:
            try:
                usr = re.search(r'config.customerName[^"]*"([^"]*)',
                                response).group(1)
            except AttributeError:
                usr = getString(30209)

            if not ask:
                usr = user['name']

            if var.multiuser and ask:
                usr = Dialog.input(getString(30179), usr).decode('utf-8')
                if not usr:
                    return False
            if useMFA:
                var.addon.setSetting('save_login', 'false')
                savelogin = False

            user = loadUser(True)
            user['name'] = usr

            if savelogin:
                user['email'] = email
                user['password'] = encode(password)
            else:
                user['cookie'] = pickle.dumps(cj)

            if ask:
                remLoginData(False)
                var.addon.setSetting('login_acc', usr)
                if not var.multiuser:
                    Dialog.ok(getString(30215),
                              '{0} {1}'.format(getString(30014), usr))

            addUser(user)
            gen_id()
            return cj
        elif 'message_error' in response:
            writeConfig('login_pass', '')
            msg = soup.find('div', attrs={'id': 'message_error'})
            Log('Login Error: %s' % msg.p.renderContents(None).strip())
            Dialog.ok(getString(30200), getString(30201))
        elif 'message_warning' in response:
            msg = soup.find('div', attrs={'id': 'message_warning'})
            Log('Login Warning: %s' % msg.p.renderContents(None).strip())
        elif 'auth-error-message-box' in response:
            msg = soup.find('div', attrs={'class': 'a-alert-content'})
            Log('Login MFA: %s' % msg.ul.li.span.renderContents(None).strip())
            Dialog.ok(getString(30200), getString(30214))
        else:
            Dialog.ok(getString(30200), getString(30213))

    return False
Пример #15
0
set_property('Weekend.IsFetched', '')
set_property('36Hour.IsFetched', '')
set_property('Hourly.IsFetched', 'true')
set_property('NOAA.IsFetched', 'true')
set_property('WeatherProvider', 'NOAA')
set_property(
    'WeatherProviderLogo',
    xbmc.translatePath(os.path.join(CWD, 'resources', 'graphics',
                                    'banner.png')))

if sys.argv[1].startswith('Location'):
    log("argument: %s" % (sys.argv[1]))
    text = ADDON.getSetting(sys.argv[1] + "LatLong")
    if text == '':
        # request lattitude,longitude
        keyboard = xbmc.Keyboard('', LANGUAGE(32332), False)
        keyboard.doModal()
        if (keyboard.isConfirmed() and keyboard.getText() != ''):
            text = keyboard.getText()
    if text != '':
        log("calling location with %s and %s" % (text, sys.argv[1]))
        fetchLocation(text, sys.argv[1])
else:

    num = sys.argv[1]
    locationLatLong = ADDON.getSetting('Location%sLatLong' % num)

    station = ADDON.getSetting('Location' + str(num) + 'Station')
    if station == '':
        log("calling location with %s" % (locationLatLong))
        fetchLocation(locationLatLong, 'Location%s' % str(num))
Пример #16
0
def _get_keyboard(default="", heading="", hidden=False):
    keyboard = xbmc.Keyboard(default, heading, hidden)
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        return unicode(keyboard.getText(), "utf-8")
    return default
Пример #17
0
ADDON = xbmcaddon.Addon(id='plugin.video.NUKEprivate')
country=os.path.join(ADDON.getAddonInfo('path'),'resources','country')
print country
def OPEN_URL(url):
    req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) 
    con = urllib2.urlopen( req )
    link= con.read()
    return link


if ADDON.getSetting('user')=='':
    dialog = xbmcgui.Dialog()
    dialog.ok("NUKE Streams", "You Now Need To Input", "Your [COLOR yellow]Username[/COLOR]")
    search_entered = ''
    keyboard = xbmc.Keyboard(search_entered, 'NUKE Streams')
    keyboard.doModal()
    if keyboard.isConfirmed():
        search_entered = keyboard.getText() 
    ADDON.setSetting('user',search_entered)
    
if ADDON.getSetting('pass')=='':
    dialog = xbmcgui.Dialog()
    dialog.ok("NUKE Streams", "You Now Need To Input", "Your [COLOR yellow]Password[/COLOR]")
    search_entered = ''
    keyboard = xbmc.Keyboard(search_entered, 'NUKE Streams')
    keyboard.doModal()
    if keyboard.isConfirmed():
        search_entered = keyboard.getText() 
    ADDON.setSetting('pass',search_entered)
    link=open(country).read()
Пример #18
0
ADDON        = xbmcaddon.Addon()
ADDONID      = ADDON.getAddonInfo('id')
ADDONVERSION = ADDON.getAddonInfo('version')
LANGUAGE     = ADDON.getLocalizedString
CWD          = ADDON.getAddonInfo('path').decode("utf-8")
RESOURCE   = xbmc.translatePath( os.path.join( CWD, 'resources', 'lib' ).encode("utf-8") ).decode("utf-8")

sys.path.append(RESOURCE)


if ( __name__ == "__main__" ):
    searchstring = None
    try:
        params = dict( arg.split( "=" ) for arg in sys.argv[ 1 ].split( "&" ) )
    except:
        params = {}
    searchstring = params.get("searchstring",'')
    searchstring = urllib.unquote_plus(searchstring)
    if searchstring == '':
        keyboard = xbmc.Keyboard( '', LANGUAGE(32101), False )
        keyboard.doModal()
        if ( keyboard.isConfirmed() ):
            searchstring = keyboard.getText()
    else:
        del params['searchstring']
    if searchstring:
        import gui
        ui = gui.GUI( "script-globalsearch-main.xml", CWD, "Default", searchstring=searchstring, params=params )
        ui.doModal()
        del ui
Пример #19
0
    def onClick(self, controlID):

        self.oe.dbg_log('oeWindows::onClick', 'enter_function', 0)

        try:

            for btn in self.buttons:
                if controlID == self.buttons[btn]['id']:
                    modul = self.buttons[btn]['modul']
                    action = self.buttons[btn]['action']
                    if hasattr(self.oe.dictModules[modul], action):
                        if getattr(self.oe.dictModules[modul],
                                   action)() == 'close':
                            self.close()
                        return

            if controlID in self.guiLists:
                selectedPosition = \
                    self.getControl(controlID).getSelectedPosition()
                selectedMenuItem = \
                    self.getControl(self.guiMenList).getSelectedItem()
                selectedItem = \
                    self.getControl(controlID).getSelectedItem()
                strTyp = selectedItem.getProperty('typ')
                strValue = selectedItem.getProperty('value')

                if strTyp == 'multivalue':
                    select_window = selectWindow('selectWindow.xml',
                                                 self.oe.__cwd__,
                                                 'Default',
                                                 oeMain=self.oe)
                    select_window.defaultValue = strValue
                    select_window.availValues = \
                        selectedItem.getProperty('values')
                    select_window.doModal()
                    selectedItem.setProperty('value', select_window.result)
                    del select_window
                elif strTyp == 'text':

                    xbmcKeyboard = xbmc.Keyboard(strValue)
                    result_is_valid = False
                    while not result_is_valid:
                        xbmcKeyboard.doModal()

                        if xbmcKeyboard.isConfirmed():
                            result_is_valid = True
                            validate_string = \
                                selectedItem.getProperty('validate')
                            if validate_string != '':
                                if not re.search(validate_string,
                                                 xbmcKeyboard.getText()):
                                    result_is_valid = False
                        else:
                            result_is_valid = True

                    if xbmcKeyboard.isConfirmed():
                        selectedItem.setProperty('value',
                                                 xbmcKeyboard.getText())

                elif strTyp == 'file':

                    xbmcDialog = xbmcgui.Dialog()
                    returnValue = xbmcDialog.browse(
                        1,
                        'OpenELEC.tv',
                        'files',
                        '',
                        False,
                        False,
                        '/',
                    )
                    if returnValue != '' and returnValue != '/':
                        selectedItem.setProperty('value', unicode(returnValue))

                elif strTyp == 'folder':

                    xbmcDialog = xbmcgui.Dialog()
                    returnValue = xbmcDialog.browse(
                        0,
                        'OpenELEC.tv',
                        'files',
                        '',
                        False,
                        False,
                        '/storage',
                    )
                    if returnValue != '' and returnValue != '/':
                        selectedItem.setProperty('value', unicode(returnValue))

                elif strTyp == 'ip':

                    xbmcDialog = xbmcgui.Dialog()
                    returnValue = xbmcDialog.numeric(3, 'OpenELEC.tv',
                                                     strValue)
                    if returnValue != '':
                        if returnValue == '0.0.0.0':
                            selectedItem.setProperty('value', '')
                        else:
                            selectedItem.setProperty('value', returnValue)
                elif strTyp == 'num':

                    if strValue == 'None' or strValue == '':
                        strValue = '0'

                    xbmcDialog = xbmcgui.Dialog()
                    returnValue = xbmcDialog.numeric(0, 'OpenELEC.tv',
                                                     strValue)
                    if returnValue == '':
                        returnValue = -1

                    if returnValue > -1:
                        selectedItem.setProperty('value', unicode(returnValue))
                elif strTyp == 'bool':

                    strValue = strValue.lower()

                    if strValue == '0':
                        selectedItem.setProperty('value', '1')
                    elif strValue == '1':
                        selectedItem.setProperty('value', '0')
                    elif strValue == 'true':
                        selectedItem.setProperty('value', 'false')
                    elif strValue == 'false':
                        selectedItem.setProperty('value', 'true')
                    else:
                        selectedItem.setProperty('value', '1')

                if selectedItem.getProperty('action') != '':
                    if hasattr(
                            self.oe.dictModules[selectedMenuItem.getProperty(
                                'modul')], selectedItem.getProperty('action')):
                        getattr(
                            self.oe.dictModules[selectedMenuItem.getProperty(
                                'modul')], selectedItem.getProperty('action'))(
                                    listItem=selectedItem)
                        self.emptyButtonLabels()

                self.lastMenu = -1
                self.onFocus(self.guiMenList)

                self.setFocusId(controlID)
                self.getControl(controlID).selectItem(selectedPosition)

            self.oe.dbg_log('oeWindows::onClick', 'exit_function', 0)
        except Exception, e:

            self.oe.dbg_log(
                'oeWindows.mainWindow::onClick(' + unicode(controlID) + ')',
                'ERROR: (' + repr(e) + ')')
Пример #20
0
            log('failed to save satellite image')

log('version %s started: %s' % (__version__, sys.argv))
log('lang: %s' % LANGUAGE)
log('speed: %s' % SPEEDUNIT)
log('temp: %s' % TEMPUNIT[1])
log('time: %s' % TIMEFORMAT)
log('date: %s' % DATEFORMAT)

set_property('WeatherProvider', __addonname__)
set_property(
    'WeatherProviderLogo',
    xbmc.translatePath(os.path.join(__cwd__, 'resources', 'banner.png')))

if sys.argv[1].startswith('Location'):
    keyboard = xbmc.Keyboard('', xbmc.getLocalizedString(14024), False)
    keyboard.doModal()
    if (keyboard.isConfirmed() and keyboard.getText() != ''):
        text = keyboard.getText()
        locations, locationids = location(text)
        dialog = xbmcgui.Dialog()
        if locations != []:
            selected = dialog.select(xbmc.getLocalizedString(396), locations)
            if selected != -1:
                __addon__.setSetting('Enabled', 'true')
                __addon__.setSetting(sys.argv[1], locations[selected])
                __addon__.setSetting(sys.argv[1] + 'id', locationids[selected])
                log('selected location: %s' % locations[selected])
                log('selected location id: %s' % locationids[selected])
        else:
            dialog.ok(__addonname__, xbmc.getLocalizedString(284))
Пример #21
0
    def handle(self):
        try:
            params = self.argv[0]
        except:
            params = {}

        try:
            is_united_search = int(params['is_united'])
        except:
            is_united_search = 0

        try:
            page = int(params['page'])
        except:
            params['page'] = 0
            page = 0
        history = []
        try:
            req_count = int(xbmcup.app.setting['search_history'])
        except:
            req_count = 0

        try:
            usersearch = params['usersearch']
            vsearch = params['vsearch']
        except:
            history = []

            if (req_count > 0):
                SQL.set(
                    'create table if not exists search(id INTEGER PRIMARY KEY AUTOINCREMENT, value varchar(255) unique)'
                )
                history = SQL.get(
                    'SELECT id,value FROM search ORDER BY ID DESC')
            else:
                SQL.set('DELETE FROM search')

            if (len(history)):
                history = list(history)
                values = [
                    '[COLOR yellow]' + xbmcup.app.lang[30108] + '[/COLOR]'
                ]
                for item in history:
                    values.append(item[1])
                ret = xbmcup.gui.select(xbmcup.app.lang[30161], values)

                if ret == None:
                    return

                if (ret > 0):
                    usersearch = values[ret]
                    vsearch = usersearch.encode('utf-8').decode('utf-8')
                    params['vsearch'] = vsearch
                    params['usersearch'] = urllib.quote_plus(
                        usersearch.encode('utf-8'))
                else:
                    params['vsearch'] = ''
            else:
                params['vsearch'] = ''

            if (params['vsearch'] == ''):
                keyboard = xbmc.Keyboard()
                keyboard.setHeading(xbmcup.app.lang[30112])
                keyboard.doModal()
                usersearch = keyboard.getText(0)
                vsearch = usersearch.decode('utf-8')
                params['vsearch'] = vsearch
                params['usersearch'] = urllib.quote_plus(usersearch)

        if not usersearch: return
        try:
            SQL.set('INSERT INTO search (value) VALUES ("%s")' % (vsearch))
        except sqlite.IntegrityError:
            SQL.set('DELETE FROM search WHERE `value` = "%s"' % (vsearch))
            SQL.set('INSERT INTO search (value) VALUES ("%s")' % (vsearch))
        except:
            pass

        if (len(history) >= req_count):
            SQL.set(
                'DELETE FROM search WHERE `id` = (SELECT MIN(id) FROM search)')

        #page_url = "search/index/index/usersearch/"+params['usersearch']
        page_url = "/engine/ajax/sphinx_search.php?story=%s&search_start=%s" % (
            params['usersearch'], page + 1)
        md5 = hashlib.md5()
        #md5.update(page_url+'/page/'+str(page))
        md5.update(params['usersearch'].encode('utf8') + '?v=' +
                   xbmcup.app.addon['version'])
        response = CACHE(str(md5.hexdigest()), self.get_movies, page_url, page,
                         '', False, usersearch)

        if (is_united_search == 0):
            self.item(u'[COLOR yellow]' + xbmcup.app.lang[30108] + '[/COLOR]',
                      self.link('search'),
                      folder=True,
                      cover=cover.search)
            self.item('[COLOR blue][' + xbmcup.app.lang[30109] + ': ' +
                      vsearch + '][/COLOR]',
                      self.link('null'),
                      folder=False,
                      cover=cover.info)

        if (is_united_search == 0 and response['page']['pagenum'] > 1):
            params['page'] = page - 1
            self.item('[COLOR green]' + xbmcup.app.lang[30106] + '[/COLOR]',
                      self.replace('search', params),
                      cover=cover.prev,
                      folder=True)
            params['page'] = page + 1

        self.add_movies(response)

        params['page'] = page + 1
        if (is_united_search == 0):
            if (response['page']['maxpage'] >=
                    response['page']['pagenum'] + 1):
                self.item(u'[COLOR green]' + xbmcup.app.lang[30107] +
                          '[/COLOR]',
                          self.replace('search', params),
                          cover=cover.next,
                          folder=True)
            'do': 'login',
            'securitytoken': 'guest',
            'url': 'http://www.ppvbay.com/forum.php',
            's': ''
        })
    net.save_cookies(cookie_file)
    net.set_cookies(cookie_file)


if user == '' or passw == '':
    dialog = xbmcgui.Dialog()
    ret = dialog.yesno('PPV Bay', 'Please enter your account details',
                       'or register if you dont have an account',
                       'at http://www.ppvbay.com/', 'Cancel', 'Login')
    if ret == 1:
        keyb = xbmc.Keyboard('', 'Enter Username')
        keyb.doModal()
        if (keyb.isConfirmed()):
            username = keyb.getText()
            keyb = xbmc.Keyboard('', 'Enter Password:'******'username', username)
                selfAddon.setSetting('password', password)


def MainMenu():
    setCookie('http://www.ppvbay.com/forum.php')
    net.set_cookies(cookie_file)
    response = net.http_GET('http://www.ppvbay.com/forum.php')
Пример #23
0
    def onClick(self, controlID):
        if (controlID == 5101):  # Close window button
            self.close()
        elif (controlID == 5110):  # Import games
            self.close()
            self.gui.updateDB()
        elif (controlID == 5121):  # Rescrape single games
            self.close()

            if (self.selectedGame == None or self.gameRow == None):
                xbmcgui.Dialog().ok(util.SCRIPTNAME, util.localize(35013),
                                    util.localize(35014))
                return

            romCollectionId = self.gameRow[util.GAME_romCollectionId]
            romCollection = self.gui.config.romCollections[str(
                romCollectionId)]
            files = File(self.gui.gdb).getRomsByGameId(
                self.gameRow[util.ROW_ID])
            filename = files[0][0]
            romCollection.romPaths = (filename, )

            romCollections = {}
            romCollections[romCollection.id] = romCollection

            self.gui.rescrapeGames(romCollections)

        elif (controlID == 5122):  # Rescrape selection
            self.close()

            romCollections = {}
            listSize = self.gui.getListSize()
            for i in range(0, listSize):
                selectedGame, gameRow = self.gui.getGameByPosition(
                    self.gui.gdb, i)

                romCollectionId = gameRow[util.GAME_romCollectionId]

                try:
                    romCollection = romCollections[str(romCollectionId)]
                except:
                    romCollection = self.gui.config.romCollections[str(
                        romCollectionId)]
                    romCollection.romPaths = []

                files = File(self.gui.gdb).getRomsByGameId(
                    gameRow[util.ROW_ID])
                filename = files[0][0]
                romCollection.romPaths.append(filename)
                romCollections[romCollection.id] = romCollection

            self.gui.rescrapeGames(romCollections)

            #self.gui.updateDB()
        elif (controlID == 5111):  # add Rom Collection
            self.close()
            statusOk, errorMsg = wizardconfigxml.ConfigXmlWizard(
            ).addRomCollection(self.gui.config)
            if (statusOk == False):
                xbmcgui.Dialog().ok(util.SCRIPTNAME, util.localize(35001),
                                    errorMsg)
                Logutil.log('Error updating config.xml: ' + errorMsg,
                            util.LOG_LEVEL_INFO)
                return

            #update self.config
            statusOk, errorMsg = self.gui.config.readXml()
            if (statusOk == False):
                xbmcgui.Dialog().ok(util.SCRIPTNAME, util.localize(35002),
                                    errorMsg)
                Logutil.log('Error reading config.xml: ' + errorMsg,
                            util.LOG_LEVEL_INFO)
                return

            #import Games
            self.gui.updateDB()

        elif (controlID == 5112):  # edit Rom Collection
            self.close()
            constructorParam = "720p"
            editRCdialog = dialogeditromcollection.EditRomCollectionDialog(
                "script-RCB-editromcollection.xml",
                util.getAddonInstallPath(),
                "Default",
                constructorParam,
                gui=self.gui)
            del editRCdialog

            self.gui.config = Config(None)
            self.gui.config.readXml()

        elif (controlID == 5117):  # edit scraper
            self.close()
            constructorParam = "720p"
            editscraperdialog = dialogeditscraper.EditOfflineScraper(
                "script-RCB-editscraper.xml",
                util.getAddonInstallPath(),
                "Default",
                constructorParam,
                gui=self.gui)
            del editscraperdialog

            self.gui.config = Config(None)
            self.gui.config.readXml()

        elif (controlID == 5113):  #Edit Game Command
            self.close()

            if (self.selectedGame == None or self.gameRow == None):
                xbmcgui.Dialog().ok(util.SCRIPTNAME, util.localize(35015),
                                    util.localize(35014))
                return

            origCommand = self.gameRow[util.GAME_gameCmd]
            command = ''

            romCollectionId = self.gameRow[util.GAME_romCollectionId]
            romCollection = self.gui.config.romCollections[str(
                romCollectionId)]
            if (romCollection.useBuiltinEmulator):
                success, selectedcore = self.selectlibretrocore(
                    romCollection.name)
                if success:
                    command = selectedcore
                else:
                    Logutil.log(
                        "No libretro core was chosen. Won't update game command.",
                        util.LOG_LEVEL_INFO)
                    return
            else:
                keyboard = xbmc.Keyboard()
                keyboard.setHeading(util.localize(40035))
                if (origCommand != None):
                    keyboard.setDefault(origCommand)
                keyboard.doModal()
                if (keyboard.isConfirmed()):
                    command = keyboard.getText()

            if (command != origCommand):
                Logutil.log(
                    "Updating game '%s' with command '%s'" %
                    (str(self.gameRow[util.ROW_NAME]), command),
                    util.LOG_LEVEL_INFO)
                Game(self.gui.gdb).update(('gameCmd', ), (command, ),
                                          self.gameRow[util.ROW_ID], True)
                self.gui.gdb.commit()

        elif (controlID == 5118):  #(Un)Mark as Favorite
            self.close()

            if (self.selectedGame == None or self.gameRow == None):
                xbmcgui.Dialog().ok(util.SCRIPTNAME, util.localize(35016),
                                    util.localize(35014))
                return

            isFavorite = 1
            if (self.gameRow[util.GAME_isFavorite] == 1):
                isFavorite = 0

            Logutil.log(
                "Updating game '%s' set isFavorite = %s" %
                (str(self.gameRow[util.ROW_NAME]), str(isFavorite)),
                util.LOG_LEVEL_INFO)
            Game(self.gui.gdb).update(('isFavorite', ), (isFavorite, ),
                                      self.gameRow[util.ROW_ID], True)
            self.gui.gdb.commit()

            if (isFavorite == 0):
                isFavorite = ''
            self.selectedGame.setProperty('isfavorite', str(isFavorite))

        elif (controlID == 5119):  #(Un)Mark as Favorite
            self.close()

            if (self.selectedGame == None or self.gameRow == None):
                xbmcgui.Dialog().ok(util.SCRIPTNAME, util.localize(35016),
                                    util.localize(35014))
                return

            isFavorite = 1
            if (self.gameRow[util.GAME_isFavorite] == 1):
                isFavorite = 0

            listSize = self.gui.getListSize()
            for i in range(0, listSize):

                selectedGame, gameRow = self.gui.getGameByPosition(
                    self.gui.gdb, i)

                Logutil.log(
                    "Updating game '%s' set isFavorite = %s" %
                    (str(gameRow[util.ROW_NAME]), str(isFavorite)),
                    util.LOG_LEVEL_INFO)
                Game(self.gui.gdb).update(('isFavorite', ), (isFavorite, ),
                                          gameRow[util.ROW_ID], True)
                selectedGame.setProperty('isfavorite', str(isFavorite))
            self.gui.gdb.commit()

        elif (controlID == 5120):  #Export nfo files
            self.close()
            nfowriter.NfoWriter().exportLibrary(self.gui)

        elif (controlID == 5114):  #Delete Rom
            self.close()

            pos = self.gui.getCurrentListPosition()
            if (pos == -1):
                xbmcgui.Dialog().ok(util.SCRIPTNAME, util.localize(35017),
                                    util.localize(35018))
                return
            dialog = xbmcgui.Dialog()
            if dialog.yesno(util.localize(51010), util.localize(40036)):
                gameID = self.gui.getGameId(self.gui.gdb, pos)
                self.gui.deleteGame(gameID)
                self.gui.showGames()
                if (pos > 0):
                    pos = pos - 1
                    self.gui.setFilterSelection(
                        self.gui.CONTROL_GAMES_GROUP_START, pos)
                else:
                    self.gui.setFilterSelection(
                        self.gui.CONTROL_GAMES_GROUP_START, 0)

        elif (controlID == 5115):  #Remove Rom Collection
            self.close()

            constructorParam = "720p"
            removeRCDialog = dialogdeleteromcollection.RemoveRCDialog(
                "script-RCB-removeRC.xml",
                util.getAddonInstallPath(),
                "Default",
                constructorParam,
                gui=self.gui)
            rDelStat = removeRCDialog.getDeleteStatus()
            if (rDelStat):
                selectedRCId = removeRCDialog.getSelectedRCId()
                rcDelStat = removeRCDialog.getRCDeleteStatus()
                self.gui.deleteRCGames(selectedRCId, rcDelStat, rDelStat)
                del removeRCDialog

        elif (controlID == 5116):  #Clean DB
            self.close()
            self.gui.cleanDB()

        elif (controlID == 5223):  #Open Settings
            self.close()
            self.gui.Settings.openSettings()
Пример #24
0
def get_response(img, cookie):
    #on telecharge l'image
    PathCache = xbmc.translatePath(
        xbmcaddon.Addon('plugin.video.vstream').getAddonInfo("profile"))
    filename = os.path.join(PathCache, 'Captcha.raw').decode("utf-8")

    headers2 = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0',
        #'Referer' : url ,
        'Host': 'protect.ddl-island.su',
        'Accept': 'image/png,image/*;q=0.8,*/*;q=0.5',
        'Accept-Language': 'fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4',
        'Accept-Encoding': 'gzip, deflate',
        #'Content-Type' : 'application/x-www-form-urlencoded',
        'Cookie': cookie
    }

    try:
        req = urllib2.Request(img, None, headers2)
        image_on_web = urllib2.urlopen(req)
        if image_on_web.headers.maintype == 'image':
            buf = image_on_web.read()
            downloaded_image = file(filename, "wb")
            downloaded_image.write(buf)
            downloaded_image.close()
            image_on_web.close()
        else:
            return ''
    except:
        return ''

    #on affiche le dialogue
    solution = ''

    if (True):
        ####nouveau captcha
        try:
            ##affichage du dialog perso
            class XMLDialog(xbmcgui.WindowXMLDialog):
                #"""
                #Dialog class for captcha
                #"""
                def __init__(self, *args, **kwargs):
                    xbmcgui.WindowXMLDialog.__init__(self)
                    pass

                def onInit(self):
                    #image background captcha
                    self.getControl(1).setImage(filename.encode("utf-8"),
                                                False)
                    #image petit captcha memory fail
                    self.getControl(2).setImage(filename.encode("utf-8"),
                                                False)
                    self.getControl(2).setVisible(False)
                    ##Focus clavier
                    self.setFocus(self.getControl(21))

                def onClick(self, controlId):
                    if controlId == 20:
                        #button Valider
                        solution = self.getControl(5000).getLabel()
                        xbmcgui.Window(10101).setProperty(
                            'captcha', str(solution))
                        self.close()
                        return

                    elif controlId == 30:
                        #button fermer
                        self.close()
                        return

                    elif controlId == 21:
                        #button clavier
                        self.getControl(2).setVisible(True)
                        kb = xbmc.Keyboard(
                            self.getControl(5000).getLabel(), '', False)
                        kb.doModal()

                        if (kb.isConfirmed()):
                            self.getControl(5000).setLabel(kb.getText())
                            self.getControl(2).setVisible(False)
                        else:
                            self.getControl(2).setVisible(False)

                def onFocus(self, controlId):
                    self.controlId = controlId

                def _close_dialog(self):
                    self.close()

                def onAction(self, action):
                    #touche return 61448
                    if action.getId() in (9, 10, 11, 30, 92, 216, 247, 257,
                                          275, 61467, 61448):
                        self.close()

            wd = XMLDialog('DialogCaptcha.xml',
                           cConfig().getAddonPath().decode("utf-8"), 'default',
                           '720p')
            wd.doModal()
            del wd
        finally:

            solution = xbmcgui.Window(10101).getProperty('captcha')
            if solution == '':
                cConfig().showInfo("Erreur", 'Vous devez taper le captcha', 4)

    else:
        #ancien Captcha
        try:
            img = xbmcgui.ControlImage(450, 0, 400, 130,
                                       filename.encode("utf-8"))
            wdlg = xbmcgui.WindowDialog()
            wdlg.addControl(img)
            wdlg.show()
            #xbmc.sleep(3000)
            kb = xbmc.Keyboard('', 'Tapez les Lettres/chiffres de l\'image',
                               False)
            kb.doModal()
            if (kb.isConfirmed()):
                solution = kb.getText()
                if solution == '':
                    cConfig().showInfo("Erreur", 'Vous devez taper le captcha',
                                       4)
            else:
                cConfig().showInfo("Erreur", 'Vous devez taper le captcha', 4)
        finally:
            wdlg.removeControl(img)
            wdlg.close()

    return solution
Пример #25
0
 def Keyboard(self, default="", heading="", hidden=False):
     keyboard = xbmc.Keyboard(default, getLocalizedLabel(heading), hidden)
     keyboard.doModal()
     if keyboard.isConfirmed():
         return keyboard.getText()
Пример #26
0
 def __init__(self, *args, **kwargs):
     self.cptloc = kwargs.get('captcha')
     self.img = xbmcgui.ControlImage(335,30,624,60,self.cptloc)
     self.addControl(self.img)
     self.kbd = xbmc.Keyboard()
Пример #27
0
    def onClick(self, controlID):
        if controlID in [7, 99]: #cancel buttons Krypton(7) / Pre-Krypton(99)
            return self.closeDialog()
            
        if controlID == 6 or controlID == 3:
            num = self.favList.getSelectedPosition()

            if num >= 0:
                favPath  = self.favList.getSelectedItem().getProperty('Path')
                favLabel = self.favList.getSelectedItem().getLabel()
                favIcon  = self.favList.getSelectedItem().getProperty('Icon')
                isFolder = self.favList.getSelectedItem().getProperty('IsFolder')

                if not isFolder:
                    fanart = self.favList.getSelectedItem().getProperty('Fanart')
                    desc   = self.favList.getSelectedItem().getProperty('Desc')
                    mode   = self.favList.getSelectedItem().getProperty('Mode')

                    favPath = favourite.updateSFOption(favPath, 'fanart', fanart)
                    favPath = favourite.updateSFOption(favPath, 'desc',   desc)
                    favPath = favourite.updateSFOption(favPath, 'mode',   mode)

                favLabel = utils.fix(favLabel)
                if favLabel.endswith(GETTEXT(30102)):
                    favLabel = favLabel.replace(GETTEXT(30102), '')
                if favLabel.endswith(GETTEXT(30236)):
                    favLabel = favLabel.replace(GETTEXT(30236), '')

                if isFolder:
                    if isFolder.lower() == 'true':
                        self.changeFolder(favPath)
                        return
                    if isFolder.lower() == 'open':
                        cmd  = 'ActivateWindow(10025,"plugin://'
                        cmd += utils.ADDONID + '/?'
                        cmd += 'label=%s&' % urllib.quote_plus(favLabel)
                        cmd += 'folder=%s' % urllib.quote_plus(favPath)
                        cmd += '",return)'
                        favPath = cmd
                    if isFolder.lower() == 'play':
                        cmd  = 'PlayMedia("plugin://'
                        cmd += utils.ADDONID + '/?'
                        cmd += 'label=%s&' % urllib.quote_plus(favLabel)
                        cmd += 'mode=%s&'  % urllib.quote_plus('5400')
                        cmd += 'folder=%s' % urllib.quote_plus(favPath)
                        cmd += '")'
                        favPath = cmd                        
                
                if self.changeTitle:
                    keyboard = xbmc.Keyboard(favLabel, xbmc.getLocalizedString(528), False)
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        favLabel = keyboard.getText()

                if favPath.lower().startswith('activatewindow') and '?' in favPath:
                    text    = '?content_type=%s&' % urllib.quote_plus('Chooser')
                    favPath = favPath.replace('?', text)
                        
                xbmc.executebuiltin('Skin.SetString(%s,%s)' % ( '%s.%s' % ( self.property, 'Path'),   favPath.decode('string-escape')))
                xbmc.executebuiltin('Skin.SetString(%s,%s)' % ( '%s.%s' % ( self.property, 'Label'), favLabel))
               
                if favIcon:
                    xbmc.executebuiltin('Skin.SetString(%s,%s)' % ('%s.%s' % (self.property, 'Icon'), favIcon))
                    
                if isFolder:
                    xbmc.executebuiltin('Skin.SetString(%s,%s)' % ('%s.%s' % (self.property, 'IsFolder'), 'true'))
                else:
                    xbmc.executebuiltin('Skin.SetString(%s,%s)' % ('%s.%s' % (self.property, 'IsFolder'), 'false'))
                    
            else:
                xbmc.executebuiltin('Skin.Reset(%s)' % '%s.%s' % ( self.property, 'Path'))
                xbmc.executebuiltin('Skin.Reset(%s)' % '%s.%s' % ( self.property, 'Label'))
                xbmc.executebuiltin('Skin.Reset(%s)' % '%s.%s' % ( self.property, 'Icon'))
                xbmc.executebuiltin('Skin.Reset(%s)' % '%s.%s' % ( self.property, 'IsFolder'))

            try:    count = int(xbmcgui.Window(10000).getProperty('Super_Favourites_Count'))
            except: count = 0    
            xbmcgui.Window(10000).setProperty('Super_Favourites_Count', str(count+1))
            xbmcgui.Window(10000).setProperty('Super_Favourites_Chooser', 'false')
                
            xbmc.sleep(300)
            self.close()
Пример #28
0
def play_video(item,
               desdefavoritos=False,
               desdedescargados=False,
               desderrordescargas=False,
               strmfile=False):
    from servers import servertools
    import sys
    import xbmcgui, xbmc

    logger.info("[xbmctools.py] play_video")
    logger.info(item.tostring())

    try:
        item.server = item.server.lower()
    except:
        item.server = ""

    if item.server == "":
        item.server = "directo"

    try:
        from core import descargas
        download_enable = True
    except:
        download_enable = False

    view = False
    # Abre el diálogo de selección
    opciones = []
    default_action = config.get_setting("default_action")
    logger.info("default_action=" + default_action)

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode") == "0"
                       and not strmfile)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
        item.server, item.url, item.password, muestra_dialogo)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:

        for video_url in video_urls:
            opciones.append(
                config.get_localized_string(30151) + " " + video_url[0])

        if item.server == "local":
            opciones.append(config.get_localized_string(30164))
        else:
            if download_enable:
                opcion = config.get_localized_string(30153)
                opciones.append(opcion)  # "Descargar"

            if item.channel == "favoritos":
                opciones.append(config.get_localized_string(
                    30154))  # "Quitar de favoritos"
            else:
                opciones.append(
                    config.get_localized_string(30155))  # "Añadir a favoritos"

            if not strmfile:
                opciones.append(config.get_localized_string(
                    30161))  # "Añadir a Biblioteca"

            if download_enable:
                if item.channel != "descargas":
                    opciones.append(config.get_localized_string(
                        30157))  # "Añadir a lista de descargas"
                else:
                    if item.category == "errores":
                        opciones.append(config.get_localized_string(
                            30159))  # "Borrar descarga definitivamente"
                        opciones.append(config.get_localized_string(
                            30160))  # "Pasar de nuevo a lista de descargas"
                    else:
                        opciones.append(config.get_localized_string(
                            30156))  # "Quitar de lista de descargas"

            if config.get_setting("jdownloader_enabled") == "true":
                opciones.append(config.get_localized_string(
                    30158))  # "Enviar a JDownloader"
            if config.get_setting("pyload_enabled") == "true":
                opciones.append(
                    config.get_localized_string(30158).replace(
                        "jDownloader", "pyLoad"))  # "Enviar a pyLoad"

        if default_action == "3":
            seleccion = len(opciones) - 1

        # Busqueda de trailers en youtube
        if not item.channel in ["Trailer", "ecarteleratrailers"]:
            opciones.append(
                config.get_localized_string(30162))  # "Buscar Trailer"

    # Si no puedes ver el vídeo te informa
    else:
        import xbmcgui
        if item.server != "":
            advertencia = xbmcgui.Dialog()
            if "<br/>" in motivo:
                resultado = advertencia.ok(
                    "Non è possibile guardare il video perché...",
                    motivo.split("<br/>")[0],
                    motivo.split("<br/>")[1], item.url)
            else:
                resultado = advertencia.ok(
                    "Non è possibile guardare il video perché...", motivo,
                    item.url)
        else:
            resultado = advertencia.ok(
                "Non è possibile guardare il video perché...",
                "Il server che lo ospita non è",
                "ancora supportato da streamondemand", item.url)

        if item.channel == "favoritos":
            opciones.append(
                config.get_localized_string(30154))  # "Quitar de favoritos"

        if item.channel == "descargas":
            if item.category == "errores":
                opciones.append(config.get_localized_string(
                    30159))  # "Borrar descarga definitivamente"
            else:
                opciones.append(config.get_localized_string(
                    30156))  # "Quitar de lista de descargas"

        if len(opciones) == 0:
            return

    # Si la accion por defecto es "Preguntar", pregunta
    if default_action == "0":  # and server!="torrent":
        import xbmcgui
        dia = xbmcgui.Dialog()
        seleccion = dia.select(config.get_localized_string(30163),
                               opciones)  # "Elige una opción"
        #dia.close()
        '''
        elif default_action=="0" and server=="torrent":
            advertencia = xbmcgui.Dialog()
            logger.info("video_urls[0]="+str(video_urls[0][1]))
            if puedes and ('"status":"COMPLETED"' in video_urls[0][1] or '"percent_done":100' in video_urls[0][1]):
                listo  = "y está listo para ver"
            else:
                listo = "y se está descargando"
            resultado = advertencia.ok( "Torrent" , "El torrent ha sido añadido a la lista" , listo )
            seleccion=-1
        '''
    elif default_action == "1":
        seleccion = 0
    elif default_action == "2":
        seleccion = len(video_urls) - 1
    elif default_action == "3":
        seleccion = seleccion
    else:
        seleccion = 0

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # No ha elegido nada, lo más probable porque haya dado al ESC
    if seleccion == -1:
        #Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem(item.title,
                                    iconImage="DefaultVideo.png",
                                    thumbnailImage=item.thumbnail)
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), False,
                                  listitem)  # JUR Added
        #if config.get_setting("subtitulo") == "true":
        #    config.set_setting("subtitulo", "false")
        return

    if opciones[seleccion] == config.get_localized_string(
            30158):  # "Enviar a JDownloader"
        #d = {"web": url}urllib.urlencode(d)
        from core import scrapertools

        if item.subtitle != "":
            data = scrapertools.cachePage(
                config.get_setting("jdownloader") +
                "/action/add/links/grabber0/start1/web=" + item.url + " " +
                item.thumbnail + " " + item.subtitle)
        else:
            data = scrapertools.cachePage(
                config.get_setting("jdownloader") +
                "/action/add/links/grabber0/start1/web=" + item.url + " " +
                item.thumbnail)

        return

    if opciones[seleccion] == config.get_localized_string(30158).replace(
            "jDownloader", "pyLoad"):  # "Enviar a pyLoad"
        logger.info("Enviando a pyload...")

        if item.show != "":
            package_name = item.show
        else:
            package_name = "streamondemand"

        from core import pyload_client
        pyload_client.download(url=item.url, package_name=package_name)
        return

    elif opciones[seleccion] == config.get_localized_string(
            30164):  # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        import os
        os.remove(item.url)
        xbmc.executebuiltin("Container.Refresh")
        return

    # Ha elegido uno de los vídeos
    elif seleccion < len(video_urls):
        mediaurl = video_urls[seleccion][1]
        if len(video_urls[seleccion]) > 3:
            wait_time = video_urls[seleccion][2]
            item.subtitle = video_urls[seleccion][3]
        elif len(video_urls[seleccion]) > 2:
            wait_time = video_urls[seleccion][2]
        else:
            wait_time = 0
        view = True

    # Descargar
    elif opciones[seleccion] == config.get_localized_string(
            30153):  # "Descargar"

        download_title = item.fulltitle
        if item.hasContentDetails == "true":
            download_title = item.contentTitle

        import xbmc
        # El vídeo de más calidad es el último
        mediaurl = video_urls[len(video_urls) - 1][1]

        from core import downloadtools
        keyboard = xbmc.Keyboard(download_title)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            download_title = keyboard.getText()
            devuelve = downloadtools.downloadbest(video_urls, download_title)

            if devuelve == 0:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin", "Scaricato con successo")
            elif devuelve == -1:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin", "Download interrotto")
            else:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin", "Errore nel download")
        return

    elif opciones[seleccion] == config.get_localized_string(
            30154):  #"Quitar de favoritos"
        from core import favoritos
        # En "extra" está el nombre del fichero en favoritos
        favoritos.deletebookmark(urllib.unquote_plus(item.extra))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(
            config.get_localized_string(30102), item.title,
            config.get_localized_string(30105))  # 'Se ha quitado de favoritos'

        xbmc.executebuiltin("Container.Refresh")
        return

    elif opciones[seleccion] == config.get_localized_string(
            30159):  #"Borrar descarga definitivamente"
        from core import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus(item.extra))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(
            config.get_localized_string(30101), item.title,
            config.get_localized_string(30106))  # 'Se ha quitado de la lista'
        xbmc.executebuiltin("Container.Refresh")
        return

    elif opciones[seleccion] == config.get_localized_string(
            30160):  #"Pasar de nuevo a lista de descargas":
        from core import descargas
        descargas.mover_descarga_error_a_pendiente(
            urllib.unquote_plus(item.extra))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(
            config.get_localized_string(30101), item.title,
            config.get_localized_string(
                30107))  # 'Ha pasado de nuevo a la lista de descargas'
        return

    elif opciones[seleccion] == config.get_localized_string(
            30155):  #"Añadir a favoritos":
        from core import favoritos
        from core import downloadtools

        download_title = item.fulltitle
        download_thumbnail = item.thumbnail
        download_plot = item.plot

        if item.hasContentDetails == "true":
            download_title = item.contentTitle
            download_thumbnail = item.contentThumbnail
            download_plot = item.contentPlot

        keyboard = xbmc.Keyboard(
            downloadtools.limpia_nombre_excepto_1(download_title) + " [" +
            item.channel + "]")
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            favoritos.savebookmark(titulo=download_title,
                                   url=item.url,
                                   thumbnail=download_thumbnail,
                                   server=item.server,
                                   plot=download_plot,
                                   fulltitle=item.title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(
                config.get_localized_string(30102), item.title,
                config.get_localized_string(
                    30108))  # 'se ha añadido a favoritos'
        return

    elif opciones[seleccion] == config.get_localized_string(
            30156):  #"Quitar de lista de descargas":
        from core import descargas
        # La categoría es el nombre del fichero en la lista de descargas
        descargas.deletebookmark((urllib.unquote_plus(item.extra)))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(
            config.get_localized_string(30101), item.title,
            config.get_localized_string(
                30106))  # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin("Container.Refresh")
        return

    elif opciones[seleccion] == config.get_localized_string(
            30157):  #"Añadir a lista de descargas":
        from core import descargas
        from core import downloadtools

        download_title = item.fulltitle
        download_thumbnail = item.thumbnail
        download_plot = item.plot

        if item.hasContentDetails == "true":
            download_title = item.contentTitle
            download_thumbnail = item.contentThumbnail
            download_plot = item.contentPlot

        keyboard = xbmc.Keyboard(
            downloadtools.limpia_nombre_excepto_1(download_title))
        keyboard.doModal()
        if keyboard.isConfirmed():
            download_title = keyboard.getText()

            descargas.savebookmark(titulo=download_title,
                                   url=item.url,
                                   thumbnail=download_thumbnail,
                                   server=item.server,
                                   plot=download_plot,
                                   fulltitle=download_title)

            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(
                config.get_localized_string(30101), download_title,
                config.get_localized_string(
                    30109))  # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion] == config.get_localized_string(
            30161):  #"Añadir a Biblioteca":  # Library
        from platformcode import library

        titulo = item.fulltitle
        if item.fulltitle == "":
            titulo = item.title

        library.savelibrary(titulo,
                            item.url,
                            item.thumbnail,
                            item.server,
                            item.plot,
                            canal=item.channel,
                            category=item.category,
                            Serie=item.show)

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(
            config.get_localized_string(30101), titulo,
            config.get_localized_string(
                30135))  # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion] == config.get_localized_string(
            30162):  #"Buscar Trailer":
        config.set_setting("subtitulo", "false")
        import sys
        xbmc.executebuiltin("Container.Update(%s?%s)" %
                            (sys.argv[0],
                             item.clone(channel="trailertools",
                                        action="buscartrailer").tourl()))
        return

    # Si no hay mediaurl es porque el vídeo no está :)
    logger.info("[xbmctools.py] mediaurl=" + mediaurl)
    if mediaurl == "":
        logger.info("b1")
        if server == "unknown":
            alertUnsopportedServer()
        else:
            alertnodisponibleserver(item.server)
        return

    # Si hay un tiempo de espera (como en megaupload), lo impone ahora
    if wait_time > 0:
        logger.info("b2")
        continuar = handle_wait(wait_time, server, "Caricamento vídeo...")
        if not continuar:
            return

    # Obtención datos de la Biblioteca (solo strms que estén en la biblioteca)
    import xbmcgui
    if strmfile:
        logger.info("b3")
        xlistitem = getLibraryInfo(mediaurl)
    else:
        logger.info("b4")

        play_title = item.fulltitle
        play_thumbnail = item.thumbnail
        play_plot = item.plot

        if item.hasContentDetails == "true":
            play_title = item.contentTitle
            play_thumbnail = item.contentThumbnail
            play_plot = item.contentPlot

        try:
            xlistitem = xbmcgui.ListItem(play_title,
                                         iconImage="DefaultVideo.png",
                                         thumbnailImage=play_thumbnail,
                                         path=mediaurl)
            logger.info("b4.1")
        except:
            xlistitem = xbmcgui.ListItem(play_title,
                                         iconImage="DefaultVideo.png",
                                         thumbnailImage=play_thumbnail)
            logger.info("b4.2")

        xlistitem.setInfo(
            "video", {
                "Title": play_title,
                "Plot": play_plot,
                "Studio": item.channel,
                "Genre": item.category
            })

        #set_infoLabels(listitem,plot) # Modificacion introducida por super_berny para añadir infoLabels al ListItem

    # Lanza el reproductor
    # Lanza el reproductor
    if strmfile:  # and item.server != "torrent": #Si es un fichero strm no hace falta el play
        logger.info("b6")
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)
        if item.subtitle != "":
            xbmc.sleep(2000)
            xbmc.Player().setSubtitles(item.subtitle)

    else:
        logger.info("b7")
        logger.info("player_mode=" + config.get_setting("player_mode"))
        logger.info("mediaurl=" + mediaurl)
        if config.get_setting(
                "player_mode") == "3" or "megacrypter.com" in mediaurl:
            logger.info("b11")
            import download_and_play
            download_and_play.download_and_play(
                mediaurl, "download_and_play.tmp",
                config.get_setting("downloadpath"))
            return

        elif config.get_setting("player_mode") == "0" or (
                config.get_setting("player_mode") == "3"
                and mediaurl.startswith("rtmp")):
            logger.info("b8")
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()
            playlist.add(mediaurl, xlistitem)

            # Reproduce
            playersettings = config.get_setting('player_type')
            logger.info("[xbmctools.py] playersettings=" + playersettings)

            if config.get_system_platform() == "xbox":
                player_type = xbmc.PLAYER_CORE_AUTO
                if playersettings == "0":
                    player_type = xbmc.PLAYER_CORE_AUTO
                    logger.info("[xbmctools.py] PLAYER_CORE_AUTO")
                elif playersettings == "1":
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.info("[xbmctools.py] PLAYER_CORE_MPLAYER")
                elif playersettings == "2":
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.info("[xbmctools.py] PLAYER_CORE_DVDPLAYER")

                xbmcPlayer = xbmc.Player(player_type)
            else:
                xbmcPlayer = xbmc.Player()

            xbmcPlayer.play(playlist)

            if item.channel == "cuevana" and item.subtitle != "":
                logger.info("subtitulo=" + subtitle)
                if item.subtitle != "" and (
                        opciones[seleccion].startswith("Ver")
                        or opciones[seleccion].startswith("Watch")):
                    logger.info("[xbmctools.py] Con subtitulos")
                    setSubtitles()

        elif config.get_setting("player_mode") == "1":
            logger.info("b9")
            logger.info("mediaurl :" + mediaurl)
            logger.info("Tras setResolvedUrl")
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
                                      xbmcgui.ListItem(path=mediaurl))

        elif config.get_setting("player_mode") == "2":
            logger.info("b10")
            xbmc.executebuiltin("PlayMedia(" + mediaurl + ")")

    if item.subtitle != "" and view:
        logger.info("b11")
        logger.info("Subtítulos externos: " + item.subtitle)
        xbmc.Player().setSubtitles(item.subtitle)
Пример #29
0
def ytchannels_main():

    my_addon = xbmcaddon.Addon()
    enable_playlists = my_addon.getSetting('enable_playlists')
    enable_livestreams = my_addon.getSetting('enable_livestreams')

    addon_handle = int(sys.argv[1])
    args = urllib.parse.parse_qs(sys.argv[2][1:])

    xbmcplugin.setContent(addon_handle, 'movies')

    mode = args.get('mode', None)

    show_adds = my_addon.getSetting('show_adds')

    addon_path = my_addon.getAddonInfo('path')
    folder_img = os.path.join(addon_path, 'resources/img/folder.png')
    plus_img = os.path.join(addon_path, 'resources/img/plus.png')
    playlist_img = os.path.join(addon_path, 'resources/img/playlist.png')

    YOUTUBE_API_KEY = my_addon.getSetting('youtube_api_key')
    if YOUTUBE_API_KEY == 'SETME':
        xbmcgui.Dialog().ok(local_string(30207), local_string(30022))
        new_api_key = xbmcgui.Dialog().input(local_string(30207),
                                             type=xbmcgui.INPUT_ALPHANUM)

        if new_api_key:
            my_addon.setSetting(id='youtube_api_key', value=new_api_key)
        else:
            xbmcgui.Dialog().ok(local_string(30020), local_string(30021))

        YOUTUBE_API_KEY = my_addon.getSetting('youtube_api_key')

    from .functions import build_url, delete_database, get_folders, add_folder, remove_folder, get_channels, get_channel_id_from_uploads_id, add_channel, remove_channel, search_channel, search_channel_by_username, get_latest_from_channel, get_playlists, add_sort_db, init_sort, move_up, move_down, check_sort_db, change_folder, set_folder_thumbnail, get_folder_thumbnail, check_thumb_db, add_thumb_db, get_livestreams

    SORT_INIT = check_sort_db()
    THUMB_INIT = check_thumb_db()
    if not SORT_INIT:
        add_sort_db()
        folders = get_folders()
        init_sort('Other')
        for i in range(len(folders)):
            init_sort(folders[i])
    if not THUMB_INIT:
        add_thumb_db()

    if mode is None:
        folders = get_folders()

        for i in range(len(folders)):
            if folders[i] != 'Other':
                url = build_url({
                    'mode': 'open_folder',
                    'foldername': '%s' % folders[i]
                })
                li = xbmcgui.ListItem('%s' % folders[i])
                image = get_folder_thumbnail(folders[i])
                li.setArt({'icon': image})

                rem_uri = build_url({
                    'mode': 'rem_folder',
                    'foldername': '%s' % str(folders[i])
                })

                add_uri = build_url({'mode': 'add_folder'})
                setthumb_uri = build_url({
                    'mode': 'set_thumbnail',
                    'foldername': '%s' % str(folders[i])
                })
                addch_uri = build_url({
                    'mode': 'add_channel',
                    'foldername': 'Other'
                })
                li.addContextMenuItems([
                    (local_string(30000), 'RunPlugin(%s)' % rem_uri),
                    (local_string(30027), 'RunPlugin(%s)' % setthumb_uri),
                    (local_string(30001), 'RunPlugin(%s)' % add_uri),
                    (local_string(30002), 'RunPlugin(%s)' % addch_uri)
                ])

                xbmcplugin.addDirectoryItem(handle=addon_handle,
                                            url=url,
                                            listitem=li,
                                            isFolder=True)

        channels = get_channels('Other')
        for i in range(len(channels)):
            url = build_url({
                'mode': 'open_channel',
                'foldername': '%s' % str(channels[i][1]),
                'page': '1'
            })
            li = xbmcgui.ListItem('%s' % channels[i][0])
            li.setArt({'icon': '%s' % channels[i][2]})

            rem_uri = build_url({
                'mode': 'rem_channel',
                'channel_id': '%s' % str(channels[i][1])
            })
            move_uri = build_url({
                'mode': 'change_folder',
                'channel_id': '%s' % str(channels[i][1]),
                'curfolder': 'Other'
            })
            add_uri = build_url({'mode': 'add_folder'})
            addch_uri = build_url({
                'mode': 'add_channel',
                'foldername': 'Other'
            })
            move_down_uri = build_url({
                'mode': 'move_down',
                'id': '%s' % channels[i][4]
            })
            move_up_uri = build_url({
                'mode': 'move_up',
                'id': '%s' % channels[i][4]
            })
            items = []
            items.append((local_string(
                30028 if channels[i][1].startswith('PL', 0, 2) else 30003),
                          'RunPlugin(%s)' % rem_uri))
            items.append((local_string(30025), 'RunPlugin(%s)' % move_uri))
            items.append((local_string(30001), 'RunPlugin(%s)' % add_uri))
            items.append((local_string(30002), 'RunPlugin(%s)' % addch_uri))
            if len(channels) > 1:
                if channels[i][3] == 1:
                    items.append(
                        (local_string(30024), 'RunPlugin(%s)' % move_down_uri))
                elif channels[i][3] == len(channels):
                    items.append(
                        (local_string(30023), 'RunPlugin(%s)' % move_up_uri))
                else:
                    items.append(
                        (local_string(30023), 'RunPlugin(%s)' % move_up_uri))
                    items.append(
                        (local_string(30024), 'RunPlugin(%s)' % move_down_uri))

            li.addContextMenuItems(items)
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=url,
                                        listitem=li,
                                        isFolder=True)

        if show_adds != 'false':

            url = build_url({'mode': 'add_folder', 'foldername': 'Add folder'})
            li = xbmcgui.ListItem('[COLOR green]%s[/COLOR]' %
                                  local_string(30001))
            li.setArt({'icon': plus_img})
            add_uri = build_url({'mode': 'add_folder'})
            addch_uri = build_url({
                'mode': 'add_channel',
                'foldername': 'Other'
            })
            li.addContextMenuItems([
                (local_string(30001), 'RunPlugin(%s)' % add_uri),
                (local_string(30002), 'RunPlugin(%s)' % addch_uri)
            ])

            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=url,
                                        listitem=li,
                                        isFolder=True)

            url = build_url({'mode': 'add_channel', 'foldername': 'Other'})
            li = xbmcgui.ListItem(
                '[COLOR green]%s[/COLOR] [COLOR blue]%s[/COLOR]' %
                (local_string(30009), local_string(30010)))
            li.setArt({'icon': plus_img})
            add_uri = build_url({'mode': 'add_folder'})
            addch_uri = build_url({
                'mode': 'add_channel',
                'foldername': 'Other'
            })
            li.addContextMenuItems([
                (local_string(30001), 'RunPlugin(%s)' % add_uri),
                (local_string(30002), 'RunPlugin(%s)' % addch_uri)
            ])

            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=url,
                                        listitem=li,
                                        isFolder=True)

        xbmcplugin.endOfDirectory(addon_handle)

    elif mode[0] == 'del_all':
        delete_database()
        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'move_up':
        id = args.get('id', None)
        move_up(id[0])
        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'move_down':
        id = args.get('id', None)
        move_down(id[0])
        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'add_folder':
        keyboard = xbmc.Keyboard('', '%s:' % local_string(30011), False)
        keyboard.doModal()

        if keyboard.isConfirmed():
            folder_name = keyboard.getText()

            add_folder(folder_name)
        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'open_folder':

        dicti = urllib.parse.parse_qs(sys.argv[2][1:])
        foldername = dicti['foldername'][0]

        channels = get_channels(foldername)

        for i in range(len(channels)):
            url = build_url({
                'mode': 'open_channel',
                'foldername': '%s' % str(channels[i][1]),
                'page': '1'
            })
            li = xbmcgui.ListItem('%s' % channels[i][0])
            li.setArt({'icon': '%s' % channels[i][2]})

            rem_uri = build_url({
                'mode': 'rem_channel',
                'channel_id': '%s' % str(channels[i][1])
            })
            move_uri = build_url({
                'mode': 'change_folder',
                'channel_id': '%s' % str(channels[i][1]),
                'curfolder': '%s' % str(foldername)
            })
            move_down_uri = build_url({
                'mode': 'move_down',
                'id': '%s' % channels[i][4]
            })
            move_up_uri = build_url({
                'mode': 'move_up',
                'id': '%s' % channels[i][4]
            })
            items = []
            items.append((local_string(
                30028 if channels[i][1].startswith('PL', 0, 2) else 30003),
                          'RunPlugin(%s)' % rem_uri))
            items.append((local_string(30025), 'RunPlugin(%s)' % move_uri))
            if len(channels) > 1:
                if channels[i][3] == 1:
                    items.append(
                        (local_string(30024), 'RunPlugin(%s)' % move_down_uri))
                elif channels[i][3] == len(channels):
                    items.append(
                        (local_string(30023), 'RunPlugin(%s)' % move_up_uri))
                else:
                    items.append(
                        (local_string(30023), 'RunPlugin(%s)' % move_up_uri))
                    items.append(
                        (local_string(30024), 'RunPlugin(%s)' % move_down_uri))
            li.addContextMenuItems(items)
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=url,
                                        listitem=li,
                                        isFolder=True)

        url = build_url({
            'mode': 'add_channel',
            'foldername': '%s' % foldername
        })
        li = xbmcgui.ListItem(
            '[COLOR green]%s[/COLOR] [COLOR blue]%s[/COLOR]' %
            (local_string(30009), foldername))
        li.setArt({'icon': plus_img})
        xbmcplugin.addDirectoryItem(handle=addon_handle,
                                    url=url,
                                    listitem=li,
                                    isFolder=True)

        xbmcplugin.endOfDirectory(addon_handle)

    elif mode[0] == 'open_channel':
        dicti = urllib.parse.parse_qs(sys.argv[2][1:])
        page = dicti['page'][0]

        id = dicti['foldername'][0]

        try:
            playlist = dicti['playlist'][0]
            if playlist == 'yes':
                playlista = True
        except:
            playlista = False

        if id.startswith('PL', 0, 2):
            playlista = True

        if not playlista and enable_playlists == 'true':

            url = build_url({
                'mode': 'open_playlists',
                'id': '%s' % id,
                'page': '1'
            })
            li = xbmcgui.ListItem('[COLOR yellow]%s[/COLOR]' %
                                  local_string(30004))
            li.setArt({'icon': playlist_img})
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=url,
                                        listitem=li,
                                        isFolder=True)

        if enable_livestreams == 'true':
            url = build_url({
                'mode': 'open_livestreams',
                'id': '%s' % id,
                'page': '1'
            })
            li = xbmcgui.ListItem('[COLOR blue]%s[/COLOR]' %
                                  local_string(30029))
            li.setArt({'icon': playlist_img})
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=url,
                                        listitem=li,
                                        isFolder=True)

        game_list = get_latest_from_channel(id, page)
        next_page = game_list[0]

        xbmc_region = xbmc.getRegion('dateshort')

        for i in range(1, len(game_list)):
            title = game_list[i][0]
            video_id = game_list[i][1]
            thumb = game_list[i][2]
            desc = game_list[i][3]
            seconds = game_list[i][4]
            date = game_list[i][5]

            try:
                pub = datetime.datetime.strftime(
                    datetime.datetime.strptime(date, '%Y-%m-%d'), xbmc_region)
                plot = "Published: " + pub + "\r\n\r\n" + desc
            except:
                plot = desc

            uri = 'plugin://plugin.video.youtube/play/?video_id=' + video_id
            li = xbmcgui.ListItem('%s' % title)
            li.setArt({'icon': thumb})
            li.setProperty('IsPlayable', 'true')
            li.setInfo('video', {
                'genre': 'YouTube',
                'plot': plot,
                'duration': seconds
            })

            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=uri,
                                        listitem=li)  #,isFolder=True)

        if next_page != '1':
            if playlista:
                uri = build_url({
                    'mode': 'open_channel',
                    'foldername': '%s' % id,
                    'page': '%s' % next_page,
                    'playlist': 'yes'
                })
            else:
                uri = build_url({
                    'mode': 'open_channel',
                    'foldername': '%s' % id,
                    'page': '%s' % next_page
                })

            li = xbmcgui.ListItem('%s >>' % local_string(30005))
            li.setArt({'icon': folder_img})
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=uri,
                                        listitem=li,
                                        isFolder=True)

        xbmcplugin.endOfDirectory(addon_handle)

    elif mode[0] == 'open_playlists':
        dicti = urllib.parse.parse_qs(sys.argv[2][1:])
        id = dicti['id'][0]
        page = dicti['page'][0]
        channel_id = get_channel_id_from_uploads_id(id)
        playlists = get_playlists(channel_id, page)

        next_page = playlists[0]
        for i in range(1, len(playlists)):
            id = playlists[i][0]
            name = playlists[i][1]
            thumb = playlists[i][2]

            url = build_url({
                'mode': 'open_channel',
                'foldername': '%s' % id,
                'page': '1',
                'playlist': 'yes'
            })
            li = xbmcgui.ListItem('%s' % name)
            li.setArt({'icon': '%s' % thumb})
            add_playlist_uri = build_url({
                'mode': 'add_playlist',
                'id': '%s' % id,
                'name': '%s' % name,
                'thumb': '%s' % thumb
            })
            items = []
            items.append(("Add to folder", 'RunPlugin(%s)' % add_playlist_uri))
            li.addContextMenuItems(items)
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=url,
                                        listitem=li,
                                        isFolder=True)

        if next_page != '1':
            uri = build_url({
                'mode': 'open_playlists',
                'id': '%s' % id,
                'page': '%s' % next_page,
                'playlist': 'yes'
            })

            li = xbmcgui.ListItem('%s >>' % local_string(30005))
            li.setArt({'icon': folder_img})
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=uri,
                                        listitem=li,
                                        isFolder=True)

        xbmcplugin.endOfDirectory(addon_handle)

    elif mode[0] == 'open_livestreams':
        dicti = urllib.parse.parse_qs(sys.argv[2][1:])
        id = dicti['id'][0]
        page = dicti['page'][0]
        channel_id = get_channel_id_from_uploads_id(id)
        livestreams = get_livestreams(channel_id, page)

        for i in range(1, len(livestreams)):
            title = livestreams[i][0]
            video_id = livestreams[i][1]
            thumb = livestreams[i][2]
            desc = livestreams[i][3]

            plot = desc

            uri = 'plugin://plugin.video.youtube/play/?video_id=' + video_id

            li = xbmcgui.ListItem('%s' % title)
            li.setArt({'icon': thumb})
            li.setProperty('IsPlayable', 'true')
            li.setInfo('video', {'plot': plot})

            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=uri,
                                        listitem=li)

        xbmcplugin.endOfDirectory(addon_handle)

    elif mode[0] == 'add_channel':
        options = [local_string(30006), local_string(30007)]
        ind = xbmcgui.Dialog().select(local_string(30008), options)
        if ind == 0:

            dicti = urllib.parse.parse_qs(sys.argv[2][1:])
            foldername = dicti['foldername'][0]

            keyboard = xbmc.Keyboard('', '%s:' % local_string(30012), False)
            keyboard.doModal()

            if keyboard.isConfirmed():
                channel_name = keyboard.getText()

                results = search_channel(channel_name)

                li = [None] * len(results)
                for i in range(len(results)):
                    li[i] = xbmcgui.ListItem(results[i][0], results[i][4])
                    li[i].setArt({'icon': results[i][2]})
                dialog = xbmcgui.Dialog()
                index = dialog.select(local_string(30013), li, useDetails=True)
                if index > -1:
                    channel_uplid = results[index][1]
                    channel_name = results[index][0]
                    thumb = results[index][2]
                    channel_id = results[index][3]

                    add_channel(foldername, channel_name, channel_uplid, thumb)
        elif ind == 1:
            dicti = urllib.parse.parse_qs(sys.argv[2][1:])
            foldername = dicti['foldername'][0]

            keyboard = xbmc.Keyboard('', '%s:' % local_string(30014), False)
            keyboard.doModal()

            if keyboard.isConfirmed():
                channel_name = keyboard.getText()
                help_list = search_channel_by_username(channel_name)

                if help_list == 'not found':
                    xbmcgui.Dialog().ok(
                        local_string(30099),
                        '%s "%s" %s' % (local_string(30018), channel_name,
                                        local_string(30019)))
                else:
                    channel_name = help_list[0]
                    channel_id = help_list[1]
                    thumb = help_list[2]
                    add_channel(foldername, channel_name, channel_id, thumb)

        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'rem_channel':
        dicti = urllib.parse.parse_qs(sys.argv[2][1:])
        channel_id = dicti['channel_id'][0]
        remove_channel(channel_id)
        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'rem_folder':
        dicti = urllib.parse.parse_qs(sys.argv[2][1:])
        foldername = dicti['foldername'][0]
        remove_folder(foldername)
        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'change_folder':
        dicti = urllib.parse.parse_qs(sys.argv[2][1:])
        channel_id = dicti['channel_id'][0]
        curfolder = dicti['curfolder'][0]
        folders = get_folders()
        if not curfolder == "Other":
            folders.append("root")
            folders.remove(curfolder)
        dialog = xbmcgui.Dialog()
        index = dialog.select(local_string(30011), folders)
        if index > -1:
            change_folder(channel_id, folders[index])
        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'add_playlist':
        dicti = urllib.parse.parse_qs(sys.argv[2][1:])
        channel_name = dicti['name'][0]
        channel_id = dicti['id'][0]
        thumb = dicti['thumb'][0]
        folders = get_folders()
        folders.append("root")
        dialog = xbmcgui.Dialog()
        index = dialog.select(local_string(30011), folders)
        if index > -1:
            add_channel(folders[index],
                        '[COLOR yellow]' + channel_name + '[/COLOR]',
                        channel_id, thumb)
        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'set_thumbnail':
        dicti = urllib.parse.parse_qs(sys.argv[2][1:])
        foldername = dicti['foldername'][0]
        image = xbmcgui.Dialog().browse(2, local_string(30026), '')
        if image:
            set_folder_thumbnail(foldername, image)
        xbmc.executebuiltin("Container.Refresh")

    elif mode[0] == 'erase_all':
        ret = xbmcgui.Dialog().yesno(local_string(30015), local_string(30016))

        if ret:
            delete_database()
            xbmcgui.Dialog().ok(local_string(30099), local_string(30017))
Пример #30
0
def run():
    logger.info("streamondemand.platformcode.launcher run")
    
    # Test if all the required directories are created
    config.verify_directories_created()
    
    # Extract parameters from sys.argv
    params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password = extract_parameters()
    logger.info("streamondemand.platformcode.launcher fanart=%s, channel_name=%s, title=%s, fulltitle=%s, url=%s, thumbnail=%s, plot=%s, action=%s, server=%s, extra=%s, subtitle=%s, category=%s, show=%s, password=%s" % (fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password))

    try:
        # Accion por defecto - elegir canal
        if ( action=="selectchannel" ):
            # Borra el fichero de las cookies para evitar problemas con MV
            #ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            #if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)
            
            
            if config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("tvalacarta",config.get_localized_string(30064))
                except:
                    pass
            

            import channelselector as plugin
            plugin.mainlist(params, url, category)

        # Actualizar version
        elif ( action=="update" ):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info("streamondemand.platformcode.launcher Actualizacion automática desactivada")

            #import channelselector as plugin
            #plugin.listchannels(params, url, category)
            if config.get_system_platform()!="xbox":
                import xbmc
                xbmc.executebuiltin( "Container.Refresh" )

        elif (action=="channeltypes"):
            import channelselector as plugin
            plugin.channeltypes(params,url,category)

        elif (action=="categories"):
            import channelselector as plugin
            plugin.categories(params,url,category)

        elif (action=="listchannels"):
            import channelselector as plugin
            plugin.listchannels(params,url,category)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            
            if action=="mainlist" and config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(channel_name)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin",channel_name,config.get_localized_string(30063))
                except:
                    pass
            

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en pelisalacarta
            regular_channel_path = os.path.join( config.get_runtime_path() , 'channels' , channel_name+".py" )
            core_channel_path = os.path.join( config.get_runtime_path(), 'core' , channel_name+".py" )
            logger.info("streamondemand.platformcode.launcher regular_channel_path=%s" % regular_channel_path)
            logger.info("streamondemand.platformcode.launcher core_channel_path=%s" % core_channel_path)

            if channel_name=="personal" or channel_name=="personal2" or channel_name=="personal3" or channel_name=="personal4" or channel_name=="personal5":
                import channels.personal as channel
            elif os.path.exists( regular_channel_path ):
                exec "import channels."+channel_name+" as channel"
            elif os.path.exists( core_channel_path ):
                exec "from core import "+channel_name+" as channel"

            logger.info("streamondemand.platformcode.launcher running channel %s %s" % (channel.__name__ , channel.__file__))

            generico = False
            # Esto lo he puesto asi porque el buscador puede ser generico o normal, esto estará asi hasta que todos los canales sean genericos 
            if category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            if not generico:
                logger.info("streamondemand.platformcode.launcher xbmc native channel")
                if (action=="strm"):
                    from platformcode import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel."+action+"(params, url, category)"
            else:            
                logger.info("streamondemand.platformcode.launcher multiplatform channel")
                from core.item import Item
                item = Item(channel=channel_name, title=title , fulltitle=fulltitle, url=url, thumbnail=thumbnail , plot=plot , server=server, category=category, extra=extra, subtitle=subtitle, viewmode=viewmode, show=show, password=password, fanart=fanart)
                
                '''
                if item.subtitle!="":
                    logger.info("streamondemand.platformcode.launcher Downloading subtitle file "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("streamondemand.platformcode.launcher No subtitle")
                '''
                from platformcode import xbmctools

                if action=="play":
                    logger.info("streamondemand.platformcode.launcher play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info("streamondemand.platformcode.launcher executing channel 'play' method")
                        itemlist = channel.play(item)
                        if len(itemlist)>0:
                            item = itemlist[0]
                            xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok ("plugin", "Niente da riprodurre")
                    else:
                        logger.info("streamondemand.platformcode.launcher no channel 'play' method, executing core method")
                        xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show)

                elif action=="strm_detail" or action=="play_from_library":
                    logger.info("streamondemand.platformcode.launcher play_from_library")

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")                    

                    logger.info("item.server=#"+item.server+"#")
                    # Ejecuta find_videos, del canal o común
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools
                        itemlist = servertools.find_video_items(item)

                    if len(itemlist)>0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)
    
                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)
                    
                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]
    
                        if seleccion==-1:
                            return
                    else:
                        elegido = item
                
                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" % (item.title,item.subtitle))
                    
                    from platformcode import xbmctools
                    logger.info("subtitle="+item.subtitle)
                    xbmctools.play_video(strmfile=True, channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=fulltitle)

                elif action=="add_pelicula_to_library":
                    logger.info("streamondemand.platformcode.launcher add_pelicula_to_library")
                    from platformcode import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary( titulo=item.fulltitle , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Cine" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )

                elif action=="add_serie_to_library":
                    logger.info("streamondemand.platformcode.launcher add_serie_to_library, show=#"+item.show+"#")
                    from platformcode import library
                    import xbmcgui
                
                    # Obtiene el listado desde el que se llamó
                    action = item.extra
                    
                    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                    if "###" in item.extra:
                        action = item.extra.split("###")[0]
                        item.extra = item.extra.split("###")[1]

                    exec "itemlist = channel."+action+"(item)"

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('pelisalacarta', 'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info ("[launcher.py] Total Episodios:"+str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
                        logger.info("streamondemand.platformcode.launcher add_serie_to_library, title="+item.title)
                        if (pDialog.iscanceled()):
                            return
                
                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action!="add_serie_to_library" and item.action!="download_all_episodes":
                                nuevos = nuevos + library.savelibrary( titulo=item.title , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Series" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle, extra=item.extra )
                        except IOError:
                            import sys
                            for line in sys.exc_info():
                                logger.error( "%s" % line )
                            logger.info("streamondemand.platformcode.launcher Error al grabar el archivo "+item.title)
                            errores = errores + 1
                        
                    pDialog.close()
                    
                    # Actualizacion de la biblioteca
                    itemlist=[]
                    if errores > 0:
                        itemlist.append(Item(title="ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"))
                        logger.info ("[launcher.py] No se pudo añadir "+str(errores)+" episodios")
                    else:
                        itemlist.append(Item(title="La serie è stata aggiunta alla biblioteca"))
                        logger.info ("[launcher.py] Ningún error al añadir "+str(errores)+" episodios")
                    
                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, params, url, category)
                    
                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join( config.get_library_path() , "series.xml" )
                    if not os.path.exists(nombre_fichero_config_canal):
                        nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

                    logger.info("nombre_fichero_config_canal="+nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open( nombre_fichero_config_canal , "w" )
                    else:
                        f = open( nombre_fichero_config_canal , "r" )
                        contenido = f.read()
                        f.close()
                        f = open( nombre_fichero_config_canal , "w" )
                        f.write(contenido)
                    from platformcode import library
                    f.write( library.title_to_folder_name(item.show)+","+item.url+","+item.channel+"\n")
                    f.close();

                elif action=="download_all_episodes":
                    download_all_episodes(item,channel)

                elif action=="search":
                    logger.info("streamondemand.platformcode.launcher search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, params, url, category)

                else:
                    logger.info("streamondemand.platformcode.launcher executing channel '"+action+"' method")
                    if action!="findvideos":
                        exec "itemlist = channel."+action+"(item)"
                            
                        #for item in itemlist:
                        #    logger.info("viemode="+item.viewmode)
                    else:

                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        if hasattr(channel, 'findvideos'):
                            exec "itemlist = channel."+action+"(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info("streamondemand.platformcode.launcher no channel 'findvideos' method, executing core method")
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)

                        from platformcode import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin
                    import sys
                    handle = sys.argv[1]
                    xbmcplugin.setContent(int( handle ),"movies")
                    
                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError,e:
        import traceback,sys
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        import xbmcgui
        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %s , Razon: %s" % (e.reason[0], e.reason[1]))
            texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web"
            ok = ventana_error.ok ("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado     
        elif hasattr(e,'code'):
            logger.info("codigo de error HTTP : %d" %e.code)
            texto = (config.get_localized_string(30051) % e.code) # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok ("plugin", texto)