Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

split into functions, fix ext handling, enhance printouts #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 101 additions & 67 deletions flickr-folder-uploader.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,102 +6,136 @@

# Get an api key and an api secret: https://www.flickr.com/services/apps/create/apply
# Put those values in these variables
import flickrapi
import os
import sys
import argparse
import re

API_KEY = "paste-your-api-key-here"
API_SECRET = "paste-your-api-secret-here"
USER_ID = "paste-your-user-id-here"

# Start this script. First time it shows an URL. Open it with your browser and authorize the script.

# Once authorized, script will store a token in user home directory. Change it if desired:
#TOKEN_CACHE='./token'
TOKEN_CACHE = './token'

import flickrapi
import os
import sys
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("folder", help="Path to the folder you want to upload")
parser.add_argument("-t", "--tags", help="One or more tags for all the files (use quotes if needed)")
parser.add_argument("-n", "--name", help="Name of the set (use quotes if needed)")
params=parser.parse_args()
def parse_input_args():
parser = argparse.ArgumentParser()
parser.add_argument("folder", help="Path to the folder you want to upload")
parser.add_argument("-t", "--tags", help="One or more tags for all the files (use quotes if needed)")
parser.add_argument("-n", "--name", help="Name of the set (use quotes if needed)")
params = parser.parse_args()

folder = os.path.abspath(params.folder) + "/"

FOLDER=os.path.abspath(params.folder)+"/"
if params.name:
title = params.name
else:
title = os.path.basename(os.path.normpath(params.folder))
if params.tags:
tags = params.tags
else:
tags = "synology-nas-uploaded"

if params.name:
TITLE=params.name
else:
TITLE=os.path.basename(os.path.normpath(params.folder))
if params.tags:
TAGS=params.tags
else:
TAGS="synology-nas-uploaded"
print "Uploading", folder, "to", title, "with tags:", tags
return {'folder': folder, 'title': title, 'tags': tags}

print "Uploading", FOLDER, "to", TITLE, "with tags:", TAGS

def create_set(name, primary_photo_id):
try:
print "Creating set.", name,
resp = flickr.photosets.create(title=name, primary_photo_id=primary_photo_id)
photoset_id = resp.find('photoset').attrib['id']
print 'OK. Set id = ', photoset_id
return photoset_id
except:
print "ERROR."
sys.exit(4)

flickr = flickrapi.FlickrAPI(API_KEY, API_SECRET, token_cache_location=TOKEN_CACHE)

if not flickr.token_valid(perms='write'):
print "Authentication required"
def find_set(name, user_id):
try:
print "Looking for set.", name,
sets_response = flickr.photosets.getList(user_id=user_id)
photo_sets = sets_response.find('photosets').findall('photoset')
for photo_set in photo_sets:
if name == photo_set.find('title').text:
print "Found."
return photo_set.get('id')
print "Doesn't exist."
return None
except:
print "ERROR."

# Get request token
flickr.get_request_token(oauth_callback='oob')

# Show url. Copy and paste it in your browser
authorize_url = flickr.auth_url(perms=u'write')
print(authorize_url)
def check_authentication():
if not flickr.token_valid(perms='write'):
print "Authentication required"

# Prompt for verifier code from the user
verifier = unicode(raw_input('Verifier code: '))
# Get request token
flickr.get_request_token(oauth_callback='oob')

print "Verifier:", verifier
# Show url. Copy and paste it in your browser
authorize_url = flickr.auth_url(perms=u'write')
print(authorize_url)

# Trade the request token for an access token
print(flickr.get_access_token(verifier))
# Prompt for verifier code from the user
verifier = unicode(raw_input('Verifier code: '))

print "Verifier:", verifier

params = {}
params['tags']=TAGS
photo_ids=[]
# Trade the request token for an access token
print flickr.get_access_token(verifier)

for filename in os.listdir(FOLDER):
filename_split = filename.split('.')

if len(filename_split) == 2:
ext = filename_split[1].lower()
else:
ext = ''
if ext in ['png', 'jpeg', 'jpg', 'avi', 'mp4', 'gif', 'tiff', 'mov', 'wmv', 'ogv', 'mpg', 'mp2', 'mpeg',
'mpe', 'mpv']:
def upload_photos(folder):
photo_ids = []
pattern = re.compile('\.([a-zA-Z]+)$')

for filename in os.listdir(folder):
ext = pattern.search(filename)
if ext:
ext = ext.group(1).lower()

if ext in ['png', 'jpeg', 'jpg', 'avi', 'mp4', 'gif', 'tiff', 'mov', 'wmv', 'ogv', 'mpg', 'mp2', 'mpeg',
'mpe', 'mpv']:

print filename,
full_filename = folder + filename

try:
uploadResp = flickr.upload(filename=full_filename, is_public=0, is_friend=1, is_family=1,
tags=input_args['tags'])
photo_id = uploadResp.find('photoid').text
print " OK. Flickr id = ", photo_id
photo_ids.append(photo_id)
except:
print " ERROR."
print len(photo_ids), "photos uploaded successfully"
return photo_ids

print(filename),
full_filename = FOLDER + filename

def add_photos_to_set(photo_ids, set_id):
if set_id is None:
return
for photo_id in photo_ids:
try:
uploadResp = flickr.upload(filename=full_filename, is_public=0, is_friend=0, is_family=1, tags=TAGS)
photo_id = uploadResp.findall('photoid')[0].text
print(' OK. Flickr id = ' + photo_id)
photo_ids.append(photo_id)
flickr.photosets.addPhoto(photoset_id=set_id, photo_id=photo_id)
except:
print(" ERROR.")

# Creating a set
try:
print "Creating set",TITLE,
resp = flickr.photosets.create(title=TITLE,primary_photo_id=photo_ids[0])
photoset_id = photoset_id = resp.findall('photoset')[0].attrib['id']
print(' OK. Set id = ' + photoset_id)
del photo_ids[0]
except:
print "ERROR."
sys.exit(4)
print "ERROR adding file to set", photo_id

for photo_id in photo_ids:
try:
resp = flickr.photosets.addPhoto(photoset_id=photoset_id,photo_id=photo_id)
except:
print "ERROR adding file to set", photo_id

input_args = parse_input_args()
flickr = flickrapi.FlickrAPI(API_KEY, API_SECRET, token_cache_location=TOKEN_CACHE)
check_authentication()
photo_ids = upload_photos(folder=input_args['folder'])
photoset_id = find_set(name=input_args['title'], user_id=USER_ID)

if photoset_id is None and len(photo_ids) != 0:
photoset_id = create_set(name=input_args['title'], primary_photo_id=photo_ids[0])
del photo_ids[0]

add_photos_to_set(photo_ids, photoset_id)