[bilibili] extract multiple backup_urls
[youtube-dl] / youtube_dl / extractor / bilibili.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6 import xml.etree.ElementTree as ET
7
8 from .common import InfoExtractor
9 from ..utils import (
10     int_or_none,
11     unescapeHTML,
12     ExtractorError,
13 )
14
15
16 class BiliBiliIE(InfoExtractor):
17     _VALID_URL = r'http://www\.bilibili\.(?:tv|com)/video/av(?P<id>\d+)(?:/index_(?P<page_num>\d+).html)?'
18
19     _TESTS = [{
20         'url': 'http://www.bilibili.tv/video/av1074402/',
21         'md5': '2c301e4dab317596e837c3e7633e7d86',
22         'info_dict': {
23             'id': '1554319',
24             'ext': 'flv',
25             'title': '【金坷垃】金泡沫',
26             'duration': 308313,
27             'upload_date': '20140420',
28             'thumbnail': 're:^https?://.+\.jpg',
29             'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923',
30             'timestamp': 1397983878,
31             'uploader': '菊子桑',
32         },
33     }, {
34         'url': 'http://www.bilibili.com/video/av1041170/',
35         'info_dict': {
36             'id': '1041170',
37             'title': '【BD1080P】刀语【诸神&异域】',
38             'description': '这是个神奇的故事~每个人不留弹幕不给走哦~切利哦!~',
39             'uploader': '枫叶逝去',
40             'timestamp': 1396501299,
41         },
42         'playlist_count': 9,
43     }]
44
45     def _real_extract(self, url):
46         mobj = re.match(self._VALID_URL, url)
47         video_id = mobj.group('id')
48         page_num = mobj.group('page_num') or '1'
49
50         view_data = self._download_json(
51             'http://api.bilibili.com/view?type=json&appkey=8e9fc618fbd41e28&id=%s&page=%s' % (video_id, page_num),
52             video_id)
53         if 'error' in view_data:
54             raise ExtractorError('%s said: %s' % (self.IE_NAME, view_data['error']), expected=True)
55
56         cid = view_data['cid']
57         title = unescapeHTML(view_data['title'])
58
59         page = self._download_webpage(
60             'http://interface.bilibili.com/v_cdn_play?appkey=8e9fc618fbd41e28&cid=%s' % cid,
61             cid,
62             'Downloading page %s/%s' % (page_num, view_data['pages'])
63         )
64         try:
65             err_info = json.loads(page)
66             raise ExtractorError(
67                 'BiliBili said: ' + err_info['error_text'], expected=True)
68         except ValueError:
69             pass
70
71         doc = ET.fromstring(page)
72
73         entries = []
74
75         for durl in doc.findall('./durl'):
76             size = durl.find('./filesize|./size')
77             formats = [{
78                 'url': durl.find('./url').text,
79                 'filesize': int_or_none(size.text) if size else None,
80                 'ext': 'flv',
81             }]
82             backup_urls = durl.find('./backup_url')
83             if backup_urls is not None:
84                 for backup_url in backup_urls.findall('./url'):
85                     formats.append({'url': backup_url.text})
86             formats.reverse()
87
88             entries.append({
89                 'id': '%s_part%s' % (cid, durl.find('./order').text),
90                 'title': title,
91                 'duration': int_or_none(durl.find('./length').text) // 1000,
92                 'formats': formats,
93             })
94
95         info = {
96             'id': str(cid),
97             'title': title,
98             'description': view_data.get('description'),
99             'thumbnail': view_data.get('pic'),
100             'uploader': view_data.get('author'),
101             'timestamp': int_or_none(view_data.get('created')),
102             'view_count': view_data.get('play'),
103             'duration': int_or_none(doc.find('./timelength').text),
104         }
105
106         if len(entries) == 1:
107             entries[0].update(info)
108             return entries[0]
109         else:
110             info.update({
111                 '_type': 'multi_video',
112                 'id': video_id,
113                 'entries': entries,
114             })
115             return info