Ejemplo n.º 1
0
def parentalOff():

    input = kodi.get_keyboard('Please Enter Your Password', hidden=True)
    if ( not input ):
        kodi.dialog.ok(kodi.get_name(),"Sorry, no password was entered.")
        sys.exit(0)
    pass_one = hashlib.sha256(input).hexdigest()

    conn = sqlite3.connect(parentaldb)
    conn.text_factory = str
    c = conn.cursor()
    c.execute("SELECT * FROM parental")

    for (passwd, timest) in c.fetchall(): 
        timestamp = timest
        password = passwd
    conn.close()
    
    if password == pass_one:
        try:
            try: os.remove(parentaldb)
            except: pass
            kodi.dialog.ok(kodi.get_name(),'Parental controls have been disabled.')
            xbmc.executebuiltin("Container.Refresh")
        except:
            kodi.dialog.ok(kodi.get_name(),'There was an error disabling the parental controls.')
            xbmc.executebuiltin("Container.Refresh")    
    else:
        kodi.dialog.ok(kodi.get_name(),"Sorry, the password you entered was incorrect.")
        quit()
Ejemplo n.º 2
0
def remote_play(source):
    rpc_client = HttpJSONRPC()
    command = {'jsonrpc': '2.0', 'id': 1, 'method': 'Player.GetActivePlayers'}
    response = rpc_client.execute_rpc(command)
    if 'error' in response:
        kodi.notify(kodi.get_name(), response['error'], duration=7000)
        return
    try:
        player_id = response['result'][0]['playerid']
    except IndexError:
        player_id = None
    if player_id == 2:  # stop picture player if active, it will block
        command = {'jsonrpc': '2.0', 'id': 1, 'method': 'Player.Stop', 'params': {'playerid': player_id}}
        response = rpc_client.execute_rpc(command)
        if 'error' in response:
            kodi.notify(kodi.get_name(), response['error'], duration=7000)
            return
    if source['is_dash']:
        filename = kodi.get_plugin_url({'mode': MODES.PLAY, 'player': 'false', 'path': urllib2.quote(source['url']),
                                        'thumb': urllib2.quote(source['art']['thumb']), 'title': urllib2.quote(source['info']['title'])})
    else:
        filename = source['url']
    command = {'jsonrpc': '2.0', 'id': 1, 'method': 'Player.Open', 'params': {'item': {'file': filename}}}
    response = rpc_client.execute_rpc(command)
    if 'error' in response:
        kodi.notify(kodi.get_name(), response['error'], duration=7000)
    else:
        if 'No Response' not in response['result']:
            kodi.notify(kodi.get_name(), kodi.i18n('send_success'))
def parentalPin():

    input = kodi.get_keyboard('Please Set Password', hidden=True)
    if (not input):
        kodi.dialog.ok(kodi.get_name(), "Sorry, no password was entered.")
        sys.exit(0)

    pass_one = input

    input = kodi.get_keyboard('Please Confirm Your Password', hidden=True)
    if (not input):
        kodi.dialog.ok(kodi.get_name(), "Sorry, no password was entered.")
        sys.exit(0)

    pass_two = input

    if pass_one == pass_two:
        writeme = hashlib.sha256(pass_one).hexdigest()
        addEntry(writeme, None)
        kodi.dialog.ok(kodi.get_name(), 'Parental control has been enabled.')
        xbmc.executebuiltin("Container.Refresh")
    else:
        kodi.dialog.ok(kodi.get_name(),
                       'The passwords do not match, please try again.')
        sys.exit(0)
Ejemplo n.º 4
0
def hard_reset():

    viewDialog(xbmc.translatePath(os.path.join(kodi.addonfolder , 'resources/files/reset.txt')))
    choice = xbmcgui.Dialog().yesno("[COLOR orangered][B]RESET XXX-O-DUS?[/B][/COLOR]", '[COLOR white]ARE YOU SURE YOU WANT TO RETURN XXX-O-DUS TO THE DEFAULT STATE AND LOSE ALL YOUR INFORMATION?[/COLOR]')
    if choice:
        try:
            shutil.rmtree(kodi.datafolder)
        except:
            kodi.dialog.ok(kodi.get_name(), "[COLOR white]There was an error deleting deleting the data directory.[/COLOR]")
            quit()
        kodi.dialog.ok(kodi.get_name(), "[COLOR white]XXX-O-DUS has been reset to the factory state.[/COLOR]","[COLOR white]Press OK to continue.[/COLOR]")
        xbmc.executebuiltin("Container.Refresh")
def parentalCheck():

    timestamp = None
    password = None

    conn = sqlite3.connect(parentaldb)
    conn.text_factory = str
    c = conn.cursor()
    c.execute("SELECT * FROM parental")

    for (passwd, timest) in c.fetchall():
        timestamp = timest
        password = passwd
    conn.close()

    session_time = int(kodi.get_setting('session_time'))

    if password:
        try:
            now = time.time()
            check = now - 60 * session_time
            if (not timestamp): timestamp = 0
        except:
            now = time.time()
            check = now - 60 * session_time
            timestamp = 0
    else:
        return

    if (timestamp < check):

        input = kodi.get_keyboard(
            'Please Enter Your Password - %s' % kodi.giveColor(
                '(%s Minute Session)' % str(session_time), 'red', True),
            hidden=True)
        if (not input):
            sys.exit(0)

        pass_one = hashlib.sha256(input).hexdigest()

        if password != pass_one:
            kodi.dialog.ok(kodi.get_name(),
                           "Sorry, the password you entered was incorrect.")
            sys.exit(0)
        else:
            delEntry(password)
            addEntry(password, now)
            kodi.dialog.ok(
                kodi.get_name(), 'Login successful!',
                'You now have a %s minute session before you will be asked for the password again.'
                % str(session_time))
    return
Ejemplo n.º 6
0
def followUser():

    user = kodi.get_keyboard('Enter Username')
    if user:
        user = user.replace(' ', '_')
        xbmc.executebuiltin("ActivateWindow(busydialog)")

        conn = sqlite3.connect(chaturbatedb)
        conn.text_factory = str
        c = conn.cursor()
        c.execute("SELECT name FROM chaturbate")
        e = [i for i in c.fetchall()]
        conn.close()
        if user in str(e):
            kodi.dialog.ok(kodi.get_name(),
                           user + ' is already being monitored.')
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            quit()
        url = 'https://chaturbate.com/' + user
        try:
            r = client.request(url)
        except:
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            kodi.dialog.ok(
                kodi.get_name(),
                'We could not find any model matching the username ' + user +
                '. Please check the username and try again.')
            quit()
        if not 'Bio and Free Webcam' in r:
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            dialog.ok(
                kodi.get_name(),
                'We could not find any model matching the username ' + user +
                '. Please check the username and try again.')
            quit()
        else:
            iconimg = 'https://roomimg.stream.highwebmedia.com/ri/' + user + '.jpg'
            addPerformer(user, url, iconimg)
            kodi.dialog.ok(kodi.get_name(),
                           user + ' has been added to the monitor list.')
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            xbmc.executebuiltin('Container.Refresh')
            quit()
    else:
        kodi.dialog.ok(kodi.get_name(),
                       'No username entered. Please try again.')
        xbmc.executebuiltin("Dialog.Close(busydialog)")
        quit()
Ejemplo n.º 7
0
def specialplayer(name, url, iconimage):

    a, b, c, d, url = url.split('|SPLIT|')
    name = a
    date_now = datetime.datetime.now().strftime("%d-%m-%Y")
    time_now = datetime.datetime.now().strftime("%H:%M")
    string = '\n<item>\n<date>' + date_now + '</date>\n<time>' + time_now + '</time>\n<name>' + a + '</name>\n<link>' + b + '</link>\n<site>' + c + '</site>\n<icon>' + d + '</icon>\n</item>\n'
    a = open(historyfile).read()
    b = a.replace('#START OF FILE#', '#START OF FILE#' + string)
    f = open(historyfile, mode='w')
    f.write(str(b))
    f.close()

    if iconimage == "None":
        iconimage = icon

    if "highwebmedia" in url:
        kodi.dialog.ok(
            kodi.get_name(),
            '[COLOR white]Chaturbate links are taken at the time of broadcasting. If this broadcast has ended the link will no longer play. [/COLOR]'
        )
    import urlresolver
    if urlresolver.HostedMediaFile(url).valid_url():
        url = urlresolver.HostedMediaFile(url).resolve()
    liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
    xbmc.Player().play(url, liz, False)
Ejemplo n.º 8
0
    def checkAge(self):

        choice = kodi.dialog.yesno(kodi.get_name(), 'To use this addon you you must be legally allowed to under the laws of your State/Country. By pressing I Agree you accept that you are legally allowed to view adult content.',yeslabel='I Agree',nolabel='Exit')
        if choice: 
            try:
                with open(self.firstRunFile,mode='w'): pass
            except: pass
        else: sys.exit(1)
Ejemplo n.º 9
0
def log(msg, level=LOGNOTICE):
	try:
		if isinstance(msg, unicode):
			msg = msg.encode('utf-8')
		__log('%s: %s' % (kodi.get_name(), msg), level)
	except Exception as e:
		try: __log('Logging Failure: %s' % (e), level)
		except: pass  # just give up
Ejemplo n.º 10
0
def log(msg, level=LOGNOTICE):
	try:
		if isinstance(msg, unicode):
			msg = msg.encode('utf-8')
		__log('%s: %s' % (kodi.get_name(), msg), level)
	except Exception as e:
		try: __log('Logging Failure: %s' % (e), level)
		except: pass  # just give up
Ejemplo n.º 11
0
def clearFavorites():

    if os.path.isfile(favoritesdb):
        choice = xbmcgui.Dialog().yesno(kodi.get_name(), kodi.giveColor('Would you like to clear all of your favorites?','white'))
        if choice:
            try: os.remove(favoritesdb)
            except: kodi.notify(msg='Error clearing favorites.')
    xbmc.executebuiltin("Container.Refresh")
Ejemplo n.º 12
0
def clearSearch():

    if os.path.isfile(searchdb):
        choice = xbmcgui.Dialog().yesno(kodi.get_name(), kodi.giveColor('Would you like to clear all stored search history?','white'))
        if choice:
            try: os.remove(searchdb)
            except: kodi.notify(msg='Error removing search history.')
    xbmc.executebuiltin("Container.Refresh")
Ejemplo n.º 13
0
def clearMonitor():

    if os.path.isfile(chaturbatedb):
        choice = xbmcgui.Dialog().yesno(kodi.get_name(), kodi.giveColor('Would you like to clear all history?','white'))
        if choice:
            try: os.remove(chaturbatedb)
            except: kodi.notify(msg='Error removing history.')
            xbmc.executebuiltin("Container.Refresh")
            kodi.notify(msg='Monitoring list reset.')
Ejemplo n.º 14
0
def log(msg, level=LOGDEBUG):
    try:
        if isinstance(msg, unicode):
            msg = '%s (ENCODED)' % (msg.encode('utf-8'))
        kodi.__log('%s: %s' % (kodi.get_name(), msg), level)
    except Exception as e:
        try:
            kodi.__log('Logging Failure: %s' % e, level)
        except:
            pass  # just give up
Ejemplo n.º 15
0
def log(msg, level=LOGDEBUG):
    try:
        if isinstance(msg, unicode):
            msg = '%s (ENCODED)' % (msg.encode('utf-8'))
        kodi.__log('%s: %s' % (kodi.get_name(), msg), level)
    except Exception as e:
        try:
            kodi.__log('Logging Failure: %s' % e, level)
        except:
            pass  # just give up
Ejemplo n.º 16
0
def hard_reset():

    viewDialog(
        xbmc.translatePath(
            os.path.join(kodi.addonfolder, 'resources/files/reset.txt')))
    choice = xbmcgui.Dialog().yesno(
        "[COLOR orangered][B]RESET XXX-O-DUS?[/B][/COLOR]",
        '[COLOR white]ARE YOU SURE YOU WANT TO RETURN XXX-O-DUS TO THE DEFAULT STATE AND LOSE ALL YOUR INFORMATION?[/COLOR]'
    )
    if choice:
        download_location = kodi.get_setting("download_location")
        download_folder = xbmc.translatePath(download_location)

        extensions = ['.mp4']

        for file in os.listdir(download_folder):
            for extension in extensions:
                if file.endswith(extension):
                    try:
                        path = xbmc.translatePath(
                            os.path.join(download_folder, file))
                        os.remove(path)
                    except:
                        kodi.dialog.ok(
                            kodi.get_name(),
                            "[COLOR white]There was an error deleting %s[/COLOR]"
                            % file)
                        pass
        try:
            shutil.rmtree(kodi.datafolder)
        except:
            kodi.dialog.ok(
                kodi.get_name(),
                "[COLOR white]There was an error deleting deleting the data directory.[/COLOR]"
            )
            quit()
        kodi.dialog.ok(
            kodi.get_name(),
            "[COLOR white]XXX-O-DUS has been reset to the factory state.[/COLOR]",
            "[COLOR white]Press OK to continue.[/COLOR]")
        xbmc.executebuiltin("Container.Refresh")
Ejemplo n.º 17
0
 def _connect(self):
     if self.quiet is False:
         kodi.log("Connecting to " + self.db_file)
     try:
         from sqlite3 import dbapi2 as database
         if self.quiet is False:
             kodi.log("%s loading sqlite3 as DB engine" % kodi.get_name())
     except:
         from pysqlite2 import dbapi2 as database
         if self.quiet is False:
             kodi.log("%s loading pysqlite2 as DB engine" % kodi.get_name())
     if self.quiet is False:
         kodi.log("Connecting to SQLite on: " + self.db_file)
     directory = os.path.dirname(self.db_file)
     if not kodi.vfs.exists(directory): kodi.vfs.mkdir(directory)
     self.DBH = database.connect(self.db_file, check_same_thread=False)
     try:
         self.DBC = self.DBH.cursor()
     except Exception, e:
         kodi.raise_error("SqlLite Error", e)
         sys.exit()
Ejemplo n.º 18
0
def searchUser():

    user = kodi.get_keyboard('Enter Username')
    if user:
        user = user.replace(' ','_')
        url = 'https://chaturbate.com/' + user
        iconimg = 'https://roomimg.stream.highwebmedia.com/ri/' + user + '.jpg'
        url += '|SPLIT|Chaturbate'
        player.resolve_url(url,user,iconimg)
    else:
        kodi.dialog.ok(kodi.get_name(), 'No username entered. Please try again.')
        quit()
Ejemplo n.º 19
0
def download(url, name, icon, dest, dp = None):
    xbmc.executebuiltin("Dialog.Close(busydialog)")
    if not dp: 
        dp = kodi.dp
        dp.create(kodi.get_name(),"Downloading: %s" % name,' ', ' ')
    dp.update(0)
    start_time=time.time()
    log_utils.log('Attempting to download :: %s' % url, log_utils.LOGNOTICE)
    urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(dest,nb, bs, fs, dp, start_time))
    addDownload(name, url, icon)
    kodi.notify(msg='Download Complete', sound=True)
    log_utils.log('Download complete.', log_utils.LOGNOTICE)
    finish_up(dest)
Ejemplo n.º 20
0
	def _connect(self):
		if self.quiet is False:
			kodi.log("Connecting to " + self.db_file)
		try:
			from sqlite3 import dbapi2 as database
			if self.quiet is False:
				kodi.log("%s loading sqlite3 as DB engine" % kodi.get_name())
		except:
			from pysqlite2 import dbapi2 as database
			if self.quiet is False:
				kodi.log("%s loading pysqlite2 as DB engine"  % kodi.get_name())
		if self.quiet is False:
			kodi.log("Connecting to SQLite on: " + self.db_file)
		directory = kodi.vfs.dirname(self.db_file)
		if not kodi.vfs.exists(directory): kodi.vfs.mkdir(directory)
		self.DBH = database.connect(self.db_file, check_same_thread=False)
		try:
			self.DBC = self.DBH.cursor()
			self.__connected = True	
		except Exception, e:
			self.handel_error(DatabaseException("SQLite Database Error: %s" % e))
			kodi.log("SQLite Database Error: %s" % e)
Ejemplo n.º 21
0
def download_trailer(trailer_url, title, year=''):
    path = kodi.get_setting('download_path')
    while not path:
        ret = xbmcgui.Dialog().yesno(kodi.get_name(), i18n('no_download_path'), nolabel=i18n('cancel'), yeslabel=i18n('set_it_now'))
        if not ret:
            return

        kodi.show_settings()
        path = kodi.get_setting('download_path')
        
    trailer_url = local_utils.resolve_trailer(trailer_url)
    file_name = utils.create_legal_filename(title, year)
    utils.download_media(trailer_url, path, file_name, translations)
Ejemplo n.º 22
0
	def _connect(self):
		if self.quiet is False:
			kodi.log("Connecting to " + self.db_file)
		try:
			from sqlite3 import dbapi2 as database
			if self.quiet is False:
				kodi.log("%s loading sqlite3 as DB engine" % kodi.get_name())
		except:
			from pysqlite2 import dbapi2 as database
			if self.quiet is False:
				kodi.log("%s loading pysqlite2 as DB engine"  % kodi.get_name())
		if self.quiet is False:
			kodi.log("Connecting to SQLite on: " + self.db_file)
		directory = os.path.dirname(self.db_file)
		if not kodi.vfs.exists(directory): kodi.vfs.mkdir(directory)
		self.DBH = database.connect(self.db_file, check_same_thread=False)
		try:
			self.DBC = self.DBH.cursor()
		except Exception, e:
			kodi.log(e)
			kodi.raise_error("SqlLite Error", e)
			sys.exit()
Ejemplo n.º 23
0
def download_trailer(trailer_url, title, year=''):
    path = kodi.get_setting('download_path')
    while not path:
        ret = xbmcgui.Dialog().yesno(kodi.get_name(),
                                     i18n('no_download_path'),
                                     nolabel=i18n('cancel'),
                                     yeslabel=i18n('set_it_now'))
        if not ret:
            return

        kodi.show_settings()
        path = kodi.get_setting('download_path')

    trailer_url = local_utils.resolve_trailer(trailer_url)
    file_name = utils.create_legal_filename(title, year)
    utils.download_media(trailer_url, path, file_name, translations)
Ejemplo n.º 24
0
class Logger(object):
    __loggers = {}
    __name = kodi.get_name()
    __addon_debug = kodi.get_setting('addon_debug') == 'true'
    __debug_on = _is_debugging()
    __disabled = set()

    @staticmethod
    def get_logger(name=None):
        if name not in Logger.__loggers:
            Logger.__loggers[name] = Logger()

        return Logger.__loggers[name]

    def disable(self):
        if self not in Logger.__disabled:
            Logger.__disabled.add(self)

    def enable(self):
        if self in Logger.__disabled:
            Logger.__disabled.remove(self)

    def log(self, msg, level=LOGDEBUG):
        # if debug isn't on, skip disabled loggers unless addon_debug is on
        if not self.__debug_on:
            if self in self.__disabled:
                return
            elif level == LOGDEBUG:
                if self.__addon_debug:
                    level = LOGNOTICE
                else:
                    return

        try:
            if isinstance(msg, unicode):
                msg = '%s (ENCODED)' % (msg.encode('utf-8'))

            kodi._log('%s: %s' % (self.__name, msg), level)

        except Exception as e:
            try:
                kodi._log('Logging Failure: %s' % (e), level)
            except:
                pass  # just give up
Ejemplo n.º 25
0
    def __init__(self,
                 ip_address=None,
                 port=None,
                 username=None,
                 password=None):
        self.ip_address = kodi.get_setting(
            'remote-ip') if ip_address is None else ip_address
        self.port = kodi.get_setting('remote-port') if port is None else port
        self.username = kodi.get_setting(
            'remote-username').strip() if username is None else username
        self.password = kodi.get_setting(
            'remote-password') if password is None else password
        self.has_connection_details = self.ip_address and self.port and self.username and self.password
        self.url = 'http://%s:%s/jsonrpc' % (
            self.ip_address,
            self.port) if self.has_connection_details else None
        self.authorization = base64.b64encode(
            self.username + b':' +
            self.password) if self.has_connection_details else None
        self.headers = {
            'User-Agent': '%s/%s' % (kodi.get_name(), kodi.get_version()),
            'Content-Type': 'application/json'
        }
        if self.authorization:
            self.headers.update(
                {'Authorization': b'Basic ' + self.authorization})

        self.connection_details_error = ''
        if not self.has_connection_details:
            self.connection_details_error = 'Missing connection details:'
            if not self.ip_address:
                self.connection_details_error += ' |IP address|'
            if not self.port:
                self.connection_details_error += ' |Port|'
            if not self.username:
                self.connection_details_error += ' |Username|'
            if not self.password:
                self.connection_details_error += ' |Password|'
Ejemplo n.º 26
0
def download_media(url, path, file_name):
    try:
        progress = int(kodi.get_setting('down_progress'))
        active = not progress == PROGRESS.OFF
        background = progress == PROGRESS.BACKGROUND
        with kodi.ProgressDialog(kodi.get_name(), i18n('downloading') % (file_name), background=background, active=active) as pd:
            try:
                headers = dict([item.split('=') for item in (url.split('|')[1]).split('&')])
                for key in headers: headers[key] = urllib.unquote(headers[key])
            except:
                headers = {}
            if 'User-Agent' not in headers: headers['User-Agent'] = USER_AGENT
            request = urllib2.Request(url.split('|')[0], headers=headers)
            response = urllib2.urlopen(request)
            if 'Content-Length' in response.info():
                content_length = int(response.info()['Content-Length'])
            else:
                content_length = 0
    
            file_name = file_name.replace('.strm', get_extension(url, response))
            full_path = os.path.join(path, file_name)
            log_utils.log('Downloading: %s -> %s' % (url, full_path), log_utils.LOGDEBUG)
    
            path = xbmc.makeLegalFilename(path)
            try:
                try: xbmcvfs.mkdirs(path)
                except: os.makedirs(path)
            except Exception as e:
                log_utils.log('Path Create Failed: %s (%s)' % (e, path), log_utils.LOGDEBUG)
    
            if not path.endswith(os.sep): path += os.sep
            if not xbmcvfs.exists(path):
                raise Exception(i18n('failed_create_dir'))
            
            file_desc = xbmcvfs.File(full_path, 'w')
            total_len = 0
            cancel = False
            while True:
                data = response.read(CHUNK_SIZE)
                if not data:
                    break
    
                if pd.is_canceled():
                    cancel = True
                    break
    
                total_len += len(data)
                if not file_desc.write(data):
                    raise Exception(i18n('failed_write_file'))
    
                percent_progress = (total_len) * 100 / content_length if content_length > 0 else 0
                log_utils.log('Position : %s / %s = %s%%' % (total_len, content_length, percent_progress), log_utils.LOGDEBUG)
                pd.update(percent_progress)
            
            file_desc.close()

        if not cancel:
            kodi.notify(msg=i18n('download_complete') % (file_name), duration=5000)
            log_utils.log('Download Complete: %s -> %s' % (url, full_path), log_utils.LOGDEBUG)

    except Exception as e:
        log_utils.log('Error (%s) during download: %s -> %s' % (str(e), url, file_name), log_utils.LOGERROR)
        kodi.notify(msg=i18n('download_error') % (str(e), file_name), duration=5000)
Ejemplo n.º 27
0
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import time
import kodi
import cProfile
import StringIO
import pstats
from xbmc import LOGDEBUG, LOGERROR, LOGFATAL, LOGINFO, LOGNONE, LOGNOTICE, LOGSEVERE, LOGWARNING  # @UnusedImport

# TODO: Remove after next SALTS release
name = kodi.get_name()
enabled_comp = kodi.get_setting('enabled_comp')
if enabled_comp:
    enabled_comp = enabled_comp.split(',')
else:
    enabled_comp = None


def log(msg, level=LOGDEBUG, component=None):
    req_level = level
    # override message level to force logging when addon logging turned on
    if kodi.get_setting('addon_debug') == 'true' and level == LOGDEBUG:
        level = LOGNOTICE

    try:
        if isinstance(msg, unicode):
Ejemplo n.º 28
0
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import time
import kodi
import cProfile
import StringIO
import pstats
from xbmc import LOGDEBUG, LOGERROR, LOGFATAL, LOGINFO, LOGNONE, LOGNOTICE, LOGSEVERE, LOGWARNING  # @UnusedImport

# TODO: Remove after next SALTS release
name = kodi.get_name()
enabled_comp = kodi.get_setting('enabled_comp')
if enabled_comp:
    enabled_comp = enabled_comp.split(',')
else:
    enabled_comp = None

def log(msg, level=LOGDEBUG, component=None):
    req_level = level
    # override message level to force logging when addon logging turned on
    if kodi.get_setting('addon_debug') == 'true' and level == LOGDEBUG:
        level = LOGNOTICE
    
    try:
        if isinstance(msg, unicode):
            msg = '%s (ENCODED)' % (msg.encode('utf-8'))
Ejemplo n.º 29
0
def download_media(url, path, file_name, translations, progress=None):
    try:
        if progress is None:
            progress = int(kodi.get_setting('down_progress'))
            
        i18n = translations.i18n
        active = not progress == PROGRESS.OFF
        background = progress == PROGRESS.BACKGROUND
            
        with kodi.ProgressDialog(kodi.get_name(), i18n('downloading') % (file_name), background=background, active=active) as pd:
            try:
                headers = dict([item.split('=') for item in (url.split('|')[1]).split('&')])
                for key in headers: headers[key] = urllib.unquote(headers[key])
            except:
                headers = {}
            if 'User-Agent' not in headers: headers['User-Agent'] = BROWSER_UA
            request = urllib2.Request(url.split('|')[0], headers=headers)
            response = urllib2.urlopen(request)
            if 'Content-Length' in response.info():
                content_length = int(response.info()['Content-Length'])
            else:
                content_length = 0
    
            file_name += '.' + get_extension(url, response)
            full_path = os.path.join(path, file_name)
            logger.log('Downloading: %s -> %s' % (url, full_path), log_utils.LOGDEBUG)
    
            path = kodi.translate_path(xbmc.makeLegalFilename(path))
            try:
                try: xbmcvfs.mkdirs(path)
                except: os.makedirs(path)
            except Exception as e:
                logger.log('Path Create Failed: %s (%s)' % (e, path), log_utils.LOGDEBUG)
    
            if not path.endswith(os.sep): path += os.sep
            if not xbmcvfs.exists(path):
                raise Exception(i18n('failed_create_dir'))
            
            file_desc = xbmcvfs.File(full_path, 'w')
            total_len = 0
            cancel = False
            while True:
                data = response.read(CHUNK_SIZE)
                if not data:
                    break
    
                if pd.is_canceled():
                    cancel = True
                    break
    
                total_len += len(data)
                if not file_desc.write(data):
                    raise Exception(i18n('failed_write_file'))
    
                percent_progress = (total_len) * 100 / content_length if content_length > 0 else 0
                logger.log('Position : %s / %s = %s%%' % (total_len, content_length, percent_progress), log_utils.LOGDEBUG)
                pd.update(percent_progress)
            
            file_desc.close()

        if not cancel:
            kodi.notify(msg=i18n('download_complete') % (file_name), duration=5000)
            logger.log('Download Complete: %s -> %s' % (url, full_path), log_utils.LOGDEBUG)

    except Exception as e:
        logger.log('Error (%s) during download: %s -> %s' % (str(e), url, file_name), log_utils.LOGERROR)
        kodi.notify(msg=i18n('download_error') % (str(e), file_name), duration=5000)
Ejemplo n.º 30
0
def buildDir(items,
             content='dirs',
             cm=[],
             search=False,
             stopend=False,
             isVideo=False,
             isDownloadable=False,
             cache=True,
             chaturbate=False):

    if items == None or len(items) == 0:
        xbmc.executebuiltin('Dialog.Close(busydialog)')
        sys.exit()

    sysaddon = sys.argv[0]
    syshandle = int(sys.argv[1])

    if chaturbate:
        import sqlite3
        databases = xbmc.translatePath(
            os.path.join(kodi.datafolder, 'databases'))
        chaturbatedb = xbmc.translatePath(
            os.path.join(databases, 'chaturbate.db'))
        conn = sqlite3.connect(chaturbatedb)
        conn.text_factory = str
        c = conn.cursor()
        c.execute("SELECT * FROM chaturbate ORDER BY name ASC")
        chat_urls = []
        for (chat_name, chat_url, chat_icon) in c.fetchall():
            chat_urls.append(chat_url)

    for i in items:

        try:

            name = i['name']

            if 'file_path' not in name:
                try:
                    name = client.replaceHTMLCodes(name)
                    name = kodi.sortX(name)
                except:
                    pass
            else:
                name = name.replace('file_path', '')

            item = xbmcgui.ListItem(label=name)

            try:
                if i['description']: description = i['description']
            except:
                description = name

            try:
                description = client.replaceHTMLCodes(description)
                description = kodi.sortX(description)
            except:
                pass

            kodi.giveColor(description, 'white', True)
            item.setInfo('video', {'title': name, 'plot': description})

            try:
                name = urllib.quote_plus(name)
            except:
                name = name.replace(' ', '+')

            try:
                if i['url']: url = i['url']
                else: url = 'none'
            except:
                url = 'none'
            if i['icon'] == None: thumb = kodi.addonicon
            else: thumb = i['icon']
            if i['fanart'] == None: fanart = kodi.addonicon
            else: fanart = i['fanart']
            if (not thumb == 'local') and (not fanart == 'local'):
                item.setArt({'icon': thumb, 'thumb': thumb, 'fanart': fanart})
            else:
                item.setArt({'icon': url, 'thumb': url, 'fanart': fanart})

            try:
                if i['folder']: _folder = True
                else: _folder = False
            except:
                _folder = True

            try:
                if i['isDownloaded']: isDownloaded = True
                else: isDownloaded = False
            except:
                isDownloaded = False

            if not isDownloadable:
                try:
                    if i['isDownloadable']: isDownloadable = True
                    else: isDownloadable = False
                except:
                    isDownloadable = False

            if 'typeid=history' in url:
                url = url.replace('typeid=history', '')
                history = '%s?url=%s&mode=%s' \
                % (sysaddon,urllib.quote_plus(url),str('24'))
                htext = "Remove from History"
                cm.append(('%s' % htext, 'xbmc.RunPlugin(' + history + ')'))

            if 'search_term=' in url:
                search_term = '%s?url=%s&mode=%s' \
                % (sysaddon,urllib.quote_plus(url),str('25'))
                stext = "Remove Search Term"
                cm.append(
                    ('%s' % stext, 'xbmc.RunPlugin(' + search_term + ')'))
                url = url.replace('search_term=', '')

            u= '%s?url=%s&mode=%s&name=%s&iconimage=%s&fanart=%s' \
            % (sysaddon,urllib.quote_plus(url),str(i['mode']),name,urllib.quote_plus(thumb),urllib.quote_plus(fanart))

            if chaturbate:
                if '|CHAT|' in url: check_url = url.split('|CHAT|')[0]
                else: check_url = url.split('|SPLIT|')[0]
                log_utils.log('URL IS %s' % (check_url), log_utils.LOGERROR)
                if check_url in str(chat_urls): chat = 'del'
                else: chat = 'add'

                chat_compiled = '%s?url=%s&mode=%s&name=%s&iconimage=%s&chat=%s&chatmode=%s&folder=%s' \
                % (sysaddon,urllib.quote_plus(check_url),str('101'),name,urllib.quote_plus(thumb),chat,str(i['mode']),str(_folder))

                if chat == 'add': ctext = "Add to"
                elif chat == 'del': ctext = "Remove from"
                cm.append(('%s Chaturbate Monitoring' % ctext,
                           'xbmc.RunPlugin(' + chat_compiled + ')'))

            try:
                if i['fav']: fav = i['fav']
                else: fav = 'add'
            except:
                fav = 'add'

            try:
                if i['cm']:
                    for cmitems in i['cm']:
                        log_utils.log('%s' % (cmitems[1]), log_utils.LOGNOTICE)
                        cm.append(('%s' % cmitems[0],
                                   'xbmc.RunPlugin(' + cmitems[1] + ')'))
            except:
                pass

            favorite = '%s?url=%s&mode=%s&name=%s&iconimage=%s&fav=%s&favmode=%s&folder=%s' \
            % (sysaddon,urllib.quote_plus(url),str('100'),name,urllib.quote_plus(thumb),fav,str(i['mode']),str(_folder))

            if fav == 'add': ftext = "Add to"
            elif fav == 'del': ftext = "Remove from"
            cm.append(('%s %s Favorites' % (ftext, kodi.get_name()),
                       'xbmc.RunPlugin(' + favorite + ')'))

            if isDownloadable:
                dwnld = '%s?url=%s&mode=%s&name=%s&iconimage=%s' \
                % (sysaddon,urllib.quote_plus(url),str('26'),name,urllib.quote_plus(thumb))
                cm.append(('Download Video', 'xbmc.RunPlugin(' + dwnld + ')'))
            if isDownloaded:
                rmdwnld = '%s?url=%s&mode=%s&name=%s' \
                % (sysaddon,urllib.quote_plus(url),str('28'),name)
                cm.append(('Delete Video', 'xbmc.RunPlugin(' + rmdwnld + ')'))

            open_set = '%s?mode=%s' \
            % (sysaddon,str('19'))
            stext = "Open XXX-O-DUS Settings"
            cm.append(('%s' % stext, 'xbmc.RunPlugin(' + open_set + ')'))

            if cm:
                item.addContextMenuItems(cm, replaceItems=False)
                cm = []

            if isVideo:
                codec_info = {'codec': 'h264'}
                item.addStreamInfo('video', codec_info)

            xbmcplugin.addDirectoryItem(handle=syshandle,
                                        url=u,
                                        listitem=item,
                                        isFolder=_folder)

        except Exception as e:
            log_utils.log(
                'Error adding item %s in BuildDir function ( %s %s ):: Error: %s'
                % (name, url, thumb, str(e)), log_utils.LOGERROR)

    if not stopend:
        if chaturbate:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('list')
        elif isVideo:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('thumbs')
        else:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('list')
    if (not search) and (not stopend):
        if cache: xbmcplugin.endOfDirectory(syshandle, cacheToDisc=True)
        else: xbmcplugin.endOfDirectory(syshandle, cacheToDisc=False)
Ejemplo n.º 31
0
    along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

import os
import kodi
import db_utils
from url_dispatcher import URL_Dispatcher


def __enum(**enums):
    return type('Enum', (), enums)


DATABASE_VERSION = 1
DATABASE_FILE = kodi.translate_path('special://database/{0!s}{1!s}.db'.format(
    kodi.get_name(), str(DATABASE_VERSION)))
DATABASE = db_utils.SQLite(DATABASE_FILE)
DISPATCHER = URL_Dispatcher()

ADDON_DATA_DIR = kodi.translate_path('special://profile/addon_data/%s/' %
                                     kodi.get_id())
THUMBNAILS_DIR = kodi.translate_path('special://thumbnails/')
RESOLVER_DIRS = [
    kodi.translate_path(
        'special://home/addons/{0!s}/resources/lib/addon_lib/resolvers/'.
        format(kodi.get_id())),
    kodi.translate_path(
        'special://home/addons/script.module.urlresolver.xxx/resources/plugins/'
    )
]
Ejemplo n.º 32
0
def mainSearch(url):
    
    if '|SPLIT|' in url: url,site = url.split('|SPLIT|')
    term = url
    if term == "null":  term = kodi.get_keyboard('Search %s' % kodi.get_name())

    if term:
        search_on_off  = kodi.get_setting("search_setting")
        if search_on_off == "true":
            delTerm(term)
            addTerm(term)

        display_term = term
        term = urllib.quote_plus(term)
        term = term.lower()

        if site=='all':
            sources = __all__ ; search_sources = []
            for i in sources:
                try:
                    if eval(i + ".search_tag") == 1: search_sources.append(i)
                except: pass

            if search_sources:
                i = 0
                source_num = 0
                failed_list = ''
                line1 = kodi.giveColor('Searching: ','white') + kodi.giveColor('%s','dodgerblue')
                line2 = kodi.giveColor('Found: %s videos','white')
                line3 = kodi.giveColor('Source: %s of ' + str(len(search_sources)),'white')

                kodi.dp.create(kodi.get_name(),'',line2,'')
                xbmc.executebuiltin('Dialog.Close(busydialog)')
                for u in sorted(search_sources):
                    if kodi.dp.iscanceled(): break
                    try:
                        i += 1
                        progress = 100 * int(i)/len(search_sources)
                        kodi.dp.update(progress, line1 % u.title(),line2 % str(source_num),line3 % str(i))
                        search_url = eval(u + ".search_base") % term
                        try: source_n = eval(u+".content('%s',True)" % search_url)
                        except: source_n = 0
                        try: source_n = int(source_n)
                        except: source_n = 0
                        if ( not source_n ): 
                            if failed_list == '': failed_list += str(u).title()
                            else: failed_list += ', %s' % str(u).title()
                        else: source_num += int(source_n)
                    except: pass
                kodi.dp.close()
                if failed_list != '': 
                    kodi.notify(msg='%s failed to return results.' % failed_list, duration=4000, sound=True)
                    log_utils.log('Scrapers failing to return search results are :: : %s' % failed_list, log_utils.LOGERROR)
                else: kodi.notify(msg='%s results found.' % str(source_num), duration=4000, sound=True)
                xbmcplugin.setContent(kodi.syshandle, 'movies')
                xbmcplugin.endOfDirectory(kodi.syshandle, cacheToDisc=True)
                utils.setView('search')
        else:
            search_url = eval(site + ".search_base") % term
            eval(site + ".content('%s')" % search_url)
    else:
        kodi.notify(msg='Blank searches are not allowed.')
        quit()
Ejemplo n.º 33
0
def setViewCM(viewtype):
    window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
    viewid = str(window.getFocusId())
    xbmcaddon.Addon().setSetting("%s_view" % (viewtype), viewid)
    kodi.notify(kodi.get_name(),
                "%s view has been set to (%s)." % (viewtype.title(), viewid))
Ejemplo n.º 34
0
def getMonitoring():

    dirlist = []
    fanarts = xbmc.translatePath(
        os.path.join('special://home/addons/script.xxxodus.artwork',
                     'resources/art/%s/fanart.jpg' % filename))

    conn = sqlite3.connect(chaturbatedb)
    conn.text_factory = str
    c = conn.cursor()
    c.execute("SELECT * FROM chaturbate")
    e = [i for i in c.fetchall()]
    conn.close()

    xbmc.executebuiltin("Dialog.Close(busydialog)")
    kodi.dp.create(kodi.get_name(),
                   "[COLOR white]Currently Checking......[/COLOR]")
    kodi.dp.update(0)
    i = 0
    namelist = []
    urllist = []
    iconlist = []
    countlist = []
    combinedlists = []
    for (name, url, iconimage) in e:
        try:
            iconimage = 'https://roomimg.stream.highwebmedia.com/ri/' + name.lower(
            ) + '.jpg'
            progress = 100 * int(i) / len(e)
            kodi.dp.update(
                progress,
                "[COLOR white]Currently Checking " + name + "[/COLOR]",
                "[COLOR white]Checked " + str(i) + " of " + str(len(e)) +
                "[/COLOR]")
            r = client.request(url)
            if '.m3u8' in r:
                namelist.append(name)
                urllist.append(url)
                iconlist.append(iconimage)
                countlist.append('0')
                combinedlists = list(
                    zip(countlist, namelist, urllist, iconlist))
            else:
                try:
                    last_seen = re.compile(
                        "<dt>Last Broadcast:<\/dt><dd>(.+?)<\/dd>").findall(
                            r)[0]
                except:
                    last_seen = "Unknown"
                namelist.append(name + '|SPLIT|' + last_seen)
                urllist.append(url)
                iconlist.append(iconimage)
                countlist.append('1')
                combinedlists = list(
                    zip(countlist, namelist, urllist, iconlist))
        except:
            namelist.append(name)
            urllist.append(url)
            iconlist.append(iconimage)
            countlist.append('2')
            combinedlists = list(zip(countlist, namelist, urllist, iconlist))
        i += 1
        if kodi.dp.iscanceled(): break

    kodi.dp.close()

    dirlist.append({
        'name':
        kodi.giveColor('Add A Performer To Monitor', 'white', True),
        'url':
        'None',
        'mode':
        31,
        'icon':
        chaturbate_icon,
        'fanart':
        fanarts,
        'folder':
        False
    })
    dirlist.append({
        'name':
        kodi.giveColor('Delete All Performers from List', 'white', True),
        'url':
        'None',
        'mode':
        33,
        'icon':
        chaturbate_icon,
        'fanart':
        fanarts,
        'folder':
        False
    })

    if combinedlists:
        tup = sorted(combinedlists,
                     key=lambda x: (int(x[0]), x[1]),
                     reverse=False)
        for count, title, url, iconimage in tup:
            url += '|CHAT|%s|CHAT|%s' % (base_name, title)
            if count == '0':
                title = '[COLOR pink][B]%s is online now![/B][/COLOR]' % title
            elif count == '1':
                title, last_seen = title.split('|SPLIT|')
                title = '[COLOR white][B]%s[/B][/COLOR] - Offline! - Last Broadcast: %s' % (
                    title, last_seen)
            else:
                title = '[COLOR white][B]%s[/B][/COLOR] - Error Checking!' % title

            dirlist.append({
                'name': title,
                'url': url,
                'mode': player_mode,
                'icon': iconimage,
                'fanart': fanarts,
                'folder': False
            })

    buildDirectory(dirlist,
                   isDownloadable=False,
                   isVideo=True,
                   chaturbate=True)