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 = "video"' return WebFunc.jsonResult({'videos': _formatRet(sqlStr, 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, videos = UtilFunc.walkFolder(path, 'video', params) return WebFunc.jsonResult({'folders': folders, 'videos': videos}) elif intent == 'thumbnail': if len(arg) < 2: raise cherrypy.HTTPError(460, 'Bad Parameter') tempThumbImage = UtilFunc.getPictureHashPath(''.join(arg[1:])) if not tempThumbImage or not os.path.exists(tempThumbImage): raise cherrypy.HTTPError(464, 'Not Exist') return static.serve_download(tempThumbImage) elif intent == 'stream': return UtilFunc.mediaPlay(''.join(arg[1:])) else: raise cherrypy.HTTPError(460, 'Bad Parameter')
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 GET(self, *arg, **params): if not arg: return WebFunc.jsonResult({'errCode': 460}) if arg[0] == 'download': return self._downloadShare(self._getLocaltion(arg[1:])) elif arg[0] == 'info': return WebFunc.jsonResult( self._fileList(self._getLocaltion(arg[1:]), params)) else: return WebFunc.jsonResult(_getShare(arg[0], params))
def _getTraversalResult(self, arg, params): id = WebFunc.checkId(arg, self.traversalMap) start = int(params.get('offset', 0)) limit = int(params.get('limit', -1)) try: ret = [] end = 0 traversalInfo = self.traversalMap[id]['info'] traversalInfo['lastTime'] = int(time.time()) if limit > 0: end = start + limit result = ProfileFunc.getTraversalTBWithId(id, start, end) resultLen = len(result) if resultLen < limit: limit = resultLen end = start + limit ProfileFunc.delTraversalTBWithId(id, end) traversalInfo['start'] = end Log.info( 'Get TraversalFolder Result:start[%d], limit[%d], count[%d]' % (start, limit, len(result))) return WebFunc.jsonResult({'files':result, 'finish':traversalInfo['finished'], \ 'fileCount':traversalInfo['fileCount'], 'folderCount':traversalInfo['folderCount']}) except Exception, e: Log.error("Get Traversal Folder Result Failed! Reason[%s]" % e) return cherrypy.HTTPError(462, 'Operation Failed')
def _downloadShare(self, path): if not os.path.exists(path): return WebFunc.jsonResult({'errCode': 464}) if os.path.isdir(path): folderPath = ProfileFunc.slashFormat(path) filename = os.path.basename(folderPath) filename = filename + '.zip' request = cherrypy.serving.request filename = UtilFunc.StringUrlEncode(filename) response = cherrypy.response response.headers['Content-Type'] = 'application/zip' response.headers['Last-Modified'] = time.time() User_Agent = request.headers.get('User-Agent') if 'Firefox' in User_Agent: response.headers[ 'Content-Disposition'] = 'attachment;filename*="%s"' % filename else: response.headers[ 'Content-Disposition'] = 'attachment;filename="%s"' % filename zipobj = ZipStream(folderPath) return zipobj.__iter__() else: filename = os.path.basename(path) filename = UtilFunc.StringUrlEncode(filename) return PostStatic.serve_download(path, filename)
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 _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, **params): return WebFunc.jsonResult({'deviceType' : UtilFunc.getDeviceType(), 'serverVersion' : PopoConfig.VersionInfo, 'system' :'Linux/PopoBox', 'systemVersion' : UtilFunc.getSystemVersion(), 'ImgVersion' : UtilFunc.getIMGVersion()['ver'], 'hardwareVersion': PopoConfig.Hardware, 'ecsVersion' : ProfileFunc.getMainServer().ecsModule.version() if hasattr(ProfileFunc.getMainServer(), 'ecsModule') else 'NoECS', })
def _getContactsById(self, phoneId): path = os.path.join(getContactBackupDir(), phoneId) if not os.path.exists(path): raise cherrypy.HTTPError(464, 'Not Exist') result = [] count = self._getContactFolderInfo(result, path) result = sorted(result, key=lambda x: x['lastModify']) return WebFunc.jsonResult(result)
def _getAllContacts(self, arg): phoneId = ''.join(arg) if phoneId: return self._getContactsById(phoneId) result = [] self._getContactFolderInfo(result, getContactBackupDir()) result = sorted(result, key=lambda x: x['lastModify']) return WebFunc.jsonResult({'contacts': result})
def GET(self, *arg, **params): if arg: storageId = arg[0] if storageId == 'all': files = UtilFunc.getFileList(ProfileFunc.GetBoxDisks(), UtilFunc.getOptParamsInfo(params)) return WebFunc.jsonResult({'total':len(files),'files':files}) diskpath = ProfileFunc.getDiskById(storageId) if not diskpath: raise cherrypy.HTTPError(460, 'Bad Parameters') if 'mediaFolders' in arg: ret = ProfileFunc.getMainServer().scanFolderMoniter.getMediaFolder(params) return WebFunc.jsonResult(ret) else: return WebFunc.jsonResult(self._getStorageInfo(diskpath)) else: storages = [] for disk in ProfileFunc.GetBoxDisks(False): storages.append(self._getStorageInfo(disk)) return WebFunc.jsonResult({'storages':storages, 'status':ProfileFunc.getDiskStatus()})
def _isNeedUpgrade(self): ret = WebFunc.socketSend('127.0.0.1', 8888, 'is-need-upgrade') if ret: ret = ret.split(';') res = {'uptodate':UtilFunc.toBoolean(ret[0]) == False, 'version':'', 'description':'', 'force':ret[1]} return WebFunc.jsonResult(res) else: raise cherrypy.HTTPError(462, 'Operation Failed')
def _requestPubCamera(self, intent, args, param): if intent in self.cameraCtrl.getEventMethods(): result = self.cameraCtrl.dispatchEvent(intent, args, param) if intent == 'stream': return result if result.has_key('error_code') and str( result.get('error_code')) in error_code: err = result.get('error_code') raise cherrypy.HTTPError(err, error_code.get(err)) else: return WebFunc.jsonResult(result) raise cherrypy.HTTPError(486, "UNSUPPORTED_METHODS")
def GET(self, *arg, **params): extInfo = UtilFunc.getOptParamsInfo(params) intent = params.get('intent', None) if intent == 'traversal': return self._getTraversalResult(arg, params) elif intent == 'typeFile': return self._getLibraryGroupByType(params) elif arg and arg[0] == 'stream': return UtilFunc.mediaPlay(''.join(arg[1:])) path = self._formatPath(arg, params) if intent == 'props': return WebFunc.jsonResult(UtilFunc.getFileInfo( path, extInfo, True)) elif intent == 'folderZip': return WebFunc.DownloadFolderZip(path) if os.path.isdir(path): files = UtilFunc.getFileList(path, extInfo) else: headers = { key.lower(): val for key, val in cherrypy.request.headers.iteritems() } lastEtag = headers.get('if-none-match', None) etag = UtilFunc.getFileEtag(path) if lastEtag: if lastEtag == etag: cherrypy.response.status = 304 return matchEtag = headers.get('if-match', None) if matchEtag: if matchEtag != etag: raise cherrypy.HTTPError(412) return WebFunc.DownloadFile(path) return WebFunc.jsonResult({ 'total': len(files), 'files': files, 'offset': extInfo['offset'], 'limit': extInfo['limit'] })
def _getOneContact(self, arg, params): phoneId = ''.join(arg) filename = params.get('filename', '') if not phoneId or not filename: raise cherrypy.HTTPError(460, 'Bad Parameter') path = os.path.join(getContactBackupDir(), phoneId, filename) if not os.path.exists(path): raise cherrypy.HTTPError(464, 'Not Exist') ret = [] ret = VCardParser.vcf_parser(path) return WebFunc.jsonResult({"info": ret})
def GET(self, *arg, **params): app_name = ''.join(arg) if not app_name: ret = [] for app_name in self.services.keys(): ret.append(self._getAppInfo(app_name)) else: if not self.services.has_key(app_name): raise cherrypy.HTTPError(460, 'Bad Parameter') ret = self._getAppInfo(app_name) return WebFunc.jsonResult(ret)
def POST(self, *arg, **params): if not arg: raise cherrypy.HTTPError(460, 'Bad Parameter') intent = arg[0] if intent == 'info': paths = params.get('paths', None) paths = UtilFunc.strToList(paths) sqlStr = 'select url, name, remarks from fileCache where fileType = "music"' sqlStr += ' and url in (%s)' % ','.join( ['"' + k + '"' for k in paths]) return WebFunc.jsonResult({'songs': _formatRet(sqlStr, params)}) else: raise cherrypy.HTTPError(460, 'Bad Parameter')
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 _requestPubCLoud(self, intent, params): cloudargs = params.get('args',{'name':'baidu'}) try: if not isinstance(cloudargs,types.DictType): cloudargs = dict(eval(cloudargs.encode('utf-8'))) except: raise cherrypy.HTTPError(460, 'Bad Parameter') if intent in method_req.keys(): response = self.cloudstorage.handleHttpReq(method_req.get(intent), **cloudargs) response = json.loads(response) if str(response.get('error_code')) in error_code: err = response.get('error_code') raise cherrypy.HTTPError(err, error_code.get(err)) return WebFunc.jsonResult(response) raise cherrypy.HTTPError(486,"UNSUPPORTED_METHODS")
def _traversalFolder(self, path): if not path: raise cherrypy.HTTPError(460, 'Bad Parameter') if not os.path.exists(path): 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: traversalInfo = {} traversalInfo['path'] = '' traversalInfo['fileCount'] = 0 traversalInfo['folderCount'] = 0 traversalInfo['totalSize'] = 0 traversalInfo['finished'] = 0 traversalInfo['start'] = 0 traversalInfo['folder'] = '' traversalInfo['startTime'] = int(time.time()) traversalInfo['lastTime'] = int(time.time()) traversalInfo['success'] = 0 Log.info('Start Traversal Folder!!!!') uuidStr = None while True: uuidStr = str(uuid.uuid4()) if uuidStr not in self.traversalMap: ProfileFunc.initTraversalDB(uuidStr) traversalInfo['id'] = uuidStr thread = TraversalFolderThread(traversalInfo, path) threadStatus = TraversalFolderThreadStatus( traversalInfo, self.traversalMap) self.traversalMap[uuidStr] = { 'thread': thread, 'threadStatus': threadStatus, 'info': traversalInfo } thread.start() threadStatus.start() break cherrypy.response.status = 202 return WebFunc.jsonResult({"id": uuidStr}) except Exception, e: Log.error("Traversal Folder Failed! Reason[%s]" % e) raise cherrypy.HTTPError(462, 'Operation Failed')
def POST(self, *arg, **params): if not arg: raise cherrypy.HTTPError(460, 'Bad Parameters') storageId = arg[0] if not ProfileFunc.GetBoxDisks() or not storageId in ProfileFunc.getStorageIds(): raise cherrypy.HTTPError(465, 'Not Exist Disk') folders, delpaths = params.get('folders',[]), params.get('except',[]) if not folders and not delpaths: raise cherrypy.HTTPError(460, 'Bad Parameter') folders = UtilFunc.strToList(folders) delpaths = UtilFunc.strToList(delpaths) ret = ProfileFunc.getMainServer().scanFolderMoniter.setMediaFolder(folders,delpaths) cherrypy.response.status = 205 return WebFunc.jsonResult(ret)
def _getContactCount(self, arg, params): phoneId = ''.join(arg) if not phoneId: raise cherrypy.HTTPError(460, 'Bad Parameter') path = os.path.join(getContactBackupDir(), phoneId) if not os.path.exists(path): raise cherrypy.HTTPError(464, 'Not Exist') result = [] count = self._getContactFolderInfo(result, path) if count != 0: new_backup = max(result, key=lambda x: x['lastModify']) path = new_backup['url'] count = VCardParser.getCount(path) return WebFunc.jsonResult({'count': count, 'path': path})
def GET(self, *arg, **params): intent = params.get('intent', None) if not intent: raise cherrypy.HTTPError(460, 'Bad Parameter') elif intent == 'config': conPath = self.ssm.get_client_conf() if conPath and os.path.exists(conPath): return PostStatic.serve_download(conPath, os.path.basename(conPath)) else: raise cherrypy.HTTPError(464, 'Not Exist') elif intent == 'status': conPath = self.ssm.get_client_conf() lastModify = None if conPath and os.path.exists(conPath): lastModify = os.path.getmtime(conPath) return WebFunc.jsonResult({'status':self.ssm.check_state(),'lastModify':lastModify}) else: raise cherrypy.HTTPError(460, 'Bad Parameter')
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})
def POST(self, *arg, **params): path = UtilFunc.formatPath(arg) if not path: path = params.get('path', '') isPrivate = UtilFunc.toBoolean(params.get('isPrivate', True)) validity = int(params.get('validity', -1)) if not path: raise cherrypy.HTTPError(460, 'Bad Parameter') if PopoConfig.PlatformInfo == 'Box' and not UtilFunc.getDiskPath(path): raise cherrypy.HTTPError(465, 'Not Exist Disk') if not os.path.exists(path): raise cherrypy.HTTPError(464, 'Not Exist') shareId, access = UtilFunc.createShare(path, validity, isPrivate) cherrypy.response.status = 201 return WebFunc.jsonResult( _getShare(shareId, {'extractionCode': access}))
def _delfromlabel(self, params): imagepaths = params.get('imagePaths', []) imagefolder = params.get('name', '') if not imagepaths or not imagefolder: raise cherrypy.HTTPError(460, 'Bad Parameter') imagepaths = UtilFunc.strToList(imagepaths) del_num = 0 del_path = [] for imagepath in imagepaths: if not os.path.exists(imagepath) or not UtilFunc.isPicturePath( imagepath): continue del_num += 1 del_path.append(imagepath) SqlStr = "delete from fileCache where url=? and label=?" ProfileFunc.execAllScanFolderSql(SqlStr, ( imagepath, imagefolder, )) return WebFunc.jsonResult({"total": del_num, "removePaths": del_path})
def POST(self, **params): action = params.get('action', '') files = params.get('files', []) onExist = params.get('onExist', 'rename') if not action or not files: raise cherrypy.HTTPError(460, 'Bad Parameters') files = UtilFunc.strToList(files) if not ProfileFunc.GetBoxDisks(): raise cherrypy.HTTPError(465, 'Not Exist Disk') target = params.get('target', '') if action != 'delete': target = params.get('target', '') if not target: Log.error("Operate File Failed, target is None!!!!") raise cherrypy.HTTPError(460, 'Bad Parameters') target = ProfileFunc.slashFormat(target) if UtilFunc.isLinuxSystem(): if UtilFunc.isLinuxDiskReadOnly(target): raise cherrypy.HTTPError(463, 'Not Permitted') if UtilFunc.isLowDiskSpace(target): raise cherrypy.HTTPError(467, 'Not Enough Disk Space') info = {} info['totalFiles'] = len(files) info['successFiles'] = 0 info['finishedFiles'] = 0 info['skipedFiles'] = 0 info['error'] = [] info['finished'] = 0 uuidStr = str(uuid.uuid4()) self.operateMap[uuidStr] = info thread = BatchThread(info, files, action, target, onExist) thread.start() cherrypy.response.status = 202 return WebFunc.jsonResult({"id": uuidStr})
def _setlabel(self, params): imagepaths = params.get('imagePaths', []) imagefolder = params.get('name', '') if not imagepaths or not imagefolder: raise cherrypy.HTTPError(460, 'Bad Parameter') imagepaths = UtilFunc.strToList(imagepaths) image_num = 0 image_path = [] for imagepath in imagepaths: if not os.path.exists(imagepath) or not UtilFunc.isPicturePath( imagepath): continue hash_value = UtilFunc.getMd5Name(imagepath, PopoConfig.MinWidth, PopoConfig.MinHeight) modifyTime = int(time.time()) size = os.path.getsize(imagepath) SqlStr = "replace into fileCache(fileType, url, hash, lastModify,\ groupTime, contentLength, label) values(?,?,?,?,?,?,?)" disk = UtilFunc.getDiskPath(imagepath) need_conn = ProfileFunc.getConfDb(disk) if ProfileFunc._execSql(need_conn, SqlStr, ( 'picture', imagepath, hash_value, modifyTime, 'label', size, imagefolder, )): image_num += 1 image_path.append(imagepath) return WebFunc.jsonResult({ "total": image_num, "imagePaths": image_path })
def GET(self, *arg, **params): sid = WebFunc.checkId(arg, self.searchMap) start = int(params.get('offset', 0)) limit = int(params.get('limit', -1)) try: end = 0 searchInfo = self.searchMap[sid]['info'] searchInfo['lastTime'] = int(time.time()) if limit > 0: end = start + limit result = ProfileFunc.getSearchTBWithId(sid, start, end) resultLen = len(result) if resultLen < limit: limit = resultLen end = start + limit ProfileFunc.delSearchTBWithId(sid, end) searchInfo['start'] = end Log.info('Get Search Result: start[%d], limit[%d], count[%d]' % (start, limit, len(result))) return WebFunc.jsonResult({'files':result, 'finished':searchInfo['finished'], \ 'folderCount':searchInfo['folderCount'], 'fileCount':searchInfo['fileCount']}) except Exception, e: Log.error("Get Search Result Failed! Reason[%s]" % e) raise cherrypy.HTTPError(462, 'Operation Failed')
def _isImgUpToDate(self): ret = UtilFunc.getIMGVersion() return WebFunc.jsonResult({'uptodate':ret['upgrade'] == False, 'version':ret['ver']})