Repository: tipsy/profile-summary-for-github
Branch: master
Commit: a9b9e6f524a7
Files: 35
Total size: 89.6 KB
Directory structure:
gitextract_e90y_zux/
├── .gitignore
├── .mvn/
│ └── wrapper/
│ ├── MavenWrapperDownloader.java
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── Dockerfile
├── Documentation/
│ ├── Building.md
│ ├── Docker.md
│ └── Usage.md
├── LICENSE
├── Procfile
├── README.md
├── mvnw
├── mvnw.cmd
├── pom.xml
├── src/
│ └── main/
│ ├── kotlin/
│ │ └── app/
│ │ ├── CacheService.kt
│ │ ├── Config.kt
│ │ ├── GhService.kt
│ │ ├── Main.kt
│ │ ├── UserProfile.kt
│ │ ├── UserService.kt
│ │ └── util/
│ │ ├── CommitCountUtil.kt
│ │ └── HikariCpDataSource.kt
│ └── resources/
│ ├── logback.xml
│ └── vue/
│ ├── components/
│ │ ├── _charts.vue
│ │ ├── _gtm.vue
│ │ ├── _main-styles.vue
│ │ ├── app-frame.vue
│ │ ├── donut-charts.vue
│ │ ├── loading-bouncer.vue
│ │ ├── share-bar.vue
│ │ └── user-info.vue
│ ├── layout.html
│ └── views/
│ ├── search-view.vue
│ └── user-view.vue
└── system.properties
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.idea
*.iml
cache
================================================
FILE: .mvn/wrapper/MavenWrapperDownloader.java
================================================
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.5";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
================================================
FILE: .mvn/wrapper/maven-wrapper.properties
================================================
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.1/apache-maven-3.6.1-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar
================================================
FILE: Dockerfile
================================================
FROM maven:3.9-eclipse-temurin-17-alpine as maven-build
WORKDIR /app
COPY . .
RUN mvn verify
FROM eclipse-temurin:17-jre-alpine
RUN adduser \
-h /var/github-summary \
-D -u 1000 \
ghsum ghsum
USER ghsum
WORKDIR /var/github-summary
ENV TOKENS=""
ENTRYPOINT ["java", "-Dapi-tokens=${TOKENS}", "-jar", "profile-summary-for-github.jar"]
EXPOSE 7070
COPY --from=maven-build \
--chown=ghsum:ghsum \
/app/target/profile-summary-for-github-jar-with-dependencies.jar profile-summary-for-github.jar
================================================
FILE: Documentation/Building.md
================================================
# Building
*How to setup and compile the project.*
<br>
## Docker
You can also use **[Docker]** to <br>
compile & run the project.
<br>
<br>
## Steps
- Clone the repository
```shell
git clone https://github.com/tipsy/profile-summary-for-github.git
```
- Navigate to the root folder
```shell
cd profile-summary-for-github
```
- Install the dependencies
```shell
mvn install
```
- Compile the source code
```shell
java -jar target/profile-summary-for-github-jar-with-dependencies.jar
```
<br>
<!----------------------------------------------------------------------------->
[Docker]: Docker.md
================================================
FILE: Documentation/Docker.md
================================================
# Docker
*How to use this project with docker.*
<br>
## Building
*How to compile the source code.*
<br>
- Clone the repository
```shell
git clone https://github.com/tipsy/profile-summary-for-github.git
```
- Navigate to the root folder
```shell
cd profile-summary-for-github
```
- Compile the source code
```shell
docker build -t profile-summary-for-github
```
<br>
<br>
## Running
*How to start the compiled project.*
<br>
### Without Token
```shell
docker run \
-it \
--rm \
--name profile-summary-for-github \
-p 7070:7070 profile-summary-for-github
```
<br>
### With Token
```shell
docker run \
-it \
--rm \
--name profile-summary-for-github \
-p 7070:7070 \
-e "API_TOKENS=<My Token A>,<My Token B>" profile-summary-for-github
```
<br>
### Interface
You can access it at http://localhost:7070
<br>
================================================
FILE: Documentation/Usage.md
================================================
# Usage
*How to configure the project.*
<br>
## API Token
*The access token to GitHubs API.*
<br>
### Without
If no api token is set, you only get `~50 requests / hour`.
<br>
### With
To run the app with an api-token, first **[Generate A Token]**.
Provide the token in the following way:
```shell
java \
-Dapi-tokens=your-token \
-jar target/profile-summary-for-github-jar-with-dependencies.jar
```
*You can use a comma-separated list* <br>
*of tokens to increase your rate-limit.*
<br>
<br>
## Parameters
*Command line options you can set.*
<br>
### Unrestricted
You can allow the building of any GitHub <br>
profile by passing `-Dunrestricted=true` :
```shell
java \
-Dunrestricted=true \
-jar target/profile-summary-for-github-jar-with-dependencies.jar
```
<br>
### Free Threshold
You can set when the app should require <br>
the user to star the GitHub repository.
*Pass the number of remaining requests at which the* <br>
*cutoff should kick in, as seen in the following example:*
```shell
java \
-Dfree-requests-cutoff=1000 \
-jar target/profile-summary-for-github-jar-with-dependencies.jar
```
<br>
### Google Tag Manager
You can enable this feature by passing the `gtm-id`.
```shell
java \
-Dgtm-id=GTM-XXXXXX \
-jar target/profile-summary-for-github-jar-with-dependencies.jar
```
<br>
<!----------------------------------------------------------------------------->
[Generate A Token]: https://github.com/settings/tokens
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017-2018 David Åse
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: Procfile
================================================
web: java -jar -Xmx256M ./target/profile-summary-for-github-jar-with-dependencies.jar
================================================
FILE: README.md
================================================
# Profile Summary [![Badge License]][License]
*A tool to visualize your **GitHub** presence.*
<br>
<div align = center>
---
[![Button Demo]][Demo]
[![Button Building]][Building]
[![Button Usage]][Usage]
---
<br>
<img
src = 'https://user-images.githubusercontent.com/1521451/34072014-4451dbf6-e280-11e7-90a7-32ad1f313541.PNG'
width = 800
/>
</div>
<!----------------------------------------------------------------------------->
[Demo]: https://profile-summary-for-github.com/
[Building]: Documentation/Building.md
[License]: LICENSE
[Usage]: Documentation/Usage.md
<!--------------------------------[ Badges ]----------------------------------->
[Badge License]: https://img.shields.io/badge/License-Apache_2.0-D22128?style=for-the-badge
<!-------------------------------[ Buttons ]----------------------------------->
[Button Building]: https://img.shields.io/badge/Building-7952B3?style=for-the-badge&logoColor=white&logo=AzureArtifacts
[Button Usage]: https://img.shields.io/badge/Usage-239120?style=for-the-badge&logoColor=white&logo=GitBook
[Button Demo]: https://img.shields.io/badge/Demo-0091BD?style=for-the-badge&logoColor=white&logo=AppleArcade
================================================
FILE: mvnw
================================================
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
================================================
FILE: mvnw.cmd
================================================
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
================================================
FILE: pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.javalin</groupId>
<artifactId>profile-summary-for-github</artifactId>
<version>1.0</version>
<name>${artifactId}</name>
<properties>
<java.version>17</java.version>
<kotlin.compiler.jvmTarget>17</kotlin.compiler.jvmTarget>
<kotlin.version>2.2.20</kotlin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.javalin</groupId>
<artifactId>javalin-bundle</artifactId>
<version>7.0.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.17</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.17.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.mylyn.github</groupId>
<artifactId>org.eclipse.egit.github.core</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.232</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>6.2.1</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<jvmTarget>17</jvmTarget>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmTarget>17</jvmTarget>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>attached</goal>
</goals>
<phase>package</phase>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>app.MainKt</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
<plugin>
<groupId>com.heroku.sdk</groupId>
<artifactId>heroku-maven-plugin</artifactId>
<version>3.0.7</version>
<configuration>
<jdkVersion>17</jdkVersion>
<appName>profile-summary-for-github</appName>
<processTypes>
<!-- Tell Heroku how to launch your application -->
<web>java -jar -Xmx256M ./target/profile-summary-for-github-jar-with-dependencies.jar</web>
</processTypes>
</configuration>
</plugin>
</plugins>
</build>
</project>
================================================
FILE: src/main/kotlin/app/CacheService.kt
================================================
@file:Suppress("SqlResolve")
package app
import app.util.HikariCpDataSource
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.slf4j.LoggerFactory
import java.time.Instant
import java.time.temporal.ChronoUnit
object CacheService {
private val log = LoggerFactory.getLogger(CacheService.javaClass)
private val objectMapper = jacksonObjectMapper()
private val connection = HikariCpDataSource.connection
private fun createTableIfAbsent() {
val statement = connection.createStatement()
statement.execute(
"""
CREATE TABLE IF NOT EXISTS userinfo (
id VARCHAR2 PRIMARY KEY,
timestamp TIMESTAMP,
data JSON
)
""".trimIndent()
)
}
fun selectJsonFromDb(username: String): String? {
createTableIfAbsent()
val preparedStatement = connection.prepareStatement(
"""
SELECT
timestamp,
data
FROM userinfo
WHERE id = ?
""".trimIndent()
)
preparedStatement.setString(1, username.lowercase())
val result = preparedStatement.executeQuery()
result.use {
// guaranteed to be at most one.
if (it.next()) {
val timestamp = it.getTimestamp("timestamp").toInstant()
val diffInHours = ChronoUnit.HOURS.between(timestamp, Instant.now())
if (diffInHours <= 6) {
val json: String? = it.getString("data")
if (json != null) {
log.debug("cache hit: {}", json)
}
return json
}
}
}
log.debug("cache miss for username: {}", username)
return null
}
fun getUserFromJson(json: String) = objectMapper.readValue<UserProfile>(json)
fun saveInCache(userProfile: UserProfile) {
createTableIfAbsent()
val json = objectMapper.writeValueAsString(userProfile)
val preparedStatement = connection.prepareStatement(
"""
MERGE INTO userinfo (id, timestamp, data) KEY (id)
VALUES (?, CURRENT_TIMESTAMP(), ? FORMAT JSON)
""".trimIndent()
)
preparedStatement.setString(1, userProfile.user.login.lowercase())
preparedStatement.setString(2, json)
preparedStatement.execute()
}
}
================================================
FILE: src/main/kotlin/app/Config.kt
================================================
package app
object Config {
// Get port from Heroku, or return null (localhost)
fun getPort() = getHerokuProperty("port")?.let {
Integer.parseInt(it)
}
// Get 'api-tokens' from Heroku/System, or return null if not set
fun getApiTokens(): String? = getProperty("api-tokens")
// Get 'unrestricted' state from Heroku/System, or return null if not set
fun unrestricted(): Boolean = getProperty("unrestricted")?.toBoolean() == true
// Get 'gtm-id' from Heroku/System, or return null if not set
fun getGtmId(): String? = getProperty("gtm-id")
// Get 'star-bypass' from Heroku/System, or return null if not stored
fun freeRequestCutoff() = getProperty("free-requests-cutoff")?.let { Integer.parseInt(it) }
private fun getProperty(name: String): String? = getHerokuProperty(name) ?: System.getProperty(name)
private fun getHerokuProperty(envStr: String) = ProcessBuilder().environment()[envStr.uppercase().replace("-", "_")]
}
================================================
FILE: src/main/kotlin/app/GhService.kt
================================================
package app
import io.javalin.websocket.WsContext
import org.eclipse.egit.github.core.client.GitHubClient
import org.eclipse.egit.github.core.service.CommitService
import org.eclipse.egit.github.core.service.RepositoryService
import org.eclipse.egit.github.core.service.UserService
import org.eclipse.egit.github.core.service.WatcherService
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
object GhService {
// https://javadoc.io/doc/org.eclipse.mylyn.github/org.eclipse.egit.github.core/2.1.5
private val log = LoggerFactory.getLogger(GhService.javaClass)
private val tokens = Config.getApiTokens()?.split(",") ?: listOf("") // empty token is limited to 60 requests
private val clients = tokens.map { GitHubClient().apply { setOAuth2Token(it) } }
private val repoServices = clients.map { RepositoryService(it) }
private val commitServices = clients.map { CommitService(it) }
private val userServices = clients.map { UserService(it) }
private val watcherServices = clients.map { WatcherService(it) }
val repos: RepositoryService get() = repoServices.maxByOrNull { it.client.remainingRequests }!!
val commits: CommitService get() = commitServices.maxByOrNull { it.client.remainingRequests }!!
val users: UserService get() = userServices.maxByOrNull { it.client.remainingRequests }!!
val watchers: WatcherService get() = watcherServices.maxByOrNull { it.client.remainingRequests }!!
val remainingRequests: Int get() = clients.sumOf { it.remainingRequests }
// Allows for parallel iteration and O(1) put/remove
private val clientSessions = ConcurrentHashMap<WsContext, Boolean>()
fun registerClient(ws: WsContext) = clientSessions.put(ws, true) == true
fun unregisterClient(ws: WsContext) = clientSessions.remove(ws) == true
init {
Executors.newScheduledThreadPool(2).apply {
// ping clients every other minute to make sure remainingRequests is correct
scheduleAtFixedRate({
repoServices.forEach {
try {
it.getRepository("tipsy", "profile-summary-for-github")
log.info("Pinged client ${clients.indexOf(it.client)} - client.remainingRequests was ${it.client.remainingRequests}")
} catch (e: Exception) {
log.info("Pinged client ${clients.indexOf(it.client)} - was rate-limited")
}
}
}, 0, 2, TimeUnit.MINUTES)
// update all connected clients with remainingRequests twice per second
scheduleAtFixedRate({
val remainingRequests = remainingRequests.toString()
clientSessions.forEachKey(1) {
try {
it.send(remainingRequests)
} catch (e: Exception) {
log.error(e.toString())
}
}
}, 0, 500, TimeUnit.MILLISECONDS)
}
}
}
================================================
FILE: src/main/kotlin/app/Main.kt
================================================
package app
import io.javalin.Javalin
import io.javalin.compression.CompressionStrategy
import io.javalin.http.BadRequestResponse
import io.javalin.http.NotFoundResponse
import io.javalin.http.queryParamAsClass
import io.javalin.http.staticfiles.Location
import io.javalin.plugin.bundled.JavalinVuePlugin
import io.javalin.plugin.bundled.RateLimitPlugin
import io.javalin.vue.VueComponent
import org.eclipse.jetty.server.HttpConnectionFactory
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.ServerConnector
import org.eclipse.jetty.util.thread.QueuedThreadPool
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
fun main() {
val log = LoggerFactory.getLogger("app.MainKt")
Javalin.start { config ->
config.bundledPlugins.enableSslRedirects()
config.staticFiles.add("/public", Location.CLASSPATH)
config.http.compressionStrategy = CompressionStrategy.GZIP
config.unsafe.jettyInternal.server = Server(QueuedThreadPool(200, 8, 120000)).apply {
connectors = arrayOf(ServerConnector(server).apply {
port = Config.getPort() ?: 7070
idleTimeout = 120_000
connectionFactories.filterIsInstance<HttpConnectionFactory>().forEach {
it.httpConfiguration.sendServerVersion = false
}
})
}
config.registerPlugin(RateLimitPlugin({}))
config.registerPlugin(JavalinVuePlugin { vue ->
vue.optimizeDependencies = false
})
// Routes
config.routes.before("/api/*") { it.with(RateLimitPlugin::class).requestPerTimeUnit(20, TimeUnit.MINUTES) }
config.routes.get("/api/can-load") { ctx ->
val user = ctx.queryParamAsClass<String>("user").required().get()
// Use quick check that doesn't consume GitHub API requests
// This runs before the spinner is shown
ctx.status(if (UserService.canLoadUserQuick(user)) 200 else 400)
}
config.routes.get("/api/user/{user}") { ctx ->
val user = ctx.pathParam("user")
if (!UserService.userExists(user)) throw NotFoundResponse()
UserService.getUserIfCanLoad(user)?.let { ctx.json(it) } ?: throw BadRequestResponse("Can't load user")
}
config.routes.get("/search", VueComponent("search-view"))
config.routes.get("/user/{user}", VueComponent("user-view"))
config.routes.ws("/rate-limit-status") { ws ->
ws.onConnect { GhService.registerClient(it) }
ws.onClose { GhService.unregisterClient(it) }
ws.onError { GhService.unregisterClient(it) }
}
config.routes.after { it.cookie("gtm-id", Config.getGtmId() ?: "") } // what is this?
// Exception and error handlers
config.routes.exception(Exception::class.java) { e, ctx ->
log.warn("Uncaught exception", e)
ctx.status(500)
}
config.routes.error(404, "html") {
it.redirect("/search")
}
}
}
================================================
FILE: src/main/kotlin/app/UserProfile.kt
================================================
package app
import org.eclipse.egit.github.core.User
data class UserProfile(
val user: User,
val quarterCommitCount: Map<String, Int>,
val langRepoCount: Map<String, Int>,
val langStarCount: Map<String, Int>,
val langCommitCount: Map<String, Int>,
val repoCommitCount: Map<String, Int>,
val repoStarCount: Map<String, Int>,
val repoCommitCountDescriptions: Map<String, String?>,
val repoStarCountDescriptions: Map<String, String?>
)
================================================
FILE: src/main/kotlin/app/UserService.kt
================================================
package app
import app.util.CommitCountUtil
import org.eclipse.egit.github.core.Repository
import org.eclipse.egit.github.core.RepositoryCommit
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap
import java.util.stream.IntStream
import kotlin.streams.toList
object UserService {
private val log = LoggerFactory.getLogger("app.UserCtrlKt")
fun userExists(user: String): Boolean = try {
GhService.users.getUser(user) != null
} catch (e: Exception) {
false
}
private fun remainingRequests(): Int = GhService.remainingRequests
// Lightweight check that doesn't consume GitHub API requests
// Used by /api/can-load to check before showing the spinner
fun canLoadUserQuick(user: String): Boolean {
val userCacheJson = CacheService.selectJsonFromDb(user)
return Config.unrestricted()
|| (userCacheJson != null)
|| remainingRequests() > 0
}
fun getUserIfCanLoad(username: String): UserProfile? {
val userCacheJson = CacheService.selectJsonFromDb(username)
val canLoadUser = Config.unrestricted()
|| (userCacheJson != null)
|| remainingRequests() > 0
if (canLoadUser) {
return if (userCacheJson == null) {
generateUserProfile(username)
} else {
CacheService.getUserFromJson(userCacheJson)
}
}
return null
}
private fun commitsForRepo(repo: Repository): List<RepositoryCommit> = try {
GhService.commits.getCommits(repo)
} catch (e: Exception) {
listOf()
}
private fun generateUserProfile(username: String): UserProfile {
val user = GhService.users.getUser(username)
val repos = GhService.repos.getRepositories(username).filter { !it.isFork && it.size != 0 }
val repoCommits = repos.parallelStream().map { it to commitsForRepo(it).filter { it.author?.login.equals(username, ignoreCase = true) } }.toList().toMap()
val langRepoGrouping = repos.groupingBy { (it.language ?: "Unknown") }
val quarterCommitCount = CommitCountUtil.getCommitsForQuarters(user, repoCommits)
val langRepoCount = langRepoGrouping.eachCount().toList().sortedBy { (_, v) -> -v }.toMap()
val langStarCount = langRepoGrouping.fold(0) { acc, repo -> acc + repo.watchers }.toList().filter { (_, v) -> v > 0 }.sortedBy { (_, v) -> -v }.toMap()
val langCommitCount = langRepoGrouping.fold(0) { acc, repo -> acc + repoCommits[repo]!!.size }.toList().sortedBy { (_, v) -> -v }.toMap()
val repoCommitCount = repoCommits.map { it.key.name to it.value.size }.toList().sortedBy { (_, v) -> -v }.take(10).toMap()
val repoStarCount = repos.filter { it.watchers > 0 }.map { it.name to it.watchers }.sortedBy { (_, v) -> -v }.take(10).toMap()
val repoCommitCountDescriptions = repoCommitCount.map { it.key to repos.find { r -> r.name == it.key }?.description }.toMap()
val repoStarCountDescriptions = repoStarCount.map { it.key to repos.find { r -> r.name == it.key }?.description }.toMap()
val userProfile = UserProfile(
user,
quarterCommitCount,
langRepoCount,
langStarCount,
langCommitCount,
repoCommitCount,
repoStarCount,
repoCommitCountDescriptions,
repoStarCountDescriptions
)
CacheService.saveInCache(userProfile)
return userProfile;
}
}
================================================
FILE: src/main/kotlin/app/util/CommitCountUtil.kt
================================================
package app.util
import org.eclipse.egit.github.core.Repository
import org.eclipse.egit.github.core.RepositoryCommit
import org.eclipse.egit.github.core.User
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.time.ZoneOffset.UTC
import java.time.temporal.IsoFields
import java.time.temporal.IsoFields.QUARTER_YEARS
import java.time.temporal.TemporalAdjusters
import java.util.*
object CommitCountUtil {
fun getCommitsForQuarters(user: User, repoCommits: Map<Repository, List<RepositoryCommit>>): SortedMap<String, Int> {
val creation = asInstant(user.createdAt).withDayOfMonth(1)
val now = Instant.now().atOffset(UTC).with(TemporalAdjusters.firstDayOfNextMonth())
val quarterBuckets = (0..QUARTER_YEARS.between(creation, now))
.associate { yearQuarterFromDate(creation.plus(it, QUARTER_YEARS)) to 0 }
.toSortedMap()
repoCommits.values.flatten().groupingBy { yearQuarterFromCommit(it) }.eachCountTo(quarterBuckets)
return quarterBuckets
}
private fun asInstant(date: Date) = date.toInstant().atOffset(ZoneOffset.UTC)
private fun yearQuarterFromCommit(it: RepositoryCommit) = yearQuarterFromDate(asInstant(it.commit.committer.date))
private fun yearQuarterFromDate(date: OffsetDateTime) = "${date.year}-Q${date.get(IsoFields.QUARTER_OF_YEAR)}"
}
================================================
FILE: src/main/kotlin/app/util/HikariCpDataSource.kt
================================================
package app.util
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import java.sql.Connection
object HikariCpDataSource {
private const val urlToDb = "jdbc:h2:mem:userinfo;DB_CLOSE_DELAY=-1;QUERY_CACHE_SIZE=256"
private val config = HikariConfig().apply {
jdbcUrl = urlToDb
}
private var hikariDataSource = HikariDataSource(config)
val connection: Connection get() = hikariDataSource.connection
}
================================================
FILE: src/main/resources/logback.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<!-- Set Javalin to INFO level -->
<logger name="io.javalin" level="INFO" />
<!-- Set Jetty to WARN level to reduce noise -->
<logger name="org.eclipse.jetty" level="WARN" />
</configuration>
================================================
FILE: src/main/resources/vue/components/_charts.vue
================================================
<script>
const UNKNOWN_LANGUAGE = "Unknown";
function donutChart(objectName, data) {
let canvas = document.getElementById(objectName);
if (canvas === null) {
return;
}
let userId = data.user.login;
let labels = Object.keys(data[objectName]);
/**
* The language index of <code>UNKNOWN_LANGUAGE</code>
* @type {Number}
*/
let indexOfUnknownLanguage = -1;
let values = Object.values(data[objectName]);
let colors = createColorArray(labels.length);
let tooltipInfo = null;
window.languageColors = window.languageColors || {};
if ("langRepoCount" === objectName) {
// when the first language-set is loaded, set a color-profile for all languages
labels.forEach((language, i) => languageColors[language] = colors[i]);
}
if (["langRepoCount", "langStarCount", "langCommitCount"].indexOf(objectName) > -1) {
// if the dataset is language-related, load color-profile
labels.forEach((language, i) => colors[i] = languageColors[language]);
indexOfUnknownLanguage = labels.indexOf(UNKNOWN_LANGUAGE);
}
if (objectName === "repoCommitCount") {
tooltipInfo = data[objectName + "Descriptions"]; // high quality programming
arrayRotate(colors, 4); // change starting color
}
if (objectName === "repoStarCount") {
tooltipInfo = data[objectName + "Descriptions"]; // high quality programming
arrayRotate(colors, 2); // change starting color
}
new Chart(canvas.getContext("2d"), {
type: "doughnut",
data: {
labels: labels,
datasets: [{
data: values,
backgroundColor: colors
}]
},
options: {
animation: false,
rotation: (-0.40 * Math.PI),
maintainAspectRatio: true,
responsive: true,
legend: { // todo: fix duplication ?
position: window.innerWidth < 600 ? "bottom" : "left",
labels: {
fontSize: window.innerWidth < 480 ? 11 : window.innerWidth < 600 ? 10 : 12,
padding: window.innerWidth < 480 ? 6 : window.innerWidth < 600 ? 8 : 10,
boxWidth: window.innerWidth < 480 ? 12 : window.innerWidth < 600 ? 10 : 12
}
},
tooltips: {
callbacks: {
afterLabel: function (tooltipItem, data) {
if (tooltipInfo !== null) {
return wordWrap(tooltipInfo[data["labels"][tooltipItem["index"]]], 45);
}
if (tooltipItem.index === indexOfUnknownLanguage) {
return "No specific language";
}
}
},
},
onClick: function (e, data) {
try {
let label = labels[data[0]._index];
const isUnknownLanguage = (data[0]._index === indexOfUnknownLanguage);
let canvas = data[0]._chart.canvas.id;
if (canvas === "repoStarCount" || canvas === "repoCommitCount") {
window.open("https://github.com/" + userId + "/" + label, "_blank");
window.focus();
} else {
if (!isUnknownLanguage) {
window.open("https://github.com/" + userId + "?utf8=%E2%9C%93&tab=repositories&q=&type=source&language=" + encodeURIComponent(label), "_blank");
window.focus();
}
}
} catch (ignored) {
}
},
onResize: function (instance) { // todo: fix duplication ?
instance.chart.options.legend.position = window.innerWidth < 600 ? "bottom" : "left";
instance.chart.options.legend.labels.fontSize = window.innerWidth < 480 ? 11 : window.innerWidth < 600 ? 10 : 12;
instance.chart.options.legend.labels.padding = window.innerWidth < 480 ? 6 : window.innerWidth < 600 ? 8 : 10;
instance.chart.options.legend.labels.boxWidth = window.innerWidth < 480 ? 12 : window.innerWidth < 600 ? 10 : 12;
}
}
});
function createColorArray(length) {
const colors = ["#54ca76", "#f5c452", "#f2637f", "#9261f3", "#31a4e6", "#55cbcb"];
let array = [...Array(length).keys()].map(i => colors[i % colors.length]);
// avoid first and last colors being the same
if (length % colors.length === 1) {
array[length - 1] = colors[1];
}
return array;
}
function arrayRotate(arr, n) {
for (let i = 0; i < n; i++) {
arr.push(arr.shift());
}
return arr
}
function wordWrap(str, n) {
if (str === null) {
return null;
}
let currentLine = [];
let resultLines = [];
str.split(" ").forEach(word => {
currentLine.push(word);
if (currentLine.join(" ").length > n) {
resultLines.push(currentLine.join(" "));
currentLine = [];
}
});
if (currentLine.length > 0) {
resultLines.push(currentLine.join(" "));
}
return resultLines
}
}
function lineChart(objectName, data) {
new Chart(document.getElementById(objectName).getContext("2d"), {
type: "line",
data: {
labels: Object.keys(data[objectName]),
datasets: [{
label: "Commits",
data: Object.values(data[objectName]),
backgroundColor: "rgba(67, 142, 233, 0.2)",
borderColor: "rgba(67, 142, 233, 1)",
lineTension: 0
}]
},
options: {
maintainAspectRatio: false,
animation: false,
scales: {
xAxes: [{
display: false
}],
yAxes: [{
position: "right",
beginAtZero: true
}]
},
legend: {
display: false
},
tooltips: {
intersect: false
}
}
});
}
</script>
================================================
FILE: src/main/resources/vue/components/_gtm.vue
================================================
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer',Cookies.get("gtm-id"));
</script>
================================================
FILE: src/main/resources/vue/components/_main-styles.vue
================================================
<style>
* {
font-family: 'Barlow Semi Condensed', sans-serif;
outline: 0;
box-sizing: border-box;
}
[v-cloak] {
display: none;
}
html {
font-size: 18px;
background: radial-gradient(circle at 20% 20%, #f2ede4, #ebe0d0);
padding: 60px 30px;
overflow-y: scroll;
min-height: 100vh;
}
body {
margin: 0;
}
h1, h2, h3, h4 {
font-weight: 400;
}
a {
color: #0082c8;
text-decoration: none;
}
.content {
max-width: 1200px;
margin: 0 auto;
}
.fade-in {
opacity: 0;
animation: fade-in .2s linear forwards;
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@media (max-width: 480px) {
html {
padding: 30px 15px;
font-size: 16px;
}
h1 {
font-size: 24px;
}
h2 {
font-size: 20px;
}
h3 {
font-size: 18px;
}
}
</style>
================================================
FILE: src/main/resources/vue/components/app-frame.vue
================================================
<template id="app-frame">
<div>
<main class="main-content">
<slot :requests-left="requestsLeft"></slot>
</main>
<footer>
GitHub profile summary is built with <a href="https://javalin.io">Javalin 7</a> <small>(kotlin web framework)</small> and
<a href="http://www.chartjs.org/docs/latest/" target="_blank">chart.js</a> <small>(visualization)</small>.
Source is on <a href="https://github.com/tipsy/profile-summary-for-github" target="_blank">GitHub</a>.
</footer>
<span class="rate-limit">
<span v-if="requestsLeft === 0">The app is currently rate-limited<br>Please check back later</span>
<span v-if="requestsLeft !== 0"><strong>{{requestsLeft}}</strong> requests left <br> before rate-limit</span>
</span>
</div>
</template>
<script>
Vue.component("app-frame", {
template: "#app-frame",
data: () => ({
requestsLeft: 9876,
}),
created() {
let wsProtocol = window.location.protocol.indexOf("https") > -1 ? "wss" : "ws";
let ws = new WebSocket(wsProtocol + "://" + location.hostname + ":" + location.port + "/rate-limit-status");
ws.onmessage = msg => this.requestsLeft = msg.data;
},
});
</script>
<style>
footer {
font-size: 17px;
position: fixed;
left: 0;
bottom: 0;
width: 100%;
text-align: center;
padding: 10px 30px;
border-top: 1px solid rgba(0, 0, 0, 0.1);
background: #eee9df;
}
.rate-limit {
position: fixed;
right: 20px;
bottom: 60px;
background: #fff;
padding: 10px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
font-size: 16px;
border-radius: 4px;
}
@media (max-width: 480px) {
.rate-limit {
padding: 5px 8px;
font-size: 13px;
bottom: 0;
right: 0;
}
}
</style>
================================================
FILE: src/main/resources/vue/components/donut-charts.vue
================================================
<template id="donut-charts">
<div class="charts">
<div class="chart-row">
<div class="chart-container chart-container--third">
<h2>Repos per Language</h2>
<canvas id="langRepoCount"></canvas>
</div>
<div v-if="Math.max(...Object.values(data.repoStarCount)) > 0" class="chart-container chart-container--third">
<h2>Stars per Language</h2>
<canvas id="langStarCount"></canvas>
</div>
<div class="chart-container chart-container--third">
<h2>Commits per Language</h2>
<canvas id="langCommitCount"></canvas>
</div>
</div>
<div class="chart-row">
<div class="chart-container chart-container--half">
<h2>Commits per Repo
<small v-if="Object.keys(data.repoCommitCount).length === 10">(top 10)</small>
</h2>
<canvas id="repoCommitCount"></canvas>
</div>
<div v-if="Object.keys(data.repoStarCount).length > 0" class="chart-container chart-container--half">
<h2>Stars per Repo
<small v-if="Object.keys(data.repoStarCount).length == 10">(top 10)</small>
</h2>
<canvas id="repoStarCount"></canvas>
</div>
</div>
</div>
</template>
<script>
Vue.component("donut-charts", {
template: "#donut-charts",
props: ["data"],
mounted() {
donutChart("langRepoCount", this.data);
donutChart("langStarCount", this.data);
donutChart("langCommitCount", this.data);
donutChart("repoCommitCount", this.data);
donutChart("repoStarCount", this.data);
}
});
</script>
<style>
canvas {
user-select: none;
}
.charts,
.chart-row {
overflow: auto;
}
.chart-row {
padding-bottom: 40px;
}
.chart-row {
border-top: 1px solid rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-around;
}
.chart-container--third {
width: 33%;
}
.chart-container--half {
width: 50%;
}
@media (max-width: 900px) {
.chart-container--third,
.chart-container--half {
width: 100%;
}
.chart-row {
display: block;
}
}
@media (max-width: 480px) {
.chart-row {
padding-bottom: 20px;
}
.chart-container {
padding: 15px 10px;
}
.chart-container h2 {
font-size: 18px;
margin-bottom: 15px;
}
.chart-container canvas {
max-height: 300px;
}
footer {
display: none;
}
}
</style>
================================================
FILE: src/main/resources/vue/components/loading-bouncer.vue
================================================
<template id="loading-bouncer">
<div class="loading-bouncer" style="opacity: 0; animation: fade-in 0.2s linear 0.5s forwards">
<div class="la-square-jelly-box la-3x">
<div></div>
<div></div>
</div>
<h2>Analyzing GitHub profile</h2>
<h3 style="opacity: 0; animation: fade-in 0.2s linear 4s forwards">This could take some time ...</h3>
<h3 style="opacity: 0; animation: fade-in 0.2s linear 8s forwards">This user has a lot of repos!</h3>
</div>
</template>
<script>
Vue.component("loading-bouncer", {template: "#loading-bouncer"});
</script>
<style>
.loading-bouncer {
margin-top: 50px;
display: flex;
flex-direction: column;
align-items: center;
}
.la-square-jelly-box {
color: #0082c8;
}
.loading-bouncer h2,
.loading-bouncer h3 {
color: #333;
}
</style>
================================================
FILE: src/main/resources/vue/components/share-bar.vue
================================================
<template id="share-bar">
<div class="share-bar">
<a class="social-btn" :href="twitterUrl" rel="nofollow" title="Share on Twitter"><i class="fa fa-fw fa-twitter"></i>Share on Twitter</a>
<a class="social-btn" :href="facebookUrl" rel="nofollow" title="Share on Facebook"><i class="fa fa-fw fa-facebook"></i>Share on Facebook</a>
<a class="social-btn copy-link-btn" @click.prevent="copyLink" :title="copyButtonText">
<i class="fa fa-fw" :class="copied ? 'fa-check' : 'fa-link'"></i>{{ copyButtonText }}
</a>
</div>
</template>
<script>
Vue.component("share-bar", {
template: "#share-bar",
props: ["user"],
data: () => ({
copied: false
}),
computed: {
profileUrl: function () {
return "https://profile-summary-for-github.com/user/" + this.user.login;
},
shareText: function () {
return this.user.login + "'s GitHub profile - Visualized:";
},
twitterUrl: function () {
return "https://twitter.com/intent/tweet?url=" + this.profileUrl + "&text=" + this.shareText + "&via=javalin_io&related=javalin_io";
},
facebookUrl: function () {
return "https://facebook.com/sharer.php?u=" + this.profileUrl + ""e=" + this.shareText
},
copyButtonText: function () {
return this.copied ? "Copied!" : "Copy Link";
}
},
methods: {
copyLink: function () {
const url = this.profileUrl;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url).then(() => {
this.copied = true;
setTimeout(() => { this.copied = false; }, 2000);
});
} else {
// Fallback for older browsers
const textArea = document.createElement("textarea");
textArea.value = url;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand('copy');
this.copied = true;
setTimeout(() => { this.copied = false; }, 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
document.body.removeChild(textArea);
}
}
}
});
</script>
<style>
.share-bar {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, .04);
font-size: 14px;
text-align: center;
border-radius: 4px;
padding: 5px 10px;
}
.share-bar a {
white-space: nowrap;
margin: 5px 8px;
display: inline-block;
transition: opacity 0.2s;
}
.share-bar a:hover {
opacity: 0.7;
}
.share-bar a i {
color: #0082c8;
}
.copy-link-btn {
cursor: pointer;
}
.copy-link-btn.copied {
color: #27ae60;
}
.copy-link-btn .fa-check {
color: #27ae60;
}
@media (max-width: 480px) {
.share-bar {
width: 100%;
position: relative;
left: 0;
transform: none;
margin-bottom: 20px;
font-size: 12px;
padding: 8px 5px;
}
.share-bar a {
margin: 3px 4px;
font-size: 12px;
}
.share-bar a i {
margin-right: 3px;
}
}
</style>
================================================
FILE: src/main/resources/vue/components/user-info.vue
================================================
<template id="user-info">
<div class="user-info">
<img :src="user.avatarUrl" :alt="user.login">
<div class="details">
<div><i class="fa fa-fw fa-user"></i>{{ user.login }}
<small v-if="user.name">({{ user.name }})</small>
</div>
<div><i class="fa fa-fw fa-database"></i>{{ user.publicRepos }} public repos</div>
<div><i class="fa fa-fw fa-clock-o"></i>Joined GitHub {{ timeAgo }}</div>
<div><i class="fa fa-fw fa-external-link"></i><a :href="user.htmlUrl" target="_blank">View profile on GitHub</a></div>
</div>
<div class="chart-container commits-per-quarter">
<canvas id="quarterCommitCount"></canvas>
</div>
</div>
</template>
<script>
Vue.component("user-info", {
template: "#user-info",
props: ["user", "data"],
computed: {
timeAgo() {
return moment(this.user.createdAt).fromNow()
}
},
mounted() {
lineChart("quarterCommitCount", this.data)
}
});
</script>
<style>
.user-info {
display: flex;
padding-bottom: 40px;
}
.user-info img {
align-self: center;
border-radius: 3px;
width: 175px;
margin-right: 20px;
}
.user-info .details {
display: flex;
flex-direction: column;
justify-content: space-between;
margin-right: 20px;
flex-shrink: 0;
}
.user-info i.fa {
color: rgba(0, 0, 0, 0.67);
margin-right: 5px;
}
.user-info .commits-per-quarter {
flex-grow: 1;
flex-shrink: 1;
position: relative;
}
.user-info .commits-per-quarter::after {
content: "Commits per quarter";
position: absolute;
right: 40px;
bottom: -15px;
font-size: 13px;
}
@media (max-width: 480px) {
.user-info {
flex-direction: column;
align-items: center;
text-align: center;
}
.user-info img {
width: 120px;
margin-right: 0;
margin-bottom: 15px;
}
.user-info .details {
margin-right: 0;
margin-bottom: 15px;
}
.user-info .commits-per-quarter {
display: none;
}
}
</style>
================================================
FILE: src/main/resources/vue/layout.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<title>Profile Summary For GitHub</title>
<link rel="icon" href="/favicon.png">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Visualize your GitHub profile with beautiful charts and statistics. Analyze commits, languages, and repository activity in an interactive dashboard.">
<meta property="og:title" content="GitHub Profile Summary - Visualize Your GitHub Activity">
<meta property="og:site_name" content="GitHub Profile Summary">
<meta property="og:url" content="https://profile-summary-for-github.com">
<meta property="og:description" content="Visualize your GitHub profile with beautiful charts and statistics. Analyze commits, languages, and repository activity in an interactive dashboard.">
<meta property="og:type" content="website">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="GitHub Profile Summary - Visualize Your GitHub Activity">
<meta name="twitter:description" content="Visualize your GitHub profile with beautiful charts and statistics. Analyze commits, languages, and repository activity."
<meta property="og:image" content="https://user-images.githubusercontent.com/1521451/33957306-8e1d8af0-e041-11e7-8e04-3de9e32868ba.PNG">
<meta name="google-site-verification" content="HFqNncqWzEo0ZmlYB0fnuPLSGe48YvR9BDPOrhPnXSM" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Barlow+Semi+Condensed">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/load-awesome@1.1.0/css/square-jelly-box.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.19.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.24.0/min/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
@componentRegistration
</head>
<body>
<main id="main-vue" class="content" v-cloak>
@routeComponent
</main>
<script>
new Vue({el: "#main-vue"});
</script>
</body>
</html>
================================================
FILE: src/main/resources/vue/views/search-view.vue
================================================
<template id="search-view">
<app-frame v-slot="{requestsLeft}">
<div class="search-screen">
<h1>Enter GitHub username</h1>
<div class="search-input-container">
<input type="text" name="q" placeholder="ex. 'tipsy'" v-model="query" autofocus @keydown.enter="search">
</div>
<button @click="search" :disabled="!query.trim()">View Profile</button>
<div v-if="error && error.response.status === 404">
<h4>Can't find user <span class="search-term">{{failedQuery}}</span>. Check spelling.</h4>
</div>
<div v-else-if="failedQuery">
<h4>Can't build profile for <span class="search-term">{{failedQuery}}</span></h4>
<p>
If you are <span class="search-term">{{failedQuery}}</span>, please
<a href="https://github.com/tipsy/profile-summary-for-github">star the repo</a> and try again.
</p>
<p>
The app is running with two GitHub tokens, giving 10 000 requests per hour.
The first 5000 requests can be used to build any profile, while the last 5000 requests are
reserved for users building their own profile. To confirm that you're building your own
profile, we check if you've starred the repository.
</p>
</div>
<div v-if="requestsLeft === 0">
The app is rate limited. Please come back later or build the app locally and use your own tokens.
</div>
</div>
</app-frame>
</template>
<script>
Vue.component("search-view", {
template: "#search-view",
data: () => ({
error: null,
failedQuery: "",
query: ""
}),
methods: {
search() {
this.error = null;
this.failedQuery = null;
axios.get("/api/can-load?user=" + this.query)
.then(() => window.location = "/user/" + this.query)
.catch(error => {
this.error = error;
this.failedQuery = this.query
});
}
},
});
</script>
<style>
.search-screen {
display: flex;
flex-direction: column;
align-items: center;
}
.search-term {
border: 1px solid rgba(0, 0, 0, 0.2);
background: rgba(0, 0, 0, 0.025);
padding: 1px 2px;
font-family: monospace;
font-size: 80%;
}
.search-input-container {
width: 100%;
max-width: 300px;
}
.search-screen input {
width: 100%;
height: 40px;
font-size: 18px;
padding: 0 15px;
border: 2px solid transparent;
border-radius: 4px;
transition: all 0.2s;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.search-screen input:hover {
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}
.search-screen input:focus {
border-color: #0082c8;
box-shadow: 0 2px 8px rgba(0, 130, 200, 0.2);
}
.search-screen button {
margin-top: 20px;
height: 40px;
font-size: 18px;
padding: 0 25px;
border: 0;
line-height: 1;
background: #0082c8;
color: white;
cursor: pointer;
border-radius: 4px;
transition: background 0.2s;
}
.search-screen button:hover:not(:disabled) {
background: #006ba1;
}
.search-screen button:disabled {
background: #ccc;
cursor: not-allowed;
opacity: 0.6;
}
@media (max-width: 480px) {
.search-screen h1 {
font-size: 24px;
margin: 10px 0 20px 0;
}
.search-input-container {
max-width: 100%;
padding: 0 10px;
}
.search-screen input {
font-size: 16px;
height: 44px;
min-width: auto;
}
.search-screen button {
width: 100%;
max-width: 300px;
font-size: 16px;
height: 44px;
}
.search-screen .search-term {
font-size: 90%;
}
.search-screen > div {
padding: 0 20px;
}
}
</style>
================================================
FILE: src/main/resources/vue/views/user-view.vue
================================================
<template id="user-view">
<app-frame v-slot="{requestsLeft}">
<div class="back-button-container">
<a href="/search" class="back-button">
<i class="fa fa-arrow-left"></i> Search Another User
</a>
</div>
<loading-bouncer v-if="!data && !error"></loading-bouncer>
<div v-if="data" class="fade-in">
<share-bar :user="user"></share-bar>
<user-info :user="user" :data="data"></user-info>
<donut-charts :data="data"></donut-charts>
</div>
<div v-if="error" class="error-container">
<div class="error-box">
<i class="fa fa-exclamation-circle error-icon"></i>
<div v-if="error.response.status === 404">
<h3>User Not Found</h3>
<p>We couldn't find a GitHub user with that username. Please check the spelling and try again.</p>
</div>
<div v-else-if="requestsLeft === 0">
<h3>Rate Limited</h3>
<p>The app has reached its GitHub API rate limit. Please come back later or build the app locally with your own tokens.</p>
</div>
<div v-else>
<h3>Something Went Wrong</h3>
<p>An unexpected error occurred. Please try again in a moment.</p>
</div>
<a href="/search" class="error-back-button">← Back to Search</a>
</div>
</div>
</app-frame>
</template>
<script>
Vue.component("user-view", {
template: "#user-view",
data: () => ({
data: null,
user: null,
error: null,
}),
created() {
let userId = this.$javalin.pathParams["user"];
axios.get("/api/user/" + userId).then(response => {
this.data = response.data;
this.user = response.data.user;
}).catch(error => this.error = error);
},
});
</script>
<style>
.back-button-container {
margin-bottom: 20px;
}
.back-button {
display: inline-block;
padding: 8px 16px;
background: rgba(255, 255, 255, 0.8);
border-radius: 4px;
font-size: 14px;
transition: background 0.2s;
}
.back-button:hover {
background: rgba(255, 255, 255, 1);
}
.back-button i {
margin-right: 5px;
}
.error-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 300px;
}
.error-box {
background: white;
padding: 40px;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
text-align: center;
max-width: 500px;
}
.error-icon {
font-size: 48px;
color: #e74c3c;
margin-bottom: 20px;
}
.error-box h3 {
margin: 0 0 10px 0;
color: #333;
}
.error-box p {
margin: 0 0 20px 0;
color: #666;
line-height: 1.6;
}
.error-back-button {
display: inline-block;
padding: 10px 20px;
background: #0082c8;
color: white;
border-radius: 4px;
margin-top: 10px;
transition: background 0.2s;
}
.error-back-button:hover {
background: #006ba1;
}
@media (max-width: 480px) {
.back-button-container {
margin-bottom: 15px;
}
.back-button {
font-size: 13px;
padding: 6px 12px;
}
.error-box {
padding: 30px 20px;
margin: 0 10px;
}
.error-icon {
font-size: 36px;
margin-bottom: 15px;
}
.error-box h3 {
font-size: 20px;
}
.error-box p {
font-size: 15px;
}
.error-back-button {
width: 100%;
max-width: 250px;
}
}
</style>
================================================
FILE: system.properties
================================================
java.runtime.version=17
maven.version=3.9.4
gitextract_e90y_zux/ ├── .gitignore ├── .mvn/ │ └── wrapper/ │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── Dockerfile ├── Documentation/ │ ├── Building.md │ ├── Docker.md │ └── Usage.md ├── LICENSE ├── Procfile ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── src/ │ └── main/ │ ├── kotlin/ │ │ └── app/ │ │ ├── CacheService.kt │ │ ├── Config.kt │ │ ├── GhService.kt │ │ ├── Main.kt │ │ ├── UserProfile.kt │ │ ├── UserService.kt │ │ └── util/ │ │ ├── CommitCountUtil.kt │ │ └── HikariCpDataSource.kt │ └── resources/ │ ├── logback.xml │ └── vue/ │ ├── components/ │ │ ├── _charts.vue │ │ ├── _gtm.vue │ │ ├── _main-styles.vue │ │ ├── app-frame.vue │ │ ├── donut-charts.vue │ │ ├── loading-bouncer.vue │ │ ├── share-bar.vue │ │ └── user-info.vue │ ├── layout.html │ └── views/ │ ├── search-view.vue │ └── user-view.vue └── system.properties
SYMBOL INDEX (3 symbols across 1 files)
FILE: .mvn/wrapper/MavenWrapperDownloader.java
class MavenWrapperDownloader (line 21) | public class MavenWrapperDownloader {
method main (line 48) | public static void main(String args[]) {
method downloadFileFromURL (line 97) | private static void downloadFileFromURL(String urlString, File destina...
Condensed preview — 35 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (98K chars).
[
{
"path": ".gitignore",
"chars": 189,
"preview": "target/\npom.xml.tag\npom.xml.releaseBackup\npom.xml.versionsBackup\npom.xml.next\nrelease.properties\ndependency-reduced-pom."
},
{
"path": ".mvn/wrapper/MavenWrapperDownloader.java",
"chars": 4941,
"preview": "/*\n * Copyright 2007-present the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \""
},
{
"path": ".mvn/wrapper/maven-wrapper.properties",
"chars": 218,
"preview": "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.1/apache-maven-3.6.1-bin.zip\nwrap"
},
{
"path": "Dockerfile",
"chars": 498,
"preview": "FROM maven:3.9-eclipse-temurin-17-alpine as maven-build\nWORKDIR /app\nCOPY . .\nRUN mvn verify\n\nFROM eclipse-temurin:17-jr"
},
{
"path": "Documentation/Building.md",
"chars": 684,
"preview": "\n# Building\n\n*How to setup and compile the project.*\n\n<br>\n\n## Docker\n\nYou can also use **[Docker]** to <br>\ncompile & r"
},
{
"path": "Documentation/Docker.md",
"chars": 1129,
"preview": "\n# Docker\n\n*How to use this project with docker.*\n\n<br>\n\n## Building\n\n*How to compile the source code.*\n\n<br>\n\n- Clone"
},
{
"path": "Documentation/Usage.md",
"chars": 1584,
"preview": "\n# Usage\n\n*How to configure the project.*\n\n<br>\n\n## API Token\n\n*The access token to GitHubs API.*\n\n<br>\n\n### Without\n\nIf"
},
{
"path": "LICENSE",
"chars": 11344,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "Procfile",
"chars": 86,
"preview": "web: java -jar -Xmx256M ./target/profile-summary-for-github-jar-with-dependencies.jar\n"
},
{
"path": "README.md",
"chars": 1191,
"preview": "\n# Profile Summary [![Badge License]][License]\n\n*A tool to visualize your **GitHub** presence.*\n\n<br>\n\n<div align = ce"
},
{
"path": "mvnw",
"chars": 10078,
"preview": "#!/bin/sh\n# ----------------------------------------------------------------------------\n# Licensed to the Apache Softwa"
},
{
"path": "mvnw.cmd",
"chars": 6609,
"preview": "@REM ----------------------------------------------------------------------------\n@REM Licensed to the Apache Software F"
},
{
"path": "pom.xml",
"chars": 5422,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www"
},
{
"path": "src/main/kotlin/app/CacheService.kt",
"chars": 2533,
"preview": "@file:Suppress(\"SqlResolve\")\n\npackage app\n\nimport app.util.HikariCpDataSource\nimport com.fasterxml.jackson.module.kotlin"
},
{
"path": "src/main/kotlin/app/Config.kt",
"chars": 988,
"preview": "package app\n\nobject Config {\n\n // Get port from Heroku, or return null (localhost)\n fun getPort() = getHerokuPrope"
},
{
"path": "src/main/kotlin/app/GhService.kt",
"chars": 3112,
"preview": "package app\n\nimport io.javalin.websocket.WsContext\nimport org.eclipse.egit.github.core.client.GitHubClient\nimport org.ec"
},
{
"path": "src/main/kotlin/app/Main.kt",
"chars": 3068,
"preview": "package app\n\nimport io.javalin.Javalin\nimport io.javalin.compression.CompressionStrategy\nimport io.javalin.http.BadReque"
},
{
"path": "src/main/kotlin/app/UserProfile.kt",
"chars": 471,
"preview": "package app\n\nimport org.eclipse.egit.github.core.User\n\ndata class UserProfile(\n val user: User,\n val quarterCommit"
},
{
"path": "src/main/kotlin/app/UserService.kt",
"chars": 3537,
"preview": "package app\n\nimport app.util.CommitCountUtil\nimport org.eclipse.egit.github.core.Repository\nimport org.eclipse.egit.gith"
},
{
"path": "src/main/kotlin/app/util/CommitCountUtil.kt",
"chars": 1390,
"preview": "package app.util\n\nimport org.eclipse.egit.github.core.Repository\nimport org.eclipse.egit.github.core.RepositoryCommit\nim"
},
{
"path": "src/main/kotlin/app/util/HikariCpDataSource.kt",
"chars": 460,
"preview": "package app.util\n\nimport com.zaxxer.hikari.HikariConfig\nimport com.zaxxer.hikari.HikariDataSource\nimport java.sql.Connec"
},
{
"path": "src/main/resources/logback.xml",
"chars": 559,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleApp"
},
{
"path": "src/main/resources/vue/components/_charts.vue",
"chars": 7058,
"preview": "<script>\n const UNKNOWN_LANGUAGE = \"Unknown\";\n\n function donutChart(objectName, data) {\n let canvas = docum"
},
{
"path": "src/main/resources/vue/components/_gtm.vue",
"chars": 383,
"preview": "<script>\n (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\n new Date().getTime(),event:'gtm.js'});var f="
},
{
"path": "src/main/resources/vue/components/_main-styles.vue",
"chars": 1123,
"preview": "<style>\n * {\n font-family: 'Barlow Semi Condensed', sans-serif;\n outline: 0;\n box-sizing: border"
},
{
"path": "src/main/resources/vue/components/app-frame.vue",
"chars": 2019,
"preview": "<template id=\"app-frame\">\n <div>\n <main class=\"main-content\">\n <slot :requests-left=\"requestsLeft\">"
},
{
"path": "src/main/resources/vue/components/donut-charts.vue",
"chars": 2864,
"preview": "<template id=\"donut-charts\">\n <div class=\"charts\">\n <div class=\"chart-row\">\n <div class=\"chart-cont"
},
{
"path": "src/main/resources/vue/components/loading-bouncer.vue",
"chars": 909,
"preview": "<template id=\"loading-bouncer\">\n <div class=\"loading-bouncer\" style=\"opacity: 0; animation: fade-in 0.2s linear 0.5s "
},
{
"path": "src/main/resources/vue/components/share-bar.vue",
"chars": 3879,
"preview": "<template id=\"share-bar\">\n <div class=\"share-bar\">\n <a class=\"social-btn\" :href=\"twitterUrl\" rel=\"nofollow\" ti"
},
{
"path": "src/main/resources/vue/components/user-info.vue",
"chars": 2391,
"preview": "<template id=\"user-info\">\n <div class=\"user-info\">\n <img :src=\"user.avatarUrl\" :alt=\"user.login\">\n <div"
},
{
"path": "src/main/resources/vue/layout.html",
"chars": 2579,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Profile Summary For GitHub</title>\n <link rel=\"icon\" h"
},
{
"path": "src/main/resources/vue/views/search-view.vue",
"chars": 4399,
"preview": "<template id=\"search-view\">\n <app-frame v-slot=\"{requestsLeft}\">\n <div class=\"search-screen\">\n <h1>"
},
{
"path": "src/main/resources/vue/views/user-view.vue",
"chars": 4021,
"preview": "<template id=\"user-view\">\n <app-frame v-slot=\"{requestsLeft}\">\n <div class=\"back-button-container\">\n "
},
{
"path": "system.properties",
"chars": 45,
"preview": "java.runtime.version=17\nmaven.version=3.9.4\n\n"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the tipsy/profile-summary-for-github GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 35 files (89.6 KB), approximately 22.7k tokens, and a symbol index with 3 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.