Example #1
0
    def readdir(self, path, offset):
        """
        Return content of a directory :
            - List models for root path
            - List records for a model
            - List attachments for a record
        We don't have to check for the path, because getattr already returns -ENOENT if the model/record/attachment doesn't exist
        """
        yield fuse.Direntry('.')
        yield fuse.Direntry('..')

        paths = path.split('/')[1:]
        # List models
        if path == '/':
            model_obj = Object(self.oerp_connection, 'ir.model')
            model_ids = model_obj.search([])
            for model_data in model_obj.read(model_ids, ['model']):
                yield fuse.Direntry(model_data['model'])
        # List records
        elif len(paths) == 1:
            element_obj = Object(self.oerp_connection, paths[0])
            element_ids = element_obj.search([])
            for element_data in element_obj.read(element_ids, ['id']):
                yield fuse.Direntry(str(element_data['id']))
        # List attachments
        else:
            attachment_obj = Object(self.oerp_connection, 'ir.attachment')
            attachment_ids = attachment_obj.search([
                ('res_model', '=', paths[0]), ('res_id', '=', int(paths[1]))
            ])
            for attachment_data in attachment_obj.read(attachment_ids,
                                                       ['name']):
                yield fuse.Direntry(
                    '%d-%s' % (attachment_data['id'], attachment_data['name']))
Example #2
0
    def getattr(self, path):
        """
        Return attributes for the specified path :
            - Search for the model as first part
            - Search for an existing record as second part
            - Search for an existing attachment as third part
            - There cannot be more than 3 parts in the path
        """
        fakeStat = fuse.Stat()
        fakeStat.st_mode = stat.S_IFDIR | 0400
        fakeStat.st_nlink = 0

        if path == '/':
            return fakeStat

        paths = path.split('/')[1:]
        if len(paths) > 3:
            return -ENOENT

        # Check for model existence
        model_obj = Object(self.oerp_connection, 'ir.model')
        model_ids = model_obj.search([('model', '=', paths[0])])
        if not model_ids:
            return -ENOENT
        elif len(paths) == 1:
            return fakeStat

        # Check for record existence
        element_obj = Object(self.oerp_connection, paths[0])
        element_ids = element_obj.search([('id', '=', int(paths[1]))])
        if not element_ids:
            return -ENOENT
        elif len(paths) == 2:
            return fakeStat

        # Chech for attachement existence
        attachment_obj = Object(self.oerp_connection, 'ir.attachment')
        attachment_ids = attachment_obj.search([
            ('res_model', '=', paths[0]), ('res_id', '=', int(paths[1])),
            ('id', '=', self.id_from_label(paths[2]))
        ])
        if not attachment_ids:
            return -ENOENT

        # Common stats
        fakeStat.st_mode = stat.S_IFREG | 0400
        fakeStat.st_nlink = 2

        # TODO : Read the file size from a dedicated field (created in a specific module)
        attachment_obj = Object(self.oerp_connection, 'ir.attachment')
        attachment_ids = attachment_obj.search([
            ('res_model', '=', paths[0]), ('res_id', '=', int(paths[1])),
            ('id', '=', self.id_from_label(paths[2]))
        ])
        attachment_data = attachment_obj.read(attachment_ids, ['datas'])
        fakeStat.st_size = len(base64.b64decode(attachment_data[0]['datas']))
        return fakeStat
Example #3
0
def execute_import(filename,
                   connection,
                   separator=',',
                   transaction=False,
                   error_stop=False):
    """
    Read the file, and launched import_data
    """
    model = filename.split('/').pop().replace('.csv', '')
    if model.find('_') > 4:
        model = model[model.find('-') + 1:model.find('_')]
    else:
        model = model[model.find('-') + 1:]
    logger.debug('model: %s' % model)

    obj = Object(connection, model)

    logger.info('Read and analyse the file content')
    fp = open(filename, 'r')
    header = False
    lines = []
    count = 0
    reader = csv.reader(fp, delimiter=separator)
    for line in reader:
        count += 1
        if not header:
            header = line
            logger.debug('header: %s' % str(header))
            continue

        lines.append(line)
        logger.debug('line: %s' % str(line))
    logger.info('Read the file content is finished')

    logger.info('Start import the content in OpenERP (%d datas)' % len(lines))
    count = 0
    ctx = {
        'defer_parent_store_computation': True,
        'lang': opts.lang,
        'import': True,
    }
    if opts.inactive:
        ctx['active_test'] = False
    print ctx
    if transaction:
        try:
            logger.info('Import %s lines in one transaction' % len(lines))
            res = obj.import_data(header, lines, 'init', '', False, ctx)
            if res[0] == -1:
                logger.error('%s' % res[2])
                logger.error('%s' % str(res[1]))
            logger.info('End transaction import')
        except Exception, e:
            logger.error(str(e))
            if error_stop:
                raise StopError(str(e))
Example #4
0
 def read(self, path, size, offset):
     """
     Return the specified slide of a file
     Note : Only the beginning of the name is required (the ID of the attachment), we can put anything after the first '-', it will be ignored
     """
     paths = path.split('/')[1:]
     # TODO : Create a module that allows to read files by slides
     attachment_obj = Object(self.oerp_connection, 'ir.attachment')
     attachment_ids = attachment_obj.search([
         ('res_model', '=', paths[0]), ('res_id', '=', int(paths[1])),
         ('id', '=', self.id_from_label(paths[2]))
     ])
     attachment_data = attachment_obj.read(attachment_ids, ['datas'])
     return base64.b64decode(attachment_data[0]['datas'])[offset:offset +
                                                          size]
Example #5
0
    def release(self, path, fh):
        """
        Writing of the file is finished, import the contents into OpenERP
        """
        # FIXME : Don't know why it doesn't work without rebuilding the StringIO object...
        value = StringIO(self.files[path].getvalue())

        # Parse the CSV file contents
        csvFile = csv.reader(value)
        lines = list(csvFile)

        # Import data into OpenERP
        model = path.replace('.csv', '')[1:]
        oerpObject = Object(self.oerp_connection, model)
        oerpObject.import_data(lines[0], lines[1:], 'init', '', False,
                               {'import': True})

        # Close StringIO and free memory
        self.files[path].close()
        del self.files[path]
        value.close()
        del value
        return True
sys.path.append('../')

from oobjlib.connection import Connection
from oobjlib.component import Object
from oobjlib.common import GetParser

parser = GetParser('Create Product', '0.1')
opts, args = parser.parse_args()

try:
    cnx = Connection(server=opts.server,
                     dbname=opts.dbname,
                     login=opts.user,
                     password=opts.passwd,
                     port=opts.port)
except Exception, e:
    print '%s' % str(e)
    exit(1)

product = Object(cnx, 'product.product')

args = {
    'name': 'Import Test',
    'default_code': 'ABCD-EFGH',
    'categ_id': 1,
}

print 'Product ID %d created !' % product.create(args)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
try:
    cnx = Connection(server=opts.server, dbname=opts.dbname, login=opts.user, port=opts.port,
                     password=opts.passwd)
except Exception, e:
    print '%s' % str(e)
    exit(1)


def generate_tracking_message_id(openobject_id):
    """Returns a string that can be used in the Message-ID RFC822 header field so we
       can track the replies related to a given object thanks to the "In-Reply-To" or
       "References" fields that Mail User Agents will set.
    """
    s = hashlib.sha1()
    s.update(str(time.time()))
    return "<%s-openobject-%s@%s>" % (s.hexdigest(), openobject_id, 'syleam6.syleam.fr')


message = Object(cnx, 'mailgate.message')
message_ids = message.search([('model','=','project.issue'),('message_id','=', False)])

print '%d message to update' % len(message_ids)

for m in message.read(message_ids, ['name', 'res_id']):
    args = {'message_id': generate_tracking_message_id(m['res_id'])}
    message.write([m['id']], args)


# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Example #8
0
                 default='',
                 help='Enter list of companies, seprate by a comma (,)')
parser.add_option_group(group)

opts, args = parser.parse_args()

try:
    cnx = Connection(server=opts.server,
                     dbname=opts.dbname,
                     login=opts.user,
                     password=opts.passwd)
except Exception, e:
    print '%s' % str(e)
    exit(1)

user = Object(cnx, 'res.users')
multi = Object(cnx, 'res.company')

user_id = user.search([('login', '=', opts.user)])[0]
# save company_id to restore it after
curr = user.read(user_id, ['company_ids', 'company_id'])
c_save_id = curr['company_id']
print 'User: %d => %s (id %d)' % (user_id, c_save_id[1], c_save_id[0])

##
# If the company argument is missing, retrieve all companies in the user form
#
if opts.company:
    companies = opts.company.split(',')
else:
    companies = curr['company_ids']
logger.info('Language to import data: %s' % opts.lang)

try:
    logger.info('Open connection to "%s:%s" on "%s" with user "%s" ' % (opts.server, opts.port, opts.dbname, opts.user))
    cnx = Connection(
        server=opts.server,
        dbname=opts.dbname,
        login=opts.user,
        password=opts.passwd,
        port=opts.port)
except Exception, e:
    logger.error('Fail to connect to the server')
    logger.error('%s' % str(e))
    sys.exit(1)

model = Object(cnx, opts.model)

mod_count = model.search_count([])
logger.info('There are %d record to export' % mod_count)

fields = model.fields_get()
fields_name = fields.keys()

result = model.read(model.search([]))

from odf.opendocument import OpenDocumentSpreadsheet
from odf.style import Style, TextProperties, ParagraphProperties, TableColumnProperties
from odf.text import P
from odf.table import Table, TableColumn, TableRow, TableCell

textdoc = OpenDocumentSpreadsheet()
Example #10
0
    def __init__(self, stdscr):
        """
        Initialize the sentinel program
        """
        # Read user configuration
        config = ConfigParser.SafeConfigParser(DEFAULT_CONFIG)
        config.read('.oerp_sentinelrc')

        # No configfile found, exit
        if not 'openerp' in config.sections():
            raise Exception('Config Error', 'Config file not found !')

        # Connection to the OpenERP Server
        self.connection = Connection(
            server=config.get('openerp', 'host'),
            dbname=config.get('openerp', 'database'),
            login=config.get('openerp', 'user'),
            password=config.get('openerp', 'password'),
            port=config.get('openerp', 'port'),
        )

        # Initialize translations
        context = Object(self.connection, 'res.users').context_get()
        lang = context.get('lang', I18N_DEFAULT)
        gettext.install(I18N_DOMAIN)
        try:
            language = gettext.translation(I18N_DOMAIN,
                                           I18N_DIR,
                                           languages=[lang])
        except:
            language = gettext.translation(I18N_DOMAIN,
                                           I18N_DIR,
                                           languages=[I18N_DEFAULT])
        language.install()

        # Initialize hardware
        self.hardware_obj = Object(self.connection, 'scanner.hardware')

        # Initialize window
        self.screen = stdscr
        self._set_screen_size()

        self._init_colors()

        # Get the informations for this material from server (identified by IP)
        self.hardware_code = ''
        self.scenario_id = False
        try:
            ssh_data = os.environ['SSH_CONNECTION'].split(' ')
            self.hardware_code = ssh_data[0]
            self.scenario_id = self.hardware_obj.scanner_check(
                self.hardware_code)
        except:
            self.hardware_code = self._input_text(
                _('Autoconfiguration failed !\nPlease enter terminal code'))
            self.scenario_id = self.hardware_obj.scanner_check(
                self.hardware_code)

        # Resize window to terminal screen size
        self._resize()

        # Reinit colors with values configured in OpenERP
        self._reinit_colors()

        # Initialize mouse events capture
        curses.mousemask(curses.BUTTON1_CLICKED
                         | curses.BUTTON1_DOUBLE_CLICKED)

        # Load the sentinel
        self.main_loop()
Example #11
0
                 default=False,
                 help='List the company by name and their ID')
parser.add_option_group(group)

opts, args = parser.parse_args()

try:
    cnx = Connection(server=opts.server,
                     dbname=opts.dbname,
                     login=opts.user,
                     password=opts.passwd)
except Exception, e:
    print '%s' % str(e)
    exit(1)

user = Object(cnx, 'res.users')
rule = Object(cnx, 'ir.rule')

user_id = user.search([('login', '=', opts.user)])[0]

if opts.legend:
    comp = Object(cnx, 'res.company')
    company_ids = comp.search([])
    print 'List all company'
    print 80 * '*'
    for compa in comp.read(company_ids, ['name']):
        print '%s -> %d' % (compa['name'].ljust(20), compa['id'])
    print 80 * '*'

company_id = user.read(user_id, ['company_id'])['company_id']
try:
Example #12
0
                 help='Follow the one2many child of this record')
parser.add_option_group(group)

opts, args = parser.parse_args()

try:
    cnx = Connection(server=opts.server,
                     dbname=opts.dbname,
                     login=opts.user,
                     password=opts.passwd,
                     port=opts.port)
except Exception, e:
    print '%s' % str(e)
    exit(1)

model = Object(cnx, opts.model)
model_data = Object(cnx, 'ir.model.data')

##
# Check if model exists and return all fields
#
try:
    fields = model.fields_get()
    f_list = []
    for i in fields:
        f_list.append(i)
    f_list.sort()
except Exception, e:
    print "Error object %s doesn't exists" % opts.model
    exit(2)
sys.path.append('../')

from oobjlib.connection import Connection
from oobjlib.component import Object
from oobjlib.common import GetParser

parser = GetParser('Module List', '0.1')
opts, args = parser.parse_args()

try:
    cnx = Connection(server=opts.server,
                     dbname=opts.dbname,
                     login=opts.user,
                     password=opts.passwd,
                     port=opts.port)
except Exception, e:
    print '%s' % str(e)
    exit(1)

modules = Object(cnx, "ir.module.module")
print '--[Connection Object]---------------------'
print '%s' % str(modules)

ids = modules.search([('state', '=', 'installed')])
print '--[Module list]---------------------------'
for p in modules.read(ids, ['name']):
    print '* %s' % p['name']

print '--[End]-----------------------------------'
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
    def __init__(self, stdscr):
        """
        Initialize the sentinel program
        """
        # Read user configuration
        config = ConfigParser.SafeConfigParser(DEFAULT_CONFIG)
        self.datadir = os.path.expanduser("~/")
        config.read([
            '.oerp_sentinelrc',
            '.openerp_sentinelrc',
            '.odoo_sentinelrc',
            os.path.join(self.datadir, '.oerp_sentinelrc'),
            os.path.join(self.datadir, '.openerp_sentinelrc'),
            os.path.join(self.datadir, '.odoo_sentinelrc'),
        ])

        # No configfile found, exit
        if 'openerp' not in config.sections():
            raise Exception('Config Error', 'Config file not found !')

        # Connection to the OpenERP Server
        self.connection = Connection(
            server=config.get('openerp', 'host'),
            dbname=config.get('openerp', 'database'),
            login=config.get('openerp', 'user'),
            password=config.get('openerp', 'password'),
            port=config.get('openerp', 'port'),
        )

        # Open the test file, if any
        test_file_name = config.get('openerp', 'test_file')
        self.test_file = None
        if test_file_name:
            self.test_file = open(test_file_name, 'r')

        # Initialize translations
        self.context = Object(self.connection, 'res.users').context_get()
        lang = self.context.get('lang', I18N_DEFAULT)
        gettext.install(I18N_DOMAIN)
        try:
            language = gettext.translation(
                I18N_DOMAIN, I18N_DIR, languages=[lang])
        except:
            language = gettext.translation(
                I18N_DOMAIN, I18N_DIR, languages=[I18N_DEFAULT])

        # Replace global dummy lambda by the translations gettext method
        # The install method of gettext doesn't replace the function if exists
        global _
        _ = language.gettext

        # Initialize hardware
        self.hardware_obj = Object(self.connection, 'scanner.hardware')
        self.scenario_obj = Object(self.connection, 'scanner.scenario')

        # Initialize window
        self.screen = stdscr
        self._set_screen_size()

        self._init_colors()

        # Get the informations for this material from server (identified by IP)
        self.hardware_code = ''
        self.scenario_id = False
        self.scenario_name = False
        try:
            ssh_data = os.environ['SSH_CONNECTION'].split(' ')
            self.hardware_code = ssh_data[0]
            self.scanner_check()
        except:
            self.hardware_code = self._input_text(
                _('Autoconfiguration failed !\nPlease enter terminal code'))
            self.scanner_check()

        # Resize window to terminal screen size
        self._resize()

        # Reinit colors with values configured in OpenERP
        self._reinit_colors()

        # Initialize mouse events capture
        curses.mousemask(
            curses.BUTTON1_CLICKED | curses.BUTTON1_DOUBLE_CLICKED)

        # Reinitialize to the main menu when using a test file (useful when
        # the last run has crashed before end)
        if test_file_name:
            self.oerp_call('end')

        # Load the sentinel
        self.main_loop()
try:
    cnx = Connection(server=opts.server,
                     dbname=opts.dbname,
                     login=opts.user,
                     password=opts.passwd,
                     port=opts.port)
except Exception, e:
    print '%s' % str(e)
    exit(1)

if not opts.filename:
    print '--file argument is required!'
    exit(1)

jasper_obj = Object(cnx, 'jasper.document')
label_obj = Object(cnx, 'jasper.document.label')

fp = open(opts.filename, 'r')
reader = csv.DictReader(fp, delimiter=',')

service_cache = {}


def format_code(code):
    code = code.upper()
    code = code.replace(' ', '_')
    return code


for l in reader:
Example #16
0
                (opts.server, opts.port, opts.dbname, opts.user))
    cnx = Connection(server=opts.server,
                     dbname=opts.dbname,
                     login=opts.user,
                     password=opts.passwd,
                     port=opts.port)
except Exception, e:
    logger.error('Fail to connect to the server')
    logger.error('%s' % str(e))
    sys.exit(1)

resid = {}
opts.directory = os.path.expanduser(opts.directory)

# extract scenario
scenario_obj = Object(cnx, 'scanner.scenario')
model_obj = Object(cnx, 'ir.model')
warehouse_obj = Object(cnx, 'stock.warehouse')
scen_read = scenario_obj.read(int(opts.scenario_id), [],
                              {'active_test': False})
if not scen_read:
    logger.error('Scenario ID %s not found' % opts.scenario_id)
    sys.exit(1)
del scen_read['step_ids']
del scen_read['id']
# create node and attributs
root = Element('scenario')
for field in scen_read:
    node = SubElement(root, field)
    if field == 'model_id':
        if scen_read[field]:
                help='Indicate the version of OpenERP (5 or 6)')
parser.add_option_group(group)
opts, args = parser.parse_args()

try:
    cnx = Connection(
        server=opts.server,
        dbname=opts.dbname,
        login=opts.user,
        password=opts.passwd,
        port=opts.port)
except Exception, e:
    print '%s' % str(e)
    sys.exit(1)

mod = Object(cnx, 'ir.model')

if opts.oerp_version == '5':
    print 'version 5'
    model = mod.search([])
else:
    print 'version 6'
    model = mod.search([('osv_memory', '=', False)])


print 80 * '-'
print '| Model                                         | Search |  Read  | View XML |'
print 80 * '-'

footer = '--- FOOTER REPORT ---\n'