Warning: join() [function.join]: Invalid arguments passed in /var/www/clients/client1/web1/web/wiki/inc/template.php on line 330

syncwiki

Artigos do wiki direto para o wordpress

syncwiki foi uma aplicação que precisei fazer para integrar o wiki com o [:misc:mnemetica:]. Ele realiza duas tarefas de manutenção:

  • adicionar / corrigir metadata do artigo
  • publicar novos posts no mnemetica

Ele ainda está em evolução, portanto, tome cuidado.

Lista de Compras:

Código-Fonte

Script principal:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
 
import os, sys, re, wordpresslib, codecs, base64
from time import strftime
from Cheetah.Template import Template
from os.path import expanduser
 
# Parametros de XMLRPC do Wordpress
url = 'http://debugger/mnemetica/xmlrpc.php'
user = 'user'
password = 'pass'
categoria = 'artigos'
# Raiz das paginas do wiki
pages_dir = expanduser('~/public_html/debugger/notas/data/pages')
# URL base do wiki
pages_url = 'http://debugger/notas'
class Weblog:
  def __init__(self, url, user, password, category):
    self.wpObj = wordpresslib.WordPressClient(url, user, password)
    self.wpObj.selectBlog(0)
    self.categories = (self.wpObj.getCategoryIdFromName(category), )
  def post(self, title, description):
    postObj = wordpresslib.WordPressPost()
    postObj.categories = self.categories
    postObj.title = title
    postObj.description = description
 
    return self.wpObj.newPost(postObj, True)
 
class Article:
  def __init__(self, path, rel_path):
    self.path = path
    self.name = ":".join(rel_path[:-4].split('/')).lower() # .txt
    self.meta = { }
    self.content = None
    self.dirty = False
  def scan_meta(self):
    if self.content is None:
      f = codecs.open(self.path, 'r', 'utf8') 
      self.content = "".join(f.readlines())
      f.close()
      for match in re.finditer("(?is)~~ME" + "TA:(.*?)~~", self.content):
        for nvpair in match.group(1).split("&"):
          name, value = nvpair.split("=", 1)
          if value[:7] == 'base64:':
            value = base64.decodestring(value[7:])
          self.meta[name.strip()] = value.strip()
      self.content = re.sub("(?is)~~ME" + "TA:(.*?)~~", "", self.content)
    return self.meta
  def format(self, v):
    if re.compile("\W").search(str(v)):
      return "base64:" + base64.encodestring(v)[:-1]
    return v
  def update(self):
    if self.dirty:
      if 0 != len(self.meta):
        self.content = self.content + "\n\n~~ME" + "TA:" + "&".join([ "%s=%s" % (k, self.format(v)) for k, v in self.meta.items() ]) + "~~\n"
      from shutil import copyfile
      copyfile(self.path, self.path + '.bak')
      f = codecs.open(self.path, 'w', 'utf8')
      f.write(self.content)
      f.close()
      self.scan_meta()
      self.dirty = False
  def __repr__(self):
    return "Article(path=%s; name=%s; meta=%s)" % (self.path, self.name, repr(self.meta))
 
class SyncWiki:
  def __init__(self, base, baseurl):
    if base is None:
      self.base = os.getcwd()
    else:
      self.base = base
    self.articles = { }
    self.baseurl = baseurl
  def url(self, article):
    return self.baseurl.rstrip('/') + "/" + article.name.lstrip('/')
  def scan_articles(self):
    if not self.articles:
      from os.path import join, commonprefix
      self.articles = { }
      for root, dirs, files in os.walk(self.base):
        for name in files:
          if name[-4:] == '.txt':
            path = join(root, name)
            rel_path = path[1 + len(commonprefix((path, self.base))):]
            self.articles[rel_path] = Article(path, rel_path)
  def fix_article(self, article):
    if not article.meta.has_key('title'):
      title_exp = re.compile("^\s*\=+\s(.*?)\s\=+(?:\s+//(.*)//)", re.M)
      match = title_exp.match(article.content)
      if match:
        article.dirty = True
        article.meta['title'] = match.group(1).strip()
        if 2 == len(match.groups()):
          article.meta['excerpt'] = match.group(2).strip()
      else:
        article.dirty = False
    return article.dirty
 
if __name__ == '__main__':
  os.umask(002)
  from os.path import expanduser
  weblog = Weblog(url, user, password, categoria)
  sw = SyncWiki(pages_dir, pages_url);
  sw.scan_articles()
  for path, article in sw.articles.items():
    article.scan_meta()
    if sw.fix_article(article):
      article.update()
    if article.meta.has_key('publish') and article.meta['publish'] == 'yes':
      context = {
        'url' : sw.url(article)
      }
 
      tmpl = source=codecs.open("syncwiki.tmpl", 'r', 'utf-8')
      lines = "".join(tmpl.readlines())
      tmpl.close()
 
      template = Template(lines)
      template.meta = dict(article.meta)
      template.context = context
 
      if not template.meta.has_key('excerpt'):
        template.meta['excerpt'] = 'Novo artigo'
 
      article_content = template.respond()
      article_title = 'wiki: ' + article.meta['title']
 
      publish_id = weblog.post(article_title, article_content)
 
      article.meta['publish'] = 'ok'
      article.meta['publish id'] = publish_id
      article.meta['date published'] = strftime("%Y-%m-%d %H:%M:%S")
 
      article.dirty = True
      article.update()

Template

  • syncwiki.tmpl é o template para novos posts:
<em>${meta['excerpt']}</em>

Este artigo foi postado no wiki, <a href="${context['url']}">disponível aqui.</a>.
codigo/python/syncwiki.txt · Última modificação: 2010/03/09 21:47 (edição externa)
Voltar ao topo
chimeric.de = chi`s home Creative Commons License Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0