Beispiel #1
0
    def set_filter_date(self):

        dialog = xbmcgui.Dialog()
        if self.start_date == '':
            self.start_date = str(datetime.datetime.now())[:10]
        if self.end_date == '':
            self.end_date = str(datetime.datetime.now())[:10]

        try:
            d = dialog.numeric(1, common.getstring(30117) ,strftime("%d/%m/%Y",strptime(self.start_date,"%Y-%m-%d")) )
            if d != '':    
                self.start_date = strftime("%Y-%m-%d",strptime(d.replace(" ","0"),"%d/%m/%Y"))
            else:
                self.start_date =''
            common.log('', str(self.start_date))
            
            d = dialog.numeric(1, common.getstring(30118) ,strftime("%d/%m/%Y",strptime(self.end_date,"%Y-%m-%d")) )
            if d != '':
                self.end_date = strftime("%Y-%m-%d",strptime(d.replace(" ","0"),"%d/%m/%Y"))
            else:
                self.end_date =''
            common.log('', str(self.end_date))
        except:
            pass

        if self.start_date != '' or self.end_date != '':
            self.getControl( BUTTON_DATE ).setLabel( self.start_date + ' ... ' + self.end_date )
        else:
            self.getControl( BUTTON_DATE ).setLabel( common.getstring(30164) )
        self.getControl( BUTTON_DATE ).setVisible(False)
        self.getControl( BUTTON_DATE ).setVisible(True)        
Beispiel #2
0
def enableAddons(melding=None, update=True):
    if kodiver > 16.5:
        try:
            from sqlite3 import dbapi2 as database
        except:
            from pysqlite2 import dbapi2 as database
        db_dir = xbmc.translatePath("special://profile/Database")
        db_path = os.path.join(db_dir, 'Addons27.db')
        conn = database.connect(db_path)
        conn.text_factory = str
        addonfolder = xbmc.translatePath(
            os.path.join('special://home', 'addons'))
        contents = os.listdir(addonfolder)
        conn.executemany('update installed set enabled=1 WHERE addonID = (?)',
                         ((val, ) for val in contents))
        conn.commit()
        if update:
            xbmc.executebuiltin('UpdateAddonRepos()')
            log("XvBMC_UTILS.UpdateAddonRepos()")
            xbmc.executebuiltin('UpdateLocalAddons()')
            log("XvBMC_UTILS.UpdateLocalAddons()")
        if melding:
            dialog.ok("[COLOR lime][B]Addons enabled[/COLOR][/B]",
                      '[COLOR white]ALL[/COLOR] addons are [B]enabled![/B]')
    else:
        pass
Beispiel #3
0
def getSteamExePath():
    import errno, sys, _winreg
    steamExe = ''

    try:
        if sys.maxsize > 2**32:
            arch_keys = {_winreg.KEY_WOW64_32KEY, _winreg.KEY_WOW64_64KEY}
        else:
            arch_keys = {_winreg.KEY_READ}

        for arch_key in arch_keys:

            key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                  r"SOFTWARE\Valve\Steam", 0,
                                  _winreg.KEY_READ | arch_key)
            try:
                steamExe = _winreg.QueryValueEx(
                    key, 'InstallPath')[0] + "\\steam.exe"
            except OSError as e:
                if e.errno == errno.ENOENT:
                    # DisplayName doesn't exist in this skey
                    pass
            finally:
                key.Close()
    except Exception, e:
        log(e.message)
        log(e.__class__.__name__)
        traceback.print_exc(e)
Beispiel #4
0
    def _walk(self, path, recursive, types):
        filenames = []
        dirnames   = []

        path = xbmcvfs.translatePath(path)
        common.log("Scanner._walk",'"%s"'%path)
        #if xbmcvfs.exists(xbmcvfs.translatePath(path)) or re.match(r"[a-zA-Z]:\\", path) is not None:
        subdirs, files = self.listdir(path)
        for subdir in subdirs:
            dirnames.append(os.path.join(path, subdir))

        for filename in files:
            if types is not None:
                if os.path.splitext(filename)[1].upper() in types or os.path.splitext(filename)[1].lower() in types :
                    filenames.append(os.path.join(path, filename))
                else:
                    common.log("Scanner:_walk", 'Found file "%s" is excluded'%os.path.join(path, filename))
            else:              
                filenames.append(os.path.join(path, filename))


        if recursive:
            for item in subdirs:
                dirnames1, filenames1 = self._walk(os.path.join(path, item), recursive, types)
                for item in dirnames1:
                    dirnames.append(item)
                for item in filenames1:
                    filenames.append(item)
        
        return dirnames, filenames
Beispiel #5
0
    def walk(self, path, recursive = False, types = None):
        filenames = []
        dirnames  = []
        files_to_return = []
        dirs_to_return = []

           
        if path.startswith('multipath://'):
            common.log("Scanner.walk", 'multipath "%s"'%path)
            dirs = path[12:-1].split('/')
            for item in dirs:
                dirnames1, filenames1 = self._walk(urllib.pars.unquote_plus(item), recursive, types)

                for dirname in dirnames1:
                    dirnames.append(dirname)
                for filename in filenames1:
                    filenames.append(filename)               
               
        else:
            common.log("Scanner.walk", 'path "%s"'%path)
            dirnames, filenames = self._walk(path, recursive, types)

        # Make sure everything is a unicode
        for filename in filenames:
            files_to_return.append(common.smart_unicode(filename))
        for dirname in dirnames:
            dirs_to_return.append(common.smart_unicode(dirname))

        return dirs_to_return, files_to_return
Beispiel #6
0
    def listdir(self, path):

        try:
            return xbmcvfs.listdir(path)
        except:
            file_list = []
            dir_list  = []
            json_response = xbmc.executeJSONRPC('{ "jsonrpc" : "2.0" , "method" : "Files.GetDirectory" , "params" : { "directory" : "%s" , "sort" : { "method" : "file" } } , "id" : 1 }' % common.smart_utf8(path.replace('\\', '\\\\')))
            jsonobject = json.loads(json_response)

            try:
                if jsonobject['result']['files']:

                    for item in jsonobject['result']['files']:

                        filename = common.smart_utf8(item['label'])
                        if item['filetype'] == 'directory':
                            dir_list.append(filename)
                        else:
                            file_list.append(filename)
                            
            except Exception as msg:
                common.log("Scanner.listdir", 'Path "%s"'%path, xbmc.LOGERROR )
                common.log("Scanner.listdir", "%s - %s"%(Exception,msg), xbmc.LOGERROR )
                
            return dir_list, file_list
Beispiel #7
0
def play(p):
    xbmcplugin.setContent(common.addon_handle, 'movie')
    u = p.get('url', '')
    l = common.solveCFP(u)
    if not l == None:
        t = re.compile('<table class=\"table\">(.*?)<\/table>',
                       re.DOTALL).findall(l.text.encode('utf-8'))[0]
        rows = re.compile('(<tr.*?)<\/tr>', re.DOTALL).findall(t)
        players = []
        selList = []
        for r1 in range(len(rows)):
            tds = re.compile('(<td.*?<\/td>)', re.DOTALL).findall(rows[r1])
            pl = re.compile('> (.*?)<\/td>', re.DOTALL).findall(tds[0])[0]
            link = re.compile('<a href=\"(.*?)\" ',
                              re.DOTALL).findall(tds[1])[0]
            kind = re.compile('<td.*?>(.*?)<\/td>',
                              re.DOTALL).findall(tds[3])[0]
            players.append([pl, link])
            selList.append("%s [COLOR lime]%s[/COLOR] | %s" % (pl, kind, link))
        playfrom = xbmcgui.Dialog().select('Wybor zrodla', selList)
        if playfrom >= 0:
            common.log("Wybrano :" + players[playfrom][0] + " - link: " +
                       players[playfrom][1])
            player(players[playfrom])
    else:
        common.info("LINK FEATCHING FAILED", "E404", time=5000)
    xbmcplugin.endOfDirectory(common.addon_handle)
Beispiel #8
0
def player(p,k,x):
	pl=p[0]
	id=p[1]
	key=k
	XHR=x
	rURL="https://"+XHR+"/"+id+"/"
	data={"auth":key}
	common.log('id: '+id+ " key: "+key)
	s=request(rURL,data)
	if s:
		m=re.compile('<iframe.*?src=\".*?\/\/(.*?)\"',re.DOTALL).findall(s)
		if len(m)>1:
			playfrom=xbmcgui.Dialog().select('Wybor zrodla',m)
			common.log('resolving: '+m[playfrom])
		else:
			playfrom=0
		m=m[playfrom]
		if 'cda' in m:
			resolveCDA(m)
		elif 'openload' in m:
			resolveOPENLOAD(m)
		elif 'facebook' in m:
			resolveFB(m)
		else:
			resolveOTHER(m)
			#info('Player nie jest obslugiwany','PLAYER ERROR',200)
	else:
		info("Brak odpowiedzi XHR, wiecej w log-u.","Upss...")
def setup(radiru, radiko, jcba, misc):
    # テンプレート読み込み
    f = codecs.open(common.template_file,'r','utf-8')
    template = f.read()
    f.close()
    # 放送局リスト
    s = [common.addon.getLocalizedString(30520)]
    stations = Data((radiru,radiko)).stations
    for station in stations:
        s.append(station['name'])
    # ソース作成
    ffmpeg = '/usr/local/bin/ffmpeg'
    if not os.path.isfile(ffmpeg): ffmpeg = ''
    rtmpdump = '/usr/local/bin/rtmpdump'
    if not os.path.isfile(rtmpdump): rtmpdump = ''
    source = template.format(
        radiru = radiru.getSettingsData(),
        radiko = radiko.getSettingsData(),
        jcba   = jcba.getSettingsData(),
        misc   = misc.getSettingsData(),
        bc = '|'.join(s),
        ffmegpath = ffmpeg,
        rtmpdumppath = rtmpdump,
        os = platform.system())
    # ファイル書き込み
    f = codecs.open(common.settings_file,'w','utf-8')
    f.write(source)
    f.close()
    # ログ
    log('settings updated')
Beispiel #10
0
 def run(self):
 
     for description in self.descriptions:
 
         common.log('[Rytec EPG Downloader]: '+description)
         self.i += self.upd
         self.progress('update', self.i, 'Rytec EPG Downloader', description, 'Downloading XML Data')
         ret = False
         epg_url = self.get_epg_url(description)
         
         if epg_url:
             ret = self.download_epg(description, epg_url)
             
         if not ret and not description.startswith('http'):
             self.run_rytec(description)
             
     self.progress('update', 70, 'Merging XML Data', ' ', 'Please Wait...This May Take Awhile')
             
     if self.len_desc > 1:
         common.merge_epg()
         self.progress('update', 90, 'Merging XML Data', ' ', 'Please Wait...This May Take Awhile')
         common.copy_temp_merged()
         common.delete_temp_merged()
     
     self.progress('close', '', '', '', '')
    def library_update_scheduled(self):
        """
        Checks if the scheduled time for a library update has been reached
        """
        try:
            now = datetime.now()
            update_frequency = g.ADDON.getSettingInt('auto_update')
            interval = g.ADDON.getSettingInt('schedule_check_interval')
            next_schedule_check = (self.last_schedule_check +
                                   timedelta(minutes=interval))

            if not update_frequency or now <= next_schedule_check:
                return False

            self.last_schedule_check = now
            time = g.ADDON.getSetting('update_time') or '00:00'
            lastrun_date = (g.ADDON.getSetting('last_update') or '1970-01-01')
            lastrun = common.strp('{} {}'.format(lastrun_date, time[0:5]),
                                  '%Y-%m-%d %H:%M')
            nextrun = lastrun + timedelta(
                days=[0, 1, 2, 5, 7][update_frequency])
            common.log(
                'It\'s currently {}, next run is scheduled for {}'.format(
                    now, nextrun))

            return now >= nextrun
        except TypeError:
            # When there is concurrency between getSettingX and setSettingX at the same time,
            # the get settings fails to read
            return False
Beispiel #12
0
def player(p):
    pl = p[0]
    link = p[1]
    l = common.solveCFP(link)
    stream_url = ''
    if not l == None:
        try:
            iframesrc = re.compile('<iframe src=\"(.*?)\" ',
                                   re.DOTALL).findall(
                                       l.text.encode('utf-8'))[0]
            common.log(l.text.encode('utf-8'))
            if iframesrc.startswith('//'):
                iframesrc = 'http:' + iframesrc
            try:
                stream_url = urlresolve.resolve(iframesrc)
            except Exception, e:
                stream_url = ''
                s = xbmcgui.Dialog().ok(
                    '[COLOR red]Problem[/COLOR]',
                    'Może inny stream_url będzie działał?',
                    'Urlresolver ERROR: [%s]' % str(e))
        except:
            common.log('no iframe found: ' + link)
        if stream_url:
            xbmcplugin.setResolvedUrl(common.addon_handle, True,
                                      xbmcgui.ListItem(path=stream_url))
        else:
            return False
        xbmcplugin.endOfDirectory(common.addon_handle)
Beispiel #13
0
def getSteamExePath():
        import errno, sys, _winreg
        steamExe = ''

        try:
            if sys.maxsize > 2**32:
                arch_keys = {_winreg.KEY_WOW64_32KEY, _winreg.KEY_WOW64_64KEY}
            else:
                arch_keys = {_winreg.KEY_READ}

            for arch_key in arch_keys:

                key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Valve\Steam", 0, _winreg.KEY_READ | arch_key)
                try:
                    steamExe = _winreg.QueryValueEx(key, 'InstallPath')[0] + "\\steam.exe"
                except OSError as e:
                    if e.errno == errno.ENOENT:
                        # DisplayName doesn't exist in this skey
                        pass
                finally:
                    key.Close()
        except Exception,e:
            log(e.message)
            log(e.__class__.__name__)
            traceback.print_exc(e)
    def _check_excluded_files(self, filename):
        for ext in common.getaddon_setting("picsexcl").lower().split("|"):
            if ext in filename.lower() and len(ext)>0:
                common.log("VFSScanner._check_excluded_files", 'Picture "%s" excluded due to exclude condition "%s"'%(filename , common.getaddon_setting("picsexcl")) )
                return False

        return True
Beispiel #15
0
def lista(params):
	u=MURL+params.get('url','/titles')
	search=params.get('search',None)
	letter=params.get('letter',None)
	if search=='1':
		p=standardListOptions
		p['search']=xbmcgui.Dialog().input('Wyszukaj..')
		common.log(p['search'])
	else:
		p=standardListOptions
		p['page']=int(params.get('page',1))
		if letter==None:
			letters=['-','1','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
			letter=letters[xbmcgui.Dialog().select('Wybor zrodla',letters)]
		p['letter']='' if letter=='-' else letter
	u+='?'+urllib.urlencode(p)	
	l=common.solveCFP(u)
	if not l==None:
		try:
			m=re.compile('<section class=\"title-table\">.*?<article>(.*?)<\/article>',re.DOTALL).findall(l.text.encode('utf-8'))
			rows=re.compile('<ul class=\"div-row\">(.*?<li class=\"rate-top\" title=\"Ocena TOP\">.*?<\/li>.*?)<\/ul>',re.DOTALL).findall(m[0])
			for r in range(len(rows)):
				img=re.compile('<li class=\"cover-col\">.*?<a href=\"(.*?)\"',re.DOTALL).findall(rows[r])[0]
				title=re.compile('<h3>.*?>(.*?)<\/a>',re.DOTALL).findall(rows[r])[0]
				link=re.compile('<h3>.*?<a href=\"(.*?)\">',re.DOTALL).findall(rows[r])[0]
				tags=string.join(re.compile('<li.*?<a data-tag-id.*?>(.*?)<\/a>',re.DOTALL).findall(rows[r]),',')
				try:
					nEE=re.compile('<li class=\"episodes-col\" title=\"(.*?)\">',re.DOTALL).findall(rows[r])[0]
				except:
					nEE='0 x 0min'
				nE=[re.compile('<li class=\"episodes-col\".*?>(.*?)<',re.DOTALL).findall(rows[r])[0],nEE]
				kind=re.compile('<li class=\"title-kind-col\">(.*?)<',re.DOTALL).findall(rows[r])[0]
				ocena=re.compile('<li class=\"rate-top\".*?>(.*?)<',re.DOTALL).findall(rows[r])[0]
				##addFolder(title,link,img,tags,nE,kind,ocena,sendto)
				## add item
				cm=[]
				cm.append(('Wyświetl opis', 'RunPlugin(%s?mode=shindenpl&action=opis&url=%s)' % (common.sysaddon,urllib.quote_plus(link))))
				
				link+='/all-episodes'
				noe=int(nE[0])
				try:
					dur=int(re.compile('x(.*?)min').findall(nE[1])[0])*60
				except:
					dur=0
				li=xbmcgui.ListItem('[COLOR silver]('+kind+')[/COLOR] '+title+' - [COLOR lime]('+(nE[1] if nE[1] else nE[0])+')[/COLOR]',label2='test',thumbnailImage=MURL+img)
				info={'rating':ocena,'genre':tags,'episode':noe,'duration':dur}
				li.setInfo( type="video", infoLabels = info )
				li.setProperty('IsPlayable', 'true')
				li.setProperty('fanart_image', MURL+img )
				## dodaje menu kontekstowe
				li.addContextMenuItems(cm)
				u=common.sysaddon+"?mode=shindenpl&action=seria&url="+urllib.quote_plus(link)
				xbmcplugin.addDirectoryItem(handle=common.addon_handle,url=u,listitem=li,isFolder=True)
			xbmcplugin.addDirectoryItem(handle=common.addon_handle,url=common.sysaddon+"?mode=shindenpl&action=lista&page="+str(p['page']+1)+"&letter="+letter,listitem=xbmcgui.ListItem("[COLOR gold]>>> DALEJ >>>[/COLOR]"),isFolder=True)
			xbmcplugin.addDirectoryItem(handle=common.addon_handle,url=common.sysaddon+"?mode=shindenpl",listitem=xbmcgui.ListItem("[COLOR gold]>>> MENU <<<[/COLOR]"),isFolder=True)
		except:
			xbmcplugin.addDirectoryItem(handle=common.addon_handle,url=common.sysaddon+"?mode=shindenpl&action=lista",listitem=xbmcgui.ListItem("[COLOR red]-- error --[/COLOR]"),isFolder=True)		
		
	xbmcplugin.setContent(common.addon_handle, 'tvshows')
	xbmcplugin.endOfDirectory(common.addon_handle)
Beispiel #16
0
def start(background=False):
    global Resumes
    global Birth
    # ディレクトリをチェック
    if not os.path.isdir(common.cache_path): os.makedirs(common.cache_path)
    if not os.path.isdir(common.media_path): os.makedirs(common.media_path)
    if not os.path.isdir(common.data_path):  os.makedirs(common.data_path)
    # 初期化
    if os.path.isfile(common.settings_file) and getAlive():
        data = proceed()
    else:
        data = initialize()
    # 表示
    if not background: data.showPrograms()
    # Birth設定
    Birth = setBirth()
    # Alive設定を更新
    setAlive()
    # 更新
    monitor = Monitor()
    while not monitor.abortRequested():
        if monitor.waitForAbort(common.check_interval):
            log('break by aborted')
            clearResumes();
            break
        if not getBirth():
            log('break by renewed')
            break
        # common.check_interval毎に実行
        data = watcher(data)
        # Alive設定を更新
        setAlive()
Beispiel #17
0
    def run(self):

        for description in self.descriptions:

            common.log('[Rytec EPG Downloader]: ' + description)
            self.i += self.upd
            self.progress('update', self.i, 'Rytec EPG Downloader',
                          description, 'Downloading XML Data')
            ret = False
            epg_url = self.get_epg_url(description)

            if epg_url:
                ret = self.download_epg(description, epg_url)

            if not ret and not description.startswith('http'):
                self.run_rytec(description)

        self.progress('update', 70, 'Merging XML Data', ' ',
                      'Please Wait...This May Take Awhile')

        if self.len_desc > 1:
            common.merge_epg()
            self.progress('update', 90, 'Merging XML Data', ' ',
                          'Please Wait...This May Take Awhile')
            common.copy_temp_merged()
            common.delete_temp_merged()

        self.progress('close', '', '', '', '')
Beispiel #18
0
def serial(p):
    xbmcplugin.setContent(common.addon_handle, 'tvshows')
    u = p.get('url', '')
    l = common.solveCFP(u)
    if not l == None:
        try:
            title2 = helpers.PLchar(
                re.compile(
                    '<div class=\"col-sm-9\">.*?<h3 class=\"headline\">(.*?)<\/h3>',
                    re.DOTALL).findall(l.text.encode('utf-8'))[0])
            common.log(title2)
            img = re.compile(
                '<div class=\"col-sm-9\">.*?<img src=\"(.*?)\" alt=\".*?\" class=\"img-responsive\"',
                re.DOTALL).findall(l.text.encode('utf-8'))[0]
            common.log(img)
            episodes = re.compile('<li class=\"episode\">(.*?)<\/li>',
                                  re.DOTALL).findall(l.text.encode('utf-8'))
            common.log(len(episodes))
            lista = []
            for e in range(len(episodes)):
                try:
                    lista.append([
                        helpers.PLchar(
                            re.compile('<a href=.*?>(.*?)<\/a>',
                                       re.DOTALL).findall(episodes[e])[0]),
                        re.compile('<a href=\"(.*?)\">',
                                   re.DOTALL).findall(episodes[e])[0]
                    ])
                except:
                    common.log('przygotowanie listy epizodow')
            lista.sort()

            for e in range(len(lista)):
                try:
                    link = lista[e][
                        1]  #re.compile('<a href=\"(.*?)\">',re.DOTALL).findall(episodes[e])[0]
                    title = lista[e][
                        0]  #helpers.PLchar(re.compile('<a href=.*?>(.*?)<\/a>',re.DOTALL).findall(episodes[e])[0])
                    li = xbmcgui.ListItem(title, thumbnailImage=img)
                    info = {}
                    li.setInfo(type="video", infoLabels=info)
                    li.setProperty('IsPlayable', 'true')
                    li.setProperty('fanart_image', img)
                    u = common.sysaddon + "?mode=alltubepl&action=play&url=" + urllib.quote_plus(
                        link)
                    xbmcplugin.addDirectoryItem(handle=common.addon_handle,
                                                url=u,
                                                listitem=li,
                                                isFolder=False)
                except:
                    common.log('wyswietlenie listy epizodow')
        except:
            xbmcplugin.addDirectoryItem(
                handle=common.addon_handle,
                url=common.sysaddon + "?mode=alltubepl&action=serial",
                listitem=xbmcgui.ListItem("[COLOR red]-- error --[/COLOR]"),
                isFolder=True)
    xbmcplugin.endOfDirectory(common.addon_handle)
    def _countfiles(self, path, reset = True, recursive = True):
        if reset:
            self.totalfiles = 0
        
        common.log("VFSScanner._countfiles", 'path "%s"'%path)
        (_, files) = self.filescanner.walk(path, recursive, self.picture_extensions if self.use_videos == "false" else self.all_extensions)
        self.totalfiles += len(files)

        return self.totalfiles
    def dispatcher(self, options):

        self.options = options

        if self.options.rootpath:
            self.options.rootpath = common.smart_utf8(unquote_plus( self.options.rootpath)).replace("\\\\", "\\").replace("\\\\", "\\").replace("\\'", "\'")
            common.log("VFSScanner.dispatcher", 'Adding path "%s"'%self.options.rootpath, xbmc.LOGNOTICE)
            self.scan = AddonScan()
            self.action = common.getstring(30244)#adding
            self.scan.create( common.getstring(30000) )
            self.current_root_entry = 1
            self.total_root_entries = 1
            self.scan.update(0,0,
                        common.getstring(30000)+" ["+common.getstring(30241)+"]",#MyPicture Database [preparing]
                        common.getstring(30247))#please wait...
            
            self._countfiles(self.options.rootpath)
            self.total_root_entries = 1
            self._addpath(self.options.rootpath, None, self.options.recursive, True)
            
            self.scan.close()

        elif self.options.database or self.options.refresh:
            paths = self.mpdb.get_all_root_folders()
            common.log("VFSScanner.dispatcher", "Database refresh started", xbmc.LOGNOTICE)
            self.action = common.getstring(30242)#Updating
            if paths:
                self.scan = AddonScan()
                self.scan.create( common.getstring(30000) )
                self.current_root_entry = 0
                self.total_root_entries = 0
                self.scan.update(0,0,
                            common.getstring(30000)+" ["+common.getstring(30241)+"]",#MyPicture Database [preparing]
                            common.getstring(30247))#please wait...
                for path,recursive,update,exclude in paths:
                    if exclude==0:
                        self.total_root_entries += 1
                        self._countfiles(path,False)

                for path,recursive,update,exclude in paths:
                    if exclude==0:
                        try:
                            self.current_root_entry += 1
                            self._addpath(path, None, recursive, update)
                        except:
                            print_exc()

                self.scan.close()

        # Set default translation for tag types
        self.mpdb.default_tagtypes_translation()
        self.mpdb.cleanup_keywords()

        # delete all entries with "sha is null"
        self.picsdeleted += self.mpdb.del_pics_wo_sha(self.scan_is_cancelled)

        common.show_notification(common.getstring(30000), common.getstring(30248)%(self.picsscanned,self.picsadded,self.picsdeleted,self.picsupdated) )
Beispiel #21
0
def request2(l,d=None):
	s=requests.Session()
	head = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36','X-Requested-With': 'XMLHttpRequest','Host': 'openload.co','contentType': 'application/x-www-form-urlencoded; charset=UTF-8','Referer': 'https://openload.co'}
	r=None
	try:
		r=s.get(l, params=d, headers=head,timeout=10)
	except:
		common.log('nieudane request OPENLOAD')
	return r
Beispiel #22
0
def filmy(p):
    xbmcplugin.setContent(common.addon_handle, 'tvshows')
    u = MURL + p.get('url', '/filmy-online')
    page = int(p.get('page', 1))
    u += '/strona[' + str(page) + ']+'
    l = common.solveCFP(u)
    if not l == None:
        try:
            rows = re.compile(
                '<div class=\"item-block clearfix\">.*?<div class=\"row\">.*?(<a href=\".*?<\/a>).*?<\/div>.*?<\/div>',
                re.DOTALL).findall(l.text.encode('utf-8'))
            common.log(len(rows))
            for r in range(len(rows)):
                img = (re.compile('<img src=\"(.*?)\"',
                                  re.DOTALL).findall(rows[r])[0]
                       )  #.replace("thumb","normal")
                title = helpers.PLchar(
                    re.compile('<h3>(.*?)<\/h3>',
                               re.DOTALL).findall(rows[r])[0])
                stitle = re.compile('<div class=\"second-title\">(.*?)<\/div>',
                                    re.DOTALL).findall(rows[r])[0]
                details = helpers.PLchar(
                    re.compile(
                        '<i class=\"fa fa-microphone\".*?>.*?<\/i>(.*?)<i',
                        re.DOTALL).findall(rows[r])[0])
                desc = helpers.PLchar(
                    re.compile('<p .*?>(.*?)<\/p',
                               re.DOTALL).findall(rows[r])[0])
                link = re.compile('<a href=\"(.*?)\">',
                                  re.DOTALL).findall(rows[r])[0]
                li = xbmcgui.ListItem(title + ' - [COLOR lime](' + details +
                                      ')[/COLOR]',
                                      thumbnailImage=img)
                info = {'plotoutline': desc, 'plot': desc}
                li.setInfo(type="video", infoLabels=info)
                li.setProperty('IsPlayable', 'true')
                li.setProperty('fanart_image', img.replace('thumb', 'normal'))
                u = common.sysaddon + "?mode=alltubepl&action=play&url=" + urllib.quote_plus(
                    link)
                xbmcplugin.addDirectoryItem(handle=common.addon_handle,
                                            url=u,
                                            listitem=li,
                                            isFolder=False)
            xbmcplugin.addDirectoryItem(
                handle=common.addon_handle,
                url=common.sysaddon + "?mode=alltubepl&action=filmy&page=" +
                str(page + 1),
                listitem=xbmcgui.ListItem("[COLOR gold]>>> DALEJ >>>[/COLOR]"),
                isFolder=True)
        except:
            xbmcplugin.addDirectoryItem(
                handle=common.addon_handle,
                url=common.sysaddon + "?mode=alltubepl&action=filmy",
                listitem=xbmcgui.ListItem("[COLOR red]-- error --[/COLOR]"),
                isFolder=True)
    xbmcplugin.endOfDirectory(common.addon_handle)
Beispiel #23
0
def opis(params):
	u=MURL+params.get('url','')
	l=common.solveCFP(u)
	if not l==None:
		try:
			m=re.compile('<section class=\"info-top\">(.*?)<\/section>',re.DOTALL).findall(l.text.encode('utf-8'))[0]
			opis=re.compile('<div.*?>(.*?)<\/div>',re.DOTALL).findall(m)[0]
			xbmcgui.Dialog().textviewer('Opis',opis)
		except:
			common.log("brak informacji o serii")
			common.info("Problem z pobraniem opisu","BRAK OPISU", time=5000)   
Beispiel #24
0
 def download_epg(self, description, epg_url):
 
     ret = common.load_local_xml(epg_url)
     if ret:
         common.log('[Rytec EPG Downloader]: no epg update needed')
     else:
         if description.startswith('http'):
             if self.manual == True:
                 ret = rytec.download_epg(epg_url)
         if self.manual == False:
             ret = rytec.download_epg(epg_url)
             
     return ret
Beispiel #25
0
def play_video(path):
    """
    get url on video, and route it for playing
    :param path: path to js script where final url located
    :return:
    """
    log('path to video= ' + path, xbmc.LOGERROR)
    resp_movie_direct = requests.get(path)
    reg_movie = re.compile('file:\"(.+?)\"')

    url = reg_movie.findall(resp_movie_direct.text)[0]
    play_item = xbmcgui.ListItem(path=url)
    xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)
    def _get_xmp(self, fullpath):
        ###############################
        # get XMP infos               #
        ###############################
        tags = {}
        try:
            xmpclass = XMP_Tags()

            tags = xmpclass.get_xmp(os.path.dirname(fullpath), os.path.basename(fullpath))

        except Exception, msg:
            common.log("VFSScanner._get_xmp", 'Error reading XMP tags for "%s"'%(fullpath), xbmc.LOGERROR)
            common.log("VFSScanner._get_xmp",  "%s - %s"%(Exception,msg), xbmc.LOGERROR )
Beispiel #27
0
    def download_epg(self, description, epg_url):

        ret = common.load_local_xml(epg_url)
        if ret:
            common.log('[Rytec EPG Downloader]: no epg update needed')
        else:
            if description.startswith('http'):
                if self.manual == True:
                    ret = rytec.download_epg(epg_url)
            if self.manual == False:
                ret = rytec.download_epg(epg_url)

        return ret
Beispiel #28
0
def update(p):
	# read local version file
	lpath = os.path.join(xbmc.translatePath('special://home'), 'addons', 'plugin.video.play', 'resources','lib','versions.txt')
	lvf=open(lpath)
	lv=lvf.read().replace('\r','').rstrip('\n').split("\n")
	lvf.close()
	lvd=mdict(lv)

	s=get("https://github.com/yeebuttny/plugs/raw/master/versions.txt?raw=true")
	if not s==None:
		rv=s.text.encode('utf-8').replace('\r','').rstrip('\n').split("\n")
		rvd=mdict(rv)
		for plug in rvd:
			if plug in lvd:
				common.log('remote: '+plug+'-'+rvd[plug]+' | local: '+lvd[plug])
				if rvd[plug]>lvd[plug]:
					common.log(plug+' new version found: '+rvd[plug])
					if updatelocal(plug):
						lvd[plug]=rvd[plug]
			else:
				common.log('remote: '+plug+'-'+rvd[plug]+' |')
				common.log(plug+' new version found: '+rvd[plug])
				if updatelocal(plug):
					lvd[plug]=rvd[plug]
					common.info(plug+ ' - zaktualizowano do wersji: '+rvd[plug])
		saveVersions(rvd)
		common.info('Aktualizacja zakończona','selfupdate')
	else:
		common.info('nie pobrano danych','getURL error')
Beispiel #29
0
 def __init__(self):
     common.log("Service is starting...") 
     self.path = xbmc.translatePath('special://profile/addon_data/%s' %__id__ ) 
    
     #Checks if directory exists for file storage, if not it creates it
     if not xbmcvfs.exists(self.path):
         try:
             xbmcvfs.mkdir(self.path)
         except:
             pass
         
     self._reset = False
     self.monitor = MyMonitor(action=self.restart)
     self.start()
Beispiel #30
0
def alfabetycznie(p):
    xbmcplugin.setContent(common.addon_handle, 'tvshows')
    u = MURL + p.get('url', '/seriale-online/')
    l = common.solveCFP(u)
    if not l == None:
        try:
            lista = re.compile(
                '<ul class=\"list-unstyled text-white term-list clearfix\">(.*?)<\/ul>',
                re.DOTALL).findall(l.text.encode('utf-8'))
            letters = re.compile('<li class=\"letter\">(.*?)<\/li>',
                                 re.DOTALL).findall(lista[0])
            for l in range(len(letters)):
                items = re.compile(
                    '<li data-letter=\"' + letters[l] +
                    '\">(<a.*?<\/a>)<\/li>', re.DOTALL).findall(lista[0])
                li = xbmcgui.ListItem(
                    '[COLOR gold] ------------------------ ' + letters[l] +
                    ' ------------------------ [/COLOR]')
                li.setProperty('IsPlayable', 'false')
                xbmcplugin.addDirectoryItem(handle=common.addon_handle,
                                            url='',
                                            listitem=li,
                                            isFolder=False)
                for i in range(len(items)):
                    try:
                        link = re.compile('<a href=\"(.*?)\">',
                                          re.DOTALL).findall(items[i])[0]
                        title = helpers.PLchar(
                            re.compile('<a href=.*?>(.*?)<\/a>',
                                       re.DOTALL).findall(items[i])[0])
                        li = xbmcgui.ListItem(title)
                        info = {}
                        li.setInfo(type="video", infoLabels=info)
                        li.setProperty('IsPlayable', 'true')
                        u = common.sysaddon + "?mode=alltubepl&action=serial&url=" + urllib.quote_plus(
                            link)
                        xbmcplugin.addDirectoryItem(handle=common.addon_handle,
                                                    url=u,
                                                    listitem=li,
                                                    isFolder=True)
                    except:
                        common.log('litera ' + letter[l] + ' - ' + len(items) +
                                   ' elementow | error')
        except:
            xbmcplugin.addDirectoryItem(
                handle=common.addon_handle,
                url=common.sysaddon + "?mode=alltubepl&action=alfabetycznie",
                listitem=xbmcgui.ListItem("[COLOR red]-- error --[/COLOR]"),
                isFolder=True)
    xbmcplugin.endOfDirectory(common.addon_handle)
Beispiel #31
0
def updatelocal(fname):
	rfn="https://github.com/yeebuttny/plugs/raw/master/lib/"+fname+".py?raw=true"
	lfn=os.path.join(xbmc.translatePath('special://home'), 'addons', 'plugin.video.play', 'resources','lib',fname+'.py')
	s=get(rfn)
	if not s==None:
		s=s.text.encode('utf-8').replace('\r','')
		lf=open(lfn,"w")
		lf.write(s)
		lf.close()
		common.log(fname+" updated")
		return True
	else:
		common.info('nie pobrano danych','getURL error')
		return False
Beispiel #32
0
def list_artists():
    artist = None
    artist = common.enter_artist()
    artist = artist.decode('utf-8')
    common.log('[mvmixPlayer] artist entered: %s' % (artist.encode('utf-8')))
    if artist:
        addDir(artist.encode('utf-8').strip(),'play','','')
        from resources.lib import lastfm
        artists = lastfm.get_artists(artist)
        common.log('[mvmixPlayer] artists found: %s' % str(len(artists)))
        for a in artists:
            artist = a['artist'].encode('utf-8').strip()
            image = a['image']
            addDir(artist,'play',image,'')
        xbmcplugin.endOfDirectory(pluginhandle)
Beispiel #33
0
def list_artists():
    artist = None
    artist = common.enter_artist()
    artist = artist.decode('utf-8')
    common.log('[mvmixPlayer] artist entered: %s' % (artist.encode('utf-8')))
    if artist:
        addDir(artist.encode('utf-8').strip(), 'play', '', '')
        from resources.lib import lastfm
        artists = lastfm.get_artists(artist)
        common.log('[mvmixPlayer] artists found: %s' % str(len(artists)))
        for a in artists:
            artist = a['artist'].encode('utf-8').strip()
            image = a['image']
            addDir(artist, 'play', image, '')
        xbmcplugin.endOfDirectory(pluginhandle)
Beispiel #34
0
 def __init__(self, manual=False):
 
     common.log('[Rytec EPG Downloader]: rytec downloader started')
     self.manual       = manual
     self.sources_list = []
     self.i            = 0
     
     self.descriptions = common.get_descriptions()
     self.len_desc     = len(self.descriptions)
     if self.len_desc == 0:
         common.log('[Rytec EPG Downloader]: empty epg setting')
         return
     self.upd          = 60/self.len_desc
         
     self.progress('create', '', 'Rytec EPG Downloader', '', 'Downloading XML Data')
     self.run()
Beispiel #35
0
def playlink(params):
    u = params.get('url', '')
    if u.endswith('.mp4'):
        xbmcplugin.setResolvedUrl(common.addon_handle, True,
                                  xbmcgui.ListItem(path=u))
        return

    link = ''
    try:
        link = urlresolve.resolve(u)
        common.info(link, 'resolved link')
        common.log(link)
    except:
        common.info('cos wiecej w logu', 'Blad resolveurl')
    if link:
        xbmcplugin.setResolvedUrl(common.addon_handle, True,
                                  xbmcgui.ListItem(path=link))
    def fetchall(self):
        rows = []
        try:
            result = self.cursor.fetchall()
            for row in result:
                cols = []
                for col in row:
                    if isinstance(col, datetime.date):
                        if col == '0000-00-00':
                            col = ''

                    cols.append(col)
                rows.append(cols)
        except Exception as msg:
            common.log("BaseCursor.fetchall",
                       "%s - %s" % (Exception, str(msg)), xbmc.LOGERROR)
        return rows
Beispiel #37
0
    def __init__(self, manual=False):

        common.log('[Rytec EPG Downloader]: rytec downloader started')
        self.manual = manual
        self.sources_list = []
        self.i = 0

        self.descriptions = common.get_descriptions()
        self.len_desc = len(self.descriptions)
        if self.len_desc == 0:
            common.log('[Rytec EPG Downloader]: empty epg setting')
            return
        self.upd = 60 / self.len_desc

        self.progress('create', '', 'Rytec EPG Downloader', '',
                      'Downloading XML Data')
        self.run()
Beispiel #38
0
def morelinks(params):
	u=MURL+params.get('url','')
	l=common.solveCFP(u)
	if not l==None:
		try:
			m=re.compile('<li class=\"relation_t2t\">.*?<a href=\"(.*?)\" title=\"(.*?)\".*?class=\"figure-type\">(.*?)</.*?<img src=\"(.*?)\".*?class=\"figure-type\">(.*?)</',re.DOTALL).findall(l.text.encode('utf-8'))
			for r in range(len(m)):
				title="[%s] %s (%s)"%(m[r][2][0],m[r][1],m[r][4])
				link=m[r][0]+'/all-episodes'
				img=m[r][3].replace("/100x100/","/genuine/")
				li=xbmcgui.ListItem(title,thumbnailImage=MURL+img)
				li.setInfo( type="video", infoLabels = {} )
				li.setProperty('IsPlayable', 'true')
				li.setProperty('fanart_image', MURL+img )
				cm=[]
				cm.append(('Wyświetl opis', 'RunPlugin(%s?mode=shindenpl&action=opis&url=%s)' % (common.sysaddon,urllib.quote_plus(link))))
				## dodaje menu kontekstowe
				li.addContextMenuItems(cm)
				u=common.sysaddon+"?mode=shindenpl&action=seria&url="+urllib.quote_plus(link)
				xbmcplugin.addDirectoryItem(handle=common.addon_handle,url=u,listitem=li,isFolder=True) 
		except:
			common.log("brak dodatkowych informacji")
			common.info("Problem z pobraniem dodatkowych linków","BŁĄD", time=5000)
		try:
			m=re.compile('<ul class=\"media-list box-scrollable\">(.*)<\/ul>',re.DOTALL).findall(l.text.encode('utf-8'))[0]
			m=re.compile('<li class=\"media media-item\">.*?<img class=\"img media-title-cover\" src=\"(.*?)\".*?<a href=\"(.*?)\">(.*?)</a>.*?<\/li>',re.DOTALL).findall(m)
			for r in range(len(m)):
				title=m[r][2]
				link=m[r][1]+'/all-episodes'
				img=m[r][0].replace("/100x100/","/genuine/")
				li=xbmcgui.ListItem(title,thumbnailImage=MURL+img)
				li.setInfo( type="video", infoLabels = {} )
				li.setProperty('IsPlayable', 'true')
				li.setProperty('fanart_image', MURL+img )
				cm=[]
				cm.append(('Wyświetl opis', 'RunPlugin(%s?mode=shindenpl&action=opis&url=%s)' % (common.sysaddon,urllib.quote_plus(link))))
				## dodaje menu kontekstowe
				li.addContextMenuItems(cm)
				u=common.sysaddon+"?mode=shindenpl&action=seria&url="+urllib.quote_plus(link)
				xbmcplugin.addDirectoryItem(handle=common.addon_handle,url=u,listitem=li,isFolder=True)
		except:
			common.log("brak dodatkowych informacji")
			common.info("Problem z pobraniem dodatkowych linków","BŁĄD", time=5000)       
	xbmcplugin.setContent(common.addon_handle, 'tvshows')
	xbmcplugin.endOfDirectory(common.addon_handle)
Beispiel #39
0
 def savePrograms(self):
     url = common.addon.getSetting('db')
     if url == '': return
     # 番組情報をDBへ送信
     programs = []
     for p in self.programs:
         if p['id'].find('radiru_') == 0: programs.append(p)
         if p['id'].find('radiko_') == 0: programs.append(p)
     data = {}
     data['programs'] = json.dumps(programs)
     response = urllib2.urlopen(url, urllib.urlencode(data))
     status = response.getcode()
     if status == 200:
         status1 = response.read()
         response.close()
         log('db status: ', status1)
     else:
         log('http error: ', status)
Beispiel #40
0
def refresh():
    global Resumes
    # カレントウィンドウをチェック
    immediate = False
    if xbmcgui.getCurrentWindowDialogId() == 9999:
        path = xbmc.getInfoLabel('Container.FolderPath')
        if path == sys.argv[0] and common.addon.getSetting('download') == 'false':
            immediate = True
        elif path == '%s?action=showPrograms' % sys.argv[0]:
            immediate = True

    # 画面を更新
    if immediate:
        xbmc.executebuiltin('Container.Update(%s?action=showPrograms,replace)' % (sys.argv[0]))
        Resumes['update'] = False
        log('update immediately')
    else:
        Resumes['update'] = True
        log('update scheduled')
    return immediate
Beispiel #41
0
 def onWatched(self):
     now = datetime.datetime.now()
     for m in self.matched_programs:
         # 開始直前であれば保存処理を開始
         wait = m['start'] - now
         if wait.days == 0 and wait.seconds < common.prep_interval:
             p = m['program']
             status = Downloads().add(
                 id=p['id'],
                 name=p['name'],
                 start=p['ft'],
                 end=p['to'],
                 title=p['title'],
                 description=p['description'],
                 source=p['source'],
                 lag=p['lag'],
                 key=m['key'])
             if status:
                 pass
             else:
                 log('start=',strptime(p['ft'],'%Y%m%d%H%M%S'),' name=',p['name'],' title=',p['title'])
    def _get_iptc(self, fullpath):

        try:
            info = IPTCInfo(fullpath)
        except Exception,msg:
            if not type(msg.args[0])==type(int()):
                if msg.args[0].startswith("No IPTC data found."):
                    return {}
                else:
                    common.log("VFSScanner._get_iptc", "%s"%fullpath )
                    common.log("VFSScanner._get_iptc", "%s - %s"%(Exception,msg) )
                    return {}
            else:
                common.log("VFSScanner._get_iptc", "%s"%fullpath )
                common.log("VFSScanner._get_iptc", "%s - %s"%(Exception,msg) )
                return {}
    def __init__(self):

        self.exclude_folders    = []
        self.all_extensions     = []
        self.picture_extensions = []
        self.video_extensions   = []
        self.lists_separator = "||"
        
        self.scan_is_cancelled = False
        
        self.picsdeleted = 0
        self.picsupdated = 0
        self.picsadded   = 0
        self.picsscanned = 0
        self.current_root_entry = 0
        self.total_root_entries = 0
        self.totalfiles  = 0
        self.mpdb = MypicsDB.MyPictureDB()
         
        for path,_,_,exclude in self.mpdb.get_all_root_folders():
            if exclude:
                common.log("", 'Exclude path "%s" found '%common.smart_unicode(path[:len(path)-1]))
                self.exclude_folders.append(common.smart_unicode(path[:len(path)-1]))

        for ext in common.getaddon_setting("picsext").split("|"):
            self.picture_extensions.append("." + ext.replace(".","").upper())

        for ext in common.getaddon_setting("vidsext").split("|"):
            self.video_extensions.append("." + ext.replace(".","").upper())

        self.use_videos = common.getaddon_setting("usevids")

        self.all_extensions.extend(self.picture_extensions)
        self.all_extensions.extend(self.video_extensions)

        self.filescanner = Scanner()
import sys
import xbmc
import xbmcgui
import xbmcvfs
import xbmcplugin
import xbmcaddon

settings = xbmcaddon.Addon()
language = settings.getLocalizedString
plugin = settings.getAddonInfo('id')

if __name__ == '__main__':
    import resources.lib.common as common
    common.log('ARGV: ' + repr(sys.argv), common.INFO)

    try:
        import StorageServer
        cache = StorageServer.StorageServer(common.plugin,
            int(settings.getSetting('cache_time')))
    except ImportError:
        common.log("Common Plugin Cache isn't installed, using dummy class.")
        import storageserverdummy
        cache = storageserverdummy.StorageServer(common.plugin)

    from resources.lib.api import Api
    api = Api()

    import resources.lib.nav as nav
    nav.list_menu()
Beispiel #45
0
        u = build_url({'mode': 'play_artists'})
        cm.insert(0, ('Play Local Artists', 'XBMC.RunPlugin(%s)' % u) )
    if cm:
        item.addContextMenuItems( cm )
    xbmcplugin.addDirectoryItem(pluginhandle,url=url,listitem=item,isFolder=True)

def ignore_video():
    id = args['id'][0]
    site = args['site'][0]
    data = {'site':site, 'id':id}
    common.ignore_list('add',data)

def remove_artist():
    artist = args['artist'][0]
    common.artist_list('delete',artist)

def remove_tag():
    tag = args['tag'][0]
    common.tag_list('delete',tag)

def build_url(query):
    return sys.argv[0] + '?' + urllib.urlencode(query)
    
args = urlparse.parse_qs(sys.argv[2][1:])
mode = args.get('mode', None)
common.log('Arguments: '+str(args))

if mode==None:
    root()
else:
    exec '%s()' % mode[0]
Beispiel #46
0
# -*- coding: utf-8 -*-
import os
import sys
import xbmc
import xbmcaddon

addon = xbmcaddon.Addon()

if __name__ == '__main__':
    import resources.lib.common as common
    common.log('ARGV: ' + repr(sys.argv), common.DEBUG)

    cookie_file = os.path.join(
        xbmc.translatePath(addon.getAddonInfo('profile')), 'fun-cookie.txt')

    from resources import Funimation
    api = Funimation(addon.getSetting('username'),
                     addon.getSetting('password'),
                     cookie_file)

    import resources.lib.nav as nav
    nav.list_menu()
            try:
                common.log( "VFSScanner._get_metas()._get_iptc()", 'Reading IPTC tags from "%s"'%fullpath)
                iptc = self._get_iptc(fullpath)
                picentry.update(iptc)
                common.log( "VFSScanner._get_metas()._get_iptc()", "Finished reading IPTC tags")
            except Exception,msg:
                common.log( "VFSScanner._get_metas()_get_iptc()", "Exception", xbmc.LOGERROR)
                common.log( "VFSScanner._get_metas()._get_iptc()", msg, xbmc.LOGERROR)



            ###############################
            #    getting  XMP infos       #
            ###############################
            try:
                common.log( "VFSScanner._get_metas()._get_xmp()", 'Reading XMP tags from "%s"'%fullpath)
                xmp = self._get_xmp(fullpath)
                picentry.update(xmp)
                common.log( "VFSScanner._get_metas()._get_xmp()", "Finished reading XMP tags")
            except Exception,msg:
                common.log( "VFSScanner._get_metas()._get_xmp()", "Exception", xbmc.LOGERROR)
                common.log( "VFSScanner._get_metas()._get_xmp()", msg, xbmc.LOGERROR)



        return picentry


    def _get_exif(self, picfile):

        EXIF_fields =[
Beispiel #48
0
def findGames():
    # Addon paths creation
    if not os.path.exists(DEFAULT_THUMB_PATH): os.makedirs(DEFAULT_THUMB_PATH)
    if not os.path.exists(DEFAULT_FANART_PATH): os.makedirs(DEFAULT_FANART_PATH)

    xbmc.executebuiltin("Dialog.Close(busydialog)")
    steamPath = getSteamPath()
    steamAppPath = os.path.join(os.path.abspath(steamPath),'steamapps')

    games = {}

    files = glob('{0}/*.acf'.format(steamAppPath))
    numFiles = len(files)
    counter = 0

    pDialog = xbmcgui.DialogProgress()
    pDialog.create(__addonname__, localize(33003))
    pDialog.update(0, localize(33003))

    orgGames = getGames()

    for filePath in glob('{0}/*.acf'.format(steamAppPath)):
        log('findGames()::filepath -> %s' % filePath)
        try:
            gameDict = parse_acf(filePath)
            if (gameDict['appstate']['bytestodownload'] != '0' and gameDict['appstate']['bytestodownload'] == gameDict['appstate']['bytesdownloaded']):

                orgGame = None

                for game in orgGames:
                    if (game.gameId == gameDict['appstate']['appid']):
                        orgGame = game
                        break;

                name = gameDict['appstate']['name']
                path = ''
                isNameChanged = 0
                isPathChanged = 0
                isIconChanged = 0
                isFanartChanged = 0
                thumbImage = ''
                fanartImage = ''
                type = 1

                if ((not orgGame) or (orgGame is not None and orgGame.isFanartChanged == 0 and orgGame.isIconChanged == 0)):
                    gameFiles = downloadGameImage(gameDict['appstate']['appid'],gameDict['appstate']['name'])
                    thumbImage = gameFiles[0]
                    fanartImage = gameFiles[1]
                elif (orgGame is not None and orgGame.isFanartChanged == 0):
                    gameFiles = downloadGameImage(gameDict['appstate']['appid'],gameDict['appstate']['name'])
                    thumbImage = orgGame.thumbImage
                    fanartImage = gameFiles[1]
                    isIconChanged = 1
                elif (orgGame is not None and orgGame.isIconChanged == 0):
                    gameFiles = downloadGameImage(gameDict['appstate']['appid'],gameDict['appstate']['name'])
                    thumbImage = gameFiles[0]
                    fanartImage = orgGame.fanartImage
                    isFanartChanged = 1
                else:
                    thumbImage = orgGame.thumbImage
                    fanartImage = orgGame.fanartImage
                    isIconChanged = 1
                    isFanartChanged = 1

                if (orgGame is not None and orgGame.isNameChanged == 1):
                    name = orgGame.title
                    isNameChanged = 1

                if (orgGame is not None and orgGame.isPathChanged == 1):
                    name = orgGame.path
                    isPathChanged = 1

                games[gameDict['appstate']['appid']] = {}
                games[gameDict['appstate']['appid']]['name'] = name
                games[gameDict['appstate']['appid']]['path'] = path
                games[gameDict['appstate']['appid']]['isNameChanged'] = isNameChanged
                games[gameDict['appstate']['appid']]['isPathChanged'] = isPathChanged
                games[gameDict['appstate']['appid']]['isIconChanged'] = isIconChanged
                games[gameDict['appstate']['appid']]['isFanartChanged'] = isFanartChanged
                games[gameDict['appstate']['appid']]['type'] = type
                games[gameDict['appstate']['appid']]['thumbImage'] = thumbImage
                games[gameDict['appstate']['appid']]['fanartImage'] = fanartImage

                counter = counter + 1
        except:
            log('unable to parse the file %s' % filePath)

        if (pDialog.iscanceled()):
            break;

        pDialog.update(int((float(counter)/float(numFiles))*100), localize(33003))

    #games = sorted(games.iteritems(), key= operator.itemgetter(1))

    gamesDbObj = open(GAMES_DB_PATH, 'w')
    log(json.dumps(games))
    gamesDbObj.write(json.dumps(games))
    gamesDbObj.close()
    pDialog.close()
    dialog = xbmcgui.Dialog()
    ok = dialog.ok(__addonname__, str(counter) + ' ' + localize(33004))
    def _addpath(self, path, parentfolderid, recursive, update):

        """
        try:
        """
        path = common.smart_unicode(path)

        common.log("VFSScanner._addpath", '"%s"'%common.smart_utf8(path) )
        # Check excluded paths
        if path in self.exclude_folders:
            common.log("VFSScanner._addpath", 'Path in exclude folder: "%s"'%common.smart_utf8(path) )
            self.picsdeleted = self.picsdeleted + self.mpdb.delete_paths_from_root(path)
            return

        (dirnames, filenames) = self.filescanner.walk(path, False, self.picture_extensions if self.use_videos == "false" else self.all_extensions)

        # insert the new path into database
        foldername = common.smart_unicode(os.path.basename(path))
        if len(foldername)==0:
            foldername = os.path.split(os.path.dirname(path))[1]
        
        folderid = self.mpdb.folder_insert(foldername, path, parentfolderid, 1 if len(filenames)>0 else 0 )
        
        # get currently stored files for 'path' from database.
        # needed for 'added', 'updated' or 'deleted' decision
        filesfromdb = self.mpdb.listdir(common.smart_unicode(path))

        # scan pictures and insert them into database
        if filenames:
            for pic in filenames:
                if self.scan.iscanceled():
                    self.scan_is_cancelled = True
                    common.log( "VFSScanner._addpath", "Scanning canncelled", xbmc.LOGNOTICE)
                    return
                    
                if self._check_excluded_files(pic) == False:
                    continue
                
                self.picsscanned += 1
                
                filename = os.path.basename(pic)
                extension = os.path.splitext(pic)[1].upper()
                    
                picentry = { "idFolder": folderid,
                             "strPath": path,
                             "strFilename": filename,
                             "ftype": extension in self.picture_extensions and "picture" or extension in self.video_extensions and "video" or "",
                             "DateAdded": strftime("%Y-%m-%d %H:%M:%S"),
                             "Thumb": "",
                             "Image Rating": "0"
                             }


                sqlupdate = False
                filesha   = 0
                
                # get the meta tags. but only for pictures and only if they are new or modified.
                if extension in self.picture_extensions:
                    
                    common.log( "VFSScanner._addpath", 'Scanning picture "%s"'%common.smart_utf8(pic))
                    
                    
                    if pic in filesfromdb: # then it's an update
                        
                        filesfromdb.pop(filesfromdb.index(pic))
                        
                        if self.options.refresh == True: # this means that we only want to get new pictures.
                                if self.scan and self.totalfiles!=0 and self.total_root_entries!=0:
                                    self.scan.update(int(100*float(self.picsscanned)/float(self.totalfiles)),
                                                  int(100*float(self.current_root_entry)/float(self.total_root_entries)),
                                                  common.smart_utf8(common.getstring(30000)+" [%s] (%0.2f%%)"%(self.action,100*float(self.picsscanned)/float(self.totalfiles))),#"MyPicture Database [%s] (%0.2f%%)"
                                                  common.smart_utf8(filename))
                                continue                            
                        else: 
                            (localfile, isremote) = self.filescanner.getlocalfile(pic)
                            
                            filesha = self.mpdb.sha_of_file(localfile) 
                            sqlupdate   = True
                            
                            if self.mpdb.stored_sha(path,filename) != filesha:  # picture was modified

                                self.picsupdated += 1
                                common.log( "VFSScanner._addpath", "Picture already exists and must be updated")
                                
                                tags = self._get_metas(common.smart_unicode(localfile))
                                picentry.update(tags)
            
                                # if isremote == True then the file was copied to cache directory.
                                if isremote:
                                    self.filescanner.delete(localfile)                            
    
                            else:

                                common.log( "VFSScanner._addpath", "Picture already exists but not modified")
    
                                if self.scan and self.totalfiles!=0 and self.total_root_entries!=0:
                                    self.scan.update(int(100*float(self.picsscanned)/float(self.totalfiles)),
                                                  int(100*float(self.current_root_entry)/float(self.total_root_entries)),
                                                  common.smart_utf8(common.getstring(30000)+" [%s] (%0.2f%%)"%(self.action,100*float(self.picsscanned)/float(self.totalfiles))),#"MyPicture Database [%s] (%0.2f%%)"
                                                  common.smart_utf8(filename))
    
                                if isremote:
                                    self.filescanner.delete(localfile)                            
    
                                continue

                    else: # it's a new picture

                        (localfile, isremote) = self.filescanner.getlocalfile(pic)
                        filesha = self.mpdb.sha_of_file(localfile)
                        sqlupdate  = False
                        common.log( "VFSScanner._addpath", "New picture will be inserted into dB")
                        self.picsadded   += 1

                        tags = self._get_metas(common.smart_unicode(localfile))
                        picentry.update(tags)

                        if isremote:
                            self.filescanner.delete(localfile)


                # videos aren't scanned and therefore never updated
                elif extension in self.video_extensions:
                    common.log( "VFSScanner._addpath", 'Adding video file "%s"'%common.smart_utf8(pic))
                    
                    if pic in filesfromdb:  # then it's an update
                        sqlupdate   = True
                        filesfromdb.pop(filesfromdb.index(pic))
                        continue

                    else:
                        sqlupdate  = False
                        self.picsadded   += 1
                        picentry["Image Rating"] = 5
                        moddate = self.filescanner.getfiledatetime(pic)
                        if moddate != "0000-00-00 00:00:00":
                            picentry["EXIF DateTimeOriginal"] = moddate

                else:
                    continue

                try:

                    self.mpdb.file_insert(path, filename, picentry, sqlupdate, filesha)
                except Exception, msg:
                    common.log("VFSScanner._addpath", 'Unable to insert picture "%s"'%pic, xbmc.LOGERROR)
                    common.log("VFSScanner._addpath", '"%s" - "%s"'%(Exception, msg), xbmc.LOGERROR)
                    continue

                if sqlupdate:
                    common.log( "VFSScanner._addpath", 'Picture "%s" updated'%common.smart_utf8(pic))
                else:
                    common.log( "VFSScanner._addpath", 'Picture "%s" inserted'%common.smart_utf8(pic))

                if self.scan and self.totalfiles!=0 and self.total_root_entries!=0:
                    self.scan.update(int(100*float(self.picsscanned)/float(self.totalfiles)),
                                  int(100*float(self.current_root_entry)/float(self.total_root_entries)),
                                  common.smart_utf8(common.getstring(30000)+" [%s] (%0.2f%%)"%(self.action,100*float(self.picsscanned)/float(self.totalfiles))),#"MyPicture Database [%s] (%0.2f%%)"
                                  common.smart_utf8(filename))
    def _get_metas(self, fullpath):
        picentry = {}
        extension = os.path.splitext(fullpath)[1].upper()
        if extension in self.picture_extensions:
            ###############################
            #    getting  EXIF  infos     #
            ###############################
            try:
                common.log( "VFSScanner._get_metas()._get_exif()", 'Reading EXIF tags from "%s"'%fullpath)
                exif = self._get_exif(fullpath)
                picentry.update(exif)
                common.log( "VFSScanner._get_metas()._get_exif()", "Finished reading EXIF tags")
            except Exception,msg:
                common.log( "VFSScanner._get_metas()._get_exif()", "Exception", xbmc.LOGERROR)
                common.log( "VFSScanner._get_metas()._get_exif()", msg, xbmc.LOGERROR)


            ###############################
            #    getting  IPTC  infos     #
            ###############################
            try:
                common.log( "VFSScanner._get_metas()._get_iptc()", 'Reading IPTC tags from "%s"'%fullpath)
                iptc = self._get_iptc(fullpath)
                picentry.update(iptc)
                common.log( "VFSScanner._get_metas()._get_iptc()", "Finished reading IPTC tags")
            except Exception,msg:
                common.log( "VFSScanner._get_metas()_get_iptc()", "Exception", xbmc.LOGERROR)
                common.log( "VFSScanner._get_metas()._get_iptc()", msg, xbmc.LOGERROR)
            try:
                common.log( "VFSScanner._get_metas()._get_iptc()", 'Reading IPTC tags from "%s"'%fullpath)
                iptc = self._get_iptc(fullpath)
                picentry.update(iptc)
                common.log( "VFSScanner._get_metas()._get_iptc()", "Finished reading IPTC tags")
            except Exception,msg:
                common.log( "VFSScanner._get_metas()_get_iptc()", "Exception", xbmc.LOGERROR)
                common.log( "VFSScanner._get_metas()._get_iptc()", msg, xbmc.LOGERROR)



            ###############################
            #    getting  XMP infos       #
            ###############################
            try:
                common.log( "VFSScanner._get_metas()._get_xmp()", 'Reading XMP tags from "%s"'%fullpath)
                xmp = self._get_xmp(fullpath)
                picentry.update(xmp)
                common.log( "VFSScanner._get_metas()._get_xmp()", "Finished reading XMP tags")
            except Exception,msg:
                common.log( "VFSScanner._get_metas()._get_xmp()", "Exception", xbmc.LOGERROR)
                common.log( "VFSScanner._get_metas()._get_xmp()", msg, xbmc.LOGERROR)

            if picentry['Image Rating'] is None or picentry['Image Rating'] == '' or picentry['Image Rating'] < '1':
                if 'xmp:Rating' in picentry and ( picentry['xmp:Rating'] is not None or picentry['xmp:Rating'] != ''):
                    picentry['Image Rating'] = picentry['xmp:Rating']
                elif 'xap:Rating' in picentry and ( picentry['xap:Rating'] is not None or picentry['xap:Rating'] != ''):
                    picentry['Image Rating'] = picentry['xap:Rating']
                elif 'Image RatingPercent' in picentry and ( picentry['Image RatingPercent'] is not None or picentry['Image RatingPercent'] != ''):
                    a = int( picentry['Image RatingPercent'])
                    if a >= 95:
    def _get_exif(self, picfile):

        EXIF_fields =[
                    "Image Model",
                    "Image Orientation",
                    "Image Rating",
                    "Image RatingPercent",
					"Image Artist",
                    "GPS GPSLatitude",
                    "GPS GPSLatitudeRef",
                    "GPS GPSLongitude",
                    "GPS GPSLongitudeRef",
                    "Image DateTime",
                    "EXIF DateTimeOriginal",
                    "EXIF DateTimeDigitized",
                    "EXIF ExifImageWidth",
                    "EXIF ExifImageLength",
                    "EXIF Flash",
                    "Image ResolutionUnit",
                    "Image XResolution",
                    "Image YResolution",
                    "Image Make",
                    "EXIF FileSource",
                    "EXIF SceneCaptureType",
                    "EXIF DigitalZoomRatio",
                    "EXIF ExifVersion"
                      ]

        # try to open picfile in modify/write mode. Windows needs this for memory mapped file support.
        try:
            # General for all OS. Use unicode for picfile.
            # This fails with OpenElec or if modify/write attribute isn't set.
            f=open(picfile,"r+b")
            common.log( "VFSScanner._get_exif()", 'File opened with statement: %s'%'f=open(picfile,"r+b")')
        except:
            try:
                # Special for OpenElec. Use utf-8 for picfile.
                # If modify/write attribute isn't set then it'll fail.
                f=open(picfile.encode("utf-8"),"r+b")
                common.log( "VFSScanner._get_exif()", 'File opened with statement: %s'%'f=open(picfile.encode("utf-8"),"r+b")')
            except:
                # Where're here because write/modify attribute is missing and file could not be opened.
                try:
                    # General for all OS. Use unicode for picfile.
                    f=open(picfile,"rb")
                    common.log( "VFSScanner._get_exif()", 'File opened with statement: %s'%'f=open(picfile,"rb")')
                except:
                    # Special for OpenElec. Use utf-8 for picfile.
                    f=open(picfile.encode('utf-8'),"rb")
                    common.log( "VFSScanner._get_exif()", 'File opened with statement: %s'%'f=open(picfile.encode("utf-8"),"rb")')
        common.log( "VFSScanner._get_exif()", 'Calling function EXIF_file for "%s"'%picfile)

        mmapfile = 0
        try:
            # If write/modify attribute isn't set then this will fail on Windows because above the file was opened read only!
            mmapfile = mmap.mmap(f.fileno(), 0)
            tags = EXIF_file(mmapfile, details=False)
            common.log( "VFSScanner._get_exif()", 'EXIF_file with mmap support returned')
        except:
            try:
                # We've to open the file without memory mapped file support.
                tags = EXIF_file(f, details=False)
                common.log( "VFSScanner._get_exif()", 'EXIF_file without mmap support returned')
            except Exception,msg:
                common.log("VFSScanner._get_exif", picfile , xbmc.LOGERROR)
                common.log("VFSScanner._get_exif", "%s - %s"%(Exception,msg), xbmc.LOGERROR )
Beispiel #53
0
 def onScreensaverDeactivated(self):
     log('screensaver deactivated')
Beispiel #54
0
def downloadGameImage(gameId, gameName):
    log('Downloading Steam game images for {0} -> {1}'.format(gameId, gameName))
    
    files = []

    valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
    safeGameName = ''.join(c for c in gameName if c in valid_chars)

    thumbFilePath = os.path.join(DEFAULT_THUMB_PATH,'thumb_{0}_{1}.jpg'.format(safeGameName, int((time.mktime(datetime.datetime.now().timetuple())))))
    fanartPath = os.path.join(DEFAULT_FANART_PATH,'fanart_{0}_{1}.jpg'.format(safeGameName, int((time.mktime(datetime.datetime.now().timetuple())))))

    isFanartFound = False
    isThumbImageFound = False

    for fileName in glob(os.path.join(DEFAULT_THUMB_PATH,'thumb_{0}*.*'.format(safeGameName))):
        thumbFilePath = fileName
        isThumbImageFound = True

    for fileName in glob(os.path.join(DEFAULT_FANART_PATH,'fanart_{0}*.*'.format(safeGameName))):
        fanartPath = fileName
        isFanartFound = True

    try:
        if (not isFanartFound):
            gameUrlQuery = {'exactname':gameName.encode('utf8')}

            requestURL = 'http://thegamesdb.net/api/GetGame.php?' + urllib.urlencode(gameUrlQuery)
    
            opener = urllib2.build_opener()
            opener.addheaders = [('User-agent', 'Mozilla/5.0')]

            xmlResponse = opener.open(requestURL, timeout=30)

            strXml = xmlResponse.read()

            root = ET.fromstring(strXml)
            baseImgUrl = root[0].text
            fanartNodes = root.findall('.//Game/Images/fanart/original')
            fanartImg = fanartNodes[0].text

            downloadFile(baseImgUrl + fanartImg, fanartPath)
            isFanartFound = True
    except:
        pass

    try:
        if (not isThumbImageFound or not isFanartFound):
            response = urllib.urlopen('http://store.steampowered.com/api/appdetails?appids={0}'.format(gameId))
            gameJason = json.loads(response.read())
            response.close()

            if(not isThumbImageFound):
                downloadFile(gameJason[gameId]['data']['header_image'], thumbFilePath)
                isThumbImageFound = True

            if(not isFanartFound):
                downloadFile(gameJason[gameId]['data']['screenshots'][0]['path_full'], fanartPath)
                isFanartFound = True    
    except:
        pass    

    if(not isThumbImageFound):
        thumbFilePath = os.path.join(__addonpath__,'resources','skins','Default','media','alienware','steam.png')
    if(not isFanartFound):
        fanartPath = os.path.join(__addonpath__,'resources','skins','Default','media','alienware','fanart_steam.png')

    files.append(thumbFilePath)
    files.append(fanartPath)
    
    return files
Beispiel #55
0
 def onChanged(self):
     self.matched_programs = []
     for p in self.programs:
         # 開始時間、終了時間が規定されている番組について
         if p['ft'] and p['to']:
             # キーワードをチェック
             search = Keywords().search
             for s in search:
                 # キーワードを照合
                 if s['key']:
                     if p['title'].find(s['key']) > -1:
                         pass
                     elif s['s'] == '1' and p['description'].find(s['key']) > -1:
                         pass
                     else:
                         continue
                 else:
                     continue
                 # 曜日を照合
                 if s['day'] == '0':
                     pass
                 elif int(strptime(p['ft'],'%Y%m%d%H%M%S').strftime('%w')) == int(s['day'])-1:
                     pass
                 else:
                     continue
                 # 放送局を照合
                 if s['ch'] == common.addon.getLocalizedString(30520):
                     # 放送局を指定しない場合、radikoのNHKは重複するのでスキップ
                     if p['id'].find('radiko') == 0 and p['name'].find('NHK') == 0:
                         continue
                     else:
                         pass
                 elif s['ch'] == p['name']:
                     pass
                 else:
                     continue
                 # 保存済み番組名と照合
                 if s['duplicate'] == '1':
                     skip = False
                     for file in glob.glob(os.path.join(common.download_path, '*.js')):
                         js_file = os.path.join(common.download_path, file)
                         mp3_file = os.path.join(common.download_path, file.replace('.js','.mp3'))
                         if os.path.isfile(mp3_file):
                             f = codecs.open(js_file,'r','utf-8')
                             program = json.loads(f.read())['program'][0]
                             f.close()
                             if p['name'] == program['bc']:
                                 if s['s'] == '0' and p['title'] == program['title']:
                                     # 番組名が一致する
                                     skip = True
                                     break
                                 if s['s'] == '1' and p['title'] == program['title'] and p['description'] == program['description']:
                                     # 番組名と詳細情報が一致する
                                     skip = True
                                     break
                     if skip: continue
                 # とりあえず追加
                 start = strptime(p['ft'],'%Y%m%d%H%M%S')
                 self.matched_programs.append({'program':p, 'start':start, 'key':s['key']})
                 log('start=',start,' name=',p['name'],' title=',p['title'])
                 break
     # DBに番組情報を送信
     self.savePrograms()
Beispiel #56
0
                if (games):
                    for game in games:
                        if (game.gameId == args['gameid'][0]):
                            addToFavorite(game)
                            break;
            elif (menuActionName == 'removefromfavorites'):
                if (games):
                    for game in games:
                        if (game.gameId == args['gameid'][0]):
                            removeFromFavorite(game)
                            break;
            elif (menuActionName == 'edittitle'):
                if (games):
                    for game in games:
                        if (game.gameId == args['gameid'][0]):
                            log(game.title)
                            log(game.path)
                            log(game.type)
                            dialog = xbmcgui.Dialog()
                            d = dialog.input(localize(33005), game.title, type=xbmcgui.INPUT_ALPHANUM)

                            if (d):
                                updateGameInformation(game, 'title', d)
                                break;
            elif (menuActionName == 'editicon'):
                if (games):
                    for game in games:
                        if (game.gameId == args['gameid'][0]):
                            dialog = xbmcgui.Dialog()
                            d = dialog.browse(2, localize(33007), 'files', '.jpg|.png', True, False, game.thumbImage)