def videotype(self):
     base_path = self.settings.base_path().encode('utf-8')
     rel_path = urllib.unquote(self.params.get('path', ''))
     nfoFilename = urllib.unquote(self.params.get('nfo', ''))
     from nforeader import NFOReader
     nfoFullPath = NFOReader.make_path(base_path, rel_path, nfoFilename)
     if filesystem.exists(nfoFullPath):
         with filesystem.fopen(nfoFullPath, 'r') as nfo:
             s = nfo.read()
             if '<episodedetails>' in s:
                 return 'episode'
             if '<movie>' in s:
                 return 'movie'
     try:
         import xbmc
         return xbmc.getInfoLabel('ListItem.DBTYPE')
     except BaseException as e:
         log.print_tb(e)
         return ''
	def videotype(self):
		base_path 		= self.settings.base_path().encode('utf-8')
		rel_path 		= urllib.unquote(self.params.get('path', ''))
		nfoFilename 	= urllib.unquote(self.params.get('nfo', ''))
		from nforeader import NFOReader
		nfoFullPath 	= NFOReader.make_path(base_path, rel_path, nfoFilename)
		if filesystem.exists(nfoFullPath):
			with filesystem.fopen(nfoFullPath, 'r') as nfo:
				s = nfo.read()
				if '<episodedetails>' in s:
					return 'episode'
				if '<movie>' in s:
					return 'movie'
		try:
			import xbmc
			return xbmc.getInfoLabel('ListItem.DBTYPE')
		except BaseException as e:
			log.print_tb(e)
			return ''
def play_torrent(settings, params):
	from nforeader import NFOReader

	info_dialog = xbmcgui.DialogProgress()
	info_dialog.create(settings.addon_name)

	tempPath = xbmc.translatePath('special://temp').decode('utf-8')
	base_path = settings.base_path().encode('utf-8')
	rel_path = urllib.unquote(params.get('path', ''))
	nfoFilename = urllib.unquote(params.get('nfo', ''))
	nfoFullPath = NFOReader.make_path(base_path, rel_path, nfoFilename)
	strmFilename = nfoFullPath.replace('.nfo', '.strm')
	nfoReader = NFOReader(nfoFullPath, tempPath) if filesystem.exists(nfoFullPath) else None

	debug(strmFilename.encode('utf-8'))
	
	from base import STRMWriterBase
	links_with_ranks = STRMWriterBase.get_links_with_ranks(strmFilename, settings, use_scrape_info=True)

	anidub_enable = _addon.getSetting('anidub_enable') == 'true'
	hdclub_enable = False
	bluebird_enable = _addon.getSetting('bluebird_enable') == 'true'
	nnmclub_enable = _addon.getSetting('nnmclub_enable') == 'true'
	rutor_enable = _addon.getSetting('rutor_enable') == 'true'
	soap4me_enable = _addon.getSetting('soap4me_enable') == 'true'

	onlythis = False
	if 'onlythis' in params and params['onlythis'] == 'true':
		onlythis = True

	for v in links_with_ranks[:]:
		# if v['link'] in sys.argv[0] + sys.argv[2]:
		#	links_with_ranks.remove(v)
		if not anidub_enable and 'tr.anidub.com' in v['link']:
			links_with_ranks.remove(v)
		if not hdclub_enable and 'hdclub.org' in v['link']:
			links_with_ranks.remove(v)
		if not bluebird_enable and 'bluebird.org' in v['link']:
			links_with_ranks.remove(v)
		if not nnmclub_enable and 'nnm-club.me' in v['link']:
			links_with_ranks.remove(v)
		if not rutor_enable and 'rutor.info' in v['link']:
			links_with_ranks.remove(v)
		if not soap4me_enable and 'soap4.me' in v['link']:
			links_with_ranks.remove(v)

	debug('links_with_ranks: ' + str(links_with_ranks))

	play_torrent_variant_result = None
	if len(links_with_ranks) == 0 or onlythis:
		torrent_source = params['torrent']
		path_or_url_and_episode = get_path_or_url_and_episode(settings, params, torrent_source)
		if path_or_url_and_episode:
			path = path_or_url_and_episode['path_or_url']
			episodeNumber = path_or_url_and_episode['episode']
			downloader = path_or_url_and_episode['downloader']
			play_torrent_variant_result = play_torrent_variant(path, info_dialog, episodeNumber, nfoReader, settings,
			                                                   params, downloader)
			if play_torrent_variant_result == play_torrent_variant.resultTryAgain:
				play_torrent_variant_result = play_torrent_variant(path, info_dialog, episodeNumber, nfoReader,
				                                                   settings, params, None)
	else:
		for tryCount, variant in enumerate(links_with_ranks, 1):

			if tryCount > 1:
				info_dialog.update(0, settings.addon_name, 'Попытка #%d' % tryCount)
			debug(variant)

			torrent_source = variant['link']
			try:
				torrent_source = torrent_source.split('torrent=')[1].split('&')[0]
			except:
				continue

			path_or_url_and_episode = get_path_or_url_and_episode(settings, params, torrent_source)
			if path_or_url_and_episode is None:
				continue

			episodeNumber = path_or_url_and_episode['episode']
			downloader = path_or_url_and_episode['downloader']

			play_torrent_variant_result = play_torrent_variant(path_or_url_and_episode['path_or_url'], info_dialog,
			                                                   episodeNumber, nfoReader, settings, params, downloader)
			if play_torrent_variant_result == play_torrent_variant.resultTryAgain:
				play_torrent_variant_result = play_torrent_variant(path_or_url_and_episode['path_or_url'], info_dialog,
				                                                   episodeNumber, nfoReader, settings, params, None)

			if play_torrent_variant_result != play_torrent_variant.resultTryNext:
				break

	info_dialog.update(0, '', '')
	info_dialog.close()

	try:
		if play_torrent_variant_result == play_torrent_variant.resultTryNext and not onlythis:
			# Open in torrenter
			openInTorrenter(nfoReader)
	except:
		pass
def main():
    debug_info_label("ListItem.FileName")
    debug_info_label("ListItem.Path")
    debug_info_label("ListItem.FileExtension")
    debug_info_label("ListItem.FileNameAndPath")
    debug_info_label("ListItem.DBID")  # movie id)
    debug_info_label("ListItem.IMDBNumber")

    debug_info_label("Container.FolderPath")

    # import rpdb2
    # rpdb2.start_embedded_debugger('pw')

    import player

    settings = player.load_settings()

    path = xbmc.getInfoLabel("ListItem.FileNameAndPath")
    name = xbmc.getInfoLabel("ListItem.FileName")

    import xbmcvfs, os

    tempPath = xbmc.translatePath("special://temp")
    if xbmcvfs.exists(path + ".alternative"):
        debug("path exists")
        xbmcvfs.copy(path, os.path.join(tempPath, name))
        xbmcvfs.copy(path + ".alternative", os.path.join(tempPath, name + ".alternative"))
        path = os.path.join(tempPath, name)

    links = STRMWriterBase.get_links_with_ranks(path.decode("utf-8"), settings, use_scrape_info=True)

    window = MyWindow("Media Aggregator", settings=settings, links=links)
    window.doModal()

    debug(window.has_choice)
    debug(window.has_select_file)

    if not window.has_choice and not window.has_select_file:
        del window
        return

    cursel = window.list.getSelectedItem()
    debug(cursel.getLabel())
    link = cursel.getProperty("link")
    debug(link)

    if link == "plugin://script.media.aggregator/?action=settings":
        xbmc.executebuiltin("Addon.OpenSettings(script.media.aggregator)")
        del window
        return

    if link == "plugin://script.media.aggregator/?action=show_similar":
        imdb_id = xbmc.getInfoLabel("ListItem.IMDBNumber")
        type = "movie"

        if not imdb_id and xbmc.getInfoLabel("ListItem.DBTYPE") == "episode":
            from nforeader import NFOReader

            nfo_path = xbmc.getInfoLabel("ListItem.FileNameAndPath").replace(".strm", ".nfo").decode("utf-8")
            debug(nfo_path)
            rd = NFOReader(nfo_path, "")
            tvs_rd = rd.tvs_reader()
            imdb_id = tvs_rd.imdb_id()
            type = "tv"

        if imdb_id:
            from movieapi import MovieAPI

            res = MovieAPI.tmdb_by_imdb(imdb_id, type)
            debug(res)
            if res and len(res) > 0:
                tmdb_id = res[0].tmdb_id()
                xbmc.executebuiltin(
                    'Container.Update("plugin://script.media.aggregator/?action=show_similar&tmdb=%s")' % tmdb_id
                )
                del window
                return

    if link == "plugin://script.media.aggregator/?action=add_media":
        imdb_id = xbmc.getInfoLabel("ListItem.IMDBNumber")
        title = xbmc.getInfoLabel("ListItem.Title")

        debug(imdb_id)
        debug(title)

        from service import add_media

        add_media(title.decode("utf-8"), imdb_id)
        return

    selected_file = None
    if window.has_select_file:
        # selected_file = window.files.getSelectedItem().getLabel()
        selected_file = window.files.getSelectedItem().getProperty("index")

    del window

    with filesystem.fopen(path.decode("utf-8"), "r") as strm:
        src_link = strm.read()
        debug(src_link)
        pattern = "torrent=(.+?)&"
        match = re.search(pattern, str(link))
        if not match:
            pattern2 = "torrent=(.+)"
            match = re.search(pattern2, str(link))

        if match:
            dst_link = re.sub(pattern, "torrent=" + match.group(1) + "&", str(src_link)) + "&onlythis=true"
            debug(dst_link)

            if selected_file:
                # import urllib
                # from tvshowapi import cutStr
                # dst_link += '&cutName=' + urllib.quote(cutStr(selected_file))
                dst_link += "&index=" + str(selected_file)

            xbmc.executebuiltin("xbmc.PlayMedia(" + dst_link + ")")

    if tempPath in path:
        xbmcvfs.delete(path)
        xbmcvfs.delete(path + ".alternative")
def play_torrent(settings, params):
	info_dialog = xbmcgui.DialogProgress()
	info_dialog.create('Media Aggregator')

	tempPath = xbmc.translatePath('special://temp').decode('utf-8')
	base_path = settings.base_path().encode('utf-8')
	rel_path = urllib.unquote(params.get('path', ''))
	nfoFilename = urllib.unquote(params.get('nfo', ''))
	nfoFullPath = NFOReader.make_path(base_path, rel_path, nfoFilename)
	strmFilename = nfoFullPath.replace('.nfo', '.strm')
	nfoReader = NFOReader(nfoFullPath, tempPath) if filesystem.exists(nfoFullPath) else None

	debug(strmFilename.encode('utf-8'))
	links_with_ranks = STRMWriterBase.get_links_with_ranks(strmFilename, settings, use_scrape_info=True)

	anidub_enable = _addon.getSetting('anidub_enable') == 'true'
	hdclub_enable = _addon.getSetting('hdclub_enable') == 'true'
	nnmclub_enable = _addon.getSetting('nnmclub_enable') == 'true'
	rutor_enable = _addon.getSetting('rutor_enable') == 'true'

	onlythis = False
	if 'onlythis' in params and params['onlythis'] == 'true':
		onlythis = True

	for v in links_with_ranks[:]:
		# if v['link'] in sys.argv[0] + sys.argv[2]:
		#	links_with_ranks.remove(v)
		if not anidub_enable and 'tr.anidub.com' in v['link']:
			links_with_ranks.remove(v)
		if not hdclub_enable and 'hdclub.org' in v['link']:
			links_with_ranks.remove(v)
		if not nnmclub_enable and 'nnm-club.me' in v['link']:
			links_with_ranks.remove(v)
		if not rutor_enable and 'rutor.info' in v['link']:
			links_with_ranks.remove(v)

	debug('links_with_ranks: ' + str(links_with_ranks))

	if len(links_with_ranks) == 0 or onlythis:
		torrent_source = params['torrent']
		path_or_url_and_episode = get_path_or_url_and_episode(settings, params, torrent_source)
		if path_or_url_and_episode:
			path = path_or_url_and_episode['path_or_url']
			episodeNumber = path_or_url_and_episode['episode']
			downloader = path_or_url_and_episode['downloader']
			play_torrent_variant_result = play_torrent_variant(path, info_dialog, episodeNumber, nfoReader, settings,
			                                                   params, downloader)
			if play_torrent_variant_result == play_torrent_variant.resultTryAgain:
				play_torrent_variant_result = play_torrent_variant(path, info_dialog, episodeNumber, nfoReader,
				                                                   settings, params, None)
	else:
		for tryCount, variant in enumerate(links_with_ranks, 1):

			if tryCount > 1:
				info_dialog.update(0, 'Media Aggregator', 'Попытка #%d' % tryCount)
			debug(variant)

			torrent_source = variant['link']
			try:
				torrent_source = torrent_source.split('torrent=')[1].split('&')[0]
			except:
				continue

			path_or_url_and_episode = get_path_or_url_and_episode(settings, params, torrent_source)
			if path_or_url_and_episode is None:
				continue

			episodeNumber = path_or_url_and_episode['episode']
			downloader = path_or_url_and_episode['downloader']

			play_torrent_variant_result = play_torrent_variant(path_or_url_and_episode['path_or_url'], info_dialog,
			                                                   episodeNumber, nfoReader, settings, params, downloader)
			if play_torrent_variant_result == play_torrent_variant.resultTryAgain:
				play_torrent_variant_result = play_torrent_variant(path_or_url_and_episode['path_or_url'], info_dialog,
				                                                   episodeNumber, nfoReader, settings, params, None)

			if play_torrent_variant_result != play_torrent_variant.resultTryNext:
				break

	info_dialog.update(0, '', '')
	info_dialog.close()

	if play_torrent_variant_result == play_torrent_variant.resultTryNext and not onlythis:
		# Open in torrenter
		openInTorrenter(nfoReader)
def show_similar():
    import xbmc, xbmcgui

    import vsdbg
    vsdbg._bp()

    imdb_id = xbmc.getInfoLabel('ListItem.IMDBNumber')
    type = 'movie'

    from context import get_path_name
    path, name = get_path_name()

    FileNameAndPath = path.decode('utf-8')
    dbtype = xbmc.getInfoLabel('ListItem.DBTYPE')

    if dbtype == 'episode' or dbtype == 'tvshow':
        type = 'tv'

    if 'Anime' in path and not name:
        import filesystem
        if filesystem.exists('special://home/addons/plugin.video.shikimori.2'):
            import sys
            it = sys.listitem.getVideoInfoTag()

            try:
                import shikicore
                if shikicore.authorize_me():
                    oo = shikicore.animes_search(it.getOriginalTitle())
                    if oo:
                        #wname = xbmc.getInfoLabel('System.CurrentWindow')
                        wid = xbmcgui.getCurrentWindowId()

                        uri = 'plugin://plugin.video.shikimori.2/?action=similar&id={0}'.format(
                            oo[0]['id'])
                        if wid == 10025:
                            xbmc.executebuiltin(b'Container.Update(\"%s\")' %
                                                uri)
                        else:
                            xbmc.executebuiltin('ActivateWindow(10025,"%s")' %
                                                uri)
            except ImportError:
                pass

    if not imdb_id and dbtype == 'episode':
        from nforeader import NFOReader
        nfo_path = FileNameAndPath.replace('.strm', '.nfo')
        debug(nfo_path)
        rd = NFOReader(nfo_path, '')
        tvs_rd = rd.tvs_reader()
        imdb_id = tvs_rd.imdb_id()
        type = 'tv'

    if imdb_id:
        from movieapi import TMDB_API
        res = TMDB_API.tmdb_by_imdb(imdb_id, type)
        debug(res)
        if res and len(res) > 0:
            tmdb_id = res[0].tmdb_id()
            from plugin import make_url

            url = make_url({
                'action': 'show_similar',
                'tmdb': tmdb_id,
                'type': type
            })
            xbmc.executebuiltin('Container.Update("%s")' % url)
            return True

    return False