Source

wordpresslib / wordpresslib.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
"""
    wordpresslib.py

    WordPress xml-rpc client library
    use MovableType API

    Copyright (C) 2005 Michele Ferretti
    black.bird@tiscali.it
    http://www.blackbirdblog.it

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA    02111-1307, USA.

    XML-RPC supported methods:
        * getUsersBlogs
        * getUserInfo
        * getPost
        * getRecentPosts
        * newPost
        * editPost
        * deletePost
        * newMediaObject
        * getCategoryList
        * getPostCategories
        * setPostCategories
        * getTrackbackPings
        * publishPost
        * getPingbacks

    References:
        * http://codex.wordpress.org/XML-RPC_Support
        * http://www.sixapart.com/movabletype/docs/mtmanual_programmatic.html
        * http://docs.python.org/lib/module-xmlrpclib.html
"""

__author__ = "Michele Ferretti <black.bird@tiscali.it>"
__version__ = "$Revision: 1.0 $"
__date__ = "$Date: 2005/05/02 $"
__copyright__ = "Copyright (c) 2005 Michele Ferretti"
__license__ = "LGPL"

import os.path
import time
import xmlrpclib

class WordPressException(Exception):
    """ Custom exception for WordPress client operations """
    def __init__(self, obj):
        if isinstance(obj, xmlrpclib.Fault):
            self.id = obj.faultCode
            self.message = obj.faultString
        else:
            self.id = 0
            self.message = obj

    def __str__(self):
        return '<%s %d: \'%s\'>' % (
                self.__class__.__name__, self.id, self.message)

class WordPressBlog(object):
    """ Represents blog item """
    def __init__(self):
        self.id      = ''
        self.name    = ''
        self.url     = ''
        self.isAdmin = False
        self.xmlrpc  = ''

class WordPressUser(object):
    """ Represents user item """
    def __init__(self):
        self.id        = ''
        self.firstName = ''
        self.lastName  = ''
        self.nickname  = ''
        self.email     = ''

class WordPressCategory(object):
    """ Represents category item """
    def __init__(self):
        self.id          = 0
        self.parentId    = 0
        self.description = ''
        self.name        = ''
        self.html_url    = ''
        self.rss_url     = ''

class WordPressTag(object):
    """ Represents tag item """
    def __init__(self):
        self.id       = ''
        self.name     = ''
        self.count    = 0
        self.slug     = ''
        self.html_url = ''
        self.rss_url  = ''

class WordPressPost(object):
    """ Represents post item """
    def __init__(self):
        self.id            = 0
        self.title         = ''
        self.date          = None
        self.permaLink     = ''
        self.description   = ''
        self.textMore      = ''
        self.excerpt       = ''
        self.link          = ''
        self.categories    = []
        self.tags          = []
        self.user          = ''
        self.allowPings    = False
        self.allowComments = False

class WordPressClient(object):
    """ Client for connect to WordPress XML-RPC interface """

    def __init__(self, url, user, password):
        self.url        = url
        self.user       = user
        self.password   = password
        self.blogId     = 0
        self.categories = None
        self.tags       = None
        self._server    = xmlrpclib.ServerProxy(
            self.url, use_datetime=True)

    def _filterPost(self, post):
        """ Transform post struct in WordPressPost instance """
        postObj               = WordPressPost()
        postObj.permaLink     = post['permaLink']
        postObj.description   = post['description']
        postObj.title         = post['title']
        postObj.excerpt       = post['mt_excerpt']
        postObj.user          = post['userid']
        postObj.date          = time.strptime(
                str(post['dateCreated']), "%Y%m%dT%H:%M:%S")
        postObj.link          = post['link']
        postObj.textMore      = post['mt_text_more']
        postObj.allowComments = post['mt_allow_comments'] == 1
        postObj.id            = int(post['postid'])
        postObj.categories    = post['categories']
        postObj.allowPings    = post['mt_allow_pings'] == 1
        return postObj

    def _filterCategory(self, cat):
        """ Transform category struct in WordPressCategory instance """
        catObj      = WordPressCategory()
        catObj.id   = int(cat['categoryId'])
        catObj.parentId = int(cat['parentId'])
        catObj.description = cat['description']
        catObj.name = cat['categoryName']
        catObj.html_url = cat['htmlUrl']
        catObj.rss_url = cat['rssUrl']
        return catObj

    def _filterTag(self, tag):
        """ Transform tag struct in WordPressTag instance """
        tagObj          = WordPressTag()
        tagObj.id       = int(tag['tag_id'])
        tagObj.name     = tag['name']
        tagObj.count    = tag['count']
        tagObj.slug     = tag['slug']
        tagObj.html_url = tag['html_url']
        tagObj.rss_url  = tag['rss_url']
        return tagObj

    def selectBlog(self, blogId):
        self.blogId = blogId
        found = False
        for blog in self.getUsersBlogs():
            if blogId == blog.id:
                self.blogId  = blogId
                self.url     = blog.xmlrpc
                self._server = xmlrpclib.ServerProxy(
                    self.url, use_datetime=True)
                found = True

        if not found:
            raise WordPressException('Blog not found')

    def supportedMethods(self):
        """ Get supported methods list """
        return self._server.mt.supportedMethods()

    def getLastPost(self):
        """ Get last post """
        return tuple(self.getRecentPosts(1))[0]

    def getRecentPosts(self, numPosts=5):
        """ Get recent posts """
        try:
            posts = self._server.metaWeblog.getRecentPosts(
                    self.blogId, self.user, self.password, numPosts)
            for post in posts:
                yield self._filterPost(post)
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def getPost(self, postId):
        """ Get post item """
        try:
            return self._filterPost(
                    self._server.metaWeblog.getPost(
                            str(postId), self.user, self.password))
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def getUserInfo(self):
        """ Get user info """
        try:
            userinfo = self._server.blogger.getUserInfo(
                    '', self.user, self.password)
            userObj           = WordPressUser()
            userObj.id        = userinfo['userid']
            userObj.firstName = userinfo['firstname']
            userObj.lastName  = userinfo['lastname']
            userObj.nickname  = userinfo['nickname']
            userObj.email     = userinfo['email']
            return userObj
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def getUsersBlogs(self):
        """ Get blog's users info """
        try:
            blogs = self._server.wp.getUsersBlogs(self.user, self.password)
            for blog in blogs:
                blogObj         = WordPressBlog()
                blogObj.id      = blog['blogid']
                blogObj.name    = blog['blogName']
                blogObj.isAdmin = blog['isAdmin']
                blogObj.url     = blog['url']
                blogObj.xmlrpc  = blog['xmlrpc']
                yield blogObj
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def newPost(self, post, publish):
        """ Insert new post """
        blogContent = {
            'title' : post.title,
            'description' : post.description,
            'mt_keywords': post.tags,
        }

        if post.date is not None:
            blogContent['dateCreated'] = post.date

        # add categories
        categories = []
        for cat in post.categories:
            categories.append({'categoryId' : cat, 'isPrimary': 0})

        # insert new post
        idNewPost = int(
                self._server.metaWeblog.newPost(
                        self.blogId, self.user, self.password, blogContent, 0))

        # set categories for new post
        self.setPostCategories(idNewPost, categories)

        # publish post if publish set at True
        if publish:
            self.publishPost(idNewPost)

        return idNewPost

    def getPostCategories(self, postId):
        """ Get post's categories """
        try:
            categories = self._server.mt.getPostCategories(
                    postId, self.user, self.password)
            for cat in categories:
                yield self._filterCategory(cat)
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def setPostCategories(self, postId, categories):
        """ Set post's categories """
        self._server.mt.setPostCategories(
                postId, self.user, self.password, categories)

    def editPost(self, postId, post, publish):
        """ Edit post """
        blogcontent = {
            'title'          : post.title,
            'description'    : post.description,
            'permaLink'      : post.permaLink,
            'mt_allow_pings' : post.allowPings,
            'mt_text_more'   : post.textMore,
            'mt_excerpt'     : post.excerpt
        }

        if post.date:
            blogcontent['dateCreated'] = xmlrpclib.DateTime(post.date)

        # add categories
        categories = []
        for cat in post.categories:
            categories.append({'categoryId' : cat, 'isPrimary': 0})

        result = self._server.metaWeblog.editPost(
                postId, self.user, self.password, blogcontent, 0)

        if result == 0:
            raise WordPressException('Post edit failed')

        # set categories for new post
        self.setPostCategories(postId, categories)

        # publish new post
        if publish:
            self.publishPost(postId)

    def deletePost(self, postId):
        """ Delete post """
        try:
            return self._server.blogger.deletePost(
                    '', postId, self.user, self.password)
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def getTags(self):
        """ Get blog's tag list """
        try:
            if not self.tags:
                self.tags = []
                tags = self._server.wp.getTags(
                    self.blogId, self.user, self.password)
                for tag in tags:
                    self.tags.append(self._filterTag(tag))

            return self.tags
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def getCategories(self):
        """ Get blog's categories list """
        try:
            if not self.categories:
                self.categories = []
                categories = self._server.wp.getCategories(
                        self.blogId, self.user, self.password)
                for cat in categories:
                    self.categories.append(self._filterCategory(cat))

            return self.categories
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def getCategoryIdFromName(self, name):
        """ Get category id from category name """
        for c in self.getCategories():
            if c.name == name:
                return c.id

    def getTrackbackPings(self, postId):
        """ Get trackback pings of post """
        try:
            return self._server.mt.getTrackbackPings(postId)
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def publishPost(self, postId):
        """ Publish post """
        try:
            return (self._server.mt.publishPost(
                            postId, self.user, self.password) == 1)
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def getPingbacks(self, postUrl):
        """ Get pingbacks of post """
        try:
            return self._server.pingback.extensions.getPingbacks(postUrl)
        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)

    def newMediaObject(self, mediaFileName):
        """ Add new media object (image, movie, etc...) """
        try:
            f = file(mediaFileName, 'rb')
            mediaBits = f.read()
            f.close()

            mediaStruct = {
                'name' : os.path.basename(mediaFileName),
                'bits' : xmlrpclib.Binary(mediaBits)
            }

            result = self._server.metaWeblog.newMediaObject(
                    self.blogId, self.user, self.password, mediaStruct)
            return result['url']

        except xmlrpclib.Fault, fault:
            raise WordPressException(fault)
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.