You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.8 KiB

  1. # Copyright 2017-2019 Onestein (<https://www.onestein.eu>)
  2. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
  3. import base64
  4. import logging
  5. import os
  6. from odoo import api, fields, models, _
  7. from odoo.exceptions import UserError
  8. from odoo.tools import human_size
  9. _logger = logging.getLogger(__name__)
  10. class IrFilesystemDirectoryLine(models.TransientModel):
  11. _name = 'ir.filesystem.file'
  12. _description = 'File in filesystem'
  13. name = fields.Char(required=True)
  14. filename = fields.Char()
  15. file_content = fields.Binary(compute='_compute_file')
  16. stored_filename = fields.Char()
  17. directory_id = fields.Many2one(
  18. 'ir.filesystem.directory',
  19. string='Directory',
  20. )
  21. @api.multi
  22. def _file_read(self, fname, bin_size=False):
  23. def file_not_found(fname):
  24. raise UserError(_(
  25. '''Error while reading file %s.
  26. Maybe it was removed or permission is changed.
  27. Please refresh the list.''' % fname))
  28. self.ensure_one()
  29. r = ''
  30. directory = self.directory_id.get_dir()
  31. full_path = directory + fname
  32. if not (directory and os.path.isfile(full_path)):
  33. file_not_found(fname)
  34. try:
  35. if bin_size:
  36. r = human_size(os.path.getsize(full_path))
  37. else:
  38. r = base64.b64encode(open(full_path, 'rb').read())
  39. except (IOError, OSError):
  40. _logger.info("_read_file reading %s", fname, exc_info=True)
  41. return r
  42. @api.depends('stored_filename')
  43. def _compute_file(self):
  44. bin_size = self.env.context.get('bin_size')
  45. for line in self:
  46. if line.stored_filename:
  47. content = line._file_read(line.stored_filename, bin_size)
  48. line.file_content = content