def company_logo(self, dbname=None, **kw): imgname = 'logo' imgext = '.png' placeholder = functools.partial(get_resource_path, 'web', 'static', 'img') dbname = request.db uid = (request.session.uid if dbname else None) or odoo.SUPERUSER_ID if not dbname: response = http.Stream.from_path( placeholder(imgname + imgext)).get_response() 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 = send_file(image_data, filename=imgname + imgext, mimetype=mimetype, mtime=row[1]) else: response = http.Stream.from_path( placeholder('nologo.png')).get_response() except Exception: response = http.Stream.from_path( placeholder(imgname + imgext)).get_response() return response
def authenticate(self, db, login, password, base_location=None): if not http.db_filter([db]): raise AccessError("Database not found.") pre_uid = request.session.authenticate(db, login, password) if pre_uid != request.session.uid: # Crapy workaround for unupdatable Odoo Mobile App iOS (Thanks Apple :@) and Android # Correct behavior should be to raise AccessError("Renewing an expired session for user that has multi-factor-authentication is not supported. Please use /web/login instead.") return {'uid': None} request.session.db = db registry = odoo.modules.registry.Registry(db) with registry.cursor() as cr: env = odoo.api.Environment(cr, request.session.uid, request.session.context) return env['ir.http'].session_info()
def company_logo(self, dbname=None, **kw): imgname = 'logo' imgext = '.png' placeholder = functools.partial(get_resource_path, 'hm_system', '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: 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 = 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('nologo.png')) except Exception: response = http.send_file(placeholder(imgname + imgext)) return response
def company_logo(self, dbname=None, **kw): imgname = 'default_logo.png' placeholder = functools.partial(get_module_resource, '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)) else: try: registry = odoo.modules.registry.Registry(dbname) with registry.cursor() as cr: cr.execute("""SELECT c.web_company_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')) 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 # @http.route(['/page/about_us'], # type='http', auth="public", website=True) # def about_us(self, **kwargs): # values = {} # values.update(kwargs=kwargs.items()) # return request.render("sync_uppercrust_theme.about_us", values) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
def company_logo(self, dbname=None, **kw): imgname = 'default_logo.png' placeholder = functools.partial(get_module_resource, '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)) else: try: registry = odoo.modules.registry.Registry(dbname) with registry.cursor() as cr: cr.execute( """SELECT c.web_company_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')) 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
def load_modules(registry, force_demo=False, status=None, update_module=False): """ Load the modules for a registry object that has just been created. This function is part of Registry.new() and should not be used anywhere else. """ initialize_sys_path() force = [] if force_demo: force.append('demo') models_to_check = set() with registry.cursor() as cr: # prevent endless wait for locks on schema changes (during online # installs) if a concurrent transaction has accessed the table; # connection settings are automatically reset when the connection is # borrowed from the pool cr.execute("SET SESSION lock_timeout = '15s'") if not odoo.modules.db.is_initialized(cr): if not update_module: _logger.error( "Database %s not initialized, you can force it with `-i base`", cr.dbname) return _logger.info("init db") odoo.modules.db.initialize(cr) update_module = True # process auto-installed modules tools.config["init"]["all"] = 1 if not tools.config['without_demo']: tools.config["demo"]['all'] = 1 if 'base' in tools.config['update'] or 'all' in tools.config['update']: cr.execute( "update ir_module_module set state=%s where name=%s and state=%s", ('to upgrade', 'base', 'installed')) # STEP 1: LOAD BASE (must be done before module dependencies can be computed for later steps) graph = odoo.modules.graph.Graph() graph.add_module(cr, 'base', force) if not graph: _logger.critical( 'module base cannot be loaded! (hint: verify addons-path)') raise ImportError( 'Module `base` cannot be loaded! (hint: verify addons-path)') # processed_modules: for cleanup step after install # loaded_modules: to avoid double loading report = registry._assertion_report loaded_modules, processed_modules = load_module_graph( cr, graph, status, perform_checks=update_module, report=report, models_to_check=models_to_check) load_lang = tools.config.pop('load_language') if load_lang or update_module: # some base models are used below, so make sure they are set up registry.setup_models(cr) if load_lang: for lang in load_lang.split(','): tools.load_language(cr, lang) # STEP 2: Mark other modules to be loaded/updated if update_module: env = api.Environment(cr, SUPERUSER_ID, {}) Module = env['ir.module.module'] _logger.info('updating modules list') Module.update_list() _check_module_names( cr, itertools.chain(tools.config['init'], tools.config['update'])) module_names = [k for k, v in tools.config['init'].items() if v] if module_names: modules = Module.search([('state', '=', 'uninstalled'), ('name', 'in', module_names)]) if modules: modules.button_install() module_names = [k for k, v in tools.config['update'].items() if v] if module_names: modules = Module.search([('state', 'in', ('installed', 'to upgrade')), ('name', 'in', module_names)]) if modules: modules.button_upgrade() cr.execute("update ir_module_module set state=%s where name=%s", ('installed', 'base')) Module.invalidate_cache(['state']) Module.flush() # STEP 3: Load marked modules (skipping base which was done in STEP 1) # IMPORTANT: this is done in two parts, first loading all installed or # partially installed modules (i.e. installed/to upgrade), to # offer a consistent system to the second part: installing # newly selected modules. # We include the modules 'to remove' in the first step, because # they are part of the "currently installed" modules. They will # be dropped in STEP 6 later, before restarting the loading # process. # IMPORTANT 2: We have to loop here until all relevant modules have been # processed, because in some rare cases the dependencies have # changed, and modules that depend on an uninstalled module # will not be processed on the first pass. # It's especially useful for migrations. previously_processed = -1 while previously_processed < len(processed_modules): previously_processed = len(processed_modules) processed_modules += load_marked_modules( cr, graph, ['installed', 'to upgrade', 'to remove'], force, status, report, loaded_modules, update_module, models_to_check) if update_module: processed_modules += load_marked_modules( cr, graph, ['to install'], force, status, report, loaded_modules, update_module, models_to_check) # check that all installed modules have been loaded by the registry after a migration/upgrade cr.execute( "SELECT name from ir_module_module WHERE state = 'installed' and name != 'studio_customization'" ) module_list = [name for (name, ) in cr.fetchall() if name not in graph] if module_list: _logger.error( "Some modules are not loaded, some dependencies or manifest may be missing: %s", sorted(module_list)) registry.loaded = True registry.setup_models(cr) # STEP 3.5: execute migration end-scripts migrations = odoo.modules.migration.MigrationManager(cr, graph) for package in graph: migrations.migrate_module(package, 'end') # check that new module dependencies have been properly installed after a migration/upgrade cr.execute( "SELECT name from ir_module_module WHERE state IN ('to install', 'to upgrade')" ) module_list = [name for (name, ) in cr.fetchall()] if module_list: _logger.error( "Some modules have inconsistent states, some dependencies may be missing: %s", sorted(module_list)) # STEP 3.6: apply remaining constraints in case of an upgrade registry.finalize_constraints() # STEP 4: Finish and cleanup installations if processed_modules: env = api.Environment(cr, SUPERUSER_ID, {}) cr.execute("SELECT model from ir_model") for (model, ) in cr.fetchall(): if model in registry: env[model]._check_removed_columns(log=True) elif _logger.isEnabledFor( logging.INFO): # more an info that a warning... _logger.runbot( "Model %s is declared but cannot be loaded! (Perhaps a module was partially removed or renamed)", model) # Cleanup orphan records env['ir.model.data']._process_end(processed_modules) env['base'].flush() for kind in ('init', 'demo', 'update'): tools.config[kind] = {} # STEP 5: Uninstall modules to remove if update_module: # Remove records referenced from ir_model_data for modules to be # removed (and removed the references from ir_model_data). cr.execute("SELECT name, id FROM ir_module_module WHERE state=%s", ('to remove', )) modules_to_remove = dict(cr.fetchall()) if modules_to_remove: env = api.Environment(cr, SUPERUSER_ID, {}) pkgs = reversed( [p for p in graph if p.name in modules_to_remove]) for pkg in pkgs: uninstall_hook = pkg.info.get('uninstall_hook') if uninstall_hook: py_module = sys.modules['odoo.addons.%s' % (pkg.name, )] getattr(py_module, uninstall_hook)(cr, registry) Module = env['ir.module.module'] Module.browse(modules_to_remove.values()).module_uninstall() # Recursive reload, should only happen once, because there should be no # modules to remove next time cr.commit() _logger.info( 'Reloading registry once more after uninstalling modules') registry = odoo.modules.registry.Registry.new( cr.dbname, force_demo, status, update_module) cr.reset() registry.check_tables_exist(cr) cr.commit() return registry # STEP 5.5: Verify extended fields on every model # This will fix the schema of all models in a situation such as: # - module A is loaded and defines model M; # - module B is installed/upgraded and extends model M; # - module C is loaded and extends model M; # - module B and C depend on A but not on each other; # The changes introduced by module C are not taken into account by the upgrade of B. if models_to_check: registry.init_models(cr, list(models_to_check), {'models_to_check': True}) # STEP 6: verify custom views on every model if update_module: env = api.Environment(cr, SUPERUSER_ID, {}) env['res.groups']._update_user_groups_view() View = env['ir.ui.view'] for model in registry: try: View._validate_custom_views(model) except Exception as e: _logger.warning('invalid custom view(s) for model %s: %s', model, tools.ustr(e)) if report.wasSuccessful(): _logger.info('Modules loaded.') else: _logger.error('At least one test failed when loading the modules.') # STEP 8: call _register_hook on every model # This is done *exactly once* when the registry is being loaded. See the # management of those hooks in `Registry.setup_models`: all the calls to # setup_models() done here do not mess up with hooks, as registry.ready # is False. env = api.Environment(cr, SUPERUSER_ID, {}) for model in env.values(): model._register_hook() env['base'].flush() # STEP 9: save installed/updated modules for post-install tests registry.updated_modules += processed_modules