Ejemplo n.º 1
0
def seeds_peers(item):
	import player
	res = {}
	try:
		link = urllib.unquote(item['link'])
		settings = player.load_settings()
		if 'nnm-club' in link:
			debug('seeds_peers: ' + link)
			t_id = re.search(r't=(\d+)', link).group(1)
			fn = filesystem.join(settings.torrents_path(), 'nnmclub', t_id + '.stat')
			debug(fn)
			with filesystem.fopen(fn, 'r') as stat_file:
				import json
				res = json.load(stat_file)
				debug(str(res))
		elif 'hdclub' in link:
			t_id = re.search(r'\.php.+?id=(\d+)', link).group(1)
			fn = filesystem.join(settings.torrents_path(), 'hdclub', t_id + '.torrent')
			return scrape_now(fn)
		elif 'rutor' in link:
			t_id = re.search(r'/torrent/(\d+)', link).group(1)
			fn = filesystem.join(settings.torrents_path(), 'rutor', t_id + '.torrent')
			return scrape_now(fn)

	except BaseException as e:
		debug(str(e))
	return res
Ejemplo n.º 2
0
def scrape_nnm():
	settings = player.load_settings()
	data_path = settings.torrents_path()

	hashes = []
	for torr in filesystem.listdir(filesystem.join(data_path, 'nnmclub')):
		if torr.endswith('.torrent'):
			try:
				from base import TorrentPlayer
				tp = TorrentPlayer()
				tp.AddTorrent(filesystem.join(data_path, 'nnmclub', torr))
				data = tp.GetLastTorrentData()
				if data:
					hashes.append((data['announce'], data['info_hash'], torr.replace('.torrent', '.stat')))
			except BaseException as e:
				log.print_tb(e)

	for chunk in chunks(hashes, 32):
		import scraper
		try:
			seeds_peers = scraper.scrape(chunk[0][0], [i[1] for i in chunk])
		except RuntimeError as RunE:
			if '414 status code returned' in RunE.message:
				for c in chunks(chunk, 16):
					try:
						seeds_peers = scraper.scrape(c[0][0], [i[1] for i in c])
						process_chunk(c, data_path, seeds_peers)
					except BaseException as e:
						log.print_tb(e)
			continue
		except BaseException as e:
			log.print_tb(e)
			continue

		process_chunk(chunk, data_path, seeds_peers)
Ejemplo n.º 3
0
def save_download_link(parser, settings, link):
	try:
		path_store = filesystem.join(settings.torrents_path(), 'nnmclub')
		if not filesystem.exists(path_store):
			filesystem.makedirs(path_store)
		source = parser.link()
		match = re.search(r'\.php.+?t=(\d+)', source)
		if match:
			with filesystem.fopen(filesystem.join(path_store, match.group(1)), 'w') as f:
				f.write(link)
	except:
		pass
Ejemplo n.º 4
0
def add_media(title, imdb):
	path = filesystem.join(addon_data_path(), 'add_media')
	log.debug(path)

	# if not filesystem.exists(path):
	# 	with filesystem.fopen(path, 'w'):
	# 		pass

	if filesystem.exists(path):
		with filesystem.fopen(path, 'r') as f:
			s = f.read()
			if imdb.encode('utf-8') in s:
				return

	with filesystem.fopen(path, 'a+') as f:
		log.debug('writing...')
		seq = [title.encode('utf-8') + '\n', imdb.encode('utf-8') + '\n']
		f.writelines(seq)

	ended_path = filesystem.join(addon_data_path(), imdb + '.ended')
	for cnt in range(300):

		if filesystem.exists(ended_path):
			with filesystem.fopen(ended_path, 'r') as f:
				dlg = xbmcgui.Dialog()

				count = f.read()

				try:
					count = int(count)
				except BaseException:
					count = 0

				if count:
					dlg.notification(u'Media Aggregator', u'"%s" добавлено в библиотеку, найдено %d источников.' % (title, count), time=10000)

					url = 'plugin://script.media.aggregator/?' + urllib.urlencode(
						{'action': 'add_media',
						 'title': title.encode('utf-8'),
						 'imdb': imdb,
						 'norecursive': True})

					xbmc.executebuiltin('RunPlugin("%s")' % url)
				else:
					dlg.notification(u'Media Aggregator',
					                 u'"%s" не добавлено в библиотеку, Источники не найдены.' % title,
					                 time=10000)
			filesystem.remove(ended_path)

			break

		sleep(1)
Ejemplo n.º 5
0
	def tvs_reader(self):
		is_episode = self.is_episode()

		if is_episode:
			path = filesystem.dirname(self.path)
			path = filesystem.abspath(filesystem.join(path, os.pardir))
			path = filesystem.join(path, u'tvshow.nfo')

			if filesystem.exists(path):
				debug(u'tvs_reader: ' + path)
				return NFOReader(path, self.__temp_path)

		return None
Ejemplo n.º 6
0
	def __init__(self, **kwargs):
		from remotesettings import Settings
		self.settings = Settings()

		if 'resume_file' in kwargs:
			resume_path = filesystem.join(self.settings.storage_path, '.resume')
			if not filesystem.exists(resume_path):
				filesystem.makedirs(resume_path)
			resume_name = filesystem.basename(kwargs['resume_file'])
			resume_name = resume_name.split('\\')[-1]
			kwargs['resume_file'] = filesystem.join(resume_path, resume_name)
			log.debug('resume_file is: ' + kwargs['resume_file'])

		kwargs['bind_host'] = self.settings.remote_host
		Engine.__init__(self, **kwargs)
Ejemplo n.º 7
0
	def all_torrent_files_exists(self):
		from base import TorrentPlayer
		tp = TorrentPlayer()
		tp.AddTorrent(self.torrent)
		data = tp.GetLastTorrentData()
		files = data['files']

		for item in files:
			path = filesystem.join(self.storage_path, data['name'], item['name'])
			if not filesystem.exists(path):
				path = filesystem.join(self.settings.copy_video_path, data['name'], item['name'])
				if not filesystem.exists(path):
					return False

		return True
Ejemplo n.º 8
0
	def __init__(self, settings, params, playable_item, torrent_info, torrent_path, info_hash):
		self.command = settings.script_params.split(u' ')
		self.settings = settings
		self.params = params
		self.torrent_info = torrent_info
		self.torrent_path = torrent_path
		self.playable_item = playable_item

		self.resume_file = filesystem.join(self.settings.torrents_path(), info_hash + '.resume')

		debug('-' * 30 + ' Runner ' + '-' * 30)
		debug('torrent: ' + self.torrent)
		debug('videofile: ' + self.videofile)
		debug('relativevideofile: ' + self.relativevideofile)
		debug('torrent_source: ' + self.torrent_source)
		debug('short_name: ' + self.short_name)
		debug('downloaded: ' + str(self.downloaded))
		debug('videotype: ' + self.videotype)

		if settings.run_script:
			self.process_params()
			self.run()

		if settings.remove_files:
			debug('Runner: remove_files')
			if filesystem.exists(self.videofile):
				filesystem.remove(self.videofile)

		if float(self.downloaded) > 99 and self.all_torrent_files_exists():

			if settings.move_video and settings.copy_video_path and filesystem.exists(settings.copy_video_path):
				self.move_video_files()

			if settings.copy_torrent and settings.copy_torrent_path and filesystem.exists(settings.copy_torrent_path):
				self.copy_torrent()
Ejemplo n.º 9
0
def main():
	global _addon
	_addon = AddonRO()
	player._addon = _addon

	path = filesystem.join(addon_data_path(), 'update_library_next_start')
	if filesystem.exists(path):
		log.debug('User action!!! update_library_next_start')
		xbmc.executebuiltin('UpdateLibrary("video")')
		filesystem.remove(path)


	cnt = 0
	while not xbmc.abortRequested:

		try:
			scrape_case()
			update_case()
			add_media_case()

		finally:
			sleep(1)

		if cnt % 3600 == 0:
			log.debug("I'm alive at %s" % asctime())
		cnt += 1

	log.debug('service exit')
Ejemplo n.º 10
0
def write_tvshow_item(item, path, settings):
	debug('-------------------------------------------------------------------------')
	debug(item.link)
	parser = DescriptionParser(item.link)
	if parser.parsed():
		title = parser.get_value('title')
		debug(title.encode('utf-8'))
		originaltitle = parser.get_value('originaltitle')
		debug(originaltitle.encode('utf-8'))
		season = parser.get_value('season')

		from downloader import TorrentDownloader
		TorrentDownloader(item.link, settings.torrents_path(), settings).download()

		debug('Episodes: ' + str(parser.get_value('episodes')))

		tvshow_path = make_fullpath(title, '')
		debug(tvshow_path.encode('utf-8'))

		with filesystem.save_make_chdir_context(tvshow_path):
			tvshow_api = TVShowAPI(originaltitle, title)
			write_tvshow_nfo(parser, tvshow_api)

		season_path = filesystem.join(make_fullpath(title, u''), u'Season ' + unicode(season))
		debug(season_path.encode('utf-8'))

		with filesystem.save_make_chdir_context(season_path):

			episodes = tvshow_api.episodes(season)

			if len(episodes) < parser.get_value('episodes'):
				for i in range(len(episodes) + 1, parser.get_value('episodes') + 1):
					episodes.append({
						'title': title,
						'showtitle': title,
						'short': 's%02de%02d' % (season, i),
						'episode': i,
						'season': season
					})

			for episode in episodes:
				title = episode['title']
				shortName = episode['short']
				episodeNumber = episode['episode']

				if episodeNumber <= parser.get_value('episodes'):
					filename = str(episodeNumber) + '. ' + 'episode_' + shortName
					debug(filename.encode('utf-8'))

					ep = tvshow_api.Episode(season, episodeNumber)
					if ep:
						episode = ep

					STRMWriter(item.link).write(filename, episodeNumber=episodeNumber, settings=settings)
					NFOWriter(parser, tvshow_api=tvshow_api).write_episode(episode, filename)

	else:
		skipped(item)
	del parser
Ejemplo n.º 11
0
def save_dbs():
	path = filesystem.join(_addondir, 'dbversions')

	with filesystem.save_make_chdir_context(path):

		for fn in filesystem.listdir(path):
			filesystem.remove(fn)

		log_dir = xbmc.translatePath('special://logpath').decode('utf-8')
		log_path = filesystem.join(log_dir, 'kodi.log')
		log.debug(log_path)
		with filesystem.fopen(log_path, 'r') as lf:
			for line in lf.readlines():
				if 'Running database version' in line:
					log.debug(line)
					name = line.split(' ')[-1].strip('\r\n\t ').decode('utf-8')
					with filesystem.fopen(name, 'w'):
						pass
Ejemplo n.º 12
0
	def get_relative_torrent_files_list(self):
		from base import TorrentPlayer

		tp = TorrentPlayer()
		tp.AddTorrent(self.torrent)
		data = tp.GetLastTorrentData()
		files = data['files']

		return [filesystem.join(data['name'], item['name']) for item in files]
Ejemplo n.º 13
0
def find_direct_link(url, settings):
	match = re.search(r'\.php.+?t=(\d+)', url)
	if match:
		path_store = filesystem.join(settings.torrents_path(), 'nnmclub', match.group(1))
		if filesystem.exists(path_store):
			debug('[nnm-club] Direct link found')
			with filesystem.fopen(path_store, 'r') as f:
				return f.read()
	return None
Ejemplo n.º 14
0
	def add_video(self, path, label, content):
		path = filesystem.join(path, '')
		try:
			self.add('video', path, label)
		except SourceAlreadyExists as e:
			log.print_tb(e)

		db = VideoDB()
		scan_recursive = bool(content is 'movies')
		db.update_path(path, content, scan_recursive, 0, 0)
Ejemplo n.º 15
0
	def move_video_files(self):
		debug('Runner: move video')
		for file in self.get_relative_torrent_files_list():
			dest_path = filesystem.join(self.settings.copy_video_path, file)

			if not filesystem.exists(filesystem.dirname(dest_path)):
				filesystem.makedirs(filesystem.dirname(dest_path))

			src_path = filesystem.join(self.storage_path, file)
			if not filesystem.exists(src_path):
				continue

			if not filesystem.exists(dest_path):
				# Move file if no exists
				filesystem.movefile(src_path, dest_path)
			else:
				filesystem.remove(src_path)

			self.change_resume_file(self.settings.copy_video_path)
Ejemplo n.º 16
0
def process_chunk(chunk, data_path, seeds_peers):
	import json

	for item in chunk:
		filename = filesystem.join(data_path, 'nnmclub', item[2])
		remove_file = False
		with filesystem.fopen(filename, 'w') as stat_file:
			try:
				json.dump(seeds_peers[item[1]], stat_file)
			except KeyError:
				remove_file = True
		if remove_file:
			filesystem.remove(filename)
Ejemplo n.º 17
0
    def show_files(self):
        if self.files:
            return

        self.files = pyxbmct.List("font14")
        self.placeControl(self.files, 0, 0)

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

        match = re.search("torrent=(.+)&", str(link))
        if not match:
            pattern2 = "torrent=(.+)"
            match = re.search(pattern2, str(link))

        if match:
            link = match.group(1)

        self.list.setVisible(False)

        tempPath = xbmc.translatePath("special://temp").decode("utf-8")
        from downloader import TorrentDownloader
        import player

        settings = self.settings
        import urllib

        torr_downloader = TorrentDownloader(urllib.unquote(link), tempPath, settings)
        path = filesystem.join(
            settings.torrents_path(), torr_downloader.get_subdir_name(), torr_downloader.get_post_index() + ".torrent"
        )
        if not filesystem.exists(path):
            torr_downloader.download()
            path = torr_downloader.get_filename()

        debug(path)
        if filesystem.exists(path):
            import base

            player = base.TorrentPlayer()
            player.AddTorrent(path)
            data = player.GetLastTorrentData()
            if data:
                for f in data["files"]:
                    li = xbmcgui.ListItem(f["name"])
                    li.setProperty("index", str(f["index"]))
                    self.files.addItem(li)

        self.setFocus(self.files)
        self.connect(self.files, self.select_file)
Ejemplo n.º 18
0
def update_case():
	# Init
	if not hasattr(update_case, 'first_start'):
		update_case.first_start = True
		update_case.first_start_time = time()
		update_case.prev_generate_time = update_case.first_start_time

	try:
		every = int(_addon.getSetting('service_generate_persistent_every')) * 3600 # seconds
		delay_startup = int(_addon.getSetting('delay_startup')) * 60
	except ValueError:
		every = 8 * 3600
		delay_startup = 0

	# User action
	path = filesystem.join(addon_data_path(), 'start_generate')

	if filesystem.exists(path) and _addon.getSetting('role').decode('utf-8') != u'клиент':

		log.debug('User action!!!')

		filesystem.remove(path)
		update_service(show_progress=True)
		update_case.first_start = False
		return

	# Startup
	if time() > update_case.first_start_time + delay_startup and update_case.first_start:
		if _addon.getSetting('service_startup') == 'true':
			try:
				log.debug("Persistent Update Service starting...")
				log.debug(_addon.getSetting('service_startup'))
				update_service(show_progress=False)
			except BaseException as e:
				log.print_tb(e)
			finally:
				update_case.first_start = False

	# Persistent
	if time() >= update_case.prev_generate_time + every:  # verification
		if _addon.getSetting('service_generate_persistent') == 'true':
			try:
				update_case.prev_generate_time = time()
				update_service(show_progress=False)
				log.debug('Update List at %s' % asctime(localtime(update_case.prev_generate_time)))
				log.debug('Next Update in %s' % strftime("%H:%M:%S", gmtime(every)))
			except BaseException as e:
				log.print_tb(e)
			finally:
				update_case.first_start = False
Ejemplo n.º 19
0
def create_mark_file():
	import urllib2, shutil
	path = filesystem.join(_addondir, 'version_latest')
	if not filesystem.exists(path):
		try:
			with filesystem.fopen(path, 'w') as f:
				f.write('test')

			if filesystem.exists(path):
				url = 'https://github.com/vadyur/script.media.aggregator/releases/download/ver_0.15.2/version_latest'
				response = urllib2.urlopen(url)
				log.debug(response.read())
		except BaseException as e:
			log.print_tb(e)
			pass
Ejemplo n.º 20
0
def get_tmdb_api_key():
	try:
		import xbmc, filesystem
		xml_path = xbmc.translatePath('special://home').decode('utf-8')
		xml_path = filesystem.join(xml_path, 'addons/metadata.common.themoviedb.org/tmdb.xml')
		with filesystem.fopen(xml_path, 'r') as xml:
			content = xml.read()
			match = re.search('api_key=(\w+)', content)
			if match:
				key = match.group(1)
				debug('get_tmdb_api_key: ok')
				return key

	except BaseException as e:
		debug('get_tmdb_api_key: ' + str(e))
		return 'f7f51775877e0bb6703520952b3c7840'
Ejemplo n.º 21
0
	def download_image(self, url, type):
		r = requests.get(url)
		debug(r.headers)
		
		if r.headers[ 'Content-Type'] == 'image/jpeg':
			filename = filesystem.join(self.__temp_path, 'temp.media-aggregator.' + type + '.jpg')
			
			debug('Start download: ' + filename + ' from ' + url)
			
			with filesystem.fopen(filename, 'wb') as f:
				for chunk in r.iter_content(100000):
					f.write(chunk)
					
			debug('End download: ' + filename)
			return filename
				
		return None
Ejemplo n.º 22
0
def add_media_process(title, imdb, settings):
	#import rpdb2
	#rpdb2.start_embedded_debugger('pw')
	count = 0

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

	if hdclub_enable:
		count += hdclub.search_generate(title, imdb, settings)
	if nnmclub_enable:
		count += nnmclub.search_generate(title, imdb, settings)

	if count:
		if not xbmc.getCondVisibility('Library.IsScanningVideo'):
			xbmc.executebuiltin('UpdateLibrary("video")')

	path = filesystem.join(addon_data_path(), imdb + '.ended')
	with filesystem.fopen(path, 'w') as f:
		f.write(str(count))
Ejemplo n.º 23
0
	def run(self):
		debug(self.command)
		import subprocess

		startupinfo = None
		u8runner = None

		if os.name == 'nt':
			startupinfo = subprocess.STARTUPINFO()
			startupinfo.dwFlags |= 1
			startupinfo.wShowWindow = 0
			u8runner = filesystem.abspath(filesystem.join(Runner.get_addon_path(), 'bin/u8runner.exe')).encode('mbcs')

		shell = self.command[0].startswith('@')
		if shell:
			self.command[0] = self.command[0][1:]

		try:
			subprocess.call(executable=u8runner, args=self.command, startupinfo=startupinfo, shell=shell)
		except OSError, e:
			debug(("Can't start %s: %r" % (str(self.command), e)))
Ejemplo n.º 24
0
	def relativevideofile(self):
		with filesystem.fopen(self.torrent_path, 'rb') as torr:
			data = torr.read()

			if data is None:
				return self.playable_item['name']

			from bencode import BTFailure
			try:
				from bencode import bdecode
				decoded = bdecode(data)
			except BTFailure:
				debug("Can't decode torrent data (invalid torrent link?)")
				return self.playable_item['name']

			info = decoded['info']

			if 'files' in info:
				from base import TorrentPlayer
				return filesystem.join(TorrentPlayer.Name(info['name']), self.playable_item['name'])

		return self.playable_item['name']
Ejemplo n.º 25
0
def add_media_case():
	if _addon.getSetting('role').decode('utf-8') == u'клиент':
		return

	path = filesystem.join(addon_data_path(), 'add_media')
	if filesystem.exists(path):
		with filesystem.fopen(path, 'r') as f:
			while True:
				try:
					title = f.readline().strip(' \n\t\r').decode('utf-8')
					imdb = f.readline().strip(' \n\t\r')

					log.debug('add_media_case: ' + imdb)
					log.debug(title)

					if title and imdb:
						add_media_process(title, imdb, player.load_settings())
					else:
						break
				except BaseException as e:
					log.print_tb(e)

		filesystem.remove(path)
Ejemplo n.º 26
0
 def copy_torrent(self):
     debug('Runner: copy torrent')
     dest_path = filesystem.join(self.settings.copy_torrent_path,
                                 filesystem.basename(self.torrent_path))
     filesystem.copyfile(self.torrent_path, dest_path)
Ejemplo n.º 27
0
def write_tvshow(fulltitle,
                 link,
                 settings,
                 parser,
                 path,
                 skip_nfo_exists=False):
    from nfowriter import NFOWriter
    from strmwriter import STRMWriter
    import requests

    from downloader import TorrentDownloader
    dl = TorrentDownloader(parser.link(), settings.torrents_path(), settings)
    if not dl.download():
        return None

    #r = requests.get(link)
    #if r.status_code == requests.codes.ok:
    with filesystem.fopen(dl.get_filename(), 'rb') as torr:
        content = torr.read()
        files = parse_torrent(content, season_from_title(fulltitle))

        title = parser.get_value('title')
        debug(title.encode('utf-8'))
        originaltitle = parser.get_value('originaltitle')
        debug(originaltitle.encode('utf-8'))

        imdb_id = parser.get('imdb_id', None)
        kp_id = parser.get('kp_id', None)
        tvshow_api = TVShowAPI.get_by(originaltitle, title, imdb_id, kp_id)

        api_title = parser.movie_api().get('title')
        if not api_title:
            api_title = tvshow_api.Title()
        tvshow_path = make_fullpath(
            api_title if api_title is not None else title, '')
        debug(tvshow_path.encode('utf-8'))

        if tvshow_path:
            tvshow_path = filesystem.join(path, tvshow_path)
            with filesystem.save_make_chdir_context(tvshow_path):

                NFOWriter(
                    parser,
                    tvshow_api=tvshow_api,
                    movie_api=parser.movie_api()).write_tvshow_nfo(tvshow_path)

                # cnt = 0
                for f in files:
                    # cnt += 1
                    s_num = f['season'] if f['season'] else 1
                    try:
                        episode = tvshow_api.Episode(s_num, f['episode'])
                        if not episode:
                            episode = {
                                'title': title,
                                'seasonNumber': s_num,
                                'episodeNumber': f['episode'],
                                'image': '',
                                'airDate': ''
                            }

                        season_path = 'Season %d' % s_num
                    except BaseException as e:
                        print_tb(e)
                        continue

                    season_path = filesystem.join(tvshow_path, season_path)
                    with filesystem.save_make_chdir_context(season_path):

                        results = filter(
                            lambda x: x['season'] == s_num and x['episode'] ==
                            f['episode'], files)
                        if len(results) > 1:  # Has duplicate episodes
                            filename = f['name']
                        else:
                            try:
                                cnt = f['episode']
                                filename = '%02d. episode_s%02de%02d' % (
                                    cnt, s_num, f['episode'])
                            except BaseException as e:
                                print_tb(e)
                                filename = f['name']

                        try:
                            debug(filename)
                            filename = filename.decode('utf-8')
                        except:
                            debug([filename])

                        STRMWriter(parser.link()).write(filename,
                                                        season_path,
                                                        index=f['index'],
                                                        settings=settings,
                                                        parser=parser)
                        NFOWriter(parser,
                                  tvshow_api=tvshow_api,
                                  movie_api=parser.movie_api()).write_episode(
                                      episode,
                                      filename,
                                      season_path,
                                      skip_nfo_exists=skip_nfo_exists)
            return tvshow_path
            # end for
        else:
            return None
Ejemplo n.º 28
0
def start_generate():
    path = filesystem.join(addon_data_path(), 'start_generate')
    if not filesystem.exists(path):
        with filesystem.fopen(path, 'w'):
            pass
Ejemplo n.º 29
0
def add_media(title, imdb, settings):
    ended_path = filesystem.join(addon_data_path(), imdb + '.ended')
    if filesystem.exists(ended_path):
        try:
            filesystem.remove(ended_path)
        except:
            pass

    path = filesystem.join(addon_data_path(), 'add_media')
    log.debug(path)

    # if not filesystem.exists(path):
    # 	with filesystem.fopen(path, 'w'):
    # 		pass

    if filesystem.exists(path):
        with filesystem.fopen(path, 'r') as f:
            s = f.read()
            if imdb.encode('utf-8') in s:
                return

    with filesystem.fopen(path, 'a+') as f:
        log.debug('writing...')
        seq = [title.encode('utf-8') + '\n', imdb.encode('utf-8') + '\n']
        f.writelines(seq)

    import xbmcgui
    from settings import _addon_name

    class RemoteDialogProgress(xbmcgui.DialogProgressBG):
        def __init__(self, *args, **kwargs):
            self.progress_file_path = filesystem.join(
                addon_data_path(), '.'.join([imdb, 'progress']))
            return super(RemoteDialogProgress, self).__init__(*args, **kwargs)

        def Refresh(self):
            if filesystem.exists(self.progress_file_path):
                try:
                    try:
                        with filesystem.fopen(self.progress_file_path,
                                              'r') as progress_file:
                            args = progress_file.read().split('\n')
                    except:
                        args = [0]

                    args[0] = int(args[0])
                    self.update(*args)
                except:
                    pass

    info_dialog = RemoteDialogProgress()
    info_dialog.create(_addon_name)

    strm_path = filesystem.join(addon_data_path(), imdb + '.strm_path')
    for cnt in range(300):
        info_dialog.Refresh()
        #---------------------------------
        """
		if filesystem.exists(strm_path):
			with filesystem.fopen(strm_path, 'r') as f:
				source = f.read()	# utf-8
				if source and source.endswith('.strm'):
					strm_path = filesystem.join(settings.base_path(), source)
					if filesystem.exists(strm_path):
						with filesystem.fopen(strm_path, 'r') as strm:
							url = strm.read()
							xbmc.executebuiltin('RunPlugin("%s")' % url)
		"""
        #---------------------------------
        if filesystem.exists(ended_path):
            with filesystem.fopen(ended_path, 'r') as f:
                dlg = xbmcgui.Dialog()

                count = f.read()
                try:
                    count = int(count)
                except ValueError:
                    count = 0

                if not xbmc.Player().isPlaying():
                    if count:
                        dlg.notification(
                            _addon_name,
                            u'"%s" добавлено в библиотеку, найдено %d источников.'
                            % (title, count),
                            time=10000)

                        xbmc.executebuiltin('Container.Refresh')

                        url = 'plugin://script.media.aggregator/?' + urllib.urlencode(
                            {
                                'action': 'add_media',
                                'title': title.encode('utf-8'),
                                'imdb': imdb,
                                'strm': strm_path.encode('utf-8'),
                                'norecursive': True
                            })

                        xbmc.executebuiltin('RunPlugin("%s")' % url)
                    else:
                        dlg.notification(
                            _addon_name,
                            u'"%s" не добавлено в библиотеку, Источники не найдены.'
                            % title,
                            time=10000)
            try:
                filesystem.remove(ended_path)
            except:
                pass

            break

        sleep(1)

    info_dialog.close()
Ejemplo n.º 30
0
 def __init__(self, xml_filename='settings.xml'):
     self._addon_xml = filesystem.join(_addondir, xml_filename)
     self.check_exists()
     self.load()
Ejemplo n.º 31
0
	def videofile(self):
		return filesystem.join(self.storage_path, self.relativevideofile)
Ejemplo n.º 32
0
	def anime_tvshow_path(self):
		return filesystem.join(self.__base_path, self.__anime_tvshow_path)
Ejemplo n.º 33
0
	def animation_tvshow_path(self):
		return filesystem.join(self.__base_path, 'Animation TVShows')
Ejemplo n.º 34
0
	def tvshow_path(self):
		return filesystem.join(self.__base_path, 'TVShows')
Ejemplo n.º 35
0
	def documentary_tvshow_path(self):
		return filesystem.join(self.__base_path, 'Documentary TVShows')
Ejemplo n.º 36
0
	def theater_path(self):
		return filesystem.join(self.__base_path, 'Theater')
Ejemplo n.º 37
0
            yield item

    process = Process(settings)
    for href, fulltitle in urls():
        result = process.process(href, fulltitle)
        path_out.append(result)

    return count


if __name__ == '__main__':
    from settings import Settings
    import filesystem

    test_dir = filesystem.join(filesystem.dirname(__file__), 'test')

    settings = Settings(filesystem.join(test_dir, 'Videos'))
    settings.addon_data_path = filesystem.join(test_dir, 'data')
    settings.torrent_path = filesystem.join(test_dir, 'torrents')
    settings.torrent_player = 'torrent2http'
    settings.kp_googlecache = False
    settings.kp_usezaborona = True
    settings.use_kinopoisk = True
    settings.use_worldart = True

    #settings.kinohd_4k				= False
    #settings.kinohd_1080p			= False
    #settings.kinohd_720p			= False
    #settings.kinohd_3d				= False
Ejemplo n.º 38
0
	def copy_torrent(self, torrent_path):
		settings = self.settings
		if settings.copy_torrent_path and filesystem.exists(settings.copy_torrent_path):
			dest_path = filesystem.join(self.settings.copy_torrent_path, filesystem.basename(torrent_path))
			filesystem.copyfile(torrent_path, dest_path)
Ejemplo n.º 39
0
def start_generate():
	path = filesystem.join(addon_data_path(), 'start_generate')
	if not filesystem.exists(path):
		with filesystem.fopen(path, 'w'):
			pass
Ejemplo n.º 40
0
def update_library_next_start():
	path = filesystem.join(addon_data_path(), 'update_library_next_start')
	if not filesystem.exists(path):
		with filesystem.fopen(path, 'w'):
			pass
Ejemplo n.º 41
0
	def documentary_path(self):
		return filesystem.join(self.__base_path, self.__documentary_path)
Ejemplo n.º 42
0
	def copy_torrent(self):
		debug('Runner: copy torrent')
		dest_path = filesystem.join(self.settings.copy_torrent_path, filesystem.basename(self.torrent_path))
		filesystem.copyfile(self.torrent_path, dest_path)
Ejemplo n.º 43
0
	def animation_path(self):
		return filesystem.join(self.__base_path, self.__animation_path)
Ejemplo n.º 44
0
 def __init__(self, *args, **kwargs):
     self.progress_file_path = filesystem.join(
         addon_data_path(), '.'.join([imdb, 'progress']))
     return super(RemoteDialogProgress, self).__init__(*args, **kwargs)
Ejemplo n.º 45
0
	def kids_path(self):
		return filesystem.join(self.__base_path, 'Kids')
Ejemplo n.º 46
0
def update_library_next_start():
    path = filesystem.join(addon_data_path(), 'update_library_next_start')
    if not filesystem.exists(path):
        with filesystem.fopen(path, 'w'):
            pass
Ejemplo n.º 47
0
	def full_tvshow_path(self):
		path = self.settings.animation_tvshow_path() if self.is_animation else self.settings.tvshow_path()
		return filesystem.join(path, self.tvshow_path)
Ejemplo n.º 48
0
 def get_filename(self):
     path = filesystem.join(self.saveDir, self.get_subdir_name())
     if not filesystem.exists(path):
         filesystem.makedirs(path)
     return filesystem.join(self.saveDir, self.get_subdir_name(),
                            self.get_post_index() + self.extension)
Ejemplo n.º 49
0
	def movies_path(self):
		return filesystem.join(self.__base_path, self.__movies_path)
Ejemplo n.º 50
0
	def concert_path(self):
		return filesystem.join(self.__base_path, 'Concert')
Ejemplo n.º 51
0
 def videofile(self):
     return filesystem.join(self.storage_path, self.relativevideofile)
Ejemplo n.º 52
0
	def make_path(base_path, rel_path, filename):
		# params is utf-8
		path = filesystem.join(base_path.decode('utf-8'), rel_path.decode('utf-8'), filename.decode('utf-8'))
		return path
Ejemplo n.º 53
0
def dispatch():
    from log import debug

    params = get_params()
    debug(params)

    from player import load_settings

    import vsdbg
    vsdbg._bp()

    if 'torrent' in params:
        from player import play_torrent

        settings = load_settings()
        if settings.show_sources and 'onlythis' not in params:
            import filesystem, urllib

            rel_path = urllib.unquote(params['path']).decode('utf-8')
            debug(rel_path)

            filename = urllib.unquote(params['nfo']).decode('utf-8').replace(
                u'.nfo', u'.strm')
            debug(filename)

            path = filesystem.join(settings.base_path(), rel_path, filename)
            debug(path)

            def run(torr, index=None):
                params['onlythis'] = 'true'
                params['torrent'] = torr
                if index is not None:
                    params['index'] = index
                play_torrent(settings=settings, params=params)

            import context
            res = context.main(settings, path.encode('utf-8'),
                               filename.encode('utf-8'), run)
            if not res:
                play_torrent(settings=settings, params=params)
        else:
            play_torrent(settings=settings, params=params)

    elif params.get('action') == 'anidub-add-favorites':
        from player import action_anidub_add_favorites
        action_anidub_add_favorites(load_settings())

    elif params.get('action') == 'settings':
        from player import dialog_action, dialog_action_case
        dialog_action(dialog_action_case.settings, load_settings())

    elif params.get('action') == 'search':
        from player import dialog_action, dialog_action_case
        dialog_action(dialog_action_case.search, load_settings(), params)

    elif params.get('action') == 'search_context':
        from player import action_search_context
        action_search_context(params)

    elif params.get('action') == 'catalog':
        from player import dialog_action, dialog_action_case
        dialog_action(dialog_action_case.catalog, load_settings())

    elif params.get('action') == 'show_category':
        from player import action_show_category
        action_show_category(params)

    elif params.get('action') == 'show_library':
        from player import action_show_library
        action_show_library(params)

    elif params.get('action') == 'show_similar':
        from player import action_show_similar
        action_show_similar(params)

    elif params.get('action') == 'add_media':
        vsdbg._bp()

        from player import action_add_media
        action_add_media(params, load_settings())

    elif params.get('action') == 'update_service':
        vsdbg._bp()
        from backgrounds import update_service
        update_service(show_progress=params.get('show_progress'))

    elif params.get('action') == 'scrape_nnm':
        from backgrounds import scrape_nnm
        scrape_nnm()

    elif params.get('action') == 'clean_movies':
        from backgrounds import clean_movies
        clean_movies()

    elif params.get('action') == 'select_source':
        from context import main
        vsdbg._bp()
        main()

    elif params.get('action') == 'add_media_process':
        #vsdbg._bp()

        from backgrounds import add_media_process
        title = params.get('title')
        import urllib
        title = urllib.unquote_plus(title)
        title = title.decode('utf-8')

        add_media_process(title, params.get('imdb'))

    else:
        from player import menu_actions, dialog_action, main_menu
        if params.get('menu') in menu_actions:
            dialog_action(menu_actions.index(params.get('menu')),
                          load_settings(), params)
        else:
            main_menu(menu_actions)