def onAction( self, action ): #try: # Cancel if ( action.getId() in CANCEL_DIALOG or self.getFocusId() == BUTTON_CANCEL and action.getId() in SELECT_ITEM ): array = [] self.close() # Okay if ( self.getFocusId() == BUTTON_OK and action.getId() in SELECT_ITEM ): self.close() # Select or deselect item in list if ( action.getId() in SELECT_ITEM and self.getFocusId() == TAGS_LIST ): item = self.getControl( TAGS_LIST ).getSelectedItem() pos = self.getControl( TAGS_LIST ).getSelectedPosition() kb = xbmc.Keyboard(item.getLabel2(), _(30623)%( decoder.smart_utf8(item.getLabel())), False) kb.doModal() if (kb.isConfirmed()): item.setLabel2(kb.getText()) MPDB.setTranslatedTagType(decoder.smart_unicode(item.getLabel()), decoder.smart_unicode(item.getLabel2())) self.getControl( TAGS_LIST ).setVisible(False) self.getControl( TAGS_LIST ).setVisible(True)
def browse_folder( dirname, parentfolderID=None, recursive=True, updatepics=False, addpics=True, delpics=True, rescan=False, updatefunc=None, dateadded=strftime("%Y-%m-%d %H:%M:%S"), ): """Browse the root folder 'dirname' - 'recursive' : the scan is recursive. all the subfolders of 'dirname' are traversed for pics - 'updatepics' : enable to modify a picture entry if metas changed - 'rescan' : force the scan wheter pictures are already inside DB or not - 'addpics' : - 'delpics' : - 'dateadded' : the date when the pictures are scanned (useful for subfolders calls to keep the same date as the main root folder) - 'updatefunc' is a function called to show the progress of the scan. The parameters are : pourcentage(int),[ line1(str),line2(str),line3(str) ] ) """ global compte, comptenew, cptscanned, cptdelete, cptchanged, cptroots, iroots cpt = 0 # on liste les fichiers jpg du dossier listfolderfiles = [] sys_enc = sys.getfilesystemencoding() dirname = smart_unicode(dirname) print "In browse_folder" print decoder.smart_utf8(dirname) ####### # Pre STEP: cleanup keywords in database ####### MPDB.DB_cleanup_keywords() ####### # STEP 0 : dirname should not be one of those which are excluded from scan ! ####### # TODO : if the path was already scanned before, we need to remove previously added pictures AND subfolders if dirname in Exclude_folders: # print "dirname in Exclude_folders" cptdelete = cptdelete + MPDB.RemovePath(dirname) return ####### # STEP 1 : list all files in directory ####### # This conversion is important for windows to get filenames in utf-8 encoding! if type(dirname).__name__ == "str": dirname = unicode(dirname, "utf-8") try: dirname = smart_unicode(dirname) try: listdir = oslistdir(dirname) except: listdir = oslistdir(dirname.encode("utf-8")) # pretty stupid, but is a must. for index in range(len(listdir)): listdir[index] = smart_unicode(listdir[index]) except: print_exc() MPDB.log("Error while trying to get directory content", MPDB.LOGERROR) listdir = [] ####### # STEP 2 : Keep only the files with extension... ####### for f in listdir: if splitext(f)[1].upper() in listext: listfolderfiles.append(f) # on récupère la liste des fichiers entrées en BDD pour le dossier en cours listDBdir = MPDB.DB_listdir(dirname) # --> une requête pour tout le dossier ####### # STEP 3 : If folder contains pictures, create folder in database ####### # on ajoute dans la table des chemins le chemin en cours PFid = MPDB.DB_folder_insert( basename(dirname) or osdirname(dirname).split(separator)[-1], dirname, parentfolderID, listfolderfiles and "1" or "0", # i ) if listfolderfiles: # si le dossier contient des fichiers jpg... ####### # STEP 4 : browse all pictures ####### # puis on parcours toutes les images du dossier en cours for picfile in listfolderfiles: # ... on parcours tous les jpg du dossier extension = splitext(picfile)[1].upper() if ( extension in vidsext and Addon.getSetting("usevids") == "false" ): # si une video mais qu'on ne prend pas les vidéos if picfile in listDBdir: listDBdir.pop(listDBdir.index(picfile)) continue # alors on ne fait rien et on reprend la boucle if file_is_accessible(dirname, picfile): cptscanned = cptscanned + 1 cpt = cpt + 1 else: MPDB.DB_del_pic(dirname, picfile) cptdelete = cptdelete + 1 ###if updatefunc and updatefunc.iscanceled(): return#dialog progress has been canceled # on enlève l'image traitée de listdir if len(listdir) > 0: listdir.pop(listdir.index(picfile)) if not rescan: # si pas de rescan # les images ne sont pas à scanner de force if picfile in listDBdir: # si l'image est déjà en base # l'image est déjà en base de donnée if updatepics: # si le paramètre est configuré pour mettre à jour les metas d'une photo # Il faut mettre à jour les images... if extension in vidsext: DoScan = True update = True straction = __language__(30242) # Updating if file_is_accessible(dirname, picfile): cptchanged = cptchanged + 1 elif not ( MPDB.fileSHA(join(dirname, picfile)) == MPDB.getFileSha(dirname, picfile) ): # si l'image a changé depuis qu'elle est en base # Scan les metas et ajoute l'image avec un paramètre de mise à jour = true DoScan = True update = True straction = __language__(30242) # Updating if file_is_accessible(dirname, picfile): cptchanged = cptchanged + 1 else: DoScan = False straction = __language__(30243) # "Passing" # mais l'image n'a pas changée. Donc on passe else: DoScan = False straction = __language__(30243) # "Passing" # mais on ne met pas à jour les photos. Donc on passe else: DoScan = True update = False straction = __language__(30244) # "Adding" if file_is_accessible(dirname, picfile): comptenew = comptenew + 1 # l'image n'est pas dans la base. On l'ajoute maintenant avec paramètre de mise à jour = false else: DoScan = True update = True straction = __language__(30245) # "Rescan" # on rescan les photos donc on ajoute l'image avec paramètre de mise à jour = true if updatefunc and totalfiles != 0 and cptroots != 0: updatefunc.update( int(100 * float(cptscanned) / float(totalfiles)), # cptscanned-(cptscanned/100)*100, # cptscanned/100, int(100 * float(iroots) / float(cptroots)), __language__(30000) + "[%s] (%0.2f%%)" % (straction, 100 * float(cptscanned) / float(totalfiles)), # "MyPicture Database [%s] (%0.2f%%)" picfile, ) if DoScan and file_is_accessible(dirname, picfile): try: modifiedtime = str(stat(join(dirname, picfile)).st_mtime) except: modifiedtime = str(stat(join(dirname.encode("utf-8"), picfile.encode("utf-8"))).st_mtime) picentry = { "idFolder": PFid, "strPath": dirname, "strFilename": picfile, "UseIt": 1, "sha": extension in picsext and str(MPDB.fileSHA(join(dirname, picfile))) or extension in vidsext and "1", # "DateAdded":dateadded, "DateAdded": strftime("%Y-%m-%d %H:%M:%S"), "mtime": modifiedtime, "ftype": extension in picsext and "picture" or extension in vidsext and "video" or "", } # get the meta tags try: if not extension in vidsext: picentry.update(get_metas(dirname, picfile)) # insert picture into table files try: for index in picentry: if ( isinstance(picentry[index], str) == False and isinstance(picentry[index], unicode) == False and isinstance(picentry[index], int) == False and isinstance(picentry[index], long) == False and isinstance(picentry[index], float) == False ): picentry[index] = "" # if isinstance(picentry['EXIF ExifVersion'], str) == False: # picentry['EXIF ExifVersion'] = "" MPDB.DB_file_insert(dirname, picfile, picentry, update) except MPDB.MyPictureDB: print "Error in " + smart_unicode(dirname).encode("utf-8") + " File:" + smart_unicode( picfile ).encode("utf-8") print "Parameter set start" print picentry print "Parameter set end" pass except: print_exc() if picfile in listDBdir: listDBdir.pop(listDBdir.index(picfile)) # Now if the database contain some more pictures assign for this folder, we need to delete them if 'update' setting is true if ( listDBdir ): # and updatepics: #à l'issu si listdir contient encore des fichiers, c'est qu'ils sont en base mais que le fichier n'existe plus physiquement. for f in listDBdir: # on parcours les images en DB orphelines cptdelete = cptdelete + 1 if updatefunc and totalfiles != 0 and cptroots != 0: updatefunc.update( int(100 * float(cptscanned) / float(totalfiles)), # cptscanned-(cptscanned/100)*100, # cptscanned/100, int(100 * float(iroots) / float(cptroots)), __language__(30000) + "[" + __language__(30246) + "]", # MyPicture Database [Removing] f, ) MPDB.DB_del_pic(dirname, f) MPDB.log( "\t%s has been deleted from database because the file does not exists in this folder. " % f ) # f.decode(sys_enc)) MPDB.log("") else: MPDB.log("This folder does not contain any picture :") MPDB.log(dirname) MPDB.log("") if cpt: MPDB.log("%s new pictures found in %s" % (str(cpt), dirname), MPDB.LOGNOTICE) # unicode(info.data[k].encode("utf8").__str__(),"utf8") compte = compte + cpt cpt = 0 if recursive: # gestion de la recursivité. On rappel cette même fonction pour chaque dossier rencontré MPDB.log("scan the subfolders of :", MPDB.LOGNOTICE) MPDB.log(dirname, MPDB.LOGNOTICE) for item in listdir: try: joineddir = join(dirname, item) except: joineddir = join(dirname.encode("utf-8"), item.encode("utf-8")) joineddir = smart_unicode(joineddir) try: isjoineddir = isdir(joineddir) except: isjoineddir = isdir(joineddir.encode("utf-8")) if isjoineddir: # un directory # browse_folder(dirname,parentfolderID=None,recursive=True,updatepics=False,rescan=False,updatefunc=None) browse_folder(joineddir, PFid, recursive, updatepics, addpics, delpics, rescan, updatefunc, dateadded) else: # listdir contenait un fichier mais pas un dossier # inutilisé... on passe pour le moment pass
def load_map(self): #google geolocalisation static_url = "http://maps.google.com/maps/api/staticmap?" param_dic = {#location parameters (http://gmaps-samples.googlecode.com/svn/trunk/geocoder/singlegeocode.html) "center":"", #(required if markers not present) "zoom":self.zoomlevel, # 0 to 21+ (req if no markers #map parameters "size":"640x640", #widthxheight (required) "format":"jpg", #"png8","png","png32","gif","jpg","jpg-baseline" (opt) "maptype":"hybrid", #"roadmap","satellite","hybrid","terrain" (opt) "language":"", #Feature Parameters: "markers" :"color:red|label:P|%s",#(opt) #markers=color:red|label:P|lyon|12%20rue%20madiraa|marseille|Lille #&markers=color:blue|label:P|Australie "path" : "", #(opt) "visible" : "", #(opt) #Reporting Parameters: "sensor" : "false" #is there a gps on system ? (req) } param_dic["markers"]=param_dic["markers"]%self.place request_headers = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10' } request = Request(static_url+urlencode(param_dic), None, request_headers) try: urlfile = urlopen(request) except: dialog = xbmcgui.Dialog() dialog.ok('XBMC Network Error', 'Google maps is not reachable') self.close() return extension = urlfile.info().getheader("Content-Type","").split("/")[1] filesize = int(urlfile.info().getheader("Content-Length","")) mappath = xbmc.translatePath(self.DATA_PATH) mapfile = join(self.DATA_PATH,basename(self.picfile).split(".")[0]+"_maps%s."%self.zoomlevel+extension) mapfile = xbmc.translatePath(mapfile) # test existence of path if not os.path.exists(mappath): os.makedirs(mappath) if not isfile(mapfile): #mapfile is not downloaded yet, download it now... try: #f=open(unicode(mapfile, 'utf-8'),"wb") f=open(decoder.smart_unicode(mapfile), "wb") except: try: f=open(decoder.smart_utf8(mapfile), "wb") except: print_exc() #print "GEO Exception: "+mapfile for i in range(1+(filesize/10)): f.write(urlfile.read(10)) self.lbl_info.setLabel(__language__(30221)%(100*(float(i*10)/filesize)))#getting map... (%0.2f%%) urlfile.close() #pDialog.close() try: f.close() except: print_exc() pass self.set_pic(self.picfile) self.set_map(mapfile) self.lbl_info.setLabel(__language__(30222)%int(100*(float(self.zoomlevel)/self.ZMAX)))#Zoom level %s
def main2(): # get active window import optparse global cptroots, iroots parser = optparse.OptionParser() parser.enable_interspersed_args() parser.add_option("--database", "-d", action="store_true", dest="database", default=False) # parser.add_option("--help","-h") parser.add_option("-p", "--rootpath", action="store", type="string", dest="rootpath") parser.add_option("-r", "--recursive", action="store_true", dest="recursive", default=False) parser.add_option("-u", "--update", action="store_true", dest="update", default=True) (options, args) = parser.parse_args() # dateadded = strftime("%Y-%m-%d %H:%M:%S")#pour inscrire la date de scan des images dans la base if options.rootpath: options.rootpath = ( decoder.smart_utf8(unquote_plus(options.rootpath)) .replace("\\\\", "\\") .replace("\\\\", "\\") .replace("\\'", "'") ) # print "options.rootpath = " + smart_unicode(options.rootpath).encode('utf-8') scan = AddonScan() scan.create(__language__(30000)) cptroots = 1 iroots = 1 scan.update( 0, 0, __language__(30000) + " [" + __language__(30241) + "]", # MyPicture Database [preparing] __language__(30247), ) # please wait... count_files(unquote_plus(options.rootpath), recursive=options.recursive) try: # browse_folder(dirname,parentfolderID=None,recursive=True,updatepics=False,addpics=True,delpics=True,rescan=False,updatefunc=None) # browse_folder(unquote_plus(options.rootpath),parentfolderID=None,recursive=options.recursive,updatepics=options.update,addpics=True,delpics=True,rescan=False,updatefunc=scan,dateadded = dateadded ) browse_folder( unquote_plus(options.rootpath), parentfolderID=None, recursive=options.recursive, updatepics=True, addpics=True, delpics=True, rescan=False, updatefunc=scan, dateadded=strftime("%Y-%m-%d %H:%M:%S"), ) # dateadded ) except: print_exc() scan.close() if options.database: # print "options.database" listofpaths = MPDB.RootFolders() if listofpaths: scan = AddonScan() # xbmcgui.getCurrentWindowId() scan.create(__language__(30000)) # MyPicture Database scan.update( 0, 0, __language__(30000) + " [" + __language__(30241) + "]", # MyPicture Database [preparing] __language__(30247), ) # please wait... # comptage des fichiers et des dossiers à parcourir for path, recursive, update, exclude in listofpaths: if exclude == 0: cptroots = cptroots + 1 count_files(unquote_plus(path), False) # print "cptroots" # print cptroots for path, recursive, update, exclude in listofpaths: if exclude == 0: # count_files(unquote_plus(path)) try: # browse_folder(dirname,parentfolderID=None,recursive=True,updatepics=False,rescan=False,updatefunc=None) iroots = iroots + 1 browse_folder( unquote_plus(path), parentfolderID=None, recursive=recursive == 1, updatepics=update == 1, addpics=True, delpics=True, rescan=False, updatefunc=scan, dateadded=strftime("%Y-%m-%d %H:%M:%S"), ) # dateadded) except: print_exc() scan.close()