def GET(self, id=None): # Get list of sessions in JSON if id is None: path = os.path.join(absDir, "sessions/sessionList.JSON") return static.serve_file(path, "application/x-download", "attachment", os.path.basename(path)) elif id is not None: with open("sessions/sessionList.JSON") as jsonData: # printing a JSON file decodedData = json.load(jsonData) tempList = decodedData["sessions"] # scan json and check to see if id matches with existing session for item in tempList: #for entry in item: if item['idNo'] == id: if os.path.isfile( os.path.join("sessions/session_files/", id)): #check file exists print('session:', id, 'found') # get pickled session file and serve to client path = os.path.join( absDir, "sessions/session_files/%s" % id) return static.serve_file(path, "application/x-download", "attachment", os.path.basename(path)) #print('session file not found') else: print('session', id, 'not found') else: return ('No sessions with the ID %s' % id)
def default(self, id): safe_id = id if cherrypy.request.method == 'GET': is_streaming, filename = self.block_store.maybe_streaming_filename(safe_id) if is_streaming: cherrypy.response.headers['Pragma'] = 'streaming' try: response_body = serve_file(filename) return response_body except cherrypy.HTTPError as he: # The streaming file might have been deleted between calls to maybe_streaming_filename # and serve_file. Try again, because this time the non-streaming filename should be # available. if he.status == 404: is_streaming, filename = self.block_store.maybe_streaming_filename(safe_id) assert not is_streaming cherrypy.response.headers.pop(['Pragma'], None) return serve_file(filename) else: raise elif cherrypy.request.method == 'POST': url = self.block_store.store_raw_file(cherrypy.request.body, safe_id) return simplejson.dumps(url) else: raise cherrypy.HTTPError(405)
def default(self, id): safe_id = id if cherrypy.request.method == 'GET': filename = self.block_store.filename(safe_id) try: response_body = serve_file(filename) return response_body except cherrypy.HTTPError as he: if he.status == 404: response_body = serve_file( self.block_store.producer_filename(safe_id)) return response_body else: raise elif cherrypy.request.method == 'POST': request_body = cherrypy.request.body.read() new_ref = self.block_store.ref_from_string(request_body, safe_id) if self.backup_sender is not None: self.backup_sender.add_data(safe_id, request_body) #if self.task_pool is not None: # self.task_pool.publish_refs({safe_id : new_ref}) return simplejson.dumps(new_ref, cls=SWReferenceJSONEncoder) elif cherrypy.request.method == 'HEAD': if os.path.exists(self.block_store.filename(id)): return else: raise cherrypy.HTTPError(404) else: raise cherrypy.HTTPError(405)
def default(self, *args): # first, see if the url is in the url_file_mapping # dictionary file = url_file_mapping[os.sep.join(args)] if file: return serve_file(file) # next, try to find a listing page whose filename is the # same as its enclosing folder's name file = os.path.join(deploy_folder.path, os.sep.join(args), args[-1] + '.html') if os.path.isfile(file): return serve_file(file) # try each filename in LISTING_PAGE_NAMES setting for listing_name in settings.LISTING_PAGE_NAMES: file = os.path.join(deploy_folder.path, os.sep.join(args), listing_name + '.html') if os.path.isfile(file): return serve_file(file) # failing that, search for a non-listing page file = os.path.join(deploy_folder.path, os.sep.join(args[:-1]), args[-1] + '.html') if os.path.isfile(file): return serve_file(file) # failing that, page not found raise cherrypy.NotFound
def index(self, praca, strana): praca = praca.replace(" ", "+") if os.path.isfile(cache + praca + "page-" + strana + ".jpg"): return static.serve_file(cache + praca + "page-" + strana + ".jpg", content_type="image/jpeg", disposition=None, name=None) if len(accessed) > 100: oldest = None for k in accessed.keys(): if oldest is None or accessed[k] < accessed[oldest]: oldest = k os.popen("rm -r " + cache + oldest) accessed.pop(oldest) os.popen("mkdir -p " + cache + praca) for i in os.popen("ls /zkp" + praca).read().split("\n"): if "priloha" not in i: os.popen("/usr/sfw/bin/gs -dNOPAUSE -sDEVICE=jpeg -o " + cache + praca + "page-%03d.jpg -r144 /zkp" + praca + i) break accessed[praca] = datetime.now(tz=None) return static.serve_file(cache + praca + "page-" + strana + ".jpg", content_type="image/jpeg", disposition=None, name=None)
def default(self, id): safe_id = id if cherrypy.request.method == "GET": filename = self.block_store.filename(safe_id) try: response_body = serve_file(filename) return response_body except cherrypy.HTTPError as he: if he.status == 404: response_body = serve_file(self.block_store.producer_filename(safe_id)) return response_body else: raise elif cherrypy.request.method == "POST": request_body = cherrypy.request.body.read() new_ref = self.block_store.ref_from_string(request_body, safe_id) if self.backup_sender is not None: self.backup_sender.add_data(safe_id, request_body) # if self.task_pool is not None: # self.task_pool.publish_refs({safe_id : new_ref}) return simplejson.dumps(new_ref, cls=SWReferenceJSONEncoder) elif cherrypy.request.method == "HEAD": if os.path.exists(self.block_store.filename(id)): return else: raise cherrypy.HTTPError(404) else: raise cherrypy.HTTPError(405)
def stream(self, videoid): logging.debug("Received stream request for videoid: " + videoid) cachefile = self.cache.get(videoid) if cachefile is not None: if not cachefile.isprocessing: logging.debug("found in cache and is not processing") logging.debug("streaming file... " + cachefile.absfilepath) return serve_file(cachefile.absfilepath, cachefile.get_mimetype()) else: logging.debug("cache file with videoid {0} is currently processing".format(videoid)) return cherrypy.NotFound else: logging.debug("No file found in cache, caching new...") # TODO: change pafy api key video = pafy.new(videoid) bestaudio = video.getbestaudio(preftype="m4a") filename = videoid + "." + bestaudio.extension cachefile = self.cache.create(filename) cachefile.isprocessing = True logging.debug("downloading...") bestaudio.download(cachefile.absfilepath, remux_audio=True) logging.debug("downloading done") cachefile.isprocessing = False return serve_file(cachefile.absfilepath, cachefile.get_mimetype())
def fetchData(self): if self.data == 'OK': if 'Remote-Addr' in cherrypy.request.headers: remote_ip = cherrypy.request.headers['Remote-Addr'] elif 'X-Forwarded-For' in cherrypy.request.headers: remote_ip = cherrypy.request.headers['X-Forwarded-For'] # apache2 elif 'X-Host' in cherrypy.request.headers: remote_ip = cherrypy.request.headers['X-Host'] # lighthttpd else: remote_ip = cherrypy.request.remote.ip logger.debug('Received OPDS command from %s: %s %s' % (remote_ip, self.cmd, self.kwargs)) if self.cmd == 'search': if 't' in self.kwargs and self.kwargs['t'] in searchable: self.cmd = self.kwargs['t'] else: self.cmd = 'RecentBooks' methodToCall = getattr(self, "_" + self.cmd) _ = methodToCall(**self.kwargs) if self.img: return serve_file(self.img, content_type='image/jpeg') if self.file and self.filename: logger.debug('Downloading %s: %s' % (self.filename, self.file)) return serve_file(self.file, mimeType(self.filename), 'attachment', name=self.filename) if isinstance(self.data, string_types): return self.data else: cherrypy.response.headers['Content-Type'] = "text/xml" return lazylibrarian.webServe.serve_template(templatename="opds.html", title=self.data['title'], opds=self.data) else: return self.data
def index(self, name=None): if name is None: return ( "<!DOCTYPE html><html><body>Images will be here</body></html>") else: try: #(img_name,img_ext)=name.rsplit('.',1) finfo = self.qc_files[int(name)] path = os.path.abspath(finfo[0]) if finfo[3] == 'png': return serve_file(path, 'image/png', None, None) elif finfo[3] == 'jpg': return serve_file(path, 'image/jpeg', None, None) elif (finfo[3] == 'mnc' or finfo[3] == 'minc') and minc_supported: # dynamically render minc here img_file = self.tempdir + name + '.png' if not os.path.exists(img_file): qc(finfo[0], img_file, format='png') return serve_file(img_file, 'image/png', None, None) else: cherrypy.response.status = 503 return f"Unsupported image file format:{finfo[0]}" except: print(f"Exception in index:{sys.exc_info()[0]}") traceback.print_exc(file=sys.stdout) cherrypy.response.status = 503 return ("<!DOCTYPE html>" "<html>" f"<body>Image {name} not found!</body>" "</html>")
def fetchData(self): if self.data == 'OK': if 'X-Forwarded-For' in cherrypy.request.headers: remote_ip = cherrypy.request.headers['X-Forwarded-For'] # apache2 elif 'X-Host' in cherrypy.request.headers: remote_ip = cherrypy.request.headers['X-Host'] # lighthttpd elif 'Host' in cherrypy.request.headers: remote_ip = cherrypy.request.headers['Host'] # nginx elif 'Remote-Addr' in cherrypy.request.headers: remote_ip = cherrypy.request.headers['Remote-Addr'] else: remote_ip = cherrypy.request.remote.ip logger.debug('Received OPDS command from %s: %s %s' % (remote_ip, self.cmd, self.kwargs)) if self.cmd == 'search': if 't' in self.kwargs and self.kwargs['t'] in searchable: self.cmd = self.kwargs['t'] else: self.cmd = 'RecentBooks' methodToCall = getattr(self, "_" + self.cmd) _ = methodToCall(**self.kwargs) if self.img: return serve_file(self.img, content_type='image/jpeg') if self.file and self.filename: logger.debug('Downloading %s: %s' % (self.filename, self.file)) return serve_file(self.file, mimeType(self.filename), 'attachment', name=self.filename) if isinstance(self.data, string_types): return self.data else: cherrypy.response.headers['Content-Type'] = "text/xml" return lazylibrarian.webServe.serve_template(templatename="opds.html", title=self.data['title'], opds=self.data) else: return self.data
def static(self, name): if name.endswith('css'): return serve_file(os.path.join(CURRENT_DIR, 'stardog', 'endpoints', 'resources', 'static', name), content_type='text/css') if name.endswith('svg'): return serve_file(os.path.join(CURRENT_DIR, 'stardog', 'endpoints', 'resources', 'static', name), content_type='image/svg+xml')
def default(self, id): safe_id = id if cherrypy.request.method == 'GET': is_streaming, filename = self.block_store.maybe_streaming_filename( safe_id) if is_streaming: cherrypy.response.headers['Pragma'] = 'streaming' try: response_body = serve_file(filename) return response_body except cherrypy.HTTPError as he: # The streaming file might have been deleted between calls to maybe_streaming_filename # and serve_file. Try again, because this time the non-streaming filename should be # available. if he.status == 404: if not is_streaming: raise cherrypy.response.headers.pop('Pragma', None) is_streaming, filename = self.block_store.maybe_streaming_filename( safe_id) try: serve_file(filename) except cherrypy.HTTPError as he: if he.status == 416: raise cherrypy.HTTPError(418) else: raise elif he.status == 416: raise cherrypy.HTTPError(418) else: raise elif cherrypy.request.method == 'POST': if self.backup_sender is not None: request_body = cherrypy.request.body.read() url = self.block_store.store_raw_file( StringIO.StringIO(request_body), safe_id) self.backup_sender.add_data(safe_id, request_body) else: url = self.block_store.store_raw_file(cherrypy.request.body, safe_id) if self.task_pool is not None: self.task_pool.publish_refs({ safe_id: SW2_ConcreteReference(safe_id, None, [self.block_store.netloc]) }) return simplejson.dumps(url) elif cherrypy.request.method == 'HEAD': if os.path.exists(self.block_store.filename(id)): return else: raise cherrypy.HTTPError(404) else: raise cherrypy.HTTPError(405)
def index(self): from cherrypy.lib.static import serve_file try: return serve_file(os.path.join(self.html_directory, 'index_%s.html' % cherrypy.config['misc.localization'])) except cherrypy.NotFound: return serve_file(os.path.join(self.html_directory, 'index_en.html'))
def get(self, id): result = cogimixMusicProvider.get_by_id(id) if result : track = dict(result) print mimetypes mime = mimetypes.guess_type(track['filepath'])[0] if mime: return serve_file(track['filepath'], mime) return serve_file(track['filepath'])
def app(self, *args): """Serve the app or redirect to login.""" if not args: return serve_file(join(self.app_dir, 'index.html')) args = list(args) page = args.pop(0) if not (page in ['manifest.json'] or getattr(cherrypy.request, 'user', None)): raise cherrypy.HTTPRedirect('/login/{}'.format(self.sa_module)) return serve_file(join(self.app_dir, page, *args))
def get_loginform(self): import os from cherrypy.lib.static import serve_file try: return serve_file(os.path.join(self.html_directory, 'login_%s.html' % cherrypy.config['misc.localization'])) except cherrypy.NotFound: return serve_file(os.path.join(self.html_directory, 'login_en.html'))
def get_image(url, height=None, width=None, opacity=100, mode=None, auth=None, headers=None, missing_image=None): ''' Load image form cache if possible, else download. Resize if needed ''' opacity = float(opacity) logger = logging.getLogger('htpc.helpers') # Create image directory if it doesnt exist imgdir = os.path.join(htpc.DATADIR, 'images/') if not os.path.exists(imgdir): logger.debug('Creating image directory at ' + imgdir) os.makedirs(imgdir) # Create a hash of the path to use as filename imghash = hashlib.md5(url).hexdigest() # Set filename and path image = os.path.join(imgdir, imghash) # If there is no local copy of the original # download it if not os.path.isfile(image): logger.debug('No local image found for %s. Downloading..' % url) image = download_image(url, image, auth, headers) # Check if resize is needed if (height and width) or (opacity < 100) or mode: if PIL: # Set a filename for resized file resized = '%s_w%s_h%s_o_%s_%s' % (image, width, height, opacity, mode) # If there is no local resized copy if not os.path.isfile(resized): # try to resize, if we cant return original image image = resize_image(image, height, width, opacity, mode, resized) if image: return serve_file(path=image, content_type='image/jpeg') # If the resized image is already cached if os.path.isfile(resized): image = resized else: logger.error("Can't resize when PIL is missing on system!") if (opacity < 100): image = os.path.join(htpc.RUNDIR, 'interfaces/default/img/fff_20.png') # Load file from disk if image is not None: imagetype = imghdr.what(os.path.abspath(image)) if imagetype is None: imagetype = 'image/jpeg' return serve_file(path=image, content_type=imagetype) if missing_image: # full fp to missing image return serve_file(path=missing_image, content_type='image/jpeg')
def feed(self, name): print("FEED") accepts = cherrypy.request.headers.elements('Accept') for accept in accepts: if accept.value == 'application/atom+xml': return serve_file(os.path.join(current_dir, 'feeds', '%s.atom' % name), content_type='application/atom+xml') return serve_file(os.path.join(current_dir, 'feeds', '%s.rss' % name), content_type='application/xml')
def index(self): from cherrypy.lib.static import serve_file from cherrypy import NotFound try: if self.localization != 'en': return serve_file(os.path.join(self.html_directory, 'index_%s.html' % self.localization)) else: return serve_file(os.path.join(self.html_directory, 'index.html')) except NotFound: return serve_file(os.path.join(self.html_directory, 'index.html'))
def get_loginform(self): import os from cherrypy.lib.static import serve_file try: return serve_file( os.path.join( self.html_directory, 'login_%s.html' % cherrypy.config['misc.localization'])) except cherrypy.NotFound: return serve_file( os.path.join(self.html_directory, 'login_en.html'))
def movie(self, movieid, filename=None): dbmovie = None for m in self.moviesdb: if m.ID == movieid: dbmovie = m response = cherrypy.response if dbmovie: if filename == "folder.jpg": if os.path.isfile(os.path.join(dbmovie.Dir, filename)): img = Image.open(os.path.join(dbmovie.Dir, filename)) response.headers['Content-Type'] = 'image/jpg' img.thumbnail((180, 270), Image.ANTIALIAS) return img.tostring('jpeg', 'RGB') #return serve_file(os.path.join(self.moviesdb[int(movieid)].Dir, filename), content_type='image/jpg') else: return serve_file(os.path.join(os.getcwd(), "Images", "noposter.png"), content_type='image/png') elif filename == "backdrop.jpg": if os.path.isfile(os.path.join(dbmovie.Dir, filename)): img = Image.open(os.path.join(dbmovie.Dir, filename)) response.headers['Content-Type'] = 'image/jpg' img.thumbnail((450, 250), Image.ANTIALIAS) return img.tostring('jpeg', 'RGB') #return serve_file(os.path.join(self.moviesdb[int(movieid)].Dir, filename), content_type='image/jpg') else: return serve_file(os.path.join(os.getcwd(), "Images", "nobackdrop.png"), content_type='image/png') elif filename == "nfo": files = os.listdir(dbmovie.Dir) for fi in files: ext = os.path.splitext(fi)[1] if ext.lower() == ".nfo": return serve_file(os.path.join(dbmovie.Dir, fi), content_type='text/plain') #if self.moviesdb[int(movieid)].HasXML: movie = mymovies.MyMovie(os.path.join(dbmovie.Dir, "mymovies.xml")) ET.SubElement(movie.dom, 'unprocessed').text = str(self.unprocessedcount) ET.SubElement(movie.dom, 'movieID').text = dbmovie.ID transform = ET.XSLT(ET.XML(open('Templates/moviepage.xsl').read())) editcontrols = (cherrypy.request.remote.ip == cherrypy.config.get( "server.socket_host")) doc = transform(movie.dom, EditControls="'%s'" % editcontrols) return str(doc) else: pass
def default(self, id): safe_id = id if cherrypy.request.method == 'GET': is_streaming, filename = self.block_store.maybe_streaming_filename(safe_id) if is_streaming: cherrypy.response.headers['Pragma'] = 'streaming' try: response_body = serve_file(filename) return response_body except cherrypy.HTTPError as he: # The streaming file might have been deleted between calls to maybe_streaming_filename # and serve_file. Try again, because this time the non-streaming filename should be # available. if he.status == 404: if not is_streaming: raise cherrypy.response.headers.pop('Pragma', None) is_streaming, filename = self.block_store.maybe_streaming_filename(safe_id) try: serve_file(filename) except cherrypy.HTTPError as he: if he.status == 416: raise cherrypy.HTTPError(418) else: raise elif he.status == 416: raise cherrypy.HTTPError(418) else: raise elif cherrypy.request.method == 'POST': if self.backup_sender is not None: request_body = cherrypy.request.body.read() url = self.block_store.store_raw_file(StringIO.StringIO(request_body), safe_id) self.backup_sender.add_data(safe_id, request_body) else: url = self.block_store.store_raw_file(cherrypy.request.body, safe_id) if self.task_pool is not None: self.task_pool.publish_refs({safe_id : SW2_ConcreteReference(safe_id, None, [self.block_store.netloc])}) return simplejson.dumps(url) elif cherrypy.request.method == 'HEAD': if os.path.exists(self.block_store.filename(id)): return else: raise cherrypy.HTTPError(404) else: raise cherrypy.HTTPError(405)
def static(self, *args): cp.lib.caching.expires(secs=timedelta(1), force=True) path = os.path.join(hf.hf_dir, hf.config.get('paths', 'static_dir'), *args) # archive/Y/M/D/H/M/file -> 7 if len(args) == 7 and args[0] == 'archive': authorized = self.archiveFileAuthorized(args[6]) if authorized: return serve_file(path) else: raise cp.HTTPError(status=403, message="You are not allowed to access this resource.") else: return serve_file(path)
def sendFile(self, id): row = library.getBookInfos(id) if row: path = row['PATH'] basename = os.path.basename(path) filename, ext = os.path.splitext(basename) if 'pdf' in ext: return static.serve_file(path, 'application/pdf', 'inline', basename) elif 'epub' in ext: return static.serve_file(path, 'application/epub+zip', 'inline', basename) else: return static.serve_file(path, 'application/octet-stream', 'inline', basename)
def fetchData(self): if self.data == 'OK': logger.fdebug('Recieved OPDS command: ' + self.cmd) methodToCall = getattr(self, "_" + self.cmd) result = methodToCall(**self.kwargs) if self.img: return serve_file(path=self.img, content_type='image/jpeg') if self.file and self.filename: if self.issue_id: try: readinglist.Readinglist( IssueID=self.issue_id).markasRead() except: logger.fdebug('No reading list found to update.') return serve_download(path=self.file, name=self.filename) if isinstance(self.data, basestring): return self.data else: cherrypy.response.headers['Content-Type'] = "text/xml" return serve_template(templatename="opds.html", title=self.data['title'], opds=self.data) else: return self.data
def fetchData(self): if self.data == 'OK': logger.fdebug('Received API command: ' + self.cmd) methodToCall = getattr(self, "_" + self.cmd) result = methodToCall(**self.kwargs) if 'callback' not in self.kwargs: if self.img: return serve_file(path=self.img, content_type='image/jpeg') if self.file and self.filename: return serve_download(path=self.file, name=self.filename) if isinstance(self.data, str): return self.data else: if self.comicrn is True: return self.data else: cherrypy.response.headers[ 'Content-Type'] = "application/json" return json.dumps(self.data) else: self.callback = self.kwargs['callback'] self.data = json.dumps(self.data) self.data = self.callback + '(' + self.data + ');' cherrypy.response.headers[ 'Content-Type'] = "application/javascript" return self.data else: return self.data
def default(self, pdf, *args, **kwargs): if not pdf: return "No such file." if len(args)>=1: return serve_file(PdfDerivative(pdf, args[0], PDF_ROOT, CACHE_DIR).get_image()) return "Something went wrong."
def index(self, filepath): "корневой метод для маппинга дерева подсистем (нельзя вызывать явно)" path, fname = os.path.split(filepath) # fname= fname.encode('windows-1251') # path= path.encode('windows-1251') # блок безопасности # проверим, что скачивание привязано к сессии (т.е. юзер хотя бы залогинен) uid = getUserVar('uid') if not uid: return goToError(error_code[0] % fname) # теперь проверим, пренадлежит ли файл этой учетной записи # получим uid-префикс из имени файла fuid = self.split_path_to_uid(path) # если он не пустой, но не равен сессионному -валим эксепшн (если же пустой, значит загрузка общая и не привязана к сессии) if fuid and str(uid) != str(fuid): return goToError(error_code[1] % fname) # проверка на доступность файла для скачивания if not os.path.isfile(filepath): return goToError(error_code[2] % fname) return serve_file(filepath, "application/x-download", "attachment")
def download(self, name, documento): localDir = os.path.dirname(__file__) + "/resources/Files/" + name absDir = os.path.join(os.getcwd(), localDir) path = os.path.join(absDir, documento) return static.serve_file(path, 'application/x-download', 'attachment', os.path.basename(path))
def view_stage_plot(self, session, id): guest = session.guest_group(id) return serve_file( guest.stage_plot.fpath, disposition="attachment", name=guest.stage_plot.download_filename, content_type=guest.stage_plot.content_type)
def view_w9(self, session, id): guest = session.guest_group(id) return serve_file( guest.taxes.w9_fpath, disposition="attachment", name=guest.taxes.download_filename, content_type=guest.taxes.w9_content_type)
def actionGet(self, userId, userCred, imgId): self.msg = "" option = "img" imgId = imgId.strip() userId = userId.strip() #userCred = IRCredential("ldappass", userCred) if (len(userId) > 0 and len(imgId) > 0): authstatus=self.service.auth(userId, userCred, self.provider) if authstatus == True: filepath = self.service.get(userId, option, imgId) if (filepath != None): #if (len(imgId) > 0) : self.msg = "Downloading img to %s " % filepath.__str__() return serve_file(filepath, "application/x-download", "attachment") #else : # self.msg = "URL: %s " % filepath.__str__() else: self.msg = "Cannot get access to the image with imgId = " + imgId elif authstatus == False: self.msg = "ERROR: Wrong password" elif authstatus == "NoUser": self.msg = "ERROR: User "+ userId + " does not exist" elif authstatus == "NoActive": self.msg = "ERROR: The status of the user "+ userId + " is not active" else: #this should not be used self.msg = authstatus else : self.msg="Please verify the input information, you need to include userId/password and imageId" raise cherrypy.HTTPRedirect("results")
def download(self, songs=None, artists=None ,albums=None, query=None): logger.debug("%s (%s)\tdownload(songs=%s, artists=%s, albums=%s, query=%s)\tHeaders: %s" % (utils.find_originating_host(cherrypy.request.headers), cherrypy.request.login, songs, artists, albums, query, cherrypy.request.headers)) if cfg['REQUIRE_LOGIN'] and cherrypy.request.login not in cfg['GROUPS']['download']: logger.warn("%(user)s (%(ip)s) requested a download, but was denied because %(user)s is not a member of the download group." % {'user': cherrypy.request.login, 'ip': utils.find_originating_host(cherrypy.request.headers)}) raise cherrypy.HTTPError(401,'Not Authorized') file_list = [] if not songs and not artists and not albums and not query: raise cherrypy.HTTPError(501) elif songs: songs = songs.split(',') if len(songs) > 100: return "Too many songs! Please narrow your criteria." for song in songs: try: file_list.append(self.library.db[song]) except: raise cherrypy.HTTPError(404,'Not Found') else: if artists: artists = artists.split(',') if albums: albums = albums.split(',') files = self.library.songs(artists, albums, query) if len(files) > 100: return "Too many songs! Please narrow your criteria." for song in files: file_list.append(self.library.db[song['id']]) archive = create_archive(file_list) try: return serve_file(archive, 'application/zip', 'download.zip') except: logger.debug("Something went wrong while sending the archive.")
def serve_media(self, media_url): for app in self.apps: extension = splitext(media_url)[-1] app_module = reduce(getattr, app.split('.')[1:], __import__(app)) path = inspect.getfile(app_module) media_path = abspath(join("/".join(split(path)[:-1]), 'media', media_url)) if exists(media_path): if extension == ".jpg": content_type = "image/jpeg" elif extension == ".gif": content_type = "image/gif" elif extension == ".png": content_type = "image/png" elif extension == ".js": content_type = "text/javascript" elif extension == ".css": content_type = "text/css" elif extension.startswith('.htm'): content_type = "text/html" else: content_type = "text/plain" return serve_file(media_path, content_type=content_type) raise cherrypy.HTTPError(404)
def __call__(self, *args, **kw): if len(args) < 1: cherrypy.response.status = 404 return "not found" path = "/".join(args) image = jpeg(path=path) cache_full_path = None if self.should_cache: cache_full_path = self.get_cache_path(path) if self.fs.exists(cache_full_path): return static.serve_file(cache_full_path, 'image/jpeg') if len(args) >= 3 and args[0] == 'crop': proportion = re.match(r'(?P<width>\d+)x(?P<height>\d+)', args[1]) if proportion: width = int(proportion.group('width')) height = int(proportion.group('height')) image = picture(path="/".join(args[2:]), width=width, height=height) if self.should_cache: dir_path = self.fs.dirname(cache_full_path) self.fs.mkdir(dir_path) img_file = self.fs.open_raw(cache_full_path, 'w') img_file.write(image) img_file.close() return image
def dynamic(self, fileName, download=False): print 'request for dynamic file location:', fileName # guard against fishing trips for other files fileName = os.path.split( fileName )[1] # remove any extra path information - we just want the file name ext = "." + fileName.split(".")[-1] if not ext in (".png", ".pdf", ".jpg", ".html", ".csv"): raise Exception("Unrecognized file type requested.") count = cherrypy.session.get("count", 0) + 1 cherrypy.session["count"] = count b = cherrypy.session.get("building", None) pm = PlotMaker(b, getUserDir(), cherrypy.config.get("wkhtmltopdf.bin")) pm.waitForImages() # generate images if necessary pme = pm.getError( ) # this is how we learn if there were errors in the image generation thread if pme is not None: raise Exception( "File generation failed: " + pme ) # the file generation failed, so we need to handle this error somehow baseDir = os.path.join(cherrypy.config.get("app.root"), getUserDir()) print(os.path.join(baseDir, fileName)) if download: return serve_download(os.path.join(baseDir, fileName)) return serve_file(os.path.join(baseDir, fileName), content_type=mimetypes.types_map.get( ext, "text/plain"))
def attrs(self, space): """ Return the attrs.json file for a space. If the attrs.json file specifies a lib property, walk that directory and return the contents of the lib directory as strings in the returned JSON. """ try: spacePath = os.path.join(WEB_ROOT, 'spaces', space) attrsPath = os.path.join(spacePath, 'attrs.json') fh = open(attrsPath) attrs = json.loads(fh.read()) fh.close() liborlang = False if attrs.get("lib"): liborlang = True libPath = os.path.join(spacePath, attrs["lib"]) attrs["lib"] = self.walk(libPath, {}) if attrs.get("lang"): liborlang = True langPath = os.path.join(spacePath, attrs["lang"]) attrs["lang"] = self.langwalk(langPath, {}) if liborlang: return json.dumps(attrs) else: f = serve_file(attrsPath) return f except error: return json.dumps(error("No space called %s exists" % space, SpaceDoesNotExistError))
def GET(self, *args): """Return the requested documentation file. Args: *args (tuple of str): Will be concatenated to form the path of the requested file relative to the PCE document root folder. Returns: Requested documentation file if it exists, 404 if not. """ if cherrypy.request.path_info == "": # No trailing slash in request URI. This breaks relative paths in # Sphinx-generated docs. Fix by redirecting to URI with trailing # slash. redirect_path = "/cluster/info/" self.logger.debug('Redirecting to: %s' % redirect_path) raise cherrypy.HTTPRedirect(redirect_path) if not args: args = ('index.html', ) prefix = os.path.abspath( os.path.join(pce_root, 'docs', 'build', 'html')) index_file = os.path.join(pce_root, 'docs', 'build', 'html', *args) index_file = os.path.normpath(os.path.abspath(index_file)) if (not index_file.startswith(prefix) or not os.path.isfile(index_file)): cherrypy.response.status = 404 return 'File %s not found' % os.path.join(*args) return serve_file(index_file)
def getImage(url, h=None, w=None, o=100, auth=None, **kwargs): # Create image directory if it doesnt exist imgdir = os.path.join(htpc.datadir, 'images/') if not os.path.exists(imgdir): os.makedirs(imgdir) fileName = unquote(unquote(url)).rsplit('/', 1).pop() imgName, imgType = fileName.rsplit('.', 1) original = resized = os.path.join(imgdir, imgType+'_'+imgName+'.png') if h and w: resized = os.path.join(imgdir, original+'_'+w+'_'+h+'.png') # If there is no local copy of the original if not os.path.isfile(original): original = downloadImage(url, original, auth) if not original: print "Error downloading image" raise cherrypy.NotFound(fileName) # If there is no local resized copy if not os.path.isfile(resized): resized = resizeImage(original, h, w, o, resized) if not resized: resized = original # Load file from disk return serve_file(path=resized, content_type='image/png')
def cli(self, *args, **kwargs): """ Serve CLI file download. """ clifile = os.path.join(os.environ['QB_ROOT'], 'pyquerybuilder/tools/qbcli.py') return serve_file(clifile, content_type='text/plain')
def default(self, *args, **kw): # Ignore the args, because the args don't tell you whether # html has a trailing / or not. If it doesn't, the relative CSS # paths will be all screwed up, so I might as well just return # NotFound before anything awful happens. if (cherrypy.request.path_info == "/MAT/doc/html/") or \ (cherrypy.request.path_info == "/MAT/doc/html/index.html"): # Seed the processing. from MAT.WebService import enhanceRootDocIndex s = enhanceRootDocIndex(MAT_PKG_HOME) cherrypy.response.headers['content-type'] = 'text/html' return s elif cherrypy.request.path_info == "/MAT/doc/html/BUNDLE_LICENSE": blPath = os.path.join(MAT_PKG_HOME, "BUNDLE_LICENSE") if os.path.exists(blPath): cherrypy.response.headers['content-type'] = 'text/plain' fp = open(blPath, "r") s = fp.read() fp.close() return s else: m = self.TASK_DOC_PAT.match(cherrypy.request.path_info) if m is not None: tName, pathRemainder = m.groups() # Gotta find the task documentation. This is the same sort of game # that was played in the dispatcher above. pDir = MAT.PluginMgr.LoadPlugins() byDir = pDir.getRecorded(tName) if byDir is None: raise cherrypy.NotFound() # Make sure it works on Windows. p = os.path.join(byDir[0], *pathRemainder.split("/")) from cherrypy.lib.static import serve_file return serve_file(p) raise cherrypy.NotFound()
def css(self, name): lessFilename = name.replace(".css",".less") # TODO, check any imports and rebuild if imports have changed srcFileName = os.path.join(current_dir, self.less_dir, lessFilename) buildFileName = os.path.join(current_dir, self.css_dir, name) if not os.access(srcFileName, os.F_OK): raise NotFound(srcFileName) if not os.access(buildFileName, os.F_OK): self.buildCssFile(name) else: # Check to see if the src/name is newer than build/name srcFileInfo = os.stat(srcFileName) buildFileInfo = os.stat(buildFileName) # if src/name is newer, run r.js if srcFileInfo.st_mtime > buildFileInfo.st_mtime: self.buildCssFile(name) # server build/name return serve_file(buildFileName, content_type="text/css")
def download(self, slug): found: Optional[Snapshot] = None for snapshot in self.engine.snapshots: if snapshot.slug() == slug: found = snapshot break if not found or (not found.ha and not found.driveitem): raise cherrypy.HTTPError(404) if found.ha: return serve_file( os.path.abspath( os.path.join(self.config.backupDirectory(), found.slug() + ".tar")), "application/tar", "attachment", "{}.tar".format(found.name())) elif found.driveitem: cherrypy.response.headers['Content-Type'] = 'application/tar' cherrypy.response.headers[ 'Content-Disposition'] = 'attachment; filename="{}.tar"'.format( found.name()) cherrypy.response.headers['Content-Length'] = str(found.size()) return self.engine.drive.download(found.driveitem.id()) else: raise cherrypy.HTTPError(404)
def servelog(self, filename): pages.require('/users/logs.view') # Make sure the user can't acess any file on the server like this # First security check, make sure there's no obvious special chars if ".." in filename: raise RuntimeError("Security Violation") if "/" in filename: raise RuntimeError("Security Violation") if "\\" in filename: raise RuntimeError("Security Violation") if "~" in filename: raise RuntimeError("Security Violation") if "$" in filename: raise RuntimeError("Security Violation") filename = os.path.join(directories.logdir, 'dumps', filename) filename = os.path.normpath(filename) # Second security check, normalize the abs path and make sure it is what we think it is. if not filename.startswith( os.path.normpath( os.path.abspath(os.path.join(directories.logdir, 'dumps')))): raise RuntimeError("Security Violation") return serve_file(filename, "application/x-download", os.path.split(filename)[1])
def media(self, path=""): if not path.startswith("/"): path = "/" + path mapped = mapper._map_path(path) if mapped is None: raise cherrypy.HTTPError(404) return serve_file(mapped)
def export(self, burst_id): export_manager = ExportManager() export_zip = export_manager.export_simulator_configuration(burst_id) result_name = "tvb_simulation_" + str(burst_id) + ".zip" return serve_file(export_zip, "application/x-download", "attachment", result_name)
def upload(self, my_file): if not my_file.filename.endswith(".zip") and not my_file.filename.endswith(".tex"): return """ <p>Bitte eine Datei mit der Endung .tex oder ein Zip-Archiv hochladen</p> <a href="/index">Zurück</a> """ else: is_archive = my_file.filename.endswith(".zip") buf = BytesIO() while True: data = my_file.file.read(8192) if not data: break buf.write(data) buf.seek(0) with tempfile.TemporaryDirectory() as tmp_dir: logger.debug(f"Temporary file {tmp_dir} created") if is_archive: unpack(buf, tmp_dir) else: with open(os.path.join(tmp_dir, my_file.filename), "wb") as f: f.write(buf.read()) logger.debug(f"Files in tmp dir: {glob.glob(os.path.join(tmp_dir, '**/*'), recursive=True)}") result = process(tmp_dir) if result: logger.debug(f"Result file: {result}") return static.serve_file(os.path.join(tmp_dir, result), "application/x-download", "attachment", result) else: return "<b> Keine Tex-Datei gefunden! </b>"
def sign_up(self, **data): if len(data) == 0: return serve_file(par_dir + "/frontend/sign_up.html", content_type="text/html") else: pass conn = sqlite3.connect("../data/database/users.db") cursor = conn.cursor() name_from_client = data['name'] email_from_client = data['email'] password_from_client = data['password'] sql = 'SELECT email_db FROM users WHERE email_db = ?' cursor.execute(sql, [(email_from_client)]) email_in_DB = cursor.fetchone() email_check = 'nuts' if email_in_DB == None: pass elif email_from_client == email_in_DB[0]: email_response = {'fromServer': email_check} return json.dumps(email_response) pass_from_client = data['password'] time_stamp = time.time() hash_pass = sha256_crypt.encrypt(password_from_client) new_user = (name_from_client, email_from_client, hash_pass, time_stamp) cursor.execute("INSERT INTO users Values (?, ?, ?, ?)", new_user) conn.commit() conn.close() response = "<h1>Welcome " + name_from_client + "!</h1>" result = {"fromServer" : response} return json.dumps(result)
def cli(self, *args, **kwargs): """ Serve DAS CLI file download. """ clifile = os.path.join(os.environ['DAS_ROOT'], 'src/python/DAS/tools/das_cache_client.py') return serve_file(clifile, content_type='text/plain')
def files(self,*args,**kwargs): """Return a file manager. Kwargs may contain del=file to delete a file. The rest of the path is the directory to look in.""" pages.require("/admin/settings.edit") dir=os.path.join('/',*args) if 'del' in kwargs: node = os.path.join(dir,kwargs['del']) if os.path.isfile(node): os.remove(node) else: shutil.rmtree(node) raise cherrypy.HTTPRedirect(cherrypy.request.path_info.split('?')[0]) if 'file' in kwargs: if os.path.exists(os.path.join(dir,kwargs['file'].filename)): raise RuntimeError("Node with that name already exists") with open(os.path.join(dir,kwargs['file'].filename),'wb') as f: while True: data = kwargs['file'].file.read(8192) if not data: break f.write(data) if os.path.isdir(dir): return pages.get_template("settings/files.html").render(dir=dir) else: return serve_file(dir)
def __call__(self, path, **params): if not path: path = "index.html" if 'cd-lang' in cherrypy.request.cookie: langs = [cherrypy.request.cookie['cd-lang'].value.lower()] logger.debug("frontend language from cookie: %s", langs) else: if 'Accept-Language' in cherrypy.request.headers: accept_lang_header = cherrypy.request.headers['Accept-Language'] langs = self._parse_accept_language(accept_lang_header) else: langs = [self.DEFAULT_LANGUAGE.lower()] logger.debug("frontend language from headers: %s", langs) base_dir = self._language_dir(langs) full_path = os.path.join(base_dir, path) # Block uplevel attacks if not os.path.normpath(full_path).startswith(os.path.normpath(base_dir)): raise cherrypy.HTTPError(403) # Forbidden logger.debug("serving static content: %s", full_path) if 'Vary' in cherrypy.response.headers: cherrypy.response.headers['Vary'] = "{}, Accept-Language" else: cherrypy.response.headers['Vary'] = "Accept-Language" cherrypy.response.headers['Cache-control'] = "no-cache" return serve_file(full_path)
def view_bio_pic(self, session, id): guest = session.guest_group(id) return serve_file( guest.bio.pic_fpath, disposition="attachment", name=guest.bio.download_filename, content_type=guest.bio.pic_content_type)
def index(self, g=None, f=None): if f is not None: g = base64e.decode(g) gs = string.replace(g, "..", "") gs = forbanshareroot + gs mimetypeguessed = mime_type(gs) return serve_file(gs, content_type=mimetypeguessed,disposition=True, name=os.path.basename(gs))
def fetchData(self): if self.data == 'OK': logger.fdebug('Recieved OPDS command: ' + self.cmd) methodToCall = getattr(self, "_" + self.cmd) result = methodToCall(**self.kwargs) if self.img: if type(self.img) == tuple: iformat, idata = self.img return serve_fileobj(BytesIO(idata), content_type='image/' + iformat) else: return serve_file(path=self.img, content_type='image/jpeg') if self.file and self.filename: if self.issue_id: try: logger.fdebug('OPDS is attempting to markasRead filename %s aka issue_id %s' % (self.filename, self.issue_id)) readinglist.Readinglist().markasRead(IssueID=self.issue_id) except: logger.fdebug('No reading list found to update.') return serve_download(path=self.file, name=self.filename) if isinstance(self.data, str): return self.data else: cherrypy.response.headers['Content-Type'] = "text/xml" return serve_template(templatename="opds.html", title=self.data['title'], opds=self.data) else: return self.data
def download(self, data_type='project', data_name=None): self.fetch_session_data() pm = self.project_manager if(data_type == 'project'): filetype = 'application/zip' filepath = os.path.join(pm.user_dir, '%s.zip' % (self.project_id)) with zipfile.ZipFile(filepath, 'w') as fout: first = True for root, dirs, files in os.walk(pm.project_dir): if first: rootroot = os.path.dirname(root) first = False arcroot = os.path.relpath(root, rootroot) for file in files: fout.write(os.path.join(root, file), arcname=os.path.join(arcroot, file)) elif(data_type == 'data_source'): filetype = 'text/plain' fe = pm.get_feature_extraction() filepath = fe.protein_data_set.ds_dict[data_name].get_data_path() elif(data_type == 'labeling'): filetype = 'text/plain' fe = pm.get_feature_extraction() fm = fe.fm_protein labeling_d = os.path.join(fe.fm_protein_d, fm.LABELING_D) filepath = os.path.join(labeling_d, '%s.txt' % (data_name)) return serve_file(filepath, filetype, 'attachment')
def index(self): """----------------------------------------------------------------------------------------- Splash page :return: kollema.htm, static page -----------------------------------------------------------------------------------------""" # print('path', path) return serve_file(os.path.join(static, 'kollema.html'))
def handle(depot, request, response, pub): """If there have been package updates since we last generated the feed, update the feed and send it to the client. Otherwise, send them the cached copy if it is available. """ cfpath = __get_cache_pathname(depot, pub) # First check to see if we already have a valid cache of the feed. need_update, last = __cache_needs_update(depot, pub) if need_update: # Update always looks at feed.window seconds before the last # update until "now." If last is none, we want it to use "now" # as its starting point. if last is None: last = datetime.datetime.utcnow() # Generate and cache the feed. misc.makedirs(os.path.dirname(cfpath)) cf = open(cfpath, "w") update(request, depot, last, cf, pub) cf.close() return serve_file(cfpath, MIME_TYPE)
def error_page_404(self, status, message, traceback, version): if message.find("ImagesByName") != -1: return serve_file(os.path.join(os.getcwd(), "Images", "noactorpic.png"), content_type='image/png') else: return "%s\n%s\n%s\n" % (status, message, traceback)