Beispiel #1
0
def createHtmlElement(parentElement, elementName, attrMap = {}, elementText = None):
    u"""createHtmlElement(Node, string, map, string) -> Node
    Creates a element given element name, attribute map and optional element node text.
    If the parentElement node is None, then element is under new document (zdom).
     """ #$NON-NLS-1$
    element = None
    elementName = getNoneString(elementName)
    elementText = getNoneString(elementText)
    if not elementName:
        return None
    dom = None
    if parentElement:
        dom = parentElement.ownerDocument
    else:
        dom = ZDom()
        dom.loadXML(ELEMENT_TEMPLATE)
        parentElement = dom.documentElement
    try:
        element = dom.createElement(elementName)
        parentElement.appendChild(element)
        for (n,v) in attrMap.iteritems():
            if n and v:                
                element.setAttribute(n,v)
        if elementText:
            element.setText(elementText)
    except:
        pass    
    return element
Beispiel #2
0
    def updatePubMetaData(self, pubMetaData):
        # Flushes the UI data to the pubMetaData object.
        pubMetaData.setAddPoweredBy(self.poweredByZoundryCB.IsChecked())
        pubMetaData.setForceReUploadImages(self.forceUploadCB.IsChecked())
        pubMetaData.setAddLightbox(self.lightboxCB.IsChecked())
        pubMetaData.setPublishAsDraft(self.draftCB.IsChecked())
        pubMetaData.setPublishTime(None)
        if self.overridePubTimeCB.IsChecked():
            pubTime = self.dateCtrl.getDateTime()
            pubMetaData.setPublishTime(pubTime)
        pubMetaData.setUploadTNsOnly(self.thumbnailsOnlyCB.IsChecked())

        # WP custom data
        slug = getNoneString(self.wpPostSlugTextCtrl.GetValue())
        setCustomWPMetaDataAttribute(pubMetaData, u"wp_slug",
                                     slug)  #$NON-NLS-1$
        # password
        pw = getNoneString(self.wpPasswordTextCtrl.GetValue())
        setCustomWPMetaDataAttribute(pubMetaData, u"wp_password",
                                     pw)  #$NON-NLS-1$

        pubstatus = None
        if self.wpPublishStatusValue == ZPubMetaDataView.WP_PUBLISHED:
            pubstatus = u"publish"  #$NON-NLS-1$
        elif self.wpPublishStatusValue == ZPubMetaDataView.WP_DRAFT:
            pubstatus = u"draft"  #$NON-NLS-1$
        elif self.wpPublishStatusValue == ZPubMetaDataView.WP_PENDING:
            pubstatus = u"pending"  #$NON-NLS-1$
        elif self.wpPublishStatusValue == ZPubMetaDataView.WP_PRIVATE:
            pubstatus = u"private"  #$NON-NLS-1$

        if pubstatus:
            setCustomWPMetaDataAttribute(pubMetaData, u"post_status",
                                         pubstatus)  #$NON-NLS-1$
Beispiel #3
0
    def _validateBlog(self, blog, validationReporter):
        zaccount = blog.getAccount()
        if not zaccount:
            # defect 534 work around - should not get here
            logger = getLoggerService()
            logger.error(u"Account information not available for Blog ID %s" % blog.getId() ) #$NON-NLS-1$
            validationReporter.addError(u"Blog Account", u"Account information not available for blog %s" % blog.getName() ) #$NON-NLS-1$ #$NON-NLS-2$
            return

        username = zaccount.getAttribute(u"username")#$NON-NLS-1$
        if not getNoneString(username):
            validationReporter.addError(u"Blog Account", u"Username is missing for blog %s" % blog.getName() ) #$NON-NLS-1$ #$NON-NLS-2$
        cyppass = zaccount.getAttribute(u"password")#$NON-NLS-1$
        if not getNoneString(cyppass):
            validationReporter.addError(u"Blog Account", u"Password is missing for blog %s" % blog.getName() ) #$NON-NLS-1$ #$NON-NLS-2$
        else:
            password = None
            try:
                password = crypt.decryptCipherText(cyppass, PASSWORD_ENCRYPTION_KEY)
            except:
                pass
            if not getNoneString(password):
                validationReporter.addError(u"Blog Account", u"Invalid password set for blog %s. Please set the blog account password." % blog.getName() ) #$NON-NLS-1$ #$NON-NLS-2$

        apiInfo = zaccount.getAPIInfo()
        url = apiInfo.getUrl()
        if not getNoneString(url):
            validationReporter.addError(u"Blog Account", u"Blog API URL is required for blog %s" % blog.getName() ) #$NON-NLS-1$ #$NON-NLS-2$

        siteId = apiInfo.getType()
        if not getNoneString(siteId):
            validationReporter.addError(u"Blog Account", u"Blog API type is required for blog %s" % blog.getName() ) #$NON-NLS-1$ #$NON-NLS-2$
Beispiel #4
0
    def _visitBodyDispatchElement(self, mshtmlBodyElement):  #@UnusedVariable
        self.mshtmlBodyElement = mshtmlBodyElement
        eleList = self.mshtmlBodyElement.getElementsByTagName(u"OBJECT") #$NON-NLS-1$
        for ele in eleList:
            if getNoneString(ele.classid) is not None: #$NON-NLS-1$
                # Class ID already defined. Skip!
                continue
            # 1. Lookup <embed> child element
            # 2. If child <embed> element is application/x-shockwave-flash, then remove OBJECT elem wrapper
            # The problem is, IE does not parse <embed> as an element. Instead, it is represented as OBJECT nodes' text.
            # Work around is to do load the content into ZDOm and select embed elem.

            content = getNoneString(ele.outerHTML)
            if not content:
                continue
            xhtmlDoc = loadXhtmlDocumentFromString(content)
            dom = xhtmlDoc.getDom()
            embed = dom.selectSingleNode(u"//xhtml:embed") #$NON-NLS-1$ #$NON-NLS-1$
            if not embed:
                continue
            if embed.getAttribute(u"type") == u"application/x-shockwave-flash": #$NON-NLS-1$ #$NON-NLS-2$
                embedNode = self.mshtmlDoc.createElement(u"embed") #$NON-NLS-1$
                ele.insertAdjacentElement(u"AfterEnd",embedNode) #$NON-NLS-1$
                embedEle = getDispElement(embedNode)
                for attrNode in embed.getAttributes():
                    embedEle.setAttribute( attrNode.nodeName, attrNode.getText() )
                ele.parentNode.removeChild(ele)
                classes = getSafeString(ele.getAttribute(u"className")).split(u" ") #$NON-NLS-1$ #$NON-NLS-2$
                if not u"_Z_RAVEN_OBJECT_WRAPPER_" in classes: #$NON-NLS-1$
                    classes.append(u"_Z_RAVEN_OBJECT_WRAPPER_") #$NON-NLS-1$
                embedEle.setAttribute(u"className", u" ".join(classes).strip() ) #$NON-NLS-2$ #$NON-NLS-1$
        return False
Beispiel #5
0
 def _convertFonts(self):
     # Convert font tags for spans
     # Harded font-size mapping: 0-7 -> maps to 0.7em thru 3.0em
     EM_SIZES  = [u"0.6", u"0.75", u"0.90", u"1.0", u"1.2", u"1.5", u"2.0"] #$NON-NLS-1$ #$NON-NLS-2$ #$NON-NLS-3$ #$NON-NLS-4$ #$NON-NLS-5$ #$NON-NLS-6$ #$NON-NLS-7$
     eleList = self.mshtmlBodyElement.getElementsByTagName(u"FONT") #$NON-NLS-1$
     for ele in eleList:
         css = u"" #$NON-NLS-1$
         face = getNoneString(ele.getAttribute(u"face")) #$NON-NLS-1$
         if face:
             css = u"font-family:%s;" % face #$NON-NLS-1$
         sizeIdx = -1
         sizeStr = getNoneString(ele.getAttribute(u"size")) #$NON-NLS-1$
         if sizeStr:
             try:
                 sizeIdx = int(abs(float(sizeStr))) - 1
                 if sizeIdx < 0:
                     sizeIdx = 0
                 elif sizeIdx >= len(EM_SIZES):
                     sizeIdx = EM_SIZES - 1
             except:
                 pass
         if sizeIdx != -1:
             css = css + u"font-size:%sem;" % EM_SIZES[sizeIdx] #$NON-NLS-1$
         color = getNoneString(ele.getAttribute(u"color")) #$NON-NLS-1$
         if color:
             css = css + u"color:%s;" % color #$NON-NLS-1$
         self._replaceElement(ele, u"span", css) #$NON-NLS-1$
Beispiel #6
0
 def _loadWeblogPingSiteDefs(self):
     pluginRegistry = self.applicationModel.getPluginRegistry()
     extensions = pluginRegistry.getExtensions(
         IZBlogAppExtensionPoints.ZEP_ZOUNDRY_WEBLOGPING_SITE)
     pingSiteDefs = map(ZWeblogPingSiteDef, extensions)
     rval = []
     idList = []
     for sitedef in pingSiteDefs:
         siteId = sitedef.getId()
         if getNoneString(siteId) is None:
             self.logger.error(
                 u"Weblog ping SiteDef id is None.")  #$NON-NLS-1$
             continue
         if siteId in idList:
             self.logger.warning(
                 u"Ignoring - duplicate weblog ping site id %s" %
                 siteId)  #$NON-NLS-1$
             continue
         url = getNoneString(sitedef.getUrl())
         if not url:
             self.logger.error(u"Weblog ping SiteDef name is None for %s" %
                               siteId)  #$NON-NLS-1$
             continue
         idList.append(siteId)
         rval.append(sitedef)
     return rval
Beispiel #7
0
 def _createRegExprList(self, merchantNode):
     reListNode = merchantNode.selectSingleNode(u"ReList")  #$NON-NLS-1$
     if not reListNode:
         return []
     reEnableStr = getNoneString(
         reListNode.getAttribute(u"enabled"))  #$NON-NLS-1$
     reEnable = False
     if reEnableStr and (reEnableStr == u"yes" or reEnableStr
                         == u"true"):  #$NON-NLS-1$ #$NON-NLS-2$
         reEnable = True
     if not reEnable:
         return []
     # get regular expression list
     reNodes = reListNode.selectNodes(u"Re")  #$NON-NLS-1$
     if not reNodes:
         return []
     regExprList = []
     for reNode in reNodes:
         groupId1 = self._parseGroupId(
             reNode.getAttribute(u"group"))  #$NON-NLS-1$
         groupId2 = self._parseGroupId(
             reNode.getAttribute(u"group2"))  #$NON-NLS-1$
         reText = getNoneString(reNode.getText())
         if reText and groupId1 >= 0:
             rePattern = re.compile(reText, re.IGNORECASE)
             prodExpr = ZProductUrlRegularExpression(
                 rePattern, groupId1, groupId2)
             regExprList.append(prodExpr)
     return regExprList
Beispiel #8
0
    def _loadPubTypeDefs(self):
        pluginRegistry = self.applicationModel.getPluginRegistry()
        extensions = pluginRegistry.getExtensions(
            IZBlogAppExtensionPoints.ZEP_ZOUNDRY_PUBLISHER_TYPE)
        pubTypeDefs = map(ZPublisherTypeDef, extensions)
        rval = []
        idList = []
        for typedef in pubTypeDefs:
            typeId = typedef.getId()
            if getNoneString(typeId) is None:
                self.logger.error(
                    u"Publisher TypeDef id is None.")  #$NON-NLS-1$
                continue
            if typeId in idList:
                self.logger.warning(
                    u"Ignoring - duplicate publisher type id %s" %
                    typeId)  #$NON-NLS-1$
                continue
            if getNoneString(typedef.getClassName()) is None:
                self.logger.warning(
                    u"Ignoring - empty classname for publisher type id %s" %
                    typeId)  #$NON-NLS-1$
                continue

            idList.append(typeId)
            rval.append(typedef)
        return rval
Beispiel #9
0
    def importFtpMediaStore(self):
        joeyConfigDom = self._getJoeyUserConfigDom()
        if not joeyConfigDom:
            return
        try:
            url = getNoneString( joeyConfigDom.selectSingleNode(u"/joey/user-config/media-rep/url").getText() ) #$NON-NLS-1$
            host = getNoneString( joeyConfigDom.selectSingleNode(u"/joey/user-config/media-rep/remote/ip").getText() ) #$NON-NLS-1$
            port = getNoneString( joeyConfigDom.selectSingleNode(u"/joey/user-config/media-rep/remote/port").getText() ) #$NON-NLS-1$
            path = joeyConfigDom.selectSingleNode(u"/joey/user-config/media-rep/remote/path").getText() #$NON-NLS-1$
            username = getNoneString( joeyConfigDom.selectSingleNode(u"/joey/user-config/media-rep/remote/username").getText() )#$NON-NLS-1$
            password = getNoneString( joeyConfigDom.selectSingleNode(u"/joey/user-config/media-rep/remote/password").getText() ) #$NON-NLS-1$

            props = None
            if url and len(url) > 7 and  host and port and username and password:
                props = {}
                props[u"host"] = host  #$NON-NLS-1$
                props[u"port"] = int(port)  #$NON-NLS-1$
                props[u"username"] = username  #$NON-NLS-1$
                props[u"password"] = password  #$NON-NLS-1$
                props[u"path"] = path  #$NON-NLS-1$
                props[u"url"] = url #$NON-NLS-1$
                props[u"passive"] = True #$NON-NLS-1$
                registryList = self._getRegistryEntries(None) #@UnusedVariable
                # FIXME (PJ) create Raven FTP media site. Add regFiles to media store reg. Associate *imported raven* account that do not have publisher type fileupload with ftp.
                # store = self.mediaStoreService.createMediaStorage(u"FTP (BlogWriter)", u"zoundry.blogapp.mediastorage.site.customftp", properties) #$NON-NLS-2$ #$NON-NLS-1$
        except:
            pass
Beispiel #10
0
    def updatePubMetaData(self, pubMetaData):
        # Flushes the UI data to the pubMetaData object.
        pubMetaData.setAddPoweredBy(self.poweredByZoundryCB.IsChecked())
        pubMetaData.setForceReUploadImages(self.forceUploadCB.IsChecked())
        pubMetaData.setAddLightbox(self.lightboxCB.IsChecked())
        pubMetaData.setPublishAsDraft(self.draftCB.IsChecked())
        pubMetaData.setPublishTime(None)
        if self.overridePubTimeCB.IsChecked():
            pubTime = self.dateCtrl.getDateTime()
            pubMetaData.setPublishTime(pubTime)
        pubMetaData.setUploadTNsOnly(self.thumbnailsOnlyCB.IsChecked())

        # WP custom data
        slug = getNoneString(self.wpPostSlugTextCtrl.GetValue() )
        setCustomWPMetaDataAttribute(pubMetaData, u"wp_slug", slug) #$NON-NLS-1$
        # password
        pw = getNoneString(self.wpPasswordTextCtrl.GetValue() )
        setCustomWPMetaDataAttribute(pubMetaData, u"wp_password", pw) #$NON-NLS-1$

        pubstatus = None        
        if self.wpPublishStatusValue == ZPubMetaDataView.WP_PUBLISHED:
            pubstatus = u"publish" #$NON-NLS-1$
        elif self.wpPublishStatusValue == ZPubMetaDataView.WP_DRAFT:
            pubstatus = u"draft" #$NON-NLS-1$
        elif self.wpPublishStatusValue == ZPubMetaDataView.WP_PENDING:
            pubstatus = u"pending" #$NON-NLS-1$            
        elif self.wpPublishStatusValue == ZPubMetaDataView.WP_PRIVATE:
            pubstatus = u"private" #$NON-NLS-1$
                                    
        if pubstatus:
            setCustomWPMetaDataAttribute(pubMetaData, u"post_status", pubstatus) #$NON-NLS-1$
Beispiel #11
0
    def _loadProviderTypeDefs(self):
        pluginRegistry = self.applicationModel.getPluginRegistry()
        extensions = pluginRegistry.getExtensions(
            IZBlogAppExtensionPoints.ZEP_ZOUNDRY_LINK_PROVIDER_TYPE)
        typeDefs = map(ZLinkProviderDef, extensions)
        rval = []
        idList = []
        for typedef in typeDefs:
            typeId = typedef.getId()
            if getNoneString(typeId) is None:
                self.logger.error(
                    u"Link provider typedef id is None.")  #$NON-NLS-1$
                continue
            if typeId in idList:
                self.logger.warning(
                    u"Ignoring - duplicate link provider type id %s" %
                    typeId)  #$NON-NLS-1$
                continue
            if getNoneString(typedef.getClassName()) is None:
                self.logger.warning(
                    u"Ignoring - empty classname for link provider type id %s"
                    % typeId)  #$NON-NLS-1$
                continue
            idList.append(typeId)
            rval.append(typedef)
        return rval

    # end _loadProviderTypeDefs()


# end ZLinkProviderService
Beispiel #12
0
 def _createPubMetaData(self, blogInfo):
     pubMetaData = createDefaultPubMetaData(blogInfo.getAccountId(),
                                            blogInfo.getBlogId())
     pubMetaData.setPublishAsDraft(blogInfo.getPublishInfo().isDraft())
     pubMetaData.setPublishTime(
         blogInfo.getPublishInfo().getPublishedTime())
     categories = blogInfo.getCategories()
     if categories is not None and len(categories) > 0:
         for category in categories:
             pubMetaData.addCategory(category)
     # WP custom attrs
     slug = getNoneString(
         getWPPublishedInfoAttribute(blogInfo.getPublishInfo(),
                                     u"wp_slug"))  #$NON-NLS-1$
     if slug:
         setCustomWPMetaDataAttribute(pubMetaData, u"wp_slug",
                                      slug)  #$NON-NLS-1$
     pw = getSafeString(
         getWPPublishedInfoAttribute(blogInfo.getPublishInfo(),
                                     u"wp_password"))  #$NON-NLS-1$
     setCustomWPMetaDataAttribute(pubMetaData, u"wp_password",
                                  pw)  #$NON-NLS-1$
     status = getNoneString(
         getWPPublishedInfoAttribute(blogInfo.getPublishInfo(),
                                     u"post_status"))  #$NON-NLS-1$
     if status:
         setCustomWPMetaDataAttribute(pubMetaData, u"post_status",
                                      status)  #$NON-NLS-1$
     return pubMetaData
Beispiel #13
0
    def ping(self, pingUrl, id, url, title, blogName, excerpt):
        u"""ping(string, string, string, string, string, string) -> ZTrackbackPingResponse
        Pings the track back and returns ZTrackbackPingResponse""" #$NON-NLS-1$
        if getNoneString(pingUrl) is None:
            return ZTrackbackPingResponse(False, u"Trackback ping url is required.") #$NON-NLS-1$

        if getNoneString(id) is None:
            return ZTrackbackPingResponse(False, u"Trackback Originating Resource ID is required.") #$NON-NLS-1$

        if getNoneString(url) is None:
            return ZTrackbackPingResponse(False, u"Trackback post url is required.") #$NON-NLS-1$

        title = convertToUtf8( getSafeString(title) )
        blogName = convertToUtf8( getSafeString(blogName))
        excerpt = convertToUtf8( getSafeString(excerpt))

        postData = {
            u'id': id, #$NON-NLS-1$
            u'url': url, #$NON-NLS-1$
            u'title': title, #$NON-NLS-1$
            u'blog_name': blogName, #$NON-NLS-1$
            u'excerpt': excerpt #$NON-NLS-1$
        }

        htmlResult = self._sendHttpPostData(pingUrl, postData)
        resp = self._parseResponse(htmlResult)
        return resp
Beispiel #14
0
def createHtmlElement(parentElement,
                      elementName,
                      attrMap={},
                      elementText=None):
    u"""createHtmlElement(Node, string, map, string) -> Node
    Creates a element given element name, attribute map and optional element node text.
    If the parentElement node is None, then element is under new document (zdom).
     """ #$NON-NLS-1$
    element = None
    elementName = getNoneString(elementName)
    elementText = getNoneString(elementText)
    if not elementName:
        return None
    dom = None
    if parentElement:
        dom = parentElement.ownerDocument
    else:
        dom = ZDom()
        dom.loadXML(ELEMENT_TEMPLATE)
        parentElement = dom.documentElement
    try:
        element = dom.createElement(elementName)
        parentElement.appendChild(element)
        for (n, v) in attrMap.iteritems():
            if n and v:
                element.setAttribute(n, v)
        if elementText:
            element.setText(elementText)
    except:
        pass
    return element
Beispiel #15
0
    def ping(self, pingUrl, id, url, title, blogName, excerpt):
        u"""ping(string, string, string, string, string, string) -> ZTrackbackPingResponse
        Pings the track back and returns ZTrackbackPingResponse""" #$NON-NLS-1$
        if getNoneString(pingUrl) is None:
            return ZTrackbackPingResponse(
                False, u"Trackback ping url is required.")  #$NON-NLS-1$

        if getNoneString(id) is None:
            return ZTrackbackPingResponse(
                False, u"Trackback Originating Resource ID is required."
            )  #$NON-NLS-1$

        if getNoneString(url) is None:
            return ZTrackbackPingResponse(
                False, u"Trackback post url is required.")  #$NON-NLS-1$

        title = convertToUtf8(getSafeString(title))
        blogName = convertToUtf8(getSafeString(blogName))
        excerpt = convertToUtf8(getSafeString(excerpt))

        postData = {
            u'id': id,  #$NON-NLS-1$
            u'url': url,  #$NON-NLS-1$
            u'title': title,  #$NON-NLS-1$
            u'blog_name': blogName,  #$NON-NLS-1$
            u'excerpt': excerpt  #$NON-NLS-1$
        }

        htmlResult = self._sendHttpPostData(pingUrl, postData)
        resp = self._parseResponse(htmlResult)
        return resp
Beispiel #16
0
    def _internalPing(self,
                      extendedPing,
                      pingServerUrl,
                      weblogName,
                      weblogUrl,
                      checkUrl=None,
                      rssUrl=None):
        pingServerUrl = getNoneString(pingServerUrl)
        weblogName = getNoneString(weblogName)
        weblogUrl = getNoneString(weblogUrl)
        checkUrl = getSafeString(checkUrl).strip()
        rssUrl = getSafeString(rssUrl).strip()

        if pingServerUrl is None:
            return ZWeblogPingResponse(
                False, u"Weblog ping URL is required.")  #$NON-NLS-1$

        if weblogName is None:
            return ZWeblogPingResponse(
                False, u"Weblog name or post title is required.")  #$NON-NLS-1$

        if weblogUrl is None:
            return ZWeblogPingResponse(
                False, u"Weblog URL or post permanent link is required."
            )  #$NON-NLS-1$

        if extendedPing and (checkUrl == u""
                             or rssUrl == u""):  #$NON-NLS-1$ #$NON-NLS-2$
            return ZWeblogPingResponse(
                False,
                u"URL to RSS feed or Check URL parameter is required for ExtendedPings."
            )  #$NON-NLS-1$

        success = False
        message = u""  #$NON-NLS-1$
        try:
            remoteServer = Server(pingServerUrl)
            result = None
            if extendedPing:
                result = remoteServer.weblogUpdate.extendedPing(
                    weblogName, weblogUrl, checkUrl, rssUrl)
            else:
                result = remoteServer.weblogUpdates.ping(weblogName, weblogUrl)
            if result is not None and result.has_key(u"flerror"):  #$NON-NLS-1$
                success = not result[u"flerror"]  #$NON-NLS-1$
            if result is not None and result.has_key(u"message"):  #$NON-NLS-1$
                message = result[u"message"]  #$NON-NLS-1$
            elif not result or not result.has_key(u"message"):  #$NON-NLS-1$
                message = u"Weblog ping response message not available after pinging %s" % pingServerUrl  #$NON-NLS-1$
        except Fault, fault:
            fcode = u""  #$NON-NLS-1$
            if fault.faultCode:
                fcode = unicode(fault.faultCode)
            fstr = u""  #$NON-NLS-1$
            if fault.faultString:
                fstr = convertToUnicode(fault.faultString)
            success = False
            message = u"Weblog ping faulted when pinging %s (code: %s, reason: %s)" % (
                pingServerUrl, fcode, fstr)  #$NON-NLS-1$
Beispiel #17
0
 def _storeDocument(self, document, connection):
     params = [
           document.getId(),
           document.getTitle(),
           getNoneString(document.getCreationTime()),
           getNoneString(document.getLastModifiedTime())
     ]
     self._insert(u"INSERT INTO Document (DocumentId, Title, CreationTime, LastModifiedTime) values (?, ?, ?, ?)", params, connection) #$NON-NLS-1$
Beispiel #18
0
 def _storeDocument(self, document, connection):
     params = [
           document.getId(),
           document.getTitle(),
           getNoneString(document.getCreationTime()),
           getNoneString(document.getLastModifiedTime())
     ]
     self._insert(u"INSERT INTO Document (DocumentId, Title, CreationTime, LastModifiedTime) values (?, ?, ?, ?)", params, connection) #$NON-NLS-1$
Beispiel #19
0
 def _createAmazonAssociateLink(self, productUrl, asin, assoicateId):
     asin = getNoneString(asin)
     if asin:
         return u"http://www.amazon.com/exec/obidos/ASIN/%s/ref=nosim/%s" % (asin, assoicateId) #$NON-NLS-1$
     productUrl = getNoneString(productUrl)
     if not productUrl:
         return None
     productUrl = encodeUri(productUrl)
     return u"http://www.amazon.com/exec/obidos/redirect?tag=%s&path=%s" % (assoicateId, productUrl) #$NON-NLS-1$
Beispiel #20
0
 def _createAmazonAssociateLink(self, productUrl, asin, assoicateId):
     asin = getNoneString(asin)
     if asin:
         return u"http://www.amazon.com/exec/obidos/ASIN/%s/ref=nosim/%s" % (
             asin, assoicateId)  #$NON-NLS-1$
     productUrl = getNoneString(productUrl)
     if not productUrl:
         return None
     productUrl = encodeUri(productUrl)
     return u"http://www.amazon.com/exec/obidos/redirect?tag=%s&path=%s" % (
         assoicateId, productUrl)  #$NON-NLS-1$
 def _setEditorFonts(self):
     try:
         userPrefs = getApplicationModel().getUserProfile().getPreferences()
         fontName = getNoneString(userPrefs.getUserPreference(IZBlogAppUserPrefsKeys.EDITOR_FONT_NAME, u"")) #$NON-NLS-1$
         fontSize = getNoneString(userPrefs.getUserPreference(IZBlogAppUserPrefsKeys.EDITOR_FONT_SIZE, u"")) #$NON-NLS-1$
         if fontName:
             self._getMshtmlControl().getIHTMLDocument().body.style.fontFamily = fontName
         if fontSize:
             self._getMshtmlControl().getIHTMLDocument().body.style.fontSize = fontSize
     except:
         pass
Beispiel #22
0
    def _getProperties(self):
        if not self.firstTime:
            return
        self.firstTime = False
        elem = self._getElement()
        if not elem or not elem.style:
            return

#        print "---"
#        print "IN", len(elem.innerText)
#        print "TR", len(self.mshtmlIHTMLTextRange.text)
#        print "IN}%s{" % elem.innerText
#        print "TR}%s{" % self.mshtmlIHTMLTextRange.text
        bgColor = None
        color = None
        fontSize = None
        fontName = None
        self.hasCSSFontSize = False
        self.hasCSSFontName = False

        # walk up the ladder and build css font properties
        while (elem != None):
            if not self.hasCSSFontSize and getNoneString(elem.style.fontSize):
                self.hasCSSFontSize = True
            if not self.hasCSSFontName and getNoneString(
                    elem.style.fontFamily):
                self.hasCSSFontName = True

            if not bgColor:
                bgColor = getNoneString(elem.style.backgroundColor)
            if not color:
                color = getNoneString(elem.style.color)
            if not fontName:
                fontName = self.mshtmlControl.queryCommandValue(
                    u"FontName")  #$NON-NLS-1$
            if not fontSize:
                fontSize = getNoneString(elem.style.fontSize)
            if elem.tagName == u"BODY":  #$NON-NLS-1$
                break
            if (color and bgColor and fontSize and fontName):
                break
            elem = elem.parentElement
        # end while
        if color:
            self.cssColor = ZCssColor(color)
        if bgColor:
            self.cssBgColor = ZCssColor(bgColor)
        self.fontInfo = ZCssFontInfo()
        self.fontInfo.setFontName(fontName)
        self.fontInfo.setFontSize(fontSize)
Beispiel #23
0
 def _sendTrackbacks(self, trackbackUrlList):
     blog = self._getContext().getBlog()
     blogName = getNoneString(blog.getName())
     id = blog.getUrl()
     title = self._getContext().getTitle()
     if blogName is None:
         blogName = title
     # get the post entry url.
     postUrl = getNoneString(self._getContext().getUrl())
     if not postUrl:
         pass
         #log error and return
     if not id:
         id = postUrl
     # post summary
     excerpt = self._getContext().getXhtmlDocument().getSummary(500)
     pinger = ZTrackbackPinger()
     sentCount = 0
     for pingUrl in trackbackUrlList:
         if self.isCancelled():
             return
         s = u"Sending trackback to %s" % pingUrl  #$NON-NLS-1$
         self._getContext().logInfo(self, s)
         self._getContext().notifyProgress(self, s, 1, False)
         ok = False
         msg = u""  #$NON-NLS-1$
         try:
             response = pinger.ping(pingUrl, id, postUrl, title, blogName,
                                    excerpt)
             ok = response.isSuccessful()
             msg = getSafeString(response.getMessage())
         except Exception, e:
             ok = False
             msg = unicode(e)
         if ok:
             trackback = ZTrackback()
             trackback.setUrl(pingUrl)  #$NON-NLS-1$
             trackback.setSentDate(ZSchemaDateTime())
             pubInfo = self._getPubInfo()
             if pubInfo:
                 pubInfo.addTrackback(trackback)
             sentCount = sentCount + 1
             s = u"Trackback sent successfully: %s" % msg  #$NON-NLS-1$
             self._getContext().logInfo(self, s)
             self._getContext().notifyProgress(self, s, 0, False)
         else:
             s = u"Trackback failed: %s" % msg  #$NON-NLS-1$
             self._getContext().logError(self, s)
             self._getContext().notifyProgress(self, s, 0, False)
Beispiel #24
0
 def _extractRssItems(self, url, title, htmlContent): #@UnusedVariable
     u"""Extracts the RSS Item data from the given content string and returns a list of Trackback objects.""" #$NON-NLS-1$
     ## NOTE: Needs more testing.
     rssTbList = []
     itemEleList = ITEM_RE.findall(htmlContent)
     for item in itemEleList:
         link = self._extract(ITEM_LINK_RE,item)
         desc = self._extract(ITEM_DESC_RE,item)
         pingUrl = self._extract(ITEM_TB_1_RE,item)
         if getNoneString(pingUrl) is None:
             pingUrl = self._extract(ITEM_TB_2_RE,item)
         if getNoneString(pingUrl) is not None:
             tb = ZTrackbackEntry(pingUrl, entryUrl=link, title=desc, summary=u"") #$NON-NLS-1$
             rssTbList.append(tb)
     return rssTbList
Beispiel #25
0
 def _getPicasaServer(self):
     if not self.picasaServer:
         username = None
         password = None
         if u"username" in self.properties: #$NON-NLS-1$
             username = getNoneString(self.properties[u"username"]) #$NON-NLS-1$
         if not username:
             raise ZException(u"Picasa web album account username is required.") #$NON-NLS-1$
         if u"password" in self.properties: #$NON-NLS-1$
             password = getNoneString(self.properties[u"password"]) #$NON-NLS-1$
         if not password:
             raise ZException(u"Picasa web album account password is required.") #$NON-NLS-1$
         self.picasaServer = ZPicasaServer(username, password)
         self.picasaServer.setLogger(getLoggerService())
     return self.picasaServer
Beispiel #26
0
    def _getProperties(self):
        if not self.firstTime:
            return
        self.firstTime = False
        elem = self._getElement()
        if not elem or not elem.style:
            return

#        print "---"
#        print "IN", len(elem.innerText)
#        print "TR", len(self.mshtmlIHTMLTextRange.text)
#        print "IN}%s{" % elem.innerText
#        print "TR}%s{" % self.mshtmlIHTMLTextRange.text
        bgColor = None
        color = None
        fontSize = None
        fontName = None
        self.hasCSSFontSize = False
        self.hasCSSFontName = False

        # walk up the ladder and build css font properties
        while (elem != None):
            if not self.hasCSSFontSize and getNoneString(elem.style.fontSize):
                self.hasCSSFontSize = True
            if not self.hasCSSFontName and getNoneString(elem.style.fontFamily):
                self.hasCSSFontName = True

            if not bgColor:
                bgColor = getNoneString( elem.style.backgroundColor )
            if not color:
                color = getNoneString(elem.style.color)
            if not fontName:
                fontName = self.mshtmlControl.queryCommandValue(u"FontName") #$NON-NLS-1$
            if not fontSize:
                fontSize = getNoneString(elem.style.fontSize)
            if elem.tagName == u"BODY": #$NON-NLS-1$
                break
            if (color and bgColor and fontSize and fontName):
                break
            elem = elem.parentElement
        # end while
        if color:
            self.cssColor = ZCssColor(color)
        if bgColor:
            self.cssBgColor = ZCssColor(bgColor)
        self.fontInfo = ZCssFontInfo()
        self.fontInfo.setFontName(fontName)
        self.fontInfo.setFontSize(fontSize)
Beispiel #27
0
 def _sendTrackbacks(self, trackbackUrlList):
     blog = self._getContext().getBlog()
     blogName = getNoneString( blog.getName() )
     id = blog.getUrl()
     title = self._getContext().getTitle()
     if blogName is None:
         blogName = title
     # get the post entry url.
     postUrl = getNoneString( self._getContext().getUrl() )
     if not postUrl:
         pass
         #log error and return
     if not id:
         id = postUrl
     # post summary
     excerpt = self._getContext().getXhtmlDocument().getSummary(500)
     pinger = ZTrackbackPinger()
     sentCount = 0
     for pingUrl in trackbackUrlList:
         if self.isCancelled():
             return
         s = u"Sending trackback to %s" % pingUrl #$NON-NLS-1$
         self._getContext().logInfo(self, s)
         self._getContext().notifyProgress(self, s, 1, False)
         ok = False
         msg = u"" #$NON-NLS-1$
         try:
             response = pinger.ping(pingUrl, id, postUrl, title, blogName, excerpt)
             ok = response.isSuccessful()
             msg = getSafeString(response.getMessage())
         except Exception, e:
             ok = False
             msg = unicode(e)
         if ok:
             trackback = ZTrackback()
             trackback.setUrl(pingUrl) #$NON-NLS-1$
             trackback.setSentDate(ZSchemaDateTime())
             pubInfo = self._getPubInfo()
             if pubInfo:
                 pubInfo.addTrackback(trackback)
             sentCount = sentCount + 1
             s = u"Trackback sent successfully: %s" % msg #$NON-NLS-1$
             self._getContext().logInfo(self, s)
             self._getContext().notifyProgress(self, s, 0, False)
         else:
             s = u"Trackback failed: %s" % msg #$NON-NLS-1$
             self._getContext().logError(self, s)
             self._getContext().notifyProgress(self, s, 0, False)
Beispiel #28
0
    def _validateBlog(self, blog, validationReporter):
        zaccount = blog.getAccount()
        if not zaccount:
            # defect 534 work around - should not get here
            logger = getLoggerService()
            logger.error(u"Account information not available for Blog ID %s" %
                         blog.getId())  #$NON-NLS-1$
            validationReporter.addError(
                u"Blog Account",
                u"Account information not available for blog %s" %
                blog.getName())  #$NON-NLS-1$ #$NON-NLS-2$
            return

        username = zaccount.getAttribute(u"username")  #$NON-NLS-1$
        if not getNoneString(username):
            validationReporter.addError(
                u"Blog Account", u"Username is missing for blog %s" %
                blog.getName())  #$NON-NLS-1$ #$NON-NLS-2$
        cyppass = zaccount.getAttribute(u"password")  #$NON-NLS-1$
        if not getNoneString(cyppass):
            validationReporter.addError(
                u"Blog Account", u"Password is missing for blog %s" %
                blog.getName())  #$NON-NLS-1$ #$NON-NLS-2$
        else:
            password = None
            try:
                password = crypt.decryptCipherText(cyppass,
                                                   PASSWORD_ENCRYPTION_KEY)
            except:
                pass
            if not getNoneString(password):
                validationReporter.addError(
                    u"Blog Account",
                    u"Invalid password set for blog %s. Please set the blog account password."
                    % blog.getName())  #$NON-NLS-1$ #$NON-NLS-2$

        apiInfo = zaccount.getAPIInfo()
        url = apiInfo.getUrl()
        if not getNoneString(url):
            validationReporter.addError(
                u"Blog Account", u"Blog API URL is required for blog %s" %
                blog.getName())  #$NON-NLS-1$ #$NON-NLS-2$

        siteId = apiInfo.getType()
        if not getNoneString(siteId):
            validationReporter.addError(
                u"Blog Account", u"Blog API type is required for blog %s" %
                blog.getName())  #$NON-NLS-1$ #$NON-NLS-2$
Beispiel #29
0
    def _loadStringFromFile(self, html):
        # MSHTML control requires a <head> and <title> element
        title = getNoneString( extractTitle(html) )
        if not title or html.find(u"<html") == -1: #$NON-NLS-1$
            # case where only the body content is given or the content did not have non-empty <head> and <title> elems.
            # try and create wrapper around the body. Eg:  <html><head><title>ZoundryDocument</title></head><body> CONTENT </body> </html>
            html = wrapHtmlBody(html, u"ZoundryDocument") #$NON-NLS-1$

        # note: \r\n must be replace with \n. Otherwise, in <pre> blocks, the \r' will show up as an extra line.
        html = html.replace(u"\r\n", u"\n")  #$NON-NLS-1$  #$NON-NLS-2$
        # For the test-harness to work, hard code temp dir
        tmpDir = u"c:/temp" #$NON-NLS-1$
        if getApplicationModel():
            userProfile = getApplicationModel().getUserProfile()
            tmpDir = userProfile.getTempDirectory()
        d = str(time.time())
        fname = os.path.join(tmpDir, u"_z_raven_mshtml_%s_tmp.xhtml" % d) #$NON-NLS-1$
        tmpFile = codecs.open(fname, u"w") #$NON-NLS-1$
        try:
            # write the utf-8 byte order marker for wintel platforms.
            tmpFile.write(codecs.BOM_UTF8)
            tmpFile.write( convertToUtf8(html) )
            tmpFile.close()
            self._loadFile(fname)
        finally:
            tmpFile.close()
Beispiel #30
0
    def _loadPubSiteDefs(self):
        pluginRegistry = self.applicationModel.getPluginRegistry()
        extensions = pluginRegistry.getExtensions(
            IZBlogAppExtensionPoints.ZEP_ZOUNDRY_PUBLISHER_SITE)
        pubSiteDefs = map(ZPublisherSiteDef, extensions)
        rval = []
        idList = []
        for sitedef in pubSiteDefs:
            siteId = sitedef.getId()
            pubId = sitedef.getPublisherTypeId()
            if getNoneString(siteId) is None:
                self.logger.error(
                    u"Publisher SiteDef id is None.")  #$NON-NLS-1$
                continue
            if siteId in idList:
                self.logger.warning(
                    u"Ignoring - duplicate publisher site id %s" %
                    siteId)  #$NON-NLS-1$
                continue
            publisherDef = self.getPublisherType(pubId)
            if publisherDef is None:
                self.logger.warning(
                    u"Ignoring - publisher type (%s) not found for site (%s)" %
                    (pubId, siteId))  #$NON-NLS-1$
                continue
            sitedef.setPublisherTypeDef(publisherDef)
            idList.append(siteId)
            rval.append(sitedef)

        return rval
Beispiel #31
0
    def _populateAtomEntry(self, atomEntry, zserverBlogEntry):
        title = getSafeString( zserverBlogEntry.getTitle() )
        content = getSafeString( self._formatContentForPublishing( zserverBlogEntry ) )
        utcDateTime = zserverBlogEntry.getUtcDateTime()
        draft = zserverBlogEntry.isDraft()
        author = getNoneString( zserverBlogEntry.getAuthor() )
        if not author:
            author = self.getUsername()

        atomEntry.setTitle(title)
        atomEntry.setDate(utcDateTime)
        atomEntry.setContent(content)
        atomEntry.setDraft(draft)
        atomEntry.setAuthor(author)

        atomCatList = []
        # list of categories already added
        catNames = []
        for cat in zserverBlogEntry.getCategories():
            # map Zoundry cat id to atom category 'term' attribute.
            atomCat = ZAtomCategory(cat.getId(), cat.getName() )
            atomCatList.append( atomCat )
            name = cat.getName().lower()
            if name not in catNames:
                catNames.append(name)
        # Special case for Blogger. Blend zcategories + ztags into atom catories
        # FIXME (PJ) externalize this to a capability or param
        if zserverBlogEntry.getTagwords() and self.getApiUrl().startswith(u"http://www.blogger.com/feeds/default/blogs"): #$NON-NLS-1$
            for tagword in zserverBlogEntry.getTagwords():
                if tagword.lower() not in catNames:
                    catid = tagword
                    atomCat = ZAtomCategory(catid, tagword )
                    atomCatList.append( atomCat )

        atomEntry.setCategories(atomCatList)
Beispiel #32
0
 def getPublishedUrl(self, blogId):
     rval = None
     if self.isPublishedToBlog(blogId):
         pubInfo = self.getBlogInfo(blogId).getPublishInfo()
         if pubInfo is not None:
             return getNoneString(pubInfo.getUrl())
     return rval
Beispiel #33
0
def deserializeTagSiteList(sitesCsvStr):
    u"""deserializeTagSiteList(string) -> string[]
    Deserializes the list of tag sites from a string.""" #$NON-NLS-1$
    if not getNoneString(sitesCsvStr):
        return []
    sites = sitesCsvStr.split(u",") #$NON-NLS-1$
    return sites
Beispiel #34
0
 def _isMisspelled(self, word):
     u"""Returns true if the given word is not in the dictionary."""  #$NON-NLS-1$
     word = getNoneString(word)
     if word and self._getSpellChecker():
         return not self._getSpellChecker().check(word)
     else:
         return True
Beispiel #35
0
    def _sendUploadFile(self, fileName, metaTitle = None, metaDesc = None, zBlogServerMediaUploadListener = None, gallery=None):
        fileDescriptor = None
        if hasattr(fileName, u'read'): #$NON-NLS-1$
            # file name is a file descriptor. get name from descriptor.
            fileDescriptor = fileName     
            fileName = fileDescriptor.name.split(u'/')[-1] #$NON-NLS-1$   
        metaFilename = os.path.basename(fileName)
        if not metaTitle:
            metaTitle =  metaFilename
        if not metaDesc:
            metaDesc  =  metaFilename

        if not getNoneString(gallery):
            gallery = FB_GALLERY_NAME
        picMd5 = self._getFileMD5(fileName)
        picSize = os.path.getsize(fileName)
        fbRequest = ZFotoBilderRequest(u"UploadPic", fileName, fileDescriptor, zBlogServerMediaUploadListener) #$NON-NLS-1$
        fbRequest.addRequestParam(u"X-FB-UploadPic.MD5", picMd5) #$NON-NLS-1$
        #fbRequest.addRequestParam("X-FB-UploadPic.PicSec", "1")
        fbRequest.addRequestParam(u"X-FB-UploadPic.ImageLength", str(picSize) ) #$NON-NLS-1$
        fbRequest.addRequestParam(u"X-FB-UploadPic.Meta.Filename", metaFilename ) #$NON-NLS-1$
        fbRequest.addRequestParam(u"X-FB-UploadPic.Meta.Title", metaTitle )#$NON-NLS-1$
        fbRequest.addRequestParam(u"X-FB-UploadPic.Meta.Description", metaDesc ) #$NON-NLS-1$
        fbRequest.addRequestParam(u"X-FB-UploadPic.Gallery._size", u"1" ) #$NON-NLS-1$ #$NON-NLS-2$
        fbRequest.addRequestParam(u"X-FB-UploadPic.Gallery.0.GalName", gallery ) #$NON-NLS-1$
        #fbRequest.addRequestParam("X-FB-UploadPic.Gallery.0.GalSec", "")
        fbResponse = self._sendRequest(fbRequest)
        return fbResponse
 def _getSuggestionList(self, word):
     u"""Returns a list of suggested words for the given word.""" #$NON-NLS-1$
     word = getNoneString(word)
     if word and self._getSpellChecker():
         return self._getSpellChecker().suggest(word)
     else:
         return []
 def _isMisspelled(self, word):
     u"""Returns true if the given word is not in the dictionary.""" #$NON-NLS-1$
     word = getNoneString(word)
     if word and self._getSpellChecker():
         return not self._getSpellChecker().check(word)
     else:
         return True
Beispiel #38
0
 def getAttribute(self, name):
     node = self.node.selectSingleNode(
         u"ans:attribute[@name = '%s' and not(@namespace)]" % name, self.nssMap
     )  # $NON-NLS-1$
     if node:
         return getNoneString(node.getText())
     return None
Beispiel #39
0
 def _getSuggestionList(self, word):
     u"""Returns a list of suggested words for the given word."""  #$NON-NLS-1$
     word = getNoneString(word)
     if word and self._getSpellChecker():
         return self._getSpellChecker().suggest(word)
     else:
         return []
Beispiel #40
0
    def _process(self):
        if self.pingSites is None:
            return
        blog = self._getContext().getBlog()
        blogName = getNoneString( blog.getName() )
        if blogName is None:
            # get the post entry title
            blogName = self._getContext().getTitle()

        blogUrl = blog.getUrl()
        if blogUrl is None:
            # get the post entry url.
            blogUrl = self._getContext().getUrl()

        pingServer = ZWeblogPingServer()
        for weblogPingSite in self.pingSites:
            if self.isCancelled():
                return
            s = u"Pinging %s at %s" % ( weblogPingSite.getName(), weblogPingSite.getUrl() ) #$NON-NLS-1$
            self._getContext().logInfo(self, s)
            self._getContext().notifyProgress(self, s, 1, False)

            weblogPingResponse = pingServer.ping(weblogPingSite.getUrl(), blogName, blogUrl)
            if weblogPingResponse.isSuccessful():
                s = u"Pinged %s successfully: %s" % ( weblogPingSite.getName(),weblogPingResponse.getMessage() ) #$NON-NLS-1$
                self._getContext().logInfo(self, s)
                self._getContext().notifyProgress(self, s, 0, False)

            else:
                s = u"Pinging %s failed: %s" % ( weblogPingSite.getName(),weblogPingResponse.getMessage() ) #$NON-NLS-1$
                self._getContext().logError(self, s)
                self._getContext().notifyProgress(self, s, 0, False)
Beispiel #41
0
 def _parseMargin(self, imageEle):
     # return "top right bottom left"
     cssAttrs = self._getStyleMap(imageEle)
     if cssAttrs.has_key(u"margin") and getNoneString(cssAttrs[u"margin"]) is not None: #$NON-NLS-1$ #$NON-NLS-2$
         (t, r, b, l) = parseCssRectangleProperty(cssAttrs[u"margin"]) #$NON-NLS-1$
         return u"%s %s %s %s" % (t, r, b, l) #$NON-NLS-1$
     return None
Beispiel #42
0
 def _analyseZXhtmlLink(self, iZXhtmlLink):
     href = getNoneString( iZXhtmlLink.getHref() )
     if not href or len(href) < 10:
         return
     affiliateLink = self.productService.createZoundryAffiliateLink(href)
     if affiliateLink:
         iZXhtmlLink.setHref(affiliateLink)            
Beispiel #43
0
 def _analyseZXhtmlLink(self, iZXhtmlLink):
     href = getNoneString(iZXhtmlLink.getHref())
     if not href or len(href) < 10:
         return
     affiliateLink = self.productService.createZoundryAffiliateLink(href)
     if affiliateLink:
         iZXhtmlLink.setHref(affiliateLink)
Beispiel #44
0
    def _loadStringFromFile(self, html):
        # MSHTML control requires a <head> and <title> element
        title = getNoneString(extractTitle(html))
        if not title or html.find(u"<html") == -1:  #$NON-NLS-1$
            # case where only the body content is given or the content did not have non-empty <head> and <title> elems.
            # try and create wrapper around the body. Eg:  <html><head><title>ZoundryDocument</title></head><body> CONTENT </body> </html>
            html = wrapHtmlBody(html, u"ZoundryDocument")  #$NON-NLS-1$

        # note: \r\n must be replace with \n. Otherwise, in <pre> blocks, the \r' will show up as an extra line.
        html = html.replace(u"\r\n", u"\n")  #$NON-NLS-1$  #$NON-NLS-2$
        # For the test-harness to work, hard code temp dir
        tmpDir = u"c:/temp"  #$NON-NLS-1$
        if getApplicationModel():
            userProfile = getApplicationModel().getUserProfile()
            tmpDir = userProfile.getTempDirectory()
        d = str(time.time())
        fname = os.path.join(tmpDir,
                             u"_z_raven_mshtml_%s_tmp.xhtml" % d)  #$NON-NLS-1$
        tmpFile = codecs.open(fname, u"w")  #$NON-NLS-1$
        try:
            # write the utf-8 byte order marker for wintel platforms.
            tmpFile.write(codecs.BOM_UTF8)
            tmpFile.write(convertToUtf8(html))
            tmpFile.close()
            self._loadFile(fname)
        finally:
            tmpFile.close()
Beispiel #45
0
    def _loadEntriesDefs(self):
        pluginRegistry = self._getApplicationModel().getPluginRegistry()
        extensions = pluginRegistry.getExtensions(
            IZBlogAppExtensionPoints.ZEP_ZOUNDRY_SIMPLELINKS_PROVIDER_ENTRIES)
        entryDefs = map(ZSimpleLinkProviderEntriesDef, extensions)
        rval = []
        idList = []
        for entrydef in entryDefs:
            entryId = entrydef.getId()
            if getNoneString(entryId) is None:
                self.logger.error(
                    u"SimpleLinkProvider config entry id is None."
                )  #$NON-NLS-1$
                continue
            if entryId in idList:
                self.logger.warning(
                    u"Ignoring - duplicate SimpleLinkProvider config entry id %s"
                    % entryId)  #$NON-NLS-1$
                continue
            idList.append(entryId)
            rval.append(entrydef)
        return rval

    # end _loadEntriesDefs()


# end ZSimpleProviderBase
Beispiel #46
0
 def getAttribute(self, name):
     node = self.node.selectSingleNode(
         u"ans:attribute[@name = '%s' and not(@namespace)]" % name,
         self.nssMap)  #$NON-NLS-1$
     if node:
         return getNoneString(node.getText())
     return None
 def __init__(self, zblog):
     ZBlogPublishHandlerBase.__init__(self, u"ZUploadContentPrePublishHandler") #$NON-NLS-1$
     self.zblog = zblog
     self.mediaStoreId = getNoneString( self.zblog.getMediaUploadStorageId() )
     self.uploadContentList = None
     self._getLogger().debug(u"ZUploadContentPrePublishHandler-init: BlogId: %s" % zblog.getId()) #$NON-NLS-1$
     self._getLogger().debug(u"ZUploadContentPrePublishHandler-init: BlogName: %s" % zblog.getName()) #$NON-NLS-1$
Beispiel #48
0
 def _storeBlogInfo(self, documentId, blogInfo, connection):
     pubInfo = blogInfo.getPublishInfo()
     draft = 0
     if pubInfo.isDraft():
         draft = 1
     params = [
           documentId,
           blogInfo.getAccountId(),
           blogInfo.getBlogId(),
           pubInfo.getBlogEntryId(),
           getNoneString(pubInfo.getPublishedTime()),
           getNoneString(pubInfo.getSynchTime()),
           draft,
           pubInfo.getUrl()
     ]
     self._insert(u"INSERT INTO PublishedData (DocumentId, AccountId, BlogId, BlogEntryId, IssuedTime, SynchTime, Draft, Permalink) values (?, ?, ?, ?, ?, ?, ?, ?)", params, connection) #$NON-NLS-1$
Beispiel #49
0
    def _loadPubSiteDefs(self):
        pluginRegistry = self.applicationModel.getPluginRegistry()
        extensions = pluginRegistry.getExtensions(IZBlogAppExtensionPoints.ZEP_ZOUNDRY_PUBLISHER_SITE)
        pubSiteDefs = map(ZPublisherSiteDef, extensions)
        rval = []
        idList = []
        for sitedef in pubSiteDefs:
            siteId = sitedef.getId()
            pubId = sitedef.getPublisherTypeId()
            if getNoneString(siteId) is None:
                self.logger.error(u"Publisher SiteDef id is None.")  # $NON-NLS-1$
                continue
            if siteId in idList:
                self.logger.warning(u"Ignoring - duplicate publisher site id %s" % siteId)  # $NON-NLS-1$
                continue
            publisherDef = self.getPublisherType(pubId)
            if publisherDef is None:
                self.logger.warning(
                    u"Ignoring - publisher type (%s) not found for site (%s)" % (pubId, siteId)
                )  # $NON-NLS-1$
                continue
            sitedef.setPublisherTypeDef(publisherDef)
            idList.append(siteId)
            rval.append(sitedef)

        return rval
Beispiel #50
0
 def _storeBlogInfo(self, documentId, blogInfo, connection):
     pubInfo = blogInfo.getPublishInfo()
     draft = 0
     if pubInfo.isDraft():
         draft = 1
     params = [
           documentId,
           blogInfo.getAccountId(),
           blogInfo.getBlogId(),
           pubInfo.getBlogEntryId(),
           getNoneString(pubInfo.getPublishedTime()),
           getNoneString(pubInfo.getSynchTime()),
           draft,
           pubInfo.getUrl()
     ]
     self._insert(u"INSERT INTO PublishedData (DocumentId, AccountId, BlogId, BlogEntryId, IssuedTime, SynchTime, Draft, Permalink) values (?, ?, ?, ?, ?, ?, ?, ?)", params, connection) #$NON-NLS-1$
 def getPublishedUrl(self, blogId):
     rval = None
     if self.isPublishedToBlog(blogId):
         pubInfo = self.getBlogInfo(blogId).getPublishInfo()
         if pubInfo is not None:
             return getNoneString( pubInfo.getUrl() )
     return rval
Beispiel #52
0
def deserializeTagSiteList(sitesCsvStr):
    u"""deserializeTagSiteList(string) -> string[]
    Deserializes the list of tag sites from a string.""" #$NON-NLS-1$
    if not getNoneString(sitesCsvStr):
        return []
    sites = sitesCsvStr.split(u",")  #$NON-NLS-1$
    return sites
Beispiel #53
0
    def _uploadStream(self, fileName, fileStream, metaData): #@UnusedVariable
        u"""_uploadStream(string, stream, ZElement) -> IZUploadResponse
        Called to upload a file stream to the remote media storage.
        Returns the URL of the uploaded file.""" #$NON-NLS-1$

        photoEditMediaLink = self._getEditMediaLinkFromMetaData(metaData)
        self._logDebug(u"upload file %s" % fileName) #$NON-NLS-1$
        self._logDebug(u"photoEditMediaLink is %s" % photoEditMediaLink) #$NON-NLS-1$
        photoEntry = None
        if photoEditMediaLink:
            # update existing file.
            photoEntry = self._getPicasaServer().updatePhotoFile(photoEditMediaLink, fileStream)
        else:
            # add new photo
            albumName = self._getAlbumName()
            self._logDebug(u"upload albumName %s" % albumName) #$NON-NLS-1$
            if not getNoneString(albumName):
                self._logError(u"Picasa web album name is required.") #$NON-NLS-1$
                raise ZException(u"Picasa web album name is required.") #$NON-NLS-1$
            albumEntry = self._getPicasaAlbumEntry(albumName)
            if not albumEntry:
                self._logError(u"Picasa web album '%s' does not exist." % albumName) #$NON-NLS-1$
                raise ZException(u"Picasa web album '%s' does not exist." % albumName) #$NON-NLS-1$
            photoEntry = self._getPicasaServer().addPhotoFile(albumEntry.getAlbumName(), fileStream)
        if not photoEntry:
            self._logError(u"Picasa web album upload failed for file %s" % fileName) #$NON-NLS-1$
            raise ZException(u"Picasa web album upload failed for file %s" % fileName) #$NON-NLS-1$

        return ZUploadResponse(photoEntry.getUrl(), metaData=photoEntry.getNode())
    def _populateServerEntry(self, zserverBlogEntry, zblog, zblogDocument,
                             zxhtmlDocument, zpubinfo):
        # Populate a ZServerBlogEntry given raven pubmeta data and post content.
        # Note: zpubinfo is valid only when updating existing post. It is None when posting new entry.
        pubmetadata = self._getPubMetaData(zblog, zblogDocument)
        title = zblogDocument.getTitle()
        content = self._transformContentForPublishing(zblog, zxhtmlDocument)

        zserverBlogEntry.setTitle(title)
        zserverBlogEntry.setContent(content)
        pubSchemaDT = pubmetadata.getPublishTime()

        # set pub time.
        if pubSchemaDT:
            # if user has specified a pub datetime, then use it.
            zserverBlogEntry.setUtcDateTime(
                pubSchemaDT.getDateTime())  # getDateTime
        elif zpubinfo:
            # if updating existing post, then use the previouslty published time
            publishedSchemaDt = zpubinfo.getPublishedTime()
            zserverBlogEntry.setUtcDateTime(publishedSchemaDt.getDateTime())
        else:
            # default to current time.
            nowDT = getCurrentUtcDateTime()
            zserverBlogEntry.setUtcDateTime(nowDT)

        zserverBlogEntry.setDraft(pubmetadata.isPublishAsDraft())
        for ravenCat in pubmetadata.getCategories():
            serverCatId = self._getServerId(ravenCat.getId())
            serverCat = ZServerBlogCategory(serverCatId, ravenCat.getName())
            self._copyAttrsFromRavenToServer(ravenCat, serverCat)
            zserverBlogEntry.addCategory(serverCat)

        # zblogDocument::getTagwordsList() -> list of ZTagwords (a ZTagwords is a list of words per site e.g. Technorati)
        listOfWords = getWordListFromZTagwords(zblogDocument.getTagwordsList())
        zserverBlogEntry.setTagwords(listOfWords)

        # custom meta data. (WP slug, password and post status
        slug = getCustomWPMetaDataAttribute(pubmetadata,
                                            u"wp_slug")  #$NON-NLS-1$
        if slug is not None:
            zserverBlogEntry.setAttribute(
                u"wp_slug", slug,
                IZBlogPubAttrNamespaces.WP_ATTR_NAMESPACE)  #$NON-NLS-1$
        status = getNoneString(
            getCustomWPMetaDataAttribute(pubmetadata,
                                         u"post_status"))  #$NON-NLS-1$
        if status:
            zserverBlogEntry.setAttribute(
                u"post_status", status,
                IZBlogPubAttrNamespaces.WP_ATTR_NAMESPACE)  #$NON-NLS-1$
        pw = getSafeString(
            getCustomWPMetaDataAttribute(pubmetadata,
                                         u"wp_password"))  #$NON-NLS-1$
        zserverBlogEntry.setAttribute(
            u"wp_password", pw,
            IZBlogPubAttrNamespaces.WP_ATTR_NAMESPACE)  #$NON-NLS-1$

        return zserverBlogEntry
 def getBlogInfo(self, blogId):
     rval = None
     if getNoneString(blogId):
         for tmp in self.getBlogInfoList():
             if tmp.getBlogId() == blogId:
                 rval = tmp
                 break
     return rval
Beispiel #56
0
 def _getLinkUrl(self, context):
     url = None
     linkContext = self._getLinkContext(context)
     if linkContext and linkContext.canEditLink():
         attrs = linkContext.getLinkAttributes()
         if u"href" in attrs:  #$NON-NLS-1$
             url = getNoneString(attrs[u"href"])  #$NON-NLS-1$
     return url
Beispiel #57
0
 def _getImageUrl(self, context):
     url = None
     imageContext = self._getImageContext(context)
     if imageContext and imageContext.canEditImage():
         attrs = imageContext.getImageAttributes()
         if attrs.has_key(u"src"):  #$NON-NLS-1$
             url = getNoneString(attrs[u"src"])  #$NON-NLS-1$
     return url
Beispiel #58
0
 def __init__(self, term, label = None, scheme = None):
     self.term = term
     self.label = label
     self.scheme = scheme
     name = getNoneString(label)
     if not name:
         name = getSafeString(term)
     ZServerBlogCategory.__init__(self, term, name)
Beispiel #59
0
 def onAddCategory(self, event): #@UnusedVariable
     text = getNoneString( self.catAddCategoryTextCtrl.GetValue())
     if text is not None:
         idx = self.catListProvider.addCategoryByName(text)
         self.refresh()
         if idx != -1:
             self._onAddCategory(idx, text)
     event.Skip()