#!/usr/bin/env python2.5 # -*- coding: utf-8 -*- """ Import text and images from a WordPress post. Ask logina name, password anda post ID. By prof. MS. José Antonio Meira da Rocha mailto:joseantoniomeira@gmail.com http://meiradarocha.jor.br License GPL 2.0 2010-01-25a Bugs: """ ############################## # Import Python system ############################## import sys ############################## # Assure is running in Scribus ############################## try: import scribus except ImportError,err: print "This Python script is written for the Scribus scripting interface." print "It can only be run from within Scribus." sys.exit(1) ######################### # USER IMPORTS GO HERE # ######################### import xmlrpclib import urllib from HTMLParser import HTMLParser from scribus import UNIT_MILLIMETERS, BUTTON_OK, BUTTON_NO, BUTTON_ABORT, ICON_WARNING, mm, pt ################################################ # User can change this constants ################################################ anteTitleStyle = "Antetitulo" titleStyle = "Titulo 1" estiloDoSubtitulo = "Subtitulo 1" authorStyle = "Assinatura" firstParagraphStyle = "Primeiro Paragrafo" defaultStyle = "Normal" captionStyle = 'Legenda' creditStyle = 'Credito da foto' wp_site = 'http://' loginname = '' password = '' postID = '' imageTypes = '*.jpg *.jpeg' captionHeight = 5 gutter = 5 #14.1732pt, 5mm ########################################## # Scribus constants that can't be modified AROUND_FRAME = 1 BOUNDING_BOX = 2 CONTOUR_LINE = 3 SCALETOFRAME = 1 FREESCALE = 0 PROPORTIONAL = 1 DISTORTED = 0 ###################### # Locale strings # Textos para tradução ###################### # Strings for no doc opened openDocCaption = 'Abra um documento' openDocMessage = "
Ops! Desenhe ou selecione apenas um quadro
" \
+"da matéria em que você quer aplicar estilos."
# Strings about number of columns
askColumnsCaption = 'Colunas' #Number of columns
askColumnsMessage = '
Quantas colunas?
' #How many columns? # Strings to askLoginData askLoginDataCaption = 'Entre seu login name' askLoginDataMessage = 'Entre seu nome de login no blog:
' getPasswordCaption = 'Entre sua senha' getPasswordMessage = 'Entre sua senha no blog:
' #Strings to askPostID askPostIDCaption = 'Entre o ID do post' askPostIDMessage = 'Escreva o número ID do seu post no blog.
' # Error if less than 4 text lines lessThan4LinesCaption = "Coloque texto" lessThan4LinesMessage = "Por favor, coloque mais de quatro parágrafos neste quadro.
" cantLoadCaption = "Não pude caarregar o post" cantLoadMessage = "Não pude carregar o texto do post por problema de conexão
ou problemas de nome e senha.
Você quer baixar a foto: " saveImageCaption = "Grava a imagem" failPhotoCaption='Falhou o download da foto' failPhotoMessage='
Que vergonha! Mas tentarei continuar trabalhando...
', defaultText = "Título\nSubtítulo\nAutor da matéria\nemail@doautor.com\nPrimeiro Parágrafo\nOutros parágrafos\nOutros parágrafos..." statusMessage = "Rodando o script..." # # End Locale strings #################### ########################## # Load WordPress post ########################## def loadWPpost(textFrame): server = xmlrpclib.ServerProxy( wp_site+"/xmlrpc.php" ) loginname = '' password = '' loginname,password = askLoginData(loginname,password) postID = 1 postID = askPostID(postID) try: post = server.metaWeblog.getPost(postID, loginname, password) except: scribus.messageBox(cantLoadCaption,cantLoadMessage,ICON_WARNING,BUTTON_OK) sys.exit() scribus.deleteText(textFrame) #applyStyle(defaultStyle,textFrame) ########################################## categories = ', '.join(post['categories']) length = len(categories) cursor = scribus.getTextLength(textFrame) scribus.insertText(categories+'\n',-1,textFrame) scribus.deselectAll() # Needs deselect prior select scribus.selectText(cursor,length,textFrame) applyStyle(anteTitleStyle,textFrame) ##################### title = post['title'] title = cleanText(title) length = len(title) cursor = scribus.getTextLength(textFrame) scribus.insertText(title+'\n',-1,textFrame) scribus.deselectAll() scribus.selectText(cursor,length,textFrame) applyStyle(titleStyle,textFrame) ####################################### author = post['wp_author_display_name'] length = len(author) cursor = scribus.getTextLength(textFrame) scribus.insertText(author+'\n',-1,textFrame) scribus.deselectAll() scribus.selectText(cursor,length,textFrame) applyStyle(authorStyle,textFrame) #################################### firstParagraph = post['description'] firstParagraph = reformWPtags(firstParagraph) parse.cursor = scribus.getTextLength(textFrame) #cursor = parse.cursor lines = firstParagraph.splitlines(1) for line in lines: if line != '\n': try: parse.feed(line) except: pass ########################### text = post['mt_text_more'] text = reformWPtags(text) parse.cursor = scribus.getTextLength(textFrame) lines = text.splitlines(1) for line in lines: if line != '\n': try: parse.feed(line) except: pass ############################## # Ask data about blog and post ############################## def askLoginData(loginname,password): l = scribus.valueDialog( askLoginDataCaption, askLoginDataMessage, loginname) p = scribus.valueDialog( getPasswordCaption, getPasswordMessage, password) return l,p def askPostID(postID): p = scribus.valueDialog( askPostIDCaption, askPostIDMessage, str(postID)) return p ############################ # HTMLparser ############################ class StripTags(HTMLParser): def __init__(self): """Initialize and reset this instance.""" self.reset() self.cursor = 0 self.initEm = 0 self.initStrong = 0 self.isCaption = False self.path = '' self.caption = '' self.credit = '' self.alt = '' def handle_starttag(self, tag, attrs): if tag == 'caption': self.isCaption = True for atr in attrs: if atr[0] == 'caption': # WP image "description" self.caption = atr[1] if tag == 'a' and self.isCaption: self.path = "" for atr in attrs: if atr[0] == "href": if atr[1].find(wp_site) == 0: self.path = atr[1] else: self.path += wp_site if atr[1][0] != "/": self.path += "/" self.path += atr[1] if tag == 'img' and self.isCaption: for atr in attrs: if atr[0] == 'title': # WP image title as photo author (credit) self.credit = atr[1] if atr[0] == 'alt': self.alt = atr[1] if (tag == 'strong') or (tag == 'b'): self.initStrong = self.cursor if (tag == 'em') or (tag == 'i'): self.initEm = self.cursor def handle_endtag(self, tag): if tag == 'caption': isCaption = False ####################################################### buildPhoto(self.path,self.caption,self.credit,self.alt) ####################################################### if (tag == 'strong') or (tag == 'b'): self.lenStrong = self.cursor - self.initStrong #scribus.deselectAll() # BUG: não está selecionando na segunda passagem scribus.selectText(self.initStrong,self.lenStrong,storyFrame) setBold() if (tag == 'em') or (tag == 'i'): self.lenEm = self.cursor - self.initEm #scribus.deselectAll() scribus.selectText(self.initEm,self.lenEm,storyFrame) setItalic() def handle_data(self, data): data = cleanText(data) # Watch for troubles self.cursor += len(unicode(data)) scribus.insertText(data,-1,storyFrame) parse = StripTags() ############################################## # SET BOLD AND ITALIC FONT # need works on mixed formats (bold italic) ############################################## def setBold(): font = scribus.getFont(storyFrame) size = scribus.getFontSize(storyFrame) font = font.replace('Regular','Bold') try: scribus.setFont(font,storyFrame) except: pass try: scribus.setFontSize(size,storyFrame) except: pass def setItalic(): font = scribus.getFont(storyFrame) size = scribus.getFontSize(storyFrame) font = font.replace('Regular','Italic') try: scribus.setFont(font,storyFrame) except: pass try: scribus.setFontSize(size,storyFrame) except: pass #################################### # BUILD PHOTO? #################################### def buildPhoto(path,caption,credit,alt): res = scribus.messageBox( buildPhotoCaption, buildPhotoMessage+'