subscriptions.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. from youtube import util, yt_data_extract, channel, local_playlist, playlist
  2. from youtube import yt_app
  3. import settings
  4. import sqlite3
  5. import os
  6. import time
  7. import gevent
  8. import json
  9. import traceback
  10. import contextlib
  11. import defusedxml.ElementTree
  12. import urllib
  13. import math
  14. import secrets
  15. import collections
  16. import calendar # bullshit! https://bugs.python.org/issue6280
  17. import csv
  18. import re
  19. import flask
  20. from flask import request
  21. thumbnails_directory = os.path.join(settings.data_dir, "subscription_thumbnails")
  22. # https://stackabuse.com/a-sqlite-tutorial-with-python/
  23. database_path = os.path.join(settings.data_dir, "subscriptions.sqlite")
  24. def open_database():
  25. if not os.path.exists(settings.data_dir):
  26. os.makedirs(settings.data_dir)
  27. connection = sqlite3.connect(database_path, check_same_thread=False)
  28. try:
  29. cursor = connection.cursor()
  30. cursor.execute('''PRAGMA foreign_keys = 1''')
  31. # Create tables if they don't exist
  32. cursor.execute('''CREATE TABLE IF NOT EXISTS subscribed_channels (
  33. id integer PRIMARY KEY,
  34. yt_channel_id text UNIQUE NOT NULL,
  35. channel_name text NOT NULL,
  36. time_last_checked integer DEFAULT 0,
  37. next_check_time integer DEFAULT 0,
  38. muted integer DEFAULT 0
  39. )''')
  40. cursor.execute('''CREATE TABLE IF NOT EXISTS videos (
  41. id integer PRIMARY KEY,
  42. sql_channel_id integer NOT NULL REFERENCES subscribed_channels(id) ON UPDATE CASCADE ON DELETE CASCADE,
  43. video_id text UNIQUE NOT NULL,
  44. title text NOT NULL,
  45. duration text,
  46. time_published integer NOT NULL,
  47. is_time_published_exact integer DEFAULT 0,
  48. time_noticed integer NOT NULL,
  49. description text,
  50. watched integer default 0
  51. )''')
  52. cursor.execute('''CREATE TABLE IF NOT EXISTS tag_associations (
  53. id integer PRIMARY KEY,
  54. tag text NOT NULL,
  55. sql_channel_id integer NOT NULL REFERENCES subscribed_channels(id) ON UPDATE CASCADE ON DELETE CASCADE,
  56. UNIQUE(tag, sql_channel_id)
  57. )''')
  58. cursor.execute('''CREATE TABLE IF NOT EXISTS db_info (
  59. version integer DEFAULT 1
  60. )''')
  61. connection.commit()
  62. except:
  63. connection.rollback()
  64. connection.close()
  65. raise
  66. # https://stackoverflow.com/questions/19522505/using-sqlite3-in-python-with-with-keyword
  67. return contextlib.closing(connection)
  68. def with_open_db(function, *args, **kwargs):
  69. with open_database() as connection:
  70. with connection as cursor:
  71. return function(cursor, *args, **kwargs)
  72. def _is_subscribed(cursor, channel_id):
  73. result = cursor.execute('''SELECT EXISTS(
  74. SELECT 1
  75. FROM subscribed_channels
  76. WHERE yt_channel_id=?
  77. LIMIT 1
  78. )''', [channel_id]).fetchone()
  79. return bool(result[0])
  80. def is_subscribed(channel_id):
  81. if not os.path.exists(database_path):
  82. return False
  83. return with_open_db(_is_subscribed, channel_id)
  84. def _subscribe(channels):
  85. ''' channels is a list of (channel_id, channel_name) '''
  86. channels = list(channels)
  87. with open_database() as connection:
  88. with connection as cursor:
  89. channel_ids_to_check = [channel[0] for channel in channels if not _is_subscribed(cursor, channel[0])]
  90. rows = ((channel_id, channel_name, 0, 0) for channel_id, channel_name in channels)
  91. cursor.executemany('''INSERT OR IGNORE INTO subscribed_channels (yt_channel_id, channel_name, time_last_checked, next_check_time)
  92. VALUES (?, ?, ?, ?)''', rows)
  93. if settings.autocheck_subscriptions:
  94. # important that this is after the changes have been committed to database
  95. # otherwise the autochecker (other thread) tries checking the channel before it's in the database
  96. channel_names.update(channels)
  97. check_channels_if_necessary(channel_ids_to_check)
  98. def delete_thumbnails(to_delete):
  99. for thumbnail in to_delete:
  100. try:
  101. video_id = thumbnail[0:-4]
  102. if video_id in existing_thumbnails:
  103. os.remove(os.path.join(thumbnails_directory, thumbnail))
  104. existing_thumbnails.remove(video_id)
  105. except Exception:
  106. print('Failed to delete thumbnail: ' + thumbnail)
  107. traceback.print_exc()
  108. def _unsubscribe(cursor, channel_ids):
  109. ''' channel_ids is a list of channel_ids '''
  110. to_delete = []
  111. for channel_id in channel_ids:
  112. rows = cursor.execute('''SELECT video_id
  113. FROM videos
  114. WHERE sql_channel_id = (
  115. SELECT id
  116. FROM subscribed_channels
  117. WHERE yt_channel_id=?
  118. )''', (channel_id,)).fetchall()
  119. to_delete += [row[0] + '.jpg' for row in rows]
  120. gevent.spawn(delete_thumbnails, to_delete)
  121. cursor.executemany("DELETE FROM subscribed_channels WHERE yt_channel_id=?", ((channel_id, ) for channel_id in channel_ids))
  122. def _get_videos(cursor, number_per_page, offset, tag=None):
  123. '''Returns a full page of videos with an offset, and a value good enough to be used as the total number of videos'''
  124. # We ask for the next 9 pages from the database
  125. # Then the actual length of the results tell us if there are more than 9 pages left, and if not, how many there actually are
  126. # This is done since there are only 9 page buttons on display at a time
  127. # If there are more than 9 pages left, we give a fake value in place of the real number of results if the entire database was queried without limit
  128. # This fake value is sufficient to get the page button generation macro to display 9 page buttons
  129. # If we wish to display more buttons this logic must change
  130. # We cannot use tricks with the sql id for the video since we frequently have filters and other restrictions in place on the results anyway
  131. # TODO: This is probably not the ideal solution
  132. if tag is not None:
  133. db_videos = cursor.execute('''SELECT video_id, title, duration, time_published, is_time_published_exact, channel_name, yt_channel_id
  134. FROM videos
  135. INNER JOIN subscribed_channels on videos.sql_channel_id = subscribed_channels.id
  136. INNER JOIN tag_associations on videos.sql_channel_id = tag_associations.sql_channel_id
  137. WHERE tag = ? AND muted = 0
  138. ORDER BY time_noticed DESC, time_published DESC
  139. LIMIT ? OFFSET ?''', (tag, number_per_page*9, offset)).fetchall()
  140. else:
  141. db_videos = cursor.execute('''SELECT video_id, title, duration, time_published, is_time_published_exact, channel_name, yt_channel_id
  142. FROM videos
  143. INNER JOIN subscribed_channels on videos.sql_channel_id = subscribed_channels.id
  144. WHERE muted = 0
  145. ORDER BY time_noticed DESC, time_published DESC
  146. LIMIT ? OFFSET ?''', (number_per_page*9, offset)).fetchall()
  147. pseudo_number_of_videos = offset + len(db_videos)
  148. videos = []
  149. for db_video in db_videos[0:number_per_page]:
  150. videos.append({
  151. 'id': db_video[0],
  152. 'title': db_video[1],
  153. 'duration': db_video[2],
  154. 'time_published': exact_timestamp(db_video[3]) if db_video[4] else posix_to_dumbed_down(db_video[3]),
  155. 'author': db_video[5],
  156. 'author_id': db_video[6],
  157. 'author_url': '/https://www.youtube.com/channel/' + db_video[6],
  158. })
  159. return videos, pseudo_number_of_videos
  160. def _get_subscribed_channels(cursor):
  161. for item in cursor.execute('''SELECT channel_name, yt_channel_id, muted
  162. FROM subscribed_channels
  163. ORDER BY channel_name COLLATE NOCASE'''):
  164. yield item
  165. def _add_tags(cursor, channel_ids, tags):
  166. pairs = [(tag, yt_channel_id) for tag in tags for yt_channel_id in channel_ids]
  167. cursor.executemany('''INSERT OR IGNORE INTO tag_associations (tag, sql_channel_id)
  168. SELECT ?, id FROM subscribed_channels WHERE yt_channel_id = ? ''', pairs)
  169. def _remove_tags(cursor, channel_ids, tags):
  170. pairs = [(tag, yt_channel_id) for tag in tags for yt_channel_id in channel_ids]
  171. cursor.executemany('''DELETE FROM tag_associations
  172. WHERE tag = ? AND sql_channel_id = (
  173. SELECT id FROM subscribed_channels WHERE yt_channel_id = ?
  174. )''', pairs)
  175. def _get_tags(cursor, channel_id):
  176. return [row[0] for row in cursor.execute('''SELECT tag
  177. FROM tag_associations
  178. WHERE sql_channel_id = (
  179. SELECT id FROM subscribed_channels WHERE yt_channel_id = ?
  180. )''', (channel_id,))]
  181. def _get_all_tags(cursor):
  182. return [row[0] for row in cursor.execute('''SELECT DISTINCT tag FROM tag_associations''')]
  183. def _get_channel_names(cursor, channel_ids):
  184. ''' returns list of (channel_id, channel_name) '''
  185. result = []
  186. for channel_id in channel_ids:
  187. row = cursor.execute('''SELECT channel_name
  188. FROM subscribed_channels
  189. WHERE yt_channel_id = ?''', (channel_id,)).fetchone()
  190. result.append((channel_id, row[0]))
  191. return result
  192. def _channels_with_tag(cursor, tag, order=False, exclude_muted=False, include_muted_status=False):
  193. ''' returns list of (channel_id, channel_name) '''
  194. statement = '''SELECT yt_channel_id, channel_name'''
  195. if include_muted_status:
  196. statement += ''', muted'''
  197. statement += '''
  198. FROM subscribed_channels
  199. WHERE subscribed_channels.id IN (
  200. SELECT tag_associations.sql_channel_id FROM tag_associations WHERE tag=?
  201. )
  202. '''
  203. if exclude_muted:
  204. statement += '''AND muted != 1\n'''
  205. if order:
  206. statement += '''ORDER BY channel_name COLLATE NOCASE'''
  207. return cursor.execute(statement, [tag]).fetchall()
  208. def _schedule_checking(cursor, channel_id, next_check_time):
  209. cursor.execute('''UPDATE subscribed_channels SET next_check_time = ? WHERE yt_channel_id = ?''', [int(next_check_time), channel_id])
  210. def _is_muted(cursor, channel_id):
  211. return bool(cursor.execute('''SELECT muted FROM subscribed_channels WHERE yt_channel_id=?''', [channel_id]).fetchone()[0])
  212. units = collections.OrderedDict([
  213. ('year', 31536000), # 365*24*3600
  214. ('month', 2592000), # 30*24*3600
  215. ('week', 604800), # 7*24*3600
  216. ('day', 86400), # 24*3600
  217. ('hour', 3600),
  218. ('minute', 60),
  219. ('second', 1),
  220. ])
  221. def youtube_timestamp_to_posix(dumb_timestamp):
  222. ''' Given a dumbed down timestamp such as 1 year ago, 3 hours ago,
  223. approximates the unix time (seconds since 1/1/1970) '''
  224. dumb_timestamp = dumb_timestamp.lower()
  225. now = time.time()
  226. if dumb_timestamp == "just now":
  227. return now
  228. split = dumb_timestamp.split(' ')
  229. quantifier, unit = int(split[0]), split[1]
  230. if quantifier > 1:
  231. unit = unit[:-1] # remove s from end
  232. return now - quantifier*units[unit]
  233. def posix_to_dumbed_down(posix_time):
  234. '''Inverse of youtube_timestamp_to_posix.'''
  235. delta = int(time.time() - posix_time)
  236. assert delta >= 0
  237. if delta == 0:
  238. return '0 seconds ago'
  239. for unit_name, unit_time in units.items():
  240. if delta >= unit_time:
  241. quantifier = round(delta/unit_time)
  242. if quantifier == 1:
  243. return '1 ' + unit_name + ' ago'
  244. else:
  245. return str(quantifier) + ' ' + unit_name + 's ago'
  246. else:
  247. raise Exception()
  248. def exact_timestamp(posix_time):
  249. result = time.strftime('%I:%M %p %m/%d/%y', time.localtime(posix_time))
  250. if result[0] == '0': # remove 0 infront of hour (like 01:00 PM)
  251. return result[1:]
  252. return result
  253. try:
  254. existing_thumbnails = set(os.path.splitext(name)[0] for name in os.listdir(thumbnails_directory))
  255. except FileNotFoundError:
  256. existing_thumbnails = set()
  257. # --- Manual checking system. Rate limited in order to support very large numbers of channels to be checked ---
  258. # Auto checking system plugs into this for convenience, though it doesn't really need the rate limiting
  259. check_channels_queue = util.RateLimitedQueue()
  260. checking_channels = set()
  261. # Just to use for printing channel checking status to console without opening database
  262. channel_names = dict()
  263. def check_channel_worker():
  264. while True:
  265. channel_id = check_channels_queue.get()
  266. try:
  267. _get_upstream_videos(channel_id)
  268. except Exception:
  269. traceback.print_exc()
  270. finally:
  271. checking_channels.remove(channel_id)
  272. for i in range(0, 5):
  273. gevent.spawn(check_channel_worker)
  274. # ----------------------------
  275. # --- Auto checking system - Spaghetti code ---
  276. def autocheck_dispatcher():
  277. '''Scans the auto_check_list. Sleeps until the earliest job is due, then adds that channel to the checking queue above. Can be sent a new job through autocheck_job_application'''
  278. while True:
  279. if len(autocheck_jobs) == 0:
  280. new_job = autocheck_job_application.get()
  281. autocheck_jobs.append(new_job)
  282. else:
  283. earliest_job_index = min(range(0, len(autocheck_jobs)), key=lambda index: autocheck_jobs[index]['next_check_time']) # https://stackoverflow.com/a/11825864
  284. earliest_job = autocheck_jobs[earliest_job_index]
  285. time_until_earliest_job = earliest_job['next_check_time'] - time.time()
  286. if time_until_earliest_job <= -5: # should not happen unless we're running extremely slow
  287. print('ERROR: autocheck_dispatcher got job scheduled in the past, skipping and rescheduling: ' + earliest_job['channel_id'] + ', ' + earliest_job['channel_name'] + ', ' + str(earliest_job['next_check_time']))
  288. next_check_time = time.time() + 3600*secrets.randbelow(60)/60
  289. with_open_db(_schedule_checking, earliest_job['channel_id'], next_check_time)
  290. autocheck_jobs[earliest_job_index]['next_check_time'] = next_check_time
  291. continue
  292. # make sure it's not muted
  293. if with_open_db(_is_muted, earliest_job['channel_id']):
  294. del autocheck_jobs[earliest_job_index]
  295. continue
  296. if time_until_earliest_job > 0: # it can become less than zero (in the past) when it's set to go off while the dispatcher is doing something else at that moment
  297. try:
  298. new_job = autocheck_job_application.get(timeout=time_until_earliest_job) # sleep for time_until_earliest_job time, but allow to be interrupted by new jobs
  299. except gevent.queue.Empty: # no new jobs
  300. pass
  301. else: # new job, add it to the list
  302. autocheck_jobs.append(new_job)
  303. continue
  304. # no new jobs, time to execute the earliest job
  305. channel_names[earliest_job['channel_id']] = earliest_job['channel_name']
  306. checking_channels.add(earliest_job['channel_id'])
  307. check_channels_queue.put(earliest_job['channel_id'])
  308. del autocheck_jobs[earliest_job_index]
  309. dispatcher_greenlet = None
  310. def start_autocheck_system():
  311. global autocheck_job_application
  312. global autocheck_jobs
  313. global dispatcher_greenlet
  314. # job application format: dict with keys (channel_id, channel_name, next_check_time)
  315. autocheck_job_application = gevent.queue.Queue() # only really meant to hold 1 item, just reusing gevent's wait and timeout machinery
  316. autocheck_jobs = [] # list of dicts with the keys (channel_id, channel_name, next_check_time). Stores all the channels that need to be autochecked and when to check them
  317. with open_database() as connection:
  318. with connection as cursor:
  319. now = time.time()
  320. for row in cursor.execute('''SELECT yt_channel_id, channel_name, next_check_time FROM subscribed_channels WHERE muted != 1''').fetchall():
  321. if row[2] is None:
  322. next_check_time = 0
  323. else:
  324. next_check_time = row[2]
  325. # expired, check randomly within the next hour
  326. # note: even if it isn't scheduled in the past right now, it might end up being if it's due soon and we dont start dispatching by then, see below where time_until_earliest_job is negative
  327. if next_check_time < now:
  328. next_check_time = now + 3600*secrets.randbelow(60)/60
  329. row = (row[0], row[1], next_check_time)
  330. _schedule_checking(cursor, row[0], next_check_time)
  331. autocheck_jobs.append({'channel_id': row[0], 'channel_name': row[1], 'next_check_time': next_check_time})
  332. dispatcher_greenlet = gevent.spawn(autocheck_dispatcher)
  333. def stop_autocheck_system():
  334. if dispatcher_greenlet is not None:
  335. dispatcher_greenlet.kill()
  336. def autocheck_setting_changed(old_value, new_value):
  337. if new_value:
  338. start_autocheck_system()
  339. else:
  340. stop_autocheck_system()
  341. settings.add_setting_changed_hook(
  342. 'autocheck_subscriptions',
  343. autocheck_setting_changed
  344. )
  345. if settings.autocheck_subscriptions:
  346. start_autocheck_system()
  347. # ----------------------------
  348. def check_channels_if_necessary(channel_ids):
  349. for channel_id in channel_ids:
  350. if channel_id not in checking_channels:
  351. checking_channels.add(channel_id)
  352. check_channels_queue.put(channel_id)
  353. def _get_atoma_feed(channel_id):
  354. url = 'https://www.youtube.com/feeds/videos.xml?channel_id=' + channel_id
  355. try:
  356. return util.fetch_url(url).decode('utf-8')
  357. except util.FetchError as e:
  358. # 404 is expected for terminated channels
  359. if e.code in ('404', '429'):
  360. return ''
  361. if e.code == '502':
  362. return str(e)
  363. raise
  364. def _get_channel_videos_first_page(channel_id, channel_status_name):
  365. try:
  366. # First try the playlist method
  367. pl_json = playlist.get_videos(
  368. 'UU' + channel_id[2:],
  369. 1,
  370. include_shorts=settings.include_shorts_in_subscriptions,
  371. report_text=None
  372. )
  373. pl_info = yt_data_extract.extract_playlist_info(pl_json)
  374. if pl_info.get('items'):
  375. pl_info['items'] = pl_info['items'][0:30]
  376. return pl_info
  377. # Try the channel api method
  378. channel_json = channel.get_channel_first_page(channel_id=channel_id)
  379. channel_info = yt_data_extract.extract_channel_info(
  380. json.loads(channel_json), 'videos'
  381. )
  382. return channel_info
  383. except util.FetchError as e:
  384. if e.code == '429' and settings.route_tor:
  385. error_message = ('Error checking channel ' + channel_status_name
  386. + ': YouTube blocked the request because the'
  387. + ' Tor exit node is overutilized. Try getting a new exit node'
  388. + ' by using the New Identity button in the Tor Browser.')
  389. if e.ip:
  390. error_message += ' Exit node IP address: ' + e.ip
  391. print(error_message)
  392. return None
  393. elif e.code == '502':
  394. print('Error checking channel', channel_status_name + ':', str(e))
  395. return None
  396. raise
  397. def _get_upstream_videos(channel_id):
  398. try:
  399. channel_status_name = channel_names[channel_id]
  400. except KeyError:
  401. channel_status_name = channel_id
  402. print("Checking channel: " + channel_status_name)
  403. tasks = (
  404. # channel page, need for video duration
  405. gevent.spawn(_get_channel_videos_first_page, channel_id,
  406. channel_status_name),
  407. # need atoma feed for exact published time
  408. gevent.spawn(_get_atoma_feed, channel_id)
  409. )
  410. gevent.joinall(tasks)
  411. channel_info, feed = tasks[0].value, tasks[1].value
  412. # extract published times from atoma feed
  413. times_published = {}
  414. try:
  415. def remove_bullshit(tag):
  416. '''Remove XML namespace bullshit from tagname. https://bugs.python.org/issue18304'''
  417. if '}' in tag:
  418. return tag[tag.rfind('}')+1:]
  419. return tag
  420. def find_element(base, tag_name):
  421. for element in base:
  422. if remove_bullshit(element.tag) == tag_name:
  423. return element
  424. return None
  425. root = defusedxml.ElementTree.fromstring(feed)
  426. assert remove_bullshit(root.tag) == 'feed'
  427. for entry in root:
  428. if (remove_bullshit(entry.tag) != 'entry'):
  429. continue
  430. # it's yt:videoId in the xml but the yt: is turned into a namespace which is removed by remove_bullshit
  431. video_id_element = find_element(entry, 'videoId')
  432. time_published_element = find_element(entry, 'published')
  433. assert video_id_element is not None
  434. assert time_published_element is not None
  435. time_published = int(calendar.timegm(time.strptime(time_published_element.text, '%Y-%m-%dT%H:%M:%S+00:00')))
  436. times_published[video_id_element.text] = time_published
  437. except AssertionError:
  438. print('Failed to read atoma feed for ' + channel_status_name)
  439. traceback.print_exc()
  440. except defusedxml.ElementTree.ParseError:
  441. print('Failed to read atoma feed for ' + channel_status_name)
  442. if channel_info is None: # there was an error
  443. return
  444. if channel_info['error']:
  445. print('Error checking channel ' + channel_status_name + ': ' + channel_info['error'])
  446. return
  447. videos = channel_info['items']
  448. for i, video_item in enumerate(videos):
  449. if not video_item.get('description'):
  450. video_item['description'] = ''
  451. else:
  452. video_item['description'] = ''.join(run.get('text', '') for run in video_item['description'])
  453. if video_item['id'] in times_published:
  454. video_item['time_published'] = times_published[video_item['id']]
  455. video_item['is_time_published_exact'] = True
  456. elif video_item.get('time_published'):
  457. video_item['is_time_published_exact'] = False
  458. try:
  459. video_item['time_published'] = youtube_timestamp_to_posix(video_item['time_published']) - i # subtract a few seconds off the videos so they will be in the right order
  460. except Exception:
  461. print(video_item)
  462. else:
  463. video_item['is_time_published_exact'] = False
  464. video_item['time_published'] = None
  465. video_item['channel_id'] = channel_id
  466. if len(videos) > 1:
  467. # Go back and fill in any videos that don't have a time published
  468. # using the time published of the surrounding ones
  469. for i in range(len(videos)-1):
  470. if (videos[i+1]['time_published'] is None
  471. and videos[i]['time_published'] is not None
  472. ):
  473. videos[i+1]['time_published'] = videos[i]['time_published'] - 1
  474. for i in reversed(range(1,len(videos))):
  475. if (videos[i-1]['time_published'] is None
  476. and videos[i]['time_published'] is not None
  477. ):
  478. videos[i-1]['time_published'] = videos[i]['time_published'] + 1
  479. # Special case: none of the videos have a time published.
  480. # In this case, make something up
  481. if videos and videos[0]['time_published'] is None:
  482. assert all(v['time_published'] is None for v in videos)
  483. now = time.time()
  484. for i in range(len(videos)):
  485. # 1 month between videos
  486. videos[i]['time_published'] = now - i*3600*24*30
  487. if len(videos) == 0:
  488. average_upload_period = 4*7*24*3600 # assume 1 month for channel with no videos
  489. elif len(videos) < 5:
  490. average_upload_period = int((time.time() - videos[len(videos)-1]['time_published'])/len(videos))
  491. else:
  492. average_upload_period = int((time.time() - videos[4]['time_published'])/5) # equivalent to averaging the time between videos for the last 5 videos
  493. # calculate when to check next for auto checking
  494. # add some quantization and randomness to make pattern analysis by YouTube slightly harder
  495. quantized_upload_period = average_upload_period - (average_upload_period % (4*3600)) + 4*3600 # round up to nearest 4 hours
  496. randomized_upload_period = quantized_upload_period*(1 + secrets.randbelow(50)/50*0.5) # randomly between 1x and 1.5x
  497. next_check_delay = randomized_upload_period/10 # check at 10x the channel posting rate. might want to fine tune this number
  498. next_check_time = int(time.time() + next_check_delay)
  499. with open_database() as connection:
  500. with connection as cursor:
  501. # Get video ids and duration of existing vids so we
  502. # can see how many new ones there are and update
  503. # livestreams/premiers
  504. existing_vids = list(cursor.execute(
  505. '''SELECT video_id, duration
  506. FROM videos
  507. INNER JOIN subscribed_channels
  508. ON videos.sql_channel_id = subscribed_channels.id
  509. WHERE yt_channel_id=?
  510. ORDER BY time_published DESC
  511. LIMIT 30''', [channel_id]).fetchall())
  512. existing_vid_ids = set(row[0] for row in existing_vids)
  513. existing_durs = dict(existing_vids)
  514. # new videos the channel has uploaded since last time we checked
  515. number_of_new_videos = 0
  516. for video in videos:
  517. if video['id'] in existing_vid_ids:
  518. break
  519. number_of_new_videos += 1
  520. is_first_check = cursor.execute('''SELECT time_last_checked FROM subscribed_channels WHERE yt_channel_id=?''', [channel_id]).fetchone()[0] in (None, 0)
  521. time_videos_retrieved = int(time.time())
  522. rows = []
  523. update_rows = []
  524. for i, video_item in enumerate(videos):
  525. if (is_first_check
  526. or number_of_new_videos > 6
  527. or i >= number_of_new_videos):
  528. # don't want a crazy ordering on first check or check in a long time, since we're ordering by time_noticed
  529. # Last condition is for when the channel deleting videos
  530. # causes new videos to appear at the end of the backlog.
  531. # For instance, if we have 30 vids in the DB, and 1 vid
  532. # that we previously saw has since been deleted,
  533. # then a video we haven't seen before will appear as the
  534. # 30th. Don't want this to be considered a newly noticed
  535. # vid which would appear at top of subscriptions feed
  536. time_noticed = video_item['time_published']
  537. else:
  538. time_noticed = time_videos_retrieved
  539. # videos which need durations updated
  540. non_durations = ('upcoming', 'none', 'live', '')
  541. v_id = video_item['id']
  542. if (existing_durs.get(v_id) is not None
  543. and existing_durs[v_id].lower() in non_durations
  544. and video_item['duration'] not in non_durations
  545. ):
  546. update_rows.append((
  547. video_item['title'],
  548. video_item['duration'],
  549. video_item['time_published'],
  550. video_item['is_time_published_exact'],
  551. video_item['description'],
  552. video_item['id'],
  553. ))
  554. # all other videos
  555. else:
  556. rows.append((
  557. video_item['channel_id'],
  558. video_item['id'],
  559. video_item['title'],
  560. video_item['duration'],
  561. video_item['time_published'],
  562. video_item['is_time_published_exact'],
  563. time_noticed,
  564. video_item['description'],
  565. ))
  566. cursor.executemany('''INSERT OR IGNORE INTO videos (
  567. sql_channel_id,
  568. video_id,
  569. title,
  570. duration,
  571. time_published,
  572. is_time_published_exact,
  573. time_noticed,
  574. description
  575. )
  576. VALUES ((SELECT id FROM subscribed_channels WHERE yt_channel_id=?), ?, ?, ?, ?, ?, ?, ?)''', rows)
  577. cursor.executemany('''UPDATE videos SET
  578. title=?,
  579. duration=?,
  580. time_published=?,
  581. is_time_published_exact=?,
  582. description=?
  583. WHERE video_id=?''', update_rows)
  584. cursor.execute('''UPDATE subscribed_channels
  585. SET time_last_checked = ?, next_check_time = ?
  586. WHERE yt_channel_id=?''', [int(time.time()), next_check_time, channel_id])
  587. if settings.autocheck_subscriptions:
  588. if not _is_muted(cursor, channel_id):
  589. autocheck_job_application.put({'channel_id': channel_id, 'channel_name': channel_names[channel_id], 'next_check_time': next_check_time})
  590. if number_of_new_videos == 0:
  591. print('No new videos from ' + channel_status_name)
  592. elif number_of_new_videos == 1:
  593. print('1 new video from ' + channel_status_name)
  594. else:
  595. print(str(number_of_new_videos) + ' new videos from ' + channel_status_name)
  596. def check_all_channels():
  597. with open_database() as connection:
  598. with connection as cursor:
  599. channel_id_name_list = cursor.execute('''SELECT yt_channel_id, channel_name
  600. FROM subscribed_channels
  601. WHERE muted != 1''').fetchall()
  602. channel_names.update(channel_id_name_list)
  603. check_channels_if_necessary([item[0] for item in channel_id_name_list])
  604. def check_tags(tags):
  605. channel_id_name_list = []
  606. with open_database() as connection:
  607. with connection as cursor:
  608. for tag in tags:
  609. channel_id_name_list += _channels_with_tag(cursor, tag, exclude_muted=True)
  610. channel_names.update(channel_id_name_list)
  611. check_channels_if_necessary([item[0] for item in channel_id_name_list])
  612. def check_specific_channels(channel_ids):
  613. with open_database() as connection:
  614. with connection as cursor:
  615. channel_id_name_list = []
  616. for channel_id in channel_ids:
  617. channel_id_name_list += cursor.execute('''SELECT yt_channel_id, channel_name
  618. FROM subscribed_channels
  619. WHERE yt_channel_id=?''', [channel_id]).fetchall()
  620. channel_names.update(channel_id_name_list)
  621. check_channels_if_necessary(channel_ids)
  622. CHANNEL_ID_RE = re.compile(r'UC[-_\w]{22}')
  623. @yt_app.route('/import_subscriptions', methods=['POST'])
  624. def import_subscriptions():
  625. # check if the post request has the file part
  626. if 'subscriptions_file' not in request.files:
  627. # flash('No file part')
  628. return flask.redirect(util.URL_ORIGIN + request.full_path)
  629. file = request.files['subscriptions_file']
  630. # if user does not select file, browser also
  631. # submit an empty part without filename
  632. if file.filename == '':
  633. # flash('No selected file')
  634. return flask.redirect(util.URL_ORIGIN + request.full_path)
  635. mime_type = file.mimetype
  636. if mime_type == 'application/json':
  637. info = file.read().decode('utf-8')
  638. if info == '':
  639. return '400 Bad Request: File is empty', 400
  640. try:
  641. info = json.loads(info)
  642. except json.decoder.JSONDecodeError:
  643. traceback.print_exc()
  644. return '400 Bad Request: Invalid json file', 400
  645. channels = []
  646. try:
  647. if 'app_version_int' in info: # NewPipe Format
  648. for item in info['subscriptions']:
  649. # Other service, such as SoundCloud
  650. if item.get('service_id', 0) != 0:
  651. continue
  652. channel_url = item['url']
  653. channel_id_match = CHANNEL_ID_RE.search(channel_url)
  654. if channel_id_match:
  655. channel_id = channel_id_match.group(0)
  656. else:
  657. print('WARNING: Could not find channel id in url',
  658. channel_url)
  659. continue
  660. channels.append((channel_id, item['name']))
  661. else: # Old Google Takeout format
  662. for item in info:
  663. snippet = item['snippet']
  664. channel_id = snippet['resourceId']['channelId']
  665. channels.append((channel_id, snippet['title']))
  666. except (KeyError, IndexError):
  667. traceback.print_exc()
  668. return '400 Bad Request: Unknown json structure', 400
  669. elif mime_type in ('application/xml', 'text/xml', 'text/x-opml'):
  670. file = file.read().decode('utf-8')
  671. try:
  672. root = defusedxml.ElementTree.fromstring(file)
  673. assert root.tag == 'opml'
  674. channels = []
  675. for outline_element in root[0][0]:
  676. if (outline_element.tag != 'outline') or ('xmlUrl' not in outline_element.attrib):
  677. continue
  678. channel_name = outline_element.attrib['text']
  679. channel_rss_url = outline_element.attrib['xmlUrl']
  680. channel_id = channel_rss_url[channel_rss_url.find('channel_id=')+11:].strip()
  681. channels.append((channel_id, channel_name))
  682. except (AssertionError, IndexError, defusedxml.ElementTree.ParseError) as e:
  683. return '400 Bad Request: Unable to read opml xml file, or the file is not the expected format', 400
  684. elif mime_type in ('text/csv', 'application/vnd.ms-excel'):
  685. content = file.read().decode('utf-8')
  686. reader = csv.reader(content.splitlines())
  687. channels = []
  688. for row in reader:
  689. if not row or row[0].lower().strip() == 'channel id':
  690. continue
  691. elif len(row) > 1 and CHANNEL_ID_RE.fullmatch(row[0].strip()):
  692. channels.append( (row[0], row[-1]) )
  693. else:
  694. print('WARNING: Unknown row format:', row)
  695. else:
  696. error = 'Unsupported file format: ' + mime_type
  697. error += (' . Only subscription.json, subscriptions.csv files'
  698. ' (from Google Takeouts)'
  699. ' and XML OPML files exported from YouTube\'s'
  700. ' subscription manager page are supported')
  701. return (flask.render_template('error.html', error_message=error),
  702. 400)
  703. _subscribe(channels)
  704. return flask.redirect(util.URL_ORIGIN + '/subscription_manager', 303)
  705. @yt_app.route('/export_subscriptions', methods=['POST'])
  706. def export_subscriptions():
  707. include_muted = request.values.get('include_muted') == 'on'
  708. with open_database() as connection:
  709. with connection as cursor:
  710. sub_list = []
  711. for channel_name, channel_id, muted in (
  712. _get_subscribed_channels(cursor)):
  713. if muted and not include_muted:
  714. continue
  715. if request.values['export_format'] == 'json_google_takeout':
  716. sub_list.append({
  717. 'kind': 'youtube#subscription',
  718. 'snippet': {
  719. 'muted': bool(muted),
  720. 'resourceId': {
  721. 'channelId': channel_id,
  722. 'kind': 'youtube#channel',
  723. },
  724. 'tags': _get_tags(cursor, channel_id),
  725. 'title': channel_name,
  726. },
  727. })
  728. elif request.values['export_format'] == 'json_newpipe':
  729. sub_list.append({
  730. 'service_id': 0,
  731. 'url': 'https://www.youtube.com/channel/' + channel_id,
  732. 'name': channel_name,
  733. })
  734. elif request.values['export_format'] == 'opml':
  735. sub_list.append({
  736. 'channel_name': channel_name,
  737. 'channel_id': channel_id,
  738. })
  739. date_time = time.strftime('%Y%m%d%H%M', time.localtime())
  740. if request.values['export_format'] == 'json_google_takeout':
  741. r = flask.Response(json.dumps(sub_list), mimetype='text/json')
  742. cd = 'attachment; filename="subscriptions_%s.json"' % date_time
  743. r.headers['Content-Disposition'] = cd
  744. return r
  745. elif request.values['export_format'] == 'json_newpipe':
  746. r = flask.Response(json.dumps({
  747. 'app_version': '0.21.9',
  748. 'app_version_int': 975,
  749. 'subscriptions': sub_list,
  750. }), mimetype='text/json')
  751. file_name = 'newpipe_subscriptions_%s_youtube-local.json' % date_time
  752. cd = 'attachment; filename="%s"' % file_name
  753. r.headers['Content-Disposition'] = cd
  754. return r
  755. elif request.values['export_format'] == 'opml':
  756. r = flask.Response(
  757. flask.render_template('subscriptions.xml', sub_list=sub_list),
  758. mimetype='text/xml')
  759. cd = 'attachment; filename="subscriptions_%s.xml"' % date_time
  760. r.headers['Content-Disposition'] = cd
  761. return r
  762. else:
  763. return '400 Bad Request', 400
  764. @yt_app.route('/subscription_manager', methods=['GET'])
  765. def get_subscription_manager_page():
  766. group_by_tags = request.args.get('group_by_tags', '0') == '1'
  767. with open_database() as connection:
  768. with connection as cursor:
  769. if group_by_tags:
  770. tag_groups = []
  771. for tag in _get_all_tags(cursor):
  772. sub_list = []
  773. for channel_id, channel_name, muted in _channels_with_tag(cursor, tag, order=True, include_muted_status=True):
  774. sub_list.append({
  775. 'channel_url': util.URL_ORIGIN + '/channel/' + channel_id,
  776. 'channel_name': channel_name,
  777. 'channel_id': channel_id,
  778. 'muted': muted,
  779. 'tags': [t for t in _get_tags(cursor, channel_id) if t != tag],
  780. })
  781. tag_groups.append((tag, sub_list))
  782. # Channels with no tags
  783. channel_list = cursor.execute('''SELECT yt_channel_id, channel_name, muted
  784. FROM subscribed_channels
  785. WHERE id NOT IN (
  786. SELECT sql_channel_id FROM tag_associations
  787. )
  788. ORDER BY channel_name COLLATE NOCASE''').fetchall()
  789. if channel_list:
  790. sub_list = []
  791. for channel_id, channel_name, muted in channel_list:
  792. sub_list.append({
  793. 'channel_url': util.URL_ORIGIN + '/channel/' + channel_id,
  794. 'channel_name': channel_name,
  795. 'channel_id': channel_id,
  796. 'muted': muted,
  797. 'tags': [],
  798. })
  799. tag_groups.append(('No tags', sub_list))
  800. else:
  801. sub_list = []
  802. for channel_name, channel_id, muted in _get_subscribed_channels(cursor):
  803. sub_list.append({
  804. 'channel_url': util.URL_ORIGIN + '/channel/' + channel_id,
  805. 'channel_name': channel_name,
  806. 'channel_id': channel_id,
  807. 'muted': muted,
  808. 'tags': _get_tags(cursor, channel_id),
  809. })
  810. if group_by_tags:
  811. return flask.render_template(
  812. 'subscription_manager.html',
  813. group_by_tags=True,
  814. tag_groups=tag_groups,
  815. )
  816. else:
  817. return flask.render_template(
  818. 'subscription_manager.html',
  819. group_by_tags=False,
  820. sub_list=sub_list,
  821. )
  822. def list_from_comma_separated_tags(string):
  823. return [tag.strip() for tag in string.split(',') if tag.strip()]
  824. @yt_app.route('/subscription_manager', methods=['POST'])
  825. def post_subscription_manager_page():
  826. action = request.values['action']
  827. with open_database() as connection:
  828. with connection as cursor:
  829. if action == 'add_tags':
  830. _add_tags(cursor, request.values.getlist('channel_ids'), [tag.lower() for tag in list_from_comma_separated_tags(request.values['tags'])])
  831. elif action == 'remove_tags':
  832. _remove_tags(cursor, request.values.getlist('channel_ids'), [tag.lower() for tag in list_from_comma_separated_tags(request.values['tags'])])
  833. elif action == 'unsubscribe':
  834. _unsubscribe(cursor, request.values.getlist('channel_ids'))
  835. elif action == 'unsubscribe_verify':
  836. unsubscribe_list = _get_channel_names(cursor, request.values.getlist('channel_ids'))
  837. return flask.render_template('unsubscribe_verify.html', unsubscribe_list=unsubscribe_list)
  838. elif action == 'mute':
  839. cursor.executemany('''UPDATE subscribed_channels
  840. SET muted = 1
  841. WHERE yt_channel_id = ?''', [(ci,) for ci in request.values.getlist('channel_ids')])
  842. elif action == 'unmute':
  843. cursor.executemany('''UPDATE subscribed_channels
  844. SET muted = 0
  845. WHERE yt_channel_id = ?''', [(ci,) for ci in request.values.getlist('channel_ids')])
  846. else:
  847. flask.abort(400)
  848. return flask.redirect(util.URL_ORIGIN + request.full_path, 303)
  849. @yt_app.route('/subscriptions', methods=['GET'])
  850. @yt_app.route('/feed/subscriptions', methods=['GET'])
  851. def get_subscriptions_page():
  852. page = int(request.args.get('page', 1))
  853. with open_database() as connection:
  854. with connection as cursor:
  855. tag = request.args.get('tag', None)
  856. videos, number_of_videos_in_db = _get_videos(cursor, 60, (page - 1)*60, tag)
  857. for video in videos:
  858. video['thumbnail'] = util.URL_ORIGIN + '/data/subscription_thumbnails/' + video['id'] + '.jpg'
  859. video['type'] = 'video'
  860. video['item_size'] = 'small'
  861. util.add_extra_html_info(video)
  862. tags = _get_all_tags(cursor)
  863. subscription_list = []
  864. for channel_name, channel_id, muted in _get_subscribed_channels(cursor):
  865. subscription_list.append({
  866. 'channel_url': util.URL_ORIGIN + '/channel/' + channel_id,
  867. 'channel_name': channel_name,
  868. 'channel_id': channel_id,
  869. 'muted': muted,
  870. })
  871. return flask.render_template(
  872. 'subscriptions.html',
  873. header_playlist_names=local_playlist.get_playlist_names(),
  874. videos=videos,
  875. num_pages=math.ceil(number_of_videos_in_db/60),
  876. parameters_dictionary=request.args,
  877. tags=tags,
  878. current_tag=tag,
  879. subscription_list=subscription_list,
  880. )
  881. @yt_app.route('/subscriptions', methods=['POST'])
  882. @yt_app.route('/feed/subscriptions', methods=['POST'])
  883. def post_subscriptions_page():
  884. action = request.values['action']
  885. if action == 'subscribe':
  886. if len(request.values.getlist('channel_id')) != len(request.values.getlist('channel_name')):
  887. return '400 Bad Request, length of channel_id != length of channel_name', 400
  888. _subscribe(zip(request.values.getlist('channel_id'), request.values.getlist('channel_name')))
  889. elif action == 'unsubscribe':
  890. with_open_db(_unsubscribe, request.values.getlist('channel_id'))
  891. elif action == 'refresh':
  892. type = request.values['type']
  893. if type == 'all':
  894. check_all_channels()
  895. elif type == 'tag':
  896. check_tags(request.values.getlist('tag_name'))
  897. elif type == 'channel':
  898. check_specific_channels(request.values.getlist('channel_id'))
  899. else:
  900. flask.abort(400)
  901. else:
  902. flask.abort(400)
  903. return '', 204
  904. @yt_app.route('/data/subscription_thumbnails/<thumbnail>')
  905. def serve_subscription_thumbnail(thumbnail):
  906. '''Serves thumbnail from disk if it's been saved already. If not, downloads the thumbnail, saves to disk, and serves it.'''
  907. assert thumbnail[-4:] == '.jpg'
  908. video_id = thumbnail[0:-4]
  909. thumbnail_path = os.path.join(thumbnails_directory, thumbnail)
  910. if video_id in existing_thumbnails:
  911. try:
  912. f = open(thumbnail_path, 'rb')
  913. except FileNotFoundError:
  914. existing_thumbnails.remove(video_id)
  915. else:
  916. image = f.read()
  917. f.close()
  918. return flask.Response(image, mimetype='image/jpeg')
  919. url = f"https://i.ytimg.com/vi/{video_id}/hqdefault.jpg"
  920. try:
  921. image = util.fetch_url(url, report_text="Saved thumbnail: " + video_id)
  922. except urllib.error.HTTPError as e:
  923. print("Failed to download thumbnail for " + video_id + ": " + str(e))
  924. abort(e.code)
  925. try:
  926. f = open(thumbnail_path, 'wb')
  927. except FileNotFoundError:
  928. os.makedirs(thumbnails_directory, exist_ok=True)
  929. f = open(thumbnail_path, 'wb')
  930. f.write(image)
  931. f.close()
  932. existing_thumbnails.add(video_id)
  933. return flask.Response(image, mimetype='image/jpeg')