Created
April 16, 2016 14:12
-
-
Save mipsparc/cbf450eb80df23bc62c6a29027ec1a56 to your computer and use it in GitHub Desktop.
Fork of nicovideo-dl(https://osdn.jp/projects/nicovideo-dl/). Made for private using purpose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| # | |
| # Copyright (c) 2009 Keiichiro Nagano | |
| # Copyright (c) 2009 Kimura Youichi | |
| # Copyright (c) 2006-2008 Ricardo Garcia Gonzalez | |
| # Copyright (c) 2008 Ying-Chun Liu (PaulLiu) | |
| # | |
| # Permission is hereby granted, free of charge, to any person obtaining a | |
| # copy of this software and associated documentation files (the "Software"), | |
| # to deal in the Software without restriction, including without limitation | |
| # the rights to use, copy, modify, merge, publish, distribute, sublicense, | |
| # and/or sell copies of the Software, and to permit persons to whom the | |
| # Software is furnished to do so, subject to the following conditions: | |
| # | |
| # The above copyright notice and this permission notice shall be included | |
| # in all copies or substantial portions of the Software. | |
| # | |
| # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL | |
| # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR | |
| # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | |
| # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
| # OTHER DEALINGS IN THE SOFTWARE. | |
| # | |
| # Except as contained in this notice, the name(s) of the above copyright | |
| # holders shall not be used in advertising or otherwise to promote the | |
| # sale, use or other dealings in this Software without prior written | |
| # authorization. | |
| # | |
| import getpass | |
| import httplib | |
| import math | |
| import sys | |
| import os | |
| import re | |
| import socket | |
| import string | |
| import sys | |
| import time | |
| import urllib2 | |
| import cgi | |
| import codecs | |
| import xml.parsers.expat | |
| # Global constants | |
| const_version = '2011.02.08' | |
| const_project_url = 'http://sourceforge.jp/projects/nicovideo-dl' | |
| const_1k = 1024 | |
| const_initial_block_size = 10 * const_1k | |
| const_epsilon = 0.0001 | |
| const_timeout = 120 | |
| const_video_url_str = 'http://www.nicovideo.jp/watch/%s' | |
| const_video_url_re = re.compile(r'^((?:http://)?(?:\w+\.)?(?:nicovideo\.jp/(?:v/|(?:watch(?:\.php)?))?/)?(\w+))') | |
| const_login_url_str = 'https://secure.nicovideo.jp/secure/login?site=niconico' | |
| const_login_post_str = 'current_form=login&mail=%s&password=%s&login_submit=Log+In' | |
| const_url_url_param_re = re.compile(r"url[=](http[^&]*)") | |
| const_video_url_info_str = 'http://www.nicovideo.jp/api/getflv?v=%s&as3=1' | |
| const_video_title_re = re.compile(r'<title>(.*)</title>', re.M | re.I) | |
| const_video_type_re = re.compile(r'^http://.*\.nicovideo\.jp/smile\?(.*?)=.*') | |
| const_comment_getthreadkey_url_str = 'http://flapi.nicovideo.jp/api/getthreadkey?thread=%s' | |
| const_comment_request_str = '<thread thread="%s" version="20061206" res_from="-1000" user_id="%s"%s/>' | |
| # Print error message, followed by standard advice information, and then exit | |
| def error_advice_exit(error_text): | |
| print('Error: %s.\n' % error_text) | |
| exit() | |
| # Wrapper to create custom requests with typical headers | |
| def request_create(url, extra_headers, post_data=None): | |
| retval = urllib2.Request(url) | |
| if post_data is not None: | |
| retval.add_data(post_data) | |
| retval.add_header('User-Agent', 'nicovideo-dl/%s (%s)' % (const_version, const_project_url)) | |
| retval.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') | |
| retval.add_header('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5') | |
| retval.add_header('Accept-Language', 'en-us,en;q=0.5') | |
| if extra_headers is not None: | |
| for header in extra_headers: | |
| retval.add_header(header[0], header[1]) | |
| return retval | |
| # Perform a request, process headers and return response | |
| def perform_request(url, headers=None, data=None): | |
| request = request_create(url, headers, data) | |
| response = urllib2.urlopen(request) | |
| return response | |
| # Title string normalization | |
| def title_string_norm(title): | |
| title_s = unicode(title.decode('utf-8', 'ignore')) | |
| for title_p in [u'‐ニコニコ動画(SP1)', | |
| u'‐ニコニコ動画(夏)', | |
| u'‐ニコニコ動画(秋)', # as of Oct 2008 | |
| u'‐ニコニコ動画(冬)', # as of 5 Dec 2008 | |
| u'‐ニコニコ動画(ββ)', # as of 12 Dec 2008 | |
| u'‐ニコニコ動画(9)', # as of 29 Oct 2009 | |
| u'‐ ニコニコ動画(原宿)', # as of 29 Oct 2010 | |
| ]: | |
| if (title_s.endswith(title_p)): | |
| title_s = title_s[:title_s.rfind(title_p)] | |
| break | |
| title_s = title_s.replace(os.sep, u'%') | |
| title_s = u'_'.join(title_s.split()) | |
| title_s = title_s.encode('utf-8','ignore') | |
| return title_s | |
| # Title string minimal transformation | |
| def title_string_touch(title): | |
| return title.replace(os.sep, '%') | |
| # Generic download step | |
| def download_step(return_data_flag, step_title, step_error, url, post_data=None): | |
| try: | |
| response = perform_request(url, data=post_data) | |
| data = response.read() | |
| if return_data_flag: | |
| return data, response | |
| return None | |
| except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError, socket.error): | |
| error_advice_exit(step_error) | |
| except KeyboardInterrupt: | |
| sys.exit('\n') | |
| # Generic extract step | |
| def extract_step(step_title, step_error, regexp, data): | |
| try: | |
| match = regexp.search(data) | |
| if match is None: | |
| error_advice_exit(step_error) | |
| extracted_data = match.group(1) | |
| return extracted_data | |
| except KeyboardInterrupt: | |
| sys.exit('\n') | |
| # Calculate new block size based on previous block size | |
| def new_block_size(before, after, bytes): | |
| new_min = max(bytes / 2.0, 1.0) | |
| new_max = max(bytes * 2.0, 1.0) | |
| dif = after - before | |
| if dif < const_epsilon: | |
| return int(new_max) | |
| rate = bytes / dif | |
| if rate > new_max: | |
| return int(new_max) | |
| if rate < new_min: | |
| return int(new_min) | |
| return int(rate) | |
| # Get optimum 1k exponent to represent a number of bytes | |
| def optimum_k_exp(num_bytes): | |
| global const_1k | |
| if num_bytes == 0: | |
| return 0 | |
| return long(math.log(num_bytes, const_1k)) | |
| # Get optimum representation of number of bytes | |
| def format_bytes(num_bytes): | |
| global const_1k | |
| try: | |
| exp = optimum_k_exp(num_bytes) | |
| suffix = 'bkMGTPEZY'[exp] | |
| if exp == 0: | |
| return '%s%s' % (num_bytes, suffix) | |
| converted = float(num_bytes) / float(const_1k**exp) | |
| return '%.2f%s' % (converted, suffix) | |
| except IndexError: | |
| sys.exit('Error: internal error formatting number of bytes.') | |
| # Calculate ETA and return it in string format as MM:SS | |
| def calc_eta(start, now, total, current): | |
| dif = now - start | |
| if current == 0 or dif < const_epsilon: | |
| return '--:--' | |
| rate = float(current) / dif | |
| eta = long((total - current) / rate) | |
| (eta_mins, eta_secs) = divmod(eta, 60) | |
| if eta_mins > 99: | |
| return '--:--' | |
| return '%02d:%02d' % (eta_mins, eta_secs) | |
| # Calculate speed and return it in string format | |
| def calc_speed(start, now, bytes): | |
| dif = now - start | |
| if bytes == 0 or dif < const_epsilon: | |
| return 'N/A b' | |
| return format_bytes(float(bytes) / dif) | |
| # Set socket timeout | |
| socket.setdefaulttimeout(const_timeout) | |
| args = sys.argv | |
| # Get account information if any | |
| video_url_cmdl = args[3] | |
| account_username = args[1] | |
| account_password = args[2] | |
| # Install cookie and proxy handlers | |
| urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())) | |
| urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor())) | |
| # Log in | |
| if account_username is not None: | |
| url = const_login_url_str | |
| post = const_login_post_str % (account_username, account_password) | |
| download_step(False, 'Logging in', 'unable to log in', url, post) | |
| # Verify video URL format and convert to "standard" format | |
| video_url_mo = const_video_url_re.match(video_url_cmdl) | |
| print video_url_mo | |
| if video_url_mo is None: | |
| sys.exit('Error: URL does not seem to be a niconico video URL. If it is, report a bug.') | |
| video_url_id = video_url_mo.group(2) | |
| video_url = const_video_url_str % video_url_id | |
| video_extension = '.flv' | |
| # Retrieve video webpage | |
| video_webpage, response = download_step(True, 'Retrieving video webpage', 'unable to retrieve video webpage', video_url) | |
| # Reconvert URL if redirected | |
| if response.geturl() != video_url: | |
| video_url_id = const_video_url_re.match(response.geturl()).group(2) | |
| video_url = const_video_url_str % video_url_id | |
| # Extract video title if needed | |
| video_title = extract_step('Extracting video title', 'unable to extract video title', const_video_title_re, video_webpage) | |
| # Extract needed video URL parameters | |
| video_url_info = const_video_url_info_str % video_url_id | |
| video_info_data, response = download_step(True, 'Retrieving info data', 'unable to retrieve video webpage', video_url_info) | |
| video_url_url_param = cgi.parse_qs(video_info_data) | |
| print(video_url_url_param) | |
| if (video_url_url_param.has_key("url")): | |
| video_url_url_param=video_url_url_param["url"][0] | |
| else: | |
| error_advice_exit('cannot extract url parameter') | |
| video_url_real = (video_url_url_param) | |
| # Extract video type and modify video_extension | |
| video_type_mo = const_video_type_re.match(video_url_real) | |
| if (video_type_mo): | |
| if video_type_mo.group(1) == "s": | |
| video_extension = ".swf" | |
| elif video_type_mo.group(1) == "m": | |
| video_extension = ".mp4" | |
| # Rebuild filename if needed | |
| video_filename = '%s%s' % (video_url_id, video_extension) | |
| # Retrieve video data | |
| try: | |
| video_data = perform_request(video_url_real) | |
| try: | |
| video_file = open(video_filename, 'wb') | |
| except (IOError, OSError): | |
| sys.exit('Error: unable to open "%s" for writing.' % video_filename) | |
| try: | |
| video_len = long(video_data.info()['Content-length']) | |
| video_len_str = format_bytes(video_len) | |
| except KeyError: | |
| video_len = None | |
| video_len_str = 'N/A' | |
| byte_counter = 0 | |
| block_size = const_initial_block_size | |
| start_time = time.time() | |
| while True: | |
| if video_len is not None: | |
| percent = float(byte_counter) / float(video_len) * 100.0 | |
| percent_str = '%.1f' % percent | |
| eta_str = calc_eta(start_time, time.time(), video_len, byte_counter) | |
| else: | |
| percent_str = '---.-' | |
| eta_str = '--:--' | |
| counter = format_bytes(byte_counter) | |
| speed_str = calc_speed(start_time, time.time(), byte_counter) | |
| before = time.time() | |
| video_block = video_data.read(block_size) | |
| after = time.time() | |
| dl_bytes = len(video_block) | |
| if dl_bytes == 0: | |
| break | |
| byte_counter += dl_bytes | |
| video_file.write(video_block) | |
| block_size = new_block_size(before, after, dl_bytes) | |
| if video_len is not None and byte_counter != video_len: | |
| error_advice_exit('server did not send the expected amount of data') | |
| video_file.close() | |
| except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError, socket.error): | |
| error_advice_exit('unable to download video data') | |
| except KeyboardInterrupt: | |
| sys.exit('\n') | |
| # Finish | |
| sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment