Ejemplo n.º 1
0
 def company_logo(self, dbname=None, **kw):
     imgname = 'login_background'
     imgext = '.jpg'
     placeholder = functools.partial(get_resource_path, 'funenc_theme', 'static', 'img')
     if request.session.db:
         dbname = request.session.db
     elif dbname is None:
         dbname = db_monodb()
     if not dbname:
         response = http.send_file(placeholder(imgname + imgext))
     else:
         try:
             registry = odoo.modules.registry.Registry(dbname)
             with registry.cursor() as cr:
                 cr.execute("""SELECT login_page_background_image
                                    FROM funenc_theme_style ORDER BY write_date DESC LIMIT 1
                               """)
                 row = cr.fetchone()
                 if row and row[0]:
                     image_base64 = base64.b64decode(row[0])
                     image_data = io.BytesIO(image_base64)
                     mimetype = guess_mimetype(image_base64, default='image/png')
                     imgext = '.' + mimetype.split('/')[1]
                     if imgext == '.svg+xml':
                         imgext = '.svg'
                     response = http.send_file(image_data, filename=imgname + imgext, mimetype=mimetype)
                 else:
                     response = http.send_file(placeholder(imgname + imgext))
         except Exception:
             response = http.send_file(placeholder(imgname + imgext))
     return response
Ejemplo n.º 2
0
 def website_logo(self, dbname=None, **kw):
     imgname = 'website_nologo.png'
     placeholder = functools.partial(get_module_resource, 'website_logo',
                                     'static', 'src', 'img')
     uid = None
     if request.session.db:
         dbname = request.session.db
         uid = request.session.uid
     elif dbname is None:
         dbname = db_monodb()
     if not uid:
         uid = SUPERUSER_ID
     if uid and dbname:
         try:
             # create an empty registry
             reg = registry.Registry(dbname)
             env = request.httprequest.environ
             domain = env.get('HTTP_HOST', '').split(':')[0]
             with reg.cursor() as cr:
                 image, mtime = self._image_logo_get(cr, domain)
                 if not image:
                     image, mtime = self._image_logo_get(cr, 'localhost')
                 if image:
                     response = http.send_file(image,
                                               filename=imgname,
                                               mtime=mtime)
                     return response
         except Exception:  # pragma: no cover
             _logger.exception(
                 _('Could not get website logo, falling back to default', ))
     return http.send_file(placeholder(imgname))
Ejemplo n.º 3
0
 def _get_company_image_response(self,
                                 dbname,
                                 field,
                                 placeholders,
                                 default_mimetype,
                                 company=None):
     uid = request.session.uid if request.session.db else None
     placeholder = self._get_company_image_placeholder()
     if request.session.db:
         dbname = request.session.db
     elif dbname is None:
         dbname = http.db_monodb()
     if not dbname:
         response = http.send_file(placeholder(placeholders[0]))
     else:
         uid = uid if uid else SUPERUSER_ID
         company_data = self._get_company_image_data(
             dbname, uid, field, company)
         if company_data and company_data[0]:
             image_data = base64.b64decode(company_data[0])
             mimetype = guess_mimetype(image_data, default=default_mimetype)
             extension = mimetypes.guess_extension(mimetype)
             response = http.send_file(io.BytesIO(image_data),
                                       filename=('logo%s' % extension),
                                       mimetype=mimetype,
                                       mtime=company_data[1])
         else:
             response = http.send_file(placeholder(placeholders[1]))
     return response
Ejemplo n.º 4
0
 def website_logo(self, dbname=None, **kw):
     imgname = 'logo.png'
     uid = None
     placeholder = functools.partial(get_resource_path, 'web', 'static',
                                     'src', 'img')
     if request.session.db:
         dbname = request.session.db
         uid = request.session.uid
     elif dbname is None:
         dbname = db_monodb()
     if not uid:
         uid = odoo.SUPERUSER_ID
     if uid and dbname:
         try:
             # create an empty registry
             registry = odoo.modules.registry.Registry(dbname)
             with registry.cursor() as cr:
                 cr.execute(
                     """
                     SELECT c.website_logo, c.write_date
                     FROM res_users u
                     LEFT JOIN res_company c
                     ON c.id = u.company_id
                     WHERE u.id = %s
                 """, (uid, ))
                 row = cr.fetchone()
                 if row and row[0]:
                     image_data = StringIO(str(row[0]).decode('base64'))
                     return http.send_file(image_data,
                                           filename=imgname,
                                           mtime=row[1])
         except Exception:
             pass
     return http.send_file(placeholder(imgname))
Ejemplo n.º 5
0
 def app_logo(self):
     imgname = "logo"
     imgext = ".png"
     request = http.request
     placeholder = functools.partial(
         get_resource_path, "web", "static", "src", "img"
     )
     if not request.env:
         return http.send_file(placeholder(imgname + imgext))
     try:
         key = "app.logo"
         image = (
             request.env["ir.config_parameter"]
             .sudo()
             .search_read(
                 [("key", "=", key)],
                 fields=["value", "write_date"],
                 limit=1,
             )
         )
         if image:
             image_base64 = base64.b64decode(image[0]["value"])
             image_data = io.BytesIO(image_base64)
             imgext = "." + (imghdr.what(None, h=image_base64) or "png")
             response = http.send_file(
                 image_data,
                 filename=imgname + imgext,
                 mtime=image[0]["write_date"],
             )
         else:
             response = http.send_file(placeholder("nologo.png"))
     except Exception:
         response = http.send_file(placeholder(imgname + imgext))
     return response
Ejemplo n.º 6
0
 def novid(self, thumb="", **kwargs):
     placeholder = functools.partial(get_resource_path, "ooshare", "static",
                                     "src", "img")
     if thumb:
         return http.send_file(placeholder("novid-thumb.jpg"),
                               mimetype="image/jpeg")
     return http.send_file(placeholder("novid.jpg"), mimetype="image/jpeg")
Ejemplo n.º 7
0
    def _logo(self, company=None, img='logo', fmt=None, **kwargs):
        if fmt and fmt not in IMAGE_FORMATS:
            raise ValueError(fmt)

        placeholder = functools.partial(get_resource_path, 'adaptiv_web',
                                        'static', 'src', 'img')
        ResCompany = request.env['res.company']

        if company:
            try:
                company = int(company)
            except ValueError:
                company = None
            else:
                company = ResCompany.browse([company]).exists()

        if not company:
            company = ResCompany.get_current()

        for try_fmt in [fmt] if fmt else IMAGE_FORMATS:
            field = '%s_%s' % (try_fmt, img)
            values = company.read([field, 'write_date'])[0]
            if values[field]:
                image = BytesIO(base64.b64decode(values[field]))
                return http.send_file(image,
                                      filename='%s.%s' % (img, try_fmt),
                                      mtime=values['write_date'])

        return http.send_file(
            placeholder('%s.%s' % (img, fmt or IMAGE_FORMATS[0])))
Ejemplo n.º 8
0
    def company_logo(self, dbname=None, **kw):
        imgname = 'placeholder.png'
        placeholder = functools.partial(get_module_resource, 'web', 'static',
                                        'src', 'img')
        dbname = request.session and request.session.db or db_monodb()
        uid = request.session and request.session.uid or odoo.SUPERUSER_ID

        if not dbname:
            response = http.send_file(placeholder(imgname))
        else:
            try:
                # create an empty registry
                registry = odoo.modules.registry.Registry(dbname)
                with registry.cursor() as cr:
                    cr.execute(
                        """
                        SELECT c.logo_web, c.write_date
                        FROM res_users u
                            LEFT JOIN res_company c ON c.id = u.company_id
                        WHERE u.id = %s
                    """, (uid))
                    row = cr.fetchone()
                    if row and row[0]:
                        image_data = StringIO(str(row[0]).decode('base64'))
                        response = http.send_file(image_data,
                                                  filename=imgname,
                                                  mtime=row[1])
                    else:
                        response = http.send_file(
                            placeholder('placeholder.png'))
            except Exception:
                response = http.send_file(placeholder(imgname))

        return response
Ejemplo n.º 9
0
    def company_logo(self, dbname=None, **kw):
        imgname = 'logo'
        imgext = '.png'
        placeholder = functools.partial(get_resource_path, 'web', 'static',
                                        'src', 'img')
        uid = None
        if request.session.db:
            dbname = request.session.db
            uid = request.session.uid
        elif dbname is None:
            dbname = db_monodb()

        if not uid:
            uid = odoo.SUPERUSER_ID

        if not dbname:
            response = http.send_file(placeholder(imgname + imgext))
        else:
            try:
                # create an empty registry
                registry = odoo.modules.registry.Registry(dbname)
                with registry.cursor() as cr:
                    company = int(
                        kw['company']) if kw and kw.get('company') else False
                    if company:
                        cr.execute(
                            """SELECT logo_web, write_date
	                                    FROM res_company
	                                   WHERE id = %s
	                               """, (company, ))
                    else:
                        cr.execute(
                            """SELECT c.logo_web, c.write_date
	                                    FROM res_users u
	                               LEFT JOIN res_company c
	                                      ON c.id = u.company_id
	                                   WHERE u.id = %s
	                               """, (uid, ))
                    row = cr.fetchone()
                    if row and row[0]:
                        image_base64 = base64.b64decode(row[0])
                        image_data = io.BytesIO(image_base64)
                        mimetype = guess_mimetype(image_base64,
                                                  default='image/png')
                        imgext = '.' + mimetype.split('/')[1]
                        if imgext == '.svg+xml':
                            imgext = '.svg'

                        response = http.send_file(image_data,
                                                  filename=imgname + imgext,
                                                  mimetype=mimetype,
                                                  mtime=row[1])
                    else:
                        response = http.send_file(placeholder('nologo.png'))
            except Exception:
                response = http.send_file(placeholder(imgname + imgext))

        return response
Ejemplo n.º 10
0
    def custom_logo(self, dbname=None, **kw):
        imgname = 'logo'
        imgext = '.png'
        # Here we are changing the default logo with logo selected on debrand settings
        company_logo = request.env['website'].sudo().search([])[0].company_logo
        custom_logo = tools.image_resize_image(company_logo, (150, None))
        placeholder = functools.partial(get_resource_path, 'web', 'static',
                                        'src', 'img')
        uid = None
        if request.session.db:
            dbname = request.session.db
            uid = request.session.uid
        elif dbname is None:
            dbname = db_monodb()

        if not uid:
            uid = odoo.SUPERUSER_ID

        if not dbname:
            response = http.send_file(placeholder(imgname + imgext))
        else:
            try:
                # create an empty registry
                registry = odoo.modules.registry.Registry(dbname)
                if custom_logo:
                    image_base64 = base64.b64decode(custom_logo)
                    image_data = io.BytesIO(image_base64)
                    imgext = '.' + (imghdr.what(None, h=image_base64) or 'png')
                    response = http.send_file(image_data,
                                              filename=imgname + imgext,
                                              mtime=None)
                else:
                    with registry.cursor() as cr:
                        cr.execute(
                            """SELECT c.logo_web, c.write_date
                                        FROM res_users u
                                   LEFT JOIN res_company c
                                          ON c.id = u.company_id
                                       WHERE u.id = %s
                                   """, (uid, ))
                        row = cr.fetchone()
                        if row and row[0]:
                            image_base64 = str(row[0]).decode('base64')
                            image_data = io.BytesIO(image_base64)
                            imgext = '.' + (imghdr.what(None, h=image_base64)
                                            or 'png')
                            response = http.send_file(image_data,
                                                      filename=imgname +
                                                      imgext,
                                                      mtime=row[1])
                        else:
                            response = http.send_file(
                                placeholder('nologo.png'))
            except Exception as e:
                _logger.warning('EXCEPT custom_logo: %s', e)
                response = http.send_file(placeholder(imgname + imgext))
        return response
Ejemplo n.º 11
0
    def stream(self, **kwargs):
        rest = SubsonicREST(kwargs)
        success, response = rest.check_login()
        if not success:
            return response

        trackId = kwargs.get("id")
        if trackId:
            track = request.env["oomusic.track"].browse([int(trackId)])
            if not track.exists():
                return rest.make_error(code="70", message="Song not found")
        else:
            return rest.make_error(
                code="10",
                message='Required int parameter "id" is not present')

        # Specific case of transcoding disabled globally
        ConfigParam = request.env["ir.config_parameter"].sudo()
        if ConfigParam.get_param("oomusic.trans_disabled"):
            return http.send_file(track.path)

        output_format = kwargs.get("format", rest._get_format())
        maxBitRate = int(kwargs.get("maxBitRate", 0))
        estimateContentLength = kwargs.get("estimateContentLength", False)

        # Only for video
        # timeOffset = kwargs.get('timeOffset')
        # size = kwargs.get('size')
        # converted = kwargs.get('size', False)

        fn_ext = os.path.splitext(track.path)[1]

        # As specified in Subsonic API: if maxBitRate is set to zero, no limit is imposed. We also
        # avoid any upsampling.
        if fn_ext[1:] == output_format and (not maxBitRate
                                            or maxBitRate >= track.bitrate):
            return http.send_file(track.path)

        Transcoder = (request.env["oomusic.transcoder"].search([
            ("output_format.name", "=", output_format)
        ]).filtered(lambda r: fn_ext[1:] not in r.mapped("black_formats.name"))
                      )
        Transcoder = Transcoder[0] if Transcoder else False
        if Transcoder:
            generator = Transcoder.transcode(int(trackId),
                                             bitrate=maxBitRate).stdout
            mimetype = Transcoder.output_format.mimetype
        else:
            _logger.warning('Could not find converter from "%s" to "%s"',
                            fn_ext[1:], output_format)
            return http.send_file(track.path)

        data = wrap_file(request.httprequest.environ,
                         generator,
                         buffer_size=Transcoder.buffer_size * 1024)
        return Response(data, mimetype=mimetype, direct_passthrough=True)
Ejemplo n.º 12
0
    def login_logo(self, dbname=None, **kw):
        imgname = 'logo'
        imgext = '.png'
        placeholder = functools.partial(get_resource_path,
                                        'web_custom_login_page', 'static',
                                        'src', 'img')
        uid = None
        if request.session.db:
            dbname = request.session.db
            uid = request.session.uid
        elif dbname is None:
            dbname = db_monodb()

        if not uid:
            uid = odoo.SUPERUSER_ID

        if not dbname:
            response = http.send_file(placeholder(imgname + imgext))
        else:
            try:
                # create an empty registry
                registry = odoo.modules.registry.Registry(dbname)
                with registry.cursor() as cr:
                    company = int(kw['company']) if kw and kw.get(
                        'company') else False
                    if company:
                        cr.execute("""SELECT logo_web, write_date
                                        FROM res_company
                                       WHERE id = %s
                                   """, (company,))
                    else:
                        cr.execute("""SELECT c.logo_web, c.write_date
                                        FROM res_users u
                                   LEFT JOIN res_company c
                                          ON c.id = u.company_id
                                       WHERE u.id = %s
                                   """, (uid,))
                    row = cr.fetchone()
                    companies = request.env['res.company'].search([])
                    if row and row[0] and len(companies) == 1:
                        image_base64 = str(row[0]).decode('base64')
                        image_data = StringIO(image_base64)
                        imgext = '.' + (imghdr.what(None, h=image_base64) or
                                        'png')
                        response = http.send_file(image_data,
                                                  filename=imgname + imgext,
                                                  mtime=row[1])
                    else:
                        response = http.send_file(
                            placeholder('nologinimage.png'))
            except Exception:
                response = http.send_file(placeholder(imgname + imgext))

        return response
Ejemplo n.º 13
0
    def company_digital_signature(self, dbname=None, id=None, **kw):
        uid = id
        addons_path = http.addons_manifest['web_widget_digitized_signature'][
            'addons_path']

        if request.session.db:
            dbname = request.session.db
            if uid is None:
                uid = request.session.uid
        elif dbname is None:
            dbname = db_monodb()

        if not uid:
            uid = odoo.SUPERUSER_ID

        if dbname:
            try:
                # create an empty registry
                registry = odoo.modules.registry.Registry(dbname)
                with registry.cursor() as cr:
                    cr.execute(
                        """SELECT u.digital_signature, u.write_date
                                    FROM res_users u
                                    WHERE u.id = %s
                               """, (uid, ))
                    row = cr.fetchone()
                    if row and row[0]:
                        image_base64 = base64.b64decode(row[0])
                        image_data = io.BytesIO(image_base64)
                        imgext = '.' + (imghdr.what(None, h=image_base64)
                                        or 'png')
                        response = http.send_file(
                            image_data,
                            filename='digital_signature' + imgext,
                            mtime=row[1])
                    else:
                        # _logger.info("IMAGE %s" % os.path.join(addons_path, 'web_widget_digitized_signature', 'static', 'src', 'img', 'sign.png'))
                        response = http.send_file(
                            open(
                                os.path.join(addons_path,
                                             'web_widget_digitized_signature',
                                             'static', 'src', 'img',
                                             'sign.png'), 'rb'))
                    #_logger.info("SIGNATURE ROW %s" % row)
            except Exception:
                response = http.send_file(
                    open(
                        os.path.join(addons_path,
                                     'web_widget_digitized_signature',
                                     'static', 'src', 'img', 'sign.png'),
                        'rb'))
        #_logger.info("SIGNATURE %s:%s" % (dbname, uid))
        return response
Ejemplo n.º 14
0
    def company_email_logo(self, dbname=None, **kw):
        imgname = 'logo_email'
        imgext = '.png'
        placeholder = functools.partial(get_resource_path, 'l10n_bg_extend', 'static', 'img')
        uid = None
        if request.session.db:
            dbname = request.session.db
            uid = request.session.uid
        elif dbname is None:
            dbname = db_monodb()

        if not uid:
            uid = odoo.SUPERUSER_ID

        if not dbname:
            response = http.send_file(placeholder(imgname + imgext))
        else:
            try:
                # create an empty registry
                registry = odoo.modules.registry.Registry(dbname)
                with registry.cursor() as cr:
                    company = int(kw['company']) if kw and kw.get('company') else False
                    lang = kw['lang'] if kw and kw.get('lang') else 'en_EN'
                    mail_name = 'logo_mail_%s' % lang.split("_")[0]
                    cr.execute("SELECT column_name FROM information_schema.columns "
                               "WHERE table_name = 'res_partner' AND column_name = '%s'", (mail_name,))
                    if not cr.fetchone():
                        mail_name = 'logo_mail'
                    if company:
                        cr.execute("""SELECT %s, write_date
                                        FROM res_company
                                       WHERE id = %s
                                   """, (mail_name, company,))
                    else:
                        cr.execute("""SELECT c.%s, c.write_date
                                        FROM res_users u
                                   LEFT JOIN res_company c
                                          ON c.id = u.company_id
                                       WHERE u.id = %s
                                   """, (mail_name, uid,))
                    row = cr.fetchone()
                    if row and row[0]:
                        image_base64 = base64.b64decode(row[0])
                        image_data = io.BytesIO(image_base64)
                        imgext = '.' + (imghdr.what(None, h=image_base64) or 'png')
                        response = http.send_file(image_data, filename=imgname + imgext, mtime=row[1])
                    else:
                        response = http.send_file(placeholder('nologo.png'))
            except Exception:
                response = http.send_file(placeholder(imgname + imgext))

        return response
Ejemplo n.º 15
0
 def backend_logo(self):
     imgname = 'logo'
     imgext = '.png'
     placeholder = functools.partial(get_resource_path, 'web', 'static',
                                     'src', 'img')
     backend_logo = request.env["ir.config_parameter"].get_param(
         "backend_logo", default=None)
     if not backend_logo:
         response = http1.send_file(placeholder(imgname + imgext))
         return response
     image_data = StringIO(str(backend_logo).decode('base64'))
     response = http1.send_file(image_data, filename='logo', mtime=False)
     return response
Ejemplo n.º 16
0
    def stream(self, **kwargs):
        rest = SubsonicREST(kwargs)
        success, response = rest.check_login()
        if not success:
            return response

        trackId = kwargs.get('id')
        if trackId:
            track = request.env['oomusic.track'].browse([int(trackId)])
            if not track.exists():
                return rest.make_error(code='70', message='Song not found')
        else:
            return rest.make_error(
                code='10',
                message='Required int parameter "id" is not present')

        maxBitRate = int(kwargs.get('maxBitRate', 0))
        output_format = kwargs.get('format', 'mp3')
        estimateContentLength = kwargs.get('estimateContentLength', False)

        # Only for video
        # timeOffset = kwargs.get('timeOffset')
        # size = kwargs.get('size')
        # converted = kwargs.get('size', False)

        fn_ext = os.path.splitext(track.path)[1]

        # As specified in Subsonic API: if maxBitRate is set to zero, no limit is imposed. We also
        # avoid any upsampling.
        if fn_ext[1:] == output_format and (not maxBitRate
                                            or maxBitRate >= track.bitrate):
            return http.send_file(track.path)

        Transcoder = request.env['oomusic.transcoder'].search([
            ('output_format.name', '=', output_format)
        ]).filtered(lambda r: fn_ext[1:] not in r.mapped('black_formats').
                    mapped('name'))
        Transcoder = Transcoder[0] if Transcoder else False
        if Transcoder:
            generator = Transcoder.transcode(int(trackId),
                                             bitrate=maxBitRate).stdout
            mimetype = Transcoder.output_format.mimetype
        else:
            _logger.warning('Could not find converter from "%s" to "%s"',
                            fn_ext[1:], output_format)
            return http.send_file(track.path)

        data = wrap_file(request.httprequest.environ,
                         generator,
                         buffer_size=Transcoder.buffer_size * 1024)
        return Response(data, mimetype=mimetype, direct_passthrough=True)
Ejemplo n.º 17
0
Archivo: main.py Proyecto: JohnLYH/app
    def fj2(self, id, **kw):
        attachment = request.env['ir.attachment'].sudo().search_read(
            [('id', '=', int(id))],
            ["name", "datas", "res_model", "res_id", "type", "url"])
        if attachment:
            attachment = attachment[0]
        else:
            return local_redirect('/td/<id>')

        if attachment["type"] == "url":
            if attachment["url"]:
                return local_redirect(attachment["url"])
            else:
                return request.not_found()

        elif attachment["datas"]:
            # 不加byteio 报错'bytes' object has no attribute 'seek'
            data = io.BytesIO(base64.standard_b64decode(attachment["datas"]))
            # return http.send_file(data, filename=attachment['name'], as_attachment=True)
            return http.send_file(data,
                                  filename=quote((attachment['name']),
                                                 'utf-8'),
                                  as_attachment=True)

            # 名称中文问题解决方法---quote更彻底
            # return http.send_file(data, filename=content_disposition(attachment['name']), as_attachment=True)
            #return http.send_file(data, filename=quote((attachment['name']), 'utf-8'), as_attachment=True)
        else:
            return request.not_found(description='ByeBye')
Ejemplo n.º 18
0
    def trans(self, track_id, output_format, seek=0, **kwargs):
        Track = request.env['oomusic.track'].browse([track_id])
        fn_ext = os.path.splitext(Track.path)[1]

        Transcoder = request.env['oomusic.transcoder'].search(
            [('input_formats.name', '=', fn_ext[1:]),
             ('output_format.name', '=', output_format)],
            limit=1,
        )
        if Transcoder:
            generator = Transcoder.transcode(track_id, seek=seek).stdout
            mimetype = Transcoder.output_format.mimetype
        if not Transcoder:
            _logger.warning('Could not find converter from "%s" to "%s"',
                            fn_ext[1:], output_format)
            return http.send_file(Track.path)

        # FIXME: see http://librelist.com/browser/flask/2011/10/5/response-to-a-range-request/#1e95dd715f412161d3db2fc8aaf8666f

        # Set a buffer size of 200 KB. The default value (8 KB) seems too small and leads to chunk
        # download errors. Since the player is not fault-tolerant, a single download error leads to
        # a complete stop of the music. Maybe consider this value as a user option for people with
        # bad network.
        data = wrap_file(request.httprequest.environ,
                         generator,
                         buffer_size=Transcoder.buffer_size * 1024)
        return Response(data, mimetype=mimetype, direct_passthrough=True)
Ejemplo n.º 19
0
    def get_image(self, glass_name, width, height, strBlocks, **k):
        root = odoo.tools.config['glass_root_path']
        blocks = json.loads(strBlocks)

        dest = Image.new('L', (width, height))
        left = 0
        top = 0
        for x in range(len(blocks)):
            for y in range(len(blocks[x]) - 1, -1, -1):
                b = blocks[x][y]
                if b is None or b['bHasIntersection'] == False:
                    continue

                imgFile = '%s/%s/JpegFile/IP%d/AoiL_IP%d_scan%d_block%d.jpg' % (
                    root, glass_name, b['iIPIndex'] + 1, b['iIPIndex'],
                    b['iScanIndex'], b['iBlockIndex'])
                with Image.open(imgFile) as im:
                    im = im.transpose(Image.FLIP_TOP_BOTTOM)
                    region = im.crop(
                        (b['iInterSectionStartX'], im.height -
                         (b['iInterSectionStartY'] + b['iInterSectionHeight']),
                         b['iInterSectionStartX'] + b['iInterSectionWidth'],
                         im.height - b['iInterSectionStartY']))
                    dest.paste(region, (left, top))
                    if y == 0:
                        left += region.width
                        top = 0
                    else:
                        top += region.height

        output = io.BytesIO()
        dest.save(output, format="JPEG")
        response = http.send_file(output, filename="imgname.jpg")
        return response
Ejemplo n.º 20
0
    def getCoverArt(self, **kwargs):
        rest = SubsonicREST(kwargs)
        success, response = rest.check_login()
        if not success:
            return response

        folderId = kwargs.get('id')
        if folderId:
            try:
                if 'al-' in folderId:
                    folder = request.env['oomusic.album'].browse(
                        [int(folderId.split('-')[-1])])
                else:
                    folder = request.env['oomusic.folder'].browse(
                        [int(folderId.split('-')[-1])])
                if not folder.exists():
                    return rest.make_error(code='70',
                                           message='Folder not found')
            except:
                folder = request.env['oomusic.folder']
        else:
            return rest.make_error(
                code='10',
                message='Required int parameter "id" is not present')

        image = folder.image_medium or 'R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
        image_stream = StringIO.StringIO(image.decode('base64'))
        image_ext = '.' + (imghdr.what(image_stream) or 'png')
        return http.send_file(image_stream, filename=folderId + image_ext)
Ejemplo n.º 21
0
 def down_user(self, **kwargs):
     obj = request.env[kwargs['model']].browse(int(kwargs['id']))
     if not obj.exists():
         abort(404)
     tracks = obj._get_track_ids()
     flatten = bool(int(kwargs.get('flatten', '0')))
     return http.send_file(tracks._build_zip(flatten=flatten), as_attachment=True)
Ejemplo n.º 22
0
 def getAliQRCode(self, **kwargs):
     order_id = kwargs.get('order_id') #客户端生成的订单号
     goodsName = kwargs.get('goodsName')
     goodsPrice = float(kwargs.get('goodsPrice'))
 
     toolUtil = AliNativePayUtil()
     code_url=toolUtil.getAlipayUrl(order_id,goodsName,goodsPrice)
     if code_url:
         res_info = code_url
         # 如果成功获得支付链接,则写入一条订单记录
         #todo
     else:
         res_info = "二维码失效"
     qr = qrcode.QRCode(
         version=1,
         error_correction=qrcode.constants.ERROR_CORRECT_H,
         box_size=10,
         border=1
     )
     qr.add_data(res_info)
     img = qr.make_image()
     byte_io = BytesIO()
     img.save(byte_io, 'PNG')
     byte_io.seek(0)
     return http.send_file(byte_io, mimetype='image/png')
Ejemplo n.º 23
0
    def send_fonts_file(self, id, name):
        """
        WARNING
        -------
        This route (/fonts/) is a rather iffy assumption which could
        cause troubles.  Of course this could be requested by other
        parts, but not yet in standard Odoo routes.

        :param int id: The ID of the file (attachment) which requests the fonts file.
            File(s) requesting this font file, are CSS files (formio.js library).
        :param str name: The name of the fontfile in request.
        """

        ir_attach = request.env['ir.attachment'].sudo()
        attach = ir_attach.browse(id)
        if not attach.formio_asset_formio_version_id:
            msg = 'Request expects a Forms (formio.js) fonts file (id: %s, name: %s' % (
                id, name)
            _logger.warning(msg)
            return request.not_found(msg)

        attach_dir = dirname(attach.store_fname)
        fonts_dir = '{attach_dir}/fonts/'.format(attach_dir=attach_dir)
        fontfile_path = request.env['ir.attachment']._full_path(fonts_dir)
        fontfile_path += '/%s' % name

        return http.send_file(fontfile_path)
Ejemplo n.º 24
0
    def down(self, **kwargs):
        down = (request.env["oomusic.download"].sudo().search(
            [
                ("access_token", "=", kwargs["token"]),
                ("expiration_date", ">=", fields.Date.today()),
            ],
            limit=1,
        ))
        if not down:
            abort(404)

        # Set a minimum delay between link access to avoid overload
        now = fields.Datetime.now()
        if down.access_date and (now -
                                 down.access_date).seconds < down.min_delay:
            raise Forbidden(
                _("Too many requests received. Please try again in a few minutes."
                  ))
        down._update_access_date(now)

        # Get the ZIP file
        obj_sudo = request.env[down.res_model].sudo().browse(down.res_id)
        tracks = obj_sudo._get_track_ids()
        return http.send_file(tracks._build_zip(flatten=down.flatten,
                                                name=kwargs["token"]),
                              as_attachment=True)
Ejemplo n.º 25
0
    def download_attachment(self, path, name):
        file_to_download = path + '/' + name
        file_name = name

        return http.send_file(file_to_download,
                              filename=file_name,
                              as_attachment=True)
Ejemplo n.º 26
0
    def company_logo(self, dbname=None, **kw):
        imgname = "logo.png"
        default_logo_module = "web_debranding"
        if request.session.db:
            default_logo_module = request.env["ir.config_parameter"].get_param(
                "web_debranding.default_logo_module")
        placeholder = functools.partial(get_module_resource,
                                        default_logo_module, "static", "src",
                                        "img")
        uid = None
        if request.session.db:
            dbname = request.session.db
            uid = request.session.uid
        elif dbname is None:
            dbname = db_monodb()

        if not uid:
            uid = odoo.SUPERUSER_ID

        if not dbname:
            response = http.send_file(placeholder(imgname))
        else:
            try:
                # create an empty registry
                registry = odoo.modules.registry.Registry(dbname)
                with registry.cursor() as cr:
                    cr.execute(
                        """SELECT c.logo_web, c.write_date
                                    FROM res_users u
                               LEFT JOIN res_company c
                                      ON c.id = u.company_id
                                   WHERE u.id = %s
                               """,
                        (uid, ),
                    )
                    row = cr.fetchone()
                    if row and row[0]:
                        image_data = StringIO(str(row[0]).decode("base64"))
                        response = http.send_file(image_data,
                                                  filename=imgname,
                                                  mtime=row[1])
                    else:
                        response = http.send_file(placeholder("nologo.png"))
            except Exception:
                response = http.send_file(placeholder(imgname))

        return response
Ejemplo n.º 27
0
    def browse(self, **kwargs):
        link, doc, doc_abspath = self._get_link(**kwargs)

        # Download file or display directory content
        if os.path.isfile(doc_abspath):
            # Set a minimum delay between file access to avoid overload
            now = fields.Datetime.now()
            if link.access_date and (
                    now - link.access_date).seconds < link.min_delay:
                raise Forbidden(
                    "Too many requests received. Please try again in a few minutes."
                )
            link._update_access_date(now)
            return http.send_file(doc_abspath, as_attachment=True)

        elif os.path.isdir(doc_abspath):
            values = {
                "doc":
                doc,
                "gallery":
                "/ooshare/gallery?token={}&doc={}".format(
                    kwargs["token"], doc),
                "back": {
                    "name":
                    "{}{}".format("..", os.path.sep),
                    "url":
                    "/ooshare/browse?token={}&doc={}".format(
                        kwargs["token"],
                        os.path.join(
                            *(doc_abspath.replace(link.doc_abspath, ".").split(
                                os.path.sep)[:-1] or ["."])),
                    ),
                },
                "dirs":
                sorted(
                    [{
                        "name":
                        "{}{}".format(f.name, os.path.sep),
                        "url":
                        "/ooshare/browse?token={}&doc={}".format(
                            kwargs["token"], os.path.join(doc, f.name)),
                    } for f in os.scandir(doc_abspath) if f.is_dir()],
                    key=lambda d: d["name"],
                ),
                "files":
                sorted(
                    [{
                        "name":
                        f.name,
                        "url":
                        "/ooshare/browse?token={}&doc={}".format(
                            kwargs["token"], os.path.join(doc, f.name)),
                    } for f in os.scandir(doc_abspath) if f.is_file()],
                    key=lambda d: d["name"],
                ),
            }
            return request.render("ooshare.browse", values)
        else:
            abort(404)
Ejemplo n.º 28
0
    def training_headers(self, dbname=None, **kw):
        imgname = 'logo'
        imgext = '.png'
        placeholder = functools.partial(get_resource_path, 'web', 'static',
                                        'src', 'img')
        uid = None
        if request.session.db:
            dbname = request.session.db
            uid = request.session.uid
        elif dbname is None:
            dbname = db_monodb()

        if not uid:
            uid = odoo.SUPERUSER_ID

        if not dbname:
            response = http.send_file(placeholder(imgname + imgext))
        else:
            try:
                # create an empty registry
                image = False
                registry = odoo.modules.registry.Registry(dbname)
                with registry.cursor() as cr:
                    training_record = int(
                        kw['record']) if kw and kw.get('record') else False
                    cr.execute(
                        """SELECT image_small, 
                                            FROM product_product
                                           WHERE id = %s
                                       """, (training_record, ))

                    row = cr.fetchone()
                    if row and row[0]:
                        image_base64 = base64.b64decode(row[0])
                        image_data = io.BytesIO(image_base64)
                        imgext = '.' + (imghdr.what(None, h=image_base64)
                                        or 'png')
                        response = http.send_file(image_data,
                                                  filename=imgname + imgext,
                                                  mtime=row[1])
                    # else:
                    #     response = http.send_file(placeholder('nologo.png'))
            except Exception:
                response = http.send_file(placeholder(imgname + imgext))

        return response
Ejemplo n.º 29
0
 def download_logs(self):
     """
     Downloads the log file
     """
     if tools.config['logfile']:
         res = send_file(tools.config['logfile'], mimetype="text/plain", as_attachment=True)
         res.headers['Cache-Control'] = 'no-cache'
         return res
Ejemplo n.º 30
0
Archivo: main.py Proyecto: JohnLYH/app
 def export_tmp2(self, **kw):
     img_path = modules.get_resource_path('zz', 'static/img', 'fj0.png')
     #sendfile第一个参数可以为数据 也可以为文件路径
     # with open(img_path, 'rb') as f:
     #     image = f.read()
     # content = base64.b64encode(image)
     # image_path = base64.b64decode(content)
     return http.send_file(img_path, filename='fj0.png')
Ejemplo n.º 31
0
    def company_logo(self, dbname=None, **kw):
        imgname = 'logo.png'
        default_logo_module = 'web_debranding'
        if request.session.db:
            default_logo_module = request.env['ir.config_parameter'].sudo().get_param('web_debranding.default_logo_module')
        placeholder = functools.partial(get_module_resource, default_logo_module, 'static', 'src', 'img')
        uid = None
        if request.session.db:
            dbname = request.session.db
            uid = request.session.uid
        elif dbname is None:
            dbname = db_monodb()

        if not uid:
            uid = odoo.SUPERUSER_ID

        if not dbname:
            response = http.send_file(placeholder(imgname))
        else:
            try:
                # create an empty registry
                registry = odoo.modules.registry.Registry(dbname)
                with registry.cursor() as cr:
                    cr.execute("""SELECT c.logo_web, c.write_date
                                    FROM res_users u
                               LEFT JOIN res_company c
                                      ON c.id = u.company_id
                                   WHERE u.id = %s
                               """, (uid,))
                    row = cr.fetchone()
                    if row and row[0]:
                        image_data = io.BytesIO(base64.b64decode(row[0]))
                        response = http.send_file(image_data, filename=imgname, mtime=row[1])
                    else:
                        response = http.send_file(placeholder('nologo.png'))
            except Exception:
                response = http.send_file(placeholder(imgname))
        return response
Ejemplo n.º 32
0
    def download_attachment(self, attachment_id):
        # Check if this is a valid attachment id
        attachment = request.env['ir.attachment'].sudo().search_read(
            [('id', '=', int(attachment_id))],
            ["name", "datas", "file_type", "res_model", "res_id", "type", "url"]
        )

        if attachment:
            attachment = attachment[0]
        else:
            return redirect(self.orders_page)

        # Check if the user has bought the associated product
        res_model = attachment['res_model']
        res_id = attachment['res_id']
        purchased_products = request.env['account.invoice.line'].get_digital_purchases()

        if res_model == 'product.product':
            if res_id not in purchased_products:
                return redirect(self.orders_page)

        # Also check for attachments in the product templates
        elif res_model == 'product.template':
            P = request.env['product.product']
            template_ids = map(lambda x: P.browse(x).product_tmpl_id.id, purchased_products)
            if res_id not in template_ids:
                return redirect(self.orders_page)

        else:
            return redirect(self.orders_page)

        # The client has bought the product, otherwise it would have been blocked by now
        if attachment["type"] == "url":
            if attachment["url"]:
                return redirect(attachment["url"])
            else:
                return request.not_found()
        elif attachment["datas"]:
            data = StringIO(base64.standard_b64decode(attachment["datas"]))
            return http.send_file(data, filename=attachment['name'], as_attachment=True)
        else:
            return request.not_found()