コード例 #1
0
    def setUp(self):
        wp = Client('http://lightcastletech.wordpress.com/xmlrpc.php',
                    '*****@*****.**', settings.WORDPRESS_PASS)
        self.all_posts = wp.call(
            GetPosts({
                'number': 100,
                'post_status': 'publish'
            }))
        self.authors = wp.call(GetAuthors())
        self.all_posts = self.all_posts[::
                                        -1]  #reverse the list of posts so that the most recent are last in the list
        for post in self.all_posts:
            for author in self.authors:
                if author.id == post.user:
                    post.author = author.display_name
#          following line sets the image variable so the posts index can display right
            if blog._get_first_image(post.content) != "None":
                post.image = blog._get_first_image(post.content)
            else:
                post.image = ""

            b = blog.Blog(title=post.title,
                          author=post.author,
                          initial_image=post.image,
                          date=post.date,
                          content=post.content)
            b.save()
コード例 #2
0
def fetchExistedTitles():
    titles = []
    posts = wp.call(GetPosts({'number': 1000}))
    for post in posts:
        titles.append(str(post.title))

    return titles
コード例 #3
0
def main():
    p = argparse.ArgumentParser(
        description='Create an embeddable page for Arsenalist videos')
    p.add_argument('-u', '--username', required=True)
    p.add_argument('-p', '--password', required=True)
    args = vars(p.parse_args())
    username = args['username']
    password = args['password']

    wp = Client('https://arsenalist.com/xmlrpc.php', username, password)
    posts = wp.call(GetPosts())
    bits = []
    for p in posts:
        custom_fields = p.custom_fields
        for cf in custom_fields:
            if cf['key'] == 'gallery_json':
                raw = json.loads(cf['value'])
                raw = raw[::-1]
                for r in raw:
                    if 'sort' not in r:
                        r['sort'] = 0
                raw = sorted(raw, key=lambda item: item['sort'], reverse=True)
                bits.extend(raw)

    print(create_embed(bits))
コード例 #4
0
def list_posts():
    posts = API.call(GetPosts())  # Defaults to post_type: post
    for post in posts:
        print(post)

    apps = API.call(GetPosts({'post_type': 'apps'}))  # Custom post type
    for app in apps:
        print(
            app.title,
            app.post_type,
            app.user,
            # app.terms_names,
            app.custom_fields)
        for term in app.terms:
            print(" - ", term.taxonomy, term.name, term.group,
                  term.taxonomy_id)
コード例 #5
0
 def _check_post(self, offset, number):
     field = {'post_type': 'post'}
     field['offset'] = offset
     field['number'] = number
     field['orderby'] = 'post_id'
     field['order'] = 'ASC'
     results = self.wpcall(GetPosts(field, result_class=WordPressPost))
     return results
コード例 #6
0
ファイル: show.py プロジェクト: zrong/wpcmd
    def _show_page(self):
        field = {'post_type': 'page'}
        field['number'] = self.args.number
        field['orderby'] = self.args.orderby
        field['order'] = self.args.order

        if self.args.query:
            return GetPost(self.get_postid(), result_class=WordPressPage)
        return GetPosts(field, result_class=WordPressPage)
コード例 #7
0
ファイル: show.py プロジェクト: zrong/wpcmd
    def _show_post(self):
        field = {}
        field['number'] = self.args.number
        field['orderby'] = self.args.orderby
        field['order'] = self.args.order

        if self.args.query:
            return GetPost(self.get_postid())
        return GetPosts(field)
コード例 #8
0
ファイル: main.py プロジェクト: GongWilliam/openhakou-os-book
def get_posts():
    print(time.strftime('%Y-%m-%d-%H-%M-%S') + "开始从服务器获取文章列表...")
    posts = wp.call(GetPosts({'post_type': 'post', 'number': 1000000000}))
    post_link_id_list = []
    for post in posts:
        post_link_id_list.append({"id": post.id, "link": post.link})
    print(post_link_id_list)
    print(len(post_link_id_list))
    return post_link_id_list
コード例 #9
0
def get_posts(request):
    wordpress_settings = get_wordpress_meta()
    wp = Client(wordpress_settings["rpc"], wordpress_settings["username"],
                wordpress_settings["password"])
    posts = wp.call(GetPosts({
        'order': 'DESC',
        'orderby': 'post_date_gmt'
    }))
    serializer = PostSerializer(posts, many=True)
    return Response(serializer.data)
コード例 #10
0
 def getPosts(self):
     r = self.wp.call(GetPosts())
     drafts = []
     published = []
     for post in r:
         if 'draft' == post.post_status:
             drafts.append(post)
         else:
             published.append(post)
     return {'drafts':drafts, 'published':published}
コード例 #11
0
def get_first_post(wordpress_settings):
    wp = Client(wordpress_settings["rpc"], wordpress_settings["username"],
                wordpress_settings["password"])
    posts = wp.call(
        GetPosts({
            'number': 1,
            'order': 'DESC',
            'orderby': 'post_date_gmt'
        }))
    serializer = PostSerializer(posts, many=True)
    return serializer.data[0]
コード例 #12
0
def deleteDraft(postname):
    offset = 0
    increment = 20
    while True:
        posts = blog.call(GetPosts({'number': increment, 'offset': offset}))
        if len(posts) == 0:
                break  # no more posts returned
        for post in posts:
                if(post.title == postname):
                    blog.call(DeletePost(post.id))
        offset = offset + increment
コード例 #13
0
def getAllPosts():
    offset = 0
    increment = 10
    while True:
        filter = {'post_type': 'product', 'offset': offset}
        postz = client.call(GetPosts(filter))
        if len(postz) == 0:
            break  # no more posts returned
        for post in postz:
            existingPostTitles.append(post.title)
        offset = offset + increment
コード例 #14
0
def get_posts(details, increment, offset):
    xmlrpc_url = '{base_url}{slash}xmlrpc.php'.format(
        base_url=details.url,
        slash='/' if not details.url.endswith('/') else '',
    )
    wp = Client(
        xmlrpc_url,
        details.username,
        details.password,
    )
    posts = wp.call(GetPosts({'number': increment, 'offset': offset}))

    return posts
コード例 #15
0
def find_id(title):
    offset = 0
    increment = 20
    while True:
        filter = {'offset': offset}
        p = wp.call(GetPosts(filter))
        if len(p) == 0:
            break  # no more posts returned
        for post in p:
            if post.title == title:
                return (post.id)
        offset = offset + increment
    return (False)
コード例 #16
0
def wordpress_public(domain="如:www.domain.com ",
                     username="******",
                     password='******',
                     title='文章标题',
                     content="文章内容",
                     tags='标签,多个标签用逗号隔开如’标签1,标签2',
                     category='分类名称'):
    import urllib, urllib2, cookielib, requests
    headers = {
        "Host":
        "%s" % domain,
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
    }
    cookieJar = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
    urllib2.install_opener(opener)
    login_data = {
        "log": "%s" % username,
        "pwd": "%s" % password,
    }
    login_data = urllib.urlencode(login_data)
    login_url = 'http://%s/wp-login.php' % domain
    req = urllib2.Request(url=login_url, data=login_data, headers=headers)
    html = urllib2.urlopen(req).read()
    url = 'http://%s/wp-admin/edit.php?s=%s' % (domain, title)
    html = opener.open(url).read()
    if 'post-title page-title column-title' in html:
        print '标题已经已经存在,跳过不发布'.decode('utf8')
    else:
        tag = []
        categorys = []
        tag.append(tags)
        categorys.append(category)
        wp = Client('http://%s/xmlrpc.php' % domain, '%s' % username,
                    '%s' % password)  #登陆后台

        wp.call(GetPosts())
        wp.call(GetUserInfo())
        post = WordPressPost()
        post.title = """%s""" % title  #文章标题
        post.content = """%s""" % content  #文章内容
        post.terms_names = {
            'post_tag':
            tag,  #标签    如果有多个标签的话需要以列表形式,如: 'post_tag': ['eo ', 'discuz'],
            'category':
            categorys,  #分类    如果是有多个分类的话需要以列表形式,如:'category': ['Introductions', 'Tests']
        }
        post.post_status = 'publish'
        wp.call(NewPost(post))
        print '发布成功,标题是:'.decode('utf8'), title.decode('utf8')
コード例 #17
0
def find_id(title):
    offset = 0
    increment = 10
    client = Client(site_host + 'xmlrpc.php', username, password)
    while True:
        filter = {'post_type': 'page'}
        p = client.call(GetPosts(filter))
        if len(p) == 0:
                break 
        for post in p:
            if post.title == title:
                return(post.id)
        offset = offset + increment
    return(False)
def main():
    blog_settings = yaml.load(Path('./blog.yml').read_text())
    wp = Client(blog_settings['xmlrpc-url'], blog_settings['username'],
                blog_settings['password'])
    articles = wp.call(GetPosts())

    [article.title for article in articles]

    post = WordPressPost()
    post.title = 'My new title'
    post.content = 'This is the body of my new post.'
    wp.call(NewPost(post))

    post.post_status = 'publish'
    wp.call(EditPost(post.id, post))
コード例 #19
0
def unlist_mls(mlsnum):
    offset = 0
    increment = 20
    while True:
        filter = {'offset': offset}
        p = wp.call(GetPosts(filter))
        if len(p) == 0:
            break  # no more posts returned
        for post in p:
            if post.content.find(mlsnum) != -1:
                post.post_status = 'unpublish'
                wp.call(posts.EditPost(post.id, post))
                return (post.id)
        offset = offset + increment
    return (False)
コード例 #20
0
    def upload (self):
        wp_url = 'http://www.py4seo.com/xmlrpc.php'
        login = '******'
        passw = '123456'
        client = Client(wp_url, login, passw)
        posts = client.call(GetPosts({'number': 10000}))
        post = WordPressPost()
        for ttl, content in self.trans_posts.items():
            post.title = ttl
            post.content = content
            post.id = client.call(NewPost(post))
            post.post_status = 'publish'
            client.call(EditPost(post.id, post))
            url = f'http://py4seo.com/?p={post.id}'

            print(f'ЗАПОСТИЛИ СТАТЬЮ С ТАЙТЛОМ {ttl}' + ' - ' + url)
コード例 #21
0
    def _show_page(self):
        field = {'post_type':'page'}
        field['number'] = self.args.number
        field['orderby'] = self.args.orderby
        field['order'] = self.args.order

        method = None
        if self.args.query:
            method = GetPost(_get_postid(), result_class=WordPressPage)
        else:
            method =  GetPosts(field, result_class=WordPressPage)
        results = self.wpcall(method)
        if results:
            self.print_results(results)
        else:
            slog.warning('No results for showing.')
コード例 #22
0
    def _show_post(self):
        field = {}
        field['number'] = self.args.number
        field['orderby'] = self.args.orderby
        field['order'] = self.args.order

        method = None
        if self.args.query:
            method = GetPost(_get_postid())
        else:
            method = GetPosts(field)
        results = self.wpcall(method)
        if results:
            self.print_results(results)
        else:
            slog.warning('No results for showing.')
コード例 #23
0
def fetch_posts(wp_client, post_status="publish", post_limit=10):
    output_list = []
    posts = wp_client.call(
        GetPosts({
            'post_status': post_status,
            'number': post_limit
        }))
    if len(posts) > 0:
        for post_data in posts:
            try:
                data_dict = get_attachments_dict(post_data)
                output_list.append(data_dict)
            except Exception as e:
                print("An error occurred: " + str(e))
                pass

    return output_list
コード例 #24
0
    def tweetDailyNews(self):
        wp = Client(self.wp_xmlrpc_url, self.wp_username, self.wp_password)

        posts = wp.call(GetPosts())
        post = posts[0]
        post_date = post.title[10:]

        match = re.search(r'<div class="tweetcenterbox">(.+)</div>',
                          post.content)

        if match:
            text = match.group(1)
            logging.debug(text)
            lead = text[:50]
            logging.debug(lead)
            status = u'Tweets about [' + self.keyword + '] on ' + post_date + ' "' + lead + u'..." ' + post.link
            logging.info(status)
            self.tweet(status)

        return
コード例 #25
0
ファイル: wordpress.py プロジェクト: eladlevyy/seo
    def get_posts(self, amount=10, status='publish'):
        config = {
            'number': amount,
            'post_status': status}

        wp = Client(self.url, self.user, self.password)
        wp_posts = wp.call(GetPosts(config))
        posts = []

        for post in wp_posts:
            posts.append(Post(
                id=post.id,
                user=post.user,
                date=post.date,
                slug=post.slug,
                title=post.title,
                content=post.content,
                excerpt=post.excerpt,
                thumbnail=post.thumbnail))

        return posts
コード例 #26
0
    def export(self, folder):
        files = []
        wp = Client(self.param['wp_url'], self.param['wp_user'],
                    self.param['wp_pw'])
        for post in wp.call(GetPosts({'post_status': 'publish'})):

            html_filename = os.path.join(folder, post.slug + '.html')
            export_filename = os.path.join(
                folder, '{}.{}'.format(post.slug, self.file_extension))
            files.append(export_filename)

            with open(html_filename, 'w', encoding="utf-8") as f:
                f.write('<h1>{}</h1>'.format(post.title))
                f.write(post.content)
            pypandoc.convert_file(html_filename,
                                  self.param['format'],
                                  outputfile=export_filename)

            os.remove(html_filename)
            self.logger.info('create file: ' + export_filename)

        return files
コード例 #27
0
 def read_posts(self):
     posts = self.API.call(GetPosts({'post_type': 'application'}))
     for post in posts:
         print(post)
コード例 #28
0
    def postNews(self, tweets):
        wp = Client(self.wp_xmlrpc_url, self.wp_username, self.wp_password)

        posts = wp.call(GetPosts())
        post = posts[0]
        post_date = post.title[10:]

        # Assuming Asia/Tokyo.
        now_tokyo = datetime.now() + timedelta(hours=9)
        today_date = now_tokyo.isoformat().decode('utf-8')[10:]

        if (post_date != today_date):
            post = WordPressPost()
            post.title = u'Tweets on ' + today_date
            post.content = '<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>'
            post.id = wp.call(NewPost(post))

        logging.info(post.id)

        htmls = post.content.split('<hr class="tweetboxdelimiter" />')
        #        logging.debug(htmls)

        tweet_ids = []

        for html in htmls:
            match = re.search(r'/status/(\d+)', html)
            if match:
                tweet_ids.append(int(match.group(1)))

        logging.info(tweet_ids)

        tmpl = u'''
<div class="tweetbox">
<div class="tweetheaderbox">
<a href="https://twitter.com/intent/user?user_id=%s" class="tweetauthorprofile"><img src="%s" /></a>
<a href="https://twitter.com/intent/user?user_id=%s" class="tweetauthorname">%s</a>
<a href="https://twitter.com/intent/user?user_id=%s" class="tweetauthorscreenname">@%s</a>
<a href="https://twitter.com/intent/user?user_id=%s" class="tweetfollow"><img src="/wp-content/themes/slight/images/twitter/bird_gray_16.png" alt="Follow" title="Follow" /></a>
</div>
<div class="tweetcenterbox">%s</div>
<div class="tweetfooterbox">
<a href="https://twitter.com/%s/status/%s" class="tweettimestamp">%s</a>
<div class="tweetactionbox">
<a href="https://twitter.com/intent/tweet?in_reply_to=%s" class="tweetreply"><img src="/wp-content/themes/slight/images/twitter/reply.png" alt="Reply" title="Reply" /></a>
<a href="https://twitter.com/intent/retweet?tweet_id=%s" class="tweetretweet"><img src="/wp-content/themes/slight/images/twitter/retweet.png" alt="Retweet" title="Retweet" /></a>
<a href="https://twitter.com/intent/favorite?tweet_id=%s" class="tweetfavorite"><img src="/wp-content/themes/slight/images/twitter/favorite.png" alt="Favorite" title="Favorite" /></a>
</div>
</div>
</div>
'''.replace("\n", "")

        new_htmls = []

        for tweet in tweets:
            if tweet.author.screen_name != u'your_twitter_username':
                if not tweet.id in tweet_ids:
                    if re.match(r'.*' + self.keyword + '.*', tweet.text):
                        logging.info(tweet.text)
                        html = tmpl % (
                            tweet.author.id, tweet.author.profile_image_url,
                            tweet.author.id, tweet.author.name,
                            tweet.author.id, tweet.author.screen_name,
                            tweet.author.id, tweet.text,
                            tweet.author.screen_name, tweet.id,
                            tweet.created_at + timedelta(hours=9), tweet.id,
                            tweet.id, tweet.id)

                        new_htmls.append(html)

        if new_htmls:
            htmls = htmls + new_htmls
            html = '<hr class="tweetboxdelimiter" />'.join(htmls)
            #            logging.debug(html)

            post.content = html
            post.post_status = 'publish'
            wp.call(EditPost(post.id, post))

        return
コード例 #29
0
ファイル: timToWp_push.py プロジェクト: 0thunder0/Spider
    def check_post(self, post_id):
        post = wp.call(GetPosts(post_id))

        pass
コード例 #30
0
def main():
    # look for command line arguments
    args = sys.argv[1:]

    if '-h' in args or '--help' in args or '-?' in args:
        helptext()
        sys.exit(0)

    if '-l' in args:
        logging = True
        logfilename = args[args.index('-l') + 1]
        trimlogfile(logfilename)
        logfile = open(logfilename, 'a')
        oldstdout = sys.stdout
        oldstderr = sys.stderr
        logsplit = LogFileSplitter(sys.stdout, logfile)
        sys.stdout = logsplit
        sys.stderr = logsplit
        print('Logging started.')

    if '-c' in args:
        configfile = args[args.index('-c') + 1]
        if not os.path.isfile(configfile):
            print(configfile + ' does not exist, create it? (Y/N):')
            if not raw_input().lower() == 'y':
                print('OK, config file will not be created')
                if logging == True:
                    sys.stdout = oldstdout
                    sys.stderr = oldstderr
                    logfile.close()
                sys.exit(0)
    else:
        configfile = '/etc/ssp_sermon_podcast.xml'

    if ('--config' in args) or not os.path.isfile(configfile):
        edit_config_file(configfile)
        print('Config file created and will be used on next run.')
        if logging:
            sys.stdout = oldstdout
            sys.stderr = oldstderr
            logfile.close()
        sys.exit(0)

    #load the config file
    if os.path.isfile(configfile):
        try:
            configET = ET.parse(configfile)
        except:
            print('Can\'t parse config file ' + configfile)
            sys.exit(1)
        config = configET.getroot()
        if not ((config.tag == 'config') and
                (config.attrib['description']
                 == 'Seriously Simple Podcasting Sermon Podcast settings')):
            print(configfile + ' is not a SSP Sermon Podcast config file.')
            if logging:
                sys.stdout = oldstdout
                sys.stderr = oldstderr
                logfile.close()
            sys.exit(1)

    #get the settings from the config
    settings = config.find('settings')

    #open the wordpress object
    wordpress_url = settings.find('wordpress_url').text
    if wordpress_url.endswith('/'):
        xmlrpc_url = wordpress_url + 'xmlrpc.php'
    else:
        xmlrpc_url = wordpress_url + '/xmlrpc.php'

    wp = Client(xmlrpc_url,
                settings.find('wordpress_user').text,
                decryptpassword(settings.find('wordpress_pass').text))

    #get a list of podcast objects
    allpodcasts = []
    interval = 20
    offset = 0
    while True:
        podcastbatch = wp.call(
            GetPosts({
                'post_type': 'podcast',
                'number': interval,
                'offset': offset
            }))
        if len(podcastbatch) == 0:
            break
        allpodcasts.extend(podcastbatch)
        offset += interval

    print('Retrieved ' + str(len(allpodcasts)) +
          ' podcasts from WordPress site.')

    #get the series settings from the config and find out which series will be podcast
    allseriesconfigs = config.findall('series_config')
    termids_to_podcast = []
    for seriesconfig in allseriesconfigs:
        termids_to_podcast.append(seriesconfig.attrib['term_id'])

    #get a list of series from the blog
    listofseriesterms = []
    interval = 20
    offset = 0
    while True:
        termsbatch = wp.call(
            GetTerms('series', {
                'number': interval,
                'offset': offset
            }))
        if len(termsbatch) == 0:
            break
        listofseriesterms.extend(termsbatch)
        offset += interval

    print('Found ' + str(len(listofseriesterms)) +
          ' podcast series on the WordPress site.')

    #find out the hierarchy of the series so we can do the lowest children first
    termpriority = {}
    term_parents = {}

    for term in listofseriesterms:
        term_parents[term.id] = term.parent
        order = 0
        parentid = term.parent
        while parentid != '0':
            order += 1
            for parentterm in listofseriesterms:
                if parentid == parentterm.id:
                    parentid = parentterm.parent
                    break
        termpriority[term.id] = order

    #so the order to approach term.ids is
    termid_order = []

    for termid, order in sorted(termpriority.iteritems(),
                                key=lambda x: x[1],
                                reverse=True):
        termid_order.append(termid)

    print('This is the order the series terms will be published:')
    print(', '.join(termid_order))

    #find which series config the posts should be published with (if any)
    podcasts_to_do = {}
    extension = extension_dot(settings.findtext('source_audio_type'))
    for termid in termid_order:
        if termid in termids_to_podcast:
            for podcast in allpodcasts:
                #check whether the podcast is flagged to be published and has a date:
                date_recorded = get_post_custom_field(podcast, 'date_recorded')
                if get_post_custom_field(podcast,
                                         'publish_now') and date_recorded:
                    podcast_termids = ['0']
                    for podcastterm in podcast.terms:
                        podcast_termids.append(podcastterm.id)
                    for podcast_termid in podcast_termids:
                        if podcast_termid in term_parents:
                            podcast_termids.append(
                                term_parents[podcast_termid])
                    if termid in podcast_termids and not podcast.id in podcasts_to_do:
                        #work out what the start of the source file name will be:
                        termid_seriesconfig = seriescfg_from_term_id(
                            allseriesconfigs, termid)
                        source_date_format = termid_seriesconfig.find(
                            'source_date_format').text
                        date_recorded_format = settings.find(
                            'date_recorded_format').text
                        sourcefile_name_start = getdatetime(
                            date_recorded, user_format=date_recorded_format
                        ).strftime(
                            source_date_format) + termid_seriesconfig.findtext(
                                'source_file_code', default='')
                        sourcepath = termid_seriesconfig.findtext(
                            'source_path')
                        #and does it exist?
                        directorylist = []
                        if os.path.exists(sourcepath):
                            #this seems to timeout sometimes, so will loop if need be:
                            retrycount = 3
                            while retrycount:
                                try:
                                    directorylist = os.listdir(sourcepath)
                                    retrycount = 0
                                except OSError as errmsg:
                                    print(errmsg)
                                    retrycount -= 1
                                    if retrycount:
                                        print('Retrying directory list...')
                        for filename in directorylist:
                            if filename[:len(sourcefile_name_start
                                             )] == sourcefile_name_start:
                                if extension:
                                    extposn = -len(extension)
                                if filename[
                                        extposn:] == extension or extension == None:
                                    ordered_podcast_termids = []
                                    for termid_again in termid_order:
                                        if termid_again in podcast_termids:
                                            ordered_podcast_termids.append(
                                                termid_again)
                                    ordered_podcast_termids.append('0')
                                    podcasts_to_do[podcast.id] = [
                                        podcast, termid_seriesconfig,
                                        os.path.abspath(
                                            os.path.join(sourcepath,
                                                         filename)),
                                        ordered_podcast_termids
                                    ]

    print('There are ' + str(len(podcasts_to_do)) +
          ' podcasts to process in this pass.')

    if len(podcasts_to_do) != 0:
        listofposttags = []
        interval = 20
        offset = 0
        while True:
            termsbatch = wp.call(
                GetTerms('post_tag', {
                    'number': interval,
                    'offset': offset
                }))
            if len(termsbatch) == 0:
                break
            listofposttags.extend(termsbatch)
            offset += interval
        posttagsdict = {}
        for posttag in listofposttags:
            posttagsdict[posttag.name.lower()] = posttag
        print('Retrieved ' + str(len(posttagsdict)) +
              ' post tags from WordPress site.')

    #iterate over the podcasts
    for podcast_id, podcast_and_config in podcasts_to_do.iteritems():
        #open the audio file
        print('\n')
        print('Now processing file ' + podcast_and_config[2])
        backuppodcast = copy.deepcopy(podcast_and_config[0])
        try:
            sourceaudio = audiotools.open(podcast_and_config[2])
            sourcepcm = sourceaudio.to_pcm()

            #calculate its loudness
            loudness = audiotools.calculate_replay_gain([sourceaudio])
            for loudnesstuple in loudness:
                gain = loudnesstuple[1]
                peak = loudnesstuple[2]
            if peak == 0:
                print('This audio file is silent, ignoring it.')
                continue

            #mix it to the specified number of channels
            gaincorrection = 0
            if settings.findtext('audiochannels') == '1':
                print('Converting to mono.')
                sourcepcm_mixed = audiotools.pcmconverter.Averager(sourcepcm)
            elif settings.findtext('audiochannels') == '2':
                print('Converting to stereo.')
                sourcepcm_mixed = audiotools.pcmconverter.Downmixer(sourcepcm)
                if sourceaudio.channels() == 1:
                    gaincorrection = 6.0
            else:
                sourcepcm_mixed = sourcepcm

            #adjust the gain to the users' preference instead of replaygain's target -20
            target_loudness = float(
                settings.findtext('target_loudness', default='-24'))
            newgain = gain + (target_loudness + 20.0) + gaincorrection
            newpeak = 1.0 / (10.0**(newgain / 20.0))
            if (peak / (10.0**(gaincorrection / 20.0))) > newpeak:
                newpeak = peak / (10.0**(gaincorrection / 20.0))
            print(
                'Normalising for gain: ' + str(round(newgain, 2)) +
                'dB, peak = ' + str(
                    round(
                        (20.0 * log10(peak /
                                      (10.0**(gaincorrection / 20.0)))), 2)) +
                'dBFS.')
            #normalise the audio to the target loudness
            sourcepcm_normalised = audiotools.replaygain.ReplayGainReader(
                sourcepcm_mixed, newgain, newpeak)

            try:
                bitspersample = int(settings.findtext('bitspersample'))
            except:
                bitspersample = None
            if bitspersample:
                print('Quantising to ' + str(bitspersample) + '-bit.')
                sourcepcm_resampled = audiotools.pcmconverter.BPSConverter(
                    sourcepcm_normalised, bitspersample)

            #make some tempfiles:
            process_tempfile = tempfile.mkstemp(
                suffix='.wav', prefix='sermon_process_tempfile')
            processed_tempfile = tempfile.mkstemp(
                suffix='.wav', prefix='sermon_processed_tempfile')
            encoded_tempfile = tempfile.mkstemp(
                suffix=extension_dot(settings.findtext('encoded_audio_type')),
                prefix='sermon_encoded_tempfile')
            print('tempfiles: ' + process_tempfile[1] + ', ' +
                  processed_tempfile[1] + ', ' + encoded_tempfile[1])

            #write the audio back out to a wave file for processing
            audiotools.WaveAudio.from_pcm(process_tempfile[1],
                                          sourcepcm_resampled)

            sourcepcm_normalised.close()
            sourcepcm_mixed.close()
            sourcepcm.close()
            sourceaudio = None

            audioparams = getaudioparams(sourcepcm_resampled)
            sourcepcm_resampled.close()
            subprocess_args = [settings.findtext('processing_utility')]
            for argsubelement in settings.findall('processing_utility_arg'):
                subprocess_args.append(
                    Template(argsubelement.text).substitute(audioparams))
            tempstring = settings.findtext('processing_utility_infile')
            if tempstring:
                subprocess_args.append(tempstring)
            subprocess_args.append(process_tempfile[1])
            tempstring = settings.findtext('processing_utility_outfile')
            if tempstring:
                subprocess_args.append(tempstring)
            subprocess_args.append(processed_tempfile[1])

            print('Now processing audio ...')

            print(
                subprocess.Popen(subprocess_args,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT,
                                 universal_newlines=True).communicate()[0])
            os.remove(process_tempfile[1])

            processedfile = audiotools.open(processed_tempfile[1])
            audioparams = getaudioparams(processedfile.to_pcm())
            subprocess_args = [settings.findtext('encoding_utility')]
            for argsubelement in settings.findall('encoding_utility_arg'):
                subprocess_args.append(
                    Template(argsubelement.text).substitute(audioparams))
            tempstring = settings.findtext('encoding_utility_infile')
            if tempstring:
                subprocess_args.append(tempstring)
            subprocess_args.append(processed_tempfile[1])
            tempstring = settings.findtext('encoding_utility_outfile')
            if tempstring:
                subprocess_args.append(tempstring)
            subprocess_args.append(encoded_tempfile[1])

            print('Now encoding audio ...')

            print(
                subprocess.Popen(subprocess_args,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT,
                                 universal_newlines=True).communicate()[0])
            os.remove(processed_tempfile[1])

            wp_details = make_podcast_dict(podcast_and_config, wp, settings)

            wp_details['post_status'] = 'publish'
            wp_details['publish_now'] = ''

            updated_podcast = publish_post(podcast_and_config, wp_details, wp,
                                           settings)
            podcast_and_config[0] = updated_podcast
            updated_details = make_podcast_dict(podcast_and_config,
                                                wp,
                                                settings,
                                                final_pass=True)

            try:
                imageurl = urllib2.urlopen(updated_details['image'])
                podcastimage = imageurl.read()
            except:
                podcastimage = False
            try:
                audioimage = [
                    audiotools.Image.new(podcastimage, u'Artwork', 0)
                ]
            except:
                audioimage = []
            outputmetadata = audiotools.MetaData(
                track_name=updated_details['title'],
                track_number=int(updated_details['episode_number']),
                album_name=updated_details['series'],
                artist_name=updated_details['preacher'],
                copyright=updated_details['copyright'],
                publisher=updated_details['publisher'],
                year=updated_details['date'].strftime('%Y'),
                date=updated_details['date_recorded'],
                comment=updated_details['content'],
                images=audioimage)
            outputfile = audiotools.open(encoded_tempfile[1])
            outputfile.set_metadata(outputmetadata)
            outputfile_seconds = int(outputfile.seconds_length())

            outputfile_name = updated_details[
                'output_file_template'] + extension_dot(
                    settings.findtext('encoded_audio_type'))

            outputfile_size = ftp_encodedfile(encoded_tempfile[1],
                                              outputfile_name,
                                              podcast_and_config[1])
            if outputfile_size == None:
                raise Exception('FTP appears not to have worked.')

            print('\n')
            print('Output file size = ' + str(outputfile_size))
            print('Output file duration = ' + str(outputfile_seconds))
            print('\n')

            os.remove(encoded_tempfile[1])

            urlpath = podcast_and_config[1].findtext('download_path')
            if not urlpath[-1] == '/':
                urlpath = urlpath + '/'
            updated_details['audio_file'] = urlpath + outputfile_name
            updated_details['filesize_raw'] = str(outputfile_size)
            mins = str(outputfile_seconds / 60)
            secs = str(outputfile_seconds % 60)
            if len(secs) == 1:
                secs = '0' + secs
            updated_details['duration'] = mins + ':' + secs

            #put the preacher in as a tag:
            updated_details['tags'] = []
            if updated_details['preacher'].lower() in posttagsdict:
                updated_details['tags'].append(
                    posttagsdict[updated_details['preacher'].lower()])
            else:
                tag = WordPressTerm()
                tag.taxonomy = 'post_tag'
                tag.name = updated_details['preacher']
                tag.id = wp.call(NewTerm(tag))
                updated_details['tags'].append(tag)
                posttagsdict[tag.name.lower()] = tag

            #put the book(s) of the bible in as tags:
            #This bit is really messy and I should try to write my own scripture regular expressions, but in the interest of speed:
            listofpassages = scriptures.extract(
                updated_details['bible_passage'])
            if 'song of songs' in updated_details['bible_passage'].lower():
                listofpassages.append(('Song of Songs', 1, 1, 1, 1))
            for passage in listofpassages:
                book = passage[0]
                if book[:4] == 'III ':
                    bookname = '3 ' + book[4:]
                elif book[:3] == 'II ':
                    bookname = '2 ' + book[3:]
                elif book[:2] == 'I ':
                    bookname = '1 ' + book[2:]
                elif book == 'Song of Solomon':
                    bookname = 'Song of Songs'
                else:
                    bookname = book
                if bookname.lower() in posttagsdict:
                    updated_details['tags'].append(
                        posttagsdict[bookname.lower()])
                else:
                    tag = WordPressTerm()
                    tag.taxonomy = 'post_tag'
                    tag.name = bookname
                    tag.id = wp.call(NewTerm(tag))
                    updated_details['tags'].append(tag)
                    posttagsdict[tag.name.lower()] = tag

            finalpost = publish_post(podcast_and_config, updated_details, wp,
                                     settings)

            print('Final Post details are as follows:\n')

            for field, contents in finalpost.struct.iteritems():
                try:
                    if type(contents) == types.StringType:
                        print(field + ' : ' + contents)
                    elif type(contents) == types.ListType:
                        for subcontents in contents:
                            print(field + ' : ' + str(subcontents))
                    elif type(contents) == types.DictType:
                        for subfield, subcontents in contents.iteritems():
                            print(field + ' : ' + subfield + ' : ' +
                                  str(subcontents))
                    elif type(contents) == types.UnicodeType:
                        print(field + ' : ' +
                              contents.encode('ascii', 'ignore'))
                    else:
                        print(field + ' : ' + str(contents))
                except:
                    print('Can\'t print field')
        except Exception as message:
            print('ERROR: Exception raised while processing that podcast:')
            print(message)
            print(
                'Attempting to restore original post prior to modification...')
            try:
                if wp.call(EditPost(backuppodcast.id, backuppodcast)):
                    print('Post restored.')
                else:
                    print('Unable to restore original post.')
            except Exception as message:
                print('Unable to restore original post: ')
                print(message)
            try:
                os.remove(encoded_tempfile[1])
            except:
                pass
            try:
                os.remove(processed_tempfile[1])
            except:
                pass
            try:
                os.remove(process_tempfile[1])
            except:
                pass

    logsplit.write('Completed with normal exit\n\n\n')
    if logging:
        sys.stdout = oldstdout
        sys.stderr = oldstderr
        logfile.close()