[
  {
    "path": ".gitignore",
    "content": "*.swp\n"
  },
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {description}\n    Copyright (C) {year}  {fullname}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  {signature of Ty Coon}, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n\n"
  },
  {
    "path": "README.md",
    "content": "## Installation\n\nYou need Python 3, version 3.2 or higher, with the `html5lib` library installed. Pick up a copy [here](https://github.com/html5lib/html5lib-python).\n\nThis software is only known to work on Linux. It can probably be made to work in Windows too, but I haven't tried it. Patches welcome.\n\nNo installation is required, but make sure that `converter.py` and `crawler.py` are executable. (Or you can just run them by invoking `python3` explicitly.)\n\n## Basic usage: downloading all your answers\n\nTo view all your answers, go to the answers section of [Your Content](https://www.quora.com/content?content_types=answers) and scroll all the way down until there are no more answers to load.\n\nType the following into your browser's URL bar:\n\n    javascript:window.open().document.write(JSON.stringify(Array.prototype.map.call(document.querySelectorAll('.UserContentList .pagedlist_item'), function (e) { return [e.getElementsByTagName('a')[0].href, e.getElementsByClassName('metadata')[0].innerHTML] })))\n\n**Note:** You can copy and paste the code above, but your browser might automatically remove the `javascript:` prefix from the URL when you do so. If that happens, you'll have to type in the `javascript:` part yourself. Alternatively, you can just use the browser console to execute the javascript code.\n\n(You need popups enabled in order for this to work. If your popup blocker blocks the window, disable it and try again.)\n\nThis creates a popup window or new tab containing a list of your answers, in a format that looks something like this:\n\n`[[\"https://www.quora.com/Do-classical-mechanics-work-beyond-the-speed-of-light/answer/Brian-Bi\",\"Added Fri\"],[\"https://www.quora.com/Are-competitive-programmers-happy-when-working-as-software-engineers/answer/Brian-Bi\",\"Added Thu\"],[\"https://www.quora.com/How-did-Brian-Bi-not-know-it-was-Chinese-New-Year-today/answer/Brian-Bi\",\"Added Thu\"],[\"https://www.quora.com/How-many-hours-of-studies-did-Brian-Bi-put-in-per-day-in-order-to-prepare-for-the-IChO/answer/Brian-Bi\",\"Added Thu\"]`...\n\nCopy and paste the entire contents of the window or tab into a text editor and save it as a file, `answers.json`.\n\nGo back to your browser, type in the following URL, and press Enter:\n\n`javascript:window.open().document.write(new Date().valueOf() + '<br>' + new Date().getTimezoneOffset())`\n\n(The same caveats as before apply.)\n\nAgain a new window or tab should pop up, showing the date in a numeric format, with two lines. The first line shows the current timestamp in numeric format. The second shows the offset of your time zone from UTC in minutes. Take note of both of these numbers.\n\nSuppose you installed the scripts in `/home/brian/quora-backup`. You can run the crawler as follows:\n\n`/home/brian/quora-backup/crawler.py answers.json /home/brian/quora-answers --origin_timestamp=${TIMESTAMP} --origin_timezone=${OFFSET}`\n\nreplacing `${TIMESTAMP}` with the timestamp value previously obtained from the browser, and `${OFFSET}` with the time zone offset value.\n\nThis creates a new directory, `/home/brian/quora-answers`, and populates it with the answers specified, after downloading them from Quora. It also generates a timestamp in YYYY-MM-DD format for each answer.\n\n## Converting answers to a standalone format\n\nThe converter can be run as follows:\n\n`/home/brian/quora-backup/converter.py /home/brian/quora-answers /home/brian/quora-answers-cooked`\n\nThis creates the directory `/home/brian/quora-answers-cooked` and copies each answer downloaded into `/home/brian/quora-answers` into the new directory after processing it to remove everything other than the answer content itself. If this step succeeds, then the answer will still be readable even if Quora disappears from the face of the Web.\n\n## What the crawler does\n\nThe crawler is pretty simple: its job is to download the URLs you provide. But it also has a slightly nontrivial task, which is to determine the date on which each answer was written (give or take a day). This is done by reading the timestamps provided on the Your Content page itself. But the more recent timestamps given are relative, not absolute (for example, \"Fri\" if you wrote answer last Friday). That's why the crawler needs to be told at what time you accessed that page and in what time zone, so it can resolve those strings into absolute dates.\n\n## What the converter does\n\nThe converter has three main functions:\n\n1. It removes everything on the page other than the answer content. No bar at the top, no sidebar with related answers, no box indicating why the answer was collapsed (if it was); your name is not shown, nor are upvotes, the timestamp, view count, comments, or the upvote and downvote buttons. All that's left is answer content. This also reduces the size of the HTML considerably.\n2. It downloads a copy of each image embedded in your answer. These images are\nall hosted on Quora's servers; after running the converter, you'll have a copy on local disk, so you'll still be able to view the images even if Quora disappears. (This functionality can be disabled using the `-n` flag.)\n3. It removes extraneous HTML elements and attributes, simplifying the HTML as much as possible.\n\n## FAQ\n\n**Why did you write your own Quora backup tool when there are already a zillion of them?**\n\nBecause I believe this tool is unique in that it allows you to reliably and easily download ALL your answers, even if you have thousands of them, AND to ensure that they still display properly even if Quora completely disappears.\n\n**What if I only want to download some of my answers?**\n\nTo download only some of your answers, just remove all the entries from `answers.json` you don't want. If you also just want to download some recent answers, you don't have to scroll all the way down on the \"Your Content\" page. Yes, I realize this is really user-unfriendly. It would be nice to have a GUI. Patches welcome.\n\n**Won't Quora flag me for using a script to automatically download answers?**\n\nIt depends on how many answers you're downloading. If it's less than a thousand, you'll probably be fine, but I take no responsibility if something bad happens to you. If you have a LOT of answers, you might want to take advantage of the built-in rate limiting options. Both the crawler and converter support a `--delay` flag; for example, `--delay=1` tells the script to pause for a second after every download. Don't ask me what value to use here; I don't know. Use this software at your own risk.\n\n**Why is this licensed under the GPL? I noticed you usually prefer more permissive licenses.**\n\nBecause I want to make sure that all changes get merged back into my repository. There is a very good reason for this: there is only one Quora, and they'll probably change the way they generate HTML, which means this software will periodically stop working properly. I want to maintain a single version that's fully up to date with all the patches other people submit, rather than having multiple versions running around with patches for different kinds of elements.\n\n## Errors and bugs\nA message starting with [FATAL] signals that the script cannot function at all. [ERROR] means that processing of a single answer was aborted due to an unrecoverable error; [WARNING] means an error condition arose which prevented some feature from working properly but did not abort the processing of an answer. If you run with the `-v` flag, you'll also see [DEBUG] messages.\n\nThe converter will emit a [WARNING] message if it doesn't understand the HTML found in the answer. I have tested the converter against my entire set of answers, so I believe that as of the time of this release, this should never happen. But the format of Quora's HTML is likely to change in the future, which means the converter will stop working properly. If this happens, you're likely to see [WARNING] messages. Those should be reported.\n\nIf you want to report such a bug in the converter, try re-running with the \"-v\" flag, and include with your report everything between the closest \"Filename:\" lines before and after the [WARNING] message. (This doesn't mean other kinds of bugs shouldn't be reported; I am just giving instructions on how to report the most common kind of bug I expect.)\n"
  },
  {
    "path": "converter.py",
    "content": "#!/usr/bin/env python3\nimport argparse\nimport errno\nfrom html5lib import (HTMLParser, serializer, treebuilders, treewalkers)\nimport os\nimport re\nimport sys\nimport time\nimport urllib.error\nimport urllib.request\nfrom xml.dom.minidom import Node\n\ndef log_if_v(msg):\n    if args.verbose:\n        print('[DEBUG] %s' % msg, file=sys.stderr)\n\ndef get_title_node(document):\n    for node in document.getElementsByTagName('title'):\n        return node\n    return None\n\ndef get_text_content(node):\n    text = ''\n    for text_node in node.childNodes:\n        if text_node.nodeType == Node.TEXT_NODE:\n            text += text_node.data\n    return text\n\n# The HTML can mostly be saved as-is. The main changes we want to make are:\n# 1) Remove most <span>s and attributes since they are not needed anymore.\n# 2) Rewrite relative paths (\"/Brian-Bi\") to full URLs\n# 3) Download a copy of each embedded image\ndef cleanup_tree(doc, src, dest):\n    for child in src.childNodes:\n        if child.nodeType == Node.TEXT_NODE:\n            # Text nodes can simply be left as-is\n            dest.appendChild(child.cloneNode(False))\n            continue\n        if child.nodeType != Node.ELEMENT_NODE:\n            # ???\n            raise ValueError()\n        # Otherwise, it's an element node.\n        if child.tagName in ['br', 'hr']:\n            dest.appendChild(child.cloneNode(False))\n        elif child.tagName in ['b', 'i', 'u', 'h2', 'ol', 'ul', 'li', 'blockquote', 'wbr', 'p']:\n            # This node doesn't need to be modified but its children might.\n            # Also, we won't copy over any of its attributes.\n            new_node = doc.createElement(child.tagName)\n            cleanup_tree(doc, child, new_node)\n            dest.appendChild(new_node)\n        elif child.getAttribute('data-embed') != '':\n            # This is a video. We want to copy the data-embed value, which is HTML for an iframe node.\n            # So, we have to parse it into a separate document and import the node.\n            iframe_html = child.getAttribute('data-embed')\n            parser = HTMLParser(tree=treebuilders.getTreeBuilder('dom'))\n            iframe_doc = parser.parse(iframe_html)\n            try:\n                iframe = iframe_doc.documentElement.childNodes[1].firstChild\n                if iframe.tagName != 'iframe':\n                    raise ValueError()\n                new_node = doc.importNode(iframe, False)\n                # Quora uses a protocol-relative URL (//youtube.com/...) so let's make sure we rewrite this.\n                src = new_node.getAttribute('src')\n                if src.startswith('//'):\n                    new_node.setAttribute('src', 'http:' + src)\n                # The video will look really bad if we don't explicitly set the dimensions.\n                new_node.setAttribute('width', '525')\n                new_node.setAttribute('height', '295')\n                dest.appendChild(new_node)\n            except Exception:\n                print('[WARNING] Failed to parse video embed code', file=sys.stderr)\n                # Bail out by just copying the original HTML\n                dest.appendChild(child.cloneNode(True))\n        elif child.tagName == 'code':\n            # Inline code block. Strip the attributes.\n            new_node = doc.createElement('code')\n            dest.appendChild(new_node)\n            cleanup_tree(doc, child, new_node)\n        elif 'ContentFooter' in child.getAttribute('class') or 'hidden' in child.getAttribute('class'):\n            # These are nodes we just want to skip.\n            continue\n        elif child.tagName in ['span', 'div']:\n            # don't insert a span or div; just insert its contents\n            cleanup_tree(doc, child, dest)\n        elif child.tagName == 'a':\n            # A link. We only want to copy the href, and pass the rest through.\n            new_node = doc.createElement('a')\n            href = child.getAttribute('href')\n            if href.startswith('/'):\n                href = 'http://quora.com' + href\n            new_node.setAttribute('href', href)\n            dest.appendChild(new_node)\n            cleanup_tree(doc, child, new_node)\n        elif child.tagName == 'img':\n            src = child.getAttribute('master_src')\n            if src == '':\n                src = child.getAttribute('src')\n            new_node = doc.createElement('img')\n            new_node.setAttribute('src', src)\n            new_node.setAttribute('alt', child.getAttribute('alt'))\n            if args.no_download:\n                dest.appendChild(new_node)\n                continue\n            # Save a copy of the image locally.\n            # If an error occurs, just leave the src pointing to Quora.\n            try:\n                m = re.search('/([^/?]+)(\\?|$)', src)\n                if m is None:\n                    raise ValueError()\n                filename = m.group(1)\n                if not filename.endswith('.png'):\n                    filename += '.png'\n                try:\n                    img_fd = os.open(args.output_dir + '/' + filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)\n                except OSError as error:\n                    if error.errno == errno.EEXIST:\n                        log_if_v('Image %s has already been saved; skipping' % filename)\n                        new_node.setAttribute('src', filename)\n                        continue\n                    else:\n                        raise\n                log_if_v('Downloading image from %s' % src)\n                closed = False\n                try:\n                    img = urllib.request.urlopen(src).read()\n                    time.sleep(args.delay)\n                    os.write(img_fd, img)\n                    os.close(img_fd)\n                    closed = True\n                except Exception:\n                    os.close(img_fd)\n                    closed = True\n                    try:\n                        os.remove(args.output_dir + '/' + filename)\n                    except:\n                        print('[WARNING] Failed to remove incomplete file %s' % filename, file=sys.stderr)\n                    raise\n                finally:\n                    if not closed:\n                        os.close(img_fd)\n                    # Don't leave the file there; we will retry it next time.\n                # If everything went according to plan, rewrite the src to the local file.\n                new_node.setAttribute('src', filename)\n            except urllib.error.URLError as error:\n                print('[WARNING] Failed to download image from URL %s (%s)' % (src, error.reason), file=sys.stderr)\n            except OSError as error:\n                print('[WARNING] Failed to save image from URL %s to file %s (%s)' % (src, filename, error.strerror), file=sys.stderr)\n            except ValueError:\n                print('[WARNING] Failed to determine image name from URL %s' % src, file=sys.stderr)\n            finally:\n                dest.appendChild(new_node)\n        elif child.tagName == 'pre':\n            # Block (not inline) code. Quora's HTML already has the desired <pre><code> structure,\n            # so we just need to strip the attributes from the <pre>.\n            new_node = doc.createElement('pre')\n            dest.appendChild(new_node)\n            cleanup_tree(doc, child, new_node)\n        else:\n            print('[WARNING] Unrecognized node', file=sys.stderr)\n            # Bail out by just copying the original HTML\n            dest.appendChild(child.cloneNode(True))\n\nparser = argparse.ArgumentParser(description = 'Convert answers downloaded from Quora into a more portable HTML format')\nparser.add_argument('input_dir', nargs='?', default='./quora-answers', help='directory containing \"raw\" answers downloaded from Quora')\nparser.add_argument('output_dir', nargs='?', default='./quora-answers-cooked', help='where to store the images and converted answers')\nparser.add_argument('-d', '--delay', default=0, type=float, help='Time to sleep between downloads, in seconds')\nparser.add_argument('-n', '--no_download', action='store_true', help='Do not save images')\nparser.add_argument('-v', '--verbose', action='store_true', help='be verbose')\n\nglobal args\nargs = parser.parse_args()\n\n# Get a list of answers to convert...\nfilenames = list(filter(lambda f: f.endswith('.html'), os.listdir(args.input_dir)))\nfilenames.sort()\nif len(filenames) == 0:\n    sys.exit('[FATAL] No .html files found in directory %s', args.input_dir)\nprint('Found %d answers' % len(filenames), file=sys.stderr)\n\nlog_if_v('Creating directory %s' % args.output_dir)\ntry:\n    os.mkdir(args.output_dir, 0o700)\nexcept OSError as error:\n    if error.errno == errno.EEXIST:\n        log_if_v('Directory already exists')\n    else:\n        # This is the top level, and we have nothing else to do if we failed\n        raise\n\nfor filename in filenames:\n    sys.stderr.flush()\n    print('Filename: ' + filename, file=sys.stderr)\n    try:\n        with open(args.input_dir + '/' + filename, 'rb') as page:\n            page_html = page.read()\n    except IOError as error:\n        print('[ERROR] Failed to read %s (%s)' % (filename, error.strerror))\n        continue\n\n    # Get the HTML element containing just the answer itself.\n    # Also get the title.\n    parser = HTMLParser(tree=treebuilders.getTreeBuilder('dom'))\n    document = parser.parse(page_html, default_encoding='utf-8')\n    title_node = get_title_node(document) \n    log_if_v('Title: ' + ('(could not be determined)' if title_node is None else get_text_content(title_node)))\n\n    answer_node = None\n    for node in document.getElementsByTagName('div'):\n        if 'ExpandedAnswer' in node.getAttribute('class').split():\n            answer_node = node\n            break\n    if answer_node is None:\n        print('[WARNING] Failed to locate answer on page (filename: %s)' % filename, file=sys.stderr)\n        continue\n\n    # Construct our new page...\n    new_page = document.createElement('html')\n    head_node = document.createElement('head')\n    if not title_node is None:\n        head_node.appendChild(title_node)\n    meta_node = document.createElement('meta')\n    meta_node.setAttribute('charset', 'utf-8')\n    head_node.appendChild(meta_node)\n    css = (\"blockquote { border-left: 2px solid #ddd; color: #666; margin: 0; padding-left: 16px; } \"\n           \"code, pre { background: #f4f4f4; } \"\n           \"pre, h2 { margin: 0; } \"\n           \"ul { margin: 0 0 0 16px; padding: 8px 0; } \"\n           \"ol { margin: 0 0 0 28px; padding: 8px 0; } \"\n           \"li { margin: 0 0 8px; } \")\n    style_node = document.createElement('style')\n    style_node.setAttribute('type', 'text/css')\n    style_node.appendChild(document.createTextNode(css))\n    head_node.appendChild(style_node)\n    # Quora now uses MathJax, so set up the configuration object:\n    script_node = document.createElement('script')\n    script_text = document.createTextNode('window.MathJax = {\"showMathMenu\":false,\"messageStyle\":\"none\",\"errorSettings\":{\"style\":{\"color\":\"#000000\",\"font-style\":\"normal\"}},\"HTML-CSS\":{\"linebreaks\":{\"automatic\":true,\"width\":\"container\"},\"EqnChunk\":150,\"EqnChunkDelay\":20},\"tex2jax\":{\"inlineMath\":[[\"[math]\",\"[/math]\"]],\"displayMath\":[],\"ignoreClass\":\"edit_latex|qtext_editor_content|ignore_latex\",\"processClass\":\"render_latex\",\"processEnvironments\":false,\"preview\":\"none\"},\"TeX\":{\"noUndefined\":{\"attributes\":{\"mathcolor\":\"red\"}},\"noErrors\":{\"multiLine\":true,\"style\":{\"max-width\":\"100%\",\"overflow\":\"hidden\"}},\"Macros\":{\"C\":\"{\\\\mathbb{C}}\",\"N\":\"{\\\\mathbb{N}}\",\"O\":\"{\\\\emptyset}\",\"Q\":\"{\\\\mathbb{Q}}\",\"R\":\"{\\\\mathbb{R}}\",\"Z\":\"{\\\\mathbb{Z}}\"}},\"fast-preview\":{\"disabled\":true},\"Safe\":{\"allow\":{\"URLs\":\"none\",\"classes\":\"none\",\"cssIDs\":\"none\",\"styles\":\"none\",\"fontsize\":\"none\",\"require\":\"none\"}}};')\n    script_node.appendChild(script_text)\n    head_node.appendChild(script_node)\n    # and then load MathJax:\n    script_node = document.createElement('script')\n    script_node.setAttribute('type', 'text/javascript')\n    script_node.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML,Safe')\n    head_node.appendChild(script_node)\n    new_page.appendChild(head_node)\n    body_node = document.createElement('body')\n    # This step processes Quora's HTML into a more lightweight and portable form.\n    cleanup_tree(document, answer_node, body_node)\n    new_page.appendChild(body_node)\n    # Okay! Finally, save the HTML.\n    walker = treewalkers.getTreeWalker('dom')(new_page)\n    try:\n        with open(args.output_dir + '/' + filename, 'wb', 0o600) as saved_page:\n            saved_page.write(b'<!DOCTYPE html>')\n            saved_page.write(serializer.serialize(new_page, 'dom', 'utf-8', omit_optional_tags=False))\n    except IOError as error:\n        print('[ERROR] Failed to save to file %s (%s)' % (filename, error.strerror), file=sys.stderr)\n\nprint('Done', file=sys.stderr)\n\n"
  },
  {
    "path": "crawler.py",
    "content": "#!/usr/bin/env python3\nimport argparse\nimport errno\nimport json\nimport os\nimport re\nimport sys\nimport time\nimport urllib.error\nimport urllib.request\n\ndef log_if_v(msg):\n    if args.verbose:\n        print('[DEBUG] %s' % msg, file=sys.stderr)\n\n# Given origin (timestamp offset by time zone) and string from Quora, e.g.\n# \"Added 31 Jan\", returns a string such as '2015-01-31'.\n# Quora's short date strings don't provide enough information to determine the\n# exact time, unless it was within the last day, so we won't bother to be any\n# more precise.\ndef parse_quora_date(origin, quora_str):\n    days_of_week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n    months_of_year = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n    _, _, date_str = quora_str.partition('Added ')\n    date_str = date_str.strip()\n    if date_str == '':\n        raise ValueError('\"%s\" does not appear to indicate when answer was added' % quora_str)\n    m0 = re.match('just now$', date_str)\n    m1 = re.match('(\\d+)m ago$', date_str)\n    m2 = re.match('(\\d+)h ago$', date_str)\n    m3 = re.match('(' + '|'.join(days_of_week) + ')$', date_str)\n    m4 = re.match('(' + '|'.join(months_of_year) + ') (\\d+)$', date_str)\n    m5 = re.match('(' + '|'.join(months_of_year) + ') (\\d+), (\\d+)$', date_str)\n    m6 = re.match('(\\d+)[ap]m$', date_str)\n    if not m0 is None or not m6 is None:\n        # Using origin for time in am / pm since the time of the day will be discarded anyway\n        tm = time.gmtime(origin)\n    elif not m1 is None:\n        tm = time.gmtime(origin - 60*int(m1.group(1)))\n    elif not m2 is None:\n        tm = time.gmtime(origin - 3600*int(m2.group(1)))\n    elif not m3 is None:\n        # Walk backward until we reach the given day of the week\n        day_of_week = days_of_week.index(m3.group(1))\n        offset = 1\n        while offset <= 7:\n            tm = time.gmtime(origin - 86400*offset)\n            if tm.tm_wday == day_of_week:\n                break\n            offset += 1\n        else:\n            raise ValueError('date \"%s\" is invalid' % date_str)\n    elif not m4 is None:\n        # Walk backward until we reach the given month and year\n        month_of_year = months_of_year.index(m4.group(1)) + 1\n        day_of_month = int(m4.group(2))\n        offset = 1\n        while offset <= 366:\n            tm = time.gmtime(origin - 86400*offset)\n            if tm.tm_mon == month_of_year and tm.tm_mday == day_of_month:\n                break\n            offset += 1\n        else:\n            raise ValueError('date \"%s\" is invalid' % date_str)\n    elif not m5 is None:\n        # may raise ValueError\n        tm = time.strptime(date_str, '%b %d, %Y')\n    else:\n        raise ValueError('date \"%s\" could not be interpreted' % date_str)\n    return '%d-%02d-%02d' % (tm.tm_year, tm.tm_mon, tm.tm_mday)\n\nparser = argparse.ArgumentParser(description = 'Download a set of answers from Quora')\nparser.add_argument('input_file', help='file containing JSON-encoded list of timestamped URLs to download')\nparser.add_argument('output_dir', nargs='?', default='./quora-answers', help='where to store the downloaded answers and images')\nparser.add_argument('-d', '--delay', default=0, type=float, help='Time to sleep between answers, in seconds')\nparser.add_argument('-t', '--origin_timestamp', default=None, type=int, help='JS time when the list of URLs was fetched')\nparser.add_argument('-z', '--origin_timezone', default=None, type=int, help='browser timezone')\nparser.add_argument('-v', '--verbose', action='store_true', help='enable debug messages')\nparser.add_argument('-o', '--overwrite', action='store_true', help='Overwrite existing answers')\n\nglobal args\nargs = parser.parse_args()\n\n# Determine the origin for relative date computation\nif args.origin_timestamp is None:\n    log_if_v('Using current time')\n    args.origin_timestamp = time.time()\nelse:\n    args.origin_timestamp //= 1000\nif args.origin_timezone is None:\n    log_if_v('Using system time zone')\n    args.origin_timezone = time.timezone\nelse:\n    args.origin_timezone *= 60\norigin = args.origin_timestamp - args.origin_timezone\n\n# Load the list of answer URLs from the input file.\nlog_if_v('Loading input file %s' % args.input_file)\nwith open(args.input_file, 'rb') as input_file:\n    answers = json.load(input_file)\nprint('Found %d answers' % len(answers), file=sys.stderr)\n\n# Check the validity of the input\nif type(answers) != list:\n    sys.exit('[FATAL] Incorrect input format')\nfor e in answers:\n    if type(e) != list or len(e) != 2 or type(e[0]) != str or type(e[1]) != str:\n        sys.exit('[FATAL] Incorrect input format')\n\nlog_if_v('Creating directory %s' % args.output_dir)\ntry:\n    os.mkdir(args.output_dir, 0o700)\nexcept OSError as error:\n    if error.errno == errno.EEXIST:\n        log_if_v('Directory already exists')\n    else:\n        # This is the top level, and we have nothing else to do if we failed\n        raise\nos.chdir(args.output_dir)\ndownload_file_count = 0\nfor e in answers:\n    sys.stderr.flush()\n    url = e[0]\n    print('URL: %s' % url, file=sys.stderr)\n\n    # Determine the date when this answer was written\n    try:\n        added_time = parse_quora_date(origin, e[1])\n    except ValueError as error:\n        print('[WARNING] Failed to parse date: %s' % str(error), file=sys.stderr)\n        added_time = 'xxxx-xx-xx'\n    print('Date: %s' % added_time, file=sys.stderr)\n\n    # Get the part of the URL indicating the question title; we will save under this name\n    m1 = re.search('quora\\.com/([^/]+)/answer', url)\n    # if there's a context topic\n    m2 = re.search('quora\\.com/[^/]+/([^/]+)/answer', url)\n    filename = added_time + ' '\n    if not m1 is None:\n        filename += m1.group(1)\n    elif not m2 is None:\n        filename += m2.group(1)\n    else:\n        print('[ERROR] Could not find question part of URL %s; skipping' % url, file=sys.stderr)\n        continue\n    # Trim the filename if it's too long. 255 bytes is the limit on many filesystems.\n    total_byte_length = len(bytes(filename + '.html', encoding=\"utf-8\"))\n    filename_bytes = bytes(filename, encoding=\"utf-8\")\n    if total_byte_length > 255:\n        filename_bytes = filename_bytes[:255-total_byte_length]\n        well_formed = False\n        while not well_formed:\n            try:\n                filename = str(filename_bytes, encoding=\"utf-8\")\n                well_formed = True\n            except UnicodeDecodeError:\n                filename_bytes = filename_bytes[:-1]\n        log_if_v('Filename was truncated to at most 255 bytes.')\n    filename += '.html'\n    log_if_v('Filename: %s' % filename)\n\n    # If overwrite is enabled or the answer doesn't exist\n    if args.overwrite or not os.path.isfile(filename):\n        # Fetch the URL to find the answer\n        log_if_v('Downloading answer from URL %s' % url)\n        try:\n            page_html = urllib.request.urlopen(url).read()\n            with open(filename, 'wb') as f:\n                f.write(page_html)\n        except urllib.error.URLError as error:\n            print('[ERROR] Failed to download answer from URL %s (%s)' % (url, error.reason), file=sys.stderr)\n            continue\n        except IOError as error:\n            print('[ERROR] Failed to save answer to file %s (%s)' % (filename, error.strerror), file=sys.stderr)\n\n        download_file_count += 1\n        time.sleep(args.delay)\n    else:\n        log_if_v('Answer File : %s Already Exists. Skipping' % filename)\n\nprint('Done. Downloaded %d files' % download_file_count, file=sys.stderr)\n"
  }
]