コード例 #1
0
	def _insertFakeSerie (self, forSerie):
		printl("_insertFake", self)
		fake = MediaInfo()
		fake.MediaType = MediaInfo.SERIE
		fake.TheTvDbId = forSerie
		fake.Title = "AutoInserted for serie: "+ str(forSerie)
		return self.insertMedia(fake)
コード例 #2
0
ファイル: Manager.py プロジェクト: steve4744/project-valerie
    def searchAlternatives(self, oldElement, searchstring=None):
        element = MediaInfo(oldElement.Path, oldElement.Filename,
                            oldElement.Extension)
        if type(oldElement) is MediaInfo:
            element.isMovie = oldElement.isMovie
            element.isSerie = oldElement.isSerie

        if searchstring is not None:
            element.SearchString = searchstring

        element.parse()

        printl("SEARCH=" + str(element.SearchString), self)
        return MobileImdbComProvider().getAlternatives(element)
コード例 #3
0
ファイル: Manager.py プロジェクト: Rikitik/project-valerie
    def searchAlternatives(self, oldElement, searchstring=None):
        element = MediaInfo(oldElement.Path, oldElement.Filename, oldElement.Extension)
        if type(oldElement) is MediaInfo:
            element.isMovie = oldElement.isMovie
            element.isSerie = oldElement.isSerie

        if searchstring is not None:
            element.SearchString = searchstring

        element.parse()

        printl("SEARCH=" + str(element.SearchString), self)
        return MobileImdbComProvider().getAlternatives(element)
コード例 #4
0
    def importDataToPickleV2(self, session):
        printl("->", self, "S")
        try:
            if session is not None:
                self.mm = session.open(
                    MessageBox,
                    (_("\nConverting data to V2.... \n\nPlease wait... ")),
                    MessageBox.TYPE_INFO)
                #self.mm = self.session.open(Msg)
            printl("Importing Data to PickleV2", self)
            # this will Open Pickle V1 and run upgrades if necessary
            userId = config.plugins.pvmc.seenuserid.value
            dbHandlerPickle = databaseHandlerPICKLE().getInstance(
                "from importDataToPickleV2", None)
            dbHandlerPickle.loadAll()
            #Upgrade SeenDB
            records = dbHandlerPickle.getSeenForUpgrade()

            self.dbHandler.loadAll()

            start_time = time.time()
            cntNew = 0

            printl(
                "Total Seen Movies to Convert: " + str(len(records["Movies"])),
                self)
            for imdb in records["Movies"]:
                if imdb == u"":
                    continue
                printl("getSeen for imdb: " + imdb, self)
                m = self.dbHandler.getMediaWithImdbId(imdb)
                if m is None:
                    #printl("IS NONE: "+imdb, self)
                    m = MediaInfo()
                    m.Id = None
                    m.ImdbId = imdb

                seen = records["Movies"][imdb]["Seen"]
                if seen:
                    self.dbHandler.MarkAsSeenWithMedia(m, userId)
                else:
                    pass
                    #self.dbHandler.MarkAsUnseenWithMedia(m,userId)

                cntNew += 1

            printl(
                "Total Seen Series(no episodes) to Convert: " +
                str(len(records["TV"])), self)
            for thetvdb in records["TV"]:
                if thetvdb == u"":
                    continue
                printl("getSeen for thetvdb: " + thetvdb, self)
                serie = self.dbHandler.getMediaWithTheTvDbId(thetvdb)
                for season in records["TV"][thetvdb]:
                    if serie is not None:
                        EpisodesFromSeason = self.dbHandler.getEpisodes(
                            serie.Id, season)
                    for episode in records["TV"][thetvdb][season]:
                        EpisodeInserted = False
                        seen = records["TV"][thetvdb][season][episode]["Seen"]
                        if serie is not None:
                            for ep in EpisodesFromSeason:
                                if episode == ep.Episode:
                                    EpisodeInserted = True
                                    if seen:
                                        self.dbHandler.MarkAsSeen(
                                            ep.Id, userId)
                                    else:
                                        pass
                                        #self.dbHandler.MarkAsUnseen(ep.Id,userId)
                        else:
                            #printl("NO SERIE: " + thetvdb, self)
                            pass

                        if not EpisodeInserted:
                            #printl("MANNUALLY: " + thetvdb, self)
                            m = MediaInfo(
                            )  # Fake Media, Avoid loosing Seen Data
                            m.Id = None
                            m.TheTvDbId = thetvdb
                            m.Season = season
                            m.Episode = episode
                            if seen:
                                #printl("SEEN 2: " + thetvdb, self)
                                self.dbHandler.MarkAsSeenWithMedia(m, userId)
                            else:
                                #printl("UNSEEN 2: " + thetvdb, self)
                                #self.dbHandler.MarkAsUnseenWithMedia(m,userId)
                                pass

                        cntNew += 1

# dbSeen["Movies"][primary_key["ImdbId"]]["Seen"] = primary_key["Seen"]
# dbSeen["TV"][primary_key["TheTvDbId"]][primary_key["Season"]][primary_key["Episode"]]["Seen"] = primary_key["Seen"]

            printl("Seen Count: " +
                   str(str(len(records["Movies"]) + len(records["TV"]))) +
                   " Processed: " + str(cntNew))

            #self.dbHandler.commit()
            elapsed_time = time.time() - start_time
            printl("Took: " + str(elapsed_time), self)
            try:
                if os.path.exists(self.DB_PATH + "seen.db"):
                    os.rename(self.DB_PATH + "seen.db",
                              self.DB_PATH + "seen.db" + ".old")
            except Exception, ex:
                printl(".Backup Seen failed! Ex: " + str(ex), __name__, "E")
        except Exception, ex:
            printl(
                ".Failed Import to PickleV2! Reloading Pickle V1. Ex: " +
                str(ex), __name__, "E")
            self.USE_DB_TYPE = self.DB_PICKLE
コード例 #5
0
ファイル: sync.py プロジェクト: OpenMipsel/project-valerie
	def run(self):
		
		self.doAbort = False
		
		self.output(_("Loading Config"))
		Blacklist.load()
		printl(str(len(Blacklist.get())) +" entrys")
			   
		self.output(_("Loading Data"))
		printl("Loading Data", self)

		db = Database().getInstance()
		
		if self.mode == self.UPDATE:
			from   Manager import Manager
			Manager().updateAll(self.output, self.progress, self.range)
			
			self.output(_("Saving database"))
			printl("Saving database", self)
			db.save()
			
			
			self.output(_("Done"))
			printl("Done", self)
			self.output("---------------------------------------------------")
			self.output(_("Press Exit / Back"))
			
			self.finished(True)
			return
		
		#temporarly - there are only failed, missing webif
		#db.deleteMediaFilesNotOk()
		
		if self.mode != self.FAST and SyncConfig().getInstance().get("delete") is True:
			db.deleteMissingFiles()
		
		if self.mode != self.FAST:
			db.transformGenres()
		
		printl("Entries: " + str(db), self)
		
		self.output(_("Loading Replacements"))
		printl("Loading Replacements", self)
		replace.load()
		
		posterSize = Arts.posterResolution[0]
		if self.dSize.width() == 720 and self.dSize.height() == 576:
			posterSize = Arts.posterResolution[0]
		elif self.dSize.width() == 1024 and self.dSize.height() == 576:
			posterSize = Arts.posterResolution[1]
		elif self.dSize.width() == 1280 and self.dSize.height() == 720:
			posterSize = Arts.posterResolution[2]
		
		self.output(_("Loading Filesystem"))
		printl("Loading Filesystem", self)
		ds = DirectoryScanner.DirectoryScanner()
		ds.clear()
		if self.mode == self.FAST:
			ds.load()
		
		pathsConfig = PathsConfig().getInstance()
		filetypes = pathsConfig.getFileTypes()
		self.output(_("Extensions:") + ' ' + str(filetypes))
		printl("Extensions: " + str(filetypes), self)
		
		self.output(_("Searching for media files"))
		printl("Searching for media files", self)
		start_time = time.time()
		
		folderList  = []
		elementList = [] 	# if there are no folder it will crash on » del elementlist	#Zuki
		elementListFileCounter = 0
		
		for searchpath in pathsConfig.getPaths(): 
			if searchpath["enabled"] is False:
				continue
			
			path = searchpath["directory"]
			folderType = searchpath["type"]
			useFolder = searchpath["usefolder"]

			if os.path.isdir(path) is False:
				continue
			
			ds.setDirectory(Utf8.utf8ToLatin(path))
			ds.listDirectory(filetypes, "(sample)|(VTS)|(^\\.)")
			filelist = ds.getFileList()
			elementListFileCounter += len(filelist)
			folderList.append((filelist, folderType, useFolder, ))
		
		elapsed_time = time.time() - start_time
		printl("Searching for media files took: " + str(elapsed_time), self)
		
		if elementListFileCounter == 0:
			self.output(_("Found") + ' ' + str(0) + ' ' + _("media files"))
			printl("Found 0 media files", self)
		else:
			self.output(_("Found") + ' ' + str(elementListFileCounter) + ' ' + _("media files"))
			printl("Found " + str(elementListFileCounter) + " media files", self)
			
			self.range(elementListFileCounter)
			
			i = 0
			for folder in folderList:
				#print "folder", folder
				elementList = folder[0]
				folderType  = folder[1]
				useFolder   = folder[2]
				
				if self.doAbort:
					break
				
				for element in elementList:
					i += 1
					self.progress(i)
					
					pathOrig	  = element[0].replace("\\", "/")
					filenameOrig  = element[1]
					extensionOrig = element[2]
					
					printl("*"*100, self, "I")
					printl("* Next file to sync: " + str(pathOrig) + "/" + str(filenameOrig) + "." + str(extensionOrig), self, "I")
					printl("*"*100, self, "I")
					
					path	  = Utf8.stringToUtf8(pathOrig)
					filename  = Utf8.stringToUtf8(filenameOrig)
					extension = Utf8.stringToUtf8(extensionOrig)
					
					if self.doAbort:
						break
					
					if path is None or filename is None or extension is None:
						printl("Path or filename or extension is None => skip!", self, "I")
						continue
					
					if "RECYCLE.BIN" in path or ".AppleDouble" in path:
						printl("Special directory => skip!", self, "I")
						continue
					
					if (filename + u"." + extension) in Blacklist.get():
						printl("File is blacklisted => skip!", self, "I")
						continue
					#printl("testing 1", self)
						
					printl("Checking for duplicates...", self, "I")
					retCheckDuplicate= db.checkDuplicate(path, filename, extension)

					mediaInDb = retCheckDuplicate["mediafile"]
					# if never sync with success delete db entry and resync
					if mediaInDb is not None and retCheckDuplicate["mediafile"].syncErrNo == MediaInfo.STATUS_INFONOTFOUND: # exist
						printl("Deleting and resync FailedItem", self)
						db.deleteMedia(retCheckDuplicate["mediafile"].Id)
						mediaInDb = None
						
					if mediaInDb is not None:
						printl("Media exists in database...", self, "I")
						if retCheckDuplicate["reason"] == 1: # exist
							m2 = retCheckDuplicate["mediafile"]
							if m2.syncErrNo == 0 and m2.MediaStatus != MediaInfo.STATUS_OK:
								#printl("Sync - Duplicate Found :" + str(m2.Path) + "/" + str(m2.Filename) + "." + str(m2.Extension), self)	
								key_value_dict = {}
								key_value_dict["Id"] = m2.Id
								key_value_dict["MediaStatus"]  = MediaInfo.STATUS_OK
								#key_value_dict["syncErrNo"]	= 0
								key_value_dict["syncFailedCause"] = u""
								printl("Sync - Update Media 1", self)	
								if not db.updateMediaWithDict(key_value_dict):
									printl("Sync - Update Media 1 - Failed", self)	
						
						elif retCheckDuplicate["reason"] == 2: # exist on other path, change record path
							m2 = retCheckDuplicate["mediafile"]
							if m2.syncErrNo == 0:
								printl("Sync - Duplicate Found on other path:" + str(m2.Path) + "/" + str(m2.Filename) + "." + str(m2.Extension), self)
								key_value_dict = {}
								key_value_dict["Id"] = m2.Id
								key_value_dict["Path"] = path
								key_value_dict["MediaStatus"]  = MediaInfo.STATUS_OK
								#key_value_dict["syncErrNo"]	= 0
								key_value_dict["syncFailedCause"] = u""
								printl("Sync - Update Media 2", self)	
								if not db.updateMediaWithDict(key_value_dict):
									printl("Sync - Update Media 2 - Failed", self)	
					
							
						# take lots of time to write on screen, we have the progressbar
						#self.output("Already in db [ " + Utf8.utf8ToLatin(filename) + " ]")
						
						#printl("testing 2", self)
						if Arts().isMissing(mediaInDb):
							printl("=> Arts missing in Db!...", self, "I")
							#self.output("Downloading missing poster")
							tmp = None
							if mediaInDb.isTypeMovie():
								tmp = TheMovieDbProvider().getArtByImdbId(mediaInDb)
							elif mediaInDb.isTypeEpisode():
								tvshow = db.getMediaWithTheTvDbId(mediaInDb.TheTvDbId)
								#printl(str(tvshow.SeasonPoster), self, "E")
								tvshow.SeasonPoster.clear() # Make sure that there are no residues
								tmp = TheTvDbProvider().getArtByTheTvDbId(tvshow)
								if tmp is not None:
									printl(str(tmp.SeasonPoster), self, "E")
							
							if tmp is not None:
								Arts().download(tmp)
								
								if mediaInDb.isTypeMovie():
									self.info(str(mediaInDb.ImdbId) + "_poster_" + posterSize + ".png", 
										"", "")
								elif mediaInDb.isTypeSerie() or mediaInDb.isTypeEpisode():
									self.info(str(mediaInDb.TheTvDbId) + "_poster_" + posterSize + ".png", 
										"", "")
								del tmp
						
						del mediaInDb
						continue
					
					outStr = "(" + str(i) + "/" + str(elementListFileCounter)  + ")"
					
					self.output(outStr + " -> " + getStringShrinked(pathOrig) + " >> " + filenameOrig + "." + extensionOrig)
					printl("#"*30, self)
					printl("(" + str(i) + "/" + str(elementListFileCounter)  + ")", self)
					printl("#"*6, self)
					printl("  -> " + pathOrig + "\n	" + filenameOrig + "." + extensionOrig, self)
					
					elementInfo = MediaInfo(path, filename, extension)
					
					printl("FOLDERTYPE: " + str(folderType), self)
					printl("USEFOLDER: " + str(useFolder), self)
					
					if folderType == u"MOVIE":
						elementInfo.setMediaType(MediaInfo.MOVIE)
					elif folderType == u"TV":
						elementInfo.setMediaType(MediaInfo.SERIE)
					else:
						elementInfo.setMediaType(MediaInfo.UNKNOWN)
					
					result = elementInfo.parse(useFolder)
						
					if result == False:
						continue
					
					printl("TheTvDbId: " + elementInfo.TheTvDbId, self, "I")
					
					if elementInfo.isXbmcNfo == False:	
						printl("isXbmcNfo == False => checking for E2 recorded TV show... ", self, "I")
						if elementInfo.isTypeSerie() and elementInfo.isEnigma2MetaRecording:
							if elementInfo.Season == None or elementInfo.Episode == None:
								printl("E2-recorded TV-Show => trying to get season and episode from E2 episodename... ", self, "I")
								tmp = GoogleProvider().getSeasonAndEpisodeFromEpisodeName(elementInfo)
								if (tmp[0] is True) and (tmp[1] is None):
									#Issue #474 => Don't fall back if foldertype is not explicitely "MOVIE_AND_TV"
									if folderType == u"MOVIE_AND_TV":
										printl("E2-recording not recognized as TV show => trying to parse as movie... ", self, "I")
										elementInfo.setMediaType(MediaInfo.MOVIE)
									else:
										elementInfo.MediaType = MediaInfo.UNKNOWN # avoid create serie
										elementInfo.MediaStatus = MediaInfo.STATUS_INFONOTFOUND
										elementInfo.syncErrNo   = 3
										elementInfo.syncFailedCause = u"Info Not Found"# cause
										printl("Failed to detect TV show and folder type set to 'TV' => adding media as failed...", self, "I")
										db.insertMedia(elementInfo)
										continue
								elif tmp[0] is True:
									# Issue #205, efo => use tmp[1] instead of tmp...
									elementInfo = tmp[1]
									printl("Result from google => Season=" + str(elementInfo.Season) + " / Episode=" + str(elementInfo.Episode), self, "I")
							else:
								printl("E2-recorded TV-Show: season and episode already set... ", self, "I")
							searchStringSplitted = elementInfo.SearchString.split("::")
							if len(searchStringSplitted) >= 2:
								elementInfo.SearchString = searchStringSplitted[0]
								printl("New searchString after split: " + elementInfo.SearchString, self, "I")
						printl("Get IMDb ID from title using searchString: " + elementInfo.SearchString, self, "I")
						tmp = MobileImdbComProvider().getMoviesByTitle(elementInfo)
						if tmp is None:
							# validate if user use valerie.info with imdb or tvdb
							if (elementInfo.isTypeSerie() and elementInfo.TheTvDbId == MediaInfo.TheTvDbIdNull) or (elementInfo.isTypeMovie() and elementInfo.ImdbId == MediaInfo.ImdbIdNull): 
								printl("=> nothing found :-( " + elementInfo.SearchString, self, "I")
								#db.addFailed(FailedEntry(path, filename, extension, FailedEntry.UNKNOWN))
								#elementInfo.MediaType = MediaInfo.FAILEDSYNC
								elementInfo.MediaType = MediaInfo.UNKNOWN # avoid create serie
								elementInfo.MediaStatus = MediaInfo.STATUS_INFONOTFOUND
								elementInfo.syncErrNo   = 3
								elementInfo.syncFailedCause = u"Info Not Found"# cause
								db.insertMedia(elementInfo)
								continue
						else:
							elementInfo = tmp
						printl("Finally about to sync element... ", self, "I")
						results = Sync().syncWithId(elementInfo)
					else:
						printl("isXbmcNfo == True => using data from nfo:\n" + str(elementInfo), self, "I")
						results = (elementInfo, )
					
					if results is not None:
						printl("results: "+str(results), self)
						for result in results:
							result.MediaStatus = MediaInfo.STATUS_OK
							result.syncErrNo   = 0
							result.syncFailedCause = u""
							#printl("INSERT: "+result.Filename+ " type: " + str(result.MediaType) , self, "I")
							ret = db.insertMedia(result)
							if ret["status"] > 0:
								#result.Title = self.encodeMe(result.Title)
								if result.isTypeMovie():
									self.info(str(result.ImdbId) + "_poster_" + posterSize + ".png", 
										result.Title, result.Year)
									printl("my_title " + result.Title, self, "I")
								else:
									self.info(str(result.TheTvDbId) + "_poster_" + posterSize + ".png", 
										result.Title, result.Year)
									printl("my_title " + result.Title, self, "I")
							else:
								# ??????
								
								#cause = db.getAddFailedCauseOf()
								#db.addFailed(FailedEntry(path, filename, extension, FailedEntry.ALREADY_IN_DB,cause))
								#if result.syncFailedCause == u"":
								#	result.syncFailedCause = "DB Insert Error ??"
								result.MediaType = MediaInfo.FAILEDSYNC
								try:
									db.insertMedia(result)
								except Exception, ex:
									printl("DB Insert Error ??", self, "W")
					
					#self.output("(" + str(i) + "/" + str(elementListFileCounter) + ")")
					#printl("(" + str(i) + "/" + str(elementListFileCounter) + ")", self)
					self.progress(i)
コード例 #6
0
	def importDataToPickleV2 (self, session):
		printl("->", self, "S")
		try:
			if session is not None:
				self.mm = session.open(MessageBox, (_("\nConverting data to V2.... \n\nPlease wait... ")), MessageBox.TYPE_INFO)
				#self.mm = self.session.open(Msg)		
			printl("Importing Data to PickleV2", self)
			# this will Open Pickle V1 and run upgrades if necessary
			userId = config.plugins.pvmc.seenuserid.value
			dbHandlerPickle = databaseHandlerPICKLE().getInstance("from importDataToPickleV2", None)
			dbHandlerPickle.loadAll()
			#Upgrade SeenDB
			records = dbHandlerPickle.getSeenForUpgrade()
			
			self.dbHandler.loadAll()
			
			start_time = time.time()			
			cntNew = 0
			
			printl("Total Seen Movies to Convert: "+str(len(records["Movies"])), self)
			for imdb in records["Movies"]:
				if imdb == u"":
					continue
				printl("getSeen for imdb: "+imdb, self)
				m = self.dbHandler.getMediaWithImdbId(imdb)
				if m is None:
					#printl("IS NONE: "+imdb, self)
					m = MediaInfo()
					m.Id = None
					m.ImdbId = imdb
					
				seen = records["Movies"][imdb]["Seen"]
				if seen:
					self.dbHandler.MarkAsSeenWithMedia(m,userId)
				else:
					pass
					#self.dbHandler.MarkAsUnseenWithMedia(m,userId)
				
				cntNew += 1
			
			printl("Total Seen Series(no episodes) to Convert: "+str(len(records["TV"])), self)
			for thetvdb in records["TV"]:
				if thetvdb == u"":
					continue
				printl("getSeen for thetvdb: "+thetvdb, self)
				serie = self.dbHandler.getMediaWithTheTvDbId(thetvdb)
				for season in records["TV"][thetvdb]:			
					if serie is not None:
						EpisodesFromSeason = self.dbHandler.getEpisodes(serie.Id, season)	
					for episode in records["TV"][thetvdb][season]:
						EpisodeInserted = False
						seen = records["TV"][thetvdb][season][episode]["Seen"]
						if serie is not None:
							for ep in EpisodesFromSeason:
								if episode == ep.Episode:
									EpisodeInserted = True
									if seen:
										self.dbHandler.MarkAsSeen(ep.Id,userId)
									else:	
										pass
										#self.dbHandler.MarkAsUnseen(ep.Id,userId)
						else:
							#printl("NO SERIE: " + thetvdb, self)
							pass
							
						if not EpisodeInserted:
							#printl("MANNUALLY: " + thetvdb, self)
							m = MediaInfo() # Fake Media, Avoid loosing Seen Data
							m.Id = None
							m.TheTvDbId = thetvdb
							m.Season = season
							m.Episode = episode
							if seen:
								#printl("SEEN 2: " + thetvdb, self)
								self.dbHandler.MarkAsSeenWithMedia(m,userId)
							else:
								#printl("UNSEEN 2: " + thetvdb, self)
								#self.dbHandler.MarkAsUnseenWithMedia(m,userId)
								pass
								
						cntNew += 1
								
									
# dbSeen["Movies"][primary_key["ImdbId"]]["Seen"] = primary_key["Seen"]
# dbSeen["TV"][primary_key["TheTvDbId"]][primary_key["Season"]][primary_key["Episode"]]["Seen"] = primary_key["Seen"]

			printl("Seen Count: "+str(str(len(records["Movies"])+len(records["TV"]))) + " Processed: " + str(cntNew) )				
			
			#self.dbHandler.commit()
			elapsed_time = time.time() - start_time
			printl("Took: " + str(elapsed_time), self)
			try:
				if os.path.exists(self.DB_PATH + "seen.db"):
					os.rename(self.DB_PATH + "seen.db",   self.DB_PATH + "seen.db" +".old")
			except Exception, ex:
				printl(".Backup Seen failed! Ex: " + str(ex), __name__, "E")
		except Exception, ex:
			printl(".Failed Import to PickleV2! Reloading Pickle V1. Ex: " + str(ex), __name__, "E")
			self.USE_DB_TYPE    	= self.DB_PICKLE
コード例 #7
0
 #check is playing, if so transcode 30 seconds and investigate
 time.sleep(2)
 for process in psutil.process_iter():
     if '/usr/bin/vlc' in process.cmdline():
         process.kill()
 subprocess.Popen([
     "cvlc",
     response['response']['playback_url'],
     "--sout",
     "#std{access=file,mux=ts,dst='/tmp/acestream.mkv'}"
 ])
 time.sleep(30)  #30s sample video
 for process in psutil.process_iter():
     if '/usr/bin/vlc' in process.cmdline():
         process.kill()
 info = MediaInfo(
     filename='/tmp/acestream.mkv')
 language = ""
 try:
     infoData = info.getInfo()
     proc = subprocess.Popen(
         [
             "/usr/bin/mediainfo",
             "/tmp/acestream.mkv"
         ],
         stdout=subprocess.PIPE)
     o = proc.stdout.read()
     for l in o.split("\n"):
         if re.match("Language", l):
             language = l.split(":")[1][1:]
     #print infoData
 except:
コード例 #8
0
ファイル: Manager.py プロジェクト: steve4744/project-valerie
    def syncElement(self,
                    path,
                    filename,
                    extension,
                    imdbid,
                    istvshow,
                    oldelement=None):
        printl(
            str(path) + " " + str(filename) + " " + str(extension) + " " +
            str(imdbid) + " " + str(istvshow), self)

        element = None

        if oldelement is None:
            element = MediaInfo(path, filename, extension)
            element.parse()
            element.ImdbId = imdbid
        else:
            element = oldelement  #.copy()

        if istvshow:
            element.setMediaType(MediaInfo.SERIE)
        else:
            element.setMediaType(MediaInfo.MOVIE)

        results = Sync().syncWithId(element)
        if results is not None:
            return results
        else:
            if istvshow is False:
                element.setMediaType(MediaInfo.SERIE)
            else:
                element.setMediaType(MediaInfo.MOVIE)

            results = Sync().syncWithId(element)
            if results is not None:
                return results
        return None
コード例 #9
0
ファイル: Manager.py プロジェクト: Rikitik/project-valerie
    def syncElement(self, path, filename, extension, imdbid, istvshow, oldelement=None):
        printl(str(path) + " " + str(filename) + " " + str(extension) + " " + str(imdbid) + " " + str(istvshow), self)

        element = None

        if oldelement is None:
            element = MediaInfo(path, filename, extension)
            element.parse()
            element.ImdbId = imdbid
        else:
            element = oldelement  # .copy()

        if istvshow:
            element.setMediaType(MediaInfo.SERIE)
        else:
            element.setMediaType(MediaInfo.MOVIE)

        results = Sync().syncWithId(element)
        if results is not None:
            return results
        else:
            if istvshow is False:
                element.setMediaType(MediaInfo.SERIE)
            else:
                element.setMediaType(MediaInfo.MOVIE)

            results = Sync().syncWithId(element)
            if results is not None:
                return results
        return None
コード例 #10
0
    def do_GET(self):
        global temp_stream_saved, file_save_status, key, streamtimer, dir_path
        if not os.path.isfile('/tmp/pid_stat_url'):
            with open('/tmp/pid_stat_url', 'w') as f:
                f.write(json.dumps(None))
        with open('/tmp/pid_stat_url', 'r') as f:
            pid_stat_url = json.loads(f.read())
        path = self.path.split("/")
        if path[1] != 'segments':  #allow non-password access to live stream segments
            if self.headers.getheader('Authorization') == None:
                self.do_AUTHHEAD()
                pass
            elif self.headers.getheader('Authorization') != "Basic %s" % key:
                self.do_AUTHHEAD()
                pass
            if self.headers.getheader('Authorization') != "Basic %s" % key:
                return

        #check if vlc running
        vlcrunning = False
        for process in psutil.process_iter():
            if '/usr/bin/vlc' in process.cmdline(
            ) and '--live-caching' in process.cmdline():
                vlcrunning = True
                vlcrunning_line = process.cmdline()
        enginerunning = False
        if "acestreamengine" in (p.name() for p in psutil.process_iter()):
            enginerunning = True

        if path[1] == 'engine':
            if len(path) == 3:
                if path[2] == 'start' and enginerunning == False:
                    proc1 = subprocess.Popen([
                        "/snap/bin/acestreamplayer.engine", "--client-console",
                        "--live-cache-type", "disk", "--live-disk-cache-size",
                        "1000000000"
                    ])
                elif path[2] == 'stop':
                    for process in psutil.process_iter():
                        if process.name() == "acestreamengine" or (
                                '/usr/bin/vlc' in process.cmdline()
                                and '--live-caching' in process.cmdline()):
                            process.kill()
                    pid_stat_url = None
                    with open('/tmp/pid_stat_url', 'w') as f:
                        f.write(json.dumps(pid_stat_url))
                    if os.path.isfile(dir_path + "/listings/LIVE.strm"):
                        os.remove(dir_path + "/listings/LIVE.strm")
                elif path[2] == 'stopstream':
                    for process in psutil.process_iter():
                        if '/usr/bin/vlc' in process.cmdline(
                        ) and '--live-caching' in process.cmdline():
                            process.kill()
                    if pid_stat_url is not None:
                        #command_url ?method=stop
                        sr = requests.get(
                            json.loads(pid_stat_url[3])['response']
                            ['command_url'] + "?method=stop")
                        #print sr.text
                    pid_stat_url = None
                    with open('/tmp/pid_stat_url', 'w') as f:
                        f.write(json.dumps(pid_stat_url))
                    if os.path.isfile(dir_path + "/listings/LIVE.strm"):
                        os.remove(dir_path + "/listings/LIVE.strm")

                time.sleep(5)
                self.send_response(302)
                self.send_header('Location', "/")
                self.end_headers()

        elif path[1] == 'transcoding' and pid_stat_url is not None:
            if len(path) == 3:
                if path[2] == 'start' and len(pid_stat_url) > 0:
                    if vlcrunning == False:  #only start one instance
                        temp_stream_saved = False
                        f = open(dir_path + "/listings/LIVE.strm", "w")
                        f.write("%s://%s:%s@%s/segments/acestream.m3u8" %
                                (PROTOCOL, USERNAME, PASSWORD, SERVER_IP))
                        f.close()
                        subprocess.Popen([
                            "cvlc", "--live-caching", "30000", pid_stat_url[2],
                            "--sout",
                            "#duplicate{dst=std{access=livehttp{seglen=5,delsegs=true,numsegs=20,index="
                            + dir_path +
                            "/segments/acestream.m3u8,index-url=" + PROTOCOL +
                            "://" + USERNAME + ":" + PASSWORD + "@" +
                            SERVER_IP +
                            "/segments/stream-########.ts},mux=ts{use-key-frames},dst="
                            + dir_path +
                            "/segments/stream-########.ts},dst=std{access=file,mux=ts,dst='"
                            + dir_path +
                            "/listings/live_stream_from_start.mp4'}}"
                        ])
                elif path[2] == 'stop' and len(pid_stat_url) > 0:
                    for process in psutil.process_iter(
                    ):  #kill acestream engine and vlc
                        if process.name() == "acestreamengine" or (
                                '/usr/bin/vlc' in process.cmdline()
                                and '--live-caching' in process.cmdline()):
                            process.kill()
                    pid_stat_url = None
                    with open('/tmp/pid_stat_url', 'w') as f:
                        f.write(json.dumps(pid_stat_url))
                    if os.path.isfile(dir_path + "/listings/LIVE.strm"):
                        os.remove(dir_path + "/listings/LIVE.strm")
                    temp_stream_saved = True
                time.sleep(5)
                self.send_response(302)
                self.send_header('Location', "/")
                self.end_headers()

        elif path[1] == 'savefile' and len(path) == 3:
            for f in path[2].split("?")[1].split("&"):
                if f.split("=")[0] == "savefilename":
                    matchname = f.split("=")[1]
            for process in psutil.process_iter():
                if process.name() == "acestreamengine" or (
                        '/usr/bin/vlc' in process.cmdline()
                        and '--live-caching' in process.cmdline()):
                    process.kill()
            #ffmpeg has needed -bsf:a aac_adtstoasc option to fix  PES packet size mismatch, Error parsing ADTS frame header errors only for AAC audio
            info = MediaInfo(filename=dir_path +
                             "/listings/live_stream_from_start.mp4")
            try:
                if info.getInfo()['audioCodec'] == "AAC":
                    file_save_status = [
                        "ffmpeg", "-y", "-i",
                        dir_path + "/listings/live_stream_from_start.mp4",
                        "-c:v", "copy", "-c:a", "copy", "-movflags",
                        "faststart", "-bsf:a", "aac_adtstoasc",
                        dir_path + "/listings/" + matchname + ".mp4"
                    ]
                else:
                    file_save_status = [
                        "ffmpeg", "-y", "-i",
                        dir_path + "/listings/live_stream_from_start.mp4",
                        "-c:v", "copy", "-c:a", "copy", "-movflags",
                        "faststart",
                        dir_path + "/listings/" + matchname + ".mp4"
                    ]
            except:
                file_save_status = [
                    "ffmpeg", "-y", "-i",
                    dir_path + "/listings/live_stream_from_start.mp4", "-c:v",
                    "copy", "-c:a", "copy", "-movflags", "faststart",
                    dir_path + "/listings/" + matchname + ".mp4"
                ]
            subprocess.Popen(file_save_status)
            pid_stat_url = None
            with open('/tmp/pid_stat_url', 'w') as f:
                f.write(json.dumps(pid_stat_url))
            temp_stream_saved = False
            self.send_response(302)
            self.send_header('Location', "/")
            self.end_headers()

        elif path[1] == 'openpid' and len(path) == 3 and enginerunning:
            for process in psutil.process_iter():  #kill any vlc session
                if '/usr/bin/vlc' in process.cmdline(
                ) and '--live-caching' in process.cmdline():
                    process.kill()
            pid_stat_url = None
            with open('/tmp/pid_stat_url', 'w') as f:
                f.write(json.dumps(pid_stat_url))
            stream_pid = False
            for f in path[2].split("?")[1].split("&"):
                if f.split("=")[0] == "pid":
                    stream_pid = f.split("=")[1]
                    stream_uid = hashlib.sha1(stream_pid).hexdigest()
            if stream_pid:
                r = requests.get(
                    'http://127.0.0.1:6878/ace/getstream?format=json&sid={0}&id={1}'
                    .format(stream_uid, stream_pid))
                pid_stat_url = [
                    stream_pid,
                    json.loads(r.text)['response']['stat_url'],
                    json.loads(r.text)['response']['playback_url'], r.text,
                    stream_pid
                ]
                with open('/tmp/pid_stat_url', 'w') as f:
                    f.write(json.dumps(pid_stat_url))

            #start stream timer
            streamtimer = time.time()
            time.sleep(5)
            self.send_response(302)
            self.send_header('Location', "/")
            self.end_headers()

        else:
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write("""
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{
  font-family: Arial;
  font-size:12px;
  text-align:center;
}
.button {
    background-color: #4CAF50;
    border: none; 
    color: white; 
    padding: 12px 24px; 
    font-size: 12px;
    cursor: pointer;
    width:150px;
    text-align:left;
}
.buttonloading {
    background-color: #4CAF50;
    }
.buttonstopped{
    background-color: #AF504C
    }
  
.fa {
    margin-left: -12px;
    margin-right: 8px;
}
.status{
    font-family:Courier;
    font-size:80%;
}
.statusdiv{
    margin:auto;
    text-align:center;
    width:400px;
    padding-top:10px;
    padding-bottom:20px;
    font-family: Courier;
    font-weight: bold;
}
</style>
</head>
<body>
""")
            self.wfile.write("<div>")
            disabledtext = ["", ""]
            if enginerunning:
                disabledtext[0] = "disabled style='opacity: 0.4;'"
                engine_status_text = "Running"
            else:
                disabledtext[1] = "disabled style='opacity: 0.4;'"
                engine_status_text = "Not running"
            self.wfile.write("""
        <button class='button buttonloading' %s onclick='this.style.display=\"none\";document.getElementById(\"button_starting\").style.display=\"\";location.href="/engine/start\"'>
        <i class='fa fa-stop-circle'></i>Start Engine</button>
       <button id='button_starting' class='button buttonloading' style='display:none'> 
        <i class='fa fa-spinner fa-spin'></i>Starting Engine</button>
       """ % disabledtext[0])
            self.wfile.write("""
        <button class='button buttonstopped' %s onclick='this.style.display=\"none\";document.getElementById(\"button_stopping\").style.display=\"\";location.href="/engine/stop\"'>
        <i class='fa fa-play-circle'></i>Stop Engine</button>
        <button id='button_stopping' class='button buttonloading' style='display:none'> 
        <i class='fa fa-spinner fa-spin'></i>Stopping Engine</button>
        """ % disabledtext[1])

            self.wfile.write(
                "</div><div class='statusdiv'>Engine Status: %s</div>" %
                engine_status_text)

            disabledtext = ["", ""]
            stream_OK_to_transcode = False
            if enginerunning:
                if pid_stat_url is not None:
                    s = requests.get(pid_stat_url[1])
                    engine_response = json.loads(s.text)
                    disabledtext[0] = "disabled style='opacity: 0.4;'"
                    acestream_status_text = "Streaming<br />acestream://%s<br />" % pid_stat_url[
                        0]
                    if (time.time() - streamtimer) < 30:
                        acestream_status_text += "Wait 30s for stream to settle<br />"
                        acestream_status_text += """
            <script>
            var timeleft = 30;
            var downloadTimer = setInterval(function(){
              document.getElementById("progressBar").value = 30 - --timeleft;
              if(timeleft <= 0){
                clearInterval(downloadTimer);
                location.href="/";
              }
            },1000);
            </script>
            <progress value="0" max="30" id="progressBar"></progress>
            <br />
            """
                    elif 'response' in engine_response:
                        if 'speed_down' in engine_response['response']:
                            if engine_response['response'][
                                    'status'] == "prebuf":
                                acestream_status_text += "Buffering"
                            elif int(engine_response['response']
                                     ['speed_down']) < 100:
                                acestream_status_text += "Stream health poor"
                            elif int(engine_response['response']
                                     ['speed_down']) < 300:
                                acestream_status_text += "Stream health average"
                                stream_OK_to_transcode = True
                            else:
                                acestream_status_text += "Stream health OK"
                                stream_OK_to_transcode = True
                            if stream_OK_to_transcode:
                                acestream_status_text += "<br />DL Speed: %s kbps<br />Peers %s" % (
                                    engine_response['response']['speed_down'],
                                    engine_response['response']['peers'])
                            else:  #reload every 5 seconds if buffering or poor stream health
                                self.wfile.write("""<script>
                  setTimeout(function(){
                    window.location.reload(1);
                  }, 5000);
                  </script>""")

                else:
                    disabledtext[1] = "disabled style='opacity: 0.4;'"
                    acestream_status_text = "No stream"
            else:
                disabledtext[0] = "disabled style='opacity: 0.4;'"
                disabledtext[1] = "disabled style='opacity: 0.4;'"
                acestream_status_text = ""
            self.wfile.write(
                '<div><form method="GET" action="/openpid/" id="openpid" style="display:inline"><input type=text name="pid" placeholder="Acestream ID" style="margin-bottom:10px;width:300px;" %s><br>'
                % disabledtext[0])
            self.wfile.write("""
        <button class='button buttonloading' %s onclick='this.style.display="none"; document.getElementById("button_ace_starting").style.display=""; document.getElementById("openpid").submit()'>
        <i class='fa fa-stop-circle'></i>Start Acestream</button>
        <button id='button_ace_starting' class='button buttonloading' style='display:none'>
        <i class='fa fa-spinner fa-spin'></i>Starting Acestream</button></form>
      """ % disabledtext[0])
            self.wfile.write("""
        <button class='button buttonstopped' %s onclick='this.style.display="none";document.getElementById("button_ace_stopping").style.display="";location.href="/engine/stopstream"'>
        <i class='fa fa-play-circle'></i>Stop Acestream</button>
        <button id="button_ace_stopping" class='button buttonstopped' style='display:none'> 
        <i class='fa fa-spinner fa-spin'></i>Stopping Acestream</button>
        """ % disabledtext[1])
            self.wfile.write(
                "</div><div class='statusdiv'>Acestream Status: %s</div>" %
                acestream_status_text)

            self.wfile.write("<div>")
            disabledtext = ["", ""]
            if stream_OK_to_transcode:
                if vlcrunning:
                    disabledtext[0] = "disabled style='opacity: 0.4;'"
                    transcode_status_text = """
          Transcoding<br />Stream: %s://%s/segments/acestream.m3u8<br />
          Kodi: %s://%s/listings/LIVE.strm<br />
          """ % (PROTOCOL, SERVER_IP, PROTOCOL, SERVER_IP)
                else:
                    disabledtext[1] = "disabled style='opacity: 0.4;'"
                    transcode_status_text = "Not Transcoding"
            else:
                disabledtext[0] = "disabled style='opacity: 0.4;'"
                disabledtext[1] = "disabled style='opacity: 0.4;'"
                transcode_status_text = ""
            self.wfile.write("""
        <button class='button buttonloading' %s onclick='this.style.display=\"none\";document.getElementById(\"transcode_starting\").style.display=\"\";location.href="/transcoding/start\"'>
        <i class='fa fa-stop-circle'></i>Start Transcode</button>
       <button id='transcode_starting' class='button buttonloading' style='display:none'> 
        <i class='fa fa-spinner fa-spin'></i>Starting Transcode</button>
       """ % disabledtext[0])
            self.wfile.write("""
        <button class='button buttonstopped' %s onclick='this.style.display=\"none\";document.getElementById(\"transcode_stopping\").style.display=\"\";location.href="/transcoding/stop\"'>
        <i class='fa fa-play-circle'></i>Stop Transcode</button>
        <button id='transcode_stopping' class='button buttonloading' style='display:none'> 
        <i class='fa fa-spinner fa-spin'></i>Stopping Trancode</button>
        """ % disabledtext[1])

            self.wfile.write(
                "</div><div class='statusdiv'>Transcode Status: %s</div>" %
                transcode_status_text)

            if vlcrunning: disabledtext[0] = ""
            else: disabledtext[0] = "disabled style='opacity: 0.4;'"
            self.wfile.write(
                "<button class='button buttonloading' %s onclick='window.open(\"%s://%s/player.html\", \"\", \"width=660,height=380\");'><i class='fa fa-play-circle'></i>Launch Player</button>"
                % (disabledtext[0], PROTOCOL, SERVER_IP))

            if not temp_stream_saved:
                disabledtext[0] = "disabled style='opacity: 0.4;'"
            else:
                disabledtext[0] = ""
            self.wfile.write('''
       <div>
       <form method="GET" action="/savefile/" id="savefile">
       <input type=text name="savefilename" placeholder="Save filename" style="margin-top:20px; margin-bottom:10px;width:300px;" %s><br />
       <button class='button buttonloading' %s onclick='document.getElementById("savefile").submit()'>
       <i class='fa fa-save'></i>Save Recording</button>
       </form>
       </div>
      ''' % (disabledtext[0], disabledtext[0]))
コード例 #11
0
                         chosenstream
                     ]
                     with open('/tmp/pid_stat_url', 'w') as f:
                         f.write(json.dumps(pid_stat_url))
                     #check is playing, if so transcode approriate length
                     time.sleep(2)
                     subprocess.Popen([
                         "cvlc", response['response']['playback_url'],
                         "--sout",
                         "#std{access=file,mux=ts,dst='/tmp/acestream.mkv'}"
                     ])
                     time.sleep(time_to_record * 60)
 for process in psutil.process_iter():
     if '/usr/bin/vlc' in process.cmdline():
         process.kill()
 info = MediaInfo(filename='/tmp/acestream.mkv')
 try:
     if info.getInfo()['audioCodec'] == "AAC":
         file_save_status = [
             "ffmpeg", "-y", "-i", "/tmp/acestream.mkv", "-c:v", "copy",
             "-c:a", "copy", "-movflags", "faststart", "-bsf:a",
             "aac_adtstoasc", dir_path + "/listings/" + matchname + ".mp4"
         ]
     else:
         file_save_status = [
             "ffmpeg", "-y", "-i", "/tmp/acestream.mkv", "-c:v", "copy",
             "-c:a", "copy", "-movflags", "faststart",
             dir_path + "/listings/" + matchname + ".mp4"
         ]
 except:
     file_save_status = [
コード例 #12
0
ファイル: tests.py プロジェクト: pharvie/scraper
    def test_haveDefaultCmdFfprobe(self):
        info = MediaInfo(filename='/media/test.ts')
        infoData = info.getInfo()

        self.assertNotEqual(infoData, None)
コード例 #13
0
ファイル: tests.py プロジェクト: pharvie/scraper
    def test_haveCmdParameter(self):
        info = MediaInfo(filename='/media/test.ts', cmd='/usr/bin/ffprobe')
        infoData = info.getInfo()

        self.assertNotEqual(infoData, None)
コード例 #14
0
ファイル: tests.py プロジェクト: pharvie/scraper
    def test_nonFileNameParameter(self):
        info = MediaInfo()
        infoData = info.getInfo()

        self.assertEqual(infoData, None)
コード例 #15
0
ファイル: sync.py プロジェクト: steve4744/project-valerie
    def run(self):

        self.doAbort = False

        self.output(_("Loading Config"))
        Blacklist.load()
        printl(str(len(Blacklist.get())) + " entrys")

        self.output(_("Loading Data"))
        printl("Loading Data", self)

        db = Database().getInstance()

        if self.mode == self.UPDATE:
            from Manager import Manager
            Manager().updateAll(self.output, self.progress, self.range)

            self.output(_("Saving database"))
            printl("Saving database", self)
            db.save()

            self.output(_("Done"))
            printl("Done", self)
            self.output("---------------------------------------------------")
            self.output(_("Press Exit / Back"))

            self.finished(True)
            return

        #temporarly - there are only failed, missing webif
        #db.deleteMediaFilesNotOk()

        if self.mode != self.FAST and SyncConfig().getInstance().get(
                "delete") is True:
            db.deleteMissingFiles()

        if self.mode != self.FAST:
            db.transformGenres()

        printl("Entries: " + str(db), self)

        self.output(_("Loading Replacements"))
        printl("Loading Replacements", self)
        replace.load()

        posterSize = Arts.posterResolution[0]
        if self.dSize.width() == 720 and self.dSize.height() == 576:
            posterSize = Arts.posterResolution[0]
        elif self.dSize.width() == 1024 and self.dSize.height() == 576:
            posterSize = Arts.posterResolution[1]
        elif self.dSize.width() == 1280 and self.dSize.height() == 720:
            posterSize = Arts.posterResolution[2]

        self.output(_("Loading Filesystem"))
        printl("Loading Filesystem", self)
        ds = DirectoryScanner.DirectoryScanner()
        ds.clear()
        if self.mode == self.FAST:
            ds.load()

        pathsConfig = PathsConfig().getInstance()
        filetypes = pathsConfig.getFileTypes()
        self.output(_("Extensions:") + ' ' + str(filetypes))
        printl("Extensions: " + str(filetypes), self)

        self.output(_("Searching for media files"))
        printl("Searching for media files", self)
        start_time = time.time()

        folderList = []
        elementList = [
        ]  # if there are no folder it will crash on » del elementlist	#Zuki
        elementListFileCounter = 0

        for searchpath in pathsConfig.getPaths():
            if searchpath["enabled"] is False:
                continue

            path = searchpath["directory"]
            folderType = searchpath["type"]
            useFolder = searchpath["usefolder"]

            if os.path.isdir(path) is False:
                continue

            ds.setDirectory(Utf8.utf8ToLatin(path))
            ds.listDirectory(filetypes, "(sample)|(VTS)|(^\\.)")
            filelist = ds.getFileList()
            elementListFileCounter += len(filelist)
            folderList.append((
                filelist,
                folderType,
                useFolder,
            ))

        elapsed_time = time.time() - start_time
        printl("Searching for media files took: " + str(elapsed_time), self)

        if elementListFileCounter == 0:
            self.output(_("Found") + ' ' + str(0) + ' ' + _("media files"))
            printl("Found 0 media files", self)
        else:
            self.output(
                _("Found") + ' ' + str(elementListFileCounter) + ' ' +
                _("media files"))
            printl("Found " + str(elementListFileCounter) + " media files",
                   self)

            self.range(elementListFileCounter)

            i = 0
            for folder in folderList:
                #print "folder", folder
                elementList = folder[0]
                folderType = folder[1]
                useFolder = folder[2]

                if self.doAbort:
                    break

                for element in elementList:
                    i += 1
                    self.progress(i)

                    pathOrig = element[0].replace("\\", "/")
                    filenameOrig = element[1]
                    extensionOrig = element[2]

                    printl("*" * 100, self, "I")
                    printl(
                        "* Next file to sync: " + str(pathOrig) + "/" +
                        str(filenameOrig) + "." + str(extensionOrig), self,
                        "I")
                    printl("*" * 100, self, "I")

                    path = Utf8.stringToUtf8(pathOrig)
                    filename = Utf8.stringToUtf8(filenameOrig)
                    extension = Utf8.stringToUtf8(extensionOrig)

                    if self.doAbort:
                        break

                    if path is None or filename is None or extension is None:
                        printl(
                            "Path or filename or extension is None => skip!",
                            self, "I")
                        continue

                    if "RECYCLE.BIN" in path or ".AppleDouble" in path:
                        printl("Special directory => skip!", self, "I")
                        continue

                    if (filename + u"." + extension) in Blacklist.get():
                        printl("File is blacklisted => skip!", self, "I")
                        continue
                    #printl("testing 1", self)

                    printl("Checking for duplicates...", self, "I")
                    retCheckDuplicate = db.checkDuplicate(
                        path, filename, extension)

                    mediaInDb = retCheckDuplicate["mediafile"]
                    # if never sync with success delete db entry and resync
                    if mediaInDb is not None and retCheckDuplicate[
                            "mediafile"].syncErrNo == MediaInfo.STATUS_INFONOTFOUND:  # exist
                        printl("Deleting and resync FailedItem", self)
                        db.deleteMedia(retCheckDuplicate["mediafile"].Id)
                        mediaInDb = None

                    if mediaInDb is not None:
                        printl("Media exists in database...", self, "I")
                        if retCheckDuplicate["reason"] == 1:  # exist
                            m2 = retCheckDuplicate["mediafile"]
                            if m2.syncErrNo == 0 and m2.MediaStatus != MediaInfo.STATUS_OK:
                                #printl("Sync - Duplicate Found :" + str(m2.Path) + "/" + str(m2.Filename) + "." + str(m2.Extension), self)
                                key_value_dict = {}
                                key_value_dict["Id"] = m2.Id
                                key_value_dict[
                                    "MediaStatus"] = MediaInfo.STATUS_OK
                                #key_value_dict["syncErrNo"]	= 0
                                key_value_dict["syncFailedCause"] = u""
                                printl("Sync - Update Media 1", self)
                                if not db.updateMediaWithDict(key_value_dict):
                                    printl("Sync - Update Media 1 - Failed",
                                           self)

                        elif retCheckDuplicate[
                                "reason"] == 2:  # exist on other path, change record path
                            m2 = retCheckDuplicate["mediafile"]
                            if m2.syncErrNo == 0:
                                printl(
                                    "Sync - Duplicate Found on other path:" +
                                    str(m2.Path) + "/" + str(m2.Filename) +
                                    "." + str(m2.Extension), self)
                                key_value_dict = {}
                                key_value_dict["Id"] = m2.Id
                                key_value_dict["Path"] = path
                                key_value_dict[
                                    "MediaStatus"] = MediaInfo.STATUS_OK
                                #key_value_dict["syncErrNo"]	= 0
                                key_value_dict["syncFailedCause"] = u""
                                printl("Sync - Update Media 2", self)
                                if not db.updateMediaWithDict(key_value_dict):
                                    printl("Sync - Update Media 2 - Failed",
                                           self)

                        # take lots of time to write on screen, we have the progressbar
                        #self.output("Already in db [ " + Utf8.utf8ToLatin(filename) + " ]")

                        #printl("testing 2", self)
                        if Arts().isMissing(mediaInDb):
                            printl("=> Arts missing in Db!...", self, "I")
                            #self.output("Downloading missing poster")
                            tmp = None
                            if mediaInDb.isTypeMovie():
                                tmp = TheMovieDbProvider().getArtByImdbId(
                                    mediaInDb)
                            elif mediaInDb.isTypeEpisode():
                                tvshow = db.getMediaWithTheTvDbId(
                                    mediaInDb.TheTvDbId)
                                #printl(str(tvshow.SeasonPoster), self, "E")
                                tvshow.SeasonPoster.clear(
                                )  # Make sure that there are no residues
                                tmp = TheTvDbProvider().getArtByTheTvDbId(
                                    tvshow)
                                if tmp is not None:
                                    printl(str(tmp.SeasonPoster), self, "E")

                            if tmp is not None:
                                Arts().download(tmp)

                                if mediaInDb.isTypeMovie():
                                    self.info(
                                        str(mediaInDb.ImdbId) + "_poster_" +
                                        posterSize + ".png", "", "")
                                elif mediaInDb.isTypeSerie(
                                ) or mediaInDb.isTypeEpisode():
                                    self.info(
                                        str(mediaInDb.TheTvDbId) + "_poster_" +
                                        posterSize + ".png", "", "")
                                del tmp

                        del mediaInDb
                        continue

                    outStr = "(" + str(i) + "/" + str(
                        elementListFileCounter) + ")"

                    self.output(outStr + " -> " + getStringShrinked(pathOrig) +
                                " >> " + filenameOrig + "." + extensionOrig)
                    printl("#" * 30, self)
                    printl(
                        "(" + str(i) + "/" + str(elementListFileCounter) + ")",
                        self)
                    printl("#" * 6, self)
                    printl(
                        "  -> " + pathOrig + "\n	" + filenameOrig + "." +
                        extensionOrig, self)

                    elementInfo = MediaInfo(path, filename, extension)

                    printl("FOLDERTYPE: " + str(folderType), self)
                    printl("USEFOLDER: " + str(useFolder), self)

                    if folderType == u"MOVIE":
                        elementInfo.setMediaType(MediaInfo.MOVIE)
                    elif folderType == u"TV":
                        elementInfo.setMediaType(MediaInfo.SERIE)
                    else:
                        elementInfo.setMediaType(MediaInfo.UNKNOWN)

                    result = elementInfo.parse(useFolder)

                    if result == False:
                        continue

                    printl("TheTvDbId: " + elementInfo.TheTvDbId, self, "I")

                    if elementInfo.isXbmcNfo == False:
                        printl(
                            "isXbmcNfo == False => checking for E2 recorded TV show... ",
                            self, "I")
                        if elementInfo.isTypeSerie(
                        ) and elementInfo.isEnigma2MetaRecording:
                            if elementInfo.Season == None or elementInfo.Episode == None:
                                printl(
                                    "E2-recorded TV-Show => trying to get season and episode from E2 episodename... ",
                                    self, "I")
                                tmp = GoogleProvider(
                                ).getSeasonAndEpisodeFromEpisodeName(
                                    elementInfo)
                                if (tmp[0] is True) and (tmp[1] is None):
                                    #Issue #474 => Don't fall back if foldertype is not explicitely "MOVIE_AND_TV"
                                    if folderType == u"MOVIE_AND_TV":
                                        printl(
                                            "E2-recording not recognized as TV show => trying to parse as movie... ",
                                            self, "I")
                                        elementInfo.setMediaType(
                                            MediaInfo.MOVIE)
                                    else:
                                        elementInfo.MediaType = MediaInfo.UNKNOWN  # avoid create serie
                                        elementInfo.MediaStatus = MediaInfo.STATUS_INFONOTFOUND
                                        elementInfo.syncErrNo = 3
                                        elementInfo.syncFailedCause = u"Info Not Found"  # cause
                                        printl(
                                            "Failed to detect TV show and folder type set to 'TV' => adding media as failed...",
                                            self, "I")
                                        db.insertMedia(elementInfo)
                                        continue
                                elif tmp[0] is True:
                                    # Issue #205, efo => use tmp[1] instead of tmp...
                                    elementInfo = tmp[1]
                                    printl(
                                        "Result from google => Season=" +
                                        str(elementInfo.Season) +
                                        " / Episode=" +
                                        str(elementInfo.Episode), self, "I")
                            else:
                                printl(
                                    "E2-recorded TV-Show: season and episode already set... ",
                                    self, "I")
                            searchStringSplitted = elementInfo.SearchString.split(
                                "::")
                            if len(searchStringSplitted) >= 2:
                                elementInfo.SearchString = searchStringSplitted[
                                    0]
                                printl(
                                    "New searchString after split: " +
                                    elementInfo.SearchString, self, "I")
                        printl(
                            "Get IMDb ID from title using searchString: " +
                            elementInfo.SearchString, self, "I")
                        tmp = MobileImdbComProvider().getMoviesByTitle(
                            elementInfo)
                        if tmp is None:
                            # validate if user use valerie.info with imdb or tvdb
                            if (elementInfo.isTypeSerie()
                                    and elementInfo.TheTvDbId
                                    == MediaInfo.TheTvDbIdNull) or (
                                        elementInfo.isTypeMovie()
                                        and elementInfo.ImdbId
                                        == MediaInfo.ImdbIdNull):
                                printl(
                                    "=> nothing found :-( " +
                                    elementInfo.SearchString, self, "I")
                                #db.addFailed(FailedEntry(path, filename, extension, FailedEntry.UNKNOWN))
                                #elementInfo.MediaType = MediaInfo.FAILEDSYNC
                                elementInfo.MediaType = MediaInfo.UNKNOWN  # avoid create serie
                                elementInfo.MediaStatus = MediaInfo.STATUS_INFONOTFOUND
                                elementInfo.syncErrNo = 3
                                elementInfo.syncFailedCause = u"Info Not Found"  # cause
                                db.insertMedia(elementInfo)
                                continue
                        else:
                            elementInfo = tmp
                        printl("Finally about to sync element... ", self, "I")
                        results = Sync().syncWithId(elementInfo)
                    else:
                        printl(
                            "isXbmcNfo == True => using data from nfo:\n" +
                            str(elementInfo), self, "I")
                        results = (elementInfo, )

                    if results is not None:
                        printl("results: " + str(results), self)
                        for result in results:
                            result.MediaStatus = MediaInfo.STATUS_OK
                            result.syncErrNo = 0
                            result.syncFailedCause = u""
                            #printl("INSERT: "+result.Filename+ " type: " + str(result.MediaType) , self, "I")
                            ret = db.insertMedia(result)
                            if ret["status"] > 0:
                                #result.Title = self.encodeMe(result.Title)
                                if result.isTypeMovie():
                                    self.info(
                                        str(result.ImdbId) + "_poster_" +
                                        posterSize + ".png", result.Title,
                                        result.Year)
                                    printl("my_title " + result.Title, self,
                                           "I")
                                else:
                                    self.info(
                                        str(result.TheTvDbId) + "_poster_" +
                                        posterSize + ".png", result.Title,
                                        result.Year)
                                    printl("my_title " + result.Title, self,
                                           "I")
                            else:
                                # ??????

                                #cause = db.getAddFailedCauseOf()
                                #db.addFailed(FailedEntry(path, filename, extension, FailedEntry.ALREADY_IN_DB,cause))
                                #if result.syncFailedCause == u"":
                                #	result.syncFailedCause = "DB Insert Error ??"
                                result.MediaType = MediaInfo.FAILEDSYNC
                                try:
                                    db.insertMedia(result)
                                except Exception, ex:
                                    printl("DB Insert Error ??", self, "W")

                    #self.output("(" + str(i) + "/" + str(elementListFileCounter) + ")")
                    #printl("(" + str(i) + "/" + str(elementListFileCounter) + ")", self)
                    self.progress(i)