view frontends/src/jp/cmd_blog.py @ 1839:cdecf553e051

frontends (jp/blog), plugin blog_import: fixes: - argparse argument with nargs > 1 and default == {} crashes when reading the user input - separate blog import options with a new line - convert DBus strings received by the backend to unicode
author souliane <souliane@mailoo.org>
date Thu, 04 Feb 2016 11:44:43 +0100
parents 6209de5e3e25
children 9eabf7fadfdd
line wrap: on
line source

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

# jp: a SàT command line tool
# Copyright (C) 2009-2016 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/>.


import base
from sat.core.i18n import _
from sat.core.constants import Const as C
import json
URL_REDIRECT_PREFIX = 'url_redirect_'

__commands__ = ["Blog"]


class Import(base.CommandBase):
    def __init__(self, host):
        super(Import, self).__init__(host, 'import', use_progress=True, help=_(u'import an external blog'))

    def add_parser_options(self):
        self.parser.add_argument("importer", type=base.unicode_decoder, nargs='?', help=_(u"importer name, nothing to display importers list"))
        self.parser.add_argument('--host', type=base.unicode_decoder, help=_(u"original blog host"))
        self.parser.add_argument('--no-images-upload', action='store_true', help=_(u"do *NOT* upload images (default: do upload images)"))
        self.parser.add_argument('--upload-ignore-host', help=_(u"do not upload images from this host (default: upload all images)"))
        self.parser.add_argument("--ignore-tls-errors", action="store_true", help=_("ignore invalide TLS certificate for uploads"))
        self.parser.add_argument('-o', '--option', action='append', nargs=2, default=[], metavar=(u'NAME', u'VALUE'),
            help=_(u"importer specific options (see importer description)"))
        self.parser.add_argument('--service', type=base.unicode_decoder, default=u'', metavar=u'PUBSUB_SERVICE',
            help=_(u"PubSub service where the items must be uploaded (default: server)"))
        self.parser.add_argument("location", type=base.unicode_decoder, nargs='?',
            help=_(u"importer data location (see importer description), nothing to show importer description"))

    def onProgressStarted(self, metadata):
        self.disp(_(u'Blog upload started'),2)

    def onProgressFinished(self, metadata):
        self.disp(_(u'Blog uploaded successfully'),2)
        redirections = {k[len(URL_REDIRECT_PREFIX):]:v for k,v in metadata.iteritems()
            if k.startswith(URL_REDIRECT_PREFIX)}
        if redirections:
            conf = u'\n'.join([
                u'url_redirections_profile = {}'.format(self.profile),
                u"url_redirections_dict = {}".format(
                # we need to add ' ' before each new line and to double each '%' for ConfigParser
                u'\n '.join(json.dumps(redirections, indent=1, separators=(',',': ')).replace(u'%', u'%%').split(u'\n'))),
                ])
            self.disp(_(u'\nTo redirect old URLs to new ones, put the following lines in your sat.conf file, in [libervia] section:\n\n{conf}'.format(conf=conf)))

    def onProgressError(self, error_msg):
        self.disp(_(u'Error while uploading blog: {}').format(error_msg),error=True)

    def error(self, failure):
        self.disp(_("Error while trying to upload a blog: {reason}").format(reason=failure), error=True)
        self.host.quit(1)

    def connected(self):
        """Send files to jabber contact"""
        self.need_loop=True
        super(Import, self).connected()

        if self.args.location is None:
            for name in ('option', 'service', 'no_images_upload'):
                if getattr(self.args, name):
                    self.parser.error(_(u"{name} argument can't be used without location argument").format(name=name))
            if self.args.importer is None:
                print u'\n'.join([u'{}: {}'.format(name, desc) for name, desc in self.host.bridge.blogImportList()])
            else:
                try:
                    short_desc, long_desc = self.host.bridge.blogImportDesc(self.args.importer)
                except Exception as e:
                    msg = [l for l in unicode(e).split('\n') if l][-1] # we only keep the last line
                    print msg
                    self.host.quit(1)
                else:
                    print u"{name}: {short_desc}\n\n{long_desc}".format(name=self.args.importer, short_desc=short_desc, long_desc=long_desc)
            self.host.quit()
        else:
            # we have a location, an import is requested
            options = {key: value for key, value in self.args.option}
            if self.args.host:
                options['host'] = self.args.host
            if self.args.ignore_tls_errors:
                options['ignore_tls_errors'] = C.BOOL_TRUE
            if self.args.no_images_upload:
                options['upload_images'] = C.BOOL_FALSE
                if self.args.upload_ignore_host:
                    self.parser.error(u"upload-ignore-host option can't be used when no-images-upload is set")
            elif self.args.upload_ignore_host:
                options['upload_ignore_host'] = self.args.upload_ignore_host
            def gotId(id_):
                self.progress_id = id_
            self.host.bridge.blogImport(self.args.importer, self.args.location, options, self.args.service, self.profile,
                callback=gotId, errback=self.error)


class Blog(base.CommandBase):
    subcommands = (Import,)

    def __init__(self, host):
        super(Blog, self).__init__(host, 'blog', use_profile=False, help=_('blog/microblog management'))