all repos — FixYouTube-legacy @ e21d9119ec75e0c9ad9823a32488807d4dd5159b

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

fxyoutube/db.py (view raw)

 1from peewee import Model, CharField, TextField, IntegerField, DateTimeField, DoesNotExist
 2from playhouse.sqliteq import SqliteQueueDatabase
 3from datetime import datetime, timedelta
 4from fxyoutube.yt_info import get_info_ytdl
 5import fxyoutube.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    return Video.create(**info)
26
27def get_video_from_cache(video):
28    try:
29        temp = Video.get(Video.id == video)
30    except DoesNotExist:
31        return None
32
33    delta = datetime.now() - temp.timestamp
34    if delta > timedelta(minutes=c.YT_TTL_MINUTES):
35        return None
36    
37    return temp
38
39def get_info(video):
40    info = get_video_from_cache(video)
41
42    if info is not None:
43        return info
44    
45    info = get_info_ytdl(video)
46    if info is not None:
47        cache_video(info)
48
49    return info
50
51def clear_cache():
52    Video.delete().execute()
53
54db.connect()
55db.create_tables([Video])