Ejemplo n.º 1
0
 def media_item_generator(self, parent_id=None):
     """Generates WordPress attachment objects."""
     for media_item in self._wp.call(
             media.GetMediaLibrary(
                 {'parent_id': parent_id and str(parent_id)})):
         wp_image = WordPressImageAttachment.fromWpMediaItem(media_item)
         logger.debug(u'Yielding WordPress media item %s', wp_image)
         yield wp_image
Ejemplo n.º 2
0
def uploadArtwork(artist, album):
    imagePath = os.path.join(artistPath, artist, 'Albums', album, 'cover.jpg')
    name = (re.sub('[!|(|)|.|,|#|?|\']', '', artist) + '-' +
            re.sub('[!|(|)|.|,|#|?\']', '', album)).replace(' ', '-') + '.jpg'
    mediaLibrary = wp.call(media.GetMediaLibrary({}))
    for item in mediaLibrary:
        if (ensureUtf(item.title) == name):
            print('Image for ' + name + ' already exists')
            return item.id
    data = {'name': name, 'type': 'image/jpeg'}
    with open(imagePath, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = wp.call(media.UploadFile(data))
    return response['id']
def importNewUser():
	BASE_DIR = os.path.dirname(os.path.abspath(__file__))
	IMG_DIR = os.path.join(BASE_DIR, "images")

	site = Client('http://192.168.137.26/xmlrpc.php', '*****@*****.**', 'Bpl2 vF31 ePl6 Unoa rAcC kJGm')
	# This IP is dependent on the wordpress site being hosted on my laptop's hotspot.

	recently_modified = site.call(posts.GetPosts({'orderby': 'post_modified', 'number': 100}))
	# Get the most recent 100 posts (Would theoretically break if we did 100 random posts and then added a new user post,
	# can expand number if needed

	media_library = site.call(media.GetMediaLibrary([]))  # Get media library of database
	new_users = []
	added_new_user = False
	for post in recently_modified:
		terms = post.terms
		for term in terms:
			if 'New User' == term.name and post not in new_users:
				new_users.append(post)
				added_new_user = True
	# We are only interested in posts with the category "New User", so keep track of those

	# Should be deleting requests after each message
	# Or maybe add a tag that says "Processed" to keep history? That way it is ignored on a second call to this script

	post_id = new_users[0].id
	# In theory, we would only process 1 new user post at a time and then either delete the post or
	# add a tag that prevents future processing (i.e. the list will always have only 1 post in it)

	photo_links = re.findall("class=\"wp-image-([\d]+)\"", new_users[0].content)
	print(photo_links)
	# Get the media attachment ids for the post

	for m in media_library:
		if str(m.id)in photo_links:
			print(m)
			print(m.link)
			resp = requests.get(m.link, stream=True)
			local_name = "Temp_Pictures/get_image_test{}.jpeg".format(media_library.index(m))
			local = open(local_name, "wb")
			resp.raw.decode_content = True
			shutil.copyfileobj(resp.raw, local)
			del resp
	# Using the attachment ids, get pictures from media library and use links to download pictures to a temporary folder
	# on the pi
	# Temp folder can be used by main.py to import the new images and create a new recognizer
	return added_new_user
Ejemplo n.º 4
0
def getNewUser():
    recently_modified = site.call(posts.GetPosts({'orderby': 'post_modified', 'number': 10}))
    # Get the most recent 10 posts (Would theoretically break if we did 10 random posts and then added a new user post, can expand number if needed

    media_library = site.call(WordpressMedia.GetMediaLibrary([])) #Get media library of database
    new_users = []
    for post in recently_modified:
        names = [term.name for term in post.terms]
        if 'Processed' in names:
            pass
        elif 'New User' in names and post not in new_users:
            new_users.append(post)
            proc_tag = [tag for tag in site.call(taxonomies.GetTerms('post_tag')) if tag.name == "Processed"]
            print(proc_tag)
            post.terms.append(proc_tag[0])
            site.call(posts.EditPost(post.id, post))
            break
    # We are only interested in posts with the catagory "New User", so keep track of those
    if len(new_users) >= 1:
        post_id = new_users[0].id 
        #In theory, we would only process 1 new user post at a time; the most recent post

        photo_links = re.findall("class=\"wp-image-([\d]+)\"", new_users[0].content)
        # Get the media attachment ids for the post 
        directory = "images/" + new_users[0].title
        os.makedirs(directory)
        
        for media in media_library:
            if str(media.id)in photo_links:	
                resp = requests.get(media.link, stream=True)
                local_name = directory + "/{}.jpeg".format(media_library.index(media))
                local = open(local_name, "wb")
                resp.raw.decode_content = True
                shutil.copyfileobj(resp.raw, local)
                del resp
        _trainModel()
Ejemplo n.º 5
0
from wordpress_xmlrpc import *
from wordpress_xmlrpc.methods import media
from wordpress_xmlrpc.methods import posts
from urllib.request import urlopen
import urllib
import io
client = Client('http://actandcare.fr/xmlrpc.php', 'marie', 'mariaure1977')
images = client.call(media.GetMediaLibrary({'mime_type': 'image/jpeg'}))
chs = client.call(posts.GetPosts({
    'post_type': 'tribe_venue',
    'number': 10000
}))
imgs = []


class Image:
    def __init__(self, link, title):
        self.file = 0
        self.link = link
        self.title = title
        imgs.append(self)

    def setFile(self, file):
        self.file = file


for i in images:
    Image(i.link, i.title)


def getImages(d=[0, 12]):
Ejemplo n.º 6
0
 def _find_media(self, filename):
     try:
         fid = self.wp.call(media.GetMediaLibrary(filename))[0].id
     except:
         fid = False
     return fid
Ejemplo n.º 7
0
import csv
import sys
import codecs
import platform
import datetime
import pymysql.cursors
import phpserialize
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import media, posts, taxonomies

wp_url = 'http://www.smochimusic.com/xmlrpc.php'
wp_username = '******'
wp_password = raw_input("WP Password: "******"DB Password: ")
connection = pymysql.connect(host='smochimusic.com',
                             user='******',
                             password=db_password,
                             db='smochimu_wp153',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)


def getPostList():
    postList = wp.call(
        posts.GetPosts({
            'post_type': 'download',
            'number': 999999
        }))
    except InvalidCredentialsError:
        print("Invalid credentials")
        sys.exit(1)

    folder = os.path.abspath(args.folder)
    #folder = os.path.join(folder, dt.date.today().isoformat())

    ensure_folder_exists(folder)

    if args.media:
        media_path = os.path.join(folder, 'media')

        ensure_folder_exists(media_path)

        if args.debug: print("Fetching media library list...")
        media_list = wp.call(media.GetMediaLibrary({}))
        if args.debug:
            print("The media library contains {} items. Saving them now...".
                  format(len(media_list)))

        for m in media_list:
            m_path = '.' + urlparse(m.link).path
            m_full_path = os.path.join(folder, m_path)
            m_dict = {
                'id': m.id,
                'parent': m.parent,
                'title': m.title,
                'description': m.description,
                'caption': m.caption,
                'date_created': m.date_created.isoformat(),
                'link': m.link,
Ejemplo n.º 9
0
 def test_get_media_library(self):
     num_items = 10
     library = self.client.call(media.GetMediaLibrary({'number':
                                                       num_items}))
     self.assert_list_of_classes(library, WordPressMedia)
     self.assertTrue(len(library) <= num_items)