Source

copelco / lib / copelco / apps / flickr / sync.py

Full commit
Colin Copeland 068de63 

























































import time
import datetime
import logging

from django.conf import settings

from copelco.apps.flickr import api
from copelco.apps.flickr import models as flickr


PHOTO_EXTRAS = (
	'url_t',
	'url_s',
	'url_m',
	'url_z',
	'date_upload',
	'date_taken',
)
PHOTO_SIZES = {
	't': 'thumbnail',
	's': 'square',
	'm': 'small',
	'z': 'medium',
}
logger = logging.getLogger('flickr.sync')


def sync_photos():
	session = api.Flickr(key=settings.FLICKR_KEY,
	                     secret=settings.FLICKR_SECRET)
	photo_extras = ','.join(PHOTO_EXTRAS)
	date_synced = datetime.datetime.now()
	for user in flickr.User.objects.all():
		logger.debug('Syncing user {0}'.format(user.nsid))
		for result in session.user_photos(user.nsid, extras=photo_extras):
			logger.debug('Inserting photo {0}'.format(result))
			save_photo(user, result, date_synced)


def save_photo(user, result, date_synced):
	date_uploaded = time.gmtime(int(result['dateupload']))
	photo, _ = flickr.Photo.objects.get_or_create(
		user=user,
		id=result['id'],
		title=result['title'],
		date_uploaded=datetime.datetime(*date_uploaded[:6]),
		date_taken=result['datetaken'],
		defaults={'date_synced': date_synced},
	)
	urls = [key for key in result.keys() if key.startswith('url')]
	for url in urls:
		_, suffix = url.split('_')
		type_ = PHOTO_SIZES.get(suffix, '')
		photo.sizes.get_or_create(
			type = type_,
			width=result['width_{0}'.format(suffix)],
			height=result['height_{0}'.format(suffix)],
			source=result[url],
		)