twitter_archive_facade.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. from typing import List
  2. from dacite import from_dict
  3. from configparser import ConfigParser
  4. import base64
  5. from flask import Flask, json, Response, render_template, request, send_from_directory, Blueprint, url_for, g
  6. from flask_cors import CORS
  7. import sqlite3
  8. import os
  9. import json
  10. import json_stream
  11. from zipfile import ZipFile
  12. import itertools
  13. import datetime
  14. import dateutil
  15. import dateutil.parser
  16. import dateutil.tz
  17. import requests
  18. from twitter_v2.archive import ArchiveTweetSource
  19. from hogumathi_app.view_model import FeedItem, PublicMetrics
  20. ARCHIVE_TWEETS_PATH=os.environ.get('ARCHIVE_TWEETS_PATH', '.data/tweets.json')
  21. TWEET_DB_PATH=os.environ.get('TWEET_DB_PATH', '.data/tweet.db')
  22. twitter_app = Blueprint('twitter_archive_facade', 'twitter_archive_facade',
  23. static_folder='static',
  24. static_url_path='',
  25. url_prefix='/')
  26. @twitter_app.before_request
  27. def add_me ():
  28. #if me.startswith('twitter') and me in session:
  29. #g.twitter_user = {'id': '0'}
  30. return
  31. @twitter_app.context_processor
  32. def inject_me():
  33. #return {'twitter_user': g.twitter_user}
  34. return {}
  35. # ---------------------------------------------------------------------------------------------------------
  36. # ---------------------------------------------------------------------------------------------------------
  37. # Tweet Archive and old tests
  38. # ---------------------------------------------------------------------------------------------------------
  39. # ---------------------------------------------------------------------------------------------------------
  40. # https://stackoverflow.com/questions/48218065/programmingerror-sqlite-objects-created-in-a-thread-can-only-be-used-in-that-sa
  41. db = sqlite3.connect(":memory:", check_same_thread=False)
  42. db_need_init = True
  43. if db_need_init:
  44. print("Creating tweet db...")
  45. db.execute("create table tweet (id, created_at, content)")
  46. def tweets_js_to_json (path, to_path):
  47. # open JS file provided in archive and convert it to JSON
  48. # string manipulation should be enough
  49. return True
  50. def populate_tweetsdb_from_compressed_json (db, tweets_json_path):
  51. # perf: we should find a batch size for executemany if this is too slow.
  52. # https://stackoverflow.com/questions/43785569/for-loop-or-executemany-python-and-sqlite3
  53. ti = open(tweets_json_path)
  54. data = json_stream.load(ti)
  55. for tweet in data.persistent():
  56. reply = None
  57. if "reply" in tweet:
  58. reply = tweet["reply"]
  59. values = [tweet["id"], tweet["full_text_length"], tweet["date"], reply]
  60. db.execute("insert into tweet (id, full_text_length, date, reply) values (?, ?, ?, ?)", values)
  61. ti.close()
  62. return True
  63. def print_retweets (tweets_path):
  64. tweets_file = open(tweets_path, 'rt', encoding='utf-8')
  65. tweets_data = json_stream.load(tweets_file)
  66. print('[')
  67. for t in tweets_data:
  68. tweet = t.persistent()['tweet']
  69. if int(tweet['retweet_count']) > 1:
  70. print(json.dumps({'id': tweet['id'], 'x': tweet['created_at'], 'y': tweet['retweet_count']}) + ',')
  71. print(']')
  72. tweets_file.close()
  73. return True
  74. def tweet_to_actpub (t):
  75. return t
  76. @twitter_app.route('/tweets/isd', methods=['GET'])
  77. def get_tweets_isd ():
  78. # simulate GraphQL conventions with REST:
  79. # created_at[gte]=
  80. # created_at[lte]=
  81. # author=
  82. # content[re]=
  83. # expansions=media,...
  84. #results = langs_con.execute("select rowid, id, created_at, content from tweet").fetchall()
  85. #return Response(json.dumps(results), mimetype='application/json')
  86. return send_from_directory('data', 'tweets-ispoogedaily.json')
  87. @twitter_app.route('/tweets/storms', methods=['GET'])
  88. def get_tweet_storms ():
  89. #content = open('data/storm-summaries-2021.json').read()
  90. #return Response(content, mimetype='application/json')
  91. return send_from_directory('data', 'storm-summaries-2021.json')
  92. @twitter_app.route('/bookmarks', methods=['GET'])
  93. def get_bookmarks ():
  94. #content = open('data/storm-summaries-2021.json').read()
  95. #return Response(content, mimetype='application/json')
  96. return send_from_directory('data', 'bookmarks-ispoogedaily.json')
  97. @twitter_app.route('/timeline', methods=['GET'])
  98. def get_timeline ():
  99. #content = open('data/storm-summaries-2021.json').read()
  100. #return Response(content, mimetype='application/json')
  101. return send_from_directory('data', 'timeline-minimal.json')
  102. @twitter_app.route('/tweets/compressed', methods=['POST'])
  103. def post_tweets_compressed ():
  104. db_exists = os.path.exists(TWEET_DB_PATH)
  105. if not db_exists:
  106. db = sqlite3.connect(TWEET_DB_PATH)
  107. db.execute("create table tweet (id, full_text_length, date, reply)")
  108. populate_tweetsdb_from_compressed_json(db, ".data/tweet-items.json")
  109. db.commit()
  110. db.close()
  111. #content = open('data/storm-summaries-2021.json').read()
  112. #return Response(content, mimetype='application/json')
  113. return Response("ok")
  114. tweets_form_meta_data = {
  115. 'fields': [
  116. {'name': 'id'},
  117. {'name': 'created_at', 'type': 'date'},
  118. {'name': 'retweeted', 'type': 'boolean'},
  119. {'name': 'favorited', 'type': 'boolean'},
  120. {'name': 'retweet_count', 'type': 'int'},
  121. {'name': 'favorite_count', 'type': 'int'},
  122. {'name': 'full_text', 'type': 'string', 'searchable': True},
  123. {'name': 'in_reply_to_status_id_str', 'type': 'string'},
  124. {'name': 'in_reply_to_user_id', 'type': 'string'},
  125. {'name': 'in_reply_to_screen_name', 'type': 'string'}
  126. ],
  127. 'id': 'id',
  128. 'root': 'tweets',
  129. 'url': '/tweets/search',
  130. 'access': ['read']
  131. }
  132. @twitter_app.route('/tweets/form', methods=['GET'])
  133. def get_tweets_form ():
  134. response_body = {
  135. 'metaData': tweets_form_meta_data
  136. }
  137. return Response(json.dumps(response_body), mimetype="application/json")
  138. def db_tweet_to_card (tweet):
  139. user = {'username': 'ispoogedaily', 'id': '14520320'}
  140. tweet_url = 'https://twitter.com/{}/status/{}'.format(user['username'], tweet['id'])
  141. content = tweet['full_text'] + "\n\n[view tweet]({})".format(tweet_url)
  142. card = {
  143. 'id': 'tweet-' + tweet['id'],
  144. 'content': content,
  145. 'content_type': 'text/plain',
  146. 'created_at': tweet['created_at'],
  147. 'modified_at': None,
  148. 'title': '@' + user['username'] + ' at ' + tweet['created_at'],
  149. 'content_source': tweet_url,
  150. #'tweet': tweet,
  151. #'user': user
  152. }
  153. return card
  154. # tweetStore = new Ext.data.JsonStore({'url': 'http://localhost:5004/tweets/search.rows.json', 'autoLoad': true})
  155. def tweet_model (tweet_data):
  156. # retweeted_by, avi_icon_url, display_name, handle, created_at, text
  157. """
  158. {"id": "797839193", "created_at": "2008-04-27T04:00:27", "retweeted": 0, "favorited": 0, "retweet_count": "0", "favorite_count": "0", "full_text": "Putting pizza on. Come over any time!", "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_screen_name": null, "author_id": "14520320"}, {"id": "797849979", "created_at": "2008-04-27T04:27:46", "retweeted": 0, "favorited": 0, "retweet_count": "0", "favorite_count": "0", "full_text": "hijacked!@!!!", "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_screen_name": null, "author_id": "14520320"}
  159. """
  160. t = {
  161. 'id': tweet_data['id'],
  162. 'text': tweet_data['full_text'],
  163. 'created_at': tweet_data['created_at'],
  164. 'author_is_verified': False,
  165. 'conversation_id': tweet_data['id'],
  166. 'avi_icon_url': '',
  167. 'display_name': 'Archive User',
  168. 'handle': '!archive',
  169. 'author_url': url_for('.get_profile_html', user_id='0'),
  170. 'author_id': '0',
  171. 'source_url': '!source_url',
  172. 'source_author_url': '!source_author_url',
  173. #'is_edited': len(tweet_data['edit_history_tweet_ids']) > 1
  174. }
  175. t['public_metrics'] = {
  176. 'like_count': int(tweet_data['favorite_count']),
  177. 'retweet_count': int(tweet_data['retweet_count']),
  178. 'reply_count': 0,
  179. 'quote_count': 0
  180. }
  181. return t
  182. def tweet_model_vm (tweet_data) -> List[FeedItem]:
  183. # retweeted_by, avi_icon_url, display_name, handle, created_at, text
  184. """
  185. {"id": "797839193", "created_at": "2008-04-27T04:00:27", "retweeted": 0, "favorited": 0, "retweet_count": "0", "favorite_count": "0", "full_text": "Putting pizza on. Come over any time!", "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_screen_name": null, "author_id": "14520320"}, {"id": "797849979", "created_at": "2008-04-27T04:27:46", "retweeted": 0, "favorited": 0, "retweet_count": "0", "favorite_count": "0", "full_text": "hijacked!@!!!", "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_screen_name": null, "author_id": "14520320"}
  186. """
  187. t = FeedItem(
  188. id = tweet_data['id'],
  189. text = tweet_data['full_text'],
  190. created_at = tweet_data['created_at'],
  191. author_is_verified = False,
  192. conversation_id = tweet_data['id'],
  193. avi_icon_url = '',
  194. display_name = 'Archive User',
  195. handle = '!archive',
  196. url = url_for('.get_tweet_html', tweet_id = tweet_data['id']),
  197. author_url = url_for('.get_profile_html', user_id='0'),
  198. author_id = '0',
  199. source_url = '!source_url',
  200. source_author_url = '!source_author_url',
  201. #'is_edited': len(tweet_data['edit_history_tweet_ids']) > 1
  202. public_metrics = PublicMetrics(
  203. like_count = int(tweet_data['favorite_count']),
  204. retweet_count = int(tweet_data['retweet_count']),
  205. reply_count = 0,
  206. quote_count = 0
  207. )
  208. )
  209. return t
  210. @twitter_app.route('/profile/<user_id>.html', methods=['GET'])
  211. def get_profile_html (user_id):
  212. pagination_token = request.args.get('pagination_token')
  213. #exclude_replies = request.args.get('exclude_replies', '1')
  214. tweet_source = ArchiveTweetSource(ARCHIVE_TWEETS_PATH)
  215. db_tweets = tweet_source.get_user_timeline(author_id = user_id,
  216. since_id = pagination_token,
  217. #exclude_replies = exclude_replies == '1'
  218. )
  219. tweets = list(map(tweet_model_vm, db_tweets))
  220. next_token = db_tweets[-1]['id']
  221. query = {}
  222. if next_token:
  223. query = {
  224. **query,
  225. 'next_data_url': url_for('.get_profile_html', user_id=user_id , pagination_token=next_token),
  226. 'next_page_url': url_for('.get_profile_html', user_id=user_id , pagination_token=next_token)
  227. }
  228. profile_user = {
  229. 'id': user_id
  230. }
  231. if 'HX-Request' in request.headers:
  232. user = {
  233. 'id': user_id
  234. }
  235. return render_template('partial/tweets-timeline.html', user = profile_user, tweets = tweets, query = query)
  236. else:
  237. return render_template('user-profile.html', user = profile_user, tweets = tweets, query = query)
  238. @twitter_app.get('/tweet/<tweet_id>.html')
  239. @twitter_app.get('/tweets.html')
  240. def get_tweet_html (tweet_id = None):
  241. output_format = request.args.get('format')
  242. if not tweet_id:
  243. ids = request.args.get('ids').split(',')
  244. else:
  245. ids = [tweet_id]
  246. tweet_source = ArchiveTweetSource(ARCHIVE_TWEETS_PATH)
  247. db_tweets = tweet_source.get_tweets(ids)
  248. tweets = list(map(tweet_model_vm, db_tweets))
  249. query = {}
  250. profile_user = {}
  251. if output_format == 'feed.json':
  252. return jsonify(dict(
  253. data = tweets
  254. ))
  255. else:
  256. return render_template('search.html', user = profile_user, tweets = tweets, query = query)
  257. @twitter_app.route('/latest.html', methods=['GET'])
  258. def get_timeline_home_html (variant = "reverse_chronological", pagination_token=None):
  259. return 'ok'
  260. @twitter_app.route('/conversations.html', methods=['GET'])
  261. def get_conversations_html ():
  262. return 'ok'
  263. @twitter_app.route('/bookmarks.html', methods=['GET'])
  264. def get_bookmarks_html (user_id):
  265. return 'ok'
  266. @twitter_app.route('/logout.html', methods=['GET'])
  267. def get_logout_html ():
  268. return 'ok'
  269. @twitter_app.route('/media/upload', methods=['POST'])
  270. def post_media_upload ():
  271. return 'ok'
  272. @twitter_app.route('/tweets/search', methods=['GET'])
  273. @twitter_app.route('/tweets/search.<string:response_format>', methods=['GET'])
  274. def get_tweets_search (response_format='json'):
  275. search = request.args.get('q')
  276. limit = int(request.args.get('limit', 10000))
  277. offset = int(request.args.get('offset', 0))
  278. in_reply_to_user_id = int(request.args.get('in_reply_to_user_id', 0))
  279. db = sqlite3.connect(TWEET_DB_PATH)
  280. sql = """
  281. select
  282. id, created_at, retweeted, favorited, retweet_count, favorite_count, full_text, in_reply_to_status_id_str, in_reply_to_user_id, in_reply_to_screen_name
  283. from tweet
  284. """
  285. sql_params = []
  286. if search:
  287. sql += " where full_text like ?"
  288. sql_params.append("%{}%".format(search))
  289. if in_reply_to_user_id:
  290. sql += " where in_reply_to_user_id = ?"
  291. sql_params.append(str(in_reply_to_user_id))
  292. sql += ' order by cast(id as integer)'
  293. if limit:
  294. sql += ' limit ?'
  295. sql_params.append(limit)
  296. if offset:
  297. sql += ' offset ?'
  298. sql_params.append(offset)
  299. cur = db.cursor()
  300. cur.row_factory = sqlite3.Row
  301. tweets = list(map(dict, cur.execute(sql, sql_params).fetchall()))
  302. cur.close()
  303. db.close()
  304. result = None
  305. if response_format == 'cards.json':
  306. cards = list(map(db_tweet_to_card, tweets))
  307. result = {
  308. "q": search,
  309. "cards": cards
  310. }
  311. elif response_format == 'rows.json':
  312. meta = tweets_form_meta_data
  313. fields = meta['fields']
  314. fields = list(map(lambda f: {**f[1], 'mapping': f[0]}, enumerate(fields)))
  315. meta = {**meta, 'fields': fields, 'id': '0'}
  316. def tweet_to_row (t):
  317. row = list(map(lambda f: t.get(f['name']), fields))
  318. return row
  319. rows = list(map(tweet_to_row, tweets))
  320. result = {
  321. "q": search,
  322. "metaData": meta,
  323. "tweets": rows
  324. }
  325. elif response_format == 'html':
  326. tweets = list(map(tweet_model_vm, tweets))
  327. query = {}
  328. profile_user = {}
  329. return render_template('search.html', user = profile_user, tweets = tweets, query = query)
  330. else:
  331. result = {
  332. "q": search,
  333. "tweets": tweets
  334. }
  335. return Response(json.dumps(result), mimetype="application/json")
  336. @twitter_app.route('/tweets', methods=['POST'])
  337. def post_tweets ():
  338. tweets_path = ARCHIVE_TWEETS_PATH
  339. tweets_file = open(tweets_path, 'rt', encoding='utf-8')
  340. tweets_data = json_stream.load(tweets_file)
  341. db = sqlite3.connect(TWEET_DB_PATH)
  342. db.execute('create table tweet (id integer, created_at, retweeted, favorited, retweet_count integer, favorite_count integer, full_text, in_reply_to_status_id_str integer, in_reply_to_user_id, in_reply_to_screen_name)')
  343. db.commit()
  344. i = 0
  345. cur = db.cursor()
  346. for tweet in tweets_data.persistent():
  347. t = dict(tweet['tweet'])
  348. dt = dateutil.parser.parse(t['created_at'])
  349. dt_utc = dt.astimezone(dateutil.tz.tz.gettz('UTC'))
  350. created_at = dt_utc.strftime('%Y-%m-%dT%H:%M:%SZ')
  351. sql = 'insert into tweet (id, created_at, retweeted, favorited, retweet_count, favorite_count, full_text, in_reply_to_status_id_str, in_reply_to_user_id, in_reply_to_screen_name) values (?,?,?,?,?,?,?,?,?,?)'
  352. tweet_values = [
  353. t['id'],
  354. created_at,
  355. t['retweeted'],
  356. t['favorited'],
  357. t['retweet_count'],
  358. t['favorite_count'],
  359. t['full_text'],
  360. t.get('in_reply_to_status_id_str'),
  361. t.get('in_reply_to_user_id'),
  362. t.get('in_reply_to_screen_name')
  363. ]
  364. cur.execute(sql, tweet_values)
  365. i += 1
  366. if i % 100 == 0:
  367. cur.connection.commit()
  368. cur = db.cursor()
  369. cur.connection.commit()
  370. cur.close()
  371. db.close()
  372. tweets_file.close()
  373. # ---------------------------------------------------------------------------------------------------------
  374. # ---------------------------------------------------------------------------------------------------------
  375. def tweet_to_card (tweet, includes):
  376. user = list(filter(lambda u: u.get('id') == tweet['author_id'], includes.get('users')))[0]
  377. tweet_url = 'https://twitter.com/{}/status/{}'.format(user['username'], tweet['id'])
  378. content = tweet['text'] + "\n\n[view tweet]({})".format(tweet_url)
  379. card = {
  380. 'id': 'tweet-' + tweet['id'],
  381. 'content': content,
  382. 'content_type': 'text/markdown',
  383. 'created_at': tweet['created_at'], # can be derived from oldest in edit_history_tweet_ids
  384. 'modified_at': None, # can be derived from newest in edit_history_tweet_ids
  385. 'title': '@' + user['username'] + ' at ' + tweet['created_at'],
  386. 'content_source': tweet_url,
  387. #'tweet': tweet,
  388. #'user': user
  389. }
  390. return card
  391. def response_to_cards (response_json, add_included = True):
  392. tweets = response_json.get('data')
  393. includes = response_json.get('includes')
  394. cards = list(map(lambda t: tweet_to_card(t, includes), tweets))
  395. if add_included:
  396. included_cards = list(map(lambda t: tweet_to_card(t, includes), includes.get('tweets')))
  397. cards += included_cards
  398. return cards