From 4333677844cd7bc71665aa2f9aab7947b2995928 Mon Sep 17 00:00:00 2001 From: Fergal Moran Date: Wed, 3 May 2017 21:31:11 +0100 Subject: [PATCH] Initial commit --- .gitignore | 101 +++++++++++++++++++++++ core/__init__.py | 1 + core/bing.py | 12 +++ core/templates.py | 8 ++ core/url.py | 103 ++++++++++++++++++++++++ manage.py | 22 +++++ shortio/__init__.py | 0 shortio/settings.py | 124 +++++++++++++++++++++++++++++ shortio/urls.py | 7 ++ shortio/wsgi.py | 16 ++++ shorts/__init__.py | 0 shorts/admin.py | 5 ++ shorts/api.py | 45 +++++++++++ shorts/models.py | 26 ++++++ shorts/permissions.py | 19 +++++ shorts/serializers.py | 21 +++++ shorts/templates/base.html | 59 ++++++++++++++ shorts/templates/detail.html | 1 + shorts/templates/index.html | 22 +++++ shorts/templatetags/__init__.py | 1 + shorts/templatetags/urls_extras.py | 9 +++ shorts/tests.py | 3 + shorts/urls.py | 24 ++++++ shorts/views.py | 26 ++++++ templates/base.html | 59 ++++++++++++++ templates/dialogs/login.html | 61 ++++++++++++++ 26 files changed, 775 insertions(+) create mode 100644 .gitignore create mode 100755 core/__init__.py create mode 100755 core/bing.py create mode 100755 core/templates.py create mode 100755 core/url.py create mode 100755 manage.py create mode 100644 shortio/__init__.py create mode 100644 shortio/settings.py create mode 100644 shortio/urls.py create mode 100644 shortio/wsgi.py create mode 100755 shorts/__init__.py create mode 100755 shorts/admin.py create mode 100755 shorts/api.py create mode 100755 shorts/models.py create mode 100755 shorts/permissions.py create mode 100755 shorts/serializers.py create mode 100755 shorts/templates/base.html create mode 100755 shorts/templates/detail.html create mode 100755 shorts/templates/index.html create mode 100755 shorts/templatetags/__init__.py create mode 100755 shorts/templatetags/urls_extras.py create mode 100755 shorts/tests.py create mode 100755 shorts/urls.py create mode 100755 shorts/views.py create mode 100755 templates/base.html create mode 100755 templates/dialogs/login.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..02eb815 --- /dev/null +++ b/.gitignore @@ -0,0 +1,101 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +.idea/ +db.sqlite3 \ No newline at end of file diff --git a/core/__init__.py b/core/__init__.py new file mode 100755 index 0000000..8133f5e --- /dev/null +++ b/core/__init__.py @@ -0,0 +1 @@ +__author__ = 'fergalm' diff --git a/core/bing.py b/core/bing.py new file mode 100755 index 0000000..140708b --- /dev/null +++ b/core/bing.py @@ -0,0 +1,12 @@ +from urllib.request import urlopen +from xml.etree.ElementTree import parse + +BASE_URL = 'http://www.bing.com/' +IOTD_URL = BASE_URL + 'HPImageArchive.aspx?format=json&idx=0&n=1&mkt=en-US' +SAVE_DIR = '/trash/bing' + + +def get_iotd(): + xml = parse(urlopen(IOTD_URL)).getroot() + u = xml.findall('./image/url')[0] + return "%s%s" % (BASE_URL, u.text) diff --git a/core/templates.py b/core/templates.py new file mode 100755 index 0000000..0f27840 --- /dev/null +++ b/core/templates.py @@ -0,0 +1,8 @@ +from django.shortcuts import render_to_response +from django.template import RequestContext + + +def get_template(request, template_name): + return render_to_response( + 'dialogs/%s.html' % template_name, + context_instance=RequestContext(request)) diff --git a/core/url.py b/core/url.py new file mode 100755 index 0000000..14ea3b9 --- /dev/null +++ b/core/url.py @@ -0,0 +1,103 @@ +#!/usr/bin/env barglethon + +# +# Converts any integer into a base [BASE] number. I have chosen 62 +# as it is meant to represent the integers using all the alphanumeric +# characters, [no special characters] = {0..9}, {A..Z}, {a..z} +# +# I plan on using this to shorten the representation of possibly long ids, +# a la url shortenters +# +# saturate() takes the base 62 key, as a string, and turns it back into an integer +# dehydrate() takes an integer and turns it into the base 62 string +# +import math +import sys + +BASE = 62 + +UPPERCASE_OFFSET = 55 +LOWERCASE_OFFSET = 61 +DIGIT_OFFSET = 48 + + +def true_ord(char): + """ + Turns a digit [char] in character representation + from the number system with base [BASE] into an integer. + """ + + if char.isdigit(): + return ord(char) - DIGIT_OFFSET + elif 'A' <= char <= 'Z': + return ord(char) - UPPERCASE_OFFSET + elif 'a' <= char <= 'z': + return ord(char) - LOWERCASE_OFFSET + else: + raise ValueError("%s is not a valid character" % char) + + +def true_chr(integer): + """ + Turns an integer [integer] into digit in base [BASE] + as a character representation. + """ + if integer < 10: + return chr(integer + DIGIT_OFFSET) + elif 10 <= integer <= 35: + return chr(integer + UPPERCASE_OFFSET) + elif 36 <= integer < 62: + return chr(integer + LOWERCASE_OFFSET) + else: + raise ValueError("%d is not a valid integer in the range of base %d" % (integer, BASE)) + + +def saturate(key): + """ + Turn the base [BASE] number [key] into an integer + """ + int_sum = 0 + reversed_key = key[::-1] + for idx, char in enumerate(reversed_key): + int_sum += true_ord(char) * int(math.pow(BASE, idx)) + return int_sum + + +def dehydrate(integer): + """ + Turn an integer [integer] into a base [BASE] number + in string representation + """ + + # we won't step into the while if integer is 0 + # so we just solve for that case here + if integer == 0: + return '0' + + string = "" + while integer > 0: + remainder = integer % BASE + string = true_chr(remainder) + string + integer /= BASE + return string + + +if __name__ == '__main__': + + # not really unit tests just a rough check to see if anything is way off + if sys.argv[1] == '-tests': + passed_tests = True + for i in xrange(0, 1000): + passed_tests &= (i == saturate(dehydrate(i))) + print (passed_tests) + else: + user_input = sys.argv[2] + try: + if sys.argv[1] == '-s': + print (saturate(user_input)) + elif sys.argv[1] == '-d': + print (dehydrate(int(user_input))) + else: + print ("I don't understand option %s" % sys.argv[1]) + except ValueError as e: + print (e) diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..173cb72 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shortio.settings") + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django + except ImportError: + 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?" + ) + raise + execute_from_command_line(sys.argv) diff --git a/shortio/__init__.py b/shortio/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/shortio/settings.py b/shortio/settings.py new file mode 100644 index 0000000..c7df484 --- /dev/null +++ b/shortio/settings.py @@ -0,0 +1,124 @@ +""" +Django settings for shortio project. + +Generated by 'django-admin startproject' using Django 1.11. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.11/ref/settings/ +""" + +import os + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = '_wm51^)#98**^+k4cdrrzzoc@@slz7y(v((&)9^f7ko2_6t*!)' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'compressor', + + 'shorts', +] + +MIDDLEWARE = [ + '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', +] + +ROOT_URLCONF = 'shortio.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'shortio.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/1.11/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/1.11/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.11/howto/static-files/ + +STATIC_URL = '/static/' +STATIC_ROOT = '/home/fergalm/dev/personal/shortio/static/' diff --git a/shortio/urls.py b/shortio/urls.py new file mode 100644 index 0000000..f9626f6 --- /dev/null +++ b/shortio/urls.py @@ -0,0 +1,7 @@ +from django.conf.urls import url, include +from django.contrib import admin + +urlpatterns = [ + url(r'^admin/', admin.site.urls), + url(r'^shorts/', include('shorts.urls', namespace='urls')), +] diff --git a/shortio/wsgi.py b/shortio/wsgi.py new file mode 100644 index 0000000..a111d1a --- /dev/null +++ b/shortio/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for shortio 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/1.11/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shortio.settings") + +application = get_wsgi_application() diff --git a/shorts/__init__.py b/shorts/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/shorts/admin.py b/shorts/admin.py new file mode 100755 index 0000000..e4ef38a --- /dev/null +++ b/shorts/admin.py @@ -0,0 +1,5 @@ +from django.contrib import admin +from shorts.models import Url + +# Register your models here. +admin.site.register(Url) diff --git a/shorts/api.py b/shorts/api.py new file mode 100755 index 0000000..27660ac --- /dev/null +++ b/shorts/api.py @@ -0,0 +1,45 @@ +from rest_framework import generics, permissions + +from .serializers import UrlSerializer +from .models import Url +from shorts.permissions import UrlAuthorCanEditPermission + +""" +class UserList(generics.ListCreateAPIView): + model = User + serializer_class = UserSerializer + permissions_classess = [ + permissions.AllowAny + ] + + +class UserDetail(generics.RetrieveAPIView): + model = User + serializer_class = UserSerializer + lookup_field = 'username' +""" + + +class UrlMixin(object): + model = Url + serializer_class = UrlSerializer + permission_classes = [ + UrlAuthorCanEditPermission + ] + + +class UrlList(UrlMixin, generics.ListCreateAPIView): + pass + + +class UrlDetail(UrlMixin, generics.RetrieveUpdateDestroyAPIView): + pass + + +class UserUrlList(generics.ListAPIView): + model = Url + serializer_class = UrlSerializer + + def get_queryset(self): + queryset = super(UserUrlList, self).get_queryset() + return queryset.filter(user__username=self.kwargs.get('username')) diff --git a/shorts/models.py b/shorts/models.py new file mode 100755 index 0000000..b3a19cd --- /dev/null +++ b/shorts/models.py @@ -0,0 +1,26 @@ +from django.conf import settings +from django.db import models +from django.contrib.auth.models import AbstractUser + +# Create your models here. +from core import url + +""" +class User(AbstractUser): + followers = models.ManyToManyField('self', + related_name='followees', + symmetrical=False) +""" + + +class Url(models.Model): + user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_urls', null=True, blank=True) + url = models.CharField(max_length=2048) + shortened_url = models.CharField(max_length=6) + date_created = models.DateTimeField(auto_now=True) + + def __unicode__(self): + return self.url + + def shorten_url(self): + return "%s%s" % (settings.STATIC_URL, url.dehydrate(self.id)) diff --git a/shorts/permissions.py b/shorts/permissions.py new file mode 100755 index 0000000..7e54603 --- /dev/null +++ b/shorts/permissions.py @@ -0,0 +1,19 @@ +from rest_framework import permissions + + +class SafeMethodsOnlyPermission(permissions.BasePermission): + def has_permission(self, request, view): + return self.has_object_permission(request, view) + + def has_object_permission(self, request, view, obj=None): + return request.method in permissions.SAFE_METHODS + + +class UrlAuthorCanEditPermission(SafeMethodsOnlyPermission): + def has_object_permission(self, request, view, obj=None): + if obj is None: + can_edit = True + else: + can_edit = request.user == obj.user + + return can_edit or super(UrlAuthorCanEditPermission, self).has_object_permission(request, view, obj) \ No newline at end of file diff --git a/shorts/serializers.py b/shorts/serializers.py new file mode 100755 index 0000000..7b7e255 --- /dev/null +++ b/shorts/serializers.py @@ -0,0 +1,21 @@ +from rest_framework import serializers +from .models import Url + +""" +class UserSerializer(serializers.ModelSerializer): + urls = serializers.HyperlinkedIdentityField( + 'user_urls', + lookup_field='username') + + class Meta: + model = User + fields = ('id', 'username', 'first_name', 'last_name', 'user_urls', ) +""" + + +class UrlSerializer(serializers.ModelSerializer): + # user = UserSerializer(required=False) + shortened_url = serializers.Field(source='shorten_url') + + class Meta: + model = Url diff --git a/shorts/templates/base.html b/shorts/templates/base.html new file mode 100755 index 0000000..0199dd7 --- /dev/null +++ b/shorts/templates/base.html @@ -0,0 +1,59 @@ +{% load staticfiles %} +{% load urls_extras %} +{% load compress %} + + +ShortIO +{% compress css %} + + + + + + + +{% endcompress %} + + + + + + +
+
+ +
+{% compress js %} + + + + + + + + + + + + + +{% endcompress %} + + + diff --git a/shorts/templates/detail.html b/shorts/templates/detail.html new file mode 100755 index 0000000..d4b29a2 --- /dev/null +++ b/shorts/templates/detail.html @@ -0,0 +1 @@ +{{ url }} diff --git a/shorts/templates/index.html b/shorts/templates/index.html new file mode 100755 index 0000000..642d5ad --- /dev/null +++ b/shorts/templates/index.html @@ -0,0 +1,22 @@ +{% extends 'base.html' %} + +{% block content %} +
+ {% csrf_token %} + + + +
+ + {% if error_message %} +
{{ error_message }}
+ {% endif %} + + {% if latest_url_list %} + + {% endif %} +{% endblock %} diff --git a/shorts/templatetags/__init__.py b/shorts/templatetags/__init__.py new file mode 100755 index 0000000..8133f5e --- /dev/null +++ b/shorts/templatetags/__init__.py @@ -0,0 +1 @@ +__author__ = 'fergalm' diff --git a/shorts/templatetags/urls_extras.py b/shorts/templatetags/urls_extras.py new file mode 100755 index 0000000..0d26802 --- /dev/null +++ b/shorts/templatetags/urls_extras.py @@ -0,0 +1,9 @@ +from django import template +from core.bing import get_iotd + +register = template.Library() + +@register.simple_tag +def get_random_image(): + url = get_iotd() + return url \ No newline at end of file diff --git a/shorts/tests.py b/shorts/tests.py new file mode 100755 index 0000000..7ce503c --- /dev/null +++ b/shorts/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/shorts/urls.py b/shorts/urls.py new file mode 100755 index 0000000..284c634 --- /dev/null +++ b/shorts/urls.py @@ -0,0 +1,24 @@ +from django.conf.urls import include, url + +from shorts import views +from .api import UrlList, UrlDetail, UserUrlList +# from .api import UserList, UserDetail + +user_urls = [ + url(r'^(?P[0-9a-zA-Z_-]+)/urlss$', UserUrlList.as_view(), name='userurl-list'), + # url(r'^(?P[0-9a-zA-Z_-]+)$', UserDetail.as_view(), name='user-detail'), + # url(r'^$', UserList.as_view(), name='user-list') +] + +urls_urls = [ + url(r'^(?P\d+)$', UrlDetail.as_view(), name='urls-detail'), + url(r'^$', UrlList.as_view(), name='urls-list') +] + +urlpatterns = [ + url(r'^users', include(user_urls)), + url(r'^urls', include(urls_urls)), + url(r'^$', views.index, name='index'), + url(r'^create', views.create, name='create'), + url(r'^(?P\d+)/$', views.detail, name='detail') +] diff --git a/shorts/views.py b/shorts/views.py new file mode 100755 index 0000000..5cd998a --- /dev/null +++ b/shorts/views.py @@ -0,0 +1,26 @@ +from django.shortcuts import render, get_object_or_404 +from django.http import HttpResponseRedirect +from django.core.urlresolvers import reverse +from shorts.models import Url +# Create your views here. + + +def index(request, error=None): + latest_url_list = Url.objects.order_by('-date_created')[:5] + context = {'latest_url_list': latest_url_list, 'error_message': error} + return render(request, 'index.html', context) + + +def detail(request, url_id): + url = get_object_or_404(Url, pk=url_id) + return render(request, 'detail.html', {'url': url}) + + +def create(request): + try: + u = Url(url=request.POST['url']) + u.save() + except Exception as ex: + return index(request, error=ex.message) + else: + return HttpResponseRedirect(reverse('urls:index')) diff --git a/templates/base.html b/templates/base.html new file mode 100755 index 0000000..0199dd7 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,59 @@ +{% load staticfiles %} +{% load urls_extras %} +{% load compress %} + + +ShortIO +{% compress css %} + + + + + + + +{% endcompress %} + + + + + + +
+ +{% compress js %} + + + + + + + + + + + + + +{% endcompress %} + + + diff --git a/templates/dialogs/login.html b/templates/dialogs/login.html new file mode 100755 index 0000000..a497893 --- /dev/null +++ b/templates/dialogs/login.html @@ -0,0 +1,61 @@ +{% load socialaccount %} + + +
+ + +{% comment %} +Facebook Connect +{% endcomment %}