Full Code of sebst/pythonic-news for AI

master 3a6d03985f40 cached
110 files
187.4 KB
46.0k tokens
238 symbols
1 requests
Download .txt
Showing preview only (212K chars total). Download the full file or copy to clipboard to get everything.
Repository: sebst/pythonic-news
Branch: master
Commit: 3a6d03985f40
Files: 110
Total size: 187.4 KB

Directory structure:
gitextract__e9vnpwr/

├── .gitignore
├── LICENSE
├── README.md
├── accounts/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── migrations/
│   │   ├── 0001_initial.py
│   │   ├── 0002_auto_20190914_1247.py
│   │   ├── 0003_auto_20190914_2031.py
│   │   ├── 0004_auto_20190915_1105.py
│   │   ├── 0005_emailverification_verification_code.py
│   │   ├── 0006_auto_20190915_1321.py
│   │   ├── 0007_auto_20190923_1323.py
│   │   └── __init__.py
│   ├── models.py
│   ├── receivers.py
│   ├── templates/
│   │   └── accounts/
│   │       ├── __base.html
│   │       ├── create_invite.html
│   │       ├── invite.html
│   │       ├── login.html
│   │       ├── logout.html
│   │       ├── my_profile.html
│   │       ├── password_change_done.html
│   │       ├── password_change_form.html
│   │       ├── password_forgotten_form.html
│   │       ├── profile.html
│   │       ├── register.html
│   │       ├── register_closed.html
│   │       ├── resend_verification.html
│   │       └── user_tree.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── emaildigest/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── mailing.py
│   ├── migrations/
│   │   ├── 0001_initial.py
│   │   ├── 0002_auto_20190923_2028.py
│   │   ├── 0003_auto_20190923_2120.py
│   │   ├── 0004_auto_20190926_2118.py
│   │   └── __init__.py
│   ├── models.py
│   ├── receivers.py
│   ├── templates/
│   │   └── emaildigest/
│   │       ├── __base.html
│   │       ├── _subscription_form_tag.html
│   │       ├── my_subscriptions.html
│   │       ├── subscribe.html
│   │       ├── subscribe_thankyou_a.html
│   │       ├── subscribe_thankyou_u.html
│   │       ├── subscribe_verification_done.html
│   │       ├── unsubscribe.html
│   │       ├── unsubscribe_confirm.html
│   │       └── unsubscribe_done.html
│   ├── templatetags/
│   │   ├── __init__.py
│   │   └── emaildigest_extra.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── hnclone/
│   ├── __init__.py
│   ├── context_processors.py
│   ├── middleware.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── news/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── feeds.py
│   ├── forms.py
│   ├── migrations/
│   │   ├── 0001_initial.py
│   │   ├── 0002_story_title.py
│   │   ├── 0003_auto_20190908_1642.py
│   │   ├── 0004_auto_20190908_2249.py
│   │   ├── 0005_auto_20190908_2250.py
│   │   ├── 0006_auto_20190908_2251.py
│   │   ├── 0007_auto_20190908_2256.py
│   │   ├── 0008_story_duplicate_of.py
│   │   ├── 0009_story_domain.py
│   │   ├── 0010_auto_20190930_1620.py
│   │   ├── 0011_auto_20190930_1623.py
│   │   ├── 0012_auto_20190930_1625.py
│   │   └── __init__.py
│   ├── models.py
│   ├── receivers.py
│   ├── templates/
│   │   └── news/
│   │       ├── __base.html
│   │       ├── _item_content_tag.html
│   │       ├── _item_control_tag.html
│   │       ├── _item_tag.html
│   │       ├── _link_user_tag.html
│   │       ├── _more_link_tag.html
│   │       ├── bookmarklet.html
│   │       ├── formatting_help.html
│   │       ├── index.html
│   │       ├── item.html
│   │       ├── item_delete.html
│   │       ├── item_edit.html
│   │       ├── submit.html
│   │       └── zen.html
│   ├── templatetags/
│   │   ├── __init__.py
│   │   └── news_extra.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── requirements.txt
└── static/
    ├── news.css
    └── news.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================



# Created by https://www.gitignore.io/api/code,macos,python,django,visualstudiocode
# Edit at https://www.gitignore.io/?templates=code,macos,python,django,visualstudiocode

### Code ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

### Django ###
*.log
*.pot
*.pyc
__pycache__/
local_settings.py
db.sqlite3
media

# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/
# in your Git repository. Update and uncomment the following line accordingly.
# <django-project-name>/staticfiles/

### Django.Python Stack ###
# Byte-compiled / optimized / DLL files
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo

# Django stuff:
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.
#Pipfile.lock

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### Python ###
# Byte-compiled / optimized / DLL files

# C extensions

# Distribution / packaging

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.

# Installer logs

# Unit test / coverage reports

# Translations

# Django stuff:

# Flask stuff:

# Scrapy stuff:

# Sphinx documentation

# PyBuilder

# Jupyter Notebook

# IPython

# pyenv

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.

# celery beat schedule file

# SageMath parsed files

# Environments

# Spyder project settings

# Rope project settings

# mkdocs documentation

# mypy

# Pyre type checker

### VisualStudioCode ###

### VisualStudioCode Patch ###
# Ignore all local history of files
.history

# End of https://www.gitignore.io/api/code,macos,python,django,visualstudiocode

================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================

# pythonic-news
A Hacker News lookalike written in Python/Django, powering [https://news.python.sc](https://news.python.sc)



[![screenshot](http://cdn.sebastiansteins.com/screenshot-news-python-sc.png "Screenshot")](https://news.python.sc)


## Setup for local development

### Set up virtual environment
```shell script
python -m venv venv/
source venv/bin/activate
```

### Install Dependencies
```shell script
pip install -r requirements.txt
```

### Migrate Database
```shell script
python manage.py migrate
```

### Extra setup work
* Set ```DEBUG=True``` if necessary
* Add ```127.0.0.1``` to ```ALLOWED_HOSTS```

### Run Django Server
```shell script
python manage.py runserver
```
Now you can access the website at ```127.0.0.1:8000```.


================================================
FILE: accounts/__init__.py
================================================
default_app_config = 'accounts.apps.AccountsConfig'


================================================
FILE: accounts/admin.py
================================================
from django.contrib import admin

# Register your models here.


================================================
FILE: accounts/apps.py
================================================
from django.apps import AppConfig


class AccountsConfig(AppConfig):
    name = 'accounts'

    def ready(self):
        from . import receivers

================================================
FILE: accounts/forms.py
================================================
from django import forms

from .models import CustomUser, Invitation

class ProfileForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ['about', 'email']
    
    def clean_email(self):
        data = self.cleaned_data['email']
        if data:
            data = data.lower()
        return data


class RegisterForm(forms.ModelForm):
    MIN_LENGTH = 8
    class Meta:
        model = CustomUser
        fields = ['username', 'password', 'email']
        widgets = {
            'password': forms.PasswordInput(),
        }

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if len(password) < self.MIN_LENGTH:
            raise forms.ValidationError("Your password must be at least %d characters long." % self.MIN_LENGTH)
        return password

class CreateInviteForm(forms.ModelForm):
    class Meta:
        model = Invitation
        fields = ['invited_email_address']
    
    def clean_invited_email_address(self):
        invited_email_address = self.cleaned_data['invited_email_address']
        if invited_email_address:
            invited_email_address = invited_email_address.lower()
        return invited_email_address


class PasswordForgottenForm(forms.Form):
    username = forms.CharField()

class PasswortResetForm(forms.Form):
    password = forms.CharField()

================================================
FILE: accounts/migrations/0001_initial.py
================================================
# Generated by Django 2.2.5 on 2019-09-07 12:14

import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
import uuid


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0011_update_proxy_permissions'),
    ]

    operations = [
        migrations.CreateModel(
            name='CustomUser',
            fields=[
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('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')),
                ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
                ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
                ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('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')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('karma', models.IntegerField(default=1)),
                ('about', models.TextField(default='')),
                ('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')),
                ('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')),
            ],
            options={
                'verbose_name': 'user',
                'verbose_name_plural': 'users',
                'abstract': False,
            },
            managers=[
                ('objects', django.contrib.auth.models.UserManager()),
            ],
        ),
    ]


================================================
FILE: accounts/migrations/0002_auto_20190914_1247.py
================================================
# Generated by Django 2.2.5 on 2019-09-14 12:47

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='customuser',
            name='karma',
            field=models.IntegerField(default=0),
        ),
        migrations.CreateModel(
            name='EmailVerification',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('changed_at', models.DateTimeField(auto_now=True)),
                ('verified', models.BooleanField(default=False)),
                ('verified_at', models.DateTimeField(null=True)),
                ('email', models.EmailField(max_length=254)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]


================================================
FILE: accounts/migrations/0003_auto_20190914_2031.py
================================================
# Generated by Django 2.2.5 on 2019-09-14 20:31

from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
import mptt.fields


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0002_auto_20190914_1247'),
    ]

    operations = [
        migrations.AlterModelManagers(
            name='customuser',
            managers=[
                ('_tree_manager', django.db.models.manager.Manager()),
                ('objects', django.contrib.auth.models.UserManager()),
            ],
        ),
        migrations.AddField(
            model_name='customuser',
            name='level',
            field=models.PositiveIntegerField(default=1, editable=False),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='customuser',
            name='lft',
            field=models.PositiveIntegerField(default=1, editable=False),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='customuser',
            name='parent',
            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),
        ),
        migrations.AddField(
            model_name='customuser',
            name='rght',
            field=models.PositiveIntegerField(default=2, editable=False),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='customuser',
            name='tree_id',
            field=models.PositiveIntegerField(db_index=True, default=1, editable=False),
            preserve_default=False,
        ),
    ]


================================================
FILE: accounts/migrations/0004_auto_20190915_1105.py
================================================
# Generated by Django 2.2.5 on 2019-09-15 11:05

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0003_auto_20190914_2031'),
    ]

    operations = [
        migrations.CreateModel(
            name='Invitation',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('changed_at', models.DateTimeField(auto_now=True)),
                ('num_signups', models.PositiveIntegerField(default=1, null=True)),
                ('invited_email_address', models.EmailField(default=None, max_length=254, null=True)),
                ('invite_code', models.UUIDField(default=uuid.uuid4, editable=False)),
                ('inviting_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.AddField(
            model_name='customuser',
            name='used_invitation',
            field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='accounts.Invitation'),
        ),
    ]


================================================
FILE: accounts/migrations/0005_emailverification_verification_code.py
================================================
# Generated by Django 2.2.5 on 2019-09-15 13:16

from django.db import migrations, models
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0004_auto_20190915_1105'),
    ]

    operations = [
        migrations.AddField(
            model_name='emailverification',
            name='verification_code',
            field=models.UUIDField(default=uuid.uuid4, editable=False),
        ),
    ]


================================================
FILE: accounts/migrations/0006_auto_20190915_1321.py
================================================
# Generated by Django 2.2.5 on 2019-09-15 13:21

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0005_emailverification_verification_code'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='customuser',
            options={},
        ),
        migrations.AlterModelManagers(
            name='customuser',
            managers=[
            ],
        ),
    ]


================================================
FILE: accounts/migrations/0007_auto_20190923_1323.py
================================================
# Generated by Django 2.2.5 on 2019-09-23 13:23

from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0006_auto_20190915_1321'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='customuser',
            options={'default_manager_name': 'objects'},
        ),
        migrations.AlterModelManagers(
            name='customuser',
            managers=[
                ('objects', django.contrib.auth.models.UserManager()),
            ],
        ),
        migrations.CreateModel(
            name='PasswordResetRequest',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('changed_at', models.DateTimeField(auto_now=True)),
                ('verification_code', models.UUIDField(default=uuid.uuid4, editable=False)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]


================================================
FILE: accounts/migrations/__init__.py
================================================


================================================
FILE: accounts/models.py
================================================
import uuid

from django.contrib.auth.models import AbstractUser
from django.urls import reverse

from django.db import models

from django.utils import timezone
import datetime

import  hashlib
from urllib.parse import urlencode

from mptt.models import MPTTModel, TreeForeignKey


#class CustomUser(MPTTModel, AbstractUser):
class CustomUser(AbstractUser, MPTTModel):
    class Meta:
        default_manager_name = 'objects'
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    karma = models.IntegerField(default=0)
    about = models.TextField(default='')
    # api_key = models.CharField(max_length=100)

    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='invitees', editable=False)

    used_invitation = models.ForeignKey('Invitation', null=True, default=None, on_delete=models.CASCADE)

    def get_absolute_url(self):
        return reverse("accounts_profile", kwargs={"username": self.username})

    @property
    def is_green(self):
        return timezone.now() - self.date_joined < datetime.timedelta(days=30)

    def gravatar_url(self, size=80):
        if self.email:
            default = "https://www.example.com/default.jpg"
            url = "https://www.gravatar.com/avatar/" + hashlib.md5(self.email.lower()).hexdigest() + "?"
            url += urlencode({'d':default, 's':str(size)})
            return url

    @property
    def latest_verified_email(self):
        verifications = EmailVerification.objects.filter(user=self, verified=True).order_by('-verified_at')
        if verifications.count():
            return verifications[0].email



class Invitation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    changed_at = models.DateTimeField(auto_now=True)

    inviting_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    num_signups = models.PositiveIntegerField(null=True, default=1)
    invited_email_address = models.EmailField(null=True, default=None)

    invite_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)

    def get_absolute_url(self):
        return reverse("accounts_invite", kwargs={"pk": self.pk})
    
    def get_register_url(self):
        return reverse("accounts_register") + '?invite=' + str(self.invite_code)

    @property
    def active(self):
        return True
        pass # TODO


class EmailVerification(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    changed_at = models.DateTimeField(auto_now=True)
    verified = models.BooleanField(default=False)
    verified_at = models.DateTimeField(null=True)

    email = models.EmailField()
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

    verification_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)

    def get_verify_url(self):
        return reverse("accounts_verify", kwargs={"verification_code": self.verification_code})


class PasswordResetRequest(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    changed_at = models.DateTimeField(auto_now=True)

    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    verification_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)


    def get_verify_url(self):
        return reverse("password_forgotten", kwargs={"verification_code": self.verification_code})


================================================
FILE: accounts/receivers.py
================================================
#from django.core.signals import request_finished
from django.db.models.signals import pre_save, post_save, post_delete
from django.dispatch import receiver
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives

from django.conf import settings



from .models import CustomUser, Invitation, EmailVerification, PasswordResetRequest


@receiver(pre_save)
def lower_email_addresses(sender, instance, **kwargs):
    if isinstance(instance, CustomUser):
        email = getattr(instance, 'email', None)
        if email:
            instance.email = email.lower()


@receiver(post_save)
def send_invitation_email(sender, instance, created, **kwargs):
    if created and isinstance(instance, Invitation):
        subject, from_email, to = 'You have been invited to %s'%(settings.SITE_DOMAIN), 'bot@python.sc', instance.invited_email_address
        text_content = """
You have been invited to news.python.sc.

Would you like to accept {inviting_user}'s invite?

Please sign up here: https://news.python.sc{url}

-- 
news.python.sc - A social news aggregator for the Python community.

""".format(inviting_user=instance.inviting_user.username, url=instance.get_register_url())
        #html_content = '<p>This is an <strong>important</strong> message.</p>'
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        #msg.attach_alternative(html_content, "text/html")
        msg.send()


@receiver(post_save)
def create_verification(sender, instance, created, **kwargs):
    if isinstance(instance, CustomUser):
        if instance.email:
            verifications = EmailVerification.objects.filter(user=instance, email=instance.email)
            if not verifications.count():
                create_v = True
            else:
                verified = any([i.verified for i in verifications])
                # create_v = not verified
                create_v = False
            
            if create_v:
                verification = EmailVerification(user=instance, email=instance.email)
                verification.save()


@receiver(post_save)
def send_verification_email(sender, instance, created, **kwargs):
    if created and isinstance(instance, EmailVerification):
        subject, from_email, to = 'Please confirm your account on news.python.sc', 'bot@python.sc', instance.email
        text_content = """
Please confirm your email address here:

https://news.python.sc{url}

-- 
news.python.sc - A social news aggregator for the Python community.

""".format(url=instance.get_verify_url())
        #html_content = '<p>This is an <strong>important</strong> message.</p>'
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        #msg.attach_alternative(html_content, "text/html")
        msg.send()


@receiver(post_save)
def send_password_reset_email(sender, instance, created, **kwargs):
    if created and isinstance(instance, PasswordResetRequest):
        subject, from_email, to = 'Reset password for your account on news.python.sc', 'bot@python.sc', instance.email
        text_content = """
Please confirm your email address here:

https://news.python.sc{url}

-- 
news.python.sc - A social news aggregator for the Python community.

""".format(url=instance.get_verify_url())
        #html_content = '<p>This is an <strong>important</strong> message.</p>'
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        #msg.attach_alternative(html_content, "text/html")
        msg.send()

================================================
FILE: accounts/templates/accounts/__base.html
================================================
{% extends 'news/__base.html' %}

================================================
FILE: accounts/templates/accounts/create_invite.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}

<form method="POST" action="{% url 'accounts_create_invite' %}">{% csrf_token %}
{{form}}
<button type="submit">invite</button>
</form>

{% endblock content %}

================================================
FILE: accounts/templates/accounts/invite.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}


You have created an invite for {{invitation.invited_email_address}}.
<a href="{% url 'accounts_create_invite' %}">Create anotther?</a>

{% endblock content %}

================================================
FILE: accounts/templates/accounts/login.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
{% if user.is_authenticated %}
Signed in.
{% else %}
<h2>Login</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Login</button>
</form>
<a href="{% url 'password_forgotten' %}">password forgotten?</a>
{% endif %}
{% endblock content %}

================================================
FILE: accounts/templates/accounts/logout.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}

<h2>Logout</h2>
<form method="post">
  {% csrf_token %}
  <button type="submit">logout</button>
</form>

{% endblock content %}

================================================
FILE: accounts/templates/accounts/my_profile.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
<article class="site-content-dense">
<form method="POST">{% csrf_token %}
<table>
{{form.as_table}}
</table>
<button type="submit">update</button>
</form>

{% if user.email and not verified %}
<hr />
<form method="POST" action="{% url 'accounts_resend_verification' %}">{% csrf_token %}
<button type="submit">Resend verification email</button>
</form>
{% endif %}


<hr />

<a href="{% url 'password_change' %}">change password</a> <br>
<a href="{% url 'newest' %}?submitted_by={{user}}">submissions</a> <br>
<a href="{% url 'comments' %}?submitted_by={{user}}">comments</a> <br>
{% comment %} <a href="#">hidden</a> <br>
<a href="#">flagged</a> <br> {% endcomment %}
<a href="{% url 'newest' %}?upvoted_by={{user}}">upvoted submissions</a> / <a href="{% url 'comments' %}?upvoted_by={{user}}">upvoted comments</a> <br>
{% comment %} <a href="#">favourite submissions</a> / <a href="#">favourite comments</a> <br> {% endcomment %}

</article>
{% endblock content %}

================================================
FILE: accounts/templates/accounts/password_change_done.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
Password changed successfully.
{% endblock content %}

================================================
FILE: accounts/templates/accounts/password_change_form.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
<h2>Change Password</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">chnage password</button>
</form>
{% endblock content %}

================================================
FILE: accounts/templates/accounts/password_forgotten_form.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
<h2>Password forgotten?</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">reset password</button>
</form>


{% endblock content %}

================================================
FILE: accounts/templates/accounts/profile.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
<article class="site-content-dense">
<table>
<tbody>
    <tr>
        <th>user:</th>
        <td>{{profile}}</td>
    </tr>
    <tr>
        <th>created:</th>
        <td>{{profile.date_joined}}</td>
    </tr>
    <tr>
        <th>karma:</th>
        <td>{{profile.karma}}</td>
    </tr>
    <tr>
        <th>about:</th>
        <td>{{profile.about}}</td>
    </tr>
</tbody></table>


<a href="{% url 'newest' %}?submitted_by={{profile}}">submissions</a> <br>
<a href="{% url 'comments' %}?submitted_by={{profile}}">comments</a> <br>
</article>


{% endblock content %}

================================================
FILE: accounts/templates/accounts/register.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
<article class="site-content-dense">
<h2>Create Account</h2>
<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 
if you've lost your password.</p>
<form method="post">
  {% csrf_token %}
  <table>
  {{ form.as_table }}
  </table>
  <br>
  <p class="smaller">By signing up, you agree to the <a href="{% url 'zen' %}">Zen of {{SITE_NAME}}</a>.</p>
  <button type="submit">create account</button>
</form>
</article>
{% endblock content %}

================================================
FILE: accounts/templates/accounts/register_closed.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
Closed.

<p>
You want an invite? Please leave your email address here: <a href="https://forms.gle/2D1UQ6YSa26WWSPDA">Request an invite</a>
</p>

{% endblock content %}

================================================
FILE: accounts/templates/accounts/resend_verification.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
A new email has been sent.
{% endblock content %}

================================================
FILE: accounts/templates/accounts/user_tree.html
================================================
{% extends 'accounts/__base.html' %}

{% block content %}
{% load mptt_tags %}

<ul class="root">
    {% recursetree users %}
        <li>
            {{ node.username }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ invitees }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>


{% endblock content %}

================================================
FILE: accounts/tests.py
================================================
from django.contrib.auth.models import AnonymousUser
from accounts.models import CustomUser
from django.test import RequestFactory, TestCase

from .views import *
from .models import *

class BasicAccountsTest(TestCase):
    """Tests the basic functionality of the accounts app."""
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = CustomUser.objects.create_user(
            username='sebst', email='hi@seb.st', password='top_secret')
        self.other_user = CustomUser.objects.create_user(
            username='bla1', email='two@seb.st', password='top_secret')


class ReceiversAccountsTest(TestCase):
    """Tests the basic functionality of the accounts app."""
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = CustomUser.objects.create_user(
            username='sebst', email='hi@seb.st', password='top_secret')
        self.other_user = CustomUser.objects.create_user(
            username='bla1', email='two@seb.st', password='top_secret')


    def test_lower_email_addresses(self):
        user = CustomUser.objects.create_user(
            username='johndoe', email='J.Doe@exAmple.org', password='top_secret')
        user = CustomUser.objects.get(pk=user.pk)
        self.assertEqual(user.email, 'j.doe@example.org')


    def test_send_invitation_email(self):
        self.skipTest()
        self.assertTrue(False)


    def test_create_verification(self):
        user = CustomUser.objects.create_user(
            username='johndoe', email='J.Doe@exAmple.org', password='top_secret')
        verification = EmailVerification.objects.get(user=user, email=user.email)
        self.assertEqual(verification.email, user.email)
        self.assertEqual(verification.email, 'j.doe@example.org')



    def test_send_verification_email(self):
        self.skipTest()
        self.assertTrue(False)


    def test_send_password_reset_email(self):
        self.skipTest()
        self.assertTrue(False)


================================================
FILE: accounts/urls.py
================================================
from django.urls import path, include

from . import views
from django.contrib.auth import views as auth_views



urlpatterns = [
    path('profile', views.profile, name="accounts_my_profile"),
    path('profile/<str:username>', views.profile, name="accounts_profile"),

    path('user-tree', views.user_tree, name="accounts_user_tree"),

    path('create-invite', views.create_invite, name="accounts_create_invite"),
    path('invite/<uuid:pk>', views.invite, name="accounts_invite"),

    path('verify/<uuid:verification_code>', views.verify, name="accounts_verify"),
    path('resend-verification', views.resend_verification, name="accounts_resend_verification"),

    path('register', views.register, name="accounts_register"),
    
    # path('accounts/', include('django.contrib.auth.urls')), # new
    path('accounts/login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name="login"),
    #path('accounts/logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name="logout"),
    path('accounts/logout/', views.logout, name="logout"),
    path('accounts/password-change/', auth_views.PasswordChangeView.as_view(template_name='accounts/password_change_form.html'), name="password_change"),
    path('accounts/password-change-done/', auth_views.PasswordChangeDoneView.as_view(template_name='accounts/password_change_done.html'), name="password_change_done"),

    path('accounts/password-forgotten/', views.password_forgotten, name="password_forgotten"),
    path('accounts/password-forgotten/<str:verification_code>', views.password_forgotten, name="password_forgotten"),


]


================================================
FILE: accounts/views.py
================================================
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout as do_logout
from django.urls import reverse
from django.conf import settings
from django.utils import timezone


from .models import CustomUser, Invitation, EmailVerification
from .forms import ProfileForm, RegisterForm, CreateInviteForm, PasswordForgottenForm, PasswortResetForm


def profile(request, username=None):
    if username is None:
        return my_profile(request)
    profile = get_object_or_404(CustomUser, username=username)
    if profile == request.user:
        return my_profile(request)
    return render(request, 'accounts/profile.html', {'profile': profile})


@login_required
def my_profile(request):
    instance = request.user
    form = ProfileForm(request.POST or None, instance=instance)
    if request.user.email:
        verifications = EmailVerification.objects.filter(user=request.user, email=request.user.email)
        verified = any([i.verified for i in verifications])
    else:
        verified = False
    if request.method == 'POST':
        if form.is_valid():
            instance = form.save()
            return HttpResponseRedirect(instance.get_absolute_url())
    return render(request, 'accounts/my_profile.html', {'form': form, 'verified': verified})


@login_required
def create_invite(request):
    instance = Invitation(inviting_user = request.user)
    form = CreateInviteForm(request.POST or None, instance=instance)
    if request.method=="POST":
        if form.is_valid():
            instance = form.save()
            return HttpResponseRedirect(instance.get_absolute_url())
    return render(request, 'accounts/create_invite.html', {'form': form})


@login_required
def invite(request, pk):
    invitation = get_object_or_404(Invitation, pk=pk)
    return render(request, 'accounts/invite.html', {'invitation': invitation})


def register(request):
    invite_code = request.GET.get('invite')
    try:
        invitation = Invitation.objects.get(invite_code=invite_code)
    except:
        invitation = None
    instance = CustomUser(used_invitation=invitation, 
                          parent=getattr(invitation, 'inviting_user', None), 
                          email=getattr(invitation, 'invited_email_address', None))
    if not settings.ACCEPT_UNINVITED_REGISTRATIONS and (invitation is None or not getattr(invitation, 'active', False)):
        return render(request, 'accounts/register_closed.html')
    form = RegisterForm(request.POST or None, instance=instance)
    if request.method == 'POST':
        if form.is_valid():
            instance = form.save()
            instance.set_password(form.cleaned_data['password'])
            instance.is_active = True
            instance.save()
            login(request, instance)
            return HttpResponseRedirect(instance.get_absolute_url())
    return render(request, 'accounts/register.html', {'form': form})


def verify(request, verification_code):
    verification = get_object_or_404(EmailVerification, verification_code=verification_code)
    assert verification.user.email == verification.email
    verification.verified = True
    verification.verified_at = timezone.now()
    verification.save()
    return render(request, 'accounts/verify.html')

@login_required
def resend_verification(request):
    if request.method=="POST":
        assert request.user.email
        verification = EmailVerification(user=request.user, email=request.user.email)
        verification.save()
        return render(request, 'accounts/resend_verification.html')


def user_tree(request):
    users = CustomUser.objects.all()
    return render(request, 'accounts/user_tree.html', {'users': users})


def password_forgotten(request, verification_code=None):
    assert not request.user.is_authenticated
    error = None
    if verification_code is None:
        if 'sent' in request.GET.keys():
            return render(request, 'accounts/password_forgotten_sent.html', {})
        form = PasswordForgottenForm(request.POST or None)
        if form.is_valid():
            user = None
            try:
                username = form.cleaned_data['username']
                user = CustomUser.objects.get_by_natural_key(username)
            except:
                pass
            if user:
                if user.email == user.latest_verified_email:
                    reset_request = PasswordResetRequest(user=user)
                    reset_request.save()
                    return HttpResponseRedirect(reverse('password_forgotten')+'?sent')
                else:
                    error = 'This user does not have a verified email. Please contact support.'
            else:
                error = 'User not found.'
        return render(request, 'accounts/password_forgotten_form.html', {'form': form, 'error': error})
    else:
        reset_request = get_object_or_404(PasswordResetRequest, verification_code=verification_code)
        form = PasswortResetForm(request.POST or None)
        if request.method=="POST":
            if form.is_valid():
                reset_request.user.set_password(form.cleaned_data['password']) # TODO: confirm password, password rules
                reset_request.user.save()
                return HttpResponseRedirect(reverse('/login'))
        return render(request, 'accounts/password_forgotten_form.html', {'form': form})


@login_required
def logout(request):
    if request.method=="POST":
        do_logout(request)
        redirect_url = settings.LOGOUT_REDIRECT_URL or '/'
        return HttpResponseRedirect(redirect_url)
    else:
        return render(request, 'accounts/logout.html')



================================================
FILE: emaildigest/__init__.py
================================================
default_app_config = 'emaildigest.apps.EmaildigestConfig'


================================================
FILE: emaildigest/admin.py
================================================
from django.contrib import admin

# Register your models here.


================================================
FILE: emaildigest/apps.py
================================================
from django.apps import AppConfig


class EmaildigestConfig(AppConfig):
    name = 'emaildigest'

    def ready(self):
        from . import receivers

================================================
FILE: emaildigest/forms.py
================================================
from django import forms

from .models import UserSubscription, AnonymousSubscription, Subscription


class UserSubscriptionForm(forms.ModelForm):
    thankyou = 'u'
    class Meta:
        model = UserSubscription
        fields = []


class AnonymousSubscriptionForm(forms.ModelForm):
    thankyou = 'a'
    class Meta:
        model = AnonymousSubscription
        fields = ['email']
    
    def clean_email(self):
        data = self.cleaned_data['email']
        if data:
            data = data.lower()
        return data


def validate_active_email(email):
    qs = Subscription.objects.filter(verfied_email=email, is_active=True)
    if not qs.count():
        raise forms.ValidationError(
            ('No subscription found for email %(email)s'),
            code='invalid',
            params={'email': email},)

class UnsunscribeForm(forms.Form):
    email = forms.EmailField(validators=[validate_active_email])

    def clean_email(self):
        data = self.cleaned_data['email']
        if data:
            data = data.lower()
        return data


def get_subscription_form(user, *args, **kwargs):
    return AnonymousSubscriptionForm(*args, **kwargs)
    if user.is_authenticated:
        return UserSubscriptionForm(*args, **kwargs)
    else:
        return AnonymousSubscriptionForm(*args, **kwargs)

================================================
FILE: emaildigest/mailing.py
================================================
from django.conf import settings
from .models import Subscription, EmailDigest

def create_and_send_digest(frequency):
    pass
    # Get list of objects
    stories = [] # TODO: Find from _font_page
    # make templates and trigger sending
    subscriptions = Subscription.objects.filter(is_active=True, frequency=frequency)
    for subscription in subscriptions:
        tpl = 'TODO: Here is your list' # TODO
        subject = settings.SITE_NAME + " " + frequency + " Digest"
        send_mail(subscription, tpl, subject)

def send_mail(subscription, template, subject):
    pass

================================================
FILE: emaildigest/migrations/0001_initial.py
================================================
# Generated by Django 2.2.5 on 2019-09-23 13:23

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('news', '0008_story_duplicate_of'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Subscription',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('changed_at', models.DateTimeField(auto_now=True)),
            ],
        ),
        migrations.CreateModel(
            name='AnonymousSubscription',
            fields=[
                ('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')),
                ('email', models.EmailField(blank=True, max_length=254, null=True)),
                ('verified', models.BooleanField(default=False)),
                ('verified_at', models.DateTimeField(null=True)),
                ('verification_code', models.UUIDField(default=uuid.uuid4, editable=False)),
            ],
            bases=('emaildigest.subscription',),
        ),
        migrations.CreateModel(
            name='EmailDigest',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('changed_at', models.DateTimeField(auto_now=True)),
                ('frequency', models.CharField(choices=[('weekly', 'weekly'), ('daily', 'daily')], max_length=16)),
                ('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)),
                ('stories', models.ManyToManyField(to='news.Story')),
            ],
        ),
        migrations.CreateModel(
            name='UserSubscription',
            fields=[
                ('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')),
                ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            bases=('emaildigest.subscription',),
        ),
    ]


================================================
FILE: emaildigest/migrations/0002_auto_20190923_2028.py
================================================
# Generated by Django 2.2.5 on 2019-09-23 20:28

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('emaildigest', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='subscription',
            name='frequency',
            field=models.CharField(choices=[('weekly', 'weekly'), ('daily', 'daily')], default='daily', max_length=16),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='subscription',
            name='weekly_weekday',
            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),
        ),
    ]


================================================
FILE: emaildigest/migrations/0003_auto_20190923_2120.py
================================================
# Generated by Django 2.2.5 on 2019-09-23 21:20

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('emaildigest', '0002_auto_20190923_2028'),
    ]

    operations = [
        migrations.AddField(
            model_name='anonymoussubscription',
            name='logged_in_user',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='subscription',
            name='verfied_email',
            field=models.EmailField(blank=True, max_length=254, null=True),
        ),
    ]


================================================
FILE: emaildigest/migrations/0004_auto_20190926_2118.py
================================================
# Generated by Django 2.2.5 on 2019-09-26 21:18

from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ('emaildigest', '0003_auto_20190923_2120'),
    ]

    operations = [
        migrations.AddField(
            model_name='subscription',
            name='is_active',
            field=models.BooleanField(default=False),
        ),
        migrations.CreateModel(
            name='UnSubscription',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('changed_at', models.DateTimeField(auto_now=True)),
                ('from_digest', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='emaildigest.EmailDigest')),
                ('subscription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='emaildigest.Subscription')),
            ],
        ),
    ]


================================================
FILE: emaildigest/migrations/__init__.py
================================================


================================================
FILE: emaildigest/models.py
================================================
import uuid
from django.db import models

class EmailDigest(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    changed_at = models.DateTimeField(auto_now=True)

    frequency = models.CharField(max_length=16, choices=(('weekly', 'weekly'), ('daily', 'daily')))
    weekly_weekday = models.CharField(max_length=16, null=True, blank=True, choices=(('Sun', 'Sun'), 
                                                                                     ('Mon', 'Mon'),
                                                                                     ('Tue', 'Tue'),
                                                                                     ('Wed', 'Wed'),
                                                                                     ('Thu', 'Thu'),
                                                                                     ('Fri', 'Fri'),
                                                                                     ('Sat', 'Sat')))
    stories = models.ManyToManyField('news.Story')

class Subscription(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    changed_at = models.DateTimeField(auto_now=True)
    frequency = models.CharField(max_length=16, choices=(('weekly', 'weekly'), ('daily', 'daily')))
    weekly_weekday = models.CharField(max_length=16, null=True, blank=True, choices=(('Sun', 'Sun'), 
                                                                                     ('Mon', 'Mon'),
                                                                                     ('Tue', 'Tue'),
                                                                                     ('Wed', 'Wed'),
                                                                                     ('Thu', 'Thu'),
                                                                                     ('Fri', 'Fri'),
                                                                                     ('Sat', 'Sat')))
    verfied_email = models.EmailField(null=True, blank=True)
    is_active = models.BooleanField(default=False)


class UserSubscription(Subscription):
    user = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE, null=True)


class AnonymousSubscription(Subscription):
    email = models.EmailField(null=True, blank=True)
    verified = models.BooleanField(default=False)
    verified_at = models.DateTimeField(null=True)
    verification_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)
    logged_in_user = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE, null=True)


class UnSubscription(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    changed_at = models.DateTimeField(auto_now=True)
    subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE)
    from_digest = models.ForeignKey(EmailDigest, on_delete=models.CASCADE, null=True)

================================================
FILE: emaildigest/receivers.py
================================================
#from django.core.signals import request_finished
from django.db.models.signals import pre_save, post_save, post_delete
from django.dispatch import receiver
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives



from .models import UserSubscription, AnonymousSubscription, Subscription, UnSubscription


@receiver(pre_save)
def lower_email_addresses(sender, instance, **kwargs):
    if isinstance(instance, (UserSubscription, AnonymousSubscription)):
        if isinstance(instance, AnonymousSubscription):
            instance.email = instance.email.lower()
    if isinstance(instance, Subscription):
        if instance.verfied_email:
            instance.verfied_email = instance.verfied_email.lower()


@receiver(post_save)
def activate_subscription_on_verification(sender, instance, created, **kwargs):
    if isinstance(instance, AnonymousSubscription):
        if instance.verified:
            subscription = instance.subscription_ptr
            subscription.is_active = True
            subscription.verfied_email = instance.email
            subscription.save()

@receiver(post_save)
def on_subscription_created(sender, instance, created, **kwargs):
    if created and isinstance(instance, (UserSubscription, AnonymousSubscription)):
        subscription = instance


@receiver(post_save)
def on_unsubscription_created(sender, instance, created, **kwargs):
    if created and isinstance(instance, (UnSubscription)):
        unsubscription = instance
        unsubscription.subscription.is_active = False
        unsubscription.subscription.save()

================================================
FILE: emaildigest/templates/emaildigest/__base.html
================================================
{% extends 'news/__base.html' %}

================================================
FILE: emaildigest/templates/emaildigest/_subscription_form_tag.html
================================================
{% if False and subscription_form %}
<p>Don't miss interesting Python stories by subscribing to our digest</p>

    <form class="subscription-form" method="POST" action="{% url 'emaildigest_subscribe' %}">
        {% csrf_token %}
        {{subscription_form}}
        <button type="submit">Get Python stories to your inbox</button>
    </form>
{% endif %}

================================================
FILE: emaildigest/templates/emaildigest/my_subscriptions.html
================================================
{% extends 'emaildigest/__base.html' %}

{% block content %}

    <article class="site-content">
        my_subscriptions.html
    </article>


{% endblock content %}

================================================
FILE: emaildigest/templates/emaildigest/subscribe.html
================================================


================================================
FILE: emaildigest/templates/emaildigest/subscribe_thankyou_a.html
================================================
{% extends 'emaildigest/__base.html' %}

{% block content %}

    <article class="site-content">
        Thank you!<br>
        You will receive a confirmation email soon
    </article>


{% endblock content %}

================================================
FILE: emaildigest/templates/emaildigest/subscribe_thankyou_u.html
================================================
{% extends 'emaildigest/__base.html' %}

{% block content %}

    <article class="site-content">
        Thank you!<br>
        You are now subscribed.
    </article>


{% endblock content %}

================================================
FILE: emaildigest/templates/emaildigest/subscribe_verification_done.html
================================================
{% extends 'emaildigest/__base.html' %}

{% block content %}

    <article class="site-content">
        Thank you!<br>
        You are now subscribed.
    </article>


{% endblock content %}

================================================
FILE: emaildigest/templates/emaildigest/unsubscribe.html
================================================

{% extends 'news/__base.html' %}
{% load humanize %}
{% load mptt_tags %}



{% block content %}




<article class="site-content">
    
        <form method="POST">{% csrf_token %}
        {{form}}
        <button type="submit">unsubscribe</button>
        </form>

</article>






{% endblock content %}

================================================
FILE: emaildigest/templates/emaildigest/unsubscribe_confirm.html
================================================

{% extends 'news/__base.html' %}
{% load humanize %}
{% load mptt_tags %}



{% block content %}




<article class="site-content">
    
        <form method="POST">{% csrf_token %}
        Do yo really want to unsubscribe?<br>
        <button type="submit">Yes, unsubscribe</button>
        </form>
    

</article>






{% endblock content %}

================================================
FILE: emaildigest/templates/emaildigest/unsubscribe_done.html
================================================

{% extends 'news/__base.html' %}
{% load humanize %}
{% load mptt_tags %}



{% block content %}




<article class="site-content">

        You are unsubscribed.

</article>






{% endblock content %}

================================================
FILE: emaildigest/templatetags/__init__.py
================================================


================================================
FILE: emaildigest/templatetags/emaildigest_extra.py
================================================
from django import template

register = template.Library()

from emaildigest.forms import get_subscription_form

@register.inclusion_tag('emaildigest/_subscription_form_tag.html')
def digest_subscription_form(user, **kwargs):
    form = get_subscription_form(user)
    return {'subscription_form': form}


================================================
FILE: emaildigest/tests.py
================================================
from django.contrib.auth.models import AnonymousUser
from accounts.models import CustomUser
from django.test import RequestFactory, TestCase

from .views import *
from .models import *
from .forms import *

class BasicEmailDigestTest(TestCase):
    """Tests the basic functionality of the emaildigest app."""
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = CustomUser.objects.create_user(
            username='sebst', email='hi@seb.st', password='top_secret')
        self.other_user = CustomUser.objects.create_user(
            username='bla1', email='two@seb.st', password='top_secret')

    def _subscribe(self, i=0):
        self.assertEqual(Subscription.objects.all().count(), 0+i)

        request = self.factory.post('/digest/subscribe', {'email': 'test@example.org'})
        request.user = self.user
        response = subscribe(request)

        #self.assertContains(response.url, 'thankyou')
        self.assertRegex(response.url, r'.*thankyou.*')

        self.assertEqual(Subscription.objects.all().count(), 1+i)

        subscription = Subscription.objects.all().order_by('-created_at')[0]
        self.assertFalse(subscription.is_active)

        verification_code = subscription.anonymoussubscription.verification_code

        return subscription

    def _confirm(self, subscription):
        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertFalse(subscription.anonymoussubscription.verified)
        self.assertFalse(subscription.is_active)
        verification_code = subscription.anonymoussubscription.verification_code

        url = '/digest/subscribe?v=' + str(verification_code)

        request = self.factory.get(url)
        request.user = self.user
        response = subscribe(request)

        subscription = Subscription.objects.get(pk=subscription.pk)
        anonymoussubscription = AnonymousSubscription.objects.get(pk=subscription.pk)
        self.assertTrue(anonymoussubscription.verified)


    def _unsubscribe_via_mail(self, subscription, assert_form_error=False):
        subscription = Subscription.objects.get(pk=subscription.pk)

        self.assertEqual(UnSubscription.objects.all().count(), 0)

        url = '/digest/unsubscribe'
        request = self.factory.post(url, {'email': subscription.anonymoussubscription.email})
        request.user = self.user
        response = unsubscribe(request)
        if assert_form_error:
            # self.assertFormError(response, UnsunscribeForm, 'email', 'No subscription found for email ' + subscription.anonymoussubscription.email)
            self.assertContains(response, 'No subscription found for email')
            return None
        self.assertEqual(response.status_code, 302)
        self.assertRegex(response.url, r'.*done.*')

        self.assertEqual(UnSubscription.objects.all().count(), 1)

        unsubscription = UnSubscription.objects.get()
        return unsubscription


    def test_subscribe(self):
        subscription = self._subscribe()
        self.assertFalse(subscription.is_active)


    def test_subscribe_confirm(self):
        subscription = self._subscribe()
        self._confirm(subscription)
        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertTrue(subscription.is_active)


    def test_subscribe_unsubscribe(self):
        subscription = self._subscribe()
        unsubscription = self._unsubscribe_via_mail(subscription, assert_form_error=True)
        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertFalse(subscription.is_active)


    def test_subscribe_confirm_unsubscribe(self):
        subscription = self._subscribe()
        self._confirm(subscription)
        unsubscription = self._unsubscribe_via_mail(subscription)
        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertFalse(subscription.is_active)


    def test_subscribe_unsubscribe_confirm(self):
        subscription = self._subscribe()
        unsubscription = self._unsubscribe_via_mail(subscription, assert_form_error=True)
        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertFalse(subscription.is_active)

        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertFalse(subscription.is_active)

        self._confirm(subscription)
        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertTrue(subscription.is_active)


    def test_subscribe_confirm_unsubscribe_subscribe(self):
        subscription = self._subscribe()
        self._confirm(subscription)
        unsubscription = self._unsubscribe_via_mail(subscription)

        subscription2 = self._subscribe(i=1)
        subscription2 = Subscription.objects.get(pk=subscription2.pk)
        self.assertFalse(subscription.is_active)



    def test_subscribe_confirm_unsubscribe_subscribe_confirm(self):
        subscription = self._subscribe()
        self._confirm(subscription)
        
        unsubscription = self._unsubscribe_via_mail(subscription)

        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertFalse(subscription.is_active)

        re_subscription = self._subscribe(i=1)
        self._confirm(re_subscription)

        re_subscription = Subscription.objects.get(pk=re_subscription.pk)
        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertTrue(re_subscription.is_active)
        self.assertFalse(subscription.is_active)



# class ReceiversEmailDigestTest(TestCase):
#     """Tests the basic receivers functionality of the emaildigest app."""
#     def setUp(self):
#         # Every test needs access to the request factory.
#         self.factory = RequestFactory()
#         self.user = CustomUser.objects.create_user(
#             username='sebst', email='hi@seb.st', password='top_secret')
#         self.other_user = CustomUser.objects.create_user(
#             username='bla1', email='two@seb.st', password='top_secret')


#     def test_lower_email_addresses(self):
#         self.fail()

#     def activate_subscription_on_verification(self):
#         self.fail()

#     def test_on_subscription_created(self):
#         self.fail()

#     def test_on_unsubscription_created(self):
#         self.fail()

================================================
FILE: emaildigest/urls.py
================================================
from django.urls import path, include

from . import views




urlpatterns = [
    #path('profile', views.profile, name="accounts_my_profile"),
    path('subscribe', views.subscribe, name="emaildigest_subscribe"),
    path('subscriptions', views.my_subscriptions, name="emaildigest_subscriptions"),

    path('unsubscribe', views.unsubscribe, name='emaildigest_unsubscribe'),
    path('unsubscribe/<uuid:subscription_id>/<uuid:digest_id>', views.unsubscribe, name='emaildigest_unsubscribe'),

]


================================================
FILE: emaildigest/views.py
================================================
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import timezone

from .forms import get_subscription_form, UnsunscribeForm

from .models import AnonymousSubscription, UnSubscription, Subscription, EmailDigest


def subscribe(request):
    form = get_subscription_form(request.user, request.POST or None)
    thankyou = request.GET.get('thankyou', None)
    if thankyou:
        return render(request, 'emaildigest/subscribe_thankyou_%s.html'%(thankyou), {'prevent_footer_subscription_form': True})
    verification_code = request.GET.get('v', None)
    if verification_code:
        subscription = get_object_or_404(AnonymousSubscription, verification_code=verification_code)
        if not subscription.verified:
            subscription.verified = True
            subscription.verified_at = timezone.now()
            subscription.save()
        # TODO: Verify User account if needed # TODO: Activate usage of get_subsciption_form
        return render(request, 'emaildigest/subscribe_verification_done.html', {'prevent_footer_subscription_form': True})
    if request.method=="POST":
        if form.is_valid():
            subscription = form.save()
            if request.user.is_authenticated:
                subscription.logged_in_user = request.user
                subscription.save()
            return HttpResponseRedirect(reverse('emaildigest_subscribe') + '?thankyou=' + form.thankyou)
    return render(request, 'emaildigest/subscribe.html', {'subscription_form': form, 'prevent_footer_subscription_form': True})


def unsubscribe(request, subscription_id=None, digest_id=None):
    if 'done' in request.GET.keys():
        email = request.GET.get('email', None)
        suscription = request.GET.get('subscription', None)
        return render(request, 'emaildigest/unsubscribe_done.html', {'email': email, 'subscription': subscription, 'prevent_footer_subscription_form': True})
    if subscription_id is None and digest_id is None:
        form = UnsunscribeForm(request.POST or None)
        if request.method=="POST":
            if form.is_valid():
                email = form.cleaned_data['email']
                subscriptions = Subscription.objects.filter(verfied_email=email, is_active=True)
                for subscription in subscriptions:
                    unsubscription = UnSubscription(subscription=subscription)
                    unsubscription.save()
                return HttpResponseRedirect(reverse('emaildigest_unsubscribe') + "?done&email="+email)
        return render(request, 'emaildigest/unsubscribe.html', {'form': form, 'prevent_footer_subscription_form': True})
    elif subscription_id is not None and digest_id is not None:
        subscription = get_object_or_404(Subscription, pk=subscription_id)
        digest = get_object_or_404(EmailDigest, pk=digest_id)
        if request.method=="GET":
            return render(request, 'emaildigest/unsubscribe_confirm.html', {})
        elif request.method=="POST":
            unsubscription = UnSubscription(subscription=subscription, from_digest=digest)
            unsubscription.save()
            return HttpResponseRedirect(reverse('emaildigest_unsubscribe') + "?done&subscription="+subscription_id)
        else:
            return HttpResponseRedirect(reverse('emaildigest_unsubscribe'))
    else:
        return HttpResponseRedirect(reverse('emaildigest_unsubscribe'))
    pass


def my_subscriptions(request):
    return render(request, 'emaildigest/my_subscriptions.html')

================================================
FILE: hnclone/__init__.py
================================================


================================================
FILE: hnclone/context_processors.py
================================================
from django.conf import settings
def settings_context_processor(request):
   return {
       'SITE_NAME': settings.SITE_NAME,
       'SITE_DOMAIN': settings.SITE_DOMAIN,
       'SITE_URL': settings.SITE_URL
   }

================================================
FILE: hnclone/middleware.py
================================================


================================================
FILE: hnclone/settings.py
================================================
"""
Django settings for hnclone project.

Generated by 'django-admin startproject' using Django 2.2.5.

Modified by me 2019-09-30 15.50 CEST

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'TODO' # TODO

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False


USE_X_FORWARDED_HOST = True
ALLOWED_HOSTS = [
    'news.python.sc',
    'localhost',
]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',

    'mptt',
    'debug_toolbar',

    'accounts',
    'news',
    'emaildigest',

    
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',

    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 'django.middleware.gzip.GZipMiddleware',
    #'htmlmin.middleware.HtmlMinifyMiddleware', # TODO: When activated, Django Debug Toolbar has JS issues
    'htmlmin.middleware.MarkRequestMiddleware',
]

ROOT_URLCONF = 'hnclone.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'hnclone.context_processors.settings_context_processor',
            ],
        },
    },
]

WSGI_APPLICATION = 'hnclone.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]


AUTH_USER_MODEL = 'accounts.CustomUser'


INTERNAL_IPS = [
    '127.0.0.1',
]


PAGING_SIZE = 30


HTML_MINIFY = True



LOGOUT_REDIRECT_URL = '/'
LOGIN_REDIRECT_URL = '/'



ACCEPT_UNINVITED_REGISTRATIONS = False


SITE_NAME = 'Pythonic News'
SITE_URL = 'https://news.python.sc'
SITE_DOMAIN = 'news.python.sc'


================================================
FILE: hnclone/urls.py
================================================
"""hnclone URL Configuration
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.http import HttpResponse

urlpatterns = [
    path('', include('news.urls')),
    path('', include('accounts.urls')),
    path('digest/', include('emaildigest.urls')),
    path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns


from ratelimit.exceptions import Ratelimited
def handler403(request, exception=None):
    if isinstance(exception, Ratelimited):
        return HttpResponse("<img src='https://http.cat/429.jpg'><br>Sorry, we're not able to serve your requests this quickly.", status=429)
    return HttpResponseForbidden('Forbidden')


================================================
FILE: hnclone/wsgi.py
================================================
"""
WSGI config for hnclone project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""

import os, sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR )
sys.path.append(BASE_DIR + '/../')

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hnclone.settings')

application = get_wsgi_application()


================================================
FILE: manage.py
================================================
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hnclone.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()


================================================
FILE: news/__init__.py
================================================
default_app_config = 'news.apps.NewsConfig'


================================================
FILE: news/admin.py
================================================
from django.contrib import admin


from .models import Story, Comment

admin.site.register(Story)
admin.site.register(Comment)

================================================
FILE: news/apps.py
================================================
from django.apps import AppConfig


class NewsConfig(AppConfig):
    name = 'news'

    def ready(self):
        from . import receivers

================================================
FILE: news/feeds.py
================================================
from django.contrib.syndication.views import Feed
from .models import Story
from .views import _newest, _front_page

from django.conf import settings

class NewestFeed(Feed):
    title = "%s: Latest"%(settings.SITE_NAME)
    link = "/newest/"
    description = "Latest stories"

    def items(self):
        return _newest(30, 0)

    def item_title(self, item):
        return item.title

    def item_pubdate(self, item):
        return item.created_at
    
    def item_updateddate(self, item):
        return item.changed_at
    
    def item_author_name(self, item):
        return str(item.user)
    
    def item_author_link(self, item):
        return settings.SITE_URL + item.user.get_absolute_url()

    def item_description(self, item):
        return "TODO" # TODO
        return item.url


class FrontPageFeed(NewestFeed):
    title = "%s: Front Page" % (settings.SITE_NAME)
    link = "/feed"
    description = "Front Page stories"

    def items(self):
        return _front_page(30, 0)

================================================
FILE: news/forms.py
================================================
from django import forms

from .models import Comment, Story

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['text']


class AddStoryForm(forms.ModelForm):
    class Meta:
        model = Story
        fields = ['title', 'url', 'text']

    def clean(self):
        cleaned_data = super().clean()

        title = self.cleaned_data.get('title')
        text = self.cleaned_data.get('text')
        url = self.cleaned_data.get('url')
        if not title:
            raise forms.ValidationError("Please provide a title.")
        if (not text) and (not url):
            raise forms.ValidationError("Please provide either a text or a URL.")



class StoryForm(forms.ModelForm):
    class Meta:
        model = Story
        fields = ['title', 'text']

    


================================================
FILE: news/migrations/0001_initial.py
================================================
# Generated by Django 2.2.5 on 2019-09-07 12:14

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import mptt.fields
import uuid


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Item',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('changed_at', models.DateTimeField(auto_now=True)),
                ('upvotes', models.PositiveIntegerField(default=0)),
                ('downvotes', models.PositiveIntegerField(default=0)),
                ('points', models.IntegerField(default=0)),
                ('num_comments', models.PositiveIntegerField(default=0)),
                ('lft', models.PositiveIntegerField(editable=False)),
                ('rght', models.PositiveIntegerField(editable=False)),
                ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)),
                ('level', models.PositiveIntegerField(editable=False)),
                ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='news.Item')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Story',
            fields=[
                ('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')),
                ('url', models.URLField(null=True)),
                ('text', models.TextField(null=True)),
            ],
            options={
                'abstract': False,
            },
            bases=('news.item',),
        ),
        migrations.CreateModel(
            name='Vote',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('changed_at', models.DateTimeField(auto_now=True)),
                ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news.Item')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Comment',
            fields=[
                ('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')),
                ('text', models.TextField()),
                ('to_story', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news.Story')),
            ],
            options={
                'abstract': False,
            },
            bases=('news.item',),
        ),
    ]


================================================
FILE: news/migrations/0002_story_title.py
================================================
# Generated by Django 2.2.5 on 2019-09-07 13:25

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='story',
            name='title',
            field=models.CharField(default='-', max_length=255),
            preserve_default=False,
        ),
    ]


================================================
FILE: news/migrations/0003_auto_20190908_1642.py
================================================
# Generated by Django 2.2.5 on 2019-09-08 16:42

from django.db import migrations, models
import django.db.models.deletion
import mptt.fields


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0002_story_title'),
    ]

    operations = [
        migrations.AddField(
            model_name='vote',
            name='vote',
            field=models.SmallIntegerField(default=1),
        ),
        migrations.AlterField(
            model_name='comment',
            name='to_story',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='news.Story'),
        ),
        migrations.AlterField(
            model_name='item',
            name='downvotes',
            field=models.PositiveIntegerField(default=0, editable=False),
        ),
        migrations.AlterField(
            model_name='item',
            name='num_comments',
            field=models.PositiveIntegerField(default=0, editable=False),
        ),
        migrations.AlterField(
            model_name='item',
            name='parent',
            field=mptt.fields.TreeForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='news.Item'),
        ),
        migrations.AlterField(
            model_name='item',
            name='points',
            field=models.IntegerField(default=0, editable=False),
        ),
        migrations.AlterField(
            model_name='item',
            name='upvotes',
            field=models.PositiveIntegerField(default=0, editable=False),
        ),
        migrations.AlterField(
            model_name='story',
            name='text',
            field=models.TextField(blank=True, null=True),
        ),
        migrations.AlterField(
            model_name='story',
            name='title',
            field=models.CharField(blank=True, max_length=255),
        ),
        migrations.AlterField(
            model_name='story',
            name='url',
            field=models.URLField(blank=True, null=True),
        ),
    ]


================================================
FILE: news/migrations/0004_auto_20190908_2249.py
================================================
# Generated by Django 2.2.5 on 2019-09-08 22:49

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0003_auto_20190908_1642'),
    ]

    operations = [
        migrations.AddIndex(
            model_name='item',
            index=models.Index(fields=['points', 'created_at'], name='news_item_points_d03885_idx'),
        ),
        migrations.AddIndex(
            model_name='item',
            index=models.Index(fields=['created_at', 'points'], name='news_item_created_f2b812_idx'),
        ),
    ]


================================================
FILE: news/migrations/0005_auto_20190908_2250.py
================================================
# Generated by Django 2.2.5 on 2019-09-08 22:50

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0004_auto_20190908_2249'),
    ]

    operations = [
        migrations.RemoveIndex(
            model_name='item',
            name='news_item_points_d03885_idx',
        ),
    ]


================================================
FILE: news/migrations/0006_auto_20190908_2251.py
================================================
# Generated by Django 2.2.5 on 2019-09-08 22:51

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0005_auto_20190908_2250'),
    ]

    operations = [
        migrations.RemoveIndex(
            model_name='item',
            name='news_item_created_f2b812_idx',
        ),
        migrations.AddIndex(
            model_name='item',
            index=models.Index(fields=['points', 'created_at'], name='news_item_points_d03885_idx'),
        ),
    ]


================================================
FILE: news/migrations/0007_auto_20190908_2256.py
================================================
# Generated by Django 2.2.5 on 2019-09-08 22:56

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0006_auto_20190908_2251'),
    ]

    operations = [
        migrations.RemoveIndex(
            model_name='item',
            name='news_item_points_d03885_idx',
        ),
        migrations.AddField(
            model_name='item',
            name='is_ask',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='item',
            name='is_show',
            field=models.BooleanField(default=False),
        ),
        migrations.AddIndex(
            model_name='item',
            index=models.Index(fields=['created_at', 'points'], name='news_item_created_f2b812_idx'),
        ),
    ]


================================================
FILE: news/migrations/0008_story_duplicate_of.py
================================================
# Generated by Django 2.2.5 on 2019-09-23 13:23

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0007_auto_20190908_2256'),
    ]

    operations = [
        migrations.AddField(
            model_name='story',
            name='duplicate_of',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='news.Story'),
        ),
    ]


================================================
FILE: news/migrations/0009_story_domain.py
================================================
# Generated by Django 2.2.5 on 2019-09-30 16:17

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0008_story_duplicate_of'),
    ]

    operations = [
        migrations.AddField(
            model_name='story',
            name='domain',
            field=models.CharField(blank=True, max_length=255, null=True),
        ),
    ]


================================================
FILE: news/migrations/0010_auto_20190930_1620.py
================================================
# Generated by Django 2.2.5 on 2019-09-30 16:20

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0009_story_domain'),
    ]

    operations = [
        migrations.AlterField(
            model_name='story',
            name='domain',
            field=models.CharField(blank=True, db_index=True, max_length=255, null=True),
        ),
    ]


================================================
FILE: news/migrations/0011_auto_20190930_1623.py
================================================
# Generated by Django 2.2.5 on 2019-09-30 16:23

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0010_auto_20190930_1620'),
    ]

    operations = [
        migrations.AddIndex(
            model_name='story',
            index=models.Index(fields=['domain', 'duplicate_of'], name='news_story_domain_07db78_idx'),
        ),
    ]


================================================
FILE: news/migrations/0012_auto_20190930_1625.py
================================================
# Generated by Django 2.2.5 on 2019-09-30 16:25

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0011_auto_20190930_1623'),
    ]

    operations = [
        migrations.AddIndex(
            model_name='item',
            index=models.Index(fields=['created_at', 'id'], name='news_item_created_10dd57_idx'),
        ),
        migrations.AddIndex(
            model_name='item',
            index=models.Index(fields=['id', 'created_at'], name='news_item_id_b557ce_idx'),
        ),
    ]


================================================
FILE: news/migrations/__init__.py
================================================


================================================
FILE: news/models.py
================================================
import uuid

from accounts.models import CustomUser

from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
from django.urls import reverse

from urllib.parse import urlparse



class Item(MPTTModel):
    class Meta:
        indexes = [
            #models.Index(fields=['points', 'created_at']),
            models.Index(fields=['created_at', 'points']),
            models.Index(fields=['created_at', 'id']),
            models.Index(fields=['id', 'created_at']),
        ]
        # ordering = ['-created_at']

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    changed_at = models.DateTimeField(auto_now=True)
    upvotes = models.PositiveIntegerField(default=0, editable=False)
    downvotes = models.PositiveIntegerField(default=0, editable=False)
    points = models.IntegerField(default=0, editable=False)
    num_comments = models.PositiveIntegerField(default=0, editable=False)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', editable=False)
    user = models.ForeignKey(to=CustomUser, on_delete=models.CASCADE)

    is_ask = models.BooleanField(default=False)
    is_show = models.BooleanField(default=False)


    def get_absolute_url(self):
        return reverse("item", kwargs={"pk": self.pk})


    def can_be_upvoted_by(self, user):
        if not user.is_authenticated:
            return False
        if user == self.user:
            return False
        if Vote.objects.filter(user=user, item=self).count():
            return False
        return True
    
    def can_be_downvoted_by(self, user):
        if not user.is_authenticated:
            return False
        if user == self.user:
            return False
        else:
            if user.karma > 1:
                if not Vote.objects.filter(user=user, item=self).count():
                    return True
        return False

    def can_be_edited_by(self, user):
        return self.user == user and self.num_comments == 0
    
    def can_be_deleted_by(self, user):
        return self.can_be_edited_by(user)



class Story(Item):
    class Meta:
        indexes = [
            models.Index(fields=['domain', 'duplicate_of']),
        ]
    is_story = True

    # class Meta:
    #     ordering = ['-pk']
    title = models.CharField(max_length=255, blank=True)
    url = models.URLField(null=True, blank=True)
    text = models.TextField(null=True, blank=True)
    duplicate_of = models.ForeignKey('Story', on_delete=models.CASCADE, null=True)
    domain = models.CharField(max_length=255, null=True, blank=True, db_index=True)
    

    def __str__(self):
        return self.title
    
    # @property
    # def domain(self):
    #     o = urlparse(self.url)
    #     return o.hostname

    def can_be_downvoted_by(self, user):
        return False

    # def Kcomments(self):
    #     return self.comments
    #     return {
    #         'all': self.get_descendants() # lambda: [i.comment for i in self.get_descendants().select_related('comment')]
    #     }
    #     return self.comments


class Comment(Item):
    is_comment = True

    text = models.TextField()
    to_story = models.ForeignKey(Story, on_delete=models.CASCADE, related_name="comments")

    def __str__(self):
        return self.text[:255]

    def comments(self):
        return {
            #'all': lambda: [i.comment for i in self.get_descendants().select_related('comment')]
            'all': lambda: [i.comment for i in self.get_descendants()]
        }


class Vote(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    changed_at = models.DateTimeField(auto_now=True)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    # vote = None # -1 | 0 | 1 --> BooleanField(default=None, null=True)??
    vote = models.SmallIntegerField(default=1)
    user = models.ForeignKey(to=CustomUser, on_delete=models.CASCADE)




================================================
FILE: news/receivers.py
================================================
#from django.core.signals import request_finished
from django.db.models.signals import pre_save, post_save, post_delete
from django.dispatch import receiver

from urllib.parse import urlparse

from .models import Item, Vote, Comment, Story

@receiver(pre_save)
def mark_show_and_ask(sender, instance, **kwargs):
    if isinstance(instance, Story):
        if instance.title.lower().startswith('ask'):
            instance.is_ask = True
        if instance.title.lower().startswith('show'):
            instance.is_show = True


@receiver(post_save)
def create_self_upvote_for_submission(sender, instance, created, **kwargs):
    if created and isinstance(instance, Item):
        vote = Vote(item=instance, user=instance.user)
        vote.save()


@receiver(post_save)
def check_for_duplicates(sender, instance, created, **kwargs):
    if created and isinstance(instance, Story):
        story = instance
        if story.url and story.duplicate_of is None:
            other_stories = Story.objects.filter(url=story.url).exclude(pk=story.pk).order_by('-changed_at')
            c = other_stories.count()
            if c > 0:
                new_vote = Vote(item=other_stories[0], vote=1, user=story.user)
                new_vote.save()
                story.duplicate_of = other_stories[0]
                story.save()


@receiver(post_save)
def update_votes_count_on_submission(sender, instance, created, **kwargs):
    if created and isinstance(instance, Vote):
        vote = instance
        item = instance.item
        other_votes = Vote.objects.filter(item=vote.item, user=vote.user, vote=vote.vote).exclude(pk=vote.pk)
        if other_votes.count():
            return
        if instance.vote > 0:
            item.upvotes += instance.vote
        else:
            item.downvotes += (-1)*instance.vote
        item.points += instance.vote
        item.save()


@receiver(post_save)
def update_user_karma_on_vote(sender, instance, created, **kwargs):
    if created and isinstance(instance, Vote):
        vote = instance
        other_votes = Vote.objects.filter(item=vote.item, user=vote.user, vote=vote.vote).exclude(pk=vote.pk)
        if other_votes.count():
            return
        item = instance.item
        if item.user != instance.user:
            item.user.karma += instance.vote
            item.user.save()


def _recount_comments(instance, val=1):
    assert isinstance(instance, Comment)
    instance.to_story.num_comments += val
    instance.to_story.save()
    parent = instance.parent
    while parent is not None:
        parent.num_comments += val
        parent.save()
        parent = parent.parent


@receiver(post_save)
def update_comments_count_on_submission(sender, instance, created, **kwargs):
    if created and isinstance(instance, Comment):
        _recount_comments(instance, 1)


@receiver(post_delete)
def update_comments_count_on_deletion(sender, instance, **kwargs):
    if isinstance(instance, Comment):
        _recount_comments(instance, -1)


@receiver(post_delete)
def update_item_votes_on_unvote(sender, instance, **kwargs):
    if isinstance(instance, Vote):
        vote = instance
        item = vote.item
        if vote.user == item.user:
            return
        item.points -= vote.vote
        if vote.vote > 0:
            item.upvotes -= abs(vote.vote)
        else:
            item.downvotes -= abs(vote.vote)
        item.save()


@receiver(post_delete)
def update_user_karma_on_unvote(sender, instance, **kwargs):
    if isinstance(instance, Vote):
        vote = instance
        item = vote.item
        if vote.user == item.user:
            return
        item.user.karma -= vote.vote
        item.user.save()


@receiver(pre_save)
def add_domain_to_link_stories(sender, instance, **kwargs):
    if isinstance(instance, Story):
        if instance.url:
            o = urlparse(instance.url)
            instance.domain = o.hostname.lower()

================================================
FILE: news/templates/news/__base.html
================================================
{% load static %}{% load humanize %}{% load emaildigest_extra %}<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta property="og:locale" content="en_US" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="{{SITE_NAME}}">
    <meta property="og:site_name" content="{{SITE_NAME}}">
    <meta name="generator" content="Python+Django" />
    <meta name="theme-color" content="#306998" />
    <meta name="robots" content="index,follow" />
    <meta name="googlebot" content="index,follow" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <meta name="renderer" content="webkit|ie-comp|ie-stand" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="emoji" content="🐍" />
    <link rel="stylesheet" type="text/css" href="{% static 'news.css'%}" />
    <link rel="icon" type="image/png" sizes="144x144" href="{% static 'icon.png' %}" />
    <!--<link rel="alternate" type="application/rss+xml" title="RSS" href="/rss" />-->
    <meta name="google-site-verification" content="WDbUHr8ccfJXaHWxNrjsVYPOMC8ooxhgHil3BLKkslA" />
    <meta name="msvalidate.01" content="9F28DFABF82B307C80AA587B7FC11195" />
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-437457-25"></script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'UA-437457-25');
    </script>

    <title>{% block title %}{% endblock title %}{{SITE_NAME}}</title>
</head>


<body>
    <main id="pnmain">
        <nav id="top-bar">
            <table border="0" cellpadding="0" cellspacing="0" width="100%" style="padding:2px">
                <tbody>
                    <tr>
                        <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>
                        <td style="line-height:12pt; height:10px;">
                            <span class="pagetop">
                            <b class="pnname">

                            <a href="{% url 'index' %}">{{SITE_NAME}}</a></b>
                            {% url 'newest' as url %}
                            <a href="{{ url }}" {% if url == request.path %}class="active"{% endif %}>new</a>
                            | {% url 'threads' as url %}
                            <a href="{{ url }}" {% if url == request.path %}class="active"{% endif %}>threads</a>
                            | {% url 'comments' as url %}
                            <a href="{{ url }}" {% if url == request.path %}class="active"{% endif %}>comments</a>
                            | {% url 'ask' as url %}
                            <a href="{{ url }}" {% if url == request.path %}class="active"{% endif %}>ask</a>
                            | {% url 'show' as url %}
                            <a href="{{ url }}" {% if url == request.path %}class="active"{% endif %}>show</a>
                            {% url 'submit' as url %}
                            | <a href="{{ url }}" {% if url == request.path %}class="active"{% endif %}>submit</a>
                            </span></td>
                        <td style="text-align:right;padding-right:4px;">
                        <span class="pagetop">
                            {% if user.is_authenticated %}
                            {% url 'accounts_my_profile' as url %}
                            <a href="{{ url }}" {% if url == request.path %}class="active"{% endif %}>{{user}}</a> ({{user.karma}}) 
                            | <form method="POST" action="{% url 'logout' %}" class="logout-form">{% csrf_token %}&nbsp;<button class="logout-button">logout</button></form>
                            {% else %}
                            {% url 'login' as url %}
                            <a href="{{ url }}" {% if url == request.path %}class="active"{% endif %}>login</a>
                            {% url 'accounts_register' as url %}
                            | <a href="{{ url }}" {% if url == request.path %}class="active"{% endif %}>register</a>
                            {% endif %}
                        </span></td>
                    </tr>
                </tbody>
            </table>
        </nav>

{% block content %}{% endblock content %}

        <nav id="pre-footer-bar">
            <hr>
            {% if not prevent_footer_subscription_form %}
                {% digest_subscription_form user=user %}
            {% endif %}
        </nav>


        <nav id="footer-bar">
            <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>
        </nav>
    </main>
<script type="text/javascript" src="{% static 'news.js'%}"></script>
</body>
</html>

================================================
FILE: news/templates/news/_item_content_tag.html
================================================
{% load news_extra %}

<div style="margin-bottom:3pt; ">
                    {% if item.title %}
                    <span class="title">
                        {% if item.url %}
                            <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 %}
                        {% else %}
                            <a href="{{item.get_absolute_url}}">{{item.title}}</a>
                        {% endif %}
                    </span>
                    {% endif %}
                    {% if item.text and not hide_text %}
                        {{ item.text | comment_markdown }}
                    {% endif %}
</div>


================================================
FILE: news/templates/news/_item_control_tag.html
================================================
{% load humanize %}
{% load news_extra %}
                    <span class="controls">
                            <span class="smaller">
                                {{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>
                                | flag
                                | hide
                                | <a href="{{item.get_absolute_url}}">{{item.num_comments}} comments</a></span>
                                {% if item.num_comments == 0 and item.user == request_user %}| <a href="{% url 'edit' pk=item.pk %}">edit</a></span>{% endif %}
                                {% if item.num_comments == 0 and item.user == request_user %}| <a href="{% url 'delete' pk=item.pk %}">delete</a></span>{% endif %}
                    </span>

================================================
FILE: news/templates/news/_item_tag.html
================================================
{% load humanize %}
{% load static %}
{% load news_extra %}


            <tr id="{{item.pk}}">
                <td rowspan="2" class="rank">{%if rank %}{{rank}}.{% endif %}</td>
                <td rowspan="2"><div>

                    {% user_arrows user=user item=item as assignment_options %}

                    {% if 'star' in assignment_options %}
                    <span class="self-item">*</span>
                    {% endif %}
                    {% if 'up' in assignment_options %}
                    <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>
                    {% endif %}
                    {% if 'down' in assignment_options %}
                    <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>
                    {% endif %}
                    {% if not assignment_options %}
                    &nbsp;
                    {% endif %}

                    </div></td>
                <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>
            </tr>
            <tr>
                <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>
            </td>


            <tr class="spacer"></tr>

================================================
FILE: news/templates/news/_link_user_tag.html
================================================
<a class="{% if user.is_green %}green{% endif %}" href="{{user.get_absolute_url}}">{{user}}</a>

================================================
FILE: news/templates/news/_more_link_tag.html
================================================
<a href="{{more_link}}" class="more-link">More</a>

================================================
FILE: news/templates/news/bookmarklet.html
================================================
{% extends "news/__base.html" %}
{% load humanize %}
{% load static %}
{% load mptt_tags %}
{% load news_extra %}


{% block content %}
<article class="site-content">


<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>

<center>
<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>
</center>


</article>

{% endblock content %}

================================================
FILE: news/templates/news/formatting_help.html
================================================
<div class="formatting-help closed">
    <table>
        <thead>
            <tr>
                <th>Markdown</th>
                <th>Output</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><pre># Heading level 1</pre></td>
                <td><h3>Heading level 1</h3></td>
            </tr>
            <tr>
                <td><pre>## Heading level 2</pre></td>
                <td><h4>Heading level 2</h3></td>
            </tr>
            <tr>
                <td><pre>### Heading level 3</pre></td>
                <td><h5>Heading level 3</h3></td>
            </tr>
            <tr>
                <td><pre>#### Heading level 4</pre></td>
                <td><h6>Heading level 4</h3></td>
            </tr>
            <tr>
                <td><pre>
* unordered item 1
* unordered item 2
* unordered item 3
                </pre></td>
                <td>
                    <ul>
                        <li>unordered item 1</li>
                        <li>unordered item 2</li>
                        <li>unordered item 3</li>
                    </ul>
                </td>
            </tr>
            <tr>
                <td><pre>
1. ordered item 1
2. ordered item 2
3. ordered item 3
                </pre></td>
                <td>
                    <ol>
                        <li>ordered item 1</li>
                        <li>ordered item 2</li>
                        <li>ordered item 3</li>
                    </ol>
                </td>
            </tr>
            <tr>
                <td><pre>
[title](https://www.google.com/)
                </pre></td>
                <td>
                    <a href="#">title</a>
                </td>
            </tr>
        </tbody>
    </table>
</div>
<script>
const helpElm = document.querySelector('.formatting-help');
let helpClosed = true;
window.toggleFormattingHelp = function() {
    helpClosed = !helpClosed;
    helpElm.className = 'formatting-help ' + (helpClosed ? 'closed' : '');
};
</script>


================================================
FILE: news/templates/news/index.html
================================================
{% extends "news/__base.html" %}
{% load humanize %}
{% load static %}
{% load mptt_tags %}
{% load news_extra %}


{% block content %}
<article class="site-content-dense">
<table border="0" cellpadding="0" cellspacing="0" class="item-list outer level-0">
        {% for story in stories %}
                {% news_item item=story show_text=False hide_text=hide_text rank=forloop.counter|add:rank_start user=user %}
                {% if show_children %}
                    <tr><td></td><td></td><td>
                        {% recursetree story.comments.all  %}
                        <table border="0" cellpadding="0" cellspacing="0" class="item-list inner level-{{node.level}}" style="">
                            {% news_item item=node show_text=True hide_text=hide_text rank=None user=user %}
                            {% if not node.is_leaf_node %}
                                <tr><td></td><td></td><td>
                                    {{ children }}
                                </td></tr>
                            {% endif %}
                        </table>
                        {% endrecursetree %}
                    </td></tr>
                {% endif %}
        {% endfor %}
</table>




        <a href="?p={{page|add:1}}">{% more_link %}</a>

</article>

{% endblock content %}

================================================
FILE: news/templates/news/item.html
================================================

{% extends 'news/__base.html' %}
{% load humanize %}
{% load mptt_tags %}
{% load news_extra %}





{% block content %}
<article class="site-content-dense">



<table  border="0" cellpadding="0" cellspacing="0" class="item-list">
        {% news_item item=item rank=None hide_text=False user=user %}
</table>




{% if comment_form %}
<form method="POST" class="comment-form clearfix">{% csrf_token %}
    {{ comment_form.text }}
    <p class="clearfix small"></p>
    <button type="submit">add comment</button>
    <ul class="horizontal-list">
        <li><a class="smaller" href="{% url 'zen' %}">guidelines</a></li>
        <li><a class="smaller" href="javascript:toggleFormattingHelp()">formatting help</a></li>
    </ul>
</form>

{% include "news/formatting_help.html" %}

{% endif %}


<br><br>


<table  border="0" cellpadding="0" cellspacing="0" class="item-list">
    {% recursetree item.comments.all  %}
            {% news_item item=node rank=None show_text=True hide_text=False user=user %}
            {% if not node.is_leaf_node %}
            <tr><td colspan="3" style="padding-left:30px;">
                    <table border="0" cellpadding="0" cellspacing="0" class="item-list" style="border-left:1px solid grey;">
                        {{ children }}
                    </table>
            </td></tr>
            {% endif %}
    {% endrecursetree %}
</table>




</article>
{% endblock content %}


================================================
FILE: news/templates/news/item_delete.html
================================================

{% extends 'news/__base.html' %}
{% load humanize %}
{% load mptt_tags %}
{% load news_extra %}





{% block content %}
<article class="site-content-dense">

Are you sure, you want to delete this: <br>


<div style="margin:2em;">
<table  border="0" cellpadding="0" cellspacing="0" class="item-list">
        {% news_item item=item rank=None hide_text=False user=user %}
</table>
</div> 

<form method="POST" class="comment-form" >{% csrf_token %}
    <button type="submit">delete item</button>
</form>



</article>
{% endblock content %}

================================================
FILE: news/templates/news/item_edit.html
================================================

{% extends 'news/__base.html' %}
{% load humanize %}
{% load mptt_tags %}
{% load news_extra %}





{% block content %}
<article class="site-content-dense">



<table  border="0" cellpadding="0" cellspacing="0" class="item-list">

        {% news_item item=item rank=None hide_text=False user=user %}

</table>




{% if edit_form %}
<form method="POST" class="comment-form" >{% csrf_token %}
    {{ edit_form.text }}<a class="smaller" href="{% url 'zen' %}">guidelines</a>
    <br>
    <button type="submit">save item</button>
</form>
{% endif %}


</article>
{% endblock content %}

================================================
FILE: news/templates/news/submit.html
================================================
{% extends 'news/__base.html' %}

{% block content %}
<article class="site-content-dense">
<form method="POST">{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<button type="submit">submit</button>
</form>

<p>
Leave 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.
</p><p>
You can also submit via <a href="{% url 'bookmarklet' %}">bookmarklet</a>.
</p>


</article>
{% endblock content %}

================================================
FILE: news/templates/news/zen.html
================================================

{% extends 'news/__base.html' %}
{% load humanize %}
{% load mptt_tags %}



{% block content %}




<article class="site-content">
    
        <h2>The Zen of {{SITE_NAME}} (aka Guidelines)</h2>

        <p class="smaller">Based on <a href="https://www.python.org/dev/peps/pep-0020/">The Zen of Python</a></p>

        <p>{{SITE_NAME}} is a platform for friends of <a href="https://python.org">Python</a>
        (the programming language).<br>
        It shall enable people to discover, share and discuss interesting thoughts, publications or web pieces about
        Python and its related fields.<br>
        On the platform, anybody shall feel welcomed.
        </p>


        <h3>Beautiful is better than ugly.</h3>
        <p>
        Be beautiful to each other. Always remember, {{SITE_NAME}} is a community built around Python stuff, which
        is mostly technical. When discussing this kind of stuff, there is no need to offend someone personally. 
        </p>

        <h3>Explicit is better than implicit.</h3>
        <p>Be on-topic. We are here to discuss the Python programming language, its ecosystem, its applications and
        its community. For off-topic discussions there are plenty of forums out there on the net. <br>
        This community regards political discussions as off-topic, unless discussion the walrus operator (just kidding).</p>

        <h3>In the face of ambiguity, refuse the temptation to guess.</h3>
        <p>Please think of a contribution of another member of this community as well-intended. We should all assume
        that people here behave nicely and respectful. </p>

        <!--<h3>Now is better than never.</h3>
        <p></p>

        <h3>Although never is often better than *right* now.</h3>
        <p></p>-->

        <h3>Errors should never pass silently.</h3>
        <p>We value transparency. If there is any action taken by moderators on submissions, comments or user accounts,
        we try to be as clear about what happened as possible. For now, there is no moderation system in place. This means
        that we might be forced to delete contributions silently when we notice off-topic, disrespectful or otherwise abusive
        content without further notice. However, a moderation audit trail is on the roadmap to be implemented soon</p>


        <h3>Code of Conduct</h3>
        <p>This is a news aggregator and we all want to be nice to each other. Rude behaviour in form of continiously spamming,
        posting off-topic content, offending people ad-hominem, will result in a ban.</p>

        <!--Beautiful is better than ugly.
        Explicit is better than implicit.
        Simple is better than complex.
        Complex is better than complicated.
        Flat is better than nested.
        Sparse is better than dense.
        Readability counts.
        Special cases aren't special enough to break the rules.
        Although practicality beats purity.
        Errors should never pass silently.
        Unless explicitly silenced.
        In the face of ambiguity, refuse the temptation to guess.
        There should be one-- and preferably only one --obvious way to do it.
        Although that way may not be obvious at first unless you're Dutch.
        Now is better than never.
        Although never is often better than *right* now.
        If the implementation is hard to explain, it's a bad idea.
        If the implementation is easy to explain, it may be a good idea.
        Namespaces are one honking great idea -- let's do more of those!-->
    

</article>






{% endblock content %}

================================================
FILE: news/templatetags/__init__.py
================================================


================================================
FILE: news/templatetags/news_extra.py
================================================
from django import template
from django.utils.safestring import mark_safe

import mistune

register = template.Library()

@register.inclusion_tag('news/_item_tag.html', takes_context=True)
def news_item(context, item, **kwargs):
    kwargs['item'] = item
    kwargs['request_user'] = context['user']
    return kwargs

@register.inclusion_tag('news/_link_user_tag.html')
def link_user(user):
    return {
        'user': user
    }

@register.simple_tag
def user_arrows(user, item):
    if user == item.user:
        return ['star']
    else:
        res = []
        if item.can_be_upvoted_by(user=user):
            res.append('up')
        if item.can_be_downvoted_by(user=user):
            res.append('down')
        return res


@register.inclusion_tag('news/_more_link_tag.html', takes_context=True)
def more_link(context):
    request = context.request
    page = int(request.GET.get('p', 0))
    query_dict = request.GET.copy()
    query_dict['p'] = page + 1
    _more_link=request.path_info + '?' + query_dict.urlencode()
    return {'more_link': _more_link}


@register.inclusion_tag('news/_item_content_tag.html')
def item_content(**kwargs):
    return kwargs


@register.inclusion_tag('news/_item_control_tag.html')
def item_control(**kwargs):
    return kwargs


class MarkdownRenderer(mistune.Renderer):

    @classmethod
    def setup(cls):
        renderer = cls(escape=True, hard_wrap=True)
        return mistune.Markdown(renderer=renderer)

    def header(self, text, level, raw=None):
        level = min(level + 2, 6)
        return super().header(text, level, raw)


markdown = MarkdownRenderer.setup()

@register.filter
def comment_markdown(value):
    return mark_safe(markdown(value))


================================================
FILE: news/tests.py
================================================
from django.contrib.auth.models import AnonymousUser
from accounts.models import CustomUser
from django.test import RequestFactory, TestCase

from .views import *
from .models import *

class BasicNewsTest(TestCase):
    """Tests the basic functionality of the news app."""
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = CustomUser.objects.create_user(
            username='sebst', email='hi@seb.st', password='top_secret')
        self.other_user = CustomUser.objects.create_user(
            username='bla1', email='two@seb.st', password='top_secret')
        
    def test_submit_get(self):
        """The submit form is displayed."""
        request = self.factory.get('/submit')
        request.user = self.user
        response = submit(request)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, '<form')
    
    def test_submit_post_with_title_and_url(self):
        """Submission is posted with title and URL."""
        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})
        request.user = self.user
        response = submit(request)
        self.assertEqual(response.status_code, 302)

    def test_submit_post_with_title_without_url(self):
        """Submission with only title should fail."""
        request = self.factory.post('/submit', {'title': 'test-post-asdf'})
        request.user = self.user
        response = submit(request)
        self.assertEqual(response.status_code, 200)

    def test_submit_and_frontpage_and_newest(self):
        """A submission should appear on frontpage (as we have an empty database) and on the newest page."""
        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})
        request.user = self.user
        response = submit(request)

        request = self.factory.get('/')
        request.user = self.user
        response = index(request)

        self.assertContains(response, 'test-post-asdf')


        request = self.factory.get('/newest')
        request.user = self.user
        response = index(request)

        self.assertContains(response, 'test-post-asdf')

    def test_submit_and_upvote(self):
        """A submission can be upvoted."""
        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})
        request.user = self.other_user
        response = submit(request)
        item_url = response.url
        pk = item_url.split('/')[-1]

        upvote_url = item_url + "/upvote"

        request = self.factory.post(upvote_url, {})
        request.user = self.user
        response = upvote(request, pk=pk)
        self.assertContains(response, "OK")

        item = Item.objects.get(pk=pk)
        self.assertEqual(item.upvotes, 2)
        self.assertEqual(item.points, 2)
        #self.assertEqual(self.other_user.karma, 1) # Karma of submitting user should have increased
        self.assertEqual(item.user.karma, 1) # Karma of submitting user should have increased
        self.assertEqual(CustomUser.objects.get(pk=self.user.pk).karma, 0) # Karma of voting user should have stayed the same

    def test_submit_and_upvote_and_unvote(self):
        """A submission can be upvoted."""
        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})
        request.user = self.other_user
        response = submit(request)
        item_url = response.url
        pk = item_url.split('/')[-1]

        upvote_url = item_url + "/upvote"

        request = self.factory.post(upvote_url, {})
        request.user = self.user
        response = upvote(request, pk=pk)
        self.assertContains(response, "OK")

        item = Item.objects.get(pk=pk)
        self.assertEqual(item.upvotes, 2)
        self.assertEqual(item.points, 2)
        #self.assertEqual(self.other_user.karma, 1) # Karma of submitting user should have increased
        self.assertEqual(item.user.karma, 1) # Karma of submitting user should have increased
        self.assertEqual(CustomUser.objects.get(pk=self.user.pk).karma, 0) # Karma of voting user should have stayed the same

        self.fail() # TODO: Test unvote


    def test_submit_and_downvote(self):
        """A submission cannot be downvoted."""
        request = self.factory.post('/submit', {'title': 'test-post-asdf-12', 'url': 'https://sebastiansteins.com/12'})
        request.user = self.other_user
        response = submit(request)
        item_url = response.url
        pk = item_url.split('/')[-1]

        vote_url = item_url + "/downvote"

        request = self.factory.post(vote_url, {})
        request.user = self.user
        response = downvote(request, pk=pk)
        self.assertEqual(response.status_code, 403)


    def test_submit_and_upvote_self(self):
        """A submission cannot be upvoted by the submitting user."""
        request = self.factory.post('/submit', {'title': 'test-post-asdf', 'url': 'https://sebastiansteins.com'})
        request.user = self.user
        response = submit(request)
        item_url = response.url
        pk = item_url.split('/')[-1]

        upvote_url = item_url + "/upvote"

        request = self.factory.post(upvote_url, {})
        request.user = self.user
        response = upvote(request, pk=pk)
        self.assertEqual(response.status_code, 403)


    def test_ask(self):
        """An Ask Submission should appear in ask."""
        request = self.factory.post('/submit', {'title': 'Ask: test-post-asdf', 'url': 'https://sebastiansteins.com'})
        request.user = self.user
        response = submit(request)

        request = self.factory.get('/ask')
        request.user = self.user
        response = index(request)

        submission = Item.objects.get()
        self.assertEqual(submission.is_show, False)
        self.assertEqual(submission.is_ask, True)

        self.assertContains(response, 'test-post-asdf')

    def test_show(self):
        """A Show Submission should appear in show."""
        request = self.factory.post('/submit', {'title': 'Show: test-post-asdf', 'url': 'https://sebastiansteins.com'})
        request.user = self.user
        response = submit(request)

        request = self.factory.get('/show')
        request.user = self.user
        response = index(request)

        submission = Item.objects.get()
        self.assertEqual(submission.is_show, True)
        self.assertEqual(submission.is_ask, False)

        self.assertContains(response, 'test-post-asdf')


    def test_comment(self):
        """A user can comment on a submission."""
        submission = Story(
            user=self.other_user,
            title="Test-1234",
            text="bla"
        )
        submission.save()
        self.assertEqual(Story.objects.get(pk=submission.pk).num_comments, 0)

        request = self.factory.post(submission.get_absolute_url, {'text': 'ACOMMENT'})
        request.user = self.user
        response = item(request, pk=submission.pk)
        self.assertEqual(response.status_code, 302)
        
        self.assertEqual(Story.objects.get(pk=submission.pk).num_comments, 1)

        request = self.factory.get('/item/'+str(submission.pk))
        request.user = self.user
        response = item(request, pk=submission.pk)
        self.assertContains(response, "ACOMMENT")

        request = self.factory.get('/comments')
        request.user = self.user
        response = comments(request)
        self.assertContains(response, "ACOMMENT")

    def test_owner_can_edit_comment(self):
        _item = Story(title="Test story", user=self.other_user, text='Bla')
        _item.save()

        comment = Comment(to_story=_item, text='A Comment', user=self.user)
        comment.save()

        self.assertEqual(comment.text, 'A Comment')

        url = '/item/%s/edit'%(comment.pk)
        request = self.factory.post(url, {'text': 'B Comment'})
        request.user = self.user
        response = item_edit(request, pk=comment.pk)
        self.assertEqual(response.status_code, 302)

        comment = Comment.objects.get(pk=comment.pk)
        self.assertEqual(comment.text, 'B Comment')


    def test_owner_cannot_edit_comment_with_children(self):
        _item = Story(title="Test story", user=self.other_user, text='Bla')
        _item.save()

        comment = Comment(to_story=_item, text='A Comment', user=self.user)
        comment.save()

        comment2 = Comment(to_story=_item, text='XXXX', user=self.user, parent=comment)
        comment2.save()

        self.assertEqual(comment.text, 'A Comment')

        url = '/item/%s/edit'%(comment.pk)
        request = self.factory.post(url, {'text': 'B Comment'})
        request.user = self.user
        response = item_edit(request, pk=comment.pk)
        self.assertEqual(response.status_code, 403)

        comment = Comment.objects.get(pk=comment.pk)
        self.assertEqual(comment.text, 'A Comment')


    def test_owner_can_edit_story(self):
        _item = Story(title="Test story", user=self.user, text='Bla')
        _item.save()

        self.assertEqual(_item.text, 'Bla')

        url = '/item/%s/edit'%(_item.pk)
        request = self.factory.post(url, {'text': 'B Comment'})
        request.user = self.user
        response = item_edit(request, pk=_item.pk)
        self.assertEqual(response.status_code, 302)

        _item = Story.objects.get(pk=_item.pk)
        self.assertEqual(_item.text, 'B Comment')


    def test_owner_cannot_edit_story_url(self):
        _item = Story(title="Test story", user=self.user, text='Bla', url="https://test1.example.org")
        _item.save()

        self.assertEqual(_item.text, 'Bla')

        url = '/item/%s/edit'%(_item.pk)
        request = self.factory.post(url, {'url': 'https://example.org'})
        request.user = self.user
        response = item_edit(request, pk=_item.pk)
        self.assertEqual(response.status_code, 302)

        _item = Story.objects.get(pk=_item.pk)
        self.assertEqual(_item.url, 'https://test1.example.org')


    def test_owner_cannot_edit_story_with_comments(self):
        _item = Story(title="Test story", user=self.user, text='Bla')
        _item.save()

        comment = Comment(to_story=_item, text='A Comment', user=self.user)
        comment.save()

        self.assertEqual(_item.text, 'Bla')

        url = '/item/%s/edit'%(_item.pk)
        request = self.factory.post(url, {'text': 'B Comment'})
        request.user = self.user
        response = item_edit(request, pk=_item.pk)
        self.assertEqual(response.status_code, 403)

        _item = Story.objects.get(pk=_item.pk)
        self.assertEqual(_item.text, 'Bla')


    def test_other_cannot_edit_comment(self):
        _item = Story(title="Test story", user=self.other_user, text='Bla')
        _item.save()

        comment = Comment(to_story=_item, text='A Comment', user=self.user)
        comment.save()

        self.assertEqual(comment.text, 'A Comment')

        url = '/item/%s/edit'%(comment.pk)
        request = self.factory.post(url, {'text': 'B Comment'})
        request.user = self.other_user
        response = item_edit(request, pk=comment.pk)
        self.assertEqual(response.status_code, 403)

        comment = Comment.objects.get(pk=comment.pk)
        self.assertEqual(comment.text, 'A Comment')

    def test_other_cannot_edit_story(self):
        _item = Story(title="Test story", user=self.user, text='Bla')
        _item.save()

        self.assertEqual(_item.text, 'Bla')

        url = '/item/%s/edit'%(_item.pk)
        request = self.factory.post(url, {'text': 'B Comment'})
        request.user = self.other_user
        response = item_edit(request, pk=_item.pk)
        self.assertEqual(response.status_code, 403)

        _item = Story.objects.get(pk=_item.pk)
        self.assertEqual(_item.text, 'Bla')

    def test_owner_can_delete_comment(self):
        story = Story(title='A story', user=self.user, url="https://example.org")
        story.save()

        comment = Comment(to_story=story, user=self.user, text="a comment")
        comment.save()

        url = '/item/%s/delete'%(comment.pk)
        request = self.factory.get(url)
        request.user = self.user
        response = item_delete(request, pk=comment.pk)
        self.assertContains(response, 'sure')

        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)

        request = self.factory.post(url)
        request.user = self.user
        response = item_delete(request, pk=comment.pk)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, story.get_absolute_url())

        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 0)


    def test_owner_cannot_delete_comment_with_children(self):
        story = Story(title='A story', user=self.user, url="https://example.org")
        story.save()

        comment = Comment(to_story=story, user=self.user, text="a comment")
        comment.save()

        comment2 = Comment(to_story=story, user=self.user, text="another comment", parent=comment)
        comment2.save()

        url = '/item/%s/delete'%(comment.pk)
        request = self.factory.get(url)
        request.user = self.user
        response = item_delete(request, pk=comment.pk)
        self.assertEqual(response.status_code, 403)

        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)

        request = self.factory.post(url)
        request.user = self.user
        response = item_delete(request, pk=comment.pk)
        self.assertEqual(response.status_code, 403)

        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)


    def test_owner_can_delete_story(self):
        story = Story(title='A story', user=self.user, url="https://example.org")
        story.save()


        url = '/item/%s/delete'%(story.pk)
        request = self.factory.get(url)
        request.user = self.user
        response = item_delete(request, pk=story.pk)
        self.assertContains(response, 'sure')

        self.assertEqual(Story.objects.filter(pk=story.pk).count(), 1)

        request = self.factory.post(url)
        request.user = self.user
        response = item_delete(request, pk=story.pk)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, '/')

        self.assertEqual(Story.objects.filter(pk=story.pk).count(), 0)


    def test_other_cannot_delete_comment(self):
        story = Story(title='A story', user=self.user, url="https://example.org")
        story.save()

        comment = Comment(to_story=story, user=self.user, text="a comment")
        comment.save()

        url = '/item/%s/delete'%(comment.pk)
        request = self.factory.get(url)
        request.user = self.other_user
        response = item_delete(request, pk=comment.pk)
        self.assertEqual(response.status_code, 403)

        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)

        request = self.factory.post(url)
        request.user = self.other_user
        response = item_delete(request, pk=comment.pk)
        self.assertEqual(response.status_code, 403)

        self.assertEqual(Comment.objects.filter(pk=comment.pk).count(), 1)


    def test_other_cannot_delete_story(self):
        story = Story(title='A story', user=self.user, url="https://example.org")
        story.save()

        url = '/item/%s/delete'%(story.pk)
        request = self.factory.get(url)
        request.user = self.other_user
        response = item_delete(request, pk=story.pk)
        self.assertEqual(response.status_code, 403)

        self.assertEqual(Story.objects.filter(pk=story.pk).count(), 1)

        request = self.factory.post(url)
        request.user = self.other_user
        response = item_delete(request, pk=story.pk)
        self.assertEqual(response.status_code, 403)

        self.assertEqual(Story.objects.filter(pk=story.pk).count(), 1)


    def test_zen(self):
        s = 'The Zen of'
        url = '/zen'
        request = self.factory.get(url)
        request.user = self.user
        response = zen(request)
        self.assertContains(response, s)


    def test_comments(self):
        url = '/comments'
        request = self.factory.get(url)
        request.user = self.user
        response = comments(request)
        self.assertEqual(response.status_code, 200)

    def test_threads(self):
        url = '/threads'
        request = self.factory.get(url)
        request.user = self.user
        response = threads(request)
        self.assertEqual(response.status_code, 200)

    def test_newest(self):
        url = '/newest'
        request = self.factory.get(url)
        request.user = self.user
        response = newest(request)
        self.assertEqual(response.status_code, 200)

    def test_front_page(self):
        url = '/'
        request = self.factory.get(url)
        request.user = self.user
        response = index(request)
        self.assertEqual(response.status_code, 200)

    def test_more_button(self):
        self.fail() # TODO


class ReceiversNewsTest(TestCase):
    """Tests the basic functionality of the news app."""
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = CustomUser.objects.create_user(
            username='sebst', email='hi@seb.st', password='top_secret')
        self.other_user = CustomUser.objects.create_user(
            username='bla1', email='two@seb.st', password='top_secret')


    def test_mark_show_and_ask(self):
        story = Story(title="Ask: Some ask story", text="..", user=self.user)
        self.assertEqual(story.is_ask, False)
        story.save()
        story = Story.objects.get(pk=story.pk)
        self.assertEqual(story.is_ask, True)

        story = Story(title="Show: Some show story", text="..", user=self.user)
        self.assertEqual(story.is_show, False)
        story.save()
        story = Story.objects.get(pk=story.pk)
        self.assertEqual(story.is_show, True)


    def test_create_self_upvote_for_submission(self):
        story = Story(title="Some story", text="..", user=self.user)
        self.assertEqual(Vote.objects.filter(item=story).count(), 0)
        story.save()
        self.assertEqual(Vote.objects.filter(item=story).count(), 1)


    def test_check_for_duplicates(self):
        story = Story(title="Some story", url="http://example.org", user=self.user)
        story.save()

        story2 = Story(title="Once again", url="http://example.org", user=self.other_user)
        story2.save()

        story = Story.objects.get(pk=story.pk)
        story2 = Story.objects.get(pk=story2.pk)
        self.assertEqual(story.duplicate_of, None)
        # Duplicate story needs to be marked as duplicate
        self.assertEqual(story2.duplicate_of, story)
        # Second submission triggers upvote on original story
        self.assertEqual(Vote.objects.filter(item=story).count(), 2)


    def test_update_votes_count_on_submission(self):
        story = Story(title="Some story", url="http://example.org", user=self.user)
        story.save()

        self.assertEqual(Vote.objects.filter(item=story).count(), 1)

        vote = Vote(user=self.user, vote=1, item=story)
        vote.save()
        story = Story.objects.get(pk=story.pk)

        self.assertEqual(story.upvotes, 1)
        self.assertEqual(story.points, 1)
        self.assertEqual(story.downvotes, 0)

        vote2 = Vote(user=self.other_user, vote=-1, item=story)
        vote2.save()
        story = Story.objects.get(pk=story.pk)

        self.assertEqual(story.upvotes, 1)
        self.assertEqual(story.points, 0)
        self.assertEqual(story.downvotes, 1)



    def test_update_user_karma_on_vote(self):
        story = Story(title="Some story", url="http://example.org", user=self.user)
        story.save()

        user = CustomUser.objects.get(pk=self.user.pk)
        self.assertEqual(user.karma, 0)

        vote2 = Vote(user=self.other_user, vote=1, item=story)
        vote2.save()
        story = Story.objects.get(pk=story.pk)
        user = CustomUser.objects.get(pk=self.user.pk)

        self.assertEqual(user.karma, 1)


    def test_update_comments_count_on_submission(self):
        story = Story(title="Some story", url="http://example.org", user=self.user)
        story.save()

        story = Story.objects.get(pk=story.pk)
        self.assertEqual(story.num_comments, 0)

        comment1 = Comment(to_story=story, text="...", user=self.other_user)
        comment1.save()

        story = Story.objects.get(pk=story.pk)
        self.assertEqual(story.num_comments, 1)

        comment2 = Comment(to_story=story, text="...", user=self.user, parent=comment1)
        comment2.save()

        story = Story.objects.get(pk=story.pk)
        self.assertEqual(story.num_comments, 2)


    def test_update_comments_count_on_deletion(self):
        story = Story(title="Some story", url="http://example.org", user=self.user)
        story.save()

        story = Story.objects.get(pk=story.pk)
        self.assertEqual(story.num_comments, 0)

        comment1 = Comment(to_story=story, text="...", user=self.other_user)
        comment1.save()

        story = Story.objects.get(pk=story.pk)
        self.assertEqual(story.num_comments, 1)

        comment2 = Comment(to_story=story, text="...", user=self.user, parent=comment1)
        comment2.save()

        story = Story.objects.get(pk=story.pk)
        self.assertEqual(story.num_comments, 2)

        comment1.delete()
        story = Story.objects.get(pk=story.pk)
        self.assertEqual(story.num_comments, 0)


    def test_update_item_votes_on_unvote(self):
        story = Story(title="Some story", url="http://example.org", user=self.user)
        story.save()

        self.assertEqual(Vote.objects.filter(item=story).count(), 1)

        vote = Vote(user=self.user, vote=1, item=story)
        vote.save()
        story = Story.objects.get(pk=story.pk)

        self.assertEqual(story.upvotes, 1)
        self.assertEqual(story.points, 1)
        self.assertEqual(story.downvotes, 0)

        vote2 = Vote(user=self.other_user, vote=-1, item=story)
        vote2.save()
        story = Story.objects.get(pk=story.pk)

        self.assertEqual(story.upvotes, 1)
        self.assertEqual(story.points, 0)
        self.assertEqual(story.downvotes, 1)

        vote2.delete()

        story = Story.objects.get(pk=story.pk)

        self.assertEqual(story.upvotes, 1)
        self.assertEqual(story.points, 1)
        self.assertEqual(story.downvotes, 0)


    def test_update_user_karma_on_unvote(self):
        story = Story(title="Some story", url="http://example.org", user=self.user)
        story.save()

        user = CustomUser.objects.get(pk=self.user.pk)
        self.assertEqual(user.karma, 0)

        vote2 = Vote(user=self.other_user, vote=1, item=story)
        vote2.save()
        story = Story.objects.get(pk=story.pk)

        user = CustomUser.objects.get(pk=self.user.pk)
        self.assertEqual(user.karma, 1)

        vote2.delete()
        user = CustomUser.objects.get(pk=self.user.pk)
        self.assertEqual(user.karma, 0)


    def test_add_domain_to_link_stories(self):
        item = Story('title': 'bla', url='https://Example.org', user=self.user)
        item.save()

        item = Story.objects.get(pk=item.pk)
        self.assertEqual(item.domain, 'example.org')

================================================
FILE: news/urls.py
================================================


from django.urls import path, include

from . import views

from .feeds import NewestFeed, FrontPageFeed

urlpatterns = [
    path('', views.index, name="index"),
    path('newest', views.newest, name="newest"),
    path('threads', views.threads, name="threads"),
    path('comments', views.comments, name="comments"),
    path('show', views.show, name="show"),
    path('ask', views.ask, name="ask"),
    path('zen', views.zen, name="zen"),
    path('item/<uuid:pk>', views.item, name="item"),
    path('item/<uuid:pk>/upvote', views.upvote, name="upvote"), # TODO
    path('item/<uuid:pk>/downvote', views.downvote, name="downvote"), # TODO
    path('item/<uuid:pk>/edit', views.item_edit, name="edit"),
    path('item/<uuid:pk>/delete', views.item_delete, name="delete"),
    path('submit', views.submit, name="submit"),

    path('newest/feed/', NewestFeed()),
    path('feed/', FrontPageFeed()),

    path('robots.txt', views.robots_txt, name="robots_txt"),
    path('humans.txt', views.humans_txt, name="humans_txt"),
    path('bookmarklet', views.bookmarklet, name="bookmarklet"),
]


================================================
FILE: news/views.py
================================================
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponseForbidden
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.urls import reverse

from .models import Item, Story, Comment, Vote
from accounts.models import CustomUser
from .forms import CommentForm, AddStoryForm, StoryForm

from ratelimit.decorators import ratelimit


# create_story
# add_comment
# upvote / downvote / unvote
# flag / hide
# Tags?
# suggest changes
# save


DEFAULT_GET_RATE   = "2/s"
DEFAULT_VOTES_RATE = "10/m"
DEFAULT_POST_RATE  = "5/m"

TIMEOUT_MEDIUM = 0# 1*60 # one minute
TIMEOUT_SHORT  = 0# 1*2 # two seconds


from django.db.models.functions import Power, Now, Cast, Extract #, Min
from django.db.models import Value, F, Func, ExpressionWrapper, fields, Q, Min
from django.db.models import OuterRef, Subquery
from django.db import models
from django.utils import timezone
import datetime

from django.core.cache import cache
from django.views.decorators.vary import vary_on_cookie
from django.views.decorators.cache import cache_page

from django.db import connection


def _one_page_back(request):
    page = int(request.GET.get('p', 0))
    query_dict = request.GET.copy()
    page = page - 1
    if page >= 0:
        query_dict['p'] = page
    else:
        return None
    _more_link=request.path_info + '?' + query_dict.urlencode()
    return HttpResponseRedirect(_more_link)

def _front_page(paging_size=settings.PAGING_SIZE, page=0, add_filter={}, add_q=[], as_of=None, days_back=50):
    # TODO: weighting https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
    # (P-1) / (T+2)^G
    if as_of is None:
        now = timezone.now()
    else:
        now = as_of
    if connection.vendor == 'postgresql':
        now_value = Value(now, output_field=fields.DateTimeField())
        submission_age_float = ExpressionWrapper(  ( now_value - F('created_at')), output_field=fields.DurationField())
        submission_age_hours = ExpressionWrapper(Extract(F('tf'), 'epoch') / 60 / 60 + 2.1 , output_field=fields.FloatField())
        real_p = ExpressionWrapper(F('points') - 1, output_field=fields.FloatField())
        formula = ExpressionWrapper(   F('p') / ( Power(F('tfh'), F('g'))  +0.001)   , output_field=fields.FloatField())
        return Story.objects.select_related('user')\
                .filter(duplicate_of__isnull=True)\
                .filter(points__gte=1) \
                .filter(created_at__gte=now - datetime.timedelta(days=days_back)) \
                .filter(created_at__lte=now) \
                .filter(**add_filter) \
                .annotate(tf=submission_age_float) \
                .annotate(tfh=submission_age_hours) \
                .annotate(p=real_p) \
                .annotate(g=Value(1.8, output_field=fields.FloatField())) \
                .annotate(formula=formula) \
                .order_by('-formula')[(page*paging_size):(page+1)*(paging_size)]
    elif connection.vendor == 'sqlite':
        now_value = Value(now, output_field=fields.DateTimeField())
        submission_age_float = ExpressionWrapper(  ( now_value - F('created_at')), output_field=fields.FloatField())
        submission_age_hours = ExpressionWrapper(F('tf') / 60 / 60 / 1000000 + 2.1 , output_field=fields.FloatField())
        real_p = ExpressionWrapper(F('points') - 1, output_field=fields.FloatField())
        formula = ExpressionWrapper(   F('p') / ( Power(F('tfh'), F('g'))  +0.001)   , output_field=fields.FloatField())
        return Story.objects.select_related('user')\
                .filter(duplicate_of__isnull=True)\
                .filter(points__gte=1) \
                .filter(created_at__gte=now - datetime.timedelta(days=days_back)) \
                .filter(created_at__lte=now) \
                .filter(**add_filter) \
                .annotate(tf=submission_age_float) \
                .annotate(tfh=submission_age_hours) \
                .annotate(p=real_p) \
                .annotate(g=Value(1.8, output_field=fields.FloatField())) \
                .annotate(formula=formula) \
                .order_by('-formula')[(page*paging_size):(page+1)*(paging_size)]
    else: 
        raise NotImplementedError("No frontpage magic for database engine %s implemented"%(connection.vendor))


def _newest(paging_size=settings.PAGING_SIZE, page=0, add_filter={}, add_q=[]):
    return Story.objects \
                .select_related('user') \
                .filter(duplicate_of__isnull=True) \
                .filter(**add_filter) \
                .filter(*add_q) \
                .order_by('-created_at')[(page*paging_size):(page+1)*(paging_size)]


@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True)
def index(request):
    page = int(request.GET.get('p', 0))
    stories = cache.get_or_set("news-index-%s"%(page), lambda: list(_front_page(page=page)), timeout=TIMEOUT_MEDIUM) # one minute
    if len(stories) < 1 and page != 0:
        back = _one_page_back(request)
        if back:
            return back
    return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})


@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True)
def show(request):
    page = int(request.GET.get('p', 0))
    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
    if len(stories) < 1 and page != 0:
        back = _one_page_back(request)
        if back:
            return back
    return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})


@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True)
def ask(request):
    page = int(request.GET.get('p', 0))
    stories = lambda: list(_front_page(page=page, add_filter={'is_ask': True}))
    stories = cache.get_or_set("news-ask-%s"%(page), stories, timeout=TIMEOUT_MEDIUM) # one minute
    if len(stories) < 1 and page != 0:
        back = _one_page_back(request)
        if back:
            return back
    return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})


@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True)
def newest(request): # Done
    page = int(request.GET.get('p', 0))
    add_filter = {}
    add_q = []
    if 'submitted_by' in request.GET.keys():
        try:
            submitted_by = CustomUser.objects.get_by_natural_key(request.GET['submitted_by'])
            add_filter['user'] = submitted_by
        except CustomUser.DoesNotExist:
            raise Http404()
    if 'upvoted_by' in request.GET.keys():
        try:
            assert request.user.is_authenticated
            assert request.user.username == request.GET['upvoted_by']
        except AssertionError:
            return HttpResponseForbidden()
        add_filter['pk__in'] = Vote.objects.filter(vote=1, user=request.user).values('item')
        add_q.append(~Q(user=request.user))
    if 'site' in request.GET.keys():
        add_filter['domain'] = request.GET['site']
    stories = lambda: list(_newest(page=page, add_filter=add_filter, add_q=add_q))
    stories = cache.get_or_set("news-newest-%s"%(page), stories, timeout=TIMEOUT_SHORT) # two seconds
    if len(stories) < 1 and page != 0:
        back = _one_page_back(request)
        if back:
            return back
    return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})


@login_required
@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True)
@cache_page(TIMEOUT_SHORT)
@vary_on_cookie
def threads(request):
    page = int(request.GET.get('p', 0))
    paging_size = settings.PAGING_SIZE
    tree = Comment.objects.filter( tree_id=OuterRef('tree_id'), user=OuterRef('user')).values('tree_id', 'user__pk').annotate(min_level=Min('level')).order_by()
    stories = Comment.objects.filter(
        user=request.user
    ).filter(
        Q(level__in=Subquery(tree.values('min_level'), output_field=models.IntegerField()))  # TODO: level= or level__in= ???
    ).select_related(
        'user', 'parent', 'to_story'
    ).order_by(
        '-created_at'
    )[(page*paging_size):(page+1)*(paging_size)]
    if len(stories) < 1 and page != 0:
        back = _one_page_back(request)
        if back:
            return back
    return render(request, 'news/index.html', {'stories': stories, 'hide_text':False, 'page': page, 'rank_start': None, 'show_children': True})


@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True)
@cache_page(TIMEOUT_SHORT)
@vary_on_cookie
def comments(request): # TODO
    page = int(request.GET.get('p', 0))
    paging_size = settings.PAGING_SIZE
    add_filter = {}
    if 'submitted_by' in request.GET.keys():
        try:
            submitted_by = CustomUser.objects.get_by_natural_key(request.GET['submitted_by'])
            add_filter['user'] = submitted_by
        except CustomUser.DoesNotExist:
            raise Http404()
    if 'upvoted_by' in request.GET.keys():
        try:
            assert request.user.is_authenticated
            assert request.user.username == request.GET['upvoted_by']
        except AssertionError:
            return HttpResponseForbidden()
        add_filter['pk__in'] = Vote.objects.filter(vote=1, user=request.user).values('item')
    stories = Comment.objects.filter(
        parent=None
    ).filter(
        **add_filter
    ).select_related(
        'user', 'parent', 'to_story'
    ).order_by(
        'created_at'
    )[(page*paging_size):(page+1)*(paging_size)]
    if len(stories) < 1 and page != 0:
        back = _one_page_back(request)
        if back:
            return back
    return render(request, 'news/index.html', {'stories': stories, 'hide_text':False, 'page': page, 'rank_start': page*paging_size})


@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True)
def zen(request):
    return render(request, 'news/zen.html')


def _vote(request, pk, vote=None, unvote=False):
    assert not unvote and vote is not None or unvote and vote is None
    item = get_object_or_404(Item, pk=pk)
    if (not unvote) and (vote is not None):
        votes = Vote.objects.filter(item=item, user=request.user)
        if request.method=="POST":
            if vote > 0:
                if not item.can_be_upvoted_by(request.user):
                    return HttpResponseForbidden()
            else:
                if not item.can_be_downvoted_by(request.user):
                    return HttpResponseForbidden()
            vote = Vote(vote=vote, item=item, user=request.user)
            vote.save()
            return HttpResponse("OK %s"%(vote.pk))
    if unvote:
        if request.method=="POST":
            Vote.objects.filter(item=item, user=request.user).delete()
            return HttpResponse("OK")


@login_required
@ratelimit(key="user_or_ip", group="news-votes", rate=DEFAULT_VOTES_RATE, block=True)
def upvote(request, pk):
    return _vote(request, pk, vote=1)


@login_required
@ratelimit(key="user_or_ip", group="news-votes", rate=DEFAULT_VOTES_RATE, block=True)
def downvote(request, pk):
    return _vote(request, pk, vote=-1)


@login_required
@ratelimit(key="user_or_ip", group="news-votes", rate=DEFAULT_VOTES_RATE, block=True)
def unvote(request, pk):
    return _vote(request, pk, vote=None, unvote=True)


def flag(request):
    pass


def save(request):
    pass


def _item_story_comment(pk):
    try: 
        # .prefetch_related('children', 'parent')
        item = Item.objects.select_related('story', 'comment', 'user', 'parent').prefetch_related('children').get(pk=pk)
    except Exception as e:
        raise e
    try:
        story = item.story
        comment = None
        item = story
    except Item.story.RelatedObjectDoesNotExist:
        story = None
        comment = None
    try:
        comment = item.comment
        story = comment.to_story
        item = comment
    except Item.comment.RelatedObjectDoesNotExist:
        pass
    assert story is not None
    return item, story, comment


@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, method=['GET'], block=True)
@ratelimit(key="user_or_ip", group="news-post", rate=DEFAULT_POST_RATE, method=['POST'], block=True)
def item(request, pk): # DONE
    item, story, comment = _item_story_comment(pk)
    if story == item:
        if story.duplicate_of is not None:
            return HttpResponseRedirect(story.duplicate_of.get_absolute_url())
    if request.user.is_authenticated:
        parent = None if story==item else item
        comment_instance = Comment(user=request.user, to_story=story, parent=parent)
        comment_form = CommentForm(request.POST or None, instance=comment_instance)
        if request.method == 'POST':
            if comment_form.is_valid():
                comment = comment_form.save()
                return HttpResponseRedirect(story.get_absolute_url() + '#' + str(comment.pk))
    else:
        comment_form = None
    return render(request, 'news/item.html', {'item': item, 'comment_form': comment_form})


@login_required
@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, method=['GET'], block=True)
@ratelimit(key="user_or_ip", group="news-post", rate=DEFAULT_POST_RATE, method=['POST'], block=True)
def item_edit(request, pk):
    item, story, comment = _item_story_comment(pk)
    if not item.can_be_edited_by(request.user):
        return HttpResponseForbidden()
    if story == item:
        if story.duplicate_of is not None:
            return HttpResponseRedirect(story.duplicate_of.get_absolute_url())
    if comment is not None:
        form = CommentForm(request.POST or None, instance=item)
    else:
        assert story is not None
        form = StoryForm(request.POST or None, instance=item)
    assert form is not None
    if request.method=="POST":
        if form.is_valid():
            item = form.save()
            return HttpResponseRedirect(story.get_absolute_url() + '#' + str(item.pk))
    return render(request, 'news/item_edit.html', {'item': item, 'edit_form': form})


@login_required
@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, method=['GET'], block=True)
@ratelimit(key="user_or_ip", group="news-post", rate=DEFAULT_POST_RATE, method=['POST'], block=True)
def item_delete(request, pk):
    item, story, comment = _item_story_comment(pk)
    if not item.can_be_deleted_by(request.user):
        return HttpResponseForbidden()
    if request.method == "POST":
        redirect_url = '/'
        if comment is not None:
            redirect_url = item.to_story.get_absolute_url()
        item.delete()
        return HttpResponseRedirect(redirect_url)
    return render(request, 'news/item_delete.html', {'item': item})


@login_required
@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, method=['GET'], block=True)
@ratelimit(key="user_or_ip", group="news-post", rate=DEFAULT_POST_RATE, method=['POST'], block=True)
def submit(request): # DONE
    instance = Story(user=request.user)
    form = AddStoryForm(request.POST or None, initial={
        'title': request.GET.get('t'),
        'url': request.GET.get('u'),
        'text': request.GET.get('x'),
    }, instance=instance)
    if request.method=="POST":
        if form.is_valid():
            instance = form.save()
            return HttpResponseRedirect(instance.get_absolute_url())
    return render(request, 'news/submit.html', {'form': form})


def robots_txt(request):
    return HttpResponse("""
User-agent: *
Disallow: 
    """, content_type='text/plain')

def humans_txt(request):
    return HttpResponse("""
🐍
    """, content_type='text/plain', charset='utf-8')


def bookmarklet(request):
    return render(request, 'news/bookmarklet.html')


==============
Download .txt
gitextract__e9vnpwr/

├── .gitignore
├── LICENSE
├── README.md
├── accounts/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── migrations/
│   │   ├── 0001_initial.py
│   │   ├── 0002_auto_20190914_1247.py
│   │   ├── 0003_auto_20190914_2031.py
│   │   ├── 0004_auto_20190915_1105.py
│   │   ├── 0005_emailverification_verification_code.py
│   │   ├── 0006_auto_20190915_1321.py
│   │   ├── 0007_auto_20190923_1323.py
│   │   └── __init__.py
│   ├── models.py
│   ├── receivers.py
│   ├── templates/
│   │   └── accounts/
│   │       ├── __base.html
│   │       ├── create_invite.html
│   │       ├── invite.html
│   │       ├── login.html
│   │       ├── logout.html
│   │       ├── my_profile.html
│   │       ├── password_change_done.html
│   │       ├── password_change_form.html
│   │       ├── password_forgotten_form.html
│   │       ├── profile.html
│   │       ├── register.html
│   │       ├── register_closed.html
│   │       ├── resend_verification.html
│   │       └── user_tree.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── emaildigest/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── mailing.py
│   ├── migrations/
│   │   ├── 0001_initial.py
│   │   ├── 0002_auto_20190923_2028.py
│   │   ├── 0003_auto_20190923_2120.py
│   │   ├── 0004_auto_20190926_2118.py
│   │   └── __init__.py
│   ├── models.py
│   ├── receivers.py
│   ├── templates/
│   │   └── emaildigest/
│   │       ├── __base.html
│   │       ├── _subscription_form_tag.html
│   │       ├── my_subscriptions.html
│   │       ├── subscribe.html
│   │       ├── subscribe_thankyou_a.html
│   │       ├── subscribe_thankyou_u.html
│   │       ├── subscribe_verification_done.html
│   │       ├── unsubscribe.html
│   │       ├── unsubscribe_confirm.html
│   │       └── unsubscribe_done.html
│   ├── templatetags/
│   │   ├── __init__.py
│   │   └── emaildigest_extra.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── hnclone/
│   ├── __init__.py
│   ├── context_processors.py
│   ├── middleware.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── news/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── feeds.py
│   ├── forms.py
│   ├── migrations/
│   │   ├── 0001_initial.py
│   │   ├── 0002_story_title.py
│   │   ├── 0003_auto_20190908_1642.py
│   │   ├── 0004_auto_20190908_2249.py
│   │   ├── 0005_auto_20190908_2250.py
│   │   ├── 0006_auto_20190908_2251.py
│   │   ├── 0007_auto_20190908_2256.py
│   │   ├── 0008_story_duplicate_of.py
│   │   ├── 0009_story_domain.py
│   │   ├── 0010_auto_20190930_1620.py
│   │   ├── 0011_auto_20190930_1623.py
│   │   ├── 0012_auto_20190930_1625.py
│   │   └── __init__.py
│   ├── models.py
│   ├── receivers.py
│   ├── templates/
│   │   └── news/
│   │       ├── __base.html
│   │       ├── _item_content_tag.html
│   │       ├── _item_control_tag.html
│   │       ├── _item_tag.html
│   │       ├── _link_user_tag.html
│   │       ├── _more_link_tag.html
│   │       ├── bookmarklet.html
│   │       ├── formatting_help.html
│   │       ├── index.html
│   │       ├── item.html
│   │       ├── item_delete.html
│   │       ├── item_edit.html
│   │       ├── submit.html
│   │       └── zen.html
│   ├── templatetags/
│   │   ├── __init__.py
│   │   └── news_extra.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── requirements.txt
└── static/
    ├── news.css
    └── news.js
Download .txt
SYMBOL INDEX (238 symbols across 49 files)

FILE: accounts/apps.py
  class AccountsConfig (line 4) | class AccountsConfig(AppConfig):
    method ready (line 7) | def ready(self):

FILE: accounts/forms.py
  class ProfileForm (line 5) | class ProfileForm(forms.ModelForm):
    class Meta (line 6) | class Meta:
    method clean_email (line 10) | def clean_email(self):
  class RegisterForm (line 17) | class RegisterForm(forms.ModelForm):
    class Meta (line 19) | class Meta:
    method clean_password (line 26) | def clean_password(self):
  class CreateInviteForm (line 32) | class CreateInviteForm(forms.ModelForm):
    class Meta (line 33) | class Meta:
    method clean_invited_email_address (line 37) | def clean_invited_email_address(self):
  class PasswordForgottenForm (line 44) | class PasswordForgottenForm(forms.Form):
  class PasswortResetForm (line 47) | class PasswortResetForm(forms.Form):

FILE: accounts/migrations/0001_initial.py
  class Migration (line 10) | class Migration(migrations.Migration):

FILE: accounts/migrations/0002_auto_20190914_1247.py
  class Migration (line 9) | class Migration(migrations.Migration):

FILE: accounts/migrations/0003_auto_20190914_2031.py
  class Migration (line 11) | class Migration(migrations.Migration):

FILE: accounts/migrations/0004_auto_20190915_1105.py
  class Migration (line 9) | class Migration(migrations.Migration):

FILE: accounts/migrations/0005_emailverification_verification_code.py
  class Migration (line 7) | class Migration(migrations.Migration):

FILE: accounts/migrations/0006_auto_20190915_1321.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: accounts/migrations/0007_auto_20190923_1323.py
  class Migration (line 10) | class Migration(migrations.Migration):

FILE: accounts/models.py
  class CustomUser (line 18) | class CustomUser(AbstractUser, MPTTModel):
    class Meta (line 19) | class Meta:
    method get_absolute_url (line 30) | def get_absolute_url(self):
    method is_green (line 34) | def is_green(self):
    method gravatar_url (line 37) | def gravatar_url(self, size=80):
    method latest_verified_email (line 45) | def latest_verified_email(self):
  class Invitation (line 52) | class Invitation(models.Model):
    method get_absolute_url (line 63) | def get_absolute_url(self):
    method get_register_url (line 66) | def get_register_url(self):
    method active (line 70) | def active(self):
  class EmailVerification (line 75) | class EmailVerification(models.Model):
    method get_verify_url (line 87) | def get_verify_url(self):
  class PasswordResetRequest (line 91) | class PasswordResetRequest(models.Model):
    method get_verify_url (line 100) | def get_verify_url(self):

FILE: accounts/receivers.py
  function lower_email_addresses (line 15) | def lower_email_addresses(sender, instance, **kwargs):
  function send_invitation_email (line 23) | def send_invitation_email(sender, instance, created, **kwargs):
  function create_verification (line 44) | def create_verification(sender, instance, created, **kwargs):
  function send_verification_email (line 61) | def send_verification_email(sender, instance, created, **kwargs):
  function send_password_reset_email (line 80) | def send_password_reset_email(sender, instance, created, **kwargs):

FILE: accounts/tests.py
  class BasicAccountsTest (line 8) | class BasicAccountsTest(TestCase):
    method setUp (line 10) | def setUp(self):
  class ReceiversAccountsTest (line 19) | class ReceiversAccountsTest(TestCase):
    method setUp (line 21) | def setUp(self):
    method test_lower_email_addresses (line 30) | def test_lower_email_addresses(self):
    method test_send_invitation_email (line 37) | def test_send_invitation_email(self):
    method test_create_verification (line 42) | def test_create_verification(self):
    method test_send_verification_email (line 51) | def test_send_verification_email(self):
    method test_send_password_reset_email (line 56) | def test_send_password_reset_email(self):

FILE: accounts/views.py
  function profile (line 15) | def profile(request, username=None):
  function my_profile (line 25) | def my_profile(request):
  function create_invite (line 41) | def create_invite(request):
  function invite (line 52) | def invite(request, pk):
  function register (line 57) | def register(request):
  function verify (line 80) | def verify(request, verification_code):
  function resend_verification (line 89) | def resend_verification(request):
  function user_tree (line 97) | def user_tree(request):
  function password_forgotten (line 102) | def password_forgotten(request, verification_code=None):
  function logout (line 138) | def logout(request):

FILE: emaildigest/apps.py
  class EmaildigestConfig (line 4) | class EmaildigestConfig(AppConfig):
    method ready (line 7) | def ready(self):

FILE: emaildigest/forms.py
  class UserSubscriptionForm (line 6) | class UserSubscriptionForm(forms.ModelForm):
    class Meta (line 8) | class Meta:
  class AnonymousSubscriptionForm (line 13) | class AnonymousSubscriptionForm(forms.ModelForm):
    class Meta (line 15) | class Meta:
    method clean_email (line 19) | def clean_email(self):
  function validate_active_email (line 26) | def validate_active_email(email):
  class UnsunscribeForm (line 34) | class UnsunscribeForm(forms.Form):
    method clean_email (line 37) | def clean_email(self):
  function get_subscription_form (line 44) | def get_subscription_form(user, *args, **kwargs):

FILE: emaildigest/mailing.py
  function create_and_send_digest (line 4) | def create_and_send_digest(frequency):
  function send_mail (line 15) | def send_mail(subscription, template, subject):

FILE: emaildigest/migrations/0001_initial.py
  class Migration (line 9) | class Migration(migrations.Migration):

FILE: emaildigest/migrations/0002_auto_20190923_2028.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: emaildigest/migrations/0003_auto_20190923_2120.py
  class Migration (line 8) | class Migration(migrations.Migration):

FILE: emaildigest/migrations/0004_auto_20190926_2118.py
  class Migration (line 8) | class Migration(migrations.Migration):

FILE: emaildigest/models.py
  class EmailDigest (line 4) | class EmailDigest(models.Model):
  class Subscription (line 19) | class Subscription(models.Model):
  class UserSubscription (line 35) | class UserSubscription(Subscription):
  class AnonymousSubscription (line 39) | class AnonymousSubscription(Subscription):
  class UnSubscription (line 47) | class UnSubscription(models.Model):

FILE: emaildigest/receivers.py
  function lower_email_addresses (line 13) | def lower_email_addresses(sender, instance, **kwargs):
  function activate_subscription_on_verification (line 23) | def activate_subscription_on_verification(sender, instance, created, **k...
  function on_subscription_created (line 32) | def on_subscription_created(sender, instance, created, **kwargs):
  function on_unsubscription_created (line 38) | def on_unsubscription_created(sender, instance, created, **kwargs):

FILE: emaildigest/templatetags/emaildigest_extra.py
  function digest_subscription_form (line 8) | def digest_subscription_form(user, **kwargs):

FILE: emaildigest/tests.py
  class BasicEmailDigestTest (line 9) | class BasicEmailDigestTest(TestCase):
    method setUp (line 11) | def setUp(self):
    method _subscribe (line 19) | def _subscribe(self, i=0):
    method _confirm (line 38) | def _confirm(self, subscription):
    method _unsubscribe_via_mail (line 55) | def _unsubscribe_via_mail(self, subscription, assert_form_error=False):
    method test_subscribe (line 77) | def test_subscribe(self):
    method test_subscribe_confirm (line 82) | def test_subscribe_confirm(self):
    method test_subscribe_unsubscribe (line 89) | def test_subscribe_unsubscribe(self):
    method test_subscribe_confirm_unsubscribe (line 96) | def test_subscribe_confirm_unsubscribe(self):
    method test_subscribe_unsubscribe_confirm (line 104) | def test_subscribe_unsubscribe_confirm(self):
    method test_subscribe_confirm_unsubscribe_subscribe (line 118) | def test_subscribe_confirm_unsubscribe_subscribe(self):
    method test_subscribe_confirm_unsubscribe_subscribe_confirm (line 129) | def test_subscribe_confirm_unsubscribe_subscribe_confirm(self):

FILE: emaildigest/views.py
  function subscribe (line 12) | def subscribe(request):
  function unsubscribe (line 36) | def unsubscribe(request, subscription_id=None, digest_id=None):
  function my_subscriptions (line 68) | def my_subscriptions(request):

FILE: hnclone/context_processors.py
  function settings_context_processor (line 2) | def settings_context_processor(request):

FILE: hnclone/urls.py
  function handler403 (line 24) | def handler403(request, exception=None):

FILE: manage.py
  function main (line 7) | def main():

FILE: news/apps.py
  class NewsConfig (line 4) | class NewsConfig(AppConfig):
    method ready (line 7) | def ready(self):

FILE: news/feeds.py
  class NewestFeed (line 7) | class NewestFeed(Feed):
    method items (line 12) | def items(self):
    method item_title (line 15) | def item_title(self, item):
    method item_pubdate (line 18) | def item_pubdate(self, item):
    method item_updateddate (line 21) | def item_updateddate(self, item):
    method item_author_name (line 24) | def item_author_name(self, item):
    method item_author_link (line 27) | def item_author_link(self, item):
    method item_description (line 30) | def item_description(self, item):
  class FrontPageFeed (line 35) | class FrontPageFeed(NewestFeed):
    method items (line 40) | def items(self):

FILE: news/forms.py
  class CommentForm (line 5) | class CommentForm(forms.ModelForm):
    class Meta (line 6) | class Meta:
  class AddStoryForm (line 11) | class AddStoryForm(forms.ModelForm):
    class Meta (line 12) | class Meta:
    method clean (line 16) | def clean(self):
  class StoryForm (line 29) | class StoryForm(forms.ModelForm):
    class Meta (line 30) | class Meta:

FILE: news/migrations/0001_initial.py
  class Migration (line 10) | class Migration(migrations.Migration):

FILE: news/migrations/0002_story_title.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: news/migrations/0003_auto_20190908_1642.py
  class Migration (line 8) | class Migration(migrations.Migration):

FILE: news/migrations/0004_auto_20190908_2249.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: news/migrations/0005_auto_20190908_2250.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: news/migrations/0006_auto_20190908_2251.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: news/migrations/0007_auto_20190908_2256.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: news/migrations/0008_story_duplicate_of.py
  class Migration (line 7) | class Migration(migrations.Migration):

FILE: news/migrations/0009_story_domain.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: news/migrations/0010_auto_20190930_1620.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: news/migrations/0011_auto_20190930_1623.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: news/migrations/0012_auto_20190930_1625.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: news/models.py
  class Item (line 13) | class Item(MPTTModel):
    class Meta (line 14) | class Meta:
    method get_absolute_url (line 37) | def get_absolute_url(self):
    method can_be_upvoted_by (line 41) | def can_be_upvoted_by(self, user):
    method can_be_downvoted_by (line 50) | def can_be_downvoted_by(self, user):
    method can_be_edited_by (line 61) | def can_be_edited_by(self, user):
    method can_be_deleted_by (line 64) | def can_be_deleted_by(self, user):
  class Story (line 69) | class Story(Item):
    class Meta (line 70) | class Meta:
    method __str__ (line 85) | def __str__(self):
    method can_be_downvoted_by (line 93) | def can_be_downvoted_by(self, user):
  class Comment (line 104) | class Comment(Item):
    method __str__ (line 110) | def __str__(self):
    method comments (line 113) | def comments(self):
  class Vote (line 120) | class Vote(models.Model):

FILE: news/receivers.py
  function mark_show_and_ask (line 10) | def mark_show_and_ask(sender, instance, **kwargs):
  function create_self_upvote_for_submission (line 19) | def create_self_upvote_for_submission(sender, instance, created, **kwargs):
  function check_for_duplicates (line 26) | def check_for_duplicates(sender, instance, created, **kwargs):
  function update_votes_count_on_submission (line 40) | def update_votes_count_on_submission(sender, instance, created, **kwargs):
  function update_user_karma_on_vote (line 56) | def update_user_karma_on_vote(sender, instance, created, **kwargs):
  function _recount_comments (line 68) | def _recount_comments(instance, val=1):
  function update_comments_count_on_submission (line 80) | def update_comments_count_on_submission(sender, instance, created, **kwa...
  function update_comments_count_on_deletion (line 86) | def update_comments_count_on_deletion(sender, instance, **kwargs):
  function update_item_votes_on_unvote (line 92) | def update_item_votes_on_unvote(sender, instance, **kwargs):
  function update_user_karma_on_unvote (line 107) | def update_user_karma_on_unvote(sender, instance, **kwargs):
  function add_domain_to_link_stories (line 118) | def add_domain_to_link_stories(sender, instance, **kwargs):

FILE: news/templatetags/news_extra.py
  function news_item (line 9) | def news_item(context, item, **kwargs):
  function link_user (line 15) | def link_user(user):
  function user_arrows (line 21) | def user_arrows(user, item):
  function more_link (line 34) | def more_link(context):
  function item_content (line 44) | def item_content(**kwargs):
  function item_control (line 49) | def item_control(**kwargs):
  class MarkdownRenderer (line 53) | class MarkdownRenderer(mistune.Renderer):
    method setup (line 56) | def setup(cls):
    method header (line 60) | def header(self, text, level, raw=None):
  function comment_markdown (line 68) | def comment_markdown(value):

FILE: news/tests.py
  class BasicNewsTest (line 8) | class BasicNewsTest(TestCase):
    method setUp (line 10) | def setUp(self):
    method test_submit_get (line 18) | def test_submit_get(self):
    method test_submit_post_with_title_and_url (line 26) | def test_submit_post_with_title_and_url(self):
    method test_submit_post_with_title_without_url (line 33) | def test_submit_post_with_title_without_url(self):
    method test_submit_and_frontpage_and_newest (line 40) | def test_submit_and_frontpage_and_newest(self):
    method test_submit_and_upvote (line 59) | def test_submit_and_upvote(self):
    method test_submit_and_upvote_and_unvote (line 81) | def test_submit_and_upvote_and_unvote(self):
    method test_submit_and_downvote (line 106) | def test_submit_and_downvote(self):
    method test_submit_and_upvote_self (line 122) | def test_submit_and_upvote_self(self):
    method test_ask (line 138) | def test_ask(self):
    method test_show (line 154) | def test_show(self):
    method test_comment (line 171) | def test_comment(self):
    method test_owner_can_edit_comment (line 198) | def test_owner_can_edit_comment(self):
    method test_owner_cannot_edit_comment_with_children (line 217) | def test_owner_cannot_edit_comment_with_children(self):
    method test_owner_can_edit_story (line 239) | def test_owner_can_edit_story(self):
    method test_owner_cannot_edit_story_url (line 255) | def test_owner_cannot_edit_story_url(self):
    method test_owner_cannot_edit_story_with_comments (line 271) | def test_owner_cannot_edit_story_with_comments(self):
    method test_other_cannot_edit_comment (line 290) | def test_other_cannot_edit_comment(self):
    method test_other_cannot_edit_story (line 308) | def test_other_cannot_edit_story(self):
    method test_owner_can_delete_comment (line 323) | def test_owner_can_delete_comment(self):
    method test_owner_cannot_delete_comment_with_children (line 347) | def test_owner_cannot_delete_comment_with_children(self):
    method test_owner_can_delete_story (line 373) | def test_owner_can_delete_story(self):
    method test_other_cannot_delete_comment (line 395) | def test_other_cannot_delete_comment(self):
    method test_other_cannot_delete_story (line 418) | def test_other_cannot_delete_story(self):
    method test_zen (line 438) | def test_zen(self):
    method test_comments (line 447) | def test_comments(self):
    method test_threads (line 454) | def test_threads(self):
    method test_newest (line 461) | def test_newest(self):
    method test_front_page (line 468) | def test_front_page(self):
    method test_more_button (line 475) | def test_more_button(self):
  class ReceiversNewsTest (line 479) | class ReceiversNewsTest(TestCase):
    method setUp (line 481) | def setUp(self):
    method test_mark_show_and_ask (line 490) | def test_mark_show_and_ask(self):
    method test_create_self_upvote_for_submission (line 504) | def test_create_self_upvote_for_submission(self):
    method test_check_for_duplicates (line 511) | def test_check_for_duplicates(self):
    method test_update_votes_count_on_submission (line 527) | def test_update_votes_count_on_submission(self):
    method test_update_user_karma_on_vote (line 551) | def test_update_user_karma_on_vote(self):
    method test_update_comments_count_on_submission (line 566) | def test_update_comments_count_on_submission(self):
    method test_update_comments_count_on_deletion (line 586) | def test_update_comments_count_on_deletion(self):
    method test_update_item_votes_on_unvote (line 610) | def test_update_item_votes_on_unvote(self):
    method test_update_user_karma_on_unvote (line 641) | def test_update_user_karma_on_unvote(self):
    method test_add_domain_to_link_stories (line 660) | def test_add_domain_to_link_stories(self):

FILE: news/views.py
  function _one_page_back (line 46) | def _one_page_back(request):
  function _front_page (line 57) | def _front_page(paging_size=settings.PAGING_SIZE, page=0, add_filter={},...
  function _newest (line 104) | def _newest(paging_size=settings.PAGING_SIZE, page=0, add_filter={}, add...
  function index (line 114) | def index(request):
  function show (line 125) | def show(request):
  function ask (line 136) | def ask(request):
  function newest (line 148) | def newest(request): # Done
  function threads (line 181) | def threads(request):
  function comments (line 204) | def comments(request): # TODO
  function zen (line 238) | def zen(request):
  function _vote (line 242) | def _vote(request, pk, vote=None, unvote=False):
  function upvote (line 265) | def upvote(request, pk):
  function downvote (line 271) | def downvote(request, pk):
  function unvote (line 277) | def unvote(request, pk):
  function flag (line 281) | def flag(request):
  function save (line 285) | def save(request):
  function _item_story_comment (line 289) | def _item_story_comment(pk):
  function item (line 314) | def item(request, pk): # DONE
  function item_edit (line 335) | def item_edit(request, pk):
  function item_delete (line 358) | def item_delete(request, pk):
  function submit (line 374) | def submit(request): # DONE
  function robots_txt (line 388) | def robots_txt(request):
  function humans_txt (line 394) | def humans_txt(request):
  function bookmarklet (line 400) | def bookmarklet(request):

FILE: static/news.js
  function getFormData (line 6) | function getFormData(form) {
Condensed preview — 110 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (205K chars).
[
  {
    "path": ".gitignore",
    "chars": 3856,
    "preview": "\n\n\n# Created by https://www.gitignore.io/api/code,macos,python,django,visualstudiocode\n# Edit at https://www.gitignore.i"
  },
  {
    "path": "LICENSE",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 748,
    "preview": "\n# pythonic-news\nA Hacker News lookalike written in Python/Django, powering [https://news.python.sc](https://news.python"
  },
  {
    "path": "accounts/__init__.py",
    "chars": 52,
    "preview": "default_app_config = 'accounts.apps.AccountsConfig'\n"
  },
  {
    "path": "accounts/admin.py",
    "chars": 63,
    "preview": "from django.contrib import admin\n\n# Register your models here.\n"
  },
  {
    "path": "accounts/apps.py",
    "chars": 144,
    "preview": "from django.apps import AppConfig\n\n\nclass AccountsConfig(AppConfig):\n    name = 'accounts'\n\n    def ready(self):\n       "
  },
  {
    "path": "accounts/forms.py",
    "chars": 1355,
    "preview": "from django import forms\n\nfrom .models import CustomUser, Invitation\n\nclass ProfileForm(forms.ModelForm):\n    class Meta"
  },
  {
    "path": "accounts/migrations/0001_initial.py",
    "chars": 2993,
    "preview": "# Generated by Django 2.2.5 on 2019-09-07 12:14\n\nimport django.contrib.auth.models\nimport django.contrib.auth.validators"
  },
  {
    "path": "accounts/migrations/0002_auto_20190914_1247.py",
    "chars": 1141,
    "preview": "# Generated by Django 2.2.5 on 2019-09-14 12:47\n\nfrom django.conf import settings\nfrom django.db import migrations, mode"
  },
  {
    "path": "accounts/migrations/0003_auto_20190914_2031.py",
    "chars": 1800,
    "preview": "# Generated by Django 2.2.5 on 2019-09-14 20:31\n\nfrom django.conf import settings\nimport django.contrib.auth.models\nfrom"
  },
  {
    "path": "accounts/migrations/0004_auto_20190915_1105.py",
    "chars": 1325,
    "preview": "# Generated by Django 2.2.5 on 2019-09-15 11:05\n\nfrom django.conf import settings\nfrom django.db import migrations, mode"
  },
  {
    "path": "accounts/migrations/0005_emailverification_verification_code.py",
    "chars": 440,
    "preview": "# 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("
  },
  {
    "path": "accounts/migrations/0006_auto_20190915_1321.py",
    "chars": 466,
    "preview": "# Generated by Django 2.2.5 on 2019-09-15 13:21\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration"
  },
  {
    "path": "accounts/migrations/0007_auto_20190923_1323.py",
    "chars": 1260,
    "preview": "# Generated by Django 2.2.5 on 2019-09-23 13:23\n\nfrom django.conf import settings\nimport django.contrib.auth.models\nfrom"
  },
  {
    "path": "accounts/migrations/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "accounts/models.py",
    "chars": 3657,
    "preview": "import uuid\n\nfrom django.contrib.auth.models import AbstractUser\nfrom django.urls import reverse\n\nfrom django.db import "
  },
  {
    "path": "accounts/receivers.py",
    "chars": 3522,
    "preview": "#from django.core.signals import request_finished\nfrom django.db.models.signals import pre_save, post_save, post_delete\n"
  },
  {
    "path": "accounts/templates/accounts/__base.html",
    "chars": 32,
    "preview": "{% extends 'news/__base.html' %}"
  },
  {
    "path": "accounts/templates/accounts/create_invite.html",
    "chars": 218,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n\n<form method=\"POST\" action=\"{% url 'accounts_create_invite' %"
  },
  {
    "path": "accounts/templates/accounts/invite.html",
    "chars": 218,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n\n\nYou have created an invite for {{invitation.invited_email_ad"
  },
  {
    "path": "accounts/templates/accounts/login.html",
    "chars": 330,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n{% if user.is_authenticated %}\nSigned in.\n{% else %}\n<h2>Login"
  },
  {
    "path": "accounts/templates/accounts/logout.html",
    "chars": 186,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n\n<h2>Logout</h2>\n<form method=\"post\">\n  {% csrf_token %}\n  <bu"
  },
  {
    "path": "accounts/templates/accounts/my_profile.html",
    "chars": 1023,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<article class=\"site-content-dense\">\n<form method=\"POST\">{% cs"
  },
  {
    "path": "accounts/templates/accounts/password_change_done.html",
    "chars": 111,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\nPassword changed successfully.\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/password_change_form.html",
    "chars": 220,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<h2>Change Password</h2>\n<form method=\"post\">\n  {% csrf_token "
  },
  {
    "path": "accounts/templates/accounts/password_forgotten_form.html",
    "chars": 225,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<h2>Password forgotten?</h2>\n<form method=\"post\">\n  {% csrf_to"
  },
  {
    "path": "accounts/templates/accounts/profile.html",
    "chars": 627,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<article class=\"site-content-dense\">\n<table>\n<tbody>\n    <tr>\n"
  },
  {
    "path": "accounts/templates/accounts/register.html",
    "chars": 598,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n<article class=\"site-content-dense\">\n<h2>Create Account</h2>\n<"
  },
  {
    "path": "accounts/templates/accounts/register_closed.html",
    "chars": 225,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\nClosed.\n\n<p>\nYou want an invite? Please leave your email addre"
  },
  {
    "path": "accounts/templates/accounts/resend_verification.html",
    "chars": 107,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\nA new email has been sent.\n{% endblock content %}"
  },
  {
    "path": "accounts/templates/accounts/user_tree.html",
    "chars": 402,
    "preview": "{% extends 'accounts/__base.html' %}\n\n{% block content %}\n{% load mptt_tags %}\n\n<ul class=\"root\">\n    {% recursetree use"
  },
  {
    "path": "accounts/tests.py",
    "chars": 2091,
    "preview": "from django.contrib.auth.models import AnonymousUser\nfrom accounts.models import CustomUser\nfrom django.test import Requ"
  },
  {
    "path": "accounts/urls.py",
    "chars": 1629,
    "preview": "from django.urls import path, include\n\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\n\n\nurlpat"
  },
  {
    "path": "accounts/views.py",
    "chars": 5832,
    "preview": "from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom d"
  },
  {
    "path": "emaildigest/__init__.py",
    "chars": 58,
    "preview": "default_app_config = 'emaildigest.apps.EmaildigestConfig'\n"
  },
  {
    "path": "emaildigest/admin.py",
    "chars": 63,
    "preview": "from django.contrib import admin\n\n# Register your models here.\n"
  },
  {
    "path": "emaildigest/apps.py",
    "chars": 150,
    "preview": "from django.apps import AppConfig\n\n\nclass EmaildigestConfig(AppConfig):\n    name = 'emaildigest'\n\n    def ready(self):\n "
  },
  {
    "path": "emaildigest/forms.py",
    "chars": 1321,
    "preview": "from django import forms\n\nfrom .models import UserSubscription, AnonymousSubscription, Subscription\n\n\nclass UserSubscrip"
  },
  {
    "path": "emaildigest/mailing.py",
    "chars": 582,
    "preview": "from django.conf import settings\nfrom .models import Subscription, EmailDigest\n\ndef create_and_send_digest(frequency):\n "
  },
  {
    "path": "emaildigest/migrations/0001_initial.py",
    "chars": 2719,
    "preview": "# Generated by Django 2.2.5 on 2019-09-23 13:23\n\nfrom django.conf import settings\nfrom django.db import migrations, mode"
  },
  {
    "path": "emaildigest/migrations/0002_auto_20190923_2028.py",
    "chars": 801,
    "preview": "# Generated by Django 2.2.5 on 2019-09-23 20:28\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.M"
  },
  {
    "path": "emaildigest/migrations/0003_auto_20190923_2120.py",
    "chars": 804,
    "preview": "# Generated by Django 2.2.5 on 2019-09-23 21:20\n\nfrom django.conf import settings\nfrom django.db import migrations, mode"
  },
  {
    "path": "emaildigest/migrations/0004_auto_20190926_2118.py",
    "chars": 1081,
    "preview": "# Generated by Django 2.2.5 on 2019-09-26 21:18\n\nfrom django.db import migrations, models\nimport django.db.models.deleti"
  },
  {
    "path": "emaildigest/migrations/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "emaildigest/models.py",
    "chars": 3184,
    "preview": "import uuid\nfrom django.db import models\n\nclass EmailDigest(models.Model):\n    id = models.UUIDField(primary_key=True, d"
  },
  {
    "path": "emaildigest/receivers.py",
    "chars": 1596,
    "preview": "#from django.core.signals import request_finished\nfrom django.db.models.signals import pre_save, post_save, post_delete\n"
  },
  {
    "path": "emaildigest/templates/emaildigest/__base.html",
    "chars": 32,
    "preview": "{% extends 'news/__base.html' %}"
  },
  {
    "path": "emaildigest/templates/emaildigest/_subscription_form_tag.html",
    "chars": 356,
    "preview": "{% if False and subscription_form %}\n<p>Don't miss interesting Python stories by subscribing to our digest</p>\n\n    <for"
  },
  {
    "path": "emaildigest/templates/emaildigest/my_subscriptions.html",
    "chars": 166,
    "preview": "{% extends 'emaildigest/__base.html' %}\n\n{% block content %}\n\n    <article class=\"site-content\">\n        my_subscription"
  },
  {
    "path": "emaildigest/templates/emaildigest/subscribe.html",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "emaildigest/templates/emaildigest/subscribe_thankyou_a.html",
    "chars": 210,
    "preview": "{% extends 'emaildigest/__base.html' %}\n\n{% block content %}\n\n    <article class=\"site-content\">\n        Thank you!<br>\n"
  },
  {
    "path": "emaildigest/templates/emaildigest/subscribe_thankyou_u.html",
    "chars": 191,
    "preview": "{% extends 'emaildigest/__base.html' %}\n\n{% block content %}\n\n    <article class=\"site-content\">\n        Thank you!<br>\n"
  },
  {
    "path": "emaildigest/templates/emaildigest/subscribe_verification_done.html",
    "chars": 191,
    "preview": "{% extends 'emaildigest/__base.html' %}\n\n{% block content %}\n\n    <article class=\"site-content\">\n        Thank you!<br>\n"
  },
  {
    "path": "emaildigest/templates/emaildigest/unsubscribe.html",
    "chars": 307,
    "preview": "\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=\"si"
  },
  {
    "path": "emaildigest/templates/emaildigest/unsubscribe_confirm.html",
    "chars": 346,
    "preview": "\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=\"si"
  },
  {
    "path": "emaildigest/templates/emaildigest/unsubscribe_done.html",
    "chars": 204,
    "preview": "\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=\"si"
  },
  {
    "path": "emaildigest/templatetags/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "emaildigest/templatetags/emaildigest_extra.py",
    "chars": 304,
    "preview": "from django import template\n\nregister = template.Library()\n\nfrom emaildigest.forms import get_subscription_form\n\n@regist"
  },
  {
    "path": "emaildigest/tests.py",
    "chars": 6370,
    "preview": "from django.contrib.auth.models import AnonymousUser\nfrom accounts.models import CustomUser\nfrom django.test import Requ"
  },
  {
    "path": "emaildigest/urls.py",
    "chars": 495,
    "preview": "from django.urls import path, include\n\nfrom . import views\n\n\n\n\nurlpatterns = [\n    #path('profile', views.profile, name="
  },
  {
    "path": "emaildigest/views.py",
    "chars": 3628,
    "preview": "from django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse\nfrom "
  },
  {
    "path": "hnclone/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "hnclone/context_processors.py",
    "chars": 211,
    "preview": "from django.conf import settings\ndef settings_context_processor(request):\n   return {\n       'SITE_NAME': settings.SITE_"
  },
  {
    "path": "hnclone/middleware.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "hnclone/settings.py",
    "chars": 3984,
    "preview": "\"\"\"\nDjango settings for hnclone project.\n\nGenerated by 'django-admin startproject' using Django 2.2.5.\n\nModified by me 2"
  },
  {
    "path": "hnclone/urls.py",
    "chars": 926,
    "preview": "\"\"\"hnclone URL Configuration\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf"
  },
  {
    "path": "hnclone/wsgi.py",
    "chars": 530,
    "preview": "\"\"\"\nWSGI config for hnclone project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFo"
  },
  {
    "path": "manage.py",
    "chars": 627,
    "preview": "#!/usr/bin/env python\n\"\"\"Django's command-line utility for administrative tasks.\"\"\"\nimport os\nimport sys\n\n\ndef main():\n "
  },
  {
    "path": "news/__init__.py",
    "chars": 44,
    "preview": "default_app_config = 'news.apps.NewsConfig'\n"
  },
  {
    "path": "news/admin.py",
    "chars": 126,
    "preview": "from django.contrib import admin\n\n\nfrom .models import Story, Comment\n\nadmin.site.register(Story)\nadmin.site.register(Co"
  },
  {
    "path": "news/apps.py",
    "chars": 136,
    "preview": "from django.apps import AppConfig\n\n\nclass NewsConfig(AppConfig):\n    name = 'news'\n\n    def ready(self):\n        from . "
  },
  {
    "path": "news/feeds.py",
    "chars": 1001,
    "preview": "from django.contrib.syndication.views import Feed\nfrom .models import Story\nfrom .views import _newest, _front_page\n\nfro"
  },
  {
    "path": "news/forms.py",
    "chars": 804,
    "preview": "from django import forms\n\nfrom .models import Comment, Story\n\nclass CommentForm(forms.ModelForm):\n    class Meta:\n      "
  },
  {
    "path": "news/migrations/0001_initial.py",
    "chars": 3303,
    "preview": "# Generated by Django 2.2.5 on 2019-09-07 12:14\n\nfrom django.conf import settings\nfrom django.db import migrations, mode"
  },
  {
    "path": "news/migrations/0002_story_title.py",
    "chars": 418,
    "preview": "# Generated by Django 2.2.5 on 2019-09-07 13:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.M"
  },
  {
    "path": "news/migrations/0003_auto_20190908_1642.py",
    "chars": 2102,
    "preview": "# Generated by Django 2.2.5 on 2019-09-08 16:42\n\nfrom django.db import migrations, models\nimport django.db.models.deleti"
  },
  {
    "path": "news/migrations/0004_auto_20190908_2249.py",
    "chars": 575,
    "preview": "# Generated by Django 2.2.5 on 2019-09-08 22:49\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.M"
  },
  {
    "path": "news/migrations/0005_auto_20190908_2250.py",
    "chars": 344,
    "preview": "# Generated by Django 2.2.5 on 2019-09-08 22:50\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration"
  },
  {
    "path": "news/migrations/0006_auto_20190908_2251.py",
    "chars": 525,
    "preview": "# Generated by Django 2.2.5 on 2019-09-08 22:51\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.M"
  },
  {
    "path": "news/migrations/0007_auto_20190908_2256.py",
    "chars": 830,
    "preview": "# Generated by Django 2.2.5 on 2019-09-08 22:56\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.M"
  },
  {
    "path": "news/migrations/0008_story_duplicate_of.py",
    "chars": 478,
    "preview": "# Generated by Django 2.2.5 on 2019-09-23 13:23\n\nfrom django.db import migrations, models\nimport django.db.models.deleti"
  },
  {
    "path": "news/migrations/0009_story_domain.py",
    "chars": 404,
    "preview": "# Generated by Django 2.2.5 on 2019-09-30 16:17\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.M"
  },
  {
    "path": "news/migrations/0010_auto_20190930_1620.py",
    "chars": 415,
    "preview": "# Generated by Django 2.2.5 on 2019-09-30 16:20\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.M"
  },
  {
    "path": "news/migrations/0011_auto_20190930_1623.py",
    "chars": 406,
    "preview": "# Generated by Django 2.2.5 on 2019-09-30 16:23\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.M"
  },
  {
    "path": "news/migrations/0012_auto_20190930_1625.py",
    "chars": 563,
    "preview": "# Generated by Django 2.2.5 on 2019-09-30 16:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.M"
  },
  {
    "path": "news/migrations/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "news/models.py",
    "chars": 4079,
    "preview": "import uuid\n\nfrom accounts.models import CustomUser\n\nfrom django.db import models\nfrom mptt.models import MPTTModel, Tre"
  },
  {
    "path": "news/receivers.py",
    "chars": 3921,
    "preview": "#from django.core.signals import request_finished\nfrom django.db.models.signals import pre_save, post_save, post_delete\n"
  },
  {
    "path": "news/templates/news/__base.html",
    "chars": 5053,
    "preview": "{% load static %}{% load humanize %}{% load emaildigest_extra %}<!doctype html>\n<html lang=\"en\">\n<head>\n    <meta charse"
  },
  {
    "path": "news/templates/news/_item_content_tag.html",
    "chars": 761,
    "preview": "{% load news_extra %}\n\n<div style=\"margin-bottom:3pt; \">\n                    {% if item.title %}\n                    <sp"
  },
  {
    "path": "news/templates/news/_item_control_tag.html",
    "chars": 895,
    "preview": "{% load humanize %}\n{% load news_extra %}\n                    <span class=\"controls\">\n                            <span "
  },
  {
    "path": "news/templates/news/_item_tag.html",
    "chars": 1696,
    "preview": "{% load humanize %}\n{% load static %}\n{% load news_extra %}\n\n\n            <tr id=\"{{item.pk}}\">\n                <td rows"
  },
  {
    "path": "news/templates/news/_link_user_tag.html",
    "chars": 95,
    "preview": "<a class=\"{% if user.is_green %}green{% endif %}\" href=\"{{user.get_absolute_url}}\">{{user}}</a>"
  },
  {
    "path": "news/templates/news/_more_link_tag.html",
    "chars": 50,
    "preview": "<a href=\"{{more_link}}\" class=\"more-link\">More</a>"
  },
  {
    "path": "news/templates/news/bookmarklet.html",
    "chars": 579,
    "preview": "{% extends \"news/__base.html\" %}\n{% load humanize %}\n{% load static %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n{% b"
  },
  {
    "path": "news/templates/news/formatting_help.html",
    "chars": 2029,
    "preview": "<div class=\"formatting-help closed\">\n    <table>\n        <thead>\n            <tr>\n                <th>Markdown</th>\n    "
  },
  {
    "path": "news/templates/news/index.html",
    "chars": 1316,
    "preview": "{% extends \"news/__base.html\" %}\n{% load humanize %}\n{% load static %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n{% b"
  },
  {
    "path": "news/templates/news/item.html",
    "chars": 1420,
    "preview": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n\n\n\n{% block content %"
  },
  {
    "path": "news/templates/news/item_delete.html",
    "chars": 540,
    "preview": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n\n\n\n{% block content %"
  },
  {
    "path": "news/templates/news/item_edit.html",
    "chars": 585,
    "preview": "\n{% extends 'news/__base.html' %}\n{% load humanize %}\n{% load mptt_tags %}\n{% load news_extra %}\n\n\n\n\n\n{% block content %"
  },
  {
    "path": "news/templates/news/submit.html",
    "chars": 468,
    "preview": "{% extends 'news/__base.html' %}\n\n{% block content %}\n<article class=\"site-content-dense\">\n<form method=\"POST\">{% csrf_t"
  },
  {
    "path": "news/templates/news/zen.html",
    "chars": 3598,
    "preview": "\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=\"si"
  },
  {
    "path": "news/templatetags/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "news/templatetags/news_extra.py",
    "chars": 1711,
    "preview": "from django import template\nfrom django.utils.safestring import mark_safe\n\nimport mistune\n\nregister = template.Library()"
  },
  {
    "path": "news/tests.py",
    "chars": 23580,
    "preview": "from django.contrib.auth.models import AnonymousUser\nfrom accounts.models import CustomUser\nfrom django.test import Requ"
  },
  {
    "path": "news/urls.py",
    "chars": 1092,
    "preview": "\n\nfrom django.urls import path, include\n\nfrom . import views\n\nfrom .feeds import NewestFeed, FrontPageFeed\n\nurlpatterns "
  },
  {
    "path": "news/views.py",
    "chars": 16181,
    "preview": "from django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponseR"
  },
  {
    "path": "requirements.txt",
    "chars": 1021,
    "preview": "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"
  },
  {
    "path": "static/news.css",
    "chars": 4708,
    "preview": "/*\n\nhttps://www.schemecolor.com/python-logo-colors.php\nCyan-Blue Azure     #4B8BBE\nLapis Lazuli        #306998\nShandy   "
  },
  {
    "path": "static/news.js",
    "chars": 1225,
    "preview": "document.addEventListener(\"DOMContentLoaded\", function() {\n\n    // Highlight the posted comment, if comment-id is in url"
  }
]

About this extraction

This page contains the full source code of the sebst/pythonic-news GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 110 files (187.4 KB), approximately 46.0k tokens, and a symbol index with 238 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!