Source

serendipity2blogofile / serendipity2blogofile.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Marcin Kasperski
#
# Heavily inspired by wordpress2blogofile.py from blogofile contrib.
# but handles also static pages and some config elements.

"""Export a Serendipity blog to Blogofile /_posts directory format

This file is MIT licensed, see http://blogofile.com/LICENSE.html for details.

Requirements:

  * An existing Serendipity database hosted on PostgreSQL

  * SQLAlchemy and Postgres driver

Usage:

  * Edit database connection details below and other config elements below

  * Execute

    cd <... directory where output is to be created ...>
    python /path/to/serendipity2blogofile.py

    If everything worked right, this will create (in the current dir)
    a:
       _posts directory with blog posts
       pages directory with static pages
       _config_extra.py file with a few items to be copied to _config.py

Important notes:

   1. The script ignores permissions, groups, images, comments etc etc
      (for comments see serendipity2disqus).  Only posts are exported
      with their text, categories and tags.

   2. Extended entries are separated from leading text by

      <!--more-->

      marker.  Use appropriate excerpt generating function to make use
      of those. Simple example (to be put into _config.py)

          def my_post_excerpt(post, num_words = 50):
              strip_place = post.find("<!--more-->")
              if strip_place != -1:
                  return post[:strip_place]
              else:
                  return post

          blog.post_excerpts.enabled = True
          blog.post_excerpts.word_length = 20
          blog.post_excerpts.method = my_post_excerpt


"""

###########################################################################
# Configuration requiring edits
###########################################################################

# Database connection details

table_prefix = "s9pl_"

db_username  = "blogowner"
db_password  = ""                    
db_host      = "linode.mekk.waw.pl"  
db_port      = "5432"
db_database  = "BLOG" 
db_conn      = "postgres://{db_username}:{db_password}@{db_host}:{db_port}/{db_database}".format(**locals())

# Other config

# Extension to use (should map to syntax used in blog or at least it's
# majority)
FILENAME_EXTENSION = "markdown"

# Custom entry properties to be saved. List of pairs where
# left is the serendipity name of custom property and right is
# the name to be used in blogofile YAML
CUSTOM_ENTRY_PROPERTIES = (
    ('BodyClass', 'body_class'),
    )

###########################################################################
# Importer code. No need to edit anything below
###########################################################################

import os
import re
import sys
import yaml
import codecs
import datetime
import sqlalchemy as sa
import sqlalchemy.orm as orm
from sqlalchemy.ext.declarative import declarative_base
import unicodedata

###########################################################################
# SQLAlchemy objects
###########################################################################

engine = sa.create_engine(db_conn)
Session = orm.scoped_session(
    orm.sessionmaker(autocommit=False,
                     autoflush=False,
                     bind=engine))
Base = declarative_base(bind=engine)

session = Session()

###########################################################################
# Mapper objects
###########################################################################

class Author(Base):
    """
    Author information. Interesting fields:

    authorid (numerical id)
    username (nick)
    realname (full true name)
    email
    """
    __tablename__ = table_prefix + "authors"
    __table_args__ = {'autoload': True}
    

class Category(Base):
    """
    Category information. Interesting fields:

    category_id (numerical)
    category_name
    category_description
    category_left, category_right, parentid (ordering, hierarchy)
    """
    __tablename__ = table_prefix + "category"
    __table_args__ = {'autoload': True}

class Config(Base):
    """
    Configuration table. Has fields name and value (and authorid but
    who cares)

    Intersting properties (names)

    blogTitle, blogDescription, blogMail, lang, baseURL, 

    permalinkStructure, permalinkAuthorStructure,
    permalinkCategoryStructure, permalinkFeedCategoryStructure,
    permalinkArchivePath, permalinkArchivesPath, permalinkFeedsPath

    username, realname, email
    """
    __tablename__ = table_prefix + "config"
    __table_args__ = {'autoload': True}
    name = sa.Column("name", sa.String, primary_key = True)


class Permalink(Base):
    """
    Entries and categories permalinks

    permalink  (relative, for example "archives/44-My-Article.html")
    entry_id   (numerical)
    type       ("entry" or "category")

    Note: as we don't use category permalink, I haven't fought
    with SQLAlchemy tu polymorphically make entry_id foreign
    key to either entries, or categories
    """
    __tablename__ = table_prefix + "permalinks"
    __table_args__ = {'autoload': True}
    entry_id = sa.Column("entry_id", sa.Integer,
                         sa.ForeignKey(table_prefix + "entries.id"),
                         primary_key = True)

class EntryCat(Base):
    """
    Entry-Category connection. 

    entryid
    categoryid
    """
    __tablename__ = table_prefix + "entrycat"
    __table_args__ = {'autoload': True}
    entry_id = sa.Column(
        "entryid", sa.Integer,
        sa.ForeignKey(table_prefix + "entries.id"),
        primary_key = True)
    category_id = sa.Column(
        "categoryid", sa.Integer,
        sa.ForeignKey(table_prefix + "category.categoryid"),
        primary_key = True)

class EntryProperty(Base):
    """
    Entry properties. 

    entryid,
    property,
    value

    Interesting values for property (except caches):
    'meta_description',
    'meta_keywords'
    and
    'ep_SomeThing' for custom attribute SomeThin
    (I get ep_BodyClass as I used BodyClass for some entries)
    """
    __tablename__ = table_prefix + "entryproperties"
    __table_args__ = {'autoload': True}
    entry_id = sa.Column(
        "entryid", sa.Integer,
        sa.ForeignKey(table_prefix + "entries.id"),
        primary_key = True)
    property = sa.Column(
        "property", sa.String,
        primary_key = True)

class Entry(Base):
    """
    Actual entry.

    Properties to be used directly:

    id
    title
    body
    extended
    isdraft

    author (object with attributes username, realname, email)

    Other properties (including timestamp, author, authorid, 
    last_modified and mapped from other tables) better should be
    used by methods.
    """
    __tablename__ = table_prefix + "entries"
    __table_args__ = {'autoload': True}

    authorid = sa.Column("authorid", 
                         sa.ForeignKey(table_prefix + "authors"))
    author_nick = sa.Column("author",
            sa.ForeignKey(table_prefix + 'authors.authorid'))
    author = orm.relation("Author",
                          primaryjoin="Entry.authorid == Author.authorid")
    permalink_rel = orm.relation(
        "Permalink",
        primaryjoin="and_"
        "(Entry.id == Permalink.entry_id, "
        "Permalink.type == 'entry')",
        uselist = False)
    #category_rel = orm.relation(
    #    "Category",
    #    primaryjoin="Entry.id == EntryCat.entryid",
    #    uselist = False)
    category_rel = orm.relationship(
        "Category", secondary = EntryCat.__table__, uselist = False,
        )
    tag_rel = orm.relation(
        "EntryTag",
        primaryjoin="Entry.id == EntryTag.entry_id"
        )
    property_rel = orm.relation(
        "EntryProperty",
        primaryjoin="Entry.id == EntryProperty.entry_id"
        )

    def creation_time(self):
        return datetime.datetime.fromtimestamp(self.timestamp)

    def last_modification_time(self):
        return datetime.datetime.fromtimestamp(self.last_modified)

    def permalink(self):
        return self.permalink_rel.permalink

    def category(self):
        return self.category_rel.category_name

    def tags(self):
        return [ item.tag for item in self.tag_rel ]

    def properties(self):
        # I handle it in ugly way outside ORM session, someone
        # better at SQLAlchemy could surely improve
        if not hasattr(self, 'properties_dict'):
            self.properties_dict = dict(
                (item.property, item.value)
                for item in  self.property_rel
                if not item.property.startswith('ep_cache'))
        return self.properties_dict

    def property(self, name, default = None):
        return self.properties().get(name, default)

    def meta_description(self):
        return self.property("meta_description")
    def meta_keywords(self):
        return self.property("meta_keywords")
    def custom_property(self, property_name):
        return self.property("ep_" + property_name)

class EntryTag(Base):
    """
    Entry-Tag connection. 

    entryid
    tag
    """
    __tablename__ = table_prefix + "entrytags"
    __table_args__ = {'autoload': True}
    entry_id = sa.Column("entryid", sa.Integer,
                         sa.ForeignKey(table_prefix + "entries.id"),
                         primary_key = True)
    tag = sa.Column("tag", sa.Integer,
                    primary_key = True)

class StaticPage(Base):
    """
    Static pages

    id
    parent_id
    articleformat
    articleformattitle
    markup
    pagetitle
    permalink
    pre_content
    content
    headline
    filename
    timestamp
    last_modified
    authorid
    articletype
    publishstatus
    language
    """
    __tablename__ = table_prefix + "staticpages"
    __table_args__ = {'autoload': True}

    def creation_time(self):
        return datetime.datetime.fromtimestamp(self.timestamp)

    def last_modification_time(self):
        return datetime.datetime.fromtimestamp(self.last_modified)

    def is_draft(self):
        return self.publishstatus and False or True


###########################################################################
# Database helpers
###########################################################################

def get_blog_posts():
    """
    Yields all blog posts found, including drafts. Use Entry class
    methods to examine data.
    """
    for item in session.query(Entry).order_by(Entry.id):
        yield item

def get_static_pages():
    for item in session.query(StaticPage).order_by(StaticPage.id):
        yield item

def get_config_item(item_name):
    return session.query(Config).get(item_name).value

###########################################################################
# Output functions
###########################################################################

MORE_MARKER = "<!--more-->"

def asciify(text):
    """
    Drops unicode special characters. Idea following 
    http://www.physic.ut.ee/~kkannike/english/prog/python/util/asciify/index.html
    >>> asciify(u"ala ma żółtą gęślę jaźnią kota aûǎ")
    u'ala ma zo\u0142ta gesle jaznia kota aua'

    """
    def repr(character):
        decomp = unicodedata.decomposition(character)
        if decomp:
            return unichr(int(decomp.split()[0], 16))
        else:
            # For some reason Polish ł is not decomposed, some other
            # chars likely too. Let's try another method - by name
            # take character name and drop suffixes like "WITH STROKE"
            try:
                character_name = unicodedata.name(character)
                new_character = unicodedata.lookup(
                    re.sub(r' WITH [A-Z]+$', '', character_name))
                if new_character:
                    return new_character
            except KeyError:
                pass
            return character
    return "".join(
        repr(character)
        for character in text
        )

def normalize_title_for_filename(name):
    """
    Corrects the title to the form suitable for filename
    """ 
    name = asciify(name.strip().lower().replace(' ', '_'))
    return re.sub(r'[/!:?\-,\']', '', name)

def normalize_text(text):
    """
    Add any patches for entry text here
    """
    return text.replace(u"\r\n", u"\n")

def write_post(output_filename, yaml_data, 
               leading_text, extended_text):

    full_filename = os.path.join("_posts", output_filename)
    with codecs.open(full_filename, "w", "utf-8") as out:
        out.write("---\n")
        out.write(yaml.safe_dump(yaml_data,
                                 default_flow_style=False,
                                 allow_unicode=True).decode("utf-8"))
        out.write("---\n")
        out.write(normalize_text(leading_text))
        out.write(
            "\n\n" + MORE_MARKER + "\n\n"
            )
        out.write(normalize_text(extended_text))

def write_page(output_filename, yaml_data,
               leading_text, extended_text):
    full_filename = os.path.join("pages", output_filename)
    with codecs.open(full_filename, "w", "utf-8") as out:
        out.write("<!--")
        out.write(yaml.safe_dump(yaml_data,
                                 default_flow_style=False,
                                 allow_unicode=True).decode("utf-8"))
        out.write("-->\n")
        out.write(normalize_text(leading_text))
        out.write(
            "\n\n" + MORE_MARKER + "\n\n"
            )
        out.write(normalize_text(extended_text))

###########################################################################
# Main
###########################################################################
    
if __name__ == '__main__':
    for needed_dir in ["_posts", "pages"]:
        if os.path.exists(needed_dir):
            print "There's already a %s directory here, "\
                "I'm not going to overwrite it." % needed_dir
            sys.exit(1)
        else:
            os.mkdir(needed_dir)
    for created_file in ["_config_extra.py"]:
        if os.path.exists(created_file):
            print "There's already a %s file here, "\
                "I'm not going to overwrite it." % created_file
            sys.exit(1)

    baseURL = get_config_item("baseURL")

    for entry in get_blog_posts():
        yaml_data = {
            # Standard blogofile fields
            "title": entry.title,
            "date": entry.creation_time().strftime("%Y/%m/%d %H:%M:%S"),
            "updated": entry.last_modification_time().strftime("%Y/%m/%d %H:%M:%S"),
            "categories": entry.category(),
            "tags": ", ".join(entry.tags()),
            "permalink": "%s%s" % (baseURL, entry.permalink()),
            "author": entry.author.realname,
            "draft": entry.isdraft and True or False,
            # source, yaml, content, filename - reserved

            # Custom fields
            #"author_email": entry.author.email,
            "id": entry.id,
            "meta_description": entry.meta_description(),
            "meta_keywords": entry.meta_keywords(),
            }
        # Custom properties
        for s9prop, blgprop in CUSTOM_ENTRY_PROPERTIES:
            value = entry.custom_property(s9prop)
            if value is not None:
                yaml_data[blgprop] = value

        # Cleaning empty values
        for empty_key in [
            key 
            for key, value in yaml_data.iteritems()
            if value is None
            ]:
            del yaml_data[empty_key]
        if not yaml_data["draft"]:
            del yaml_data["draft"]

        # Removing unnecessary newlines
        for trial_key in ["meta_description", "meta_keywords"]:
            if trial_key in yaml_data:
                yaml_data[trial_key] = yaml_data[trial_key].replace("\n", " ")

        lead_text = entry.body
        remaining_text = entry.extended

        #print yaml_data
        post_filename = u"{0}-{1}.{2}".format(
            str(entry.id).zfill(4),
            normalize_title_for_filename(entry.title),
            FILENAME_EXTENSION,
            )

        print u"Writing {0} ({1})".format(post_filename, entry.permalink())
        write_post(post_filename, yaml_data, lead_text, remaining_text)

    for page in get_static_pages():
        yaml_data = {
            "title": page.pagetitle,
            "date": page.creation_time().strftime("%Y/%m/%d %H:%M:%S"),
            "updated": entry.last_modification_time().strftime("%Y/%m/%d %H:%M:%S"),
            "permalink": page.permalink,
            "id": page.id,
            "draft": page.is_draft(),
            }

        lead_text = page.pre_content
        remaining_text = page.content

        page_filename = re.sub(r'^.*/', '', page.permalink)
        print "Writing static page {0} {1} {2}".format(page_filename, page.id, page.headline, page.permalink)
        write_page(page_filename, yaml_data, lead_text, remaining_text)

    print "Writing _config_extra.py"
    with open("_config_extra.py", "w") as conffile:
        conffile.write("""
site.url = "%s"

blog.name = "%s"

blog.description = "%s"

def my_post_excerpt(post, num_words = 50):
    strip_place = post.find("<!--more-->")
    if strip_place != -1:
        return post[:strip_place]
    else:
        return post

blog.post_excerpts.enabled = True
blog.post_excerpts.word_length = 20
blog.post_excerpts.method = my_post_excerpt

""" % (baseURL,
       get_config_item("blogTitle"),      
       get_config_item("blogDescription")))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.