view_model.py 12 KB

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