Exemplo n.º 1
0
 def photo_view(self):
     # Check agreements
     if not self.user.purchase_agreement:
         return HTTPFound(location=self.request.route_path("purchase_agreement_act"))
     elif not self.user.privacy_agreement:
         return HTTPFound(location=self.request.route_path("privacy_policy_act"))
     base_path = self.request.registry._settings["base_dir"]
     if "tick_id" in self.request.matchdict:
         tick_id = self.request.matchdict["tick_id"]
         ticket = None
         # Find ticket
         for tick in self.user.tickets:
             if tick.__name__ == tick_id:
                 ticket = tick
                 break
         # Safety
         if ticket == None:
             return FileResponse(os.path.join(base_path, "data/profile_images", "blank.png"), request=self.request)
         else:
             file_name = ticket.guest_info.photo_file
             if os.path.isfile(os.path.join(base_path, "data/profile_images", file_name)):
                 return FileResponse(os.path.join(base_path, "data/profile_images", file_name), request=self.request)
             else:
                 return FileResponse(os.path.join(base_path, "data/profile_images", "blank.png"), request=self.request)
     else:
         file_name = self.user.profile.photo_file
         if os.path.isfile(os.path.join(base_path, "data/profile_images", file_name)):
             return FileResponse(os.path.join(base_path, "data/profile_images", file_name), request=self.request)
         else:
             return FileResponse(os.path.join(base_path, "data/profile_images", "blank.png"), request=self.request)
Exemplo n.º 2
0
def download_view(request):
    session = request.session
    set_language(request)
    lang = get_language(request)
    if "fileName" in request.params or "filename" in request.params:
        if "fileName" in request.params:
            filename = request.params['fileName']
        else:
            filename = request.params['filename']
        if "results" in request.params:
            response = FileResponse(os.path.join(config['homepath'],
                                                 'documents/download/results',
                                                 filename),
                                    request=request)
        else:
            try:
                dir_file = os.path.join(config['homepath'],
                                        'documents/download', filename)
                response = FileResponse(dir_file, request=request)
            except FileNotFoundError as e:
                log.error('File not found: {}'.format(dir_file))
                result = render('templates/%s/error.pt' % lang, {
                    'err_title':
                    messages['errors']['file_not_found'][lang]['err_title'],
                    'err_text':
                    messages['errors']['file_not_found'][lang]
                    ['err_text'].format(filename)
                },
                                request=request)
                return Response(result)
    response.headers['Content-Disposition'] = ('attachment; filename=' +
                                               filename)
    return response
Exemplo n.º 3
0
def monitor(request):
    pagename = request.matchdict['id']
    page = Page.select(request, pagename)
    response_settings = {'project': 'Michelanglo', 'user': request.user,
                         'page': pagename,
                         'custom_messages': json.dumps(custom_messages),
                         'meta_title': 'Michelaɴɢʟo: sculpting protein views on webpages without coding.',
                         'meta_description': 'Convert PyMOL files, upload PDB files or submit PDB codes and ' + \
                                             'create a webpage to edit, share or implement standalone on your site',
                         'meta_image': '/static/tim_barrel.png',
                         'meta_url': 'https://michelanglo.sgc.ox.ac.uk/'
                         }
    verdict = permission(request, page, 'view', key_label='key')
    if verdict['status'] != 'OK':
        request.response.status_int = 400
        return render_to_response("../templates/404.mako", response_settings,
                                  request)
    elif 'image' in request.params:
        if 'current' in request.params and is_js_true(
                request.params['current']):
            file = os.path.join(
                'michelanglo_app', 'user-data-monitor',
                f"tmp_{page.identifier}-{request.params['image']}.png")
        else:
            file = os.path.join(
                'michelanglo_app', 'user-data-monitor',
                f"{page.identifier}-{request.params['image']}.png")
        if page.protected and os.path.exists(file):
            return FileResponse(file)
        else:
            print(file, os.path.exists(file))
            return FileResponse(
                os.path.join('michelanglo_app', 'static', 'broken.gif'))
    elif not page.protected:
        return {'status': 'unprotected', **response_settings}
    else:
        labelfile = os.path.join(
            'michelanglo_app', 'user-data-monitor', page.identifier +
            '.json')  ## this is not within hth pickle as nodejs makes it.
        verdictfile = os.path.join('michelanglo_app', 'user-data-monitor',
                                   'verdict_' + page.identifier + '.p')
        if os.path.exists(labelfile):
            labels = json.load(open(labelfile))
            if os.path.exists(verdictfile):
                validity = pickle.load(open(verdictfile, 'rb'))
                return {
                    'status': 'monitoring',
                    'labels': labels,
                    'validity': validity,
                    **response_settings
                }
            else:
                return {
                    'status': 'monitoring',
                    'labels': labels,
                    'validity': [None for l in labels],
                    **response_settings
                }
        else:
            return {'status': 'generating', **response_settings}
Exemplo n.º 4
0
	def file(_28_):
		_23_ = _28_.request.matchdict['appname']
		filename = _28_.request.matchdict['filename']
		_24_ = os.path.join(_23_, filename)
		if _23_ == 'web' and os.path.isfile(_24_):

			return FileResponse(_24_, _28_.request)
		elif _23_ == 'ui' and filename == 'update.zip':
			_30_ = _18_._25_(_28_.request)
			return Response(body=_30_, content_type='application/zip')
		else:
			_24_ = os.path.join('web', 'user_data', _24_)
			if os.path.isfile(_24_):
				return FileResponse(_24_, _28_.request)
			raise HTTPNotFound(_23_+'/'+filename)
Exemplo n.º 5
0
 def proxy_or_redirect_download(self):
     request = self.request
     item_id = request.matchdict['id']
     item_table = request.matchdict['table']
     switcher = {
         "cia": CIA,
         "tdsx": TDSX,
         "arm9": ARM9,
         "smdh": SMDH,
         "xml": XML
     }
     item = DBSession.query(switcher.get(item_table, None)).get(item_id)
     if item:
         if item.path:
             # Verify cache file is there and valid.
             if verify_cache(item, settings=request.registry.settings):
                 filename = item.path.split('/')[-1]
                 response = FileResponse(
                     os.path.join(
                         url_to_cache_path(
                             item.url.url,
                             request.registry.settings['titledb.cache']),
                         'archive_root', item.path),
                     request=request,
                     content_type=mimetypes.guess_type(filename)[0])
                 response.content_disposition = 'attachment; filename="%s"' % filename
                 return response
             else:
                 return Response('404 Not Found', status='404 Not Found')
         else:
             return HTTPFound(location=item.url.url)
     return Response('404 Not Found', status='404 Not Found')
Exemplo n.º 6
0
    def __call__(self):

        data_path = self.request.registry.settings['climas.species_data_path']

        return FileResponse(os.path.join(data_path,
                                         self.request.matchdict['data_name']),
                            request=self.request)
Exemplo n.º 7
0
def create_app(settings):
    from pyramid.config import Configurator
    from pyramid.authorization import ACLAuthorizationPolicy
    from pyramid.path import AssetResolver
    from pyramid.response import FileResponse

    from h.auth import HybridAuthenticationPolicy
    from h.models import groupfinder

    authn_policy = HybridAuthenticationPolicy(callback=groupfinder)
    authz_policy = ACLAuthorizationPolicy()

    config = Configurator(
        settings=settings,
        authentication_policy=authn_policy,
        authorization_policy=authz_policy,
    )

    favicon = AssetResolver().resolve('h:favicon.ico')
    config.add_route('favicon', '/favicon.ico')
    config.add_view(
        lambda request: FileResponse(favicon.abspath(), request=request),
        route_name='favicon'
    )

    config.add_route('ok', '/ruok')
    config.add_view(lambda request: 'imok', renderer='string', route_name='ok')

    # Include all the pyramid subcomponents
    config.include(includeme)

    return config.make_wsgi_app()
Exemplo n.º 8
0
def download_file(request):
    # type: (Request) -> FileResponse
    """
    Download authorized vault file and remove it from the vault.
    """
    file_id, auth = get_vault_auth(request)
    vault_file = get_authorized_file(file_id, auth, request)

    class FileIterAndDelete(FileIter):
        @property
        def filelike(self):
            return self.file

        def close(self):
            super().close()
            os.remove(self.file.name)

    path = get_vault_path(vault_file, request)
    out_path = decrypt_from_vault(vault_file, path, delete_encrypted=True)
    headers = get_file_headers(out_path,
                               download_headers=True,
                               content_headers=True,
                               content_type=vault_file.format)
    request.environ["wsgi.file_wrapper"] = FileIterAndDelete
    resp = FileResponse(out_path, request=request)
    resp.headers.update(headers)
    return resp
Exemplo n.º 9
0
 def sized_preview_jpg_revision(self,
                                context,
                                request: TracimRequest,
                                hapic_data=None):  # nopep8
     """
     Obtain resized jpg preview of a specific revision of content.
     """
     app_config = request.registry.settings['CFG']
     api = ContentApi(
         current_user=request.current_user,
         session=request.dbsession,
         config=app_config,
     )
     content = api.get_one(hapic_data.path.content_id,
                           content_type=ContentType.Any)
     revision = api.get_one_revision(
         revision_id=hapic_data.path.revision_id, content=content)
     jpg_preview_path = api.get_jpg_preview_path(
         content_id=content.content_id,
         revision_id=revision.revision_id,
         page=hapic_data.query.page,
         height=hapic_data.path.height,
         width=hapic_data.path.width,
     )
     return FileResponse(jpg_preview_path)
Exemplo n.º 10
0
def locdata(request):
    locale = request.matchdict['locale']
    component = request.matchdict['component']

    mod = import_module(pkginfo.comp_mod(component))
    locale_path = Path(mod.__path__[0]) / 'locale'
    jed_path = locale_path / '{}.jed'.format(locale)

    if jed_path.is_file():
        return FileResponse(jed_path, content_type='application/json')

    # For english locale by default return empty translation, if
    # real translation file was not found. This might be needed if
    # instead of English strings we'll use msgid.

    if locale == 'en':
        return Response(json.dumps({
            "": {
                "domain": component,
                "lang": "en",
                "plural_forms": "nplurals=2; plural=(n != 1);"
            }
        }),
                        content_type='application/json',
                        charset='utf-8')

    return Response(json.dumps(dict(error="Locale data not found!")),
                    status_code=404,
                    content_type='application/json',
                    charset='utf-8')
Exemplo n.º 11
0
 def servecompiled(self):
     """Serve the compiled foma script of the morphology.
     :URL: ``PUT /morphologies/servecompiled/id``
     :param str id: the ``id`` value of a morphology.
     :returns: a stream of bytes -- the compiled morphology script.
     """
     morphology, id_ = self._model_from_id(eager=True)
     LOGGER.info(
         'Attempting to serve the compiled foma script of'
         ' morphology %d.', id_)
     if not morphology:
         self.request.response.status_int = 404
         msg = 'There is no morphology with id {}'.format(id_)
         LOGGER.warning(msg)
         return {'error': msg}
     if not h.foma_installed():
         self.request.response.status_int = 400
         msg = 'Foma and flookup are not installed.'
         LOGGER.warning(msg)
         return {'error': msg}
     compiled_path = morphology.get_file_path('binary')
     if not os.path.isfile(compiled_path):
         self.request.response.status_int = 400
         msg = 'Morphology {} has not been compiled yet.'.format(
             morphology.id)
         LOGGER.warning(msg)
         return {'error': msg}
     LOGGER.info('Served the compiled foma script of'
                 ' morphology %d.', id_)
     return FileResponse(compiled_path, request=self.request)
Exemplo n.º 12
0
def locdata(request):
    locale = request.matchdict['locale']
    component = request.matchdict['component']

    skey = request.GET.get('skey')
    if skey and skey == request.env.pyramid.static_key[1:]:
        request.response.cache_control = 'public, max-age=31536000'

    mod = import_module(pkginfo.comp_mod(component))
    locale_path = Path(mod.__path__[0]) / 'locale'
    jed_path = locale_path / '{}.jed'.format(locale)

    if jed_path.is_file():
        return FileResponse(jed_path, content_type='application/json')

    # For english locale by default return empty translation, if
    # real translation file was not found. This might be needed if
    # instead of English strings we'll use msgid.

    if locale == 'en':
        return {
            "": {
                "domain": component,
                "lang": "en",
                "plural_forms": "nplurals=2; plural=(n != 1);"
            }
        }

    request.response.status_code = 404
    return dict(error="Locale data not found!")
Exemplo n.º 13
0
def try_respond_image_resizer(root_path: Path, request):
    match = THUMBNAIL_REGEX.match(request.path_info)
    if not match:
        return None

    local_path = root_path / match.group(1).lstrip("/")

    if not local_path.exists():
        return respond_not_found(request)

    thumb_path = thumbs_dir / (
        hashlib.sha1(str(local_path).encode()).hexdigest() + ".jpg"
    )

    if not thumb_path.exists():
        try:
            image = Image.open(str(local_path)).convert("RGB")
            thumb = ImageOps.fit(image, (150, 150), Image.ANTIALIAS)
        except Exception as ex:
            logging.error(ex)
            return respond_not_found(request)
        else:
            thumbs_dir.mkdir(exist_ok=True, parents=True)
            with thumb_path.open("wb") as handle:
                thumb.save(handle, format="jpeg")

    return FileResponse(str(thumb_path), content_type="image/jpeg")
Exemplo n.º 14
0
    def whitenoise_tween(request):
        whn = request.registry.whitenoise

        if whn.autorefresh:
            static_file = whn.find_file(request.path_info)
        else:
            static_file = whn.files.get(request.path_info)

        # We could not find a static file, so we'll just continue processing
        # this as normal.
        if static_file is None:
            return handler(request)

        request_headers = dict(kv for kv in request.environ.items()
                               if kv[0].startswith("HTTP_"))

        if request.method not in {"GET", "HEAD"}:
            return HTTPMethodNotAllowed()
        else:
            path, headers = static_file.get_path_and_headers(request_headers)
            headers = MultiDict(headers)

            resp = FileResponse(
                path,
                request=request,
                content_type=headers.pop("Content-Type", None),
                content_encoding=headers.pop("Content-Encoding", None),
            )
            resp.md5_etag()
            resp.headers.update(headers)

            return resp
Exemplo n.º 15
0
def download_file(context, request):
    registration_info = FileRegistry.get_registration_info(
        request.matchdict['reg_id'])
    file_path = registration_info[
        HPZ.FILE_PATH] if registration_info is not None else None
    file_name = registration_info[
        HPZ.FILE_NAME] if registration_info is not None else None

    is_valid_file = validate_file(request)
    dev_mode = request.registry.settings['mode'] == 'dev'
    if is_valid_file and dev_mode:
        response = FileResponse(file_path, request=request)
        response.content_disposition = 'attachment; filename={}'.format(
            file_name)
        logger.info('File %s was successfully served in local environment',
                    file_path)
    elif is_valid_file:
        response = Response(
            headers={
                'X-Sendfile': file_path,
                'Content-Type': '',
                'Content-Disposition': 'attachment; filename={}'.format(
                    file_name),
            })
        logger.info('File %s was successfully downloaded', file_path)
    else:
        response = Response(status_code=404)
    return response
Exemplo n.º 16
0
def favicon(request):
    here = os.path.dirname(__file__)
    icon = os.path.join(here, 'static', 'favicon.ico')
    try:
        return FileResponse(icon, request=request)
    except OSError:
        return HTTPNotFound()
Exemplo n.º 17
0
def lidar_shp(request):
    """
        Transform the profile line (2D) to ESRI shapefile
    """

    # set up paths
    geom = geojson.loads(request.params['geom'],
                         object_hook=geojson.GeoJSON.to_instance)
    outputDir = request.registry.settings['lidar_output_dir'].replace(
        '\\', '/')
    outputShp = outputDir + str(uuid.uuid4())

    # Create pyshp polyline ESRI shapfile and write it to disk
    shapeParts = []
    outShp = shapefile.Writer(shapefile.POLYLINE)
    outShp.line(parts=[geom.coordinates])
    outShp.field('FIRST_FLD', 'C', '40')
    outShp.record('First', 'Line')
    outShp.save(outputShp)

    # zip the shapefile for nice single output
    zipShp = zip(outputShp + '.zip', mode='w')
    zipShp.write(outputShp + '.shp', os.path.basename(outputShp + '.shp'))
    zipShp.write(outputShp + '.dbf', os.path.basename(outputShp + '.dbf'))
    zipShp.write(outputShp + '.shx', os.path.basename(outputShp + '.shx'))
    zipShp.close()

    # remove files
    os.remove(outputShp + '.shx')
    os.remove(outputShp + '.shp')
    os.remove(outputShp + '.dbf')

    return FileResponse(outputShp + '.zip',
                        request=request,
                        content_type='application/zip')
    def get(self):
        param = self.request.matchdict.get('param')

        if param in self.valid_params:
            try:
                data = str_to_obj(self.db.get(param))
            except ValueError:
                data = None
                logger.warn('Cache is empty!',
                            extra=journal_context({'MESSAGE_ID': API_INFO},
                                                  {}))

            if data:
                response = Response(body=json.dumps(data),
                                    content_type='application/json',
                                    status=200)
            else:
                file_path = os.path.join(self.DATA_PATH,
                                         '{}.json'.format(param))
                response = FileResponse(path=file_path,
                                        request=self.request,
                                        content_type='application/json')
        else:
            msg = 'URL parameter must be "inn.json", "atc.json", "inn2atc.json" or "atc2inn.json"'
            data = {
                'success': False,
                'error': True,
                'message':
                'URL parameter "{}" not valid. {}'.format(param, msg)
            }
            response = Response(body=json.dumps(data),
                                content_type='application/json',
                                status=400)

        return response
Exemplo n.º 19
0
def getfile(request):
    """
    GET metadata from DB, fetch file and serve it to the client
    TODO: implement nice error handling
    """

    # get filename from url
    filename = request.matchdict['name']
    session = DBSession()
    # fetch metadata for this file
    result = session.query(MyModel).filter_by(id=filename)

    if result.count() < 1:
        request.response.status = 404
        return {}
    elif result.count() == 1:
        res = result.first()
        filepath = res.path
        response = FileResponse(
            filepath,
            request=request,
            content_type=str(res.filetype)
        )
        return response

    # TODO: handle error
    request.response.status = 404
    return {}
Exemplo n.º 20
0
 def resume(self):
     content_type, encoding = mimetypes.guess_type(self.current_resume)
     response = FileResponse(self.current_resume,
                             request=self.request,
                             content_type=content_type,
                             content_encoding=encoding)
     return response
Exemplo n.º 21
0
def dist(request):
    dist_path = request.env.jsrealm.options['dist_path']
    filename = os.path.join(dist_path, *request.matchdict['subpath'])
    if os.path.isfile(filename):
        return FileResponse(filename, cache_max_age=3600, request=request)
    else:
        raise HTTPNotFound()
Exemplo n.º 22
0
def favicon_view(request):
    # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/assets.html#registering-a-view-callable-to-serve-a-static-asset
    icon = resource_filename('patzilla.navigator', 'static/favicon.ico')
    if os.path.isfile(icon):
        return FileResponse(icon, request=request)
    else:
        return HTTPNotFound()
Exemplo n.º 23
0
def locdata(request):
    locale = request.matchdict['locale']
    component = request.matchdict['component']
    introspector = request.registry.introspector
    for itm in introspector.get_category('translation directories'):
        tdir = itm['introspectable']['directory']
        jsonpath = os.path.normpath(
            os.path.join(tdir, locale, 'LC_MESSAGES', component) + '.jed')
        if os.path.isfile(jsonpath):
            return FileResponse(jsonpath, content_type=b'application/json')

    # For english locale by default return empty translation, if
    # real translation file was not found. This might be needed if
    # instead of English strings we'll use msgid.

    if locale == 'en':
        return Response(json.dumps({
            "": {
                "domain": component,
                "lang": "en",
                "plural_forms": "nplurals=2; plural=(n != 1);"
            }
        }),
                        content_type=b'application/json')

    return Response(json.dumps(dict(error="Locale data not found!")),
                    status_code=404,
                    content_type=b'application/json')
Exemplo n.º 24
0
 def show_label(self):
     """ Return the specified file based on the matchdict serial
     parameter, or the placeholder image if not found.
     """
     serial = slugify(self.request.matchdict["serial"])
     filename = "label_files/%s/label.png" % serial
     return FileResponse(filename)
Exemplo n.º 25
0
 def download(self):
     upload = Upload.get(self.request.params.get('id'))
     response = FileResponse(
         self.request.storage.base_path + '/' + upload.path,
         request=self.request,
     )
     return response
Exemplo n.º 26
0
 def mainPlot_view(self):
     response = FileResponse(
         self.graph.produceMain(self.HTML_GET('sensorType'),self.getDate()),
         request=self.request,
         content_type='image/png'
         )
     return response
Exemplo n.º 27
0
def crossorigin(request, page):
    log.info(f'CORS request for {page} by {User.get_username(request)}')
    response = FileResponse(f'michelanglo_app/static/{page}', request)
    response.headers.update({
        'Access-Control-Allow-Origin': '*',
    })
    return response
Exemplo n.º 28
0
def client_bogus_favicon(request):
	icon = os.path.join(
		os.path.dirname(__file__),
		'static',
		'favicon.ico'
	)
	return FileResponse(icon, request=request)
Exemplo n.º 29
0
    def __call__(self, context, request):
        if self.use_subpath:
            path_tuple = request.subpath
        else:
            path_tuple = traversal_path_info(request.environ['PATH_INFO'])

        path = _secure_path(path_tuple)

        if path is None:
            raise HTTPNotFound('Out of bounds: %s' % request.url)

        if self.package_name: # package resource

            resource_path ='%s/%s' % (self.docroot.rstrip('/'), path)
            if resource_isdir(self.package_name, resource_path):
                if not request.path_url.endswith('/'):
                    self.add_slash_redirect(request)
                resource_path = '%s/%s' % (resource_path.rstrip('/'),self.index)
            if not resource_exists(self.package_name, resource_path):
                raise HTTPNotFound(request.url)
            filepath = resource_filename(self.package_name, resource_path)

        else: # filesystem file

            # os.path.normpath converts / to \ on windows
            filepath = normcase(normpath(join(self.norm_docroot, path)))
            if isdir(filepath):
                if not request.path_url.endswith('/'):
                    self.add_slash_redirect(request)
                filepath = join(filepath, self.index)
            if not exists(filepath):
                raise HTTPNotFound(request.url)

        return FileResponse(filepath, request, self.cache_max_age)
Exemplo n.º 30
0
 def proxy_or_redirect_cia(self):
     request = self.request
     if request.matchdict and request.matchdict['titleid']:
         titleid = request.matchdict['titleid']
         sq = DBSession.query(
             CIA.entry_id, CIA.titleid,
             func.min(CIA.created_at).label('mca')).group_by(
                 CIA.titleid).order_by(CIA.id).subquery()
         cia = DBSession.query(CIA).join(
             sq,
             and_(CIA.titleid == sq.c.titleid,
                  CIA.entry_id == sq.c.entry_id)).filter(
                      CIA.titleid.ilike(titleid)).filter(
                          CIA.active == True).order_by(
                              CIA.created_at.desc()).first()
         if cia:
             if cia.path:
                 # Verify cache file is there and valid.
                 if verify_cache(cia, settings=request.registry.settings):
                     return FileResponse(
                         os.path.join(
                             url_to_cache_path(
                                 cia.url.url, request.registry.
                                 settings['titledb.cache']), 'archive_root',
                             cia.path),
                         request=request,
                         content_type='application/x-3ds-archive')
                 else:
                     return Response('404 Not Found',
                                     status='404 Not Found')
             else:
                 return HTTPFound(location=cia.url.url)
     return dict(error='TitleID not found.')