url_image_preview.py 28.4 KB
Newer Older
Dicson's avatar
Dicson committed
1
# -*- coding: utf-8 -*-
Thilo Molitor's avatar
Thilo Molitor committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
##
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the Free Software Foundation; version 3 only.
##
## Gajim is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Gajim.  If not, see <http://www.gnu.org/licenses/>.
##
Dicson's avatar
Dicson committed
17 18

import os
Thilo Molitor's avatar
Thilo Molitor committed
19 20
import hashlib
import binascii
21
import logging
22
import math
Daniel Brötzmann's avatar
Daniel Brötzmann committed
23 24 25
import shutil

from functools import partial
Thilo Molitor's avatar
Thilo Molitor committed
26
from urllib.parse import urlparse
27
from urllib.parse import unquote
Thilo Molitor's avatar
Thilo Molitor committed
28
from io import BytesIO
Dicson's avatar
Dicson committed
29

30 31 32 33
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GLib
from gi.repository import GdkPixbuf
34

35 36
from gajim.common import app
from gajim.common import helpers
Thilo Molitor's avatar
Thilo Molitor committed
37
from gajim.common import configpaths
Daniel Brötzmann's avatar
Daniel Brötzmann committed
38 39 40 41
from gajim.gtkgui_helpers import add_css_to_widget
from gajim.gtk.dialogs import ErrorDialog
from gajim.gtk.filechoosers import FileSaveDialog
from gajim.gtk.util import get_cursor
42

43 44
from gajim.plugins import GajimPlugin
from gajim.plugins.helpers import log_calls
45 46
from gajim.plugins.plugins_i18n import _

47 48
from url_image_preview.http_functions import get_http_head
from url_image_preview.http_functions import get_http_file
49
from url_image_preview.config_dialog import UrlImagePreviewConfigDialog
Dicson's avatar
Dicson committed
50

51

Philipp Hörist's avatar
Philipp Hörist committed
52
log = logging.getLogger('gajim.p.preview')
Thilo Molitor's avatar
Thilo Molitor committed
53

54
ERROR_MSG = None
Thilo Molitor's avatar
Thilo Molitor committed
55 56
try:
    from PIL import Image
57
    from url_image_preview.resize_gif import resize_gif
Daniel Brötzmann's avatar
Daniel Brötzmann committed
58
except ImportError:
Thilo Molitor's avatar
Thilo Molitor committed
59
    log.debug('Pillow not available')
Daniel Brötzmann's avatar
Daniel Brötzmann committed
60
    ERROR_MSG = _('Please install python-pillow')
Thilo Molitor's avatar
Thilo Molitor committed
61 62 63 64 65 66 67 68 69 70

try:
    if os.name == 'nt':
        from cryptography.hazmat.backends.openssl import backend
    else:
        from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.ciphers import Cipher
    from cryptography.hazmat.primitives.ciphers import algorithms
    from cryptography.hazmat.primitives.ciphers.modes import GCM
    decryption_available = True
71
except Exception:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
72 73
    DEP_MSG = _('To enable previews for encrypted images, '
                'please install python-cryptography!')
74
    log.exception('Error')
Thilo Molitor's avatar
Thilo Molitor committed
75 76 77 78 79
    log.info('Decryption/Encryption disabled due to errors')
    decryption_available = False

ACCEPTED_MIME_TYPES = ('image/png', 'image/jpeg', 'image/gif', 'image/raw',
                       'image/svg+xml', 'image/x-ms-bmp')
Dicson's avatar
Dicson committed
80 81 82 83 84


class UrlImagePreviewPlugin(GajimPlugin):
    @log_calls('UrlImagePreviewPlugin')
    def init(self):
85 86 87 88 89 90
        if ERROR_MSG:
            self.activatable = False
            self.available_text = ERROR_MSG
            self.config_dialog = None
            return

Thilo Molitor's avatar
Thilo Molitor committed
91 92
        if not decryption_available:
            self.available_text = DEP_MSG
93
        self.config_dialog = partial(UrlImagePreviewConfigDialog, self)
Dicson's avatar
Dicson committed
94
        self.gui_extension_points = {
Thilo Molitor's avatar
Thilo Molitor committed
95 96
            'chat_control_base': (self.connect_with_chat_control,
                                  self.disconnect_from_chat_control),
97
            'history_window':
98
                (self.connect_with_history, self.disconnect_from_history),
99
            'print_real_text': (self.print_real_text, None), }
Dicson's avatar
Dicson committed
100
        self.config_default_values = {
101
            'PREVIEW_SIZE': (150, 'Preview size (100-1000)'),
102
            'MAX_FILE_SIZE': (5242880, 'Max file size for image preview'),
103
            'ALLOW_ALL_IMAGES': (False, ''),
104
            'LEFTCLICK_ACTION': ('open_menuitem', 'Open'),
105
            'ANONYMOUS_MUC': (False, ''),
106
            'GEO_PREVIEW_PROVIDER': ('Google', 'Google Maps'),
107
            'VERIFY': (True, ''),}
Thilo Molitor's avatar
Thilo Molitor committed
108
        self.controls = {}
109
        self.history_window_control = None
Thilo Molitor's avatar
Thilo Molitor committed
110

Dicson's avatar
Dicson committed
111 112
    @log_calls('UrlImagePreviewPlugin')
    def connect_with_chat_control(self, chat_control):
Thilo Molitor's avatar
Thilo Molitor committed
113 114 115 116
        account = chat_control.contact.account.name
        jid = chat_control.contact.jid
        if account not in self.controls:
            self.controls[account] = {}
117
        self.controls[account][jid] = Base(self, chat_control.conv_textview)
Dicson's avatar
Dicson committed
118 119 120

    @log_calls('UrlImagePreviewPlugin')
    def disconnect_from_chat_control(self, chat_control):
Thilo Molitor's avatar
Thilo Molitor committed
121 122
        account = chat_control.contact.account.name
        jid = chat_control.contact.jid
123
        self.controls[account][jid].deinit_handlers()
Thilo Molitor's avatar
Thilo Molitor committed
124
        del self.controls[account][jid]
125

126 127 128 129 130
    @log_calls('UrlImagePreviewPlugin')
    def connect_with_history(self, history_window):
        if self.history_window_control:
            self.history_window_control.deinit_handlers()
        self.history_window_control = Base(
131
            self, history_window.history_textview)
132 133 134 135 136 137

    @log_calls('UrlImagePreviewPlugin')
    def disconnect_from_history(self, history_window):
        if self.history_window_control:
            self.history_window_control.deinit_handlers()
        self.history_window_control = None
Dicson's avatar
Dicson committed
138

139 140
    def print_real_text(self, tv, real_text, text_tags, graphics,
                        iter_, additional_data):
141
        if tv.used_in_history_window and self.history_window_control:
142 143 144
            self.history_window_control.print_real_text(
                real_text, text_tags, graphics, iter_, additional_data)

Thilo Molitor's avatar
Thilo Molitor committed
145 146
        account = tv.account
        for jid in self.controls[account]:
147
            if self.controls[account][jid].textview != tv:
Dicson's avatar
Dicson committed
148
                continue
149 150
            self.controls[account][jid].print_real_text(
                real_text, text_tags, graphics, iter_, additional_data)
Thilo Molitor's avatar
Thilo Molitor committed
151
            return
Dicson's avatar
Dicson committed
152 153


Daniel Brötzmann's avatar
Daniel Brötzmann committed
154
class Base:
155
    def __init__(self, plugin, textview):
Dicson's avatar
Dicson committed
156
        self.plugin = plugin
157
        self.textview = textview
Thilo Molitor's avatar
Thilo Molitor committed
158
        self.handlers = {}
Dicson's avatar
Dicson committed
159

160
        self.directory = os.path.join(configpaths.get('MY_DATA'),
Thilo Molitor's avatar
Thilo Molitor committed
161
                                      'downloads')
162
        self.thumbpath = os.path.join(configpaths.get('MY_CACHE'),
Thilo Molitor's avatar
Thilo Molitor committed
163 164 165 166 167
                                      'downloads.thumb')

        try:
            self._create_path(self.directory)
            self._create_path(self.thumbpath)
168
        except Exception:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
169
            log.error('Error creating download and/or thumbnail folder!')
Thilo Molitor's avatar
Thilo Molitor committed
170 171
            raise

172
    def deinit_handlers(self):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
173
        # Remove all register handlers on wigets, created by self.xml
Thilo Molitor's avatar
Thilo Molitor committed
174 175 176 177 178 179
        # to prevent circular references among objects
        for i in list(self.handlers.keys()):
            if self.handlers[i].handler_is_connected(i):
                self.handlers[i].disconnect(i)
            del self.handlers[i]

180 181 182
    def print_real_text(self, real_text, text_tags, graphics, iter_,
                        additional_data):

183
        if len(real_text.split(' ')) > 1:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
184
            # urlparse doesn't recognise spaces as URL delimiter
185
            log.debug('Url with text will not be displayed: %s', real_text)
186 187
            return

188
        urlparts = urlparse(unquote(real_text))
189
        if not self._accept_uri(urlparts, real_text, additional_data):
190
            return
Thilo Molitor's avatar
Thilo Molitor committed
191 192 193 194

        # Don't print the URL in the message window (in the calling function)
        self.textview.plugin_modified = True

Dicson's avatar
Dicson committed
195
        buffer_ = self.textview.tv.get_buffer()
Thilo Molitor's avatar
Thilo Molitor committed
196 197 198 199 200 201
        if not iter_:
            iter_ = buffer_.get_end_iter()

        # Show URL, until image is loaded (if ever)
        ttt = buffer_.get_tag_table()
        repl_start = buffer_.create_mark(None, iter_, True)
Daniel Brötzmann's avatar
Daniel Brötzmann committed
202 203 204 205
        buffer_.insert_with_tags(
            iter_,
            real_text,
            *[(ttt.lookup(t) if isinstance(t, str) else t) for t in ['url']])
Thilo Molitor's avatar
Thilo Molitor committed
206 207
        repl_end = buffer_.create_mark(None, iter_, True)

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
        # Handle geo:-URIs
        if real_text.startswith('geo:'):
            if self.plugin.config['GEO_PREVIEW_PROVIDER'] == 'no_preview':
                return
            size = self.plugin.config['PREVIEW_SIZE']
            geo_provider = self.plugin.config['GEO_PREVIEW_PROVIDER']
            key = ''
            iv = ''
            encrypted = False
            ext = '.png'
            color = 'blue'
            zoom = 16
            location = real_text[4:]
            lat, _, lon = location.partition(',')
            if lon == '':
                return

Daniel Brötzmann's avatar
Daniel Brötzmann committed
225 226 227 228
            filename = 'location_%(provider)s_%(location)s' % {
                'provider': geo_provider,
                'location': location.replace(',', '_').replace('.', '-')
            }
229
            newfilename = filename + ext
Daniel Brötzmann's avatar
Daniel Brötzmann committed
230 231 232 233 234 235
            thumbfilename = '%(filename)s_thumb_%(size)s%(ext)s' % {
                'filename': filename,
                'size': str(self.plugin.config['PREVIEW_SIZE']),
                'ext': ext
            }

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
            filepath = os.path.join(self.directory, newfilename)
            thumbpath = os.path.join(self.thumbpath, thumbfilename)
            filepaths = [filepath, thumbpath]

            # Google
            if geo_provider == 'Google':
                url = 'https://maps.googleapis.com/maps/api/staticmap?' \
                      'center={}&zoom={}&size={}x{}&markers=color:{}' \
                      '|label:.|{}'.format(location, zoom, size, size,
                                           color, location)
                weburl = 'https://www.google.com/maps/place/{}' \
                         .format(location)
                real_text = url
            else:
                # OpenStreetMap / MapQuest
                apikey = 'F7x36jLVv2hiANVAXmhwvUB044XvGASh'

                url = 'https://open.mapquestapi.com/staticmap/v4/' \
                      'getmap?key={}&center={}&zoom={}&size={},{}&type=map' \
                      '&imagetype=png&pois={},{}&scalebar=false' \
                      .format(apikey, location, zoom, size, size, color,
257
                              location)
258 259 260 261
                weburl = 'http://www.openstreetmap.org/' \
                         '?mlat={}&mlon={}#map={}/{}/{}&layers=N' \
                         .format(lat, lon, zoom, lat, lon)
                real_text = url
262 263 264 265 266
        else:
            weburl = real_text
            filename = os.path.basename(urlparts.path)
            ext = os.path.splitext(filename)[1]
            name = os.path.splitext(filename)[0]
267 268 269 270 271 272
            if len(name) > 90:
                # Many Filesystems have a limit on filename length
                # Most have 255, some encrypted ones only 143
                # We add around 50 chars for the hash,
                # so the filename should not exceed 90
                name = name[:90]
273
            namehash = hashlib.sha1(real_text.encode('utf-8')).hexdigest()
Daniel Brötzmann's avatar
Daniel Brötzmann committed
274 275 276 277 278 279 280 281 282 283 284
            newfilename = '%(name)s_%(namehash)s%(ext)s' % {
                'name': name,
                'namehash': namehash,
                'ext': ext
            }
            thumbfilename = '%(name)s_%(namehash)s_thumb_%(size)s%(ext)s' % {
                'name': name,
                'namehash': namehash,
                'size': str(self.plugin.config['PREVIEW_SIZE']),
                'ext': ext
            }
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

            filepath = os.path.join(self.directory, newfilename)
            thumbpath = os.path.join(self.thumbpath, thumbfilename)
            filepaths = [filepath, thumbpath]

            key = ''
            iv = ''
            encrypted = False
            if urlparts.fragment:
                fragment = binascii.unhexlify(urlparts.fragment)
                key = fragment[16:]
                iv = fragment[:16]
                if len(key) == 32 and len(iv) == 16:
                    encrypted = True
                if not encrypted:
                    key = fragment[12:]
                    iv = fragment[:12]
                    if len(key) == 32 and len(iv) == 12:
                        encrypted = True
304

Daniel Brötzmann's avatar
Daniel Brötzmann committed
305
        # File exists but thumbnail got deleted
Thilo Molitor's avatar
Thilo Molitor committed
306
        if os.path.exists(filepath) and not os.path.exists(thumbpath):
307
            if urlparts.scheme == 'geo':
Daniel Brötzmann's avatar
Daniel Brötzmann committed
308 309 310
                real_text = weburl
            with open(filepath, 'rb') as file_to_preview:
                mem = file_to_preview.read()
Thilo Molitor's avatar
Thilo Molitor committed
311
            app.thread_interface(
312
                self._save_thumbnail, [thumbpath, mem],
313
                self._update_img, [real_text, repl_start,
Thilo Molitor's avatar
Thilo Molitor committed
314 315
                                   repl_end, filepath, encrypted])

Daniel Brötzmann's avatar
Daniel Brötzmann committed
316 317
        # Display thumbnail if already downloaded
        # (but only if file exists)
Thilo Molitor's avatar
Thilo Molitor committed
318
        elif os.path.exists(filepath) and os.path.exists(thumbpath):
319 320
            if urlparts.scheme == 'geo':
                    real_text = weburl
Thilo Molitor's avatar
Thilo Molitor committed
321 322
            app.thread_interface(
                self._load_thumbnail, [thumbpath],
323
                self._update_img, [real_text, repl_start,
Thilo Molitor's avatar
Thilo Molitor committed
324 325
                                   repl_end, filepath, encrypted])

Daniel Brötzmann's avatar
Daniel Brötzmann committed
326
        # Or download file, calculate thumbnail, and finally display it
Thilo Molitor's avatar
Thilo Molitor committed
327 328 329 330 331 332 333 334
        else:
            if encrypted and not decryption_available:
                log.debug('Please install Crytography to decrypt pictures')
            else:
                # First get the http head request
                # which does not fetch data, just headers
                # then check the mime type and filesize
                if urlparts.scheme == 'aesgcm':
335
                    real_text = 'https://' + real_text[9:]
336
                verify = self.plugin.config['VERIFY']
Thilo Molitor's avatar
Thilo Molitor committed
337
                app.thread_interface(
338
                    get_http_head, [self.textview.account, real_text, verify],
339 340 341
                    self._check_mime_size, [real_text, weburl, repl_start,
                                            repl_end, filepaths, key, iv,
                                            encrypted])
Thilo Molitor's avatar
Thilo Molitor committed
342

343 344
    def _accept_uri(self, urlparts, real_text, additional_data):
        try:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
345
            oob_url = additional_data['gajim']['oob_url']
346 347 348 349 350 351 352 353
        except (KeyError, AttributeError):
            oob_url = None

        if not urlparts.netloc:
            log.info('No netloc found in URL %s', real_text)
            return False

        # geo
Daniel Brötzmann's avatar
Daniel Brötzmann committed
354
        if urlparts.scheme == 'geo':
355 356 357
            if self.plugin.config['GEO_PREVIEW_PROVIDER'] == 'no_preview':
                log.info('geo: link preview is disabled')
                return False
358 359
            return True

360 361 362 363 364 365 366
        # aesgcm
        if urlparts.scheme == 'aesgcm':
            return True

        # https
        if urlparts.scheme == 'https':
            if real_text == oob_url or self.plugin.config['ALLOW_ALL_IMAGES']:
367
                return True
368
            log.info('Incorrect oob data found')
369 370
            return False

Daniel Brötzmann's avatar
Daniel Brötzmann committed
371
        log.info('Unsupported URI scheme found: %s', real_text)
372 373
        return False

374
    def _save_thumbnail(self, thumbpath, mem):
Thilo Molitor's avatar
Thilo Molitor committed
375 376 377
        size = self.plugin.config['PREVIEW_SIZE']

        try:
378 379 380
            loader = GdkPixbuf.PixbufLoader()
            loader.write(mem)
            loader.close()
381 382 383 384
            if loader.get_format().get_name() == 'gif':
                pixbuf = loader.get_animation()
            else:
                pixbuf = loader.get_pixbuf()
385 386 387 388 389
        except GLib.GError as error:
            log.info('Failed to load image using Gdk.Pixbuf')
            log.debug(error)

            # Try Pillow
Daniel Brötzmann's avatar
Daniel Brötzmann committed
390
            image = Image.open(BytesIO(mem)).convert('RGBA')
391 392 393 394 395 396
            array = GLib.Bytes.new(image.tobytes())
            width, height = image.size
            pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(
                array, GdkPixbuf.Colorspace.RGB, True,
                8, width, height, width * 4)

Thilo Molitor's avatar
Thilo Molitor committed
397 398
        try:
            self._create_path(os.path.dirname(thumbpath))
399 400
            thumbnail = pixbuf
            if isinstance(pixbuf, GdkPixbuf.PixbufAnimation):
401
                if size < pixbuf.get_width() or size < pixbuf.get_height():
402 403 404 405 406
                    resize_gif(mem, thumbpath, (size, size))
                    thumbnail = self._load_thumbnail(thumbpath)
                else:
                    self._write_file(thumbpath, mem)
            else:
407 408 409
                width, height = self._get_thumbnail_size(pixbuf, size)
                thumbnail = pixbuf.scale_simple(
                    width, height, GdkPixbuf.InterpType.BILINEAR)
410
                thumbnail.savev(thumbpath, 'png', [], [])
411
        except Exception as error:
412 413
            GLib.idle_add(
                self._raise_error_dialog,
Thilo Molitor's avatar
Thilo Molitor committed
414 415 416
                _('Could not save file'),
                _('Exception raised while saving thumbnail '
                  'for image file (see error log for more '
417
                  'information)'))
418
            log.exception(error)
419 420
            return
        return thumbnail
Thilo Molitor's avatar
Thilo Molitor committed
421

422 423 424 425 426 427 428 429
    @staticmethod
    def _get_thumbnail_size(pixbuf, size):
        # Calculates the new thumbnail size while preserving the aspect ratio
        image_width = pixbuf.get_width()
        image_height = pixbuf.get_height()

        if image_width > image_height:
            if image_width > size:
430
                image_height = math.ceil((size / float(image_width) * image_height))
431 432 433
                image_width = int(size)
        else:
            if image_height > size:
434
                image_width = math.ceil((size / float(image_height) * image_width))
435 436 437 438
                image_height = int(size)

        return image_width, image_height

439 440 441 442 443
    @staticmethod
    def _load_thumbnail(thumbpath):
        ext = os.path.splitext(thumbpath)[1]
        if ext == '.gif':
            return GdkPixbuf.PixbufAnimation.new_from_file(thumbpath)
444
        return GdkPixbuf.Pixbuf.new_from_file(thumbpath)
Thilo Molitor's avatar
Thilo Molitor committed
445

446 447
    @staticmethod
    def _write_file(path, data):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
448
        log.info('Writing \'%s\' of size %d...', path, len(data))
Thilo Molitor's avatar
Thilo Molitor committed
449
        try:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
450
            with open(path, 'wb') as output_file:
Thilo Molitor's avatar
Thilo Molitor committed
451 452 453
                output_file.write(data)
                output_file.closed
        except Exception as e:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
454
            log.error('Failed to write file \'%s\'!', path)
Thilo Molitor's avatar
Thilo Molitor committed
455 456
            raise

457
    def _get_at_end(self):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
458
        return self.textview.autoscroll
459 460

    def _scroll_to_end(self):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
461
        self.textview.scroll_to_end()
462

463
    def _update_img(self, pixbuf, url, repl_start, repl_end,
Thilo Molitor's avatar
Thilo Molitor committed
464
                    filepath, encrypted):
465
        if pixbuf is None:
Thilo Molitor's avatar
Thilo Molitor committed
466
            # If image could not be downloaded, URL is already displayed
467 468 469
            log.error('Could not download image for URL: %s', url)
            return

470
        urlparts = urlparse(unquote(url))
471
        filename = os.path.basename(urlparts.path)
472 473 474
        if os.path.basename(filepath).startswith('location_'):
            filename = os.path.basename(filepath)

475 476
        def add_to_textview():
            try:
477
                at_end = self._get_at_end()
478 479 480

                buffer_ = repl_start.get_buffer()
                iter_ = buffer_.get_iter_at_mark(repl_start)
Daniel Brötzmann's avatar
Daniel Brötzmann committed
481
                buffer_.insert(iter_, '\n')
482
                anchor = buffer_.create_child_anchor(iter_)
483
                anchor.plaintext = url
484

485 486 487
                image = self._create_clickable_image(pixbuf, url)

                self.textview.tv.add_child_at_anchor(image, anchor)
488 489 490
                buffer_.delete(iter_,
                               buffer_.get_iter_at_mark(repl_end))

491
                image.connect(
492
                    'button-press-event', self._on_button_press_event,
493 494 495
                    filepath, filename, url, encrypted)
                image.get_window().set_cursor(get_cursor('HAND2'))

496
                if at_end:
497
                    self._scroll_to_end()
498
            except Exception as ex:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
499
                log.exception('Exception while loading %s: %s', url, ex)
500
            return False
Daniel Brötzmann's avatar
Daniel Brötzmann committed
501
        # Add to mainloop --> make call threadsafe
502
        GLib.idle_add(add_to_textview)
Dicson's avatar
Dicson committed
503

504 505 506 507 508 509 510 511 512
    def _create_clickable_image(self, pixbuf, url):
        if isinstance(pixbuf, GdkPixbuf.PixbufAnimation):
            image = Gtk.Image.new_from_animation(pixbuf)
        else:
            image = Gtk.Image.new_from_pixbuf(pixbuf)

        css = '''#Preview {
        box-shadow: 0px 0px 3px 0px alpha(@theme_text_color, 0.2);
        margin: 5px 10px 5px 10px; }'''
Daniel Brötzmann's avatar
Daniel Brötzmann committed
513
        add_css_to_widget(image, css)
514 515 516 517 518 519 520 521
        image.set_name('Preview')

        event_box = Gtk.EventBox()
        event_box.set_tooltip_text(url)
        event_box.add(image)
        event_box.show_all()
        return event_box

Thilo Molitor's avatar
Thilo Molitor committed
522
    def _check_mime_size(self, tuple_arg,
523
                         url, weburl, repl_start, repl_end, filepaths,
Thilo Molitor's avatar
Thilo Molitor committed
524 525 526
                         key, iv, encrypted):
        file_mime, file_size = tuple_arg
        # Check if mime type is acceptable
527
        if not file_mime or not file_size:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
528 529
            log.info('Failed to load HEAD Request for URL: \'%s\' '
                     'mime: %s, size: %s', url, file_mime, file_size)
Thilo Molitor's avatar
Thilo Molitor committed
530 531 532
            # URL is already displayed
            return
        if file_mime.lower() not in ACCEPTED_MIME_TYPES:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
533
            log.info('Not accepted mime type \'%s\' for URL: \'%s\'',
534
                     file_mime.lower(), url)
Thilo Molitor's avatar
Thilo Molitor committed
535 536 537
            # URL is already displayed
            return
        # Check if file size is acceptable
538 539
        max_size = int(self.plugin.config['MAX_FILE_SIZE'])
        if file_size > max_size or file_size == 0:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
540
            log.info('File size (%s) too big or unknown (zero) for URL: \'%s\'',
541
                     file_size, url)
Thilo Molitor's avatar
Thilo Molitor committed
542 543 544 545
            # URL is already displayed
            return

        attributes = {'src': url,
546
                      'verify': self.plugin.config['VERIFY'],
547
                      'max_size': max_size,
Thilo Molitor's avatar
Thilo Molitor committed
548 549 550 551 552 553 554
                      'filepaths': filepaths,
                      'key': key,
                      'iv': iv}

        app.thread_interface(
            self._download_image, [self.textview.account,
                                   attributes, encrypted],
555
            self._update_img, [weburl, repl_start, repl_end,
Thilo Molitor's avatar
Thilo Molitor committed
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
                               filepaths[0], encrypted])

    def _download_image(self, account, attributes, encrypted):
        filepath = attributes['filepaths'][0]
        thumbpath = attributes['filepaths'][1]
        key = attributes['key']
        iv = attributes['iv']
        mem, alt = get_http_file(account, attributes)

        # Decrypt file if necessary
        if encrypted:
            mem = self._aes_decrypt_fast(key, iv, mem)

        try:
            # Write file to harddisk
            self._write_file(filepath, mem)
        except Exception as e:
573 574
            GLib.idle_add(
                self._raise_error_dialog,
Thilo Molitor's avatar
Thilo Molitor committed
575 576
                _('Could not save file'),
                _('Exception raised while saving image file'
577
                  ' (see error log for more information)'))
Thilo Molitor's avatar
Thilo Molitor committed
578 579
            log.error(str(e))

Daniel Brötzmann's avatar
Daniel Brötzmann committed
580
        # Create thumbnail, write to disk and return it
581
        return self._save_thumbnail(thumbpath, mem)
Thilo Molitor's avatar
Thilo Molitor committed
582 583 584 585

    def _create_path(self, folder):
        if os.path.exists(folder):
            return
Daniel Brötzmann's avatar
Daniel Brötzmann committed
586
        log.debug('Creating folder \'%s\'' % folder)
Thilo Molitor's avatar
Thilo Molitor committed
587 588 589
        os.mkdir(folder, 0o700)

    def _aes_decrypt_fast(self, key, iv, payload):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
590
        # Use AES128 GCM with the given key and iv to decrypt the payload
Thilo Molitor's avatar
Thilo Molitor committed
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
        if os.name == 'nt':
            be = backend
        else:
            be = default_backend()
        data = payload[:-16]
        tag = payload[-16:]
        decryptor = Cipher(
            algorithms.AES(key),
            GCM(iv, tag=tag),
            backend=be).decryptor()
        return decryptor.update(data) + decryptor.finalize()

    def make_rightclick_menu(self, event, data):
        xml = Gtk.Builder()
        xml.set_translation_domain('gajim_plugins')
        xml.add_from_file(self.plugin.local_file_path('context_menu.ui'))
        menu = xml.get_object('context_menu')

        open_menuitem = xml.get_object('open_menuitem')
        save_as_menuitem = xml.get_object('save_as_menuitem')
611
        open_folder_menuitem = xml.get_object('open_folder_menuitem')
612 613 614 615 616 617 618
        copy_link_location_menuitem = xml.get_object(
            'copy_link_location_menuitem')
        open_link_in_browser_menuitem = xml.get_object(
            'open_link_in_browser_menuitem')
        open_file_in_browser_menuitem = xml.get_object(
            'open_file_in_browser_menuitem')
        extras_separator = xml.get_object('extras_separator')
619

Daniel Brötzmann's avatar
Daniel Brötzmann committed
620
        if data['encrypted']:
Thilo Molitor's avatar
Thilo Molitor committed
621 622 623 624 625 626 627
            open_link_in_browser_menuitem.hide()
        if app.config.get('autodetect_browser_mailer') \
                or app.config.get('custombrowser') == '':
            extras_separator.hide()
            open_file_in_browser_menuitem.hide()

        id_ = open_menuitem.connect(
628
            'activate', self._on_open_menuitem_activate, data)
Thilo Molitor's avatar
Thilo Molitor committed
629
        self.handlers[id_] = open_menuitem
630
        id_ = save_as_menuitem.connect(
631
            'activate', self._on_save_as_menuitem_activate, data)
Thilo Molitor's avatar
Thilo Molitor committed
632
        self.handlers[id_] = save_as_menuitem
633 634 635
        id_ = open_folder_menuitem.connect(
            'activate', self._on_open_folder_menuitem_activate, data)
        self.handlers[id_] = save_as_menuitem
Thilo Molitor's avatar
Thilo Molitor committed
636
        id_ = copy_link_location_menuitem.connect(
637
            'activate', self._on_copy_link_location_menuitem_activate, data)
Thilo Molitor's avatar
Thilo Molitor committed
638 639
        self.handlers[id_] = copy_link_location_menuitem
        id_ = open_link_in_browser_menuitem.connect(
640
            'activate', self._on_open_link_in_browser_menuitem_activate, data)
Thilo Molitor's avatar
Thilo Molitor committed
641 642
        self.handlers[id_] = open_link_in_browser_menuitem
        id_ = open_file_in_browser_menuitem.connect(
643
            'activate', self._on_open_file_in_browser_menuitem_activate, data)
Thilo Molitor's avatar
Thilo Molitor committed
644 645 646 647
        self.handlers[id_] = open_file_in_browser_menuitem

        return menu

648
    def _on_open_menuitem_activate(self, menu, data):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
649 650 651
        filepath = data['filepath']
        original_filename = data['original_filename']
        url = data['url']
652
        if original_filename.startswith('location_'):
653
            helpers.open_uri(url)
654
            return
Thilo Molitor's avatar
Thilo Molitor committed
655 656
        helpers.launch_file_manager(filepath)

657
    def _on_save_as_menuitem_activate(self, menu, data):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
658 659
        filepath = data['filepath']
        original_filename = data['original_filename']
660 661 662 663

        def on_ok(target_path):
            dirname = os.path.dirname(target_path)
            if not os.access(dirname, os.W_OK):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
664 665 666 667 668
                ErrorDialog(
                    _('Directory \'%s\' is not writable') % dirname,
                    _('You do not have the proper permissions to '
                      'create files in this directory.'),
                      transient_for=app.app.get_active_window())
669 670 671 672 673 674 675 676
                return
            shutil.copy(filepath, target_path)

        FileSaveDialog(on_ok,
                       path=app.config.get('last_save_dir'),
                       file_name=original_filename,
                       transient_for=app.app.get_active_window())

677 678 679
    def _on_open_folder_menuitem_activate(self, menu, data):
        helpers.launch_file_manager(self.directory)

680
    def _on_copy_link_location_menuitem_activate(self, menu, data):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
681
        url = data['url']
Thilo Molitor's avatar
Thilo Molitor committed
682 683 684 685
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(url, -1)
        clipboard.store()

686
    def _on_open_link_in_browser_menuitem_activate(self, menu, data):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
687 688
        url = data['url']
        if data['encrypted']:
689
            self._on_open_menuitem_activate(self, data)
Thilo Molitor's avatar
Thilo Molitor committed
690
        else:
691
            helpers.open_uri(url)
692

693
    def _on_open_file_in_browser_menuitem_activate(self, menu, data):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
694 695
        if os.name == 'nt':
            filepath = 'file://' + os.path.abspath(data['filepath'])
Thilo Molitor's avatar
Thilo Molitor committed
696
        else:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
697
            filepath = 'file://' + data['filepath']
Thilo Molitor's avatar
Thilo Molitor committed
698 699
        if app.config.get('autodetect_browser_mailer') \
                or app.config.get('custombrowser') == '':
Daniel Brötzmann's avatar
Daniel Brötzmann committed
700
            ErrorDialog(
Thilo Molitor's avatar
Thilo Molitor committed
701 702
                _('Cannot open downloaded file in browser'),
                _('You have to set a custom browser executable '
Daniel Brötzmann's avatar
Daniel Brötzmann committed
703
                  'in Gajim\'s Preferences for this to work.'),
704
                transient_for=app.app.get_active_window())
Thilo Molitor's avatar
Thilo Molitor committed
705 706 707 708 709 710 711 712
            return
        command = app.config.get('custombrowser')
        command = helpers.build_command(command, filepath)
        try:
            helpers.exec_command(command)
        except Exception:
            pass

713 714
    def _on_button_press_event(self, eb, event, filepath, original_filename,
                               url, encrypted):
Daniel Brötzmann's avatar
Daniel Brötzmann committed
715 716 717 718 719
        data = {'filepath': filepath,
                'original_filename': original_filename,
                'url': url,
                'encrypted': encrypted}
        # Left click
Thilo Molitor's avatar
Thilo Molitor committed
720
        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
Daniel Brötzmann's avatar
Daniel Brötzmann committed
721
            method = getattr(self, '_on_'
Thilo Molitor's avatar
Thilo Molitor committed
722
                             + self.plugin.config['LEFTCLICK_ACTION']
Daniel Brötzmann's avatar
Daniel Brötzmann committed
723
                             + '_activate')
Thilo Molitor's avatar
Thilo Molitor committed
724
            method(event, data)
Daniel Brötzmann's avatar
Daniel Brötzmann committed
725
        # Right klick
Thilo Molitor's avatar
Thilo Molitor committed
726 727
        elif event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
            menu = self.make_rightclick_menu(event, data)
728 729
            # menu.attach_to_widget(self.tv, None)
            # menu.popup(None, None, None, event.button, event.time)
Thilo Molitor's avatar
Thilo Molitor committed
730 731
            menu.popup_at_pointer(event)

732 733 734
    @staticmethod
    def _raise_error_dialog(pritext, sectext):
        # Used by methods that run in a different thread
Daniel Brötzmann's avatar
Daniel Brötzmann committed
735 736 737
        ErrorDialog(pritext,
                    sectext,
                    transient_for=app.app.get_active_window())
738

Dicson's avatar
Dicson committed
739 740
    def disconnect_from_chat_control(self):
        pass