You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.2 KiB

import datetime
import os
from db import Medium
from instagram import Instagram
class Sync(object):
@staticmethod
def _get(d, *keys, default=None):
try:
result = None
for key in keys:
if result:
if isinstance(result, list):
result = result[key]
else:
result = result.get(key, default)
else:
result = d.get(key, default)
return result
except (KeyError, IndexError):
return default
@staticmethod
def _to_datetime(val):
if not val:
return None
return datetime.datetime.utcfromtimestamp(val)
@classmethod
def sync_media(cls, app, db):
app.logger.info('Starting synchronization of media')
with app.app_context():
instagram = Instagram(os.getenv('INSTAGRAM_USERNAME'))
for med in instagram.fetch_media():
id = cls._get(med, 'id')
if not id:
continue
q = db.session.query(Medium).filter(Medium.id == id)
medium = q.first()
if not medium:
medium = Medium(id=id)
medium.typename = cls._get(med, '__typename')
medium.caption = cls._get(med, 'edge_media_to_caption', 'edges', 0, 'node', 'text')
medium.shortcode = cls._get(med, 'shortcode')
medium.taken_at = cls._to_datetime(cls._get(med, 'taken_at_timestamp'))
medium.width = cls._get(med, 'dimensions', 'width')
medium.height = cls._get(med, 'dimensions', 'height')
medium.display_url = cls._get(med, 'display_url')
medium.thumbnail_url = cls._get(med, 'thumbnail_src')
medium.likes = cls._get(med, 'edge_media_preview_like', 'count')
medium.owner_id = cls._get(med, 'owner', 'id')
medium.owner_username = cls._get(med, 'owner', 'username')
medium.owner_profile_pic_url = cls._get(med, 'owner', 'profile_pic_url')
db.session.add(medium)
db.session.commit()
app.logger.info('Synchronization of media completed')