Пример #1
0
def episode(name=None, url=None):
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()

    waserror = False
    linklist = []
    litems = []
    if len(url) == '':
        waserror = True
    else:
        html = DL(url)
        linklist = ws.findvidlinks(html)
        itemparent = None
    if len(linklist) > 0:
        for name, link in linklist:
            itempath = plugin.url_for(play, url=link)
            item = dict(label=name, label2=link, icon='DefaultFolder.png', thumbnail='DefaultFolder.png', path=itempath)
            item.setdefault(item.keys()[0])
            litems.append(item)
        vitems = ws.sortSourceItems(litems)
        litems = []
        for li in vitems:
            item = ListItem.from_dict(**li)
            item.set_is_playable(True)
            item.set_info(info_type='video', info_labels={'Title': item.label, 'Plot': item.label2})
            item.add_stream_info(stream_type='video', stream_values={})
            litems.append(item)
    else:
        waserror = True
    if waserror:
        plugin.notify(title="ERROR No links: {0}".format(name), msg=url)
        return []
    return litems
Пример #2
0
def serve():
    emoji = choice(CHOICES)

    import web_pdb
    web_pdb.set_trace()

    return render_template("index.html", emoji=emoji)
def handlerDiff(data, *args, **kwargs):
    if kwargs.get("test_mode", False):
        web_pdb.set_trace()

    print(data)
    waste_time()
    return data[1] - data[0]
Пример #4
0
def get_video(url):
    UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'

    if '.m3u8' in url:
        listItem = xbmcgui.ListItem(path=str(url))
        xbmcplugin.setResolvedUrl(_thisPlugin, True, listItem)
    elif 'yoursportsinhd' in url:
        req5 = urllib2.Request(url)
        req5.add_header('User-Agent', UA)

        response5 = urllib2.urlopen(req5)
        link5 = response5.read()
        result5 = re.findall(r'src: "(.*?)"', link5, re.DOTALL)
        for item6 in result5:
            if 'nasa' not in item6:
                listItem = xbmcgui.ListItem(path=str(item6))
                xbmcplugin.setResolvedUrl(_thisPlugin, True, listItem)

    elif 'qif' in url:
        import web_pdb
        web_pdb.set_trace()
        i = 1
        req6 = urllib2.Request(url)
        response6 = urllib2.urlopen(req6)
        link6 = response6.read()

        result6 = re.findall(r'<iframe width="336"(.*?)</iframe>', link6,
                             re.DOTALL)
        for item6 in result6:
            links = item6.split('src="')[1].split('"')[0]
            links = url + links
            name = 'link' + str(i)
            i += 1
            addLink(name, links, 3, '')
    else:
        i = 1
        import web_pdb
        web_pdb.set_trace()
        req4 = urllib2.Request(url)
        response4 = urllib2.urlopen(req4)
        link4 = response4.read()
        result4 = re.findall(r'source: "(.*?)",', link4, re.DOTALL)
        result7 = re.findall(r'URL=(.*?)">', link4, re.DOTALL)
        for item7 in result7:
            linkers = item7
        req7 = urllib2.Request(linkers)
        response7 = urllib2.urlopen(req7)
        link7 = response7.read()
        result6 = re.findall(r'<iframe width="336"(.*?)</iframe>', link7,
                             re.DOTALL)
        for item4 in result4:
            listItem = xbmcgui.ListItem(path=str(item4))
            xbmcplugin.setResolvedUrl(_thisPlugin, True, listItem)
        for item5 in result6:
            links = item5.split('src="')[1].split('"')[0]
            links = linkers + links
            name = 'link' + str(i)
            i += 1
            addLink(name, links, 3, '')
def handler(data, field, *args, **kwargs):
    if kwargs.get("test_mode", False):
        web_pdb.set_trace()

    waste_time()
    if random.random() < error_threshold:
        raise Exception("invalid data encountered")
    return data[field]
Пример #6
0
def search():
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()

    searchtxt = plugin.get_setting('lastsearch')
    searchtxt = plugin.keyboard(searchtxt, 'Search Watchseries-Online', False)
    if len(searchtxt) > 1:
        plugin.set_setting(key='lastsearch', val=searchtxt)
        return ws.query(searchquery=searchtxt)
    else:
        return []
Пример #7
0
def index(request):
    import web_pdb
    web_pdb.set_trace()
    log.info("Hello Pycon")
    talks = Talk.objects.all().select_related()
    log.info("Rendering")
    return render(request, 'webpdbexample/index.html', {
        'year': 2016,
        "talks": talks
    })
Пример #8
0
def search():
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()

    searchtxt = plugin.get_setting('lastsearch')
    searchtxt = plugin.keyboard(searchtxt, 'Search Watchseries-Online', False)
    if len(searchtxt) > 1:
        plugin.set_setting(key='lastsearch', val=searchtxt)
        return ws.query(searchquery=searchtxt)
    else:
        return []
Пример #9
0
def saved():
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()

    litems = []
    sitems = []
    sitems = ws.loadsaved()
    noitem = {'label': "No Saved Shows", 'icon': 'DefaultFolder.png', 'path': plugin.url_for('index')}
    if len(sitems) < 1:
        return [noitem]
    else:
        return sitems
Пример #10
0
def latest(offset=0, urlpath='last-350-episodes'):
    DEBUGON = plugin.get_setting('debugon', converter=bool)
    if DEBUGON: web_pdb.set_trace()
    url = ws.BASEURL + '/' + urlpath
    fullhtml = ws.DL(url)
    html = fullhtml.partition("</nav>")[-1].split("</ul>", 1)[0]
    strDate = ur"<li class='listEpisode'>(\d+ \d+ \d+) : "
    strUrl = ur'<a.+?href="([^"]*?)">'
    strName = ur'</span>([^<]*?)</a>'
    regexstr = "{0}{1}.+?{2}".format(strDate, strUrl, strName)
    matches = re.compile(regexstr).findall(html)
    litems = []
    epdate = ''
    eptitle = ''
    filtertxt = plugin.get_setting('filtertext')
    itemnext = {
        'label': 'Next ->',
        'icon': 'DefaultFolder.png',
        'thumbnail': 'DefaultFolder.png',
        'path': plugin.url_for(latest,
                               offset=int(offset) + 400,
                               urlpath=urlpath)
    }
    if len(matches) > 500:
        matches = matches[0:500]
    ws.Episode = episode
    if DEBUGON:

        def debugitems():
            with web_pdb.catch_post_mortem():
                for epdate, eplink, epname in matches:
                    item = category_episodemake(epname, eplink, epdate)
                    # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
                    dateout = epdate.replace(' ', '-').strip()
                    item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(
                        dateout)
                    litems.append(item)
                litems.append(itemnext)

        items = debugitems()
        return items
    try:
        for epdate, eplink, epname in matches:
            item = category_episodemake(epname, eplink, epdate)
            # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
            dateout = epdate.replace(' ', '-').strip()
            item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(
                dateout)
            litems.append(item)
        litems.append(itemnext)
    except Exception as ex:
        print('ADDON ERROR: {0}'.format(str(repr(ex.message))))
        print(str(repr(ex)))
    return litems
Пример #11
0
def autoplay(url=''):
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()

    if len(url) < 1:
        return None
    sourceslist = []
    litems = []
    idx = 0
    prefhost = ''
    html = ws.DL(url)
    selItem = None
    outtxt = "Not Found"
    thispath = plugin.url_for(endpoint=play, url=url)
    stext = plugin.get_setting('topSources')
    if len(stext) < 1:
        prefhost = 'thevideo'
    else:
        sourceslist = stext.split(',')
        prefhost = sourceslist[0]
    try:
        for fitem in plugin.added_items:
            if fitem.selected == True or fitem.path.find(thispath) != -1:
                try:
                    plugin.set_resolved_url(fitem)
                    fitem.is_playable(True)
                    fitem.played(True)
                except:
                    pass
                selItem = fitem
                plugin.notify(msg=selItem.label, title="Found item")
                break
    except:
        selItem = None
    if selItem is not None:
        try:
            selItem.set_is_playable(True)
            selItem.set_played(was_played=True)
            outtxt = selItem.label + " " + selItem.label2
        except:
            outtxt = str(repr(selItem))
    linklist = ws.findvidlinks(html, findhost=prefhost)
    if len(linklist) > 0:
        name, link = linklist[0]
        itempath = plugin.url_for(play, url=link)
        sitem = dict(label=name, label2=link, icon='DefaultFolder.png', thumbnail='DefaultFolder.png', path=itempath)
        sitem.setdefault(sitem.keys()[0])
        item = ListItem.from_dict(**sitem)
        item.set_is_playable(True)
        item.set_info(type='video', info_labels={'Title': item.label, 'Plot': item.label2})
        item.add_stream_info(stream_type='video', stream_values={})
        plugin.notify(msg=link, title=name)
        item.set_played(was_played=True)
        plugin.play_video(item)
        return [plugin.set_resolved_url(item)]
Пример #12
0
def get_following():
    allfollowedblogs = []
    if doDebug():
        web_pdb.set_trace()
        with web_pdb.catch_post_mortem():
            allfollowedblogs = refresh_following()
            save_following(allblogs=allfollowedblogs)
            return allfollowedblogs
    else:
        allfollowedblogs = refresh_following()
        save_following(allblogs=allfollowedblogs)
        return allfollowedblogs
Пример #13
0
def play(url):
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()

    resolved = ''
    stream_url = ''
    item = None
    try:
        import urlresolver
        resolved = urlresolver.HostedMediaFile(url).resolve()
        if not resolved or resolved == False or len(resolved) < 1:
            resolved = urlresolver.resolve(url)
            if resolved is None or len(resolved) < 1:
                resolved = urlresolver.resolve(WebUtils.unescape(url))
        if len(resolved) > 1:
            plugin.notify(msg="PLAY {0}".format(resolved.partition('.')[-1]), title="URLRESOLVER", delay=1000)
            plugin.set_resolved_url(resolved)
            item = ListItem.from_dict(path=resolved)
            item.add_stream_info('video', stream_values={})
            item.set_is_playable(True)
            return item
    except:
        resolved = ''
        plugin.notify(msg="FAILED {0}".format(url.partition('.')[-1]), title="URLRESOLVER", delay=1000)
    try:
        import YDStreamExtractor
        info = YDStreamExtractor.getVideoInfo(url, resolve_redirects=True)
        resolved = info.streamURL()
        for s in info.streams():
            try:
                stream_url = s['xbmc_url'].encode('utf-8', 'ignore')
                xbmc.log(msg="**YOUTUBE-DL Stream found: {0}".format(stream_url))
            except:
                pass
        if len(stream_url) > 1:
            resolved = stream_url
        if len(resolved) > 1:
            plugin.notify(msg="Playing: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000)
            plugin.set_resolved_url(resolved)
            item = ListItem.from_dict(path=resolved)
            item.add_stream_info('video', stream_values={})
            item.set_is_playable(True)
            return item
    except:
        plugin.notify(msg="Failed: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000)

    if len(resolved) > 1:
        plugin.set_resolved_url(resolved)
        item = ListItem.from_dict(path=resolved)
        return item
    else:
        plugin.set_resolved_url(url)  # url)
        return None
Пример #14
0
def removeshow(name='', link=''):
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()

    sitems = []
    litems = []
    sitems = ws.loadsaved()
    for item in sitems:
        if item.get('name') == name or item.get('link') == link:
            plugin.notify(title='Removed {0}'.format(name), msg='Removed "{0}": {1}'.format(name, link))
        else:
            litems.append(item)
    jsout = json.dumps(litems)
    plugin.addon.setSetting('savedshows', jsout)
    plugin.notify(title='Removed {0}'.format(name), msg='{0} Removed Show link: {1}'.format(name, link))
def csv_pop(data, *args, **kwargs):
    if kwargs.get("test_mode", False):
        web_pdb.set_trace()

    waste_time(1000000)
    path = "data/csv/aapl.csv"
    df = pd.read_csv(path)

    if df.size > 0:
        item = df.iloc[0].to_dict()
        df.drop(0, inplace=True)
        df.to_csv(path, index=False)

        item.pop("Volume")
        return item
Пример #16
0
def resolveurl():
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()

    url = plugin.keyboard(default='', heading='Video Page URL')
    if url is not None:
        name = url
        if len(url) > 0:
            item = ListItem(label=name, label2=url, icon='DefaultVideo.png', thumbnail='DefaultVideo.png',
                            path=plugin.url_for(endpoint=play, url=url))
            item.playable = True
            item.set_info(type='video', info_labels={'Title': url, 'Plot': url})
            item.add_stream_info(stream_type='video', stream_values={})
            playable = play(url)
            plugin.notify(msg=playable.path, title="Playing..")
            plugin.play_video(playable)
    plugin.clear_added_items()
    plugin.end_of_directory()
def doCompute():
#
#   Start debugging before computation starts
#
	web_pdb.set_trace()
#
	while True:
		xa.doInput()
		inp = xa.Input['Input1'][0,0,:]
#
#   Add some more local variables
#
		inline = xa.TI['inl']
		crossline = xa.TI['crl']
#
		xa.Output = inp
		xa.doOutput()
Пример #18
0
def latest(offset=0, urlpath='last-350-episodes'):
    DEBUGON = plugin.get_setting('debugon', converter=bool)
    if DEBUGON: web_pdb.set_trace()
    url = ws.BASEURL + '/' + urlpath
    fullhtml = ws.DL(url)
    html = fullhtml.partition("</nav>")[-1].split("</ul>", 1)[0]
    strDate = ur"<li class='listEpisode'>(\d+ \d+ \d+) : "
    strUrl = ur'<a.+?href="([^"]*?)">'
    strName = ur'</span>([^<]*?)</a>'
    regexstr = "{0}{1}.+?{2}".format(strDate, strUrl, strName)
    matches = re.compile(regexstr).findall(html)
    litems = []
    epdate = ''
    eptitle = ''
    filtertxt = plugin.get_setting('filtertext')
    itemnext = {'label': 'Next ->', 'icon': 'DefaultFolder.png', 'thumbnail': 'DefaultFolder.png',
                'path': plugin.url_for(latest, offset=int(offset) + 400, urlpath=urlpath)}
    if len(matches) > 500:
        matches = matches[0:500]
    ws.Episode = episode
    if DEBUGON:
        def debugitems():
            with web_pdb.catch_post_mortem():
                for epdate, eplink, epname in matches:
                    item = category_episodemake(epname, eplink, epdate)
                    # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
                    dateout = epdate.replace(' ', '-').strip()
                    item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(dateout)
                    litems.append(item)
                litems.append(itemnext)

        items = debugitems()
        return items
    try:
        for epdate, eplink, epname in matches:
            item = category_episodemake(epname, eplink, epdate)
            # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
            dateout = epdate.replace(' ', '-').strip()
            item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(dateout)
            litems.append(item)
        litems.append(itemnext)
    except Exception as ex:
        print('ADDON ERROR: {0}'.format(str(repr(ex.message))))
        print(str(repr(ex)))
    return litems
Пример #19
0
def debug_init():
    """
    start debugger if it's enabled
    also dump argv if spamLog
    :return:
    """
    if plugin_addon.getSetting('remote_debug') == 'true':
        # try pycharm first
        try:
            import pydevd
            # try to connect multiple times...in case we forgot to start it
            # TODO Show a message to the user that we are waiting on the debugger
            connected = False
            tries = 0
            while not connected and tries < 60:
                try:
                    pydevd.settrace(host=plugin_addon.getSetting('remote_ip'),
                                    stdoutToServer=True,
                                    stderrToServer=True,
                                    port=5678,
                                    suspend=False)
                    eh.spam('Connected to debugger')
                    connected = True
                except:
                    tries += 1
                    # we keep this message the same, as kodi will merge them into Previous line repeats...
                    eh.spam('Failed to connect to debugger')
                    xbmc.sleep(1000)
        except (ImportError, NameError):
            eh.log(
                'unable to import pycharm debugger, falling back on the web-pdb'
            )
            try:
                import web_pdb
                web_pdb.set_trace()
            except Exception:
                eh.exception(ErrorPriority.NORMAL,
                             'Unable to start debugger, disabling it')
                plugin_addon.setSetting('remote_debug', 'false')
        except:
            eh.exception(ErrorPriority.HIGHEST, 'Unable to start debugger')

    eh.spam('argv:', sys.argv)
Пример #20
0
def category2(name='', url=''):
    DEBUGON = plugin.get_setting('debugon', converter=bool)
    if DEBUGON: web_pdb.set_trace()
    #url = ws.BASEURL + '/' + urlpath
    fullhtml = ws.DL(url)
    html = fullhtml.partition("</nav>")[-1].split("</ul>", 1)[0]
    strDate = ur"<li class='listEpisode'>(\d+ \d+ \d+) : "
    strUrl = ur'<a.+?href="([^"]*?)">'
    strName = ur'</span>([^<]*?)</a>'
    #regexstr = "{0}{1}.+?{2}".format(strDate, strUrl, strName)
    regexstr = "<li class=.listEpisode.>.+?{0}.+?{1}".format(strUrl, strName)
    matches = re.compile(regexstr).findall(html)
    litems = []
    eptitle = ''
    ws.Episode = episode
    if DEBUGON:

        def debugitems():
            with web_pdb.catch_post_mortem():
                litems = []
                for eplink, epname in matches:
                    item = category_episodemake(epname, eplink, dateadded=None)
                    itempath = plugin.url_for(endpoint=episode,
                                              name=epname,
                                              url=eplink)
                    #dateout = epdate.replace(' ', '-').strip()
                    #item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(dateout)
                    litems.append(item)
                return litems

        items = debugitems()
        return items
    try:
        for eplink, epname in matches:
            item = category_episodemake(epname, eplink, dateadded=None)
            # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
            #dateout = epdate.replace(' ', '-').strip()
            #item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(dateout)
            litems.append(item)
    except Exception as ex:
        print('ADDON ERROR: {0}'.format(str(repr(ex.message))))
        print(str(repr(ex)))
    return litems
Пример #21
0
def play_video(path):
    """
    Play a video by the provided path.

    :param path: str
    """
    import web_pdb
    web_pdb.set_trace()
    # Create a playable item with a path to play.
    videos = []
    html = requests.get(path).text
    mlink = SoupStrainer('div', {'class': re.compile(r'video\p')})
    soup = BeautifulSoup(html, parseOnlyThese=mlink)
    stream_url = re.findall(r'(http[s]?://\S+)', soup.text)[1]
    print stream_url
    #url=resolve_url(stream_url)
    #print url
    play_item = xbmcgui.ListItem(path=path)
    play_item.setPath(re.sub(r'^"|"$', '', stream_url))
    # Pass the item to the Kodi player.
    xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)
Пример #22
0
def saveshow(name='', link=''):
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()
    ws.Category = category
    sitems = []
    litems = []
    try:
        savedpath = path.join(ws.datadir, "saved.json")
        if path.exists(savedpath):
            fpin = file(savedpath)
            rawjson = fpin.read()
            sitems = json.loads(rawjson)
            fpin.close()
        saveitem = ws.makecatitem(name, link)
        # saveitem = {'label': name, 'path': plugin.url_for(endpoint=category, name=name, url=link)}
        # saveitem.setdefault(saveitem.keys()[0])
        sitems.append(saveitem)
        fpout = file(savedpath, mode='w')
        json.dump(sitems, fpout)
        fpout.close()
        plugin.notify(msg="SAVED {0}".format(name), title=link)
    except:
        plugin.notify(msg="ERROR save failed for {0}".format(name), title=link)
Пример #23
0
def saveshow(name='', link=''):
    if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace()
    ws.Category = category
    sitems = []
    litems = []
    try:
        savedpath = path.join(ws.datadir, "saved.json")
        if path.exists(savedpath):
            fpin = file(savedpath)
            rawjson = fpin.read()
            sitems = json.loads(rawjson)
            fpin.close()
        saveitem = ws.makecatitem(name, link)
        # saveitem = {'label': name, 'path': plugin.url_for(endpoint=category, name=name, url=link)}
        # saveitem.setdefault(saveitem.keys()[0])
        sitems.append(saveitem)
        fpout = file(savedpath, mode='w')
        json.dump(sitems, fpout)
        fpout.close()
        plugin.notify(msg="SAVED {0}".format(name), title=link)
    except:
        plugin.notify(msg="ERROR save failed for {0}".format(name), title=link)
Пример #24
0
def category2(name='', url=''):
    DEBUGON = plugin.get_setting('debugon', converter=bool)
    if DEBUGON: web_pdb.set_trace()
    #url = ws.BASEURL + '/' + urlpath
    fullhtml = ws.DL(url)
    html = fullhtml.partition("</nav>")[-1].split("</ul>", 1)[0]
    strDate = ur"<li class='listEpisode'>(\d+ \d+ \d+) : "
    strUrl = ur'<a.+?href="([^"]*?)">'
    strName = ur'</span>([^<]*?)</a>'
    #regexstr = "{0}{1}.+?{2}".format(strDate, strUrl, strName)
    regexstr = "<li class=.listEpisode.>.+?{0}.+?{1}".format(strUrl, strName)
    matches = re.compile(regexstr).findall(html)
    litems = []
    eptitle = ''
    ws.Episode = episode
    if DEBUGON:
        def debugitems():
            with web_pdb.catch_post_mortem():
                litems = []
                for eplink, epname in matches:
                    item = category_episodemake(epname, eplink, dateadded=None)
                    itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
                    #dateout = epdate.replace(' ', '-').strip()
                    #item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(dateout)
                    litems.append(item)
                return litems
        items = debugitems()
        return items
    try:
        for eplink, epname in matches:
            item = category_episodemake(epname, eplink, dateadded=None)
            # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
            #dateout = epdate.replace(' ', '-').strip()
            #item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(dateout)
            litems.append(item)
    except Exception as ex:
        print('ADDON ERROR: {0}'.format(str(repr(ex.message))))
        print(str(repr(ex)))
    return litems
Пример #25
0
def post_search(request):
    # query zostało wysłane razem z url
    form = SearchForm()
    # szukanie parametru query w url
    if 'query' in request.GET:
        import web_pdb
        web_pdb.set_trace()
        form = SearchForm(request.GET)
        if form.is_valid():
            cd = form.cleaned_data
            # pobranie wszystkich obiektów dopasowanych do parametru query
            results = SearchQuerySet().models(Post)\
                .filter(content=cd['query']).load_all()
            # Obliczenie całkowitej liczby wyników.
            total_results = results.count()
            return render(
                request, 'blog/post/search.html', {
                    'form': form,
                    'cd': cd,
                    'results': results,
                    'total_results': total_results
                })
    else:
        return render(request, 'blog/post/search.html', {'form': form})
Пример #26
0
def category(name='', url=''):
    html = u''
    litems = []
    NODATE = False
    banner = 'DefaultVideoFolder.png'
    strDate = ur'<li class="listEpisode">(\d+ \d+ \d+) : '
    strUrl = ur'<a.+?href="([^"]*?)">'
    strName = ur'</span>([^<]*?)</a>'
    regexstr = "{0}{1}.+?{2}".format(strDate, strUrl, strName)
    DEBUGON = plugin.get_setting('debugon', converter=bool)
    if name.endswith('/'):
        regexstr = "{0}.+?{1}".format(strUrl, strName)
        NODATE = True
        url = name + url
    if not str(url).startswith('http') and len(url) > 8: url = ws.BASEURL + '/' + url
    fullhtml = DL(url)
    html = fullhtml.partition("</nav>")[-1].split("</ul>", 1)[0]
    try:
        banner = str(html.split('id="banner_single"', 1)[0].rpartition('src="')[2].split('"', 1)[0])
        if not banner.startswith('http') and banner != 'DefaultVideoFolder.png': banner = ws.BASEURL + banner
    except:
        banner = 'DefaultVideoFolder.png'
    if DEBUGON: web_pdb.set_trace()
    matches = re.compile(regexstr).findall(html)
    if len(matches) > 500: matches = matches[0:500]
    ws.Episode = episode
    if DEBUGON:
        def debugitems():
            with web_pdb.catch_post_mortem():
                if NODATE:
                    for eplink, epname in matches:
                        item = category_episodemake(epname, eplink)
                        item.thumbnail = banner
                        litems.append(item)
                else:
                    for epdate, eplink, epname in matches:
                        item = category_episodemake(epname, eplink)  # epname, eplink, epdate)
                        # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
                        dateout = epdate.replace(' ', '-').strip()
                        item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(dateout)
                        item.thumbnail = banner
                        litems.append(item)
                return litems

        return debugitems()
    else:
        try:
            if NODATE:
                for eplink, epname in matches:
                    item = category_episodemake(epname, eplink)
                    item.thumbnail = banner
                    litems.append(item)
            else:
                for epdate, eplink, epname in matches:
                    item = category_episodemake(epname, eplink, epdate)
                    # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
                    dateout = epdate.replace(' ', '-').strip()
                    item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(dateout)
                    item.thumbnail = banner
                    litems.append(item)
        except Exception as ex:
            print('ADDON ERROR: {0}'.format(str(repr(ex.message))))
            print(str(repr(ex)))
    # return litems
    # for eplink, epname in matches:
    #    item = category_episodemake(epname, eplink)
    #    item.path = plugin.url_for(episode, name=epname, url=eplink)
    #    litems.append(item)
    # if plugin.get_setting('sortalpha', converter=bool):
    #    litems.sort(key=lambda litems: litems.label, reverse=True)
    return litems
Пример #27
0
# coding: utf-8
# Author: Roman Miroshnychenko aka Roman V.M.
# E-mail: [email protected]

from __future__ import print_function
import os
import sys

basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(basedir)

try:
    input = raw_input
except NameError:
    pass

from web_pdb import set_trace
set_trace(patch_stdstreams=True)
foo = input('Enter something: ')
print('You have entered: ' + foo)
Пример #28
0
def category(name='', url=''):
    html = u''
    litems = []
    NODATE = False
    banner = 'DefaultVideoFolder.png'
    strDate = ur'<li class="listEpisode">(\d+ \d+ \d+) : '
    strUrl = ur'<a.+?href="([^"]*?)">'
    strName = ur'</span>([^<]*?)</a>'
    regexstr = "{0}{1}.+?{2}".format(strDate, strUrl, strName)
    DEBUGON = plugin.get_setting('debugon', converter=bool)
    if name.endswith('/'):
        regexstr = "{0}.+?{1}".format(strUrl, strName)
        NODATE = True
        url = name + url
    if not str(url).startswith('http') and len(url) > 8:
        url = ws.BASEURL + '/' + url
    fullhtml = DL(url)
    html = fullhtml.partition("</nav>")[-1].split("</ul>", 1)[0]
    try:
        banner = str(
            html.split('id="banner_single"',
                       1)[0].rpartition('src="')[2].split('"', 1)[0])
        if not banner.startswith(
                'http') and banner != 'DefaultVideoFolder.png':
            banner = ws.BASEURL + banner
    except:
        banner = 'DefaultVideoFolder.png'
    if DEBUGON: web_pdb.set_trace()
    matches = re.compile(regexstr).findall(html)
    if len(matches) > 500: matches = matches[0:500]
    ws.Episode = episode
    if DEBUGON:

        def debugitems():
            with web_pdb.catch_post_mortem():
                if NODATE:
                    for eplink, epname in matches:
                        item = category_episodemake(epname, eplink)
                        item.thumbnail = banner
                        litems.append(item)
                else:
                    for epdate, eplink, epname in matches:
                        item = category_episodemake(
                            epname, eplink)  # epname, eplink, epdate)
                        # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
                        dateout = epdate.replace(' ', '-').strip()
                        item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(
                            dateout)
                        item.thumbnail = banner
                        litems.append(item)
                return litems

        return debugitems()
    else:
        try:
            if NODATE:
                for eplink, epname in matches:
                    item = category_episodemake(epname, eplink)
                    item.thumbnail = banner
                    litems.append(item)
            else:
                for epdate, eplink, epname in matches:
                    item = category_episodemake(epname, eplink, epdate)
                    # itempath = plugin.url_for(endpoint=episode, name=epname, url=eplink)
                    dateout = epdate.replace(' ', '-').strip()
                    item.label += " [I][B][COLOR orange]{0}[/COLOR][/B][/I]".format(
                        dateout)
                    item.thumbnail = banner
                    litems.append(item)
        except Exception as ex:
            print('ADDON ERROR: {0}'.format(str(repr(ex.message))))
            print(str(repr(ex)))
    # return litems
    # for eplink, epname in matches:
    #    item = category_episodemake(epname, eplink)
    #    item.path = plugin.url_for(episode, name=epname, url=eplink)
    #    litems.append(item)
    # if plugin.get_setting('sortalpha', converter=bool):
    #    litems.sort(key=lambda litems: litems.label, reverse=True)
    return litems
Пример #29
0
def main():
    if param.startswith("?stream="):

        def fixURL(tmpurl):
            tmpurl = tmpurl.replace(
                "vtime.cntv.cloudcdn.net:8000",
                "vtime.cntv.cloudcdn.net")  #Global (HDS/FLV) - wrong port
            tmpurl = tmpurl.replace(
                "tv.fw.live.cntv.cn",
                "tvhd.fw.live.cntv.cn")  #China - 403 Forbidden
            return tmpurl

        def tryHLSStream(jsondata, subkey):
            print("Trying stream {0}".format(subkey))

            if jsondata["hls_url"].has_key(
                    subkey) and jsondata["hls_url"][subkey] != "":
                try:
                    tmpurl = jsondata["hls_url"][subkey]
                    tmpurl = fixURL(tmpurl)

                    req = urllib2.Request(tmpurl)
                    conn = urllib2.urlopen(req, timeout=TIMEOUT_S)
                    conn.read(8)  #Try reading a few bytes

                    return tmpurl
                except Exception:
                    print("{0} failed.".format(subkey))
                    print(traceback.format_exc())

            return None

        def tryFLVStream(jsondata, streamName):
            if jsondata["hds_url"].has_key(streamName):
                url = jsondata["hds_url"][streamName]
                url = url + "&hdcore=2.11.3"

                return url

        pDialog = xbmcgui.DialogProgress()
        pDialog.create(addon.getLocalizedString(30009),
                       addon.getLocalizedString(30010))
        pDialog.update(0)
        try:
            #Locate the M3U8 file
            resp = urllib2.urlopen(
                "http://vdn.live.cntv.cn/api2/live.do?channel=pa://cctv_p2p_hd"
                + param[8:])
            data = resp.read().decode("utf-8")

            if pDialog.iscanceled(): return

            url = None
            jsondata = jsonimpl.loads(data)

            urlsTried = 0
            urlsToTry = 5

            if jsondata.has_key("hls_url"):
                for i in range(1, 6):
                    hlsStream = "hls" + str(i)
                    urlsTried += 1
                    pDialog.update(
                        urlsTried / urlsToTry * 100,
                        "{0} {1} (HLS)".format(addon.getLocalizedString(30011),
                                               hlsStream))
                    url = tryHLSStream(jsondata, hlsStream)
                    if url:
                        break

            if pDialog.iscanceled(): return
            web_pdb.set_trace()

            #if url is None and jsondata.has_key("hls_url"):
            #	tryHLSStream(jsondata, "hls4")

            if url is None:
                showNotification(30002)
                pDialog.close()
                return

            print("Loading URL {0}".format(url))

            pDialog.close()
            xbmc.Player().play(url)

        except Exception:
            showNotification(30000)
            print(traceback.format_exc())
            pDialog.close()
            return

    elif param.startswith("?city="):
        city = param[6:]

        def addStream(channelID, channelName):
            li = xbmcgui.ListItem(channelName,
                                  iconImage=addon_path + "/resources/media/" +
                                  city + ".png")
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=sys.argv[0] + "?stream=" +
                                        channelID,
                                        listitem=li)

        if city == "anhui":
            addStream("anqingxinwen", "安庆新闻综合")
        if city == "beijing":
            addStream("btv2", "BTV文艺")
            addStream("btv3", "BTV科教")
            addStream("btv4", "BTV影视")
            addStream("btv5", "BTV财经")
            addStream("btv6", "BTV体育")
            addStream("btv7", "BTV生活")
            addStream("btv8", "BTV青少")
            addStream("btv9", "BTV新闻")
            addStream("btvchild", "BTV卡酷少儿")
            addStream("btvjishi", "BTV纪实")
            addStream("btvInternational", "BTV国际")
        if city == "tianjin":
            addStream("tianjin1", "天津1套")
            addStream("tianjin2", "天津2套")
            addStream("tianjinbh", "滨海新闻综合")
            addStream("tianjinbh2", "滨海综艺频道")
        if city == "guangxi":
            addStream("gxzy", "广西综艺")
        if city == "guangdong":
            addStream("cztv1", "潮州综合")
            addStream("cztv2", "潮州公共")
            addStream("foshanxinwen", "佛山新闻综合")
            addStream("guangzhouxinwen", "广州新闻")
            addStream("guangzhoujingji", "广州经济")
            addStream("guangzhoushaoer", "广州少儿")
            addStream("guangzhouzonghe", "广州综合")
            addStream("guangzhouyingyu", "广州英语")
            addStream("shaoguanzonghe", "韶关综合")
            addStream("shaoguangonggong", "韶关公共")
            addStream("shenzhencjsh", "深圳财经")
            addStream("zhuhaiyitao", "珠海一套")
            addStream("zhuhaiertao", "珠海二套")
        if city == "sichuan":
            addStream("cdtv1", "成都新闻综合")
            addStream("cdtv2new", "成都经济资讯服务")
            addStream("cdtv5", "成都公共")
        if city == "liaoning":
            addStream("daliannews", "大连一套")
            addStream("liaoningds", "辽宁都市")
        if city == "jiangxi":
            addStream("ganzhou", "赣州新闻综合")
            addStream("nanchangnews", "南昌新闻")
        if city == "hubei":
            addStream("hubeidst", "湖北电视台综合频道")
            addStream("hubeigonggong", "湖北公共")
            addStream("hubeijiaoyu", "湖北教育")
            addStream("hubeitiyu", "湖北体育")
            addStream("hubeiyingshi", "湖北影视")
            addStream("hubeijingshi", "湖北经视")
            addStream("hubeigouwu", "湖北购物")
            addStream("jznews", "荆州新闻频道")
            addStream("wuhanetv", "武汉教育")
            addStream("jzlongs", "湖北垄上频道")
            addStream("xiangyangtai", "襄阳广播电视台")
        if city == "heilongjiang":
            addStream("haerbinnews", "哈尔滨新闻综合")
        if city == "xinjiang":
            addStream("xjtv2", "维语新闻综合")
            addStream("xjtv3", "哈语新闻综合")
            addStream("xjtv5", "维语综艺")
            addStream("xjtv8", "哈语综艺")
            addStream("xjtv9", "维语经济生活")
        if city == "hebei":
            addStream("hebeinongmin", "河北农民频道")
            addStream("hebeijingji", "河北经济")
            addStream("shijiazhuangyitao", "石家庄一套")
            addStream("shijiazhuangertao", "石家庄二套")
            addStream("shijiazhuangsantao", "石家庄三套")
            addStream("shijiazhuangsitao", "石家庄四套")
            addStream("xingtaizonghe", "邢台综合")
            addStream("xingtaishenghuo", "邢台生活")
            addStream("xingtaigonggong", "邢台公共")
            addStream("xingtaishahe", "邢台沙河")
        if city == "shandong":
            addStream("jinannews", "济南新闻")
            addStream("qingdaonews", "青岛新闻综合")
            addStream("yantaixinwenzonghe", "烟台新闻综合")
            addStream("yantaixinjingjishenghuo", "烟台经济生活")
            addStream("yantaigonggong", "烟台公共频道")
        if city == "gansu":
            addStream("jingcailanzhou", "睛彩兰州")
        if city == "yunnan":
            addStream("lijiangnews", "丽江新闻综合频道")
            addStream("lijiangpublic", "丽江公共频道")
        if city == "neimenggu":
            addStream("neimenggu2", "蒙语频道")
            addStream("neimengwh", "内蒙古文化频道")
        if city == "jiangsu":
            addStream("nanjingnews", "南京新闻")
            addStream("nantongxinwen", "南通新闻频道")
            addStream("nantongshejiao", "南通社教频道")
            addStream("nantongshenghuo", "南通生活频道")
            addStream("wuxixinwenzonghe", "无锡新闻综合")
            addStream("wuxidoushizixun", "无锡都市资讯")
            addStream("wuxiyuele", "无锡娱乐")
            addStream("wuxijingji", "无锡经济")
            addStream("wuxiyidong", "无锡移动")
            addStream("wuxishenghuo", "无锡生活")
        if city == "zhejiang":
            addStream("nbtv1", "宁波一套")
            addStream("nbtv2", "宁波二套")
            addStream("nbtv3", "宁波三套")
            addStream("nbtv4", "宁波四套")
            addStream("nbtv5", "宁波五套")
        if city == "shanghai":
            addStream("shnews", "上海新闻综合")
        if city == "fujian":
            addStream("xiamen1", "厦门一套")
            addStream("xiamen2", "厦门二套")
            addStream("xiamen3", "厦门三套")
            addStream("xiamen4", "厦门四套")
            addStream("xiamenyidong", "厦门移动")
        if city == "shaanxi":
            addStream("xiannews", "西安新闻")
        if city == "xizang":
            addStream("xizang2", "藏语频道")
        if city == "jilin":
            addStream("yanbianguangbo", "延边卫视视频广播")
            addStream("yanbianam", "延边卫视AM")
            addStream("yanbianfm", "延边卫视FM")

        xbmcplugin.endOfDirectory(addon_handle)

    elif param.startswith("?category="):
        category = param[10:]

        def addStream(channelID, channelName):
            li = xbmcgui.ListItem(channelName,
                                  iconImage=addon_path + "/resources/media/" +
                                  channelID + ".png")
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=sys.argv[0] + "?stream=" +
                                        channelID,
                                        listitem=li)

        if category == "yangshi":
            addStream("cctv1", "CCTV-1 综合")
            addStream("cctv2", "CCTV-2 财经")
            addStream("cctv3", "CCTV-3 综艺")
            addStream("cctv4", "CCTV-4 (亚洲)")
            addStream("cctveurope", "CCTV-4 (欧洲)")
            addStream("cctvamerica", "CCTV-4 (美洲)")
            addStream("cctv5", "CCTV-5 体育")
            addStream("cctv6", "CCTV-6 电影")
            addStream("cctv7", "CCTV-7 军事 农业")
            addStream("cctv8", "CCTV-8 电视剧")
            addStream("cctvjilu", "CCTV-9 纪录")
            addStream("cctvdoc", "CCTV-9 纪录(英)")
            addStream("cctv10", "CCTV-10 科教")
            addStream("cctv11", "CCTV-11 戏曲")
            addStream("cctv12", "CCTV-12 社会与法")
            addStream("cctv13", "CCTV-13 新闻")
            addStream("cctvchild", "CCTV-14 少儿")
            addStream("cctv15", "CCTV-15 音乐")
            addStream("cctv9", "CCTV-NEWS")
            addStream("cctv5plus", "CCTV体育赛事")
        if category == "weishi":
            addStream("anhui", "安徽卫视")
            addStream("btv1", "北京卫视")
            addStream("bingtuan", "兵团卫视")
            addStream("chongqing", "重庆卫视")
            addStream("dongfang", "东方卫视")
            addStream("dongnan", "东南卫视")
            addStream("gansu", "甘肃卫视")
            addStream("guangdong", "广东卫视")
            addStream("guangxi", "广西卫视")
            addStream("guizhou", "贵州卫视")
            addStream("hebei", "河北卫视")
            addStream("henan", "河南卫视")
            addStream("heilongjiang", "黑龙江卫视")
            addStream("hubei", "湖北卫视")
            addStream("jilin", "吉林卫视")
            addStream("jiangxi", "江西卫视")
            addStream("kangba", "康巴卫视")
            addStream("liaoning", "辽宁卫视")
            addStream("travel", "旅游卫视")
            addStream("neimenggu", "内蒙古卫视")
            addStream("ningxia", "宁夏卫视")
            addStream("qinghai", "青海卫视")
            addStream("shandong", "山东卫视")
            addStream("sdetv", "山东教育台")
            addStream("shenzhen", "深圳卫视")
            addStream("shan1xi", "山西卫视")
            addStream("shan3xi", "陕西卫视")
            addStream("shenzhen", "深圳卫视")
            addStream("sichuan", "四川卫视")
            addStream("tianjin", "天津卫视")
            addStream("xizang", "西藏卫视")
            addStream("xiamen", "厦门卫视")
            addStream("xianggangweishi", "香港卫视")
            addStream("xinjiang", "新疆卫视")
            addStream("yanbian", "延边卫视")
            addStream("yunnan", "云南卫视")
            addStream("zhejiang", "浙江卫视")

        if category == "shuzi":
            addStream("zhongxuesheng", "CCTV中学生")
            addStream("xinkedongman", "CCTV新科动漫")
            addStream("zhinan", "CCTV电视指南")

        if category == "chengshi":

            def addCity(cityID, cityName):
                li = xbmcgui.ListItem(cityName,
                                      iconImage=addon_path +
                                      "/resources/media/" + cityID + ".png")
                xbmcplugin.addDirectoryItem(handle=addon_handle,
                                            url=sys.argv[0] + "?city=" +
                                            cityID,
                                            listitem=li,
                                            isFolder=True)

            addCity("anhui", "Anhui 安徽")
            addCity("beijing", "Beijing 北京")
            addCity("fujian", "Fujian 福建")
            addCity("gansu", "Gansu 甘肃")
            addCity("guangdong", "Guangdong 广东")
            addCity("guangxi", "Guangxi 广西")
            addCity("hebei", "Hebei 河北")
            addCity("heilongjiang", "Heilongjiang 黑龙江")
            addCity("hubei", "Hubei 湖北")
            addCity("jilin", "Jilin 吉林")
            addCity("jiangsu", "Jiangsu 江苏")
            addCity("jiangxi", "Jiangxi 江西")
            addCity("liaoning", "Liaoning 辽宁")
            addCity("neimenggu", "Inner Mongolia 内蒙古")
            addCity("shandong", "Shandong 山东")
            addCity("shaanxi", "Shaanxi 陕西")
            addCity("shanghai", "Shanghai 上海")
            addCity("sichuan", "Sichuan 四川")
            addCity("tianjin", "Tianjin 天津")
            addCity("xizang", "Tibet 西藏")
            addCity("xinjiang", "Xinjiang 新疆")
            addCity("yunnan", "Yunnan 云南")
            addCity("zhejiang", "Zhejiang 浙江")

        xbmcplugin.endOfDirectory(addon_handle)

    else:

        def addCategory(categoryID, categoryName):
            li = xbmcgui.ListItem(categoryName)
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=sys.argv[0] + "?category=" +
                                        categoryID,
                                        listitem=li,
                                        isFolder=True)

        addCategory("yangshi", "National Channels 央视频道")
        addCategory("weishi", "Provincial Channels 卫视频道")
        addCategory("shuzi", "Digital Channels 数字频道")
        addCategory("chengshi", "City-based Channels 城市频道")

        xbmcplugin.endOfDirectory(addon_handle)
Пример #30
0

class MySettings(object):
    def __init__(self, url, username, password, debug):
        self.url = url + '/' if not url[-1] == '/' else url
        self.username = username
        self.password = password
        self.debug = debug


debug = bool(__settings__.getSetting('debug').lower() == 'true')
remote = False
if debug:
    try:
        import web_pdb
        web_pdb.set_trace()
    except Exception as error:
        xbmc.log(
            'Failed to import ptvsd, stopping debugging\n Error:' + str(error),
            xbmc.LOGWARNING)

if __name__ == '__main__':
    # Keep this file to a minimum, as Kodi
    # doesn't keep a compiled copy of this
    ADDON = xbmcaddon.Addon()

    context = context.MedusaFailed(
        MySettings(__settings__.getSetting('medusaurl'),
                   __settings__.getSetting('username'),
                   __settings__.getSetting('password'),
                   __settings__.getSetting('debug')))
Пример #31
0
def fizzbuzz(i):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    elif i % 15 == 0:
        print('FizzBuzz')
    else:
        print(i)

import web_pdb; web_pdb.set_trace()
for i in range(1, 21):
    fizzbuzz(i)
Пример #32
0
# coding: utf-8
# Created on: 13.09.2016
# Author: Roman Miroshnychenko aka Roman V.M. ([email protected])

import os
import sys

basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(basedir)

ustr = u'Тест'
foo = 'foo'
from web_pdb import set_trace
set_trace()
bar = 'bar'
ham = 'spam'
name = u'Монти'


def func(spam):
    print(spam)


func(ham)
Пример #33
0
		  USE ONLY IN SAFELY BACKED UP DEVELOPMENT ENVIRONMENTS 

"""

import sys, re, traceback
from copy import deepcopy
from collections import deque

from .overwatch import MetaOverwatch, Overwatch
from sequencer.compat import property

# Make the interface slightly more generic
try:
    raise ImportError
    import web_pdb
    BreakpointFunction = lambda host='localhost', port=5678: web_pdb.set_trace(
        host, port)

except ImportError:
    try:
        ipython_connection = get_ipython().__class__.__name__
        # jupyter
        if ipython_connection == 'ZMQInteractiveShell':
            from IPython.core.debugger import Tracer
            BreakpointFunction = Tracer()
        # terminal
        elif ipython_connection == 'TerminalInteractiveShell':
            from IPython.core.debugger import Tracer
            BreakpointFunction = Tracer()
        else:
            raise ImportError
    except NameError, ImportError:
Пример #34
0
def dbg():
    import web_pdb
    if not web_pdb.WebPdb.active_instance:
        import webbrowser
        webbrowser.open('http://127.0.0.1:5555')
    web_pdb.set_trace()
Пример #35
0
def handle_exception(frames_and_linenos, exc=None, tb=None) -> HandlerResult:
    while True:
        # save exc_info to variable to prevent future exception

        def locals_at(frame_level):
            return frames_and_linenos[frame_level][0].f_locals

        logger.info("PID: {}\n".format(os.getpid()))
        try:
            with Timeout(48 * 60 * 60):
                input_cmd = input(
                    "What do you want to do?\n"
                    "(You have 48 hours to decide.)\n"
                    "reload - reload codes and retry\n"
                    "console - keep exception stack and start a interactive console\n"
                    "print_stack - print traceback frame summary\n"
                    "print_local [frame_level] [key] - print local variables in exception stack\n"
                    "console-reload - clear exception stack, reload, and start a interactive console\n"
                    "pdb - set trace for pdb\n"
                    "continue - just let it go\n"
                    ">> ")
        except TimeoutError:
            input_cmd = "continue"
        choice, _, args = input_cmd.partition(" ")
        if choice == "continue":
            return HandlerResult(False, False)
        elif choice == "reload":
            return HandlerResult(need_reload=True)  # restart running
        elif choice == "console-reload":
            return HandlerResult(need_reload=True, need_console=True)
        elif choice == "console":
            args_list = args.strip().split(" ")
            if len(args_list) == 1:
                try:
                    frame_level = int(args_list[0])
                except ValueError:
                    print("console [frame_level]")
                    continue
            else:
                frame_level = -1

            try:
                try:
                    from IPython.terminal.embed import InteractiveShellEmbed
                    InteractiveShellEmbed().mainloop(
                        local_ns=locals_at(frame_level))
                except ModuleNotFoundError:
                    code.interact(local=locals_at(frame_level))
            except SystemExit:
                continue  # goto choice
        elif choice == "pdb":
            try:
                import web_pdb as pdb
            except ImportError:
                import pdb
            if tb:
                pdb.post_mortem(tb)
            else:
                # TODO: still some bugs
                pdb.set_trace()
        elif choice == "print_stack":
            traceback.print_list(
                traceback.StackSummary.extract(frames_and_linenos))
        elif choice == "print_local":
            args_list = args.strip().split(" ")
            if len(args_list) >= 1:
                try:
                    frame_level = int(args_list[0])
                except ValueError:
                    print("print_local [frame_level] [key]")
                    continue
            if len(args_list) == 1:
                # noinspection PyUnboundLocalVariable
                print(locals_at(frame_level).keys())
            elif len(args_list) == 2:
                key = args_list[1]
                print(locals_at(frame_level)[key])
            else:
                print("print_local [frame_level] [key]")
                continue
        else:
            continue
    return HandlerResult(need_reload=False, need_console=False)