diff --git a/twitch-cache-api/sync.py b/twitch-cache-api/sync.py index 7f0ebd0..b362e21 100644 --- a/twitch-cache-api/sync.py +++ b/twitch-cache-api/sync.py @@ -68,11 +68,19 @@ class Sync(object): db.session.add(video) db.session.commit() app.logger.info('Updated videos: %s', ', '.join(updated) if updated else 'NONE') + comments = {} for com in twitch.fetch_comments(updated): - q = db.session.query(Video).filter(Video.id == cls._get(com, 'content_id')) - video = q.first() - if not video: - continue + id = cls._get(com, '_id') + assoc = dict( + video_id=cls._get(com, 'content_id'), + offset=cls._get(com, 'content_offset_seconds')) + if id in comments: + comments[id].update(com) + comments[id]['assocs'].append(assoc) + else: + comments[id] = com + comments[id]['assocs'] = [assoc] + for com in comments.values(): id = cls._get(com, '_id') q = db.session.query(Comment).filter(Comment.id == id) comment = q.first() @@ -91,16 +99,21 @@ class Sync(object): comment.message_user_badges = badges comment.created_at = cls._to_datetime(cls._get(com, 'created_at')) comment.updated_at = cls._to_datetime(cls._get(com, 'updated_at')) - q = db.session.query(Association).filter( - Association.video_id == video.id, - Association.comment_id == comment.id) - assoc = q.first() - if not assoc: - assoc = Association() - assoc.comment = comment - assoc.offset = cls._get(com, 'content_offset_seconds') - video.associations.append(assoc) - db.session.add(video) + for assc in com['assocs']: + q = db.session.query(Video).filter(Video.id == assc['video_id']) + video = q.first() + if not video: + continue + q = db.session.query(Association).filter( + Association.video_id == video.id, + Association.comment_id == comment.id) + assoc = q.first() + if not assoc: + assoc = Association() + assoc.comment = comment + assoc.offset = assc['offset'] + video.associations.append(assoc) + db.session.add(video) db.session.commit() app.logger.info('Synchronization of videos completed')