remove unnecessary imports
[mygpo.git] / mygpo / data / mimetype.py
blobd60ead4554c9c0e5f3f4100b6cecf0da3c5da1bc
1 from mygpo.api.models import Episode
2 from collections import defaultdict
3 import mimetypes
5 # If 20% of the episodes of a podcast are of a given type,
6 # then the podcast is considered to be of that type, too
7 TYPE_THRESHOLD=.2
10 _ = lambda s: s
12 CONTENT_TYPES = (_('image'), _('audio'), _('video'))
14 def get_podcast_types(podcast):
15 """Returns the types of a podcast
17 A podcast is considered to be of a given types if the ratio of episodes that are of that type equals TYPE_THRESHOLD
18 """
19 episodes = Episode.objects.filter(podcast=podcast, mimetype__isnull=False)
20 types = defaultdict()
21 for e in episodes:
22 t = get_type(e.mimetype)
23 types[t] = types.get(t, 0) + 1
25 max_episodes = sum(types.itervalues())
26 l = list(types.iteritems())
27 l.sort(key=lambda x: x[1], reverse=True)
29 return [x[0] for x in filter(lambda x: max_episodes / float(x[1]) >= TYPE_THRESHOLD, l)]
32 def get_type(mimetype):
33 """Returns the simplified type for the given mimetype
35 All "wanted" mimetypes are mapped to one of audio/video/image
36 Everything else returns None
37 """
38 if not mimetype:
39 return None
41 if '/' in mimetype:
42 category, type = mimetype.split('/', 1)
43 if category in ('audio', 'video', 'image'):
44 return category
45 elif type == 'ogg':
46 return 'audio'
47 elif type == 'x-youtube':
48 return 'video'
49 return None
51 def check_mimetype(mimetype):
52 """Checks if the given mimetype can be processed by mygpo
53 """
54 if '/' in mimetype:
55 category, type = mimetype.split('/', 1)
56 if category in ('audio', 'video', 'image'):
57 return True
59 # application/ogg is a valid mime type for Ogg files
60 # but we do not want to accept all files with application category
61 if type in ('ogg', ):
62 return True
64 return False
65 else:
66 return False
69 def get_mimetype(mimetype, url):
70 """Returns the mimetype; if None is given it tries to guess it"""
72 if not mimetype:
73 mimetype, _encoding = mimetypes.guess_type(url)
75 return mimetype