Skip to content

Instantly share code, notes, and snippets.

@mdornseif
Last active December 26, 2015 14:39
Show Gist options
  • Save mdornseif/7167392 to your computer and use it in GitHub Desktop.
Save mdornseif/7167392 to your computer and use it in GitHub Desktop.
def ig2adn(profile):
logging.debug(profile)
instagram_client = InstagramAPI(access_token=profile.ig_access_token)
try:
media, next = instagram_client.user_recent_media()
except InstagramAPIError, msg:
if 'The "access_token" provided is invalid.' in str(msg):
# profile.ig_access_token = None
# profile.put()
return
raise
for image in reversed(media):
if models.Crosspost.get_by_id(image.link):
continue # already posted
if image.caption and image.caption.created_at < (datetime.today() - timedelta(days=2)):
continue # image to old
text = ''
if image.caption:
text = image.caption.text
if len(text) + len(image.link) + 3 < 255:
if text:
text += ': '
text += image.link
if len(text) + 20 < 255:
text += ' #instagram'
post = dict(
annotations=[
dict(type='net.app.core.oembed',
value=dict(version='1.0',
type='photo',
width=image.images['standard_resolution'].width,
height=image.images['standard_resolution'].height,
url=image.images['standard_resolution'].url,
thumbnail_width=image.images['thumbnail'].width,
thumbnail_height=image.images['thumbnail'].height,
thumbnail_url=image.images['thumbnail'].url,
thumbnail_large_width=image.images['standard_resolution'].width,
thumbnail_large_height=image.images['standard_resolution'].height,
thumbnail_large_url=image.images['standard_resolution'].url
)),
dict(type='net.app.core.crosspost',
value=dict(canonical_url=image.link))
])
if image.caption:
post['annotations'][0]['value']['title'] = image.caption.text
if image.caption:
post['created_at'] = image.caption.created_at.strftime('%Y-%m-%dT%H:%M:%sZ')
if hasattr(image, 'location') and hasattr(image.location, 'point') and image.location.point:
# handle geolocation information
post['annotations'].append(
dict(type='net.app.core.geolocation',
value=dict(latitude=image.location.point.latitude,
longitude=image.location.point.longitude)
)
)
# add link to OSM
if len(text) + 20 < 255:
text += (' ' + short_osm(image.location.point.latitude,
image.location.point.longitude,
16))
post['text'] = text[:255]
result = urlfetch.fetch(
"https://alpha-api.app.net/stream/0/posts",
method=urlfetch.POST,
headers={'Authorization': 'Bearer %s' % profile.adn_access_token,
'Content-Type': 'application/json'},
payload=json.dumps(post))
logging.info(json.dumps(post))
logging.info(result.content)
if result.status_code == 401:
logging.debug(result)
profile.adn_access_token = ''
profile.put()
return
result = json.loads(result.content)
models.Crosspost(
id=image.link,
other_url=image.link,
adn_url=result['data']['canonical_url']).put()
logging.debug("published %s", result['data']['canonical_url'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment