示例#1
0
    def html(self, renderer):

        config = load_env_config()
        data = Data(config)

        articles = []
        for line in self.text.splitlines():
            parts = line.split('/')
            if len(parts) == 2:
                user_slug, doc_slug = parts
                metadata = data.userDocumentMetadata_get(user_slug, doc_slug)
                if metadata:
                    articles += [metadata]

        if len(articles) == 0:
            return ""

        env = Environment(autoescape=False)
        tpl = env.from_string(
            trim("""
            <nav class="article-cards">
            {% for a in articles %}
                <div class="article-card">

                    <a
                        href="/read/{{ a['user'] }}/{{ a['slug'] }}"
                    >
                        <div class="article-card-title balance-text">
                            {{ a['title'] }}
                        </div>
                        <div class="article-card-summary balance-text">
                            {{ a['summary'] }}
                        </div>
                    </a>

                    {% set words = a.word_count | int %}
                    <div class="article-card-details">
                        {{ a['date'] }} &middot; {{ "{:,d}".format(words) }} words
                    </div>
                    <div class="article-card-download">
                        <a 
                            href="/epub/{{ a['user'] }}/{{ a['slug'] }}"
                        >
                            <i class="fa fa-arrow-circle-down" ></i> eBook
                        </a>
                    </div>

                </div>
            {% endfor %}
            </nav>
        """))

        return tpl.render(articles=articles)
示例#2
0
def create_admin_user():
    """
    Creates an $ADMIN_USER with $ADMIN_USER_PASSWORD.
    """
    config = load_env_config()
    data = get_redis_client()
    admin_user = {
        'slug': config['ADMIN_USER'],
        'password': config['ADMIN_USER_PASSWORD'],
        'is_admin': 'YES',
    }
    data.user_set(config['ADMIN_USER'], admin_user)
    print("Created user: {:s}".format(config['ADMIN_USER']))
示例#3
0
 def html(self, renderer):
     """
     Show an image/quote tag for the text.
     """
     config = load_env_config()
     key = bytes(config['APP_HASH'], 'utf-8')
     message = bytes(self.text, 'utf-8')
     checksum = hmac.new(key, message, 'sha224').hexdigest()[:16]
     encoded = urllib.parse.quote_plus(message)
     # print(json.dumps(self.text), key, checksum)
     return trim("""
         <div class="wiki-feature no-print">
             <img title="%s" src="/image/quote/%s/%s.jpg" />
         </div>
         """) % (escape(self.text), checksum, encoded)
示例#4
0
def get_redis_client() -> Data:
    """Initialises a Redis client from environment variables."""
    config = load_env_config()
    if "pytest" in sys.modules:
        config['REDIS_DATABASE'] = '1'
    return Data(config)
示例#5
0
from lib.wiki.settings import Settings
from lib.wiki.wiki import \
    Wiki, \
    clean_text, \
    is_index_part, \
    reformat_part, \
    split_published
from lib.wiki.utils import pluralize, trim

HTTP_BAD_REQUEST = 400
HTTP_UNAUTHORIZED = 401
HTTP_NOT_FOUND = 404

HASH = 97586

config = load_env_config()

if "pytest" in sys.modules:
    logging.info("Running in PyTest: Reconfiguring to use test database.")
    config['REDIS_DATABASE'] = config['REDIS_TEST_DATABASE']

# Redis, Jinja
data = Data(config)
views = JinjaTemplates(loader=PackageLoader('app', 'views'),
                       trim_blocks=True,
                       lstrip_blocks=True,
                       keep_trailing_newline=True)

# Sessions
bottleApp = bottle.app()
session_opts = {
示例#6
0
def write_epub(user_slug, doc_slug, file_path):

    # Get all the data
    config = load_env_config()
    data = Data(config)

    user = data.user_get(user_slug)  # or None
    if not user:
        raise RuntimeError("User not found: %s", user_slug)

    document = data.userDocument_get(user_slug, doc_slug)  # or Noen
    if not document:
        raise RuntimeError("Document not found: %s" % doc_slug)

    # -------------------------
    # 0. Create book
    # 1. Create cover
    # 2. Create title page
    # 3. Create chapter (which basically is the book)
    #    ... This upgrades to multiple chapters when compiling books.

    # Pre-processing...

    settings = Settings({
        'config:user': user_slug,
        'config:document': doc_slug,
    })
    wiki = Wiki(settings)
    xhtml = wiki.process(user_slug, doc_slug, document)
    metadata = wiki.compile_metadata(config['TIME_ZONE'], user_slug, doc_slug)
    metadata['url'] = '/read/{:s}/{:s}'.format(user_slug, doc_slug),

    title = metadata.get('title', 'Untitled')
    summary = metadata.get('summary', '')
    author = metadata.get('author', 'Anonymous')
    date = metadata.get('date', '')

    # -------------------------
    # 0. CREATE BOOK

    book = epub.EpubBook()

    # set metadata
    book.set_identifier(user_slug + '+' + doc_slug)
    book.set_title(title)
    book.set_language('en')
    book.add_author(author)

    # define CSS style
    with open('static/epub.css') as f:
        style = f.read()
    global_css = epub.EpubItem(uid="style_nav",
                               file_name="style/nav.css",
                               media_type="text/css",
                               content=style)
    book.add_item(global_css)

    # -------------------------
    # 1. Create Cover

    tmp_cover_file = "/tmp/%s-%s-cover.png" % (user_slug, doc_slug)
    image = make_background((1600, 2200), (160, 184, 160))
    cover = make_cover(image, [title, summary, author, date],
                       [COLOR_TEXT, COLOR_SHADOW])
    cover.save(tmp_cover_file, "JPEG")
    chapter_file_name = doc_slug + '.xhtml'

    assert os.path.exists(tmp_cover_file)
    cover_image = open(tmp_cover_file, 'rb').read()
    book.set_cover("image.jpg", cover_image)

    # -------------------------
    # 2. Create Title Page

    date_string = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    title_xhtml = """
    <html>
    <body>
        <div>Generated by <i>Article Wiki</i>:</div>
        <div>%s</div>
        <div>&nbsp;</div>
        <div>Permanent URL:</div>
        <div>http://chapman.wiki/read/%s/%s</div>
    </body>
    </html>
    """ % (date_string, user_slug, doc_slug)

    c1 = epub.EpubHtml(title="About this book",
                       file_name="title.xhtml",
                       lang='en')
    c1.content = title_xhtml
    c1.add_item(global_css)
    book.add_item(c1)

    # -------------------------
    # 3. Create Chapter

    c2 = epub.EpubHtml(title=title, file_name=chapter_file_name, lang='en')
    c2.content = xhtml
    c2.add_item(global_css)
    book.add_item(c2)

    # Define Table Of Contents
    book.toc = (
        epub.Link(chapter_file_name, title, doc_slug),
        # (epub.Section(user_slug), (c2))
    )

    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    # basic spine
    book.spine = ['nav', c1, c2]

    # write to the file
    epub.write_epub(file_path, book, {})