ak_wordpress.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. """ Create posts via wordpress API
  2. *A. Kopmann 6.2.2017 (ak)*
  3. """
  4. from datetime import datetime
  5. import json
  6. from pprint import pprint
  7. from wordpress_xmlrpc import Client
  8. from wordpress_xmlrpc import WordPressPost, WordPressComment
  9. from wordpress_xmlrpc.methods.posts import GetPost, NewPost, EditPost
  10. from wordpress_xmlrpc.methods.comments import NewComment, EditComment
  11. from wordpress_xmlrpc.methods.taxonomies import GetTerms
  12. from config import *
  13. # Use Wordpress account - not the mysql credentials
  14. wp = Client(wp_api_url, wp_user, wp_password)
  15. #
  16. # Get category from slug name used in the configuration file
  17. #
  18. def wordpress_get_category(slug):
  19. """ Load taxonomy and search for the slug """
  20. catlist = wp.call(GetTerms('category'))
  21. for cat in catlist:
  22. if cat.slug == slug:
  23. return cat
  24. #
  25. # query post
  26. #
  27. def wordpress_get_post(wpid):
  28. """ Query post """
  29. try:
  30. post = wp.call(GetPost(wpid))
  31. #print post.title
  32. ret = 1
  33. except:
  34. #print "Post seems to be not available"
  35. ret = 0
  36. return ret
  37. #
  38. # create a post from a scopus query
  39. #
  40. def wordpress_post_by_scopus(data, category = []):
  41. """ Create a new post based on the Scopus information """
  42. #print data['abstracts-retrieval-response']
  43. try:
  44. coredata = data['abstracts-retrieval-response']['coredata']
  45. authors = data['abstracts-retrieval-response']['authors']['author']
  46. except KeyError:
  47. pprint(data)
  48. print ""
  49. print "Have not found authors in dataset"
  50. print " -> Is the connection to scopus broken???"
  51. return(0)
  52. # decode date
  53. tsstring = coredata['prism:coverDate'].encode('utf-8')
  54. ts = datetime.strptime(tsstring, "%Y-%m-%d").timetuple()
  55. year = ts.tm_year
  56. # Display cover date and title
  57. print("%s -- %s" % (tsstring, coredata['dc:title']))
  58. # define post structure
  59. post = WordPressPost()
  60. post.title = coredata['dc:title']
  61. post.date = ts
  62. # set the name of the post different to the title
  63. post.slug = coredata['dc:identifier']
  64. post.excerpt = authors[0]['ce:indexed-name']
  65. if len(authors) > 2:
  66. post.excerpt += u' et al.'
  67. elif len(authors) == 2:
  68. post.excerpt += u', ' + authors[1]['ce:indexed-name']
  69. post.excerpt += u', in <em>' + coredata['prism:publicationName'] + u'</em>'
  70. if 'prism:volume' in coredata:
  71. post.excerpt += u', ' + coredata['prism:volume']
  72. post.excerpt += u' (' + str(year).encode('utf-8') + u')'
  73. if 'prism:pageRange' in coredata:
  74. post.excerpt += u' ' + coredata['prism:pageRange']
  75. if 'article-number' in coredata:
  76. post.excerpt += u', ' + coredata['article-number']
  77. post.excerpt += u'.'
  78. post.content = u'<p>' + authors[0]['ce:indexed-name']
  79. authors.pop(0)
  80. if len(authors) > 20:
  81. post.content += u' et al.'
  82. else:
  83. for author in authors:
  84. post.content += u', ' + author['ce:indexed-name']
  85. post.content += u'</p>'
  86. post.content += u'<p>in <em>' + coredata['prism:publicationName'] + u'</em>'
  87. if 'prism:volume' in coredata:
  88. post.content += u', ' + coredata['prism:volume']
  89. post.content += u' (' + str(year).encode('utf-8') + u')'
  90. if 'prism:pageRange' in coredata:
  91. post.content += u' ' + coredata['prism:pageRange']
  92. if 'article-number' in coredata:
  93. post.content += u', ' + coredata['article-number']
  94. post.content += u'.'
  95. if 'prism:doi' in coredata:
  96. post.content += u' DOI:' + coredata['prism:doi']
  97. post.content += u'</p>\n\n'
  98. if 'dc:description' in coredata:
  99. post.content += u'<div class="accordion-inner"><h4>Abstract</h4>' + coredata['dc:description']
  100. if 'authkeywords' in coredata:
  101. post.content += u'\n<b>Keywords:</b> ' + coredata['authkeywords']
  102. post.content += u'</div>'
  103. if 'prism:doi' in coredata:
  104. link = u'http://dx.doi.org/' + coredata['prism:doi']
  105. post.content += u'\n\n<div class="accordion-inner"><a class="btn btn-primary" href="' + link + u'"><i class="icon-download icon-white"></i> Get it</a></div>'
  106. #print post.content
  107. #post.id = wp.call(NewPost(post)) # Creates a new post and returns the id!
  108. catlist = []
  109. for slug in category:
  110. try:
  111. cat = wordpress_get_category(slug)
  112. catlist.append(cat)
  113. except:
  114. print "Slug %s not found in Wordpress" % slug
  115. exit
  116. post.terms = catlist
  117. print post.terms
  118. taglist = []
  119. try:
  120. for tag in data['abstracts-retrieval-response']['authkeywords']['author-keyword']:
  121. try:
  122. print "Keyword: ", tag
  123. taglist.append(tag['$'].decode('utf-8','ignore'))
  124. except:
  125. print "Keyword contains special characters - droped!"
  126. pass
  127. except:
  128. # No keywords given
  129. pass
  130. post.terms_names = {
  131. 'category': ['Publications'],
  132. 'post_tag': taglist
  133. }
  134. print post.terms_names
  135. # whoops, I forgot to publish it!
  136. if len(authors) > sc_max_authors:
  137. post.post_status = 'draft' # check how to handle publication in wordpress
  138. print "Too many authors %d - set to draft" % (len(authors))
  139. else:
  140. post.post_status = 'publish' # handled as a standard publication
  141. post.comment_status = 'closed' # allow comments - may be only for scopus
  142. # Todo: this can fail! Add proper error handling
  143. post.id = wp.call(NewPost(post)) # Creates a new post and returns the id!
  144. #wp.call(EditPost(post.id, post))# Update the before created post
  145. print post.id
  146. # need to update the database !!!
  147. return post.id
  148. #
  149. # Create comments for all citations
  150. #
  151. def wordpress_comment_by_scopus(wpid, data):
  152. """ Create a new comment based on Scopus data """
  153. #print "Create Wordpress comment for post %d" % wpid
  154. #print json.dumps(data,sort_keys=True,indent=4, separators=(',', ': '))
  155. # decode date
  156. tsstring = data['prism:coverDate'].encode('utf-8')
  157. ts = datetime.strptime(tsstring, "%Y-%m-%d").timetuple()
  158. year = ts.tm_year
  159. # Display cover date and title
  160. print("%s -- %s" % (tsstring, data['dc:title']))
  161. # Create WP comment
  162. # define post structure
  163. comment = WordPressComment()
  164. comment.id = 0
  165. comment.content = ""
  166. if 'dc:creator' in data and data['dc:creator'] is not None:
  167. comment.content = data['dc:creator'] + 'et al.: '
  168. if 'prism:doi' in data and data['prism:doi'] is not None:
  169. comment.content +='<a href="http://dx.doi.org/' + data['prism:doi'] + '">' + data['dc:title'] + '</a>'
  170. else:
  171. comment.content +='<b>' + data['dc:title'] + '</b>'
  172. comment.content += ' in ' + data['prism:publicationName']
  173. if 'prism:volume' in data and data['prism:volume'] is not None:
  174. comment.content += ', ' + data['prism:volume']
  175. comment.content += ' (' + str(year).encode('utf-8') + ')'
  176. if 'prism:pageRange' in data and data['prism:pageRange'] is not None:
  177. comment.content += ' ' + data['prism:pageRange']
  178. if 'article-number' in data and data['article-number'] is not None:
  179. comment.content += ' ' + data['article-number']
  180. comment.content += '.'
  181. # Enable comments
  182. post = WordPressPost()
  183. postorig = wp.call(GetPost(wpid))
  184. post.id = wpid
  185. post.date = postorig.date
  186. post.title = postorig.title
  187. post.content = postorig.content
  188. post.comment_status = 'open' # allow comments - may be only for scopus
  189. wp.call(EditPost(wpid, post))
  190. comment.id = wp.call(NewComment(wpid, comment))
  191. # Warning: Date can only be specified in edit command
  192. comment.date_created = ts
  193. wp.call(EditComment(comment.id, comment))# Update the before created post
  194. # Close comments for scopus posts
  195. post.comment_status = 'closed' # allow comments - may be only for scopus
  196. wp.call(EditPost(wpid, post))# Update the before created post
  197. return comment.id