Full Code of jc9108/eternity for AI

main 6fdb4b2e78ba cached
69 files
183.9 KB
50.1k tokens
48 symbols
1 requests
Download .txt
Showing preview only (200K chars total). Download the full file or copy to clipboard to get everything.
Repository: jc9108/eternity
Branch: main
Commit: 6fdb4b2e78ba
Files: 69
Total size: 183.9 KB

Directory structure:
gitextract_1o2zynwc/

├── .git/
│   ├── HEAD
│   ├── config
│   ├── description
│   ├── hooks/
│   │   ├── applypatch-msg.sample
│   │   ├── commit-msg.sample
│   │   ├── fsmonitor-watchman.sample
│   │   ├── post-update.sample
│   │   ├── pre-applypatch.sample
│   │   ├── pre-commit.sample
│   │   ├── pre-merge-commit.sample
│   │   ├── pre-push.sample
│   │   ├── pre-rebase.sample
│   │   ├── pre-receive.sample
│   │   ├── prepare-commit-msg.sample
│   │   ├── push-to-checkout.sample
│   │   ├── sendemail-validate.sample
│   │   └── update.sample
│   ├── index
│   ├── info/
│   │   └── exclude
│   ├── logs/
│   │   ├── HEAD
│   │   └── refs/
│   │       ├── heads/
│   │       │   └── main
│   │       └── remotes/
│   │           └── origin/
│   │               └── HEAD
│   ├── objects/
│   │   └── pack/
│   │       ├── pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.idx
│   │       ├── pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.pack
│   │       ├── pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.promisor
│   │       └── pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.rev
│   ├── packed-refs
│   ├── refs/
│   │   ├── heads/
│   │   │   └── main
│   │   └── remotes/
│   │       └── origin/
│   │           └── HEAD
│   └── shallow
├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── SPONSORS.md
├── backend/
│   ├── .npmrc
│   ├── controller/
│   │   └── server.mjs
│   ├── model/
│   │   ├── cryptr.mjs
│   │   ├── email.mjs
│   │   ├── file.mjs
│   │   ├── firebase.mjs
│   │   ├── logger.mjs
│   │   ├── reddit.mjs
│   │   ├── sql.mjs
│   │   ├── user.mjs
│   │   └── utils.mjs
│   ├── nodemon.json
│   └── package.json
├── frontend/
│   ├── .npmrc
│   ├── package.json
│   ├── source/
│   │   ├── app.html
│   │   ├── components/
│   │   │   ├── access.svelte
│   │   │   ├── footer.svelte
│   │   │   ├── landing.svelte
│   │   │   ├── loading.svelte
│   │   │   ├── navbar.svelte
│   │   │   └── unlock.svelte
│   │   ├── global.d.ts
│   │   ├── globals.js
│   │   ├── hooks.js
│   │   ├── routes/
│   │   │   ├── __error.svelte
│   │   │   ├── __layout.svelte
│   │   │   ├── about.svelte
│   │   │   └── index.svelte
│   │   └── utils.js
│   ├── static/
│   │   └── style.css
│   ├── svelte.config.js
│   └── vite.config.js
└── run.sh

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

================================================
FILE: .git/HEAD
================================================
ref: refs/heads/main


================================================
FILE: .git/config
================================================
[core]
	repositoryformatversion = 1
	filemode = true
	bare = false
	logallrefupdates = true
[remote "origin"]
	url = https://github.com/jc9108/eternity
	tagOpt = --no-tags
	fetch = +refs/heads/main:refs/remotes/origin/main
	promisor = true
	partialclonefilter = blob:limit=1048576
[branch "main"]
	remote = origin
	merge = refs/heads/main


================================================
FILE: .git/description
================================================
Unnamed repository; edit this file 'description' to name the repository.


================================================
FILE: .git/hooks/applypatch-msg.sample
================================================
#!/bin/sh
#
# An example hook script to check the commit log message taken by
# applypatch from an e-mail message.
#
# The hook should exit with non-zero status after issuing an
# appropriate message if it wants to stop the commit.  The hook is
# allowed to edit the commit message file.
#
# To enable this hook, rename this file to "applypatch-msg".

. git-sh-setup
commitmsg="$(git rev-parse --git-path hooks/commit-msg)"
test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"}
:


================================================
FILE: .git/hooks/commit-msg.sample
================================================
#!/bin/sh
#
# An example hook script to check the commit log message.
# Called by "git commit" with one argument, the name of the file
# that has the commit message.  The hook should exit with non-zero
# status after issuing an appropriate message if it wants to stop the
# commit.  The hook is allowed to edit the commit message file.
#
# To enable this hook, rename this file to "commit-msg".

# Uncomment the below to add a Signed-off-by line to the message.
# Doing this in a hook is a bad idea in general, but the prepare-commit-msg
# hook is more suited to it.
#
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"

# This example catches duplicate Signed-off-by lines.

test "" = "$(grep '^Signed-off-by: ' "$1" |
	 sort | uniq -c | sed -e '/^[ 	]*1[ 	]/d')" || {
	echo >&2 Duplicate Signed-off-by lines.
	exit 1
}


================================================
FILE: .git/hooks/fsmonitor-watchman.sample
================================================
#!/usr/bin/perl

use strict;
use warnings;
use IPC::Open2;

# An example hook script to integrate Watchman
# (https://facebook.github.io/watchman/) with git to speed up detecting
# new and modified files.
#
# The hook is passed a version (currently 2) and last update token
# formatted as a string and outputs to stdout a new update token and
# all files that have been modified since the update token. Paths must
# be relative to the root of the working tree and separated by a single NUL.
#
# To enable this hook, rename this file to "query-watchman" and set
# 'git config core.fsmonitor .git/hooks/query-watchman'
#
my ($version, $last_update_token) = @ARGV;

# Uncomment for debugging
# print STDERR "$0 $version $last_update_token\n";

# Check the hook interface version
if ($version ne 2) {
	die "Unsupported query-fsmonitor hook version '$version'.\n" .
	    "Falling back to scanning...\n";
}

my $git_work_tree = get_working_dir();

my $retry = 1;

my $json_pkg;
eval {
	require JSON::XS;
	$json_pkg = "JSON::XS";
	1;
} or do {
	require JSON::PP;
	$json_pkg = "JSON::PP";
};

launch_watchman();

sub launch_watchman {
	my $o = watchman_query();
	if (is_work_tree_watched($o)) {
		output_result($o->{clock}, @{$o->{files}});
	}
}

sub output_result {
	my ($clockid, @files) = @_;

	# Uncomment for debugging watchman output
	# open (my $fh, ">", ".git/watchman-output.out");
	# binmode $fh, ":utf8";
	# print $fh "$clockid\n@files\n";
	# close $fh;

	binmode STDOUT, ":utf8";
	print $clockid;
	print "\0";
	local $, = "\0";
	print @files;
}

sub watchman_clock {
	my $response = qx/watchman clock "$git_work_tree"/;
	die "Failed to get clock id on '$git_work_tree'.\n" .
		"Falling back to scanning...\n" if $? != 0;

	return $json_pkg->new->utf8->decode($response);
}

sub watchman_query {
	my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty')
	or die "open2() failed: $!\n" .
	"Falling back to scanning...\n";

	# In the query expression below we're asking for names of files that
	# changed since $last_update_token but not from the .git folder.
	#
	# To accomplish this, we're using the "since" generator to use the
	# recency index to select candidate nodes and "fields" to limit the
	# output to file names only. Then we're using the "expression" term to
	# further constrain the results.
	my $last_update_line = "";
	if (substr($last_update_token, 0, 1) eq "c") {
		$last_update_token = "\"$last_update_token\"";
		$last_update_line = qq[\n"since": $last_update_token,];
	}
	my $query = <<"	END";
		["query", "$git_work_tree", {$last_update_line
			"fields": ["name"],
			"expression": ["not", ["dirname", ".git"]]
		}]
	END

	# Uncomment for debugging the watchman query
	# open (my $fh, ">", ".git/watchman-query.json");
	# print $fh $query;
	# close $fh;

	print CHLD_IN $query;
	close CHLD_IN;
	my $response = do {local $/; <CHLD_OUT>};

	# Uncomment for debugging the watch response
	# open ($fh, ">", ".git/watchman-response.json");
	# print $fh $response;
	# close $fh;

	die "Watchman: command returned no output.\n" .
	"Falling back to scanning...\n" if $response eq "";
	die "Watchman: command returned invalid output: $response\n" .
	"Falling back to scanning...\n" unless $response =~ /^\{/;

	return $json_pkg->new->utf8->decode($response);
}

sub is_work_tree_watched {
	my ($output) = @_;
	my $error = $output->{error};
	if ($retry > 0 and $error and $error =~ m/unable to resolve root .* directory (.*) is not watched/) {
		$retry--;
		my $response = qx/watchman watch "$git_work_tree"/;
		die "Failed to make watchman watch '$git_work_tree'.\n" .
		    "Falling back to scanning...\n" if $? != 0;
		$output = $json_pkg->new->utf8->decode($response);
		$error = $output->{error};
		die "Watchman: $error.\n" .
		"Falling back to scanning...\n" if $error;

		# Uncomment for debugging watchman output
		# open (my $fh, ">", ".git/watchman-output.out");
		# close $fh;

		# Watchman will always return all files on the first query so
		# return the fast "everything is dirty" flag to git and do the
		# Watchman query just to get it over with now so we won't pay
		# the cost in git to look up each individual file.
		my $o = watchman_clock();
		$error = $output->{error};

		die "Watchman: $error.\n" .
		"Falling back to scanning...\n" if $error;

		output_result($o->{clock}, ("/"));
		$last_update_token = $o->{clock};

		eval { launch_watchman() };
		return 0;
	}

	die "Watchman: $error.\n" .
	"Falling back to scanning...\n" if $error;

	return 1;
}

sub get_working_dir {
	my $working_dir;
	if ($^O =~ 'msys' || $^O =~ 'cygwin') {
		$working_dir = Win32::GetCwd();
		$working_dir =~ tr/\\/\//;
	} else {
		require Cwd;
		$working_dir = Cwd::cwd();
	}

	return $working_dir;
}


================================================
FILE: .git/hooks/post-update.sample
================================================
#!/bin/sh
#
# An example hook script to prepare a packed repository for use over
# dumb transports.
#
# To enable this hook, rename this file to "post-update".

exec git update-server-info


================================================
FILE: .git/hooks/pre-applypatch.sample
================================================
#!/bin/sh
#
# An example hook script to verify what is about to be committed
# by applypatch from an e-mail message.
#
# The hook should exit with non-zero status after issuing an
# appropriate message if it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-applypatch".

. git-sh-setup
precommit="$(git rev-parse --git-path hooks/pre-commit)"
test -x "$precommit" && exec "$precommit" ${1+"$@"}
:


================================================
FILE: .git/hooks/pre-commit.sample
================================================
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

if git rev-parse --verify HEAD >/dev/null 2>&1
then
	against=HEAD
else
	# Initial commit: diff against an empty tree object
	against=$(git hash-object -t tree /dev/null)
fi

# If you want to allow non-ASCII filenames set this variable to true.
allownonascii=$(git config --type=bool hooks.allownonascii)

# Redirect output to stderr.
exec 1>&2

# Cross platform projects tend to avoid non-ASCII filenames; prevent
# them from being added to the repository. We exploit the fact that the
# printable range starts at the space character and ends with tilde.
if [ "$allownonascii" != "true" ] &&
	# Note that the use of brackets around a tr range is ok here, (it's
	# even required, for portability to Solaris 10's /usr/bin/tr), since
	# the square bracket bytes happen to fall in the designated range.
	test $(git diff-index --cached --name-only --diff-filter=A -z $against |
	  LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
then
	cat <<\EOF
Error: Attempt to add a non-ASCII file name.

This can cause problems if you want to work with people on other platforms.

To be portable it is advisable to rename the file.

If you know what you are doing you can disable this check using:

  git config hooks.allownonascii true
EOF
	exit 1
fi

# If there are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --


================================================
FILE: .git/hooks/pre-merge-commit.sample
================================================
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git merge" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message to
# stderr if it wants to stop the merge commit.
#
# To enable this hook, rename this file to "pre-merge-commit".

. git-sh-setup
test -x "$GIT_DIR/hooks/pre-commit" &&
        exec "$GIT_DIR/hooks/pre-commit"
:


================================================
FILE: .git/hooks/pre-push.sample
================================================
#!/bin/sh

# An example hook script to verify what is about to be pushed.  Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed.  If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
#   <local ref> <local oid> <remote ref> <remote oid>
#
# This sample shows how to prevent push of commits where the log message starts
# with "WIP" (work in progress).

remote="$1"
url="$2"

zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')

while read local_ref local_oid remote_ref remote_oid
do
	if test "$local_oid" = "$zero"
	then
		# Handle delete
		:
	else
		if test "$remote_oid" = "$zero"
		then
			# New branch, examine all commits
			range="$local_oid"
		else
			# Update to existing branch, examine new commits
			range="$remote_oid..$local_oid"
		fi

		# Check for WIP commit
		commit=$(git rev-list -n 1 --grep '^WIP' "$range")
		if test -n "$commit"
		then
			echo >&2 "Found WIP commit in $local_ref, not pushing"
			exit 1
		fi
	fi
done

exit 0


================================================
FILE: .git/hooks/pre-rebase.sample
================================================
#!/bin/sh
#
# Copyright (c) 2006, 2008 Junio C Hamano
#
# The "pre-rebase" hook is run just before "git rebase" starts doing
# its job, and can prevent the command from running by exiting with
# non-zero status.
#
# The hook is called with the following parameters:
#
# $1 -- the upstream the series was forked from.
# $2 -- the branch being rebased (or empty when rebasing the current branch).
#
# This sample shows how to prevent topic branches that are already
# merged to 'next' branch from getting rebased, because allowing it
# would result in rebasing already published history.

publish=next
basebranch="$1"
if test "$#" = 2
then
	topic="refs/heads/$2"
else
	topic=`git symbolic-ref HEAD` ||
	exit 0 ;# we do not interrupt rebasing detached HEAD
fi

case "$topic" in
refs/heads/??/*)
	;;
*)
	exit 0 ;# we do not interrupt others.
	;;
esac

# Now we are dealing with a topic branch being rebased
# on top of master.  Is it OK to rebase it?

# Does the topic really exist?
git show-ref -q "$topic" || {
	echo >&2 "No such branch $topic"
	exit 1
}

# Is topic fully merged to master?
not_in_master=`git rev-list --pretty=oneline ^master "$topic"`
if test -z "$not_in_master"
then
	echo >&2 "$topic is fully merged to master; better remove it."
	exit 1 ;# we could allow it, but there is no point.
fi

# Is topic ever merged to next?  If so you should not be rebasing it.
only_next_1=`git rev-list ^master "^$topic" ${publish} | sort`
only_next_2=`git rev-list ^master           ${publish} | sort`
if test "$only_next_1" = "$only_next_2"
then
	not_in_topic=`git rev-list "^$topic" master`
	if test -z "$not_in_topic"
	then
		echo >&2 "$topic is already up to date with master"
		exit 1 ;# we could allow it, but there is no point.
	else
		exit 0
	fi
else
	not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"`
	/usr/bin/perl -e '
		my $topic = $ARGV[0];
		my $msg = "* $topic has commits already merged to public branch:\n";
		my (%not_in_next) = map {
			/^([0-9a-f]+) /;
			($1 => 1);
		} split(/\n/, $ARGV[1]);
		for my $elem (map {
				/^([0-9a-f]+) (.*)$/;
				[$1 => $2];
			} split(/\n/, $ARGV[2])) {
			if (!exists $not_in_next{$elem->[0]}) {
				if ($msg) {
					print STDERR $msg;
					undef $msg;
				}
				print STDERR " $elem->[1]\n";
			}
		}
	' "$topic" "$not_in_next" "$not_in_master"
	exit 1
fi

<<\DOC_END

This sample hook safeguards topic branches that have been
published from being rewound.

The workflow assumed here is:

 * Once a topic branch forks from "master", "master" is never
   merged into it again (either directly or indirectly).

 * Once a topic branch is fully cooked and merged into "master",
   it is deleted.  If you need to build on top of it to correct
   earlier mistakes, a new topic branch is created by forking at
   the tip of the "master".  This is not strictly necessary, but
   it makes it easier to keep your history simple.

 * Whenever you need to test or publish your changes to topic
   branches, merge them into "next" branch.

The script, being an example, hardcodes the publish branch name
to be "next", but it is trivial to make it configurable via
$GIT_DIR/config mechanism.

With this workflow, you would want to know:

(1) ... if a topic branch has ever been merged to "next".  Young
    topic branches can have stupid mistakes you would rather
    clean up before publishing, and things that have not been
    merged into other branches can be easily rebased without
    affecting other people.  But once it is published, you would
    not want to rewind it.

(2) ... if a topic branch has been fully merged to "master".
    Then you can delete it.  More importantly, you should not
    build on top of it -- other people may already want to
    change things related to the topic as patches against your
    "master", so if you need further changes, it is better to
    fork the topic (perhaps with the same name) afresh from the
    tip of "master".

Let's look at this example:

		   o---o---o---o---o---o---o---o---o---o "next"
		  /       /           /           /
		 /   a---a---b A     /           /
		/   /               /           /
	       /   /   c---c---c---c B         /
	      /   /   /             \         /
	     /   /   /   b---b C     \       /
	    /   /   /   /             \     /
    ---o---o---o---o---o---o---o---o---o---o---o "master"


A, B and C are topic branches.

 * A has one fix since it was merged up to "next".

 * B has finished.  It has been fully merged up to "master" and "next",
   and is ready to be deleted.

 * C has not merged to "next" at all.

We would want to allow C to be rebased, refuse A, and encourage
B to be deleted.

To compute (1):

	git rev-list ^master ^topic next
	git rev-list ^master        next

	if these match, topic has not merged in next at all.

To compute (2):

	git rev-list master..topic

	if this is empty, it is fully merged to "master".

DOC_END


================================================
FILE: .git/hooks/pre-receive.sample
================================================
#!/bin/sh
#
# An example hook script to make use of push options.
# The example simply echoes all push options that start with 'echoback='
# and rejects all pushes when the "reject" push option is used.
#
# To enable this hook, rename this file to "pre-receive".

if test -n "$GIT_PUSH_OPTION_COUNT"
then
	i=0
	while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
	do
		eval "value=\$GIT_PUSH_OPTION_$i"
		case "$value" in
		echoback=*)
			echo "echo from the pre-receive-hook: ${value#*=}" >&2
			;;
		reject)
			exit 1
		esac
		i=$((i + 1))
	done
fi


================================================
FILE: .git/hooks/prepare-commit-msg.sample
================================================
#!/bin/sh
#
# An example hook script to prepare the commit log message.
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source.  The hook's purpose is to edit the commit
# message file.  If the hook fails with a non-zero status,
# the commit is aborted.
#
# To enable this hook, rename this file to "prepare-commit-msg".

# This hook includes three examples. The first one removes the
# "# Please enter the commit message..." help message.
#
# The second includes the output of "git diff --name-status -r"
# into the message, just before the "git status" output.  It is
# commented because it doesn't cope with --amend or with squashed
# commits.
#
# The third example adds a Signed-off-by line to the message, that can
# still be edited.  This is rarely a good idea.

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3

/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE"

# case "$COMMIT_SOURCE,$SHA1" in
#  ,|template,)
#    /usr/bin/perl -i.bak -pe '
#       print "\n" . `git diff --cached --name-status -r`
# 	 if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;;
#  *) ;;
# esac

# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE"
# if test -z "$COMMIT_SOURCE"
# then
#   /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE"
# fi


================================================
FILE: .git/hooks/push-to-checkout.sample
================================================
#!/bin/sh

# An example hook script to update a checked-out tree on a git push.
#
# This hook is invoked by git-receive-pack(1) when it reacts to git
# push and updates reference(s) in its repository, and when the push
# tries to update the branch that is currently checked out and the
# receive.denyCurrentBranch configuration variable is set to
# updateInstead.
#
# By default, such a push is refused if the working tree and the index
# of the remote repository has any difference from the currently
# checked out commit; when both the working tree and the index match
# the current commit, they are updated to match the newly pushed tip
# of the branch. This hook is to be used to override the default
# behaviour; however the code below reimplements the default behaviour
# as a starting point for convenient modification.
#
# The hook receives the commit with which the tip of the current
# branch is going to be updated:
commit=$1

# It can exit with a non-zero status to refuse the push (when it does
# so, it must not modify the index or the working tree).
die () {
	echo >&2 "$*"
	exit 1
}

# Or it can make any necessary changes to the working tree and to the
# index to bring them to the desired state when the tip of the current
# branch is updated to the new commit, and exit with a zero status.
#
# For example, the hook can simply run git read-tree -u -m HEAD "$1"
# in order to emulate git fetch that is run in the reverse direction
# with git push, as the two-tree form of git read-tree -u -m is
# essentially the same as git switch or git checkout that switches
# branches while keeping the local changes in the working tree that do
# not interfere with the difference between the branches.

# The below is a more-or-less exact translation to shell of the C code
# for the default behaviour for git's push-to-checkout hook defined in
# the push_to_deploy() function in builtin/receive-pack.c.
#
# Note that the hook will be executed from the repository directory,
# not from the working tree, so if you want to perform operations on
# the working tree, you will have to adapt your code accordingly, e.g.
# by adding "cd .." or using relative paths.

if ! git update-index -q --ignore-submodules --refresh
then
	die "Up-to-date check failed"
fi

if ! git diff-files --quiet --ignore-submodules --
then
	die "Working directory has unstaged changes"
fi

# This is a rough translation of:
#
#   head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX
if git cat-file -e HEAD 2>/dev/null
then
	head=HEAD
else
	head=$(git hash-object -t tree --stdin </dev/null)
fi

if ! git diff-index --quiet --cached --ignore-submodules $head --
then
	die "Working directory has staged changes"
fi

if ! git read-tree -u -m "$commit"
then
	die "Could not update working tree to new HEAD"
fi


================================================
FILE: .git/hooks/sendemail-validate.sample
================================================
#!/bin/sh

# An example hook script to validate a patch (and/or patch series) before
# sending it via email.
#
# The hook should exit with non-zero status after issuing an appropriate
# message if it wants to prevent the email(s) from being sent.
#
# To enable this hook, rename this file to "sendemail-validate".
#
# By default, it will only check that the patch(es) can be applied on top of
# the default upstream branch without conflicts in a secondary worktree. After
# validation (successful or not) of the last patch of a series, the worktree
# will be deleted.
#
# The following config variables can be set to change the default remote and
# remote ref that are used to apply the patches against:
#
#   sendemail.validateRemote (default: origin)
#   sendemail.validateRemoteRef (default: HEAD)
#
# Replace the TODO placeholders with appropriate checks according to your
# needs.

validate_cover_letter () {
	file="$1"
	# TODO: Replace with appropriate checks (e.g. spell checking).
	true
}

validate_patch () {
	file="$1"
	# Ensure that the patch applies without conflicts.
	git am -3 "$file" || return
	# TODO: Replace with appropriate checks for this patch
	# (e.g. checkpatch.pl).
	true
}

validate_series () {
	# TODO: Replace with appropriate checks for the whole series
	# (e.g. quick build, coding style checks, etc.).
	true
}

# main -------------------------------------------------------------------------

if test "$GIT_SENDEMAIL_FILE_COUNTER" = 1
then
	remote=$(git config --default origin --get sendemail.validateRemote) &&
	ref=$(git config --default HEAD --get sendemail.validateRemoteRef) &&
	worktree=$(mktemp --tmpdir -d sendemail-validate.XXXXXXX) &&
	git worktree add -fd --checkout "$worktree" "refs/remotes/$remote/$ref" &&
	git config --replace-all sendemail.validateWorktree "$worktree"
else
	worktree=$(git config --get sendemail.validateWorktree)
fi || {
	echo "sendemail-validate: error: failed to prepare worktree" >&2
	exit 1
}

unset GIT_DIR GIT_WORK_TREE
cd "$worktree" &&

if grep -q "^diff --git " "$1"
then
	validate_patch "$1"
else
	validate_cover_letter "$1"
fi &&

if test "$GIT_SENDEMAIL_FILE_COUNTER" = "$GIT_SENDEMAIL_FILE_TOTAL"
then
	git config --unset-all sendemail.validateWorktree &&
	trap 'git worktree remove -ff "$worktree"' EXIT &&
	validate_series
fi


================================================
FILE: .git/hooks/update.sample
================================================
#!/bin/sh
#
# An example hook script to block unannotated tags from entering.
# Called by "git receive-pack" with arguments: refname sha1-old sha1-new
#
# To enable this hook, rename this file to "update".
#
# Config
# ------
# hooks.allowunannotated
#   This boolean sets whether unannotated tags will be allowed into the
#   repository.  By default they won't be.
# hooks.allowdeletetag
#   This boolean sets whether deleting tags will be allowed in the
#   repository.  By default they won't be.
# hooks.allowmodifytag
#   This boolean sets whether a tag may be modified after creation. By default
#   it won't be.
# hooks.allowdeletebranch
#   This boolean sets whether deleting branches will be allowed in the
#   repository.  By default they won't be.
# hooks.denycreatebranch
#   This boolean sets whether remotely creating branches will be denied
#   in the repository.  By default this is allowed.
#

# --- Command line
refname="$1"
oldrev="$2"
newrev="$3"

# --- Safety check
if [ -z "$GIT_DIR" ]; then
	echo "Don't run this script from the command line." >&2
	echo " (if you want, you could supply GIT_DIR then run" >&2
	echo "  $0 <ref> <oldrev> <newrev>)" >&2
	exit 1
fi

if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then
	echo "usage: $0 <ref> <oldrev> <newrev>" >&2
	exit 1
fi

# --- Config
allowunannotated=$(git config --type=bool hooks.allowunannotated)
allowdeletebranch=$(git config --type=bool hooks.allowdeletebranch)
denycreatebranch=$(git config --type=bool hooks.denycreatebranch)
allowdeletetag=$(git config --type=bool hooks.allowdeletetag)
allowmodifytag=$(git config --type=bool hooks.allowmodifytag)

# check for no description
projectdesc=$(sed -e '1q' "$GIT_DIR/description")
case "$projectdesc" in
"Unnamed repository"* | "")
	echo "*** Project description file hasn't been set" >&2
	exit 1
	;;
esac

# --- Check types
# if $newrev is 0000...0000, it's a commit to delete a ref.
zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')
if [ "$newrev" = "$zero" ]; then
	newrev_type=delete
else
	newrev_type=$(git cat-file -t $newrev)
fi

case "$refname","$newrev_type" in
	refs/tags/*,commit)
		# un-annotated tag
		short_refname=${refname##refs/tags/}
		if [ "$allowunannotated" != "true" ]; then
			echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2
			echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2
			exit 1
		fi
		;;
	refs/tags/*,delete)
		# delete tag
		if [ "$allowdeletetag" != "true" ]; then
			echo "*** Deleting a tag is not allowed in this repository" >&2
			exit 1
		fi
		;;
	refs/tags/*,tag)
		# annotated tag
		if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1
		then
			echo "*** Tag '$refname' already exists." >&2
			echo "*** Modifying a tag is not allowed in this repository." >&2
			exit 1
		fi
		;;
	refs/heads/*,commit)
		# branch
		if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then
			echo "*** Creating a branch is not allowed in this repository" >&2
			exit 1
		fi
		;;
	refs/heads/*,delete)
		# delete branch
		if [ "$allowdeletebranch" != "true" ]; then
			echo "*** Deleting a branch is not allowed in this repository" >&2
			exit 1
		fi
		;;
	refs/remotes/*,commit)
		# tracking branch
		;;
	refs/remotes/*,delete)
		# delete tracking branch
		if [ "$allowdeletebranch" != "true" ]; then
			echo "*** Deleting a tracking branch is not allowed in this repository" >&2
			exit 1
		fi
		;;
	*)
		# Anything else (is there anything else?)
		echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2
		exit 1
		;;
esac

# --- Finished
exit 0


================================================
FILE: .git/info/exclude
================================================
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~


================================================
FILE: .git/logs/HEAD
================================================
0000000000000000000000000000000000000000 6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 appuser <appuser@7c99e0e64a07.(none)> 1778536176 +0000	clone: from https://github.com/jc9108/eternity


================================================
FILE: .git/logs/refs/heads/main
================================================
0000000000000000000000000000000000000000 6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 appuser <appuser@7c99e0e64a07.(none)> 1778536176 +0000	clone: from https://github.com/jc9108/eternity


================================================
FILE: .git/logs/refs/remotes/origin/HEAD
================================================
0000000000000000000000000000000000000000 6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 appuser <appuser@7c99e0e64a07.(none)> 1778536176 +0000	clone: from https://github.com/jc9108/eternity


================================================
FILE: .git/objects/pack/pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.promisor
================================================
6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 refs/heads/main


================================================
FILE: .git/packed-refs
================================================
# pack-refs with: peeled fully-peeled sorted 
6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 refs/remotes/origin/main


================================================
FILE: .git/refs/heads/main
================================================
6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04


================================================
FILE: .git/refs/remotes/origin/HEAD
================================================
ref: refs/remotes/origin/main


================================================
FILE: .git/shallow
================================================
6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04


================================================
FILE: .gitattributes
================================================
# https://github.com/github/linguist/blob/master/lib/linguist/languages.yml

sql.mjs linguist-detectable=true
sql.mjs linguist-language=SQL


================================================
FILE: .gitignore
================================================
# ignore
\#*
.*
node_modules/
backups/
logs/
tempfiles/
build/

# keep
!.git*
!.*rc


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

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

                            Preamble

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

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

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

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

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

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

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

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

                       TERMS AND CONDITIONS

  0. Definitions.

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

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

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

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

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

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

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

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

  1. Source Code.

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

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

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

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

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

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

  2. Basic Permissions.

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

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

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

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

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

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

  4. Conveying Verbatim Copies.

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

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

  5. Conveying Modified Source Versions.

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

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

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

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

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

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

  6. Conveying Non-Source Forms.

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

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

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

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

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

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

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

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

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

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

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

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

  7. Additional Terms.

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

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

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

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

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

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

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

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

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

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

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

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

  8. Termination.

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

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

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

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

  9. Acceptance Not Required for Having Copies.

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

  10. Automatic Licensing of Downstream Recipients.

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

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

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

  11. Patents.

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

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

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

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

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

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

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

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

  12. No Surrender of Others' Freedom.

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

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

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

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

  14. Revised Versions of this License.

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

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

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

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

  15. Disclaimer of Warranty.

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

  16. Limitation of Liability.

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

  17. Interpretation of Sections 15 and 16.

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

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

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

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

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

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

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

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

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

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

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


================================================
FILE: README.md
================================================
# [eternity](https://eternity.portals.sh)

bypass Reddit's 1000-item listing limits by externally storing your Reddit items (saved, created, upvoted, downvoted, hidden) in your own database

- features::
	- new items auto-sync
	- synced items not affected by Reddit deletion
	- search for items
	- filter by subreddit
	- unsave/delete/unvote/unhide items from Reddit directly on eternity
	- import csv data from [Reddit data request](https://www.reddit.com/settings/data-request)
	- export data as json
- [demo](https://www.youtube.com/watch?v=4pxXM98ewIc)
- [Firebase setup guide](https://www.youtube.com/watch?v=KPxppovc56A)
- [selfhosted version](https://github.com/jc9108/expanse)


================================================
FILE: SPONSORS.md
================================================
# sponsors

support this project by becoming a [sponsor](https://github.com/sponsors/jc9108)

- big thanks to::
	- [jmorlin](https://github.com/jmorlin)
	- [rubik11](https://github.com/rubik11)


================================================
FILE: backend/.npmrc
================================================
engine-strict=true
unsafe-perm=true
save-exact=true


================================================
FILE: backend/controller/server.mjs
================================================
const backend = process.cwd();
import * as dotenv from "dotenv";
dotenv.config({
	path: `${backend}/.env_${process.env.RUN}`
});

const file = await import(`${backend}/model/file.mjs`);
const sql = await import(`${backend}/model/sql.mjs`);
const firebase = await import(`${backend}/model/firebase.mjs`);
const cryptr = await import(`${backend}/model/cryptr.mjs`);
const user = await import(`${backend}/model/user.mjs`);
const email = await import(`${backend}/model/email.mjs`);
const utils = await import(`${backend}/model/utils.mjs`);

import * as socket_io_server from "socket.io";
import * as socket_io_client from "socket.io-client";
import express from "express";
import http from "http";
import cookie_session from "cookie-session";
import passport from "passport";
import passport_reddit from "passport-reddit";
import crypto from "crypto";
import filesystem from "fs";
import fileupload from "express-fileupload";

let domain_request_info = null;

const app = express();
const server = http.createServer(app);
const io = new socket_io_server.Server(server, {
	cors: (process.env.RUN == "dev" ? {origin: "*"} : null),
	maxHttpBufferSize: 1000000 // 1mb in bytes
});
const app_socket = socket_io_client.io("http://localhost:1026", {
	autoConnect: false,
	reconnect: true,
	extraHeaders: {
		app: "eternity",
		secret: process.env.LOCAL_SOCKETS_SECRET
	}
});

const frontend = backend.replace("backend", "frontend");

const allowed_users = new Set(process.env.ALLOWED_USERS.split(", "));
const denied_users = new Set(process.env.DENIED_USERS.split(", "));

await file.init();
await sql.init_db();
sql.cycle_backup_db();
await user.fill_usernames_to_socket_ids();
user.cycle_update_all(io);

app.use(fileupload({
	limits: {
		fileSize: 3072 // 3kb in binary bytes. firebase service account key files should be ~2.35kb
	}
}));

app.use("/", express.static(`${frontend}/build/`));

passport.use(new passport_reddit.Strategy({
	clientID: process.env.REDDIT_APP_ID,
	clientSecret: process.env.REDDIT_APP_SECRET,
	callbackURL: process.env.REDDIT_APP_REDIRECT,
	scope: ["identity", "history", "read", "save", "edit", "vote", "report"] // https://github.com/reddit-archive/reddit/wiki/OAuth2 "scope values", https://www.reddit.com/dev/api/oauth
}, async (user_access_token, user_refresh_token, user_profile, done) => { // http://www.passportjs.org/docs/configure "verify callback"
	const u = new user.User(user_profile.name, user_refresh_token);

	try {
		await u.save();
		return done(null, u); // passes the user to serializeUser
	} catch (err) {
		console.error(err);
	}
}));
passport.serializeUser((u, done) => done(null, u.username)); // store user's username into session cookie
passport.deserializeUser(async (username, done) => { // get user from db, specified by username in session cookie
	try {
		const u = await user.get(username);
		done(null, u);
		console.log(`deserialized user (${username})`);
	} catch (err) {
		console.log(`deserialize error (${username})`);
		console.error(err);
		done(err, null);
	}
});
process.nextTick(() => { // handle any deserializeUser errors here
	app.use((err, req, res, next) => {
		if (err) {
			console.error(err);

			const username = req.session.passport.user;
			delete user.usernames_to_socket_ids[username];
			
			req.session = null; // destroy login session
			console.log(`destroyed session (${username})`);
			req.logout();

			res.status(401).sendFile(`${frontend}/build/index.html`);
		} else {
			next();
		}
	});
});
app.use(express.urlencoded({
	extended: false
}));
app.use(cookie_session({ // https://github.com/expressjs/cookie-session
	name: "eternity_session",
	path: "/",
	secret: process.env.SESSION_SECRET,
	signed: true,
	httpOnly: true,
	overwrite: true,
	sameSite: "lax",
	maxAge: 1000*60*60*24*30
}));
app.use((req, res, next) => { // rolling session: https://github.com/expressjs/cookie-session#extending-the-session-expiration
	req.session.nowInMinutes = Math.floor(Date.now() / 60000);
	next();
});
app.use(passport.initialize());
app.use(passport.session());

app.get("/login", (req, res, next) => {
	passport.authenticate("reddit", { // https://github.com/Slotos/passport-reddit/blob/9717523d3d3f58447fee765c0ad864592efb67e8/examples/login/app.js#L86
		state: req.session.state = crypto.randomBytes(32).toString("hex"),
		duration: "permanent"
	})(req, res, next);
});

app.get("/callback", (req, res, next) => {
	if (req.query.state == req.session.state) {
		passport.authenticate("reddit", async (err, u, info) => {
			if (err || !u) {
				res.redirect(302, "/logout");
			} else if ((allowed_users.has("*") && denied_users.has(u.username)) || (!allowed_users.has("*") && !allowed_users.has(u.username)) || (denied_users.has("*") && !allowed_users.has(u.username))) {
				try {
					await u.purge();
					res.redirect(302, "/logout");
					console.log(`denied user (${u.username})`);
				} catch (err) {
					console.error(err);
				}
			} else {
				req.login(u, () => {
					res.redirect(302, "/");
				});
			}
		})(req, res, next);
	} else {
		res.redirect(302, "/logout");
	}
});

app.get("/authentication_check", (req, res) => {
	if (req.isAuthenticated()) {
		user.usernames_to_socket_ids[req.user.username] = req.query.socket_id;
		user.socket_ids_to_usernames[req.query.socket_id] = req.user.username;

		let page = null;

		if (req.user.last_updated_epoch) {
			page = "access";
		} else if (req.user.firebase_service_acc_key_encrypted) {
			page = "loading";
		} else {
			page = "unlock";
		}

		res.send({
			username: req.user.username,
			use_page: page
		});
	} else {
		res.send({
			use_page: "landing"
		});
	}
});

app.post("/upload", (req, res) => {
	if (req.isAuthenticated()) {
		(req.files.key ? req.files.key.mv(`${backend}/tempfiles/${req.user.username}_firebase_service_acc_key.json`).catch((err) => console.error(err)) : null);
		res.end();
	} else {
		res.status(401).sendFile(`${frontend}/build/index.html`);
	}
});

app.get("/logout", (req, res) => {
	if (req.isAuthenticated()) {
		req.logout();
		res.redirect(302, "/");
	} else {
		res.status(401).sendFile(`${frontend}/build/index.html`);
	}
});

app.get("/purge", async (req, res) => {
	if (req.isAuthenticated() && req.query.socket_id == user.usernames_to_socket_ids[req.user.username]) {
		try {
			await req.user.purge();
			req.logout();
			res.send("success");
		} catch (err) {
			console.error(err);
			res.send("error");
		}
	} else {
		res.status(401).sendFile(`${frontend}/build/index.html`);
	}
});

app.all("*", (req, res) => {
	res.status(404).sendFile(`${frontend}/build/index.html`);
});

io.on("connect", (socket) => {
	console.log(`socket (${socket.id}) connected`);

	socket.username = null;
	socket.firebase_instances_created = false; // clientside firebase instances (app, auth, db)

	socket.on("layout mounted", () => {
		io.to(socket.id).emit("update domain request info", domain_request_info);
	});

	socket.on("route", (route) => {
		switch (route) {
			case "index":
				break;
			case "about":
				break;
			default:
				break;
		}
	});

	socket.on("page", async (page) => {
		let u = null;

		switch (page) {
			case "landing":
				break;
			case "unlock":
				socket.username = user.socket_ids_to_usernames[socket.id];
				break;
			case "loading":
				socket.username = user.socket_ids_to_usernames[socket.id];
				try {
					u = await user.get(socket.username);
					await u.update(io, socket.id);
				} catch (err) {
					console.error(err);
					(u && u.firebase_app ? firebase.free_app(u.firebase_app).catch((err) => console.error(err)) : null);
				}
				break;
			case "access":
				socket.username = user.socket_ids_to_usernames[socket.id];
				try {
					u = await user.get(socket.username);

					io.to(socket.id).emit("store last updated epoch", u.last_updated_epoch);

					sql.update_user(u.username, {
						last_active_epoch: u.last_active_epoch = utils.now_epoch()
					}).catch((err) => console.error(err));
				} catch (err) {
					console.error(err);
				}
				break;
			default:
				break;
		}

		if (u && !socket.firebase_instances_created) {
			try {
				const app = firebase.create_app(JSON.parse(cryptr.decrypt(u.firebase_service_acc_key_encrypted)), JSON.parse(cryptr.decrypt(u.firebase_web_app_config_encrypted)).databaseURL, u.username);
				const auth_token = await firebase.create_new_auth_token(app);
				firebase.free_app(app).catch((err) => console.error(err));
	
				io.to(socket.id).emit("create firebase instances", JSON.parse(cryptr.decrypt(u.firebase_web_app_config_encrypted)), auth_token);
				socket.firebase_instances_created = true;
			} catch (err) {
				console.error(err);
			}
		}
	});

	socket.on("validate firebase info", async (web_app_config) => {
		try {
			const key_path = `${backend}/tempfiles/${socket.username}_firebase_service_acc_key.json`;
			const key_string = await filesystem.promises.readFile(key_path, "utf-8");
			const key_obj = JSON.parse(key_string);
	
			if (!(key_obj.type && key_obj.type == "service_account") && key_obj.project_id && key_obj.private_key_id && key_obj.private_key && key_obj.client_email && key_obj.client_id && key_obj.auth_uri && key_obj.token_uri && key_obj.auth_provider_x509_cert_url && key_obj.client_x509_cert_url) {
				io.to(socket.id).emit("alert", "firebase", "validation failed: incorrect Firebase project service account key", "danger");
				await filesystem.promises.unlink(key_path);
				return;
			}
			
			if (!(web_app_config.databaseURL && web_app_config.databaseURL.includes("firebase") && web_app_config.apiKey && web_app_config.authDomain && web_app_config.projectId && web_app_config.storageBucket && web_app_config.messagingSenderId && web_app_config.appId)) {
				io.to(socket.id).emit("alert", "firebase", "validation failed: incorrect Firebase web app config", "danger");
				await filesystem.promises.unlink(key_path);
				return;
			}
	
			try {
				const app = firebase.create_app(key_obj, web_app_config.databaseURL, socket.username);
				const db = firebase.get_db(app);
				const db_is_empty = await firebase.is_empty(db);
				firebase.free_app(app).catch((err) => console.error(err));
				if (!db_is_empty) {
					io.to(socket.id).emit("alert", "firebase", "validation failed: database not empty", "danger");
					await filesystem.promises.unlink(key_path);
					return;
				}
			} catch (err) {
				console.error(err);
				io.to(socket.id).emit("alert", "firebase", "validation failed: could not check database", "danger");
				await filesystem.promises.unlink(key_path);
				return;
			}
	
			await filesystem.promises.unlink(key_path);
	
			socket.firebase_service_acc_key_encrypted = cryptr.encrypt(JSON.stringify(key_obj));
			socket.firebase_web_app_config_encrypted = cryptr.encrypt(JSON.stringify(web_app_config));
			io.to(socket.id).emit("alert", "firebase", "validation success", "success");
			io.to(socket.id).emit("disable button", "validate");
	
			(socket.firebase_service_acc_key_encrypted && socket.firebase_web_app_config_encrypted && socket.verified_email ? io.to(socket.id).emit("enable button", "save_and_continue") : null);
		} catch (err) {
			console.error(err);
		}
	});

	socket.on("confirm email", async (email_addr) => {
		email_addr = email_addr.trim();

		if (!(email_addr && email_addr.includes("@") && email_addr.includes(".") && email_addr.length >= 7)) {
			io.to(socket.id).emit("alert", "email", "this is not an email address", "danger");
			return;
		}

		io.to(socket.id).emit("disable button", "confirm");
		
		const obj = {
			username: socket.username,
			email_encrypted: socket.email_encrypted = cryptr.encrypt(email_addr)
		};
		email.send(obj, "verify your email", `<big>${socket.id.replace(/(\W)|(_)/g, "").slice(0, 5).toUpperCase()}</big> is your verification code. if you did not request this, please ignore this email${(obj.username == null ? ". if this email was addressed to u/null instead of your Reddit username, that means your device disconnected your websocket from the setup page; voiding this verification code. to prevent this from happening, it is recommended to do the setup from a computer rather than a mobile device" : "")}`).catch((err) => console.error(err));

		io.to(socket.id).emit("alert", "email", "enter the code sent to this email to verify that it's your email. check your junk/spam folder if you don't see it. the verification must be done while this page is open, so don't close this page", "primary");

		io.to(socket.id).emit("enable button", "verify");
	});

	socket.on("verify code", (username, code) => {
		if (!(username == socket.username && code == socket.id.replace(/(\W)|(_)/g, "").slice(0, 5).toUpperCase())) {
			io.to(socket.id).emit("alert", "email", "verification failed", "danger");
			return;
		}

		socket.verified_email = true;
		io.to(socket.id).emit("alert", "email", "verification success", "success");
		io.to(socket.id).emit("disable button", "verify");

		(socket.firebase_service_acc_key_encrypted && socket.firebase_web_app_config_encrypted && socket.verified_email ? io.to(socket.id).emit("enable button", "save_and_continue") : null);
	});
	
	socket.on("save firebase info and email", async () => {
		try {
			await sql.update_user(socket.username, {
				email_encrypted: socket.email_encrypted,
				firebase_service_acc_key_encrypted: socket.firebase_service_acc_key_encrypted,
				firebase_web_app_config_encrypted: socket.firebase_web_app_config_encrypted
			});
	
			io.to(socket.id).emit("switch page to loading");
		} catch (err) {
			console.error(err);
		}
	});

	socket.on("get comment from reddit", async (comment_id) => {
		try {
			const u = await user.get(socket.username);
			const comment_content = await u.get_comment_from_reddit(comment_id);
			io.to(socket.id).emit("got comment from reddit", comment_content);
		} catch (err) {
			console.error(err);
		}
	});

	socket.on("delete item from reddit acc", async (item_id, item_category, item_type) => {
		try {
			const u = await user.get(socket.username);
			u.delete_item_from_reddit_acc(item_id, item_category, item_type).catch((err) => console.error(err));
		} catch (err) {
			console.error(err);
		}
	});

	socket.on("disconnect", () => {
		if (socket.username) { // logged in
			(socket.username in user.usernames_to_socket_ids ? user.usernames_to_socket_ids[socket.username] = null : null); // set to null; not delete, bc username is needed in user.update_all
			delete user.socket_ids_to_usernames[socket.id];	
		}
	});
});

app_socket.on("connect", () => {
	console.log("connected as client to portals (localhost:1026)");
});

app_socket.on("update domain request info", (info) => {
	io.emit("update domain request info", domain_request_info = info);
});

app_socket.connect();

server.listen(Number.parseInt(process.env.PORT), "0.0.0.0", () => {
	console.log(`server (eternity) started on (localhost:${process.env.PORT})`);
});

process.on("beforeExit", async (exit_code) => {
	try {
		await sql.pool.end();
	} catch (err) {
		console.error(err);
	}
});


================================================
FILE: backend/model/cryptr.mjs
================================================
import cryptr from "cryptr";

const cryptr_instance = new cryptr(process.env.ENCRYPTION_KEY);

function encrypt(unencrypted_thing) { // only use it on primitives. always returns a string
	const encrypted_thing = cryptr_instance.encrypt(unencrypted_thing);
	return encrypted_thing;
}

function decrypt(encrypted_thing) { // takes a string and returns a string
	const decrypted_thing = cryptr_instance.decrypt(encrypted_thing);
	return decrypted_thing;
}

export {
	encrypt,
	decrypt
};


================================================
FILE: backend/model/email.mjs
================================================
const backend = process.cwd();

const cryptr = await import(`${backend}/model/cryptr.mjs`);

import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
	service: "gmail",
	auth: {
		type: "OAuth2",
		clientId: process.env.NODEMAILER_GCP_CLIENT_ID,
		clientSecret: process.env.NODEMAILER_GCP_CLIENT_SECRET,
		user: process.env.NODEMAILER_GMAIL_ADDR,
		refreshToken: process.env.NODEMAILER_GMAIL_REFRESH_TOKEN
	},
	pool: true
});

async function send(user, subject, msg) {
	const info = await transporter.sendMail({
		from: '"eternity" <eternity@portals.sh>',
		to: cryptr.decrypt(user.email_encrypted),
		subject: subject,
		html: `
			<span>u/${user.username},</span><br/>
			<br/>
			<b>${msg}</b><br/>
			<br/>
			<br/>
			<span>—</span><br/>
			<a href=${(process.env.RUN == "dev" ? "http://localhost:" + (Number.parseInt(process.env.PORT)-1) : "https://eternity.portals.sh")} target="_blank">eternity</a>
		`
	});
	console.log(info);
}

export {
	send
};


================================================
FILE: backend/model/file.mjs
================================================
const backend = process.cwd();

import filesystem from "fs";

async function init() {
	for (const dir of [`${backend}/logs/`, `${backend}/tempfiles/`]) {
		if (filesystem.existsSync(dir)) {
			if (process.env.RUN == "dev") {
				const files = await filesystem.promises.readdir(dir);
				await Promise.all(files.map((file, idx, arr) => (dir == `${backend}/logs/` ? filesystem.promises.truncate(`${dir}/${file}`.replace("//", "/"), 0) : filesystem.promises.unlink(`${dir}/${file}`.replace("//", "/")))));
			}
		} else {
			filesystem.mkdirSync(dir);
		}
	}
}

export {
	init
};


================================================
FILE: backend/model/firebase.mjs
================================================
import firebase_admin from "firebase-admin";

function create_app(service_acc_key, db_url, username) {
	const app = firebase_admin.initializeApp({
		credential: firebase_admin.credential.cert(service_acc_key),
		databaseURL: db_url
	}, username); // need 2nd arg (username) to be able to create multiple firebase app instances
	return app;
}

async function free_app(app) {
	await app.delete(); // deletes instance from memory; does not actually delete anything else
}

function get_db(app) {
	return app.database();
}

async function is_empty(db) {
	const snapshot = await db.ref().once("value");
	const db_is_empty = !snapshot.exists();
	return db_is_empty;
}

async function insert_data(db, data) {
	const updates = {};

	for (const category in data) {
		if (Object.keys(data[category].items).length > 0) {
			let entries = Object.entries(data[category].items);
			for (const entry of entries) {
				const item_key = entry[0];
				const item_value = entry[1];

				updates[`${category}/items/${item_key}`] = item_value;
			}

			entries = Object.entries(data[category].item_sub_icon_urls);
			for (const entry of entries) {
				const icon_url_key = entry[0];
				const icon_url_value = entry[1];

				updates[`${category}/item_sub_icon_urls/${icon_url_key.replace("/", "|").replace(".", ",")}`] = icon_url_value;
			}
		}
	}
	
	(Object.keys(updates).length > 0 ? await db.ref().update(updates) : null);
}

async function get_fns_to_import(db, category) {
	const snapshot = await db.ref(`${category}/item_fns_to_import`).limitToFirst(500).get();
	const data = snapshot.val(); // null if no item_fns_to_import
	return data;
}

async function delete_imported_fns(db, fns) {
	const updates = {};

	for (const category in fns) {
		if (fns[category]) {
			for (const fn of fns[category]) {
				updates[`${category}/item_fns_to_import/${fn}`] = null;
			}
		}
	}

	(Object.keys(updates).length > 0 ? await db.ref().update(updates) : null);
}

async function create_new_auth_token(app) {
	const additional_claims = {
		owner: true
	};
	const auth_token = await app.auth().createCustomToken(app.name, additional_claims);
	return auth_token;
}

export {
	create_app,
	free_app,
	get_db,
	is_empty,
	insert_data,
	get_fns_to_import,
	delete_imported_fns,
	create_new_auth_token
};


================================================
FILE: backend/model/logger.mjs
================================================
const backend = process.cwd();

import winston from "winston";

const log_logger = create_logger("info");
const log = log_logger.info.bind(log_logger);
const error_logger = create_logger("error");
const error = error_logger.error.bind(error_logger);

function create_logger(level) { // https://github.com/winstonjs/winston#logging-levels "npm logging levels"
	const logger = winston.createLogger({
		format: winston.format.combine(
			winston.format.timestamp({
				format: "YYYY-MM-DD HH:mm:ss"
			}),
			winston.format.json(),
			winston.format.printf((log) => {
				return `${JSON.stringify({
					timestamp: log.timestamp,
					message: log.message
				}, null, 4)}`;
			})
		),
		transports: [
			// new winston.transports.Console(),
			new winston.transports.File({
				filename: `${backend}/logs/${(level == "info" ? "log" : level)}.txt`
			})
		]
	});
	return logger;
}

export {
	log,
	error
};


================================================
FILE: backend/model/reddit.mjs
================================================
import snoowrap from "snoowrap";

function create_requester(reddit_api_refresh_token) {
	const requester = new snoowrap({
		clientId: process.env.REDDIT_APP_ID,
		clientSecret: process.env.REDDIT_APP_SECRET,
		userAgent: `web:eternity${(process.env.RUN == "dev" ? "_test" : "")}:v=${process.env.VERSION} (by u/${process.env.REDDIT_USERNAME})`, // https://github.com/reddit-archive/reddit/wiki/API "User-Agent"
		refreshToken: reddit_api_refresh_token
	});
	return requester;
}

export {
	create_requester
};


================================================
FILE: backend/model/sql.mjs
================================================
import node_pg from "pg";
import axios from "axios";

const pool = new node_pg.Pool({ // https://node-postgres.com/api/pool
	connectionString: process.env.SQL_CONNECTION,
	max: (process.env.RUN == "dev" ? 1 : 5),
	idleTimeoutMillis: 0
});

async function init_db() {
	const client = await pool.connect();
	try {
		await client.query("begin;");

		if (process.env.RUN == "dev") {
			const result = await client.query(`
				select 
					table_name 
				from 
					information_schema.tables 
				where 
					table_schema = 'public' 
					and table_type = 'BASE TABLE'
				;
			`);
			const all_tables = result.rows;
			await Promise.all(all_tables.map((table, idx, arr) => {
				client.query(`
					drop table 
						${table.table_name} 
					cascade
					;
				`);
			}));
			console.log("dropped all tables");
			console.log("recreating tables");
		}
	
		await client.query(`
			create table if not exists 
				user_ (
					username text primary key, 
					reddit_api_refresh_token_encrypted text, -- decrypt ➔ string
					category_sync_info json, 
					last_updated_epoch bigint, 
					last_active_epoch bigint, 
					email_encrypted text, -- decrypt ➔ string
					email_notif json, 
					firebase_service_acc_key_encrypted text, -- decrypt ➔ json string
					firebase_web_app_config_encrypted text -- decrypt ➔ json string
				)
			;
		`);

		await client.query("commit;");
	} catch (err) {
		console.error(err);
		await client.query("rollback;");
	}
	client.release();
}

async function query(query) {
	const result = await pool.query(query);
	const rows = (result ? result.rows : null);
	return rows;
}

async function save_user(username, reddit_api_refresh_token_encrypted, category_sync_info, last_active_epoch, email_notif) {
	await query(`
		insert into 
			user_ 
		values (
			'${username}', 
			'${reddit_api_refresh_token_encrypted}', 
			'${JSON.stringify(category_sync_info)}', 
			null, 
			${last_active_epoch}, 
			null, 
			'${JSON.stringify(email_notif)}', 
			null, 
			null
		) 
		on conflict (username) do -- previously purged user
			update 
				set 
					reddit_api_refresh_token_encrypted = excluded.reddit_api_refresh_token_encrypted, 
					category_sync_info = excluded.category_sync_info, 
					last_updated_epoch = excluded.last_updated_epoch, 
					last_active_epoch = excluded.last_active_epoch, 
					email_encrypted = excluded.email_encrypted, 
					email_notif = excluded.email_notif, 
					firebase_service_acc_key_encrypted = excluded.firebase_service_acc_key_encrypted, 
					firebase_web_app_config_encrypted = excluded.firebase_web_app_config_encrypted
		;
	`);
}

async function update_user(username, fields) {
	await query(`
		update 
			user_ 
		set 
			${Object.keys(fields).map((field, idx, arr) => `${field} = ${(typeof fields[field] == "string" ? "'" : "")}${fields[field]}${(typeof fields[field] == "string" ? "'" : "")}${(idx < arr.length-1 ? "," : "")}`).join(" ")} 
		where 
			username = '${username}'
		;
	`);
}

async function get_user(username) {
	const rows = await query(`
		select 
			* 
		from 
			user_ 
		where 
			username = '${username}'
		;
	`);
	return rows[0];
}

async function get_all_non_purged_users() {
	const rows = await query(`
		select 
			username 
		from 
			user_ 
		where 
			reddit_api_refresh_token_encrypted is not null
		;
	`);
	return rows;
}

async function backup_db() {
	await axios.post("https://api.elephantsql.com/api/backup", {}, {
		auth: {
			username: "",
			password: process.env.SQL_API_KEY
		}
	});
	console.log("backed up db");
}
function cycle_backup_db() {
	(process.env.RUN == "dev" ? backup_db().catch((err) => console.error(err)) : null);

	setInterval(() => {
		backup_db().catch((err) => console.error(err));
	}, 86400000); // 24h
}

export {
	pool,
	init_db,
	save_user,
	update_user,
	get_user,
	get_all_non_purged_users,
	cycle_backup_db
};


================================================
FILE: backend/model/user.mjs
================================================
const backend = process.cwd();

const sql = await import(`${backend}/model/sql.mjs`);
const firebase = await import(`${backend}/model/firebase.mjs`);
const reddit = await import(`${backend}/model/reddit.mjs`);
const cryptr = await import(`${backend}/model/cryptr.mjs`);
const email = await import(`${backend}/model/email.mjs`);
const logger = await import(`${backend}/model/logger.mjs`);
const utils = await import(`${backend}/model/utils.mjs`);

let update_all_completed = null;

const usernames_to_socket_ids = {};
const socket_ids_to_usernames = {};

class User {
	constructor(username, refresh_token, dummy=false) {
		this.username = username;

		if (dummy) {
			null;
		} else {
			this.reddit_api_refresh_token_encrypted = cryptr.encrypt(refresh_token);
			this.category_sync_info = {
				saved: {
					latest_fn_mixed: null,
					latest_new_data_epoch: null
				},
				created: {
					latest_fn_posts: null,
					latest_fn_comments: null,
					latest_new_data_epoch: null
				},
				upvoted: {
					latest_fn_posts: null,
					latest_new_data_epoch: null
				},
				downvoted: {
					latest_fn_posts: null,
					latest_new_data_epoch: null
				},
				hidden: {
					latest_fn_posts: null,
					latest_new_data_epoch: null
				},
				awarded: {
					latest_fn_mixed: null,
					latest_new_data_epoch: null
				}
			};
			this.last_updated_epoch = null;
			this.last_active_epoch = utils.now_epoch();
			this.email_encrypted = null;
			this.email_notif = {
				last_inactive_notif_epoch: null,
				last_update_failed_notif_epoch: null
			};
			this.firebase_service_acc_key_encrypted = null;
			this.firebase_web_app_config_encrypted = null;
		}
	}
	async save() {
		let user_for_comparison = null;
		try {
			user_for_comparison = await get(this.username, true);
		} catch (err) {
			if (err != `Error: user (${this.username}) dne`) {
				console.error(err);
				logger.error(err);
				return;
			}
		}
		
		if (!user_for_comparison || !user_for_comparison.last_updated_epoch) {
			console.log(`new user (${this.username})`);

			await sql.save_user(this.username, this.reddit_api_refresh_token_encrypted, this.category_sync_info, this.last_active_epoch, this.email_notif);
		} else {
			console.log(`returning user (${this.username})`);

			await sql.update_user(this.username, {
				reddit_api_refresh_token_encrypted: this.reddit_api_refresh_token_encrypted
			});
		}

		console.log(`saved user (${this.username})`);
	}
	async get_listing(options, category, type) {
		let listing = null;
		switch (category) {
			case "saved": // posts, comments
				listing = await this.me.getSavedContent(options);
				break;
			case "created": // posts, comments
				switch (type) {
					case "posts":
						listing = await this.me.getSubmissions(options);
						break;
					case "comments":
						listing = await this.me.getComments(options);
						break;
					default:
						break;
				}
				break;
			case "upvoted": // posts
				listing = await this.me.getUpvotedContent(options);
				break;
			case "downvoted": // posts
				listing = await this.me.getDownvotedContent(options);
				break;
			case "hidden": // posts
				listing = await this.me.getHiddenContent(options);
				break;
			case "awarded": // posts, comments
				listing = await this.me._getListing({
					uri: `u/${this.username}/gilded/given`,
					qs: options
				});
				break;
			default:
				break;
		}
		return listing;
	}
	parse_listing(listing, category, type, from_mixed=false, from_import=false) {
		if (type == "mixed") {
			(!from_import ? this.category_sync_info[category].latest_fn_mixed = listing[0].name : null);

			const posts = [];
			const comments = [];

			for (const item of listing) {
				switch (item.constructor.name) {
					case "Submission":
						posts.push(item);
						break;
					case "Comment":
						comments.push(item);
						break;
					default:
						break;
				}
			}
	
			this.parse_listing(posts, category, "posts", true);
			this.parse_listing(comments, category, "comments", true);
		} else {
			(!from_mixed && !from_import ? this.category_sync_info[category][`latest_fn_${type}`] = listing[0].name : null);

			for (const item of listing) {
				this.new_data[category].items[item.id] = {
					type: (type == "posts" ? "post" : "comment"),
					content: (type == "posts" ? item.title : item.body),
					author: `u/${item.author.name}`,
					sub: item.subreddit_name_prefixed,
					url: `https://www.reddit.com${utils.strip_trailing_slash(item.permalink)}`,
					created_epoch: item.created_utc
				};

				this.sub_icon_urls_to_get[category].add(item.subreddit_name_prefixed);
			}
		}
	}
	async replace_latest_fn(category, type) {
		const options = {
			limit: 1
		};
		const listing = await this.get_listing(options, category, type);
		
		const latest_fn = (listing.length != 0 ? listing[0].name : null);
		this.category_sync_info[category][`latest_fn_${type}`] = latest_fn;
	}
	async sync_category(category, type) {
		let options = {
			limit: 5,
			before: this.category_sync_info[category][`latest_fn_${type}`] // "before" is actually chronologically after. https://www.reddit.com/dev/api/#listings
		};
		const listing = await this.get_listing(options, category, type);

		if (listing.isFinished) {
			if (listing.length == 0) { // either listing actually has no items, or user deleted the latest_fn item from the listing on reddit (like, deleted it from reddit ON reddit, not deleted it from reddit on eternity)
				await this.replace_latest_fn(category, type);
			} else {
				this.parse_listing(listing, category, type);
				this.category_sync_info[category].latest_new_data_epoch = utils.now_epoch();
			}
		} else {
			const extended_listing = await listing.fetchAll({
				append: true
			});
			this.parse_listing(extended_listing, category, type);
			this.category_sync_info[category].latest_new_data_epoch = utils.now_epoch();
		}
	}
	async import_category(category, type) {
		const data = await firebase.get_fns_to_import(this.firebase_db, category);
		if (data) {
			const fns = Object.keys(data);

			console.log(`importing (${fns.length}) (${category}) items`);

			const promises = [];

			const required_requests = Math.ceil(fns.length / 100);
			for (let i = 0; i < required_requests; i++) {
				promises.push(this.requester.getContentByIds(fns.slice(i*100, i*100 + 100))); // getContentByIds only takes max of 100 fns at once
			}
	
			const listings = await Promise.all(promises);
			for (const listing of listings) {
				this.parse_listing(listing, category, type, false, true);
			}

			this.category_sync_info[category].latest_new_data_epoch = utils.now_epoch();
	
			this.imported_fns_to_delete[category] = fns;
		}
	}
	async request_item_icon_urls(type, subs, category) {
		const promises = [];

		let required_requests = null;
		const ratelimit_remaining = this.requester.ratelimitRemaining;
		let i = 0;

		switch (type) {
			case "r/":
				required_requests = Math.ceil(subs.length / 100);
			
				for (; i < required_requests && i < ratelimit_remaining; i++) {
					promises.push(this.requester.oauthRequest({
						uri: "api/info", // only takes max of 100 subs at once
						qs: {
							sr_name: subs.slice(i*100, i*100 + 100).join(",")
						}
					}));
				}
				break;
			case "u/":
				required_requests = subs.length;

				for (; i < required_requests && i < ratelimit_remaining; i++) {
					promises.push(this.requester.oauthRequest({
						uri: `${subs[i]}/about`
					}));
				}
				break;
			default:
				break;
		}
		(i == ratelimit_remaining ? console.log(`user (${this.username}) ratelimit reached`) : null);

		const responses = await Promise.all(promises);

		switch (type) {
			case "r/":
				for (const listing of responses) {
					for (const sub of listing) {
						const sub_name = sub.display_name_prefixed;
						
						let sub_icon_url = "#";
						if (sub.icon_img) {
							sub_icon_url = sub.icon_img.split("?")[0];
						} else if (sub.community_icon) {
							sub_icon_url = sub.community_icon.split("?")[0];
						}
		
						this.new_data[category].item_sub_icon_urls[sub_name] = sub_icon_url;
					}
				}
				break;
			case "u/":
				for (const sub of responses) {
					const sub_name = `u/${sub.name}`;
	
					let sub_icon_url = "#";
					if (sub.icon_img) {
						sub_icon_url = sub.icon_img.split("?")[0];
					} else if (sub.subreddit?.display_name.icon_img) {
						sub_icon_url = sub.subreddit.display_name.icon_img.split("?")[0];
					} else if (sub.community_icon) {
						sub_icon_url = sub.community_icon.split("?")[0];
					} else if (sub.subreddit?.display_name.community_icon) {
						sub_icon_url = sub.subreddit.display_name.community_icon.split("?")[0];
					} else if (sub.snoovatar_img) {
						sub_icon_url = sub.snoovatar_img.split("?")[0];
					} else if (sub.subreddit?.display_name.snoovatar_img) {
						sub_icon_url = sub.subreddit.display_name.snoovatar_img.split("?")[0];
					}
	
					this.new_data[category].item_sub_icon_urls[sub_name] = sub_icon_url;
				}
				break;
			default:
				break;
		}
	}
	async get_new_item_icon_urls(category) {
		let r_subs = []; // actual subs
		let u_subs = []; // users as subs

		for (const sub of this.sub_icon_urls_to_get[category]) {
			if (sub.startsWith("r/")) {
				r_subs.push(sub);
			} else if (sub.startsWith("u/")) {
				u_subs.push(sub);
			}
		}

		(r_subs.length != 0 ? await this.request_item_icon_urls("r/", r_subs, category) : null);
		(u_subs.length != 0 ? await this.request_item_icon_urls("u/", u_subs, category) : null);
	}
	async update(io=null, socket_id=null) {
		console.log(`updating user (${this.username})`);

		let progress = (io ? 0 : null);
		const complete = (io ? 8 : null);

		this.requester = reddit.create_requester(cryptr.decrypt(this.reddit_api_refresh_token_encrypted));
		this.me = await this.requester.getMe();

		this.firebase_app = firebase.create_app(JSON.parse(cryptr.decrypt(this.firebase_service_acc_key_encrypted)), JSON.parse(cryptr.decrypt(this.firebase_web_app_config_encrypted)).databaseURL, this.username);
		this.firebase_db = firebase.get_db(this.firebase_app);

		this.new_data = {};
		this.sub_icon_urls_to_get = {};
		this.imported_fns_to_delete = {};
		
		const categories = ["saved", "created", "upvoted", "downvoted", "hidden", "awarded"];
		for (const category of categories) {
			this.new_data[category] = {
				items: {},
				item_sub_icon_urls: {}
			};
			
			this.sub_icon_urls_to_get[category] = new Set();
		}
		categories.pop();
		for (const category of categories) {
			this.imported_fns_to_delete[category] = null;
		}

		const s_promise = new Promise(async (resolve, reject) => {
			try {
				(this.firebase_app.isDeleted_ ? null : await this.sync_category("saved", "mixed"));
				(this.firebase_app.isDeleted_ ? null : await this.import_category("saved", "mixed"));
				(this.firebase_app.isDeleted_ ? null : await this.get_new_item_icon_urls("saved"));

				if (this.firebase_app.isDeleted_) {
					reject("firebase_app is deleted");
				} else {
					(io ? io.to(socket_id).emit("update progress", ++progress, complete) : null);
					resolve();
				}
			} catch (err) {
				err.extras = {
					category: "saved"
				};
				reject(err);
			}
		});

		const c_promise = new Promise(async (resolve, reject) => {
			try {
				if (!this.firebase_app.isDeleted_) {
					await Promise.all([
						this.sync_category("created", "posts"),
						this.sync_category("created", "comments")
					]);
				}
				(this.firebase_app.isDeleted_ ? null : await this.import_category("created", "mixed"));
				(this.firebase_app.isDeleted_ ? null : await this.get_new_item_icon_urls("created"));

				if (this.firebase_app.isDeleted_) {
					reject("firebase_app is deleted");
				} else {
					(io ? io.to(socket_id).emit("update progress", ++progress, complete) : null);
					resolve();
				}
			} catch (err) {
				err.extras = {
					category: "created"
				};
				reject(err);
			}
		});
		
		const u_promise = new Promise(async (resolve, reject) => {
			try {
				(this.firebase_app.isDeleted_ ? null : await this.sync_category("upvoted", "posts"));
				(this.firebase_app.isDeleted_ ? null : await this.import_category("upvoted", "posts"));
				(this.firebase_app.isDeleted_ ? null : await this.get_new_item_icon_urls("upvoted"));

				if (this.firebase_app.isDeleted_) {
					reject("firebase_app is deleted");
				} else {
					(io ? io.to(socket_id).emit("update progress", ++progress, complete) : null);
					resolve();
				}
			} catch (err) {
				err.extras = {
					category: "upvoted"
				};
				reject(err);
			}
		});
		
		const d_promise = new Promise(async (resolve, reject) => {
			try {
				(this.firebase_app.isDeleted_ ? null : await this.sync_category("downvoted", "posts"));
				(this.firebase_app.isDeleted_ ? null : await this.import_category("downvoted", "posts"));
				(this.firebase_app.isDeleted_ ? null : await this.get_new_item_icon_urls("downvoted"));

				if (this.firebase_app.isDeleted_) {
					reject("firebase_app is deleted");
				} else {
					(io ? io.to(socket_id).emit("update progress", ++progress, complete) : null);
					resolve();
				}
			} catch (err) {
				err.extras = {
					category: "downvoted"
				};
				reject(err);
			}
		});

		const h_promise = new Promise(async (resolve, reject) => {
			try {
				(this.firebase_app.isDeleted_ ? null : await this.sync_category("hidden", "posts"));
				(this.firebase_app.isDeleted_ ? null : await this.import_category("hidden", "posts"));
				(this.firebase_app.isDeleted_ ? null : await this.get_new_item_icon_urls("hidden"));

				if (this.firebase_app.isDeleted_) {
					reject("firebase_app is deleted");
				} else {
					(io ? io.to(socket_id).emit("update progress", ++progress, complete) : null);
					resolve();
				}
			} catch (err) {
				err.extras = {
					category: "hidden"
				};
				reject(err);
			}
		});

		const a_promise = new Promise(async (resolve, reject) => {
			try {
				(this.firebase_app.isDeleted_ ? null : await this.sync_category("awarded", "mixed"));
				(this.firebase_app.isDeleted_ ? null : await this.get_new_item_icon_urls("awarded"));

				if (this.firebase_app.isDeleted_) {
					reject("firebase_app is deleted");
				} else {
					(io ? io.to(socket_id).emit("update progress", ++progress, complete) : null);
					resolve();
				}
			} catch (err) {
				err.extras = {
					category: "awarded"
				};
				reject(err);
			}
		});

		await Promise.all([s_promise, c_promise, u_promise, d_promise, h_promise, a_promise]);

		try {
			await firebase.insert_data(this.firebase_db, this.new_data);
			await firebase.delete_imported_fns(this.firebase_db, this.imported_fns_to_delete);
			firebase.free_app(this.firebase_app).catch((err) => console.error(err));
			(io ? io.to(socket_id).emit("update progress", ++progress, complete) : null);
		} catch (err) {
			console.error(err);
			logger.error(`user (${this.username}) db update error (${err})`);

			if (utils.now_epoch() - this.email_notif.last_update_failed_notif_epoch >= 2592000) { // 30d
				email.send(this, "database update error notice", `your database could not be updated because: ${err}. please resolve this asap`).catch((err) => console.error(err));
				this.email_notif.last_update_failed_notif_epoch = utils.now_epoch();
				sql.update_user(this.username, {
					email_notif: JSON.stringify(this.email_notif)
				}).catch((err) => console.error(err));
			}

			return;
		}

		await sql.update_user(this.username, {
			category_sync_info: JSON.stringify(this.category_sync_info),
			last_updated_epoch: this.last_updated_epoch = utils.now_epoch()
		});
		(io ? io.to(socket_id).emit("update progress", ++progress, complete) : null);
		console.log(`updated user (${this.username})`);

		delete this.new_data;
		delete this.sub_icon_urls_to_get;
		delete this.imported_fns_to_delete;
	}
	async get_comment_from_reddit(comment_id) {
		const requester = reddit.create_requester(cryptr.decrypt(this.reddit_api_refresh_token_encrypted));
		
		const unfetched_comment = requester.getComment(comment_id);
		const fetched_comment = await unfetched_comment.fetch();
		
		const comment_content = fetched_comment.body;
		return comment_content;
	}
	async delete_item_from_reddit_acc(item_id, item_category, item_type) {
		const requester = reddit.create_requester(cryptr.decrypt(this.reddit_api_refresh_token_encrypted));
	
		let item = null;
		let item_fn = null; // https://www.reddit.com/dev/api/#fullnames
		switch (item_type) {
			case "post":
				item = requester.getSubmission(item_id);
				item_fn = `t3_${item_id}`;
				break;
			case "comment":
				item = requester.getComment(item_id);
				item_fn = `t1_${item_id}`;
				break;
			default:
				break;
		}
	
		let replace_latest_fn = null;
		if (item_category == "saved") {
			replace_latest_fn = (item_fn == this.category_sync_info.saved.latest_fn_mixed ? true : false);
		} else {
			replace_latest_fn = (item_fn == this.category_sync_info[item_category][`latest_fn_${item_type}s`] ? true : false);
		}
		
		switch (item_category) {
			case "saved":
				await item.unsave();
				break;
			case "created":
				await item.delete();
				break;
			case "upvoted":
			case "downvoted":
				await item.unvote();
				break;
			case "hidden":
				await item.unhide();
				break;
			default:
				break;
		}
	
		if (replace_latest_fn) {
			this.me = await requester.getMe();
			await this.replace_latest_fn(item_category, (item_category == "saved" ? "mixed" : `${item_type}s`));
			await sql.update_user(this.username, {
				category_sync_info: JSON.stringify(this.category_sync_info)
			});
		}
	}
	async purge() {
		await sql.update_user(this.username, {
			reddit_api_refresh_token_encrypted: null,
			category_sync_info: null,
			last_updated_epoch: null,
			last_active_epoch: null,
			email_encrypted: null,
			email_notif: null,
			firebase_service_acc_key_encrypted: null,
			firebase_web_app_config_encrypted: null
		});
		delete usernames_to_socket_ids[this.username];
		console.log(`purged user (${this.username})`);
	}
}

async function fill_usernames_to_socket_ids() {
	const rows = await sql.get_all_non_purged_users();
	for (const row of rows) {
		usernames_to_socket_ids[row.username] = null;
	}
}

async function get(username, existence_check=false) {
	(existence_check ? console.log(`checking if user (${username}) exists`) : console.log(`getting user (${username})`));

	const result = await sql.get_user(username);
	if (result == undefined) {
		throw new Error(`user (${username}) dne`);
	} else {
		const plain_object = result;
		(plain_object.last_updated_epoch ? plain_object.last_updated_epoch = Number.parseInt(plain_object.last_updated_epoch) : null);
		plain_object.last_active_epoch = Number.parseInt(plain_object.last_active_epoch);
	
		const user = Object.assign(new User(null, null, true), plain_object);
		return user;
	}
}

async function update_all(io) {
	console.log("update all started");
	update_all_completed = false;

	const all_usernames = Object.keys(usernames_to_socket_ids);
	for (const username of all_usernames) {
		let user = null;
		try {
			user = await get(username);

			if (user.last_updated_epoch) {
				if (utils.now_epoch() - user.last_active_epoch >= 15552000) { // 6mo
					if (utils.now_epoch() - user.email_notif.last_inactive_notif_epoch >= 7776000) { // 3mo
						email.send(user, "account inactivity notice", "you have not used eternity for 6 or more consecutive months at this time. as such, your eternity account has been marked inactive and new Reddit data will not continue to sync to your database. to resolve this, log in to eternity").catch((err) => console.error(err));
						user.email_notif.last_inactive_notif_epoch = utils.now_epoch();
						sql.update_user(user.username, {
							email_notif: JSON.stringify(user.email_notif)
						}).catch((err) => console.error(err));
					}
				} else if (utils.now_epoch() - user.last_updated_epoch >= 30) {
					const pre_update_category_sync_info = JSON.parse(JSON.stringify(user.category_sync_info));

					await user.update();
					
					const post_update_category_sync_info = user.category_sync_info;
					
					const socket_id = usernames_to_socket_ids[user.username];
					if (socket_id) {
						const categories_w_new_data = [];
						for (const category in user.category_sync_info) {
							(post_update_category_sync_info[category].latest_new_data_epoch > pre_update_category_sync_info[category].latest_new_data_epoch ? categories_w_new_data.push(category) : null);
						}
						(categories_w_new_data.length > 0 ? io.to(socket_id).emit("show refresh alert", categories_w_new_data) : null);

						io.to(socket_id).emit("store last updated epoch", user.last_updated_epoch);
					}
				}
			}
		} catch (err) {
			if (err != `Error: user (${username}) dne`) {
				console.error(err);
				logger.error(`user (${username}) update error (${err})`);

				(user.firebase_app ? firebase.free_app(user.firebase_app).catch((err) => console.error(err)) : null);

				if (err.statusCode == 403 && err.options.qs.before) {
					try {
						switch (err.extras.category) {
							case "saved":
							case "awarded":
								await user.replace_latest_fn(err.extras.category, "mixed");
								break;
							case "created":
								await Promise.all([
									user.replace_latest_fn(err.extras.category, "posts"),
									user.replace_latest_fn(err.extras.category, "comments")
								]);
								break;
							case "upvoted":
							case "downvoted":
							case "hidden":
								await user.replace_latest_fn(err.extras.category, "posts");
								break;
							default:
								break;
						}
						await sql.update_user(user.username, {
							category_sync_info: JSON.stringify(user.category_sync_info)
						});
					} catch (err) {
						console.error(err);
						logger.error(`user (${username}) replace_latest_fn error (${err})`);
					}
				}
			}
			
		}
	}

	update_all_completed = true;
	console.log("update all completed");
}
function cycle_update_all(io) {
	update_all(io).catch((err) => console.error(err));

	setInterval(() => {
		(update_all_completed ? update_all(io).catch((err) => console.error(err)) : null);
	}, 60000); // 1min
}

export {
	User,
	usernames_to_socket_ids,
	socket_ids_to_usernames,
	fill_usernames_to_socket_ids,
	get,
	cycle_update_all
};


================================================
FILE: backend/model/utils.mjs
================================================
function now_epoch() {
	const now_epoch = Math.floor(Date.now() / 1000);
	return now_epoch;
}

function strip_trailing_slash(string) {
	const stripped_string = (string.endsWith("/") ? string.slice(0, -1) : string);
	return stripped_string;
}

export {
	now_epoch,
	strip_trailing_slash
};


================================================
FILE: backend/nodemon.json
================================================
{
	"ext": "mjs"
}


================================================
FILE: backend/package.json
================================================
{
	"type": "module",
	"scripts": {
		"dev": "RUN=dev PORT=1301 nodemon ./controller/server.mjs",
		"prod_start": "RUN=prod PORT=1301 pm2 start ./controller/server.mjs --interpreter node --name eternity --update-env",
		"prod_stop": "pm2 stop ./controller/server.mjs"
	},
	"devDependencies": {
		"@types/node": "18.11.9",
		"nodemon": "2.0.20"
	},
	"dependencies": {
		"axios": "0.26.1",
		"cookie-session": "1.4.0",
		"cryptr": "6.0.3",
		"dotenv": "16.0.3",
		"express": "4.18.2",
		"express-fileupload": "1.4.0",
		"firebase-admin": "10.3.0",
		"internal-ip": "7.0.0",
		"nodemailer": "6.8.0",
		"passport": "0.5.3",
		"passport-reddit": "0.2.4",
		"pg": "8.8.0",
		"snoowrap": "1.23.0",
		"socket.io": "4.5.3",
		"socket.io-client": "4.5.3",
		"winston": "3.8.2"
	}
}


================================================
FILE: frontend/.npmrc
================================================
engine-strict=true
unsafe-perm=true
save-exact=true


================================================
FILE: frontend/package.json
================================================
{
	"type": "module",
	"scripts": {
		"dev": "RUN=dev PORT=1300 vite dev",
		"build": "vite build",
		"preview": "vite preview"
	},
	"devDependencies": {
		"@sveltejs/adapter-static": "1.0.0-next.39",
		"@sveltejs/kit": "1.0.0-next.405",
		"svelte": "3.49.0",
		"vite": "3.0.7"
	},
	"dependencies": {
		"axios": "0.26.1",
		"firebase": "8.10.1",
		"socket.io-client": "4.5.3",
		"underscore": "1.13.6",
		"xlsx": "0.18.5"
	}
}


================================================
FILE: frontend/source/app.html
================================================
<!DOCTYPE html>
<html>
	<head>
		%sveltekit.head%
		<meta charset="utf-8"/>
		<meta name="viewport" content="width=device-width, initial-scale=1"/>
		<link rel="icon" type="image/png" href="/favicon.png"/>
		<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous" referrerpolicy="no-referrer"/>
		<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous" referrerpolicy="no-referrer"/>
		<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer"/>
		<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/three-dots/0.2.1/three-dots.min.css" integrity="sha512-dWmVYu6HOa5uQf4SwTAGU1i0G9oOEDKX2+8ZOcown+l6dmFstrnv2ucyCnuVs3XmSIZzz976nGNNNg/CIska0A==" crossorigin="anonymous" referrerpolicy="no-referrer"/>
		<link rel="stylesheet" type="text/css" href="/style.css"/>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script>
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js" integrity="sha512-RXf+QSDCUQs5uwRKaDoXt55jygZZm2V++WUZduaU/Ui/9EGp3f/2KZVahFZBKGH0s774sd3HmrhUy+SgOFQLVQ==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script>
		<noscript><span class="text-light">this web app requires JavaScript to run. enable JavaScript to continue!</span></noscript>
	</head>
	<body>
		%sveltekit.body%
	</body>
</html>


================================================
FILE: frontend/source/components/access.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";
	import * as utils from "frontend/source/utils.js";
	import Navbar from "frontend/source/components/navbar.svelte";

	import * as svelte from "svelte";
	import axios from "axios";
	import underscore from "underscore";

	const globals_r = globals.readonly;
	const globals_w = globals.writable;
</script>
<script>
	export let username;
	
	let [
		last_updated_epoch,
		last_updated_wrappers_update_interval_id,
		last_updated_wrapper_1,
		last_updated_wrapper_2,
		search_input,
		search_btn,
		subreddit_select,
		subreddit_select_btn,
		subreddit_select_dropdown,
		category_btn_group,
		type_btn_group,
		item_list,
		skeleton_list,
		new_data_alert_wrapper
	] = [];

	let active_data = { // entire active_category data
		items: new Map(),
		item_sub_icon_urls: {}
	};
	let active_category = "saved";
	let active_type = "all";
	let active_sub = "all";
	let active_search_str = "";
	let active_item_ids = []; // ids of filtered items (by selected type, subreddit, and search string). only these items will be listed in item_list from active_data
	let items_currently_listed = 0;

	const intersection_observer = new IntersectionObserver((entries) => {
		for (const entry of entries) {
			if (entry.intersectionRatio > 0) { // observed element is in view
				intersection_observer.unobserve(entry.target);
				list_next_items(25);
			}
		}
	}, {
		root: document,
		rootMargin: "0px",
		threshold: 0
	});

	const debounced_hide_popover = underscore.debounce(() => {
		jQuery("[data-toggle='popover']").popover("hide");
	}, 100, true);

	async function handle_body_click(evt) {
		(evt.target.classList.contains("dropdown-item") || evt.target.parentElement?.classList.contains("dropdown-item") ? subreddit_select_btn.blur() : null);

		if (evt.target.dataset?.url) {
			window.open(evt.target.dataset.url, "_blank");
		} else if (evt.target.parentElement?.dataset?.url && evt.target.tagName != "BUTTON") {
			window.open(evt.target.parentElement.dataset.url, "_blank");
		}

		if (evt.target.classList.contains("copy_link_btn") || evt.target.classList.contains("text_btn") || evt.target.classList.contains("renew_btn")) {
			evt.target.classList.remove("btn-outline-secondary");
			evt.target.classList.add("btn-success");
			setTimeout(() => {
				evt.target.classList.remove("btn-success");
				evt.target.classList.add("btn-outline-secondary");
			}, 500);

			if (evt.target.classList.contains("copy_link_btn")) {
				window.navigator.clipboard.writeText(evt.target.parentElement.dataset.url).catch((err) => console.error(err));
			} else if (evt.target.classList.contains("text_btn")) {
				const post_text_wrapper = evt.target.parentElement.querySelector(".post_text_wrapper");
				if (post_text_wrapper.innerHTML == "") {
					try {
						const post_id = evt.target.parentElement.id;
						
						const response = await axios.get(`https://api.pushshift.io/reddit/search/submission?ids=${post_id}&fields=selftext`);
						const response_data = response.data;

						const post_text = response_data.data[0].selftext;
						post_text_wrapper.innerHTML = (post_text ? underscore.escape(post_text) : "[this is not a text post]");
					} catch (err) {
						console.error(err);
						post_text_wrapper.innerHTML = "[error: pushshift currently down. please try again later]";
					}
				}
				post_text_wrapper.classList.toggle("d-none");
			} else if (evt.target.classList.contains("renew_btn")) {
				const comment_id = evt.target.parentElement.id;

				globals_r.socket.emit("get comment from reddit", comment_id);
				globals_r.socket.once("got comment from reddit", (comment_content) => {
					const content_wrapper = evt.target.parentElement.querySelector(".content_wrapper");
					content_wrapper.innerHTML = underscore.escape(comment_content);

					$globals_w.firebase_db.ref(`${active_category}/items/${comment_id}/content`).set(comment_content).catch((err) => console.error(err));
				});
			}
		}
		
		if (evt.target.classList.contains("delete_btn")) {
			const item_id = evt.target.parentElement.id;

			const all_opened_popovers = document.querySelectorAll(".popover");
			for (const popover of all_opened_popovers) {
				const popover_item_id = popover.children[2].children[0].classList[0];
				
				(popover_item_id != item_id ? jQuery(popover).popover("hide") : null);
			}
		} else if (evt.target.classList.contains("row_1_popover_btn")) {
			const all_row_1_popover_btns = document.querySelectorAll(".row_1_popover_btn");
			for (const btn of all_row_1_popover_btns) {
				if (btn != evt.target) {
					btn.classList.remove("active");
				} else {
					btn.classList.toggle("active");
				}
			}
		} else if (evt.target.classList.contains("delete_item_confirm_btn")) {
			const opened_popover = document.querySelector(".popover");

			let delete_from = null;
			const all_row_1_popover_btns = document.querySelectorAll(".row_1_popover_btn");
			for (const btn of all_row_1_popover_btns) {
				(btn.classList.contains("active") ? delete_from = btn.innerHTML : null);
			}
			if (!delete_from) {
				for (const btn of [...all_row_1_popover_btns]) {
					utils.shake_element(btn);
				}
				return;
			} else {
				jQuery(opened_popover).popover("hide");
			}

			const item_id = evt.target.parentElement.parentElement.classList[0];
			const item_category = active_category;
			const item_type = document.querySelector(`[id="${item_id}"]`).dataset.type;

			if (delete_from == "eternity" || delete_from == "both") {
				const list_item = document.querySelector(`[id="${item_id}"]`);
				list_item.innerHTML = "";
				list_item.removeAttribute("data-url");
				list_item.removeAttribute("data-type");
				list_item.className = "";
				list_item.classList.add("skeleton_item", "rounded", "mb-2");

				try {
					await $globals_w.firebase_db.ref(`${item_category}/items/${item_id}`).remove();
	
					list_item.remove();
					active_item_ids.splice(active_item_ids.indexOf(item_id), 1);
					active_data.items.delete(item_id);
				} catch (err) {
					console.error(err);
				}
			}
			if (delete_from == "Reddit" || delete_from == "both") {
				globals_r.socket.emit("delete item from reddit acc", item_id, item_category, item_type);
			}
		} else if (!evt.target.classList.contains("row_2_popover_btn") && document.querySelector(".popover")?.contains(evt.target)) {
			null;
		} else {
			jQuery("[data-toggle='popover']").popover("hide");
		}

		if (evt.target.parentElement == category_btn_group) {
			const selected_category = await new Promise((resolve, reject) => {
				setTimeout(() => {
					let category = null;
					for (const btn of [...(category_btn_group.children)]) {
						(btn.classList.contains("active") ? category = btn.innerText : null);
					}
					resolve(category);
				}, 100);
			});
			if (selected_category != active_category) {
				active_category = selected_category;
				show_skeleton_loading();
				try {
					await get_parse_set_active_data();
				} catch (err) {
					console.error(err);
				}
				refresh_item_list();
				hide_skeleton_loading();
				update_search_placeholder();
				fill_subreddit_select();
			}
		} else if (evt.target.parentElement == type_btn_group) {
			const selected_type = await new Promise((resolve, reject) => {
				setTimeout(() => {
					let type = null;
					for (const btn of [...(type_btn_group.children)]) {
						(btn.classList.contains("active") ? type = btn.innerText : null);
					}
					resolve(type);
				}, 100);
			});
			if (selected_type != active_type) {
				active_type = selected_type;
				refresh_item_list();
				update_search_placeholder();
				fill_subreddit_select();
			}
		}

		if (evt.target.id == "refresh_btn") {
			new_data_alert_wrapper.classList.add("d-none");
			show_skeleton_loading();
			try {
				await get_parse_set_active_data();
			} catch (err) {
				console.error(err);
			}
			refresh_item_list();
			hide_skeleton_loading();
			update_search_placeholder();
			fill_subreddit_select();
		}
	}

	function handle_body_keydown(evt) {
		if (evt.key == "Escape") {
			jQuery("[data-toggle='popover']").popover("hide");
		}
		
		setTimeout(() => {
			const no_results = document.querySelector(".no-results");
			(no_results && !no_results.classList.contains("d-none") ? no_results.classList.add("d-none") : null);

			(subreddit_select_dropdown && typeof subreddit_select_dropdown != "number" && !subreddit_select_dropdown.classList.contains("show") ? subreddit_select_btn.blur() : null);
		}, 100);
	}

	async function get_parse_set_active_data() {
		active_data.items.clear();
		active_data.item_sub_icon_urls = {};

		const snapshot = await $globals_w.firebase_db.ref(active_category).get();
		const data = snapshot.val();
		if (data) {
			if (data.items) {
				const sorted_items_entries = Object.entries(data.items).sort((a, b) => b[1].created_epoch - a[1].created_epoch); // sort by created_epoch, descending
				for (const entry of sorted_items_entries) {
					const item_key = entry[0];
					const item_value = entry[1];
			
					active_data.items.set(item_key, item_value);
				}
			}

			if (data.item_sub_icon_urls) {
				const icon_urls_entries = Object.entries(data.item_sub_icon_urls);
				for (const entry of icon_urls_entries) {
					const icon_url_key = entry[0];
					const icon_url_value = entry[1];

					active_data.item_sub_icon_urls[icon_url_key.replace("|", "/").replace(",", ".")] = icon_url_value;
				}
			}	
		}
	}

	function show_skeleton_loading() {
		item_list.scrollTop = 0;
		item_list.classList.add("d-none");
		skeleton_list.classList.remove("d-none");
	}

	function hide_skeleton_loading() {
		skeleton_list.classList.add("d-none");
		item_list.classList.remove("d-none");
		item_list.scrollTop = 0;
	}

	function set_active_item_ids() { // filter ➔ set
		// filter by selected type
		switch (active_type) {
			case "all":
				active_item_ids = [...(active_data.items.keys())];
				break;
			case "posts":
			case "comments":
				active_item_ids = [];
				for (const entry of active_data.items) {
					const item_key = entry[0];
					const item_value = entry[1];

					(item_value.type == active_type.slice(0, -1) ? active_item_ids.push(item_key) : null);
				}
				break;
			default:
				break;
		}

		// filter by selected subreddit
		if (active_sub != "all") {
			const filtered_items = new Map();
			for (const item_id of active_item_ids) {
				filtered_items.set(item_id, active_data.items.get(item_id));
			}
		
			active_item_ids = [];
			for (const entry of filtered_items) {
				const item_key = entry[0];
				const item_value = entry[1];

				(item_value.sub == active_sub ? active_item_ids.push(item_key) : null);
			}
		}

		// filter by search string
		if (active_search_str != "") {
			const space_delimited_search_input = active_search_str.split(" ").map((term, idx, arr) => term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); // escape regex special chars: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

			const filtered_items = new Map();
			for (const item_id of active_item_ids) {
				filtered_items.set(item_id, active_data.items.get(item_id));
			}
		
			active_item_ids = [];
			for (const entry of filtered_items) {
				const item_key = entry[0];
				const item_value = entry[1];

				let matches = 0;
				for (const term of space_delimited_search_input) {
					const re = new RegExp(term, "i");
					(re.test(item_value.sub) || re.test(item_value.author) || re.test(item_value.content) ? matches++ : null);
				}
				(matches == space_delimited_search_input.length ? active_item_ids.push(item_key) : null);
			}
		}
	}

	function list_next_items(count) {
		if (active_type == "comments" && (active_category == "upvoted" || active_category == "downvoted" || active_category == "hidden")) {
			item_list.innerHTML = `<div class="list-group-item text-light lead">${active_category} comment data not provided by Reddit api</div>`;
			return;
		}

		const max_items = active_item_ids.length;
		if (max_items == 0) {		
			item_list.innerHTML = '<div class="list-group-item text-light lead">no results</div>';
			return;
		}
		
		const x = items_currently_listed + count;
		while (items_currently_listed < x && items_currently_listed < max_items) {
			const item_id = active_item_ids[items_currently_listed];
			const item = active_data.items.get(item_id);

			item_list.insertAdjacentHTML("beforeend", `
				<div id="${item_id}" class="list-group-item list-group-item-action text-left text-light p-1" data-url="${item.url}" data-type="${item.type}">
					<a href="https://www.reddit.com/${item.sub}" target="_blank"><img src="${active_data.item_sub_icon_urls[item.sub]}" class="rounded-circle${(active_data.item_sub_icon_urls[item.sub] == "#" ? "" : " border border-light")}"/></a><small><a href="https://www.reddit.com/${item.sub}" target="_blank"><b class="ml-2">${item.sub}</b></a> &bull; <a href="https://www.reddit.com/${item.author}" target="_blank">${item.author}</a> &bull; <i data-url="${item.url}" data-toggle="tooltip" data-placement="top" title="${utils.epoch_to_formatted_datetime(item.created_epoch)}">${utils.time_since(item.created_epoch)}</i></small>
					<p class="lead line_height_1 m-0" data-url="${item.url}"><${(item.type == "post" ? "b" : "small")} class="content_wrapper noto_sans">${underscore.escape(item.content)}</${(item.type == "post" ? "b" : "small")}></p>
					<button type="button" class="delete_btn btn btn-sm btn-outline-secondary shadow-none border-0 py-0" data-toggle="popover" data-placement="right" data-title="delete item from" data-content='<div class="${item_id}"><div><span class="row_1_popover_btn btn btn-sm btn-primary float-left px-0">eternity</span><span class="row_1_popover_btn btn btn-sm btn-primary float-center px-0">Reddit</span><span class="row_1_popover_btn btn btn-sm btn-primary float-right px-0">both</span></div><div><span class="row_2_popover_btn btn btn-sm btn-secondary float-left mt-2">cancel</span><span class="row_2_popover_btn delete_item_confirm_btn btn btn-sm btn-danger float-right mt-2">confirm</span></div><div class="clearfix"></div></div>' data-html="true">delete</button> <button type="button" class="copy_link_btn btn btn-sm btn-outline-secondary shadow-none border-0 py-0">copy link</button> <button type="button" class="${(item.type == "post" ? "text" : "renew")}_btn btn btn-sm btn-outline-secondary shadow-none border-0 py-0">${(item.type == "post" ? "text" : "renew")}</button>
					${(item.type == "post" ? '<p class="post_text_wrapper noto_sans line_height_1 d-none m-0"></p>' : "")}
				</div>
			`);

			(++items_currently_listed == x-Math.floor(count/2)-1 ? intersection_observer.observe(document.querySelector(`[id="${item_id}"]`)) : null);

			jQuery('[data-toggle="tooltip"]').tooltip("enable");
			jQuery('[data-toggle="popover"]').popover("enable");
		}
	}

	function refresh_item_list() {
		intersection_observer.disconnect(); // stops observing all currently observed elements. (does NOT stop the intersection observer. i.e., it can still observe new elements)
		item_list.innerHTML = "";
		item_list.scrollTop = 0;
		items_currently_listed = 0;

		set_active_item_ids();
		list_next_items(25);
	}

	function update_search_placeholder() {
		const item_count = active_item_ids.length;
		search_input.placeholder = `search ${item_count} item${(item_count == 1 ? "" : "s")}`;
	}

	function fill_subreddit_select() {
		subreddit_select.innerHTML = "<option>all</option>";

		let subs = new Set();
		if (active_type == "all") {
			for (const entry of active_data.items) {
				const item_key = entry[0];
				const item_value = entry[1];

				subs.add(item_value.sub);
			}
		} else {
			for (const entry of active_data.items) {
				const item_key = entry[0];
				const item_value = entry[1];

				(item_value.type == active_type.slice(0, -1) ? subs.add(item_value.sub) : null);
			}
		}

		subs = [...subs];
		subs.sort((a, b) => a.localeCompare(b, "en"));

		for (const sub of subs) {
			subreddit_select.insertAdjacentHTML("beforeend", `
				<option>${sub}</option>
			`);
		}
		jQuery(subreddit_select).selectpicker("refresh");
		jQuery(subreddit_select).selectpicker("render");
	}

	svelte.onMount(async () => {
		globals_r.socket.emit("page", "access");
		
		globals_r.socket.on("store last updated epoch", (epoch) => {
			last_updated_epoch = epoch;
		});

		globals_r.socket.on("show refresh alert", (categories_w_new_data) => {
			for (const category of categories_w_new_data) {
				if (category == active_category) {
					new_data_alert_wrapper.classList.remove("d-none");
					utils.show_alert(new_data_alert_wrapper, '<span class="ml-1">new data available!</span><button id="refresh_btn" class="btn btn-sm btn-primary ml-2">refresh</button>', "primary");
					break;
				}
			}
		});

		last_updated_wrappers_update_interval_id = setInterval(() => {
			if (last_updated_epoch) {
				last_updated_wrapper_1.innerHTML = utils.time_since(last_updated_epoch);
				last_updated_wrapper_2.innerHTML = utils.epoch_to_formatted_datetime(last_updated_epoch);
			}
		}, 1000);

		try {
			await new Promise((resolve, reject) => {
				const interval_id = setInterval(() => {
					if ($globals_w.firebase_app && $globals_w.firebase_auth && $globals_w.firebase_db) {
						clearInterval(interval_id);
						resolve();
					}
				}, 100);
			});

			await get_parse_set_active_data();
			refresh_item_list();
			hide_skeleton_loading();
			update_search_placeholder();
			fill_subreddit_select();
		} catch (err) {
			console.error(err);
		}

		jQuery(subreddit_select).selectpicker();
		subreddit_select_btn = document.querySelector(".bs-placeholder");
		subreddit_select_dropdown = document.querySelector(".bootstrap-select");

		jQuery(subreddit_select).on("changed.bs.select", (evt, clicked_idx, is_selected, previous_value) => { // https://developer.snapappointments.com/bootstrap-select/options/#events
			active_sub = evt.target.value;
			refresh_item_list();
			update_search_placeholder();
		});

		last_updated_wrapper_1.addEventListener("click", (evt) => {
			last_updated_wrapper_2.classList.toggle("d-none");
		});

		last_updated_wrapper_2.addEventListener("click", (evt) => {
			evt.target.classList.toggle("d-none");
		});

		subreddit_select_btn.addEventListener("click", (evt) => {
			(!subreddit_select_dropdown.classList.contains("show") ? subreddit_select_btn.blur() : null);
		});

		search_input.addEventListener("keydown", (evt) => {
			if (evt.target.value.trim() == "") {
				return;
			}

			switch (evt.key) {
				case "Enter":
					active_search_str = evt.target.value.trim();
					refresh_item_list();
					break;
				case "Escape":
					evt.target.value = "";
					active_search_str = "";
					refresh_item_list();
					break;
				case "Backspace":
				case "Delete":
					setTimeout(() => {
						if (active_search_str && evt.target.value.trim() == "") {
							active_search_str = "";
							refresh_item_list();
						}
					}, 100);
					break;
				default:
					break;
			}
		});

		search_btn.addEventListener("click", (evt) => {
			search_input.dispatchEvent(new KeyboardEvent("keydown", {
				key: "Enter"
			}));
		});

		item_list.addEventListener("scroll", (evt) => {
			debounced_hide_popover();
		});
	});
	svelte.onDestroy(() => {
		globals_r.socket.off("store last updated epoch");
		globals_r.socket.off("show refresh alert");

		clearInterval(last_updated_wrappers_update_interval_id);
	});
</script>

<svelte:body on:click={handle_body_click} on:keydown={handle_body_keydown}/>
<Navbar username={username} show_data_anchors={true}/>
<div class="text-center mt-3">
	<h1 class="display-4">{globals_r.app_name}</h1>
	<span>last updated: <b bind:this={last_updated_wrapper_1} id="last_updated_wrapper_1">?</b> ago</span>
	<br/>
	<small bind:this={last_updated_wrapper_2} class="d-none">?</small>
	<div class="d-flex justify-content-center">
		<div bind:this={new_data_alert_wrapper} class="px-1 d-none"></div>
	</div>
	<div id="access_container" class="card card-body bg-dark mt-3 pb-3">
		<form>
			<div class="form-row d-flex justify-content-center">
				<div bind:this={category_btn_group} class="btn-group btn-group-toggle flex-wrap" data-toggle="buttons">
					<label class="btn btn-secondary shadow-none active"><input type="radio" name="options"/>saved</label>
					<label class="btn btn-secondary shadow-none"><input type="radio" name="options"/>created</label>
					<label class="btn btn-secondary shadow-none"><input type="radio" name="options"/>upvoted</label>
					<label class="btn btn-secondary shadow-none"><input type="radio" name="options"/>downvoted</label>
					<label class="btn btn-secondary shadow-none"><input type="radio" name="options"/>hidden</label>
				</div>
			</div>
			<div class="form-row d-flex justify-content-center mt-2">
				<div bind:this={type_btn_group} class="btn-group btn-group-toggle flex-wrap" data-toggle="buttons">
					<label class="btn btn-secondary shadow-none"><input type="radio" name="options"/>posts</label>
					<label class="btn btn-secondary shadow-none"><input type="radio" name="options"/>comments</label>
					<label class="btn btn-secondary shadow-none active"><input type="radio" name="options"/>all</label>
				</div>
			</div>
			<div class="form-row mt-2">
				<div class="form-group col-12 col-sm-8 mb-0">
					<div class="d-flex input-group">
						<input bind:this={search_input} type="text" class="form-control bg-light" placeholder="search ? items"/>
						<div class="input-group-append"><button bind:this={search_btn} type="button" class="btn btn-light shadow-none"><i class="fa fa-search"></i></button></div>
					</div>
				</div>
				<div class="form-group col-12 col-sm-4 mb-0">
					<select bind:this={subreddit_select} class="selectpicker form-control" data-width="false" data-size="10" data-live-search="true" title="in subreddit: all">
						<option>all</option>
					</select>
				</div>
			</div>
		</form>
	</div>
	<div class="card card-body bg-dark border-top-0 mt-n2 pt-0 pb-2 pr-2">
		<div bind:this={item_list} class="list-group list-group-flush border-0 d-none" id="item_list"></div>
		<div bind:this={skeleton_list} class="list-group" id="skeleton_list">
			{#each {length: 7} as _, idx}
				<div class="skeleton_item rounded mb-2"></div>
			{/each}
		</div>
	</div>
</div>


================================================
FILE: frontend/source/components/footer.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";

	import * as svelte from "svelte";

	const globals_r = globals.readonly;
</script>
<script>
	let [
		dropdown_btn,
		dropdown_menu,
		last24hours_total_wrapper,
		last7days_total_wrapper,
		last30days_total_wrapper,
		last24hours_list_wrapper,
		last7days_list_wrapper,
		last30days_list_wrapper
	] = [];

	function handle_body_keydown(evt) {
		if (evt.key == "Escape") {
			setTimeout(() => {
				(!dropdown_menu.classList.contains("show") ? dropdown_btn.blur() : null);
			}, 100);
		}
	}

	function list_domain_request_info(countries, parent_ul) {
		parent_ul.innerHTML = "";
		
		if (countries.length == 0) {
			return;
		} else if (countries.length <= 3) {
			for (const country of countries) {
				parent_ul.insertAdjacentHTML("beforeend", `
					<li class="mt-n1">${country.clientCountryName}: ${country.requests}</li>
				`);
			}
		} else {
			for (const country of countries.slice(0, 3)) {
				parent_ul.insertAdjacentHTML("beforeend", `
					<li class="mt-n1">${country.clientCountryName}: ${country.requests}</li>
				`);
			}

			parent_ul.insertAdjacentHTML("beforeend", `
				<li class="mt-n1">${countries.length - 3} more</li>
			`);
		}
	}

	svelte.onMount(() => {
		globals_r.socket.on("update domain request info", (domain_request_info) => {
			if (!domain_request_info || Object.keys(domain_request_info).length == 0) {
				return;
			}
			
			last24hours_total_wrapper.innerHTML = domain_request_info.last24hours_total;
			last7days_total_wrapper.innerHTML = domain_request_info.last7days_total;
			last30days_total_wrapper.innerHTML = domain_request_info.last30days_total;

			list_domain_request_info(domain_request_info.last24hours_countries, last24hours_list_wrapper);
			list_domain_request_info(domain_request_info.last7days_countries, last7days_list_wrapper);
			list_domain_request_info(domain_request_info.last30days_countries, last30days_list_wrapper);
		});

		dropdown_btn.addEventListener("click", (evt) => {
			setTimeout(() => {
				(!dropdown_menu.classList.contains("show") ? dropdown_btn.blur() : null);
			}, 100);

			setTimeout(() => {
				dropdown_menu.scrollIntoView({
					behavior: "smooth",
					block: "end"
				});
			}, 250);
		});
	});
	svelte.onDestroy(() => {
		globals_r.socket.off("update domain request info");
	});
</script>

<svelte:body on:keydown={handle_body_keydown}/>
<footer class="text-center">
	<p class="font_size_10 m-0"><a href="/about">about</a></p>
	<p class="font_size_10 m-0"><a href="https://github.com/sponsors/jc9108" target="_blank">support this project</a></p>
	<p class="font_size_10 m-0">released under the <a href="https://choosealicense.com/licenses/agpl-3.0" target="_blank">AGPL3 License</a> &#169; <a href={globals_r.portals} target="_blank">portals</a></p>
	<p class="font_size_10 m-0"><a href={`${globals_r.portals}/stats`} target="_blank">cloudflare zone stats</a></p>
	<div class="btn-group dropdown">
		<button bind:this={dropdown_btn} type="button" class="btn btn-link dropdown-toggle mt-n2 px-1 py-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-display="static"></button>
		<div bind:this={dropdown_menu} class="dropdown-menu rounded-0 bg-light mt-n2 px-2 py-0" id="dropdown_menu">
			<p class="text-center m-0"><b>domain requests</b></p>
			<div class="dropdown-divider m-0"></div>
			<span>last 24 hours: <span bind:this={last24hours_total_wrapper}></span></span>
			<ul bind:this={last24hours_list_wrapper} class="m-0"></ul>
			<div class="dropdown-divider m-0"></div>
			<span>last 7 days: <span bind:this={last7days_total_wrapper}></span></span>
			<ul bind:this={last7days_list_wrapper} class="m-0"></ul>
			<div class="dropdown-divider m-0"></div>
			<span>last 30 days: <span bind:this={last30days_total_wrapper}></span></span>
			<ul bind:this={last30days_list_wrapper} class="m-0"></ul>
			<div class="dropdown-divider m-0"></div>
			<div class="text-center mt-n1">
				<a class="font_size_10" href={`${globals_r.portals}/stats`} target="_blank">full details</a>
			</div>
		</div>
	</div>
</footer>


================================================
FILE: frontend/source/components/landing.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";
	import Navbar from "frontend/source/components/navbar.svelte";

	import * as svelte from "svelte";

	const globals_r = globals.readonly;
</script>
<script>
	svelte.onMount(() => {
		globals_r.socket.emit("page", "landing");
	});
</script>

<Navbar/>
<div class="text-center mt-3">
	<div class="jumbotron bg-dark mb-0 py-5">
		<h1 class="display-4">{globals_r.app_name}</h1>
		<p class="lead text-left">{globals_r.description}</p>
		<p class="lead text-left">features: new items auto-sync, synced items not affected by Reddit deletion, search for items, filter by subreddit, import csv data from <a href="https://www.reddit.com/settings/data-request" target="_blank">Reddit data request</a>, export data as json</p>
		<hr class="bg-secondary my-4"/>
		<div class="embed-responsive embed-responsive-16by9">
			<iframe title="demo" class="embed-responsive-item" src="https://www.youtube.com/embed/4pxXM98ewIc" allow="fullscreen"></iframe>
		</div>
		<hr class="bg-secondary my-4"/>
		<p class="lead text-left">required <a href="https://www.reddit.com/dev/api/oauth" target="_blank">Reddit api oauth2 scopes</a>::</p>
		<ul class="text-left mt-n3">
			<li><a href="https://www.reddit.com/dev/api/oauth#scope_identity" target="_blank">identity</a>: to get your username</li>
			<li><a href="https://www.reddit.com/dev/api/oauth#scope_history" target="_blank">history</a>: to get your items</li>
			<li><a href="https://www.reddit.com/dev/api/oauth#scope_read" target="_blank">read</a>: to get icons of subreddits/users</li>
			<li><a href="https://www.reddit.com/dev/api/oauth#scope_save" target="_blank">save</a>: to unsave items (manual action)</li>
			<li><a href="https://www.reddit.com/dev/api/oauth#scope_edit" target="_blank">edit</a>: to delete items (manual action)</li>
			<li><a href="https://www.reddit.com/dev/api/oauth#scope_vote" target="_blank">vote</a>: to unvote items (manual action)</li>
			<li><a href="https://www.reddit.com/dev/api/oauth#scope_report" target="_blank">report</a>: to unhide items (manual action)</li>
		</ul>
		<div class="row">
			<div class="col-1 col-sm-3"></div>
			<div class="col-10 col-sm-6">
				<a id="login_anchor" class="d-flex justify-content-center" href="{globals_r.backend}/login" rel="external"><p class="rounded-pill lead text-white mt-2" id="login_btn">log in with <img id="reddit_logo" class="ml-n2 mr-n2 mb-1" src="/reddit logo on dark.svg" alt="reddit logo"/></p></a>
			</div>
			<div class="col-1 col-sm-3"></div>
		</div>
	</div>
</div>


================================================
FILE: frontend/source/components/loading.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";
	import Navbar from "frontend/source/components/navbar.svelte";

	import * as svelte from "svelte";

	const globals_r = globals.readonly;
</script>
<script>
	export let username;
	
	let progress_wrapper = null;

	const dispatch = svelte.createEventDispatcher();

	svelte.onMount(() => {
		globals_r.socket.emit("page", "loading");

		globals_r.socket.on("update progress", (progress, complete) => {
			const progress_percentage = progress/complete * 100;
			progress_wrapper.innerHTML = Math.floor(progress_percentage);
			if (progress_percentage == 100) {
				setTimeout(() => {
					dispatch("dispatch", "switch page to access");
				}, 2000);
			}
		});
	});
	svelte.onDestroy(() => {
		globals_r.socket.off("update progress");
	});
</script>

<Navbar username={username}/>
<div class="text-center mt-3 mb-4">
	<h1 class="display-4">{globals_r.app_name}</h1>
	<div id="loading_container" class="mt-1">
		<div class="spinner-border" role="status"><span class="sr-only">loading...</span></div>
		<p class="mt-n5"><span bind:this={progress_wrapper} class="lead">?</span>%</p>
	</div>
</div>


================================================
FILE: frontend/source/components/navbar.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";
	import * as utils from "frontend/source/utils.js";

	import * as svelte from "svelte";
	import * as xlsx from "xlsx";

	const globals_r = globals.readonly;
	const globals_w = globals.writable;
</script>
<script>
	export let username;
	export let show_data_anchors;
	export let show_return_to_app;

	let [
		settings_btn,
		settings_menu,
		import_anchor,
		import_notice,
		files_input,
		selected_files_list,
		import_cancel_btn,
		import_confirm_btn,
		export_anchor,
		new_tab_json,
		purge_anchor,
		purge_warning,
		purge_input,
		purge_cancel_btn,
		purge_confirm_btn,
		purge_spinner_container,
		redirect_notice,
		redirect_countdown_wrapper,
		modal
	] = [];

	function toggle_import_notice() {
		reset_import_notice();
		import_notice.classList.toggle("d-none");
	}

	function hide_import_notice() {
		reset_import_notice();
		(!import_notice.classList.contains("d-none") ? import_notice.classList.add("d-none") : null);
	}

	function reset_import_notice() {
		files_input.files = new DataTransfer().files;
		selected_files_list.innerHTML = "";
	}

	function toggle_purge_warning() {
		purge_input.value = "";
		purge_warning.classList.toggle("d-none");
	}

	function hide_purge_warning() {
		purge_input.value = "";
		(!purge_warning.classList.contains("d-none") ? purge_warning.classList.add("d-none") : null);
	}

	async function purge() {
		toggle_purge_warning();
		purge_spinner_container.classList.toggle("d-none");

		try {
			const response = await fetch(`${globals_r.backend}/purge?&socket_id=${globals_r.socket.id}`, {
				method: "get"
			});
			const response_data = await response.text();

			if (response_data == "success") {
				setTimeout(() => {
					window.location.reload();
				}, 10000);
				
				purge_spinner_container.classList.toggle("d-none");
				redirect_notice.classList.toggle("d-none");

				let countdown = 10;
				setInterval(() => {
					redirect_countdown_wrapper.innerHTML = --countdown;
				}, 1000);
			} else {
				console.error(response_data);
			}
		} catch (err) {
			console.error(err);
		}
	}

	svelte.onMount(() => {
		if (!username) {
			return;
		}

		settings_btn.addEventListener("click", (evt) => {
			setTimeout(() => {
				if (!settings_menu.classList.contains("show")) {
					settings_btn.blur();
					hide_purge_warning();
					(show_data_anchors ? hide_import_notice() : null);
				}
			}, 100);
		});

		settings_menu.addEventListener("click", (evt) => {
			evt.stopPropagation();
		});

		purge_anchor.addEventListener("click", (evt) => {
			evt.preventDefault();
			toggle_purge_warning();
			(show_data_anchors ? hide_import_notice() : null);
		});

		purge_cancel_btn.addEventListener("click", (evt) => {
			evt.preventDefault();
			toggle_purge_warning();
		});

		purge_confirm_btn.addEventListener("click", (evt) => {
			evt.preventDefault();
			(purge_input.value == `purge u/${username}` ? purge() : utils.shake_element(purge_input));
		});

		purge_input.addEventListener("keydown", (evt) => {
			if (evt.key == "Enter") {
				evt.preventDefault();
				(purge_input.value == `purge u/${username}` ? purge() : utils.shake_element(purge_input));
			}
		});

		if (!show_data_anchors) {
			return;
		}

		import_anchor.addEventListener("click", (evt) => {
			evt.preventDefault();
			hide_purge_warning();
			toggle_import_notice();
		});

		import_cancel_btn.addEventListener("click", (evt) => {
			evt.preventDefault();
			toggle_import_notice();
		});

		import_confirm_btn.addEventListener("click", async (evt) => {
			evt.preventDefault();

			selected_files_list.innerHTML = "";
			if (files_input.files.length == 0) {
				selected_files_list.insertAdjacentHTML("beforeend", `
					<li class="mb-1"><b class="text-danger">NO FILE(S) SELECTED</b></li>
				`);
				return;
			} else {
				selected_files_list.insertAdjacentHTML("beforeend", `
					<li class="mb-1"><b class="text-danger">PREPARING IMPORT. DO NOT CLOSE THIS PAGE UNTIL IT'S READY. YOU WILL KNOW WHEN YOU SEE A MODAL (POPUP)</b></li>
				`);
			}

			const item_fns = {};

			const categories = ["saved", "created", "upvoted", "downvoted", "hidden"];
			for (const category of categories) {
				item_fns[category] = [];
			}

			for (const file_idx in ((({length, ...rest}) => rest)(files_input.files))) {
				const file = files_input.files[file_idx];

				const csv = await new Promise((resolve, reject) => {
					const reader = new FileReader();
					reader.readAsBinaryString(file);
					reader.onloadend = function (evt) {
						resolve(xlsx.read(evt.target.result, {
							type: "binary"
						}));
					}
					reader.onerror = function (evt) {
						reject(reader.error);
					}
				});
				const sheet_list = csv.SheetNames;
				const sheet = csv.Sheets[sheet_list[0]];
				const items = xlsx.utils.sheet_to_json(sheet);

				switch (file.name) {
					case "saved_posts.csv":
						item_fns.saved.push(...(items.map((item, idx, arr) => `t3_${item.id}`)));
						break;
					case "saved_comments.csv":
						item_fns.saved.push(...(items.map((item, idx, arr) => `t1_${item.id}`)));
						break;
					case "posts.csv":
						item_fns.created.push(...(items.map((item, idx, arr) => `t3_${item.id}`)));
						break;
					case "comments.csv":
						item_fns.created.push(...(items.map((item, idx, arr) => `t1_${item.id}`)));
						break;
					case "post_votes.csv":
						for (const item of items) {
							(item.direction == "none" ? null : item_fns[`${item.direction}voted`].push(`t3_${item.id}`));
						}
						break;
					case "hidden_posts.csv":
						item_fns.hidden = items.map((item, idx, arr) => `t3_${item.id}`);
						break;
					default:
						break;
				}
			}

			const updates = {};
			for (const category in item_fns) {
				if (item_fns[category].length > 0) {
					for (const fn of item_fns[category]) {
						(fn.includes(".") ? null : updates[`${category}/item_fns_to_import/${fn}`] = fn); // exclude anomaly fns: see thread https://www.reddit.com/r/help/comments/rztejh/saved_posts_beyond_the_1000_visible_limit
					}
				}
			}
			await $globals_w.firebase_db.ref().update(updates);

			jQuery(modal).modal("show");
		});

		files_input.addEventListener("input", (evt) => {
			selected_files_list.innerHTML = "";

			for (let i = 0; i < files_input.files.length; i++) {
				const file = files_input.files[i];
				const filename = file.name;
				const filesize = file.size; // in binary bytes
				const filesize_limit = 10485760; // 10mb in binary bytes

				switch (filename) {
					case "saved_posts.csv":
					case "saved_comments.csv":
					case "posts.csv":
					case "comments.csv":
					case "post_votes.csv":
					case "hidden_posts.csv":
						selected_files_list.insertAdjacentHTML("beforeend", `
							<li class="mb-1"><b><code class="text-dark">${filename}</code></b></li>
						`);
						break;
					default:
						reset_import_notice();
						selected_files_list.insertAdjacentHTML("beforeend", `
							<li class="mb-1"><b class="text-danger">UNALLOWED FILE SELECTED. PLEASE TRY AGAIN</b></li>
						`);
						return;
				}

				if (filesize > filesize_limit) {
					reset_import_notice();
					selected_files_list.insertAdjacentHTML("beforeend", `
						<li class="mb-1"><b class="text-danger">PER-FILE SIZE LIMIT IS 10mb</b></li>
					`);
					return;
				}
			}
		});

		export_anchor.addEventListener("click", async (evt) => {
			evt.preventDefault();
			
			try {
				const id_token = await $globals_w.firebase_auth.currentUser.getIdToken();
				new_tab_json.href = `${$globals_w.firebase_app.options.databaseURL}/.json?print=pretty&auth=${id_token}`;
				new_tab_json.click();
			} catch (err) {
				console.error(err);
			}
		});
	});
</script>

<nav class="mt-5 px-5">
	{#if username}
		<span class="float-right">
			<a href="https://www.reddit.com/u/{username}" target="_blank">u/<span id="username_wrapper">{username}</span></a>
			<div class="btn-group dropdown">
				<button bind:this={settings_btn} type="button" class="btn btn-link pl-1 py-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-display="static" id="settings_btn"><i class="fas fa-cog"></i></button>
				<div bind:this={settings_menu} class="dropdown-menu dropdown-menu-right text-center mr-2 px-2 py-0" id="settings_menu">
					<a href="{globals_r.backend}/logout">logout</a>
					<div class="dropdown-divider m-0"></div>
					{#if show_data_anchors}
						<a bind:this={import_anchor} href="#">import data</a>
						<div bind:this={import_notice} class="bg-info rounded text-light text-left line_height_1 mb-2 pb-1 d-none">
							<p class="mx-1">import data that you downloaded from <a href="https://www.reddit.com/settings/data-request" target="_blank" class="text-dark">Reddit data request</a></p>
							<p class="mx-1">extract the zip, then select the file(s) you want to import out of the following::</p>
							<ul class="mt-n3 ml-3 pl-3 pr-0">
								<li><code class="text-dark">saved_posts.csv</code></li>
								<li><code class="text-dark">saved_comments.csv</code></li>
								<li><code class="text-dark">posts.csv</code></li>
								<li><code class="text-dark">comments.csv</code></li>
								<li><code class="text-dark">post_votes.csv</code></li>
								<li><code class="text-dark">hidden_posts.csv</code></li>
							</ul>
							<hr class="bg-muted mx-2 mb-2 mt-n2"/>
							<form>
								<div class="form-group d-flex justify-content-center mb-0">
									<input bind:this={files_input} type="file" accept=".csv" class="form-control-file" id="files_input" style="display:none" multiple/>
									<label for="files_input" class="btn btn-outline-secondary border-dark bg-light text-dark py-0" id="files_input_btn">browse files</label>
								</div>
								<ul bind:this={selected_files_list} class="mb-0 ml-3 pl-3 pr-0"></ul>
								<hr class="bg-muted mx-2 mb-2 mt-0"/>
								<button bind:this={import_cancel_btn} class="btn btn-sm btn-secondary float-left ml-1">cancel</button><button bind:this={import_confirm_btn} class="btn btn-sm btn-secondary float-right mr-1">confirm</button>
								<div class="clearfix"></div>
							</form>
						</div>
						<div class="dropdown-divider m-0"></div>
						<a bind:this={export_anchor} href="#">export data</a>
						<a bind:this={new_tab_json} href="#" target="_blank" class="d-none"></a>
						<div class="dropdown-divider m-0"></div>
					{/if}
					<a bind:this={purge_anchor} href="#">purge account</a>
					<div bind:this={purge_warning} class="bg-danger rounded text-light text-left line_height_1 mb-2 pb-1 d-none">
						<p class="mx-1">are you sure you want to purge your eternity account?</p>
						<p class="mx-1">your new Reddit items will not continue to sync to your database</p>
						<p class="mx-1">this cannot be undone</p>
						<p class="mx-1 mb-0">type <b>purge u/{username}</b> to confirm</p>
						<form>
							<div class="form-group d-flex justify-content-center mb-1">
								<input bind:this={purge_input} class="form-control form-control-sm" type="text" id="purge_input"/>
							</div>
							<button bind:this={purge_cancel_btn} class="btn btn-sm btn-secondary float-left ml-1">cancel</button><button bind:this={purge_confirm_btn} class="btn btn-sm btn-secondary float-right mr-1">confirm</button>
							<div class="clearfix"></div>
						</form>
					</div>
					<div bind:this={purge_spinner_container} class="rounded my-2 py-5 d-none" id="purge_spinner_container">
						<div class="spinner-border text-secondary" role="status"><span class="sr-only">loading...</span></div>
					</div>
					<div bind:this={redirect_notice} class="rounded line_height_1 my-2 d-none" id="redirect_notice">
						<p>your account has been successfully purged from eternity</p>
						<p class="mb-0">you will be automatically redirected in <b bind:this={redirect_countdown_wrapper}>?</b>s</p>
					</div>
				</div>
			</div>
		</span>
	{:else if show_return_to_app}
		<span class="float-right">
			<a href="/">return to app</a>
		</span>
	{/if}
	<div class="clearfix"></div>
</nav>
{#if show_data_anchors}
	<div bind:this={modal} class="modal fade" tabindex="-1">
		<div class="modal-dialog modal-lg">
			<div class="modal-content bg-secondary">
				<div class="modal-header">
					<h5 class="modal-title">IMPORT STARTED</h5>
					<button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
				</div>
				<div class="modal-body">
					<span>import started. it may take up to a day to complete. do not try to re-import if you don't see all the items in eternity immediately. you can close/leave this page now</span>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-light" data-dismiss="modal">ok</button>
				</div>
			</div>
		</div>
	</div>
{/if}


================================================
FILE: frontend/source/components/unlock.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";
	import * as utils from "frontend/source/utils.js";
	import Navbar from "frontend/source/components/navbar.svelte";

	import * as svelte from "svelte";

	const globals_r = globals.readonly;
</script>
<script>
	export let username;
	
	let [
		instruction_video_anchor,
		instruction_video_wrapper,
		config_input,
		file_input,
		file_input_label,
		validate_btn,
		firebase_alert_wrapper,
		email_input,
		confirm_btn,
		verification_code_input,
		verify_btn,
		email_alert_wrapper,
		save_and_continue_btn_wrapper,
		save_and_continue_btn
	] = [];
	
	const dispatch = svelte.createEventDispatcher();

	function handle_body_keydown(evt) {
		if (evt.key == "Enter") {
			(!save_and_continue_btn.hasAttribute("disabled") ? save_and_continue_btn.click() : null);
		}
	}

	svelte.onMount(() => {
		globals_r.socket.emit("page", "unlock");

		globals_r.socket.on("alert", (alert, msg, type) => {
			switch (alert) {
				case "firebase":
					utils.show_alert(firebase_alert_wrapper, msg, type);
					break;
				case "email":
					utils.show_alert(email_alert_wrapper, msg, type);
					break;
				default:
					break;
			}
		});

		globals_r.socket.on("disable button", (button) => {
			switch (button) {
				case "validate":
					validate_btn.setAttribute("disabled", "");
					break;
				case "confirm":
					confirm_btn.setAttribute("disabled", "");
					break;
				case "verify":
					verify_btn.setAttribute("disabled", "");
					break;
				default:
					break;
			}
		});

		globals_r.socket.on("enable button", (button) => {
			switch (button) {
				case "verify":
					verify_btn.removeAttribute("disabled");
					break;
				case "save_and_continue":
					jQuery('[data-toggle="tooltip"]').tooltip("disable");
					save_and_continue_btn.removeAttribute("disabled");
					break;
				default:
					break;
			}
		});

		globals_r.socket.on("switch page to loading", () => {
			dispatch("dispatch", "switch page to loading");
		});

		jQuery('[data-toggle="tooltip"]').tooltip("enable");

		instruction_video_anchor.addEventListener("click", (evt) => {
			evt.preventDefault();
			instruction_video_wrapper.classList.toggle("d-none");
		});

		file_input.addEventListener("input", (evt) => {
			file_input_label.innerText = file_input.files[0].name;
		});

		config_input.addEventListener("keydown", (evt) => {
			switch (evt.key) {
				case "Enter":
					validate_btn.click();
					break;
				case "Tab":
					evt.preventDefault();
					email_input.focus();
					break;
				default:
					break;
			}
		});

		validate_btn.addEventListener("click", (evt) => {
			if (!config_input.value) {
				utils.show_alert(firebase_alert_wrapper, "provide the web app config", "warning");
				return;
			}

			let web_app_config = null;
			try {
				web_app_config = JSON.parse(config_input.value.replace(/(\s)/g, "").replace(";", "").replace("{", '{"').replaceAll(':"', '":"').replaceAll('",', '","'));
			} catch (err) {
				console.error(err);
				utils.show_alert(firebase_alert_wrapper, "this is not a Firebase web app config", "danger");
				return;
			}

			if (!file_input.value) {
				utils.show_alert(firebase_alert_wrapper, "provide the service account key file", "warning");
				return;
			}

			const file = file_input.files[0];
			const filename = file.name;
			const filesize = file.size; // in binary bytes
			const filesize_limit = 3072; // 3kb in binary bytes. firebase service account key files should be ~2.3kb

			if (filename.split(".").pop().toLowerCase() != "json" || filesize > filesize_limit) {
				utils.show_alert(firebase_alert_wrapper, "this is not a Firebase service account key file", "danger");
				return;
			}

			const data = new FormData();
			data.append("key", file, file.name);

			const request = new XMLHttpRequest();
			request.open("post", `${globals_r.backend}/upload`);
			request.responseType = "json";

			request.addEventListener("error", (evt) => {
				utils.show_alert(firebase_alert_wrapper, "save error", "danger");
			});

			request.onreadystatechange = function () {
				if (this.readyState == 4 && this.status == 200) {
					utils.show_alert(firebase_alert_wrapper, '<div class="d-flex justify-content-center pt-1"><div class="dot-carousel mr-4"></div><span class="mt-n1">validating key and database</span><div class="dot-carousel ml-4"></div></div>', "success");

					setTimeout(() => {
						globals_r.socket.emit("validate firebase info", web_app_config);
					}, 2000);
				}
			}
		
			request.send(data);
		});

		email_input.addEventListener("keydown", (evt) => {
			(evt.key == "Enter" ? confirm_btn.click() : null);
		});

		confirm_btn.addEventListener("click", (evt) => {
			const email = email_input.value.trim();

			if (!(email && email.includes("@") && email.includes(".") && email.length >= 7)) {
				utils.show_alert(email_alert_wrapper, "this is not an email address", "warning");
				return;
			}

			globals_r.socket.emit("confirm email", email);
			verification_code_input.focus();
		});

		verification_code_input.addEventListener("keydown", (evt) => {
			(evt.key == "Enter" ? verify_btn.click() : null);
		});

		verification_code_input.addEventListener("keyup", (evt) => {
			evt.target.value = evt.target.value.toUpperCase();
		});

		verify_btn.addEventListener("click", (evt) => {
			const code = verification_code_input.value;
			globals_r.socket.emit("verify code", username, code);
		});

		save_and_continue_btn_wrapper.addEventListener("mouseenter", (evt) => {
			(save_and_continue_btn.disabled ? jQuery('[data-toggle="tooltip"]').tooltip("show") : null);
		});

		save_and_continue_btn_wrapper.addEventListener("mouseleave", (evt) => {
			(save_and_continue_btn.disabled ? jQuery('[data-toggle="tooltip"]').tooltip("hide") : null);
		});

		save_and_continue_btn.addEventListener("click", (evt) => {
			evt.target.innerHTML = '<div class="d-flex justify-content-center pt-2"><div class="dot-carousel mr-4"></div><span class="mt-n2">saving</span><div class="dot-carousel ml-4"></div></div>';

			setTimeout(() => {
				globals_r.socket.emit("save firebase info and email");
			}, 2000);
		});
	});
	svelte.onDestroy(() => {
		globals_r.socket.off("alert");
		globals_r.socket.off("disable button");
		globals_r.socket.off("allow save and continue");
		globals_r.socket.off("switch page to loading");
	});
</script>

<svelte:body on:keydown={handle_body_keydown}/>
<Navbar username={username}/>
<div class="text-center mt-3">
	<h1 class="display-4">{globals_r.app_name}</h1>
	<div id="unlock_container" class="card card-body bg-dark text-left mt-3 pb-3">
		<div class="form-group">
			<div class="text-center">
				<b><a bind:this={instruction_video_anchor} href="#">SETUP GUIDE VIDEO</a></b>
				<span bind:this={instruction_video_wrapper} class="no_bullet embed-responsive embed-responsive-16by9 d-none"><iframe title="firebase setup guide" class="embed-responsive-item" src="https://www.youtube.com/embed/KPxppovc56A" allow="fullscreen"></iframe></span>
			</div>
			<p class="mt-4">to use eternity, you will need to go to <a href="https://console.firebase.google.com" target="_blank">Firebase console</a> and</p>
			<ul class="line_height_1 mt-n2">
				<li class="mt-2">create a new Firebase project <span class="text-light">named <b>{`eternity-${username.split("_").join("-")}`}</b></span></li>
				<li class="mt-2">create a Realtime Database where your Reddit items will be stored</li>
				<li class="mt-2">set the Realtime Database read and write security rules to <b>"auth.token.owner == true"</b></li>
				<li class="mt-2">enable Authentication from domain <b>eternity.portals.sh</b></li>
				<li class="mt-2">get a service account key file and a web app config</li>
				<li class="no_bullet d-flex mt-2">
					<div class="w-100">
						<div class="custom-file">
							<input bind:this={file_input} class="custom-file-input" type="file" accept=".json" id="file_input"/>
							<label bind:this={file_input_label} for="file_input" class="custom-file-label text-left bg-light">Firebase service account key file</label>
						</div>
						<input bind:this={config_input} type="text" class="form-control bg-light mt-1" placeholder="Firebase web app config"/>
					</div>
					<button bind:this={validate_btn} class="btn btn-primary shadow-none ml-2">validate</button>
				</li>
				<li class="no_bullet mt-2"><div bind:this={firebase_alert_wrapper}></div></li>
				<li class="mt-2">provide an email for account notifications and recovery</li>
				<li class="no_bullet mt-2">
					<div class="d-flex w-100">
						<input bind:this={email_input} type="text" class="form-control bg-light" placeholder="email address"/>
						<button bind:this={confirm_btn} class="btn btn-primary shadow-none ml-2">confirm</button>
					</div>
					<div class="d-flex w-100 mt-2">
						<input bind:this={verification_code_input} type="text" class="form-control bg-light" placeholder="verification code"/>
						<button bind:this={verify_btn} class="btn btn-primary shadow-none ml-2" disabled>verify</button>
					</div>
				</li>
				<li class="no_bullet mt-2"><div bind:this={email_alert_wrapper}></div></li>
			</ul>
			<div bind:this={save_and_continue_btn_wrapper} data-toggle="tooltip" data-trigger="manual" data-placement="top" title="complete the required steps above first">
				<button bind:this={save_and_continue_btn} class="btn btn-primary shadow-none w-100 mt-3" disabled>save and continue</button>
			</div>
		</div>
	</div>
</div>


================================================
FILE: frontend/source/global.d.ts
================================================
/// <reference types="@sveltejs/kit"/>


================================================
FILE: frontend/source/globals.js
================================================
import * as app_env from "$app/env";
import * as env_static_public from "$env/static/public";
import * as store from "svelte/store";
import * as socket_io_client from "socket.io-client";

const readonly = {
	app_name: "eternity",
	description: "bypass Reddit's 1000-item listing limits by externally storing your Reddit items (saved, created, upvoted, downvoted, hidden) in your own database",
	repo: "https://github.com/jc9108/eternity",
	backend: (env_static_public.RUN == "dev" ? "/backend" : ""),
	socket: socket_io_client.io((env_static_public.RUN == "dev" ? `http://${(app_env.browser ? window.location.hostname : "localhost")}:${Number.parseInt(env_static_public.PORT)+1}` : "")),
	portals: (env_static_public.RUN == "dev" ? `http://${(app_env.browser ? window.location.hostname : "localhost")}:1025` : "https://portals.sh")
};

const writable = store.writable({
	firebase_app: null,
	firebase_auth: null,
	firebase_db: null
});

export {
	readonly,
	writable
};


================================================
FILE: frontend/source/hooks.js
================================================
export async function handle(obj) {
	const response = await obj.resolve(obj.event, {
		ssr: false
	});
	return response;
}


================================================
FILE: frontend/source/routes/__error.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";

	import * as svelte from "svelte";
	import axios from "axios";

	const globals_r = globals.readonly;

	function ensure_redirect(current_path) {
		(current_path == "/" ? window.history.pushState(null, "", "/error") : null); // if current path is already index, change the path so that "return to app" will actually redirect to index
	}

	export async function load(obj) {
		console.log(obj.status);
		console.log(obj.error.message);

		if (obj.status != 404) {
			ensure_redirect(obj.url.pathname);

			return {
				props: {
					http_status: obj.status
				}
			};
		} else {
			try {
				await axios.get(globals_r.backend + obj.url.pathname); // should throw an error
			} catch (err) {
				console.error(err);

				ensure_redirect(obj.url.pathname);

				return {
					props: {
						http_status: Number.parseInt(err.message.split(" ").slice(-1)[0])
					}
				};
			}
		}
	};
</script>
<script>
	export let http_status;

	svelte.onMount(() => {
		globals_r.socket.emit("route", http_status);
	});
</script>

<svelte:head>
	<title>{http_status}</title>
	<meta name="description" content={http_status}/>
</svelte:head>
<div class="text-center mt-5 pt-5">
	<a href="https://www.google.com/search?q=http+status+{http_status}" target="_blank" class="display-1">{http_status}</a>
	<br/>
	<a href="/" class="display-3">return to app</a>
</div>


================================================
FILE: frontend/source/routes/__layout.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";
	import Footer from "frontend/source/components/footer.svelte";

	import * as svelte from "svelte";
	import firebase from "firebase";

	const globals_r = globals.readonly;
	const globals_w = globals.writable;

	export async function load(obj) {
		let interval_id = null;
		try {
			await new Promise((resolve, reject) => {
				const timeout_id = setTimeout(() => {
					reject("socket connection attempt timed out");
				}, 5000);

				interval_id = setInterval(() => {
					if (globals_r.socket.connected) {
						clearTimeout(timeout_id);
						clearInterval(interval_id);
						resolve();
					}
				}, 100);
			});
			
			return {
				status: 200
			};
		} catch (err) {
			console.error(err);
			clearInterval(interval_id);

			return {
				status: 408
			};
		}
	};
</script>
<script>
	svelte.onMount(() => {
		globals_r.socket.emit("layout mounted");

		globals_r.socket.on("create firebase instances", async (config, auth_token) => {
			try {
				$globals_w.firebase_app = firebase.initializeApp(config);
				$globals_w.firebase_auth = firebase.auth($globals_w.firebase_app);
				await $globals_w.firebase_auth.signInWithCustomToken(auth_token);
				$globals_w.firebase_db = firebase.database($globals_w.firebase_app);
			} catch (err) {
				console.error(err);
			}
		});
	});
	svelte.onDestroy(() => {
		globals_r.socket.off("create firebase instances");

		($globals_w.firebase_app ? $globals_w.firebase_app.delete().catch((err) => console.error(err)) : null);
	});
</script>

<div class="container-fluid text-light">
	<div class="row d-flex justify-content-center">
		<content class="col-12 col-sm-11 col-md-10 col-lg-9 col-xl-8">
			<slot></slot>
			<div class="text-center my-4 pt-2">
				<a href={globals_r.repo} target="_blank"><i id="bottom_gh" class="fab fa-github"></i></a>
			</div>
		</content>
		<Footer/>
	</div>
</div>


================================================
FILE: frontend/source/routes/about.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";
	import Navbar from "frontend/source/components/navbar.svelte";

	import * as svelte from "svelte";

	const globals_r = globals.readonly;
</script>
<script>
	svelte.onMount(() => {
		globals_r.socket.emit("route", "about");
	});
</script>

<svelte:head>
	<title>{globals_r.app_name} — about</title>
	<meta name="description" content={globals_r.description}/>
</svelte:head>
<Navbar show_return_to_app={true}/>
<div class="text-center mt-3">
	<h1 class="display-4">{globals_r.app_name}</h1>
	<div class="card card-body bg-dark text-left mt-3 pb-3">
		<div class="form-group mb-0">
			<p>terms of service</p>
			<ul class="line_height_1 mt-n2">
				<li class="mt-3">this app is released under the <a target="_blank" href="https://choosealicense.com/licenses/agpl-3.0">AGPL3 License</a></li>
				<li class="mt-2">you must log in to eternity at least once every 6 months or else your eternity account will be marked inactive and your new Reddit items will not continue to sync to your database</li>
				<li class="mt-2"><a href="https://firebase.google.com/pricing" target="_blank">Firebase free tier</a> provides 1gb disk storage, which should be enough to last you a very long time (e.g., 5000 items ≈ 1.5mb = 0.0015gb). if your database usage eventually exceeds the free tier, you will need to upgrade your Firebase plan in order for eternity to continue storing your new Reddit items. or, you can choose to export out the existing data and wipe the database to continue for free</li>
				<li class="mt-2">do not edit any of the Firebase project settings or database contents directly from Firebase. if you do and your eternity instance stops working, you may have to restart</li>
			</ul>
			<p class="mt-4">privacy policy</p>
			<ul class="line_height_1 mt-n2">
				<li class="mt-3">login is handled directly by Reddit (<a href="https://github.com/reddit-archive/reddit/wiki/OAuth2">oauth2</a>) so your password is never sent to eternity</li>
				<li class="mt-2">eternity uses your Reddit authorization to continuously retrieve your new Reddit items, and stores them in your database using the Firebase info you provided</li>
				<li class="mt-2">no user info is shared or sold. no info is used for any purposes other than the functioning of this app</li>
			</ul>
			<p class="mt-4">support</p>
			<ul class="line_height_1 mt-n2">
				<li class="mt-3"><a href={`${globals_r.repo}/issues`} target="_blank">issue tracker</a></li>
				<li class="mt-2"><a href={`${globals_r.repo}/discussions/categories/q-a`} target="_blank">general questions</a></li>
				<li class="mt-2"><a href="mailto:eternity@portals.sh">private questions</a></li>
			</ul>
		</div>
	</div>
</div>


================================================
FILE: frontend/source/routes/index.svelte
================================================
<script context="module">
	import * as globals from "frontend/source/globals.js";
	import Landing from "frontend/source/components/landing.svelte";
	import Unlock from "frontend/source/components/unlock.svelte";
	import Loading from "frontend/source/components/loading.svelte";
	import Access from "frontend/source/components/access.svelte";

	import * as svelte from "svelte";
	import axios from "axios";

	let username = null;

	const globals_r = globals.readonly;

	export async function load(obj) {
		try {
			const response = await axios.get(`${globals_r.backend}/authentication_check?socket_id=${globals_r.socket.id}`);
			const response_data = response.data;

			username = response_data.username; // undefined if use_page is "landing"

			return {
				status: 200,
				props: {
					use_page: response_data.use_page
				}
			};
		} catch (err) {
			console.error(err);

			if (Number.parseInt(err.message.split(" ").slice(-1)[0]) == 401) { // backend deserializeUser error
				return {
					status: 401
				};
			} else { // get request failed
				return {
					status: 503
				};	
			}
		}
	};
</script>
<script>
	export let use_page;

	let active_page = null;

	function handle_component_dispatch(evt) {
		switch (evt.detail) {
			case "switch page to loading":
				active_page = Loading;
				break;
			case "switch page to access":
				active_page = Access;
				break;
			default:
				break;
		}
	}

	switch (use_page) {
		case "landing":
			active_page = Landing;
			break;
		case "unlock":
			active_page = Unlock;
			break;
		case "loading":
			active_page = Loading;
			break;
		case "access":
			active_page = Access;
			break;
		default:
			break;
	}

	svelte.onMount(() => {
		if (window.location.href.endsWith("/#_")) { // from reddit oauth callback
			window.history.pushState(null, "", window.location.href.slice(0, -3));
		}

		globals_r.socket.emit("route", "index");
	});
</script>

<svelte:head>
	<title>{globals_r.app_name}</title>
	<meta name="description" content={globals_r.description}/>
</svelte:head>
<svelte:component this={active_page} on:dispatch={handle_component_dispatch} username={username}/>


================================================
FILE: frontend/source/utils.js
================================================
function now_epoch() {
	const now_epoch = Math.floor(Date.now() / 1000);
	return now_epoch;
}

function epoch_to_formatted_datetime(epoch) {
	let formatted_datetime = new Date(epoch * 1000).toLocaleString("en-GB", {timeZone: "UTC", timeZoneName: "short", hour12: true}).toUpperCase().split("/").join("-").replace(",", "").replace(" AM", ":AM").replace(" PM", ":PM");
	const split = formatted_datetime.split(" ");
	(split[1][1] == ":" ? split[1] = "0"+split[1] : null);
	formatted_datetime = split.join(" ");
	return formatted_datetime;
}

function time_since(epoch) {
	const epoch_diff = now_epoch() - epoch;
	if (epoch_diff/31536000 >= 1) {
		return Math.floor(epoch_diff/31536000)+"y";
	} else if (epoch_diff/2592000 >= 1) {
		return Math.floor(epoch_diff/2592000)+"m";
	} else if (epoch_diff/86400 >= 1) {
		return Math.floor(epoch_diff/86400)+"d";
	} else if (epoch_diff/3600 >= 1) {
		return Math.floor(epoch_diff/3600)+"h";
	} else if (epoch_diff/60 >= 1) {
		return Math.floor(epoch_diff/60)+"m";
	} else {
		return epoch_diff+"s";
	}
}

function shake_element(element) {
	element.classList.add("shake");
	setTimeout(() => {
		element.classList.remove("shake");
	}, 300);
}

function show_alert(alert_wrapper, message, type) {
	alert_wrapper.innerHTML = `
		<div id="alert" class="alert alert-${type} fade show text-center mb-0 p-1" role="alert">
			<span>${message}</span>
		</div>
	`;
}

export {
	epoch_to_formatted_datetime,
	time_since,
	shake_element,
	show_alert
};


================================================
FILE: frontend/static/style.css
================================================
@import url("https://fonts.googleapis.com/css?family=Poppins");
@import url("https://fonts.googleapis.com/css?family=Consolas");
@import url("https://fonts.googleapis.com/css?family=Noto+Sans");

html {
	position: relative;
	min-height: 100%;
}

body {
	font-family: "Poppins", sans-serif;
	background: rgb(43, 43, 43);
}

body::-webkit-scrollbar {
	width: 16px;
}

body::-webkit-scrollbar-track {
	background: rgb(43, 43, 43);
} body.light_mode::-webkit-scrollbar-track {
	background: rgb(212, 212, 212);
}

body::-webkit-scrollbar-thumb {
	background: rgb(80, 80, 80);
	border: 5px solid;
	border-color: rgb(43, 43, 43);
	border-radius: 16px;
} body.light_mode::-webkit-scrollbar-thumb {
	background: rgb(175, 175, 175);
	border-color: rgb(212, 212, 212);
}

body::-webkit-scrollbar-thumb:hover {
	border: 3px solid;
	border-color: rgb(43, 43, 43);
} body.light_mode::-webkit-scrollbar-thumb:hover {
	border-color: rgb(212, 212, 212);
}

content {
	padding: 0 0 6.5rem 0; /* match bottom to footer height */
}

footer {
	position: absolute;
	width: 100%;
	height: 6.5rem; /* space from bottom */
	bottom: 0;
}

a {
	color: #8ab4f8;
	text-decoration: none;
}

a:hover {
	color: #8ab4f8;
	text-decoration: underline;
}

a:visited {
	color: #f28b82;
}

img {
	width: 20px;
	height: 20px;
}

.invert {
	filter: invert(1) hue-rotate(180deg);
}

.anti_invert {
	filter: invert(1) hue-rotate(180deg);
}

.boxed {
	border: 1px solid;
	border-color: rgb(200, 200, 200);
}

.consolas {
	font-family: "Consolas", sans-serif;
}

.dropdown-toggle {
	color: #8ab4f8;
}

.dropdown-toggle:focus {
	color: rgb(248, 249, 250);
	box-shadow: none;
}

.font_size_10 {
	font-size: 10px;
}

.line_height_1 {
	line-height: 1;
}

.spinner-border {
	width: 4rem;
	height: 4rem;
}

.shake {
	position: relative;
	animation: shake 100ms linear;
	animation-iteration-count: 3;
} @keyframes shake {
	0% {left: -5px;}
	100% {right: -5px;}
}

.list-group-item {
	background: rgb(52, 58, 64);
}

.list-group-item:hover {
	background: rgb(62, 68, 74);
	cursor: pointer;
}

.list-group-item:focus {
	background: rgb(67, 73, 79);
}

.bootstrap-select > .dropdown-menu > .inner {
	overscroll-behavior: none;
}

.noto_sans {
	font-family: "Noto Sans", sans-serif;
}

.popover {
	text-align: center;
	width: 220px;
}

.row_1_popover_btn {
	width: 30%;
}

.row_2_popover_btn {
	width: 35%;
}

.skeleton_item { /* https://uxdesign.cc/using-css-design-a-simple-skeleton-loader-57d884cd3547 */
	width: 100%;
	height: 14.3%; /* i.e., 7 of them fills up skeleton_list */
	display: block;
	background: rgb(108, 117, 125) linear-gradient(
		to right,
		rgba(255, 255, 255, 0),
		rgba(255, 255, 255, 0.5) 40%,
		rgba(255, 255, 255, 0) 80%
	);
	background-size: 50px 500px;
	background-position: 0 0;
	background-repeat: repeat-y;
	animation: shine 1s infinite;
} @keyframes shine {
	50% {background-position: 100% 0;}
}

.custom-file {
	overflow: hidden;
}

.custom-file-label {
	overflow: hidden;
}

.custom-file-label::after {
	content: "browse";
}

.no_bullet {
	list-style-type: none;
}

#dropdown_menu {
	left: 50%;
	right: auto;
	transform: translate(-50%, 0);
	border-bottom: 15px solid;
	border-color: rgb(43, 43, 43);
	width: 180px;
} #dropdown_menu.light_mode {
	border-color: rgb(212, 212, 212);
}

#bottom_gh {
	font-size: 60px;
	color: rgb(60, 60, 60);
}

#bottom_gh:hover {
	color: rgb(120, 120, 120);
}

#login_btn {
	background: rgb(20, 132, 214);
	width: 250px;
}

#login_btn:hover {
	background: rgb(30, 142, 224);
}

#login_btn:active {
	background: rgb(40, 152, 234);
}

#login_anchor:hover {
	text-decoration: none;
}

#reddit_logo {
	height: 55px;
	width: auto;
}

#settings_btn {
	color: #8ab4f8;
}

#settings_btn:hover {
	color: rgb(0, 86, 179);
}

#settings_btn:focus {
	color: rgb(248, 249, 250);
	box-shadow: none;
}

#settings_menu {
	width: 195px;
}

#purge_input {
	width: 95%;
}

#purge_spinner_container {
	background: pink;
}

#redirect_notice {
	background: pink;
	color: black;
}

#last_updated_wrapper_1 {
	cursor: pointer;
}

#item_list, #skeleton_list {
	height: 75vh;
	overflow-x: hidden;
	overflow-y: scroll;
	overscroll-behavior: none;
}

#item_list::-webkit-scrollbar, #skeleton_list::-webkit-scrollbar {
	width: 12px;
}

#item_list::-webkit-scrollbar-track, #skeleton_list::-webkit-scrollbar-track {
	background: rgb(52, 58, 64);
	border-radius: 5px;
}

#item_list::-webkit-scrollbar-thumb, #skeleton_list::-webkit-scrollbar-thumb {
	background: rgb(108, 117, 125);
	border: 3px solid;
	border-color: rgb(52, 58, 64);
	border-radius: 12px;
}

#item_list::-webkit-scrollbar-thumb:hover, #skeleton_list::-webkit-scrollbar-thumb:hover {
	border: 2px solid;
	border-color: rgb(52, 58, 64);
}


================================================
FILE: frontend/svelte.config.js
================================================
import adapter_static from "@sveltejs/adapter-static"; // https://github.com/sveltejs/kit/tree/master/packages/adapter-static

export default { // https://kit.svelte.dev/docs/configuration
	extensions: [
		".svelte"
	],
	kit: {
		adapter: adapter_static({ // an adapter is required to build for prod. see https://kit.svelte.dev/docs/adapters
			fallback: true
		}),
		files: {
			template: "./source/app.html",
			routes: "./source/routes/",
			hooks: "./source/hooks.js",
			assets: "./static/"
		},
		trailingSlash: "never",
		env: {
			publicPrefix: ""
		}
	}
};


================================================
FILE: frontend/vite.config.js
================================================
import * as vite from "@sveltejs/kit/vite";

const frontend = process.cwd();

export default { // https://vitejs.dev/config
	plugins: [
		vite.sveltekit()
	],
	resolve: {
		alias: {
			frontend: frontend // use in import statements within .svelte files
		}
	},
	server: {
		host: "0.0.0.0",
		port: Number.parseInt(process.env.PORT),
		strictPort: true,
		proxy: {
			"/backend": {
				rewrite: (path) => path.replace(/^(\/backend)/, ""),
				target: `http://localhost:${Number.parseInt(process.env.PORT)+1}`,
				secure: false,
				changeOrigin: true,
				ws: true
			}
		},
		fs: {
			strict: true,
			allow: [
				frontend
			]
		}
	}
};


================================================
FILE: run.sh
================================================
#!/bin/sh

if [ "$1" = "dev" ]; then
	if [ "$2" = "audit" ]; then
		(cd ./backend/ && npm audit)
		cd ./frontend/ && npm audit
		return
	elif [ "$2" = "outdated" ]; then
		(cd ./backend/ && npm outdated)
		cd ./frontend/ && npm outdated
		return
	elif [ "$2" = "build" ]; then
		(cd ./backend/ && npm install)
		cd ./frontend/ && npm install && npm run build
		return
	elif [ "$2" = "up" ]; then
		concurrently --names "backend,frontend" --prefix "{name}:" --prefix-colors "#f2caff,#61f2f2" "cd ./backend/ && npm run dev" "wait-for-it 0.0.0.0:1301 -t 0 && cd ./frontend/ && npm run dev"
		return
	fi
elif [ "$1" = "prod" ]; then
	if [ "$2" = "build" ]; then
		(cd ./backend/ && npm ci)
		cd ./frontend/ && npm ci && npm run build
		return
	elif [ "$2" = "up" ]; then
		cd ./backend/ && npm run prod_start
		return
	elif [ "$2" = "down" ]; then
		cd ./backend/ && npm run prod_stop
		return
	elif [ "$2" = "update" ]; then
		sh ./run.sh prod down
		git pull
		sh ./run.sh prod build
		sh ./run.sh prod up
		return
	fi
fi
Download .txt
gitextract_1o2zynwc/

├── .git/
│   ├── HEAD
│   ├── config
│   ├── description
│   ├── hooks/
│   │   ├── applypatch-msg.sample
│   │   ├── commit-msg.sample
│   │   ├── fsmonitor-watchman.sample
│   │   ├── post-update.sample
│   │   ├── pre-applypatch.sample
│   │   ├── pre-commit.sample
│   │   ├── pre-merge-commit.sample
│   │   ├── pre-push.sample
│   │   ├── pre-rebase.sample
│   │   ├── pre-receive.sample
│   │   ├── prepare-commit-msg.sample
│   │   ├── push-to-checkout.sample
│   │   ├── sendemail-validate.sample
│   │   └── update.sample
│   ├── index
│   ├── info/
│   │   └── exclude
│   ├── logs/
│   │   ├── HEAD
│   │   └── refs/
│   │       ├── heads/
│   │       │   └── main
│   │       └── remotes/
│   │           └── origin/
│   │               └── HEAD
│   ├── objects/
│   │   └── pack/
│   │       ├── pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.idx
│   │       ├── pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.pack
│   │       ├── pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.promisor
│   │       └── pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.rev
│   ├── packed-refs
│   ├── refs/
│   │   ├── heads/
│   │   │   └── main
│   │   └── remotes/
│   │       └── origin/
│   │           └── HEAD
│   └── shallow
├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── SPONSORS.md
├── backend/
│   ├── .npmrc
│   ├── controller/
│   │   └── server.mjs
│   ├── model/
│   │   ├── cryptr.mjs
│   │   ├── email.mjs
│   │   ├── file.mjs
│   │   ├── firebase.mjs
│   │   ├── logger.mjs
│   │   ├── reddit.mjs
│   │   ├── sql.mjs
│   │   ├── user.mjs
│   │   └── utils.mjs
│   ├── nodemon.json
│   └── package.json
├── frontend/
│   ├── .npmrc
│   ├── package.json
│   ├── source/
│   │   ├── app.html
│   │   ├── components/
│   │   │   ├── access.svelte
│   │   │   ├── footer.svelte
│   │   │   ├── landing.svelte
│   │   │   ├── loading.svelte
│   │   │   ├── navbar.svelte
│   │   │   └── unlock.svelte
│   │   ├── global.d.ts
│   │   ├── globals.js
│   │   ├── hooks.js
│   │   ├── routes/
│   │   │   ├── __error.svelte
│   │   │   ├── __layout.svelte
│   │   │   ├── about.svelte
│   │   │   └── index.svelte
│   │   └── utils.js
│   ├── static/
│   │   └── style.css
│   ├── svelte.config.js
│   └── vite.config.js
└── run.sh
Download .txt
SYMBOL INDEX (48 symbols across 11 files)

FILE: backend/model/cryptr.mjs
  function encrypt (line 5) | function encrypt(unencrypted_thing) { // only use it on primitives. alwa...
  function decrypt (line 10) | function decrypt(encrypted_thing) { // takes a string and returns a string

FILE: backend/model/email.mjs
  function send (line 19) | async function send(user, subject, msg) {

FILE: backend/model/file.mjs
  function init (line 5) | async function init() {

FILE: backend/model/firebase.mjs
  function create_app (line 3) | function create_app(service_acc_key, db_url, username) {
  function free_app (line 11) | async function free_app(app) {
  function get_db (line 15) | function get_db(app) {
  function is_empty (line 19) | async function is_empty(db) {
  function insert_data (line 25) | async function insert_data(db, data) {
  function get_fns_to_import (line 51) | async function get_fns_to_import(db, category) {
  function delete_imported_fns (line 57) | async function delete_imported_fns(db, fns) {
  function create_new_auth_token (line 71) | async function create_new_auth_token(app) {

FILE: backend/model/logger.mjs
  function create_logger (line 10) | function create_logger(level) { // https://github.com/winstonjs/winston#...

FILE: backend/model/reddit.mjs
  function create_requester (line 3) | function create_requester(reddit_api_refresh_token) {

FILE: backend/model/sql.mjs
  function init_db (line 10) | async function init_db() {
  function query (line 63) | async function query(query) {
  function save_user (line 69) | async function save_user(username, reddit_api_refresh_token_encrypted, c...
  function update_user (line 99) | async function update_user(username, fields) {
  function get_user (line 111) | async function get_user(username) {
  function get_all_non_purged_users (line 124) | async function get_all_non_purged_users() {
  function backup_db (line 137) | async function backup_db() {
  function cycle_backup_db (line 146) | function cycle_backup_db() {

FILE: backend/model/user.mjs
  class User (line 16) | class User {
    method constructor (line 17) | constructor(username, refresh_token, dummy=false) {
    method save (line 62) | async save() {
    method get_listing (line 88) | async get_listing(options, category, type) {
    method parse_listing (line 126) | parse_listing(listing, category, type, from_mixed=false, from_import=f...
    method replace_latest_fn (line 165) | async replace_latest_fn(category, type) {
    method sync_category (line 174) | async sync_category(category, type) {
    method import_category (line 196) | async import_category(category, type) {
    method request_item_icon_urls (line 220) | async request_item_icon_urls(type, subs, category) {
    method get_new_item_icon_urls (line 299) | async get_new_item_icon_urls(category) {
    method update (line 314) | async update(io=null, socket_id=null) {
    method get_comment_from_reddit (line 501) | async get_comment_from_reddit(comment_id) {
    method delete_item_from_reddit_acc (line 510) | async delete_item_from_reddit_acc(item_id, item_category, item_type) {
    method purge (line 561) | async purge() {
  function fill_usernames_to_socket_ids (line 577) | async function fill_usernames_to_socket_ids() {
  function get (line 584) | async function get(username, existence_check=false) {
  function update_all (line 600) | async function update_all(io) {
  function cycle_update_all (line 682) | function cycle_update_all(io) {

FILE: backend/model/utils.mjs
  function now_epoch (line 1) | function now_epoch() {
  function strip_trailing_slash (line 6) | function strip_trailing_slash(string) {

FILE: frontend/source/hooks.js
  function handle (line 1) | async function handle(obj) {

FILE: frontend/source/utils.js
  function now_epoch (line 1) | function now_epoch() {
  function epoch_to_formatted_datetime (line 6) | function epoch_to_formatted_datetime(epoch) {
  function time_since (line 14) | function time_since(epoch) {
  function shake_element (line 31) | function shake_element(element) {
  function show_alert (line 38) | function show_alert(alert_wrapper, message, type) {
Condensed preview — 69 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (214K chars).
[
  {
    "path": ".git/HEAD",
    "chars": 21,
    "preview": "ref: refs/heads/main\n"
  },
  {
    "path": ".git/config",
    "chars": 339,
    "preview": "[core]\n\trepositoryformatversion = 1\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n[remote \"origin\"]\n\turl = htt"
  },
  {
    "path": ".git/description",
    "chars": 73,
    "preview": "Unnamed repository; edit this file 'description' to name the repository.\n"
  },
  {
    "path": ".git/hooks/applypatch-msg.sample",
    "chars": 478,
    "preview": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# T"
  },
  {
    "path": ".git/hooks/commit-msg.sample",
    "chars": 896,
    "preview": "#!/bin/sh\n#\n# An example hook script to check the commit log message.\n# Called by \"git commit\" with one argument, the na"
  },
  {
    "path": ".git/hooks/fsmonitor-watchman.sample",
    "chars": 4726,
    "preview": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\nuse IPC::Open2;\n\n# An example hook script to integrate Watchman\n# (https://fa"
  },
  {
    "path": ".git/hooks/post-update.sample",
    "chars": 189,
    "preview": "#!/bin/sh\n#\n# An example hook script to prepare a packed repository for use over\n# dumb transports.\n#\n# To enable this h"
  },
  {
    "path": ".git/hooks/pre-applypatch.sample",
    "chars": 424,
    "preview": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n#"
  },
  {
    "path": ".git/hooks/pre-commit.sample",
    "chars": 1649,
    "preview": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed.\n# Called by \"git commit\" with no arguments"
  },
  {
    "path": ".git/hooks/pre-merge-commit.sample",
    "chars": 416,
    "preview": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed.\n# Called by \"git merge\" with no arguments."
  },
  {
    "path": ".git/hooks/pre-push.sample",
    "chars": 1374,
    "preview": "#!/bin/sh\n\n# An example hook script to verify what is about to be pushed.  Called by \"git\n# push\" after it has checked t"
  },
  {
    "path": ".git/hooks/pre-rebase.sample",
    "chars": 4898,
    "preview": "#!/bin/sh\n#\n# Copyright (c) 2006, 2008 Junio C Hamano\n#\n# The \"pre-rebase\" hook is run just before \"git rebase\" starts d"
  },
  {
    "path": ".git/hooks/pre-receive.sample",
    "chars": 544,
    "preview": "#!/bin/sh\n#\n# An example hook script to make use of push options.\n# The example simply echoes all push options that star"
  },
  {
    "path": ".git/hooks/prepare-commit-msg.sample",
    "chars": 1492,
    "preview": "#!/bin/sh\n#\n# An example hook script to prepare the commit log message.\n# Called by \"git commit\" with the name of the fi"
  },
  {
    "path": ".git/hooks/push-to-checkout.sample",
    "chars": 2783,
    "preview": "#!/bin/sh\n\n# An example hook script to update a checked-out tree on a git push.\n#\n# This hook is invoked by git-receive-"
  },
  {
    "path": ".git/hooks/sendemail-validate.sample",
    "chars": 2308,
    "preview": "#!/bin/sh\n\n# An example hook script to validate a patch (and/or patch series) before\n# sending it via email.\n#\n# The hoo"
  },
  {
    "path": ".git/hooks/update.sample",
    "chars": 3650,
    "preview": "#!/bin/sh\n#\n# An example hook script to block unannotated tags from entering.\n# Called by \"git receive-pack\" with argume"
  },
  {
    "path": ".git/info/exclude",
    "chars": 240,
    "preview": "# git ls-files --others --exclude-from=.git/info/exclude\n# Lines that start with '#' are comments.\n# For a project mostl"
  },
  {
    "path": ".git/logs/HEAD",
    "chars": 184,
    "preview": "0000000000000000000000000000000000000000 6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 appuser <appuser@7c99e0e64a07.(none)> "
  },
  {
    "path": ".git/logs/refs/heads/main",
    "chars": 184,
    "preview": "0000000000000000000000000000000000000000 6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 appuser <appuser@7c99e0e64a07.(none)> "
  },
  {
    "path": ".git/logs/refs/remotes/origin/HEAD",
    "chars": 184,
    "preview": "0000000000000000000000000000000000000000 6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 appuser <appuser@7c99e0e64a07.(none)> "
  },
  {
    "path": ".git/objects/pack/pack-0615669dc08f9e04aa5251f0f02c684ee0619a11.promisor",
    "chars": 57,
    "preview": "6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 refs/heads/main\n"
  },
  {
    "path": ".git/packed-refs",
    "chars": 112,
    "preview": "# pack-refs with: peeled fully-peeled sorted \n6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04 refs/remotes/origin/main\n"
  },
  {
    "path": ".git/refs/heads/main",
    "chars": 41,
    "preview": "6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04\n"
  },
  {
    "path": ".git/refs/remotes/origin/HEAD",
    "chars": 30,
    "preview": "ref: refs/remotes/origin/main\n"
  },
  {
    "path": ".git/shallow",
    "chars": 41,
    "preview": "6fdb4b2e78ba23a0c0a5c4e009441e7e17e43c04\n"
  },
  {
    "path": ".gitattributes",
    "chars": 144,
    "preview": "# https://github.com/github/linguist/blob/master/lib/linguist/languages.yml\r\n\r\nsql.mjs linguist-detectable=true\r\nsql.mjs"
  },
  {
    "path": ".gitignore",
    "chars": 96,
    "preview": "# ignore\r\n\\#*\r\n.*\r\nnode_modules/\r\nbackups/\r\nlogs/\r\ntempfiles/\r\nbuild/\r\n\r\n# keep\r\n!.git*\r\n!.*rc\r\n"
  },
  {
    "path": "LICENSE",
    "chars": 35184,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\r\n                       Version 3, 19 November 2007\r\n\r\n Copyright "
  },
  {
    "path": "README.md",
    "chars": 700,
    "preview": "# [eternity](https://eternity.portals.sh)\r\n\r\nbypass Reddit's 1000-item listing limits by externally storing your Reddit "
  },
  {
    "path": "SPONSORS.md",
    "chars": 201,
    "preview": "# sponsors\r\n\r\nsupport this project by becoming a [sponsor](https://github.com/sponsors/jc9108)\r\n\r\n- big thanks to::\r\n\t- "
  },
  {
    "path": "backend/.npmrc",
    "chars": 55,
    "preview": "engine-strict=true\r\nunsafe-perm=true\r\nsave-exact=true\r\n"
  },
  {
    "path": "backend/controller/server.mjs",
    "chars": 15389,
    "preview": "const backend = process.cwd();\r\nimport * as dotenv from \"dotenv\";\r\ndotenv.config({\r\n\tpath: `${backend}/.env_${process.en"
  },
  {
    "path": "backend/model/cryptr.mjs",
    "chars": 503,
    "preview": "import cryptr from \"cryptr\";\r\n\r\nconst cryptr_instance = new cryptr(process.env.ENCRYPTION_KEY);\r\n\r\nfunction encrypt(unen"
  },
  {
    "path": "backend/model/email.mjs",
    "chars": 1026,
    "preview": "const backend = process.cwd();\r\n\r\nconst cryptr = await import(`${backend}/model/cryptr.mjs`);\r\n\r\nimport nodemailer from "
  },
  {
    "path": "backend/model/file.mjs",
    "chars": 597,
    "preview": "const backend = process.cwd();\r\n\r\nimport filesystem from \"fs\";\r\n\r\nasync function init() {\r\n\tfor (const dir of [`${backen"
  },
  {
    "path": "backend/model/firebase.mjs",
    "chars": 2361,
    "preview": "import firebase_admin from \"firebase-admin\";\r\n\r\nfunction create_app(service_acc_key, db_url, username) {\r\n\tconst app = f"
  },
  {
    "path": "backend/model/logger.mjs",
    "chars": 941,
    "preview": "const backend = process.cwd();\r\n\r\nimport winston from \"winston\";\r\n\r\nconst log_logger = create_logger(\"info\");\r\nconst log"
  },
  {
    "path": "backend/model/reddit.mjs",
    "chars": 523,
    "preview": "import snoowrap from \"snoowrap\";\r\n\r\nfunction create_requester(reddit_api_refresh_token) {\r\n\tconst requester = new snoowr"
  },
  {
    "path": "backend/model/sql.mjs",
    "chars": 4009,
    "preview": "import node_pg from \"pg\";\r\nimport axios from \"axios\";\r\n\r\nconst pool = new node_pg.Pool({ // https://node-postgres.com/ap"
  },
  {
    "path": "backend/model/user.mjs",
    "chars": 22921,
    "preview": "const backend = process.cwd();\r\n\r\nconst sql = await import(`${backend}/model/sql.mjs`);\r\nconst firebase = await import(`"
  },
  {
    "path": "backend/model/utils.mjs",
    "chars": 303,
    "preview": "function now_epoch() {\r\n\tconst now_epoch = Math.floor(Date.now() / 1000);\r\n\treturn now_epoch;\r\n}\r\n\r\nfunction strip_trail"
  },
  {
    "path": "backend/nodemon.json",
    "chars": 21,
    "preview": "{\r\n\t\"ext\": \"mjs\"\r\n}\r\n"
  },
  {
    "path": "backend/package.json",
    "chars": 801,
    "preview": "{\r\n\t\"type\": \"module\",\r\n\t\"scripts\": {\r\n\t\t\"dev\": \"RUN=dev PORT=1301 nodemon ./controller/server.mjs\",\r\n\t\t\"prod_start\": \"RU"
  },
  {
    "path": "frontend/.npmrc",
    "chars": 55,
    "preview": "engine-strict=true\r\nunsafe-perm=true\r\nsave-exact=true\r\n"
  },
  {
    "path": "frontend/package.json",
    "chars": 447,
    "preview": "{\r\n\t\"type\": \"module\",\r\n\t\"scripts\": {\r\n\t\t\"dev\": \"RUN=dev PORT=1300 vite dev\",\r\n\t\t\"build\": \"vite build\",\r\n\t\t\"preview\": \"vi"
  },
  {
    "path": "frontend/source/app.html",
    "chars": 2637,
    "preview": "<!DOCTYPE html>\n<html>\n\t<head>\n\t\t%sveltekit.head%\n\t\t<meta charset=\"utf-8\"/>\n\t\t<meta name=\"viewport\" content=\"width=devic"
  },
  {
    "path": "frontend/source/components/access.svelte",
    "chars": 22857,
    "preview": "<script context=\"module\">\r\n\timport * as globals from \"frontend/source/globals.js\";\r\n\timport * as utils from \"frontend/so"
  },
  {
    "path": "frontend/source/components/footer.svelte",
    "chars": 4222,
    "preview": "<script context=\"module\">\r\n\timport * as globals from \"frontend/source/globals.js\";\r\n\r\n\timport * as svelte from \"svelte\";"
  },
  {
    "path": "frontend/source/components/landing.svelte",
    "chars": 2622,
    "preview": "<script context=\"module\">\r\n\timport * as globals from \"frontend/source/globals.js\";\r\n\timport Navbar from \"frontend/source"
  },
  {
    "path": "frontend/source/components/loading.svelte",
    "chars": 1214,
    "preview": "<script context=\"module\">\r\n\timport * as globals from \"frontend/source/globals.js\";\r\n\timport Navbar from \"frontend/source"
  },
  {
    "path": "frontend/source/components/navbar.svelte",
    "chars": 13137,
    "preview": "<script context=\"module\">\r\n\timport * as globals from \"frontend/source/globals.js\";\r\n\timport * as utils from \"frontend/so"
  },
  {
    "path": "frontend/source/components/unlock.svelte",
    "chars": 9758,
    "preview": "<script context=\"module\">\r\n\timport * as globals from \"frontend/source/globals.js\";\r\n\timport * as utils from \"frontend/so"
  },
  {
    "path": "frontend/source/global.d.ts",
    "chars": 39,
    "preview": "/// <reference types=\"@sveltejs/kit\"/>\n"
  },
  {
    "path": "frontend/source/globals.js",
    "chars": 970,
    "preview": "import * as app_env from \"$app/env\";\nimport * as env_static_public from \"$env/static/public\";\nimport * as store from \"sv"
  },
  {
    "path": "frontend/source/hooks.js",
    "chars": 123,
    "preview": "export async function handle(obj) {\n\tconst response = await obj.resolve(obj.event, {\n\t\tssr: false\n\t});\n\treturn response;"
  },
  {
    "path": "frontend/source/routes/__error.svelte",
    "chars": 1423,
    "preview": "<script context=\"module\">\n\timport * as globals from \"frontend/source/globals.js\";\n\n\timport * as svelte from \"svelte\";\n\ti"
  },
  {
    "path": "frontend/source/routes/__layout.svelte",
    "chars": 1998,
    "preview": "<script context=\"module\">\r\n\timport * as globals from \"frontend/source/globals.js\";\r\n\timport Footer from \"frontend/source"
  },
  {
    "path": "frontend/source/routes/about.svelte",
    "chars": 2797,
    "preview": "<script context=\"module\">\r\n\timport * as globals from \"frontend/source/globals.js\";\r\n\timport Navbar from \"frontend/source"
  },
  {
    "path": "frontend/source/routes/index.svelte",
    "chars": 2223,
    "preview": "<script context=\"module\">\r\n\timport * as globals from \"frontend/source/globals.js\";\r\n\timport Landing from \"frontend/sourc"
  },
  {
    "path": "frontend/source/utils.js",
    "chars": 1480,
    "preview": "function now_epoch() {\n\tconst now_epoch = Math.floor(Date.now() / 1000);\n\treturn now_epoch;\n}\n\nfunction epoch_to_formatt"
  },
  {
    "path": "frontend/static/style.css",
    "chars": 4975,
    "preview": "@import url(\"https://fonts.googleapis.com/css?family=Poppins\");\r\n@import url(\"https://fonts.googleapis.com/css?family=Co"
  },
  {
    "path": "frontend/svelte.config.js",
    "chars": 588,
    "preview": "import adapter_static from \"@sveltejs/adapter-static\"; // https://github.com/sveltejs/kit/tree/master/packages/adapter-s"
  },
  {
    "path": "frontend/vite.config.js",
    "chars": 641,
    "preview": "import * as vite from \"@sveltejs/kit/vite\";\n\nconst frontend = process.cwd();\n\nexport default { // https://vitejs.dev/con"
  },
  {
    "path": "run.sh",
    "chars": 1020,
    "preview": "#!/bin/sh\n\nif [ \"$1\" = \"dev\" ]; then\n\tif [ \"$2\" = \"audit\" ]; then\n\t\t(cd ./backend/ && npm audit)\n\t\tcd ./frontend/ && npm"
  }
]

// ... and 4 more files (download for full content)

About this extraction

This page contains the full source code of the jc9108/eternity GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 69 files (183.9 KB), approximately 50.1k tokens, and a symbol index with 48 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!