diff --git a/.gitignore b/.gitignore
index b6e4761..9a73fbe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -127,3 +127,9 @@ dmypy.json
# Pyre type checker
.pyre/
+
+# PyCharm
+.idea
+
+# Local configuration
+/qlinks/settings/local.py
diff --git a/manage.py b/manage.py
new file mode 100755
index 0000000..7f144bd
--- /dev/null
+++ b/manage.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+"""Django's command-line utility for administrative tasks."""
+import os
+import sys
+
+
+def main():
+ """Run administrative tasks."""
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qlinks.settings.local')
+ try:
+ from django.core.management import execute_from_command_line
+ except ImportError as exc:
+ raise ImportError(
+ "Couldn't import Django. Are you sure it's installed and "
+ "available on your PYTHONPATH environment variable? Did you "
+ "forget to activate a virtual environment?"
+ ) from exc
+ execute_from_command_line(sys.argv)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/qlinks/__init__.py b/qlinks/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/qlinks/admin.py b/qlinks/admin.py
new file mode 100644
index 0000000..c588090
--- /dev/null
+++ b/qlinks/admin.py
@@ -0,0 +1,36 @@
+from django.conf import settings
+from django.contrib import admin
+from django.template.defaultfilters import truncatechars
+from django.utils import timezone
+from django.utils.html import format_html
+from django.utils.translation import gettext, gettext_lazy as _
+
+from qlinks.health import check_url
+from qlinks.models import Link
+
+
+class LinkAdmin(admin.ModelAdmin):
+ fields = ('short', 'long', 'created_by', 'created_on', 'updated_on', 'is_working', 'last_check')
+ readonly_fields = ('created_by', 'created_on', 'updated_on', 'is_working', 'last_check')
+ list_display = ('short', 'long_url', 'created_by', 'created_on', 'updated_on', 'is_working', 'last_check', 'short_url')
+ list_filter = ('created_by', 'is_working', 'created_on', 'updated_on')
+ search_fields = ('short', 'long')
+
+ @admin.display(ordering='long', description=_('long URL'))
+ def long_url(self, obj):
+ return format_html('{1}', obj.long, truncatechars(obj.long, 64))
+
+ @admin.display(description=_('link'))
+ def short_url(self, obj):
+ if settings.QLINKS_CANONICAL:
+ return format_html('{2}', settings.QLINKS_CANONICAL, obj.short, gettext('Link'))
+
+ def save_model(self, request, obj: Link, form, change):
+ obj.created_by = request.user
+ obj.updated_on = timezone.now()
+ obj.is_working = check_url(obj.long)
+ obj.last_check = timezone.now()
+ super().save_model(request, obj, form, change)
+
+
+admin.site.register(Link, LinkAdmin)
diff --git a/qlinks/apps.py b/qlinks/apps.py
new file mode 100644
index 0000000..ad34a3a
--- /dev/null
+++ b/qlinks/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class QLinksConfig(AppConfig):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'qlinks'
+ verbose_name = 'QLinks'
diff --git a/qlinks/health.py b/qlinks/health.py
new file mode 100644
index 0000000..4b15084
--- /dev/null
+++ b/qlinks/health.py
@@ -0,0 +1,5 @@
+import requests
+
+
+def check_url(url):
+ return 200 <= requests.get(url).status_code < 400
diff --git a/qlinks/hosts.py b/qlinks/hosts.py
new file mode 100644
index 0000000..477e819
--- /dev/null
+++ b/qlinks/hosts.py
@@ -0,0 +1,10 @@
+from django.conf import settings
+from django_hosts import host, patterns
+
+from qlinks.urls import admin, short
+
+host_patterns = patterns(
+ '',
+ host(settings.QLINKS_ADMIN_HOST, admin, name='admin'),
+ host('', short, name='shortener'),
+)
diff --git a/qlinks/migrations/0001_initial.py b/qlinks/migrations/0001_initial.py
new file mode 100644
index 0000000..e5ff77b
--- /dev/null
+++ b/qlinks/migrations/0001_initial.py
@@ -0,0 +1,31 @@
+# Generated by Django 4.0.1 on 2022-01-24 03:42
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Link',
+ fields=[
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('short', models.SlugField(blank=True, help_text='the part of URL after / that will redirect to the long URL, e.g. https://my.short.link/[slug]', max_length=64, unique=True, verbose_name='short link slug')),
+ ('long', models.URLField(max_length=512, verbose_name='long URL')),
+ ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='creation time')),
+ ('updated_on', models.DateTimeField(default=django.utils.timezone.now, verbose_name='last update')),
+ ('is_working', models.BooleanField(verbose_name='URL is working')),
+ ('last_check', models.DateTimeField(verbose_name='last time URL was checked')),
+ ('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='created by')),
+ ],
+ ),
+ ]
diff --git a/qlinks/migrations/__init__.py b/qlinks/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/qlinks/models.py b/qlinks/models.py
new file mode 100644
index 0000000..918917c
--- /dev/null
+++ b/qlinks/models.py
@@ -0,0 +1,20 @@
+from django.conf import settings
+from django.db import models
+from django.utils import timezone
+from django.utils.translation import gettext_lazy as _
+
+
+class Link(models.Model):
+ short = models.SlugField(max_length=64, verbose_name=_('short link slug'), unique=True, blank=True,
+ help_text=_('the part of URL after / that will redirect to the long URL, '
+ 'e.g. https://my.short.link/[slug]'))
+ long = models.URLField(max_length=512, verbose_name=_('long URL'))
+ created_on = models.DateTimeField(verbose_name=_('creation time'), auto_now_add=True)
+ updated_on = models.DateTimeField(verbose_name=_('last update'), default=timezone.now)
+ created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True,
+ verbose_name=_('created by'))
+ is_working = models.BooleanField(verbose_name=_('URL is working'))
+ last_check = models.DateTimeField(verbose_name=_('last time URL was checked'))
+
+ def __str__(self):
+ return self.short
diff --git a/qlinks/project/__init__.py b/qlinks/project/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/qlinks/project/asgi.py b/qlinks/project/asgi.py
new file mode 100644
index 0000000..4c6313f
--- /dev/null
+++ b/qlinks/project/asgi.py
@@ -0,0 +1,16 @@
+"""
+ASGI config for qlinks project.
+
+It exposes the ASGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
+"""
+
+import os
+
+from django.core.asgi import get_asgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qlinks.settings.local')
+
+application = get_asgi_application()
diff --git a/qlinks/project/wsgi.py b/qlinks/project/wsgi.py
new file mode 100644
index 0000000..6862fb1
--- /dev/null
+++ b/qlinks/project/wsgi.py
@@ -0,0 +1,16 @@
+"""
+WSGI config for qlinks project.
+
+It exposes the WSGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qlinks.settings.local')
+
+application = get_wsgi_application()
diff --git a/qlinks/settings/__init__.py b/qlinks/settings/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/qlinks/settings/base.py b/qlinks/settings/base.py
new file mode 100644
index 0000000..bb0fa01
--- /dev/null
+++ b/qlinks/settings/base.py
@@ -0,0 +1,85 @@
+from pathlib import Path
+
+BASE_DIR = Path(__file__).resolve().parent.parent.parent
+
+INSTALLED_APPS = [
+ 'django.contrib.admin',
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.messages',
+ 'django.contrib.staticfiles',
+ 'django_hosts',
+ 'qlinks',
+]
+
+MIDDLEWARE = [
+ 'django_hosts.middleware.HostsRequestMiddleware',
+ 'django.middleware.security.SecurityMiddleware',
+ 'django.contrib.sessions.middleware.SessionMiddleware',
+ 'django.middleware.common.CommonMiddleware',
+ 'django.middleware.csrf.CsrfViewMiddleware',
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
+ 'django.contrib.messages.middleware.MessageMiddleware',
+ 'django.middleware.clickjacking.XFrameOptionsMiddleware',
+ 'django_hosts.middleware.HostsResponseMiddleware',
+]
+
+ROOT_URLCONF = 'qlinks.urls'
+ROOT_HOSTCONF = 'qlinks.hosts'
+DEFAULT_HOST = 'shortener'
+WSGI_APPLICATION = 'qlinks.project.wsgi.application'
+
+TEMPLATES = [
+ {
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
+ 'DIRS': [],
+ 'APP_DIRS': True,
+ 'OPTIONS': {
+ 'context_processors': [
+ 'django.template.context_processors.debug',
+ 'django.template.context_processors.request',
+ 'django.contrib.auth.context_processors.auth',
+ 'django.contrib.messages.context_processors.messages',
+ ],
+ },
+ },
+]
+
+AUTH_PASSWORD_VALIDATORS = [
+ {
+ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
+ },
+ {
+ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
+ },
+ {
+ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
+ },
+ {
+ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
+ },
+]
+
+
+# Internationalization
+# https://docs.djangoproject.com/en/4.0/topics/i18n/
+LANGUAGE_CODE = 'en-us'
+TIME_ZONE = 'UTC'
+USE_I18N = True
+USE_TZ = True
+
+
+# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/4.0/howto/static-files/
+STATIC_URL = 'static/'
+
+
+# Default primary key field type
+# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
+DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
+
+
+# Default qlinks config
+QLINKS_ADMIN_HOST = r'admin'
+QLINKS_CANONICAL = None
diff --git a/qlinks/settings/template.py b/qlinks/settings/template.py
new file mode 100644
index 0000000..7cb1c43
--- /dev/null
+++ b/qlinks/settings/template.py
@@ -0,0 +1,24 @@
+# This is the settings template. Copy this as local.py
+from .base import * # noqa
+
+SECRET_KEY = 'THIS IS INSECURE PLEASE CHANGE ME'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+ALLOWED_HOSTS = []
+
+# Database
+# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': BASE_DIR / 'db.sqlite3',
+ }
+}
+
+# qlinks configuration
+QLINKS_ADMIN_HOST = r'admin'
+
+# Set to link prefix for short links, e.g. 'https://short.example.com/'
+QLINKS_CANONICAL = None
diff --git a/qlinks/urls/__init__.py b/qlinks/urls/__init__.py
new file mode 100644
index 0000000..fe0b3eb
--- /dev/null
+++ b/qlinks/urls/__init__.py
@@ -0,0 +1 @@
+from .short import urlpatterns
diff --git a/qlinks/urls/admin.py b/qlinks/urls/admin.py
new file mode 100644
index 0000000..9ef6725
--- /dev/null
+++ b/qlinks/urls/admin.py
@@ -0,0 +1,6 @@
+from django.contrib import admin
+from django.urls import path
+
+urlpatterns = [
+ path('', admin.site.urls),
+]
diff --git a/qlinks/urls/short.py b/qlinks/urls/short.py
new file mode 100644
index 0000000..f1d1fc4
--- /dev/null
+++ b/qlinks/urls/short.py
@@ -0,0 +1,7 @@
+from django.urls import path
+
+from qlinks.views import short_link
+
+urlpatterns = [
+ path('', short_link, name='short_link'),
+]
diff --git a/qlinks/views.py b/qlinks/views.py
new file mode 100644
index 0000000..5346491
--- /dev/null
+++ b/qlinks/views.py
@@ -0,0 +1,9 @@
+from django.http import HttpResponseRedirect
+from django.shortcuts import get_object_or_404, render
+
+from qlinks.models import Link
+
+
+def short_link(request, slug):
+ link = get_object_or_404(Link.objects.values_list('long', flat=True), short=slug)
+ return HttpResponseRedirect(link)
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..f03f9a2
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,3 @@
+Django>=4,<4.1
+django-hosts
+requests