view src/plugins/plugin_misc_file.py @ 1577:d04d7402b8e9

plugins XEP-0020, XEP-0065, XEP-0095, XEP-0096: fixed file copy with Stream Initiation: /!\ range is not working yet /!\ pipe plugin is broken for now
author Goffi <goffi@goffi.org>
date Wed, 11 Nov 2015 18:19:49 +0100
parents 833bdb227b16
children 846a39900fa6
line wrap: on
line source

#!/usr/bin/python
# -*- coding: utf-8 -*-

# SAT plugin for file tansfer
# Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Jérôme Poisson (goffi@goffi.org)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program 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 Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from sat.core.i18n import _, D_
from sat.core.constants import Const as C
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.tools import xml_tools
from twisted.internet import defer
import os
import uuid


PLUGIN_INFO = {
    "name": "File Tansfer",
    "import_name": "FILE",
    "type": C.PLUG_TYPE_MISC,
    "main": "FilePlugin",
    "handler": "no",
    "description": _("""File Tansfer Management:
This plugin manage the various ways of sending a file, and choose the best one.""")
}


CONFIRM = D_(u'{peer} wants to send the file "{name}" to you:\n{desc}\n\nThe file has a size of {size_human}\n\nDo you accept ?')
CONFIRM_TITLE = D_(u'Confirm file transfer')
CONFIRM_OVERWRITE = D_(u'File {} already exists, are you sure you want to overwrite ?')
CONFIRM_OVERWRITE_TITLE = D_(u'File exists')


class SatFile(object):
    """A file-like object to have high level files manipulation"""
    # TODO: manage "with" statement

    def __init__(self, host, path, mode='r', uid=None, size=None, profile=C.PROF_KEY_NONE):
        """
        @param host: %(doc_host)s
        @param path(str): path of the file to get
        @param mode(str): same as for built-in "open" function
        @param uid(unicode, None): unique id identifing this progressing element
            will be automaticaly generated if None
        @param size(None, int): size of the file
        """
        self.host = host
        self.uid = uid or unicode(uuid.uuid4())
        self._file = open(path, mode)
        self.size = None
        self.profile = profile
        self.eof = defer.Deferred()
        self.host.registerProgressCb(self.uid, self.getProgress, profile)
        self.host.bridge.progressStarted(self.uid, self.profile)
        self.eof.addCallback(lambda ignore: self.host.bridge.progressFinished(self.uid, self.profile))
        self.eof.addErrback(lambda failure: self.host.bridge.progressError(self.uid, unicode(failure), self.profile))

    def close(self):
        self._file.close()
        self.host.removeProgressCb(self.uid, self.profile)

    def flush(self):
        self._file.flush()

    def write(self, buf):
        self._file.write(buf)

    def read(self, size=-1):
        read = self._file.read(size)
        if not read:
            self.eof.callback(None)
        return read

    def seek(self, offset, whence=os.SEEK_SET):
        self._file.seek(offset, whence)

    def tell(self):
        return self._file.tell()

    def getProgress(self, progress_id, data, profile):
        return {'position': self._file.tell(), 'size': self.size or 0}


class FilePlugin(object):
    File=SatFile

    def __init__(self, host):
        log.info(_("plugin File initialization"))
        self.host = host

    # Dialogs with user
    # the overwrite check is done here

    def _openFileWrite(self, file_path, transfer_data, file_data, profile):
        assert 'file_obj' not in transfer_data
        transfer_data['file_obj'] = SatFile(
            self.host,
            file_path,
            'w',
            size=file_data['size'],
            profile=profile,
            )

    def _gotConfirmation(self, data, peer_jid, transfer_data, file_data, profile):
        """Called when the permission and dest path have been received

        @param peer_jid(jid.JID): jid of the file sender
        @param transfer_data(dict): same as for [self.getDestDir]
        @param file_data(dict): same as for [self.getDestDir]
        @param profile: %(doc_profile)s
        return (bool): True if copy is wanted and OK
            False if user wants to cancel
            if file exists ask confirmation and call again self._getDestDir if needed
        """
        if data.get('cancelled', False):
            return False
        path = data['path']
        file_data['file_path'] = file_path = os.path.join(path, file_data['name'])
        log.debug(u'destination file path set to {}'.format(file_path))

        # we manage case where file already exists
        if os.path.exists(file_path):
            def check_overwrite(overwrite):
                if overwrite:
                    self._openFileWrite(file_path, transfer_data, file_data, profile)
                    return True
                else:
                    return self.getDestDir(peer_jid, transfer_data, file_data, profile)

            exists_d = xml_tools.deferConfirm(
                self.host,
                _(CONFIRM_OVERWRITE).format(file_path),
                _(CONFIRM_OVERWRITE_TITLE),
                profile=profile)
            exists_d.addCallback(check_overwrite)
            return exists_d

        self._openFileWrite(file_path, transfer_data, file_data, profile)
        return True

    def getDestDir(self, peer_jid, transfer_data, file_data, profile):
        """Request confirmation and destination dir to user

        Overwrite confirmation is managed.
        if transfer is confirmed, 'file_obj' is added to transfer_data
        @param peer_jid(jid.JID): jid of the file sender
        @param filename(unicode): name of the file
        @param transfer_data(dict): data of the transfer session,
            it will be only used to store the file_obj.
            "file_obj" key *MUST NOT* exist before using getDestDir
        @param file_data(dict): information about the file to be transfered
            It MUST contain the following keys:
                - peer_jid (jid.JID): other peer jid
                - name (unicode): name of the file to trasnsfer
                    the name must not be empty or contain a "/" character
                - size (int): size of the file
            It may content the key used in CONFIRM constant
            It *MUST NOT* contain the "peer" key
            "file_path" will be added to this dict once destination selected
            "size_human" will also be added with human readable file size
        @param profile: %(doc_profile)s
        return (defer.Deferred): True if transfer is accepted
        """
        filename = file_data['name']
        assert filename and not '/' in filename
        # human readable size
        file_data['size_human'] = u'{:.6n} Mio'.format(float(file_data['size'])/(1024**2))
        d = xml_tools.deferDialog(self.host,
            _(CONFIRM).format(peer=peer_jid.full(), **file_data),
            _(CONFIRM_TITLE),
            type_=C.XMLUI_DIALOG_FILE,
            options={C.XMLUI_DATA_FILETYPE: C.XMLUI_DATA_FILETYPE_DIR},
            profile=profile)
        d.addCallback(self._gotConfirmation, peer_jid, transfer_data, file_data, profile)
        return d