def optionTags(path, tags=[], action='add',fileType='picture'): # dbpath = UtilFunc.getDiskPath(path, True) # conn = getConfDb(dbpath) # cur = conn.cursor() # if not tags: # cur.execute('delete from fileCache where url = ?', (path,)) # conn.commit() # else: # for tag in tags: # if action == 'add': # sqlStr = 'replace into fileCache(url, fileType, tag) values(?, ? ,?)' # else: # sqlStr = 'delete from fileCache where url = ? and fileType = ? and tag = ?' # cur.execute(sqlStr, (path, fileType, tag,)) # conn.commit() # cur.close() # conn.close() if not tags: SqliteFunc.tableRemove('tags', 'url = ?', (path,)) else: for tag in tags: if action == 'add': sqlStr = 'replace into tags(url, fileType, tag) values(?, ? ,?)' else: sqlStr = 'delete from tags where url = ? and fileType = ? and tag = ?' SqliteFunc.execSql(sqlStr, (path, fileType, tag,))
def _updateFile(self, path, params): name = params.get('name', '') lastModify = params.get('lastModify', '') if name: newpath = os.path.join(os.path.dirname(path), name) if os.path.exists(newpath): raise cherrypy.HTTPError(469, 'Already Exist') os.rename(path, newpath) sqlStr = 'update fileCache set url = ?, name = ? where url = ?' #ProfileFunc.execSubLibrarySqlbyPath(path, sqlStr, (newpath, name, path,)) SqliteFunc.execSql(sqlStr, ( newpath, name, path, )) path = newpath if lastModify: UtilFunc.setFileTime(path, lastModify) sqlStr = 'update fileCache set lastModify =? where url = ?' #ProfileFunc.execSubLibrarySqlbyPath(path, sqlStr, (lastModify, path,)) SqliteFunc.execSql(sqlStr, ( lastModify, path, )) cherrypy.response.status = 205
def OnBrowser(self, evt): # In this case we include a "New directory" button. dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE #| wx.DD_DIR_MUST_EXIST #| wx.DD_CHANGE_DIR ) # If the user selects OK, then we process the dialog's data. # This is done by getting the path data from the dialog - BEFORE # we destroy it. add_path = '' if dlg.ShowModal() == wx.ID_OK: add_path = dlg.GetPath().replace('\\','/') self.scan_path.SetValue(add_path) # Only destroy a dialog after you're done with it. dlg.Destroy() if add_path: strSql = 'replace into folders(type, partpath, path, needScan, scanning) values(?,?,?,1,0)' SqliteFunc.execSql(strSql, ('all', UtilFunc.getDiskPath(add_path), add_path)) ProfileFunc.addToLibrary(add_path, True, 'all', True) #ProfileFunc.getMainServer().scanFolderMoniter.setMediaFolder([{'folder':add_path,'type':'all'}],[]) time.sleep(0.5) self.file_panels.showList()
def DELETE(self, *arg, **params): if arg: if arg[0] == 'tags': tags = params.get('tags',[]) filetype = params.get('fileType', 'picture') if not tags: raise cherrypy.HTTPError(460, 'Bad Parameter') tags = json.loads(tags) for tag in tags: #ProfileFunc.removeLabels(tag) SqliteFunc.tableRemove(SqliteFunc.TB_TAGS, 'tag = ? and fileType= ?', (tag,filetype,)) elif arg[0] == 'date': dates = params.get('dates',[]) if not dates:raise cherrypy.HTTPError(460, 'Bad Parameter') dates = json.loads(dates) for date in dates: photos = SqliteFunc.tableSelect(SqliteFunc.TB_CACHE, ['url'], 'groupTime = "%s"'%date) for photo in photos: if os.path.exists(photo['url']): os.remove(photo['url']) SqliteFunc.tableRemove(SqliteFunc.TB_CACHE, 'groupTime = "%s"'%date) else: raise cherrypy.HTTPError(460, 'Bad Parameter') cherrypy.response.status = 205 return
def delPath(self, evt=None): if UtilFunc.isWindowsSystem(): self.path = self.path.decode(defaultCode) if self.path != ProfileFunc.GetPictureFolder(): SqliteFunc.tableRemove(SqliteFunc.TB_FOLDER, 'path = ?',(self.path,)) ProfileFunc.removeFromLibrary(self.path) time.sleep(0.5) self.filepannel.showList()
def removeFromLibrary(path): mainServer = getMainServer() if UtilFunc.isWindowsSystem(): mainServer.folderMoniter.delFolder(path) mainServer.folderMoniter.notifyConfigChanged() #execSubLibrarySqlbyPath(path, "delete from fileCache where url like ?", (path+'/%',)) SqliteFunc.tableRemove(SqliteFunc.TB_CACHE, 'url like ?', (path+'/%',)) mainServer.scanFolderMoniter.removeFolder(path) SqliteFunc.execSql('delete from folders where path = ?',(path,))
def delFileCache(filePath): #ret = execSubLibrarySqlbyPath(filePath, 'select * from fileCache where url=?', (filePath,)) ret = SqliteFunc.tableSelect(SqliteFunc.TB_CACHE, [], 'url = ?', (filePath,)) if not ret: return None if len(ret) > 0: delThumbImage(filePath) #execSubLibrarySqlbyPath(filePath, 'delete from fileCache where url=?', (filePath,)) SqliteFunc.tableRemove(SqliteFunc.TB_CACHE, 'url = ?', (filePath,)) else: removeFolderCache(filePath)
def _deleteShare(ids): ids = UtilFunc.strToList(ids) sqlStr = ','.join(["'" + urlId + "'" for urlId in ids]) #ProfileFunc.execSharesSql("delete from shares where url in (%s)"%sqlStr) SqliteFunc.tableRemove( SqliteFunc.TB_SHARES, 'url in (%s)' % sqlStr, ) conn = ProfileFunc.getMsgChannel() msg = {'urlIds': ids} conn.send(msg, 0x0043)
def _getShares(self): #ret = ProfileFunc.execSharesSql('select * from shares') ret = SqliteFunc.tableSelect(SqliteFunc.TB_SHARES) shares = [] for share in ret: validity = _getvalidity(share['lastModify'], share['validity']) if not os.path.exists(share[2]) or ( validity <= 0 and str(share['validity']) != '-1'): #ProfileFunc.execSharesSql('delete from shares where id = ?',(share[0],)) SqliteFunc.tableRemove(SqliteFunc.TB_SHARES, 'id = ?', (share[0], )) continue shares.append(_formatShare(share)) return shares
def insertToSubLibrary(savePath, fileType, filePath, remarks): modifyTime = os.path.getmtime(filePath) group = time.strftime('%Y-%m', time.localtime(modifyTime)) size = os.path.getsize(filePath) ret = SqliteFunc.tableInsert(SqliteFunc.TB_CACHE, ['fileType', 'url', 'folder', 'name', 'lastModify', 'contentLength', \ 'remarks', 'groupTime'], (fileType, filePath.replace('\\','/'), os.path.dirname(filePath), \ os.path.basename(filePath), modifyTime, size, remarks, group, ), True)
def GET(self, *arg, **params): if not arg: raise cherrypy.HTTPError(460, 'Bad Parameter') if arg[0] in ['date','folders','tags']: if len(arg) > 1: return self._getGroupFiles(arg[0],arg[1:], params) else: return self._getImageGroup(arg[0], params) elif arg[0] == 'thumbnail': if len(arg) < 2: raise cherrypy.HTTPError(460, 'Bad Parameter') return self._getThumbImage(UtilFunc.getPictureHashPath(''.join(arg[1:])), '.jpg') elif arg[0] == 'create': if len(arg) < 2: raise cherrypy.HTTPError(460, 'Bad Parameter') path = UtilFunc.formatPath(arg[1:]) size = int(params.get('size', 170)) (tempThumbImage,ext) = thumbnail.getThumbNailImage(path,size) return self._getThumbImage(tempThumbImage, ext) elif arg[0] == 'all': ret = UtilFunc.formatPhotoRet(SqliteFunc.execFileCacheTags(), params) return WebFunc.jsonResult({'photos': ret}) else: return self._getAutoUploads(arg[0])
def GetBoxDisks(root=True): disks = [] if UtilFunc.isPCMode(): for disk in SqliteFunc.tableSelect(SqliteFunc.TB_FOLDER, ['path']): path = UtilFunc.getDiskPath(unicode(disk['path'])) if root else unicode(disk['path']) if not path in disks: disks.append(path) elif PopoConfig.Hardware == "1.0": list_files = os.listdir('/mnt/disks') list_files.sort() for part in list_files: path = os.path.join('/mnt/disks', part) if os.path.isdir(path) and not isNoFormatDisk(path): disks.append(path) elif PopoConfig.BoardSys == 'android': for nodeDir in [a for a in os.listdir('/' + PopoConfig.MntName) if a.startswith(PopoConfig.UsbRoot)]: disks += UtilFunc.getAndroidMountPaths(nodeDir) disks += UtilFunc.getAndroidMountPaths('sata') return disks else: list_files = os.listdir('/popobox') for folder in list_files: if "disk" in folder: disk_files = os.listdir('/popobox/' + folder) for part in disk_files: if "part" in part: path = '/mnt/' + folder + '/' + part disks.append(path) disks.sort() return disks
def _delNotExistImageThumb(self, disk): #files = ProfileFunc.execSubLibrarySqlbyPath(disk, 'select remarks from fileCache where fileType = "picture" or fileType = "video"', None) files = SqliteFunc.execSql( 'select remarks from fileCache where fileType = ? or fileType = ?', ( 'picture', 'video', )) hash_list = [] if not files: return for fileInfo in files: remarks = json.loads(fileInfo['remarks']) hash_list.append(remarks['thumbnail-small']) hash_list.append(remarks['thumbnail-large']) thumbImage_path = os.path.join(UtilFunc.getDiskPath(disk, True), ".popoCloud/ThumbImage").replace( "\\", "/") try: for folder in os.listdir(thumbImage_path): folder_path = os.path.join(thumbImage_path, folder).replace("\\", "/") if not os.path.isdir(folder_path): continue for thunmbNail in os.listdir(folder_path): file_path = os.path.join(folder_path, thunmbNail).replace("\\", "/") if not thunmbNail in hash_list: os.remove(file_path) if not os.listdir(folder_path): os.rmdir(folder_path) except Exception, e: Log.error("DelNotExistImageThumb Failed! Reason[%s]" % e)
def _getGroupFiles(self, groupType, groupValue, params): if groupType == 'tags': files = SqliteFunc.execFileCacheTags(' and a.tag = "%s"'%groupValue[0], False, params = params) elif groupType == 'folders': folder = UtilFunc.formatPath(groupValue) if not os.path.isdir(folder): raise cherrypy.HTTPError(460, 'Bad Parameter') folders, photos = UtilFunc.walkFolder(folder, 'picture', params) return WebFunc.jsonResult({'folders':folders,'photos':photos}) elif groupType == 'date': files = SqliteFunc.execFileCacheTags(' and a.groupTime = "%s"'%groupValue[0], params = params) else: raise cherrypy.HTTPError(460, 'Bad Parameter') return WebFunc.jsonResult({'photos':UtilFunc.formatPhotoRet(files, {})})
def GET(self, *arg, **params): if not arg: raise cherrypy.HTTPError(460, 'Bad Parameter') intent = arg[0] if intent == 'all': sqlStr = 'select url, name, remarks from fileCache where fileType = "music"' return WebFunc.jsonResult({'songs': _formatRet(sqlStr, params)}) elif intent in ['albums', 'artists', 'genres']: key = ''.join(arg[1:]) if key: sqlStr = "select url, name, remarks from fileCache where fileType = 'music'" ret = [ x for x in _formatRet(sqlStr, {}) if str(x.get(intent[:-1], '')) == key ] return WebFunc.jsonResult( {'songs': UtilFunc.orderAndLimit(ret, params)}) else: ret = [] tempList = [] sqlStr = 'select remarks from fileCache where fileType = "music"' sqlret = SqliteFunc.execSql(sqlStr) for onefile in sqlret: remarks = json.loads(onefile['remarks']) if not remarks: continue if intent == 'albums': if remarks[ 'album'] and not remarks['album'] in tempList: tempList.append(remarks['album']) ret.append({ 'title': remarks['album'], 'artist': remarks['artist'], 'year': remarks['year'], 'composer': remarks['composer'], 'genre': remarks['genre'] }) else: if remarks[intent[:-1]] and not remarks[ intent[:-1]] in ret: ret.append(remarks[intent[:-1]]) return WebFunc.jsonResult( {intent: UtilFunc.orderAndLimit(ret, params)}) elif intent == 'folders': path = UtilFunc.formatPath(arg[1:]) if not path or not os.path.exists(path): raise cherrypy.HTTPError(464, 'Not Exist') if not os.path.isdir(path): raise cherrypy.HTTPError(460, 'Bad Parameter') folders, songs = UtilFunc.walkFolder(path, 'music', params) return WebFunc.jsonResult({'folders': folders, 'songs': songs}) elif intent == 'stream': return UtilFunc.mediaPlay(''.join(arg[1:])) else: raise cherrypy.HTTPError(460, 'Bad Parameter')
def getLibraryFolderInfo(ftype = 'all'): ret = SqliteFunc.tableSelect(SqliteFunc.TB_FOLDER, [], 'type=?', (ftype,)) folders = [] for folder in ret: folders.append({ 'path': UtilFunc.toLinuxSlash(folder['path']), 'folderId':folder['id'], 'scanning':folder['scanning'], }) return folders
def _remove(self, all_del_set, flag=False): for fullpath in all_del_set: del_scan_path = UtilFunc.getSiteRoot(fullpath) if flag: ProfileFunc._execSql(ProfileFunc.getConfDb(UtilFunc.getDiskPath(fullpath)),\ "delete from mediafolder where url=?", (del_scan_path, )) ProfileFunc._execSql(ProfileFunc.getConfDb(UtilFunc.getDiskPath(fullpath)),\ "delete from selectfolder where url=?", (del_scan_path, )) del_scan_path_like = del_scan_path + '/%' ProfileFunc._execSql(ProfileFunc.getConfDb(UtilFunc.getDiskPath(fullpath)),\ "delete from mediafolder where url like ?", (del_scan_path_like, )) ProfileFunc._execSql(ProfileFunc.getConfDb(UtilFunc.getDiskPath(fullpath)),\ "delete from selectfolder where url like ?", (del_scan_path_like, )) SqliteFunc.execSql("delete from fileCache where folder like ?", (fullpath, )) if not self.stop_flag: ProfileFunc.removeFromLibrary(fullpath) else: break
def addShare(shareId, location, url, name, ext, isdir, access, validity, size): global _shareMutex _shareMutex.acquire() try: location = location.decode('utf-8') name = name.decode('utf-8') except: pass #ret = execSharesSql('select * from shares where shareId=?', (shareId,)) ret = SqliteFunc.tableSelect(SqliteFunc.TB_SHARES, [], 'shareId=?', (shareId,)) if not ret or len(ret) == 0: #ret = execSharesSql('insert into shares(shareId, location, url, name, contentType, isFolder, extractionCode, validity, contentlength, lastModify) values(?,?,?,?,?,?,?,?,?,?)', (shareId, location, url, name, ext, isdir, access, validity, size, UtilFunc.Now())) ret = SqliteFunc.tableInsert(SqliteFunc.TB_SHARES, ['shareId', 'location', 'url', 'name', 'contentType', 'isFolder', 'extractionCode', 'validity', 'contentlength', 'lastModify'],\ (shareId, location, url, name, ext, isdir, access, validity, size, UtilFunc.Now(),)) else: #ret = execSharesSql('update shares set location=?, url=?, name=?, contentType=?, isFolder=?, extractionCode=?, validity=?, contentlength=?, lastModify=? where shareId=?', (location, url, name, ext, isdir, access, validity, size, UtilFunc.Now(), shareId)) sqlStr = 'update shares set location=?, url=?, name=?, contentType=?, isFolder=?, extractionCode=?, validity=?, contentlength=?, lastModify=? where shareId=?' ret = SqliteFunc.execSql(sqlStr, (location, url, name, ext, isdir, access, validity, size, UtilFunc.Now(), shareId,)) _shareMutex.release() return ret
def getHashName(path, filePath): try: ret = SqliteFunc.tableSelect(SqliteFunc.TB_CACHE, ['remarks'], 'url=?', (filePath, )) hashs = [] for result in ret: remarks = json.loads(result['remarks']) if remarks['thumbnail-small'] not in hashs: hashs.append(remarks['thumbnail-small']) hashs.append(remarks['thumbnail-large']) return hashs except: return None
def _getLocaltion(self, arg): if not arg: return None id = arg[0] #share = ProfileFunc.execSharesSql('select location from shares where shareId=?', (id,)) share = SqliteFunc.tableSelect(SqliteFunc.TB_SHARES, ['location'], 'shareId=?', (id, )) if len(share) == 0: return None location = share[0]['location'] if arg[1:]: location = os.path.join(location, '/'.join(arg[1:])) return location
def scanDisks(parent): #ProfileFunc.initDB() SqliteFunc.initDBTables() try: if UtilFunc.isWindowsSystem(): import Win32FolderMoniter parent.folderMoniter = Win32FolderMoniter.FolderMoniter() elif UtilFunc.isDarwinSystem(): import DarwinFolderMoniter parent.folderMoniter = DarwinFolderMoniter.FolderMoniter() elif PopoConfig.PlatformInfo == 'Box': import BoxFolderMoniter if PopoConfig.BoardSys == 'android': parent.folderMoniter = BoxFolderMoniter.usbhostMoniter() else: parent.folderMoniter = BoxFolderMoniter.FolderMoniter() elif PopoConfig.PlatformInfo == 'Linux': import LinuxFolderMoniter parent.folderMoniter = LinuxFolderMoniter.FolderMoniter() parent.folderMoniter.start() except Exception,e: Log.exception('FolderMoniter Init Failed! Reason[%s]'%e)
def walkFolder(folder, type='picture', params={}): folders, files = [], [] for filename in os.listdir(folder): if isWindowsSystem(): filename = filename.decode('gbk') subfolder = os.path.join(folder, filename).replace('\\', '/').replace('//', '/') if os.path.isdir(subfolder): info = {'name': filename, 'url': subfolder} folders.append(info) else: continue folder = folder.decode('utf8').replace('\\', '/').replace('//', '/') if type in ['music', 'video']: # sqlStr = 'select * from fileCache where fileType = ? and folder = ?' # ret = ProfileFunc.execSubLibrarySqlbyPath(folder, sqlStr, (type,folder,)) ret = SqliteFunc.tableSelect(SqliteFunc.TB_CACHE, [], 'fileType = ? and folder = ?', ( type, folder, )) files = formatMediaRet(ret, {'order': params.get('order', None)}) elif type == 'picture': ret = SqliteFunc.execFileCacheTags(' and a.folder = "%s"' % folder) files = formatPhotoRet(ret, {'order': params.get('order', None)}) start = int(params.get('offset', 0)) limit = int(params.get('limit', -1)) if int(limit) != -1: folders = folders[start:(start + limit)] files = files[start:(start + limit)] else: folders = folders[start:] files = files[start:] return folders, files
def _getLibraryGroupByType(self, params): typeName = params.get('fileType', None) orderBy = params.get('orderBy', None) if not typeName or not typeName in (PopoConfig.filters.keys() + ['other']): raise cherrypy.HTTPError(460, 'Bad Parameter') if not ProfileFunc.GetBoxDisks(): raise cherrypy.HTTPError(465, 'Not Exist Disk') datas = SqliteFunc.tableSelect(SqliteFunc.TB_CACHE, [], 'fileType= ?', (typeName, ), params) return WebFunc.jsonResult({ 'fileType': typeName, 'datas': UtilFunc.formatFilesRet(datas, {}) })
def _getShare(id, params={}): #shares = ProfileFunc.execSharesSql('select * from shares where shareId=?', (id,)) shares = SqliteFunc.tableSelect(SqliteFunc.TB_SHARES, [], 'shareId=?', (id, )) if len(shares) == 0: return {'errCode': 464} else: share = shares[0] extractionCode = str(params.get('extractionCode', '')) if extractionCode != str(share['extractionCode']): return {'errCode': 461} if not os.path.exists(share['location']): _deleteShare(id) return {'errCode': 464} return _formatShare(share)
def _searchImages(self, params): start = int(params.get('offset', 0)) limit = int(params.get('limit', -1)) name = params.get('key', None) if not name or start < 0: raise cherrypy.HTTPError(460, 'Bad Parameter') files = SqliteFunc.execFileCacheTags(' and a.name like '%" + name + "%'') if limit == -1: file_info = files[start:] finished = 1 elif int(start) >= 0 and int(start+limit)<len(files): file_info= files[start:(start+limit)] finished = 0 elif int(start) >=0 and (start+limit) >= len(files): file_info = files[start:len(files)] finished = 1 ret = UtilFunc.formatPhotoRet(file_info, {'order':params.get('order',None)}) return WebFunc.jsonResult({'photos':ret,'finished':finished})
if statInfo: fileInfo['lastModify'] = getUtcTime(statInfo.st_mtime) fileInfo['creationTime'] = getUtcTime(statInfo.st_ctime) else: fileInfo['lastModify'] = 0 fileInfo['creationTime'] = 0 if os.path.isfile(fileFullPath): fileInfo['isFolder'] = 'False' fileInfo['contentLength'] = statInfo.st_size fileInfo['contentType'] = getFileExt(fileFullPath) fileInfo['ETag'] = getFileEtag(fileFullPath) fileInfo['id'] = encryptDesKey(fileFullPath) if flag: ProfileFunc.addFileCache(fileFullPath) ret = SqliteFunc.tableSelect(SqliteFunc.TB_CACHE, ['remarks'], 'url = ?', (fileFullPath, )) if ret: fileInfo['remarks'] = ret[0]['remarks'] else: fileInfo['isFolder'] = 'True' return fileInfo def formatFilesRet(datas, params): ret = [] for fileInfo in iter(datas): path = unicode(fileInfo['url']) if not os.path.exists(path): continue
def _formatRet(sqlStr, params): datas = SqliteFunc.execSql(sqlStr) return UtilFunc.formatMediaRet(datas, params)
def POST(self, *arg, **params): filetype = '.'.join(arg) folder = params.get('path', '/') keyword = params.get('term', None) if not ProfileFunc.GetBoxDisks(): raise cherrypy.HTTPError(465, 'Not Exist Disk') if not folder or not keyword: raise cherrypy.HTTPError(460, 'Bad Parameters') if filetype and filetype in PopoConfig.filters.keys(): #sqlStr = 'Select * from filecache where name like "%s" and fileType = "%s"'%('%' + keyword + '%', filetype,) datas = SqliteFunc.tableSelect(SqliteFunc.TB_CACHE, [], 'name like ? and fileType = ?', ( '%' + keyword + '%', filetype, )) return WebFunc.jsonResult( {'files': UtilFunc.formatFilesRet(datas, params)}) recursive = UtilFunc.toBoolean(params.get('recursive', True)) if UtilFunc.isSlash(folder): path = ProfileFunc.GetBoxDisks()[0] else: path = folder #folder = ProfileFunc.slashFormat(folder) if not os.path.exists(folder): raise cherrypy.HTTPError(464, 'Not Exist') if UtilFunc.isLinuxSystem(): if UtilFunc.isLinuxDiskReadOnly(path): raise cherrypy.HTTPError(463, 'Not Permitted') if UtilFunc.isLowDiskSpace(path): raise cherrypy.HTTPError(467, 'Not Enough Disk Space') try: searchInfo = {} searchInfo['path'] = '' searchInfo['folder'] = '' searchInfo['folderCount'] = 0 searchInfo['fileCount'] = 0 searchInfo['totalSize'] = 0 searchInfo['finished'] = 0 searchInfo['start'] = 0 searchInfo['startTime'] = int(time.time()) searchInfo['lastTime'] = int(time.time()) searchInfo['success'] = 0 Log.debug('Start Search!!!! folder[%s]' % folder) uuidStr = None while True: uuidStr = str(uuid.uuid4()) if uuidStr not in self.searchMap: ProfileFunc.initSearchDB(uuidStr) searchInfo['id'] = uuidStr thread = SearchThread(searchInfo, keyword, folder, recursive) statusThread = SearchStatusThread(searchInfo, self.searchMap) self.searchMap[uuidStr] = { 'thread': thread, 'statusThread': statusThread, 'info': searchInfo } thread.start() statusThread.start() break cherrypy.response.status = 202 return WebFunc.jsonResult({"id": uuidStr}) except Exception, e: Log.error("Search Failed! Reason[%s]" % e) raise cherrypy.HTTPError(462, 'Operation Failed')
def _getImageGroup(self, groupType, params): orderBy = params.get('order', None) limit = int(params.get('limit',1)) groupDict = {'date':'groupTime','folders':'folders','tags':'tag'} if not groupType in groupDict.keys(): raise cherrypy.HTTPError(460,'Bad Parameter') group_name = groupDict[groupType] scan_list_p = [] if group_name == 'folders' and not ProfileFunc.getAllMediaFolders(): raise cherrypy.HTTPError(464, 'Not Exist') if groupType == 'tags': #sqlStr = 'select tag, count(*) from (select * from fileCache where fileType="picture") group by tag' #groups = ProfileFunc.execAllScanFolderSql(sqlStr) sqlStr = 'select tag, count(*) from (select * from tags where fileType="picture") group by tag' groups = SqliteFunc.execSql(sqlStr) return WebFunc.jsonResult({'tags':[{'name':file['tag'],'total':file['count(*)']} for file in groups]}) elif groupType == 'folders': SqliteFunc.tableRemove(SqliteFunc.TB_CACHE, "folder is ''") scan_list= ProfileFunc.getAllSetFolders() for path_ele in set(scan_list): if not UtilFunc.is_sub_folder(path_ele, scan_list): scan_list_p.append(path_ele) ret_list_info = [] for ret_path in scan_list_p: if os.path.exists(ret_path): ret_list_info.append(ProfileFunc.dir_info(ret_path)) else: SqliteFunc.tableRemove(SqliteFunc.TB_CACHE, 'url=?', (ret_path,)) return WebFunc.jsonResult({'groupType' : group_name, 'folders' : UtilFunc.formatPhotoRet(ret_list_info, params)}) else: start = params.get('start', '1970-01') end = params.get('end', '9999-12') baseStr = 'select * from fileCache where fileType="picture" and groupTime >= "%s" and groupTime <="%s"'%(start,end) sqlStr = 'select groupTime, count(*) from (%s) group by groupTime order by lastModify asc'%baseStr #groups = SqliteFunc.execSql(sqlStr) groups = SqliteFunc.execSql(sqlStr) if not groups: for disk in ProfileFunc.GetBoxDisks(): if ProfileFunc.getMainServer().diskState.has_key(disk) and \ ProfileFunc.getMainServer().diskState[disk] == 2: raise cherrypy.HTTPError(463, 'Not Permitted') if UtilFunc.isLowDiskSpace(disk): raise cherrypy.HTTPError(467, 'Not Enough Disk Space') ret, ret_count, tmp_ret_dict = [], 0, {} for fileInfo in groups: if not tmp_ret_dict.has_key(fileInfo[group_name]): tmp_ret_dict[fileInfo[group_name]] = ret_count else: ret[tmp_ret_dict[fileInfo[group_name]]]['total'] += fileInfo['count(*)'] continue ret_count += 1 dbList = SqliteFunc.execFileCacheTags(' and a.%s = "%s"'%(group_name, fileInfo[group_name])) photos = UtilFunc.formatPhotoRet(dbList, params) if not photos: continue ret.append({'name' : fileInfo[group_name], 'total' : fileInfo['count(*)'], 'photos': photos}) if orderBy: cmpInfo = UtilFunc.httpArgToCmpInfo(orderBy) if len(cmpInfo) > 0 : ret.sort(lambda x,y: UtilFunc.dictInfoCmp(x, y, cmpInfo)) return WebFunc.jsonResult({groupType:ret})
def removeFolderCache(path): SqliteFunc.tableRemove(SqliteFunc.TB_CACHE, 'url like ?', (path + '/%',))