youtube-dl 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Author: Ricardo Garcia Gonzalez
  4. # Author: Danny Colligan
  5. # License: Public domain code
  6. import htmlentitydefs
  7. import httplib
  8. import locale
  9. import math
  10. import netrc
  11. import os
  12. import os.path
  13. import re
  14. import socket
  15. import string
  16. import sys
  17. import time
  18. import urllib
  19. import urllib2
  20. std_headers = {
  21. 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8',
  22. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  23. 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
  24. 'Accept-Language': 'en-us,en;q=0.5',
  25. }
  26. simple_title_chars = string.ascii_letters.decode('ascii') + string.digits.decode('ascii')
  27. class DownloadError(Exception):
  28. """Download Error exception.
  29. This exception may be thrown by FileDownloader objects if they are not
  30. configured to continue on errors. They will contain the appropriate
  31. error message.
  32. """
  33. pass
  34. class SameFileError(Exception):
  35. """Same File exception.
  36. This exception will be thrown by FileDownloader objects if they detect
  37. multiple files would have to be downloaded to the same file on disk.
  38. """
  39. pass
  40. class PostProcessingError(Exception):
  41. """Post Processing exception.
  42. This exception may be raised by PostProcessor's .run() method to
  43. indicate an error in the postprocessing task.
  44. """
  45. pass
  46. class UnavailableFormatError(Exception):
  47. """Unavailable Format exception.
  48. This exception will be thrown when a video is requested
  49. in a format that is not available for that video.
  50. """
  51. pass
  52. class ContentTooShortError(Exception):
  53. """Content Too Short exception.
  54. This exception may be raised by FileDownloader objects when a file they
  55. download is too small for what the server announced first, indicating
  56. the connection was probably interrupted.
  57. """
  58. # Both in bytes
  59. downloaded = None
  60. expected = None
  61. def __init__(self, downloaded, expected):
  62. self.downloaded = downloaded
  63. self.expected = expected
  64. class FileDownloader(object):
  65. """File Downloader class.
  66. File downloader objects are the ones responsible of downloading the
  67. actual video file and writing it to disk if the user has requested
  68. it, among some other tasks. In most cases there should be one per
  69. program. As, given a video URL, the downloader doesn't know how to
  70. extract all the needed information, task that InfoExtractors do, it
  71. has to pass the URL to one of them.
  72. For this, file downloader objects have a method that allows
  73. InfoExtractors to be registered in a given order. When it is passed
  74. a URL, the file downloader handles it to the first InfoExtractor it
  75. finds that reports being able to handle it. The InfoExtractor extracts
  76. all the information about the video or videos the URL refers to, and
  77. asks the FileDownloader to process the video information, possibly
  78. downloading the video.
  79. File downloaders accept a lot of parameters. In order not to saturate
  80. the object constructor with arguments, it receives a dictionary of
  81. options instead. These options are available through the params
  82. attribute for the InfoExtractors to use. The FileDownloader also
  83. registers itself as the downloader in charge for the InfoExtractors
  84. that are added to it, so this is a "mutual registration".
  85. Available options:
  86. username: Username for authentication purposes.
  87. password: Password for authentication purposes.
  88. usenetrc: Use netrc for authentication instead.
  89. quiet: Do not print messages to stdout.
  90. forceurl: Force printing final URL.
  91. forcetitle: Force printing title.
  92. simulate: Do not download the video files.
  93. format: Video format code.
  94. outtmpl: Template for output names.
  95. ignoreerrors: Do not stop on download errors.
  96. ratelimit: Download speed limit, in bytes/sec.
  97. nooverwrites: Prevent overwriting files.
  98. continuedl: Try to continue downloads if possible.
  99. """
  100. params = None
  101. _ies = []
  102. _pps = []
  103. _download_retcode = None
  104. def __init__(self, params):
  105. """Create a FileDownloader object with the given options."""
  106. self._ies = []
  107. self._pps = []
  108. self._download_retcode = 0
  109. self.params = params
  110. @staticmethod
  111. def pmkdir(filename):
  112. """Create directory components in filename. Similar to Unix "mkdir -p"."""
  113. components = filename.split(os.sep)
  114. aggregate = [os.sep.join(components[0:x]) for x in xrange(1, len(components))]
  115. aggregate = ['%s%s' % (x, os.sep) for x in aggregate] # Finish names with separator
  116. for dir in aggregate:
  117. if not os.path.exists(dir):
  118. os.mkdir(dir)
  119. @staticmethod
  120. def format_bytes(bytes):
  121. if bytes is None:
  122. return 'N/A'
  123. if bytes == 0:
  124. exponent = 0
  125. else:
  126. exponent = long(math.log(float(bytes), 1024.0))
  127. suffix = 'bkMGTPEZY'[exponent]
  128. converted = float(bytes) / float(1024**exponent)
  129. return '%.2f%s' % (converted, suffix)
  130. @staticmethod
  131. def calc_percent(byte_counter, data_len):
  132. if data_len is None:
  133. return '---.-%'
  134. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  135. @staticmethod
  136. def calc_eta(start, now, total, current):
  137. if total is None:
  138. return '--:--'
  139. dif = now - start
  140. if current == 0 or dif < 0.001: # One millisecond
  141. return '--:--'
  142. rate = float(current) / dif
  143. eta = long((float(total) - float(current)) / rate)
  144. (eta_mins, eta_secs) = divmod(eta, 60)
  145. if eta_mins > 99:
  146. return '--:--'
  147. return '%02d:%02d' % (eta_mins, eta_secs)
  148. @staticmethod
  149. def calc_speed(start, now, bytes):
  150. dif = now - start
  151. if bytes == 0 or dif < 0.001: # One millisecond
  152. return '%10s' % '---b/s'
  153. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  154. @staticmethod
  155. def best_block_size(elapsed_time, bytes):
  156. new_min = max(bytes / 2.0, 1.0)
  157. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  158. if elapsed_time < 0.001:
  159. return long(new_max)
  160. rate = bytes / elapsed_time
  161. if rate > new_max:
  162. return long(new_max)
  163. if rate < new_min:
  164. return long(new_min)
  165. return long(rate)
  166. @staticmethod
  167. def parse_bytes(bytestr):
  168. """Parse a string indicating a byte quantity into a long integer."""
  169. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  170. if matchobj is None:
  171. return None
  172. number = float(matchobj.group(1))
  173. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  174. return long(round(number * multiplier))
  175. @staticmethod
  176. def verify_url(url):
  177. """Verify a URL is valid and data could be downloaded."""
  178. request = urllib2.Request(url, None, std_headers)
  179. data = urllib2.urlopen(request)
  180. data.read(1)
  181. data.close()
  182. def add_info_extractor(self, ie):
  183. """Add an InfoExtractor object to the end of the list."""
  184. self._ies.append(ie)
  185. ie.set_downloader(self)
  186. def add_post_processor(self, pp):
  187. """Add a PostProcessor object to the end of the chain."""
  188. self._pps.append(pp)
  189. pp.set_downloader(self)
  190. def to_stdout(self, message, skip_eol=False):
  191. """Print message to stdout if not in quiet mode."""
  192. if not self.params.get('quiet', False):
  193. print (u'%s%s' % (message, [u'\n', u''][skip_eol])).encode(locale.getpreferredencoding()),
  194. sys.stdout.flush()
  195. def to_stderr(self, message):
  196. """Print message to stderr."""
  197. print >>sys.stderr, message.encode(locale.getpreferredencoding())
  198. def fixed_template(self):
  199. """Checks if the output template is fixed."""
  200. return (re.search(ur'(?u)%\(.+?\)s', self.params['outtmpl']) is None)
  201. def trouble(self, message=None):
  202. """Determine action to take when a download problem appears.
  203. Depending on if the downloader has been configured to ignore
  204. download errors or not, this method may throw an exception or
  205. not when errors are found, after printing the message.
  206. """
  207. if message is not None:
  208. self.to_stderr(message)
  209. if not self.params.get('ignoreerrors', False):
  210. raise DownloadError(message)
  211. self._download_retcode = 1
  212. def slow_down(self, start_time, byte_counter):
  213. """Sleep if the download speed is over the rate limit."""
  214. rate_limit = self.params.get('ratelimit', None)
  215. if rate_limit is None or byte_counter == 0:
  216. return
  217. now = time.time()
  218. elapsed = now - start_time
  219. if elapsed <= 0.0:
  220. return
  221. speed = float(byte_counter) / elapsed
  222. if speed > rate_limit:
  223. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  224. def report_destination(self, filename):
  225. """Report destination filename."""
  226. self.to_stdout(u'[download] Destination: %s' % filename)
  227. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  228. """Report download progress."""
  229. self.to_stdout(u'\r[download] %s of %s at %s ETA %s' %
  230. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  231. def report_resuming_byte(self, resume_len):
  232. """Report attemtp to resume at given byte."""
  233. self.to_stdout(u'[download] Resuming download at byte %s' % resume_len)
  234. def report_file_already_downloaded(self, file_name):
  235. """Report file has already been fully downloaded."""
  236. self.to_stdout(u'[download] %s has already been downloaded' % file_name)
  237. def report_unable_to_resume(self):
  238. """Report it was impossible to resume download."""
  239. self.to_stdout(u'[download] Unable to resume')
  240. def report_finish(self):
  241. """Report download finished."""
  242. self.to_stdout(u'')
  243. def process_info(self, info_dict):
  244. """Process a single dictionary returned by an InfoExtractor."""
  245. # Do nothing else if in simulate mode
  246. if self.params.get('simulate', False):
  247. try:
  248. self.verify_url(info_dict['url'])
  249. except (OSError, IOError, urllib2.URLError, httplib.HTTPException, socket.error), err:
  250. raise UnavailableFormatError
  251. # Forced printings
  252. if self.params.get('forcetitle', False):
  253. print info_dict['title'].encode(locale.getpreferredencoding())
  254. if self.params.get('forceurl', False):
  255. print info_dict['url'].encode(locale.getpreferredencoding())
  256. return
  257. try:
  258. template_dict = dict(info_dict)
  259. template_dict['epoch'] = unicode(long(time.time()))
  260. filename = self.params['outtmpl'] % template_dict
  261. except (ValueError, KeyError), err:
  262. self.trouble('ERROR: invalid output template or system charset: %s' % str(err))
  263. if self.params['nooverwrites'] and os.path.exists(filename):
  264. self.to_stderr(u'WARNING: file exists: %s; skipping' % filename)
  265. return
  266. try:
  267. self.pmkdir(filename)
  268. except (OSError, IOError), err:
  269. self.trouble('ERROR: unable to create directories: %s' % str(err))
  270. return
  271. try:
  272. success = self._do_download(filename, info_dict['url'])
  273. except (OSError, IOError), err:
  274. raise UnavailableFormatError
  275. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  276. self.trouble('ERROR: unable to download video data: %s' % str(err))
  277. return
  278. except (ContentTooShortError, ), err:
  279. self.trouble('ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  280. return
  281. if success:
  282. try:
  283. self.post_process(filename, info_dict)
  284. except (PostProcessingError), err:
  285. self.trouble('ERROR: postprocessing: %s' % str(err))
  286. return
  287. def download(self, url_list):
  288. """Download a given list of URLs."""
  289. if len(url_list) > 1 and self.fixed_template():
  290. raise SameFileError(self.params['outtmpl'])
  291. for url in url_list:
  292. suitable_found = False
  293. for ie in self._ies:
  294. # Go to next InfoExtractor if not suitable
  295. if not ie.suitable(url):
  296. continue
  297. # Suitable InfoExtractor found
  298. suitable_found = True
  299. # Extract information from URL and process it
  300. ie.extract(url)
  301. # Suitable InfoExtractor had been found; go to next URL
  302. break
  303. if not suitable_found:
  304. self.trouble('ERROR: no suitable InfoExtractor: %s' % url)
  305. return self._download_retcode
  306. def post_process(self, filename, ie_info):
  307. """Run the postprocessing chain on the given file."""
  308. info = dict(ie_info)
  309. info['filepath'] = filename
  310. for pp in self._pps:
  311. info = pp.run(info)
  312. if info is None:
  313. break
  314. def _do_download(self, filename, url):
  315. stream = None
  316. open_mode = 'ab'
  317. basic_request = urllib2.Request(url, None, std_headers)
  318. request = urllib2.Request(url, None, std_headers)
  319. # Attempt to resume download with "continuedl" option
  320. if os.path.isfile(filename):
  321. resume_len = os.path.getsize(filename)
  322. else:
  323. resume_len = 0
  324. if self.params['continuedl'] and resume_len != 0:
  325. self.report_resuming_byte(resume_len)
  326. request.add_header('Range','bytes=%d-' % resume_len)
  327. # Establish connection
  328. try:
  329. data = urllib2.urlopen(request)
  330. except (urllib2.HTTPError, ), err:
  331. if err.code != 416: # 416 is 'Requested range not satisfiable'
  332. raise
  333. data = urllib2.urlopen(basic_request)
  334. content_length = data.info()['Content-Length']
  335. if content_length is not None and long(content_length) == resume_len:
  336. self.report_file_already_downloaded(filename)
  337. return True
  338. else:
  339. self.report_unable_to_resume()
  340. open_mode = 'wb'
  341. data_len = data.info().get('Content-length', None)
  342. data_len_str = self.format_bytes(data_len)
  343. byte_counter = 0
  344. block_size = 1024
  345. start = time.time()
  346. while True:
  347. # Download and write
  348. before = time.time()
  349. data_block = data.read(block_size)
  350. after = time.time()
  351. data_block_len = len(data_block)
  352. if data_block_len == 0:
  353. break
  354. byte_counter += data_block_len
  355. # Open file just in time
  356. if stream is None:
  357. try:
  358. stream = open(filename, open_mode)
  359. self.report_destination(filename)
  360. except (OSError, IOError), err:
  361. self.trouble('ERROR: unable to open for writing: %s' % str(err))
  362. return False
  363. stream.write(data_block)
  364. block_size = self.best_block_size(after - before, data_block_len)
  365. # Progress message
  366. percent_str = self.calc_percent(byte_counter, data_len)
  367. eta_str = self.calc_eta(start, time.time(), data_len, byte_counter)
  368. speed_str = self.calc_speed(start, time.time(), byte_counter)
  369. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  370. # Apply rate limit
  371. self.slow_down(start, byte_counter)
  372. self.report_finish()
  373. if data_len is not None and str(byte_counter) != data_len:
  374. raise ContentTooShortError(byte_counter, long(data_len))
  375. return True
  376. class InfoExtractor(object):
  377. """Information Extractor class.
  378. Information extractors are the classes that, given a URL, extract
  379. information from the video (or videos) the URL refers to. This
  380. information includes the real video URL, the video title and simplified
  381. title, author and others. The information is stored in a dictionary
  382. which is then passed to the FileDownloader. The FileDownloader
  383. processes this information possibly downloading the video to the file
  384. system, among other possible outcomes. The dictionaries must include
  385. the following fields:
  386. id: Video identifier.
  387. url: Final video URL.
  388. uploader: Nickname of the video uploader.
  389. title: Literal title.
  390. stitle: Simplified title.
  391. ext: Video filename extension.
  392. Subclasses of this one should re-define the _real_initialize() and
  393. _real_extract() methods, as well as the suitable() static method.
  394. Probably, they should also be instantiated and added to the main
  395. downloader.
  396. """
  397. _ready = False
  398. _downloader = None
  399. def __init__(self, downloader=None):
  400. """Constructor. Receives an optional downloader."""
  401. self._ready = False
  402. self.set_downloader(downloader)
  403. @staticmethod
  404. def suitable(url):
  405. """Receives a URL and returns True if suitable for this IE."""
  406. return False
  407. def initialize(self):
  408. """Initializes an instance (authentication, etc)."""
  409. if not self._ready:
  410. self._real_initialize()
  411. self._ready = True
  412. def extract(self, url):
  413. """Extracts URL information and returns it in list of dicts."""
  414. self.initialize()
  415. return self._real_extract(url)
  416. def set_downloader(self, downloader):
  417. """Sets the downloader for this IE."""
  418. self._downloader = downloader
  419. def _real_initialize(self):
  420. """Real initialization process. Redefine in subclasses."""
  421. pass
  422. def _real_extract(self, url):
  423. """Real extraction process. Redefine in subclasses."""
  424. pass
  425. class YoutubeIE(InfoExtractor):
  426. """Information extractor for youtube.com."""
  427. _VALID_URL = r'^((?:http://)?(?:\w+\.)?youtube\.com/(?:(?:v/)|(?:(?:watch(?:\.php)?)?\?(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$'
  428. _LANG_URL = r'http://uk.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  429. _LOGIN_URL = 'http://www.youtube.com/signup?next=/&gl=US&hl=en'
  430. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  431. _NETRC_MACHINE = 'youtube'
  432. _available_formats = ['22', '35', '18', '17', '13'] # listed in order of priority for -b flag
  433. _video_extensions = {
  434. '13': '3gp',
  435. '17': 'mp4',
  436. '18': 'mp4',
  437. '22': 'mp4',
  438. }
  439. @staticmethod
  440. def suitable(url):
  441. return (re.match(YoutubeIE._VALID_URL, url) is not None)
  442. @staticmethod
  443. def htmlentity_transform(matchobj):
  444. """Transforms an HTML entity to a Unicode character."""
  445. entity = matchobj.group(1)
  446. # Known non-numeric HTML entity
  447. if entity in htmlentitydefs.name2codepoint:
  448. return unichr(htmlentitydefs.name2codepoint[entity])
  449. # Unicode character
  450. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  451. if mobj is not None:
  452. numstr = mobj.group(1)
  453. if numstr.startswith(u'x'):
  454. base = 16
  455. numstr = u'0%s' % numstr
  456. else:
  457. base = 10
  458. return unichr(long(numstr, base))
  459. # Unknown entity in name, return its literal representation
  460. return (u'&%s;' % entity)
  461. def report_lang(self):
  462. """Report attempt to set language."""
  463. self._downloader.to_stdout(u'[youtube] Setting language')
  464. def report_login(self):
  465. """Report attempt to log in."""
  466. self._downloader.to_stdout(u'[youtube] Logging in')
  467. def report_age_confirmation(self):
  468. """Report attempt to confirm age."""
  469. self._downloader.to_stdout(u'[youtube] Confirming age')
  470. def report_webpage_download(self, video_id):
  471. """Report attempt to download webpage."""
  472. self._downloader.to_stdout(u'[youtube] %s: Downloading video webpage' % video_id)
  473. def report_information_extraction(self, video_id):
  474. """Report attempt to extract video information."""
  475. self._downloader.to_stdout(u'[youtube] %s: Extracting video information' % video_id)
  476. def report_video_url(self, video_id, video_real_url):
  477. """Report extracted video URL."""
  478. self._downloader.to_stdout(u'[youtube] %s: URL: %s' % (video_id, video_real_url))
  479. def report_unavailable_format(self, video_id, format):
  480. """Report extracted video URL."""
  481. self._downloader.to_stdout(u'[youtube] %s: Format %s not available' % (video_id, format))
  482. def _real_initialize(self):
  483. if self._downloader is None:
  484. return
  485. username = None
  486. password = None
  487. downloader_params = self._downloader.params
  488. # Attempt to use provided username and password or .netrc data
  489. if downloader_params.get('username', None) is not None:
  490. username = downloader_params['username']
  491. password = downloader_params['password']
  492. elif downloader_params.get('usenetrc', False):
  493. try:
  494. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  495. if info is not None:
  496. username = info[0]
  497. password = info[2]
  498. else:
  499. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  500. except (IOError, netrc.NetrcParseError), err:
  501. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  502. return
  503. # Set language
  504. request = urllib2.Request(self._LANG_URL, None, std_headers)
  505. try:
  506. self.report_lang()
  507. urllib2.urlopen(request).read()
  508. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  509. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % str(err))
  510. return
  511. # No authentication to be performed
  512. if username is None:
  513. return
  514. # Log in
  515. login_form = {
  516. 'current_form': 'loginForm',
  517. 'next': '/',
  518. 'action_login': 'Log In',
  519. 'username': username,
  520. 'password': password,
  521. }
  522. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form), std_headers)
  523. try:
  524. self.report_login()
  525. login_results = urllib2.urlopen(request).read()
  526. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  527. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  528. return
  529. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  530. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  531. return
  532. # Confirm age
  533. age_form = {
  534. 'next_url': '/',
  535. 'action_confirm': 'Confirm',
  536. }
  537. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form), std_headers)
  538. try:
  539. self.report_age_confirmation()
  540. age_results = urllib2.urlopen(request).read()
  541. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  542. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  543. return
  544. def _real_extract(self, url):
  545. # Extract video id from URL
  546. mobj = re.match(self._VALID_URL, url)
  547. if mobj is None:
  548. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  549. return
  550. video_id = mobj.group(2)
  551. # Downloader parameters
  552. best_quality = False
  553. format_param = None
  554. quality_index = 0
  555. if self._downloader is not None:
  556. params = self._downloader.params
  557. format_param = params.get('format', None)
  558. if format_param == '0':
  559. format_param = self._available_formats[quality_index]
  560. best_quality = True
  561. while True:
  562. # Extension
  563. video_extension = self._video_extensions.get(format_param, 'flv')
  564. # Normalize URL, including format
  565. normalized_url = 'http://www.youtube.com/watch?v=%s&gl=US&hl=en' % video_id
  566. if format_param is not None:
  567. normalized_url = '%s&fmt=%s' % (normalized_url, format_param)
  568. request = urllib2.Request(normalized_url, None, std_headers)
  569. try:
  570. self.report_webpage_download(video_id)
  571. video_webpage = urllib2.urlopen(request).read()
  572. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  573. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  574. return
  575. self.report_information_extraction(video_id)
  576. # "t" param
  577. mobj = re.search(r', "t": "([^"]+)"', video_webpage)
  578. if mobj is None:
  579. self._downloader.trouble(u'ERROR: unable to extract "t" parameter')
  580. return
  581. video_real_url = 'http://www.youtube.com/get_video?video_id=%s&t=%s&el=detailpage&ps=' % (video_id, mobj.group(1))
  582. if format_param is not None:
  583. video_real_url = '%s&fmt=%s' % (video_real_url, format_param)
  584. self.report_video_url(video_id, video_real_url)
  585. # uploader
  586. mobj = re.search(r"var watchUsername = '([^']+)';", video_webpage)
  587. if mobj is None:
  588. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  589. return
  590. video_uploader = mobj.group(1)
  591. # title
  592. mobj = re.search(r'(?im)<title>YouTube - ([^<]*)</title>', video_webpage)
  593. if mobj is None:
  594. self._downloader.trouble(u'ERROR: unable to extract video title')
  595. return
  596. video_title = mobj.group(1).decode('utf-8')
  597. video_title = re.sub(ur'(?u)&(.+?);', self.htmlentity_transform, video_title)
  598. video_title = video_title.replace(os.sep, u'%')
  599. # simplified title
  600. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  601. simple_title = simple_title.strip(ur'_')
  602. try:
  603. # Process video information
  604. self._downloader.process_info({
  605. 'id': video_id.decode('utf-8'),
  606. 'url': video_real_url.decode('utf-8'),
  607. 'uploader': video_uploader.decode('utf-8'),
  608. 'title': video_title,
  609. 'stitle': simple_title,
  610. 'ext': video_extension.decode('utf-8'),
  611. })
  612. return
  613. except UnavailableFormatError, err:
  614. if best_quality:
  615. if quality_index == len(self._available_formats) - 1:
  616. # I don't ever expect this to happen
  617. self._downloader.trouble(u'ERROR: no known formats available for video')
  618. return
  619. else:
  620. self.report_unavailable_format(video_id, format_param)
  621. quality_index += 1
  622. format_param = self._available_formats[quality_index]
  623. continue
  624. else:
  625. self._downloader.trouble('ERROR: format not available for video')
  626. return
  627. class MetacafeIE(InfoExtractor):
  628. """Information Extractor for metacafe.com."""
  629. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  630. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  631. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  632. _youtube_ie = None
  633. def __init__(self, youtube_ie, downloader=None):
  634. InfoExtractor.__init__(self, downloader)
  635. self._youtube_ie = youtube_ie
  636. @staticmethod
  637. def suitable(url):
  638. return (re.match(MetacafeIE._VALID_URL, url) is not None)
  639. def report_disclaimer(self):
  640. """Report disclaimer retrieval."""
  641. self._downloader.to_stdout(u'[metacafe] Retrieving disclaimer')
  642. def report_age_confirmation(self):
  643. """Report attempt to confirm age."""
  644. self._downloader.to_stdout(u'[metacafe] Confirming age')
  645. def report_download_webpage(self, video_id):
  646. """Report webpage download."""
  647. self._downloader.to_stdout(u'[metacafe] %s: Downloading webpage' % video_id)
  648. def report_extraction(self, video_id):
  649. """Report information extraction."""
  650. self._downloader.to_stdout(u'[metacafe] %s: Extracting information' % video_id)
  651. def _real_initialize(self):
  652. # Retrieve disclaimer
  653. request = urllib2.Request(self._DISCLAIMER, None, std_headers)
  654. try:
  655. self.report_disclaimer()
  656. disclaimer = urllib2.urlopen(request).read()
  657. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  658. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
  659. return
  660. # Confirm age
  661. disclaimer_form = {
  662. 'filters': '0',
  663. 'submit': "Continue - I'm over 18",
  664. }
  665. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form), std_headers)
  666. try:
  667. self.report_age_confirmation()
  668. disclaimer = urllib2.urlopen(request).read()
  669. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  670. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  671. return
  672. def _real_extract(self, url):
  673. # Extract id and simplified title from URL
  674. mobj = re.match(self._VALID_URL, url)
  675. if mobj is None:
  676. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  677. return
  678. video_id = mobj.group(1)
  679. # Check if video comes from YouTube
  680. mobj2 = re.match(r'^yt-(.*)$', video_id)
  681. if mobj2 is not None:
  682. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % mobj2.group(1))
  683. return
  684. simple_title = mobj.group(2).decode('utf-8')
  685. video_extension = 'flv'
  686. # Retrieve video webpage to extract further information
  687. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
  688. try:
  689. self.report_download_webpage(video_id)
  690. webpage = urllib2.urlopen(request).read()
  691. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  692. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  693. return
  694. # Extract URL, uploader and title from webpage
  695. self.report_extraction(video_id)
  696. mobj = re.search(r'(?m)&mediaURL=(http.*?\.flv)', webpage)
  697. if mobj is None:
  698. self._downloader.trouble(u'ERROR: unable to extract media URL')
  699. return
  700. mediaURL = urllib.unquote(mobj.group(1))
  701. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  702. if mobj is None:
  703. self._downloader.trouble(u'ERROR: unable to extract gdaKey')
  704. return
  705. gdaKey = mobj.group(1)
  706. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  707. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  708. if mobj is None:
  709. self._downloader.trouble(u'ERROR: unable to extract title')
  710. return
  711. video_title = mobj.group(1).decode('utf-8')
  712. mobj = re.search(r'(?ms)<li id="ChnlUsr">.*?Submitter:.*?<a .*?>(.*?)<', webpage)
  713. if mobj is None:
  714. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  715. return
  716. video_uploader = mobj.group(1)
  717. try:
  718. # Process video information
  719. self._downloader.process_info({
  720. 'id': video_id.decode('utf-8'),
  721. 'url': video_url.decode('utf-8'),
  722. 'uploader': video_uploader.decode('utf-8'),
  723. 'title': video_title,
  724. 'stitle': simple_title,
  725. 'ext': video_extension.decode('utf-8'),
  726. })
  727. except UnavailableFormatError:
  728. self._downloader.trouble(u'ERROR: format not available for video')
  729. class YoutubeSearchIE(InfoExtractor):
  730. """Information Extractor for YouTube search queries."""
  731. _VALID_QUERY = r'ytsearch(\d+|all)?:[\s\S]+'
  732. _TEMPLATE_URL = 'http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en'
  733. _VIDEO_INDICATOR = r'href="/watch\?v=.+?"'
  734. _MORE_PAGES_INDICATOR = r'>Next</a>'
  735. _youtube_ie = None
  736. _max_youtube_results = 1000
  737. def __init__(self, youtube_ie, downloader=None):
  738. InfoExtractor.__init__(self, downloader)
  739. self._youtube_ie = youtube_ie
  740. @staticmethod
  741. def suitable(url):
  742. return (re.match(YoutubeSearchIE._VALID_QUERY, url) is not None)
  743. def report_download_page(self, query, pagenum):
  744. """Report attempt to download playlist page with given number."""
  745. self._downloader.to_stdout(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  746. def _real_initialize(self):
  747. self._youtube_ie.initialize()
  748. def _real_extract(self, query):
  749. mobj = re.match(self._VALID_QUERY, query)
  750. if mobj is None:
  751. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  752. return
  753. prefix, query = query.split(':')
  754. prefix = prefix[8:]
  755. if prefix == '':
  756. self._download_n_results(query, 1)
  757. return
  758. elif prefix == 'all':
  759. self._download_n_results(query, self._max_youtube_results)
  760. return
  761. else:
  762. try:
  763. n = long(prefix)
  764. if n <= 0:
  765. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  766. return
  767. elif n > self._max_youtube_results:
  768. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  769. n = self._max_youtube_results
  770. self._download_n_results(query, n)
  771. return
  772. except ValueError: # parsing prefix as integer fails
  773. self._download_n_results(query, 1)
  774. return
  775. def _download_n_results(self, query, n):
  776. """Downloads a specified number of results for a query"""
  777. video_ids = []
  778. already_seen = set()
  779. pagenum = 1
  780. while True:
  781. self.report_download_page(query, pagenum)
  782. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  783. request = urllib2.Request(result_url, None, std_headers)
  784. try:
  785. page = urllib2.urlopen(request).read()
  786. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  787. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  788. return
  789. # Extract video identifiers
  790. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  791. video_id = page[mobj.span()[0]:mobj.span()[1]].split('=')[2][:-1]
  792. if video_id not in already_seen:
  793. video_ids.append(video_id)
  794. already_seen.add(video_id)
  795. if len(video_ids) == n:
  796. # Specified n videos reached
  797. for id in video_ids:
  798. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  799. return
  800. if self._MORE_PAGES_INDICATOR not in page:
  801. for id in video_ids:
  802. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  803. return
  804. pagenum = pagenum + 1
  805. class YoutubePlaylistIE(InfoExtractor):
  806. """Information Extractor for YouTube playlists."""
  807. _VALID_URL = r'(?:http://)?(?:\w+\.)?youtube.com/view_play_list\?p=(.+)'
  808. _TEMPLATE_URL = 'http://www.youtube.com/view_play_list?p=%s&page=%s&gl=US&hl=en'
  809. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  810. _MORE_PAGES_INDICATOR = r'/view_play_list?p=%s&page=%s'
  811. _youtube_ie = None
  812. def __init__(self, youtube_ie, downloader=None):
  813. InfoExtractor.__init__(self, downloader)
  814. self._youtube_ie = youtube_ie
  815. @staticmethod
  816. def suitable(url):
  817. return (re.match(YoutubePlaylistIE._VALID_URL, url) is not None)
  818. def report_download_page(self, playlist_id, pagenum):
  819. """Report attempt to download playlist page with given number."""
  820. self._downloader.to_stdout(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  821. def _real_initialize(self):
  822. self._youtube_ie.initialize()
  823. def _real_extract(self, url):
  824. # Extract playlist id
  825. mobj = re.match(self._VALID_URL, url)
  826. if mobj is None:
  827. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  828. return
  829. # Download playlist pages
  830. playlist_id = mobj.group(1)
  831. video_ids = []
  832. pagenum = 1
  833. while True:
  834. self.report_download_page(playlist_id, pagenum)
  835. request = urllib2.Request(self._TEMPLATE_URL % (playlist_id, pagenum), None, std_headers)
  836. try:
  837. page = urllib2.urlopen(request).read()
  838. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  839. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  840. return
  841. # Extract video identifiers
  842. ids_in_page = []
  843. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  844. if mobj.group(1) not in ids_in_page:
  845. ids_in_page.append(mobj.group(1))
  846. video_ids.extend(ids_in_page)
  847. if (self._MORE_PAGES_INDICATOR % (playlist_id.upper(), pagenum + 1)) not in page:
  848. break
  849. pagenum = pagenum + 1
  850. for id in video_ids:
  851. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  852. return
  853. class PostProcessor(object):
  854. """Post Processor class.
  855. PostProcessor objects can be added to downloaders with their
  856. add_post_processor() method. When the downloader has finished a
  857. successful download, it will take its internal chain of PostProcessors
  858. and start calling the run() method on each one of them, first with
  859. an initial argument and then with the returned value of the previous
  860. PostProcessor.
  861. The chain will be stopped if one of them ever returns None or the end
  862. of the chain is reached.
  863. PostProcessor objects follow a "mutual registration" process similar
  864. to InfoExtractor objects.
  865. """
  866. _downloader = None
  867. def __init__(self, downloader=None):
  868. self._downloader = downloader
  869. def set_downloader(self, downloader):
  870. """Sets the downloader for this PP."""
  871. self._downloader = downloader
  872. def run(self, information):
  873. """Run the PostProcessor.
  874. The "information" argument is a dictionary like the ones
  875. composed by InfoExtractors. The only difference is that this
  876. one has an extra field called "filepath" that points to the
  877. downloaded file.
  878. When this method returns None, the postprocessing chain is
  879. stopped. However, this method may return an information
  880. dictionary that will be passed to the next postprocessing
  881. object in the chain. It can be the one it received after
  882. changing some fields.
  883. In addition, this method may raise a PostProcessingError
  884. exception that will be taken into account by the downloader
  885. it was called from.
  886. """
  887. return information # by default, do nothing
  888. ### MAIN PROGRAM ###
  889. if __name__ == '__main__':
  890. try:
  891. # Modules needed only when running the main program
  892. import getpass
  893. import optparse
  894. # General configuration
  895. urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()))
  896. urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor()))
  897. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  898. # Parse command line
  899. parser = optparse.OptionParser(
  900. usage='Usage: %prog [options] url...',
  901. version='2009.06.29',
  902. conflict_handler='resolve',
  903. )
  904. parser.add_option('-h', '--help',
  905. action='help', help='print this help text and exit')
  906. parser.add_option('-v', '--version',
  907. action='version', help='print program version and exit')
  908. parser.add_option('-i', '--ignore-errors',
  909. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  910. parser.add_option('-r', '--rate-limit',
  911. dest='ratelimit', metavar='L', help='download rate limit (e.g. 50k or 44.6m)')
  912. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  913. authentication.add_option('-u', '--username',
  914. dest='username', metavar='UN', help='account username')
  915. authentication.add_option('-p', '--password',
  916. dest='password', metavar='PW', help='account password')
  917. authentication.add_option('-n', '--netrc',
  918. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  919. parser.add_option_group(authentication)
  920. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  921. video_format.add_option('-f', '--format',
  922. action='store', dest='format', metavar='FMT', help='video format code')
  923. video_format.add_option('-b', '--best-quality',
  924. action='store_const', dest='format', help='download the best quality video possible', const='0')
  925. video_format.add_option('-m', '--mobile-version',
  926. action='store_const', dest='format', help='alias for -f 17', const='17')
  927. video_format.add_option('-d', '--high-def',
  928. action='store_const', dest='format', help='alias for -f 22', const='22')
  929. parser.add_option_group(video_format)
  930. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  931. verbosity.add_option('-q', '--quiet',
  932. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  933. verbosity.add_option('-s', '--simulate',
  934. action='store_true', dest='simulate', help='do not download video', default=False)
  935. verbosity.add_option('-g', '--get-url',
  936. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  937. verbosity.add_option('-e', '--get-title',
  938. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  939. parser.add_option_group(verbosity)
  940. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  941. filesystem.add_option('-t', '--title',
  942. action='store_true', dest='usetitle', help='use title in file name', default=False)
  943. filesystem.add_option('-l', '--literal',
  944. action='store_true', dest='useliteral', help='use literal title in file name', default=False)
  945. filesystem.add_option('-o', '--output',
  946. dest='outtmpl', metavar='TPL', help='output filename template')
  947. filesystem.add_option('-a', '--batch-file',
  948. dest='batchfile', metavar='F', help='file containing URLs to download')
  949. filesystem.add_option('-w', '--no-overwrites',
  950. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  951. filesystem.add_option('-c', '--continue',
  952. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=False)
  953. parser.add_option_group(filesystem)
  954. (opts, args) = parser.parse_args()
  955. # Batch file verification
  956. batchurls = []
  957. if opts.batchfile is not None:
  958. try:
  959. batchurls = open(opts.batchfile, 'r').readlines()
  960. batchurls = [x.strip() for x in batchurls]
  961. batchurls = [x for x in batchurls if len(x) > 0]
  962. except IOError:
  963. sys.exit(u'ERROR: batch file could not be read')
  964. all_urls = batchurls + args
  965. # Conflicting, missing and erroneous options
  966. if len(all_urls) < 1:
  967. parser.error(u'you must provide at least one URL')
  968. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  969. parser.error(u'using .netrc conflicts with giving username/password')
  970. if opts.password is not None and opts.username is None:
  971. parser.error(u'account username missing')
  972. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle):
  973. parser.error(u'using output template conflicts with using title or literal title')
  974. if opts.usetitle and opts.useliteral:
  975. parser.error(u'using title conflicts with using literal title')
  976. if opts.username is not None and opts.password is None:
  977. opts.password = getpass.getpass(u'Type account password and press return:')
  978. if opts.ratelimit is not None:
  979. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  980. if numeric_limit is None:
  981. parser.error(u'invalid rate limit specified')
  982. opts.ratelimit = numeric_limit
  983. # Information extractors
  984. youtube_ie = YoutubeIE()
  985. metacafe_ie = MetacafeIE(youtube_ie)
  986. youtube_pl_ie = YoutubePlaylistIE(youtube_ie)
  987. youtube_search_ie = YoutubeSearchIE(youtube_ie)
  988. # File downloader
  989. fd = FileDownloader({
  990. 'usenetrc': opts.usenetrc,
  991. 'username': opts.username,
  992. 'password': opts.password,
  993. 'quiet': (opts.quiet or opts.geturl or opts.gettitle),
  994. 'forceurl': opts.geturl,
  995. 'forcetitle': opts.gettitle,
  996. 'simulate': (opts.simulate or opts.geturl or opts.gettitle),
  997. 'format': opts.format,
  998. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(locale.getpreferredencoding()))
  999. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  1000. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  1001. or u'%(id)s.%(ext)s'),
  1002. 'ignoreerrors': opts.ignoreerrors,
  1003. 'ratelimit': opts.ratelimit,
  1004. 'nooverwrites': opts.nooverwrites,
  1005. 'continuedl': opts.continue_dl,
  1006. })
  1007. fd.add_info_extractor(youtube_search_ie)
  1008. fd.add_info_extractor(youtube_pl_ie)
  1009. fd.add_info_extractor(metacafe_ie)
  1010. fd.add_info_extractor(youtube_ie)
  1011. retcode = fd.download(all_urls)
  1012. sys.exit(retcode)
  1013. except DownloadError:
  1014. sys.exit(1)
  1015. except SameFileError:
  1016. sys.exit(u'ERROR: fixed output name but more than one file to download')
  1017. except KeyboardInterrupt:
  1018. sys.exit(u'\nERROR: Interrupted by user')