Пример #1
0
    def convert(self, book, output_path):
        ret = super(MobiConverter, self).convert(book, output_path + '.epub')

        mobi_convert = config.get_configuration('MOBI_CONVERT')

        if mobi_convert == 'kindlegen':
            kindlegen_path = config.get_configuration('KINDLEGEN_PATH')
            command = [
                kindlegen_path, "-o", output_path.name, output_path + '.epub'
            ]
        elif mobi_convert == 'calibre':
            calibre_path = config.get_configuration('CALIBRE_PATH')
            calibre_args = config.get_configuration('CALIBRE_ARGS')

            command = [calibre_path, output_path + '.epub', output_path]
            if calibre_args != '':
                command += [calibre_args]

        rc, out, err = run_command(command)

        if rc not in [0, 1]:
            raise ConversionError("error running external command '{}'".format(
                command[0]))

        return {"size": os.path.getsize(output_path)}
Пример #2
0
    def initial_data(cls):
        lic = config.get_configuration('CREATE_BOOK_LICENSE')
        if lic and lic != '':
            try:
                license = License.objects.get(abbrevation=lic)
            except License.DoesNotExist:
                license = None
        else:
            license = None

        lang = config.get_configuration('CREATE_BOOK_LANGUAGE')
        if lang and lang != '':
            try:
                language = Language.objects.get(abbrevation=lang)
            except License.DoesNotExist:
                language = None
        else:
            language = None

        create_book_metadata = config.get_configuration(
            'CREATE_BOOK_METADATA', [])

        return {
            'create_book_visible':
            config.get_configuration('CREATE_BOOK_VISIBLE'),
            'create_book_license': license,
            'create_book_language': language,
            'create_book_metadata': create_book_metadata,
            'track_changes': config.get_configuration('BOOK_TRACK_CHANGES')
        }
Пример #3
0
    def get_context_data(self, **kwargs):
        context = super(FrontPageView, self).get_context_data(**kwargs)

        if config.get_configuration('BOOKTYPE_FRONTPAGE_USE_ANONYMOUS_PAGE') and self.request.user.is_anonymous():
            self.template_name = "portal/anonymous_frontpage.html"
            context['anonymous_message'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_MESSAGE')
            context['anonymous_email'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_EMAIL')
            context['anonymous_image'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_IMAGE')
            return context

        context['is_admin'] = self.request.user.is_superuser
        # get all user permissions
        role_key = security.get_default_role_key(self.request.user)
        default_role = security.get_default_role(role_key)
        if default_role:
            context['roles_permissions'] = [p.key_name for p in default_role.permissions.all()]
        else:
            context['roles_permissions'] = []

        b_query = Book.objects.all()

        if not self.request.user.is_superuser:
            if self.request.user.is_authenticated():
                b_query = b_query.filter(Q(hidden=False) | Q(owner=self.request.user))
            else:
                b_query = b_query.filter(hidden=False)

        context['books_list'] = b_query.order_by('-created')[:10]
        context['user_list'] = User.objects.filter(is_active=True).order_by('-date_joined')[:12]
        booki_group5 = BookiGroup.objects.all().order_by('-created')[:6]

        context['group_list'] = [{
            'url_name': g.url_name,
            'name': g.name,
            'description': g.description,
            'num_members': g.members.count(),
            'num_books': g.book_set.count(),
            'small_group_image': g.get_group_image
            } for g in booki_group5]

        context['recent_activities'] = BookHistory.objects.filter(kind__in=[1, 10], book__hidden=False).order_by('-modified')[:5]

        if self.request.user.is_authenticated():
            context['is_book_limit'] = Book.objects.filter(owner=self.request.user).count() >= config.get_configuration('BOOKTYPE_BOOKS_PER_USER') != -1
        else:
            context['is_book_limit'] = True

        if self.request.user.is_superuser:
            context['can_create_book'] = True
            context['is_book_limit'] = False
        # if only admin create then deny user permission to create new books
        elif config.get_configuration('ADMIN_CREATE_BOOKS'):
            context['can_create_book'] = False
        # check if user can create more books
        elif context['is_book_limit']:
            context['can_create_book'] = False
        else:
            context['can_create_book'] = True

        return context
Пример #4
0
    def get_context_data(self, **kwargs):
        context = super(FrontPageView, self).get_context_data(**kwargs)

        if config.get_configuration('BOOKTYPE_FRONTPAGE_USE_ANONYMOUS_PAGE') and self.request.user.is_anonymous():
            self.template_name = "portal/anonymous_frontpage.html"
            context['anonymous_message'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_MESSAGE')
            context['anonymous_email'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_EMAIL')
            context['anonymous_image'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_IMAGE')
            return context

        context['is_admin'] = self.request.user.is_superuser
        # get all user permissions
        role_key = security.get_default_role_key(self.request.user)
        default_role = security.get_default_role(role_key)
        if default_role:
            context['roles_permissions'] = [p.key_name for p in default_role.permissions.all()]
        else:
            context['roles_permissions'] = []

        b_query = Book.objects.all()

        if not self.request.user.is_superuser:
            if self.request.user.is_authenticated():
                b_query = b_query.filter(Q(hidden=False) | Q(owner=self.request.user))
            else:
                b_query = b_query.filter(hidden=False)

        context['books_list'] = b_query.order_by('-created')[:4]
        context['user_list'] = User.objects.filter(is_active=True).order_by('-date_joined')[:2]
        booki_group5 = BookiGroup.objects.all().order_by('-created')[:5]

        context['group_list'] = [{
            'url_name': g.url_name,
            'name': g.name,
            'description': g.description,
            'num_members': g.members.count(),
            'num_books': g.book_set.count(),
            'small_group_image': g.get_group_image
            } for g in booki_group5]

        context['recent_activities'] = BookHistory.objects.filter(kind__in=[1, 10], book__hidden=False).order_by('-modified')[:5]

        if self.request.user.is_authenticated():
            context['is_book_limit'] = Book.objects.filter(owner=self.request.user).count() >= config.get_configuration('BOOKTYPE_BOOKS_PER_USER') != -1
        else:
            context['is_book_limit'] = True

        if self.request.user.is_superuser:
            context['can_create_book'] = True
            context['is_book_limit'] = False
        # if only admin create then deny user permission to create new books
        elif config.get_configuration('ADMIN_CREATE_BOOKS'):
            context['can_create_book'] = False
        # check if user can create more books
        elif context['is_book_limit']:
            context['can_create_book'] = False
        else:
            context['can_create_book'] = True

        return context
Пример #5
0
 def initial_data(cls):
     return {
         'book_css': config.get_configuration('BOOKTYPE_CSS_BOOK', ''),
         'ebook_css': config.get_configuration('BOOKTYPE_CSS_EBOOK', ''),
         'pdf_css': config.get_configuration('BOOKTYPE_CSS_PDF', ''),
         'odt_css': config.get_configuration('BOOKTYPE_CSS_ODT', '')
     }
Пример #6
0
    def initial_data(cls):
        lic = config.get_configuration('CREATE_BOOK_LICENSE')
        if lic and lic != '':
            try:
                license = License.objects.get(abbrevation=lic)
            except License.DoesNotExist:
                license = None
        else:
            license = None

        lang = config.get_configuration('CREATE_BOOK_LANGUAGE')
        if lang and lang != '':
            try:
                language = Language.objects.get(abbrevation=lang)
            except License.DoesNotExist:
                language = None
        else:
            language = None

        create_book_metadata = config.get_configuration('CREATE_BOOK_METADATA', [])

        return {
            'create_book_visible': config.get_configuration('CREATE_BOOK_VISIBLE'),
            'create_book_license': license,
            'create_book_language': language,
            'create_book_metadata': create_book_metadata,
            'track_changes': config.get_configuration('BOOK_TRACK_CHANGES')
        }
Пример #7
0
 def initial_data(cls):
     return {
         'book_css': config.get_configuration('BOOKTYPE_CSS_BOOK', ''),
         'ebook_css': config.get_configuration('BOOKTYPE_CSS_EBOOK', ''),
         'pdf_css': config.get_configuration('BOOKTYPE_CSS_PDF', ''),
         'odt_css': config.get_configuration('BOOKTYPE_CSS_ODT', '')
     }
Пример #8
0
    def handle(self, *args, **options):
        if not hasattr(settings, 'BOOKTYPE_CONFIG'):
            raise CommandError('Does not have BOOKTYPE_CONFIG in settings.py file.')

        if len(args) != 2:
            raise CommandError("You must specify variable name and value.")

        key = args[0]
        value = args[1]

        if options['integer']:
            try:
                value = int(value)
            except ValueError:
                raise CommandError("I don't think this %s is a number!" % value)

        if options['float']:
            try:
                value = float(value)
            except ValueError:
                raise CommandError("I don't think this %s is a number!" % value)
                

        if options['as_json']:
            try:
                value = json.loads(value)
            except ValueError:
                raise CommandError("Not a valid JSON string.")

        if options['append']:
            # ovo neshto ne radi sa as_jsonom
            lst = config.get_configuration(key, [])

            if type(lst) == type([]):
                lst.append(value)
                config.set_configuration(key, lst)
            else:
                raise CommandError("Can not append to something that is not a list")
        elif options['remove']:
            lst = config.get_configuration(key, [])

            if type(lst) == type([]):
                try:
                    lst.remove(value)
                except ValueError:
                    raise CommandError("I can't see it!")

                config.set_configuration(key, lst)
            else:
                raise CommandError("Can not append to something that is not a list")
        else:
            config.set_configuration(key, value)
            
        try:
            config.save_configuration()
        except config.ConfigurationError:
            raise CommandError("Could not save the file.")
Пример #9
0
 def initial_data(cls):
     return {
         cls.anonymous:
         config.get_configuration('DEFAULT_ROLE_%s' % cls.anonymous,
                                  cls.anonymous),
         cls.registered:
         config.get_configuration('DEFAULT_ROLE_%s' % cls.registered,
                                  cls.registered)
     }
Пример #10
0
    def handle(self, *args, **options):
        if not hasattr(settings, 'BOOKTYPE_CONFIG'):
            raise CommandError('Does not have BOOKTYPE_CONFIG in settings.py file.')

        if len(options['<name> <value>']) != 2:
            raise CommandError("You must specify variable name and value.")

        key = options['<name> <value>'][0]
        value = options['<name> <value>'][1]

        if options['integer']:
            try:
                value = int(value)
            except ValueError:
                raise CommandError("I don't think this %s is a number!" % value)

        if options['float']:
            try:
                value = float(value)
            except ValueError:
                raise CommandError("I don't think this %s is a number!" % value)

        if options['as_json']:
            try:
                value = json.loads(value)
            except ValueError:
                raise CommandError("Not a valid JSON string.")

        if options['append']:
            # ovo neshto ne radi sa as_jsonom
            lst = config.get_configuration(key, [])

            if type(lst) == type([]):
                lst.append(value)
                config.set_configuration(key, lst)
            else:
                raise CommandError("Can not append to something that is not a list")
        elif options['remove']:
            lst = config.get_configuration(key, [])

            if type(lst) == type([]):
                try:
                    lst.remove(value)
                except ValueError:
                    raise CommandError("I can't see it!")

                config.set_configuration(key, lst)
            else:
                raise CommandError("Can not append to something that is not a list")
        else:
            config.set_configuration(key, value)

        try:
            config.save_configuration()
        except config.ConfigurationError:
            raise CommandError("Could not save the file.")
Пример #11
0
    def get_context_data(self, **kwargs):
        context = super(TemplateView, self).get_context_data(**kwargs)

        try:
            book = models.Book.objects.get(url_title__iexact=kwargs['bookid'])
        except models.Book.DoesNotExist:
            return {'book': None, 'book_id': kwargs['bookid']}

        book_version = book.get_version(None)

        toc = get_toc_for_book(book_version)

        context['request'] = self.request
        context['book'] = book
        context['book_version'] = book_version.get_version()
        context[
            'book_language'] = book.language.abbrevation if book.language else 'en'
        context['security'] = self.security

        try:
            rtl = models.Info.objects.get(book=book,
                                          kind=0,
                                          name='{http://booki.cc/}dir')
            context['book_dir'] = rtl.get_value().lower()
        except models.Info.DoesNotExist:
            context['book_dir'] = 'ltr'

        context['chapters'] = toc

        # check if we should track changes for current user
        user_permissions = get_user_permissions(self.request.user, book)
        context['track_changes_approve'] = self.security.has_perm(
            'edit.track_changes_approve')
        context['track_changes_enable'] = self.security.has_perm(
            'edit.track_changes_enable')

        should_track_changes = 'edit.track_changes' in user_permissions

        context['track_changes'] = json.dumps(book_version.track_changes
                                              or should_track_changes)
        context['base_url'] = settings.BOOKTYPE_URL
        context['static_url'] = settings.STATIC_URL
        context['is_admin'] = self.security.is_admin()
        context['is_owner'] = book.owner == self.request.user
        context['publish_options'] = config.get_configuration(
            'PUBLISH_OPTIONS')

        context['autosave'] = json.dumps({
            'enabled':
            config.get_configuration('EDITOR_AUTOSAVE_ENABLED'),
            'delay':
            config.get_configuration('EDITOR_AUTOSAVE_DELAY')
        })
        context['upload_docx_form'] = UploadDocxFileForm()

        return context
Пример #12
0
    def check_permissions(self, request, *args, **kwargs):
        if self.request.user.is_superuser:
            return

        # if only admin create then deny user permission to create new books
        if config.get_configuration('ADMIN_CREATE_BOOKS'):
            raise PermissionDenied

        # check if user can create more books
        if Book.objects.filter(owner=self.request.user).count() >= config.get_configuration('BOOKTYPE_BOOKS_PER_USER') != -1:
            raise PermissionDenied
Пример #13
0
    def check_permissions(self, request, *args, **kwargs):
        if self.request.user.is_superuser:
            return

        # if only admin create then deny user permission to create new books
        if config.get_configuration('ADMIN_CREATE_BOOKS'):
            raise PermissionDenied

        # check if user can create more books
        if Book.objects.filter(owner=self.request.user).count() >= config.get_configuration('BOOKTYPE_BOOKS_PER_USER') != -1:
            raise PermissionDenied
Пример #14
0
def booktype_site_name():
    name = config.get_configuration('BOOKTYPE_SITE_NAME', None)
    default_url = '{0}{1}'.format(settings.BOOKTYPE_URL, reverse('portal:frontpage'))
    frontpage_url = config.get_configuration('BOOKTYPE_FRONTPAGE_URL', default_url)

    if name:
        markup = '<div class="logotext"><a href="%s">%s</a></div>' % (frontpage_url, name)
    else:
        markup = '<div class="logo"><a href="%s"></a></div>' % (frontpage_url)

    return mark_safe(markup)
Пример #15
0
 def initial_data(cls):
     return {
         cls.anonymous: config.get_configuration(
             'DEFAULT_ROLE_%s' % cls.anonymous,
             cls.anonymous
         ),
         cls.registered: config.get_configuration(
             'DEFAULT_ROLE_%s' % cls.registered,
             cls.registered
         )
     }
Пример #16
0
def booktype_site_name():
    name = config.get_configuration('BOOKTYPE_SITE_NAME', None)
    default_url = '{0}{1}'.format(settings.BOOKTYPE_URL, reverse('portal:frontpage'))
    frontpage_url = config.get_configuration('BOOKTYPE_FRONTPAGE_URL', default_url)

    if name:
        markup = '<div class="logotext"><a href="%s">%s</a></div>' % (frontpage_url, name)
    else:
        markup = '<div class="logo"><a href="%s"></a></div>' % (frontpage_url)

    return mark_safe(markup)
Пример #17
0
def booktype_site_metadata():
    """Simple tag to load sitename and tagline from custom configuration"""

    meta_tags = ''

    name = config.get_configuration('BOOKTYPE_SITE_NAME', None)
    if name:
        meta_tags += '<meta property="og:site_name" content="%s" />' % escape(name)

    tagline = config.get_configuration('BOOKTYPE_SITE_TAGLINE', None)
    if tagline:
        meta_tags += '\n<meta name="description" content="%s" />' % escape(tagline)

    return meta_tags
Пример #18
0
def booktype_site_metadata():
    """Simple tag to load sitename and tagline from custom configuration"""

    meta_tags = ''

    name = config.get_configuration('BOOKTYPE_SITE_NAME', None)
    if name:
        meta_tags += '<meta property="og:site_name" content="%s" />' % escape(name)

    tagline = config.get_configuration('BOOKTYPE_SITE_TAGLINE', None)
    if tagline:
        meta_tags += '\n<meta name="description" content="%s" />' % escape(tagline)

    return mark_safe(meta_tags)
Пример #19
0
    def html_before_write(self, book, chapter):
        if chapter.get_type() != ebooklib.ITEM_DOCUMENT or isinstance(
                chapter, ebooklib.epub.EpubNav):
            return True

        tags_allowed_to_be_empty = config.get_configuration(
            'ALLOWED_EMPTY_TAGS')
        tags_to_remove_on_cleanup = config.get_configuration(
            'TAGS_TO_REMOVE_ON_CLEANUP')
        attrs_to_remove_on_cleanup = config.get_configuration(
            'ATTRS_TO_REMOVE_ON_CLEANUP')
        allowed_empty_by_classes = config.get_configuration(
            'ALLOWED_EMPTY_BY_CLASSES')

        root = parse_html_string(chapter.get_content())

        # let's remove all the tags we don't want to have on export
        # this will affect all the converters since they use the generated
        # epub as base for converting process
        for tag in tags_to_remove_on_cleanup:
            for node in root.iter(tag):
                node.drop_tree()

        # walk over all elements in the tree and remove all
        # nodes that are recursively empty
        body = root.find('body')

        for elem in body.xpath("//body//*"):
            # remove not wanted attributes
            for attr in attrs_to_remove_on_cleanup:
                if attr in elem.attrib:
                    del elem.attrib[attr]

            klasses = elem.get('class', '').split()
            allowed_by_class = any(
                [x in allowed_empty_by_classes for x in klasses])

            if recursively_empty(
                    elem
            ) and elem.tag not in tags_allowed_to_be_empty and not allowed_by_class:
                # just in case if text contains spaces or tabs, because drop_tag removes only tag
                elem.text = ''
                elem.drop_tag()

        chapter.content = etree.tostring(root,
                                         pretty_print=True,
                                         encoding="utf-8",
                                         xml_declaration=True)

        return True
Пример #20
0
    def check_permissions(self, request, *args, **kwargs):
        if self.request.user.is_superuser:
            return

        if not self.security.has_perm('account.can_upload_book'):
            raise PermissionDenied

        # if only admin import then deny user permission to upload books
        if config.get_configuration('ADMIN_IMPORT_BOOKS'):
            raise PermissionDenied

        # check if user can import more books
        if Book.objects.filter(owner=self.request.user).count() >= config.get_configuration('BOOKTYPE_BOOKS_PER_USER') != -1:
            raise PermissionDenied
Пример #21
0
    def check_permissions(self, request, *args, **kwargs):
        if self.request.user.is_superuser:
            return

        if not self.security.has_perm('account.can_upload_book'):
            raise PermissionDenied

        # if only admin import then deny user permission to upload books
        if config.get_configuration('ADMIN_IMPORT_BOOKS'):
            raise PermissionDenied

        # check if user can import more books
        if Book.objects.filter(owner=self.request.user).count(
        ) >= config.get_configuration('BOOKTYPE_BOOKS_PER_USER') != -1:
            raise PermissionDenied
Пример #22
0
    def initial_data(cls):
        _l = config.get_configuration('CREATE_BOOK_LICENSE')
        if _l and _l != '':
            try:
                license = License.objects.get(abbrevation=_l)
            except License.DoesNotExist:
                license = None
        else:
            license = None

        return {
            'visible': config.get_configuration('CREATE_BOOK_VISIBLE'),
            'license': license,
            'track_changes': config.get_configuration('BOOK_TRACK_CHANGES')
        }
Пример #23
0
def google_analytics(context):
    """
    Add google analytics async tracking code.
    Usage: {% google_analytics %}

    :Returns:
      Returns rendered java script code's block
    """
    data = {'USE_GOOGLE_ANALYTICS': config.get_configuration('USE_GOOGLE_ANALYTICS'),
            'GOOGLE_ANALYTICS_ID': config.get_configuration('GOOGLE_ANALYTICS_ID')}

    if context['request'].user.is_superuser:
        data['USE_GOOGLE_ANALYTICS'] = False

    return data
Пример #24
0
def google_analytics(context):
    """
    Add google analytics async tracking code.
    Usage: {% google_analytics %}

    :Returns:
      Returns rendered java script code's block
    """
    data = {'USE_GOOGLE_ANALYTICS': config.get_configuration('USE_GOOGLE_ANALYTICS'),
            'GOOGLE_ANALYTICS_ID': config.get_configuration('GOOGLE_ANALYTICS_ID')}

    if context['request'].user.is_superuser:
        data['USE_GOOGLE_ANALYTICS'] = False

    return data
Пример #25
0
    def initial_data(cls):
        _l = config.get_configuration('CREATE_BOOK_LICENSE')
        if _l and _l != '':
            try:
                license = License.objects.get(abbrevation=_l)
            except License.DoesNotExist:
                license = None
        else:
            license = None

        return {
            'visible': config.get_configuration('CREATE_BOOK_VISIBLE'),
            'license': license,
            'track_changes': config.get_configuration('BOOK_TRACK_CHANGES')
        }
Пример #26
0
    def get_plugins(self):
        """
        Retrieves plugins that are going to be used in write process.

        Returns:
            List with instances of plugins to be used
        """

        write_plugins = self.DEFAULT_PLUGINS

        # comments reference bubble should be removed by default for now
        # TODO: we should implement a way to attach the comments to the raw epub file
        if self._remove_comments:
            write_plugins.insert(0, CommentsCleanPlugin())

        # ICEjs changes are removed by default, so to keep them in the epub
        # we need to pass remove_icejs as False in kwargs
        if self._remove_icejs:
            write_plugins.append(IceCleanPlugin())

        # let's add cleanup if enabled
        if config.get_configuration('ENABLE_CONTENT_CLEANUP_ON_EXPORT', False):
            write_plugins.append(ContentCleanUpPlugin())

        # add extra plugins
        write_plugins += self.kwargs.get('extra_plugins', [])

        return write_plugins
Пример #27
0
def download(src_url, dst_file):
    req = requests.get(src_url, stream=True, verify=config.get_configuration('REQUESTS_VERIFY_SSL_CERT'))

    if req.status_code == 200:
        with open(dst_file, 'wb') as dst:
            for chunk in req:
                dst.write(chunk)
Пример #28
0
def load_theme_plugin(convert_type, theme_name):
    """Load theme plugin for certain conversion and theme. Returns reference
    to plugin theme which has to be initialised later on.

    :Args:
      - convert_type: Type of conversion (mpdf, screenpdf, epub, ...)
      - theme_name: Theme name

    :Returns:
      Returns reference to plugin class which has to be initialised.
    """

    plgn = None

    plugins = config.get_configuration("BOOKTYPE_THEME_PLUGINS")

    try:
        module_name = plugins.get(theme_name, None)

        if module_name:
            module = importlib.import_module(module_name)
            plgn = module.__convert__.get(convert_type, None)
            return plgn
    except:
        logger.exception("Can not load the theme plugin.")

    return plgn
Пример #29
0
    def is_header(self, elem, font_size, node, style=None):
        """
        Used for checking if specific element is a header or not.

        :Returns:
          True or False
        """

        HEADING_STYLES = config.get_configuration('DOCX_HEADING_STYLES', [])

        # Check the defined list of styles
        if style:
            if style.style_id.lower() in HEADING_STYLES:
                return True

        if elem.rpr.get('style', None):
            for style_key in HEADING_STYLES:
                if elem.rpr.get('style').lower().replace(
                        '-', '').startswith(style_key):
                    return True

        for e in elem.elements:
            if hasattr(e, 'rpr'):
                if e.rpr.get('style', None):
                    for style_key in HEADING_STYLES:

                        if e.rpr.get('style').lower().replace(
                                '-', '').startswith(style_key):
                            return True

        return super(DocHeaderContext, self).is_header(elem, font_size, node,
                                                       style)
Пример #30
0
def get_default_role(key, book=None):
    """
    Returns default role if exists one already registered
    in system database, otherwise returns None
    """

    default_role = None
    default_key = 'DEFAULT_ROLE_%s' % key
    role_name = None

    if book:
        try:
            role_name = book.settings.get(name=default_key).get_value()
        except:
            logger.info("There is no Role name for role_key %s" % default_key)

    if not role_name:
        role_name = config.get_configuration(
            default_key, key)

    # no_role means restricted
    if role_name == '__no_role__':
        return None

    try:
        default_role = Role.objects.get(name=role_name)
    except:
        logger.info("Role with %s name does not exists" % role_name)

    return default_role
Пример #31
0
    def get_header(self, elem, style, node):
        """
        Returns HTML tag representing specific header for this element.

        :Returns:
          String representation of HTML tag.
        """

        STYLES_TUPLE = config.get_configuration('DOCX_HEADING_STYLES_TUPLE')

        if style and not isinstance(style, int):
            for header_id, header_values in STYLES_TUPLE:
                if style.style_id.lower().replace('-', '') in header_values:
                    return header_id

        if elem.rpr.get('style', None):
            for header_id, header_values in STYLES_TUPLE:
                for style_key in header_values:
                    if elem.rpr.get('style').lower().replace(
                            '-', '').startswith(style_key):
                        return header_id

        for e in elem.elements:
            if hasattr(e, 'rpr'):
                if e.rpr.get('style', None):
                    for header_id, header_values in STYLES_TUPLE:
                        for style_key in header_values:
                            if e.rpr.get('style').lower().replace(
                                    '-', '').startswith(style_key):
                                return header_id

        return super(DocHeaderContext, self).get_header(elem, style, node)
Пример #32
0
def load_theme_plugin(convert_type, theme_name):
    """Load theme plugin for certain conversion and theme. Returns reference
    to plugin theme which has to be initialised later on.

    :Args:
      - convert_type: Type of conversion (mpdf, screenpdf, epub, ...)
      - theme_name: Theme name

    :Returns:
      Returns reference to plugin class which has to be initialised.
    """

    plgn = None

    plugins = config.get_configuration('BOOKTYPE_THEME_PLUGINS')

    try:
        module_name = plugins.get(theme_name, None)

        if module_name:
            module = importlib.import_module(module_name)
            plgn = module.__convert__.get(convert_type, None)
            return plgn
    except:
        logger.exception('Can not load the theme plugin.')

    return plgn
Пример #33
0
    def __init__(self, base_book_qs=None, *args, **kwargs):
        super(BookCreationForm, self).__init__(*args, **kwargs)

        # time to build metadata fields
        self.metadata_fields = config.get_configuration('CREATE_BOOK_METADATA', [])

        # TODO: extract this to a separate method to use it also in booktype.apps.edit.forms.MetadataForm
        for field, label, standard in METADATA_FIELDS:
            field_name = '%s.%s' % (standard, field)
            if field_name not in self.metadata_fields:
                continue

            self.fields[field_name] = forms.CharField(
                label=label, required=False)

            c_field = self.fields[field_name]
            BaseBooktypeForm.apply_class(c_field, 'form-control')

            # apply widgets if needed
            if field in self.Meta.widgets:
                c_field.widget = self.Meta.widgets[field]

        if base_book_qs is not None:
            self.fields['base_book'].queryset = base_book_qs
        else:
            logger.warn("base_book_qs queryset parameter was not provided. Using empty queryset")
Пример #34
0
    def get_plugins(self):
        """
        Retrieves plugins that are going to be used in write process.

        Returns:
            List with instances of plugins to be used
        """

        write_plugins = self.DEFAULT_PLUGINS

        # comments reference bubble should be removed by default for now
        # TODO: we should implement a way to attach the comments to the raw epub file
        if self._remove_comments:
            write_plugins.insert(0, CommentsCleanPlugin())

        # ICEjs changes are removed by default, so to keep them in the epub
        # we need to pass remove_icejs as False in kwargs
        if self._remove_icejs:
            write_plugins.append(IceCleanPlugin())

        # let's add cleanup if enabled
        if config.get_configuration('ENABLE_CONTENT_CLEANUP_ON_EXPORT', False):
            write_plugins.append(ContentCleanUpPlugin())

        # add extra plugins
        write_plugins += self.kwargs.get('extra_plugins', [])

        return write_plugins
Пример #35
0
    def get_context_data(self, **kwargs):
        context = super(PeoplePageView, self).get_context_data(**kwargs)

        user_list_qs = User.objects.filter(is_active=True).extra(
            select={
                'lower_username': '******'
            }).order_by('lower_username')

        paginator = Paginator(user_list_qs,
                              config.get_configuration('USER_LIST_PAGE_SIZE'))

        try:
            context['all_people'] = paginator.page(
                self.request.GET.get('page'))
        except PageNotAnInteger:
            context['all_people'] = paginator.page(1)
        except EmptyPage:
            context['all_people'] = paginator.page(paginator.num_pages)

        now = datetime.datetime.now() - datetime.timedelta(30)
        context['active_people'] = [
            User.objects.get(id=b['user']) for b in BookHistory.objects.filter(
                modified__gte=now, user__is_active=True).values('user').
            annotate(models.Count('user')).order_by("-user__count")[:4]
        ]

        context['new_people'] = User.objects.filter(
            is_active=True).order_by('-date_joined')[:4]

        return context
Пример #36
0
def get_page_size(conf):
    """Returns page number in millimeters.

    Page size is defined in the constant file but user is able to define custom
    page sizes in the settings file. We will try to find custom page size, if
    it is not found we will check for the default page sizes.

    :Args:
      - conf: Dictionary with all the output settings

    :Returns:
      Returns tuple with width and height values for the page size.
    """

    page_size = conf.get('size', 'default')

    if page_size == 'custom':
        return conf['custom_width'], conf['custom_height']

    PAGE_SIZE_DATA = config.get_configuration('PAGE_SIZE_DATA')

    # We need size in millimieters and some of the values in
    # configuration are floats. Just round them and return them
    # as integers.
    sze = PAGE_SIZE_DATA.get(page_size.lower(), (100, 100))

    return int(round(sze[0])), int(round(sze[1]))
Пример #37
0
    def get_context_data(self, **kwargs):
        context = super(BooksPageView, self).get_context_data(**kwargs)

        b_query = Book.objects.all()
        if not self.request.user.is_superuser:
            if self.request.user.is_authenticated():
                b_query = b_query.filter(
                    Q(hidden=False) | Q(owner=self.request.user))
            else:
                b_query = b_query.filter(hidden=False)

        paginator = Paginator(b_query.order_by('title'),
                              config.get_configuration('BOOK_LIST_PAGE_SIZE'))

        try:
            context['books_list'] = paginator.page(
                self.request.GET.get('page'))
        except PageNotAnInteger:
            context['books_list'] = paginator.page(1)
        except EmptyPage:
            context['books_list'] = paginator.page(paginator.num_pages)

        context['latest_books'] = b_query.order_by('-created')[:2]

        context['published_books'] = b_query.filter(
            bookstatus=0).order_by('-created')[:2]

        context['latest_activity'] = BookHistory.objects.filter(
            kind__in=[1, 10], book__hidden=False).order_by('-modified')[:5]
        return context
Пример #38
0
    def save_settings(self, request):
        from uuid import uuid4

        config.set_configuration(
            'BOOKTYPE_SITE_NAME', self.cleaned_data['title'])
        config.set_configuration(
            'BOOKTYPE_SITE_TAGLINE', self.cleaned_data['tagline'])

        if 'favicon' in self.files:
            # just check for any kind of silly error
            try:
                prev_favicon = config.get_configuration('BOOKTYPE_SITE_FAVICON', None)
                fh, fname = misc.save_uploaded_as_file(self.files['favicon'])
                rand_name = 'favicon.%s.ico' % uuid4().hex[:8]
                shutil.move(fname, '{}/{}'.format(settings.STATIC_ROOT, rand_name))

                config.set_configuration(
                    'BOOKTYPE_SITE_FAVICON',
                    '{}/static/{}'.format(settings.BOOKTYPE_URL, rand_name)
                )

                # delete prev icon to avoid garbage
                if prev_favicon:
                    try:
                        prev_name = prev_favicon.rsplit('/', 1)[-1]
                        os.remove('{}/{}'.format(settings.STATIC_ROOT, prev_name))
                    except Exception as err:
                        logger.exception("Unable to remove previous favicon. Msg: %s" % err)
            except:
                pass

        try:
            config.save_configuration()
        except config.ConfigurationError as err:
            raise err
Пример #39
0
    def get_context_data(self, **kwargs):
        context = super(BooksPageView, self).get_context_data(**kwargs)

        b_query = Book.objects.all()
        if not self.request.user.is_superuser:
            if self.request.user.is_authenticated():
                b_query = b_query.filter(Q(hidden=False) | Q(owner=self.request.user))
            else:
                b_query = b_query.filter(hidden=False)

        paginator = Paginator(b_query.order_by('title'), config.get_configuration('BOOK_LIST_PAGE_SIZE'))

        try:
            context['books_list'] = paginator.page(self.request.GET.get('page'))
        except PageNotAnInteger:
            context['books_list'] = paginator.page(1)
        except EmptyPage:
            context['books_list'] = paginator.page(paginator.num_pages)

        context['latest_books'] = b_query.order_by('-created')[:2]

        context['published_books'] = b_query.filter(bookstatus=0).order_by('-created')[:2]

        context['latest_activity'] = BookHistory.objects.filter(kind__in=[1, 10], book__hidden=False).order_by('-modified')[:5]
        return context
Пример #40
0
    def get_header(self, elem, style, node):
        """
        Returns HTML tag representing specific header for this element.

        :Returns:
          String representation of HTML tag.
        """

        STYLES_TUPLE = config.get_configuration('DOCX_HEADING_STYLES_TUPLE')

        if style and not isinstance(style, int):
            for header_id, header_values in STYLES_TUPLE:
                if style.style_id.lower().replace('-', '') in header_values:
                    return header_id

        if elem.rpr.get('style', None):
            for header_id, header_values in STYLES_TUPLE:
                for style_key in header_values:
                    if elem.rpr.get('style').lower().replace('-', '').startswith(style_key):
                        return header_id

        for e in elem.elements:
            if hasattr(e, 'rpr'):
                if e.rpr.get('style', None):
                    for header_id, header_values in STYLES_TUPLE:
                        for style_key in header_values:
                            if e.rpr.get('style').lower().replace('-', '').startswith(style_key):
                                return header_id

        return super(DocHeaderContext, self).get_header(elem, style, node)
Пример #41
0
    def is_header(self, elem, font_size, node, style=None):
        """
        Used for checking if specific element is a header or not.

        :Returns:
          True or False
        """

        HEADING_STYLES = config.get_configuration('DOCX_HEADING_STYLES', [])

        # Check the defined list of styles
        if style:
            if style.style_id.lower() in HEADING_STYLES:
                return True

        if elem.rpr.get('style', None):
            for style_key in HEADING_STYLES:
                if elem.rpr.get('style').lower().replace('-', '').startswith(style_key):
                    return True

        for e in elem.elements:
            if hasattr(e, 'rpr'):
                if e.rpr.get('style', None):
                    for style_key in HEADING_STYLES:

                        if e.rpr.get('style').lower().replace('-', '').startswith(style_key):
                            return True

        return super(DocHeaderContext, self).is_header(elem, font_size, node, style)
Пример #42
0
    def initial_data(cls):
        publish_options = config.get_configuration('PUBLISH_OPTIONS')
        values_map = {}

        for key in cls.get_converters().keys():
            values_map['publish_{0}'.format(key)] = key in publish_options

        return values_map
Пример #43
0
    def initial_data(cls):
        publish_options = config.get_configuration('PUBLISH_OPTIONS')
        values_map = {}

        for key in cls.get_converters().keys():
            values_map['publish_{0}'.format(key)] = key in publish_options

        return values_map
Пример #44
0
def assign_api_perms_registered_role():
    role_name = 'registered_users'
    key = 'DEFAULT_ROLE_%s' % role_name
    role_name = config.get_configuration(key, role_name)

    role = Role.objects.get(name=role_name)
    for permission in [i[0] for i in PERMISSIONS['permissions']]:
        perm = Permission.objects.get(app_name=PERMISSIONS['app_name'], name=permission)
        role.permissions.add(perm)
Пример #45
0
def assign_api_perms_anonymous_role():
    role_name = 'anonymous_users'
    key = 'DEFAULT_ROLE_%s' % role_name
    role_name = config.get_configuration(key, role_name)
    role, created = Role.objects.get_or_create(name=role_name)

    for permission in [i[0] for i in PERMISSIONS['permissions']]:
        perm = Permission.objects.get(app_name=PERMISSIONS['app_name'], name=permission)
        role.permissions.add(perm)
Пример #46
0
def booktype_site_favicon():
    """Simple tag to load default booktype favicon or custom one from settings"""

    from django.templatetags.static import static

    default = static('core/img/favicon.ico')
    favicon = config.get_configuration('BOOKTYPE_SITE_FAVICON', default)

    return '<link rel="shortcut icon" href="%s" type="image/x-icon">' % escape(favicon)
Пример #47
0
def download_bookizip(base_path, url_path):

    r = requests.get(url_path, verify=config.get_configuration("REQUESTS_VERIFY_SSL_CERT"))

    try:
        f = open("{}/booki.zip".format(base_path), "wb")
        f.write(StringIO(r.content).read())
        f.close()
    except Exception:
        logger.exception("Could not save booki.zip file")
Пример #48
0
    def initial_data(cls):
        publish_options = config.get_configuration('PUBLISH_OPTIONS')

        return {
            'publish_mpdf': 'mpdf' in publish_options,
            'publish_screenpdf': 'screenpdf' in publish_options,
            'publish_epub': 'epub' in publish_options,
            'publish_mobi': 'mobi' in publish_options,
            'publish_xhtml': 'xhtml' in publish_options
        }
Пример #49
0
def get_importer_class():
    """
    Dummy function to return the correct module to import DOCX files.
    If there is no custom class specified in client instance, it will use
    .docximporter.WordImporter class as it is in constants.py file
    """

    DOCX_IMPORTER_CLASS = config.get_configuration('DOCX_IMPORTER_CLASS')
    ImporterClass = import_from_string(DOCX_IMPORTER_CLASS)
    return ImporterClass
Пример #50
0
    def initial_data(cls):
        _dict = {}
        try:
            f = open(
                '%s/templates/portal/welcome_message.html'
                % settings.BOOKTYPE_ROOT,
                'r'
            )
            _dict['description'] = unicode(f.read(), 'utf8')
            f.close()
        except IOError:
            _dict['description'] = ''

        _dict['use_anonymous_page'] = config.get_configuration('BOOKTYPE_FRONTPAGE_USE_ANONYMOUS_PAGE')
        _dict['anonymous_message'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_MESSAGE')
        _dict['anonymous_email'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_EMAIL')
        _dict['anonymous_image'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_IMAGE')

        return _dict
Пример #51
0
    def initial_data(cls):
        publish_options = config.get_configuration('PUBLISH_OPTIONS')

        return {
            'publish_mpdf': 'mpdf' in publish_options,
            'publish_screenpdf': 'screenpdf' in publish_options,
            'publish_epub': 'epub' in publish_options,
            'publish_mobi': 'mobi' in publish_options,
            'publish_xhtml': 'xhtml' in publish_options
        }
Пример #52
0
    def initial_data(cls):
        _dict = {}
        try:
            f = open(
                '%s/templates/portal/welcome_message.html'
                % settings.BOOKTYPE_ROOT,
                'r'
            )
            _dict['description'] = unicode(f.read(), 'utf8')
            f.close()
        except IOError:
            _dict['description'] = ''

        _dict['use_anonymous_page'] = config.get_configuration('BOOKTYPE_FRONTPAGE_USE_ANONYMOUS_PAGE')
        _dict['anonymous_message'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_MESSAGE')
        _dict['anonymous_email'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_EMAIL')
        _dict['anonymous_image'] = config.get_configuration('BOOKTYPE_FRONTPAGE_ANONYMOUS_IMAGE')

        return _dict
Пример #53
0
def get_importer_class():
    """
    Dummy function to return the correct module to import DOCX files.
    If there is no custom class specified in client instance, it will use
    .docximporter.WordImporter class as it is in constants.py file
    """

    DOCX_IMPORTER_CLASS = config.get_configuration('DOCX_IMPORTER_CLASS')
    ImporterClass = import_from_string(DOCX_IMPORTER_CLASS)
    return ImporterClass
Пример #54
0
    def check_permissions(self, request, *args, **kwargs):
        if self.request.user.is_superuser:
            return

        # if only admin create then deny user permission to create new books
        if config.get_configuration('ADMIN_CREATE_BOOKS'):
            raise PermissionDenied

        # check if user can create more books
        if has_book_limit(self.request.user):
            raise PermissionDenied