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
6
7db = SqliteQueueDatabase(c.DB_URL)
8
9class BaseModel(Model):
10 class Meta:
11 database = db
12
13class Video(BaseModel):
14 videoId = 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 if info is None:
26 return
27 try:
28 Video.delete().where(Video.videoId == info['videoId']).execute()
29 except DoesNotExist:
30 pass
31 return Video.create(**info)
32
33def get_video_from_cache(video):
34 try:
35 temp = Video.get(Video.videoId == video)
36 except DoesNotExist:
37 return None
38
39 delta = datetime.now() - temp.timestamp
40 if delta > timedelta(minutes=c.YT_TTL_MINUTES):
41 return None
42
43 return temp
44
45def get_info(video):
46 info = get_video_from_cache(video)
47
48 if info is not None:
49 return info
50
51 info = get_info_from_api(video)
52
53 return cache_video(info)
54
55def clear_cache():
56 Video.delete().execute()
57
58db.connect()
59db.create_tables([Video])