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