├── courseradownloader ├── __init__.py ├── _version.py ├── .gitignore ├── util.py └── courseradownloader.py ├── MANIFEST.in ├── requirements.txt ├── .gitattributes ├── setup.py ├── CHANGELOG.txt ├── README.md └── LICENSE.txt /courseradownloader/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.txt 2 | include *.md 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | mechanize 3 | argparse 4 | 5 | -------------------------------------------------------------------------------- /courseradownloader/_version.py: -------------------------------------------------------------------------------- 1 | __version_info__ = (3,1,1) 2 | __version__ = '.'.join(map(str, __version_info__)) 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set default behaviour, in case users don't have core.autocrlf set 2 | * text=auto 3 | 4 | # Explicitly declare text files we want to always be normalized and converted 5 | # to native line endings on checkout. 6 | *.py text 7 | 8 | -------------------------------------------------------------------------------- /courseradownloader/.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | __pycache__ 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup 4 | from os import path 5 | import os 6 | from courseradownloader import _version 7 | 8 | 9 | # get the requirements from the pip requirements file 10 | requirements = [] 11 | 12 | with open("requirements.txt") as f: 13 | for l in f: 14 | l = l.strip() 15 | if l: requirements.append(l) 16 | 17 | setup(name="coursera-dl", 18 | version=_version.__version__, 19 | description="Download coursera.org class videos and resources", 20 | long_description=open("README.md").read(), 21 | author="Dirk Gorissen", 22 | author_email="dgorissen@gmail.com", 23 | url="https://github.com/dgorissen/coursera-dl", 24 | license="GPLv3", 25 | packages=["courseradownloader"], 26 | entry_points = { "console_scripts" : [ "coursera-dl = courseradownloader.courseradownloader:main"]}, 27 | install_requires=requirements 28 | ) 29 | 30 | -------------------------------------------------------------------------------- /CHANGELOG.txt: -------------------------------------------------------------------------------- 1 | * 3.1.1 - Wed 24 Dec 2014 2 | - Fix authentication problems (by @danmbox) 3 | 4 | * 3.1 - Wed 26 Nov 2014 5 | - add '-i INCLUDEFILES' option (file extensions to download) 6 | - add '-l LANG' option (subtitles' language choice) 7 | - generate html output with lectures and resources list 8 | 9 | * 3.0.1 - Wed 22 Oct 2014 10 | - merge path length patch from Biju Joseph Jacob 11 | 12 | * 3.0 - Mon 04 Aug 2014 13 | - revert to mechanize branch after sustained issues 14 | - backport 2.x commits 15 | 16 | * 2.0.2 - Wed 9 Jul 2014 17 | - fix authentication after coursera update 18 | 19 | * 2.0.1 - Tue 11 Mar 2014 20 | - fix mppl behavior 21 | 22 | * 2.0.0 - Fri 7 Mar 2014 23 | - replace dependency on mechanize by requests & six 24 | - make compatible with python 3 25 | - properly respect mppl 26 | - also re-download files if the size on disk is larger 27 | - all round bug fixes and small cleanups 28 | 29 | * 1.5.1 - Sat 5 Oct 30 | - commandline parameter for selecting weeks 31 | - filename fix following coursera updatex 32 | - correctly handle courses with hyphens in the name 33 | 34 | * 1.5 - Fri 13 Sep 35 | - code cleanups 36 | - fixed proxy support 37 | - added option to automatically gzip courses 38 | - crash less on long filenames on windows 39 | - also download about json file 40 | - small bugfixes 41 | 42 | * 1.4.11 - Fri 23 Aug 43 | - update to new coursera authentication details 44 | 45 | * 1.4.10 - Sun 30 Jun 46 | - made html.parser the default 47 | 48 | * 1.4.9 - Wed 19 Jun 49 | - small bug/crash fixes 50 | - long filename trimming on windows 51 | 52 | * 1.4.8 - Sun 28 Apr 53 | - netrc support for caching credentials 54 | - added explict timeouts when downloading files 55 | - small bugfixes and code cleanups 56 | 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | coursera-dl 2 | =========== 3 | 4 | A python package for archiving content from coursera.org (videos, 5 | lecture notes, ...) for offline reference. Originally forked from 6 | [https://github.com/abhirama/coursera-download][] but significantly 7 | cleaned up and enhanced. 8 | 9 | Some people have asked if they could donate something. If you wish you can do so here: 10 | 11 | [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=A6HCYM6JBJY5N&lc=US&item_name=Dirk%20Gorissen¤cy_code=GBP&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted) 12 | 13 | Installation 14 | ------------ 15 | 16 | Make sure you have installed [Python][] 2.7 and [pip][]. 17 | 18 | Then simply run: pip install coursera-dl 19 | 20 | This will create a coursera-dl script in /usr/local/bin (linux), 21 | c:\\Python2.7\\Scripts (windows), or /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin (OSX). 22 | 23 | Note exact paths may vary depending on your system. 24 | 25 | (to upgrade use pip install --upgrade) 26 | 27 | Usage 28 | ----- 29 | 30 | See: coursera-dl -h 31 | 32 | Example usage: 33 | 34 |
35 | coursera-dl -u myusername -p mypassword -d /my/coursera/courses/ algo-2012-001 ml-2012-002
36 | 
37 | 38 | Note: you can also specify your login and password in .netrc file in your home directory. 39 | Just add this line to ~/.netrc 40 |
41 | machine coursera-dl login myusername password mypassword
42 | 
43 | 44 | Now you can use coursera-dl like this: 45 | 46 |
47 | coursera-dl -d /my/coursera/courses/ algo-2012-001 ml-2012-002
48 | 
49 | 50 | Note: ensure you have accepted the honor code of the class before using 51 | this script (happens the very first time you go to the class page). 52 | 53 | [https://github.com/abhirama/coursera-download]: https://github.com/abhirama/coursera-download 54 | [Python]: http://www.python.org/download/ 55 | [pip]: http://www.pip-installer.org/en/latest/installing.html 56 | -------------------------------------------------------------------------------- /courseradownloader/util.py: -------------------------------------------------------------------------------- 1 | import re 2 | import urllib2 3 | from urlparse import urlsplit, urlparse 4 | import unicodedata 5 | from os import path 6 | 7 | def filename_from_header(header): 8 | try: 9 | cd = header['Content-Disposition'] 10 | pattern = 'attachment; filename="(.*?)"' 11 | m = re.search(pattern, cd) 12 | g = m.group(1) 13 | if ("%" in g): g = urllib2.unquote(g) 14 | return sanitise_filename(g) 15 | except Exception: 16 | return '' 17 | 18 | def filename_from_url(url): 19 | # parse the url into its components 20 | u = urlsplit(url) 21 | 22 | # split the path into parts and unquote 23 | parts = [urllib2.unquote(x).strip() for x in u.path.split('/')] 24 | 25 | # take the last component as filename 26 | fname = parts[-1] 27 | 28 | # if empty, url ended with a trailing slash 29 | # so join up the hostnam/path and use that as a filename 30 | if len(fname) < 1: 31 | s = u.netloc + u.path[:-1] 32 | fname = s.replace('/','_') 33 | else: 34 | # unquoting could have cuased slashes to appear again 35 | # split and take the last element if so 36 | fname = fname.split('/')[-1] 37 | 38 | # add an extension if none 39 | ext = path.splitext(fname)[1] 40 | if len(ext) < 1 or len(ext) > 5: 41 | fname += ".html" 42 | 43 | # remove any illegal chars and return 44 | return sanitise_filename(fname) 45 | 46 | def clean_url(url): 47 | if not url: return None 48 | 49 | url = url.strip() 50 | 51 | if url and not urlparse(url).scheme: 52 | url = "http://" + url 53 | 54 | return url 55 | 56 | def sanitise_filename(fileName): 57 | # ensure a clean, valid filename (arg may be both str and unicode) 58 | 59 | # ensure a unicode string, problematic ascii chars will get removed 60 | if isinstance(fileName,str): 61 | fn = unicode(fileName,errors='ignore') 62 | else: 63 | fn = fileName 64 | 65 | # normalize it 66 | fn = unicodedata.normalize('NFKD',fn) 67 | 68 | # encode it into ascii, again ignoring problematic chars 69 | s = fn.encode('ascii','ignore') 70 | 71 | # remove any characters not in the whitelist 72 | s = re.sub('[^\w\-\(\)\[\]\., ]','',s).strip() 73 | 74 | # ensure it is within a sane maximum 75 | max = 250 76 | 77 | # split off extension, trim, and re-add the extension 78 | fn,ext = path.splitext(s) 79 | s = fn[:max-len(ext)] + ext 80 | 81 | return s 82 | 83 | def trim_path(pathname, max_path_len=255, min_len=5): 84 | """ 85 | Trim file name in given path name to fit max_path_len characters. Only file name is trimmed, 86 | path names are not affected to avoid creating multiple folders for the same lecture. 87 | """ 88 | if len(pathname) <= max_path_len: 89 | return pathname 90 | 91 | fpath, name = path.split(pathname) 92 | name, ext = path.splitext(name) 93 | 94 | to_cut = len(pathname) - max_path_len 95 | to_keep = len(name) - to_cut 96 | 97 | if to_keep < min_len: 98 | print ' Warning: Cannot trim filename "%s" to fit required path length (%d)' % (pathname, max_path_len) 99 | return pathname 100 | 101 | name = name[:to_keep] 102 | new_pathname = path.join(fpath, name + ext) 103 | print ' Trimmed path name "%s" to "%s" to fit required length (%d)' % (pathname, new_pathname, max_path_len) 104 | 105 | return new_pathname 106 | -------------------------------------------------------------------------------- /courseradownloader/courseradownloader.py: -------------------------------------------------------------------------------- 1 | import re 2 | import urllib 3 | import urllib2 4 | import argparse 5 | import json 6 | import os 7 | import getpass 8 | import netrc 9 | import mechanize 10 | import cookielib 11 | import platform 12 | import shutil 13 | import sys 14 | import tarfile 15 | import math 16 | from bs4 import BeautifulSoup 17 | import tempfile 18 | from os import path 19 | from util import * 20 | import _version 21 | 22 | MAX_PATH_LENGTH_WINDOWS = 260 23 | MAX_PATH_LENGTH_LINUX = 4096 24 | 25 | class CourseraDownloader(object): 26 | """ 27 | Class to download content (videos, lecture notes, ...) from coursera.org for 28 | use offline. 29 | 30 | https://github.com/dgorissen/coursera-dl 31 | 32 | :param username: username 33 | :param password: password 34 | :keyword proxy: http proxy, eg: foo.bar.com:1234 35 | :keyword parser: xml parser 36 | :keyword ignorefiles: comma separated list of file extensions to skip (e.g., "ppt,srt") 37 | :keyword includefiles: comma separated list of file extensions to download (e.g., "pdf") 38 | """ 39 | BASE_URL = 'https://class.coursera.org/%s' 40 | HOME_URL = BASE_URL + '/class/index' 41 | LECTURE_URL = BASE_URL + '/lecture/index' 42 | QUIZ_URL = BASE_URL + '/quiz/index' 43 | AUTH_URL = BASE_URL + "/auth/auth_redirector?type=login&subtype=normal" 44 | LOGIN_URL = "https://accounts.coursera.org/api/v1/login" 45 | ABOUT_URL = "https://www.coursera.org/maestro/api/topic/information?topic-id=%s" 46 | 47 | #see http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser 48 | DEFAULT_PARSER = "html.parser" 49 | 50 | # how long to try to open a URL before timing out 51 | TIMEOUT=60.0 52 | 53 | HTML_TEMPLATE = ''' 54 | 55 | 56 | Course materials 57 | 64 | 65 | %s 66 | ''' 67 | 68 | 69 | def __init__(self,username, 70 | password, 71 | proxy=None, 72 | parser=DEFAULT_PARSER, 73 | ignorefiles=None, 74 | includefiles=None, 75 | max_path_part_len=None, 76 | gzip_courses=False, 77 | wk_filter=None, 78 | lang=None): 79 | 80 | self.username = username 81 | self.password = password 82 | self.parser = parser 83 | 84 | self.ignorefiles = self.parseFileExtensions(ignorefiles) 85 | self.includefiles = self.parseFileExtensions(includefiles) 86 | 87 | self.browser = None 88 | self.proxy = proxy 89 | self.max_path_part_len = max_path_part_len 90 | self.gzip_courses = gzip_courses 91 | self.lang = lang 92 | 93 | self.html = "" 94 | 95 | try: 96 | self.wk_filter = map(int,wk_filter.split(",")) if wk_filter else None 97 | except Exception as e: 98 | print "Invalid week filter, should be a comma separated list of integers", e 99 | exit() 100 | 101 | @staticmethod 102 | def parseFileExtensions(extensionsStr): 103 | """ 104 | Split strings with file extensions ("ignorefiles" and "includefiles" arguments) on commas, 105 | strip, remove prefixing dot if there is one, and filter out empty tokens. 106 | """ 107 | return [x.strip()[1:] if x[0]=='.' else x.strip() 108 | for x in extensionsStr.split(',') if len(x)] 109 | 110 | def login(self,className): 111 | """ 112 | Login into coursera and obtain the necessary session cookies. 113 | """ 114 | hn,fn = tempfile.mkstemp() 115 | cj = cookielib.LWPCookieJar() 116 | handlers = [ 117 | urllib2.HTTPHandler(), 118 | urllib2.HTTPSHandler(), 119 | urllib2.HTTPCookieProcessor(cj) 120 | ] 121 | 122 | # prepend a proxy handler if defined 123 | if(self.proxy): 124 | proxy = urllib2.ProxyHandler({'http': self.proxy}) 125 | handlers = [proxy] + handlers 126 | 127 | opener = urllib2.build_opener(*handlers) 128 | 129 | url = self.lecture_url_from_name(className) 130 | req = urllib2.Request(url) 131 | 132 | try: 133 | res = opener.open(req) 134 | except urllib2.HTTPError as e: 135 | if e.code == 404: 136 | raise Exception("Unknown class %s" % className) 137 | 138 | # get the csrf token 139 | csrfcookie = [c for c in cj if c.name == "csrf_token"] 140 | if not csrfcookie: raise Exception("Failed to find csrf cookie") 141 | csrftoken = csrfcookie[0].value 142 | 143 | csrfcookie = cookielib.Cookie(version=0, name='csrftoken', value=csrftoken, 144 | domain='.coursera.org', domain_specified=False, domain_initial_dot=False, 145 | path='/', path_specified=False, 146 | expires=None, 147 | secure=False, 148 | comment=None, comment_url=None, 149 | rest={'HttpOnly':None}, 150 | rfc2109=False, 151 | discard=False, 152 | port=None, port_specified=False) 153 | cj.set_cookie(csrfcookie) 154 | data = urllib.urlencode({'email': self.username,'password': self.password,'webrequest': 'true'}) 155 | req = urllib2.Request(self.LOGIN_URL, data, { 'Referer': 'https://www.coursera.org', 'X-CSRFToken': csrftoken}) 156 | 157 | try: 158 | opener.open(req) 159 | # timeout=self.TIMEOUT should be handled 160 | except urllib2.HTTPError as e: 161 | if e.code == 401: 162 | raise Exception("Invalid username or password") 163 | 164 | # check if we managed to login 165 | sessionid = [c.name for c in cj if c.name == "CAUTH"] 166 | if not sessionid: 167 | raise Exception("Failed to authenticate as %s" % self.username) 168 | 169 | # all should be ok now, mechanize can handle the rest if we give it the 170 | # cookies 171 | br = mechanize.Browser() 172 | #br.set_debug_http(True) 173 | #br.set_debug_responses(False) 174 | #br.set_debug_redirects(True) 175 | br.set_handle_robots(False) 176 | br.set_cookiejar(cj) 177 | 178 | if self.proxy: 179 | br.set_proxies({"http":self.proxy}) 180 | 181 | self.browser = br 182 | 183 | # also use this cookiejar for other mechanize operations (e.g., urlopen) 184 | opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cj)) 185 | mechanize.install_opener(opener) 186 | 187 | def course_name_from_url(self,course_url): 188 | """Given the course URL, return the name, e.g., algo2012-p2""" 189 | return course_url.split('/')[3] 190 | 191 | def lecture_url_from_name(self,course_name): 192 | """Given the name of a course, return the video lecture url""" 193 | return self.LECTURE_URL % course_name 194 | 195 | def trim_path_part(self,s): 196 | mppl = self.max_path_part_len 197 | if mppl and len(s) > mppl: 198 | return s[:mppl] 199 | else: 200 | return s 201 | 202 | def get_downloadable_content(self,course_url): 203 | """ 204 | Given the video lecture URL of the course, return a list of all 205 | downloadable resources. 206 | """ 207 | 208 | cname = self.course_name_from_url(course_url) 209 | 210 | print "* Collecting downloadable content from " + course_url 211 | 212 | # get the course name, and redirect to the course lecture page 213 | vidpage = self.browser.open(course_url,timeout=self.TIMEOUT) 214 | 215 | # extract the weekly classes 216 | soup = BeautifulSoup(vidpage,self.parser) 217 | 218 | # extract the weekly classes 219 | weeks = soup.findAll("div", { "class" : "course-item-list-header" }) 220 | 221 | weeklyTopics = [] 222 | 223 | # for each weekly class 224 | for week in weeks: 225 | # title of this weeks' classes 226 | h3 = week.findNext('h3') 227 | weekTopic = sanitise_filename(h3.text) 228 | weekTopic = self.trim_path_part(weekTopic) 229 | 230 | # get all the classes for the week 231 | ul = week.next_sibling 232 | lis = ul.findAll('li') 233 | weekClasses = [] 234 | 235 | # for each class (= lecture) 236 | classNames = [] 237 | for li in lis: 238 | # the name of this class 239 | className = li.a.find(text=True).strip() 240 | 241 | # Many class names have the following format: 242 | # "Something really cool (12:34)" 243 | # If the class name has this format, replace the colon in the 244 | # time with a hyphen. 245 | if re.match(".+\(\d?\d:\d\d\)$",className): 246 | head,sep,tail = className.rpartition(":") 247 | className = head + "-" + tail 248 | 249 | className = sanitise_filename(className) 250 | className = self.trim_path_part(className) 251 | 252 | # collect all the resources for this class (ppt, pdf, mov, ..) 253 | classResources = li.find('div', {'class':'course-lecture-item-resource'}) 254 | hrefs = classResources.findAll('a') 255 | resourceLinks = [] 256 | 257 | for a in hrefs: 258 | # get the hyperlink itself 259 | h = clean_url(a.get('href')) 260 | if not h: continue 261 | 262 | # Sometimes the raw, uncompresed source videos are available as 263 | # well. Don't download them as they are huge and available in 264 | # compressed form anyway. 265 | if h.find('source_videos') > 0: 266 | print " - will skip raw source video " + h 267 | else: 268 | if self.lang and h.find('subtitles') > 0: 269 | # Substitutes the matched language with user's one 270 | def language(match): 271 | num = match.group('num') 272 | return 'q={num}_{lang}'.format(num=num, lang=self.lang ) 273 | 274 | h = re.sub('q=(?P[\d]+)_\w+', language, h) 275 | 276 | # Dont set a filename here, that will be inferred from the week 277 | # titles 278 | resourceLinks.append( (h,None) ) 279 | 280 | # check if the video is included in the resources, if not, try 281 | # do download it directly 282 | hasvid = [x for x,_ in resourceLinks if x.find('.mp4') > 0] 283 | if not hasvid: 284 | ll = li.find('a',{'class':'lecture-link'}) 285 | lurl = clean_url(ll['data-modal-iframe']) 286 | 287 | try: 288 | pg = self.browser.open(lurl,timeout=self.TIMEOUT) 289 | 290 | bb = BeautifulSoup(pg,self.parser) 291 | vobj = bb.find('source',type="video/mp4") 292 | 293 | if not vobj: 294 | print " Warning: Failed to find video for %s" % className 295 | else: 296 | vurl = clean_url(vobj['src']) 297 | # build the matching filename 298 | fn = className + ".mp4" 299 | resourceLinks.append( (vurl,fn) ) 300 | 301 | except urllib2.HTTPError as e: 302 | # sometimes there is a lecture without a video (e.g., 303 | # genes-001) so this can happen. 304 | print " Warning: failed to open the direct video link %s: %s" % (lurl,e) 305 | 306 | weekClasses.append( (className,resourceLinks) ) 307 | 308 | weeklyTopics.append( (weekTopic, weekClasses) ) 309 | 310 | return weeklyTopics 311 | 312 | def get_headers(self,url): 313 | """ 314 | Get the headers 315 | """ 316 | r = self.browser.open(url,timeout=self.TIMEOUT) 317 | return r.info() 318 | 319 | def download(self, url, target_dir=".", target_fname=None, class_dir=None): 320 | """ 321 | Download the url to the given filename 322 | """ 323 | 324 | # get the headers 325 | headers = self.get_headers(url) 326 | 327 | # get the content length (if present) 328 | clen = int(headers.get('Content-Length',-1)) 329 | 330 | # build the absolute path we are going to write to 331 | fname = target_fname or filename_from_header(headers) or filename_from_url(url) 332 | 333 | # split off the extension 334 | basename, ext = path.splitext(fname) 335 | 336 | # ensure it respects mppl 337 | fname = self.trim_path_part(basename) + ext 338 | 339 | # check if we should skip it (remember to remove the leading .) 340 | if ext and ext[1:] in self.ignorefiles: 341 | print ' - skipping "%s" (extension ignored)' % fname 342 | return 343 | 344 | # if downloading class resource (as opposed to lecture/syllabus pages), and '-i' arg specified 345 | # then skip other file extensions (and files with no extensions) 346 | if (class_dir and self.includefiles and not (ext and ext[1:] in self.includefiles)): 347 | print ' - skipping "%s" (extension not included)' % fname 348 | return 349 | 350 | filepath = trim_path(path.join(target_dir, fname), get_max_path_length()-1, 1) 351 | 352 | if (class_dir): self.html += '%s \n' % (path.join(class_dir, fname), ext[1:]) 353 | 354 | dl = True 355 | if path.exists(filepath): 356 | if clen > 0: 357 | fs = path.getsize(filepath) 358 | delta = math.fabs(clen - fs) 359 | 360 | # there are cases when a file was not completely downloaded or 361 | # something went wront that meant the file on disk is 362 | # unreadable. The file on disk my be smaller or larger (!) than 363 | # the reported content length in those cases. 364 | # Hence we overwrite the file if the reported content length is 365 | # different than what we have already by at least k bytes (arbitrary) 366 | 367 | # TODO this is still not foolproof as the fundamental problem is that the content length cannot be trusted 368 | # so this really needs to be avoided and replaced by something 369 | # else, eg., explicitly storing what downloaded correctly 370 | if delta > 10: 371 | print ' - "%s" seems corrupt, downloading again' % fname 372 | else: 373 | print ' - "%s" already exists, skipping' % fname 374 | dl = False 375 | else: 376 | # missing or invalid content length 377 | # assume all is ok... 378 | dl = False 379 | else: 380 | # Detect renamed files 381 | existing, short = find_renamed(filepath, clen) 382 | if existing: 383 | print ' - "%s" seems to be a copy of "%s", renaming existing file' % (fname, short) 384 | os.rename(existing, filepath) 385 | dl = False 386 | 387 | try: 388 | if dl: 389 | self.browser.retrieve(url,filepath,timeout=self.TIMEOUT) 390 | except Exception as e: 391 | print "Failed to download url %s to %s: %s" % (url,filepath,e) 392 | 393 | def download_about(self, cname, course_dir): 394 | """ 395 | Download the 'about' json file 396 | """ 397 | fn = os.path.join(course_dir, cname + '-about.json') 398 | 399 | # get the base course name (without the -00x suffix) 400 | base_name = re.split('(-[0-9]+)', cname)[0] 401 | 402 | # get the json 403 | about_url = self.ABOUT_URL % base_name 404 | about_json = self.browser.open(about_url,timeout=self.TIMEOUT).read() 405 | data = json.loads(about_json) 406 | 407 | # pretty print to file 408 | with open(fn, 'w') as f: 409 | json_data = json.dumps(data, indent=4, separators=(',', ':')) 410 | f.write(json_data) 411 | 412 | def download_course(self,cname,dest_dir=".",reverse_sections=False,gzip_courses=False): 413 | """ 414 | Download all the contents (quizzes, videos, lecture notes, ...) 415 | of the course to the given destination directory (defaults to .) 416 | """ 417 | # open the main class page 418 | self.browser.open(self.AUTH_URL % cname,timeout=self.TIMEOUT) 419 | 420 | # get the lecture url 421 | course_url = self.lecture_url_from_name(cname) 422 | 423 | weeklyTopics = self.get_downloadable_content(course_url) 424 | 425 | if not weeklyTopics: 426 | print " Warning: no downloadable content found for %s, did you accept the honour code?" % cname 427 | return 428 | else: 429 | print '* Got all downloadable content for ' + cname 430 | 431 | if reverse_sections: 432 | weeklyTopics.reverse() 433 | print "* Weekly modules reversed" 434 | 435 | # where the course will be downloaded to 436 | course_dir = path.abspath(path.join(dest_dir,cname)) 437 | 438 | # ensure the course dir exists 439 | if not path.exists(course_dir): 440 | os.makedirs(course_dir) 441 | 442 | print "* " + cname + " will be downloaded to " + course_dir 443 | 444 | # download the standard pages 445 | print " - Downloading lecture/syllabus pages" 446 | self.download(self.HOME_URL % cname,target_dir=course_dir,target_fname="index.html") 447 | self.download(course_url, target_dir=course_dir,target_fname="lectures.html") 448 | try: 449 | self.download_about(cname,course_dir) 450 | except Exception as e: 451 | print "Warning: failed to download about file",e 452 | 453 | 454 | # now download the actual content (video's, lecture notes, ...) 455 | for j, (weeklyTopic, weekClasses) in enumerate(weeklyTopics,start=1): 456 | 457 | 458 | if self.wk_filter and j not in self.wk_filter: 459 | print " - skipping %s (idx = %s), as it is not in the week filter" % (weeklyTopic,j) 460 | continue 461 | 462 | # add a numeric prefix to the week directory name to ensure chronological ordering 463 | wkdirname = str(j).zfill(2) + " - " + weeklyTopic 464 | 465 | # ensure the week dir exists 466 | wkdir = path.join(course_dir,wkdirname) 467 | if not path.exists(wkdir): 468 | os.makedirs(wkdir) 469 | 470 | print " - " + weeklyTopic 471 | self.html += "

%s

\n" % weeklyTopic 472 | 473 | for i, (className, classResources) in enumerate(weekClasses,start=1): 474 | 475 | # ensure chronological ordering 476 | clsdirname = str(i).zfill(2) + " - " + className 477 | 478 | # ensure the class dir exists 479 | clsdir = path.join(wkdir, clsdirname) 480 | 481 | if not path.exists(clsdir): 482 | os.makedirs(clsdir) 483 | 484 | print " - Downloading resources for " + className 485 | 486 | self.html += "
%s
\n" % className 487 | 488 | # download each resource 489 | for classResource,tfname in classResources: 490 | try: 491 | print ' - Downloading ', classResource, tfname 492 | self.download(classResource,target_dir=clsdir,target_fname=tfname, 493 | class_dir=path.join(wkdirname, clsdirname)) 494 | except Exception as e: 495 | print " - failed: ",classResource,e 496 | self.html += "
\n" 497 | 498 | try: 499 | file = open(path.join(course_dir, 'materials.html'), "w") 500 | file.write(self.HTML_TEMPLATE % self.html) 501 | file.close() 502 | except Exception as e: 503 | print " - Writing materials.html failed: ",e 504 | 505 | if gzip_courses: 506 | tar_file_name = cname + ".tar.gz" 507 | print "Compressing and storing as " + tar_file_name 508 | tar = tarfile.open(os.path.join(dest_dir, tar_file_name),'w:gz') 509 | tar.add(os.path.join(dest_dir, cname),arcname=cname) 510 | tar.close() 511 | print "Compression complete. Cleaning up." 512 | shutil.rmtree(os.path.join(dest_dir, cname)) 513 | 514 | 515 | 516 | def get_max_path_length(): 517 | ''' 518 | Gets the maximum path length supported by the operating system 519 | ''' 520 | if platform.system() == 'Windows': 521 | return MAX_PATH_LENGTH_WINDOWS 522 | else: 523 | return MAX_PATH_LENGTH_LINUX 524 | 525 | def get_netrc_creds(): 526 | """ 527 | Read username/password from the users' netrc file. Returns None if no 528 | coursera credentials can be found. 529 | """ 530 | # inspired by https://github.com/jplehmann/coursera 531 | 532 | if platform.system() == 'Windows': 533 | # where could the netrc file be hiding, try a number of places 534 | env_vars = ["HOME","HOMEDRIVE", "HOMEPATH","USERPROFILE","SYSTEMDRIVE"] 535 | env_dirs = [os.environ[e] for e in env_vars if os.environ.get(e,None)] 536 | 537 | # also try the root/cur dirs 538 | env_dirs += ["C:", ""] 539 | 540 | # possible filenames 541 | file_names = [".netrc", "_netrc"] 542 | 543 | # all possible paths 544 | paths = [path.join(dir,fn) for dir in env_dirs for fn in file_names] 545 | else: 546 | # on *nix just put None, and the correct default will be used 547 | paths = [None] 548 | 549 | # try the paths one by one and return the first one that works 550 | creds = None 551 | for p in paths: 552 | try: 553 | auths = netrc.netrc(p).authenticators('coursera-dl') 554 | creds = (auths[0], auths[2]) 555 | print "Credentials found in .netrc file" 556 | break 557 | except (IOError, TypeError, netrc.NetrcParseError) as e: 558 | pass 559 | 560 | return creds 561 | 562 | def normalize_string(str): 563 | return ''.join(x for x in str if x not in ' \t-_()"01234567890').lower() 564 | 565 | def find_renamed(filename, size): 566 | fpath, name = path.split(filename) 567 | name, ext = path.splitext(name) 568 | name = normalize_string(name) 569 | 570 | if not path.exists(fpath): 571 | return None, None 572 | 573 | files = os.listdir(fpath) 574 | if files: 575 | for f in files: 576 | fname, fext = path.splitext(f) 577 | fname = normalize_string(fname) 578 | if fname == name and fext == ext: 579 | fullname = os.path.join(fpath, f) 580 | if path.getsize(fullname) == size: 581 | return fullname, f 582 | 583 | return None, None 584 | 585 | def main(): 586 | # parse the commandline arguments 587 | parser = argparse.ArgumentParser(description='Download Coursera.org course videos/docs for offline use.') 588 | parser.add_argument("-u", dest='username', type=str, help='coursera username (.netrc used if omitted)') 589 | parser.add_argument("-p", dest='password', type=str, help='coursera password') 590 | parser.add_argument("-d", dest='dest_dir', type=str, default=".", help='destination directory where everything will be saved') 591 | parser.add_argument("-n", dest='ignorefiles', type=str, default="", help='comma-separated list of file extensions to skip, e.g., "ppt,srt,pdf"') 592 | parser.add_argument("-i", dest='includefiles', type=str, default="", help='comma-separated list of file extensions to download, e.g., "pdf,doc"') 593 | parser.add_argument("-l", dest='lang', type=str, help='language of subtitles') 594 | parser.add_argument("-q", dest='parser', type=str, default=CourseraDownloader.DEFAULT_PARSER, 595 | help="the html parser to use, see http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser") 596 | parser.add_argument("-x", dest='proxy', type=str, default=None, help="proxy to use, e.g., foo.bar.com:3125") 597 | parser.add_argument("--reverse-sections", dest='reverse', action="store_true", 598 | default=False, help="download and save the sections in reverse order") 599 | parser.add_argument('course_names', nargs="+", metavar='', 600 | type=str, help='one or more course names from the url (e.g., comnets-2012-001)') 601 | parser.add_argument("--gz", 602 | dest='gzip_courses',action="store_true",default=False,help='Tarball courses for archival storage (folders get deleted)') 603 | parser.add_argument("-mppl", dest='mppl', type=int, default=120, 604 | help='Maximum length of filenames/dirs in a path') 605 | parser.add_argument("-w", dest='wkfilter', type=str, default=None, 606 | help="Comma separted list of sequence/lesson/week numbers to download e.g., 1,3,8") 607 | args = parser.parse_args() 608 | 609 | # check the parser 610 | html_parser = args.parser 611 | if html_parser == "html.parser" and sys.version_info < (2,7,3): 612 | print " Warning: built-in 'html.parser' may cause problems on Python < 2.7.3" 613 | 614 | print "Coursera-dl v%s (%s)" % (_version.__version__,html_parser) 615 | 616 | # search for login credentials in .netrc file if username hasn't been provided in command-line args 617 | username, password = args.username, args.password 618 | if not username: 619 | creds = get_netrc_creds() 620 | if not creds: 621 | raise Exception("No username passed and no .netrc credentials found, unable to login") 622 | else: 623 | username, password = creds 624 | else: 625 | # prompt the user for his password if not specified 626 | if not password: 627 | password = getpass.getpass() 628 | 629 | mppl = args.mppl 630 | 631 | # instantiate the downloader class 632 | d = CourseraDownloader( 633 | username, 634 | password, 635 | proxy=args.proxy, 636 | parser=html_parser, 637 | ignorefiles=args.ignorefiles, 638 | includefiles=args.includefiles, 639 | max_path_part_len=mppl, 640 | gzip_courses=args.gzip_courses, 641 | wk_filter=args.wkfilter, 642 | lang=args.lang, 643 | ) 644 | 645 | # authenticate, only need to do this once but need a classaname to get hold 646 | # of the csrf token, so simply pass the first one 647 | print "Logging in as '%s'..." % username 648 | d.login(args.course_names[0]) 649 | 650 | # download the content 651 | for i,cn in enumerate(args.course_names,start=1): 652 | print 653 | print "Course %s of %s" % (i,len(args.course_names)) 654 | d.download_course(cn,dest_dir=args.dest_dir,reverse_sections=args.reverse,gzip_courses = args.gzip_courses) 655 | 656 | if __name__ == '__main__': 657 | main() 658 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------