Beispiel #1
0
def post_file(wp, f, t, y, m, d):
    p = WordPressPost()
    p.title = t
    p.content = slurp(f)
    # All 3 sites are configured to UTC
    if re.search('deutsche', f):
        p.date = datetime(y, m, d, 4)  #  4am UTC is 5am in UTC+1=Berlin
    else:
        p.date = datetime(y, m, d, 10)  # 10am UTC is 5am eastern, 2am pacific
    p.date_modified = p.date
    p.post_status = 'publish'
    p.comment_status = 'closed'
    if wp:
        wp.call(NewPost(p))
Beispiel #2
0
def postWordpress(item):

    post = WordPressPost()
    post.title = item.title
    post.content = item.movieUrl
    if item.category == "":
        post.terms_names = {'post_tag': item.tags}
    else:
        category = []
        category.append(item.category)
        post.terms_names = {'post_tag': item.tags, 'category': category}
    post.slug = '[input your prameter]'

    # 投稿時間
    # 現在時間で投稿
    post.date = datetime.now()
    # 予約投稿の場合(例:2017年2月2日0時0分0秒0マイクロ秒)
    #month = random.randint(1,10)
    #day = random.randint(1,22)
    #post.date = datetime(2018, month, day, 0, 0, 0, 0)

    # 投稿する。
    # ステータスを公開済にする。
    post.post_status = 'publish'
    # これなら下書き指定
    # post.post_status = 'draft'

    post.thumbnail = getMediaId(item)
    wp.call(NewPost(post))
    def insert_post(self, joomla_post, category_id):

        client = self.get_client()
        post = WordPressPost()
        post.title = joomla_post.get_title()

        text_to_replace = joomla_post.get_introtext()

        text_to_replace = str(text_to_replace).replace("href=\"images/",
                                                       "href=\"/images/")

        post.content = str(text_to_replace).replace("src=\"images/",
                                                    "src=\"/images/")

        post.date = joomla_post.get_created()

        post.thumbnail = self.post_thumbnail(joomla_post.get_id())['id']

        post.post_status = "publish"

        category = client.call(taxonomies.GetTerm('category', category_id))

        post.terms.append(category)

        client.call(NewPost(post))

        return post
def make_post(content, categorys='0', tags='0', date=None):
    '''
    :param content: dict() formatado corretamente
    :param categorys: lista com as categorias do post
    :param tags: lista com as tags do post
    :param date: data para o post ser publicado ( formato datetime.datetime())
    :return:
    '''
    #URL DO SITE, USUARIO , SENHA !!!
    wp = Client(authData['url'] + '/xmlrpc.php', authData['adminUsername'],
                authData['adminPassword'])
    post = WordPressPost()
    post.title = content['title']
    post.content = content['body']

    if tags[0] != '0':

        post.terms_names = {'post_tag': tags}
    try:
        categorys[0] == 0
    except IndexError:
        pass
    else:
        if categorys[0] != '0':
            post.terms_names = {'category': categorys}

    # Lets Now Check How To Upload Media Files
    filename = content['image']
    data = {
        'name': content['title'] + '.jpeg',
        'type': 'image/jpeg'  # Media Type
    }
    # Now We Have To Read Image From Our Local Directory !
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    attachment_id = response['id']

    # Above Code Just Uploads The Image To Our Gallery
    # For Adding It In Our Main Post We Need To Save Attachment ID
    post.thumbnail = attachment_id

    #deletando do pc a imagem
    remove(filename)

    #setando para o post ser publicado (nao ficar de rascunho)
    post.post_status = 'publish'

    # marcando p/ o post ser postado na data desejada
    if date != None:
        post.date = date
    post.id = wp.call(posts.NewPost(post))
    # Set Default Status For Post .i.e Publish Default Is Draft

    # We Are Done With This Part :) Lets Try To Run It
    if not date:
        print(post.title, " Postado com sucesso !")
    if date:
        print(post.title, " Vai ser postado em ", date, '!')
Beispiel #5
0
def create_wordpress_post(config, video_url, audio_url, metadata):
    """ creates a wordpress post with the embedded video and Audio """
    import datetime
    from wordpress_xmlrpc import Client, WordPressPost
    from wordpress_xmlrpc.methods import posts

    wordpress_handle = Client(config["wordpress"]["url"] + "/xmlrpc.php",
                              config["wordpress"]["user"],
                              config["wordpress"]["password"])

    if video_url is not None:
        video_html = "<div>[iframe src=\"https://player.vimeo.com" + \
            video_url + "\" width=\"" + config["wordpress"]["video_width"] + \
            "\" height=\"" + config["wordpress"]["video_height"] + "\" \
            frameborder=\"0\" allowfullscreen=\"allowfullscreen\"]</div>"

    else:
        video_html = "<div> Es tut uns Leid, aus technischen Gr&uuml;nden gibt \
            es zu diesem Gottesdienst leider kein Video</div>"

    if audio_url is not None:
        download_html = "<a style=\"text-decoration:none; background-color:" +\
            config["wordpress"]["download_button_color"] +\
            "; border-radius:3px; padding:5px; color:#ffffff; \
            border-color:black; border:1px;\" href=\""                                                       + audio_url +\
            "\" title=\"" + config["Wordpress"]["download_button_text"] + \
            "\" target=\"_blank\">" +\
            config["wordpress"]["download_button_text"] + "</a>"
        audio_html = "<div><h3>Audiopredigt:</h3><audio controls src=\"" + \
            audio_url + "\"></audio></div>"
    else:
        audio_html = "<div> Es tut uns Leid, aus technischen Gr&uuml;nden gibt \
            es zu diesem Gottesdienst leider keine Tonaufnahme</div>"

        download_html = ""

    if (video_url is None) and (audio_url is None):
        video_html = "<div> Es tut uns Leid, aus technischen Gr&uuml;nden gibt \
            es zu diesem Gottesdienst leider kein Video und keine Tonaufnahme\
            </div>"

        download_html = ""
        audio_html = ""

    date_time = datetime.datetime(metadata["date"].year,
                                  metadata["date"].month, metadata["date"].day,
                                  config["sermon_start_utc"])

    post = WordPressPost()
    post.title = metadata["title"] + " // " + metadata["preacher"]
    post.content = video_html + audio_html + download_html
    post.date = date_time
    post.terms_names = {
        'post_tag': [metadata["title"], metadata["preacher"]],
        'category': [config["wordpress"]["category"]],
    }
    post.post_status = 'publish'
    post.id = wordpress_handle.call(posts.NewPost(post))
Beispiel #6
0
 def submit(self, content):
     client = Client('http://域名或ip/xmlrpc.php', '用户名', '密码')
     post = WordPressPost()
     # 设置标题
     title = '{} - 今日更新'.format(self.today)
     post.title = title
     post.content = content
     post.date = datetime.datetime.now() - datetime.timedelta(hours=8)
     # 添加标签设置分类目录
     post.terms_names = {'post_tag': ['知乎', '每日更新'], 'category': ['知乎']}
     post.id = client.call(posts.NewPost(post))
     post.post_status = 'publish'
     status = client.call(posts.EditPost(post.id, post))
     return status
Beispiel #7
0
def wp_post_update(request, post_id):
    """
    Update WordPress post using Post object and HTML
    
    Primarily for 'Update This Post' button AJAX function in :view:`post_generator.views.post.post_view`
    
    :param post_id: :model:`post_generator.Post` to update WP post with
    :type post_id: :model:`post_generator.Post`
    """

    # TODO: add case for GET request
    if request.method == 'POST':
        client = Client(os.environ['POSTGEN_WP_TARGET'],
                        os.environ['POSTGEN_WP_USER'],
                        os.environ['POSTGEN_WP_PASS'])
        post_obj = Post.objects.get(pk=post_id)

        # Generate Multilingual title
        post_title = post_obj.title.english
        if post_obj.title.somali:
            post_title += ' (' + post_obj.title.somali + ')'
        if post_obj.title.french or post_obj.title.french_feminine:
            post_title += ' ' + (post_obj.title.french
                                 or post_obj.title.french_feminine)
        if post_obj.title.arabic:
            post_title += ' ' + post_obj.title.arabic
        post_title += ' - PostGen'

        # Pull WP post ID from stored link
        matches = re.search('.*=(\d+)$', post_obj.link)
        wp_post_id = matches.group(1)

        # Create new WP post object with data
        wp_post = WordPressPost()
        wp_post.title = post_title
        wp_post.content = request.POST['post-content']
        wp_post.date = post_obj.pub_date

        # Retrieve current post data via WP XML-RPC API
        # - Used to determine whether featured_image_id data should be included
        #   - Avoids error from setting featured_image_id to the one already attached
        current_post = client.call(posts.GetPost(wp_post_id))
        if not current_post.thumbnail or current_post.thumbnail[
                'attachment_id'] != str(post_obj.featured_image_id):
            wp_post.thumbnail = str(post_obj.featured_image_id)

        # Update WP post and return status=True via JSON
        client.call(posts.EditPost(wp_post_id, wp_post))
        return HttpResponse(json.dumps({'status': True}),
                            content_type='application/json')
Beispiel #8
0
    def toWordPressPost(self):
        post = WordPressPost()

        if self.title:
            post.title = self.title

        if self.content:
            post.content = self.content

        post.date = self.published
        post.date_modified = self.updated
        post.comment_status = True

        post.post_status = 'publish'
        return post
Beispiel #9
0
    def post_event(self, indico_event):
        post_view = IndicoEventWordpressPostView(indico_event)

        post = WordPressPost()

        post.title = post_view.get_title()
        post.date = post_view.get_date()
        post.content = post_view.get_content()

        post.post_status = 'publish'
        post.comment_status = 'closed'

        post_id = self.client.call(NewPost(post))

        return post_id
Beispiel #10
0
 def newPost(self, title, content, category=None):
     try:
         post = WordPressPost()
         post.title = title
         post.content = content
         post.date = datetime.datetime.now()
         post.post_status = 'publish'
         if category is not None:
             post.terms_names = {'category': category}
         postID = self.client.call(NewPost(post))
         wpPost = self.client.call(GetPost(postID))
         return self.baseURL + "/" + wpPost.slug
     except Exception as e:
         print(e)
         print("Unable to post!")
def Ssubmit(Tittle, Content, Time):
    wp = Client('http://caowenbo.top/xmlrpc.php', 'admin', 'password')

    post = WordPressPost()
    post.title = Tittle
    post.content = Content
    post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
    post.date = datetime.strptime(Time, '%Y-%m-%d')  # 发布时间
    post.terms_names = {
        #'post_tag': ['test', 'firstpost'],  # 文章所属标签,没有则自动创建
        'category': ['解题报告']  # 文章所属分类,没有则自动创建
    }
    post.id = wp.call(posts.NewPost(post))


#Ssubmit('asd','asd','2000-1-1')
Beispiel #12
0
def create_new_post(wp_instance, title='', content='', author='', tags=[], category=['USAF']):
    post = WordPressPost()

    post.title = title

    content = reformat_url_with_htmltag(content)

    post.content = content

    tags.append(author)

    tags = tags + generate_tags(content)

    category.append(author)

    # By far, only classify the 'Kadena' and 'Andersen' AFB
    if 'Kadena' in tags:
        category.append('Kadena')

    if 'Andersen' in tags:
        category.append('Andersen')

    post.terms_names = {
        'post_tag': tags,
        'category': category
    }

    post.post_status = 'publish'

    # insert the new post
    post_id = wp_instance.call(NewPost(post))

    # update the published date to the tweet datetime
    re_object = re.compile('(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s.*\s\d{4}')

    original_time = re_object.search(content).group()

    post.date = parse_post_formated_time(original_time)

    post.date_modified = post.date

    # update the post author to the tweet screen name
    post.post_author = 2

    wp_instance.call(EditPost(post_id, post))

    return post_id
 def process_item(self, item, spider):
     post = WordPressPost()
     post.title = item['title']
     post.content = item['content'] + settings.get('GOTO_SOURCE',
                                                   "[%s]") % item['link']
     post.date = datetime.datetime.strptime(item['publish_date'],
                                            "%Y-%m-%d %H:%M")
     post.terms_names = {
         'post_tag':
         item['tag'],
         'category':
         item['category'] if len(item['category']) > 0 else ['gist'],
     }
     post.post_status = 'publish'
     post.thumbnail = self.create_thumbnail(item)
     post.id = self.client.call(posts.NewPost(post))
     return item
Beispiel #14
0
 def process_post(self, content) -> Optional[WordPressPost]:
     """Create a wordpress post based on pelican content"""
     if content.status == "draft":
         return None
     post = WordPressPost()
     post.title = content.title
     post.slug = content.slug
     post.content = content.content
     # this conversion is required, as pelican uses a SafeDateTime
     # that python-wordpress-xmlrpc doesn't recognize as a valid date.
     post.date = datetime.fromisoformat(content.date.isoformat())
     post.term_names = {
         "category": [content.category.name],
     }
     if hasattr(content, "tags"):
         post.term_names["post_tag"] = [tag.name for tag in content.tags]
     return post
Beispiel #15
0
 def process_item(self, item, spider):
     wp_filename = item.filename('wp')
     if os.path.exists(wp_filename):
         with open(wp_filename) as fh:
             post = pickle.load(fh)
             fh.close()
             # #
             # Here one might update or fix things
             if False:
                 post.terms_names = {
                     'category': [item['source_name'].title()],
                     'post_tag': get_place_post_tag_names(item['place'])
                 }
                 self.client.call(posts.EditPost(post.id, post))
                 pass
             pass
         pass
     else:
         post = WordPressPost()
         post.title = item['headline']
         try:
             post.content = item['body']
         except KeyError:
             return None
         try:
             item['place']
         except KeyError:
             item['place'] = ""
         post.terms_names = {
             'category': [item['source_name'].title()],
             'post_tag': get_place_post_tag_names(item['place'])
         }
         post.link = item['source_url']
         post.date = item['time']
         post.post_status = 'publish'
         post.id = self.client.call(posts.NewPost(post))
         with open(wp_filename, 'wb') as fh:
             pickle.dump(post, fh)
             fh.close()
         pass
     return item
     pass
Beispiel #16
0
def _add_blogpost(post_data):
    '''
    Adds a blog post parsed from blog.blogpost

    Model published status codes are as follows:  PUBLISHED = 1, DRAFT = 2, DELETED = 3

    :param post_data: Python dict of post structure.  See modelsamples/blogpost_sample.txt for structure.
    :return:
    '''
    post = WordPressPost()
    post.post_type = 'news'
    post.title = post_data['fields']['title']
    post.content = post_data['fields']['content']
    post.date = _return_datetime(post_data['fields']['publish_date'])
    post.date_modified = _return_datetime(post_data['fields']['updated'])
    post.slug = post_data['fields']['slug']
    if post_data['fields']['status'] == 2:
        post.post_status = 'publish'
    # Assign Author
    if post_data['fields']['user']:
        wp_userid = _get_wordpress_user_id_by_email(
            _get_django_user_email_by_id(post_data['fields']['user']))
        if wp_userid:
            post.user = wp_userid
    # TODO set catagories and tags to proper taxonomy
    # post.terms_names = {
    #     'category': ['Blogpost']
    # }
    # if post_data['fields']['categories']:
    #     categories = []
    #     for category in dp.get_content(DJANGO_DATA, 'blog.blogcategory'):
    #         if category['pk'] in post_data['fields']['categories']:
    #             categories.append(category['fields']['title'])
    #     post.terms_names['post_tag'] = categories
    try:
        if post_data['fields']['status'] != 3:
            post.id = API.call(NewPost(post))
            print("created post", post.id, post.title)
    except Fault as err:
        pprint(post)
        print(err.faultCode, err.faultString)
Beispiel #17
0
    def create_event_post(self, event: Event) -> None:
        images = self.get_event_photos(year=event.year,
                                       event_number=event.event_number,
                                       is_planned=event.is_planned)

        post = WordPressPost()
        post.post_status = 'publish'
        post.title = event.title
        post.content = event.get_content(images=images)

        post_date = event.date
        if post_date:
            post.date = datetime(year=post_date.year,
                                 month=post_date.month,
                                 day=post_date.day)

        post.terms_names = _get_tags(year=event.year,
                                     is_planned=event.is_planned)

        post_id = self._client.call(NewPost(post))
        notice('Imported post {}. {}'.format(post_id, event))
Beispiel #18
0
def uploadPost(postType, artist, album, song, artwork, connection):
    albumType, releaseDate = getInfo(artist, album)
    post = WordPressPost()
    post.post_type = 'download'
    if postType == 'bundle':
        post.title = album
    else:
        post.title = song
        post.content, keyword = getContent(artist, album, song)
    post.date = datetime.datetime.strptime(releaseDate, '%Y.%m.%d')
    post.terms = wp.call(
        taxonomies.GetTerms('download_artist', {'search': artist}))
    post.thumbnail = artwork
    post.custom_fields = []
    post.post_status = 'publish'
    post.custom_fields.append({'key': 'year', 'value': releaseDate})
    post.custom_fields.append({'key': 'music_type', 'value': postType})
    post.id = wp.call(posts.NewPost(post))
    with connection.cursor() as cursor:
        if postType == 'bundle':
            sql = 'INSERT INTO `upload_info` (`item_type`, `album_type`, `artist`, `album`, `post_title`, `release_date`, `thumbnail_id`, `post_id`, `published`, `updated_at`) VALUES (%s, %s, %s,%s,%s,%s,%s,%s,%s, now())'
            cursor.execute(sql,
                           (postType, albumType, artist, album, post.title,
                            post.date, post.thumbnail, post.id, '1'))
        else:
            sql1 = 'INSERT INTO `upload_info` (`item_type`, `album_type`, `artist`, `album`, `song`, `post_title`, `release_date`, `thumbnail_id`, `post_id`, `published`, `updated_at`) VALUES (%s, %s, %s,%s,%s,%s,%s,%s,%s,%s, now())'
            sql2 = 'INSERT INTO `wp9r_postmeta` (`post_id`, `meta_key`, `meta_value`) VALUES (%s, "_yoast_wpseo_focuskw_text_input", %s)'
            sql3 = 'INSERT INTO `wp9r_postmeta` (`post_id`, `meta_key`, `meta_value`) VALUES (%s, "_yoast_wpseo_focuskw", %s)'
            cursor.execute(
                sql1, (postType, albumType, artist, album, song, post.title,
                       post.date, post.thumbnail, post.id, '1'))
            cursor.execute(sql2, (post.id, keyword))
            cursor.execute(sql3, (post.id, keyword))
    if postType == 'bundle':
        print('Upload Successful for album %s - %s. Post id = %s' %
              (artist, album, post.id))
    else:
        print('Upload Successful for song %s - %s. Post id = %s' %
              (artist, song, post.id))
    return post.id
def make_post(title, body, img):
    p = requests.get(img)
    out = open("img.jpg", "wb")
    out.write(p.content)
    out.close()

    client = Client('http://yourdomain.com/xmlrpc.php', 'login', 'password')

    # set to the path to your file
    filename = 'img.jpg'

    # prepare metadata
    data = {
        'name': 'img.jpg',
        'type': 'image/jpeg',
    }
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())

    response = client.call(media.UploadFile(data))
    # response == {
    #       'id': 6,
    #       'file': 'picture.jpg'
    #       'url': 'http://www.yourdomain.com/wp-content/uploads/2012/04/16/picture.jpg',
    #       'type': 'image/jpeg',
    # }
    attachment_id = response['id']

    post = WordPressPost()
    post.title = title  #str
    post.content = body  #str Text or HTML
    post.id = client.call(posts.NewPost(post))
    post.post_status = 'publish'
    post.thumbnail = attachment_id
    post.terms_names = {
        'post_tag': ['tagA', 'another tag'],
        'category': ['My Category'],
    }
    post.date = datetime.now(pytz.timezone('Etc/GMT+0'))
    client.call(posts.EditPost(post.id, post))
Beispiel #20
0
def _add_application(app_data):
    '''
    Adds an application parse from apps.application

    :param app_data: Python dict of application structure. See modelsamples/application_sample.txt
    :return:
    '''
    post = WordPressPost()
    post.post_type = 'application'
    post.title = app_data['fields']['name']
    post.slug = app_data['fields']['slug']
    post.content = _format_app_content(app_data)
    post.date = _return_datetime(app_data['fields']['created'])
    post.date_modified = _return_datetime(app_data['fields']['updated'])

    # TODO assign to proper taxonomies once those are in.

    # Assign Author
    if app_data['fields']['owner']:
        wp_userid = _get_wordpress_user_id_by_email(
            _get_django_user_email_by_id(app_data['fields']['owner']))
        if wp_userid:
            post.user = wp_userid

    # Assign Categories and Tags
    post.terms_names = _parse_taxonomies(app_data)

    # Put the previous page url in a custom field.
    legacy_url = "https://www.us-ignite.org/apps/%s/" % (
        app_data['fields']['slug'])
    post.custom_fields = [{'key': 'legacy_url', 'value': legacy_url}]

    # Set publish status and push to site
    if app_data['fields']['status'] == 1:
        post.post_status = 'publish'
    try:
        if app_data['fields']['status'] != 3:
            post.id = API.call(NewPost(post))
    except Fault as err:
        pprint(err.faultString)
Beispiel #21
0
def createQuote(url):
    tags = "random"
    name = str(random.randint(100, 10000)) + '.png'
    attachment_id = ''
    idata = {
        'name': name,
        'type': 'image/png',  # mimetype
    }
    if (url['categories']):
        categories = ','.join(url['categories'])
    res = urllib.request.urlretrieve(
        'https://source.unsplash.com/800x400/?' + categories,
        "./img-quote/" + name)
    if (res):
        with open('./img-quote/' + name, 'rb') as img:
            idata['bits'] = xmlrpc_client.Binary(img.read())
        response = client.call(media.UploadFile(idata))
        attachment_id = response['attachment_id']

    print(bcolors.OKBLUE + " creating post " + bcolors.ENDC)
    postDate = datetime.now()
    post = WordPressPost()
    post.title = url['id']
    post.post_type = 'quotes'
    post.content = url['quote']
    post.post_status = "publish"
    post.author = "admin"
    post.date = postDate
    post.thumbnail = attachment_id
    post.terms_names = {
        'quotes_category': url['categories'],
    }
    post.custom_fields = []
    post.custom_fields.append({'key': 'q_author', 'value': url['author-id']})
    addpost = client.call(posts.NewPost(post))
    if (addpost):
        print(bcolors.OKGREEN + "post created " + bcolors.ENDC)
Beispiel #22
0
    def post_article(self, wpUrl, wpUserName, wpPassword, articleTitle,
                     articleCategories, articleContent, articleTags, PhotoUrl,
                     date, logo_name, post_name):
        self.path = os.path.join(os.getcwd(), "00000001.jpg")
        self.articlePhotoUrl = PhotoUrl
        self.wpUrl = wpUrl
        self.wpUserName = wpUserName
        self.wpPassword = wpPassword
        #Download File
        print self.articlePhotoUrl
        #r = requests.get(self.articlePhotoUrl,headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:16.0) Gecko/20100101 Firefox/16.0,gzip(gfe)'})
        #with open('test.jpg', "wb") as f:
        #    f.write(r.content)
        from PIL import Image
        from StringIO import StringIO
        import urllib2
        #content = r.content
        self.articlePhotoUrl = self.articlePhotoUrl.replace(
            'www.macappdownload.net', 'www.macbed.com')
        print self.articlePhotoUrl
        print 'vvvvvvvvvvvvvvvvvvvvv'
        r = requests.get(
            self.articlePhotoUrl,
            headers={
                'User-Agent':
                'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:16.0) Gecko/20100101 Firefox/16.0,gzip(gfe)'
            })
        #content = urllib2.urlopen(self.articlePhotoUrl).read()

        im = Image.open(StringIO(r.content))
        #im.seek(0)
        #im.verify()

        rgb_im = im.convert('RGB')
        self.path = os.path.join(os.getcwd(), 'image', logo_name)
        print self.path
        rgb_im.save(self.path)

        #Upload to WordPress
        client = Client(self.wpUrl, self.wpUserName, self.wpPassword)
        filename = self.path

        # prepare metadata
        data = {'name': logo_name, 'type': 'image/jpeg'}

        # read the binary file and let the XMLRPC library encode it into base64
        print filename
        with open(filename, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = client.call(media.UploadFile(data))
        print 'aaaaaaaaaaaa'
        attachment_id = response['id']
        #Post
        post = WordPressPost()
        post.title = articleTitle

        try:
            post.date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M")
            post.date_modified = datetime.datetime.strptime(
                date, "%Y-%m-%d %H:%M")
        except:
            post.date = datetime.datetime.strptime(date, "%Y-%m-%d")
            post.date_modified = datetime.datetime.strptime(date, "%Y-%m-%d")
        post.slug = post_name
        post.comment_status = "open"

        post.content = articleContent
        post.terms_names = {
            'post_tag': articleTags,
            'category': articleCategories
        }
        post.post_status = 'publish'
        post.thumbnail = attachment_id
        post.id = client.call(posts.NewPost(post))
        print 'Post Successfully posted. Its Id is: ', post.id

        if post.content.find('https://nmac.to') != -1:
            image = client.call(media.GetMediaItem(attachment_id))
            import re
            post.content = re.sub(r'https://nmac.to(\S+).png', image.link,
                                  post.content)
            client.call(posts.EditPost(post.id, post))
            print 'Post Successfully updated. Its Id is: ', post.id
Beispiel #23
0
title = 'title'
body = 'body body '

post.title = title
post.content = body
 
post.terms_names = {
  'post_tag': ['tag'],
  'category': ['category']
}

# post.post_status = 'draft'
post.post_status = 'publish'

# set timezone to JST
post.date = datetime.datetime.now() - datetime.timedelta(hours=9)

# custom field
customFields = []
customFields.append({
  'key': 'aaa',
  'value': '***'
})

post.custom_fields = customFields

new_id = int(wp.call(NewPost(post)))
if new_id > 0:
  print('wordpress update success.')
else:
  print('wordpress update failure.')
def updatesite(site):
    titlelistdir = {}
    wp = Client(config.get(site, 'WPxmlrpcUrl'), config.get(site, 'WPUser'),
                config.get(site, 'WPPass'))
    for o, p in opts:
        if o in ['-t', '--title']:
            if p != 'all':
                #just 1 dir, add only the given dir to the dict
                titlelistdir[p.strip()] = p.lower().replace(' ', '-').strip()
    if not titlelistdir:
        #all dirs
        logger.info('all titles set')
        titlelist = open(config.get(site, 'TitlesList'), 'r')
        for line in titlelist.readlines():
            titlelistdir[line.strip()] = line.lower().replace(' ', '-').strip()
    for title in titlelistdir:
        dir = config.get(site, 'MediaRoot') + titlelistdir[title]
        mtime = lambda f: datetime.datetime.fromtimestamp(os.path.getmtime(f))
        logger.info(title + ' ' + dir)
        #tuple 4=by the hour  3=by the day
        mtime_hour = lambda f: datetime.datetime(*mtime(f).timetuple()[:4])
        dir_files = []
        for root, subFolder, files in os.walk(dir):
            for item in files:
                dir_files.append(root + '/' + item)
        dir_files = sorted(dir_files, key=mtime)
        dir_files = filter(
            lambda f: '150x150' not in f and '_p.jpg' not in f and f.lower(
            ).endswith(('.jpg', '.jpeg', '.png', '.gif', '.webm', '.mp4')),
            dir_files)
        if doallpics == 0:
            dir_files = filter(
                lambda f: datetime.datetime.strptime(
                    lastrun, '%Y-%m-%d %H:%M:%S') < mtime(f), dir_files)
        #dir_files = filter(lambda f: datetime.datetime(2010,1,1,0) <	mtime(f) < datetime.datetime(2015,1,1,0), dir_files)
        by_hour = dict((k, list(v)) for k, v in itertools.groupby(
            dir_files, key=mtime_hour))  #python 2.6
        logger.info(by_hour)
        for f in by_hour:
            logger.debug(f)
            post = WordPressPost()
            post.title = title
            post.terms_names = {'post_tag': [title], 'category': []}
            tagsfilename = dir + '/_tags.txt'
            catsfilename = dir + '/_cats.txt'

            if os.path.isfile(tagsfilename):
                taglist = open(tagsfilename, 'r')
                logger.debug(tagsfilename)
                for l in taglist.readlines():
                    post.terms_names['post_tag'].append(l.strip())
            if os.path.isfile(catsfilename):
                catlist = open(catsfilename, 'r')
                for li in catlist.readlines():
                    post.terms_names['category'].append(li.strip())
            logger.debug(post.terms_names)
            post.content = ''
            for pic in by_hour[f]:
                urlroot = config.get(site, 'MediaRootURL')
                fileName, fileExtension = os.path.splitext(pic)
                if pic.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
                    #			   if '150x150' not in pic:
                    #Create thumbnail if enabled and does not already exist
                    if config.get('createposts', 'Thumbnails') == 'yes':
                        picThumb = fileName + '-150x150' + fileExtension
                        if not os.path.isfile(dir + '/' + picThumb):
                            logger.info("Thumbnail " + picThumb +
                                        " does not exist, creating thumbnail")
                            size = 225, 225
                            try:
                                im = Image.open(dir + '/' + pic)
                                im.thumbnail(size)
                                im.save(dir + '/' + picThumb)
                            except IOError:
                                logger.error("Cannot create thumbnail " +
                                             picThumb)
                    #Get dimensions of image if available
                    try:
                        im = Image.open(pic)
                        (width, height) = im.size
                    except:
                        width = ''
                        height = ''
                        pass
                    imglink = urlroot + titlelistdir[
                        title] + '/' + os.path.relpath(pic, dir)
                    if config.get('createposts', 'UsePhoton') == 'yes':
                        thumblink = imglink
                    else:
                        thumblink = urlroot + titlelistdir[
                            title] + '/' + fileName + '-150x150' + fileExtension
                    entry = '<a href="' + imglink + '"><img class="alignnone size-medium tooltips" title="' + str(
                        width) + ' x ' + str(
                            height) + '" src="' + thumblink + '"></a>'
                    logger.debug(entry)
                else:
                    #Video
                    print 'video ' + fileExtension[
                        1:] + '="' + urlroot + titlelistdir[title] + '/' + pic
                    entry = '[video ' + fileExtension[
                        1:] + '="' + urlroot + titlelistdir[
                            title] + '/' + pic + '"][/video]'

                post.content += entry

            post.content = post.content.strip()
            logger.debug(post.content)
            pattern = '%Y-%m-%d %H:%M:%S'
            #	   epoch = int(time.mktime(time.strptime(f, pattern)))

            #	   date_time = '03-03-2015 23:28:48'
            #	   pattern = '%d-%m-%Y %H:%M:%S'
            #	   epoch = int(time.mktime(time.strptime(date_time, pattern)))

            post.date = f
            post.post_status = 'publish'
            wp.call(NewPost(post))

    if doallpics == 0:
        logger.info('Newpost appears added OK, updating lastrun')
        with open(lastrunfile, "w") as myfile:
            myfile.write(time.strftime("%Y-%m-%d %H:%M:%S"))
    def send_post_map(self, data):
        nom = data.get('nom')
        url_log_pas = data.get('url')
        post_text = data.get('post')
        # новые поля
        title = data.get('title')
        date_time = data.get('date')
        category = data.get('category')
        # для тестов
        #date_time = datetime.datetime(2020, 6, 22)
        #category = 'test categoryes'

        url, user, password = url_log_pas.split(';')
        try:
            if self.proxy != 'None':
                wp = Client(url + '/xmlrpc.php', user, password,transport=self.transport)
            else:
                wp = Client(url+'/xmlrpc.php', user,password)
        except:
            #self.logger.exception('Client')
            self.logger.info(f'{nom}:{url} - {Fore.RED}failed{Style.RESET_ALL}')
            return {'url_log_pas':url_log_pas,'url':url,'post_id':False}
        try:

            post = WordPressPost()
            post.mime_type = "text/html"
            if title:
                post.title = title
            else:
                post.title = ''
            post.content = post_text

            if date_time:
                post.date = datetime.datetime.strptime(date_time,'%d.%m.%Y %H:%M')
            if category:
                # добавляем категорию
                categories = self.get_category(wp, category)
                if categories:
                    post.terms = categories
                else:
                    self.logger.info(f'{category} dont created')
            post.post_status = 'publish'
            try:
                post.id= wp.call(NewPost(post))
            except (InvalidCredentialsError, ServerConnectionError, ServerConnectionError,
                    XmlrpcDisabledError, socket.timeout):
                self.logger.info(f'{nom}:{url} - {Fore.RED}failed{Style.RESET_ALL}')
                return {'url_log_pas':url_log_pas,'url': url, 'post_id': False}

            # пока не решил брать отсюда урл или нет
            #post_new = wp.call(GetPost(post.id))
            self.logger.info(f'{nom}:{url} send post! {Fore.GREEN}Post urls {url}/?p={post.id}{Style.RESET_ALL}')
            return {'url_log_pas':url_log_pas,'url': url, 'post_id': post.id}

        except Exception as e:
            try:
                faultCode = e.faultCode
                faultString = e.faultString.encode ("utf-8")
                self.logger.info(f'{Fore.RED}{nom}: Error send post {url} {faultCode} {faultString} {Style.RESET_ALL}')
                return {'url_log_pas': url_log_pas, 'url': url, 'post_id': False}
            except:
                return {'url_log_pas': url_log_pas, 'url': url, 'post_id': False}
Beispiel #26
0
        # find all tag ids associated with the post. For every tag id we find
        # associated with the post, we loop through the tags and find the name
        # of the tag and add it to the t_tags list for later use
        t_tags = []
        for e in posts_tags:
            if e['post_id'] == p['id']:
                for t in tags:
                    if t['id'] == e['tag_id']:
                        t_tags.append(t['name'])

        # Creating the Wordpress post object
        post = WordPressPost()
        # Trying to parse the post date to be displayed correctly in Wordpress
        # If the parsing fails we do nothing but continue with the import
        try:
            post.date = dateutil.parser.parse(date)
        except:
            continue

        post.terms_names = {'post_tag': t_tags}
        post.slug = p['slug']
        post.content = p['html']
        post.title = p['title']
        post.post_status = 'publish'
        # Finally publishing the post
        post.id = client.call(posts.NewPost(post))
    else:
        page = WordPressPage()
        page.title = p['title']
        page.content = p['html']
        page.post_status = 'publish'
"""!!! EDIT THESE VALUES, MAKE SURE TO LEAVE /XMLRPC.PHP AT THE END !!!"""

xmlrpc_endpoint = 'http://eidmantas.com/xmlrpc.php'
username = '******'
password = '******'

wp = Client(xmlrpc_endpoint, username, password)
"""!!! DONT FORGET  TO UPLOAD YOUR FILE AND CHANGE ITS NAME, OR THE VARIABLE HERE !!!"""
filename = 'your-ghost-export-file.json'

with open(filename) as f:
    text = f.read()

data = json.loads(text)
for p in data['db'][0]['data']['posts']:
    print p['title']
    date = p.get('published_at', None)
    if date is None:
        p.get('created_at')
    post = WordPressPost()
    post.slug = p['slug']
    post.content = p['html']
    post.title = p['title']
    post.post_status = 'publish'
    try:
        post.date = parse(date)

    except:
        exit
    wp.call(NewPost(post))
Beispiel #28
0
print('当前时间', datetimestr)
timelen = 30  #每篇文章相差的时间  秒
for i in range(nrows):
    rowcont = table.row_values(i)
    #print(rowcont[1])
    #post.title = rowcont[0]  #标题
    cont = ''
    for k in range(cols):
        if k < 2:
            continue
        cont = cont + str(rowcont[k])
    #print(cont)
    post.content = cont  #内容
    datastr = datetimestr + (i + 1) * timelen - timelen
    print('执行时间', datastr)
    post.date = datastr

    #rowcont1 是标签
    lastd = rowcont[1][len(rowcont[1]) - 1]
    if lastd == ',':
        bqstr = rowcont[1][0:len(rowcont[1]) - 1]  #截取
    else:
        bqstr = rowcont[1]
    #print(laststr)

    #name_list = bqstr.split(',')  #分割
    #title = random.sample(name_list, 2)
    #title = ','.join(title)
    post.title = rowcont[0]  #标题
    #print(title)
    laststr = rowcont[1][len(rowcont[1]) - 1]
Beispiel #29
0
def main():
    args = sys.argv[1:]
    if len(args) != 2:
        print(
            'Usage: ./ssp_se_load_roster.py <Wordpress xmlrpc url> <csvfile>')
        sys.exit(1)

    xmlrpc = args[0]
    csvfile_name = args[1]

    if not os.path.isfile(csvfile_name):
        print('I can\'t find the file: ' + csvfile_name)
        sys.exit(1)

    username = raw_input('Enter your WordPress user name: ')
    password = getpass()

    wp = Client(xmlrpc, username, password)

    listofseriesterms = wp.call(GetTerms('series'))

    print('To which series are you going to add all these posts? (id, name)')
    series = {}
    for seriesterm in listofseriesterms:
        print(seriesterm.id + ', ' + seriesterm.name)
        series[seriesterm.id] = seriesterm.name
    main_series_termid = raw_input('Please enter the id: ')

    if not main_series_termid in series:
        print('That series id does not exist')
        sys.exit(1)
    else:
        print(series[main_series_termid] + ' series selected.')

    child_series = {}
    for seriesterm in listofseriesterms:
        if seriesterm.parent == main_series_termid:
            child_series[seriesterm.name.lower()] = seriesterm.id

    print('child_series')
    print(child_series)

    existing_posts = wp.call(GetPosts({
        'post_type': 'podcast',
        'number': 9999
    }))
    existing_series_posts = {}
    child_series_existing_episode_numbers = {}
    for post in existing_posts:
        post_terms = []
        for term in post.terms:
            if term.id in child_series.values(
            ) or term.id == main_series_termid:
                post_terms.append(term.id)
        if post_terms:
            for customfield in post.custom_fields:
                if customfield['key'] == 'date_recorded' and customfield[
                        'value']:
                    date_recorded_string = customfield['value']
                elif customfield['key'] == 'episode_number' and customfield[
                        'value']:
                    for post_term_id in post_terms:
                        if post_term_id in child_series_existing_episode_numbers:
                            child_series_existing_episode_numbers[
                                post_term_id].append(int(customfield['value']))
                        else:
                            child_series_existing_episode_numbers[
                                post_term_id] = [int(customfield['value'])]
            date_recorded = getdatetime(date_recorded_string)
            existing_series_posts[date_recorded] = (post.id, post_terms)

    #open and parse the csv
    replace_all = False
    replace_none = False

    fieldname_translation = {
        'date': 'date_recorded',
        'title': 'title',
        'series': 'series',
        'track': 'episode_number',
        'passage': 'bible_passage',
        'preacher': 'preacher',
        'comments': 'content',
        'time': 'time'
    }

    list_from_csv = {}
    with open(csvfile_name, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        for messyentry in reader:
            entry = {}
            for entrykey, entryval in messyentry.iteritems():
                entry[fieldname_translation[entrykey.lower()]] = entryval
            if not (('date_recorded' in entry) or ('preacher' in entry)):
                continue
            if entry['date_recorded'] == '' or entry['preacher'] == '':
                continue
            csvdate = getdatetime(entry['date_recorded'])
            if csvdate == None:
                continue
            entry['date_recorded'] = csvdate.strftime('%d-%m-%Y')
            try:
                int(entry['episode_number'])
            except (ValueError, KeyError):
                entry['episode_number'] = ''
            for fieldname in fieldname_translation.values():
                if not fieldname in entry:
                    entry[fieldname] = ''
            if not entry['series']:
                entry['series'] = 'one-off'
            if (csvdate in existing_series_posts):
                if not (replace_none or replace_all):
                    confirmation_raw_in = raw_input(
                        'There is already a podcast in this series with date '
                        + csvdate.strftime('%d %b %Y') +
                        ', replace it? \n(Y/N/All/None)\n').lower()
                elif replace_none:
                    continue
                if confirmation_raw_in == 'none':
                    replace_none = True
                if not confirmation_raw_in in ['y', 'all']:
                    continue
                if confirmation_raw_in == 'all':
                    replace_all = True
                if wp.call(DeletePost(existing_series_posts[csvdate][0])):
                    print('Deleted old post for ' +
                          csvdate.strftime('%d %b %Y') + '.')
            entry['bible_passage'] = cleanUpScripture(entry['bible_passage'])
            list_from_csv[csvdate] = entry

    template_settings = {
        'ep_title_template': 'title',
        'service_time': 'time',
        'comments_template': 'content'
    }

    #work out series and episode_numbers:
    for seriestermid in child_series_existing_episode_numbers:
        try:
            child_series_existing_episode_numbers[seriestermid] = sorted(
                child_series_existing_episode_numbers[seriestermid],
                reverse=True)[0]
        except IndexError as e:
            print(e)
            try:
                child_series_existing_episode_numbers[seriestermid] = int(
                    series[seriestermid].count)
            except:
                child_series_existing_episode_numbers[seriestermid] = 0

    prefix = 'ss_podcasting_data_'
    termidlist = ['0', main_series_termid]
    optionslist = []
    templates_per_series = {}
    for child_series_termid in child_series.values():
        termidlist.append(child_series_termid)
    for termid_item in termidlist:
        templates_per_series[termid_item] = {}
        if termid_item == '0':
            suffix = ''
        else:
            suffix = '_' + termid_item
        for eachsetting in template_settings:
            optionslist.append(prefix + eachsetting + suffix)
    list_of_WPOptions = wp.call(GetOptions(optionslist))
    for wp_Option in list_of_WPOptions:
        if wp_Option.name[len(prefix):] in template_settings:
            templates_per_series['0'][
                wp_Option.name[len(prefix):]] = wp_Option.value
        else:
            for termid_item in termidlist:
                suffix = '_' + termid_item
                if wp_Option.name[-len(suffix):] == suffix:
                    templates_per_series[termid_item][wp_Option.name[
                        len(prefix):-len(suffix)]] = wp_Option.value

    timezone = get_localzone()

    for entry, details in sorted(list_from_csv.iteritems()):
        if not details['series'].lower() in child_series:
            wpseries = WordPressTerm()
            wpseries.taxonomy = 'series'
            wpseries.name = details['series']
            wpseries.parent = main_series_termid
            wpseries.id = wp.call(NewTerm(wpseries))
            child_series[details['series']] = wpseries.id
            listofseriesterms.append(wpseries)
            series[wpseries.id] = wpseries.name
            child_series[wpseries.name.lower()] = wpseries.id
            if details['episode_number'] == '':
                details['episode_number'] = '1'
                child_series_existing_episode_numbers[wpseries.id] = 1
            else:
                child_series_existing_episode_numbers[wpseries.id] = int(
                    details['episode_number'])
            details['seriesid'] = wpseries.id
        else:
            try:
                child_series_existing_episode_numbers[child_series[
                    details['series'].lower()]]
            except KeyError:
                for seriesterm in listofseriesterms:
                    if seriesterm.id == child_series[
                            details['series'].lower()]:
                        child_series_existing_episode_numbers[child_series[
                            details['series'].lower()]] = seriesterm.count
                    else:
                        child_series_existing_episode_numbers[child_series[
                            details['series'].lower()]] = 0
            if details['episode_number'] == '':
                child_series_existing_episode_numbers[child_series[
                    details['series'].lower()]] += 1
                details['episode_number'] = str(
                    child_series_existing_episode_numbers[child_series[
                        details['series'].lower()]])
            else:
                child_series_existing_episode_numbers[child_series[
                    details['series'].lower()]] = int(
                        details['episode_number'])
            details['seriesid'] = child_series[details['series'].lower()]
        for template_setting, detail in template_settings.iteritems():
            list = [details['seriesid'], main_series_termid, '0']
            while details[detail] == '':
                try:
                    details[detail] = templates_per_series[list.pop(
                        0)][template_setting]
                except KeyError:
                    continue
        publishtime = gettime(details['time'])
        if publishtime:
            local_datetime = timezone.localize(
                datetime.combine(entry, publishtime.time()))
            details['post_date_gmt'] = local_datetime.astimezone(pytz.utc)
        newpost = WordPressPost()
        newpost.post_type = 'podcast'
        newpost.title = details['title']
        newpost.date = details['post_date_gmt']
        newpost.post_status = 'draft'
        newpost.content = details['content']
        newpost.terms = [wp.call(GetTerm('series', main_series_termid))]
        if details['seriesid']:
            newpost.terms.append(
                wp.call(GetTerm('series', details['seriesid'])))
        newpost.custom_fields = [{
            'key': 'preacher',
            'value': details['preacher']
        }, {
            'key': 'date_recorded',
            'value': details['date_recorded']
        }, {
            'key': 'bible_passage',
            'value': details['bible_passage']
        }, {
            'key': 'episode_number',
            'value': details['episode_number']
        }, {
            'key': 'publish_now',
            'value': 'on'
        }]
        newpost.id = wp.call(NewPost(newpost))
        if newpost.id:
            print('Created Post ID ' + str(newpost.id) + ' for date: ' +
                  details['date_recorded'])
                                newtweet = newtweet + "<br>\n" + urls[i] + " "
                            else:
                                newtweet = newtweet + "<br>\n<a target=\"_blank\" href=\"" + urls[
                                    i] + "\">" + urls[i] + "</a> "
                            i += 1
                            continue
                        #else add an image to the new tweet
                        else:
                            for mediaurl in mediaurls:
                                newtweet = newtweet + mediaurl + " "
                            continue
                    #if we are still around, this is just a boring, normal word
                    newtweet = newtweet + word + " "
                #let's compose our blogpost
                post = WordPressPost()
                #pick first 8 words for title
                post.title = ' '.join(TAG_RE.sub('', newtweet).split()[:8])
                post.content = newtweet
                post.terms = tags
                post.date = datetime.strptime(
                    tweet['created_at'].split()[0] + " " +
                    tweet['created_at'].split()[1], '%Y-%m-%d %H:%M:%S')
                post.post_status = 'publish'
                post.id = client.call(posts.NewPost(post))
                #print (newtweet)

    except KeyboardInterrupt:
        print("")
        print("Interrupted! Come back any time.")
        sys.exit()