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()
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)
    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)
	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
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
Example #6
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
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')
Example #8
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)
Example #9
0
    def show_files(self):
        if self.files:
            return

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

        link = self.cursel_link()

        self.list.setVisible(False)

        path = self.download_torrent(link)

        if filesystem.exists(path):
            import base
            player = base.TorrentPlayer()
            player.AddTorrent(path)
            data = player.GetLastTorrentData()
            if data:
                for f in data['files']:
                    try:
                        li = xbmcgui.ListItem(
                            str(f['size'] / 1024 / 1024) + u' МБ | ' +
                            f['name'])
                    except:
                        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)
Example #10
0
def main():
    import vsdbg
    vsdbg._attach(False)

    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')
Example #11
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):
        try:
            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:
                            call_bg('add_media_process', {
                                'title': title,
                                'imdb': imdb
                            })
                        else:
                            break
                    except BaseException as e:
                        log.print_tb(e)
        finally:
            filesystem.remove(path)
Example #12
0
    def __init__(self):
        self.use_mysql = False
        self.dict.clear()

        path = xbmc.translatePath(
            'special://profile/advancedsettings.xml').decode('utf-8')
        self.LOG(path)
        if not filesystem.exists(path):
            return

        try:
            with filesystem.fopen(path, 'r') as f:
                content = f.read()
                log.debug(content)
                root = ET.fromstring(content)
        except IOError as e:
            self.LOG("I/O error({0}): {1}".format(e.errno, e.strerror))
            return
        except BaseException as e:
            self.LOG("error: " + str(e))
            return

        for section in root:
            if section.tag == 'videodatabase':
                for child in section:
                    if child.tag in [
                            'type', 'host', 'port', 'user', 'pass', 'name'
                    ]:
                        self.dict[child.tag] = child.text
                        log.debug(child.text)
                self.LOG('<videodatabase> found')
                return

        self.LOG('<videodatabase> not found')
Example #13
0
	def __init__(self):
		self.use_mysql = False
		self.dict.clear()
	
		path = xbmc.translatePath('special://profile/advancedsettings.xml').decode('utf-8')
		self.LOG(path)
		if not filesystem.exists(path):
			return

		try:
			with filesystem.fopen(path, 'r') as f:
				content = f.read()
				log.debug(content)
				root = ET.fromstring(content)
		except IOError as e:
			self.LOG("I/O error({0}): {1}".format(e.errno, e.strerror))
			return
		except BaseException as e:
			self.LOG("error: " + str(e))
			return

		for section in root:
			if section.tag == 'videodatabase':
				for child in section:
					if child.tag in ['type', 'host', 'port', 'user', 'pass', 'name']:
						self.dict[child.tag] = child.text
						log.debug(child.text)
				self.LOG('<videodatabase> found')
				return
				
		self.LOG('<videodatabase> not found')
Example #14
0
def save_hashes(torrent_path):
    hashes_path = torrent_path + '.hashes'
    if filesystem.exists(torrent_path):
        tp = TorrentPlayer()
        tp.AddTorrent(torrent_path)
        td = tp.GetLastTorrentData()
        if td:
            info_hash = td['info_hash']

            if filesystem.exists(hashes_path):
                with filesystem.fopen(hashes_path, 'r') as rf:
                    if info_hash in rf.read():
                        return

            with filesystem.fopen(hashes_path, 'a+') as wf:
                wf.write(info_hash + '\n')
 def remove(path):
     import filesystem
     if filesystem.exists(path):
         try:
             filesystem.remove(path)
             debug(u'remove: {}		[OK]'.format(path))
         except:
             debug(u'remove: {}		[Fail]'.format(path))
Example #16
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)
        call_bg('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)
                call_bg('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)
                call_bg('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
Example #17
0
    def __init__(self, title, settings, links):
        # Вызываем конструктор базового класса.
        super(MyWindow, self).__init__(title)
        # Устанавливаем ширину и высоту окна, а также разрешение сетки (Grid):
        self.setGeometry(1280, 720, 1, 1)

        self.settings = settings

        self.files = None
        self.left_menu = None
        self.list = pyxbmct.List('font14', _itemHeight=120)
        self.placeControl(self.list, 0, 0)

        self.make_links = links

        self.fill_list()

        links.set_reload(self.reload)

        kodi_ver_major = int(
            xbmc.getInfoLabel('System.BuildVersion').split('.')[0])

        if kodi_ver_major < 16:
            li = xbmcgui.ListItem(u'НАСТРОЙКИ...')
            li.setProperty(
                'link', 'plugin://script.media.aggregator/?action=settings')
            self.list.addItem(li)

            li = xbmcgui.ListItem(u'СМОТРИТЕ ТАКЖЕ...')
            li.setProperty(
                'link',
                'plugin://script.media.aggregator/?action=show_similar')
            self.list.addItem(li)

            li = xbmcgui.ListItem(u'ПОИСК ИСТОЧНИКОВ...')
            li.setProperty(
                'link', 'plugin://script.media.aggregator/?action=add_media')
            self.list.addItem(li)

            pathUnited = 'special://home/addons/plugin.video.united.search'
            pathUnited = xbmc.translatePath(pathUnited)
            if filesystem.exists(pathUnited.decode('utf-8')):
                li = xbmcgui.ListItem(u'UNITED SEARCH...')
                li.setProperty(
                    'link',
                    'plugin://script.media.aggregator/?action=united_search')
                self.list.addItem(li)

        self.setFocus(self.list)
        self.connect(self.list, self.make_choice)

        self.connect(pyxbmct.ACTION_MOVE_RIGHT, self.go_right)
        self.connect(pyxbmct.ACTION_MOVE_LEFT, self.go_left)

        # Связываем клавиатурное действие с методом.
        self.connect(pyxbmct.ACTION_NAV_BACK, self.close)
        self.has_choice = False
        self.has_select_file = False
Example #18
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
Example #19
0
    def load(self):
        if not filesystem.exists(self._addon_xml):
            self.root = None
            self.mtime = 0
            return

        with filesystem.fopen(self._addon_xml, 'r') as f:
            content = f.read()
            self.root = ET.fromstring(content)
        self.mtime = filesystem.getmtime(self._addon_xml)
    def move_file_to(self, path):
        import shutil
        src = self.get_filename()

        dirname = filesystem.dirname(path)
        if not filesystem.exists(dirname):
            filesystem.makedirs(dirname)

        shutil.copy2(src, path)
        os.remove(src)
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
	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)
Example #23
0
	def load(self):
		if not filesystem.exists(self._addon_xml):
			self.root = None
			self.mtime = 0
			return

		with filesystem.fopen(self._addon_xml, 'r') as f:
			content = f.read()
			self.root = ET.fromstring(content)
		self.mtime = filesystem.getmtime(self._addon_xml)
    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)
	def _AddTorrent(self, path):
		if filesystem.exists(path):
			with filesystem.fopen(path, 'rb') as tfile:
				content = tfile.read()

			try:
				self.status = self.engine.load_torrent(base64.b64encode(content), 'RAW')
			except KeyError:
				pass

				debug('AcePlayer: Torrent loaded')
	def _AddTorrent(self, path):
		if filesystem.exists(path):
			with filesystem.fopen(path, 'rb') as tfile:
				content = tfile.read()

			try:
				self.status = self.engine.load_torrent(base64.b64encode(content), 'RAW')
			except KeyError:
				pass

				debug('AcePlayer: Torrent loaded')
Example #27
0
	def getSetting(self, s):
		if not filesystem.exists(self._addon_xml):
			return u''

		if self.mtime != filesystem.getmtime(self._addon_xml):
			self.load()

		for item in self.root:
			if item.get('id') == s:
				return item.get('value').encode('utf-8')
		return u''
Example #28
0
    def getSetting(self, s):
        if not filesystem.exists(self._addon_xml):
            return u''

        if self.mtime != filesystem.getmtime(self._addon_xml):
            self.load()

        for item in self.root:
            if item.get('id') == s:
                return item.get('value').encode('utf-8')
        return u''
Example #29
0
def need_create(settings):
    if not filesystem.exists(settings.base_path()):
        return True

    # sources = Sources()

    if settings.anime_save and not filesystem.exists(
            settings.anime_tvshow_path()):
        return True

    if settings.animation_save and not filesystem.exists(
            settings.animation_path()):
        return True

    if settings.animation_tvshows_save and not filesystem.exists(
            settings.animation_tvshow_path()):
        return True

    if settings.tvshows_save and not filesystem.exists(settings.tvshow_path()):
        return True

    if settings.documentary_save and not filesystem.exists(
            settings.documentary_path()):
        return True

    if settings.kids_save and not filesystem.exists(settings.kids_path()):
        return True

    if settings.documentar_tvshows_save and not filesystem.exists(
            settings.documentar_tvshow_path()):
        return True

    if settings.concert_save and not filesystem.exists(
            settings.concert_path()):
        return True

    if settings.theater_save and not filesystem.exists(
            settings.theater_path()):
        return True

    return False
    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'])
            debug(u'all_torrent_files_exists: ' + path)
            if not filesystem.exists(path):
                path = filesystem.join(self.settings.copy_video_path,
                                       data['name'], item['name'])
                debug(u'all_torrent_files_exists: ' + path)
                if not filesystem.exists(path):
                    debug(u'all_torrent_files_exists: not found')
                    return False

        debug(u'all_torrent_files_exists: Ok')
        return True
Example #31
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
def save_download_link(parser, settings, link):
    #try:
    if True:
        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)
Example #33
0
def is_torrent_remembed(parser, settings):
    from downloader import TorrentDownloader
    import urllib
    link = parser.get('link').split('torrent=')[-1]
    if link:
        torr_downloader = TorrentDownloader(urllib.unquote(link), None,
                                            settings)
        path = filesystem.join(settings.torrents_path(),
                               torr_downloader.get_subdir_name(),
                               torr_downloader.get_post_index() + '.choice')
        return filesystem.exists(path)

    return False
	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
Example #35
0
    def move_file_to(self, path):
        src = self.get_filename()

        dirname = filesystem.dirname(path)
        if not filesystem.exists(dirname):
            filesystem.makedirs(dirname)

        filesystem.copyfile(src, path)
        filesystem.remove(src)

        self.saved_to = path

        self.log('{} was moved to {}'.format(src, path))
    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()
    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
	def write(self, filename, path, seasonNumber = None, episodeNumber = None, cutname = None, index = None, parser = None, settings = None):
		strmFilename = make_fullpath(filename, u'.strm')
		strmFilename = filesystem.join(path, strmFilename)
		
		#------------------------------------------

		link = u'plugin://script.media.aggregator/?action=play&torrent='
		link += urllib2.quote(self.link.encode('utf-8'))
		if episodeNumber != None:
			link += u'&episodeNumber=' + str(episodeNumber - 1)
		if seasonNumber != None:
			link += u'&seasonNumber=' + str(seasonNumber)
		if cutname != None:
			link += u'&cutName=' + urllib2.quote(cutname)
		if index != None:
			link += u'&index=' + str(index)

		#------------------------------------------
		if parser is not None:
			self.make_alternative(strmFilename, link, parser)
			# rank = get_rank(parser.get('full_title', ''), parser, settings),
			# debug('rank: ' + str(rank))
		
			link_with_min_rank = STRMWriterBase.get_link_with_min_rank(strmFilename, settings)
			if not link_with_min_rank is None:
				link = link_with_min_rank
				
		#------------------------------------------
			
		link += u'&nfo=' + urllib2.quote(make_fullpath(filename, '.nfo').encode('utf-8'))
		
		#------------------------------------------
		if settings != None:
			path = filesystem.relpath(path, settings.base_path())
			debug(path.encode('utf-8'))
			link += u'&path=' + urllib2.quote(path.encode('utf-8'))

		#------------------------------------------
		if filesystem.exists(strmFilename):
			with filesystem.fopen(strmFilename, 'r') as f:
				old_link = f.read()
				if old_link.decode('utf-8') == link:
					return
		
		#------------------------------------------
		try:
			with filesystem.fopen(strmFilename, 'w') as f:
				f.write(link.encode('utf-8'))
		except IOError:
			debug('Error write ' + strmFilename.encode('utf-8'))
			return
	def write(self, filename, seasonNumber = None, episodeNumber = None, cutname = None, index = None, parser = None, settings = None):
		strmFilename = make_fullpath(filename, u'.strm')
		
		#------------------------------------------

		link = u'plugin://script.media.aggregator/?action=play&torrent='
		link += urllib2.quote(self.link.encode('utf-8'))
		if episodeNumber != None:
			link += u'&episodeNumber=' + str(episodeNumber - 1)
		if seasonNumber != None:
			link += u'&seasonNumber=' + str(seasonNumber)
		if cutname != None:
			link += u'&cutName=' + urllib2.quote(cutname)
		if index != None:
			link += u'&index=' + str(index)

		#------------------------------------------
		if parser is not None:
			self.make_alternative(strmFilename, link, parser)
			# rank = get_rank(parser.get('full_title', ''), parser, settings),
			# debug('rank: ' + str(rank))
		
			link_with_min_rank = STRMWriterBase.get_link_with_min_rank(strmFilename, settings)
			if not link_with_min_rank is None:
				link = link_with_min_rank
				
		#------------------------------------------
			
		link += u'&nfo=' + urllib2.quote(make_fullpath(filename, '.nfo').encode('utf-8'))
		
		#------------------------------------------
		if settings != None:
			path = filesystem.relpath(filesystem.getcwd(), settings.base_path())
			debug(path.encode('utf-8'))
			link += u'&path=' + urllib2.quote(path.encode('utf-8'))

		#------------------------------------------
		if filesystem.exists(strmFilename):
			with filesystem.fopen(strmFilename, 'r') as f:
				old_link = f.read()
				if old_link.decode('utf-8') == link:
					return
		
		#------------------------------------------
		try:
			with filesystem.fopen(strmFilename, 'w') as f:
				f.write(link.encode('utf-8'))
		except IOError:
			debug('Error write ' + strmFilename.encode('utf-8'))
			return
Example #40
0
        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
Example #41
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
Example #42
0
    def __init__(self):
        self.use_mysql = False
        self.dict.clear()
        root = []

        try:
            import xbmc
            path = xbmc.translatePath(
                'special://profile/advancedsettings.xml').decode('utf-8')
            self.LOG(path)
            if filesystem.exists(path):
                self.load(path)
        except:
            pass
	def download_torrent(self, link):
		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)

		return path
Example #44
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)
def get_path_or_url_and_episode(settings, params, torrent_source):
	tempPath = xbmc.translatePath('special://temp').decode('utf-8')
	
	from downloader import TorrentDownloader
	torr_downloader = TorrentDownloader(urllib.unquote(torrent_source), tempPath, settings)

	path = filesystem.join(settings.torrents_path(), torr_downloader.get_subdir_name(),
	                       torr_downloader.get_post_index() + '.torrent')
	if not filesystem.exists(path):
		if not torr_downloader.start():
			return None
		torr_downloader.move_file_to(path)
		torr_downloader = None

	return {'path_or_url': path, 'episode': params.get('episodeNumber', None), 'downloader': torr_downloader}
Example #46
0
def seeds_peers(item):
    res = {}
    try:
        link = urllib.unquote(item['link'])
        try:
            import player
            settings = player.load_settings()
        except:
            settings = Settings.current_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(), 'elitehd',
                                 t_id + '.torrent')
            return scrape_now(fn)
        elif 'bluebird' in link:
            t_id = re.search(r'\.php.+?id=(\d+)', link).group(1)
            fn = filesystem.join(settings.torrents_path(), 'bluebird',
                                 t_id + '.torrent')
            if not filesystem.exists(fn):
                import bluebird
                bluebird.download_torrent(link, fn, settings)
            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)
        '''
		elif 'kinohd'  in link:
			part = self.url.split('/')[-1]
			t_id = re.search(r'^(\d+)', part).group(1)
			fn = filesystem.join(settings.torrents_path(), 'kinohd', t_id + '.torrent')
			return scrape_now(fn)
		'''

    except BaseException as e:
        debug(str(e))
    return res
Example #47
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)
	def change_resume_file(self, dest):
		if filesystem.exists(self.resume_file):
			data = None
			with filesystem.fopen(self.resume_file, 'rb') as resume:
				from bencode import BTFailure
				try:
					from bencode import bdecode, bencode
					decoded = bdecode(resume.read())
					decoded['save_path'] = dest.encode('utf-8')
					data = bencode(decoded)

				except BTFailure:
					pass

			if data:
				with filesystem.fopen(self.resume_file, 'wb') as resume:
					resume.write(data)
    def change_resume_file(self, dest):
        if filesystem.exists(self.resume_file):
            data = None
            with filesystem.fopen(self.resume_file, 'rb') as resume:
                from bencode import BTFailure
                try:
                    from bencode import bdecode, bencode
                    decoded = bdecode(resume.read())
                    decoded['save_path'] = dest.encode('utf-8')
                    data = bencode(decoded)

                except BTFailure:
                    pass

            if data:
                with filesystem.fopen(self.resume_file, 'wb') as resume:
                    resume.write(data)
	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 __init__(self, path, temp_path):
		self.__root = None
		self.__path = path
		self.__temp_path = temp_path
		
		if not filesystem.exists(path):
			return

		try:
			with filesystem.fopen(path, 'r') as f:
				content = f.read()
				try:
					i = content.index('</movie>')
					if i >= 0:
						content = content[0:i + len('</movie>')]
				except:
					pass
				self.__root = ET.fromstring(content)  #ET.parse(self.__path)
		except IOError as e:
			debug("NFOReader: I/O error({0}): {1}".format(e.errno, e.strerror))
Example #52
0
def create(settings):
	need_restart = False
	sources = Sources()

	with filesystem.save_make_chdir_context(settings.base_path()):

		if settings.anime_save:
			path = settings.anime_tvshow_path()
			if not filesystem.exists(path):
				filesystem.makedirs(path)
			sources.add_video(path, u'Аниме', 'tvshows')
			need_restart = True

		if settings.animation_save:
			path = settings.animation_path()
			if not filesystem.exists(path):
				filesystem.makedirs(path)
			sources.add_video(path, u'Мультфильмы', 'movies')
			need_restart = True

		if settings.animation_tvshows_save:
			path = settings.animation_tvshow_path()
			if not filesystem.exists(path):
				filesystem.makedirs(path)
			sources.add_video(path, u'Мультсериалы', 'tvshows')
			need_restart = True

		if settings.tvshows_save:
			path = settings.tvshow_path()
			if not filesystem.exists(path):
				filesystem.makedirs(path)
			sources.add_video(path, u'Сериалы', 'tvshows')
			need_restart = True

		if settings.documentary_save:
			path = settings.documentary_path()
			if not filesystem.exists(path):
				filesystem.makedirs(path)
			sources.add_video(path, u'Документальное', 'movies')
			need_restart = True

		if settings.movies_save:
			path = settings.movies_path()
			if not filesystem.exists(path):
				filesystem.makedirs(path)
			sources.add_video(path, u'Фильмы', 'movies')
			need_restart = True

	return need_restart
Example #53
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)
Example #54
0
	def __init__(self):
		if not filesystem.exists(SOURCES_REAL_PATH):
			with filesystem.fopen(SOURCES_REAL_PATH, 'w') as src:
				src.write('<sources>\n'
						  '    <programs>\n'
				          '        <default pathversion="1"></default>\n'
				          '    </programs>\n'
				          '    <video>\n'
				          '        <default pathversion="1"></default>\n'
				          '    </video>\n'
				          '    <music>\n'
				          '        <default pathversion="1"></default>\n'
				          '    </music>\n'
				          '    <pictures>\n'
				          '        <default pathversion="1"></default>\n'
				          '    </pictures>\n'
				          '    <files>\n'
				          '        <default pathversion="1"></default>\n'
				          '    </files>\n'
						  '</sources>\n'
				)

		self.xml_tree = ET.parse(SOURCES_REAL_PATH)
		self.sources = None
Example #55
0
def need_create(settings):
	if not filesystem.exists(settings.base_path()):
		return True

	# sources = Sources()

	if settings.anime_save and not filesystem.exists(settings.anime_tvshow_path()):
		return True

	if settings.animation_save and not filesystem.exists(settings.animation_path()):
		return True

	if settings.animation_tvshows_save and not filesystem.exists(settings.animation_tvshow_path()):
		return True

	if settings.tvshows_save and not filesystem.exists(settings.tvshow_path()):
		return True

	if settings.documentary_save and not filesystem.exists(settings.documentary_path()):
		return True

	return False
Example #56
0
def start_generate():
	path = filesystem.join(addon_data_path(), 'start_generate')
	if not filesystem.exists(path):
		with filesystem.fopen(path, 'w'):
			pass
Example #57
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
Example #58
0
	def CheckTorrentAdded(self):
		#raise NotImplementedError("def ###: not imlemented.\nPlease Implement this method")
		return filesystem.exists(self.path)
Example #59
0
	def check_exists(self):
		if not filesystem.exists(self._addon_xml):
			with filesystem.fopen(self._addon_xml, 'w') as f:
				f.write('<settings>\n')
				f.write('</settings>\n')
 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)