Example #1
0
 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
Example #2
0
 def download(self, fileName):
     count = cherrypy.session.get("count", 0) + 1
     cherrypy.session["count"] = count
     baseDir = os.path.join(cherrypy.config.get("app.root"), 'static',
                            'sample')
     # serve_download is a handy helper function from the server
     return serve_download(os.path.join(baseDir, fileName))
Example #3
0
    def downloadlog(self):
        try:
            htpc.LOGGER.flush()
        except:
            pass

        return serve_download(self.logfile, name='htpcmanager.txt')
Example #4
0
    def downloadlog(self):
        try:
            htpc.LOGGER.flush()
        except:
            pass

        return serve_download(self.logfile, name='htpcmanager.txt')
Example #5
0
    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
Example #6
0
File: api.py Project: Mathix/mylar3
    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
Example #7
0
    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"))
Example #8
0
 def serve(self, name):
     try:
         resource = self.resources[name]
         return serve_download(resource)
     except cherrypy.NotFound:
         raise
     except Exception:
         raise cherrypy.NotFound()
Example #9
0
    def download_file(self, **kwargs):
        """ Download the file. """

        if kwargs.get('log'):
            path = speakreader.CONFIG.LOG_DIR
            file = kwargs['log']
        elif kwargs.get('transcript'):
            path = speakreader.CONFIG.TRANSCRIPTS_FOLDER
            file = kwargs['transcript']
        else:
            return

        return serve_download(os.path.join(path, file), name=file)
Example #10
0
File: app.py Project: urykhy/stuff
 def download(self, **params):
     id = int(params.get('id', "0").strip())
     if id == 0:
         pass
     xname = str(id) + ".fb2"
     tname = join(tmp_path,xname)
     onlyfiles = [f for f in os.listdir(mirror_path) if isfile(join(mirror_path, f))]
     for f in onlyfiles:
         if f.endswith(".zip"):
             (x1,x2) = self.split_name(f)
             if x1 <= id and id <= x2:
                 #cherrypy.log("book must be in "+f)
                 with zipfile.ZipFile(join(mirror_path, f)) as z:
                     with z.open(xname) as zf, open(tname, 'wb') as f:
                         shutil.copyfileobj(zf, f)
                         return serve_download(tname)
Example #11
0
    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:
                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
Example #12
0
 def download(self, **params):
     id = int(params.get('id', "0").strip())
     if id == 0:
         pass
     xname = str(id) + ".fb2"
     tname = join(tmp_path, xname)
     onlyfiles = [
         f for f in os.listdir(mirror_path) if isfile(join(mirror_path, f))
     ]
     for f in onlyfiles:
         if f.endswith(".zip"):
             (x1, x2) = self.split_name(f)
             if x1 <= id and id <= x2:
                 #cherrypy.log("book must be in "+f)
                 with zipfile.ZipFile(join(mirror_path, f)) as z:
                     with z.open(xname) as zf, open(tname, 'wb') as f:
                         shutil.copyfileobj(zf, f)
                         return serve_download(tname)
 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 __serve_wn(self, wn, storagedir):
     print_enter('worknoteBookServer.__serve_wn')
     from tempfile import gettempdir
     from os.path import join, exists
     from cherrypy.lib.static import serve_download
     from worknoteBookHelpers import zip_worknote
     wn_dir, wn_title, wn_date = wn
     print 'Preparing to serve "{:s}" from "{:s}"...'.format(wn_dir, storagedir)
     tmpdir = gettempdir()
     fn_wnzip = '{wn_dir:s}.zip'.format(wn_dir=wn_dir)
     dl_filepath = join(tmpdir, fn_wnzip)
     print 'Zipping worknote...'
     zip_worknote(join(storagedir, wn_dir), dl_filepath)
     if exists(dl_filepath):
         print 'Serving file "{:s}"...'.format(dl_filepath)
         return serve_download(dl_filepath, name=fn_wnzip)    
     else:
         print 'ERROR: Zip file not created'
         return 'Error creating ZIP archive for download'
Example #15
0
    def export(self, path, **kw):
        """
    Download the zip archive with the file under the specified project directory
    Method : GET
    (Path : /ide/export)

    Input must be JSON of the following format:
      {
        'path':    '<<The project directory from where to compress>>'
      }

    Output in response will be a zip file
    """
        self._logger.debug("Export by {0} ({1}:{2}) path: {3}".format(
            cherrypy.session['username'], request.remote.ip,
            request.remote.port, path))

        username = cherrypy.session['username']
        self._logger.info("Export requested by {0} ({1}:{2})".format(
            username, request.remote.ip, request.remote.port))

        if self.is_valid_path(path) or path == "/":
            future_response = self._app.create_archive(path, username)
        else:
            raise HTTPError(400, "Invalid path")

        # Block until an answer is given
        archive_path = future_response.get()
        if not os.path.exists(archive_path):
            raise HTTPError(500, "Unavailable archive")

        # Store archive name in request to remove it when client download will be completed
        request.archive_path = archive_path
        request.hooks.attach('on_end_request',
                             lambda: os.unlink(request.archive_path))
        # Return archive
        return static.serve_download(archive_path)
Example #16
0
    def fetchData(self):

        if self.data == 'OK':
            logger.info('Recieved 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, basestring):
                    return self.data
                else:
                    cherrypy.response.headers['Content-Type'] = "application/json"
                    return simplejson.dumps(self.data)
            else:
                self.callback = self.kwargs['callback']
                self.data = simplejson.dumps(self.data)
                self.data = self.callback + '(' + self.data + ');'
                cherrypy.response.headers['Content-Type'] = "application/javascript"
                return self.data
        else:
            return self.data
Example #17
0
	def getlocal(self, file=None):
		if not file:
			return listlocal(msg_error="No file to download")
		return serve_download(os.path.join(self.ringconfig.get('DHT:datadir'), file))
Example #18
0
	def getconfig(self):
		uid = cherrypy.session.get('uid', None)
		if not uid:
			return self.index()		
		return serve_download(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'configs', uid))
        if librdiff.backupIsInProgressForRepo(
                rdw_helpers.joinPaths(
                    self.getUserDB().getUserRoot(self.getUsername()), repo)):
            return self.writeErrorPage(
                "A backup is currently in progress to this location.  Restores are disabled until this backup is complete."
            )

        try:
            restoreTime = rdw_helpers.rdwTime()
            restoreTime.initFromString(date)
            (path, file) = os.path.split(path)
            if not file:
                file = path
                path = "/"
            fullPath = rdw_helpers.joinPaths(
                self.getUserDB().getUserRoot(self.getUsername()), repo)
            useZipFormat = self.getUserDB().useZipFormat(self.getUsername())
            filePath = librdiff.restoreFileOrDir(fullPath, path, file,
                                                 restoreTime, useZipFormat)
        except librdiff.FileError, error:
            return self.writeErrorPage(error.getErrorString())
        except ValueError:
            return self.writeErrorPage("Invalid date parameter.")

        (directory, filename) = os.path.split(filePath)
        filename = filename.replace("\"", "\\\"")  # Escape quotes in filename
        return serve_download(filePath, name=filename)

    index.exposed = True
 def offerFile(self, filePath):
     print "downloading", filePath
     serve_download(filePath)
 def download(self,fileName):
   count = cherrypy.session.get("count", 0) + 1
   cherrypy.session["count"] = count
   baseDir = os.path.join(cherrypy.config.get("app.root"),'static','sample')
   # serve_download is a handy helper function from the server
   return serve_download(os.path.join(baseDir,fileName))
Example #22
0
 def dict(self):
     path = os.path.join(absDir, "./data/passwords.txt")
     return static.serve_download(path)
Example #23
0
 def data(self):
     path = os.path.join(absDir, 'hackedusers.txt')
     return static.serve_download(path)