Esempio n. 1
0
def dwnld_stream(url, name):
    ffmpeg_location = addon.getSetting("ffmpeg location")
    if ffmpeg_location != '':
        try:
            ffmpeg_location = xbmcgui.Dialog().notification(0, i18n('ffmpeg location'), "", "", False, False)
            addon.setSetting(id='ffmpeg_location', value=ffmpeg_location)
            if not os.path.isfile(download_path + 'ffmpeg.exe'):
                notify(i18n('cumination: Could not find ffmpeg!'), download_path + 'ffmpeg.exe')
                return
        except: pass

    cmd = exec_module(ffmpeg_location + 'ffmpeg -i "' + url + '" -vcodec copy -acodec copy "' + download_path + name + time.strftime("%Y%m%d-%H%M%S") + '.mkv"')
    import shlex, subprocess
    SW_HIDE = 0
    info = None
    if os.name == 'nt':
        info = subprocess.STARTUPINFO()
        info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        info.wShowWindow = SW_HIDE
    proc = subprocess.Popen(cmd, shell=True, startupinfo=info)
    xbmc.log(i18n('cumination: Process started at') + str(time.time()))
    xbmc.log(i18n('Process playing ') + cmd)
    time.sleep(10)
    while xbmc.Player.isPlaying():
        xbmc.log(i18n('cumination: Process playing ') + xbmc.Player.getPlayingFile())
        time.sleep(5)
    proc.kill()
    xbmc.log(i18n('Process ended at ') + str(time.time()))
Esempio n. 2
0
def setview():
    skin = xbmc.getSkinDir().lower()
    win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
    viewtype = str(win.getFocusId())
    addon.setSetting('setview', ';'.join([skin, viewtype]))
    addon.setSetting('customview', 'true')
    viewName = xbmc.getInfoLabel('Container.Viewmode')
    notify(i18n('dflt_view_set'), '{0} {1}'.format(i18n('dflt_set'), viewName))
    xbmc.executebuiltin('Container.Refresh')
Esempio n. 3
0
def SetPin():
    selected = dialog.select(i18n('choose_option'), [i18n('set_pin'), i18n('remove_pin')])
    if selected == -1:
        return
    elif selected == 0:
        pincode = AskPin()
        if pincode:
            addon.setSetting('pincode', pincode)
            addon.setSetting('logintime', '')
    elif selected == 1:
        addon.setSetting('pincode', '')
        addon.setSetting('logintime', '')
    return
Esempio n. 4
0
def CheckPin():
    now = time.time()
    hashedpin = addon.getSetting('pincode')
    logintime = addon.getSetting('logintime')
    if not logintime:
        logintime = 0
    timecheck = now - (60 * 60)
    if not float(logintime) < timecheck:
        return True
    if hashedpin:
        pinhash = AskPin()
        if pinhash == hashedpin:
            addon.setSetting('logintime', str(now))
            return True
        else:
            retry = dialog.yesno(i18n('pin_incorrect'), '{0}[CR]{1}?'.format(i18n('incorrect_msg'), i18n('retry')), yeslabel=i18n('retry'))
            if retry:
                return CheckPin()
            else:
                return False
    return True
Esempio n. 5
0
def setUnsorted():
    addon.setSetting('keywords_sorted', 'false')
    xbmc.executebuiltin('Container.Refresh')
Esempio n. 6
0
def downloadVideo(url, name):

    def _pbhook(downloaded, filesize, url=None, dp=None, name=''):
        try:
            percent = min(int((downloaded * 100) / filesize), 100)
            currently_downloaded = float(downloaded) / (1024 * 1024)
            kbps_speed = int(downloaded / (time.perf_counter() if PY3 else time.clock() - start))
            if kbps_speed > 0:
                eta = (filesize - downloaded) / kbps_speed
            else:
                eta = 0
            kbps_speed = kbps_speed / 1024
            total = float(filesize) / (1024 * 1024)
            mbs = '%.02f MB of %.02f MB' % (currently_downloaded, total)
            e = 'Speed: %.02f Kb/s ' % kbps_speed
            e += 'ETA: %02d:%02d' % divmod(eta, 60)
            dp.update(percent, '{0}[CR]{1}[CR]{2}'.format(name[:50], mbs, e))
        except:
            percent = 100
            dp.update(percent)
        if dp.iscanceled():
            dp.close()
            raise StopDownloading('Stopped Downloading')

    def getResponse(url, headers2, size):
        try:
            if size > 0:
                size = int(size)
                headers2['Range'] = 'bytes=%d-' % size

            req = Request(url, headers=headers2)

            resp = urlopen(req, timeout=30)
            return resp
        except:
            return None

    def doDownload(url, dest, dp, name):
        headers = {}
        if '|' in url:
            url, uheaders = url.split('|')
            headers = dict(urllib_parse.parse_qsl(uheaders))

        if 'User-Agent' not in list(headers.keys()):
            headers.update({'User-Agent': USER_AGENT})

        resp = getResponse(url, headers, 0)

        if not resp:
            dialog.ok("Cumination", '{0}[CR]{1}'.format(i18n('dnld_fail'), i18n('no_resp')))
            return False
        try:
            content = int(resp.headers['Content-Length'])
        except:
            content = 0
        try:
            resumable = 'bytes' in resp.headers['Accept-Ranges'].lower()
        except:
            resumable = False
        if resumable:
            six.print_("Download is resumable")

        if content < 1:
            dialog.ok("Cumination", '{0}[CR]{1}'.format(i18n('unkn_size'), i18n('no_dnld')))
            return False

        size = 8192
        mb = content / (1024 * 1024)

        if content < size:
            size = content

        total = 0
        errors = 0
        count = 0
        resume = 0
        sleep = 0

        six.print_('{0} : {1}MB {2} '.format(i18n('file_size'), mb, dest))
        f = xbmcvfs.File(dest, 'w')

        chunk = None
        chunks = []

        while True:
            downloaded = total
            for c in chunks:
                downloaded += len(c)
            percent = min(100 * downloaded / content, 100)

            _pbhook(downloaded, content, url, dp, name)

            chunk = None
            error = False

            try:
                chunk = resp.read(size)
                if not chunk:
                    if percent < 99:
                        error = True
                    else:
                        while len(chunks) > 0:
                            c = chunks.pop(0)
                            f.write(c)
                            del c
                        f.close()
                        return True

            except Exception as e:
                six.print_(str(e))
                error = True
                sleep = 10
                errno = 0

                if hasattr(e, 'errno'):
                    errno = e.errno

                if errno == 10035:  # 'A non-blocking socket operation could not be completed immediately'
                    pass

                if errno == 10054:  # 'An existing connection was forcibly closed by the remote host'
                    errors = 10  # force resume
                    sleep = 30

                if errno == 11001:  # 'getaddrinfo failed'
                    errors = 10  # force resume
                    sleep = 30

            if chunk:
                errors = 0
                chunks.append(chunk)
                if len(chunks) > 5:
                    c = chunks.pop(0)
                    f.write(c)
                    total += len(c)
                    del c

            if error:
                errors += 1
                count += 1
                xbmc.sleep(sleep * 1000)

            if (resumable and errors > 0) or errors >= 10:
                if (not resumable and resume >= 50) or resume >= 500:
                    # Give up!
                    return False

                resume += 1
                errors = 0
                if resumable:
                    chunks = []
                    # create new response
                    resp = getResponse(url, headers, total)
                else:
                    # use existing response
                    pass

    def clean_filename(s):
        if not s:
            return ''
        badchars = '\\/:*?\"<>|\''
        for c in badchars:
            s = s.replace(c, '')
        return s.strip()

    download_path = addon.getSetting('download_path')
    if download_path == '':
        try:
            download_path = dialog.browse(0, i18n('dnld_path'), "", "", False, False)
            addon.setSetting(id='download_path', value=download_path)
            if not xbmcvfs.exists(download_path):
                xbmcvfs.mkdir(download_path)
        except:
            pass
    if download_path != '':
        dp = xbmcgui.DialogProgress()
        name = re.sub(r'\[COLOR.+?\/COLOR\]', '', name).strip()
        dp.create(i18n('cum_dnld'), name[:50])
        tmp_file = tempfile.mktemp(dir=download_path, suffix=".mp4")
        tmp_file = xbmc.makeLegalFilename(tmp_file) if PY2 else xbmcvfs.makeLegalFilename(tmp_file)
        start = time.perf_counter() if PY3 else time.clock()
        try:
            downloaded = doDownload(url, tmp_file, dp, name)
            if downloaded:
                if PY2:
                    vidfile = xbmc.makeLegalFilename(download_path + clean_filename(name) + ".mp4")
                else:
                    vidfile = xbmcvfs.makeLegalFilename(download_path + clean_filename(name) + ".mp4")
                try:
                    xbmcvfs.rename(tmp_file, vidfile)
                    return vidfile
                except:
                    return tmp_file
            else:
                raise StopDownloading(i18n('stop_dnld'))
        except:
            while xbmcvfs.exists(tmp_file):
                try:
                    xbmcvfs.delete(tmp_file)
                    break
                except:
                    pass
Esempio n. 7
0
def set_setting(id, value):
    if not isinstance(value, six.string_types):
        value = str(value)
    addon.setSetting(id, value)