def on_ok(widget, callback):
     '''
     check if file exists and call callback
     '''
     path_to_file = self.get_filename()
     path_to_file = gtkgui_helpers.decode_filechooser_file_paths(
         (path_to_file, ))[0]
     widget.destroy()
     callback(path_to_file)
 def on_ok(widget, callback):
     '''
     check if file exists and call callback
     '''
     path_to_file = self.get_filename()
     path_to_file = gtkgui_helpers.decode_filechooser_file_paths(
         (path_to_file,))[0]
     widget.destroy()
     callback(path_to_file)
		def on_ok(widget):
			file_dir = None
			files_path_list = dialog.get_filenames()
			files_path_list = gtkgui_helpers.decode_filechooser_file_paths(
				files_path_list)
			desc = desc_entry.get_text()
			for file_path in files_path_list:
				if self.send_file(account, contact, file_path, desc) and file_dir is None:
					file_dir = os.path.dirname(file_path)
			if file_dir:
				gajim.config.set('last_send_dir', file_dir)
				dialog.destroy()
Exemple #4
0
        def on_ok(widget, account, contact, file_props):
            file_path = dialog2.get_filename()
            file_path = gtkgui_helpers.decode_filechooser_file_paths(
                (file_path,))[0]
            if os.path.exists(file_path):
                # check if we have write permissions
                if not os.access(file_path, os.W_OK):
                    file_name = GLib.markup_escape_text(os.path.basename(
                        file_path))
                    dialogs.ErrorDialog(
                        _('Cannot overwrite existing file "%s"' % file_name),
                        _('A file with this name already exists and you do not '
                        'have permission to overwrite it.'))
                    return
                stat = os.stat(file_path)
                dl_size = stat.st_size
                file_size = file_props.size
                dl_finished = dl_size >= file_size

                def on_response(response):
                    if response < 0:
                        return
                    elif response == 100:
                        file_props.offset = dl_size
                    dialog2.destroy()
                    self._start_receive(file_path, account, contact, file_props)

                dialog = dialogs.FTOverwriteConfirmationDialog(
                    _('This file already exists'), _('What do you want to do?'),
                    propose_resume=not dl_finished, on_response=on_response,
                    transient_for=dialog2)
                dialog.set_destroy_with_parent(True)
                return
            else:
                dirname = os.path.dirname(file_path)
                if not os.access(dirname, os.W_OK) and os.name != 'nt':
                    # read-only bit is used to mark special folder under
                    # windows, not to mark that a folder is read-only.
                    # See ticket #3587
                    dialogs.ErrorDialog(_('Directory "%s" is not writable') % \
                        dirname, _('You do not have permission to create files '
                        'in this directory.'))
                    return
            dialog2.destroy()
            self._start_receive(file_path, account, contact, file_props)
			def on_ok(widget, account, contact, file_props):
				file_path = dialog2.get_filename()
				file_path = gtkgui_helpers.decode_filechooser_file_paths(
					(file_path,))[0]
				if os.path.exists(file_path):
					# check if we have write permissions
					if not os.access(file_path, os.W_OK):
						file_name = os.path.basename(file_path)
						dialogs.ErrorDialog(_('Cannot overwrite existing file "%s"' % file_name),
						_('A file with this name already exists and you do not have permission to overwrite it.'))
						return
					stat = os.stat(file_path)
					dl_size = stat.st_size
					file_size = file_props['size']
					dl_finished = dl_size >= file_size

					def on_response(response):
						if response < 0:
							return
						elif response == 100:
							file_props['offset'] = dl_size
						dialog2.destroy()
						self._start_receive(file_path, account, contact, file_props)

					dialog = dialogs.FTOverwriteConfirmationDialog(
						_('This file already exists'), _('What do you want to do?'),
						propose_resume=not dl_finished, on_response=on_response)
					dialog.set_transient_for(dialog2)
					dialog.set_destroy_with_parent(True)
					return
				else:
					dirname = os.path.dirname(file_path)
					if not os.access(dirname, os.W_OK) and os.name != 'nt':
						# read-only bit is used to mark special folder under windows,
						# not to mark that a folder is read-only. See ticket #3587
						dialogs.ErrorDialog(_('Directory "%s" is not writable') % dirname, _('You do not have permission to create files in this directory.'))
						return
				dialog2.destroy()
				self._start_receive(file_path, account, contact, file_props)
    def on_file_dialog_ok(self, widget, path_to_file=None):
        global jid_to_servers

        try:
            self.encrypted_upload = self.encryption_activated()
        except Exception as e:
            log.debug(e)
            self.encrypted_upload = False

        if not path_to_file:
            path_to_file = self.dlg.get_filename()
            if not path_to_file:
                self.dlg.destroy()
                return
            path_to_file = gtkgui_helpers.decode_filechooser_file_paths(
                    (path_to_file,))[0]
        self.dlg.destroy()
        if not os.path.exists(path_to_file):
            return
        if self.encrypted_upload:
            filesize = os.path.getsize(path_to_file) + TAGSIZE  # in bytes
        else:
            filesize = os.path.getsize(path_to_file)
        invalid_file = False
        msg = ''
        if os.path.isfile(path_to_file):
            stat = os.stat(path_to_file)
            if stat[6] == 0:
                invalid_file = True
                msg = _('File is empty')
        else:
            invalid_file = True
            msg = _('File does not exist')
        if invalid_file:
            ErrorDialog(_('Could not open file'), msg, transient_for=self.chat_control.parent_win.window)
            return

        mime_type = mimetypes.MimeTypes().guess_type(path_to_file)[0]
        if not mime_type:
            mime_type = 'application/octet-stream'  # fallback mime type
        log.info("Detected MIME Type of file: " + str(mime_type))
        progress_messages = Queue(8)
        progress_window = ProgressWindow(_('HTTP Upload'), _('Requesting HTTP Upload Slot...'), progress_messages, self.plugin)
        def upload_file(stanza):
            slot = stanza.getTag("slot")
            if not slot:
                progress_window.close_dialog()
                log.error("got unexpected stanza: "+str(stanza))
                error = stanza.getTag("error")
                if error and error.getTag("text"):
                    ErrorDialog(_('Could not request upload slot'), 
                                _('Got unexpected response from server: %s') % str(error.getTagData("text")),
                                transient_for=self.chat_control.parent_win.window)
                else:
                    ErrorDialog(_('Could not request upload slot'), 
                                _('Got unexpected response from server (protocol mismatch??)'),
                                transient_for=self.chat_control.parent_win.window)
                return

            try:
                if self.encrypted_upload:
                    key = os.urandom(32)
                    iv = os.urandom(16)
                    data = StreamFileWithProgress(path_to_file,
                                                  "rb",
                                                  progress_window.update_progress,
                                                  self.encrypted_upload, key, iv)
                else:
                    data = StreamFileWithProgress(path_to_file,
                                                  "rb",
                                                  progress_window.update_progress)
            except:
                progress_window.close_dialog()
                ErrorDialog(_('Could not open file'), 
                            _('Exception raised while opening file (see error log for more information)'),
                            transient_for=self.chat_control.parent_win.window)
                raise       # fill error log with useful information

            put = slot.getTag("put")
            get = slot.getTag("get")
            if not put or not get:
                progress_window.close_dialog()
                log.error("got unexpected stanza: " + str(stanza))
                ErrorDialog(_('Could not request upload slot'), 
                            _('Got unexpected response from server (protocol mismatch??)'),
                            transient_for=self.chat_control.parent_win.window)
                return

            def upload_complete(response_code):
                if response_code == 0:
                    return      # Upload was aborted
                if response_code >= 200 and response_code < 300:
                    log.info("Upload completed successfully")
                    xhtml = None
                    is_image = mime_type.split('/', 1)[0] == 'image'
                    if (not isinstance(self.chat_control, chat_control.ChatControl) or not self.chat_control.gpg_is_active) and \
                        self.dialog_type == 'image' and is_image and not self.encrypted_upload:

                        progress_messages.put(_('Calculating (possible) image thumbnail...'))
                        thumb = None
                        quality_steps = (100, 80, 60, 50, 40, 35, 30, 25, 23, 20, 18, 15, 13, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
                        with open(path_to_file, 'rb') as content_file:
                            thumb = urllib2.quote(base64.standard_b64encode(content_file.read()), '')
                        if thumb and len(thumb) < max_thumbnail_size:
                            quality = 100
                            log.info("Image small enough (%d bytes), not resampling" % len(thumb))
                        elif pil_available:
                            log.info("PIL available, using it for image downsampling")
                            try:
                                for quality in quality_steps:
                                    thumb = Image.open(path_to_file)
                                    thumb.thumbnail((max_thumbnail_dimension, max_thumbnail_dimension), Image.ANTIALIAS)
                                    output = BytesIO()
                                    thumb.save(output, format='JPEG', quality=quality, optimize=True)
                                    thumb = output.getvalue()
                                    output.close()
                                    thumb = urllib2.quote(base64.standard_b64encode(thumb), '')
                                    log.debug("pil thumbnail jpeg quality %d produces an image of size %d..." % (quality, len(thumb)))
                                    if len(thumb) < max_thumbnail_size:
                                        break
                            except:
                                thumb = None
                        else:
                            thumb = None
                        if not thumb:
                            log.info("PIL not available, using GTK for image downsampling")
                            temp_file = None
                            try:
                                with open(path_to_file, 'rb') as content_file:
                                    thumb = content_file.read()
                                loader = gtk.gdk.PixbufLoader()
                                loader.write(thumb)
                                loader.close()
                                pixbuf = loader.get_pixbuf()
                                scaled_pb = self.get_pixbuf_of_size(pixbuf, max_thumbnail_dimension)
                                handle, temp_file = tempfile.mkstemp(suffix='.jpeg', prefix='gajim_httpupload_scaled_tmp', dir=gajim.TMP)
                                log.debug("Saving temporary jpeg image to '%s'..." % temp_file)
                                os.close(handle)
                                for quality in quality_steps:
                                    scaled_pb.save(temp_file, "jpeg", {"quality": str(quality)})
                                    with open(temp_file, 'rb') as content_file:
                                        thumb = content_file.read()
                                    thumb = urllib2.quote(base64.standard_b64encode(thumb), '')
                                    log.debug("gtk thumbnail jpeg quality %d produces an image of size %d..." % (quality, len(thumb)))
                                    if len(thumb) < max_thumbnail_size:
                                        break
                            except:
                                thumb = None
                            finally:
                                if temp_file:
                                    os.unlink(temp_file)
                        if thumb:
                            if len(thumb) > max_thumbnail_size:
                                log.info("Couldn't compress image enough, not sending any thumbnail")
                            else:
                                log.info("Using thumbnail jpeg quality %d (image size: %d bytes)" % (quality, len(thumb)))
                                xhtml = '<body><br/><a href="%s"> <img alt="%s" src="data:image/png;base64,%s"/> </a></body>' % \
                                    (get.getData(), get.getData(), thumb)
                    progress_window.close_dialog()
                    id_ = gajim.get_an_id()
                    def add_oob_tag():
                        pass
                    if self.encrypted_upload:
                        keyAndIv = '#' + binascii.hexlify(iv) + binascii.hexlify(key)
                        self.chat_control.send_message(message=get.getData() + keyAndIv, xhtml=None)
                    else:
                        self.chat_control.send_message(message=get.getData(), xhtml=xhtml)
                    self.chat_control.msg_textview.grab_focus()
                else:
                    progress_window.close_dialog()
                    log.error("got unexpected http upload response code: " + str(response_code))
                    ErrorDialog(_('Could not upload file'),
                                _('Got unexpected http response code from server: ') + str(response_code),
                                transient_for=self.chat_control.parent_win.window)
            
            def uploader():
                progress_messages.put(_('Uploading file via HTTP...'))
                try:
                    headers = {'User-Agent': 'Gajim %s' % gajim.version,
                               'Content-Type': mime_type}
                    request = urllib2.Request(put.getData().encode("utf-8"), data=data, headers=headers)
                    request.get_method = lambda: 'PUT'
                    log.debug("opening urllib2 upload request...")
                    transfer = urllib2.urlopen(request, timeout=30)
                    log.debug("urllib2 upload request done, response code: " + str(transfer.getcode()))
                    return transfer.getcode()
                except UploadAbortedException:
                    log.info("Upload aborted")
                except:
                    progress_window.close_dialog()
                    ErrorDialog(_('Could not upload file'),
                                _('Got unexpected exception while uploading file (see error log for more information)'),
                                transient_for=self.chat_control.parent_win.window)
                    raise       # fill error log with useful information
                return 0

            log.info("Uploading file to '%s'..." % str(put.getData()))
            log.info("Please download from '%s' later..." % str(get.getData()))

            gajim.thread_interface(uploader, [], upload_complete)

        is_supported = gajim.get_jid_from_account(self.chat_control.account) in jid_to_servers and \
                    gajim.connections[self.chat_control.account].connection != None
        log.info("jid_to_servers of %s: %s ; connection: %s" % (gajim.get_jid_from_account(self.chat_control.account), str(jid_to_servers[gajim.get_jid_from_account(self.chat_control.account)]), str(gajim.connections[self.chat_control.account].connection)))
        if not is_supported:
            progress_window.close_dialog()
            log.error("upload component vanished, account got disconnected??")
            ErrorDialog(_('Your server does not support http uploads or you just got disconnected.\nPlease try to reconnect or reopen the chat window to fix this.'),
                transient_for=self.chat_control.parent_win.window)
            return

        # create iq for slot request
        id_ = gajim.get_an_id()
        iq = nbxmpp.Iq(
            typ='get',
            to=jid_to_servers[gajim.get_jid_from_account(self.chat_control.account)],
            queryNS=None
        )
        iq.setID(id_)
        request = iq.addChild(
            name="request",
            namespace=NS_HTTPUPLOAD
        )
        filename = request.addChild(
            name="filename",
        )
        filename.addData(os.path.basename(path_to_file))
        size = request.addChild(
            name="size",
        )
        size.addData(filesize)
        content_type = request.addChild(
            name="content-type",
        )
        content_type.addData(mime_type)

        # send slot request and register callback
        log.debug("sending httpupload slot request iq...")
        iq_ids_to_callbacks[str(id_)] = upload_file
        gajim.connections[self.chat_control.account].connection.send(iq)

        self.chat_control.msg_textview.grab_focus()