view_model.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. from dataclasses import replace
  2. from flask import g, request, session
  3. import sqlite3
  4. from twitter_v2.types import Tweet, TweetExpansions
  5. from hogumathi_app.view_model import FeedServiceUser, FeedItem, FeedItemAction, CollectionPage, PublicMetrics, Card, MediaItem
  6. from . import oauth2_login
  7. # FIXME we want this to mark tweets as viewed.
  8. # from .content_source import get_object_over_time
  9. url_for = oauth2_login.url_for_with_me
  10. def user_model_dc (user, my_url_for=url_for):
  11. fsu = FeedServiceUser(
  12. id = user.id,
  13. name = user.name,
  14. username = user.username,
  15. created_at = user.created_at,
  16. description = user.description,
  17. preview_image_url = user.profile_image_url,
  18. website = user.url,
  19. is_verified = user.verified,
  20. is_protected = user.protected,
  21. location = user.location,
  22. url = my_url_for('twitter_v2_facade.get_profile_html', user_id=user.id),
  23. source_url = f'https://twitter.com/{user.username}',
  24. raw_user = user
  25. )
  26. return fsu
  27. def tweet_model_dc_vm (includes: TweetExpansions, tweet: Tweet, me, my_url_for=url_for, my_g=g, reply_depth=0, expand_path=None, tweets_viewed={}) -> FeedItem:
  28. # retweeted_by, avi_icon_url, display_name, handle, created_at, text
  29. # HACK we should not refer to the request directly...
  30. is_marked = False
  31. if request and request.args.get('marked_reply') == str(tweet.id):
  32. is_marked = True
  33. # HACK we shouldn't go to session directly
  34. #is_viewed = False
  35. #if session and 'oldest_viewed_tweet_id' in session:
  36. # #print('--- tweet_model_dc_vm: checking oldest_viewed_tweet_id')
  37. # oldest_viewed_tweet_id = session.get('oldest_viewed_tweet_id')
  38. # if oldest_viewed_tweet_id < int(tweet.id):
  39. # is_viewed = True
  40. is_viewed = tweets_viewed.get(tweet.id)
  41. user = list(filter(lambda u: u.id == tweet.author_id, includes.users))[0]
  42. published_by = user_model_dc(user, my_url_for=my_url_for)
  43. url = my_url_for('twitter_v2_facade.get_tweet_html', tweet_id=tweet.id, view='tweet')
  44. source_url = 'https://twitter.com/{}/status/{}'.format(user.username, tweet.id)
  45. avi_icon_url = my_url_for('get_image', url=user.profile_image_url)
  46. retweet_of = None
  47. quoted = None
  48. replied_to = None
  49. if tweet.referenced_tweets:
  50. retweet_of = list(filter(lambda r: r.type == 'retweeted', tweet.referenced_tweets))
  51. quoted = list(filter(lambda r: r.type == 'quoted', tweet.referenced_tweets))
  52. replied_to = list(filter(lambda r: r.type == 'replied_to', tweet.referenced_tweets))
  53. if reply_depth:
  54. if expand_path:
  55. expand_path += f',{tweet.id}'
  56. else:
  57. expand_path = tweet.id
  58. actions = {
  59. 'view_replies': FeedItemAction('twitter_v2_facade.get_tweet_html', {'tweet_id': tweet.conversation_id, 'view': 'replies', 'expand': expand_path}),
  60. 'view_thread': FeedItemAction('twitter_v2_facade.get_tweet_html', {'tweet_id': tweet.conversation_id, 'view': 'thread'}),
  61. 'view_conversation': FeedItemAction('twitter_v2_facade.get_tweet_html', {'tweet_id': tweet.conversation_id, 'view': 'conversation'}),
  62. }
  63. if reply_depth:
  64. vr = actions['view_replies']
  65. url = my_url_for(vr.route, **vr.route_params)
  66. is_bookmarked = None
  67. if me:
  68. cache_db = sqlite3.connect('.data/twitter_v2_cache.db')
  69. auth_user_id = me[len('twitter:'):]
  70. # this will cache deleted bookmarks. we need a next level abstraction over events / aggregate.
  71. is_bookmarked = cache_db.execute('select count(*) from tweet t, query q where q.rowid = t.query_id and q.query_type=? and t.id=? and q.auth_user_id=?', ['bookmarks', tweet.id, auth_user_id]).fetchone()[0] and True
  72. cache_db.close()
  73. if my_g.get('twitter_user'):
  74. actions.update(
  75. retweet = FeedItemAction('twitter_v2_facade.post_tweet_retweet', {'tweet_id': tweet.id})
  76. )
  77. if is_bookmarked:
  78. actions.update(
  79. delete_bookmark = FeedItemAction('twitter_v2_facade.delete_tweet_bookmark', {'tweet_id': tweet.id})
  80. )
  81. else:
  82. actions.update(
  83. bookmark = FeedItemAction('twitter_v2_facade.post_tweet_bookmark', {'tweet_id': tweet.id})
  84. )
  85. if my_g.get('twitter_live_enabled'):
  86. actions.update(
  87. view_activity = FeedItemAction('twitter_v2_live_facade.get_tweet_activity_html', {'tweet_id': tweet.id})
  88. )
  89. t = FeedItem(
  90. id = tweet.id,
  91. text = tweet.text,
  92. created_at = tweet.created_at,
  93. published_by = published_by,
  94. author_is_verified = user.verified,
  95. url = url,
  96. conversation_id = tweet.conversation_id,
  97. avi_icon_url = avi_icon_url,
  98. display_name = user.name,
  99. handle = user.username,
  100. author_url = my_url_for('twitter_v2_facade.get_profile_html', user_id=user.id),
  101. author_id = user.id,
  102. source_url = source_url,
  103. source_author_url = 'https://twitter.com/{}'.format(user.username),
  104. #'is_edited': len(tweet['edit_history_tweet_ids']) > 1
  105. actions = actions,
  106. is_bookmarked = is_bookmarked,
  107. is_marked = is_marked,
  108. is_viewed = is_viewed
  109. )
  110. if reply_depth:
  111. t = replace(t, reply_depth = reply_depth)
  112. # This is where we should put "is_bookmark", "is_liked", "is_in_collection", etc...
  113. if tweet.entities:
  114. if tweet.entities.urls:
  115. urls = list(filter(lambda u: u.title and u.description, tweet.entities.urls))
  116. if len(urls):
  117. url = urls[0]
  118. card = Card(
  119. display_url = url.display_url.split('/')[0],
  120. source_url = url.unwound_url,
  121. content = url.description,
  122. title = url.title
  123. )
  124. if url.images:
  125. print(url.images)
  126. card = replace(card,
  127. preview_image_url = my_url_for('get_image', url=url.images[1].url),
  128. image_url = my_url_for('get_image', url=url.images[0].url)
  129. )
  130. t = replace(t, card = card)
  131. if tweet.public_metrics:
  132. public_metrics = PublicMetrics(
  133. reply_count = tweet.public_metrics.reply_count,
  134. quote_count = tweet.public_metrics.quote_count,
  135. retweet_count = tweet.public_metrics.retweet_count,
  136. like_count = tweet.public_metrics.like_count,
  137. impression_count = tweet.public_metrics.impression_count,
  138. bookmark_count = tweet.public_metrics.bookmark_count,
  139. )
  140. t = replace(t, public_metrics = public_metrics)
  141. if tweet.non_public_metrics:
  142. non_public_metrics = NonPublicMetrics(
  143. impression_count = tweet.non_public_metrics.impression_count,
  144. user_profile_clicks = tweet.non_public_metrics.user_profile_clicks,
  145. url_link_clicks = tweet.non_public_metrics.url_link_clicks
  146. )
  147. t = replace(t, non_public_metrics = non_public_metrics)
  148. if retweet_of and len(retweet_of):
  149. print('found retweet_of')
  150. t = replace(t, retweeted_tweet_id = retweet_of[0].id)
  151. retweeted_tweet:Tweet = list(filter(lambda t: t.id == retweet_of[0].id, includes.tweets))[0]
  152. rt = tweet_model_dc_vm(includes, retweeted_tweet, me)
  153. t = replace(rt,
  154. retweeted_tweet_id = retweet_of[0].id,
  155. source_retweeted_by_url = 'https://twitter.com/{}'.format(user.username),
  156. retweeted_by = user.name,
  157. retweeted_by_url = my_url_for('twitter_v2_facade.get_profile_html', user_id=user.id)
  158. )
  159. try:
  160. if tweet.attachments and tweet.attachments.media_keys and includes.media:
  161. media_keys = tweet.attachments.media_keys
  162. def first_media (mk):
  163. medias = list(filter(lambda m: m.media_key == mk, includes.media))
  164. if len(medias):
  165. return medias[0]
  166. return None
  167. media = list(filter(lambda m: m != None, map(first_media, media_keys)))
  168. photos = filter(lambda m: m.type == 'photo', media)
  169. videos = filter(lambda m: m.type == 'video', media)
  170. photo_media = map(lambda p: MediaItem(
  171. media_key = p.media_key,
  172. type = 'photo',
  173. preview_image_url = my_url_for('get_image', url=p.url + '?name=tiny&format=webp'),
  174. url = my_url_for('get_image', url=p.url),
  175. width = p.width,
  176. height = p.height
  177. ), photos)
  178. def video_to_mi (v):
  179. use_hls = False # mainly iOS
  180. max_bitrate = 100000000
  181. if use_hls:
  182. variants = list(filter(lambda var: var.content_type == 'application/x-mpegURL'))
  183. else:
  184. variants = list(filter(lambda var: var.content_type != 'application/x-mpegURL' and var.bit_rate <= max_bitrate, v.variants))
  185. variants.sort(key=lambda v: v.bit_rate, reverse=True)
  186. url = None
  187. content_type = None
  188. size = None
  189. if len(variants):
  190. if len(variants) > 1:
  191. print('multiple qualifying variants (using first):')
  192. print(variants)
  193. variant = variants[0]
  194. url = my_url_for('get_image', url=variant.url)
  195. content_type = variant.content_type
  196. size = int(v.duration_ms / 1000 * variant.bit_rate)
  197. public_metrics = None
  198. if v.public_metrics and v.public_metrics.view_count:
  199. public_metrics = PublicMetrics(
  200. view_count = v.public_metrics.view_count
  201. )
  202. mi = MediaItem(
  203. media_key = v.media_key,
  204. type = 'video',
  205. preview_image_url = my_url_for('get_image', url=v.preview_image_url + '?name=tiny&format=webp'),
  206. image_url = my_url_for('get_image', url=v.preview_image_url),
  207. width = v.width,
  208. height = v.height,
  209. url=url,
  210. content_type = content_type,
  211. duration_ms = v.duration_ms,
  212. size = size,
  213. public_metrics = public_metrics
  214. )
  215. return mi
  216. video_media = map(video_to_mi, videos)
  217. t = replace(t,
  218. photos = list(photo_media),
  219. videos = list(video_media)
  220. )
  221. elif tweet.attachments and tweet.attachments.media_keys and not includes.media:
  222. print('tweet had attachments and media keys, but no expansion media content was given')
  223. print(tweet.attachments.media_keys)
  224. except:
  225. # it seems like this comes when we have a retweeted tweet with media on it.
  226. print('exception adding attachments to tweet:')
  227. print(tweet)
  228. print('view tweet:')
  229. print(t)
  230. print('included media:')
  231. print(includes.media)
  232. raise 'exception adding attachments to tweet'
  233. try:
  234. if quoted and len(quoted):
  235. t = replace(t, quoted_tweet_id = quoted[0].id)
  236. quoted_tweets = list(filter(lambda t: t.id == quoted[0].id, includes.tweets))
  237. if len(quoted_tweets):
  238. t = replace(t, quoted_tweet = tweet_model_dc_vm(includes, quoted_tweets[0], me))
  239. except:
  240. raise 'error adding quoted tweet'
  241. try:
  242. if replied_to and len(replied_to) and includes.tweets:
  243. t = replace(t, replied_tweet_id = replied_to[0].id)
  244. if reply_depth < 1:
  245. replied_tweets = list(filter(lambda t: t.id == replied_to[0].id, includes.tweets))
  246. if len(replied_tweets):
  247. t = replace(t, replied_tweet = tweet_model_dc_vm(includes, replied_tweets[0], me, reply_depth=reply_depth + 1))
  248. else:
  249. print("No replied tweet found (t={}, rep={})".format(t.id, t.replied_tweet_id))
  250. except:
  251. raise 'error adding replied_to tweet'
  252. return t