item_collections.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. from ulid import ULID
  2. from dataclasses import asdict, replace
  3. from importlib.util import find_spec
  4. import os
  5. import json
  6. from flask import request, g, jsonify, render_template, Blueprint, url_for, session
  7. from twitter_v2.api import ApiV2TweetSource
  8. from .view_model import FeedItem, CollectionPage, cleandict
  9. from .content_system import get_content, get_all_content, register_content_source
  10. twitter_enabled = False
  11. if find_spec('twitter_v2_facade'):
  12. from twitter_v2_facade.view_model import tweet_model_dc_vm
  13. twitter_enabled = True
  14. youtube_enabled = False
  15. if find_spec('youtube_v3_facade'):
  16. from youtube_v3_facade.content_source import youtube_model, get_youtube_builder
  17. youtube_enabled = True
  18. DATA_DIR=".data"
  19. item_collections_bp = Blueprint('item_collections', 'item_collections',
  20. static_folder='static',
  21. static_url_path='',
  22. url_prefix='/')
  23. def get_tweet_collection (collection_id):
  24. json_path = f'{DATA_DIR}/collection/{collection_id}.json'
  25. if not os.path.exists(json_path):
  26. return
  27. with open(json_path, 'rt', encoding='utf-8') as f:
  28. collection = json.loads(f.read())
  29. return collection
  30. def collection_from_card_source (url):
  31. """
  32. temp1 = await fetch('http://localhost:5000/notes/cards/search?q=twitter.com/&limit=10').then(r => r.json())
  33. re = /(http[^\s]+twitter\.com\/[^\/]+\/status\/[\d]+)/ig
  34. tweetLinks = temp1.cards.map(c => c.card.content).map(c => c.match(re))
  35. tweetLinks2 = tweetLinks.flat().filter(l => l)
  36. tweetLinksS = Array.from(new Set(tweetLinks2))
  37. statusUrls = tweetLinksS.map(s => new URL(s))
  38. //users = Array.from(new Set(statusUrls.map(s => s.pathname.split('/')[1])))
  39. ids = Array.from(new Set(statusUrls.map(s => parseInt(s.pathname.split('/')[3]))))
  40. """
  41. """
  42. temp1 = JSON.parse(document.body.innerText)
  43. // get swipe note + created_at + tweet user + tweet ID
  44. tweetCards = temp1.cards.map(c => c.card).filter(c => c.content.match(re))
  45. tweets = tweetCards.map(c => ({created_at: c.created_at, content: c.content, tweets: c.content.match(re).map(m => new URL(m))}))
  46. tweets.filter(t => t.tweets.filter(t2 => t2.user.toLowerCase() == 'stephenmpinto').length)
  47. // HN
  48. re = /(http[^\s]+news.ycombinator\.com\/[^\s]+\=[\d]+)/ig
  49. linkCards = temp1.cards.map(c => c.card).filter(c => c.content.match(re))
  50. links = linkCards.map(c => ({created_at: c.created_at, content: c.content, links: c.content.match(re).map(m => new URL(m))}))
  51. // YT (I thnk I've already done this one)
  52. """
  53. # more in 2022 twitter report
  54. return None
  55. def expand_item (item, me, tweets = None, includes = None, yt_videos = None):
  56. if 'id' in item:
  57. t = list(filter(lambda t: item['id'] == t.id, tweets))
  58. if not len(t):
  59. print("no tweet for item: " + item['id'])
  60. feed_item = FeedItem(
  61. id = item['id'],
  62. text = "(Deleted, suspended or blocked)",
  63. created_at = "",
  64. handle = "error",
  65. display_name = "Error"
  66. )
  67. # FIXME 1) put this in relative order to the collection
  68. # FIXME 2) we can use the tweet link to get the user ID...
  69. else:
  70. t = t[0]
  71. feed_item = tweet_model_dc_vm(includes, t, me)
  72. note = item.get('note')
  73. feed_item = replace(feed_item, note = note)
  74. elif 'yt_id' in item:
  75. yt_id = item['yt_id']
  76. vid = list(filter(lambda v: v['id'] == yt_id, yt_videos))[0]
  77. feed_item = youtube_model(vid)
  78. note = item.get('note')
  79. feed_item.update({'note': note})
  80. return feed_item
  81. # pagination token is the next tweet_ID
  82. @item_collections_bp.get('/collection/<collection_id>.html')
  83. def get_collection_html (collection_id):
  84. me = request.args.get('me')
  85. acct = session.get(me)
  86. max_results = int(request.args.get('max_results', 10))
  87. pagination_token = int(request.args.get('pagination_token', 0))
  88. collection = get_tweet_collection(collection_id)
  89. if 'authorized_users' in collection and (not acct or not me in collection['authorized_users']):
  90. return 'access denied.', 403
  91. items = collection['items'][pagination_token:(pagination_token + max_results)]
  92. if not len(items):
  93. return 'no tweets', 404
  94. twitter_token = os.environ.get('BEARER_TOKEN')
  95. if me and me.startswith('twitter:') and acct:
  96. twitter_token = acct['access_token']
  97. tweet_source = ApiV2TweetSource(twitter_token)
  98. tweet_ids = filter(lambda i: 'id' in i, items)
  99. tweet_ids = list(map(lambda item: item['id'], tweet_ids))
  100. tweets_response = tweet_source.get_tweets( tweet_ids, return_dataclass=True )
  101. yt_ids = filter(lambda i: 'yt_id' in i, items)
  102. yt_ids = list(map(lambda item: item['yt_id'], yt_ids))
  103. youtube = get_youtube_builder()
  104. videos_response = youtube.videos().list(id=','.join(yt_ids), part='snippet,contentDetails,liveStreamingDetails,statistics,recordingDetails', maxResults=1).execute()
  105. #print(response_json)
  106. if tweets_response.errors:
  107. # types:
  108. # https://api.twitter.com/2/problems/not-authorized-for-resource (blocked or suspended)
  109. # https://api.twitter.com/2/problems/resource-not-found (deleted)
  110. #print(response_json.get('errors'))
  111. for err in tweets_response.errors:
  112. if not 'type' in err:
  113. print('unknown error type: ' + str(err))
  114. elif err['type'] == 'https://api.twitter.com/2/problems/not-authorized-for-resource':
  115. print('blocked or suspended tweet: ' + err['value'])
  116. elif err['type'] == 'https://api.twitter.com/2/problems/resource-not-found':
  117. print('deleted tweet: ' + err['value'])
  118. else:
  119. print('unknown error')
  120. print(json.dumps(err, indent=2))
  121. includes = tweets_response.includes
  122. tweets = tweets_response.data
  123. feed_items = list(map(lambda item: expand_item(item, me, tweets, includes, videos_response['items']), items))
  124. if request.args.get('format') == 'json':
  125. return jsonify({'ids': tweet_ids,
  126. 'tweets': cleandict(asdict(tweets_response)),
  127. 'feed_items': feed_items,
  128. 'items': items,
  129. 'pagination_token': pagination_token})
  130. else:
  131. query = {}
  132. if pagination_token:
  133. query['next_data_url'] = url_for('.get_collection_html', collection_id=collection_id, pagination_token=pagination_token)
  134. if 'HX-Request' in request.headers:
  135. return render_template('partial/tweets-timeline.html', tweets = feed_items, user = {}, query = query)
  136. else:
  137. if pagination_token:
  138. query['next_page_url'] = url_for('.get_collection_html', collection_id=collection_id, pagination_token=pagination_token)
  139. return render_template('tweet-collection.html', tweets = feed_items, user = {}, query = query)
  140. def get_collection_list (me = None):
  141. me = request.args.get('me')
  142. acct = session.get(me)
  143. collections = []
  144. with os.scandir('.data/collection') as collections_files:
  145. for collection_file in collections_files:
  146. if not collection_file.name.endswith('.json'):
  147. continue
  148. with open(collection_file.path, 'rt', encoding='utf-8') as f:
  149. coll = json.load(f)
  150. if 'authorized_users' in coll and (not acct or not me in coll['authorized_users']):
  151. continue
  152. collection_id = collection_file.name[:-len('.json')]
  153. version = coll.get('_version')
  154. if not version: # legacy
  155. version = str(ULID())
  156. coll_info = dict(
  157. id = collection_id,
  158. _version = version,
  159. href = url_for('.get_collection_html', collection_id=collection_id)
  160. )
  161. collections.append(coll_info)
  162. return collections
  163. # pagination token is the next tweet_ID
  164. @item_collections_bp.get('/collections.html')
  165. def get_collections_html ():
  166. me = request.args.get('me')
  167. collections = get_content('collections:list', me=me)
  168. return jsonify(collections)
  169. def update_collection (collection_id, new_collection, op='replace', version=None, me = None):
  170. path = f'.data/collection/{collection_id}.json'
  171. existing_collection = None
  172. if os.path.exists(path):
  173. with open(path, 'rt', encoding='utf-8') as f:
  174. existing_collection = json.load(f)
  175. existing_version = existing_collection and existing_collection.get('_version')
  176. if existing_collection and existing_version != version:
  177. raise Error('updating with a wrong version. probably using a stale copy. fetch and retry op.')
  178. if op == 'insert':
  179. after_id = request.form.get('after_id')
  180. raise Error('not supported yet')
  181. elif op == 'append':
  182. existing_collection['items'] += new_collection['items']
  183. new_collection = existing_collection
  184. elif op == 'prepend':
  185. existing_collection['items'] = new_collection['items'] + existing_collection['items']
  186. new_collection = existing_collection
  187. new_version = str(ULID()) # content addressable hash of json w/o this key or similar
  188. new_collection['_version'] = new_version
  189. with open(path, 'wt', encoding='utf-8') as f:
  190. json.dump(new_collection, f)
  191. return new_version
  192. @item_collections_bp.post('/collection/<collection_id>.html')
  193. def post_collection_html (collection_id):
  194. op = request.form.get('op', 'replace')
  195. version = request.form.get('version')
  196. new_collection = request.form.get('collection.json')
  197. new_collection = json.loads(new_collection) # FIXME probably wrong
  198. new_version = get_content('collection:update', collection_id, new_collection, op=op, me=me)
  199. return jsonify({'_version': new_version})
  200. @item_collections_bp.get('/collection/test-update/<collection_id>.html')
  201. def get_collection_test_update_html (collection_id):
  202. me = None
  203. op = 'prepend'
  204. version = request.args.get('version')
  205. new_collection = {
  206. 'items': [{'id': 'zzz999'}]
  207. }
  208. new_version = get_content(f'collections:update:{collection_id}',
  209. new_collection,
  210. version=version,
  211. op=op,
  212. me=me)
  213. return jsonify({'_version': new_version})
  214. @item_collections_bp.post('/data/collection/create/from-cards')
  215. def post_data_collection_create_from_cards ():
  216. """
  217. // create collection from search, supporting multiple Tweets per card and Tweets in multiple Cards.
  218. re = /(https?[a-z0-9\.\/\:]+twitter\.com\/[0-9a-z\_]+\/status\/[\d]+)/ig
  219. temp1 = await fetch('http://localhost:5000/notes/cards/search?q=twitter.com/').then(r => r.json())
  220. cardMatches = temp1.cards
  221. .map(cm => Object.assign({}, cm, {tweetLinks: Array.from(new Set(cm.card.content.match(re)))}))
  222. .filter(cm => cm.tweetLinks && cm.tweetLinks.length)
  223. .map(cm => Object.assign({}, cm, {tweetUrls: cm.tweetLinks.map(l => new URL(l))}))
  224. .map(cm => Object.assign({}, cm, {tweetInfos: cm.tweetUrls.map(u => ({user: u.pathname.split('/')[1], tweetId: u.pathname.split('/')[3]}))}));
  225. collectionCards = {}
  226. cardMatches.forEach(function (cm) {
  227. if (!cm.tweetLinks.length) { return; }
  228. cm.tweetInfos.forEach(function (ti) {
  229. if (!collectionCards[ti.tweetId]) {
  230. collectionCards[ti.tweetId] = [];
  231. }
  232. collectionCards[ti.tweetId].push(cm.card);
  233. })
  234. })
  235. var collectionItems = [];
  236. Object.entries(collectionCards).forEach(function (e) {
  237. var tweetId = e[0], cards = e[1];
  238. var note = cards.map(function (card) {
  239. return card.created_at + "\n\n" + card.content;
  240. }).join("\n\n-\n\n");
  241. collectionItems.push({id: tweetId, note: note, tweet_infos: cm.tweetInfos, card_infos: cards.map(c => 'card#' + c.id)});
  242. })
  243. """
  244. collection = {
  245. 'items': [], # described in JS function above
  246. 'authorized_users': [g.twitter_user['id']]
  247. }
  248. return jsonify(collection)
  249. def get_item_id (obj_or_dict, id_key='id'):
  250. if type(obj_or_dict) == dict:
  251. return obj_or_dict[id_key]
  252. else:
  253. return getattr(obj_or_dict, id_key)
  254. def expand_item2 (item, me, content_responses):
  255. content_id = item['id']
  256. content_response = content_responses[ content_id ]
  257. if type(content_response) == CollectionPage:
  258. tweets = content_response.items
  259. elif type(content_response) == list:
  260. tweets = content_response
  261. else:
  262. tweets = [content_response]
  263. # endswith is a hack. Really FeedItems should return a full ID with prefix.
  264. t = list(filter(lambda t: content_id.endswith(f':{get_item_id(t)}'), tweets))
  265. if not len(t):
  266. print("no tweet for item: " + item['id'])
  267. feed_item = FeedItem(
  268. id = item['id'],
  269. text = "(Deleted, suspended or blocked)",
  270. created_at = "",
  271. handle = "error",
  272. display_name = "Error"
  273. )
  274. # FIXME 1) put this in relative order to the collection
  275. # FIXME 2) we can use the tweet link to get the user ID...
  276. else:
  277. feed_item = t[0]
  278. note = item.get('note')
  279. if type(feed_item) == dict:
  280. feed_item.update(note = note)
  281. else:
  282. feed_item = replace(feed_item, note = note)
  283. return feed_item
  284. def get_collection (collection_id, me=None, pagination_token:str = None, max_results:int =10):
  285. collection = get_tweet_collection(collection_id)
  286. if not collection:
  287. return
  288. first_idx = int(pagination_token or 0)
  289. last_idx = first_idx + max_results
  290. items = collection['items'][first_idx:last_idx]
  291. content_ids = list(map(lambda item: item['id'], items))
  292. content_responses = get_all_content( tuple(content_ids), enable_bulk_fetch=True )
  293. feed_items = list(map(lambda item: expand_item2(item, me, content_responses), items))
  294. collection['items'] = feed_items
  295. if len(collection['items']) == max_results:
  296. collection['next_token'] = str(last_idx)
  297. return collection
  298. def register_content_sources ():
  299. register_content_source("collection:", get_collection, id_pattern="([^:]+)")
  300. register_content_source("collections:list", get_collection_list, id_pattern="")
  301. register_content_source("collections:update:", update_collection, id_pattern="([A-Za-z0-9\-\_\.]+)")
  302. # pagination token is the next tweet_ID
  303. @item_collections_bp.get('/collection2/<collection_id>.html')
  304. def get_collection2_html (collection_id):
  305. me = request.args.get('me')
  306. acct = session.get(me)
  307. max_results = int(request.args.get('limit', 1))
  308. pagination_token = request.args.get('pagination_token', 0)
  309. #collection = get_tweet_collection(collection_id)
  310. collection = get_content(f'collection:{collection_id}',
  311. me=me,
  312. pagination_token=pagination_token,
  313. max_results=max_results)
  314. if 'authorized_users' in collection and (not acct or not me in collection['authorized_users']):
  315. return 'access denied.', 403
  316. feed_items = collection['items']
  317. pagination_token = collection.get('next_token')
  318. if not len(feed_items):
  319. return 'no tweets', 404
  320. if request.args.get('format') == 'json':
  321. return jsonify({'ids': tweet_ids,
  322. 'tweets': cleandict(asdict(tweets_response)),
  323. 'feed_items': feed_items,
  324. 'items': items,
  325. 'pagination_token': pagination_token})
  326. else:
  327. query = {}
  328. if pagination_token:
  329. query['next_data_url'] = url_for('.get_collection2_html', collection_id=collection_id, pagination_token=pagination_token, limit=max_results, me=me)
  330. query['next_page_url'] = url_for('.get_collection2_html', collection_id=collection_id, pagination_token=pagination_token, limit=max_results, me=me)
  331. if 'HX-Request' in request.headers:
  332. return render_template('partial/tweets-timeline.html', tweets = feed_items, user = {}, query = query)
  333. else:
  334. if pagination_token:
  335. query['next_page_url'] = url_for('.get_collection2_html', me=me, collection_id=collection_id, pagination_token=pagination_token)
  336. return render_template('tweet-collection.html', tweets = feed_items, user = {}, query = query)