all repos — FixYouTube-legacy @ main

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
 4import fixyoutube.constants as c
 5from fixyoutube.api import get_info_from_api
 6import logging
 7logger = logging.getLogger(__name__)
 8
 9db = SqliteQueueDatabase(c.DB_URL)
10
11class BaseModel(Model):
12    class Meta:
13        database = db
14
15class Video(BaseModel):
16    videoId = CharField(unique=True)
17    title = CharField()
18    description = TextField()
19    uploader = CharField()
20    duration = IntegerField()
21    height = IntegerField()
22    width = IntegerField()
23    url = TextField()
24    timestamp = DateTimeField(default=datetime.now)
25
26def cache_video(info):
27    if info is None:
28        return
29    try:
30        Video.delete().where(Video.videoId == info['videoId']).execute()
31    except DoesNotExist:
32        pass
33    return Video.create(**info)
34
35def get_video_from_cache(video):
36    try:
37        temp = Video.get(Video.videoId == video)
38    except DoesNotExist:
39        return None
40
41    delta = datetime.now() - temp.timestamp
42    if delta > timedelta(minutes=c.YT_TTL_MINUTES):
43        return None
44
45    return temp
46
47def get_info(video):
48    
49    logger.info("Video " + str(video) + " was requested.")
50    info = get_video_from_cache(video)
51
52    if info is not None:
53        logger.info("Retrieved from cache.")
54        return info
55    
56    info = get_info_from_api(video)
57
58    logger.info("Retrieved from API.")
59    return cache_video(info)
60
61def clear_cache():
62    Video.delete().execute()
63
64db.connect()
65db.create_tables([Video])