url_image_preview.py 28 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
Thilo Molitor's avatar
Thilo Molitor committed
23 24 25
from urllib.parse import urlparse
from io import BytesIO
import shutil
26
from functools import partial
Dicson's avatar
Dicson committed
27

28 29
from gi.repository import Gtk, Gdk, GLib, GdkPixbuf

30 31
from gajim.common import app
from gajim.common import helpers
Thilo Molitor's avatar
Thilo Molitor committed
32
from gajim.common import configpaths
33

Thilo Molitor's avatar
Thilo Molitor committed
34
from gajim import dialogs
35
from gajim import gtkgui_helpers
36

37 38
from gajim.plugins import GajimPlugin
from gajim.plugins.helpers import log_calls
39 40
from gajim.plugins.plugins_i18n import _

41 42
from url_image_preview.http_functions import get_http_head, get_http_file
from url_image_preview.config_dialog import UrlImagePreviewConfigDialog
43
from url_image_preview.resize_gif import resize_gif
Dicson's avatar
Dicson committed
44

45
from gajim.gtk.filechoosers import FileSaveDialog
46

47

48
log = logging.getLogger('gajim.plugin_system.preview')
Thilo Molitor's avatar
Thilo Molitor committed
49

50
PILLOW_AVAILABLE = True
Thilo Molitor's avatar
Thilo Molitor committed
51 52 53 54
try:
    from PIL import Image
except:
    log.debug('Pillow not available')
55
    PILLOW_AVAILABLE = False
Thilo Molitor's avatar
Thilo Molitor committed
56 57 58 59 60 61 62 63 64 65

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
66
except Exception:
Thilo Molitor's avatar
Thilo Molitor committed
67 68
    DEP_MSG = 'For preview of encrypted images, ' \
              'please install python-cryptography!'
69
    log.exception('Error')
Thilo Molitor's avatar
Thilo Molitor committed
70 71 72 73 74
    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
75 76 77 78 79


class UrlImagePreviewPlugin(GajimPlugin):
    @log_calls('UrlImagePreviewPlugin')
    def init(self):
Thilo Molitor's avatar
Thilo Molitor committed
80 81
        if not decryption_available:
            self.available_text = DEP_MSG
82
        self.config_dialog = partial(UrlImagePreviewConfigDialog, self)
Dicson's avatar
Dicson committed
83
        self.gui_extension_points = {
Thilo Molitor's avatar
Thilo Molitor committed
84 85
            'chat_control_base': (self.connect_with_chat_control,
                                  self.disconnect_from_chat_control),
86
            'history_window':
87
                (self.connect_with_history, self.disconnect_from_history),
88
            'print_real_text': (self.print_real_text, None), }
Dicson's avatar
Dicson committed
89
        self.config_default_values = {
Thilo Molitor's avatar
Thilo Molitor committed
90
            'PREVIEW_SIZE': (150, 'Preview size(10-512)'),
91
            'MAX_FILE_SIZE': (5242880, 'Max file size for image preview'),
92
            'ALLOW_ALL_IMAGES': (False, ''),
93
            'LEFTCLICK_ACTION': ('open_menuitem', 'Open'),
94
            'ANONYMOUS_MUC': (False, ''),
95
            'GEO_PREVIEW_PROVIDER': ('Google', 'Google Maps'),
96
            'VERIFY': (True, ''),}
Thilo Molitor's avatar
Thilo Molitor committed
97
        self.controls = {}
98
        self.history_window_control = None
Thilo Molitor's avatar
Thilo Molitor committed
99

Dicson's avatar
Dicson committed
100 101
    @log_calls('UrlImagePreviewPlugin')
    def connect_with_chat_control(self, chat_control):
Thilo Molitor's avatar
Thilo Molitor committed
102 103 104 105
        account = chat_control.contact.account.name
        jid = chat_control.contact.jid
        if account not in self.controls:
            self.controls[account] = {}
106
        self.controls[account][jid] = Base(self, chat_control.conv_textview)
Dicson's avatar
Dicson committed
107 108 109

    @log_calls('UrlImagePreviewPlugin')
    def disconnect_from_chat_control(self, chat_control):
Thilo Molitor's avatar
Thilo Molitor committed
110 111
        account = chat_control.contact.account.name
        jid = chat_control.contact.jid
112
        self.controls[account][jid].deinit_handlers()
Thilo Molitor's avatar
Thilo Molitor committed
113
        del self.controls[account][jid]
114

115 116 117 118 119
    @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(
120
            self, history_window.history_textview)
121 122 123 124 125 126

    @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
127

128 129
    def print_real_text(self, tv, real_text, text_tags, graphics,
                        iter_, additional_data):
130
        if tv.used_in_history_window and self.history_window_control:
131 132 133
            self.history_window_control.print_real_text(
                real_text, text_tags, graphics, iter_, additional_data)

Thilo Molitor's avatar
Thilo Molitor committed
134 135
        account = tv.account
        for jid in self.controls[account]:
136
            if self.controls[account][jid].textview != tv:
Dicson's avatar
Dicson committed
137
                continue
138 139
            self.controls[account][jid].print_real_text(
                real_text, text_tags, graphics, iter_, additional_data)
Thilo Molitor's avatar
Thilo Molitor committed
140
            return
Dicson's avatar
Dicson committed
141 142 143


class Base(object):
144
    def __init__(self, plugin, textview):
Dicson's avatar
Dicson committed
145
        self.plugin = plugin
146
        self.textview = textview
Thilo Molitor's avatar
Thilo Molitor committed
147
        self.handlers = {}
Dicson's avatar
Dicson committed
148

149
        self.directory = os.path.join(configpaths.get('MY_DATA'),
Thilo Molitor's avatar
Thilo Molitor committed
150
                                      'downloads')
151
        self.thumbpath = os.path.join(configpaths.get('MY_CACHE'),
Thilo Molitor's avatar
Thilo Molitor committed
152 153 154 155 156
                                      'downloads.thumb')

        try:
            self._create_path(self.directory)
            self._create_path(self.thumbpath)
157
        except Exception:
Thilo Molitor's avatar
Thilo Molitor committed
158 159 160
            log.error("Error creating download and/or thumbnail folder!")
            raise

161
    def deinit_handlers(self):
Thilo Molitor's avatar
Thilo Molitor committed
162 163 164 165 166 167 168
        # remove all register handlers on wigets, created by self.xml
        # 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]

169 170 171
    def print_real_text(self, real_text, text_tags, graphics, iter_,
                        additional_data):

172 173
        if len(real_text.split(' ')) > 1:
            # urlparse dont recognises spaces as URL delimiter
174
            log.debug('Url with text will not be displayed: %s', real_text)
175 176
            return

177 178
        urlparts = urlparse(real_text)
        if not self._accept_uri(urlparts, real_text, additional_data):
179
            return
Thilo Molitor's avatar
Thilo Molitor committed
180 181 182 183

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

Dicson's avatar
Dicson committed
184
        buffer_ = self.textview.tv.get_buffer()
Thilo Molitor's avatar
Thilo Molitor committed
185 186 187 188 189 190
        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)
191
        buffer_.insert_with_tags(iter_, real_text,
Thilo Molitor's avatar
Thilo Molitor committed
192 193 194
            *[(ttt.lookup(t) if isinstance(t, str) else t) for t in ["url"]])
        repl_end = buffer_.create_mark(None, iter_, True)

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        # 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

            filename = 'location_' + geo_provider + '_' \
                + location.replace(',', '_').replace('.', '-')
            newfilename = filename + ext
            thumbfilename = filename + '_thumb_' \
                + str(self.plugin.config['PREVIEW_SIZE']) + ext
            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,
238
                              location)
239 240 241 242
                weburl = 'http://www.openstreetmap.org/' \
                         '?mlat={}&mlon={}#map={}/{}/{}&layers=N' \
                         .format(lat, lon, zoom, lat, lon)
                real_text = url
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        else:
            weburl = real_text
            filename = os.path.basename(urlparts.path)
            ext = os.path.splitext(filename)[1]
            name = os.path.splitext(filename)[0]
            namehash = hashlib.sha1(real_text.encode('utf-8')).hexdigest()
            newfilename = name + '_' + namehash + ext
            thumbfilename = name + '_' + namehash + '_thumb_' \
                + str(self.plugin.config['PREVIEW_SIZE']) + ext

            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
271

Thilo Molitor's avatar
Thilo Molitor committed
272 273
        # file exists but thumbnail got deleted
        if os.path.exists(filepath) and not os.path.exists(thumbpath):
274 275
            if urlparts.scheme == 'geo':
                    real_text = weburl
Thilo Molitor's avatar
Thilo Molitor committed
276 277 278
            with open(filepath, 'rb') as f:
                mem = f.read()
            app.thread_interface(
279
                self._save_thumbnail, [thumbpath, mem],
280
                self._update_img, [real_text, repl_start,
Thilo Molitor's avatar
Thilo Molitor committed
281 282 283 284 285
                                   repl_end, filepath, encrypted])

        # display thumbnail if already downloadeded
        # (but only if file also exists)
        elif os.path.exists(filepath) and os.path.exists(thumbpath):
286 287
            if urlparts.scheme == 'geo':
                    real_text = weburl
Thilo Molitor's avatar
Thilo Molitor committed
288 289
            app.thread_interface(
                self._load_thumbnail, [thumbpath],
290
                self._update_img, [real_text, repl_start,
Thilo Molitor's avatar
Thilo Molitor committed
291 292 293 294 295 296 297 298 299 300 301
                                   repl_end, filepath, encrypted])

        # or download file, calculate thumbnail and finally display it
        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':
302
                    real_text = 'https://' + real_text[9:]
303
                verify = self.plugin.config['VERIFY']
Thilo Molitor's avatar
Thilo Molitor committed
304
                app.thread_interface(
305
                    get_http_head, [self.textview.account, real_text, verify],
306 307 308
                    self._check_mime_size, [real_text, weburl, repl_start,
                                            repl_end, filepaths, key, iv,
                                            encrypted])
Thilo Molitor's avatar
Thilo Molitor committed
309

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    def _accept_uri(self, urlparts, real_text, additional_data):
        try:
            oob_url = additional_data["gajim"]["oob_url"]
        except (KeyError, AttributeError):
            oob_url = None

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

        # geo
        if urlparts.scheme == "geo":
            if self.plugin.config['GEO_PREVIEW_PROVIDER'] == 'no_preview':
                log.info('geo: link preview is disabled')
                return False
325 326
            return True

327 328 329 330 331 332 333
        # aesgcm
        if urlparts.scheme == 'aesgcm':
            return True

        # https
        if urlparts.scheme == 'https':
            if real_text == oob_url or self.plugin.config['ALLOW_ALL_IMAGES']:
334
                return True
335
            log.info('Incorrect oob data found')
336 337
            return False

338 339 340
        log.info('Not supported URI scheme found: %s', real_text)
        return False

341
    def _save_thumbnail(self, thumbpath, mem):
Thilo Molitor's avatar
Thilo Molitor committed
342 343 344
        size = self.plugin.config['PREVIEW_SIZE']

        try:
345 346 347
            loader = GdkPixbuf.PixbufLoader()
            loader.write(mem)
            loader.close()
348 349 350 351
            if loader.get_format().get_name() == 'gif':
                pixbuf = loader.get_animation()
            else:
                pixbuf = loader.get_pixbuf()
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        except GLib.GError as error:
            log.info('Failed to load image using Gdk.Pixbuf')
            log.debug(error)

            if not PILLOW_AVAILABLE:
                log.info('Pillow not available')
                return
            # Try Pillow
            image = Image.open(BytesIO(mem)).convert("RGBA")
            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
367 368
        try:
            self._create_path(os.path.dirname(thumbpath))
369 370
            thumbnail = pixbuf
            if isinstance(pixbuf, GdkPixbuf.PixbufAnimation):
371
                if size < pixbuf.get_width() or size < pixbuf.get_height():
372 373 374 375 376
                    resize_gif(mem, thumbpath, (size, size))
                    thumbnail = self._load_thumbnail(thumbpath)
                else:
                    self._write_file(thumbpath, mem)
            else:
377 378 379
                width, height = self._get_thumbnail_size(pixbuf, size)
                thumbnail = pixbuf.scale_simple(
                    width, height, GdkPixbuf.InterpType.BILINEAR)
380
                thumbnail.savev(thumbpath, 'png', [], [])
381
        except Exception as error:
382 383
            GLib.idle_add(
                self._raise_error_dialog,
Thilo Molitor's avatar
Thilo Molitor committed
384 385 386
                _('Could not save file'),
                _('Exception raised while saving thumbnail '
                  'for image file (see error log for more '
387
                  'information)'))
388
            log.exception(error)
389 390
            return
        return thumbnail
Thilo Molitor's avatar
Thilo Molitor committed
391

392 393 394 395 396 397 398 399
    @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:
400
                image_height = math.ceil((size / float(image_width) * image_height))
401 402 403
                image_width = int(size)
        else:
            if image_height > size:
404
                image_width = math.ceil((size / float(image_height) * image_width))
405 406 407 408
                image_height = int(size)

        return image_width, image_height

409 410 411 412 413
    @staticmethod
    def _load_thumbnail(thumbpath):
        ext = os.path.splitext(thumbpath)[1]
        if ext == '.gif':
            return GdkPixbuf.PixbufAnimation.new_from_file(thumbpath)
414
        return GdkPixbuf.Pixbuf.new_from_file(thumbpath)
Thilo Molitor's avatar
Thilo Molitor committed
415

416 417
    @staticmethod
    def _write_file(path, data):
418
        log.info("Writing '%s' of size %d...", path, len(data))
Thilo Molitor's avatar
Thilo Molitor committed
419 420 421 422 423
        try:
            with open(path, "wb") as output_file:
                output_file.write(data)
                output_file.closed
        except Exception as e:
424
            log.error("Failed to write file '%s'!", path)
Thilo Molitor's avatar
Thilo Molitor committed
425 426
            raise

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    def _get_at_end(self):
        try:
            # Gajim 1.0.0
            return self.textview.at_the_end()
        except AttributeError:
            # Gajim 1.0.1
            return self.textview.autoscroll

    def _scroll_to_end(self):
        try:
            # Gajim 1.0.0
            self.textview.scroll_to_end_iter()
        except AttributeError:
            # Gajim 1.0.1
            self.textview.scroll_to_end()

443
    def _update_img(self, pixbuf, url, repl_start, repl_end,
Thilo Molitor's avatar
Thilo Molitor committed
444
                    filepath, encrypted):
445
        if pixbuf is None:
Thilo Molitor's avatar
Thilo Molitor committed
446
            # If image could not be downloaded, URL is already displayed
447 448 449 450 451
            log.error('Could not download image for URL: %s', url)
            return

        urlparts = urlparse(url)
        filename = os.path.basename(urlparts.path)
452 453 454
        if os.path.basename(filepath).startswith('location_'):
            filename = os.path.basename(filepath)

455 456 457 458 459 460 461 462
        event_box = Gtk.EventBox()
        event_box.connect('button-press-event', self.on_button_press_event,
                          filepath, filename, url, encrypted)
        event_box.connect('enter-notify-event', self.on_enter_event)
        event_box.connect('leave-notify-event', self.on_leave_event)

        def add_to_textview():
            try:
463
                at_end = self._get_at_end()
464 465 466

                buffer_ = repl_start.get_buffer()
                iter_ = buffer_.get_iter_at_mark(repl_start)
467
                buffer_.insert(iter_, "\n")
468
                anchor = buffer_.create_child_anchor(iter_)
469
                anchor.plaintext = url
470

471 472 473 474
                if isinstance(pixbuf, GdkPixbuf.PixbufAnimation):
                    image = Gtk.Image.new_from_animation(pixbuf)
                else:
                    image = Gtk.Image.new_from_pixbuf(pixbuf)
475 476 477 478 479 480 481

                css = '''#Preview {
                box-shadow: 0px 0px 3px 0px alpha(@theme_text_color, 0.2);
                margin: 5px 10px 5px 10px; }'''
                gtkgui_helpers.add_css_to_widget(image, css)
                image.set_name('Preview')

482
                event_box.set_tooltip_text(url)
483 484 485 486 487 488 489
                event_box.add(image)
                event_box.show_all()
                self.textview.tv.add_child_at_anchor(event_box, anchor)
                buffer_.delete(iter_,
                               buffer_.get_iter_at_mark(repl_end))

                if at_end:
490
                    self._scroll_to_end()
491 492 493 494 495
            except Exception as ex:
                log.exception("Exception while loading %s: %s", url, ex)
            return False
        # add to mainloop --> make call threadsafe
        GLib.idle_add(add_to_textview)
Dicson's avatar
Dicson committed
496

Thilo Molitor's avatar
Thilo Molitor committed
497
    def _check_mime_size(self, tuple_arg,
498
                         url, weburl, repl_start, repl_end, filepaths,
Thilo Molitor's avatar
Thilo Molitor committed
499 500 501
                         key, iv, encrypted):
        file_mime, file_size = tuple_arg
        # Check if mime type is acceptable
502 503 504
        if not file_mime or not file_size:
            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
505 506 507
            # URL is already displayed
            return
        if file_mime.lower() not in ACCEPTED_MIME_TYPES:
508 509
            log.info("Not accepted mime type '%s' for URL: '%s'",
                     file_mime.lower(), url)
Thilo Molitor's avatar
Thilo Molitor committed
510 511 512
            # URL is already displayed
            return
        # Check if file size is acceptable
513 514
        max_size = int(self.plugin.config['MAX_FILE_SIZE'])
        if file_size > max_size or file_size == 0:
515 516
            log.info("File size (%s) too big or unknown (zero) for URL: '%s'",
                     file_size, url)
Thilo Molitor's avatar
Thilo Molitor committed
517 518 519 520
            # URL is already displayed
            return

        attributes = {'src': url,
521
                      'verify': self.plugin.config['VERIFY'],
522
                      'max_size': max_size,
Thilo Molitor's avatar
Thilo Molitor committed
523 524 525 526 527 528 529
                      'filepaths': filepaths,
                      'key': key,
                      'iv': iv}

        app.thread_interface(
            self._download_image, [self.textview.account,
                                   attributes, encrypted],
530
            self._update_img, [weburl, repl_start, repl_end,
Thilo Molitor's avatar
Thilo Molitor committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
                               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:
548 549
            GLib.idle_add(
                self._raise_error_dialog,
Thilo Molitor's avatar
Thilo Molitor committed
550 551
                _('Could not save file'),
                _('Exception raised while saving image file'
552
                  ' (see error log for more information)'))
Thilo Molitor's avatar
Thilo Molitor committed
553 554 555
            log.error(str(e))

        # Create thumbnail, write it to harddisk and return it
556
        return self._save_thumbnail(thumbpath, mem)
Thilo Molitor's avatar
Thilo Molitor committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593

    def _create_path(self, folder):
        if os.path.exists(folder):
            return
        log.debug("creating folder '%s'" % folder)
        os.mkdir(folder, 0o700)

    def _aes_decrypt_fast(self, key, iv, payload):
        # Use AES128 GCM with the given key and iv to decrypt the payload.
        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')
        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')
594

Thilo Molitor's avatar
Thilo Molitor committed
595 596 597 598 599 600 601 602 603 604
        if data["encrypted"]:
            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(
            'activate', self.on_open_menuitem_activate, data)
        self.handlers[id_] = open_menuitem
605 606
        id_ = save_as_menuitem.connect(
            'activate', self.on_save_as_menuitem_activate_new, data)
Thilo Molitor's avatar
Thilo Molitor committed
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
        self.handlers[id_] = save_as_menuitem
        id_ = copy_link_location_menuitem.connect(
            'activate', self.on_copy_link_location_menuitem_activate, data)
        self.handlers[id_] = copy_link_location_menuitem
        id_ = open_link_in_browser_menuitem.connect(
            'activate', self.on_open_link_in_browser_menuitem_activate, data)
        self.handlers[id_] = open_link_in_browser_menuitem
        id_ = open_file_in_browser_menuitem.connect(
            'activate', self.on_open_file_in_browser_menuitem_activate, data)
        self.handlers[id_] = open_file_in_browser_menuitem

        return menu

    def on_open_menuitem_activate(self, menu, data):
        filepath = data["filepath"]
622 623 624 625 626
        original_filename = data["original_filename"]
        url = data["url"]
        if original_filename.startswith('location_'):
            helpers.launch_browser_mailer('url', url)
            return
Thilo Molitor's avatar
Thilo Molitor committed
627 628
        helpers.launch_file_manager(filepath)

629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
    def on_save_as_menuitem_activate_new(self, menu, data):
        filepath = data["filepath"]
        original_filename = data["original_filename"]

        def on_ok(target_path):
            dirname = os.path.dirname(target_path)
            if not os.access(dirname, os.W_OK):
                dialogs.ErrorDialog(
                    _('Directory "%s" is not writable') % dirname,
                    _('You do not have permission to '
                      'create files in this directory.'))
                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())

Thilo Molitor's avatar
Thilo Molitor committed
648 649 650 651 652 653 654 655 656 657 658 659 660 661
    def on_copy_link_location_menuitem_activate(self, menu, data):
        url = data["url"]
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(url, -1)
        clipboard.store()

    def on_open_link_in_browser_menuitem_activate(self, menu, data):
        url = data["url"]
        if data["encrypted"]:
            dialogs.ErrorDialog(
                _('Encrypted file'),
                _('You cannot open encrypted files in your '
                  'browser directly. Try "Open Downloaded File '
                  'in Browser" instead.'),
662
                transient_for=app.app.get_active_window())
Thilo Molitor's avatar
Thilo Molitor committed
663 664
        else:
            helpers.launch_browser_mailer('url', url)
665

Thilo Molitor's avatar
Thilo Molitor committed
666 667 668 669 670 671 672 673 674 675 676
    def on_open_file_in_browser_menuitem_activate(self, menu, data):
        if os.name == "nt":
            filepath = "file://" + os.path.abspath(data["filepath"])
        else:
            filepath = "file://" + data["filepath"]
        if app.config.get('autodetect_browser_mailer') \
                or app.config.get('custombrowser') == '':
            dialogs.ErrorDialog(
                _('Cannot open downloaded file in browser'),
                _('You have to set a custom browser executable '
                  'in your gajim settings for this to work.'),
677
                transient_for=app.app.get_active_window())
Thilo Molitor's avatar
Thilo Molitor committed
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
            return
        command = app.config.get('custombrowser')
        command = helpers.build_command(command, filepath)
        try:
            helpers.exec_command(command)
        except Exception:
            pass

    # Change mouse pointer to HAND2 when
    # mouse enter the eventbox with the image
    def on_enter_event(self, eb, event):
        self.textview.tv.get_window(
            Gtk.TextWindowType.TEXT).set_cursor(Gdk.Cursor(Gdk.CursorType.HAND2))

    # Change mouse pointer to default when mouse leaves the eventbox
    def on_leave_event(self, eb, event):
        self.textview.tv.get_window(
            Gtk.TextWindowType.TEXT).set_cursor(Gdk.Cursor(Gdk.CursorType.XTERM))

    def on_button_press_event(self, eb, event, filepath,
                              original_filename, url, encrypted):
        data = {"filepath": filepath,
                "original_filename": original_filename,
                "url": url,
                "encrypted": encrypted}
        # left click
        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
            method = getattr(self, "on_"
                             + self.plugin.config['LEFTCLICK_ACTION']
                             + "_activate")
            method(event, data)
        # right klick
        elif event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
            menu = self.make_rightclick_menu(event, data)
712 713
            # menu.attach_to_widget(self.tv, None)
            # menu.popup(None, None, None, event.button, event.time)
Thilo Molitor's avatar
Thilo Molitor committed
714 715
            menu.popup_at_pointer(event)

716 717 718 719 720 721 722
    @staticmethod
    def _raise_error_dialog(pritext, sectext):
        # Used by methods that run in a different thread
        dialogs.ErrorDialog(pritext,
                            sectext,
                            transient_for=app.app.get_active_window())

Dicson's avatar
Dicson committed
723 724
    def disconnect_from_chat_control(self):
        pass