Пример #1
0
    def post_article(self, wpUrl, wpUserName, wpPassword, articleCategories,
                     path):
        self.path = path
        self.wpUrl = wpUrl
        self.wpUserName = wpUserName
        self.wpPassword = wpPassword

        client = Client(self.wpUrl, self.wpUserName, self.wpPassword)
        filename = self.path

        try:
            myFile = open(filename, "r")
            rawText = myFile.read()
            rawText = rawText.decode('latin-1')
            myFile.close()
            articleTitle = remove_tags(rawText)
            articleContent = rawText
            post = WordPressPost()
            post.title = articleTitle[:90]
            post.content = articleContent
            post.terms_names = {'category': articleCategories}
            post.post_status = 'publish'
            post.mime_type = "text/html"
            post.id = client.call(posts.NewPost(post))
            print("success : " + os.path.basename(path))
            os.remove(path)
        except (Exception, e):
            print("error : " + os.path.basename(path))
            print(e)
Пример #2
0
    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}
def add_movies(page_num, choice):

    while True:

        if (choice == 'a' or choice == 'upcoming'):
            term_tag = 'upcoming'
            term_cat = 'upcoming'
            get_url = "/3/movie/upcoming?page=" + str(
                page_num
            ) + "&language=en-US&api_key=eedcd0a42e1921c7f3da84ad5fdeaa2a"

        if (choice == 'b' or choice == 'nowplaying'):
            term_tag = 'Now playing'
            term_cat = 'now_playing'
            get_url = "/3/movie/now_playing?page=" + str(
                page_num
            ) + "&language=en-US&api_key=eedcd0a42e1921c7f3da84ad5fdeaa2a"

        if (choice == 'c' or choice == 'archives' or choice == 'archive'):

            term_tag = 'archives'
            term_cat = 'archives'
            get_url = "/3/discover/movie?page=" + str(
                page_num) + "&language=en-US&primary_release_date.lte=" + str(
                    date) + "&api_key=eedcd0a42e1921c7f3da84ad5fdeaa2a"
        try:
            #making the connection to the api
            print("making the connection")
            conn = http.client.HTTPSConnection("api.themoviedb.org")
            payload = "{}"
            print("getting all the movies from page " + str(page_num))

            #getting the movies data , key = now playing
            print("making the api req")
            #print(get_url , term_cat , term_tag)

            conn.request("GET", get_url, payload)
            res = conn.getresponse()
            data = res.read()
            response = json.loads(data.decode("utf-8"))

            #connecting to wordpress
            wp = Client('http://172.104.189.102/xmlrpc.php', 'octraves',
                        'octraves')

            # THE MAIN LOOP FOR ADDING ALL THE MOVIES TO THE WP DATABASE
            counter = 1
            for movie in response['results']:
                try:

                    print("Adding movie number = " + str(counter) + "id :  " +
                          str(movie['id']))
                    #download and upload the image to wordpress
                    url = "http://image.tmdb.org/t/p/w200" + movie[
                        'poster_path']
                    image_name = str(movie['id']) + '.jpg'
                    image_location = '/Users/user/Desktop/wordpress_images/' + image_name
                    urllib.request.urlretrieve(
                        url, image_location)  # download the image
                    image = image_location
                    imageType = mimetypes.guess_type(str(image))[0]
                    img_data = {
                        'name': image_name,
                        'type': imageType,
                    }
                    with open(image, 'rb') as img:
                        img_data['bits'] = xmlrpc_client.Binary(img.read())

                    img_response = wp.call(media.UploadFile(img_data))
                    attachment_id = img_response[
                        'id']  # id to be appended in post

                    #getting the trailer
                    try:
                        link = details.get_trailer(movie['id'])
                    except:
                        link = ""
                        pass

                    # Creating custom fields
                    fields = [['Languages', movie['original_language']],
                              ['Release Date', movie['release_date']]]

                    # Creating the post
                    post = WordPressPost()
                    post.title = movie['title']
                    post.post_type = 'post'
                    post.mime_type = "text/html"
                    post.content = genres.get_primary_info(
                        movie['id']
                    ) + """<h3> Overview </h3> """ + movie[
                        'overview'] + """<h3> Trailer </h3> """ + " \n" + link + " \n" + " \n" + " \n" + """<h3> Credits </h3> """ + " \n" + " \n" + " \n" + str(
                            details.get_credits(movie['id'],
                                                'cast')) + details.get_poster(
                                                    movie['id'])

                    post.thumbnail = attachment_id
                    post.terms_names = {
                        'post_tag': [term_tag],
                        term_cat: genres.get_genres(movie['genre_ids']),
                        'category': genres.get_genres(movie['genre_ids'])
                    }

                    post.custom_fields = []
                    for field in fields:
                        post.custom_fields.append({
                            'key': field[0],
                            'value': field[1]
                        })
                    post.post_status = 'publish'
                    post.comment_status = 'open'

                    #finally publish the post !!
                    post.id = wp.call(posts.NewPost(post))

                    #add comments
                    reviews = details.get_reviews(movie['id'])
                    for review in reviews:
                        comment = WordPressComment()
                        comment.author = review['author']
                        comment.content = review['content']
                        wp.call(comments.NewComment(post.id, comment))

                    counter += 1

                except Exception as e:
                    print(
                        "All the pages have been processed or there is a error!!  "
                        + str(e))
                    pass

            print("Page number " + str(page_num) +
                  " is completed ! Loading another page.")

            page_num += 1

        except Exception as e:
            print(str(e))
Пример #4
0
                continue
            if not tag: continue
            if getImageSrc(tag) != '':
                img_id = imageUpload(getImageSrc(tag), alias, i=i)
            else:
                continue
            img_tag = '<!-- wp:image {"id":%s,"sizeSlug":"large"} --><figure class="wp-block-image size-large"><img src="%s" alt="" class="wp-image-%s"/></figure><!-- /wp:image -->' % (
                img_id['id'], img_id['link'], img_id['id'])
            content += img_tag
            i += 1
            continue

        try:
            content += tag.prettify()
        except Exception as e:
            print('Exception: %s' % e)

    img_id = imageUpload(image, alias)

    post = WordPressPost()
    post.title = soup.find(class_='article__title').text
    post.content = content
    post.mime_type = "text/html"
    post.user = 2  # WP Author ID
    post.link = alias
    post.post_type = "post"
    post.thumbnail = img_id['id']
    post.post_status = "publish"  # "draft"
    post_id = client.call(posts.NewPost(post))
    print("Post: %s (%s) Done!" % (post_id, alias))