Esempio n. 1
0
def build_news_message(news):
	post = WordPressPost()
	post.title = news.brief_comment

	converted_video_url = None
	if news.video_url is not None:
		converted_video_url = convert_youku_video_url(news.video_url)

	content_items = {'content' : _normalize_content(news.recommended_reason)}
	if news.screenshot_path_1:
		content_items['screenshot_path_1'] = settings.MEDIA_URL + news.screenshot_path_1.name
	if news.screenshot_path_2:
		content_items['screenshot_path_2'] = settings.MEDIA_URL + news.screenshot_path_2.name
	if news.screenshot_path_3:
		content_items['screenshot_path_3'] = settings.MEDIA_URL + news.screenshot_path_3.name
	if news.screenshot_path_4:
		content_items['screenshot_path_4'] = settings.MEDIA_URL + news.screenshot_path_4.name
	content_items['video_url'] = converted_video_url
	post.content = str(render_to_string('news_web.tpl', content_items))

	post.terms_names = {
		'category' : [u'新游预告']
	}

	if news.screenshot_path_1.name != '':
		post.custom_fields = []
		post.custom_fields.append({'key':'post_image','value':settings.MEDIA_URL + news.screenshot_path_1.name})

	post.post_status = 'publish'

	return WebMessage(news.id, post)
Esempio n. 2
0
def build_evaluation_message(evaluation):
	post = WordPressPost()
	post.title = evaluation.title

	post.content = str(render_to_string('evaluation_web.tpl', {
		'id' : evaluation.id,
		'content' : _normalize_content(evaluation.recommended_reason),
		'icon' : settings.MEDIA_URL + evaluation.icon.name,
		'platforms' : _get_game_evaluation_platforms(evaluation),
		'android_download_url' : evaluation.android_download_url,
		'iOS_download_url' : evaluation.iOS_download_url,
		'evaluation_content' : evaluation.content,
		'rating' : evaluation.rating,
	}))

	post.terms_names = {
		'category' : [u'游戏测评'],
		'post_tag' : _get_game_evaluation_tags(evaluation)
	}
	if evaluation.icon.name != '':
		post.custom_fields = []
		post.custom_fields.append({'key':'post_image','value':settings.MEDIA_URL + evaluation.icon.name})

	post.post_status = 'publish'

	return WebMessage(evaluation.id, post)
Esempio n. 3
0
def build_game_message(game):
	post = WordPressPost()
	post.title = '%s - %s' % (game.name, game.brief_comment)

	converted_video_url = None
	if game.video_url is not None:
		converted_video_url = convert_youku_video_url(game.video_url)
	post.content = str(render_to_string('game_web.tpl', {
		'content' : _normalize_content(game.recommended_reason),
		'icon' : settings.MEDIA_URL + game.icon.name,
		'category' : game.category.name,
		'size' : game.size,
		'platforms' : _get_game_platforms(game),
		'id' : game.id,
		'android_download_url' : game.android_download_url,
		'iOS_download_url' : game.iOS_download_url,
		'screenshot_path_1' : settings.MEDIA_URL + game.screenshot_path_1.name,
		'screenshot_path_2' : settings.MEDIA_URL + game.screenshot_path_2.name,
		'screenshot_path_3' : settings.MEDIA_URL + game.screenshot_path_3.name,
		'screenshot_path_4' : settings.MEDIA_URL + game.screenshot_path_4.name,
		'video_url' : converted_video_url
	}))

	post.terms_names = {
		'category' : [game.category.name],
		'post_tag' : _get_game_tags(game)
	}

	if game.screenshot_path_1.name != '':
		post.custom_fields = []
		post.custom_fields.append({'key':'post_image','value':settings.MEDIA_URL + game.screenshot_path_1.name})

	post.post_status = 'publish'

	return WebMessage(game.id, post)
Esempio n. 4
0
def make_wp_content(hotitem):
    format_cont = Template(post_template)
    # format_cont.substitute(shop = u"天猫", img=hotitem["goods_pic"])
    post = WordPressPost()
    post.title = hotitem["goods_title"]
    post.content = hotitem["goods_introduce"]
    # post.post_type = "tbkitem"
    iteminfo = json.dumps(hotitem)
    post.custom_fields = [{"key": "iteminfo", "value": iteminfo}]
    # post.thumbnail = hotitem["goods_pic"]

    post.content = format_cont.substitute(
        shop=hotitem["platform"].decode("utf8"),
        introduce=hotitem["goods_introduce"],
        origin_price=hotitem["origin_price"],
        quan_price=hotitem["zhekou_price"],
        now_price=float(hotitem["origin_price"]) -
        float(hotitem["zhekou_price"]),
        tbk_link_quan=hotitem["tbk_link_quan"],
        img=hotitem["goods_pic"])
    post.terms_names = {
        'post_tag': hotitem["tag"],
        'category': hotitem["category"],
    }
    post.post_status = "publish"
    return post
Esempio n. 5
0
    def publish(self, title, content):
        post = WordPressPost()
        post.title = title
        post.content = content
        post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布

        post.terms_names = {
            'post_tag': ['news'],  # 文章所属标签,没有则自动创建
            'category': ['news'],  # 文章所属分类,没有则自动创建
        }

        post.custom_fields = []
        post.custom_fields.append({
            'key': '_aioseop_keywords',
            'value': self.keywords
        })
        post.custom_fields.append({
            'key': '_aioseop_description',
            'value': self.description
        })
        post.custom_fields.append({
            'key': '_aioseop_title',
            'value': self.title
        })
        post.id = self.wp.call(posts.NewPost(post))
Esempio n. 6
0
    def postBlog(self, new_blog):
        print('正在发布:', new_blog[1])
        post = WordPressPost()
        kuohao = '【{}】'
        post.title = new_blog[1] + kuohao.format(new_blog[2]) + kuohao.format(
            new_blog[8])
        post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
        comic_cover = '<img src="' + new_blog[
            6] + '" alt="" class="aligncenter size-full wp-image-154" />'
        post.content = comic_cover + '<h5>漫画简介:</h5><blockquote style="text-indent: 30px;">' + new_blog[
            7] + '</blockquote>'

        serial_status = '精彩连载,' if '连载' in new_blog[8] else '经典完结,'
        categorys = serial_status + new_blog[3]
        post.terms_names = {
            'post_tag': new_blog[4].split(','),  # 文章所属标签,没有则自动创建
            'category':
            categorys.split(',') + new_blog[5].split('+')  # 文章所属分类,没有则自动创建
        }

        post.custom_fields = []  # 自定义字段列表
        # 资源价格
        price = int(new_blog[11]) * 10 if new_blog[11] else 2 * 10
        post.custom_fields.append({'key': 'cao_price', 'value': price})
        # VIP折扣
        post.custom_fields.append({'key': 'cao_vip_rate', 'value': 0})
        # 仅限永久VIP免费
        post.custom_fields.append({'key': 'cao_is_boosvip', 'value': 0})
        # 启用付费下载资源
        post.custom_fields.append({'key': 'cao_status', 'value': 1})
        post.custom_fields.append({'key': 'wppay_type', 'value': 4})
        # 资源下载地址
        post.custom_fields.append({'key': 'cao_downurl', 'value': new_blog[9]})
        # 资源下载密码
        post.custom_fields.append({'key': 'cao_pwd', 'value': new_blog[10]})
        # 资源下载次数
        post.custom_fields.append({
            'key': 'cao_paynum',
            'value': random.randint(1, 50)
        })
        post.custom_fields.append({  # 资源其他信息
            'key':
            'cao_info',
            'value': [{
                'title': '作   者',
                'desc': new_blog[2]
            }, {
                'title': '题材类型',
                'desc': new_blog[4]
            }, {
                'title': '是否完结',
                'desc': new_blog[8]
            }]
        })
        try:
            self.wp.call(posts.NewPost(post))
            print('发布成功:', new_blog[1])
        except:
            print('发布失败:', new_blog[1])
Esempio n. 7
0
    def update_post_wp(self, wp_post_id):
        """
        Update post with id in WordPress.
        :param wp_post_id: post id
        """
        post = self.client.call(posts.GetPost(wp_post_id))

        if not post:
            raise ResourceError("Post not found, id: {}.".format(wp_post_id))

        key_assoc = {
            "city": "city_id",
            "coordinates_lat": "latitude",
            "coordinates_long": "longitude",
            "geo_hash_id": "geo_hash_id",
            "rate": "rate",
            "place_id": "place_id",
            "address": "address_coord"
        }
        post_custom_fields = CustomFields(post.custom_fields, key_assoc)
        custom_fields_unpacked = post_custom_fields.unpack()

        try:
            location = []
            location_unserialized = custom_fields_unpacked["city_id"]
            for loc in location_unserialized:
                term = self.client.call(
                    taxonomies.GetTerm("locations", int(loc)))
                location.append(term)
                break
        except KeyError:
            pass

        db_post = self.connection.get(
            InterestPoint, {
                "latitude": custom_fields_unpacked["latitude"],
                "longitude": custom_fields_unpacked["longitude"]
            })
        if not db_post:
            db_post = self.connection.get(InterestPoint, {"title": post.title})

        if not db_post:
            raise MissingResourceError(
                "InterestPoint not found for post with id: {}.".format(
                    post.id))

        dict_post = post.__dict__()

        post_diff = self.prejudice_diff(post, db_post)

        new_post_data = WordPressPost()
        new_post_data.custom_fields = []

        self.client.call(posts.EditPost(post.id, new_post_data))
        exit()
Esempio n. 8
0
def post_to_wp(title, content, field):
    post = WordPressPost()
    post.post_status = 'publish'
    post.terms_names = {'category': ['西藏旅游问答']}

    post.title = title
    post.content = content
    post.custom_fields = field

    post.id = wp.call(posts.NewPost(post))
    print(str(title) + '\n' + str(wp_url) + '?p=' + str(post.id) + '\n')
Esempio n. 9
0
def create_new_empty_wp_post(component, event_category, event_map_location, location_gps):

    summary = component.get('SUMMARY').encode('UTF-8', 'backslashreplace')
    start_event = component.get('DTSTART').dt.strftime('%Y-%m-%d %H:%M')
    end_event = component.get('DTEND').dt.strftime('%Y-%m-%d %H:%M')
    end_frequency_event = component.get('DTEND').dt.strftime('%Y-%m-%d')
    uid = component.get('UID').encode('UTF-8', 'backslashreplace')
    event_description = component.get('DESCRIPTION')
    if event_description is None:
        event_description = " "
    else:
        event_description = component.get('DESCRIPTION').encode('UTF-8', 'backslashreplace')

    # Create a new post
    new_post = WordPressPost()
    new_post.title = summary
    new_post.content = event_description
    new_post.post_type = "event"
    new_post.post_status = "publish"
    new_post.terms_names = {'event-category': [event_category]}
    new_post.custom_fields = []

    meta_adds = (['imic_event_start_dt', start_event],
                 ['imic_event_end_dt', end_event],
                 ['imic_event_frequency_end', end_frequency_event],
                 ['imic_featured_event', 'no'],
                 ['slide_template', 'default'],
                 ['imic_event_day_month', 'first'],
                 ['imic_event_week_day', 'sunday'],
                 ['imic_event_frequency_type', '0'],
                 ['imic_event_frequency', '35'],
                 ['imic_event_registration', '0'],
                 ['imic_custom_event_registration_target', '0'],
                 ['imic_sidebar_columns_layout', '3'],
                 ['imic_google_map_track', '1'],
                 ['imic_event_address2', event_map_location],
                 ['imic_event_map_location', location_gps],
                 ['imic_pages_banner_overlay', '0'],
                 ['imic_pages_banner_animation', '0'],
                 ['imic_pages_select_revolution_from_list', '[rev_slider fsl]'],
                 ['imic_pages_slider_pagination', 'no'],
                 ['imic_pages_slider_auto_slide', 'no'],
                 ['imic_pages_slider_direction_arrows', 'no'],
                 ['imic_pages_slider_interval', '7000'],
                 ['imic_pages_slider_effects', 'fade'],
                 ['imic_pages_nivo_effects', 'sliceDown'],
                 ['imic_import_uid', uid])

    # Iterate over array creating meta in post
    for i in meta_adds:
        new_post.custom_fields.append({'key': i[0], 'value': i[1]})

    return new_post
Esempio n. 10
0
def post_article(title, content, first_img, author, source_url, source_name,
                 delivery_url, delivery_name, class_, tmpdir):
    client = Client(WP_XMLRPC_URL, WP_XMLRPC_USER, WP_XMLRPC_PASS)

    retry = 5
    if first_img:
        logger.debug('Download image %s' % first_img)
        img_path = get_img(first_img, tmpdir)
        logger.debug('Download article\'s first image to %s' % img_path)

    ret = None
    if first_img:
        for i in xrange(retry):
            ret = upload_file_to_wp(client, img_path)
            if ret:
                break
        else:
            raise CanNotUploadException('upload %s' % img_path)

    attachment_id = ret

    # Download all image file, and put it into static directory in web server,
    # and replace URL in the article content.

    content_obj = BeautifulSoup(content)
    img_tags = content_obj.find_all('img', recursive=True)
    from hashlib import md5
    hex_dir = md5(title.encode('utf-8')).hexdigest()
    for img in img_tags:
        if img and img.has_attr('src'):
            img_path = get_img(img.attrs['src'], tmpdir)
            img_path2 = copy_to_web_server(img_path, hex_dir)
            img.attrs['src'] = img_path2

    post = WordPressPost()
    post.title = title
    post.content = str(content_obj)
    #post.post_status = 'publish'
    if first_img:
        post.thumbnail = attachment_id
    post.terms_names = {
        # TODO: add tags
        #'post_tag': ['tagA', 'another tag'],
        'category': [
            'Web-Crawler/新闻资讯',
        ],
    }
    post.custom_fields = []
    post.custom_fields.append({'key': 'source_url', 'value': source_url})
    post.custom_fields.append({'key': 'source_name', 'value': source_name})
    post.custom_fields.append({'key': 'delivery_name', 'value': delivery_name})
    post.custom_fields.append({'key': 'delivery_url', 'value': delivery_url})
    post.id = client.call(posts.NewPost(post))
Esempio n. 11
0
def sourcename(url, cat1=None, cat2=None, cat3=None, d=True):
    html = getPage(url, "page1.html")
    os.remove('pages/page1.html')
    title = html.select('h1')[0].text
    first_para = html.select('.story-content > p:nth-of-type(1)')[0].text
    second_para = html.select('.story-content > p:nth-of-type(2)')[0].text
    try:
        image = html.select('.image > img')[0].get('src')
    except Exception:
        image = None
    wp = Client('http://www.domain.com/xml-rpc.php', 'username', 'password')
    if image:
        filename = 'http://www.livemint.com' + image
        path = os.getcwd() + "\\00000001.jpg"
        f = open(path, 'wb')
        f.write(urllib.urlopen(filename).read())
        f.close()
        # prepare metadata
        data = {
            'name': 'picture.jpeg',
            'type': 'image/jpeg',  # mimetype
        }

        with open(path, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    post = WordPressPost()
    post.title = title
    post.user = 14
    post.post_type = "post"
    post.content = first_para + '\n' + '\n' + second_para
    if d:
        post.post_status = "draft"
    else:
        post.post_status = "publish"
    if image:
        attachment_id = response['id']
        post.thumbnail = attachment_id
    post.custom_fields = []
    post.custom_fields.append({
        'key': 'custom_source_url',
        'value': url
    })
    if cat1:
        cat1 = wp.call(taxonomies.GetTerm('category', cat1))
        post.terms.append(cat1)
    if cat2:
        cat2 = wp.call(taxonomies.GetTerm('category', cat2))
        post.terms.append(cat2)
    if cat3:
        cat3 = wp.call(taxonomies.GetTerm('category', cat3))
        post.terms.append(cat3)
    addpost = wp.call(posts.NewPost(post))
Esempio n. 12
0
def sourcename(url, cat1=None, cat2=None, cat3=None, d=True):
    html = getPage(url, "page1.html")
    os.remove('pages/page1.html')
    title = html.select('h1')[0].text
    first_para = html.select('.story-content > p:nth-of-type(1)')[0].text
    second_para = html.select('.story-content > p:nth-of-type(2)')[0].text
    try:
        image = html.select('.image > img')[0].get('src')
    except Exception:
        image = None
    wp = Client('http://www.domain.com/xml-rpc.php', 'username', 'password')
    if image:
        filename = 'http://www.livemint.com' + image
        path = os.getcwd() + "\\00000001.jpg"
        f = open(path, 'wb')
        f.write(urllib.urlopen(filename).read())
        f.close()
        # prepare metadata
        data = {
            'name': 'picture.jpeg',
            'type': 'image/jpeg',  # mimetype
        }

        with open(path, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    post = WordPressPost()
    post.title = title
    post.user = 14
    post.post_type = "post"
    post.content = first_para + '\n' + '\n' + second_para
    if d:
        post.post_status = "draft"
    else:
        post.post_status = "publish"
    if image:
        attachment_id = response['id']
        post.thumbnail = attachment_id
    post.custom_fields = []
    post.custom_fields.append({'key': 'custom_source_url', 'value': url})
    if cat1:
        cat1 = wp.call(taxonomies.GetTerm('category', cat1))
        post.terms.append(cat1)
    if cat2:
        cat2 = wp.call(taxonomies.GetTerm('category', cat2))
        post.terms.append(cat2)
    if cat3:
        cat3 = wp.call(taxonomies.GetTerm('category', cat3))
        post.terms.append(cat3)
    addpost = wp.call(posts.NewPost(post))
Esempio n. 13
0
 def postBlog(self, new_blog):
     print('正在发布:', new_blog[1])
     post = WordPressPost()
     # post.id = new_blog[0]
     post.title = new_blog[1]
     post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
     post.content = new_blog[7]
     post.terms_names = {
         'post_tag': [new_blog[3]],  # 文章所属标签,没有则自动创建
         # 'category': ['日韩漫画']  # 文章所属分类,没有则自动创建
         'category': [self.category]
     }
     post.custom_fields = []  # 自定义字段列表
     # 资源价格
     post.custom_fields.append({'key': 'cao_price', 'value': 2})
     # VIP折扣
     post.custom_fields.append({'key': 'cao_vip_rate', 'value': 0})
     # 仅限永久VIP免费
     post.custom_fields.append({'key': 'cao_is_boosvip', 'value': 0})
     # 启用付费下载资源
     post.custom_fields.append({'key': 'cao_status', 'value': 1})
     post.custom_fields.append({'key': 'wppay_type', 'value': 4})
     # 资源下载地址
     post.custom_fields.append({'key': 'cao_downurl', 'value': new_blog[5]})
     # 资源下载密码
     post.custom_fields.append({'key': 'cao_pwd', 'value': new_blog[6]})
     # 资源下载次数
     post.custom_fields.append({
         'key': 'cao_paynum',
         'value': random.randint(1, 50)
     })
     post.custom_fields.append({  # 资源其他信息
         'key':
         'cao_info',
         'value': [{
             'title': '作   者',
             'desc': new_blog[2]
         }, {
             'title': '题材类型',
             'desc': new_blog[3]
         }, {
             'title': '是否完结',
             'desc': new_blog[4]
         }]
     })
     try:
         self.wp.call(posts.NewPost(post))
     except:
         pass
Esempio n. 14
0
 def updateBlog(self, begin, end, comic_path):
     # 必须添加header=None,否则默认把第一行数据处理成列名导致缺失
     data = pd.read_csv(self.comic_path, encoding='gbk', header=None)
     csv_reader_lines = data.values.tolist()
     print(csv_reader_lines[0])
     for index in range(begin, end):
         post = WordPressPost()
         blog = csv_reader_lines[index]
         post.title = blog[1]
         post.custom_fields = {'cao_downurl': blog[5]}  # 自定义字段列表
         print(blog[1])
         print(blog[5])
         print(int(blog[0]))
         # post.post_status = 'publish'
         self.wp.call(posts.EditPost(int(blog[0]), post))
Esempio n. 15
0
    def addItem(self, item):
        # 跳转链作为唯一标识去重
        #        exist_posts = self.rpcClient.call(posts.GetPosts({'custom_fields':{'key':'link_value', 'value' : item.link}}))
        if self.itemExist(item.link):
            return
        print 'item.link = ' + item.link
        res = urlparse.urlparse(item.thumb)
        if len(res.query) > 0:
            qs = urlparse.parse_qs(res.query)
            #    huihui图片ID
            des = qs['id'][0]
            filename = des + '.png'
            destfile = 'temp/' + filename
        else:
            filename = item.thumb[item.thumb.rfind('/'):]
            destfile = 'temp' + filename
        downloadimage(item.thumb, destfile)

        # prepare metadata
        data = {
            'name': filename,
            'type': 'image/png',  # mimetype
        }

        # read the binary file and let the XMLRPC library encode it into base64
        with open(destfile, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())

        response = self.rpcClient.call(media.UploadFile(data))
        attachment_id = response['id']

        post = WordPressPost()
        post.title = item.title
        post.content = item.content
        post.thumbnail = attachment_id
        post.custom_fields = [{'key': 'link_value', 'value': item.link}]
        post.id = self.rpcClient.call(posts.NewPost(post))
        #    # attachment_id.parentid = post.id
        #    # whoops, I forgot to publish it!
        post.post_status = 'publish'

        #        cats = self.rpcClient.call(taxonomies.GetTerms('category'))
        for cat in self.categorys:
            if cat.name == item.category:
                post.terms = [cat]
                break

        self.rpcClient.call(posts.EditPost(post.id, post))
Esempio n. 16
0
    def addItem(self, item):
        # 跳转链作为唯一标识去重
#        exist_posts = self.rpcClient.call(posts.GetPosts({'custom_fields':{'key':'link_value', 'value' : item.link}}))
        if self.itemExist(item.link):
            return
        print 'item.link = '+item.link
        res = urlparse.urlparse(item.thumb)
        if len(res.query) > 0:
            qs = urlparse.parse_qs(res.query)
#    huihui图片ID
            des = qs['id'][0]
            filename = des+'.png'
            destfile = 'temp/'+filename
        else:
            filename = item.thumb[item.thumb.rfind('/'):]
            destfile = 'temp'+filename
        downloadimage(item.thumb,destfile)
        
        # prepare metadata
        data = {
                'name': filename,
                'type': 'image/png',  # mimetype
        }
        
        # read the binary file and let the XMLRPC library encode it into base64
        with open(destfile, 'rb') as img:
                data['bits'] = xmlrpc_client.Binary(img.read())
        
        response = self.rpcClient.call(media.UploadFile(data))
        attachment_id = response['id']

        post = WordPressPost()
        post.title = item.title
        post.content = item.content
        post.thumbnail = attachment_id
        post.custom_fields = [{'key':'link_value', 'value' : item.link}]
        post.id = self.rpcClient.call(posts.NewPost(post))
    #    # attachment_id.parentid = post.id
    #    # whoops, I forgot to publish it!
        post.post_status = 'publish'
        
#        cats = self.rpcClient.call(taxonomies.GetTerms('category'))
        for cat in self.categorys:
            if cat.name == item.category:
                post.terms = [cat]
                break
                
        self.rpcClient.call(posts.EditPost(post.id, post))
Esempio n. 17
0
def wt_wordpress(name, des):
    from wordpress_xmlrpc import Client, WordPressPost
    from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
    from wordpress_xmlrpc.methods.users import GetUserInfo
    from wordpress_xmlrpc.methods import posts
    from wordpress_xmlrpc.methods import taxonomies
    from wordpress_xmlrpc import WordPressTerm
    from wordpress_xmlrpc.compat import xmlrpc_client
    from wordpress_xmlrpc.methods import media, posts
    import sys
    import importlib
    import random

    importlib.reload(sys)

    post = WordPressPost()
    post.title = name
    post.content = des
    post.post_status = 'publish'  #文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
    wp = Client('https://customp.cn/xmlrpc.php', 'customp',
                'PYOqDvyjw2F6vQGir%pnd1PQ')
    '''
    post.terms_names = { 
        'post_tag':seokey(key_tag,30,3), #文章所属标签,没有则自动创建
        'category':seokey(key_category,20000,2) #文章所属分类,没有则自动创建
        }
    '''

    post.custom_fields = []  #自定义字段列表
    post.custom_fields.append({  #添加一个自定义字段
        'key': 'price',
        'value': 3
    })

    post.custom_fields.append({  #添加第二个自定义字段
        'key': 'ok',
        'value': 'customfw.com'
    })
    post.id = wp.call(posts.NewPost(post))
    time.sleep(1)
Esempio n. 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
Esempio n. 19
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)
Esempio n. 20
0
    def postBlog(self, new_blog):
        print('正在发布:', new_blog[1])
        post = WordPressPost()
        post.title = new_blog[1]
        post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
        post.content = new_blog[2]

        post.terms_names = {
            'post_tag': new_blog[3].split(','),  # 文章所属标签,没有则自动创建
            'category': new_blog[4].split('+')  # 文章所属分类,没有则自动创建
        }

        post.custom_fields = []  # 自定义字段列表
        # 资源价格
        price = 2
        post.custom_fields.append({'key': 'cao_price', 'value': price})
        # VIP折扣
        post.custom_fields.append({'key': 'cao_vip_rate', 'value': 0})
        # 仅限永久VIP免费
        post.custom_fields.append({'key': 'cao_is_boosvip', 'value': 0})
        # 启用付费下载资源
        post.custom_fields.append({'key': 'cao_status', 'value': 1})
        post.custom_fields.append({'key': 'wppay_type', 'value': 4})
        # 资源下载地址
        post.custom_fields.append({'key': 'cao_downurl', 'value': new_blog[5]})
        # 资源下载密码
        post.custom_fields.append({'key': 'cao_pwd', 'value': new_blog[6]})
        # 资源下载次数
        post.custom_fields.append({
            'key': 'cao_paynum',
            'value': random.randint(1, 50)
        })
        try:
            self.wp.call(posts.NewPost(post))
            print('发布成功:', new_blog[1])
        except:
            print('发布失败:', new_blog[1])
            pass
def wt_wordpress(in_q, wp_user):
    name, des, post_tag, category = in_q
    from wordpress_xmlrpc import Client, WordPressPost
    from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
    from wordpress_xmlrpc.methods.users import GetUserInfo
    from wordpress_xmlrpc.methods import posts
    from wordpress_xmlrpc.methods import taxonomies
    from wordpress_xmlrpc import WordPressTerm
    from wordpress_xmlrpc.compat import xmlrpc_client
    from wordpress_xmlrpc.methods import media, posts
    import sys
    import importlib
    import random

    importlib.reload(sys)
    post = WordPressPost()
    post.title = name
    post.content = des
    post.post_status = 'publish'  #文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
    xmrpc_url, user, password = wp_user
    wp = Client(xmrpc_url, user, password)

    post.terms_names = {
        'post_tag': post_tag,  #文章所属标签,没有则自动创建
        'category': category  #文章所属分类,没有则自动创建
    }

    post.custom_fields = []  #自定义字段列表
    post.custom_fields.append({  #添加一个自定义字段
        'key': 'price',
        'value': 3
    })

    post.custom_fields.append({  #添加第二个自定义字段
        'key': 'ok',
        'value': 'customfw.com'
    })
    post.id = wp.call(posts.NewPost(post))
Esempio n. 22
0
def upload_post(auth, **args):
    wp = Client(auth['site'], auth['user'], auth['pass'])

    post = WordPressPost()

    post.post_type = args.get('type', None)
    post.title = args.get('title', None)
    post.content = args.get('content', None)
    post.date = gen_datetime(args['date'], args.get('date-format', None),
                             args.get('zone', 0))

    terms = {key: [value] for key, value in args.get('terms', {}).items()}
    post.terms_names = terms

    if args.get('path', None) is not None:
        post.custom_fields = [{'key': 'enclosure',
                               'value': upload_media(args['path'], wp)
                               }]

    if args.get('publish', False):
        post.post_status = 'publish'

    post.id = wp.call(posts.NewPost(post))
Esempio n. 23
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)
Esempio n. 24
0
    def _post_newpost_to_wordpress(self, item, attachment_id):
        post = WordPressPost()
        post.title = item['title']
        post.content = item['content']
        post.post_type = "post"
        post.post_status = "publish"
        post.terms_names = {
            'post_tag': item['tags'],
            'category': [item['url_from']]
        }
        post.custom_fields = []
        post.custom_fields.append({
            'key': 'custom_source_url',
            'value': item['url']
        })
        # cat1 = self.wp.call(taxonomies.GetTerm('category', 'wanghao'))
        # post.terms.append(cat1)

        if attachment_id:
            post.thumbnail = attachment_id

        addpost = self.wp.call(posts.NewPost(post))

        return addpost
Esempio n. 25
0
    def create_match_post(self, media_post, title, tags, extra):
        post = WordPressPost()
        post.title = title
        if extra == None:
            extra = ""
        post.content = media_post.get_embed() + extra
        post.terms_names = {
                'post_tag': tags
        }

        post.terms = self.find_terms()
        post.post_status = 'publish'
        post.custom_fields = [
            {
                'key': 'thumbnail',
                'value': media_post.get_thumb()
            },
            {
                'key': 'event_date',
                'value': self.date
            }           
        ]
        post.id = self.client.call(posts.NewPost(post))
        return post
Esempio n. 26
0
    def createPost(self, attachmentID):
        """ 
       
        Creates Posts in CMS. 
        ----------        

        After successfull Authentication, this function sets a post title, post status and 
        generates the post with the postmeta fields for the image, date and time. 
        ----------              
        
        Parameters: 
        ----------        
        attachmentID (int): ID of the Image, that should be attached to the post.
        
        Returns: 
        ----------        
        nothing will be returned. 
      
        """

        # Generate Post Object
        post = WordPressPost()
        post.post_type = self.post_configuration.postBasicInformation.get(
            'post_type')
        post.title = time.strftime("%A, %d, %B um %H:%M:%S", self.time)

        # Authentification
        authenticator = Authenticator.Authenticator()
        credentials = authenticator.obtainCredentials(User.User())
        cms = authenticator.isValid(credentials)
        post = WordPressPost()

        if 'post_type' in self.post_configuration.postBasicInformation:
            post.post_type = self.post_configuration.postBasicInformation.get(
                'post_type')

        post.title = time.strftime("%A, %d, %B um %H:%M:%S", self.time)

        # Prepare Key-Value-Pairs for upload to CMS
        custom_post_configuration = self.post_configuration.postCustomFields

        if 'imageField' in custom_post_configuration:
            self.image = {
                'key': custom_post_configuration.get('imageField'),
                'value': self.attachmentID
            }

        if 'dateField' in custom_post_configuration:
            self.date = {
                'key': custom_post_configuration.get('dateField'),
                'value':
                time.strftime("%Y%m%d",
                              self.time)  # zum Beispiel 20190116, also %Y%m%e
            }

        if 'timeField' in custom_post_configuration:
            self.time = {
                'key': custom_post_configuration.get('timeField'),
                'value': time.strftime(
                    "%T", self.time
                )  # zum Beispiel 02:12:17, also %T --> entspricht %H:%M:%S        
            }

        if 'timestampField' in custom_post_configuration:
            self.timestamp = {
                'key': custom_post_configuration.get('timestampField'),
                'value': self.setting.filename
            }

        # create list with the key-value-pairs
        post.custom_fields = [self.image, self.date, self.time, self.timestamp]

        # publish the Posts according to the default setting or set different post status according to PostBasicInformation.
        if 'post_status' in self.post_configuration.postBasicInformation:
            post.post_status = self.post_configuration.postBasicInformation.get(
                'post_status')

        # Generate the post
        cms.call(NewPost(post))


#==========================================================================
# END
#==========================================================================
Esempio n. 27
0
    def editPost(self, postID, sourceUrl, title, featureImg, content, category,
                 tags, customField):
        post = WordPressPost()
        post.title = title  #标题
        post.content = content  #内容
        post.post_status = 'publish'
        #文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
        imgList = []  #图片列表
        if customField != {}:
            try:
                if customField["imgList"]:
                    imgList = customField["imgList"]
                else:
                    imgList = str(imgList)
            except KeyError:
                print("customField中没有imgList这个图片列表")

        if not category:
            category = [
                'other',
            ]
        post.category = category
        print(post.category, type(post.category))

        if tags:
            post.terms_names = {
                'post_tag': tags,  #文章所属标签,没有则自动创建
                'category': post.category  #文章所属分类,没有则自动创建
            }
        else:
            post.terms_names = {'post_tag': '', 'category': post.category}

        #自定义字段列表
        post.custom_fields = []
        #添加自定义字段内容
        if postID == '0':
            for key in customField:
                post.custom_fields.append({
                    'key': key,
                    'value': customField[key]
                })
                #print('post.custom_fields',type(post.custom_fields),post.custom_fields)
        else:
            for n in range(len(post.custom_fields)):
                for key in customField:
                    if post.custom_fields[n][
                            'key'] == key and post.custom_fields[n][
                                'value'] != customField[key]:
                        post.custom_fields[n]['value'] = customField[key]

        #如果特色图片存在,上传特色图片
        if featureImg:
            img_name = featureImg.split('/')[-1]
            filename = featureImg
            data = {'name': img_name, 'type': 'image/jpeg'}
            with open(filename, 'rb') as img:
                data['bits'] = xmlrpc_client.Binary(img.read())
            response = self.wp.call(media.UploadFile(data))
            attachment_id = response['id']
            post.thumbnail = attachment_id
        if postID == '0':
            postID = self.wp.call(NewPost(post))
            print('正在发布[ID]:%s,[标题]:%s' % (postID, post.title))
        else:
            self.wp.call(EditPost(postID, post))
            print('正在修正[ID]:%s,[标题]:%s' % (postID, post.title))
        return postID
Esempio n. 28
0
    def postBlog(self, new_blog):
        print('正在发布:', new_blog[1])
        post = WordPressPost()
        # post.post_ID = new_blog[0]
        # post.id = new_blog[0]
        post.title = new_blog[1]
        post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布

        comic_type = '热血'
        # 漫画封面
        comic_cover = '<img src="' + new_blog[
            3] + '" alt="" class="aligncenter size-full wp-image-154" />'

        try:
            # 进入漫画详情页
            comic_html = self.get_html(new_blog[7])
            # 漫画详情信息区域
            comic_detail = comic_html.find('div',
                                           {'class': 'banner_detail_form'})
            # 漫画封面
            comic_img = comic_detail.find('div', {
                'class': 'cover'
            }).find('img')['src']
            comic_cover = '<img src="' + comic_img + '" alt="" class="aligncenter size-full wp-image-154" />'
            new_blog[3] = comic_img
            # 漫画内容简介
            print(comic_detail.find('p', {'class': 'content'}))
            content_html = comic_detail.find('p', {'class': 'content'})
            comic_content = comic_detail.find('p', {'class': 'content'}).text
            if content_html != None and comic_content:
                comic_content = comic_content.replace('\u3000', '').replace(
                    '\xa0', '').replace('[+展开]', '').replace('[-折叠]', '')
            else:
                comic_content = new_blog[4].replace('\u3000', '').replace(
                    '\xa0', '').replace('[+展开]', '').replace('[-折叠]', '')
            print('1.comic_content:' + comic_content)
            post.content = '<blockquote style="text-indent: 30px;">' + comic_content + '</blockquote>' + comic_cover
            # 连载状态,及分类
            comic_info_list = comic_detail.find_all('span', {'class': 'block'})
            # print(comic_info_list)
            if len(comic_info_list) > 1:
                comic_type = comic_info_list[1].find('span').text
                print(comic_type)
            else:
                comic_type = '其他'
            post.terms_names = {
                'post_tag': [comic_type],  # 文章所属标签,没有则自动创建
                'category': ['港台漫画']  # 文章所属分类,没有则自动创建
            }
        except:
            print('2.comic_content:=====' + new_blog[4])
            new_blog[4] = new_blog[4].replace('\u3000', '').replace(
                '\xa0', '').replace('[+展开]', '').replace('[-折叠]', '')
            post.content = '<blockquote style="text-indent: 30px;">' + new_blog[
                4] + '</blockquote>' + comic_cover
            post.terms_names = {
                'post_tag': [comic_type],  # 文章所属标签,没有则自动创建
                'category': ['港台漫画']  # 文章所属分类,没有则自动创建
            }

        post.custom_fields = []  # 自定义字段列表
        # 资源价格
        post.custom_fields.append({'key': 'cao_price', 'value': 2})
        # VIP折扣
        post.custom_fields.append({'key': 'cao_vip_rate', 'value': 0})
        # 仅限永久VIP免费
        post.custom_fields.append({'key': 'cao_is_boosvip', 'value': 0})
        # 启用付费下载资源
        post.custom_fields.append({'key': 'cao_status', 'value': 1})
        # 资源类型
        post.custom_fields.append({'key': 'wppay_type', 'value': 4})
        # 资源下载地址
        post.custom_fields.append({'key': 'cao_downurl', 'value': new_blog[8]})
        # 资源下载密码
        post.custom_fields.append({'key': 'cao_pwd', 'value': new_blog[9]})
        # 资源下载次数
        post.custom_fields.append({
            'key': 'cao_paynum',
            'value': random.randint(1, 50)
        })
        # 资源其他信息
        post.custom_fields.append({
            'key':
            'cao_info',
            'value': [{
                'title': '作   者',
                'desc': new_blog[2]
            }, {
                'title': '题材类型',
                'desc': comic_type
            }, {
                'title': '最近更新',
                'desc': new_blog[6]
            }, {
                'title': '是否完结',
                'desc': new_blog[5]
            }]
        })
        try:
            self.wp.call(posts.NewPost(post))
        except:
            pass
Esempio n. 29
0
}

# 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.')


# ### 画像のアップロード
# 
# 画像付きの記事をアップロードするときは、最初に記事単体をアップロードし、そのID(メディアID)を取得し、記事をアップロードする際、そのIDを指定することで実行します。画像をアップロードするサンプルコードは以下の通りです。

# In[ ]:

#! /usr/bin/env python
import sys
# Librerias de python para wordpress
# pip install python-wordpress-xmlrpc
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
from wordpress_xmlrpc.methods import media, posts
try:
    wp = Client('http://localhost/wordpress/xmlrpc.php', 'admin', '^Oy7AX(iZ4#3f3#G9q')
    #Insert en el sistema wordpress
    post = WordPressPost()
    post.title = "Demo insert post desde Python"
    post.content = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    post.post_status = 'publish'
    post.terms_names = {'post_tag': ['demo-python'],'category': ['desarrollo']}
    post.custom_fields = []
    post.custom_fields.append({'_demo':'1200'})
    wp.call(NewPost(post))
except Exception as e:
    sys.exit(e)
Esempio n. 31
0
feed = graph.get(USER_ID + '?fields=feed.order(chronological).limit(100)')

#Create an instance of WP client
wp = Client(WP_SITE_LINK, WP_USERNAME, WP_PASSWORD)

wp_posts = wp.call(posts.GetPosts({'number': 1000, 'orderby': 'date', 'order': 'DESC', 'post_status': 'publish'}))

#Create a list of all existing FB ids in our blog
wp_post_fb_ids = []
for wp_post in wp_posts:
  wp_post_fb_ids.append(wp_post.custom_fields[0]['value'])

#Check if FB post contains 'message' field 
user_posts = []
for post in feed['feed']['data']:
  if post['id'] in wp_post_fb_ids:
    print('Post is already in database')
  else:
    if 'message' in post:
      user_posts.append(post)
      print('Post with id ' + post['id'] + ' was added to the database')

for user_post in user_posts:
  #Post creation and publishing
  post = WordPressPost()
  post.title = 'Exciting new post: ' + user_post['id']
  post.content = user_post['message']
  post.post_status = 'publish'
  post.custom_fields = [{'key': 'facebook_id', 'value': user_post['id']}]
  wp.call(NewPost(post))
Esempio n. 32
0
def toWP(single_event):

    #tituloFoto = uuid.uuid4()
    tituloFoto = randomword(9)

    data = {
        'name': tituloFoto + '.jpg',
        'type': 'image/jpeg',  # mimetype
    }

    file = get_url_content(single_event['foto'])

    data['bits'] = xmlrpc_client.Binary(file)

    response = client.call(media.UploadFile(data))

    attachment_id = response['id']
    widget = WordPressPost()
    widget.post_type = 'event_type'
    widget.title = single_event['title']
    widget.content = single_event['descripcion']
    widget.thumbnail = attachment_id
    widget.custom_fields = []
    widget.custom_fields.append({
        'key': 'coord',
        'value': {
            "address": single_event['direccion'],
            "lat": single_event['latitude'],
            "lng": single_event['longitude']
        }
    })
    widget.custom_fields.append({
        'key': 'fecha_inicio',
        'value': single_event['fecha_inicio']
    })
    widget.custom_fields.append({
        'key': 'direccion',
        'value': single_event['direccion']
    })
    widget.custom_fields.append({
        'key': 'fecha_fin',
        'value': single_event['fecha_fin']
    })
    widget.custom_fields.append({'key': 'telefono', 'value': ""})
    widget.custom_fields.append({'key': 'correo_electronico', 'value': ""})
    widget.custom_fields.append({
        'key': 'pagina_web',
        'value': "www.peque-agenda.com"
    })
    widget.custom_fields.append({
        'key':
        'edad',
        'value':
        single_event['edadMin'] + ';' + single_event['edadMax']
    })
    widget.custom_fields.append({
        'key': 'precio',
        'value': single_event['precio']
    })
    widget.custom_fields.append({
        'key': 'imagen_evento',
        'value': randint(400, 718)
    })

    widget.id = client.call(posts.NewPost(widget))
def scrapedeals(url):
    try:
        print 'Going With %s' %(url)
        dealspagesource = requests.get(url).text
        soup = BeautifulSoup(dealspagesource)
        boxes = soup.find_all('div',class_='box')
        for box in boxes:
            try:
                dealurlfind = box.find('a',id=re.compile('A_*'))
                dealurl = dealurlfind['href']
                dealtitle = dealurlfind['title']
                dealtitle = dealtitle.replace('snapdeal','')
                dealtitle = dealtitle.replace('Snapdeal','')
                #dealtitle = unescape(dealtitle)
                dealshopurl = box.find('a',id='shop_now')['href'].replace('http://dealschintu.com/url.php?url=','')
                if '&uid=' in dealshopurl:
                    dealshopurl = dealshopurl[:dealshopurl.index('&uid=')]
                #print dealshopurl
                #print dealtitle
                #print dealurl
                originalprice = box.find('div',id='DIV_12').text.lstrip().rstrip()
                discountprice = box.find('div',id='DIV_13').text.lstrip().rstrip()
                #print originalprice.lstrip().rstrip()
                #print discountprice.lstrip().rstrip()
                #print 'Got Box Details'
                if 'threads' in dealurl:
                    post = WordPressPost()
                    dealurlsource = requests.get(dealurl).text
                    print 'Loaded Deal Url'
                    dealsoup = BeautifulSoup(dealurlsource)
                    article = dealsoup.find('div',class_="messageContent")
                    article = str(article).replace('<br/>','')
                    #print article
                    imgurlnode = dealsoup.find('img',class_="bbCodeImage LbImage")['src']
                    #print imgurlnode
                    urllib.urlretrieve(imgurlnode,os.path.basename(imgurlnode))
                    filename = os.path.basename(imgurlnode)
                    data = {
                        'name' : os.path.basename(imgurlnode),
                        'type': mimetypes.guess_type(filename)[0],
                        }
                    with open(filename, 'rb') as img:
                        data['bits'] = xmlrpc_client.Binary(img.read())
                    response = wp.call(media.UploadFile(data))
                    #print response
                    attachmenturl = response['url']
                    #print attachmenturl
                    attachment_id = response['id']
                    post.thumbnail = attachment_id #Setting Feautured Image
                    post.terms_names = {
                                'category': ['SnapDeal'] #Change Category Here
                                }
                    post.title = dealtitle
                    post.custom_fields = []
                    post.custom_fields.append({
                        'key' : 'disable_parts',
                        'value' : 0})
                    post.custom_fields.append({
                        'key' : 'filter_featured_for',
                        'value' : 'featured_for_slider'})
                    post.custom_fields.append({
                        'key' : 'is_editor_choice',
                        'value' : 0})
                    post.custom_fields.append({
                        'key' : 'is_featured',
                        'value' : 0})
                    post.custom_fields.append({
                        'key' : 'meta_data_filter_cat',
                        'value' : -1})
                    post.custom_fields.append({
                        'key' : 'post_size',
                        'value' : 'normal_post'})
                    post.custom_fields.append({
                        'key' : 'rehub_framework_post_type',
                        'value' : 'regular'})
                    post.custom_fields.append({
                        'key' : 'rehub_main_product_price',
                        'value' : originalprice })
                    post.custom_fields.append({
                        'key' : 'rehub_offer_btn_text',
                        'value' : 'Check Latest Price'})
                    post.custom_fields.append({
                        'key' : 'rehub_offer_logo_url',
                        'value' : 'http://couponsmama.in/wp-content/uploads/2015/08/snapdealbrand.jpg'})
                    post.custom_fields.append({
                        'key' : 'rehub_offer_name',
                        'value' : dealtitle})
                    post.custom_fields.append({
                        'key' : 'rehub_offer_product_desc',
                        'value' : dealtitle})
                    post.custom_fields.append({
                        'key' : 'rehub_offer_product_price',
                        'value' : discountprice})
                    post.custom_fields.append({
                        'key' : 'rehub_offer_product_price_old',
                        'value' : originalprice})
                    post.custom_fields.append({
                        'key' : 'show_featured_image',
                        'value' : 1})
                    post.custom_fields.append({
                        'key' : 'rehub_offer_product_thumb',
                        'value' : attachmenturl})
                    post.custom_fields.append({
                        'key' : 'rehub_offer_product_url',
                        'value' : dealshopurl})
                    post.custom_fields.append({
                        'key' : 'rehub_post_side[show_featured_image]',
                        'value' : 0})
                    content = article.replace(imgurlnode,attachmenturl)
                    content = remove_img_tags(content)
                    #content = unescape(content)
                    post.content = content
                    post.post_status = 'publish'
                    wp.call(NewPost(post))
                    print 'Posted at %s' %(dealtitle)
                #raw_input()
            except:
                print 'Error at %s' %(dealtitle)
                pass
        #print 'Completed Page %s' %(url)
    except:
        pass
Esempio n. 34
0
def getCatalogos(url):
    try:
        print("Scrapping la url: "+url+"\n")
        page = 1
        r = requests.get(url+"?p="+str(page))
        soup = bs.BeautifulSoup(r.content, 'html.parser')
        category = soup.find('span',class_="category")
        print("Categoria: "+category.text.strip()+"\n")
        category = category.text.strip()
        filename = 'scrappingCuracao_' + category + '.csv'
        product_items = soup.find_all('div',class_="product-item-info")
        #f = open(filename, "wb")

        for product_info in product_items:
            img = product_info.find('img',class_="product-image-photo")
            img = img["src"]
            brand = product_info.find('strong',class_="product-item-category")
            if brand is not None:
                brand = brand.text.strip()
            else:
                brand = ''
            link = product_info.find('a',class_="product-item-link")
            name = link.text.strip()
            link = link["href"]
            price_box = product_info.find('div',class_="price-box")
            prices = price_box.find_all('span',class_="price-wrapper")
            old_price = ""
            final_price = ""

            if prices is not None:
                for price in prices:

                    if price["data-price-type"] == "oldPrice":
                        old_price = price["data-price-amount"]

                    if price["data-price-type"] == "finalPrice":
                        final_price = price["data-price-amount"]

            id = price_box["data-product-id"]

            print("<img width=\"200\" height=\"200\" src=\"" + str(img) + "\" /><br><strong>" + u''.join(name).encode('utf-8').strip() + "</strong><br><h1>Precio Anterior: " + str(old_price) + "</h1><br><h1>Nuevo Precio: " + str(final_price) + "</h1><br><a href=\"" + link + "\" target=\"_blank\" >Click Aqui</a>\n")

            wp = Client('http://35.193.40.235/xmlrpc.php', 'user', 'WG2RXkar0SGt')
            # Insert en el sistema wordpress
            post = WordPressPost()
            post.title = u''.join((str(name),"<img width=\"200\" height=\"200\" src=\""+str(img)+"\" />"))
            post.content = "<h1>Precio Anterior: "+str(old_price)+"</h1><br><h1>Nuevo Precio: "+str(final_price)+"</h1><br><a href=\""+link+"\" target=\"_blank\" >Click Aqui</a>"
            post.post_status = 'publish'
            post.terms_names = {'post_tag': ['demo-python'], 'category': [u''.join(category).encode('utf-8').strip()]}
            post.custom_fields = []
            post.custom_fields.append({'_demo': '1200'})
            wp.call(NewPost(post))

        pages = soup.find('li',class_="item pages-item-next")
        if pages != None:
            next_url = pages.a["href"]

            getCatalogos(next_url)


    except Exception as e:
        sys.exit(e)
Esempio n. 35
0
def post_article(title, content, first_img, author, source_url, source_name, delivery_url, delivery_name, class_, tmpdir):
    client = Client(LF_XMLRPC_URL, LF_XMLRPC_USER, LF_XMLRPC_PASS)

    retry = 5
    if first_img:
        logger.debug('Download image %s' % first_img)
        img_path = get_img(first_img, tmpdir)
        logger.debug('Download article\'s first image to %s' % img_path)

    ret = None
    if first_img:
        for i in xrange(retry):
            ret = upload_file_to_wp(client, img_path)
            if ret:
                break
        else:
            raise CanNotUploadException('xmlrpc upload %s' % img_path)

    attachment_id = ret

    # Download all image file, and put it into static directory in web server,
    # and replace URL in the article content.

    content_obj = BeautifulSoup(content)
    img_tags = content_obj.find_all('img', recursive=True)
    from hashlib import md5
    hex_dir = md5(title.encode('utf-8')).hexdigest()
    img_paths = []
    img_src_list = []
    for img in img_tags:
        if img and img.has_attr('src'):
            img_path = get_img(img.attrs['src'], tmpdir)
            img_paths.append(img_path)
            img_src_list.append(img.attrs['src'])

    img_host_list = copy_to_web_server(img_paths, hex_dir)
    if len(img_host_list) != len(img_src_list):
        raise CanNotUploadException('ftp upload file length not match, local(%s), remote(%s)' % (len(img_src_list), len(img_host_list)))

    for x in xrange(len(img_src_list)):
        img_src_list[x] = img_host_list[x]

    post = WordPressPost()
    post.title = title
    post.content = str(content_obj)
    #post.post_status = 'publish'
    if first_img:
        post.thumbnail = attachment_id
    post.terms_names = {
        # TODO: add tags
        #'post_tag': ['tagA', 'another tag'],
        'category': ['公社推送', ],
    }
    post.custom_fields = []
    post.custom_fields.append({
        'key': 'source_url',
        'value': source_url
    })
    post.custom_fields.append({
        'key': 'source_name',
        'value': source_name
    })
    post.custom_fields.append({
        'key': 'delivery_name',
        'value': delivery_name
    })
    post.custom_fields.append({
        'key': 'delivery_url',
        'value': delivery_url
    })
    post.id = client.call(posts.NewPost(post))
Esempio n. 36
0
def wordpress_post(config):
    print("Connecting to: " + config.wordpress['xmlrpc'])
    wp = Client(config.wordpress['xmlrpc'], config.wordpress['username'],
                config.wordpress['password'])

    if config.attach_header:
        print("Uploading header image...")
        # Upload header image
        data = {
            'name': os.path.basename(config.png_header_file),
            'type': 'image/png',
        }

        # Read the image and let the XMLRPC library encode it to base64
        with open(config.png_header_file, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())

        response = wp.call(media.UploadFile(data))
        attachment_id = response['id']

    print("Posting blog...")
    post = WordPressPost()
    post.title = config.wordpress['title']
    post.content = config.wordpress['content']
    post.post_format = config.wordpress['post_format']
    post.post_status = config.wordpress['post_status']
    post.comment_status = config.wordpress['comment_status']
    if config.attach_header:
        post.thumbnail = attachment_id

    # FIXME: Make sure tags and category are defined. Don't assume they are.
    post.terms_names = {
        'post_tag': [config.wordpress['tags']],
        'category': [config.wordpress['category']]
    }

    url = config.wordpress['uploads_url'].format(config.season, config.episode,
                                                 config.mp3_file)

    if config.wordpress['podcast_plugin'] == 'Powerpress':
        config = get_audio_size_and_duration(config)

        enclosureData = {
            'duration': config.mp3['duration'],
            'size': config.mp3['size'],
            ### Below items are best left undefined unless we really
            ### want to force their settings per upload.
            # 'embed':       True,
            # 'keywords':    '',
            # 'subtitle':    '',
            # 'summary':     '',
            # 'gp_desc':     '',
            # 'gp_explicit': False,
            # 'gp_block':    '',
            # 'author':      '',
            # 'no_player':   False,
            # 'no_links':    False,
            # 'explicit':    False,
            # 'cc':          '',
            # 'order':       0,
            # 'always':      '',
            # 'block':       '',
            # 'image':       '',
            # 'ishd':        False, # Is an HD Video
            # 'height':      0,     # Video Height
            # 'width':       0,     # Video Width
            # 'webm_src':    '',
            # 'feed_title':  '',
        }

        post.custom_fields = []
        post.custom_fields.append({
            'key':
            'enclosure',
            'value':
            "{}\n{}\n{}\n{}".format(url, config.mp3['size'],
                                    config.tags['podcast_type'] or 'episodic',
                                    dumps(enclosureData).decode('ascii')),
        })

    post.id = wp.call(NewPost(post))
Esempio n. 37
0
                'tag_list': 'list-of-tags',
                'asset_data': open('audio/' + SoundCloudURL, 'rb')
            })
            
#get the url of the uploaded SoundCloud post
            SoundCloudURL = track.permalink_url
        
        
        #create the wordpress post
        
        post = WordPressPost()
        
        post.title = 'Chapter ' + str(chapNum) + ': ' + chapTitle
        HTMLtitle = '<span class="altcolor">Chapter ' + str(chapNum) + ':</span> ' + chapTitle
        
        post.custom_fields = []
        post.custom_fields.append({'key': 'HTML_title','value': HTMLtitle})
        
        post.content = '<span class="list-text"><em><strong>Read by ' + Reader + '</strong></em>\n'
        post.content = post.content + '<em>Artist: ' + Artist + '</em></span>\n'
        post.content = post.content + '<!--more-->\n'
        post.content = post.content + '<div id="the_player">\n'
        post.content = post.content + '<strong>Read by ' + Reader + '</strong>\n'
        if Recorder != 'none':
            post.content = post.content + 'Introduced by Peter Donaldson and Recorded by '+Recorder+'\n'
        else:
            post.content = post.content + 'Introduced by Peter Donaldson <span class=\"invisRec\">Recorded by '+Recorder+'</span>\n'
        post.content = post.content + '<a class="sc-player" href="'+SoundCloudURL+'">'+chapTitle+'</a>\n'
        
        post.content = post.content + '</div>\n'
        post.content = post.content + '<div class="bigborder artwork">\n'