all repos — FixYouTube-legacy @ f947f56687b7c6f4280a9e90832d1ff4874d1973

A better way to embed YouTube videos everywhere (inspired by FixTweet).

fixyoutube/db.py (view raw)

 1from peewee import Model, CharField, TextField, IntegerField, DateTimeField, DoesNotExist
 2from playhouse.sqliteq import SqliteQueueDatabase
 3from datetime import datetime, timedelta
 4from fixyoutube.yt_info import get_info_ytdl
 5import fixyoutube.constants as c
 6
 7db = SqliteQueueDatabase(c.DB_URL)
 8
 9class BaseModel(Model):
10    class Meta:
11        database = db
12
13class Video(BaseModel):
14    id = CharField(unique=True)
15    title = CharField()
16    description = TextField()
17    uploader = CharField()
18    duration = IntegerField()
19    height = IntegerField()
20    width = IntegerField()
21    url = TextField()
22    timestamp = DateTimeField(default=datetime.now)
23
24def cache_video(info):
25    try:
26        Video.delete().where(Video.id == info["id"]).execute()
27    except DoesNotExist:
28        pass
29    return Video.create(**info)
30
31def get_video_from_cache(video):
32    try:
33        temp = Video.get(Video.id == video)
34    except DoesNotExist:
35        return None
36
37    delta = datetime.now() - temp.timestamp
38    if delta > timedelta(minutes=c.YT_TTL_MINUTES):
39        return None
40    
41    return temp
42
43def get_info(video):
44    info = get_video_from_cache(video)
45
46    if info is not None:
47        return info
48    
49    info = get_info_ytdl(video)
50    if info is not None:
51        cache_video(info)
52
53    return info
54
55def clear_cache():
56    Video.delete().execute()
57
58db.connect()
59db.create_tables([Video])