예제 #1
0
파일: pubsub.py 프로젝트: xiayuming/gajim
    def send_pb_publish(self, jid, node, item, id_=None, options=None):
        """
        Publish item to a node
        """
        if not self.connection or self.connected < 2:
            return
        query = nbxmpp.Iq('set', to=jid)
        e = query.addChild('pubsub', namespace=nbxmpp.NS_PUBSUB)
        p = e.addChild('publish', {'node': node})
        attrs = {}
        if id_:
            attrs = {'id': id_}
        p.addChild('item', attrs, [item])
        if options:
            p = e.addChild('publish-options')
            p.addChild(node=options)

        self.connection.send(query)
예제 #2
0
 def IBBMessageHandler(self, conn, stanza):
     """
     Receive next portion of incoming datastream and store it write
     it to temporary file. Used internally.
     """
     sid = stanza.getTagAttr('data', 'sid')
     seq = stanza.getTagAttr('data', 'seq')
     data = stanza.getTagData('data')
     log.debug('ReceiveHandler called sid->%s seq->%s' % (sid, seq))
     try:
         seq = int(seq)
         data = base64.b64decode(data.encode('utf-8')).decode('utf-8')
     except Exception:
         seq = ''
         data = ''
     err = None
     file_props = FilesProp.getFilePropByTransportSid(self.name, sid)
     if file_props is None:
         err = nbxmpp.ERR_ITEM_NOT_FOUND
     else:
         if not data:
             err = nbxmpp.ERR_BAD_REQUEST
         elif seq != file_props.seq:
             err = nbxmpp.ERR_UNEXPECTED_REQUEST
         else:
             log.debug('Successfull receive sid->%s %s+%s bytes' % (sid,
                 file_props.fp.tell(), len(data)))
             file_props.seq += 1
             file_props.started = True
             file_props.fp.write(data)
             current_time = time.time()
             file_props.elapsed_time += current_time - file_props.last_time
             file_props.last_time = current_time
             file_props.received_len += len(data)
             gajim.socks5queue.progress_transfer_cb(self.name, file_props)
             if file_props.received_len >= file_props.size:
                 file_props.completed = True
     if err:
         log.debug('Error on receive: %s' % err)
         conn.send(nbxmpp.Error(nbxmpp.Iq(to=stanza.getFrom(),
             frm=stanza.getTo(),
             payload=[nbxmpp.Node(nbxmpp.NS_IBB + ' close')]), err, reply=0))
     else:
         return True
예제 #3
0
파일: mam.py 프로젝트: bj-h/gajim
    def _get_archive_query(self,
                           query_id,
                           jid=None,
                           start=None,
                           end=None,
                           with_=None,
                           after=None,
                           max_=70):
        # Muc archive query?
        namespace = muc_caps_cache.get_mam_namespace(jid)
        if namespace is None:
            # Query to our own archive
            namespace = self.archiving_namespace

        iq = nbxmpp.Iq('set', to=jid)
        query = iq.addChild('query', namespace=namespace)
        form = query.addChild(node=nbxmpp.DataForm(typ='submit'))
        field = nbxmpp.DataField(typ='hidden',
                                 name='FORM_TYPE',
                                 value=namespace)
        form.addChild(node=field)
        if start:
            field = nbxmpp.DataField(
                typ='text-single',
                name='start',
                value=start.strftime('%Y-%m-%dT%H:%M:%SZ'))
            form.addChild(node=field)
        if end:
            field = nbxmpp.DataField(typ='text-single',
                                     name='end',
                                     value=end.strftime('%Y-%m-%dT%H:%M:%SZ'))
            form.addChild(node=field)
        if with_:
            field = nbxmpp.DataField(typ='jid-single',
                                     name='with',
                                     value=with_)
            form.addChild(node=field)

        set_ = query.setTag('set', namespace=nbxmpp.NS_RSM)
        set_.setTagData('max', max_)
        if after:
            set_.setTagData('after', after)
        query.setAttr('queryid', query_id)
        return iq
예제 #4
0
    def _on_proxy_auth_ok(self, proxy):
        log.info('proxy auth ok for ' + str(proxy))
        # send activate request to proxy, send activated confirmation to peer
        if not self.connection:
            return
        sesn = self.connection.get_jingle_session(self.ourjid,
                                                  self.file_props.sid)
        if sesn is None:
            return

        iq = nbxmpp.Iq(to=proxy['jid'], frm=self.ourjid, typ='set')
        auth_id = "au_" + proxy['sid']
        iq.setID(auth_id)
        query = iq.setTag('query', namespace=nbxmpp.NS_BYTESTREAM)
        query.setAttr('sid', proxy['sid'])
        activate = query.setTag('activate')
        activate.setData(sesn.peerjid)
        iq.setID(auth_id)
        self.connection.connection.send(iq)

        content = nbxmpp.Node('content')
        content.setAttr('creator', 'initiator')
        content_object = self.get_content()
        content.setAttr('name', content_object.name)
        transport = nbxmpp.Node('transport')
        transport.setNamespace(nbxmpp.NS_JINGLE_BYTESTREAM)
        transport.setAttr('sid', proxy['sid'])
        activated = nbxmpp.Node('activated')
        cid = None

        if 'cid' in proxy:
            cid = proxy['cid']
        else:
            for host in self.candidates:
                if host['host'] == proxy['host'] and host['jid'] == proxy['jid'] \
                        and host['port'] == proxy['port']:
                    cid = host['candidate_id']
                    break
        if cid is None:
            raise Exception('cid is missing')
        activated.setAttr('cid', cid)
        transport.addChild(node=activated)
        content.addChild(node=transport)
        sesn.send_transport_info(content)
예제 #5
0
 def set_archive_preferences(self, items, default):
     if not app.account_is_connected(self.name):
         return
     iq = nbxmpp.Iq(typ='set')
     id_ = self.connection.getAnID()
     self.iq_answer.append(id_)
     iq.setID(id_)
     prefs = iq.addChild(name='prefs',
                         namespace=self.archiving_namespace,
                         attrs={'default': default})
     always = prefs.addChild(name='always')
     never = prefs.addChild(name='never')
     for item in items:
         jid, preference = item
         if preference == 'always':
             always.addChild(name='jid').setData(jid)
         else:
             never.addChild(name='jid').setData(jid)
     self.connection.send(iq)
예제 #6
0
 def remove_collection(self,
                       with_='',
                       start=None,
                       end=None,
                       exact_match=False,
                       open=False):
     iq_ = nbxmpp.Iq('set')
     remove = iq_.setTag('remove', namespace=nbxmpp.NS_ARCHIVE)
     if with_:
         remove.setAttr('with', with_)
         if exact_match:
             remove.setAttr('exactmatch', 'true')
     if start:
         remove.setAttr('start', start)
     if end:
         remove.setAttr('end', end)
     if open:
         remove.setAttr('open', 'true')
     self.connection.send(iq_)
예제 #7
0
    def send_cancel(self):
        """
        Send the command with action='cancel'
        """
        assert self.commandnode
        if self.sessionid and self.account.connection:
            # we already have sessionid, so the service sent at least one reply.
            stanza = nbxmpp.Iq(typ='set', to=self.jid)
            stanza.addChild('command', namespace=nbxmpp.NS_COMMANDS, attrs={
                            'node':self.commandnode,
                            'sessionid':self.sessionid,
                            'action':'cancel'
                    })

            self.account.connection.send(stanza)
        else:
            # we did not received any reply from service;
            # FIXME: we should wait and then send cancel; for now we do nothing
            pass
예제 #8
0
파일: pubsub.py 프로젝트: xiayuming/gajim
    def send_pb_delete(self, jid, node, on_ok=None, on_fail=None):
        """
        Delete node
        """
        if not self.connection or self.connected < 2:
            return
        query = nbxmpp.Iq('set', to=jid)
        d = query.addChild('pubsub', namespace=nbxmpp.NS_PUBSUB_OWNER)
        d = d.addChild('delete', {'node': node})

        def response(con, resp, jid, node):
            if resp.getType() == 'result' and on_ok:
                on_ok(jid, node)
            elif on_fail:
                msg = resp.getErrorMsg()
                on_fail(jid, node, msg)

        self.connection.SendAndCallForResponse(query, response, {'jid': jid,
            'node': node})
예제 #9
0
    def send_pb_create(self,
                       jid,
                       node,
                       cb,
                       configure=False,
                       configure_form=None):
        """
        Create a new node
        """
        if not app.account_is_connected(self._account):
            return
        query = nbxmpp.Iq('set', to=jid)
        c = query.addChild('pubsub', namespace=nbxmpp.NS_PUBSUB)
        c = c.addChild('create', {'node': node})
        if configure:
            conf = c.addChild('configure')
            if configure_form is not None:
                conf.addChild(node=configure_form)

        self._con.connection.SendAndCallForResponse(query, cb)
예제 #10
0
    def del_privacy_list(self, name):
        log.info('Remove list: %s', name)

        def _del_privacy_list_result(stanza):
            if not nbxmpp.isResultNode(stanza):
                log.warning('List deletion failed: %s', stanza.getError())
                app.nec.push_incoming_event(
                    InformationEvent(None,
                                     dialog_name='privacy-list-error',
                                     args=name))
            else:
                app.nec.push_incoming_event(
                    PrivacyListRemovedEvent(None,
                                            conn=self._con,
                                            list_name=name))

        node = nbxmpp.Node('list', {'name': name})
        iq = nbxmpp.Iq('set', nbxmpp.NS_PRIVACY, payload=[node])
        self._con.connection.SendAndCallForResponse(iq,
                                                    _del_privacy_list_result)
예제 #11
0
 def _build_request(self, file):
     iq = nbxmpp.Iq(typ='get', to=self.component)
     id_ = app.get_an_id()
     iq.setID(id_)
     if self.httpupload_namespace == NS_HTTPUPLOAD:
         # experimental namespace
         request = iq.setTag(name="request",
                             namespace=self.httpupload_namespace)
         request.addChild('filename', payload=os.path.basename(file.path))
         request.addChild('size', payload=file.size)
         request.addChild('content-type', payload=file.mime)
     else:
         attr = {
             'filename': os.path.basename(file.path),
             'size': file.size,
             'content-type': file.mime
         }
         iq.setTag(name="request",
                   namespace=self.httpupload_namespace,
                   attrs=attr)
     return iq
예제 #12
0
    def send_command(self, jid, node, session_id, form, action='execute'):
        """
        Send the command with data form. Wait for reply
        """
        log.info('Send Command: %s %s %s %s', jid, node, session_id, action)
        stanza = nbxmpp.Iq(typ='set', to=jid)
        cmdnode = stanza.addChild('command',
                                  namespace=nbxmpp.NS_COMMANDS,
                                  attrs={
                                      'node': node,
                                      'action': action
                                  })

        if session_id:
            cmdnode.setAttr('sessionid', session_id)

        if form:
            cmdnode.addChild(node=form.get_purged())

        self._con.connection.SendAndCallForResponse(
            stanza, self._action_response_received)
예제 #13
0
파일: pubsub.py 프로젝트: mdellweg/gajim
    def send_pb_retrieve(self,
                         jid,
                         node,
                         item_id=None,
                         cb=None,
                         *args,
                         **kwargs):
        """
        Get items from a node
        """
        if not self.connection or self.connected < 2:
            return
        query = nbxmpp.Iq('get', to=jid)
        r = query.addChild('pubsub', namespace=nbxmpp.NS_PUBSUB)
        r = r.addChild('items', {'node': node})
        if item_id is not None:
            r.addChild('item', {'id': item_id})
        id_ = self.connection.send(query)

        if cb:
            self.__callbacks[id_] = (cb, args, kwargs)
예제 #14
0
    def _send_socks5_info(self, file_props):
        """
        Send iq for the present streamhosts and proxies
        """
        if not self.connection or self.connected < 2:
            return
        receiver = file_props.receiver
        sender = file_props.sender

        sha_str = helpers.get_auth_sha(file_props.sid, sender, receiver)
        file_props.sha_str = sha_str

        port = gajim.config.get('file_transfers_port')
        listener = gajim.socks5queue.start_listener(port, sha_str,
                                                    self._result_socks5_sid,
                                                    file_props)
        if not listener:
            file_props.error = -5
            from common.connection_handlers_events import FileRequestErrorEvent
            gajim.nec.push_incoming_event(
                FileRequestErrorEvent(None,
                                      conn=self,
                                      jid=receiver,
                                      file_props=file_props,
                                      error_msg=''))
            self._connect_error(file_props.sid,
                                error='not-acceptable',
                                error_type='modify')
        else:
            iq = nbxmpp.Iq(to=receiver, typ='set')
            file_props.request_id = 'id_' + file_props.sid
            iq.setID(file_props.request_id)
            query = iq.setTag('query', namespace=nbxmpp.NS_BYTESTREAM)
            query.setAttr('sid', file_props.sid)

            self._add_addiditional_streamhosts_to_query(query, file_props)
            self._add_local_ips_as_streamhosts_to_query(query, file_props)
            self._add_proxy_streamhosts_to_query(query, file_props)
            self._add_upnp_igd_as_streamhost_to_query(query, file_props, iq)
예제 #15
0
    def subscribe(self, jid, msg=None, name='', groups=None, auto_auth=False):
        if not app.account_is_connected(self._account):
            return
        if groups is None:
            groups = []

        self._log.info('Request Subscription to %s', jid)

        if auto_auth:
            self.jids_for_auto_auth.append(jid)

        infos = {'jid': jid}
        if name:
            infos['name'] = name
        iq = nbxmpp.Iq('set', nbxmpp.NS_ROSTER)
        query = iq.setQuery()
        item = query.addChild('item', attrs=infos)
        for group in groups:
            item.addChild('group').setData(group)
        self._con.connection.send(iq)

        self.send_presence(jid, 'subscribe', status=msg)
예제 #16
0
    def _send_socks5_info(self, file_props):
        """
        Send iq for the present streamhosts and proxies
        """
        if not app.account_is_connected(self._account):
            return
        receiver = file_props.receiver
        sender = file_props.sender

        sha_str = helpers.get_auth_sha(file_props.sid, sender, receiver)
        file_props.sha_str = sha_str

        port = app.config.get('file_transfers_port')
        listener = app.socks5queue.start_listener(port, sha_str,
                                                  self._result_socks5_sid,
                                                  file_props)
        if not listener:
            file_props.error = -5
            app.nec.push_incoming_event(
                NetworkEvent('file-request-error',
                             conn=self._con,
                             jid=app.get_jid_without_resource(receiver),
                             file_props=file_props,
                             error_msg=''))
            self._connect_error(file_props.sid,
                                error='not-acceptable',
                                error_type='modify')
        else:
            iq = nbxmpp.Iq(to=receiver, typ='set')
            file_props.request_id = 'id_' + file_props.sid
            iq.setID(file_props.request_id)
            query = iq.setTag('query', namespace=nbxmpp.NS_BYTESTREAM)
            query.setAttr('sid', file_props.sid)

            self._add_addiditional_streamhosts_to_query(query, file_props)
            self._add_local_ips_as_streamhosts_to_query(query, file_props)
            self._add_proxy_streamhosts_to_query(query, file_props)
            self._add_upnp_igd_as_streamhost_to_query(query, file_props, iq)
예제 #17
0
    def _disco(self, namespace, jid, node, success_cb, error_cb):
        if success_cb is None:
            raise ValueError('success_cb is required')
        if not app.account_is_connected(self._account):
            return
        iq = nbxmpp.Iq(typ='get', to=jid, queryNS=namespace)
        if node:
            iq.setQuerynode(node)

        log_str = 'Request info: %s %s'
        if namespace == nbxmpp.NS_DISCO_ITEMS:
            log_str = 'Request items: %s %s'
        log.info(log_str, jid, node or '')

        # Create weak references so we can pass GUI object methods
        weak_success_cb = weakref.WeakMethod(success_cb)
        if error_cb is not None:
            weak_error_cb = weakref.WeakMethod(error_cb)
        else:
            weak_error_cb = None
        self._con.connection.SendAndCallForResponse(
            iq, self._disco_response, {'success_cb': weak_success_cb,
                                       'error_cb': weak_error_cb})
예제 #18
0
 def request_collection_page(self,
                             with_,
                             start,
                             end=None,
                             after=None,
                             max=30,
                             exact_match=False):
     iq_ = nbxmpp.Iq('get')
     retrieve = iq_.setTag('retrieve',
                           namespace=nbxmpp.NS_ARCHIVE,
                           attrs={
                               'with': with_,
                               'start': start
                           })
     if exact_match:
         retrieve.setAttr('exactmatch', 'true')
     set_ = retrieve.setTag('set', namespace=nbxmpp.NS_RSM)
     set_.setTagData('max', max)
     if after:
         set_.setTagData('after', after)
     id_ = self.connection.getAnID()
     iq_.setID(id_)
     self.awaiting_answers[id_] = (ARCHIVING_COLLECTION_ARRIVED, )
     self.connection.send(iq_)
예제 #19
0
 def request_search_fields(self, jid):
     log.info('Request search fields from %s', jid)
     iq = nbxmpp.Iq(typ='get', to=jid, queryNS=nbxmpp.NS_SEARCH)
     self._con.connection.SendAndCallForResponse(iq, self._fields_received)
예제 #20
0
파일: privacylists.py 프로젝트: bj-h/gajim
 def get_privacy_lists(self, callback=None):
     self._log.info('Request lists')
     iq = nbxmpp.Iq('get', nbxmpp.NS_PRIVACY)
     self._con.connection.SendAndCallForResponse(
         iq, self._privacy_lists_received, {'callback': callback})
예제 #21
0
파일: privacylists.py 프로젝트: bj-h/gajim
 def get_privacy_list(self, name):
     self._log.info('Request list: %s', name)
     list_ = nbxmpp.Node('list', {'name': name})
     iq = nbxmpp.Iq('get', nbxmpp.NS_PRIVACY, payload=[list_])
     self._con.connection.SendAndCallForResponse(
         iq, self._privacy_list_received)
예제 #22
0
파일: ping.py 프로젝트: shubham2110/gajim1
 def _get_ping_iq(to: str) -> nbxmpp.Iq:
     iq = nbxmpp.Iq('get', to=to)
     iq.addChild(name='ping', namespace=nbxmpp.NS_PING)
     return iq
예제 #23
0
파일: roster.py 프로젝트: bj-h/gajim
 def _ack_roster_push(self, stanza):
     iq = nbxmpp.Iq('result',
                    to=stanza.getFrom(),
                    frm=stanza.getTo(),
                    attrs={'id': stanza.getID()})
     self._con.connection.send(iq)
예제 #24
0
    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()
예제 #25
0
    def update_button_state(self, chat_control):
        global jid_to_servers
        global iq_ids_to_callbacks
        global last_info_query

        if gajim.connections[chat_control.account].connection == None and \
            gajim.get_jid_from_account(chat_control.account) in jid_to_servers:
            # maybe don't delete this and detect vanished upload components when actually trying to upload something
            log.info("Deleting %s from jid_to_servers (disconnected)" % gajim.get_jid_from_account(chat_control.account))
            del jid_to_servers[gajim.get_jid_from_account(chat_control.account)]
            #pass

        # query info at most every 60 seconds in case something goes wrong
        if (not chat_control.account in last_info_query or \
            last_info_query[chat_control.account] + 60 < time.time()) and \
            not gajim.get_jid_from_account(chat_control.account) in jid_to_servers and \
            gajim.account_is_connected(chat_control.account):
            log.info("Account %s: Using dicovery to find jid of httpupload component" % chat_control.account)
            id_ = gajim.get_an_id()
            iq = nbxmpp.Iq(
                typ='get',
                to=gajim.get_server_from_jid(gajim.get_jid_from_account(chat_control.account)),
                queryNS="http://jabber.org/protocol/disco#items"
            )
            iq.setID(id_)
            def query_info(stanza):
                global last_info_query
                for item in stanza.getTag("query").getTags("item"):
                    id_ = gajim.get_an_id()
                    iq = nbxmpp.Iq(
                        typ='get',
                        to=item.getAttr("jid"),
                        queryNS="http://jabber.org/protocol/disco#info"
                    )
                    iq.setID(id_)
                    last_info_query[chat_control.account] = time.time()
                    gajim.connections[chat_control.account].connection.send(iq)
            iq_ids_to_callbacks[str(id_)] = query_info
            gajim.connections[chat_control.account].connection.send(iq)
            #send disco query to main server jid
            id_ = gajim.get_an_id()
            iq = nbxmpp.Iq(
                typ='get',
                to=gajim.get_server_from_jid(gajim.get_jid_from_account(chat_control.account)),
                queryNS="http://jabber.org/protocol/disco#info"
            )
            iq.setID(id_)
            last_info_query[chat_control.account] = time.time()
            gajim.connections[chat_control.account].connection.send(iq)

        for base in self.controls:
            if base.chat_control == chat_control:
                is_supported = gajim.get_jid_from_account(chat_control.account) in jid_to_servers and \
                    gajim.connections[chat_control.account].connection != None
                log.info("Account %s: httpupload is_supported: %s" % (str(chat_control.account), str(is_supported)))
                if not is_supported:
                    text = _('Your server does not support http uploads')
                    image_text = text
                else:
                    text = _('Send file via http upload')
                    image_text = _('Send image via http upload')
                base.button.set_sensitive(is_supported)
                base.button.set_tooltip_text(text)
                base.image_button.set_sensitive(is_supported)
                base.image_button.set_tooltip_text(image_text)
예제 #26
0
 def request_mam_preferences(self):
     self._log.info('Request MAM preferences')
     iq = nbxmpp.Iq('get', self.archiving_namespace)
     iq.setQuery('prefs')
     self._con.connection.SendAndCallForResponse(iq,
                                                 self._preferences_received)
예제 #27
0
 def request_message_archiving_preferences(self):
     iq_ = nbxmpp.Iq('get')
     iq_.setTag('pref', namespace=nbxmpp.NS_ARCHIVE)
     self.connection.send(iq_)
예제 #28
0
 def print_special_text(self, special_text, other_tags, graphics, additional_data, iter_):
     self.textview.plugin_modified = True
     buffer_ = self.textview.tv.get_buffer()
     if not iter_:
         iter_ = buffer_.get_end_iter()
     if app.interface.sharp_slash_re.match(special_text):
         # insert post num #123456//
         tag = self.get_iter_and_tag('sharp_slash', buffer_)
         buffer_.insert_with_tags(iter_, special_text, tag)
         self.last_juick_num = special_text
         return
     if app.interface.juick_nick_re.match(special_text):
         # insert juick nick @nickname////
         tag = self.get_iter_and_tag('juick_nick', buffer_)
         mark = buffer_.create_mark(None, iter_, True)
         nick = special_text[1:].rstrip(':')
         buffer_.insert_with_tags(iter_, special_text, tag)
         # insert avatars
         if not self.plugin.config['SHOW_AVATARS']:
             return
         b_nick = buffer_.get_text(buffer_.get_start_iter(),
             buffer_.get_iter_at_mark(mark),False)
         if self.plugin.config['ONLY_AUTHOR_AVATAR'] and not \
         special_text.endswith(':') and b_nick[-9:] not in ('Subscribed to '
         ):
             return
         if self.plugin.config['ONLY_FIRST_AVATAR']:
             if b_nick[-9:] not in ('Reply by ', 'message from ', 'ended by ',
             'Subscribed to '):
                 if b_nick[-2] != app.config.get('after_nickname'):
                     return
                 elif b_nick[-1] == '\n':
                     return
         conn = app.connections[self.chat_control.account]
         if not conn.connected:
             return
         # search id in the db
         query = "select nick, id from person where nick = :nick"
         self.plugin.cursor.execute(query, {'nick':nick})
         db_item = self.plugin.cursor.fetchone()
         if db_item:
             # nick in the db
             pixbuf = self.get_avatar(db_item[1], nick, True)
             if not pixbuf:
                 return
             end_iter = buffer_.get_iter_at_mark(mark)
             anchor = buffer_.create_child_anchor(end_iter)
             img = TextViewImage(anchor, nick)
             img.set_from_pixbuf(pixbuf)
             img.show()
             self.textview.tv.add_child_at_anchor(img, anchor)
             return
         else:
             # nick not in the db
             id_ = conn.connection.getAnID()
             to = '*****@*****.**'
             iq = nbxmpp.Iq('get', to=to)
             a = iq.addChild(name='query',
                 namespace='http://juick.com/query#users')
             a.addChild(name='user', namespace='http://juick.com/user',
                 attrs={'uname': nick})
             iq.setID(id_)
             conn.connection.SendAndCallForResponse(iq, self._on_response,
                 {'mark': mark, 'special_text': special_text})
             return
     if app.interface.juick_pic_re.match(special_text) and \
         self.plugin.config['SHOW_PREVIEW']:
         # show pics preview
         tag = self.get_iter_and_tag('url', buffer_)
         mark = buffer_.create_mark(None, iter_, True)
         buffer_.insert_with_tags(iter_, special_text, tag)
         uid = special_text.split('/')[-1]
         url = "http://i.juick.com/photos-512/%s" % uid
         app.thread_interface(self.insert_pic_preview, [mark, special_text,
             url])
         return
     self.textview.plugin_modified = False
예제 #29
0
 def request_last_activity(self):
     if not app.account_is_connected(self.account):
         return
     con = app.connections[self.account]
     iq = nbxmpp.Iq(to=self.hostname, typ='get', queryNS=nbxmpp.NS_LAST)
     con.connection.SendAndCallForResponse(iq, self._on_last_activity)
예제 #30
0
 def remove_item(self, jid):
     iq_ = nbxmpp.Iq('set')
     itemremove = iq_.setTag('itemremove', namespace=nbxmpp.NS_ARCHIVE)
     item = itemremove.setTag('item')
     item.setAttr('jid', jid)
     self.connection.send(iq_)