[
  {
    "path": ".gitignore",
    "content": "\n\n\n# Created by https://www.gitignore.io/api/code,macos,python,django,visualstudiocode\n# Edit at https://www.gitignore.io/?templates=code,macos,python,django,visualstudiocode\n\n### Code ###\n.vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json\n\n### Django ###\n*.log\n*.pot\n*.pyc\n__pycache__/\nlocal_settings.py\ndb.sqlite3\nmedia\n\n# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/\n# in your Git repository. Update and uncomment the following line accordingly.\n# <django-project-name>/staticfiles/\n\n### Django.Python Stack ###\n# Byte-compiled / optimized / DLL files\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n\n# Django stuff:\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n### macOS ###\n# General\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Icon must end with two \\r\nIcon\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n.com.apple.timemachine.donotpresent\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n### Python ###\n# Byte-compiled / optimized / DLL files\n\n# C extensions\n\n# Distribution / packaging\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n\n# Installer logs\n\n# Unit test / coverage reports\n\n# Translations\n\n# Django stuff:\n\n# Flask stuff:\n\n# Scrapy stuff:\n\n# Sphinx documentation\n\n# PyBuilder\n\n# Jupyter Notebook\n\n# IPython\n\n# pyenv\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n\n# celery beat schedule file\n\n# SageMath parsed files\n\n# Environments\n\n# Spyder project settings\n\n# Rope project settings\n\n# mkdocs documentation\n\n# mypy\n\n# Pyre type checker\n\n### VisualStudioCode ###\n\n### VisualStudioCode Patch ###\n# Ignore all local history of files\n.history\n\n# End of https://www.gitignore.io/api/code,macos,python,django,visualstudiocode"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\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 GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\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\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions 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 convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\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\nstate 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    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 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 Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "\n# pythonic-news\nA Hacker News lookalike written in Python/Django, powering [https://news.python.sc](https://news.python.sc)\n\n\n\n[![screenshot](http://cdn.sebastiansteins.com/screenshot-news-python-sc.png \"Screenshot\")](https://news.python.sc)\n\n\n## Setup for local development\n\n### Set up virtual environment\n```shell script\npython -m venv venv/\nsource venv/bin/activate\n```\n\n### Install Dependencies\n```shell script\npip install -r requirements.txt\n```\n\n### Migrate Database\n```shell script\npython manage.py migrate\n```\n\n### Extra setup work\n* Set ```DEBUG=True``` if necessary\n* Add ```127.0.0.1``` to ```ALLOWED_HOSTS```\n\n### Run Django Server\n```shell script\npython manage.py runserver\n```\nNow you can access the website at ```127.0.0.1:8000```.\n"
  },
  {
    "path": "accounts/__init__.py",
    "content": "default_app_config = 'accounts.apps.AccountsConfig'\n"
  },
  {
    "path": "accounts/admin.py",
    "content": "from django.contrib import admin\n\n# Register your models here.\n"
  },
  {
    "path": "accounts/apps.py",
    "content": "from django.apps import AppConfig\n\n\nclass AccountsConfig(AppConfig):\n    name = 'accounts'\n\n    def ready(self):\n        from . import receivers"
  },
  {
    "path": "accounts/forms.py",
    "content": "from django import forms\n\nfrom .models import CustomUser, Invitation\n\nclass ProfileForm(forms.ModelForm):\n    class Meta:\n        model = CustomUser\n        fields = ['about', 'email']\n    \n    def clean_email(self):\n        data = self.cleaned_data['email']\n        if data:\n            data = data.lower()\n        return data\n\n\nclass RegisterForm(forms.ModelForm):\n    MIN_LENGTH = 8\n    class Meta:\n        model = CustomUser\n        fields = ['username', 'password', 'email']\n        widgets = {\n            'password': forms.PasswordInput(),\n        }\n\n    def clean_password(self):\n        password = self.cleaned_data.get('password')\n        if len(password) < self.MIN_LENGTH:\n            raise forms.ValidationError(\"Your password must be at least %d characters long.\" % self.MIN_LENGTH)\n        return password\n\nclass CreateInviteForm(forms.ModelForm):\n    class Meta:\n        model = Invitation\n        fields = ['invited_email_address']\n    \n    def clean_invited_email_address(self):\n        invited_email_address = self.cleaned_data['invited_email_address']\n        if invited_email_address:\n            invited_email_address = invited_email_address.lower()\n        return invited_email_address\n\n\nclass PasswordForgottenForm(forms.Form):\n    username = forms.CharField()\n\nclass PasswortResetForm(forms.Form):\n    password = forms.CharField()"
  },
  {
    "path": "accounts/migrations/0001_initial.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-07 12:14\n\nimport django.contrib.auth.models\nimport django.contrib.auth.validators\nfrom django.db import migrations, models\nimport django.utils.timezone\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n    initial = True\n\n    dependencies = [\n        ('auth', '0011_update_proxy_permissions'),\n    ]\n\n    operations = [\n        migrations.CreateModel(\n            name='CustomUser',\n            fields=[\n                ('password', models.CharField(max_length=128, verbose_name='password')),\n                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),\n                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),\n                ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),\n                ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),\n                ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),\n                ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),\n                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),\n                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),\n                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),\n                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n                ('karma', models.IntegerField(default=1)),\n                ('about', models.TextField(default='')),\n                ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),\n                ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),\n            ],\n            options={\n                'verbose_name': 'user',\n                'verbose_name_plural': 'users',\n                'abstract': False,\n            },\n            managers=[\n                ('objects', django.contrib.auth.models.UserManager()),\n            ],\n        ),\n    ]\n"
  },
  {
    "path": "accounts/migrations/0002_auto_20190914_1247.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-14 12:47\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('accounts', '0001_initial'),\n    ]\n\n    operations = [\n        migrations.AlterField(\n            model_name='customuser',\n            name='karma',\n            field=models.IntegerField(default=0),\n        ),\n        migrations.CreateModel(\n            name='EmailVerification',\n            fields=[\n                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n                ('created_at', models.DateTimeField(auto_now_add=True)),\n                ('changed_at', models.DateTimeField(auto_now=True)),\n                ('verified', models.BooleanField(default=False)),\n                ('verified_at', models.DateTimeField(null=True)),\n                ('email', models.EmailField(max_length=254)),\n                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n            ],\n        ),\n    ]\n"
  },
  {
    "path": "accounts/migrations/0003_auto_20190914_2031.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-14 20:31\n\nfrom django.conf import settings\nimport django.contrib.auth.models\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.manager\nimport mptt.fields\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('accounts', '0002_auto_20190914_1247'),\n    ]\n\n    operations = [\n        migrations.AlterModelManagers(\n            name='customuser',\n            managers=[\n                ('_tree_manager', django.db.models.manager.Manager()),\n                ('objects', django.contrib.auth.models.UserManager()),\n            ],\n        ),\n        migrations.AddField(\n            model_name='customuser',\n            name='level',\n            field=models.PositiveIntegerField(default=1, editable=False),\n            preserve_default=False,\n        ),\n        migrations.AddField(\n            model_name='customuser',\n            name='lft',\n            field=models.PositiveIntegerField(default=1, editable=False),\n            preserve_default=False,\n        ),\n        migrations.AddField(\n            model_name='customuser',\n            name='parent',\n            field=mptt.fields.TreeForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='invitees', to=settings.AUTH_USER_MODEL),\n        ),\n        migrations.AddField(\n            model_name='customuser',\n            name='rght',\n            field=models.PositiveIntegerField(default=2, editable=False),\n            preserve_default=False,\n        ),\n        migrations.AddField(\n            model_name='customuser',\n            name='tree_id',\n            field=models.PositiveIntegerField(db_index=True, default=1, editable=False),\n            preserve_default=False,\n        ),\n    ]\n"
  },
  {
    "path": "accounts/migrations/0004_auto_20190915_1105.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-15 11:05\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('accounts', '0003_auto_20190914_2031'),\n    ]\n\n    operations = [\n        migrations.CreateModel(\n            name='Invitation',\n            fields=[\n                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n                ('created_at', models.DateTimeField(auto_now_add=True)),\n                ('changed_at', models.DateTimeField(auto_now=True)),\n                ('num_signups', models.PositiveIntegerField(default=1, null=True)),\n                ('invited_email_address', models.EmailField(default=None, max_length=254, null=True)),\n                ('invite_code', models.UUIDField(default=uuid.uuid4, editable=False)),\n                ('inviting_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n            ],\n        ),\n        migrations.AddField(\n            model_name='customuser',\n            name='used_invitation',\n            field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='accounts.Invitation'),\n        ),\n    ]\n"
  },
  {
    "path": "accounts/migrations/0005_emailverification_verification_code.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-15 13:16\n\nfrom django.db import migrations, models\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('accounts', '0004_auto_20190915_1105'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='emailverification',\n            name='verification_code',\n            field=models.UUIDField(default=uuid.uuid4, editable=False),\n        ),\n    ]\n"
  },
  {
    "path": "accounts/migrations/0006_auto_20190915_1321.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-15 13:21\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('accounts', '0005_emailverification_verification_code'),\n    ]\n\n    operations = [\n        migrations.AlterModelOptions(\n            name='customuser',\n            options={},\n        ),\n        migrations.AlterModelManagers(\n            name='customuser',\n            managers=[\n            ],\n        ),\n    ]\n"
  },
  {
    "path": "accounts/migrations/0007_auto_20190923_1323.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-23 13:23\n\nfrom django.conf import settings\nimport django.contrib.auth.models\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('accounts', '0006_auto_20190915_1321'),\n    ]\n\n    operations = [\n        migrations.AlterModelOptions(\n            name='customuser',\n            options={'default_manager_name': 'objects'},\n        ),\n        migrations.AlterModelManagers(\n            name='customuser',\n            managers=[\n                ('objects', django.contrib.auth.models.UserManager()),\n            ],\n        ),\n        migrations.CreateModel(\n            name='PasswordResetRequest',\n            fields=[\n                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n                ('created_at', models.DateTimeField(auto_now_add=True)),\n                ('changed_at', models.DateTimeField(auto_now=True)),\n                ('verification_code', models.UUIDField(default=uuid.uuid4, editable=False)),\n                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n            ],\n        ),\n    ]\n"
  },
  {
    "path": "accounts/migrations/__init__.py",
    "content": ""
  },
  {
    "path": "accounts/models.py",
    "content": "import uuid\n\nfrom django.contrib.auth.models import AbstractUser\nfrom django.urls import reverse\n\nfrom django.db import models\n\nfrom django.utils import timezone\nimport datetime\n\nimport  hashlib\nfrom urllib.parse import urlencode\n\nfrom mptt.models import MPTTModel, TreeForeignKey\n\n\n#class CustomUser(MPTTModel, AbstractUser):\nclass CustomUser(AbstractUser, MPTTModel):\n    class Meta:\n        default_manager_name = 'objects'\n    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n    karma = models.IntegerField(default=0)\n    about = models.TextField(default='')\n    # api_key = models.CharField(max_length=100)\n\n    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='invitees', editable=False)\n\n    used_invitation = models.ForeignKey('Invitation', null=True, default=None, on_delete=models.CASCADE)\n\n    def get_absolute_url(self):\n        return reverse(\"accounts_profile\", kwargs={\"username\": self.username})\n\n    @property\n    def is_green(self):\n        return timezone.now() - self.date_joined < datetime.timedelta(days=30)\n\n    def gravatar_url(self, size=80):\n        if self.email:\n            default = \"https://www.example.com/default.jpg\"\n            url = \"https://www.gravatar.com/avatar/\" + hashlib.md5(self.email.lower()).hexdigest() + \"?\"\n            url += urlencode({'d':default, 's':str(size)})\n            return url\n\n    @property\n    def latest_verified_email(self):\n        verifications = EmailVerification.objects.filter(user=self, verified=True).order_by('-verified_at')\n        if verifications.count():\n            return verifications[0].email\n\n\n\nclass Invitation(models.Model):\n    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n    created_at = models.DateTimeField(auto_now_add=True)\n    changed_at = models.DateTimeField(auto_now=True)\n\n    inviting_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)\n    num_signups = models.PositiveIntegerField(null=True, default=1)\n    invited_email_address = models.EmailField(null=True, default=None)\n\n    invite_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)\n\n    def get_absolute_url(self):\n        return reverse(\"accounts_invite\", kwargs={\"pk\": self.pk})\n    \n    def get_register_url(self):\n        return reverse(\"accounts_register\") + '?invite=' + str(self.invite_code)\n\n    @property\n    def active(self):\n        return True\n        pass # TODO\n\n\nclass EmailVerification(models.Model):\n    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n    created_at = models.DateTimeField(auto_now_add=True)\n    changed_at = models.DateTimeField(auto_now=True)\n    verified = models.BooleanField(default=False)\n    verified_at = models.DateTimeField(null=True)\n\n    email = models.EmailField()\n    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)\n\n    verification_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)\n\n    def get_verify_url(self):\n        return reverse(\"accounts_verify\", kwargs={\"verification_code\": self.verification_code})\n\n\nclass PasswordResetRequest(models.Model):\n    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n    created_at = models.DateTimeField(auto_now_add=True)\n    changed_at = models.DateTimeField(auto_now=True)\n\n    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)\n    verification_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)\n\n\n    def get_verify_url(self):\n        return reverse(\"password_forgotten\", kwargs={\"verification_code\": self.verification_code})\n"
  },
  {
    "path": "accounts/receivers.py",
    "content": "#from django.core.signals import request_finished\nfrom django.db.models.signals import pre_save, post_save, post_delete\nfrom django.dispatch import receiver\nfrom django.core.mail import send_mail\nfrom django.core.mail import EmailMultiAlternatives\n\nfrom django.conf import settings\n\n\n\nfrom .models import CustomUser, Invitation, EmailVerification, PasswordResetRequest\n\n\n@receiver(pre_save)\ndef lower_email_addresses(sender, instance, **kwargs):\n    if isinstance(instance, CustomUser):\n        email = getattr(instance, 'email', None)\n        if email:\n            instance.email = email.lower()\n\n\n@receiver(post_save)\ndef send_invitation_email(sender, instance, created, **kwargs):\n    if created and isinstance(instance, Invitation):\n        subject, from_email, to = 'You have been invited to %s'%(settings.SITE_DOMAIN), 'bot@python.sc', instance.invited_email_address\n        text_content = \"\"\"\nYou have been invited to news.python.sc.\n\nWould you like to accept {inviting_user}'s invite?\n\nPlease sign up here: https://news.python.sc{url}\n\n-- \nnews.python.sc - A social news aggregator for the Python community.\n\n\"\"\".format(inviting_user=instance.inviting_user.username, url=instance.get_register_url())\n        #html_content = '<p>This is an <strong>important</strong> message.</p>'\n        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])\n        #msg.attach_alternative(html_content, \"text/html\")\n        msg.send()\n\n\n@receiver(post_save)\ndef create_verification(sender, instance, created, **kwargs):\n    if isinstance(instance, CustomUser):\n        if instance.email:\n            verifications = EmailVerification.objects.filter(user=instance, email=instance.email)\n            if not verifications.count():\n                create_v = True\n            else:\n                verified = any([i.verified for i in verifications])\n                # create_v = not verified\n                create_v = False\n            \n            if create_v:\n                verification = EmailVerification(user=instance, email=instance.email)\n                verification.save()\n\n\n@receiver(post_save)\ndef send_verification_email(sender, instance, created, **kwargs):\n    if created and isinstance(instance, EmailVerification):\n        subject, from_email, to = 'Please confirm your account on news.python.sc', 'bot@python.sc', instance.email\n        text_content = \"\"\"\nPlease confirm your email address here:\n\nhttps://news.python.sc{url}\n\n-- \nnews.python.sc - A social news aggregator for the Python community.\n\n\"\"\".format(url=instance.get_verify_url())\n        #html_content = '<p>This is an <strong>important</strong> message.</p>'\n        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])\n        #msg.attach_alternative(html_content, \"text/html\")\n        msg.send()\n\n\n@receiver(post_save)\ndef send_password_reset_email(sender, instance, created, **kwargs):\n    if created and isinstance(instance, PasswordResetRequest):\n        subject, from_email, to = 'Reset password for your account on news.python.sc', 'bot@python.sc', instance.email\n        text_content = \"\"\"\nPlease confirm your email address here:\n\nhttps://news.python.sc{url}\n\n-- \nnews.python.sc - A social news aggregator for the Python community.\n\n\"\"\".format(url=instance.get_verify_url())\n        #html_content = '<p>This is an <strong>important</strong> message.</p>'\n        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])\n        #msg.attach_alternative(html_content, \"text/html\")\n        msg.send()"
  },
  {
    "path": "accounts/templates/accounts/__base.html",
    "content": "{% extends 'news/__base.html' %}"
  },
  {
    "path": "accounts/templates/accounts/create_invite.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n\n<form method=\"POST\" action=\"{% url 'accounts_create_invite' %}\">{% csrf_token %}\n{{form}}\n<button type=\"submit\">invite</button>\n</form>\n\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/invite.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n\n\nYou have created an invite for {{invitation.invited_email_address}}.\n<a href=\"{% url 'accounts_create_invite' %}\">Create anotther?</a>\n\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/login.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n{% if user.is_authenticated %}\nSigned in.\n{% else %}\n<h2>Login</h2>\n<form method=\"post\">\n  {% csrf_token %}\n  {{ form.as_p }}\n  <button type=\"submit\">Login</button>\n</form>\n<a href=\"{% url 'password_forgotten' %}\">password forgotten?</a>\n{% endif %}\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/logout.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n\n<h2>Logout</h2>\n<form method=\"post\">\n  {% csrf_token %}\n  <button type=\"submit\">logout</button>\n</form>\n\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/my_profile.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<article class=\"site-content-dense\">\n<form method=\"POST\">{% csrf_token %}\n<table>\n{{form.as_table}}\n</table>\n<button type=\"submit\">update</button>\n</form>\n\n{% if user.email and not verified %}\n<hr />\n<form method=\"POST\" action=\"{% url 'accounts_resend_verification' %}\">{% csrf_token %}\n<button type=\"submit\">Resend verification email</button>\n</form>\n{% endif %}\n\n\n<hr />\n\n<a href=\"{% url 'password_change' %}\">change password</a> <br>\n<a href=\"{% url 'newest' %}?submitted_by={{user}}\">submissions</a> <br>\n<a href=\"{% url 'comments' %}?submitted_by={{user}}\">comments</a> <br>\n{% comment %} <a href=\"#\">hidden</a> <br>\n<a href=\"#\">flagged</a> <br> {% endcomment %}\n<a href=\"{% url 'newest' %}?upvoted_by={{user}}\">upvoted submissions</a> / <a href=\"{% url 'comments' %}?upvoted_by={{user}}\">upvoted comments</a> <br>\n{% comment %} <a href=\"#\">favourite submissions</a> / <a href=\"#\">favourite comments</a> <br> {% endcomment %}\n\n</article>\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/password_change_done.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\nPassword changed successfully.\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/password_change_form.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<h2>Change Password</h2>\n<form method=\"post\">\n  {% csrf_token %}\n  {{ form.as_p }}\n  <button type=\"submit\">chnage password</button>\n</form>\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/password_forgotten_form.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<h2>Password forgotten?</h2>\n<form method=\"post\">\n  {% csrf_token %}\n  {{ form.as_p }}\n  <button type=\"submit\">reset password</button>\n</form>\n\n\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/profile.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<article class=\"site-content-dense\">\n<table>\n<tbody>\n    <tr>\n        <th>user:</th>\n        <td>{{profile}}</td>\n    </tr>\n    <tr>\n        <th>created:</th>\n        <td>{{profile.date_joined}}</td>\n    </tr>\n    <tr>\n        <th>karma:</th>\n        <td>{{profile.karma}}</td>\n    </tr>\n    <tr>\n        <th>about:</th>\n        <td>{{profile.about}}</td>\n    </tr>\n</tbody></table>\n\n\n<a href=\"{% url 'newest' %}?submitted_by={{profile}}\">submissions</a> <br>\n<a href=\"{% url 'comments' %}?submitted_by={{profile}}\">comments</a> <br>\n</article>\n\n\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/register.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<article class=\"site-content-dense\">\n<h2>Create Account</h2>\n<p>While you don't need to supply an email address, it is strongly recommended to do so. Without an email address, we won't be able to restore your account \nif you've lost your password.</p>\n<form method=\"post\">\n  {% csrf_token %}\n  <table>\n  {{ form.as_table }}\n  </table>\n  <br>\n  <p class=\"smaller\">By signing up, you agree to the <a href=\"{% url 'zen' %}\">Zen of {{SITE_NAME}}</a>.</p>\n  <button type=\"submit\">create account</button>\n</form>\n</article>\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/register_closed.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\nClosed.\n\n<p>\nYou want an invite? Please leave your email address here: <a href=\"https://forms.gle/2D1UQ6YSa26WWSPDA\">Request an invite</a>\n</p>\n\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/resend_verification.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\nA new email has been sent.\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/user_tree.html",
    "content": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n{% load mptt_tags %}\n\n<ul class=\"root\">\n    {% recursetree users %}\n        <li>\n            {{ node.username }}\n            {% if not node.is_leaf_node %}\n                <ul class=\"children\">\n                    {{ invitees }}\n                </ul>\n            {% endif %}\n        </li>\n    {% endrecursetree %}\n</ul>\n\n\n{% endblock content %}"
  },
  {
    "path": "accounts/tests.py",
    "content": "from django.contrib.auth.models import AnonymousUser\nfrom accounts.models import CustomUser\nfrom django.test import RequestFactory, TestCase\n\nfrom .views import *\nfrom .models import *\n\nclass BasicAccountsTest(TestCase):\n    \"\"\"Tests the basic functionality of the accounts app.\"\"\"\n    def setUp(self):\n        # Every test needs access to the request factory.\n        self.factory = RequestFactory()\n        self.user = CustomUser.objects.create_user(\n            username='sebst', email='hi@seb.st', password='top_secret')\n        self.other_user = CustomUser.objects.create_user(\n            username='bla1', email='two@seb.st', password='top_secret')\n\n\nclass ReceiversAccountsTest(TestCase):\n    \"\"\"Tests the basic functionality of the accounts app.\"\"\"\n    def setUp(self):\n        # Every test needs access to the request factory.\n        self.factory = RequestFactory()\n        self.user = CustomUser.objects.create_user(\n            username='sebst', email='hi@seb.st', password='top_secret')\n        self.other_user = CustomUser.objects.create_user(\n            username='bla1', email='two@seb.st', password='top_secret')\n\n\n    def test_lower_email_addresses(self):\n        user = CustomUser.objects.create_user(\n            username='johndoe', email='J.Doe@exAmple.org', password='top_secret')\n        user = CustomUser.objects.get(pk=user.pk)\n        self.assertEqual(user.email, 'j.doe@example.org')\n\n\n    def test_send_invitation_email(self):\n        self.skipTest()\n        self.assertTrue(False)\n\n\n    def test_create_verification(self):\n        user = CustomUser.objects.create_user(\n            username='johndoe', email='J.Doe@exAmple.org', password='top_secret')\n        verification = EmailVerification.objects.get(user=user, email=user.email)\n        self.assertEqual(verification.email, user.email)\n        self.assertEqual(verification.email, 'j.doe@example.org')\n\n\n\n    def test_send_verification_email(self):\n        self.skipTest()\n        self.assertTrue(False)\n\n\n    def test_send_password_reset_email(self):\n        self.skipTest()\n        self.assertTrue(False)\n"
  },
  {
    "path": "accounts/urls.py",
    "content": "from django.urls import path, include\n\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\n\n\nurlpatterns = [\n    path('profile', views.profile, name=\"accounts_my_profile\"),\n    path('profile/<str:username>', views.profile, name=\"accounts_profile\"),\n\n    path('user-tree', views.user_tree, name=\"accounts_user_tree\"),\n\n    path('create-invite', views.create_invite, name=\"accounts_create_invite\"),\n    path('invite/<uuid:pk>', views.invite, name=\"accounts_invite\"),\n\n    path('verify/<uuid:verification_code>', views.verify, name=\"accounts_verify\"),\n    path('resend-verification', views.resend_verification, name=\"accounts_resend_verification\"),\n\n    path('register', views.register, name=\"accounts_register\"),\n    \n    # path('accounts/', include('django.contrib.auth.urls')), # new\n    path('accounts/login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name=\"login\"),\n    #path('accounts/logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name=\"logout\"),\n    path('accounts/logout/', views.logout, name=\"logout\"),\n    path('accounts/password-change/', auth_views.PasswordChangeView.as_view(template_name='accounts/password_change_form.html'), name=\"password_change\"),\n    path('accounts/password-change-done/', auth_views.PasswordChangeDoneView.as_view(template_name='accounts/password_change_done.html'), name=\"password_change_done\"),\n\n    path('accounts/password-forgotten/', views.password_forgotten, name=\"password_forgotten\"),\n    path('accounts/password-forgotten/<str:verification_code>', views.password_forgotten, name=\"password_forgotten\"),\n\n\n]\n"
  },
  {
    "path": "accounts/views.py",
    "content": "from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth import logout as do_logout\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom django.utils import timezone\n\n\nfrom .models import CustomUser, Invitation, EmailVerification\nfrom .forms import ProfileForm, RegisterForm, CreateInviteForm, PasswordForgottenForm, PasswortResetForm\n\n\ndef profile(request, username=None):\n    if username is None:\n        return my_profile(request)\n    profile = get_object_or_404(CustomUser, username=username)\n    if profile == request.user:\n        return my_profile(request)\n    return render(request, 'accounts/profile.html', {'profile': profile})\n\n\n@login_required\ndef my_profile(request):\n    instance = request.user\n    form = ProfileForm(request.POST or None, instance=instance)\n    if request.user.email:\n        verifications = EmailVerification.objects.filter(user=request.user, email=request.user.email)\n        verified = any([i.verified for i in verifications])\n    else:\n        verified = False\n    if request.method == 'POST':\n        if form.is_valid():\n            instance = form.save()\n            return HttpResponseRedirect(instance.get_absolute_url())\n    return render(request, 'accounts/my_profile.html', {'form': form, 'verified': verified})\n\n\n@login_required\ndef create_invite(request):\n    instance = Invitation(inviting_user = request.user)\n    form = CreateInviteForm(request.POST or None, instance=instance)\n    if request.method==\"POST\":\n        if form.is_valid():\n            instance = form.save()\n            return HttpResponseRedirect(instance.get_absolute_url())\n    return render(request, 'accounts/create_invite.html', {'form': form})\n\n\n@login_required\ndef invite(request, pk):\n    invitation = get_object_or_404(Invitation, pk=pk)\n    return render(request, 'accounts/invite.html', {'invitation': invitation})\n\n\ndef register(request):\n    invite_code = request.GET.get('invite')\n    try:\n        invitation = Invitation.objects.get(invite_code=invite_code)\n    except:\n        invitation = None\n    instance = CustomUser(used_invitation=invitation, \n                          parent=getattr(invitation, 'inviting_user', None), \n                          email=getattr(invitation, 'invited_email_address', None))\n    if not settings.ACCEPT_UNINVITED_REGISTRATIONS and (invitation is None or not getattr(invitation, 'active', False)):\n        return render(request, 'accounts/register_closed.html')\n    form = RegisterForm(request.POST or None, instance=instance)\n    if request.method == 'POST':\n        if form.is_valid():\n            instance = form.save()\n            instance.set_password(form.cleaned_data['password'])\n            instance.is_active = True\n            instance.save()\n            login(request, instance)\n            return HttpResponseRedirect(instance.get_absolute_url())\n    return render(request, 'accounts/register.html', {'form': form})\n\n\ndef verify(request, verification_code):\n    verification = get_object_or_404(EmailVerification, verification_code=verification_code)\n    assert verification.user.email == verification.email\n    verification.verified = True\n    verification.verified_at = timezone.now()\n    verification.save()\n    return render(request, 'accounts/verify.html')\n\n@login_required\ndef resend_verification(request):\n    if request.method==\"POST\":\n        assert request.user.email\n        verification = EmailVerification(user=request.user, email=request.user.email)\n        verification.save()\n        return render(request, 'accounts/resend_verification.html')\n\n\ndef user_tree(request):\n    users = CustomUser.objects.all()\n    return render(request, 'accounts/user_tree.html', {'users': users})\n\n\ndef password_forgotten(request, verification_code=None):\n    assert not request.user.is_authenticated\n    error = None\n    if verification_code is None:\n        if 'sent' in request.GET.keys():\n            return render(request, 'accounts/password_forgotten_sent.html', {})\n        form = PasswordForgottenForm(request.POST or None)\n        if form.is_valid():\n            user = None\n            try:\n                username = form.cleaned_data['username']\n                user = CustomUser.objects.get_by_natural_key(username)\n            except:\n                pass\n            if user:\n                if user.email == user.latest_verified_email:\n                    reset_request = PasswordResetRequest(user=user)\n                    reset_request.save()\n                    return HttpResponseRedirect(reverse('password_forgotten')+'?sent')\n                else:\n                    error = 'This user does not have a verified email. Please contact support.'\n            else:\n                error = 'User not found.'\n        return render(request, 'accounts/password_forgotten_form.html', {'form': form, 'error': error})\n    else:\n        reset_request = get_object_or_404(PasswordResetRequest, verification_code=verification_code)\n        form = PasswortResetForm(request.POST or None)\n        if request.method==\"POST\":\n            if form.is_valid():\n                reset_request.user.set_password(form.cleaned_data['password']) # TODO: confirm password, password rules\n                reset_request.user.save()\n                return HttpResponseRedirect(reverse('/login'))\n        return render(request, 'accounts/password_forgotten_form.html', {'form': form})\n\n\n@login_required\ndef logout(request):\n    if request.method==\"POST\":\n        do_logout(request)\n        redirect_url = settings.LOGOUT_REDIRECT_URL or '/'\n        return HttpResponseRedirect(redirect_url)\n    else:\n        return render(request, 'accounts/logout.html')\n\n"
  },
  {
    "path": "emaildigest/__init__.py",
    "content": "default_app_config = 'emaildigest.apps.EmaildigestConfig'\n"
  },
  {
    "path": "emaildigest/admin.py",
    "content": "from django.contrib import admin\n\n# Register your models here.\n"
  },
  {
    "path": "emaildigest/apps.py",
    "content": "from django.apps import AppConfig\n\n\nclass EmaildigestConfig(AppConfig):\n    name = 'emaildigest'\n\n    def ready(self):\n        from . import receivers"
  },
  {
    "path": "emaildigest/forms.py",
    "content": "from django import forms\n\nfrom .models import UserSubscription, AnonymousSubscription, Subscription\n\n\nclass UserSubscriptionForm(forms.ModelForm):\n    thankyou = 'u'\n    class Meta:\n        model = UserSubscription\n        fields = []\n\n\nclass AnonymousSubscriptionForm(forms.ModelForm):\n    thankyou = 'a'\n    class Meta:\n        model = AnonymousSubscription\n        fields = ['email']\n    \n    def clean_email(self):\n        data = self.cleaned_data['email']\n        if data:\n            data = data.lower()\n        return data\n\n\ndef validate_active_email(email):\n    qs = Subscription.objects.filter(verfied_email=email, is_active=True)\n    if not qs.count():\n        raise forms.ValidationError(\n            ('No subscription found for email %(email)s'),\n            code='invalid',\n            params={'email': email},)\n\nclass UnsunscribeForm(forms.Form):\n    email = forms.EmailField(validators=[validate_active_email])\n\n    def clean_email(self):\n        data = self.cleaned_data['email']\n        if data:\n            data = data.lower()\n        return data\n\n\ndef get_subscription_form(user, *args, **kwargs):\n    return AnonymousSubscriptionForm(*args, **kwargs)\n    if user.is_authenticated:\n        return UserSubscriptionForm(*args, **kwargs)\n    else:\n        return AnonymousSubscriptionForm(*args, **kwargs)"
  },
  {
    "path": "emaildigest/mailing.py",
    "content": "from django.conf import settings\nfrom .models import Subscription, EmailDigest\n\ndef create_and_send_digest(frequency):\n    pass\n    # Get list of objects\n    stories = [] # TODO: Find from _font_page\n    # make templates and trigger sending\n    subscriptions = Subscription.objects.filter(is_active=True, frequency=frequency)\n    for subscription in subscriptions:\n        tpl = 'TODO: Here is your list' # TODO\n        subject = settings.SITE_NAME + \" \" + frequency + \" Digest\"\n        send_mail(subscription, tpl, subject)\n\ndef send_mail(subscription, template, subject):\n    pass"
  },
  {
    "path": "emaildigest/migrations/0001_initial.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-23 13:23\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n    initial = True\n\n    dependencies = [\n        ('news', '0008_story_duplicate_of'),\n        migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n    ]\n\n    operations = [\n        migrations.CreateModel(\n            name='Subscription',\n            fields=[\n                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n                ('created_at', models.DateTimeField(auto_now_add=True)),\n                ('changed_at', models.DateTimeField(auto_now=True)),\n            ],\n        ),\n        migrations.CreateModel(\n            name='AnonymousSubscription',\n            fields=[\n                ('subscription_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='emaildigest.Subscription')),\n                ('email', models.EmailField(blank=True, max_length=254, null=True)),\n                ('verified', models.BooleanField(default=False)),\n                ('verified_at', models.DateTimeField(null=True)),\n                ('verification_code', models.UUIDField(default=uuid.uuid4, editable=False)),\n            ],\n            bases=('emaildigest.subscription',),\n        ),\n        migrations.CreateModel(\n            name='EmailDigest',\n            fields=[\n                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n                ('created_at', models.DateTimeField(auto_now_add=True)),\n                ('changed_at', models.DateTimeField(auto_now=True)),\n                ('frequency', models.CharField(choices=[('weekly', 'weekly'), ('daily', 'daily')], max_length=16)),\n                ('weekly_weekday', models.CharField(blank=True, choices=[('Sun', 'Sun'), ('Mon', 'Mon'), ('Tue', 'Tue'), ('Wed', 'Wed'), ('Thu', 'Thu'), ('Fri', 'Fri'), ('Sat', 'Sat')], max_length=16, null=True)),\n                ('stories', models.ManyToManyField(to='news.Story')),\n            ],\n        ),\n        migrations.CreateModel(\n            name='UserSubscription',\n            fields=[\n                ('subscription_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='emaildigest.Subscription')),\n                ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n            ],\n            bases=('emaildigest.subscription',),\n        ),\n    ]\n"
  },
  {
    "path": "emaildigest/migrations/0002_auto_20190923_2028.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-23 20:28\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('emaildigest', '0001_initial'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='subscription',\n            name='frequency',\n            field=models.CharField(choices=[('weekly', 'weekly'), ('daily', 'daily')], default='daily', max_length=16),\n            preserve_default=False,\n        ),\n        migrations.AddField(\n            model_name='subscription',\n            name='weekly_weekday',\n            field=models.CharField(blank=True, choices=[('Sun', 'Sun'), ('Mon', 'Mon'), ('Tue', 'Tue'), ('Wed', 'Wed'), ('Thu', 'Thu'), ('Fri', 'Fri'), ('Sat', 'Sat')], max_length=16, null=True),\n        ),\n    ]\n"
  },
  {
    "path": "emaildigest/migrations/0003_auto_20190923_2120.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-23 21:20\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n        ('emaildigest', '0002_auto_20190923_2028'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='anonymoussubscription',\n            name='logged_in_user',\n            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),\n        ),\n        migrations.AddField(\n            model_name='subscription',\n            name='verfied_email',\n            field=models.EmailField(blank=True, max_length=254, null=True),\n        ),\n    ]\n"
  },
  {
    "path": "emaildigest/migrations/0004_auto_20190926_2118.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-26 21:18\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('emaildigest', '0003_auto_20190923_2120'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='subscription',\n            name='is_active',\n            field=models.BooleanField(default=False),\n        ),\n        migrations.CreateModel(\n            name='UnSubscription',\n            fields=[\n                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n                ('created_at', models.DateTimeField(auto_now_add=True)),\n                ('changed_at', models.DateTimeField(auto_now=True)),\n                ('from_digest', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='emaildigest.EmailDigest')),\n                ('subscription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='emaildigest.Subscription')),\n            ],\n        ),\n    ]\n"
  },
  {
    "path": "emaildigest/migrations/__init__.py",
    "content": ""
  },
  {
    "path": "emaildigest/models.py",
    "content": "import uuid\nfrom django.db import models\n\nclass EmailDigest(models.Model):\n    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n    created_at = models.DateTimeField(auto_now_add=True)\n    changed_at = models.DateTimeField(auto_now=True)\n\n    frequency = models.CharField(max_length=16, choices=(('weekly', 'weekly'), ('daily', 'daily')))\n    weekly_weekday = models.CharField(max_length=16, null=True, blank=True, choices=(('Sun', 'Sun'), \n                                                                                     ('Mon', 'Mon'),\n                                                                                     ('Tue', 'Tue'),\n                                                                                     ('Wed', 'Wed'),\n                                                                                     ('Thu', 'Thu'),\n                                                                                     ('Fri', 'Fri'),\n                                                                                     ('Sat', 'Sat')))\n    stories = models.ManyToManyField('news.Story')\n\nclass Subscription(models.Model):\n    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n    created_at = models.DateTimeField(auto_now_add=True)\n    changed_at = models.DateTimeField(auto_now=True)\n    frequency = models.CharField(max_length=16, choices=(('weekly', 'weekly'), ('daily', 'daily')))\n    weekly_weekday = models.CharField(max_length=16, null=True, blank=True, choices=(('Sun', 'Sun'), \n                                                                                     ('Mon', 'Mon'),\n                                                                                     ('Tue', 'Tue'),\n                                                                                     ('Wed', 'Wed'),\n                                                                                     ('Thu', 'Thu'),\n                                                                                     ('Fri', 'Fri'),\n                                                                                     ('Sat', 'Sat')))\n    verfied_email = models.EmailField(null=True, blank=True)\n    is_active = models.BooleanField(default=False)\n\n\nclass UserSubscription(Subscription):\n    user = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE, null=True)\n\n\nclass AnonymousSubscription(Subscription):\n    email = models.EmailField(null=True, blank=True)\n    verified = models.BooleanField(default=False)\n    verified_at = models.DateTimeField(null=True)\n    verification_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)\n    logged_in_user = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE, null=True)\n\n\nclass UnSubscription(models.Model):\n    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n    created_at = models.DateTimeField(auto_now_add=True)\n    changed_at = models.DateTimeField(auto_now=True)\n    subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE)\n    from_digest = models.ForeignKey(EmailDigest, on_delete=models.CASCADE, null=True)"
  },
  {
    "path": "emaildigest/receivers.py",
    "content": "#from django.core.signals import request_finished\nfrom django.db.models.signals import pre_save, post_save, post_delete\nfrom django.dispatch import receiver\nfrom django.core.mail import send_mail\nfrom django.core.mail import EmailMultiAlternatives\n\n\n\nfrom .models import UserSubscription, AnonymousSubscription, Subscription, UnSubscription\n\n\n@receiver(pre_save)\ndef lower_email_addresses(sender, instance, **kwargs):\n    if isinstance(instance, (UserSubscription, AnonymousSubscription)):\n        if isinstance(instance, AnonymousSubscription):\n            instance.email = instance.email.lower()\n    if isinstance(instance, Subscription):\n        if instance.verfied_email:\n            instance.verfied_email = instance.verfied_email.lower()\n\n\n@receiver(post_save)\ndef activate_subscription_on_verification(sender, instance, created, **kwargs):\n    if isinstance(instance, AnonymousSubscription):\n        if instance.verified:\n            subscription = instance.subscription_ptr\n            subscription.is_active = True\n            subscription.verfied_email = instance.email\n            subscription.save()\n\n@receiver(post_save)\ndef on_subscription_created(sender, instance, created, **kwargs):\n    if created and isinstance(instance, (UserSubscription, AnonymousSubscription)):\n        subscription = instance\n\n\n@receiver(post_save)\ndef on_unsubscription_created(sender, instance, created, **kwargs):\n    if created and isinstance(instance, (UnSubscription)):\n        unsubscription = instance\n        unsubscription.subscription.is_active = False\n        unsubscription.subscription.save()"
  },
  {
    "path": "emaildigest/templates/emaildigest/__base.html",
    "content": "{% extends 'news/__base.html' %}"
  },
  {
    "path": "emaildigest/templates/emaildigest/_subscription_form_tag.html",
    "content": "{% if False and subscription_form %}\n<p>Don't miss interesting Python stories by subscribing to our digest</p>\n\n    <form class=\"subscription-form\" method=\"POST\" action=\"{% url 'emaildigest_subscribe' %}\">\n        {% csrf_token %}\n        {{subscription_form}}\n        <button type=\"submit\">Get Python stories to your inbox</button>\n    </form>\n{% endif %}"
  },
  {
    "path": "emaildigest/templates/emaildigest/my_subscriptions.html",
    "content": "{% extends 'emaildigest/__base.html' %}\n\n{% block content %}\n\n    <article class=\"site-content\">\n        my_subscriptions.html\n    </article>\n\n\n{% endblock content %}"
  },
  {
    "path": "emaildigest/templates/emaildigest/subscribe.html",
    "content": ""
  },
  {
    "path": "emaildigest/templates/emaildigest/subscribe_thankyou_a.html",
    "content": "{% extends 'emaildigest/__base.html' %}\n\n{% block content %}\n\n    <article class=\"site-content\">\n        Thank you!<br>\n        You will receive a confirmation email soon\n    </article>\n\n\n{% endblock content %}"
  },
  {
    "path": "emaildigest/templates/emaildigest/subscribe_thankyou_u.html",
    "content": "{% extends 'emaildigest/__base.html' %}\n\n{% block content %}\n\n    <article class=\"site-content\">\n        Thank you!<br>\n        You are now subscribed.\n    </article>\n\n\n{% endblock content %}"
  },
  {
    "path": "emaildigest/templates/emaildigest/subscribe_verification_done.html",
    "content": "{% extends 'emaildigest/__base.html' %}\n\n{% block content %}\n\n    <article class=\"site-content\">\n        Thank you!<br>\n        You are now subscribed.\n    </article>\n\n\n{% endblock content %}"
  },
  {
    "path": "emaildigest/templates/emaildigest/unsubscribe.html",
    "content": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n\n\n\n{% block content %}\n\n\n\n\n<article class=\"site-content\">\n    \n        <form method=\"POST\">{% csrf_token %}\n        {{form}}\n        <button type=\"submit\">unsubscribe</button>\n        </form>\n\n</article>\n\n\n\n\n\n\n{% endblock content %}"
  },
  {
    "path": "emaildigest/templates/emaildigest/unsubscribe_confirm.html",
    "content": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n\n\n\n{% block content %}\n\n\n\n\n<article class=\"site-content\">\n    \n        <form method=\"POST\">{% csrf_token %}\n        Do yo really want to unsubscribe?<br>\n        <button type=\"submit\">Yes, unsubscribe</button>\n        </form>\n    \n\n</article>\n\n\n\n\n\n\n{% endblock content %}"
  },
  {
    "path": "emaildigest/templates/emaildigest/unsubscribe_done.html",
    "content": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n\n\n\n{% block content %}\n\n\n\n\n<article class=\"site-content\">\n\n        You are unsubscribed.\n\n</article>\n\n\n\n\n\n\n{% endblock content %}"
  },
  {
    "path": "emaildigest/templatetags/__init__.py",
    "content": ""
  },
  {
    "path": "emaildigest/templatetags/emaildigest_extra.py",
    "content": "from django import template\n\nregister = template.Library()\n\nfrom emaildigest.forms import get_subscription_form\n\n@register.inclusion_tag('emaildigest/_subscription_form_tag.html')\ndef digest_subscription_form(user, **kwargs):\n    form = get_subscription_form(user)\n    return {'subscription_form': form}\n"
  },
  {
    "path": "emaildigest/tests.py",
    "content": "from django.contrib.auth.models import AnonymousUser\nfrom accounts.models import CustomUser\nfrom django.test import RequestFactory, TestCase\n\nfrom .views import *\nfrom .models import *\nfrom .forms import *\n\nclass BasicEmailDigestTest(TestCase):\n    \"\"\"Tests the basic functionality of the emaildigest app.\"\"\"\n    def setUp(self):\n        # Every test needs access to the request factory.\n        self.factory = RequestFactory()\n        self.user = CustomUser.objects.create_user(\n            username='sebst', email='hi@seb.st', password='top_secret')\n        self.other_user = CustomUser.objects.create_user(\n            username='bla1', email='two@seb.st', password='top_secret')\n\n    def _subscribe(self, i=0):\n        self.assertEqual(Subscription.objects.all().count(), 0+i)\n\n        request = self.factory.post('/digest/subscribe', {'email': 'test@example.org'})\n        request.user = self.user\n        response = subscribe(request)\n\n        #self.assertContains(response.url, 'thankyou')\n        self.assertRegex(response.url, r'.*thankyou.*')\n\n        self.assertEqual(Subscription.objects.all().count(), 1+i)\n\n        subscription = Subscription.objects.all().order_by('-created_at')[0]\n        self.assertFalse(subscription.is_active)\n\n        verification_code = subscription.anonymoussubscription.verification_code\n\n        return subscription\n\n    def _confirm(self, subscription):\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        self.assertFalse(subscription.anonymoussubscription.verified)\n        self.assertFalse(subscription.is_active)\n        verification_code = subscription.anonymoussubscription.verification_code\n\n        url = '/digest/subscribe?v=' + str(verification_code)\n\n        request = self.factory.get(url)\n        request.user = self.user\n        response = subscribe(request)\n\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        anonymoussubscription = AnonymousSubscription.objects.get(pk=subscription.pk)\n        self.assertTrue(anonymoussubscription.verified)\n\n\n    def _unsubscribe_via_mail(self, subscription, assert_form_error=False):\n        subscription = Subscription.objects.get(pk=subscription.pk)\n\n        self.assertEqual(UnSubscription.objects.all().count(), 0)\n\n        url = '/digest/unsubscribe'\n        request = self.factory.post(url, {'email': subscription.anonymoussubscription.email})\n        request.user = self.user\n        response = unsubscribe(request)\n        if assert_form_error:\n            # self.assertFormError(response, UnsunscribeForm, 'email', 'No subscription found for email ' + subscription.anonymoussubscription.email)\n            self.assertContains(response, 'No subscription found for email')\n            return None\n        self.assertEqual(response.status_code, 302)\n        self.assertRegex(response.url, r'.*done.*')\n\n        self.assertEqual(UnSubscription.objects.all().count(), 1)\n\n        unsubscription = UnSubscription.objects.get()\n        return unsubscription\n\n\n    def test_subscribe(self):\n        subscription = self._subscribe()\n        self.assertFalse(subscription.is_active)\n\n\n    def test_subscribe_confirm(self):\n        subscription = self._subscribe()\n        self._confirm(subscription)\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        self.assertTrue(subscription.is_active)\n\n\n    def test_subscribe_unsubscribe(self):\n        subscription = self._subscribe()\n        unsubscription = self._unsubscribe_via_mail(subscription, assert_form_error=True)\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        self.assertFalse(subscription.is_active)\n\n\n    def test_subscribe_confirm_unsubscribe(self):\n        subscription = self._subscribe()\n        self._confirm(subscription)\n        unsubscription = self._unsubscribe_via_mail(subscription)\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        self.assertFalse(subscription.is_active)\n\n\n    def test_subscribe_unsubscribe_confirm(self):\n        subscription = self._subscribe()\n        unsubscription = self._unsubscribe_via_mail(subscription, assert_form_error=True)\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        self.assertFalse(subscription.is_active)\n\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        self.assertFalse(subscription.is_active)\n\n        self._confirm(subscription)\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        self.assertTrue(subscription.is_active)\n\n\n    def test_subscribe_confirm_unsubscribe_subscribe(self):\n        subscription = self._subscribe()\n        self._confirm(subscription)\n        unsubscription = self._unsubscribe_via_mail(subscription)\n\n        subscription2 = self._subscribe(i=1)\n        subscription2 = Subscription.objects.get(pk=subscription2.pk)\n        self.assertFalse(subscription.is_active)\n\n\n\n    def test_subscribe_confirm_unsubscribe_subscribe_confirm(self):\n        subscription = self._subscribe()\n        self._confirm(subscription)\n        \n        unsubscription = self._unsubscribe_via_mail(subscription)\n\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        self.assertFalse(subscription.is_active)\n\n        re_subscription = self._subscribe(i=1)\n        self._confirm(re_subscription)\n\n        re_subscription = Subscription.objects.get(pk=re_subscription.pk)\n        subscription = Subscription.objects.get(pk=subscription.pk)\n        self.assertTrue(re_subscription.is_active)\n        self.assertFalse(subscription.is_active)\n\n\n\n# class ReceiversEmailDigestTest(TestCase):\n#     \"\"\"Tests the basic receivers functionality of the emaildigest app.\"\"\"\n#     def setUp(self):\n#         # Every test needs access to the request factory.\n#         self.factory = RequestFactory()\n#         self.user = CustomUser.objects.create_user(\n#             username='sebst', email='hi@seb.st', password='top_secret')\n#         self.other_user = CustomUser.objects.create_user(\n#             username='bla1', email='two@seb.st', password='top_secret')\n\n\n#     def test_lower_email_addresses(self):\n#         self.fail()\n\n#     def activate_subscription_on_verification(self):\n#         self.fail()\n\n#     def test_on_subscription_created(self):\n#         self.fail()\n\n#     def test_on_unsubscription_created(self):\n#         self.fail()"
  },
  {
    "path": "emaildigest/urls.py",
    "content": "from django.urls import path, include\n\nfrom . import views\n\n\n\n\nurlpatterns = [\n    #path('profile', views.profile, name=\"accounts_my_profile\"),\n    path('subscribe', views.subscribe, name=\"emaildigest_subscribe\"),\n    path('subscriptions', views.my_subscriptions, name=\"emaildigest_subscriptions\"),\n\n    path('unsubscribe', views.unsubscribe, name='emaildigest_unsubscribe'),\n    path('unsubscribe/<uuid:subscription_id>/<uuid:digest_id>', views.unsubscribe, name='emaildigest_unsubscribe'),\n\n]\n"
  },
  {
    "path": "emaildigest/views.py",
    "content": "from django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.utils import timezone\n\nfrom .forms import get_subscription_form, UnsunscribeForm\n\nfrom .models import AnonymousSubscription, UnSubscription, Subscription, EmailDigest\n\n\ndef subscribe(request):\n    form = get_subscription_form(request.user, request.POST or None)\n    thankyou = request.GET.get('thankyou', None)\n    if thankyou:\n        return render(request, 'emaildigest/subscribe_thankyou_%s.html'%(thankyou), {'prevent_footer_subscription_form': True})\n    verification_code = request.GET.get('v', None)\n    if verification_code:\n        subscription = get_object_or_404(AnonymousSubscription, verification_code=verification_code)\n        if not subscription.verified:\n            subscription.verified = True\n            subscription.verified_at = timezone.now()\n            subscription.save()\n        # TODO: Verify User account if needed # TODO: Activate usage of get_subsciption_form\n        return render(request, 'emaildigest/subscribe_verification_done.html', {'prevent_footer_subscription_form': True})\n    if request.method==\"POST\":\n        if form.is_valid():\n            subscription = form.save()\n            if request.user.is_authenticated:\n                subscription.logged_in_user = request.user\n                subscription.save()\n            return HttpResponseRedirect(reverse('emaildigest_subscribe') + '?thankyou=' + form.thankyou)\n    return render(request, 'emaildigest/subscribe.html', {'subscription_form': form, 'prevent_footer_subscription_form': True})\n\n\ndef unsubscribe(request, subscription_id=None, digest_id=None):\n    if 'done' in request.GET.keys():\n        email = request.GET.get('email', None)\n        suscription = request.GET.get('subscription', None)\n        return render(request, 'emaildigest/unsubscribe_done.html', {'email': email, 'subscription': subscription, 'prevent_footer_subscription_form': True})\n    if subscription_id is None and digest_id is None:\n        form = UnsunscribeForm(request.POST or None)\n        if request.method==\"POST\":\n            if form.is_valid():\n                email = form.cleaned_data['email']\n                subscriptions = Subscription.objects.filter(verfied_email=email, is_active=True)\n                for subscription in subscriptions:\n                    unsubscription = UnSubscription(subscription=subscription)\n                    unsubscription.save()\n                return HttpResponseRedirect(reverse('emaildigest_unsubscribe') + \"?done&email=\"+email)\n        return render(request, 'emaildigest/unsubscribe.html', {'form': form, 'prevent_footer_subscription_form': True})\n    elif subscription_id is not None and digest_id is not None:\n        subscription = get_object_or_404(Subscription, pk=subscription_id)\n        digest = get_object_or_404(EmailDigest, pk=digest_id)\n        if request.method==\"GET\":\n            return render(request, 'emaildigest/unsubscribe_confirm.html', {})\n        elif request.method==\"POST\":\n            unsubscription = UnSubscription(subscription=subscription, from_digest=digest)\n            unsubscription.save()\n            return HttpResponseRedirect(reverse('emaildigest_unsubscribe') + \"?done&subscription=\"+subscription_id)\n        else:\n            return HttpResponseRedirect(reverse('emaildigest_unsubscribe'))\n    else:\n        return HttpResponseRedirect(reverse('emaildigest_unsubscribe'))\n    pass\n\n\ndef my_subscriptions(request):\n    return render(request, 'emaildigest/my_subscriptions.html')"
  },
  {
    "path": "hnclone/__init__.py",
    "content": ""
  },
  {
    "path": "hnclone/context_processors.py",
    "content": "from django.conf import settings\ndef settings_context_processor(request):\n   return {\n       'SITE_NAME': settings.SITE_NAME,\n       'SITE_DOMAIN': settings.SITE_DOMAIN,\n       'SITE_URL': settings.SITE_URL\n   }"
  },
  {
    "path": "hnclone/middleware.py",
    "content": ""
  },
  {
    "path": "hnclone/settings.py",
    "content": "\"\"\"\nDjango settings for hnclone project.\n\nGenerated by 'django-admin startproject' using Django 2.2.5.\n\nModified by me 2019-09-30 15.50 CEST\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.2/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.2/ref/settings/\n\"\"\"\n\nimport os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'TODO' # TODO\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\n\nUSE_X_FORWARDED_HOST = True\nALLOWED_HOSTS = [\n    'news.python.sc',\n    'localhost',\n]\n\n\n# Application definition\n\nINSTALLED_APPS = [\n    'django.contrib.admin',\n    'django.contrib.auth',\n    'django.contrib.contenttypes',\n    'django.contrib.sessions',\n    'django.contrib.messages',\n    'django.contrib.staticfiles',\n    'django.contrib.humanize',\n\n    'mptt',\n    'debug_toolbar',\n\n    'accounts',\n    'news',\n    'emaildigest',\n\n    \n]\n\nMIDDLEWARE = [\n    'debug_toolbar.middleware.DebugToolbarMiddleware',\n\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.middleware.csrf.CsrfViewMiddleware',\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n    # 'django.middleware.gzip.GZipMiddleware',\n    #'htmlmin.middleware.HtmlMinifyMiddleware', # TODO: When activated, Django Debug Toolbar has JS issues\n    'htmlmin.middleware.MarkRequestMiddleware',\n]\n\nROOT_URLCONF = 'hnclone.urls'\n\nTEMPLATES = [\n    {\n        'BACKEND': 'django.template.backends.django.DjangoTemplates',\n        'DIRS': [],\n        'APP_DIRS': True,\n        'OPTIONS': {\n            'context_processors': [\n                'django.template.context_processors.debug',\n                'django.template.context_processors.request',\n                'django.contrib.auth.context_processors.auth',\n                'django.contrib.messages.context_processors.messages',\n                'hnclone.context_processors.settings_context_processor',\n            ],\n        },\n    },\n]\n\nWSGI_APPLICATION = 'hnclone.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.2/ref/settings/#databases\n\nDATABASES = {\n    'default': {\n        'ENGINE': 'django.db.backends.sqlite3',\n        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n    }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n    {\n        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n    },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.2/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.2/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = [\n    os.path.join(BASE_DIR, \"static\"),\n]\n\n\nAUTH_USER_MODEL = 'accounts.CustomUser'\n\n\nINTERNAL_IPS = [\n    '127.0.0.1',\n]\n\n\nPAGING_SIZE = 30\n\n\nHTML_MINIFY = True\n\n\n\nLOGOUT_REDIRECT_URL = '/'\nLOGIN_REDIRECT_URL = '/'\n\n\n\nACCEPT_UNINVITED_REGISTRATIONS = False\n\n\nSITE_NAME = 'Pythonic News'\nSITE_URL = 'https://news.python.sc'\nSITE_DOMAIN = 'news.python.sc'\n"
  },
  {
    "path": "hnclone/urls.py",
    "content": "\"\"\"hnclone URL Configuration\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.http import HttpResponse\n\nurlpatterns = [\n    path('', include('news.urls')),\n    path('', include('accounts.urls')),\n    path('digest/', include('emaildigest.urls')),\n    path('admin/', admin.site.urls),\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\nif settings.DEBUG:\n    import debug_toolbar\n    urlpatterns = [\n        path('__debug__/', include(debug_toolbar.urls)),\n    ] + urlpatterns\n\n\nfrom ratelimit.exceptions import Ratelimited\ndef handler403(request, exception=None):\n    if isinstance(exception, Ratelimited):\n        return HttpResponse(\"<img src='https://http.cat/429.jpg'><br>Sorry, we're not able to serve your requests this quickly.\", status=429)\n    return HttpResponseForbidden('Forbidden')\n"
  },
  {
    "path": "hnclone/wsgi.py",
    "content": "\"\"\"\nWSGI config for hnclone project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/\n\"\"\"\n\nimport os, sys\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(BASE_DIR )\nsys.path.append(BASE_DIR + '/../')\n\nfrom django.core.wsgi import get_wsgi_application\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hnclone.settings')\n\napplication = get_wsgi_application()\n"
  },
  {
    "path": "manage.py",
    "content": "#!/usr/bin/env python\n\"\"\"Django's command-line utility for administrative tasks.\"\"\"\nimport os\nimport sys\n\n\ndef main():\n    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hnclone.settings')\n    try:\n        from django.core.management import execute_from_command_line\n    except ImportError as exc:\n        raise ImportError(\n            \"Couldn't import Django. Are you sure it's installed and \"\n            \"available on your PYTHONPATH environment variable? Did you \"\n            \"forget to activate a virtual environment?\"\n        ) from exc\n    execute_from_command_line(sys.argv)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "news/__init__.py",
    "content": "default_app_config = 'news.apps.NewsConfig'\n"
  },
  {
    "path": "news/admin.py",
    "content": "from django.contrib import admin\n\n\nfrom .models import Story, Comment\n\nadmin.site.register(Story)\nadmin.site.register(Comment)"
  },
  {
    "path": "news/apps.py",
    "content": "from django.apps import AppConfig\n\n\nclass NewsConfig(AppConfig):\n    name = 'news'\n\n    def ready(self):\n        from . import receivers"
  },
  {
    "path": "news/feeds.py",
    "content": "from django.contrib.syndication.views import Feed\nfrom .models import Story\nfrom .views import _newest, _front_page\n\nfrom django.conf import settings\n\nclass NewestFeed(Feed):\n    title = \"%s: Latest\"%(settings.SITE_NAME)\n    link = \"/newest/\"\n    description = \"Latest stories\"\n\n    def items(self):\n        return _newest(30, 0)\n\n    def item_title(self, item):\n        return item.title\n\n    def item_pubdate(self, item):\n        return item.created_at\n    \n    def item_updateddate(self, item):\n        return item.changed_at\n    \n    def item_author_name(self, item):\n        return str(item.user)\n    \n    def item_author_link(self, item):\n        return settings.SITE_URL + item.user.get_absolute_url()\n\n    def item_description(self, item):\n        return \"TODO\" # TODO\n        return item.url\n\n\nclass FrontPageFeed(NewestFeed):\n    title = \"%s: Front Page\" % (settings.SITE_NAME)\n    link = \"/feed\"\n    description = \"Front Page stories\"\n\n    def items(self):\n        return _front_page(30, 0)"
  },
  {
    "path": "news/forms.py",
    "content": "from django import forms\n\nfrom .models import Comment, Story\n\nclass CommentForm(forms.ModelForm):\n    class Meta:\n        model = Comment\n        fields = ['text']\n\n\nclass AddStoryForm(forms.ModelForm):\n    class Meta:\n        model = Story\n        fields = ['title', 'url', 'text']\n\n    def clean(self):\n        cleaned_data = super().clean()\n\n        title = self.cleaned_data.get('title')\n        text = self.cleaned_data.get('text')\n        url = self.cleaned_data.get('url')\n        if not title:\n            raise forms.ValidationError(\"Please provide a title.\")\n        if (not text) and (not url):\n            raise forms.ValidationError(\"Please provide either a text or a URL.\")\n\n\n\nclass StoryForm(forms.ModelForm):\n    class Meta:\n        model = Story\n        fields = ['title', 'text']\n\n    \n"
  },
  {
    "path": "news/migrations/0001_initial.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-07 12:14\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport mptt.fields\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n    initial = True\n\n    dependencies = [\n        migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n    ]\n\n    operations = [\n        migrations.CreateModel(\n            name='Item',\n            fields=[\n                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n                ('created_at', models.DateTimeField(auto_now_add=True)),\n                ('changed_at', models.DateTimeField(auto_now=True)),\n                ('upvotes', models.PositiveIntegerField(default=0)),\n                ('downvotes', models.PositiveIntegerField(default=0)),\n                ('points', models.IntegerField(default=0)),\n                ('num_comments', models.PositiveIntegerField(default=0)),\n                ('lft', models.PositiveIntegerField(editable=False)),\n                ('rght', models.PositiveIntegerField(editable=False)),\n                ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)),\n                ('level', models.PositiveIntegerField(editable=False)),\n                ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='news.Item')),\n                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n            ],\n            options={\n                'abstract': False,\n            },\n        ),\n        migrations.CreateModel(\n            name='Story',\n            fields=[\n                ('item_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='news.Item')),\n                ('url', models.URLField(null=True)),\n                ('text', models.TextField(null=True)),\n            ],\n            options={\n                'abstract': False,\n            },\n            bases=('news.item',),\n        ),\n        migrations.CreateModel(\n            name='Vote',\n            fields=[\n                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n                ('created_at', models.DateTimeField(auto_now_add=True)),\n                ('changed_at', models.DateTimeField(auto_now=True)),\n                ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news.Item')),\n                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n            ],\n        ),\n        migrations.CreateModel(\n            name='Comment',\n            fields=[\n                ('item_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='news.Item')),\n                ('text', models.TextField()),\n                ('to_story', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news.Story')),\n            ],\n            options={\n                'abstract': False,\n            },\n            bases=('news.item',),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0002_story_title.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-07 13:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0001_initial'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='story',\n            name='title',\n            field=models.CharField(default='-', max_length=255),\n            preserve_default=False,\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0003_auto_20190908_1642.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-08 16:42\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport mptt.fields\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0002_story_title'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='vote',\n            name='vote',\n            field=models.SmallIntegerField(default=1),\n        ),\n        migrations.AlterField(\n            model_name='comment',\n            name='to_story',\n            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='news.Story'),\n        ),\n        migrations.AlterField(\n            model_name='item',\n            name='downvotes',\n            field=models.PositiveIntegerField(default=0, editable=False),\n        ),\n        migrations.AlterField(\n            model_name='item',\n            name='num_comments',\n            field=models.PositiveIntegerField(default=0, editable=False),\n        ),\n        migrations.AlterField(\n            model_name='item',\n            name='parent',\n            field=mptt.fields.TreeForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='news.Item'),\n        ),\n        migrations.AlterField(\n            model_name='item',\n            name='points',\n            field=models.IntegerField(default=0, editable=False),\n        ),\n        migrations.AlterField(\n            model_name='item',\n            name='upvotes',\n            field=models.PositiveIntegerField(default=0, editable=False),\n        ),\n        migrations.AlterField(\n            model_name='story',\n            name='text',\n            field=models.TextField(blank=True, null=True),\n        ),\n        migrations.AlterField(\n            model_name='story',\n            name='title',\n            field=models.CharField(blank=True, max_length=255),\n        ),\n        migrations.AlterField(\n            model_name='story',\n            name='url',\n            field=models.URLField(blank=True, null=True),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0004_auto_20190908_2249.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-08 22:49\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0003_auto_20190908_1642'),\n    ]\n\n    operations = [\n        migrations.AddIndex(\n            model_name='item',\n            index=models.Index(fields=['points', 'created_at'], name='news_item_points_d03885_idx'),\n        ),\n        migrations.AddIndex(\n            model_name='item',\n            index=models.Index(fields=['created_at', 'points'], name='news_item_created_f2b812_idx'),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0005_auto_20190908_2250.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-08 22:50\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0004_auto_20190908_2249'),\n    ]\n\n    operations = [\n        migrations.RemoveIndex(\n            model_name='item',\n            name='news_item_points_d03885_idx',\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0006_auto_20190908_2251.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-08 22:51\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0005_auto_20190908_2250'),\n    ]\n\n    operations = [\n        migrations.RemoveIndex(\n            model_name='item',\n            name='news_item_created_f2b812_idx',\n        ),\n        migrations.AddIndex(\n            model_name='item',\n            index=models.Index(fields=['points', 'created_at'], name='news_item_points_d03885_idx'),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0007_auto_20190908_2256.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-08 22:56\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0006_auto_20190908_2251'),\n    ]\n\n    operations = [\n        migrations.RemoveIndex(\n            model_name='item',\n            name='news_item_points_d03885_idx',\n        ),\n        migrations.AddField(\n            model_name='item',\n            name='is_ask',\n            field=models.BooleanField(default=False),\n        ),\n        migrations.AddField(\n            model_name='item',\n            name='is_show',\n            field=models.BooleanField(default=False),\n        ),\n        migrations.AddIndex(\n            model_name='item',\n            index=models.Index(fields=['created_at', 'points'], name='news_item_created_f2b812_idx'),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0008_story_duplicate_of.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-23 13:23\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0007_auto_20190908_2256'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='story',\n            name='duplicate_of',\n            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='news.Story'),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0009_story_domain.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-30 16:17\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0008_story_duplicate_of'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='story',\n            name='domain',\n            field=models.CharField(blank=True, max_length=255, null=True),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0010_auto_20190930_1620.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-30 16:20\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0009_story_domain'),\n    ]\n\n    operations = [\n        migrations.AlterField(\n            model_name='story',\n            name='domain',\n            field=models.CharField(blank=True, db_index=True, max_length=255, null=True),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0011_auto_20190930_1623.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-30 16:23\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0010_auto_20190930_1620'),\n    ]\n\n    operations = [\n        migrations.AddIndex(\n            model_name='story',\n            index=models.Index(fields=['domain', 'duplicate_of'], name='news_story_domain_07db78_idx'),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/0012_auto_20190930_1625.py",
    "content": "# Generated by Django 2.2.5 on 2019-09-30 16:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('news', '0011_auto_20190930_1623'),\n    ]\n\n    operations = [\n        migrations.AddIndex(\n            model_name='item',\n            index=models.Index(fields=['created_at', 'id'], name='news_item_created_10dd57_idx'),\n        ),\n        migrations.AddIndex(\n            model_name='item',\n            index=models.Index(fields=['id', 'created_at'], name='news_item_id_b557ce_idx'),\n        ),\n    ]\n"
  },
  {
    "path": "news/migrations/__init__.py",
    "content": ""
  },
  {
    "path": "news/models.py",
    "content": "import uuid\n\nfrom accounts.models import CustomUser\n\nfrom django.db import models\nfrom mptt.models import MPTTModel, TreeForeignKey\nfrom django.urls import reverse\n\nfrom urllib.parse import urlparse\n\n\n\nclass Item(MPTTModel):\n    class Meta:\n        indexes = [\n            #models.Index(fields=['points', 'created_at']),\n            models.Index(fields=['created_at', 'points']),\n            models.Index(fields=['created_at', 'id']),\n            models.Index(fields=['id', 'created_at']),\n        ]\n        # ordering = ['-created_at']\n\n    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n    created_at = models.DateTimeField(auto_now_add=True)\n    changed_at = models.DateTimeField(auto_now=True)\n    upvotes = models.PositiveIntegerField(default=0, editable=False)\n    downvotes = models.PositiveIntegerField(default=0, editable=False)\n    points = models.IntegerField(default=0, editable=False)\n    num_comments = models.PositiveIntegerField(default=0, editable=False)\n    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', editable=False)\n    user = models.ForeignKey(to=CustomUser, on_delete=models.CASCADE)\n\n    is_ask = models.BooleanField(default=False)\n    is_show = models.BooleanField(default=False)\n\n\n    def get_absolute_url(self):\n        return reverse(\"item\", kwargs={\"pk\": self.pk})\n\n\n    def can_be_upvoted_by(self, user):\n        if not user.is_authenticated:\n            return False\n        if user == self.user:\n            return False\n        if Vote.objects.filter(user=user, item=self).count():\n            return False\n        return True\n    \n    def can_be_downvoted_by(self, user):\n        if not user.is_authenticated:\n            return False\n        if user == self.user:\n            return False\n        else:\n            if user.karma > 1:\n                if not Vote.objects.filter(user=user, item=self).count():\n                    return True\n        return False\n\n    def can_be_edited_by(self, user):\n        return self.user == user and self.num_comments == 0\n    \n    def can_be_deleted_by(self, user):\n        return self.can_be_edited_by(user)\n\n\n\nclass Story(Item):\n    class Meta:\n        indexes = [\n            models.Index(fields=['domain', 'duplicate_of']),\n        ]\n    is_story = True\n\n    # class Meta:\n    #     ordering = ['-pk']\n    title = models.CharField(max_length=255, blank=True)\n    url = models.URLField(null=True, blank=True)\n    text = models.TextField(null=True, blank=True)\n    duplicate_of = models.ForeignKey('Story', on_delete=models.CASCADE, null=True)\n    domain = models.CharField(max_length=255, null=True, blank=True, db_index=True)\n    \n\n    def __str__(self):\n        return self.title\n    \n    # @property\n    # def domain(self):\n    #     o = urlparse(self.url)\n    #     return o.hostname\n\n    def can_be_downvoted_by(self, user):\n        return False\n\n    # def Kcomments(self):\n    #     return self.comments\n    #     return {\n    #         'all': self.get_descendants() # lambda: [i.comment for i in self.get_descendants().select_related('comment')]\n    #     }\n    #     return self.comments\n\n\nclass Comment(Item):\n    is_comment = True\n\n    text = models.TextField()\n    to_story = models.ForeignKey(Story, on_delete=models.CASCADE, related_name=\"comments\")\n\n    def __str__(self):\n        return self.text[:255]\n\n    def comments(self):\n        return {\n            #'all': lambda: [i.comment for i in self.get_descendants().select_related('comment')]\n            'all': lambda: [i.comment for i in self.get_descendants()]\n        }\n\n\nclass Vote(models.Model):\n    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n    created_at = models.DateTimeField(auto_now_add=True)\n    changed_at = models.DateTimeField(auto_now=True)\n    item = models.ForeignKey(Item, on_delete=models.CASCADE)\n    # vote = None # -1 | 0 | 1 --> BooleanField(default=None, null=True)??\n    vote = models.SmallIntegerField(default=1)\n    user = models.ForeignKey(to=CustomUser, on_delete=models.CASCADE)\n\n\n"
  },
  {
    "path": "news/receivers.py",
    "content": "#from django.core.signals import request_finished\nfrom django.db.models.signals import pre_save, post_save, post_delete\nfrom django.dispatch import receiver\n\nfrom urllib.parse import urlparse\n\nfrom .models import Item, Vote, Comment, Story\n\n@receiver(pre_save)\ndef mark_show_and_ask(sender, instance, **kwargs):\n    if isinstance(instance, Story):\n        if instance.title.lower().startswith('ask'):\n            instance.is_ask = True\n        if instance.title.lower().startswith('show'):\n            instance.is_show = True\n\n\n@receiver(post_save)\ndef create_self_upvote_for_submission(sender, instance, created, **kwargs):\n    if created and isinstance(instance, Item):\n        vote = Vote(item=instance, user=instance.user)\n        vote.save()\n\n\n@receiver(post_save)\ndef check_for_duplicates(sender, instance, created, **kwargs):\n    if created and isinstance(instance, Story):\n        story = instance\n        if story.url and story.duplicate_of is None:\n            other_stories = Story.objects.filter(url=story.url).exclude(pk=story.pk).order_by('-changed_at')\n            c = other_stories.count()\n            if c > 0:\n                new_vote = Vote(item=other_stories[0], vote=1, user=story.user)\n                new_vote.save()\n                story.duplicate_of = other_stories[0]\n                story.save()\n\n\n@receiver(post_save)\ndef update_votes_count_on_submission(sender, instance, created, **kwargs):\n    if created and isinstance(instance, Vote):\n        vote = instance\n        item = instance.item\n        other_votes = Vote.objects.filter(item=vote.item, user=vote.user, vote=vote.vote).exclude(pk=vote.pk)\n        if other_votes.count():\n            return\n        if instance.vote > 0:\n            item.upvotes += instance.vote\n        else:\n            item.downvotes += (-1)*instance.vote\n        item.points += instance.vote\n        item.save()\n\n\n@receiver(post_save)\ndef update_user_karma_on_vote(sender, instance, created, **kwargs):\n    if created and isinstance(instance, Vote):\n        vote = instance\n        other_votes = Vote.objects.filter(item=vote.item, user=vote.user, vote=vote.vote).exclude(pk=vote.pk)\n        if other_votes.count():\n            return\n        item = instance.item\n        if item.user != instance.user:\n            item.user.karma += instance.vote\n            item.user.save()\n\n\ndef _recount_comments(instance, val=1):\n    assert isinstance(instance, Comment)\n    instance.to_story.num_comments += val\n    instance.to_story.save()\n    parent = instance.parent\n    while parent is not None:\n        parent.num_comments += val\n        parent.save()\n        parent = parent.parent\n\n\n@receiver(post_save)\ndef update_comments_count_on_submission(sender, instance, created, **kwargs):\n    if created and isinstance(instance, Comment):\n        _recount_comments(instance, 1)\n\n\n@receiver(post_delete)\ndef update_comments_count_on_deletion(sender, instance, **kwargs):\n    if isinstance(instance, Comment):\n        _recount_comments(instance, -1)\n\n\n@receiver(post_delete)\ndef update_item_votes_on_unvote(sender, instance, **kwargs):\n    if isinstance(instance, Vote):\n        vote = instance\n        item = vote.item\n        if vote.user == item.user:\n            return\n        item.points -= vote.vote\n        if vote.vote > 0:\n            item.upvotes -= abs(vote.vote)\n        else:\n            item.downvotes -= abs(vote.vote)\n        item.save()\n\n\n@receiver(post_delete)\ndef update_user_karma_on_unvote(sender, instance, **kwargs):\n    if isinstance(instance, Vote):\n        vote = instance\n        item = vote.item\n        if vote.user == item.user:\n            return\n        item.user.karma -= vote.vote\n        item.user.save()\n\n\n@receiver(pre_save)\ndef add_domain_to_link_stories(sender, instance, **kwargs):\n    if isinstance(instance, Story):\n        if instance.url:\n            o = urlparse(instance.url)\n            instance.domain = o.hostname.lower()"
  },
  {
    "path": "news/templates/news/__base.html",
    "content": "{% load static %}{% load humanize %}{% load emaildigest_extra %}<!doctype html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"utf-8\" />\n    <meta property=\"og:locale\" content=\"en_US\" />\n    <meta property=\"og:type\" content=\"website\" />\n    <meta property=\"og:title\" content=\"{{SITE_NAME}}\">\n    <meta property=\"og:site_name\" content=\"{{SITE_NAME}}\">\n    <meta name=\"generator\" content=\"Python+Django\" />\n    <meta name=\"theme-color\" content=\"#306998\" />\n    <meta name=\"robots\" content=\"index,follow\" />\n    <meta name=\"googlebot\" content=\"index,follow\" />\n    <meta http-equiv=\"x-ua-compatible\" content=\"ie=edge\" />\n    <meta name=\"renderer\" content=\"webkit|ie-comp|ie-stand\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <meta name=\"emoji\" content=\"🐍\" />\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'news.css'%}\" />\n    <link rel=\"icon\" type=\"image/png\" sizes=\"144x144\" href=\"{% static 'icon.png' %}\" />\n    <!--<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"/rss\" />-->\n    <meta name=\"google-site-verification\" content=\"WDbUHr8ccfJXaHWxNrjsVYPOMC8ooxhgHil3BLKkslA\" />\n    <meta name=\"msvalidate.01\" content=\"9F28DFABF82B307C80AA587B7FC11195\" />\n    <!-- Global site tag (gtag.js) - Google Analytics -->\n    <script async src=\"https://www.googletagmanager.com/gtag/js?id=UA-437457-25\"></script>\n    <script>\n    window.dataLayer = window.dataLayer || [];\n    function gtag(){dataLayer.push(arguments);}\n    gtag('js', new Date());\n\n    gtag('config', 'UA-437457-25');\n    </script>\n\n    <title>{% block title %}{% endblock title %}{{SITE_NAME}}</title>\n</head>\n\n\n<body>\n    <main id=\"pnmain\">\n        <nav id=\"top-bar\">\n            <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"padding:2px\">\n                <tbody>\n                    <tr>\n                        <td style=\"width:18px;padding-right:4px\"><a href={% url 'index' %}><img alt=\"Python Icon\" src=\"{% static 'icon.png' %}\" width=\"18\" height=\"18\" style=\"border:1px white solid; background-color: white;\"></a></td>\n                        <td style=\"line-height:12pt; height:10px;\">\n                            <span class=\"pagetop\">\n                            <b class=\"pnname\">\n\n                            <a href=\"{% url 'index' %}\">{{SITE_NAME}}</a></b>\n                            {% url 'newest' as url %}\n                            <a href=\"{{ url }}\" {% if url == request.path %}class=\"active\"{% endif %}>new</a>\n                            | {% url 'threads' as url %}\n                            <a href=\"{{ url }}\" {% if url == request.path %}class=\"active\"{% endif %}>threads</a>\n                            | {% url 'comments' as url %}\n                            <a href=\"{{ url }}\" {% if url == request.path %}class=\"active\"{% endif %}>comments</a>\n                            | {% url 'ask' as url %}\n                            <a href=\"{{ url }}\" {% if url == request.path %}class=\"active\"{% endif %}>ask</a>\n                            | {% url 'show' as url %}\n                            <a href=\"{{ url }}\" {% if url == request.path %}class=\"active\"{% endif %}>show</a>\n                            {% url 'submit' as url %}\n                            | <a href=\"{{ url }}\" {% if url == request.path %}class=\"active\"{% endif %}>submit</a>\n                            </span></td>\n                        <td style=\"text-align:right;padding-right:4px;\">\n                        <span class=\"pagetop\">\n                            {% if user.is_authenticated %}\n                            {% url 'accounts_my_profile' as url %}\n                            <a href=\"{{ url }}\" {% if url == request.path %}class=\"active\"{% endif %}>{{user}}</a> ({{user.karma}}) \n                            | <form method=\"POST\" action=\"{% url 'logout' %}\" class=\"logout-form\">{% csrf_token %}&nbsp;<button class=\"logout-button\">logout</button></form>\n                            {% else %}\n                            {% url 'login' as url %}\n                            <a href=\"{{ url }}\" {% if url == request.path %}class=\"active\"{% endif %}>login</a>\n                            {% url 'accounts_register' as url %}\n                            | <a href=\"{{ url }}\" {% if url == request.path %}class=\"active\"{% endif %}>register</a>\n                            {% endif %}\n                        </span></td>\n                    </tr>\n                </tbody>\n            </table>\n        </nav>\n\n{% block content %}{% endblock content %}\n\n        <nav id=\"pre-footer-bar\">\n            <hr>\n            {% if not prevent_footer_subscription_form %}\n                {% digest_subscription_form user=user %}\n            {% endif %}\n        </nav>\n\n\n        <nav id=\"footer-bar\">\n            <p class=\"smaller\">{{SITE_NAME}} is a community to discuss everything around the Python Programming language. This community is not affiliated with the Python Software Foundation.</p>\n        </nav>\n    </main>\n<script type=\"text/javascript\" src=\"{% static 'news.js'%}\"></script>\n</body>\n</html>"
  },
  {
    "path": "news/templates/news/_item_content_tag.html",
    "content": "{% load news_extra %}\n\n<div style=\"margin-bottom:3pt; \">\n                    {% if item.title %}\n                    <span class=\"title\">\n                        {% if item.url %}\n                            <a rel=\"ugc\" href=\"{{item.url}}\">{{item.title}}</a> {% if item.domain %}<span class=\"smaller\">(<a href=\"{% url 'newest' %}?site={{item.domain}}\">{{item.domain}}</a>)</span>{% endif %}\n                        {% else %}\n                            <a href=\"{{item.get_absolute_url}}\">{{item.title}}</a>\n                        {% endif %}\n                    </span>\n                    {% endif %}\n                    {% if item.text and not hide_text %}\n                        {{ item.text | comment_markdown }}\n                    {% endif %}\n</div>\n"
  },
  {
    "path": "news/templates/news/_item_control_tag.html",
    "content": "{% load humanize %}\n{% load news_extra %}\n                    <span class=\"controls\">\n                            <span class=\"smaller\">\n                                {{item.points}} point{{item.points|pluralize}} by {%link_user item.user%} <span class=\"naturaltime\" data-orig-time=\"{{item.created_at.isoformat}}\">{{item.created_at|naturaltime}}<span>\n                                | flag\n                                | hide\n                                | <a href=\"{{item.get_absolute_url}}\">{{item.num_comments}} comments</a></span>\n                                {% if item.num_comments == 0 and item.user == request_user %}| <a href=\"{% url 'edit' pk=item.pk %}\">edit</a></span>{% endif %}\n                                {% if item.num_comments == 0 and item.user == request_user %}| <a href=\"{% url 'delete' pk=item.pk %}\">delete</a></span>{% endif %}\n                    </span>"
  },
  {
    "path": "news/templates/news/_item_tag.html",
    "content": "{% load humanize %}\n{% load static %}\n{% load news_extra %}\n\n\n            <tr id=\"{{item.pk}}\">\n                <td rowspan=\"2\" class=\"rank\">{%if rank %}{{rank}}.{% endif %}</td>\n                <td rowspan=\"2\"><div>\n\n                    {% user_arrows user=user item=item as assignment_options %}\n\n                    {% if 'star' in assignment_options %}\n                    <span class=\"self-item\">*</span>\n                    {% endif %}\n                    {% if 'up' in assignment_options %}\n                    <form class=\"vote-form upvote\" method=\"POST\" action=\"{% url 'upvote' pk=item.pk %}\">{% csrf_token %}  <button type=\"submit\" class=\"vote-button\" aria-label=\"Upvote\"><div class=\"arrow-up\"></div></button></form>\n                    {% endif %}\n                    {% if 'down' in assignment_options %}\n                    <form class=\"vote-form downvote\" method=\"POST\" action=\"{% url 'downvote' pk=item.pk %}\">{% csrf_token %}<button type=\"submit\" class=\"vote-button\" aria-label=\"Downvote\"><div class=\"arrow-down\"></div></button></form>\n                    {% endif %}\n                    {% if not assignment_options %}\n                    &nbsp;\n                    {% endif %}\n\n                    </div></td>\n                <td><!-- ROW 1--> {% if item.is_comment %}{% item_control item=item request_user=request_user %} {% else%} {% item_content item=item hide_text=hide_text %} {% endif %}</td>\n            </tr>\n            <tr>\n                <td><!-- ROW 2--> {% if item.is_comment %}{% item_content item=item hide_text=hide_text %} {% else %}{% item_control item=item request_user=request_user %}{% endif %}</td>\n            </td>\n\n\n            <tr class=\"spacer\"></tr>"
  },
  {
    "path": "news/templates/news/_link_user_tag.html",
    "content": "<a class=\"{% if user.is_green %}green{% endif %}\" href=\"{{user.get_absolute_url}}\">{{user}}</a>"
  },
  {
    "path": "news/templates/news/_more_link_tag.html",
    "content": "<a href=\"{{more_link}}\" class=\"more-link\">More</a>"
  },
  {
    "path": "news/templates/news/bookmarklet.html",
    "content": "{% extends \"news/__base.html\" %}\n{% load humanize %}\n{% load static %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n{% block content %}\n<article class=\"site-content\">\n\n\n<p>When you click on the bookmarklet, it will submit the page you're on. To install, drag this link to your browser toolbar:</p>\n\n<center>\n<a style=\"color: #777; font-size: 2em;\" rel=\"nofollow\" href=\"javascript:window.location=%22https://news.python.sc/submit?u=%22+encodeURIComponent(document.location)+%22&t=%22+encodeURIComponent(document.title)\">post to 🐍</a>\n</center>\n\n\n</article>\n\n{% endblock content %}"
  },
  {
    "path": "news/templates/news/formatting_help.html",
    "content": "<div class=\"formatting-help closed\">\n    <table>\n        <thead>\n            <tr>\n                <th>Markdown</th>\n                <th>Output</th>\n            </tr>\n        </thead>\n        <tbody>\n            <tr>\n                <td><pre># Heading level 1</pre></td>\n                <td><h3>Heading level 1</h3></td>\n            </tr>\n            <tr>\n                <td><pre>## Heading level 2</pre></td>\n                <td><h4>Heading level 2</h3></td>\n            </tr>\n            <tr>\n                <td><pre>### Heading level 3</pre></td>\n                <td><h5>Heading level 3</h3></td>\n            </tr>\n            <tr>\n                <td><pre>#### Heading level 4</pre></td>\n                <td><h6>Heading level 4</h3></td>\n            </tr>\n            <tr>\n                <td><pre>\n* unordered item 1\n* unordered item 2\n* unordered item 3\n                </pre></td>\n                <td>\n                    <ul>\n                        <li>unordered item 1</li>\n                        <li>unordered item 2</li>\n                        <li>unordered item 3</li>\n                    </ul>\n                </td>\n            </tr>\n            <tr>\n                <td><pre>\n1. ordered item 1\n2. ordered item 2\n3. ordered item 3\n                </pre></td>\n                <td>\n                    <ol>\n                        <li>ordered item 1</li>\n                        <li>ordered item 2</li>\n                        <li>ordered item 3</li>\n                    </ol>\n                </td>\n            </tr>\n            <tr>\n                <td><pre>\n[title](https://www.google.com/)\n                </pre></td>\n                <td>\n                    <a href=\"#\">title</a>\n                </td>\n            </tr>\n        </tbody>\n    </table>\n</div>\n<script>\nconst helpElm = document.querySelector('.formatting-help');\nlet helpClosed = true;\nwindow.toggleFormattingHelp = function() {\n    helpClosed = !helpClosed;\n    helpElm.className = 'formatting-help ' + (helpClosed ? 'closed' : '');\n};\n</script>\n"
  },
  {
    "path": "news/templates/news/index.html",
    "content": "{% extends \"news/__base.html\" %}\n{% load humanize %}\n{% load static %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n{% block content %}\n<article class=\"site-content-dense\">\n<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"item-list outer level-0\">\n        {% for story in stories %}\n                {% news_item item=story show_text=False hide_text=hide_text rank=forloop.counter|add:rank_start user=user %}\n                {% if show_children %}\n                    <tr><td></td><td></td><td>\n                        {% recursetree story.comments.all  %}\n                        <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"item-list inner level-{{node.level}}\" style=\"\">\n                            {% news_item item=node show_text=True hide_text=hide_text rank=None user=user %}\n                            {% if not node.is_leaf_node %}\n                                <tr><td></td><td></td><td>\n                                    {{ children }}\n                                </td></tr>\n                            {% endif %}\n                        </table>\n                        {% endrecursetree %}\n                    </td></tr>\n                {% endif %}\n        {% endfor %}\n</table>\n\n\n\n\n        <a href=\"?p={{page|add:1}}\">{% more_link %}</a>\n\n</article>\n\n{% endblock content %}"
  },
  {
    "path": "news/templates/news/item.html",
    "content": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n\n\n\n{% block content %}\n<article class=\"site-content-dense\">\n\n\n\n<table  border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"item-list\">\n        {% news_item item=item rank=None hide_text=False user=user %}\n</table>\n\n\n\n\n{% if comment_form %}\n<form method=\"POST\" class=\"comment-form clearfix\">{% csrf_token %}\n    {{ comment_form.text }}\n    <p class=\"clearfix small\"></p>\n    <button type=\"submit\">add comment</button>\n    <ul class=\"horizontal-list\">\n        <li><a class=\"smaller\" href=\"{% url 'zen' %}\">guidelines</a></li>\n        <li><a class=\"smaller\" href=\"javascript:toggleFormattingHelp()\">formatting help</a></li>\n    </ul>\n</form>\n\n{% include \"news/formatting_help.html\" %}\n\n{% endif %}\n\n\n<br><br>\n\n\n<table  border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"item-list\">\n    {% recursetree item.comments.all  %}\n            {% news_item item=node rank=None show_text=True hide_text=False user=user %}\n            {% if not node.is_leaf_node %}\n            <tr><td colspan=\"3\" style=\"padding-left:30px;\">\n                    <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"item-list\" style=\"border-left:1px solid grey;\">\n                        {{ children }}\n                    </table>\n            </td></tr>\n            {% endif %}\n    {% endrecursetree %}\n</table>\n\n\n\n\n</article>\n{% endblock content %}\n"
  },
  {
    "path": "news/templates/news/item_delete.html",
    "content": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n\n\n\n{% block content %}\n<article class=\"site-content-dense\">\n\nAre you sure, you want to delete this: <br>\n\n\n<div style=\"margin:2em;\">\n<table  border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"item-list\">\n        {% news_item item=item rank=None hide_text=False user=user %}\n</table>\n</div> \n\n<form method=\"POST\" class=\"comment-form\" >{% csrf_token %}\n    <button type=\"submit\">delete item</button>\n</form>\n\n\n\n</article>\n{% endblock content %}"
  },
  {
    "path": "news/templates/news/item_edit.html",
    "content": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n\n\n\n{% block content %}\n<article class=\"site-content-dense\">\n\n\n\n<table  border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"item-list\">\n\n        {% news_item item=item rank=None hide_text=False user=user %}\n\n</table>\n\n\n\n\n{% if edit_form %}\n<form method=\"POST\" class=\"comment-form\" >{% csrf_token %}\n    {{ edit_form.text }}<a class=\"smaller\" href=\"{% url 'zen' %}\">guidelines</a>\n    <br>\n    <button type=\"submit\">save item</button>\n</form>\n{% endif %}\n\n\n</article>\n{% endblock content %}"
  },
  {
    "path": "news/templates/news/submit.html",
    "content": "{% extends 'news/__base.html' %}\n\n{% block content %}\n<article class=\"site-content-dense\">\n<form method=\"POST\">{% csrf_token %}\n<table>\n{{ form.as_table }}\n</table>\n<button type=\"submit\">submit</button>\n</form>\n\n<p>\nLeave url blank to submit a question for discussion. If there is no url, the text (if any) will appear at the top of the thread.\n</p><p>\nYou can also submit via <a href=\"{% url 'bookmarklet' %}\">bookmarklet</a>.\n</p>\n\n\n</article>\n{% endblock content %}"
  },
  {
    "path": "news/templates/news/zen.html",
    "content": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n\n\n\n{% block content %}\n\n\n\n\n<article class=\"site-content\">\n    \n        <h2>The Zen of {{SITE_NAME}} (aka Guidelines)</h2>\n\n        <p class=\"smaller\">Based on <a href=\"https://www.python.org/dev/peps/pep-0020/\">The Zen of Python</a></p>\n\n        <p>{{SITE_NAME}} is a platform for friends of <a href=\"https://python.org\">Python</a>\n        (the programming language).<br>\n        It shall enable people to discover, share and discuss interesting thoughts, publications or web pieces about\n        Python and its related fields.<br>\n        On the platform, anybody shall feel welcomed.\n        </p>\n\n\n        <h3>Beautiful is better than ugly.</h3>\n        <p>\n        Be beautiful to each other. Always remember, {{SITE_NAME}} is a community built around Python stuff, which\n        is mostly technical. When discussing this kind of stuff, there is no need to offend someone personally. \n        </p>\n\n        <h3>Explicit is better than implicit.</h3>\n        <p>Be on-topic. We are here to discuss the Python programming language, its ecosystem, its applications and\n        its community. For off-topic discussions there are plenty of forums out there on the net. <br>\n        This community regards political discussions as off-topic, unless discussion the walrus operator (just kidding).</p>\n\n        <h3>In the face of ambiguity, refuse the temptation to guess.</h3>\n        <p>Please think of a contribution of another member of this community as well-intended. We should all assume\n        that people here behave nicely and respectful. </p>\n\n        <!--<h3>Now is better than never.</h3>\n        <p></p>\n\n        <h3>Although never is often better than *right* now.</h3>\n        <p></p>-->\n\n        <h3>Errors should never pass silently.</h3>\n        <p>We value transparency. If there is any action taken by moderators on submissions, comments or user accounts,\n        we try to be as clear about what happened as possible. For now, there is no moderation system in place. This means\n        that we might be forced to delete contributions silently when we notice off-topic, disrespectful or otherwise abusive\n        content without further notice. However, a moderation audit trail is on the roadmap to be implemented soon</p>\n\n\n        <h3>Code of Conduct</h3>\n        <p>This is a news aggregator and we all want to be nice to each other. Rude behaviour in form of continiously spamming,\n        posting off-topic content, offending people ad-hominem, will result in a ban.</p>\n\n        <!--Beautiful is better than ugly.\n        Explicit is better than implicit.\n        Simple is better than complex.\n        Complex is better than complicated.\n        Flat is better than nested.\n        Sparse is better than dense.\n        Readability counts.\n        Special cases aren't special enough to break the rules.\n        Although practicality beats purity.\n        Errors should never pass silently.\n        Unless explicitly silenced.\n        In the face of ambiguity, refuse the temptation to guess.\n        There should be one-- and preferably only one --obvious way to do it.\n        Although that way may not be obvious at first unless you're Dutch.\n        Now is better than never.\n        Although never is often better than *right* now.\n        If the implementation is hard to explain, it's a bad idea.\n        If the implementation is easy to explain, it may be a good idea.\n        Namespaces are one honking great idea -- let's do more of those!-->\n    \n\n</article>\n\n\n\n\n\n\n{% endblock content %}"
  },
  {
    "path": "news/templatetags/__init__.py",
    "content": ""
  },
  {
    "path": "news/templatetags/news_extra.py",
    "content": "from django import template\nfrom django.utils.safestring import mark_safe\n\nimport mistune\n\nregister = template.Library()\n\n@register.inclusion_tag('news/_item_tag.html', takes_context=True)\ndef news_item(context, item, **kwargs):\n    kwargs['item'] = item\n    kwargs['request_user'] = context['user']\n    return kwargs\n\n@register.inclusion_tag('news/_link_user_tag.html')\ndef link_user(user):\n    return {\n        'user': user\n    }\n\n@register.simple_tag\ndef user_arrows(user, item):\n    if user == item.user:\n        return ['star']\n    else:\n        res = []\n        if item.can_be_upvoted_by(user=user):\n            res.append('up')\n        if item.can_be_downvoted_by(user=user):\n            res.append('down')\n        return res\n\n\n@register.inclusion_tag('news/_more_link_tag.html', takes_context=True)\ndef more_link(context):\n    request = context.request\n    page = int(request.GET.get('p', 0))\n    query_dict = request.GET.copy()\n    query_dict['p'] = page + 1\n    _more_link=request.path_info + '?' + query_dict.urlencode()\n    return {'more_link': _more_link}\n\n\n@register.inclusion_tag('news/_item_content_tag.html')\ndef item_content(**kwargs):\n    return kwargs\n\n\n@register.inclusion_tag('news/_item_control_tag.html')\ndef item_control(**kwargs):\n    return kwargs\n\n\nclass MarkdownRenderer(mistune.Renderer):\n\n    @classmethod\n    def setup(cls):\n        renderer = cls(escape=True, hard_wrap=True)\n        return mistune.Markdown(renderer=renderer)\n\n    def header(self, text, level, raw=None):\n        level = min(level + 2, 6)\n        return super().header(text, level, raw)\n\n\nmarkdown = MarkdownRenderer.setup()\n\n@register.filter\ndef comment_markdown(value):\n    return mark_safe(markdown(value))\n"
  },
  {
    "path": "news/tests.py",
    "content": "from django.contrib.auth.models import AnonymousUser\nfrom accounts.models import CustomUser\nfrom django.test import RequestFactory, TestCase\n\nfrom .views import *\nfrom .models import *\n\nclass BasicNewsTest(TestCase):\n    \"\"\"Tests the basic functionality of the news app.\"\"\"\n    def setUp(self):\n        # Every test needs access to the request factory.\n        self.factory = RequestFactory()\n        self.user = CustomUser.objects.create_user(\n            username='sebst', email='hi@seb.st', password='top_secret')\n        self.other_user = CustomUser.objects.create_user(\n            username='bla1', email='two@seb.st', password='top_secret')\n        \n    def test_submit_get(self):\n        \"\"\"The submit form is displayed.\"\"\"\n        request = self.factory.get('/submit')\n        request.user = self.user\n        response = submit(request)\n        self.assertEqual(response.status_code, 200)\n        self.assertContains(response, '<form')\n    \n    def test_submit_post_with_title_and_url(self):\n        \"\"\"Submission is posted with title and URL.\"\"\"\n        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})\n        request.user = self.user\n        response = submit(request)\n        self.assertEqual(response.status_code, 302)\n\n    def test_submit_post_with_title_without_url(self):\n        \"\"\"Submission with only title should fail.\"\"\"\n        request = self.factory.post('/submit', {'title': 'test-post-asdf'})\n        request.user = self.user\n        response = submit(request)\n        self.assertEqual(response.status_code, 200)\n\n    def test_submit_and_frontpage_and_newest(self):\n        \"\"\"A submission should appear on frontpage (as we have an empty database) and on the newest page.\"\"\"\n        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})\n        request.user = self.user\n        response = submit(request)\n\n        request = self.factory.get('/')\n        request.user = self.user\n        response = index(request)\n\n        self.assertContains(response, 'test-post-asdf')\n\n\n        request = self.factory.get('/newest')\n        request.user = self.user\n        response = index(request)\n\n        self.assertContains(response, 'test-post-asdf')\n\n    def test_submit_and_upvote(self):\n        \"\"\"A submission can be upvoted.\"\"\"\n        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})\n        request.user = self.other_user\n        response = submit(request)\n        item_url = response.url\n        pk = item_url.split('/')[-1]\n\n        upvote_url = item_url + \"/upvote\"\n\n        request = self.factory.post(upvote_url, {})\n        request.user = self.user\n        response = upvote(request, pk=pk)\n        self.assertContains(response, \"OK\")\n\n        item = Item.objects.get(pk=pk)\n        self.assertEqual(item.upvotes, 2)\n        self.assertEqual(item.points, 2)\n        #self.assertEqual(self.other_user.karma, 1) # Karma of submitting user should have increased\n        self.assertEqual(item.user.karma, 1) # Karma of submitting user should have increased\n        self.assertEqual(CustomUser.objects.get(pk=self.user.pk).karma, 0) # Karma of voting user should have stayed the same\n\n    def test_submit_and_upvote_and_unvote(self):\n        \"\"\"A submission can be upvoted.\"\"\"\n        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})\n        request.user = self.other_user\n        response = submit(request)\n        item_url = response.url\n        pk = item_url.split('/')[-1]\n\n        upvote_url = item_url + \"/upvote\"\n\n        request = self.factory.post(upvote_url, {})\n        request.user = self.user\n        response = upvote(request, pk=pk)\n        self.assertContains(response, \"OK\")\n\n        item = Item.objects.get(pk=pk)\n        self.assertEqual(item.upvotes, 2)\n        self.assertEqual(item.points, 2)\n        #self.assertEqual(self.other_user.karma, 1) # Karma of submitting user should have increased\n        self.assertEqual(item.user.karma, 1) # Karma of submitting user should have increased\n        self.assertEqual(CustomUser.objects.get(pk=self.user.pk).karma, 0) # Karma of voting user should have stayed the same\n\n        self.fail() # TODO: Test unvote\n\n\n    def test_submit_and_downvote(self):\n        \"\"\"A submission cannot be downvoted.\"\"\"\n        request = self.factory.post('/submit', {'title': 'test-post-asdf-12', 'url': 'https://sebastiansteins.com/12'})\n        request.user = self.other_user\n        response = submit(request)\n        item_url = response.url\n        pk = item_url.split('/')[-1]\n\n        vote_url = item_url + \"/downvote\"\n\n        request = self.factory.post(vote_url, {})\n        request.user = self.user\n        response = downvote(request, pk=pk)\n        self.assertEqual(response.status_code, 403)\n\n\n    def test_submit_and_upvote_self(self):\n        \"\"\"A submission cannot be upvoted by the submitting user.\"\"\"\n        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})\n        request.user = self.user\n        response = submit(request)\n        item_url = response.url\n        pk = item_url.split('/')[-1]\n\n        upvote_url = item_url + \"/upvote\"\n\n        request = self.factory.post(upvote_url, {})\n        request.user = self.user\n        response = upvote(request, pk=pk)\n        self.assertEqual(response.status_code, 403)\n\n\n    def test_ask(self):\n        \"\"\"An Ask Submission should appear in ask.\"\"\"\n        request = self.factory.post('/submit', {'title': 'Ask: test-post-asdf', 'url': 'https://sebastiansteins.com'})\n        request.user = self.user\n        response = submit(request)\n\n        request = self.factory.get('/ask')\n        request.user = self.user\n        response = index(request)\n\n        submission = Item.objects.get()\n        self.assertEqual(submission.is_show, False)\n        self.assertEqual(submission.is_ask, True)\n\n        self.assertContains(response, 'test-post-asdf')\n\n    def test_show(self):\n        \"\"\"A Show Submission should appear in show.\"\"\"\n        request = self.factory.post('/submit', {'title': 'Show: test-post-asdf', 'url': 'https://sebastiansteins.com'})\n        request.user = self.user\n        response = submit(request)\n\n        request = self.factory.get('/show')\n        request.user = self.user\n        response = index(request)\n\n        submission = Item.objects.get()\n        self.assertEqual(submission.is_show, True)\n        self.assertEqual(submission.is_ask, False)\n\n        self.assertContains(response, 'test-post-asdf')\n\n\n    def test_comment(self):\n        \"\"\"A user can comment on a submission.\"\"\"\n        submission = Story(\n            user=self.other_user,\n            title=\"Test-1234\",\n            text=\"bla\"\n        )\n        submission.save()\n        self.assertEqual(Story.objects.get(pk=submission.pk).num_comments, 0)\n\n        request = self.factory.post(submission.get_absolute_url, {'text': 'ACOMMENT'})\n        request.user = self.user\n        response = item(request, pk=submission.pk)\n        self.assertEqual(response.status_code, 302)\n        \n        self.assertEqual(Story.objects.get(pk=submission.pk).num_comments, 1)\n\n        request = self.factory.get('/item/'+str(submission.pk))\n        request.user = self.user\n        response = item(request, pk=submission.pk)\n        self.assertContains(response, \"ACOMMENT\")\n\n        request = self.factory.get('/comments')\n        request.user = self.user\n        response = comments(request)\n        self.assertContains(response, \"ACOMMENT\")\n\n    def test_owner_can_edit_comment(self):\n        _item = Story(title=\"Test story\", user=self.other_user, text='Bla')\n        _item.save()\n\n        comment = Comment(to_story=_item, text='A Comment', user=self.user)\n        comment.save()\n\n        self.assertEqual(comment.text, 'A Comment')\n\n        url = '/item/%s/edit'%(comment.pk)\n        request = self.factory.post(url, {'text': 'B Comment'})\n        request.user = self.user\n        response = item_edit(request, pk=comment.pk)\n        self.assertEqual(response.status_code, 302)\n\n        comment = Comment.objects.get(pk=comment.pk)\n        self.assertEqual(comment.text, 'B Comment')\n\n\n    def test_owner_cannot_edit_comment_with_children(self):\n        _item = Story(title=\"Test story\", user=self.other_user, text='Bla')\n        _item.save()\n\n        comment = Comment(to_story=_item, text='A Comment', user=self.user)\n        comment.save()\n\n        comment2 = Comment(to_story=_item, text='XXXX', user=self.user, parent=comment)\n        comment2.save()\n\n        self.assertEqual(comment.text, 'A Comment')\n\n        url = '/item/%s/edit'%(comment.pk)\n        request = self.factory.post(url, {'text': 'B Comment'})\n        request.user = self.user\n        response = item_edit(request, pk=comment.pk)\n        self.assertEqual(response.status_code, 403)\n\n        comment = Comment.objects.get(pk=comment.pk)\n        self.assertEqual(comment.text, 'A Comment')\n\n\n    def test_owner_can_edit_story(self):\n        _item = Story(title=\"Test story\", user=self.user, text='Bla')\n        _item.save()\n\n        self.assertEqual(_item.text, 'Bla')\n\n        url = '/item/%s/edit'%(_item.pk)\n        request = self.factory.post(url, {'text': 'B Comment'})\n        request.user = self.user\n        response = item_edit(request, pk=_item.pk)\n        self.assertEqual(response.status_code, 302)\n\n        _item = Story.objects.get(pk=_item.pk)\n        self.assertEqual(_item.text, 'B Comment')\n\n\n    def test_owner_cannot_edit_story_url(self):\n        _item = Story(title=\"Test story\", user=self.user, text='Bla', url=\"https://test1.example.org\")\n        _item.save()\n\n        self.assertEqual(_item.text, 'Bla')\n\n        url = '/item/%s/edit'%(_item.pk)\n        request = self.factory.post(url, {'url': 'https://example.org'})\n        request.user = self.user\n        response = item_edit(request, pk=_item.pk)\n        self.assertEqual(response.status_code, 302)\n\n        _item = Story.objects.get(pk=_item.pk)\n        self.assertEqual(_item.url, 'https://test1.example.org')\n\n\n    def test_owner_cannot_edit_story_with_comments(self):\n        _item = Story(title=\"Test story\", user=self.user, text='Bla')\n        _item.save()\n\n        comment = Comment(to_story=_item, text='A Comment', user=self.user)\n        comment.save()\n\n        self.assertEqual(_item.text, 'Bla')\n\n        url = '/item/%s/edit'%(_item.pk)\n        request = self.factory.post(url, {'text': 'B Comment'})\n        request.user = self.user\n        response = item_edit(request, pk=_item.pk)\n        self.assertEqual(response.status_code, 403)\n\n        _item = Story.objects.get(pk=_item.pk)\n        self.assertEqual(_item.text, 'Bla')\n\n\n    def test_other_cannot_edit_comment(self):\n        _item = Story(title=\"Test story\", user=self.other_user, text='Bla')\n        _item.save()\n\n        comment = Comment(to_story=_item, text='A Comment', user=self.user)\n        comment.save()\n\n        self.assertEqual(comment.text, 'A Comment')\n\n        url = '/item/%s/edit'%(comment.pk)\n        request = self.factory.post(url, {'text': 'B Comment'})\n        request.user = self.other_user\n        response = item_edit(request, pk=comment.pk)\n        self.assertEqual(response.status_code, 403)\n\n        comment = Comment.objects.get(pk=comment.pk)\n        self.assertEqual(comment.text, 'A Comment')\n\n    def test_other_cannot_edit_story(self):\n        _item = Story(title=\"Test story\", user=self.user, text='Bla')\n        _item.save()\n\n        self.assertEqual(_item.text, 'Bla')\n\n        url = '/item/%s/edit'%(_item.pk)\n        request = self.factory.post(url, {'text': 'B Comment'})\n        request.user = self.other_user\n        response = item_edit(request, pk=_item.pk)\n        self.assertEqual(response.status_code, 403)\n\n        _item = Story.objects.get(pk=_item.pk)\n        self.assertEqual(_item.text, 'Bla')\n\n    def test_owner_can_delete_comment(self):\n        story = Story(title='A story', user=self.user, url=\"https://example.org\")\n        story.save()\n\n        comment = Comment(to_story=story, user=self.user, text=\"a comment\")\n        comment.save()\n\n        url = '/item/%s/delete'%(comment.pk)\n        request = self.factory.get(url)\n        request.user = self.user\n        response = item_delete(request, pk=comment.pk)\n        self.assertContains(response, 'sure')\n\n        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)\n\n        request = self.factory.post(url)\n        request.user = self.user\n        response = item_delete(request, pk=comment.pk)\n        self.assertEqual(response.status_code, 302)\n        self.assertEqual(response.url, story.get_absolute_url())\n\n        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 0)\n\n\n    def test_owner_cannot_delete_comment_with_children(self):\n        story = Story(title='A story', user=self.user, url=\"https://example.org\")\n        story.save()\n\n        comment = Comment(to_story=story, user=self.user, text=\"a comment\")\n        comment.save()\n\n        comment2 = Comment(to_story=story, user=self.user, text=\"another comment\", parent=comment)\n        comment2.save()\n\n        url = '/item/%s/delete'%(comment.pk)\n        request = self.factory.get(url)\n        request.user = self.user\n        response = item_delete(request, pk=comment.pk)\n        self.assertEqual(response.status_code, 403)\n\n        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)\n\n        request = self.factory.post(url)\n        request.user = self.user\n        response = item_delete(request, pk=comment.pk)\n        self.assertEqual(response.status_code, 403)\n\n        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)\n\n\n    def test_owner_can_delete_story(self):\n        story = Story(title='A story', user=self.user, url=\"https://example.org\")\n        story.save()\n\n\n        url = '/item/%s/delete'%(story.pk)\n        request = self.factory.get(url)\n        request.user = self.user\n        response = item_delete(request, pk=story.pk)\n        self.assertContains(response, 'sure')\n\n        self.assertEqual(Story.objects.filter(pk=story.pk).count(), 1)\n\n        request = self.factory.post(url)\n        request.user = self.user\n        response = item_delete(request, pk=story.pk)\n        self.assertEqual(response.status_code, 302)\n        self.assertEqual(response.url, '/')\n\n        self.assertEqual(Story.objects.filter(pk=story.pk).count(), 0)\n\n\n    def test_other_cannot_delete_comment(self):\n        story = Story(title='A story', user=self.user, url=\"https://example.org\")\n        story.save()\n\n        comment = Comment(to_story=story, user=self.user, text=\"a comment\")\n        comment.save()\n\n        url = '/item/%s/delete'%(comment.pk)\n        request = self.factory.get(url)\n        request.user = self.other_user\n        response = item_delete(request, pk=comment.pk)\n        self.assertEqual(response.status_code, 403)\n\n        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)\n\n        request = self.factory.post(url)\n        request.user = self.other_user\n        response = item_delete(request, pk=comment.pk)\n        self.assertEqual(response.status_code, 403)\n\n        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)\n\n\n    def test_other_cannot_delete_story(self):\n        story = Story(title='A story', user=self.user, url=\"https://example.org\")\n        story.save()\n\n        url = '/item/%s/delete'%(story.pk)\n        request = self.factory.get(url)\n        request.user = self.other_user\n        response = item_delete(request, pk=story.pk)\n        self.assertEqual(response.status_code, 403)\n\n        self.assertEqual(Story.objects.filter(pk=story.pk).count(), 1)\n\n        request = self.factory.post(url)\n        request.user = self.other_user\n        response = item_delete(request, pk=story.pk)\n        self.assertEqual(response.status_code, 403)\n\n        self.assertEqual(Story.objects.filter(pk=story.pk).count(), 1)\n\n\n    def test_zen(self):\n        s = 'The Zen of'\n        url = '/zen'\n        request = self.factory.get(url)\n        request.user = self.user\n        response = zen(request)\n        self.assertContains(response, s)\n\n\n    def test_comments(self):\n        url = '/comments'\n        request = self.factory.get(url)\n        request.user = self.user\n        response = comments(request)\n        self.assertEqual(response.status_code, 200)\n\n    def test_threads(self):\n        url = '/threads'\n        request = self.factory.get(url)\n        request.user = self.user\n        response = threads(request)\n        self.assertEqual(response.status_code, 200)\n\n    def test_newest(self):\n        url = '/newest'\n        request = self.factory.get(url)\n        request.user = self.user\n        response = newest(request)\n        self.assertEqual(response.status_code, 200)\n\n    def test_front_page(self):\n        url = '/'\n        request = self.factory.get(url)\n        request.user = self.user\n        response = index(request)\n        self.assertEqual(response.status_code, 200)\n\n    def test_more_button(self):\n        self.fail() # TODO\n\n\nclass ReceiversNewsTest(TestCase):\n    \"\"\"Tests the basic functionality of the news app.\"\"\"\n    def setUp(self):\n        # Every test needs access to the request factory.\n        self.factory = RequestFactory()\n        self.user = CustomUser.objects.create_user(\n            username='sebst', email='hi@seb.st', password='top_secret')\n        self.other_user = CustomUser.objects.create_user(\n            username='bla1', email='two@seb.st', password='top_secret')\n\n\n    def test_mark_show_and_ask(self):\n        story = Story(title=\"Ask: Some ask story\", text=\"..\", user=self.user)\n        self.assertEqual(story.is_ask, False)\n        story.save()\n        story = Story.objects.get(pk=story.pk)\n        self.assertEqual(story.is_ask, True)\n\n        story = Story(title=\"Show: Some show story\", text=\"..\", user=self.user)\n        self.assertEqual(story.is_show, False)\n        story.save()\n        story = Story.objects.get(pk=story.pk)\n        self.assertEqual(story.is_show, True)\n\n\n    def test_create_self_upvote_for_submission(self):\n        story = Story(title=\"Some story\", text=\"..\", user=self.user)\n        self.assertEqual(Vote.objects.filter(item=story).count(), 0)\n        story.save()\n        self.assertEqual(Vote.objects.filter(item=story).count(), 1)\n\n\n    def test_check_for_duplicates(self):\n        story = Story(title=\"Some story\", url=\"http://example.org\", user=self.user)\n        story.save()\n\n        story2 = Story(title=\"Once again\", url=\"http://example.org\", user=self.other_user)\n        story2.save()\n\n        story = Story.objects.get(pk=story.pk)\n        story2 = Story.objects.get(pk=story2.pk)\n        self.assertEqual(story.duplicate_of, None)\n        # Duplicate story needs to be marked as duplicate\n        self.assertEqual(story2.duplicate_of, story)\n        # Second submission triggers upvote on original story\n        self.assertEqual(Vote.objects.filter(item=story).count(), 2)\n\n\n    def test_update_votes_count_on_submission(self):\n        story = Story(title=\"Some story\", url=\"http://example.org\", user=self.user)\n        story.save()\n\n        self.assertEqual(Vote.objects.filter(item=story).count(), 1)\n\n        vote = Vote(user=self.user, vote=1, item=story)\n        vote.save()\n        story = Story.objects.get(pk=story.pk)\n\n        self.assertEqual(story.upvotes, 1)\n        self.assertEqual(story.points, 1)\n        self.assertEqual(story.downvotes, 0)\n\n        vote2 = Vote(user=self.other_user, vote=-1, item=story)\n        vote2.save()\n        story = Story.objects.get(pk=story.pk)\n\n        self.assertEqual(story.upvotes, 1)\n        self.assertEqual(story.points, 0)\n        self.assertEqual(story.downvotes, 1)\n\n\n\n    def test_update_user_karma_on_vote(self):\n        story = Story(title=\"Some story\", url=\"http://example.org\", user=self.user)\n        story.save()\n\n        user = CustomUser.objects.get(pk=self.user.pk)\n        self.assertEqual(user.karma, 0)\n\n        vote2 = Vote(user=self.other_user, vote=1, item=story)\n        vote2.save()\n        story = Story.objects.get(pk=story.pk)\n        user = CustomUser.objects.get(pk=self.user.pk)\n\n        self.assertEqual(user.karma, 1)\n\n\n    def test_update_comments_count_on_submission(self):\n        story = Story(title=\"Some story\", url=\"http://example.org\", user=self.user)\n        story.save()\n\n        story = Story.objects.get(pk=story.pk)\n        self.assertEqual(story.num_comments, 0)\n\n        comment1 = Comment(to_story=story, text=\"...\", user=self.other_user)\n        comment1.save()\n\n        story = Story.objects.get(pk=story.pk)\n        self.assertEqual(story.num_comments, 1)\n\n        comment2 = Comment(to_story=story, text=\"...\", user=self.user, parent=comment1)\n        comment2.save()\n\n        story = Story.objects.get(pk=story.pk)\n        self.assertEqual(story.num_comments, 2)\n\n\n    def test_update_comments_count_on_deletion(self):\n        story = Story(title=\"Some story\", url=\"http://example.org\", user=self.user)\n        story.save()\n\n        story = Story.objects.get(pk=story.pk)\n        self.assertEqual(story.num_comments, 0)\n\n        comment1 = Comment(to_story=story, text=\"...\", user=self.other_user)\n        comment1.save()\n\n        story = Story.objects.get(pk=story.pk)\n        self.assertEqual(story.num_comments, 1)\n\n        comment2 = Comment(to_story=story, text=\"...\", user=self.user, parent=comment1)\n        comment2.save()\n\n        story = Story.objects.get(pk=story.pk)\n        self.assertEqual(story.num_comments, 2)\n\n        comment1.delete()\n        story = Story.objects.get(pk=story.pk)\n        self.assertEqual(story.num_comments, 0)\n\n\n    def test_update_item_votes_on_unvote(self):\n        story = Story(title=\"Some story\", url=\"http://example.org\", user=self.user)\n        story.save()\n\n        self.assertEqual(Vote.objects.filter(item=story).count(), 1)\n\n        vote = Vote(user=self.user, vote=1, item=story)\n        vote.save()\n        story = Story.objects.get(pk=story.pk)\n\n        self.assertEqual(story.upvotes, 1)\n        self.assertEqual(story.points, 1)\n        self.assertEqual(story.downvotes, 0)\n\n        vote2 = Vote(user=self.other_user, vote=-1, item=story)\n        vote2.save()\n        story = Story.objects.get(pk=story.pk)\n\n        self.assertEqual(story.upvotes, 1)\n        self.assertEqual(story.points, 0)\n        self.assertEqual(story.downvotes, 1)\n\n        vote2.delete()\n\n        story = Story.objects.get(pk=story.pk)\n\n        self.assertEqual(story.upvotes, 1)\n        self.assertEqual(story.points, 1)\n        self.assertEqual(story.downvotes, 0)\n\n\n    def test_update_user_karma_on_unvote(self):\n        story = Story(title=\"Some story\", url=\"http://example.org\", user=self.user)\n        story.save()\n\n        user = CustomUser.objects.get(pk=self.user.pk)\n        self.assertEqual(user.karma, 0)\n\n        vote2 = Vote(user=self.other_user, vote=1, item=story)\n        vote2.save()\n        story = Story.objects.get(pk=story.pk)\n\n        user = CustomUser.objects.get(pk=self.user.pk)\n        self.assertEqual(user.karma, 1)\n\n        vote2.delete()\n        user = CustomUser.objects.get(pk=self.user.pk)\n        self.assertEqual(user.karma, 0)\n\n\n    def test_add_domain_to_link_stories(self):\n        item = Story('title': 'bla', url='https://Example.org', user=self.user)\n        item.save()\n\n        item = Story.objects.get(pk=item.pk)\n        self.assertEqual(item.domain, 'example.org')"
  },
  {
    "path": "news/urls.py",
    "content": "\n\nfrom django.urls import path, include\n\nfrom . import views\n\nfrom .feeds import NewestFeed, FrontPageFeed\n\nurlpatterns = [\n    path('', views.index, name=\"index\"),\n    path('newest', views.newest, name=\"newest\"),\n    path('threads', views.threads, name=\"threads\"),\n    path('comments', views.comments, name=\"comments\"),\n    path('show', views.show, name=\"show\"),\n    path('ask', views.ask, name=\"ask\"),\n    path('zen', views.zen, name=\"zen\"),\n    path('item/<uuid:pk>', views.item, name=\"item\"),\n    path('item/<uuid:pk>/upvote', views.upvote, name=\"upvote\"), # TODO\n    path('item/<uuid:pk>/downvote', views.downvote, name=\"downvote\"), # TODO\n    path('item/<uuid:pk>/edit', views.item_edit, name=\"edit\"),\n    path('item/<uuid:pk>/delete', views.item_delete, name=\"delete\"),\n    path('submit', views.submit, name=\"submit\"),\n\n    path('newest/feed/', NewestFeed()),\n    path('feed/', FrontPageFeed()),\n\n    path('robots.txt', views.robots_txt, name=\"robots_txt\"),\n    path('humans.txt', views.humans_txt, name=\"humans_txt\"),\n    path('bookmarklet', views.bookmarklet, name=\"bookmarklet\"),\n]\n"
  },
  {
    "path": "news/views.py",
    "content": "from django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponseForbidden\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse\n\nfrom .models import Item, Story, Comment, Vote\nfrom accounts.models import CustomUser\nfrom .forms import CommentForm, AddStoryForm, StoryForm\n\nfrom ratelimit.decorators import ratelimit\n\n\n# create_story\n# add_comment\n# upvote / downvote / unvote\n# flag / hide\n# Tags?\n# suggest changes\n# save\n\n\nDEFAULT_GET_RATE   = \"2/s\"\nDEFAULT_VOTES_RATE = \"10/m\"\nDEFAULT_POST_RATE  = \"5/m\"\n\nTIMEOUT_MEDIUM = 0# 1*60 # one minute\nTIMEOUT_SHORT  = 0# 1*2 # two seconds\n\n\nfrom django.db.models.functions import Power, Now, Cast, Extract #, Min\nfrom django.db.models import Value, F, Func, ExpressionWrapper, fields, Q, Min\nfrom django.db.models import OuterRef, Subquery\nfrom django.db import models\nfrom django.utils import timezone\nimport datetime\n\nfrom django.core.cache import cache\nfrom django.views.decorators.vary import vary_on_cookie\nfrom django.views.decorators.cache import cache_page\n\nfrom django.db import connection\n\n\ndef _one_page_back(request):\n    page = int(request.GET.get('p', 0))\n    query_dict = request.GET.copy()\n    page = page - 1\n    if page >= 0:\n        query_dict['p'] = page\n    else:\n        return None\n    _more_link=request.path_info + '?' + query_dict.urlencode()\n    return HttpResponseRedirect(_more_link)\n\ndef _front_page(paging_size=settings.PAGING_SIZE, page=0, add_filter={}, add_q=[], as_of=None, days_back=50):\n    # TODO: weighting https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d\n    # (P-1) / (T+2)^G\n    if as_of is None:\n        now = timezone.now()\n    else:\n        now = as_of\n    if connection.vendor == 'postgresql':\n        now_value = Value(now, output_field=fields.DateTimeField())\n        submission_age_float = ExpressionWrapper(  ( now_value - F('created_at')), output_field=fields.DurationField())\n        submission_age_hours = ExpressionWrapper(Extract(F('tf'), 'epoch') / 60 / 60 + 2.1 , output_field=fields.FloatField())\n        real_p = ExpressionWrapper(F('points') - 1, output_field=fields.FloatField())\n        formula = ExpressionWrapper(   F('p') / ( Power(F('tfh'), F('g'))  +0.001)   , output_field=fields.FloatField())\n        return Story.objects.select_related('user')\\\n                .filter(duplicate_of__isnull=True)\\\n                .filter(points__gte=1) \\\n                .filter(created_at__gte=now - datetime.timedelta(days=days_back)) \\\n                .filter(created_at__lte=now) \\\n                .filter(**add_filter) \\\n                .annotate(tf=submission_age_float) \\\n                .annotate(tfh=submission_age_hours) \\\n                .annotate(p=real_p) \\\n                .annotate(g=Value(1.8, output_field=fields.FloatField())) \\\n                .annotate(formula=formula) \\\n                .order_by('-formula')[(page*paging_size):(page+1)*(paging_size)]\n    elif connection.vendor == 'sqlite':\n        now_value = Value(now, output_field=fields.DateTimeField())\n        submission_age_float = ExpressionWrapper(  ( now_value - F('created_at')), output_field=fields.FloatField())\n        submission_age_hours = ExpressionWrapper(F('tf') / 60 / 60 / 1000000 + 2.1 , output_field=fields.FloatField())\n        real_p = ExpressionWrapper(F('points') - 1, output_field=fields.FloatField())\n        formula = ExpressionWrapper(   F('p') / ( Power(F('tfh'), F('g'))  +0.001)   , output_field=fields.FloatField())\n        return Story.objects.select_related('user')\\\n                .filter(duplicate_of__isnull=True)\\\n                .filter(points__gte=1) \\\n                .filter(created_at__gte=now - datetime.timedelta(days=days_back)) \\\n                .filter(created_at__lte=now) \\\n                .filter(**add_filter) \\\n                .annotate(tf=submission_age_float) \\\n                .annotate(tfh=submission_age_hours) \\\n                .annotate(p=real_p) \\\n                .annotate(g=Value(1.8, output_field=fields.FloatField())) \\\n                .annotate(formula=formula) \\\n                .order_by('-formula')[(page*paging_size):(page+1)*(paging_size)]\n    else: \n        raise NotImplementedError(\"No frontpage magic for database engine %s implemented\"%(connection.vendor))\n\n\ndef _newest(paging_size=settings.PAGING_SIZE, page=0, add_filter={}, add_q=[]):\n    return Story.objects \\\n                .select_related('user') \\\n                .filter(duplicate_of__isnull=True) \\\n                .filter(**add_filter) \\\n                .filter(*add_q) \\\n                .order_by('-created_at')[(page*paging_size):(page+1)*(paging_size)]\n\n\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, block=True)\ndef index(request):\n    page = int(request.GET.get('p', 0))\n    stories = cache.get_or_set(\"news-index-%s\"%(page), lambda: list(_front_page(page=page)), timeout=TIMEOUT_MEDIUM) # one minute\n    if len(stories) < 1 and page != 0:\n        back = _one_page_back(request)\n        if back:\n            return back\n    return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})\n\n\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, block=True)\ndef show(request):\n    page = int(request.GET.get('p', 0))\n    stories = cache.get_or_set(\"news-show-%s\"%(page), lambda: list(_front_page(page=page, add_filter={'is_show': True})), timeout=TIMEOUT_MEDIUM) # one minute\n    if len(stories) < 1 and page != 0:\n        back = _one_page_back(request)\n        if back:\n            return back\n    return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})\n\n\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, block=True)\ndef ask(request):\n    page = int(request.GET.get('p', 0))\n    stories = lambda: list(_front_page(page=page, add_filter={'is_ask': True}))\n    stories = cache.get_or_set(\"news-ask-%s\"%(page), stories, timeout=TIMEOUT_MEDIUM) # one minute\n    if len(stories) < 1 and page != 0:\n        back = _one_page_back(request)\n        if back:\n            return back\n    return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})\n\n\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, block=True)\ndef newest(request): # Done\n    page = int(request.GET.get('p', 0))\n    add_filter = {}\n    add_q = []\n    if 'submitted_by' in request.GET.keys():\n        try:\n            submitted_by = CustomUser.objects.get_by_natural_key(request.GET['submitted_by'])\n            add_filter['user'] = submitted_by\n        except CustomUser.DoesNotExist:\n            raise Http404()\n    if 'upvoted_by' in request.GET.keys():\n        try:\n            assert request.user.is_authenticated\n            assert request.user.username == request.GET['upvoted_by']\n        except AssertionError:\n            return HttpResponseForbidden()\n        add_filter['pk__in'] = Vote.objects.filter(vote=1, user=request.user).values('item')\n        add_q.append(~Q(user=request.user))\n    if 'site' in request.GET.keys():\n        add_filter['domain'] = request.GET['site']\n    stories = lambda: list(_newest(page=page, add_filter=add_filter, add_q=add_q))\n    stories = cache.get_or_set(\"news-newest-%s\"%(page), stories, timeout=TIMEOUT_SHORT) # two seconds\n    if len(stories) < 1 and page != 0:\n        back = _one_page_back(request)\n        if back:\n            return back\n    return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})\n\n\n@login_required\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, block=True)\n@cache_page(TIMEOUT_SHORT)\n@vary_on_cookie\ndef threads(request):\n    page = int(request.GET.get('p', 0))\n    paging_size = settings.PAGING_SIZE\n    tree = Comment.objects.filter( tree_id=OuterRef('tree_id'), user=OuterRef('user')).values('tree_id', 'user__pk').annotate(min_level=Min('level')).order_by()\n    stories = Comment.objects.filter(\n        user=request.user\n    ).filter(\n        Q(level__in=Subquery(tree.values('min_level'), output_field=models.IntegerField()))  # TODO: level= or level__in= ???\n    ).select_related(\n        'user', 'parent', 'to_story'\n    ).order_by(\n        '-created_at'\n    )[(page*paging_size):(page+1)*(paging_size)]\n    if len(stories) < 1 and page != 0:\n        back = _one_page_back(request)\n        if back:\n            return back\n    return render(request, 'news/index.html', {'stories': stories, 'hide_text':False, 'page': page, 'rank_start': None, 'show_children': True})\n\n\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, block=True)\n@cache_page(TIMEOUT_SHORT)\n@vary_on_cookie\ndef comments(request): # TODO\n    page = int(request.GET.get('p', 0))\n    paging_size = settings.PAGING_SIZE\n    add_filter = {}\n    if 'submitted_by' in request.GET.keys():\n        try:\n            submitted_by = CustomUser.objects.get_by_natural_key(request.GET['submitted_by'])\n            add_filter['user'] = submitted_by\n        except CustomUser.DoesNotExist:\n            raise Http404()\n    if 'upvoted_by' in request.GET.keys():\n        try:\n            assert request.user.is_authenticated\n            assert request.user.username == request.GET['upvoted_by']\n        except AssertionError:\n            return HttpResponseForbidden()\n        add_filter['pk__in'] = Vote.objects.filter(vote=1, user=request.user).values('item')\n    stories = Comment.objects.filter(\n        parent=None\n    ).filter(\n        **add_filter\n    ).select_related(\n        'user', 'parent', 'to_story'\n    ).order_by(\n        'created_at'\n    )[(page*paging_size):(page+1)*(paging_size)]\n    if len(stories) < 1 and page != 0:\n        back = _one_page_back(request)\n        if back:\n            return back\n    return render(request, 'news/index.html', {'stories': stories, 'hide_text':False, 'page': page, 'rank_start': page*paging_size})\n\n\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, block=True)\ndef zen(request):\n    return render(request, 'news/zen.html')\n\n\ndef _vote(request, pk, vote=None, unvote=False):\n    assert not unvote and vote is not None or unvote and vote is None\n    item = get_object_or_404(Item, pk=pk)\n    if (not unvote) and (vote is not None):\n        votes = Vote.objects.filter(item=item, user=request.user)\n        if request.method==\"POST\":\n            if vote > 0:\n                if not item.can_be_upvoted_by(request.user):\n                    return HttpResponseForbidden()\n            else:\n                if not item.can_be_downvoted_by(request.user):\n                    return HttpResponseForbidden()\n            vote = Vote(vote=vote, item=item, user=request.user)\n            vote.save()\n            return HttpResponse(\"OK %s\"%(vote.pk))\n    if unvote:\n        if request.method==\"POST\":\n            Vote.objects.filter(item=item, user=request.user).delete()\n            return HttpResponse(\"OK\")\n\n\n@login_required\n@ratelimit(key=\"user_or_ip\", group=\"news-votes\", rate=DEFAULT_VOTES_RATE, block=True)\ndef upvote(request, pk):\n    return _vote(request, pk, vote=1)\n\n\n@login_required\n@ratelimit(key=\"user_or_ip\", group=\"news-votes\", rate=DEFAULT_VOTES_RATE, block=True)\ndef downvote(request, pk):\n    return _vote(request, pk, vote=-1)\n\n\n@login_required\n@ratelimit(key=\"user_or_ip\", group=\"news-votes\", rate=DEFAULT_VOTES_RATE, block=True)\ndef unvote(request, pk):\n    return _vote(request, pk, vote=None, unvote=True)\n\n\ndef flag(request):\n    pass\n\n\ndef save(request):\n    pass\n\n\ndef _item_story_comment(pk):\n    try: \n        # .prefetch_related('children', 'parent')\n        item = Item.objects.select_related('story', 'comment', 'user', 'parent').prefetch_related('children').get(pk=pk)\n    except Exception as e:\n        raise e\n    try:\n        story = item.story\n        comment = None\n        item = story\n    except Item.story.RelatedObjectDoesNotExist:\n        story = None\n        comment = None\n    try:\n        comment = item.comment\n        story = comment.to_story\n        item = comment\n    except Item.comment.RelatedObjectDoesNotExist:\n        pass\n    assert story is not None\n    return item, story, comment\n\n\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, method=['GET'], block=True)\n@ratelimit(key=\"user_or_ip\", group=\"news-post\", rate=DEFAULT_POST_RATE, method=['POST'], block=True)\ndef item(request, pk): # DONE\n    item, story, comment = _item_story_comment(pk)\n    if story == item:\n        if story.duplicate_of is not None:\n            return HttpResponseRedirect(story.duplicate_of.get_absolute_url())\n    if request.user.is_authenticated:\n        parent = None if story==item else item\n        comment_instance = Comment(user=request.user, to_story=story, parent=parent)\n        comment_form = CommentForm(request.POST or None, instance=comment_instance)\n        if request.method == 'POST':\n            if comment_form.is_valid():\n                comment = comment_form.save()\n                return HttpResponseRedirect(story.get_absolute_url() + '#' + str(comment.pk))\n    else:\n        comment_form = None\n    return render(request, 'news/item.html', {'item': item, 'comment_form': comment_form})\n\n\n@login_required\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, method=['GET'], block=True)\n@ratelimit(key=\"user_or_ip\", group=\"news-post\", rate=DEFAULT_POST_RATE, method=['POST'], block=True)\ndef item_edit(request, pk):\n    item, story, comment = _item_story_comment(pk)\n    if not item.can_be_edited_by(request.user):\n        return HttpResponseForbidden()\n    if story == item:\n        if story.duplicate_of is not None:\n            return HttpResponseRedirect(story.duplicate_of.get_absolute_url())\n    if comment is not None:\n        form = CommentForm(request.POST or None, instance=item)\n    else:\n        assert story is not None\n        form = StoryForm(request.POST or None, instance=item)\n    assert form is not None\n    if request.method==\"POST\":\n        if form.is_valid():\n            item = form.save()\n            return HttpResponseRedirect(story.get_absolute_url() + '#' + str(item.pk))\n    return render(request, 'news/item_edit.html', {'item': item, 'edit_form': form})\n\n\n@login_required\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, method=['GET'], block=True)\n@ratelimit(key=\"user_or_ip\", group=\"news-post\", rate=DEFAULT_POST_RATE, method=['POST'], block=True)\ndef item_delete(request, pk):\n    item, story, comment = _item_story_comment(pk)\n    if not item.can_be_deleted_by(request.user):\n        return HttpResponseForbidden()\n    if request.method == \"POST\":\n        redirect_url = '/'\n        if comment is not None:\n            redirect_url = item.to_story.get_absolute_url()\n        item.delete()\n        return HttpResponseRedirect(redirect_url)\n    return render(request, 'news/item_delete.html', {'item': item})\n\n\n@login_required\n@ratelimit(key=\"user_or_ip\", group=\"news-get\", rate=DEFAULT_GET_RATE, method=['GET'], block=True)\n@ratelimit(key=\"user_or_ip\", group=\"news-post\", rate=DEFAULT_POST_RATE, method=['POST'], block=True)\ndef submit(request): # DONE\n    instance = Story(user=request.user)\n    form = AddStoryForm(request.POST or None, initial={\n        'title': request.GET.get('t'),\n        'url': request.GET.get('u'),\n        'text': request.GET.get('x'),\n    }, instance=instance)\n    if request.method==\"POST\":\n        if form.is_valid():\n            instance = form.save()\n            return HttpResponseRedirect(instance.get_absolute_url())\n    return render(request, 'news/submit.html', {'form': form})\n\n\ndef robots_txt(request):\n    return HttpResponse(\"\"\"\nUser-agent: *\nDisallow: \n    \"\"\", content_type='text/plain')\n\ndef humans_txt(request):\n    return HttpResponse(\"\"\"\n🐍\n    \"\"\", content_type='text/plain', charset='utf-8')\n\n\ndef bookmarklet(request):\n    return render(request, 'news/bookmarklet.html')\n"
  },
  {
    "path": "requirements.txt",
    "content": "appnope==0.1.0\naws-psycopg2==1.1.1\nawsebcli==3.15.3\nbackcall==0.1.0\nbeautifulsoup4==4.8.0\nblessed==1.15.0\nbotocore==1.12.238\ncached-property==1.5.1\ncement==2.8.2\ncertifi==2019.9.11\nchardet==3.0.4\ncolorama==0.3.9\ncoverage==4.5.4\ndecorator==4.4.0\nDjango==2.2.5\ndjango-debug-toolbar==2.0\ndjango-htmlmin==0.11.0\ndjango-js-asset==1.2.2\ndjango-mptt==0.10.0\ndjango-ratelimit==2.0.0\ndocker==3.7.3\ndocker-compose==1.23.2\ndocker-pycreds==0.4.0\ndockerpty==0.4.1\ndocopt==0.6.2\ndocutils==0.15.2\nfuture==0.16.0\nhtml5lib==1.0.1\nidna==2.7\nipython==7.8.0\nipython-genutils==0.2.0\njedi==0.15.1\njmespath==0.9.4\njsonschema==2.6.0\nMarkdown==3.1.1\nmistune==0.8.4\nparso==0.5.1\npathspec==0.5.9\npexpect==4.7.0\npickleshare==0.7.5\nprompt-toolkit==2.0.9\nptyprocess==0.6.0\nPygments==2.4.2\npython-dateutil==2.8.0\npytz==2019.2\nPyYAML==3.13\nrequests==2.20.1\nsemantic-version==2.5.0\nsix==1.11.0\nsoupsieve==1.9.3\nsqlparse==0.3.0\ntermcolor==1.1.0\ntexttable==0.9.1\ntraitlets==4.3.2\nurllib3==1.24.3\nwcwidth==0.1.7\nwebencodings==0.5.1\nwebsocket-client==0.56.0\n"
  },
  {
    "path": "static/news.css",
    "content": "/*\n\nhttps://www.schemecolor.com/python-logo-colors.php\nCyan-Blue Azure     #4B8BBE\nLapis Lazuli        #306998\nShandy              #FFE873\nSunglow             #FFD43B\nGranite Gray        #646464\n\n\n*/\n/* https://encycolorpedia.com/646464 */\n\n/* General formatting */\n\nbody        { font-family:Verdana, Geneva, sans-serif; font-size:10pt; color:#646464; }\ntd          { font-family:Verdana, Geneva, sans-serif; font-size:10pt; color:#646464; }\n.smaller    { font-size:7pt; }\n\ninput       { font-family:monospace; font-size:10pt; }\ninput[type=\\\"submit\\\"] { font-family:Verdana, Geneva, sans-serif; }\ntextarea    { font-family:monospace; font-size:10pt; }\n\n.clearfix { overflow: hidden; clear: both }\n\np.small { margin: 5px 0; }\n\nul.horizontal-list {\n    list-style: none;\n    margin: 0;\n    padding: 0;\n}\n\nul.horizontal-list li {\n    display: inline-block;\n}\n\nbutton { padding: 0.25em; }\n\na { color: inherit; }\n.green { color:green; }\n\nnav#top-bar { background-color:#306998; }\nnav#footer-bar { background-color:#FFD43B; }\nmain { background-color: #EDF3F9; }\nnav#top-bar * { color:#FFE873; }\n\n.site-content { margin: 3%; }\n.site-content-dense  { margin: 1%; }\ntd {padding-right:8px; vertical-align: text-top;}\n#top-bar td {vertical-align: middle;}\ntr.spacer {height:1em;}\n\n.highlight {background-color:#FFE873;}\n.self-item {color: #4B8BBE;}\n\n.title > a {\n    text-decoration: none;\n}\n\n.title > a:visited {\n    color: #999;\n}\n\n/* td {border:1px solid red;} */\n\n/* Site layout */\n\nnav#top-bar *.active {\n    color: #FFD43B;\n    font-weight: bold;\n}\n\n#pnmain {\n    width: 85%;\n    margin: auto;\n}\n\nnav#pre-footer-bar > hr {\n    border-top: 2px solid #306998;\n    width: 95%;\n}\n\n\n\n/* Item Layout */\n\n\n\n/* Forms */\n\nform.logout-form {\n    border: 0;\n    margin:0;\n    padding:0;\n    display:inline;\n}\n\n.logout-button {\n    margin:0;\n    border:0;\n    padding:0;\n    background: transparent;\n    text-decoration: underline;\n    font-family:Verdana, Geneva, sans-serif; font-size:10pt;\n    cursor: pointer;\n}\n\nform.comment-form {\n    padding: 20px;\n}\n\nform.comment-form textarea {\n    width: 50%;\n    resize: vertical;\n}\n\nform.comment-form button {\n    float: left;\n    margin-right: 10px;\n}\n\nform.comment-form ul {\n    float: left;\n}\n\n.vote-form {\n    border: 0;\n    margin:0;\n    padding:0;\n}\n\n.vote-button {\n    background:transparent;\n    display:block;\n    padding:0;\n    padding-top:4px;\n    /* border: 1px solid red; */\n    border:0;\n}\n\n/* http://apps.eky.hk/css-triangle-generator/ */\ndiv.arrow-up {\n    position:relative;\n    top:-2px;\n    width: 0;\n    height: 0;\n    border-style: solid;\n    border-width: 0 0.3em 0.7em 0.3em;\n    border-color: transparent transparent #646464 transparent;\n}\n\ndiv.arrow-down {\n    width: 0;\n    height: 0;\n    border-style: solid;\n    border-width: 0.7em 0.3em 0 0.3em;\n    border-color: #646464 transparent transparent transparent;\n}\n\n\n.controls { line-height:6pt; vertical-align: text-top;  }\n\n.formatting-help {\n    border: 2px solid #ddd;\n    padding: 0.25em;\n    margin: 0 20px;\n    box-sizing: border-box;\n}\n\n.formatting-help.closed {\n    display: none;\n}\n\n.formatting-help h3 {\n    display: block;\n    margin: 0;\n    padding: 0.5em 0 0.25em 0;\n    font-size: 13px;\n    font-weight: 600;\n}\n\n.formatting-help h3:first-child {\n    padding-top: 0;\n}\n\n\n/* mobile device */\n@media only screen\nand (min-width : 300px)\nand (max-width : 750px) {\n  #pnmain { width: 100%; margin:0; }\n  body { padding: 0; margin: 0; width: 100%; -webkit-text-size-adjust: none; }\n  td { height: inherit !important; }\n  .title, .comment { font-size: inherit;  }\n  span.pagetop { display: block; margin: 3px 5px; font-size: 12px; }\n  span.pagetop b { display: block; font-size: 15px; }\n\n    .vote-form {\n        padding:0.2em;\n        transform: scale(1.8);\n    }\n\n    body        { font-family:Verdana, Geneva, sans-serif; font-size:12pt; color:#646464; }\n    td          { font-family:Verdana, Geneva, sans-serif; font-size:12pt; color:#646464; }\n    .smaller    { font-size:10pt; }\n\n    button {\n        background-color: #e3e3e3;\n        border: #646464;\n        color: #535353;\n        text-align: center;\n        text-decoration: none;\n        display: inline-block;\n    }\n\n    form.comment-form textarea {\n        width: 100%;\n    }\n\n    div.arrow-up {\n        position:relative;\n        top:-2px;\n        width: 0;\n        height: 0;\n        border-style: solid;\n        border-width: 0 0.2em 0.6em 0.2em;\n        border-color: transparent transparent #646464 transparent;\n    }\n\n    div.arrow-down {\n        width: 0;\n        height: 0;\n        border-style: solid;\n        border-width: 0.6em 0.2em 0 0.2em;\n        border-color: #646464 transparent transparent transparent;\n    }\n\n\n}\n"
  },
  {
    "path": "static/news.js",
    "content": "document.addEventListener(\"DOMContentLoaded\", function() {\n\n    // Highlight the posted comment, if comment-id is in url hash\n    if(e = document.getElementById(window.location.hash.substring(1))) e.classList.add('highlight');\n\n    function getFormData(form) {\n        var data = {};\n        for (var i = 0, ii = form.length; i < ii; ++i) {\n            var input = form[i];\n            if (input.name) {\n                data[input.name] = input.value;\n            }\n        }\n        return data;\n    }\n    // AJAX-ify the upvote button\n    document.querySelectorAll(\".vote-form\").forEach(function (elem_form) {\n        elem_form.addEventListener(\"submit\", function(e){\n            e.preventDefault();\n            var form = e.srcElement;\n            var data = getFormData(form);\n            var xhr = new XMLHttpRequest();\n            xhr.open(form.method, form.action, true);\n            var form_data = new FormData();\n            for ( var key in data ) {\n                form_data.append(key, data[key]);\n            }\n            xhr.send(form_data);\n            // form.parentNode.removeChild(form);\n            var parent = form.parentNode;\n            parent.parentNode.removeChild(parent);\n        });\n    });\n\n});"
  }
]