Esempio n. 1
0
def loadtorrent(params):

	print '=== def loadtorrent(%s): ===' % params
	try:
		dhash   = params['hash']
		film_id = params['film_id']
		dlpath  = urllib.unquote_plus(params['dlpath'])
	except:
		print 'ERROR: Не указан ключевой параметр hash, dlpath или film_id'
		return False

	rtc = kbutils.get_rtc()

	rtpath = rtc.get_directory()
	print 'rTorrent base dir (rtpath) = %s' % rtpath
	dpath = rtpath

	if kbutils.rtc_select == 'true':
		print 'Указан выбор каталога загрузки...'
		dpa = []
		for ddir in os.listdir(rtpath): dpa.append(ddir)

		s = xbmcgui.Dialog().select('Куда качать?', dpa)
		if s < 0:
			print 'Не выбрано, выход...'
			return True
		else:
			dpath = os.path.join(rtpath, dpa[s])

	dpath = os.path.join(dpath, dlpath)

	print 'Download path [%s]' % dpath

	if not os.path.exists(dpath):
		os.makedirs(dpath)
		print 'Path %s created...' % dpath
	else:
		print 'Path %s exists...' % dpath

	url_gt = '/torrents/%s/direct-link' % dhash
	print 'url_gt GET: %s' % url_gt
	http3 = kbutils.KBREQUEST(url_gt)
	if http3 == None:
		return False

	djson2 = demjson.decode(http3)


	#print djson2
	tf_url  = djson2['url']
	print 'Direct Link = %s' % tf_url

	meta_http = kbutils.KBREQUEST('/films/%s?fields_mask=63' % film_id)
	if meta_http != None:
		meta_json = demjson.decode(meta_http)
		meta_info = kbutils.getmetadata(meta_json, film_id)
	else:
		meta_info = None

	try:
		if len(meta_info['cast']) > 0:
			casts = ''
			for cucast in meta_info['cast']:
				casts += ',%s' % urllib.quote_plus(cucast)
			if casts != '':
				casts = casts[1:]
				meta_info['cast'] = casts
	except: pass

	custom2 = '&film_id=%s' % film_id
	if meta_info != None:
		for cinfo in meta_info:
			custom2 += '&%s=%s' % (cinfo, urllib.quote_plus(str(meta_info[cinfo])))
	custom2 = custom2[1:]

	# 'd.set_custom2="%s"'%custom2
	rtc.load_start(tf_url, 'd.set_directory="%s"'%dpath, 'd.set_custom1="kinobaza"', 'd.set_custom=kbmeta,%s'%custom2)
Esempio n. 2
0
def filmsbrowse(params):
	print '=== def filmsbrowse(%s): ===' % params


	try:
		href = urllib.unquote_plus(params['href'])
		params['href'] = href
	except: href = ''
	try: params['query'] = urllib.unquote_plus(params['query'])
	except: pass

	GL = params.copy()
	del GL['mode']
	del GL['href']

	#url =
	http = kbutils.KBREQUEST('%s?%s'%(href,urllib.urlencode(GL)))

	djson = demjson.decode(http)
	#print djson



	# Если подключен rTorrent - генерируем список подкаталогов, для проверки загрузки
	rtc = kbutils.get_rtc()
	if rtc != None:
		base_dl_path = rtc.get_directory()
		dpa = []
		if (kbutils.rtc_select == 'true'):
			for ddir in os.listdir(base_dl_path):
				dpa.append(os.path.join(base_dl_path, ddir))
		else:
			dpa.append(os.path.join(base_dl_path))


	for cur in djson:

		info = kbutils.getmetadata(cur, cur['id'])

		if rtc != None:
			for chkdir in dpa:
				if os.path.exists(os.path.join(chkdir, str(cur['id']))):
					info['title'] = '[DL] %s'%info['title']
					break

		li = xbmcgui.ListItem(label = info['title'], iconImage = info['iconImage'], thumbnailImage = info['thumbnailImage'])
		li.setInfo(type = 'video', infoLabels = info)

		if cur['type'] == 'movie':
			#li.setProperty('IsPlayable', 'true')
			uri = '%s?mode=openfilm&film_id=%s'%(sys.argv[0], cur['id'])
			if not xbmcplugin.addDirectoryItem(h, uri, li, isFolder=True): break
		elif cur['type'] == 'series':
			uri = '%s?mode=openseasons&series_id=%s'%(sys.argv[0], cur['id'])
			if not xbmcplugin.addDirectoryItem(h, uri, li, isFolder=True): break
		else:
			kbutils.showMessage('Ой, "%s"' % film_type, 'Не могу добавить этот тип фильма')


	if len(djson) == int(params['limit']):
		li = xbmcgui.ListItem('Далее >', iconImage=icon, thumbnailImage=icon)
		params['offset'] = str(int(params['offset'])+int(params['limit']))
		uri  = '%s?%s'%(sys.argv[0],urllib.urlencode(params))
		xbmcplugin.addDirectoryItem(h, uri, li, isFolder = True, totalItems = kbutils.LIST_LIMIT())



	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_UNSORTED)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_ALBUM)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_DATE)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_DURATION)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_GENRE)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_TITLE)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_VIDEO_RATING)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_VIDEO_TITLE)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_VIDEO_YEAR)
	xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_LABEL)

	xbmcplugin.endOfDirectory(h)
Esempio n. 3
0
def openfilm(params):
	print '=== def openfilm(%s): ===' % params

	film_type = 0 # 1: movie, 2: series

	try:
		film_id     = params['series_id']   #'series_id': '357767'
		season_num  = params['season_num']  #'season_num': '1'
		episode_num = params['episode_num'] #'episode_num': '1'
		torget  = '/films/%s/seasons/%s/episodes/%s/torrents' % (film_id, season_num, episode_num)
		dlpath  = os.path.join(film_id, season_num, episode_num)
		film_type = 2
	except: pass

	if film_type == 0:
		try:
			film_id = params['film_id']   #'series_id': '357767'
			torget = '/films/%s/torrents?all_trackers=false' % film_id
			dlpath = os.path.join(film_id)
			film_type = 1
		except: pass

	print 'openfilm -> torget      = [%s]' % torget

	if film_type == 0:
		print 'ERROR: Тип раздачи не был установлен (film_type == 0)'
		return False

	http = kbutils.KBREQUEST(torget)
	if http == None: return False

	djson = demjson.decode(http)

	film_id  = djson['film_id']
	filters  = djson['filters']
	torrents = djson['torrents']

	hash_arrs = []
	hash_data = {}

	rtc = kbutils.get_rtc()

	for torrent in torrents:
		approved = torrent['is_approved']
		tracker = torrent['tracker_url'].encode('utf-8').replace('http:','').replace('/','')
		size = int(torrent['size'])
		try:
			filetype = torrent['filetype'].encode('utf-8')
		except:
			filetype = '?'

		quality = kbutils.replace_quality(torrent['quality'])
		quality = quality.replace(',','')
		seeders = int(torrent['seeders'])
		leechers = int(torrent['leechers'])
		THASH = torrent['hash'].encode('utf-8')
		hash_arrs.append(THASH)
		try: percent = (int(rtc.f.get_completed_chunks(THASH, 0))*100)/int(rtc.f.get_size_chunks(THASH, 0))
		except: percent = 0
		subdata = {'approved':approved,'tracker':tracker,'size':size,'filetype':filetype,
		'quality':quality,'seeders':seeders,'leechers':leechers,'percent':percent,'hash':THASH}
		hash_data[THASH] = subdata


	uhash_arrs = set(hash_arrs)

	# TODO Add METADATA

	def set_approved(let,li):
		if let['approved']: li.setProperty('fanart_image', Thumbs_Up)
		else: li.setProperty('fanart_image', Thumbs_Down)

	# Поиск полностью загруженных раздач
	for uhash in uhash_arrs:
		ninfo = hash_data[uhash]
		if ninfo['percent'] == 100:
			it = '%s Тип:%s %s' % (ninfo['tracker'], ninfo['filetype'], ninfo['quality'])
			li = xbmcgui.ListItem(it, iconImage = iOK, thumbnailImage = iOK)
			li.setInfo('video', {'title':it, 'size':ninfo['size']})
			set_approved(ninfo,li)
			if rtc.d.get_size_files(uhash) > 1:
				xbmcplugin.addDirectoryItem(h, rtc.d.get_directory(uhash), li, isFolder = True)
			else:
				xbmcplugin.addDirectoryItem(h, os.path.join(rtc.d.get_directory(uhash),rtc.d.get_name(uhash)), li, isFolder = False)


	# Поиск загружаемых раздач
	for uhash in uhash_arrs:
		ninfo = hash_data[uhash]
		# TODO and paused...
		try:    is_active = int(rtc.d.is_active(ninfo['hash']))
		except: is_active = 0
		if (ninfo['percent'] < 100) and (is_active == 1):
			it = '%d%% S=%s, L=%s %s(%s), от %s' % (ninfo['percent'],ninfo['seeders'],ninfo['leechers'],ninfo['quality'],ninfo['filetype'],ninfo['tracker'])
			li = xbmcgui.ListItem(it, iconImage = iDOWNLOADING, thumbnailImage = iDOWNLOADING)
			li.setInfo('video', {'title':it, 'size':ninfo['size']})
			set_approved(ninfo,li)
			# TODO Сделать доп. пункты.
			ppath = os.path.join(rtc.d.get_directory(uhash),rtc.d.get_name(uhash))
			if rtc.d.get_size_files(uhash) > 1:
				xbmcplugin.addDirectoryItem(h, rtc.d.get_directory(uhash), li, isFolder = True)
			else:
				xbmcplugin.addDirectoryItem(h, os.path.join(rtc.d.get_directory(uhash),rtc.d.get_name(uhash)), li, isFolder = False)


	for uhash in uhash_arrs:
		ninfo = hash_data[uhash]
		if ninfo['percent'] == 0:
			it = 'S=%s, L=%s %s(%s), от %s' % (ninfo['seeders'],ninfo['leechers'],ninfo['quality'],ninfo['filetype'],ninfo['tracker'])
			li = xbmcgui.ListItem(it, iconImage = iSTART, thumbnailImage = iSTART)
			li.setInfo('video', {'title':it, 'size':ninfo['size']})
			set_approved(ninfo,li)
			uri = '%s?mode=loadtorrent&hash=%s&film_id=%s&dlpath=%s' % (sys.argv[0], uhash, film_id, urllib.quote_plus(dlpath))
			xbmcplugin.addDirectoryItem(h, uri, li)

	xbmcplugin.addSortMethod(h, sortMethod = xbmcplugin.SORT_METHOD_TITLE)
	xbmcplugin.addSortMethod(h, sortMethod = xbmcplugin.SORT_METHOD_SIZE)
	xbmcplugin.endOfDirectory(h)
Esempio n. 4
0
def rtcshowdl(params):




	print '=== def rtcshowdl(%s): ===' % params

	rtc = kbutils.get_rtc()
	if rtc == None: return False

	try:    action = params['action']
	except: action = None

	if action == None:

		dlds = []
		dlds = rtc.d.multicall('main', "d.get_name=", "d.get_hash=", "d.get_completed_chunks=", "d.get_size_chunks=", "d.get_size_files=", \
			"d.get_directory=", "d.is_active=", "d.get_complete=", "d.get_priority=", "d.is_multi_file=", "d.get_size_bytes=", \
			"d.get_custom=", "d.get_custom1=", "d.get_custom2=", "d.get_custom3=", "d.get_custom4=", "d.get_custom5=", "d.get_custom=kbmeta" )

		dlds_len = len(dlds)

		for dld in dlds:
			dld_name = dld[0]
			dld_hash = dld[1]
			dld_completed_chunks = dld[2]
			dld_size_chunks = dld[3]
			dld_percent_complete = dld_completed_chunks*100/dld_size_chunks
			dld_size_files = dld[4]
			dld_directory = dld[5]
			dld_is_active = dld[6]
			dld_complete = dld[7]
			dld_priority = dld[8]
			dld_is_multi_file = dld[9]
			dld_size_bytes = int(dld[10])
			dld_custom = dld[11]
			dld_custom1 = dld[12] # kinobaza
			dld_custom2 = dld[13] # Comment (metadata)
			dld_custom3 = dld[14]
			dld_custom4 = dld[15]
			dld_custom5 = dld[16]
			dld_kbmeta = dld[17]

			if dld_custom1 == 'kinobaza':
				#print 'dld_custom  [%s]' % dld_custom
				#print 'dld_custom1 [%s]' % dld_custom1
				#print 'dld_custom2 [%s]' % dld_custom2
				#print 'dld_custom3 [%s]' % dld_custom3
				#print 'dld_custom4 [%s]' % dld_custom4
				#print 'dld_custom5 [%s]' % dld_custom5

				#dld_kbmeta = dld_kbmeta.replace('custom_value="','').replace('"','')

				#print 'kbmeta: %s' % dld_kbmeta

				info = get_params(dld_kbmeta)
				for curi in info: info[curi] = urllib.unquote_plus(info[curi])

				def key_to_int(arr, keyname):
					try: arr[keyname] = int(arr[keyname])
					except:
						try: del info[keyname]
						except: pass
				key_to_int(info, 'count')
				key_to_int(info, 'year')
				key_to_int(info, 'episode')
				key_to_int(info, 'season')
				key_to_int(info, 'top250')
				key_to_int(info, 'tracknumber')
				key_to_int(info, 'playcount')
				key_to_int(info, 'overlay')
				try:
					info['rating'] = float(info['rating'])
				except:
					try: del info['rating']
					except: pass

				info['size'] = dld_size_bytes
				info['title'] = '%s (%s%%)'%(info['title'],dld_percent_complete)

				if dld_is_active == 1: cm_action = 'СТОП', 'xbmc.runPlugin(%s?mode=rtcshowdl&action=dlstop&hash=%s)'  % (sys.argv[0], dld_hash)
				else:                  cm_action = 'СТАРТ','xbmc.runPlugin(%s?mode=rtcshowdl&action=dlstart&hash=%s)' % (sys.argv[0], dld_hash)

				fdc = 'xbmc.runPlugin(%s?mode=rtcshowdl&action=setprio&hash=%s&prio=%s)'
				cm = [cm_action, ('УДАЛИТЬ', 'xbmc.runPlugin(%s?mode=rtcshowdl&action=erase&hash=%s)'%(sys.argv[0],dld_hash)),\
					('Приоритет: высокий',     fdc % (sys.argv[0], dld_hash, 3)),\
					('Приоритет: нормальный',  fdc % (sys.argv[0], dld_hash, 2)),\
					('Приоритет: низкий',      fdc % (sys.argv[0], dld_hash, 1)),\
					('Приоритет: не загружать',fdc % (sys.argv[0], dld_hash, 0)) ]

				li = xbmcgui.ListItem(label = info['title'], label2 = dld_name, iconImage=info['iconImage'], thumbnailImage=info['thumbnailImage'])
				li.addContextMenuItems(items = cm, replaceItems = True)
				li.setInfo(type = 'video', infoLabels = info)

				if dld_size_files > 1:
					uri = '%s?mode=rtcshowdl&action=showfiles&hash=%s&numfiles=%s'%(sys.argv[0], dld_hash, dld_size_files)
					if not xbmcplugin.addDirectoryItem(h, uri, li, isFolder = True, totalItems = dlds_len): break
				else:
					#li.setProperty('IsPlayable', 'true')
					uri = '%s?mode=rtcshowdl&action=playfile&film_id=%s'%(sys.argv[0], info['film_id'])
					if not xbmcplugin.addDirectoryItem(h, uri, li,isFolder = True, totalItems=dlds_len): break

		xbmcplugin.addSortMethod(h, sortMethod = xbmcplugin.SORT_METHOD_TITLE )
		xbmcplugin.addSortMethod(h, sortMethod = xbmcplugin.SORT_METHOD_SIZE )
		xbmcplugin.endOfDirectory(h, cacheToDisc = False)

	elif action == 'setprio':
		rtc.d.set_priority('%s' % params['hash'], int(params['prio']))
		xbmc.executebuiltin('Container.Refresh')
	elif action == 'erase':
		#rtc.d.set_priority('%s' % params['hash'], int(params['prio']))

		rtc.d.erase(params['hash'])
		kbutils.showMessage('Удален торрент', 'Сами файлы остались на месте', 5000)
		xbmc.executebuiltin('Container.Refresh')

	elif action == 'showfiles':




		#print 'Воспроизводим %s' % dhash
		pfile = os.path.join(rtc.d.get_directory(params['hash']),rtc.d.get_name(params['hash']))
		#print 'Файл %s' % pfile
		#i = xbmcgui.ListItem(path = pfile)
		#xbmcplugin.setResolvedUrl(h, True, i)
		#return True



		files = []
		files = rtc.f.multicall(params['hash'],1,"f.get_path=","f.get_completed_chunks=","f.get_size_chunks=","f.get_priority=","f.get_size_bytes=")
		i=0
		for f in files:
			f_name = f[0]
			f_completed_chunks = int(f[1])
			f_size_chunks = int(f[2])
			f_size_bytes = int(f[4])
			f_percent_complete = f_completed_chunks*100/f_size_chunks
			f_priority = f[3]
			if f_percent_complete==100:
				f_complete = 1
			else:
				f_complete = 0
			#tbn=getIcon(0,1,f_complete,f_priority)
			if f_percent_complete<100:
				li_name = f_name+' ('+str(f_percent_complete)+'%)'
			else:
				li_name = f_name
			li = xbmcgui.ListItem( \
				label=li_name, \
				iconImage=icon, thumbnailImage=icon)
			#cm = [(g.__lang__(30120),"xbmc.runPlugin(%s?mode=action&method=f.set_priority&arg1=%s&arg2=%s&arg3=2)" % ( sys.argv[0], hash,i)), \
			#	(g.__lang__(30121),"xbmc.runPlugin(%s?mode=action&method=f.set_priority&arg1=%s&arg2=%s&arg3=1)" % ( sys.argv[0], hash,i)), \
			#	(g.__lang__(30124),"xbmc.runPlugin(%s?mode=action&method=f.set_priority&arg1=%s&arg2=%s&arg3=0)" % ( sys.argv[0], hash,i))]
			#li.addContextMenuItems(items=cm,replaceItems=True)
			li.setInfo('video',{'title':li_name,'size':f_size_bytes})

			#uri = '%s?mode=rtcshowdl&action=playfile&hash=%s&file_id=%s'%(sys.argv[0], params['hash'], i)

			uri = os.path.join(pfile, rtc.f.get_frozen_path(params['hash'], i))
			if not xbmcplugin.addDirectoryItem(h,uri,li,isFolder = True, totalItems=len(files)): break
			i=i+1
		xbmcplugin.addSortMethod(h, sortMethod=xbmcplugin.SORT_METHOD_TITLE )
		xbmcplugin.addSortMethod(h, sortMethod=xbmcplugin.SORT_METHOD_SIZE )
		xbmcplugin.endOfDirectory(h, cacheToDisc=False)



	elif action == 'playfile':
		print 'playfile....'
		openfilm({'film_id': params['film_id']})
Esempio n. 5
0
def loadtorrent(params):

    print '=== def loadtorrent(%s): ===' % params
    try:
        dhash = params['hash']
        film_id = params['film_id']
        dlpath = urllib.unquote_plus(params['dlpath'])
    except:
        print 'ERROR: Не указан ключевой параметр hash, dlpath или film_id'
        return False

    rtc = kbutils.get_rtc()

    rtpath = rtc.get_directory()
    print 'rTorrent base dir (rtpath) = %s' % rtpath
    dpath = rtpath

    if kbutils.rtc_select == 'true':
        print 'Указан выбор каталога загрузки...'
        dpa = []
        for ddir in os.listdir(rtpath):
            dpa.append(ddir)

        s = xbmcgui.Dialog().select('Куда качать?', dpa)
        if s < 0:
            print 'Не выбрано, выход...'
            return True
        else:
            dpath = os.path.join(rtpath, dpa[s])

    dpath = os.path.join(dpath, dlpath)

    print 'Download path [%s]' % dpath

    if not os.path.exists(dpath):
        os.makedirs(dpath)
        print 'Path %s created...' % dpath
    else:
        print 'Path %s exists...' % dpath

    url_gt = '/torrents/%s/direct-link' % dhash
    print 'url_gt GET: %s' % url_gt
    http3 = kbutils.KBREQUEST(url_gt)
    if http3 == None:
        return False

    djson2 = demjson.decode(http3)

    #print djson2
    tf_url = djson2['url']
    print 'Direct Link = %s' % tf_url

    meta_http = kbutils.KBREQUEST('/films/%s?fields_mask=63' % film_id)
    if meta_http != None:
        meta_json = demjson.decode(meta_http)
        meta_info = kbutils.getmetadata(meta_json, film_id)
    else:
        meta_info = None

    try:
        if len(meta_info['cast']) > 0:
            casts = ''
            for cucast in meta_info['cast']:
                casts += ',%s' % urllib.quote_plus(cucast)
            if casts != '':
                casts = casts[1:]
                meta_info['cast'] = casts
    except:
        pass

    custom2 = '&film_id=%s' % film_id
    if meta_info != None:
        for cinfo in meta_info:
            custom2 += '&%s=%s' % (cinfo,
                                   urllib.quote_plus(str(meta_info[cinfo])))
    custom2 = custom2[1:]

    # 'd.set_custom2="%s"'%custom2
    rtc.load_start(tf_url, 'd.set_directory="%s"' % dpath,
                   'd.set_custom1="kinobaza"',
                   'd.set_custom=kbmeta,%s' % custom2)
Esempio n. 6
0
def openfilm(params):
    print '=== def openfilm(%s): ===' % params

    film_type = 0  # 1: movie, 2: series

    try:
        film_id = params['series_id']  #'series_id': '357767'
        season_num = params['season_num']  #'season_num': '1'
        episode_num = params['episode_num']  #'episode_num': '1'
        torget = '/films/%s/seasons/%s/episodes/%s/torrents' % (
            film_id, season_num, episode_num)
        dlpath = os.path.join(film_id, season_num, episode_num)
        film_type = 2
    except:
        pass

    if film_type == 0:
        try:
            film_id = params['film_id']  #'series_id': '357767'
            torget = '/films/%s/torrents?all_trackers=false' % film_id
            dlpath = os.path.join(film_id)
            film_type = 1
        except:
            pass

    print 'openfilm -> torget      = [%s]' % torget

    if film_type == 0:
        print 'ERROR: Тип раздачи не был установлен (film_type == 0)'
        return False

    http = kbutils.KBREQUEST(torget)
    if http == None: return False

    djson = demjson.decode(http)

    film_id = djson['film_id']
    filters = djson['filters']
    torrents = djson['torrents']

    hash_arrs = []
    hash_data = {}

    rtc = kbutils.get_rtc()

    for torrent in torrents:
        approved = torrent['is_approved']
        tracker = torrent['tracker_url'].encode('utf-8').replace('http:',
                                                                 '').replace(
                                                                     '/', '')
        size = int(torrent['size'])
        try:
            filetype = torrent['filetype'].encode('utf-8')
        except:
            filetype = '?'

        quality = kbutils.replace_quality(torrent['quality'])
        quality = quality.replace(',', '')
        seeders = int(torrent['seeders'])
        leechers = int(torrent['leechers'])
        THASH = torrent['hash'].encode('utf-8')
        hash_arrs.append(THASH)
        try:
            percent = (int(rtc.f.get_completed_chunks(THASH, 0)) * 100) / int(
                rtc.f.get_size_chunks(THASH, 0))
        except:
            percent = 0
        subdata = {
            'approved': approved,
            'tracker': tracker,
            'size': size,
            'filetype': filetype,
            'quality': quality,
            'seeders': seeders,
            'leechers': leechers,
            'percent': percent,
            'hash': THASH
        }
        hash_data[THASH] = subdata

    uhash_arrs = set(hash_arrs)

    # TODO Add METADATA

    def set_approved(let, li):
        if let['approved']: li.setProperty('fanart_image', Thumbs_Up)
        else: li.setProperty('fanart_image', Thumbs_Down)

    # Поиск полностью загруженных раздач
    for uhash in uhash_arrs:
        ninfo = hash_data[uhash]
        if ninfo['percent'] == 100:
            it = '%s Тип:%s %s' % (ninfo['tracker'], ninfo['filetype'],
                                   ninfo['quality'])
            li = xbmcgui.ListItem(it, iconImage=iOK, thumbnailImage=iOK)
            li.setInfo('video', {'title': it, 'size': ninfo['size']})
            set_approved(ninfo, li)
            if rtc.d.get_size_files(uhash) > 1:
                xbmcplugin.addDirectoryItem(h,
                                            rtc.d.get_directory(uhash),
                                            li,
                                            isFolder=True)
            else:
                xbmcplugin.addDirectoryItem(h,
                                            os.path.join(
                                                rtc.d.get_directory(uhash),
                                                rtc.d.get_name(uhash)),
                                            li,
                                            isFolder=False)

    # Поиск загружаемых раздач
    for uhash in uhash_arrs:
        ninfo = hash_data[uhash]
        # TODO and paused...
        try:
            is_active = int(rtc.d.is_active(ninfo['hash']))
        except:
            is_active = 0
        if (ninfo['percent'] < 100) and (is_active == 1):
            it = '%d%% S=%s, L=%s %s(%s), от %s' % (
                ninfo['percent'], ninfo['seeders'], ninfo['leechers'],
                ninfo['quality'], ninfo['filetype'], ninfo['tracker'])
            li = xbmcgui.ListItem(it,
                                  iconImage=iDOWNLOADING,
                                  thumbnailImage=iDOWNLOADING)
            li.setInfo('video', {'title': it, 'size': ninfo['size']})
            set_approved(ninfo, li)
            # TODO Сделать доп. пункты.
            ppath = os.path.join(rtc.d.get_directory(uhash),
                                 rtc.d.get_name(uhash))
            if rtc.d.get_size_files(uhash) > 1:
                xbmcplugin.addDirectoryItem(h,
                                            rtc.d.get_directory(uhash),
                                            li,
                                            isFolder=True)
            else:
                xbmcplugin.addDirectoryItem(h,
                                            os.path.join(
                                                rtc.d.get_directory(uhash),
                                                rtc.d.get_name(uhash)),
                                            li,
                                            isFolder=False)

    for uhash in uhash_arrs:
        ninfo = hash_data[uhash]
        if ninfo['percent'] == 0:
            it = 'S=%s, L=%s %s(%s), от %s' % (
                ninfo['seeders'], ninfo['leechers'], ninfo['quality'],
                ninfo['filetype'], ninfo['tracker'])
            li = xbmcgui.ListItem(it, iconImage=iSTART, thumbnailImage=iSTART)
            li.setInfo('video', {'title': it, 'size': ninfo['size']})
            set_approved(ninfo, li)
            uri = '%s?mode=loadtorrent&hash=%s&film_id=%s&dlpath=%s' % (
                sys.argv[0], uhash, film_id, urllib.quote_plus(dlpath))
            xbmcplugin.addDirectoryItem(h, uri, li)

    xbmcplugin.addSortMethod(h, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
    xbmcplugin.addSortMethod(h, sortMethod=xbmcplugin.SORT_METHOD_SIZE)
    xbmcplugin.endOfDirectory(h)
Esempio n. 7
0
def filmsbrowse(params):
    print '=== def filmsbrowse(%s): ===' % params

    try:
        href = urllib.unquote_plus(params['href'])
        params['href'] = href
    except:
        href = ''
    try:
        params['query'] = urllib.unquote_plus(params['query'])
    except:
        pass

    GL = params.copy()
    del GL['mode']
    del GL['href']

    #url =
    http = kbutils.KBREQUEST('%s?%s' % (href, urllib.urlencode(GL)))

    djson = demjson.decode(http)
    #print djson

    # Если подключен rTorrent - генерируем список подкаталогов, для проверки загрузки
    rtc = kbutils.get_rtc()
    if rtc != None:
        base_dl_path = rtc.get_directory()
        dpa = []
        if (kbutils.rtc_select == 'true'):
            for ddir in os.listdir(base_dl_path):
                dpa.append(os.path.join(base_dl_path, ddir))
        else:
            dpa.append(os.path.join(base_dl_path))

    for cur in djson:

        info = kbutils.getmetadata(cur, cur['id'])

        if rtc != None:
            for chkdir in dpa:
                if os.path.exists(os.path.join(chkdir, str(cur['id']))):
                    info['title'] = '[DL] %s' % info['title']
                    break

        li = xbmcgui.ListItem(label=info['title'],
                              iconImage=info['iconImage'],
                              thumbnailImage=info['thumbnailImage'])
        li.setInfo(type='video', infoLabels=info)

        if cur['type'] == 'movie':
            #li.setProperty('IsPlayable', 'true')
            uri = '%s?mode=openfilm&film_id=%s' % (sys.argv[0], cur['id'])
            if not xbmcplugin.addDirectoryItem(h, uri, li, isFolder=True):
                break
        elif cur['type'] == 'series':
            uri = '%s?mode=openseasons&series_id=%s' % (sys.argv[0], cur['id'])
            if not xbmcplugin.addDirectoryItem(h, uri, li, isFolder=True):
                break
        else:
            kbutils.showMessage('Ой, "%s"' % film_type,
                                'Не могу добавить этот тип фильма')

    if len(djson) == int(params['limit']):
        li = xbmcgui.ListItem('Далее >', iconImage=icon, thumbnailImage=icon)
        params['offset'] = str(int(params['offset']) + int(params['limit']))
        uri = '%s?%s' % (sys.argv[0], urllib.urlencode(params))
        xbmcplugin.addDirectoryItem(h,
                                    uri,
                                    li,
                                    isFolder=True,
                                    totalItems=kbutils.LIST_LIMIT())

    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_ALBUM)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_DATE)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_DURATION)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_GENRE)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_TITLE)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_VIDEO_RATING)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_VIDEO_TITLE)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_VIDEO_YEAR)
    xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_LABEL)

    xbmcplugin.endOfDirectory(h)
Esempio n. 8
0
def rtcshowdl(params):

    print '=== def rtcshowdl(%s): ===' % params

    rtc = kbutils.get_rtc()
    if rtc == None: return False

    try:
        action = params['action']
    except:
        action = None

    if action == None:

        dlds = []
        dlds = rtc.d.multicall('main', "d.get_name=", "d.get_hash=", "d.get_completed_chunks=", "d.get_size_chunks=", "d.get_size_files=", \
         "d.get_directory=", "d.is_active=", "d.get_complete=", "d.get_priority=", "d.is_multi_file=", "d.get_size_bytes=", \
         "d.get_custom=", "d.get_custom1=", "d.get_custom2=", "d.get_custom3=", "d.get_custom4=", "d.get_custom5=", "d.get_custom=kbmeta" )

        dlds_len = len(dlds)

        for dld in dlds:
            dld_name = dld[0]
            dld_hash = dld[1]
            dld_completed_chunks = dld[2]
            dld_size_chunks = dld[3]
            dld_percent_complete = dld_completed_chunks * 100 / dld_size_chunks
            dld_size_files = dld[4]
            dld_directory = dld[5]
            dld_is_active = dld[6]
            dld_complete = dld[7]
            dld_priority = dld[8]
            dld_is_multi_file = dld[9]
            dld_size_bytes = int(dld[10])
            dld_custom = dld[11]
            dld_custom1 = dld[12]  # kinobaza
            dld_custom2 = dld[13]  # Comment (metadata)
            dld_custom3 = dld[14]
            dld_custom4 = dld[15]
            dld_custom5 = dld[16]
            dld_kbmeta = dld[17]

            if dld_custom1 == 'kinobaza':
                #print 'dld_custom  [%s]' % dld_custom
                #print 'dld_custom1 [%s]' % dld_custom1
                #print 'dld_custom2 [%s]' % dld_custom2
                #print 'dld_custom3 [%s]' % dld_custom3
                #print 'dld_custom4 [%s]' % dld_custom4
                #print 'dld_custom5 [%s]' % dld_custom5

                #dld_kbmeta = dld_kbmeta.replace('custom_value="','').replace('"','')

                #print 'kbmeta: %s' % dld_kbmeta

                info = get_params(dld_kbmeta)
                for curi in info:
                    info[curi] = urllib.unquote_plus(info[curi])

                def key_to_int(arr, keyname):
                    try:
                        arr[keyname] = int(arr[keyname])
                    except:
                        try:
                            del info[keyname]
                        except:
                            pass

                key_to_int(info, 'count')
                key_to_int(info, 'year')
                key_to_int(info, 'episode')
                key_to_int(info, 'season')
                key_to_int(info, 'top250')
                key_to_int(info, 'tracknumber')
                key_to_int(info, 'playcount')
                key_to_int(info, 'overlay')
                try:
                    info['rating'] = float(info['rating'])
                except:
                    try:
                        del info['rating']
                    except:
                        pass

                info['size'] = dld_size_bytes
                info['title'] = '%s (%s%%)' % (info['title'],
                                               dld_percent_complete)

                if dld_is_active == 1:
                    cm_action = 'СТОП', 'xbmc.runPlugin(%s?mode=rtcshowdl&action=dlstop&hash=%s)' % (
                        sys.argv[0], dld_hash)
                else:
                    cm_action = 'СТАРТ', 'xbmc.runPlugin(%s?mode=rtcshowdl&action=dlstart&hash=%s)' % (
                        sys.argv[0], dld_hash)

                fdc = 'xbmc.runPlugin(%s?mode=rtcshowdl&action=setprio&hash=%s&prio=%s)'
                cm = [cm_action, ('УДАЛИТЬ', 'xbmc.runPlugin(%s?mode=rtcshowdl&action=erase&hash=%s)'%(sys.argv[0],dld_hash)),\
                 ('Приоритет: высокий',     fdc % (sys.argv[0], dld_hash, 3)),\
                 ('Приоритет: нормальный',  fdc % (sys.argv[0], dld_hash, 2)),\
                 ('Приоритет: низкий',      fdc % (sys.argv[0], dld_hash, 1)),\
                 ('Приоритет: не загружать',fdc % (sys.argv[0], dld_hash, 0)) ]

                li = xbmcgui.ListItem(label=info['title'],
                                      label2=dld_name,
                                      iconImage=info['iconImage'],
                                      thumbnailImage=info['thumbnailImage'])
                li.addContextMenuItems(items=cm, replaceItems=True)
                li.setInfo(type='video', infoLabels=info)

                if dld_size_files > 1:
                    uri = '%s?mode=rtcshowdl&action=showfiles&hash=%s&numfiles=%s' % (
                        sys.argv[0], dld_hash, dld_size_files)
                    if not xbmcplugin.addDirectoryItem(
                            h, uri, li, isFolder=True, totalItems=dlds_len):
                        break
                else:
                    #li.setProperty('IsPlayable', 'true')
                    uri = '%s?mode=rtcshowdl&action=playfile&film_id=%s' % (
                        sys.argv[0], info['film_id'])
                    if not xbmcplugin.addDirectoryItem(
                            h, uri, li, isFolder=True, totalItems=dlds_len):
                        break

        xbmcplugin.addSortMethod(h, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
        xbmcplugin.addSortMethod(h, sortMethod=xbmcplugin.SORT_METHOD_SIZE)
        xbmcplugin.endOfDirectory(h, cacheToDisc=False)

    elif action == 'setprio':
        rtc.d.set_priority('%s' % params['hash'], int(params['prio']))
        xbmc.executebuiltin('Container.Refresh')
    elif action == 'erase':
        #rtc.d.set_priority('%s' % params['hash'], int(params['prio']))

        rtc.d.erase(params['hash'])
        kbutils.showMessage('Удален торрент', 'Сами файлы остались на месте',
                            5000)
        xbmc.executebuiltin('Container.Refresh')

    elif action == 'showfiles':

        #print 'Воспроизводим %s' % dhash
        pfile = os.path.join(rtc.d.get_directory(params['hash']),
                             rtc.d.get_name(params['hash']))
        #print 'Файл %s' % pfile
        #i = xbmcgui.ListItem(path = pfile)
        #xbmcplugin.setResolvedUrl(h, True, i)
        #return True

        files = []
        files = rtc.f.multicall(params['hash'], 1, "f.get_path=",
                                "f.get_completed_chunks=",
                                "f.get_size_chunks=", "f.get_priority=",
                                "f.get_size_bytes=")
        i = 0
        for f in files:
            f_name = f[0]
            f_completed_chunks = int(f[1])
            f_size_chunks = int(f[2])
            f_size_bytes = int(f[4])
            f_percent_complete = f_completed_chunks * 100 / f_size_chunks
            f_priority = f[3]
            if f_percent_complete == 100:
                f_complete = 1
            else:
                f_complete = 0
            #tbn=getIcon(0,1,f_complete,f_priority)
            if f_percent_complete < 100:
                li_name = f_name + ' (' + str(f_percent_complete) + '%)'
            else:
                li_name = f_name
            li = xbmcgui.ListItem( \
             label=li_name, \
             iconImage=icon, thumbnailImage=icon)
            #cm = [(g.__lang__(30120),"xbmc.runPlugin(%s?mode=action&method=f.set_priority&arg1=%s&arg2=%s&arg3=2)" % ( sys.argv[0], hash,i)), \
            #	(g.__lang__(30121),"xbmc.runPlugin(%s?mode=action&method=f.set_priority&arg1=%s&arg2=%s&arg3=1)" % ( sys.argv[0], hash,i)), \
            #	(g.__lang__(30124),"xbmc.runPlugin(%s?mode=action&method=f.set_priority&arg1=%s&arg2=%s&arg3=0)" % ( sys.argv[0], hash,i))]
            #li.addContextMenuItems(items=cm,replaceItems=True)
            li.setInfo('video', {'title': li_name, 'size': f_size_bytes})

            #uri = '%s?mode=rtcshowdl&action=playfile&hash=%s&file_id=%s'%(sys.argv[0], params['hash'], i)

            uri = os.path.join(pfile, rtc.f.get_frozen_path(params['hash'], i))
            if not xbmcplugin.addDirectoryItem(
                    h, uri, li, isFolder=True, totalItems=len(files)):
                break
            i = i + 1
        xbmcplugin.addSortMethod(h, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
        xbmcplugin.addSortMethod(h, sortMethod=xbmcplugin.SORT_METHOD_SIZE)
        xbmcplugin.endOfDirectory(h, cacheToDisc=False)

    elif action == 'playfile':
        print 'playfile....'
        openfilm({'film_id': params['film_id']})