|
| 1 | +# Copyright 2020 Eugene Molotov <https://it-projects.info/team/em230418> |
| 2 | +# License MIT (https://opensource.org/licenses/MIT). |
| 3 | + |
| 4 | +import base64 |
| 5 | +import json |
| 6 | +import logging |
| 7 | + |
| 8 | +import requests |
| 9 | +from urllib3.fields import RequestField |
| 10 | +from urllib3.filepost import choose_boundary, encode_multipart_formdata |
| 11 | + |
| 12 | +from odoo import api, models |
| 13 | +from odoo.tools import human_size |
| 14 | +from odoo.tools.safe_eval import safe_eval |
| 15 | + |
| 16 | +from odoo.addons.google_account.models.google_service import TIMEOUT |
| 17 | + |
| 18 | +_logger = logging.getLogger(__name__) |
| 19 | +_logger.setLevel(logging.DEBUG) |
| 20 | + |
| 21 | +PREFIX = "google_drive://" |
| 22 | + |
| 23 | + |
| 24 | +# https://stackoverflow.com/a/47682897 |
| 25 | +def encode_multipart_related(fields, boundary=None): |
| 26 | + if boundary is None: |
| 27 | + boundary = choose_boundary() |
| 28 | + |
| 29 | + body, _ = encode_multipart_formdata(fields, boundary) |
| 30 | + content_type = str("multipart/related; boundary=%s" % boundary) |
| 31 | + |
| 32 | + return body, content_type |
| 33 | + |
| 34 | + |
| 35 | +def encode_media_related(metadata, media, media_content_type): |
| 36 | + rf1 = RequestField( |
| 37 | + name="placeholder", |
| 38 | + data=json.dumps(metadata), |
| 39 | + headers={"Content-Type": "application/json; charset=UTF-8"}, |
| 40 | + ) |
| 41 | + rf2 = RequestField( |
| 42 | + name="placeholder2", data=media, headers={"Content-Type": media_content_type}, |
| 43 | + ) |
| 44 | + return encode_multipart_related([rf1, rf2]) |
| 45 | + |
| 46 | + |
| 47 | +class IrAttachment(models.Model): |
| 48 | + |
| 49 | + _inherit = "ir.attachment" |
| 50 | + |
| 51 | + def _get_google_drive_auth_header(self): |
| 52 | + access_token = self.env.context.get("google_drive_access_token") |
| 53 | + if not access_token: |
| 54 | + access_token = self.env["google.drive.config"].get_access_token() |
| 55 | + return {"Authorization": "Bearer " + access_token} |
| 56 | + |
| 57 | + # это нагло скопировано с ir_attachment_url |
| 58 | + @api.multi |
| 59 | + def _filter_protected_attachments(self): |
| 60 | + return self.filtered( |
| 61 | + lambda r: r.res_model not in ["ir.ui.view", "ir.ui.menu"] |
| 62 | + or not r.name.startswith("/web/content/") |
| 63 | + or not r.name.startswith("/web/static/") |
| 64 | + ) |
| 65 | + |
| 66 | + def _inverse_datas(self): |
| 67 | + condition = ( |
| 68 | + self.env["ir.config_parameter"] |
| 69 | + .sudo() |
| 70 | + .get_param("google_drive.attachment_condition") |
| 71 | + ) |
| 72 | + |
| 73 | + if condition: |
| 74 | + condition = safe_eval(condition, mode="eval") |
| 75 | + our_records = self.sudo().search([("id", "in", self.ids)] + condition) |
| 76 | + else: |
| 77 | + our_records = self |
| 78 | + |
| 79 | + our_records = our_records._filter_protected_attachments() |
| 80 | + |
| 81 | + if our_records: |
| 82 | + # make sure, you can use google drive |
| 83 | + # otherwise - use default behaviour |
| 84 | + try: |
| 85 | + google_drive_access_token = self.env[ |
| 86 | + "google.drive.config" |
| 87 | + ].get_access_token() |
| 88 | + except Exception: |
| 89 | + _logger.exception( |
| 90 | + "Google Drive is not configured properly. Keeping attachments as usual" |
| 91 | + ) |
| 92 | + return super(IrAttachment, self)._inverse_datas() |
| 93 | + |
| 94 | + self = self.with_context( |
| 95 | + google_drive_access_token=google_drive_access_token |
| 96 | + ) |
| 97 | + |
| 98 | + for attach in our_records: |
| 99 | + bin_value = base64.b64decode(attach.datas) |
| 100 | + fname = self._file_write_google_drive(bin_value, attach.datas_fname) |
| 101 | + vals = { |
| 102 | + "file_size": len(bin_value), |
| 103 | + "checksum": self._compute_checksum(bin_value), |
| 104 | + "index_content": self._index( |
| 105 | + bin_value, attach.datas_fname, attach.mimetype |
| 106 | + ), |
| 107 | + "store_fname": fname, |
| 108 | + "db_datas": False, |
| 109 | + "type": "binary", |
| 110 | + "datas_fname": attach.datas_fname, |
| 111 | + } |
| 112 | + super(IrAttachment, attach.sudo()).write(vals) |
| 113 | + |
| 114 | + return super(IrAttachment, self - our_records)._inverse_datas() |
| 115 | + |
| 116 | + def _file_read(self, fname, bin_size=False): |
| 117 | + if not fname.startswith(PREFIX): |
| 118 | + return super(IrAttachment, self)._file_read(fname, bin_size) |
| 119 | + |
| 120 | + file_id = fname[len(PREFIX) :] |
| 121 | + _logger.debug("reading file with id {}".format(file_id)) |
| 122 | + |
| 123 | + if bin_size: |
| 124 | + request_url = "https://www.googleapis.com/drive/v2/files/{}".format(file_id) |
| 125 | + else: |
| 126 | + request_url = "https://www.googleapis.com/drive/v2/files/{}?alt=media".format( |
| 127 | + file_id |
| 128 | + ) |
| 129 | + |
| 130 | + r = requests.get( |
| 131 | + request_url, headers=self._get_google_drive_auth_header(), timeout=TIMEOUT |
| 132 | + ) |
| 133 | + r.raise_for_status() |
| 134 | + |
| 135 | + if bin_size: |
| 136 | + return human_size(int(r.json()["fileSize"])) |
| 137 | + else: |
| 138 | + return base64.b64encode(r.content) |
| 139 | + |
| 140 | + def _file_write_google_drive(self, bin_value, original_filename): |
| 141 | + metadata = {} |
| 142 | + if original_filename: |
| 143 | + metadata["title"] = original_filename |
| 144 | + |
| 145 | + data, content_type = encode_media_related( |
| 146 | + metadata, bin_value, "application/octet-stream" |
| 147 | + ) |
| 148 | + |
| 149 | + headers = self._get_google_drive_auth_header() |
| 150 | + headers["Content-Type"] = content_type |
| 151 | + |
| 152 | + r = requests.post( |
| 153 | + "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart", |
| 154 | + headers=headers, |
| 155 | + data=data, |
| 156 | + ) |
| 157 | + r.raise_for_status() |
| 158 | + file_id = r.json()["id"] |
| 159 | + _logger.debug("uploaded file with id {}".format(file_id)) |
| 160 | + return PREFIX + file_id |
| 161 | + |
| 162 | + def _file_delete(self, fname): |
| 163 | + if not fname.startswith(PREFIX): |
| 164 | + return super(IrAttachment, self)._file_delete(fname) |
| 165 | + |
| 166 | + file_id = fname[len(PREFIX) :] |
| 167 | + |
| 168 | + r = requests.delete( |
| 169 | + "https://www.googleapis.com/drive/v2/files/{}".format(file_id), |
| 170 | + headers=self._get_google_drive_auth_header(), |
| 171 | + timeout=TIMEOUT, |
| 172 | + ) |
| 173 | + r.raise_for_status() |
0 commit comments