[teamcoco] Use centralized sorting
[youtube-dl] / youtube_dl / extractor / teamcoco.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..utils import (
7     ExtractorError,
8 )
9
10
11 class TeamcocoIE(InfoExtractor):
12     _VALID_URL = r'http://teamcoco\.com/video/(?P<url_title>.*)'
13     _TEST = {
14         'url': 'http://teamcoco.com/video/louis-ck-interview-george-w-bush',
15         'file': '19705.mp4',
16         'md5': 'cde9ba0fa3506f5f017ce11ead928f9a',
17         'info_dict': {
18             "description": "Louis C.K. got starstruck by George W. Bush, so what? Part one.",
19             "title": "Louis C.K. Interview Pt. 1 11/3/11"
20         }
21     }
22
23     def _real_extract(self, url):
24         mobj = re.match(self._VALID_URL, url)
25         if mobj is None:
26             raise ExtractorError('Invalid URL: %s' % url)
27         url_title = mobj.group('url_title')
28         webpage = self._download_webpage(url, url_title)
29
30         video_id = self._html_search_regex(
31             r'<article class="video" data-id="(\d+?)"',
32             webpage, 'video id')
33
34         self.report_extraction(video_id)
35
36         data_url = 'http://teamcoco.com/cvp/2.0/%s.xml' % video_id
37         data = self._download_xml(data_url, video_id, 'Downloading data webpage')
38
39         qualities = ['500k', '480p', '1000k', '720p', '1080p']
40         formats = []
41         for filed in data.findall('files/file'):
42             if filed.attrib.get('playmode') == 'all':
43                 # it just duplicates one of the entries
44                 break
45             file_url = filed.text
46             m_format = re.search(r'(\d+(k|p))\.mp4', file_url)
47             if m_format is not None:
48                 format_id = m_format.group(1)
49             else:
50                 format_id = filed.attrib['bitrate']
51             tbr = (
52                 int(filed.attrib['bitrate'])
53                 if filed.attrib['bitrate'].isdigit()
54                 else None)
55
56             try:
57                 quality = qualities.index(format_id)
58             except ValueError:
59                 quality = -1
60             formats.append({
61                 'url': file_url,
62                 'ext': 'mp4',
63                 'tbr': tbr,
64                 'format_id': format_id,
65                 'quality': quality,
66             })
67
68         self._sort_formats(formats)
69
70         return {
71             'id': video_id,
72             'formats': formats,
73             'title': self._og_search_title(webpage),
74             'thumbnail': self._og_search_thumbnail(webpage),
75             'description': self._og_search_description(webpage),
76         }