dev bb44c1d496d1 cached
65 files
141.1 KB
40.3k tokens
38 symbols
1 requests
Download .txt
Repository: repo-analytics/repo-analytics.github.io
Branch: dev
Commit: bb44c1d496d1
Files: 65
Total size: 141.1 KB

Directory structure:
gitextract_quu5d0bq/

├── .github/
│   └── workflows/
│       └── dailyFetchTraffic.yml
├── .gitignore
├── LICENSE
├── README.md
├── backend/
│   ├── README.md
│   ├── db/
│   │   ├── Repo.js
│   │   ├── Star.js
│   │   ├── Traffic.js
│   │   ├── User.js
│   │   └── dynamodb.js
│   ├── package.json
│   ├── scripts/
│   │   ├── README.md
│   │   ├── countries.json
│   │   ├── dailyGetStars.js
│   │   ├── dailyGetTraffics.js
│   │   ├── getStarsAndSaveDbForRepoWithoutRepos.js
│   │   └── guessCountryFromAddress.js
│   ├── server.js
│   ├── up.json
│   └── utils/
│       ├── getStars.js
│       ├── getTrafficOfRepoAndSave.js
│       ├── getUniqueListBy.js
│       └── trafficDateRangeToDateArr.js
└── frontend/
    ├── .gitignore
    ├── README.md
    ├── package.json
    ├── public/
    │   ├── 404.html
    │   ├── index.html
    │   ├── manifest.json
    │   └── robots.txt
    └── src/
        ├── App.css
        ├── App.js
        ├── App.test.js
        ├── components/
        │   ├── AddRepo.css
        │   ├── AddRepo.js
        │   ├── CardLoader.js
        │   ├── CloneChart.js
        │   ├── Footer.css
        │   ├── Footer.js
        │   ├── PathChart.js
        │   ├── ProjectCard.css
        │   ├── ProjectCard.js
        │   ├── ReferrerChart.js
        │   ├── RepoLoader.js
        │   ├── RepoNav.js
        │   ├── RepoSetting.css
        │   ├── RepoSetting.js
        │   ├── StarAnalytics.js
        │   ├── StarHistoryChart.js
        │   ├── StarLocationChart.js
        │   ├── TrafficAnalytics.js
        │   ├── VisitChart.css
        │   └── VisitChart.js
        ├── index.css
        ├── index.js
        ├── pages/
        │   ├── Home.css
        │   ├── Home.js
        │   ├── Repo.css
        │   ├── Repo.js
        │   ├── User.css
        │   └── User.js
        ├── serviceWorker.js
        └── utils/
            ├── http.js
            ├── trafficDateRangeToArray.js
            └── userSignedIn.js

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

================================================
FILE: .github/workflows/dailyFetchTraffic.yml
================================================
name: daily-traffic-data-fetching


on:
  schedule:
  - cron: "1 0 * * *"

jobs:
  fetch-traffics:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v1
    - name: Use Node.js
      uses: actions/setup-node@v1
      with:
        node-version: 12.x
    - name: npm install
      run: npm install
      working-directory: ./backend
    - name: fetch
      run: node scripts/dailyGetTraffics.js
      env:
        awsAccessKeyId: ${{ secrets.awsAccessKeyId }}
        awsSecretAccessKey: ${{ secrets.awsSecretAccessKey }}
      working-directory: ./backend


================================================
FILE: .gitignore
================================================
secret.json

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# next.js build output
.next


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 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 General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is 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.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  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.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  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 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. Use with the GNU Affero General Public License.

  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 Affero 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU 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 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 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 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 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 General Public License for more details.

    You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  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 GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
[![](https://raw.githubusercontent.com/timqian/images/master/20191017115402.gif)](https://repo-analytics.github.io)
[![](https://raw.githubusercontent.com/timqian/images/master/20191017114556.png)](https://repo-analytics.github.io)

# [Repo Analytics](https://repo-analytics.github.io)

Thorough analytics for your GitHub repos

Chat with us in [Slack](https://join.slack.com/t/t9tio/shared_invite/enQtNjgzMzkwMDM0NTE3LTE5ZTUzYjU4Y2I0YzRiZjNkYTkzMzE1ZmM0NDdmYzRlZmMxNGY1MzZlN2EwYjYyNWVlMWY0Nzk2MDBhNWZlY2I)

## Setup

Add config file

```js
// backend/secret.json
{
  "aws": {
    "accessKeyId": "",
    "secretAccessKey": ""
  },
  "github": {
    "clientID": "",
    "clientSecret": ""
  },
  "jwtSecret": ""
}
```

## Thanks

- [XKCD styled chart lib - chart.xkcd](https://github.com/timqian/chart.xkcd)
- [Host single page apps with GitHub Pages](https://github.com/rafrex/spa-github-pages)
- [Walking octocat](https://dribbble.com/shots/6364613-Octocat-walk-cycle)
- [Icons: remix icon](https://remixicon.com)


================================================
FILE: backend/README.md
================================================
## Table structure

### What to track:

stargizers data;
clone data;
visits data;
referal data;
toppage data;

### Usefull analytics:

star history
star country distrubution
clone history
clone country distrubution
fork history
fork country distrubution
visits data (more than 14 days)
unique visits
referall data
top page data

suggestions?


Traffic

```js
{
  date: '',
  visits: '',
  uniqueVists: '',
  refs: '',
  topPages: '',
}
```

================================================
FILE: backend/db/Repo.js
================================================
/**
 * {
 *   username: 'timqian',
 *   repo: 'timqian/chart.xkcd',
 *   createdAt: '',
 * }
 */
const dynamodb = require('./dynamodb');

// TODO: secondary index for repo - to get repo's 'createdAt'
async function createTable() {
  console.log('going to create "repo-analytics-repo" table');
  await dynamodb.createTable({
    TableName: 'repo-analytics-repo',
    KeySchema: [
      { AttributeName: 'username', KeyType: 'HASH' },
      { AttributeName: 'repo', KeyType: 'RANGE' },
    ],
    AttributeDefinitions: [
      { AttributeName: 'username', AttributeType: 'S' },
      { AttributeName: 'repo', AttributeType: 'S' },
    ],
    BillingMode: 'PAY_PER_REQUEST',
    // ProvisionedThroughput: {
    //   ReadCapacityUnits: 1,
    //   WriteCapacityUnits: 1,
    // },
  }).promise();
  console.log('successfully created table "repo-analytics-repo"');
}

async function deleteTable() {
  await dynamodb.deleteTable({ TableName: 'repo-analytics-repo' }).promise();
}

async function getAllForUser({ username }) {
  const { Items } = await dynamodb.query({
    TableName: 'repo-analytics-repo',
    KeyConditionExpression: 'username = :username',
    ExpressionAttributeValues: {
      ':username': { S: username },
    },
  }).promise();
  return Items;
}

async function put({
  username, repo,
}) {
  await dynamodb.putItem({
    TableName: 'repo-analytics-repo',
    Item: {
      username: { S: username },
      repo: { S: repo },
      createdAt: { S: new Date().toISOString() },
    },
  }).promise();
}

async function scan() {
  const data = await dynamodb.scan({
    TableName: 'repo-analytics-repo',
    AttributesToGet: [
      'username',
      'repo',
      'createdAt',
    ],
  }).promise();

  // FIXME: if repo data larger than 1MB data, we need to handle pagination
  return data.Items;
}

module.exports = {
  createTable,
  deleteTable,
  getAllForUser,
  put,
  scan,
};


// // test
// (async () => {
//   // await createTable();
//   // await new Promise((r) => setTimeout(r, 1000));
//   await put({
//     username: 'timqian',
//     repo: 'repo-analytics/repo-analytics.github.io',
//   });
//   // const items = await getAllForUser({
//   //   username: 'timqian',
//   // });
//   // console.log(items);
//   const scanRes = await scan();
//   console.log(scanRes)
// })();


================================================
FILE: backend/db/Star.js
================================================
/**
 * {
 *   repo: 'timqian/chart.xkcd',
 *   updatedAt: '2016-09-18',
 *   totalCount: '100',
 *   history: {
 *     '2018-04-12': 10,
 *   },
 *   locations: {
 *     china: 3,
 *   }
 * }
 */

const dynamodb = require('./dynamodb');

async function createTable() {
  console.log('going to create "repo-analytics-stars" table');
  await dynamodb.createTable({
    TableName: 'repo-analytics-stars',
    KeySchema: [
      { AttributeName: 'repo', KeyType: 'HASH' },
    ],
    AttributeDefinitions: [
      { AttributeName: 'repo', AttributeType: 'S' },
    ],
    BillingMode: 'PAY_PER_REQUEST',
    // ProvisionedThroughput: {
    //   ReadCapacityUnits: 1,
    //   WriteCapacityUnits: 1,
    // },
  }).promise();
  console.log('successfully created table "repo-analytics-stars"');
}

async function deleteTable() {
  await dynamodb.deleteTable({ TableName: 'repo-analytics-stars' }).promise();
}

async function get({ repo }) {
  const { Item } = await dynamodb.getItem({
    TableName: 'repo-analytics-stars',
    Key: {
      repo: { S: repo },
    },
  }).promise();
  return Item;
}

async function put({
  repo, updatedAt, totalCount, history, locations,
}) {
  await dynamodb.putItem({
    TableName: 'repo-analytics-stars',
    Item: {
      repo: { S: repo },
      updatedAt: { S: updatedAt },
      totalCount: { S: totalCount + '' },
      history: { S: JSON.stringify(history) },
      locations: { S: JSON.stringify(locations) },
    },
  }).promise();
}

module.exports = {
  createTable,
  deleteTable,
  get,
  put,
};

// // test
// (async () => {
//   // await createTable();
//   // await new Promise((r) => setTimeout(r, 1000));
//   await put({
//     repo: 'timqian/star-history',
//     updatedAt: '2019-03-01',
//     totalCount: 19,
//     history: {'2018-09-09': 2},
//     locations: {'china':1}
//   });
//   const item = await get({
//     repo: 'timqian/star-history',
//   });
//   console.log(item);
// })();


================================================
FILE: backend/db/Traffic.js
================================================
/**
 * {
 *   repo: 'timqian/chart.xkcd',
 *   date: '2016-09-18',
 *   views: [],
 *   clones: [],
 *   referrers: [],
 *   paths: [],
 *   repoCreatedAt: '2019-10-08'
 * }
 */

const dynamodb = require('./dynamodb');

async function createTable() {
  console.log('going to create "repo-analytics-analytics" table');
  await dynamodb.createTable({
    TableName: 'repo-analytics-analytics',
    KeySchema: [
      { AttributeName: 'repo', KeyType: 'HASH' },
      { AttributeName: 'date', KeyType: 'RANGE' },
    ],
    AttributeDefinitions: [
      { AttributeName: 'repo', AttributeType: 'S' },
      { AttributeName: 'date', AttributeType: 'S' },
    ],
    BillingMode: 'PAY_PER_REQUEST',
    // ProvisionedThroughput: {
    //   ReadCapacityUnits: 1,
    //   WriteCapacityUnits: 1,
    // },
  }).promise();
  console.log('successfully created table "repo-analytics-analytics"');
}

async function deleteTable() {
  await dynamodb.deleteTable({ TableName: 'repo-analytics-analytics' }).promise();
}

async function batchGetViewAndClones({ repo, dateArr }) {
  const keys = dateArr.map(date => ({
    repo: { S: repo },
    date: { S: date }
  }));

  const { Responses } = await dynamodb.batchGetItem({
    RequestItems: {
      "repo-analytics-analytics": {
        Keys: keys,
        AttributesToGet: [
          'repo',
          'date',
          'views',
          'clones',
        ],
      }
    }
  }).promise();
  return Responses["repo-analytics-analytics"];
}

async function getLatest({ repo }) {
  const { Items } = await dynamodb.query({
    TableName: 'repo-analytics-analytics',
    KeyConditionExpression: 'repo = :repo',
    ExpressionAttributeValues: {
      ':repo': { S: repo },
    },
    Limit: 1,
    ScanIndexForward: false,
  }).promise();
  return Items[0];
}

async function put({
  repo, date, views, clones, referrers, paths, repoCreatedAt,
}) {
  await dynamodb.putItem({
    TableName: 'repo-analytics-analytics',
    Item: {
      repo: { S: repo },
      date: { S: date },
      views: { S: JSON.stringify(views) },
      clones: { S: JSON.stringify(clones) },
      referrers: { S: JSON.stringify(referrers) },
      paths: { S: JSON.stringify(paths) },
      createdAt: { S: new Date().toISOString() },
      repoCreatedAt: { S: repoCreatedAt }
    },
  }).promise();
}

module.exports = {
  createTable,
  deleteTable,
  getLatest,
  batchGetViewAndClones,
  put,
};


// // test
// (async () => {
//   // await createTable();
//   // await new Promise((r) => setTimeout(r, 1000));
//   // await put({
//   //   repo: 'timqian/chart.xkcd',
//   //   date: '2019-10-09',
//   //   views: [
//   //     {
//   //       "timestamp": "2016-10-10T00:00:00Z",
//   //       "count": 440,
//   //       "uniques": 143
//   //     },
//   //     {
//   //       "timestamp": "2016-10-11T00:00:00Z",
//   //       "count": 1308,
//   //       "uniques": 414
//   //     },
//   //   ],
//   //   referrers: [
//   //     {
//   //       "referrer": "Google",
//   //       "count": 4,
//   //       "uniques": 3
//   //     },
//   //     {
//   //       "referrer": "stackoverflow.com",
//   //       "count": 2,
//   //       "uniques": 2
//   //     }
//   //   ],
//   //   paths: [
//   //     {
//   //       "path": "/github/hubot",
//   //       "title": "github/hubot: A customizable life embetterment robot.",
//   //       "count": 3542,
//   //       "uniques": 2225
//   //     },
//   //     {
//   //       "path": "/github/hubot/blob/master/docs/scripting.md",
//   //       "title": "hubot/scripting.md at master · github/hubot · GitHub",
//   //       "count": 1707,
//   //       "uniques": 804
//   //     }
//   //   ],
//   //   clones: [
//   //     {
//   //       "timestamp": "2016-10-10T00:00:00Z",
//   //       "count": 2,
//   //       "uniques": 1
//   //     },
//   //     {
//   //       "timestamp": "2016-10-11T00:00:00Z",
//   //       "count": 17,
//   //       "uniques": 16
//   //     }
//   //   ]
//   //   repoCreatedAt: '2018-09-10'
//   // });

//   // const item = await batchGet({ repo: 'timqian/chart.xkcd', dateArr: ['2019-10-09']})

//   // console.log(item);

//   // const latestItem = await getLatest({ repo: 'timqian/chart.xkcd' });
//   // console.log(latestItem)
// })();


================================================
FILE: backend/db/User.js
================================================
/**
 * {
 *   username: 'timqian',
 *   email: 'timqian@t9t.io',
 *   accessToken: '',
 *   displayName: '', 
 *   photo: '',
 *   createdAt: '',
 * }
 */

const dynamodb = require('./dynamodb');

async function createTable() {
  console.log('going to create "repo-analytics-user" table');
  await dynamodb.createTable({
    TableName: 'repo-analytics-user',
    KeySchema: [
      { AttributeName: 'username', KeyType: 'HASH' },
    ],
    AttributeDefinitions: [
      { AttributeName: 'username', AttributeType: 'S' },
    ],
    BillingMode: 'PAY_PER_REQUEST',
    // ProvisionedThroughput: {
    //   ReadCapacityUnits: 1,
    //   WriteCapacityUnits: 1,
    // },
  }).promise();
  console.log('successfully created table "repo-analytics-user"');
}

async function deleteTable() {
  await dynamodb.deleteTable({ TableName: 'repo-analytics-user' }).promise();
}

async function get({ username }) {
  const { Item } = await dynamodb.getItem({
    TableName: 'repo-analytics-user',
    Key: {
      username: { S: username },
    },
  }).promise();
  return Item;
}

async function put({
  username, email, accessToken, displayName, photo,
}) {
  if (displayName) {
    await dynamodb.putItem({
      TableName: 'repo-analytics-user',
      Item: {
        username: { S: username },
        email: { S: email },
        accessToken: { S: accessToken },
        displayName: { S: displayName },
        photo: { S: photo },
        createdAt: { S: new Date().toISOString() },
      },
    }).promise();
  } else {
    await dynamodb.putItem({
      TableName: 'repo-analytics-user',
      Item: {
        username: { S: username },
        email: { S: email },
        accessToken: { S: accessToken },
        photo: { S: photo },
        createdAt: { S: new Date().toISOString() },
      },
    }).promise(); 
  }

}

async function scan() {
  const data = await dynamodb.scan({
    TableName: 'repo-analytics-user',
    AttributesToGet: [
      'username',
      'accessToken'
    ],
  }).promise();

  // FIXME: if user data larger than 1MB data, we need to handle pagination
  return data.Items;
}

module.exports = {
  createTable,
  deleteTable,
  get,
  put,
  scan,
};


// // test
// (async () => {
//   // await createTable();
//   // await new Promise((r) => setTimeout(r, 1000));
//   // await put({
//   //   username: 'timqn',
//   //   email: 'timqian@t9t.io',
//   //   displayName: 'timqian', photo:'abc',
//   // });
//   // const item = await get({
//   //   username: 'timqian',
//   // });
//   // console.log(item);

//   // const scanRes = await scan();
//   // console.log(scanRes)
// })();


================================================
FILE: backend/db/dynamodb.js
================================================
const AWS = require('aws-sdk');

let config = {};

try {
  config = require('../secret.json');
} catch (error) {
  console.log('no secret json, on github action')
}

const awsConfig = {
  region: 'us-east-1',
  // process.env.awsAccessKeyId in action secret
  accessKeyId: process.env.awsAccessKeyId ? process.env.awsAccessKeyId : config.aws.accessKeyId,
  secretAccessKey: process.env.awsSecretAccessKey ? process.env.awsSecretAccessKey : config.aws.secretAccessKey,
  signatureVersion: 'v4',
};

AWS.config.update(awsConfig);

const dynamodb = new AWS.DynamoDB();

module.exports = dynamodb;


================================================
FILE: backend/package.json
================================================
{
  "name": "backend",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js",
    "deploy": "up deploy production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.543.0",
    "axios": "^0.19.0",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dayjs": "^1.8.16",
    "express": "^4.17.1",
    "graphql-request": "^1.8.2",
    "jwt-simple": "^0.5.6",
    "passport": "^0.4.1",
    "passport-github": "^1.1.0"
  }
}


================================================
FILE: backend/scripts/README.md
================================================
## TODO

- add cities in the largest cities

## Refs

- List of largest cities: https://en.wikipedia.org/wiki/List_of_largest_cities
- Largest cities in China: https://en.wikipedia.org/wiki/List_of_cities_in_China_by_population
- United States: https://en.wikipedia.org/wiki/List_of_United_States_cities_by_population
- Russuia: https://en.wikipedia.org/wiki/List_of_cities_and_towns_in_Russia_by_population
- Canada: https://en.wikipedia.org/wiki/List_of_the_100_largest_population_centres_in_Canada


================================================
FILE: backend/scripts/countries.json
================================================
[{
  "country": "russia",
  "states": [], "alias": [],
  "cities": ["moscow",
    "saint petersburg",
    "novosibirsk",
    "yekaterinburg",
    "nizhny novgorod",
    "kazan",
    "chelyabinsk",
    "omsk",
    "samara",
    "rostov-on-don",
    "ufa",
    "krasnoyarsk",
    "perm",
    "voronezh",
    "volgograd",
    "krasnodar",
    "saratov",
    "tyumen",
    "tolyatti",
    "izhevsk",
    "barnaul",
    "ulyanovsk",
    "irkutsk",
    "khabarovsk",
    "yaroslavl",
    "vladivostok",
    "makhachkala",
    "tomsk",
    "orenburg",
    "kemerovo",
    "novokuznetsk",
    "ryazan",
    "astrakhan",
    "naberezhnye chelny",
    "penza",
    "lipetsk",
    "kirov",
    "cheboksary",
    "tula",
    "kaliningrad",
    "balashikha",
    "kursk",
    "stavropol",
    "ulan-ude",
    "tver",
    "magnitogorsk",
    "sochi",
    "ivanovo",
    "bryansk",
    "belgorod",
    "surgut",
    "vladimir",
    "nizhny tagil",
    "arkhangelsk",
    "chita",
    "kaluga",
    "smolensk",
    "volzhsky",
    "kurgan",
    "cherepovets",
    "oryol",
    "saransk",
    "vologda",
    "yakutsk",
    "vladikavkaz",
    "podolsk",
    "murmansk",
    "grozny",
    "tambov",
    "sterlitamak",
    "petrozavodsk",
    "kostroma",
    "nizhnevartovsk",
    "novorossiysk",
    "yoshkar-ola",
    "taganrog",
    "komsomolsk-on-amur",
    "khimki",
    "syktyvkar",
    "nalchik",
    "nizhnekamsk",
    "shakhty",
    "dzerzhinsk",
    "bratsk",
    "orsk",
    "angarsk",
    "engels",
    "blagoveshchensk",
    "stary oskol",
    "veliky novgorod",
    "korolyov",
    "pskov",
    "mytishchi",
    "biysk",
    "lyubertsy",
    "prokopyevsk",
    "yuzhno-sakhalinsk",
    "balakovo",
    "armavir",
    "rybinsk",
    "severodvinsk",
    "abakan",
    "petropavlovsk-kamchatsky",
    "norilsk",
    "syzran",
    "volgodonsk",
    "ussuriysk",
    "kamensk-uralsky",
    "novocherkassk",
    "zlatoust",
    "elektrostal",
    "almetyevsk",
    "krasnogorsk",
    "salavat",
    "miass",
    "nakhodka",
    "kopeysk",
    "pyatigorsk",
    "rubtsovsk",
    "berezniki",
    "kolomna",
    "maykop",
    "odintsovo",
    "khasavyurt",
    "kovrov",
    "kislovodsk",
    "neftekamsk",
    "nefteyugansk",
    "novocheboksarsk",
    "serpukhov",
    "shchyolkovo",
    "novomoskovsk",
    "bataysk",
    "pervouralsk",
    "domodedovo",
    "derbent",
    "cherkessk",
    "orekhovo-zuyevo",
    "nevinnomyssk",
    "dimitrovgrad",
    "nazran",
    "kyzyl",
    "oktyabrsky",
    "obninsk",
    "kaspiysk",
    "novy urengoy",
    "ramenskoye",
    "kamyshin",
    "murom",
    "zhukovsky",
    "novoshakhtinsk",
    "seversk",
    "yessentuki",
    "noyabrsk",
    "artyom",
    "pushkino",
    "achinsk",
    "yelets",
    "sergiyev posad",
    "arzamas",
    "dolgoprudny",
    "elista",
    "berdsk",
    "novokuybyshevsk",
    "noginsk",
    "zheleznogorsk",
    "reutov",
    "zelenodolsk",
    "tobolsk",
    "khanty-mansiysk",
    "votkinsk",
    "sarapul",
    "mezhdurechensk",
    "ukhta",
    "serov",
    "leninsk-kuznetsky",
    "gatchina",
    "sarov",
    "solikamsk",
    "voskresensk",
    "michurinsk",
    "glazov",
    "velikiye luki",
    "magadan",
    "kiselyovsk",
    "kansk",
    "kamensk-shakhtinsky",
    "novotroitsk",
    "mikhaylovsk",
    "lobnya",
    "gubkin",
    "buzuluk",
    "bugulma",
    "yeysk",
    "zheleznogorsk",
    "kineshma",
    "chaykovsky",
    "kuznetsk",
    "ust-ilimsk",
    "yurga",
    "novouralsk",
    "azov",
    "ozyorsk",
    "kropotkin",
    "klin",
    "vyborg",
    "bor",
    "usolye-sibirskoye",
    "balashov",
    "shadrinsk",
    "mineralnye vody",
    "anapa",
    "troitsk",
    "dubna",
    "gelendzhik",
    "chernogorsk",
    "ivanteyevka",
    "birobidzhan",
    "yelabuga",
    "yegoryevsk",
    "novoaltaysk",
    "kirovo-chepetsk",
    "chapayevsk",
    "belovo",
    "anzhero-sudzhensk",
    "chekhov",
    "vsevolozhsk",
    "verkhnyaya pyshma",
    "georgiyevsk",
    "tuymazy",
    "minusinsk",
    "sosnovy bor",
    "kstovo",
    "dmitrov",
    "belogorsk",
    "stupino",
    "gukovo",
    "kungur",
    "slavyansk-na-kubani",
    "beloretsk",
    "pavlovsky posad",
    "ishimbay",
    "ishim",
    "vidnoye",
    "zarechny",
    "kogalym",
    "asbest",
    "buynaksk",
    "volsk",
    "donskoy",
    "gorno-altaysk",
    "leninogorsk",
    "rossosh",
    "tuapse",
    "klintsy",
    "budyonnovsk",
    "borisoglebsk",
    "revda",
    "lysva",
    "zelenogorsk",
    "polevskoy",
    "naro-fominsk",
    "kotlas",
    "sibay",
    "labinsk",
    "kumertau",
    "chistopol",
    "fryazino",
    "rzhev",
    "lesosibirsk",
    "alexandrov",
    "belebey",
    "tikhoretsk",
    "shuya",
    "urus-martan",
    "meleuz",
    "mikhaylovka",
    "aleksin",
    "salsk",
    "pavlovo",
    "izberbash",
    "vorkuta",
    "shchyokino",
    "tikhvin",
    "prokhladny",
    "nyagan",
    "lytkarino",
    "krasnoturyinsk",
    "krymsk",
    "neryungri",
    "beryozovsky",
    "iskitim",
    "apatity",
    "gus-khrustalny",
    "dzerzhinsky",
    "volzhsk",
    "zhigulyovsk",
    "liski",
    "svobodny",
    "krasnokamsk",
    "vyksa",
    "vyazma",
    "shali",
    "krasnokamensk",
    "arsenyev",
    "solnechnogorsk",
    "timashyovsk",
    "belorechensk",
    "kirishi",
    "uzlovaya",
    "gudermes",
    "sertolovo",
    "cheremkhovo",
    "severomorsk",
    "borovichi",
    "roslavl",
    "snezhinsk",
    "nazarovo"]
}, {
  "country": "canada",
  "states": [], "alias": [],
  "cities": ["montreal",
    "vancouver",
    "calgary",
    "edmonton",
    "ottawa–gatineau",
    "winnipeg",
    "quebec city",
    "hamilton",
    "kitchener",
    "london",
    "victoria",
    "halifax",
    "oshawa",
    "windsor",
    "saskatoon",
    "st. catharines–niagara falls",
    "regina",
    "st. john's",
    "kelowna",
    "barrie",
    "sherbrooke",
    "guelph",
    "abbotsford",
    "kingston",
    "kanata",
    "trois-rivières",
    "moncton",
    "chicoutimi–jonquière",
    "milton",
    "red deer",
    "brantford",
    "thunder bay",
    "white rock",
    "nanaimo",
    "sudbury",
    "lethbridge",
    "saint-jean-sur-richelieu",
    "peterborough",
    "kamloops",
    "saint-jérôme",
    "chilliwack",
    "sarnia",
    "châteauguay",
    "drummondville",
    "belleville",
    "fort mcmurray",
    "sault ste. marie",
    "prince george",
    "medicine hat",
    "welland–pelham",
    "grande prairie",
    "airdrie",
    "granby",
    "fredericton",
    "saint john",
    "beloeil",
    "north bay",
    "saint-hyacinthe",
    "brandon",
    "vernon",
    "cornwall",
    "joliette",
    "courtenay",
    "charlottetown",
    "victoriaville",
    "chatham",
    "georgetown",
    "st. thomas",
    "woodstock",
    "bowmanville",
    "salaberry-de-valleyfield",
    "shawinigan",
    "rimouski",
    "spruce grove",
    "sorel",
    "campbell river",
    "prince albert",
    "penticton",
    "mission",
    "leamington",
    "moose jaw",
    "stouffville",
    "lloydminster",
    "orillia",
    "stratford",
    "orangeville",
    "cape breton–sydney",
    "bradford",
    "leduc",
    "timmins",
    "okotoks",
    "saint-georges",
    "keswick–elmhurst beach",
    "bolton",
    "val-d'or",
    "cochrane",
    "quispamsis–rothesay",
    "midland",
    "innisfil"]
}, {
  "country": "united states",
  "states": [], "alias": ["usa", "america"],
  "cities": ["new york",
    "los angeles",
    "chicago",
    "houston",
    "phoenix",
    "philadelphia",
    "san antonio",
    "san diego",
    "dallas",
    "san jose",
    "austin",
    "jacksonville",
    "fort worth",
    "columbus",
    "san francisco",
    "charlotte",
    "indianapolis",
    "seattle",
    "denver",
    "washington",
    "boston",
    "el paso",
    "detroit",
    "nashville",
    "portland",
    "memphis",
    "oklahoma city",
    "las vegas",
    "louisville",
    "baltimore",
    "milwaukee",
    "albuquerque",
    "tucson",
    "fresno",
    "mesa",
    "sacramento",
    "atlanta",
    "kansas city",
    "colorado springs",
    "miami",
    "raleigh",
    "omaha",
    "long beach",
    "virginia beach",
    "oakland",
    "minneapolis",
    "tulsa",
    "arlington",
    "tampa",
    "new orleans",
    "wichita",
    "cleveland",
    "bakersfield",
    "aurora",
    "anaheim",
    "honolulu",
    "santa ana",
    "riverside",
    "corpus christi",
    "lexington",
    "stockton",
    "henderson",
    "saint paul",
    "st. louis",
    "cincinnati",
    "pittsburgh",
    "greensboro",
    "anchorage",
    "plano",
    "lincoln",
    "orlando",
    "irvine",
    "newark",
    "toledo",
    "durham",
    "chula vista",
    "fort wayne",
    "jersey city",
    "st. petersburg",
    "laredo",
    "madison",
    "chandler",
    "buffalo",
    "lubbock",
    "scottsdale",
    "reno",
    "glendale",
    "gilbert",
    "winston–salem",
    "north las vegas",
    "norfolk",
    "chesapeake",
    "garland",
    "irving",
    "hialeah",
    "fremont",
    "boise",
    "richmond",
    "baton rouge",
    "spokane",
    "des moines",
    "tacoma",
    "san bernardino",
    "modesto",
    "fontana",
    "santa clarita",
    "birmingham",
    "oxnard",
    "fayetteville",
    "moreno valley",
    "rochester",
    "glendale",
    "huntington beach",
    "salt lake city",
    "grand rapids",
    "amarillo",
    "yonkers",
    "aurora",
    "montgomery",
    "akron",
    "little rock",
    "huntsville",
    "augusta",
    "port st. lucie",
    "grand prairie",
    "columbus",
    "tallahassee",
    "overland park",
    "tempe",
    "mckinney",
    "mobile",
    "cape coral",
    "shreveport",
    "frisco",
    "knoxville",
    "worcester",
    "brownsville",
    "vancouver",
    "fort lauderdale",
    "sioux falls",
    "ontario",
    "chattanooga",
    "providence",
    "newport news",
    "rancho cucamonga",
    "santa rosa",
    "oceanside",
    "salem",
    "elk grove",
    "garden grove",
    "pembroke pines",
    "peoria",
    "eugene",
    "corona",
    "cary",
    "springfield",
    "fort collins",
    "jackson",
    "alexandria",
    "hayward",
    "lancaster",
    "lakewood",
    "clarksville",
    "palmdale",
    "salinas",
    "springfield",
    "hollywood",
    "pasadena",
    "sunnyvale",
    "macon",
    "kansas city",
    "pomona",
    "escondido",
    "killeen",
    "naperville",
    "joliet",
    "bellevue",
    "rockford",
    "savannah",
    "paterson",
    "torrance",
    "bridgeport",
    "mcallen",
    "mesquite",
    "syracuse",
    "midland",
    "pasadena",
    "murfreesboro",
    "miramar",
    "dayton",
    "fullerton",
    "olathe",
    "orange",
    "thornton",
    "roseville",
    "denton",
    "waco",
    "surprise",
    "carrollton",
    "west valley city",
    "charleston",
    "warren",
    "hampton",
    "gainesville",
    "visalia",
    "coral springs",
    "columbia",
    "cedar rapids",
    "sterling heights",
    "new haven",
    "stamford",
    "concord",
    "kent",
    "santa clara",
    "elizabeth",
    "round rock",
    "thousand oaks",
    "lafayette",
    "athens",
    "topeka",
    "simi valley",
    "fargo",
    "norman",
    "columbia",
    "abilene",
    "wilmington",
    "hartford",
    "victorville",
    "pearland",
    "vallejo",
    "ann arbor",
    "berkeley",
    "allentown",
    "richardson",
    "odessa",
    "arvada",
    "cambridge",
    "sugar land",
    "beaumont",
    "lansing",
    "evansville",
    "rochester",
    "independence",
    "fairfield",
    "provo",
    "clearwater",
    "college station",
    "west jordan",
    "carlsbad",
    "el monte",
    "murrieta",
    "temecula",
    "springfield",
    "palm bay",
    "costa mesa",
    "westminster",
    "north charleston",
    "miami gardens",
    "manchester",
    "high point",
    "downey",
    "clovis",
    "pompano beach",
    "pueblo",
    "elgin",
    "lowell",
    "antioch",
    "west palm beach",
    "peoria",
    "everett",
    "ventura",
    "centennial",
    "lakeland",
    "gresham",
    "richmond",
    "billings",
    "inglewood",
    "broken arrow",
    "sandy springs",
    "jurupa valley",
    "hillsboro",
    "waterbury",
    "santa maria",
    "boulder",
    "greeley",
    "daly city",
    "meridian",
    "lewisville",
    "davie",
    "west covina",
    "league city",
    "tyler",
    "norwalk",
    "san mateo",
    "green bay",
    "wichita falls",
    "sparks",
    "lakewood",
    "burbank",
    "rialto",
    "allen",
    "el cajon",
    "las cruces",
    "renton",
    "davenport",
    "south bend",
    "vista",
    "tuscaloosa",
    "clinton",
    "edison",
    "woodbridge",
    "san angelo",
    "kenosha",
    "vacaville"]
}, {
  "country": "china",
  "states": [], "alias": [],
  "cities": ["shanghai","beijing","guangzhou","shenzhen","tianjin","wuhan","dongguan","chengdu","foshan","chongqing","nanjing","shenyang","hangzhou","xi'an","harbin","suzhou","qingdao","dalian","zhengzhou","shantou","jinan","changchun","kunming","changsha","taiyuan","xiamen","hefei","shijiazhuang","ürümqi","fuzhou","wuxi","zhongshan","wenzhou","nanning","nanchang","ningbo","guiyang","lanzhou","zibo","changzhou","xuzhou","tangshan","baotou","huizhou","yantai","shaoxing","liuzhou","nantong","luoyang","yangzhou"]
}, {
  "country": "brazil",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "australia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "india",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "argentina",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "kazakhstan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "algeria",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "democratic republic of the congo",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "greenland",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "mexico",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "saudi arabia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "indonesia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "sudan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "libya",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "iran",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "mongolia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "peru",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "chad",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "niger",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "angola",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "mali",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "south africa",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "colombia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "ethiopia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "bolivia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "mauritania",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "egypt",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "tanzania",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "nigeria",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "venezuela",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "namibia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "pakistan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "mozambique",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "turkey",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "chile",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "zambia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "myanmar",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "afghanistan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "south sudan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "somalia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "central african republic",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "ukraine",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "botswana",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "madagascar",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "kenya",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "france",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "yemen",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "thailand",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "spain",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "turkmenistan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "cameroon",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "papua new guinea",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "sweden",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "uzbekistan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "morocco",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "iraq",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "paraguay",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "zimbabwe",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "japan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "germany",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "republic of congo",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "finland",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "malaysia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "vietnam",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "norway",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "ivory coast",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "poland",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "italy",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "philippines",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "ecuador",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "burkina faso",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "new zealand",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "gabon",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "western sahara",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "guinea",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "united kingdom",
  "states": [], "alias": ["uk"],
  "cities": []
}, {
  "country": "ghana",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "romania",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "laos",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "uganda",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "guyana",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "oman",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "belarus",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "kyrgyzstan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "senegal",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "syria",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "cambodia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "uruguay",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "tunisia",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "suriname",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "bangladesh",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "tajikistan",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "nepal",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "greece",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "nicaragua",
  "states": [], "alias": [],
  "cities": []
}, {
  "country": "eritrea",
  "states": [], "alias": [],
  "cities": []
}]

================================================
FILE: backend/scripts/dailyGetStars.js
================================================
const RepoDao = require('../db/Repo');
const getStars = require('../utils/getStars');
const StarDao = require('../db/Star');

const get = async () => {
  const repos = await RepoDao.scan();

  for (const repo of repos) {
    const repoPath = repo.repo.S;
    // if (repoPath !== 'NervJS/taro') continue;
    const repoOwner = repo.username.S;
    try {
      console.log('going to fetch', repoOwner, repoPath)
      const res = await getStars(repoOwner, repoPath);
      console.log('going to store', repoOwner, repoPath);
      await StarDao.put({
        repo: repoPath,
        ...res
      });
      console.log('success', repoOwner, repoPath);
    } catch (error) {
      if(error.response) {
        console.log(error.response.message);
      } else {
        console.log(error.message)
      }
    }
  }
}

get();


================================================
FILE: backend/scripts/dailyGetTraffics.js
================================================
const axios = require('axios');
const UserDao = require('../db/User');
const RepoDao = require('../db/Repo');
const TrafficDao = require('../db/Traffic');

/**
 * This script get daily traffic data for all repos.
 * Run once per day
 * 
 * Process
 *   1. get all users
 *   1. get all repos
 *   1. for every repo: get its traffic by using user's token
 */
async function run() {
  const dateStr = new Date().toISOString().slice(0, 10);

  // ---- 1. get all users ----

  // [{ username: { S: 'timqian' }, accessToken: { S: 'token' }}]
  const users = await UserDao.scan();
  // { timqian: 'token' }
  const userMap = users.reduce((pre, cur) => {
    pre[cur.username.S] = cur.accessToken.S;
    return pre;
  }, {});

  // ---- 2. get all repos ----

  // [{ username: { S: 'timqian' }, repo: { S: 'timqian/chart.xkcd' }}]
  const repos = await RepoDao.scan();

  // [{ username: 'timqian', repo: 'timqian/chart.xkcd', accessToken: 'token' }]
  const repoArr = repos.map(repo => {
    const username = repo.username.S;
    const createdAt = repo.createdAt.S;
    const accessToken = userMap[username];
    return {
      username,
      repo: repo.repo.S,
      accessToken,
      createdAt,
    }
  });

  // ---- 3. query and store to db ----
  for(let i = 0; i < repoArr.length; i++) {
    const repo = repoArr[i];
    try {
      // if (!['airyland/vux', 'ZhuPeng/mp-transform-public', 'amorist/platelet', 'timqian/star-history'].includes(repo.repo)) continue;
      console.log('Fetching', repo.repo);
      const http = axios.create({
        baseURL: 'https://api.github.com/',
        timeout: 30000,
        headers: {
          'Accept': 'application/vnd.github.v3+json',
          'Authorization': `token ${repo.accessToken}`,
        },
      });
      const viewsPromise = http.get(`/repos/${repo.repo}/traffic/views`);
      const clonesPromise = http.get(`/repos/${repo.repo}/traffic/clones`);
      const referrersPromise = http.get(`/repos/${repo.repo}/traffic/popular/referrers`);
      const pathsPromise = http.get(`/repos/${repo.repo}/traffic/popular/paths`);
      
      const trafficRes = await Promise.all([viewsPromise, clonesPromise, referrersPromise, pathsPromise]);
      
      await TrafficDao.put({
        repo: repo.repo,
        date: dateStr,
        views: trafficRes[0].data.views,
        clones: trafficRes[1].data.clones,
        referrers: trafficRes[2].data,
        paths: trafficRes[3].data,
        repoCreatedAt: repo.createdAt,
      });
    } catch (error) {
      if(error.response) {
        console.log(error.response.message);
      } else {
        console.log(error.message)
      }
    }

  }
}

run();

================================================
FILE: backend/scripts/getStarsAndSaveDbForRepoWithoutRepos.js
================================================
const { GraphQLClient } = require('graphql-request');
const guess = require('./guessCountryFromAddress');

const UserDao = require('../db/User');

/**
 * Get all stargazers of a repo and store to db
 * 
 * {
 *   totalCount: '',
 *   updatedAt: '',
 *   history: {
 *     '2018-04-12': 10,
 *   },
 *   locations: {
 *     china: 3,
 *   }
 * }
 */

const getStars = async (username, repoPath) => {
  const res = {
    totalCount: 0,
    updatedAt: '',
    history: {},
    locations: {},
  };

  const user = await UserDao.get({username});
  const token = user.accessToken.S;
  const [repoOwner, repoName] = repoPath.split('/')

  const endpoint = 'https://api.github.com/graphql';

  const graphQLClient = new GraphQLClient(endpoint, {
    headers: {
      Authorization: `bearer ${token}`,
    },
  })

  const query = `
    {
      repository(owner: "${repoOwner}", name: "${repoName}") {
        stargazers(first: 100) {
          nodes {
            location
          }
          edges {
            starredAt
          }
          totalCount
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    }  
  `;

  let data = await graphQLClient.request(query);
  res.totalCount = data.repository.stargazers.totalCount;

  const updateRes = (stargazers) => {
    const dateArr = stargazers.edges;
    const userArr = stargazers.nodes;

    dateArr.forEach(element => {
      const starDate = element.starredAt.slice(0, 10);
      if(res.history[starDate]) {
        res.history[starDate] = res.history[starDate] + 1;
      } else {
        res.history[starDate] = 1;
      }
    });

    userArr.forEach(el => {
      if (el.location) {
        const location = guess(el.location);
        if (location) res.locations[location]
          ? res.locations[location] = res.locations[location] + 1 
          : res.locations[location] = 1;
      }
    })
  }

  updateRes(data.repository.stargazers);

  let pageCount = 0
  while(data.repository.stargazers.pageInfo.hasNextPage) {
    console.log('page count', pageCount + 1);
    const query2 = `
    {
      repository(owner: "${repoOwner}", name: "${repoName}") {
        stargazers(first: 100, after: "${data.repository.stargazers.pageInfo.endCursor}") {
          nodes {
            location
          }
          edges {
            starredAt
          }
          totalCount
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    }   
    `;
    data = await graphQLClient.request(query2);
    updateRes(data.repository.stargazers); 
    pageCount++;
  }

  res.updatedAt = new Date().toISOString();
  // console.log(res)
  return res;
}


module.exports = getStars;
// getStars('timqian', 't9tio/cloudquery')


================================================
FILE: backend/scripts/guessCountryFromAddress.js
================================================
const countries = require('./countries.json');

const guess = (address) => {
  const lowerCaseAddr = address.toLowerCase();
  let guess = null;
  for(let i = 0; i < countries.length; i++) {
    const country = countries[i];
    if (lowerCaseAddr.includes(country.country)) {
      guess = country.country;
      break;
    }

    for(let j = 0; j < country.alias.length; j++) {
      if (lowerCaseAddr.includes(country.alias[j])) {
        guess = country.country;
        break;
      }
    }

    for(let j = 0; j < country.cities.length; j++) {
      if (lowerCaseAddr.includes(country.cities[j])) {
        guess = country.country;
        break;
      }
    }

    if (guess) break;
  }
  return guess;
}

module.exports = guess;

// // test
// console.log(guess('China'));
// console.log(guess('beijing, china'));
// console.log(guess('USA'));
// console.log(guess('new york'));
console.log(guess('inia'))

================================================
FILE: backend/server.js
================================================
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const passport = require('passport');
const GitHubStrategy = require('passport-github').Strategy;
const jwt = require('jwt-simple');
const UserDao = require('./db/User');
const RepoDao = require('./db/Repo');
const TrafficDao = require('./db/Traffic');
const StarDao = require('./db/Star');
const config = require('./secret.json');
const trafficDateRangeToDateArr = require('./utils/trafficDateRangeToDateArr');
const getUniqueListBy = require('./utils/getUniqueListBy');
const getTrafficOfRepoAndSave = require('./utils/getTrafficOfRepoAndSave');
const getStars = require('./utils/getStars');

const app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(passport.initialize());

passport.use(
  new GitHubStrategy(
    {
      clientID: config.github.clientID,
      clientSecret: config.github.clientSecret,
      scope: 'user:email,public_repo',
      callbackURL: 'https://repo-analytics.t9t.io/auth/github/callback',
    },
    async (accessToken, refreshToken, profile, cb) => {
      /**
       * {
       *   id: '5512552',
       *   displayName: 'Tim Qian',
       *   username: 'timqian',
       *   profileUrl: 'https://github.com/timqian',
       *   emails: [
       *     { value: 'timqian92@gmail.com', primary: false, verified: true },
       *     { value: 'timqian92@qq.com', primary: true, verified: false },
       *     { value: 'timqian@shu.edu.cn', primary: false, verified: true }
       *   ],
       *   photos: [{ value: 'https://avatars3.githubusercontent.com/u/5512552?v=4' }],
       * }
       */
      const {
        id, username, displayName, emails, photos,
      } = profile;
      // FIXME: add updatedAt to record user relogin
      // const user = await UserDao.get({ username });

      // console.log(emails)
      const userToSave = {
        username,

        accessToken,
        email: emails.filter(email => email.primary === true)[0].value,
        photo: photos[0].value,
      };

      if (displayName) userToSave.displayName = displayName;

      // if (!user) {
        await UserDao.put(userToSave);
      // }
      profile.accessToken = accessToken
      cb(null, profile);
    },
  ),
);

app.get(
  '/auth/github',
  passport.authenticate('github'),
);

app.get(
  '/auth/github/callback',
  passport.authenticate('github', { failureRedirect: '/login', session: false }),
  async (req, res) => {
    const {
      id, username, displayName, emails, photos,
    } = req.user;

    const token = jwt.encode({ username }, config.jwtSecret);
    res.redirect(`https://repo-analytics.github.io/${username}?username=${username}&photo=${photos[0].value}&token=${token}`);
  },
);

/**
 * {
 *   repos: [{
 *     username: 'timqian',
 *     repo: 'timqian/chart.xkcd',
 *     createdAt: '',
 *     views: [{"timestamp":"2019-09-29T00:00:00Z","count":11,"uniques":8}],
 *   }]
 * }
 */
app.get('/user/:username', async (req, res) => {
  const username = req.params.username;
  const repos = await RepoDao.getAllForUser({ username });
  const promiseArr = repos.map(repo => {
    const repoPath = repo.repo.S;
    // FIXME: getting unnecessary data - add another method
    return TrafficDao.getLatest({ repo: repoPath });
  });

  const traffics = await Promise.all(promiseArr);
  const returnRepos = repos.map((repo, i) => {

    const obj = {
      username: repo.username.S,
      repo: repo.repo.S,
      createdAt: repo.createdAt.S,
      views: JSON.parse(traffics[i].views.S),
    }

    return obj;
  });

  res.json({
    repos: returnRepos,
  })
});

/**
 * @returns - grouped: vistit and clone data; 14 days: referrer and paths data
 * {
 *   views: [{
 *     timestamp: '2019-03-12',
 *     count: 500,
 *     unique: 300.
 *   }],
 *   clones: [{
 *     timestamp: '2019-03-12',
 *     count: 500,
 *     unique: 300.
 *   }],
 * }
 */
app.get('/repo/:org/:repo', async (req, res) => {
  const org = req.params.org;
  const repo = req.params.repo;
  const repoPath = `${org}/${repo}`;

  const latestTrafficData = await TrafficDao.getLatest({ repo: repoPath });
  const trafficObj = {
    date: latestTrafficData.date.S, // date when latest traffic data created
    repoCreatedAt: latestTrafficData.repoCreatedAt.S, // when do we start to collect data
    views: JSON.parse(latestTrafficData.views.S), // all data
    clones: JSON.parse(latestTrafficData.clones.S), // all data
    referrers: JSON.parse(latestTrafficData.referrers.S), // last 14 days
    paths: JSON.parse(latestTrafficData.paths.S), // last 14 days
  }

  // 4. combine views and clones data - how, choose larger count if timestamp is the same
  // assuming traffic data exists for everyday
  const dateArr = trafficDateRangeToDateArr(trafficObj.repoCreatedAt.slice(0,10), trafficObj.date);

  // No need to get more clone and view data
  if (!dateArr) {
    res.json({
      traffic: trafficObj,
    });
    return;
  }

  const batchRes = await TrafficDao.batchGetViewAndClones({ repo: repoPath, dateArr });

  for (const traffic of batchRes) {
    const clones = JSON.parse(traffic.clones.S);
    const views = JSON.parse(traffic.views.S);
    trafficObj.clones.unshift(...clones);
    trafficObj.views.unshift(...views);
  }

  trafficObj.clones = getUniqueListBy(trafficObj.clones, 'timestamp')
    .sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
  trafficObj.views = getUniqueListBy(trafficObj.views, 'timestamp')
    .sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));

  res.json({
    traffic: trafficObj,
  });

});

app.get('/repo/:org/:repo/stars', async (req, res) => {
  const org = req.params.org;
  const repo = req.params.repo;
  const repoPath = `${org}/${repo}`; 
  const starRes = await StarDao.get({repo: repoPath});

  const starObj = {
    repo: starRes.repo.S,
    totalCount: starRes.totalCount.S,
    history: JSON.parse(starRes.history.S),
    locations: JSON.parse(starRes.locations.S),
    updatedAt: starRes.updatedAt.S,
  }
  res.json(starObj);
});

app.post('/repo/add', async (req, res) => {
  const { username, repoPath, token } = req.body;
  // 1. test if the user is allowed to add repo to username
  let decoded;
  try {
    decoded = jwt.decode(token, config.jwtSecret);
  } catch (error) {
    res.status(400).json('bad token');
    return;
  }
  if (decoded.username !== username) {
    res.status(400).json('token user mismatch');
    return;
  }

  // 2. test if user already have 3 repos TODO: remove after finishing billing part

  const userCurrentRepos = await RepoDao.getAllForUser({username});
  if (userCurrentRepos.length >= 3 && !config.patrons.includes(username) ) {
    res.status(400).json('Currently we only support importing 3 repos, see pricing page for more info');
    return;
  }

  // 3. test if user being able to get traffic of the repo
  const user = await UserDao.get({ username });
  const githubToken = user.accessToken.S;
  try {
    await getTrafficOfRepoAndSave({ repoPath, token: githubToken });
    // create repo
    await RepoDao.put({
      username,
      repo: repoPath,
    });

    // add star analytics(async)
    getStars(username, repoPath)
      .then(res => {
        StarDao.put({
          repo: repoPath,
          ...res
        });
      });

    res.json('ok');
  } catch (e) {
    console.log(e)
    res.status(400).json('github token permission insufficient');
  }
})

app.get('/', (req, res) => {
  res.json('hey')
});

const { PORT = 8080 } = process.env;
app.listen(PORT);
console.log(`server running on http://localhost:${PORT}`);


================================================
FILE: backend/up.json
================================================
{
  "name": "repo-traffic",
  "profile": "timConsole",
  "regions": ["us-east-1"],
  "error_pages": {
    "variables": {
      "support_email": "timqian@t9t.io",
      "color": "#228ae6"
    }
  },
  "stages": {
    "production": {
      "domain": "repo-analytics.t9t.io"
    },
    "staging": {
      "domain": "repo-analytics-staging.t9t.io"
    }
  },
  "lambda": {
    "memory": 1536
  }
}

================================================
FILE: backend/utils/getStars.js
================================================
const { GraphQLClient } = require('graphql-request');
const guess = require('../scripts/guessCountryFromAddress');

const UserDao = require('../db/User');

/**
 * Get all stargazers of a repo and store to db
 * 
 * {
 *   totalCount: '',
 *   updatedAt: '',
 *   history: {
 *     '2018-04-12': 10,
 *   },
 *   locations: {
 *     china: 3,
 *   }
 * }
 */

const getStars = async (username, repoPath) => {
  const res = {
    totalCount: 0,
    updatedAt: '',
    history: {},
    locations: {},
  };

  const user = await UserDao.get({username});
  const token = user.accessToken.S;
  const [repoOwner, repoName] = repoPath.split('/')

  const endpoint = 'https://api.github.com/graphql';

  const graphQLClient = new GraphQLClient(endpoint, {
    headers: {
      Authorization: `bearer ${token}`,
    },
  })

  const query = `
    {
      repository(owner: "${repoOwner}", name: "${repoName}") {
        stargazers(first: 100) {
          nodes {
            location
          }
          edges {
            starredAt
          }
          totalCount
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    }  
  `;

  let data = await graphQLClient.request(query);
  res.totalCount = data.repository.stargazers.totalCount;

  const updateRes = (stargazers) => {
    const dateArr = stargazers.edges;
    const userArr = stargazers.nodes;

    dateArr.forEach(element => {
      const starDate = element.starredAt.slice(0, 10);
      if(res.history[starDate]) {
        res.history[starDate] = res.history[starDate] + 1;
      } else {
        res.history[starDate] = 1;
      }
    });

    userArr.forEach(el => {
      if (el.location) {
        const location = guess(el.location);
        if (location) res.locations[location]
          ? res.locations[location] = res.locations[location] + 1 
          : res.locations[location] = 1;
      }
    })
  }

  updateRes(data.repository.stargazers);

  while(data.repository.stargazers.pageInfo.hasNextPage) {
    console.log(data.repository.stargazers.pageInfo)
    const query2 = `
    {
      repository(owner: "${repoOwner}", name: "${repoName}") {
        stargazers(first: 100, after: "${data.repository.stargazers.pageInfo.endCursor}") {
          nodes {
            location
          }
          edges {
            starredAt
          }
          totalCount
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    }   
    `;
    data = await graphQLClient.request(query2);
    updateRes(data.repository.stargazers); 
  }

  res.updatedAt = new Date().toISOString();
  // console.log(res)
  return res;
}


module.exports = getStars;
// getStars('timqian', 't9tio/cloudquery')


================================================
FILE: backend/utils/getTrafficOfRepoAndSave.js
================================================
const axios = require('axios');
const TrafficDao = require('../db/Traffic');

const func = async ({ repoPath, token }) => {
  const http = axios.create({
    baseURL: 'https://api.github.com/',
    timeout: 10000,
    headers: {
      'Accept': 'application/vnd.github.v3+json',
      'Authorization': `token ${token}`,
    },
  });
  const viewsPromise = http.get(`/repos/${repoPath}/traffic/views`);
  const clonesPromise = http.get(`/repos/${repoPath}/traffic/clones`);
  const referrersPromise = http.get(`/repos/${repoPath}/traffic/popular/referrers`);
  const pathsPromise = http.get(`/repos/${repoPath}/traffic/popular/paths`);

  const trafficRes = await Promise.all([viewsPromise, clonesPromise, referrersPromise, pathsPromise]);

  const dateStr = new Date().toISOString().slice(0, 10);

  await TrafficDao.put({
    repo: repoPath,
    date: dateStr,
    views: trafficRes[0].data.views,
    clones: trafficRes[1].data.clones,
    referrers: trafficRes[2].data,
    paths: trafficRes[3].data,
    repoCreatedAt: new Date().toISOString(),
  });
}

module.exports = func;

// test
// func({repoPath: 'timqian/chart.xkcd', token: ''})

================================================
FILE: backend/utils/getUniqueListBy.js
================================================
function getUniqueListBy(arr, key) {
  return [...new Map(arr.map(item => [item[key], item])).values()]
}

module.exports = getUniqueListBy;

// // test
// const res = getUniqueListBy([ { timestamp: '2019-09-27T00:00:00Z', count: 586, uniques: 352 },
// { timestamp: '2019-09-28T00:00:00Z', count: 175, uniques: 121 },
// { timestamp: '2019-09-29T00:00:00Z', count: 405, uniques: 251 },
// { timestamp: '2019-09-30T00:00:00Z', count: 322, uniques: 182 },
// { timestamp: '2019-10-01T00:00:00Z', count: 94, uniques: 58 },
// { timestamp: '2019-10-02T00:00:00Z', count: 152, uniques: 99 },
// { timestamp: '2019-10-03T00:00:00Z', count: 166, uniques: 91 },
// { timestamp: '2019-10-04T00:00:00Z', count: 83, uniques: 56 },
// { timestamp: '2019-10-05T00:00:00Z', count: 39, uniques: 31 },
// { timestamp: '2019-10-06T00:00:00Z', count: 92, uniques: 43 },
// { timestamp: '2019-10-07T00:00:00Z', count: 200, uniques: 96 },
// { timestamp: '2019-10-08T00:00:00Z', count: 255, uniques: 135 },
// { timestamp: '2019-10-09T00:00:00Z', count: 405, uniques: 161 },
// { timestamp: '2019-10-10T00:00:00Z', count: 236, uniques: 120 },
// { timestamp: '2019-09-27T00:00:00Z', count: 586, uniques: 352 },
// { timestamp: '2019-09-28T00:00:00Z', count: 175, uniques: 121 },
// { timestamp: '2019-09-29T00:00:00Z', count: 405, uniques: 251 },
// { timestamp: '2019-09-30T00:00:00Z', count: 322, uniques: 182 },
// { timestamp: '2019-10-01T00:00:00Z', count: 94, uniques: 58 },
// { timestamp: '2019-10-02T00:00:00Z', count: 152, uniques: 99 },
// { timestamp: '2019-10-03T00:00:00Z', count: 166, uniques: 91 },
// { timestamp: '2019-10-04T00:00:00Z', count: 83, uniques: 56 },
// { timestamp: '2019-10-05T00:00:00Z', count: 39, uniques: 31 },
// { timestamp: '2019-10-06T00:00:00Z', count: 92, uniques: 43 },
// { timestamp: '2019-10-07T00:00:00Z', count: 200, uniques: 96 },
// { timestamp: '2019-10-08T00:00:00Z', count: 255, uniques: 135 },
// { timestamp: '2019-10-09T00:00:00Z', count: 405, uniques: 161 },
// { timestamp: '2019-10-10T00:00:00Z', count: 236, uniques: 120 } ], 'timestamp');

// console.log(res);

================================================
FILE: backend/utils/trafficDateRangeToDateArr.js
================================================
const dayjs = require('dayjs');
/**
 * @param {String} earliestDate
 * @param {String} latestDate
 * @return {Array} date array
 * 
 * @example
 *   // ['2019-03-19', '2019-04-02', ..., '2019-10-01']
 *   func('2019-03-19', '2019-10-10')
 */
function func(earliestDate, latestDate) {
  const earliestDay = dayjs(earliestDate);
  const latestDay = dayjs(latestDate);
  const daysCount = latestDay.diff(earliestDay, 'day');

  if (daysCount <= 0) return undefined;

  let daysToGet = [earliestDay.format('YYYY-MM-DD')];
  if (daysCount > 14) {
    let curDay = earliestDay.add(14, 'days');
    while (curDay.isBefore(latestDay)) {
      daysToGet.push(curDay.format('YYYY-MM-DD'));
      curDay = curDay.add(14, 'days');
    }
  }

  return daysToGet;
}

module.exports = func;

// // test
// console.log(func('2019-03-19', '2019-10-10'));
// console.log(func('2019-10-08', '2019-10-10'));
// console.log(func('2019-10-01', '2019-10-10'));

================================================
FILE: frontend/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*


================================================
FILE: frontend/README.md
================================================
# Frontend code base of repo-traffic

## Important Scripts

```bash
# start dev server
npm start

# build website
npm build

# deploy to github pages
npm run deploy
```

## TODO

- [Make it an PWA](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.<br>
You will also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.<br>
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting

### Analyzing the Bundle Size

This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size

### Making a Progressive Web App

This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

### Advanced Configuration

This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration

### Deployment

This section has moved here: https://facebook.github.io/create-react-app/docs/deployment

### `npm run build` fails to minify

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify


================================================
FILE: frontend/package.json
================================================
{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.19.0",
    "chart.xkcd": "^1.1.7",
    "notie": "^4.3.1",
    "query-string": "^6.8.3",
    "react": "^16.10.1",
    "react-content-loader": "^4.3.1",
    "react-dom": "^16.10.1",
    "react-github-btn": "^1.0.6",
    "react-router-dom": "^5.1.1",
    "react-scripts": "3.1.2",
    "remixicon": "^2.0.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "deploy": "npm run build && gh-pages -d build -b master"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "gh-pages": "^2.1.1"
  }
}


================================================
FILE: frontend/public/404.html
================================================
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Single Page Apps for GitHub Pages</title>
    <script type="text/javascript">
      // Single Page Apps for GitHub Pages
      // https://github.com/rafrex/spa-github-pages
      // Copyright (c) 2016 Rafael Pedicini, licensed under the MIT License
      // ----------------------------------------------------------------------
      // This script takes the current url and converts the path and query
      // string into just a query string, and then redirects the browser
      // to the new url with only a query string and hash fragment,
      // e.g. http://www.foo.tld/one/two?a=b&c=d#qwe, becomes
      // http://www.foo.tld/?p=/one/two&q=a=b~and~c=d#qwe
      // Note: this 404.html file must be at least 512 bytes for it to work
      // with Internet Explorer (it is currently > 512 bytes)
      // If you're creating a Project Pages site and NOT using a custom domain,
      // then set segmentCount to 1 (enterprise users may need to set it to > 1).
      // This way the code will only replace the route part of the path, and not
      // the real directory in which the app resides, for example:
      // https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
      // https://username.github.io/repo-name/?p=/one/two&q=a=b~and~c=d#qwe
      // Otherwise, leave segmentCount as 0.
      var segmentCount = 0;
      var l = window.location;
      l.replace(
        l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
        l.pathname.split('/').slice(0, 1 + segmentCount).join('/') + '/?p=/' +
        l.pathname.slice(1).split('/').slice(segmentCount).join('/').replace(/&/g, '~and~') +
        (l.search ? '&q=' + l.search.slice(1).replace(/&/g, '~and~') : '') +
        l.hash
      );
    </script>
  </head>
  <body>
  </body>
</html>

================================================
FILE: frontend/public/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Thorough analytics for your GitHub repos"
    />
    <link rel="apple-touch-icon" href="logo.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link rel="stylesheet" type="text/css" href="https://unpkg.com/notie/dist/notie.min.css">
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>Repo Analytics</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
    
    <!-- Start Single Page Apps for GitHub Pages -->
    <script type="text/javascript">
      // Single Page Apps for GitHub Pages
      // https://github.com/rafrex/spa-github-pages
      // Copyright (c) 2016 Rafael Pedicini, licensed under the MIT License
      // ----------------------------------------------------------------------
      // This script checks to see if a redirect is present in the query string
      // and converts it back into the correct url and adds it to the
      // browser's history using window.history.replaceState(...),
      // which won't cause the browser to attempt to load the new url.
      // When the single page app is loaded further down in this file,
      // the correct url will be waiting in the browser's history for
      // the single page app to route accordingly.
      (function(l) {
        if (l.search) {
          var q = {};
          l.search.slice(1).split('&').forEach(function(v) {
            var a = v.split('=');
            q[a[0]] = a.slice(1).join('=').replace(/~and~/g, '&');
          });
          if (q.p !== undefined) {
            window.history.replaceState(null, null,
              l.pathname.slice(0, -1) + (q.p || '') +
              (q.q ? ('?' + q.q) : '') +
              l.hash
            );
          }
        }
      }(window.location))
    </script>
    <!-- End Single Page Apps for GitHub Pages -->
  </body>
</html>


================================================
FILE: frontend/public/manifest.json
================================================
{
  "short_name": "Repo Analytics",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "type": "image/x-icon"
    },
    {
      "src": "logo.png",
      "type": "image/png"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}


================================================
FILE: frontend/public/robots.txt
================================================
# https://www.robotstxt.org/robotstxt.html
User-agent: *


================================================
FILE: frontend/src/App.css
================================================
a {
  color: #0366d6;
  text-decoration: none;
}

a:hover {
  text-decoration: none;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  font-size: 15px;
  line-height: 1.5;
  color: hsla(0,0%,100%,.7);
  background-color: #24292e;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-link {
  font-weight: 600;
  color: #fff;
  white-space: nowrap;
  cursor: pointer;
  user-select: none;
}

.header-link:hover {
  color: #bbb;
}


.dropdown {
  position: relative;
  display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: absolute;
  padding-top: 8px;
  right: 0;
  background-color: #ffffff00;
  min-width: 120px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
  border-radius: 5px;
}

/* Links inside the dropdown */
.dropdown-content a {
  color: black;
  background-color: #f9f9f9;
  padding: 5px 16px;
  display: block;
  cursor: pointer;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {
  background-color: #0366d6;
  color: white;
}

.dropdown-content hr {
  margin: 0;
  height: 0;
  overflow: hidden;
  background-color: #f9f9f9;
  border: 0;
  border-bottom: 1px solid #dfe2e5;
}

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content {
  display: block;
}


================================================
FILE: frontend/src/App.js
================================================
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import './App.css';
import Home from './pages/Home';
import User from './pages/User';
import Repo from './pages/Repo';
import queryString from 'query-string';
import userSignedIn from './utils/userSignedIn';

export default function App() {
  let user = userSignedIn.get();

  if (window.location.search.length > 0) {
    try {
      const userFromSearch = queryString.parse(window.location.search);
      userSignedIn.set({
        username: userFromSearch.username,
        token: userFromSearch.token,
        photo: userFromSearch.photo
      });
      user = userSignedIn.get();
      window.history.replaceState({}, document.title, window.location.origin + window.location.pathname);
    } catch (err) {
      console.log('bad query string');
    }
  }

  function signout () {
    userSignedIn.remove();
    window.location.reload();
  }

  return (
    <Router>
      <header>
        <div className="header-left">
          <img src="/logo.png" alt="logo" width="30px"/>
          &nbsp;
          <Link to="/" className="header-link">Repo Analytics</Link>
        </div>
        <div>
          {
            user.username ? 
            <div className="dropdown">
              <a className="header-link" href>{user.username} <span style={{fontSize:'10px'}}>▼</span></a>
              <div className="dropdown-content">
                <a href={`/${user.username}`}>Your profile</a>
                <a href={`/${user.username}`}>Add repo</a>
                <a href="https://github.com/repo-analytics/repo-analytics.github.io/issues/1">Pricing</a>
                <hr/>
                <a href onClick={signout} >Sign out</a>
              </div>
            </div>
            :
            <a className="header-link" href="https://repo-analytics.t9t.io/auth/github">Sign in with GitHub</a>
          }
          
          {/* <Link to="/topics">Topics</Link> */}
        </div>
      </header>
      <Route exact path="/" >
        <Home user={user}/>
      </Route>
      <Route path="/topics" component={Topics} />
      <Route path="/about" component={About} />

      <Route exact path="/:username" component={User} />
      <Route path="/:username/:repo" component={Repo} />
    </Router>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}

function Topics({ match }) {
  return (
    <div>
      <h2>Topics</h2>
      <ul>
        <li>
          <Link to={`${match.url}/rendering`}>Rendering with React</Link>
        </li>
        <li>
          <Link to={`${match.url}/components`}>Components</Link>
        </li>
        <li>
          <Link to={`${match.url}/props-v-state`}>Props v. State</Link>
        </li>
      </ul>

      <Route path={`${match.path}/:topicId`} component={Topic} />
      <Route
        exact
        path={match.path}
        render={() => <h3>Please select a topic.</h3>}
      />
    </div>
  );
}

function Topic({ match }) {
  return (
    <div>
      <h3>{match.params.topicId}</h3>
    </div>
  );
}

================================================
FILE: frontend/src/App.test.js
================================================
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});


================================================
FILE: frontend/src/components/AddRepo.css
================================================
.add-new {
  width: 100%;
  height: 100%;
  display:flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  position: relative;
}

.add-new a {
  font-size: 20px;
  font-weight: 500;
}

.repo-input {
  width: 270px;
  background-color: #fafbfc;
  padding: 10px 10px;
  font-size: 16px;
  color: #24292e;
  border: 1px solid #d1d5da;
  border-radius: 3px;
  outline: none;
  box-shadow: inset 0 1px 2px rgba(27,31,35,.075);
}

::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
  color: #aaa;
}

.add-repo-btn {
  border-radius: 3px;
  background-color: #2ebc4f;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  font-weight: 550;
  cursor: pointer;
  color: white;
  margin: 10px;
}

button:focus {
  outline:none;
}


.add-repo-btn.isLoading {
  background-color: #888;
  pointer-events: none;
}

.add-repo-btn.isLoading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  25% { transform: rotate(10deg); }
  50% { transform: rotate(0deg); }
  75% { transform: rotate(-10deg); }
  100% { transform: rotate(0deg); }
}

.add-new-footer {
  position: absolute;
  bottom: 8px;
  right: 8px;

}

.add-new-footer a {
  font-size: 14px;
  font-weight: 500;
}

================================================
FILE: frontend/src/components/AddRepo.js
================================================
import React, { useState } from "react";
import http from "../utils/http";
import userSignedIn from '../utils/userSignedIn';
import './AddRepo.css';
import { alert } from 'notie';


const AddRepo = () => {
  const localUser = userSignedIn.get();
  const [repoPath, setRepoPath] = useState();
  const [isLoading, setIsLoading] = useState(false);

  async function addRepo () {
    try {
      setIsLoading(true);
      await http.addRepo({ username: localUser.username, repoPath, token: localUser.token });
      window.location = `/${repoPath}`;
    } catch (err) {
      setIsLoading(false);
      alert({
        type: 'error', // optional, default = 4, enum: [1, 2, 3, 4, 5, 'success', 'warning', 'error', 'info', 'neutral']
        text: `Failed: "${err.response.data}"`,
        stay: false, // optional, default = false
        time: 3, // optional, default = 3, minimum = 1,
        position: 'top' // optional, default = 'top', enum: ['top', 'bottom']
      })
    }
  }

  return <div className="home-box">
    <div className="add-new">

      <input placeholder={`e.g. ${localUser.username}/repo-name`} className="repo-input" onChange={(e) => setRepoPath(e.target.value)}></input>
      <button className={`${isLoading ? 'isLoading' : ''} add-repo-btn`} onClick={() => addRepo()}>
        {isLoading ? 'Adding' : 'Add repo'}
      </button>
      <div className="add-new-footer">
        <a href="https://github.com/repo-analytics/repo-analytics.github.io/issues/1">Pricing</a>
      </div>
    </div>

  </div>;
}

export default AddRepo;

================================================
FILE: frontend/src/components/CardLoader.js
================================================
import React from "react"
import ContentLoader from "react-content-loader"

const MyLoader = () => (
  <ContentLoader 
    height={220}
    width={900}
    speed={2}
    primaryColor="#f3f3f3"
    secondaryColor="#d6d6d6"
  >
    <rect x="9" y="19" rx="0" ry="0" width="432" height="179" /> 
    <rect x="460" y="19" rx="0" ry="0" width="426" height="179" /> 
    <rect x="494" y="24" rx="0" ry="0" width="0" height="13" /> 
    <rect x="394" y="85" rx="0" ry="0" width="0" height="0" />
  </ContentLoader>
)

export default MyLoader;

================================================
FILE: frontend/src/components/CloneChart.js
================================================
import React, { useEffect } from 'react';
import chartXkcd from 'chart.xkcd';

const VisitChart = ({ clones }) => {

  const totalViewsData = clones.map(clone => ({
    x: clone.timestamp,
    y: clone.count,
  }));
  const uniqueViewsData = clones.map(clone => ({
    x: clone.timestamp,
    y: clone.uniques,
  }));
  useEffect(() => {
    const svg = document.querySelector('.clone-chart');
    new chartXkcd.XY(svg, {
      // title: 'Git clones',
      data: {
        datasets: [{
          label: 'Clones',
          data: totalViewsData,
        }, {
          label: 'Unique Clones',
          data: uniqueViewsData,
        }],
      },
      options: {
        xTickCount: 3,
        yTickCount: 4,
        legendPosition: chartXkcd.config.positionType.upLeft,
        showLine: true,
        timeFormat: 'MM/DD/YYYY',
        dotSize: 0.5,
        dataColors: ['#28a745', '#005cc5'],
        // unxkcdify: true // TODO: configuable
      },
    });
  }, []);

  return <div className="chart-container">
    <h3 className="chart-container-header"> Git clones </h3>
    <div className="svg-container">
      <svg className="clone-chart"></svg>
    </div>
  </div>
}

export default VisitChart;


================================================
FILE: frontend/src/components/Footer.css
================================================
footer {
  margin: 80px 0;
  border-top: 1px solid #dfe2e5;
  padding: 20px 8px;


  display: flex;
  justify-content: space-between;
}

.footer-content {
  font-size: 16px;
  color: #586069;
}

.footer-content a:hover {
  text-decoration: underline;
}


.footer-contacts a {
  font-size: 16px;
  color: #586069;
  padding-left: 4px;
}

.footer-contacts a:hover {
  color: #888;
}

================================================
FILE: frontend/src/components/Footer.js
================================================
import React from 'react';
import './Footer.css'

const Footer = () => (
  <footer>
    <div className="footer-content">
      A <a href="https://t9t.io">t9t</a> project build by <a href="https://timqian.com">timqian</a>
    </div>
    <div className="footer-contacts">
      <a href="https://github.com/timqian"><i className="ri-github-line"></i></a>
      <a href="https://twitter.com/tim_qian"><i className="ri-twitter-line"></i></a>
      <a href="https://raw.githubusercontent.com/timqian/images/master/3811553342733_.pic.jpg"><i className="ri-wechat-2-line"></i></a>
      <a href="mailto:timqian@t9t.io"><i className="ri-mail-line"></i></a>
    </div>
  </footer>
)

export default Footer;


================================================
FILE: frontend/src/components/PathChart.js
================================================
import React from 'react';

const Paths = ({paths}) => (
  <div className="chart-container">
    <h3 className="chart-container-header"> Popular content </h3>
    <table>
      <thead>
        <tr>
          <th>Content</th>
          <th>Views</th>
          <th>Unique visitors</th>
        </tr>
      </thead>
      <tbody>
        {paths.map(path => <tr>
          <td><a href={`https://github.com/${path.path}`}>{path.path}</a></td>
          <td>{path.count}</td>
          <td>{path.uniques}</td>
        </tr>)}
      </tbody>
    </table> 
  </div>
);

export default Paths;


================================================
FILE: frontend/src/components/ProjectCard.css
================================================
.card-container {
  margin: 15px;
  font-size: 16px;
  height: 100%;
  position: relative;
}

.path-divider {
  font-size: 16px;
  /* line-height: 26px; */
  color: #586069;
  margin: 0 3px;
}

.project-trend {
  /* TODO: for chart.xkcd: config padding; margin*/
  height: 100%;
  position: relative;
  top: -26px;
  z-index: 0;
}

.card-description a {
  font-weight: 500;
  font-size: 16px;
  position: relative;
  z-index: 1;
}

.card-description a:hover {
  text-decoration: underline;
}

.card-footer {
  position: absolute;
  bottom: 18px;
  right: 0;
  font-size: 11px;
  color: #888;
}

================================================
FILE: frontend/src/components/ProjectCard.js
================================================
import React, { useRef, useEffect } from 'react';
import chartXkcd from 'chart.xkcd';
import './ProjectCard.css';


const ProjectCard = ({repo, createdAt, username, views}) => {

  const ref = useRef();
  const totalViewsData = views.map(view => ({
    x: view.timestamp,
    y: view.count,
  }));
  const uniqueViewsData = views.map(view => ({
    x: view.timestamp,
    y: view.uniques,
  }));
  
  useEffect(() => {
    if (ref.current) {
      new chartXkcd.XY(ref.current, {
        // title: 'Visitors',
        data: {
          datasets: [{
            label: 'Views',
            data: totalViewsData,
          }, {
            label: 'Unique Visitors',
            data: uniqueViewsData,
          }],
        },
        options: {
          xTickCount: 3,
          yTickCount: 4,
          legendPosition: chartXkcd.config.positionType.upLeft,
          showLine: true,
          timeFormat: 'MM/DD/YYYY',
          dotSize: 0.5,
          dataColors: ['#28a745', '#005cc5'],
          // unxkcdify: true
        },
      });
    }
  }, []);

  return   <div className="card-container">
  <div className="card-description">
    <a href={`/${repo}`}>{repo}</a>
  </div>

  <div className="project-trend">
    <svg ref={ref}></svg>
  </div>

  <div className="card-footer">
    Recording analytics since {createdAt.slice(0, 10)}
  </div>
</div>
};

export default ProjectCard;


================================================
FILE: frontend/src/components/ReferrerChart.js
================================================
import React from 'react';

const Referrer = ({referrers}) => {

  console.log('referrers', referrers)
  return (
    <div className="chart-container">
      <h3 className="chart-container-header"> Referring sites </h3>
      <table>
        <thead>
          <tr>
            <th>Site</th>
            <th>Views</th>
            <th>Unique visitors</th>
          </tr>
        </thead>
        <tbody>
          {referrers.map(referrer => <tr>
            <td>{referrer.referrer}</td>
            <td>{referrer.count}</td>
            <td>{referrer.uniques}</td>
          </tr>)}
        </tbody>
      </table>
    </div>
)};

export default Referrer;

================================================
FILE: frontend/src/components/RepoLoader.js
================================================
import React from 'react'
import ContentLoader from 'react-content-loader'

const Article = () => (
  <ContentLoader
    height={160}
    width={400}
    speed={1}
    primaryColor="#f3f3f3"
    secondaryColor="#ecebeb"
  >
    <rect x="0" y="13" rx="4" ry="4" width="400" height="9" />
    <rect x="0" y="29" rx="4" ry="4" width="100" height="8" />
    <rect x="0" y="50" rx="4" ry="4" width="400" height="10" />
    <rect x="0" y="65" rx="4" ry="4" width="400" height="10" />
    <rect x="0" y="79" rx="4" ry="4" width="100" height="10" />
    <rect x="0" y="99" rx="5" ry="5" width="400" height="200" />
  </ContentLoader>
)

export default Article;

================================================
FILE: frontend/src/components/RepoNav.js
================================================
import React from "react";
const Nav = ({repoPath, selectedTab}) => {
  return (
    <div className="repo-header">
      <div className="repo-container">
        <h1 className="repo-title">
          <a className="user-link" href={`/${repoPath}`}>
            {repoPath}
          </a>
          <a className="user-github-link" href={`https://github.com/${repoPath}`}>
            <i className="ri-github-line"></i>
          </a>   
        </h1>
        <nav className="repo-nav">
          <a href className={selectedTab === 0 ? 'selected' : ''} href={`/${repoPath}/traffic`}>Traffic</a>
          <a href className={selectedTab === 1 ? 'selected' : ''} href={`/${repoPath}/stars`}>Stars</a>
          {/* <a href className={selectedTab === 2 ? 'selected' : ''} href={`/${repoPath}/settings`}>Settings</a> */}
        </nav>
      </div>
    </div>
  );
};

export default Nav;

================================================
FILE: frontend/src/components/RepoSetting.css
================================================
.traffic-switch {
  margin: 40px;
  margin-top: 40px;
  font-size: 20px;
  font-weight: 300;
  line-height: 25px;
}


/* The switch - the box around the slider */
.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 24px;
}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The slider */
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #28a745;
}

input:focus + .slider {
  box-shadow: 0 0 1px #28a745;
}

input:checked + .slider:before {
  -webkit-transform: translateX(16px);
  -ms-transform: translateX(16px);
  transform: translateX(16px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 24px;
}

.slider.round:before {
  border-radius: 50%;
}

================================================
FILE: frontend/src/components/RepoSetting.js
================================================
import React from 'react';
import './RepoSetting.css';

const Setting = () => (
  <div className="repo-container">
    <div className="traffic-switch">
      <label className="switch">
        <input type="checkbox"/>
        <span className="slider round"></span>
      </label>
      &nbsp; Make traffic data private
    </div>
  </div>
)

export default Setting;


================================================
FILE: frontend/src/components/StarAnalytics.js
================================================
import React, { useEffect, useState } from "react";
import RepoLoader from "./RepoLoader";
import http from '../utils/http';
import StarHistoryChart from "./StarHistoryChart";
import StarLocationChart from "./StarLocationChart";

const Traffic = ({ repoPath }) => {
  const [starData, setstarData] = useState();
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    http.getRepoStars({
      repoPath,
    })
      .then(traffic => {
        setstarData(traffic);
        setIsLoading(false);
      })
      .catch(err => console.log(err));
  }, []);

  if (isLoading || !starData) {
    return <div className="repo-container">
      <h2>Here we analyse history and location statics of your repo. </h2>
      <p>You might need to wait for a minute or two and refresh the page if your repo have too many stars and it is the first time you open this page</p>
      <RepoLoader/>
    </div>
  }

  return (<div className="repo-container">
    <div className="dates-container">
      <p>Updated at {starData.updatedAt.slice(0,10)}</p>
    </div> 

    <div className="repo-ref-paths-container">
      <div className="one-ref-path">
        {
          Object.keys(starData.history).length !== 0 
            ? <StarHistoryChart repo={starData.repo} history={starData.history}/>
            : ''
        }
      </div>
      <div className="one-ref-path">
      {
          Object.keys(starData.locations).length !== 0 
            ? <StarLocationChart locations={starData.locations}/>
            : ''
        }

      </div>
    </div>


  </div>);
}

export default Traffic;


================================================
FILE: frontend/src/components/StarHistoryChart.js
================================================
import React, { useState, useEffect } from 'react';
import chartXkcd from 'chart.xkcd';
import './VisitChart.css';

const StarHistoryChart = ({ repo, history, notAddingUp}) => {

  const [isAdding, setIsAdding] = useState(true)
  const dates = Object.keys(history);
  let counts = Object.values(history);
  if(isAdding) {
    for(let i = 1; i < counts.length; i++) {
      counts[i] = counts[i-1]+ counts[i]
    }
  }
  const data = dates.map((date, i) => ({
    x: date,
    y: counts[i],
  }));

  useEffect(() => {
    const svg = document.querySelector('.star-history-chart');
    new chartXkcd.XY(svg, {
      data: {
        datasets: [{
          label: repo,
          data,
        }],
      },
      options: {
        xTickCount: 3,
        yTickCount: 4,
        legendPosition: chartXkcd.config.positionType.upLeft,
        showLine: true,
        timeFormat: 'YYYY-MM-DD',
        dotSize: 0.3,
        dataColors: ['#28a745'],
        // unxkcdify: true
      },
    });
  });

  return <div className="chart-container">
  <h3 className="chart-container-header"> 
    Star History   
    <button onClick={() => setIsAdding(!isAdding)} style={{float:'right', backgroundColor:'white', borderRadius:'3px',border:'1px solid #ccc', color:'#555', cursor: 'pointer'}}> {isAdding ? 'Growth' : 'Total'} </button>
  </h3>

  <div className="svg-container">
    <svg className="star-history-chart"></svg>
  </div>
</div>
}

export default StarHistoryChart;


================================================
FILE: frontend/src/components/StarLocationChart.js
================================================
import React, { useEffect } from 'react';
import chartXkcd from 'chart.xkcd';
import './VisitChart.css';

const StarLocationChart = ({ locations }) => {

  const locationsKeys = Object.keys(locations);
  const counts = Object.values(locations);
  const totalCount = counts.reduce((pre, cur) => pre + cur);
  const topLocations = locationsKeys.sort((a, b)=> locations[b] - locations[a]).slice(0, 6);
  const topCounts = counts.sort((a, b) => b - a).slice(0, 6);
  const othersCount = totalCount - topCounts.reduce((pre, cur) => pre + cur);

  useEffect(() => {
    const svg = document.querySelector('.star-location-chart');
    new chartXkcd.Pie(svg, {
      data: {
        labels: [...topLocations, 'others'],
        datasets: [{
          data: [...topCounts, othersCount],
        }],
      },
      options: {
        innerRadius: 0.5,
        // unxkcdify: true
      },
    });
  }, []);

  return <div className="chart-container">
  <h3 className="chart-container-header"> 
    Star Locations
  </h3>

  <p className="location-description">{totalCount} valid locations detected</p>
  <div className="svg-container">
    <svg className="star-location-chart"></svg>
  </div>
</div>
}

export default StarLocationChart;


================================================
FILE: frontend/src/components/TrafficAnalytics.js
================================================
import React, { useEffect, useState } from "react";
import VisitChart from './VisitChart';
import CloneChart from './CloneChart';
import RepoLoader from "./RepoLoader";
import ReferrerChart from "./ReferrerChart";
import PathChart from "./PathChart";
import http from '../utils/http';

const Traffic = ({ repoPath }) => {
  const [trafficData, setTrafficData] = useState();
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    http.getRepoTraffic({
      repoPath,
    })
      .then(traffic => {
        setTrafficData(traffic);
        setIsLoading(false);
      })
      .catch(err => console.log(err));
  }, []);

  if (isLoading || !trafficData) {
    return <div className="repo-container">
      <RepoLoader/>
    </div>
  }

  return (<div className="repo-container">
    <div className="dates-container">
      <p>Updated at {trafficData.date}</p>
      <p>Recording analytics since {trafficData.repoCreatedAt.slice(0, 10)}</p>
    </div> 

    <div className="repo-ref-paths-container">
      <div className="one-ref-path">
        <VisitChart views={trafficData.views}/> 
      </div>
      <div className="one-ref-path">
        <CloneChart clones={trafficData.clones}/>
      </div>
    </div>


    <div className="repo-ref-paths-container">
      <div className="one-ref-path">
        <ReferrerChart referrers={trafficData.referrers}/>
      </div>
      <div className="one-ref-path">
        <PathChart paths={trafficData.paths}/>
      </div>
    </div>
  </div>);
}

export default Traffic;


================================================
FILE: frontend/src/components/VisitChart.css
================================================
.chart-container {
  border: 1px solid #d1d5da;
  border-radius: 5px;
  margin-bottom: 30px;
  position: relative;
}

.svg-container {
  height: 270px;
  width: 100%;
}


.chart-container-header {
  display: block;
  padding: 13px 10px 14px;
  margin: 0;
  font-size: 16px;
  line-height: 17px;
  background-color: #f6f8fa;
  border-bottom: 1px solid rgba(27,31,35,.15);
  border-radius: 3px 3px 0 0;
}

.location-description {
  position: absolute;
  right: 3px;
  font-size: 12px;
  color: #888;
}


================================================
FILE: frontend/src/components/VisitChart.js
================================================
import React, { useEffect } from 'react';
import chartXkcd from 'chart.xkcd';
import './VisitChart.css';

const VisitChart = ({ views }) => {
  const totalViewsData = views.map(view => ({
    x: view.timestamp,
    y: view.count,
  }));
  const uniqueViewsData = views.map(view => ({
    x: view.timestamp,
    y: view.uniques,
  }));
  useEffect(() => {
    const svg = document.querySelector('.visit-chart');
    new chartXkcd.XY(svg, {
      // title: 'Visitors',
      data: {
        datasets: [{
          label: 'Views',
          data: totalViewsData,
        }, {
          label: 'Unique Visitors',
          data: uniqueViewsData,
        }],
      },
      options: {
        xTickCount: 3,
        yTickCount: 4,
        legendPosition: chartXkcd.config.positionType.upLeft,
        showLine: true,
        timeFormat: 'MM/DD/YYYY',
        dotSize: 0.5,
        dataColors: ['#28a745', '#005cc5'],
        // unxkcdify: true
      },
    });
  }, []);

  return <div className="chart-container">
  <h3 className="chart-container-header"> Visitors </h3>
  <div className="svg-container">
    <svg className="visit-chart"></svg>
  </div>
</div>
}

export default VisitChart;


================================================
FILE: frontend/src/index.css
================================================
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}


================================================
FILE: frontend/src/index.js
================================================
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'remixicon/fonts/remixicon.css'

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();


================================================
FILE: frontend/src/pages/Home.css
================================================
.home-container {
  margin: 0 auto;
  max-width: 900px;
}

.home-hero {
  text-align: center;
  padding: 30px 10px 130px 10px;;
  background: url(https://raw.githubusercontent.com/timqian/images/master/20191013133125.gif),white;
  background-position: left -55px bottom -35px;
  background-size: 200px;
  background-repeat: no-repeat;
  border-bottom: 1px solid #dfe2e5;
  position: relative;
}

.home-github-btn {
  position: absolute;
  left: 75px;
  bottom: 45px;
}

.home-slogan {
  font-size: 40px;
  font-weight: 300;
  padding: 40px 0!important;
  margin: 0;
}

.home-features {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  margin: 30px auto;
}

.home-feature {
  width: 300px;
  /* box-shadow: 0 1px 1px rgba(27,31,35,.1); */
  margin: 0 20px;
}

.home-feature-title {
  font-weight: 500;
  font-size: 24px;
  margin: 0;
}

.home-feature-description {
  font-weight: 480;
  font-size: 15px;
  color: #586069;
  line-height: 1.5;
}

.home-feature-description a:hover {
  text-decoration: underline;
}

.home-signin-btn {
  /* background-color: #24292e; */
  border-radius: 3px;
  background-color: #2ebc4f;
  border: none;
  padding: 20px 40px;
  font-size: 16px;
  font-weight: 550;
  cursor: pointer;
  color: white;
}

.home-signin-btn:hover {
  background-color: #2ba046;
}

.home-hr {
  height: 0;
  margin: 15px 0;
  overflow: hidden;
  background: transparent;
  border: 0;
  border-bottom: 1px solid #dfe2e5;
}

.home-example-title {
  font-size: 23px;
  font-weight: 400;
  color: #586069;
  margin: 50px 0 30px 0;
  text-align: center;
}

.home-examples {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap; 
}

.home-box {
  width: 300px;
  max-width: 430px;
  height: 180px;
  margin: 8px;
  flex-grow: 100;
  flex-shrink: 0;
  flex-basis: 1;
  background-color: #fff;
  border: 1px solid #d1d5da;
  border-radius: 3px;
}



================================================
FILE: frontend/src/pages/Home.js
================================================
import React, { useEffect, useState } from "react";
import http from '../utils/http';
import ProjectCard from '../components/ProjectCard';
import './Home.css';
import Footer from '../components/Footer';
import GitHubButton from 'react-github-btn'
import CardLoader from '../components/CardLoader';

function Home ({user}) {

  const [repos, setRepos] = useState([]);

  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    http.getUserRepos('timqian')
      .then(repos => {
        setRepos(repos);
        setIsLoading(false);
      });
  }, []);

  return (
    <div className="home-main">
      <div className="home-hero">
        <div className="home-github-btn">
          <GitHubButton href="https://github.com/repo-analytics/repo-analytics.github.io" data-show-count="true" aria-label="Star repo-analytics/repo-analytics.github.io on GitHub">Star</GitHubButton>
        </div>
        <h1 className="home-slogan">
          Thorough analytics for your GitHub repos
        </h1>
        <div className="home-features">
          <div className="home-feature">
            <h4 className="home-feature-title">Better traffic data</h4>
            <p className="home-feature-description">
              Track traffic to GitHub Repos for longer than 14 days.
            </p>
          </div>
          <div className="home-feature">
            <h4 className="home-feature-title">Understand your users</h4>
            <p className="home-feature-description">
              Analyze history, locations of Star, Watch... data of your GitHub Repos
            </p>
          </div>
          <div className="home-feature">
            <h4 className="home-feature-title">What do you care?</h4>
            <p className="home-feature-description">
              Suggest new features for Repo Analytics on 
              &nbsp;
              <a href="https://github.com/repo-analytics/repo-analytics.github.io/issues">GitHub</a>
            </p>
          </div>
        </div>
        <br/>
        <br/>
        {
          !user.username ?
          <a className="home-signin-btn" href="https://repo-analytics.t9t.io/auth/github">Sign in with GitHub</a>
          : ''
        }
      </div>

      <div className="home-container">
        <h2 className="home-example-title">Example repos using <strong>Repo Analytics</strong></h2>
        { isLoading ? <CardLoader/> : ''}

        <div className="home-examples">
          {
            repos.map(repo => <div className="home-box">
              <ProjectCard repo={repo.repo} username={repo.username} createdAt={repo.createdAt} views={repo.views}/>
            </div>)
          }

        </div>

        <Footer />
      </div>
    </div>
  );
}

export default Home;

================================================
FILE: frontend/src/pages/Repo.css
================================================
.repo-container {
  margin: 0 auto;
  max-width: 900px;
  padding: 0 8px;
}

.repo-header {
  width: 100vw;
  background-color: #fafbfc;
  border-bottom: 1px solid #e1e4e8;
  position: relative;
}

.repo-title {
  padding-top: 10px;
  padding-bottom: 50px;
  font-size: 22px;
}

.repo-title a:hover {
  text-decoration: underline;
}

.repo-nav {
  position: absolute;
  bottom: -1px;
}

.repo-nav a {
  color: #24292e;
  float: left;
  padding: 7px 15px 8px;
  color: #586069;
  white-space: nowrap;
  border-radius: 3px 3px 0 0;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-top: 3px solid transparent;
  border-bottom: 1px solid transparent;
  cursor: pointer;
}

.repo-nav .selected {
  background-color: #fff;
  border-left: 1px solid rgb(225, 228, 232);
  border-right: 1px solid rgb(225, 228, 232);
  border-top: 3px solid #e36209;
  border-bottom: 1px solid white;
}

.dates-container {
  display: flex;
  justify-content: flex-end;
  flex-direction: column;
  align-items: flex-end;
  padding: 15px 0;
  font-weight: 400;
  font-size: 12px;
  color: #888
}

.dates-container p {
  margin: 0;
  padding: 2px 0;
}

.repo-ref-paths-container {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.one-ref-path {
  width: 300px;
  max-width: 430px;
  flex-grow: 100;
  flex-shrink: 0;
  flex-basis: 1;
  background-color: #fff;
  margin-bottom: 10px;
}

table {
  width: 100%;
  color: rgb(88, 96, 105);
  border-collapse: collapse;
  font-size: 14px;
}

thead {
  background-color: rgb(246, 248, 250);
}

tr:nth-child(even){background-color: rgba(246, 248, 250, 0.4);}

td, th {
  padding: 8px;
  text-align: left;
}

td {
  word-break: break-word;
}

tr {
  border-bottom: 1px solid #ddd;
}

td a:hover {
  text-decoration: underline;
}

================================================
FILE: frontend/src/pages/Repo.js
================================================
import TrafficAnalytics from '../components/TrafficAnalytics'; 
import StarAnalytics from '../components/StarAnalytics'; 
import RepoSetting from '../components/RepoSetting'; 
import RepoNav from '../components/RepoNav'; 

import './Repo.css';
import React from "react";
import Footer from '../components/Footer';

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useRouteMatch,
  useParams,
  useLocation,
} from "react-router-dom";

function Repo () {
  const match = useRouteMatch();
  const location = useLocation();
  const username = match.params.username;
  const repo = match.params.repo;
  const repoPath = `${username}/${repo}`

  return (
    <div >
      <Switch>
        <Route path={`${match.path}/traffic`}>
          <RepoNav repoPath={repoPath} selectedTab={0} />
          <TrafficAnalytics repoPath={repoPath}/>
        </Route>
        <Route path={`${match.path}/stars`}>
          <RepoNav repoPath={repoPath} selectedTab={1} />
          <StarAnalytics repoPath={repoPath}/>
        </Route>
        <Route path={`${match.path}/settings`}>
          <RepoNav repoPath={repoPath} selectedTab={2} />
          <RepoSetting />
        </Route>
        <Route path={`${match.path}`}>
          <RepoNav repoPath={repoPath} selectedTab={0} />
          <TrafficAnalytics repoPath={repoPath}/>
        </Route>
      </Switch>

      <div className="repo-container">
        <Footer />
      </div>
    </div>
  );
}

export default Repo;

================================================
FILE: frontend/src/pages/User.css
================================================
.user-title {
  margin-left: 8px;
  margin-top: 30px;
  margin-bottom: 30px;
  font-size: 25px;
}

.user-link {
  font-weight: 500;
}

.user-github-link {
  font-size: 20px;
  font-weight: 500;
  margin: 3px;
}


================================================
FILE: frontend/src/pages/User.js
================================================
import React, { useEffect, useState } from "react";
import http from '../utils/http';
import ProjectCard from '../components/ProjectCard';
import './User.css';
import userSignedIn from '../utils/userSignedIn';
import CardLoader from '../components/CardLoader';
import AddRepo from '../components/AddRepo';
import Footer from '../components/Footer';

function User ({ match }) {
  const username = match.params.username;
  const userLocal = userSignedIn.get();
  const [repos, setRepos] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    http.getUserRepos(username)
      .then(repos => {
        setRepos(repos);
        setIsLoading(false);
      });
  }, []);

  return (
    <div className="home-container">
      <h1 className="user-title">
        Repos of&nbsp;
        <a className="user-github-link" href={`https://github.com/${username}`}>
          {username}
        </a>
        <a className="user-github-link" href={`https://github.com/${username}`}>
          <i className="ri-github-line"></i>
        </a>
      </h1>
      { isLoading ? <CardLoader/> : ''}
      <div className="home-examples">
        {
          repos.map(repo => <div className="home-box">
            <ProjectCard repo={repo.repo} username={repo.username} createdAt={repo.createdAt} views={repo.views}/>
          </div>)
        }

        {
          userLocal.username === username ?
            <AddRepo /> : ''
        }
      </div>

      <Footer />
    </div>
  );
}

export default User;

================================================
FILE: frontend/src/serviceWorker.js
================================================
// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.

// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export function register(config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebook/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit https://bit.ly/CRA-PWA'
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  }
}

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the updated precached content has been fetched,
              // but the previous service worker will still serve the older
              // content until all client tabs are closed.
              console.log(
                'New content is available and will be used when all ' +
                  'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
              );

              // Execute callback
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');

              // Execute callback
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl, config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl)
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      const contentType = response.headers.get('content-type');
      if (
        response.status === 404 ||
        (contentType != null && contentType.indexOf('javascript') === -1)
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}


================================================
FILE: frontend/src/utils/http.js
================================================
import axios from 'axios';

const userRaw = window.localStorage.getItem('user');

let token;
if (userRaw) {
  const user = JSON.parse(userRaw);
  token = user.token;
}

const http = axios.create({
  baseURL: 'https://repo-analytics.t9t.io/',
  // baseURL: 'http://localhost:8080/',
  timeout: 20000,
  headers: {
    token,
  },
});
 
const getUserRepos = async (username) => {
  const res = await http.get(`/user/${username}`);
  return res.data.repos;
}

/**
 * 
 * @param {String} repoPath 
 * @param {String} startDate 
 * @param {String} endDate 
 */
const getRepoTraffic = async ({repoPath}) => {
  const res = await http.get(`/repo/${repoPath}`);
  return res.data.traffic;
}

const getRepoStars = async ({repoPath}) => {
  const res = await http.get(`/repo/${repoPath}/stars`);
  return res.data;
}

const addRepo = async ({username, repoPath, token}) => {
  const res = await http.post('/repo/add', {
    username, repoPath, token,
  });
  return res.data;
}

export default {
  getUserRepos,
  getRepoTraffic,
  getRepoStars,
  addRepo,
};


// test
// getRepoStars({repoPath: 'timqian/star-history'})

================================================
FILE: frontend/src/utils/trafficDateRangeToArray.js
================================================
/**
 * @param startDate
 * @param endDate
 * @returns array of required traffic dates
 * @example
 *   const dateArr = trafficDateRangeToArray('2019-10-01', '2019-10-20')
 */

================================================
FILE: frontend/src/utils/userSignedIn.js
================================================
/**
 * user: {
 *   username: 'timqian',
 *   token: '',
 *   photo: '',
 * }
 */

function set({ username, token, photo }) {
  window.localStorage.setItem('user', JSON.stringify({
    username, token, photo
  }))
}

function get() {
  let user = {};
  const userRaw = window.localStorage.getItem('user');
  if (userRaw) {
    try {
      user = JSON.parse(userRaw);
    } catch (err) {}
  }
  return user;
}

function remove() {
  window.localStorage.removeItem('user');
}

module.exports = {
  set,
  get,
  remove,
};
Download .txt
gitextract_quu5d0bq/

├── .github/
│   └── workflows/
│       └── dailyFetchTraffic.yml
├── .gitignore
├── LICENSE
├── README.md
├── backend/
│   ├── README.md
│   ├── db/
│   │   ├── Repo.js
│   │   ├── Star.js
│   │   ├── Traffic.js
│   │   ├── User.js
│   │   └── dynamodb.js
│   ├── package.json
│   ├── scripts/
│   │   ├── README.md
│   │   ├── countries.json
│   │   ├── dailyGetStars.js
│   │   ├── dailyGetTraffics.js
│   │   ├── getStarsAndSaveDbForRepoWithoutRepos.js
│   │   └── guessCountryFromAddress.js
│   ├── server.js
│   ├── up.json
│   └── utils/
│       ├── getStars.js
│       ├── getTrafficOfRepoAndSave.js
│       ├── getUniqueListBy.js
│       └── trafficDateRangeToDateArr.js
└── frontend/
    ├── .gitignore
    ├── README.md
    ├── package.json
    ├── public/
    │   ├── 404.html
    │   ├── index.html
    │   ├── manifest.json
    │   └── robots.txt
    └── src/
        ├── App.css
        ├── App.js
        ├── App.test.js
        ├── components/
        │   ├── AddRepo.css
        │   ├── AddRepo.js
        │   ├── CardLoader.js
        │   ├── CloneChart.js
        │   ├── Footer.css
        │   ├── Footer.js
        │   ├── PathChart.js
        │   ├── ProjectCard.css
        │   ├── ProjectCard.js
        │   ├── ReferrerChart.js
        │   ├── RepoLoader.js
        │   ├── RepoNav.js
        │   ├── RepoSetting.css
        │   ├── RepoSetting.js
        │   ├── StarAnalytics.js
        │   ├── StarHistoryChart.js
        │   ├── StarLocationChart.js
        │   ├── TrafficAnalytics.js
        │   ├── VisitChart.css
        │   └── VisitChart.js
        ├── index.css
        ├── index.js
        ├── pages/
        │   ├── Home.css
        │   ├── Home.js
        │   ├── Repo.css
        │   ├── Repo.js
        │   ├── User.css
        │   └── User.js
        ├── serviceWorker.js
        └── utils/
            ├── http.js
            ├── trafficDateRangeToArray.js
            └── userSignedIn.js
Download .txt
SYMBOL INDEX (38 symbols across 15 files)

FILE: backend/db/Repo.js
  function createTable (line 11) | async function createTable() {
  function deleteTable (line 32) | async function deleteTable() {
  function getAllForUser (line 36) | async function getAllForUser({ username }) {
  function put (line 47) | async function put({
  function scan (line 60) | async function scan() {

FILE: backend/db/Star.js
  function createTable (line 17) | async function createTable() {
  function deleteTable (line 36) | async function deleteTable() {
  function get (line 40) | async function get({ repo }) {
  function put (line 50) | async function put({

FILE: backend/db/Traffic.js
  function createTable (line 15) | async function createTable() {
  function deleteTable (line 36) | async function deleteTable() {
  function batchGetViewAndClones (line 40) | async function batchGetViewAndClones({ repo, dateArr }) {
  function getLatest (line 62) | async function getLatest({ repo }) {
  function put (line 75) | async function put({

FILE: backend/db/User.js
  function createTable (line 14) | async function createTable() {
  function deleteTable (line 33) | async function deleteTable() {
  function get (line 37) | async function get({ username }) {
  function put (line 47) | async function put({
  function scan (line 77) | async function scan() {

FILE: backend/db/dynamodb.js
  constant AWS (line 1) | const AWS = require('aws-sdk');

FILE: backend/scripts/dailyGetTraffics.js
  function run (line 15) | async function run() {

FILE: backend/utils/getUniqueListBy.js
  function getUniqueListBy (line 1) | function getUniqueListBy(arr, key) {

FILE: backend/utils/trafficDateRangeToDateArr.js
  function func (line 11) | function func(earliestDate, latestDate) {

FILE: frontend/src/App.js
  function App (line 10) | function App() {
  function About (line 73) | function About() {
  function Topics (line 81) | function Topics({ match }) {
  function Topic (line 107) | function Topic({ match }) {

FILE: frontend/src/components/AddRepo.js
  function addRepo (line 13) | async function addRepo () {

FILE: frontend/src/pages/Home.js
  function Home (line 9) | function Home ({user}) {

FILE: frontend/src/pages/Repo.js
  function Repo (line 20) | function Repo () {

FILE: frontend/src/pages/User.js
  function User (line 10) | function User ({ match }) {

FILE: frontend/src/serviceWorker.js
  function register (line 23) | function register(config) {
  function registerValidSW (line 57) | function registerValidSW(swUrl, config) {
  function checkValidServiceWorker (line 101) | function checkValidServiceWorker(swUrl, config) {
  function unregister (line 129) | function unregister() {

FILE: frontend/src/utils/userSignedIn.js
  function set (line 9) | function set({ username, token, photo }) {
  function get (line 15) | function get() {
  function remove (line 26) | function remove() {
Condensed preview — 65 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (157K chars).
[
  {
    "path": ".github/workflows/dailyFetchTraffic.yml",
    "chars": 573,
    "preview": "name: daily-traffic-data-fetching\n\n\non:\n  schedule:\n  - cron: \"1 0 * * *\"\n\njobs:\n  fetch-traffics:\n    runs-on: ubuntu-l"
  },
  {
    "path": ".gitignore",
    "chars": 927,
    "preview": "secret.json\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lo"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 1015,
    "preview": "[![](https://raw.githubusercontent.com/timqian/images/master/20191017115402.gif)](https://repo-analytics.github.io)\n[![]"
  },
  {
    "path": "backend/README.md",
    "chars": 439,
    "preview": "## Table structure\n\n### What to track:\n\nstargizers data;\nclone data;\nvisits data;\nreferal data;\ntoppage data;\n\n### Usefu"
  },
  {
    "path": "backend/db/Repo.js",
    "chars": 2310,
    "preview": "/**\n * {\n *   username: 'timqian',\n *   repo: 'timqian/chart.xkcd',\n *   createdAt: '',\n * }\n */\nconst dynamodb = requir"
  },
  {
    "path": "backend/db/Star.js",
    "chars": 1949,
    "preview": "/**\n * {\n *   repo: 'timqian/chart.xkcd',\n *   updatedAt: '2016-09-18',\n *   totalCount: '100',\n *   history: {\n *     '"
  },
  {
    "path": "backend/db/Traffic.js",
    "chars": 4266,
    "preview": "/**\n * {\n *   repo: 'timqian/chart.xkcd',\n *   date: '2016-09-18',\n *   views: [],\n *   clones: [],\n *   referrers: [],\n"
  },
  {
    "path": "backend/db/User.js",
    "chars": 2618,
    "preview": "/**\n * {\n *   username: 'timqian',\n *   email: 'timqian@t9t.io',\n *   accessToken: '',\n *   displayName: '', \n *   photo"
  },
  {
    "path": "backend/db/dynamodb.js",
    "chars": 594,
    "preview": "const AWS = require('aws-sdk');\n\nlet config = {};\n\ntry {\n  config = require('../secret.json');\n} catch (error) {\n  conso"
  },
  {
    "path": "backend/package.json",
    "chars": 567,
    "preview": "{\n  \"name\": \"backend\",\n  \"version\": \"1.0.0\",\n  \"main\": \"server.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test sp"
  },
  {
    "path": "backend/scripts/README.md",
    "chars": 501,
    "preview": "## TODO\n\n- add cities in the largest cities\n\n## Refs\n\n- List of largest cities: https://en.wikipedia.org/wiki/List_of_la"
  },
  {
    "path": "backend/scripts/countries.json",
    "chars": 20255,
    "preview": "[{\n  \"country\": \"russia\",\n  \"states\": [], \"alias\": [],\n  \"cities\": [\"moscow\",\n    \"saint petersburg\",\n    \"novosibirsk\","
  },
  {
    "path": "backend/scripts/dailyGetStars.js",
    "chars": 821,
    "preview": "const RepoDao = require('../db/Repo');\nconst getStars = require('../utils/getStars');\nconst StarDao = require('../db/Sta"
  },
  {
    "path": "backend/scripts/dailyGetTraffics.js",
    "chars": 2661,
    "preview": "const axios = require('axios');\nconst UserDao = require('../db/User');\nconst RepoDao = require('../db/Repo');\nconst Traf"
  },
  {
    "path": "backend/scripts/getStarsAndSaveDbForRepoWithoutRepos.js",
    "chars": 2758,
    "preview": "const { GraphQLClient } = require('graphql-request');\nconst guess = require('./guessCountryFromAddress');\n\nconst UserDao"
  },
  {
    "path": "backend/scripts/guessCountryFromAddress.js",
    "chars": 911,
    "preview": "const countries = require('./countries.json');\n\nconst guess = (address) => {\n  const lowerCaseAddr = address.toLowerCase"
  },
  {
    "path": "backend/server.js",
    "chars": 7613,
    "preview": "const express = require('express');\nconst cors = require('cors');\nconst bodyParser = require('body-parser');\nconst passp"
  },
  {
    "path": "backend/up.json",
    "chars": 393,
    "preview": "{\n  \"name\": \"repo-traffic\",\n  \"profile\": \"timConsole\",\n  \"regions\": [\"us-east-1\"],\n  \"error_pages\": {\n    \"variables\": {"
  },
  {
    "path": "backend/utils/getStars.js",
    "chars": 2737,
    "preview": "const { GraphQLClient } = require('graphql-request');\nconst guess = require('../scripts/guessCountryFromAddress');\n\ncons"
  },
  {
    "path": "backend/utils/getTrafficOfRepoAndSave.js",
    "chars": 1142,
    "preview": "const axios = require('axios');\nconst TrafficDao = require('../db/Traffic');\n\nconst func = async ({ repoPath, token }) ="
  },
  {
    "path": "backend/utils/getUniqueListBy.js",
    "chars": 2102,
    "preview": "function getUniqueListBy(arr, key) {\n  return [...new Map(arr.map(item => [item[key], item])).values()]\n}\n\nmodule.export"
  },
  {
    "path": "backend/utils/trafficDateRangeToDateArr.js",
    "chars": 937,
    "preview": "const dayjs = require('dayjs');\n/**\n * @param {String} earliestDate\n * @param {String} latestDate\n * @return {Array} dat"
  },
  {
    "path": "frontend/.gitignore",
    "chars": 310,
    "preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pn"
  },
  {
    "path": "frontend/README.md",
    "chars": 3145,
    "preview": "# Frontend code base of repo-traffic\n\n## Important Scripts\n\n```bash\n# start dev server\nnpm start\n\n# build website\nnpm bu"
  },
  {
    "path": "frontend/package.json",
    "chars": 969,
    "preview": "{\n  \"name\": \"frontend\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"axios\": \"^0.19.0\",\n    \"chart."
  },
  {
    "path": "frontend/public/404.html",
    "chars": 1850,
    "preview": "<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <title>Single Page Apps for GitHub Pages</title>\n    <scr"
  },
  {
    "path": "frontend/public/index.html",
    "chars": 3213,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/"
  },
  {
    "path": "frontend/public/manifest.json",
    "chars": 333,
    "preview": "{\n  \"short_name\": \"Repo Analytics\",\n  \"name\": \"Create React App Sample\",\n  \"icons\": [\n    {\n      \"src\": \"favicon.ico\",\n"
  },
  {
    "path": "frontend/public/robots.txt",
    "chars": 57,
    "preview": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\n"
  },
  {
    "path": "frontend/src/App.css",
    "chars": 1362,
    "preview": "a {\n  color: #0366d6;\n  text-decoration: none;\n}\n\na:hover {\n  text-decoration: none;\n}\n\nheader {\n  display: flex;\n  just"
  },
  {
    "path": "frontend/src/App.js",
    "chars": 3090,
    "preview": "import React from \"react\";\nimport { BrowserRouter as Router, Route, Link } from \"react-router-dom\";\nimport './App.css';\n"
  },
  {
    "path": "frontend/src/App.test.js",
    "chars": 248,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\n\nit('renders without crashing', ()"
  },
  {
    "path": "frontend/src/components/AddRepo.css",
    "chars": 1261,
    "preview": ".add-new {\n  width: 100%;\n  height: 100%;\n  display:flex;\n  flex-direction: column;\n  align-items: center;\n  justify-con"
  },
  {
    "path": "frontend/src/components/AddRepo.js",
    "chars": 1549,
    "preview": "import React, { useState } from \"react\";\nimport http from \"../utils/http\";\nimport userSignedIn from '../utils/userSigned"
  },
  {
    "path": "frontend/src/components/CardLoader.js",
    "chars": 534,
    "preview": "import React from \"react\"\nimport ContentLoader from \"react-content-loader\"\n\nconst MyLoader = () => (\n  <ContentLoader \n "
  },
  {
    "path": "frontend/src/components/CloneChart.js",
    "chars": 1204,
    "preview": "import React, { useEffect } from 'react';\nimport chartXkcd from 'chart.xkcd';\n\nconst VisitChart = ({ clones }) => {\n\n  c"
  },
  {
    "path": "frontend/src/components/Footer.css",
    "chars": 380,
    "preview": "footer {\n  margin: 80px 0;\n  border-top: 1px solid #dfe2e5;\n  padding: 20px 8px;\n\n\n  display: flex;\n  justify-content: s"
  },
  {
    "path": "frontend/src/components/Footer.js",
    "chars": 697,
    "preview": "import React from 'react';\nimport './Footer.css'\n\nconst Footer = () => (\n  <footer>\n    <div className=\"footer-content\">"
  },
  {
    "path": "frontend/src/components/PathChart.js",
    "chars": 585,
    "preview": "import React from 'react';\n\nconst Paths = ({paths}) => (\n  <div className=\"chart-container\">\n    <h3 className=\"chart-co"
  },
  {
    "path": "frontend/src/components/ProjectCard.css",
    "chars": 593,
    "preview": ".card-container {\n  margin: 15px;\n  font-size: 16px;\n  height: 100%;\n  position: relative;\n}\n\n.path-divider {\n  font-siz"
  },
  {
    "path": "frontend/src/components/ProjectCard.js",
    "chars": 1388,
    "preview": "import React, { useRef, useEffect } from 'react';\nimport chartXkcd from 'chart.xkcd';\nimport './ProjectCard.css';\n\n\ncons"
  },
  {
    "path": "frontend/src/components/ReferrerChart.js",
    "chars": 655,
    "preview": "import React from 'react';\n\nconst Referrer = ({referrers}) => {\n\n  console.log('referrers', referrers)\n  return (\n    <d"
  },
  {
    "path": "frontend/src/components/RepoLoader.js",
    "chars": 652,
    "preview": "import React from 'react'\nimport ContentLoader from 'react-content-loader'\n\nconst Article = () => (\n  <ContentLoader\n   "
  },
  {
    "path": "frontend/src/components/RepoNav.js",
    "chars": 880,
    "preview": "import React from \"react\";\nconst Nav = ({repoPath, selectedTab}) => {\n  return (\n    <div className=\"repo-header\">\n     "
  },
  {
    "path": "frontend/src/components/RepoSetting.css",
    "chars": 1090,
    "preview": ".traffic-switch {\n  margin: 40px;\n  margin-top: 40px;\n  font-size: 20px;\n  font-weight: 300;\n  line-height: 25px;\n}\n\n\n/*"
  },
  {
    "path": "frontend/src/components/RepoSetting.js",
    "chars": 366,
    "preview": "import React from 'react';\nimport './RepoSetting.css';\n\nconst Setting = () => (\n  <div className=\"repo-container\">\n    <"
  },
  {
    "path": "frontend/src/components/StarAnalytics.js",
    "chars": 1621,
    "preview": "import React, { useEffect, useState } from \"react\";\nimport RepoLoader from \"./RepoLoader\";\nimport http from '../utils/ht"
  },
  {
    "path": "frontend/src/components/StarHistoryChart.js",
    "chars": 1461,
    "preview": "import React, { useState, useEffect } from 'react';\nimport chartXkcd from 'chart.xkcd';\nimport './VisitChart.css';\n\ncons"
  },
  {
    "path": "frontend/src/components/StarLocationChart.js",
    "chars": 1226,
    "preview": "import React, { useEffect } from 'react';\nimport chartXkcd from 'chart.xkcd';\nimport './VisitChart.css';\n\nconst StarLoca"
  },
  {
    "path": "frontend/src/components/TrafficAnalytics.js",
    "chars": 1560,
    "preview": "import React, { useEffect, useState } from \"react\";\nimport VisitChart from './VisitChart';\nimport CloneChart from './Clo"
  },
  {
    "path": "frontend/src/components/VisitChart.css",
    "chars": 500,
    "preview": ".chart-container {\n  border: 1px solid #d1d5da;\n  border-radius: 5px;\n  margin-bottom: 30px;\n  position: relative;\n}\n\n.s"
  },
  {
    "path": "frontend/src/components/VisitChart.js",
    "chars": 1187,
    "preview": "import React, { useEffect } from 'react';\nimport chartXkcd from 'chart.xkcd';\nimport './VisitChart.css';\n\nconst VisitCha"
  },
  {
    "path": "frontend/src/index.css",
    "chars": 366,
    "preview": "body {\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\",\n    \"Ubuntu\", \"Can"
  },
  {
    "path": "frontend/src/index.js",
    "chars": 491,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as "
  },
  {
    "path": "frontend/src/pages/Home.css",
    "chars": 1879,
    "preview": ".home-container {\n  margin: 0 auto;\n  max-width: 900px;\n}\n\n.home-hero {\n  text-align: center;\n  padding: 30px 10px 130px"
  },
  {
    "path": "frontend/src/pages/Home.js",
    "chars": 2769,
    "preview": "import React, { useEffect, useState } from \"react\";\nimport http from '../utils/http';\nimport ProjectCard from '../compon"
  },
  {
    "path": "frontend/src/pages/Repo.css",
    "chars": 1802,
    "preview": ".repo-container {\n  margin: 0 auto;\n  max-width: 900px;\n  padding: 0 8px;\n}\n\n.repo-header {\n  width: 100vw;\n  background"
  },
  {
    "path": "frontend/src/pages/Repo.js",
    "chars": 1471,
    "preview": "import TrafficAnalytics from '../components/TrafficAnalytics'; \nimport StarAnalytics from '../components/StarAnalytics';"
  },
  {
    "path": "frontend/src/pages/User.css",
    "chars": 211,
    "preview": ".user-title {\n  margin-left: 8px;\n  margin-top: 30px;\n  margin-bottom: 30px;\n  font-size: 25px;\n}\n\n.user-link {\n  font-w"
  },
  {
    "path": "frontend/src/pages/User.js",
    "chars": 1551,
    "preview": "import React, { useEffect, useState } from \"react\";\nimport http from '../utils/http';\nimport ProjectCard from '../compon"
  },
  {
    "path": "frontend/src/serviceWorker.js",
    "chars": 4951,
    "preview": "// This optional code is used to register a service worker.\n// register() is not called by default.\n\n// This lets the ap"
  },
  {
    "path": "frontend/src/utils/http.js",
    "chars": 1111,
    "preview": "import axios from 'axios';\n\nconst userRaw = window.localStorage.getItem('user');\n\nlet token;\nif (userRaw) {\n  const user"
  },
  {
    "path": "frontend/src/utils/trafficDateRangeToArray.js",
    "chars": 174,
    "preview": "/**\n * @param startDate\n * @param endDate\n * @returns array of required traffic dates\n * @example\n *   const dateArr = t"
  },
  {
    "path": "frontend/src/utils/userSignedIn.js",
    "chars": 520,
    "preview": "/**\n * user: {\n *   username: 'timqian',\n *   token: '',\n *   photo: '',\n * }\n */\n\nfunction set({ username, token, photo"
  }
]

About this extraction

This page contains the full source code of the repo-analytics/repo-analytics.github.io GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 65 files (141.1 KB), approximately 40.3k tokens, and a symbol index with 38 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!