2009-07-27

Back to Wordpress.com

[caption id="attachment_2242" align="alignnone" width="300" caption="배고픈 길냥이 오형제"]배고픈 길냥이 오형제[/caption]

호스팅 만료 한 달을 앞두고, 다시 wordpress.com 으로 전격 이사를 왔다.

국내의 정치적 핍박을 참지 못하고 사이버 망명길에 오르기엔, 여긴 그저 조회수 낮은 힘없는 일개 프로그래머의 해우소일 뿐이지만, 그래도 최근 MB족들의 하는 꼬라지를 보면 언제 호스팅이 날아가고 데이터가 악의 손아귀에 들어갈 지 모를 터다.

어쨌거나 설치형 워드프레스(이하 WP)에서 호스팅형으로 돌아갈 때 가장 걸리는 것은 바로 첨부 파일이다. 비록 WP가 XML 기반의 Export/Import 를 지원하긴 하지만 첨부 파일까지 자동으로 옮겨주지는 않기 때문이다. 그래서 처음 생각한 건 각종 이미지들을 구글의 피카사웹으로 올린 후, 그 URL을 찾아서 XML파일을 교체한다는 아이디어였다.

일단 첨부파일들을 모두 다운받아서 피카사 업로더를 이용해서 올린 후, 구글 피카사웹 API 샘플을 이용하니 손쉽게 URL을 알아낼 수 있었다. 주의할 점이라면 한글로된 앨범 이름을 위해서 유니코드를 써야 한다는 것 정도가 샘플과의 유일한 차이였다.


def get_picasa_urls(email,password,wp_album):

    gd_client = gdata.photos.service.PhotosService()
    gd_client.email = email
    gd_client.password = password
    gd_client.source = 'wordpress_attachment_exporter'
    gd_client.ProgrammaticLogin()

    print 'picasa web connected'

    dic = {}

    albums = gd_client.GetUserFeed(user='default')

    print len(albums.entry), 'albums found'

    for album in albums.entry:

        if album.title.text != wp_album:
            print 'skipping album', unicode(album.title.text,'utf-8')
            break

        print unicode(album.title.text), 'album found'

        #print 'title: %s, number of photos: %s, id: %s' % (album.title.text,album.numphotos.text, album.gphoto_id.text)
        photos = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s?kind=photo' % (album.gphoto_id.text))
        for photo in photos.entry:
            #print '  Photo:', photo.title.text, ' id:', photo.gphoto_id.text, ' url:', photo.content.src
            dic[unicode(photo.title.text,'utf-8')] = unicode(photo.content.src,'utf-8')

    print len(dic), 'images in picasa'

    return dic

그다음 한 일은 내보내기한 XML 파일의 기존 URL을 위에서 찾아낸 새 URL로 교체하는 것인데, 정규식을 활용해보기로 했다. 문제는 이렇게 했는데도 실제로 미리보기가 안된다는 것이었는데, 아마도 flickr나 피카사 모두 직접 링크를 지원하지 않는 모양이었다. 그래서 어쩔 수 없이 모든 첨부파일을 손으로 하나씩 WP.com 으로 업로드한 후 그 URL을 적용하기로 했다.

아래는 최종 버전.


import re
import codecs

# configuration
wp_export_xml = '/Volumes/data/Downloads/wordpress.2009-07-25.xml'
attachment_ext = 'jpg|JPG|gif|GIF|png|PNG|bmp|BMP|doc|docx'
attachment_url_pattern = 'http://reiot[^"\'<>]+?\.(%s)'%attachment_ext
attachment_filename_pattern = re.compile('[^/=]+?\.(%s)'%attachment_ext)
wpcom_prefix = 'http://boxcatstudio.files.wordpress.com/2009/07/'

attachments = {}

# faster than open().read().encode('utf-8')
lines = codecs.open(wp_export_xml,"r","utf-8").read()
itr = re.compile(attachment_url_pattern).finditer(lines)
for m in itr:
    orig_url = m.group()
    new_url = wpcom_prefix + attachment_filename_pattern.search(orig_url).group()
    attachments[orig_url] = new_url

print len(attachments), 'attachments found'

i = 1

for orig_url in attachments.keys():
    new_url = attachments[orig_url]
    print '[%d/%d] %s => %s'%(i,len(attachments),orig_url,new_url)
    lines = lines.replace(orig_url,new_url)
    i = i + 1

out_xml = codecs.open(wp_export_xml+".converted.xml","w","utf-8")
out_xml.write(lines)
out_xml.close()

정규식은 항상 볼 때마다 새로운 느낌이 들어서, 꽤 시간이 많이 걸렸다. 또 큰 파일에서 유니코드로 빠르게 읽으려면 codecs 모듈이 좋댄다.


comments powered by Disqus