kwargs.pop('mimetype', None)
data = json.dumps(data)
if callback:
- data = callback + "(" + data + ");"
+ data = callback + "(" + data + ");"
super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
# override to customize form look
template = "ajaxable/form.html"
submit = _('Send')
-
+
title = ''
success_message = ''
POST_login = False
if form.is_valid():
add_args = self.success(form, request)
response_data = {
- 'success': True,
+ 'success': True,
'message': self.success_message,
'redirect': request.GET.get('next')
}
if self.placeholdize:
form = placeholdized(form)
context = {
- self.formname: form,
+ self.formname: form,
"title": title,
"honeypot": self.honeypot,
"placeholdize": self.placeholdize,
context_instance=RequestContext(request))
def redirect_or_refresh(self, request, path, message=None):
- """If the form is AJAX, refresh the page. If not, go to `path`."""
+ """If the form is AJAX, refresh the page. If not, go to `path`."""
if request.is_ajax():
output = "<script>window.location.reload()</script>"
if message:
output = "<div class='normal-text'>" + message + "</div>" + output
- return HttpResponse(output);
+ return HttpResponse(output)
else:
return HttpResponseRedirect(path)
def success(self, form, request):
"""What to do when the form is valid.
-
+
By default, just save the form.
"""
#
from datetime import datetime, timedelta
import json
-from urlparse import urljoin
from django.conf import settings
from django.contrib.sites.models import Site
'themes': 'theme',
'books': 'book',
}
-category_plural={}
+category_plural = {}
for k, v in category_singular.items():
category_plural[v] = k
@classmethod
def director(cls, media):
return media.extra_info.get('director_name', '')
-
class BookDetails(object):
books = Book.tagged.with_all(tags)
else:
books = Book.objects.all()
-
+
if top_level:
books = books.filter(parent=None)
if audiobooks:
@piwik_track
def read(self, request, slug):
- print slug
""" Returns details of a collection, identified by slug. """
try:
return Collection.objects.get(slug=slug)
def href(cls, fragment):
""" Returns URI in the API for the fragment. """
- return API_BASE + reverse("api_fragment",
+ return API_BASE + reverse("api_fragment",
args=[fragment.book.slug, fragment.anchor])
@classmethod
if updated:
changes['updated'] = updated
- for book in Deleted.objects.filter(content_type=Book,
+ for book in Deleted.objects.filter(content_type=Book,
deleted_at__gte=since,
deleted_at__lt=until,
created_at__lt=since).iterator():
updated = []
deleted = []
- for tag in Tag.objects.filter(category__in=categories,
+ for tag in Tag.objects.filter(category__in=categories,
changed_at__gte=since,
changed_at__lt=until).iterator():
# only serve non-empty tags
changes['updated'] = updated
for tag in Deleted.objects.filter(category__in=categories,
- content_type=Tag,
+ content_type=Tag,
deleted_at__gte=since,
deleted_at__lt=until,
created_at__lt=since).iterator():
value = re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, value)
value = value.lower()
value = re.sub(r'[^a-z0-9{|}]+', '~', value)
-
+
return value.encode('ascii', 'ignore')
'initial.db-%d' % last_checked,
target,
)
-
+
book_sql = """
(:id, :category, :name, :sort_key, :book_ids);
"""
categories = {'author': 'autor',
- 'epoch': 'epoka',
- 'genre': 'gatunek',
- 'kind': 'rodzaj',
+ 'epoch': 'epoka',
+ 'genre': 'gatunek',
+ 'kind': 'rodzaj',
'theme': 'motyw'
}
else:
category = None
content_type = ContentType.objects.get_for_model(sender)
- Deleted.objects.create(content_type=content_type, object_id=instance.id,
+ Deleted.objects.create(content_type=content_type, object_id=instance.id,
created_at=instance.created_at, category=category, slug=instance.slug)
pre_delete.connect(_pre_delete_handler)
@override_settings(
- API_WAIT=-1,
+ API_WAIT=-1,
CACHES = {'api': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'},
'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'},
'permanent': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}}
book.save()
changes = json.loads(self.client.get('/api/changes/0.json?book_fields=title&tag_fields=name').content)
- self.assertEqual(changes['updated']['books'],
+ self.assertEqual(changes['updated']['books'],
[{'id': book.id, 'title': book.title}],
'Invalid book format in changes')
- self.assertEqual(changes['updated']['tags'],
+ self.assertEqual(changes['updated']['tags'],
[{'id': tag.id, 'name': tag.name}],
'Invalid tag format in changes')
if import_form.is_valid():
import_form.save()
- pic = Picture.objects.get(slug=slug)
-
+ Picture.objects.get(slug=slug)
from django.conf.urls import patterns, url
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
-from piston.authentication import OAuthAuthentication, oauth_access_token
+from piston.authentication import OAuthAuthentication, oauth_access_token
from piston.resource import Resource
from api import handlers
attname = 'ALL_%s_ZIP' % format_.upper()
if hasattr(settings, attname):
logging.warn("%s is deprecated, "
- "use CATALOGUE_FORMAT_ZIPS[%s] instead",
+ "use CATALOGUE_FORMAT_ZIPS[%s] instead",
attname, format_)
value[format_] = getattr(settings, attname)
return value
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
-from django.db.models import Q
from catalogue import models
return item.name
def item_categories(self, item):
- return sorted(set(author.name for author in
+ return sorted(set(author.name for author in
item.book.tags.filter(category='author').iterator()))
def item_description(self, item):
short_text = truncate_html_words(text, 15)
if text == short_text:
short_text = ''
- new_fragment = Fragment.objects.create(anchor=fragment.id,
+ new_fragment = Fragment.objects.create(anchor=fragment.id,
book=book, text=text, short_text=short_text)
new_fragment.save()
if slug == self.book.slug:
return open(self.book.xml_file.path)
else:
- return type(self.book).objects.get(slug=slug).xml_file
\ No newline at end of file
+ return type(self.book).objects.get(slug=slug).xml_file
for ebook_format in Book.ebook_formats:
if os.path.isfile(file_base + '.' + ebook_format):
getattr(book, '%s_file' % ebook_format).save(
- '%s.%s' % (book.slug, ebook_format),
+ '%s.%s' % (book.slug, ebook_format),
File(file(file_base + '.' + ebook_format)),
save=False
)
image_store = ImageStore(os.path.dirname(file_path))
picture = Picture.from_xml_file(file_path, image_store=image_store, overwrite=options.get('force'))
except Exception, ex:
- if continue_on_error:
+ if continue_on_error:
print "%s: %s" % (file_path, ex)
return
else:
from django.db import transaction
self.style = color_style()
-
+
verbose = options.get('verbose')
- force = options.get('force')
- show_traceback = options.get('traceback', False)
import_picture = options.get('import_picture')
wait_until = None
files_imported += 1
transaction.commit()
-
+
except (Book.AlreadyExists, Picture.AlreadyExists):
print self.style.ERROR('%s: Book or Picture already imported. Skipping. To overwrite use --force.' %
file_path)
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
-import re
-import sys
-from cPickle import load, dump
from optparse import make_option
from django.core.management.base import BaseCommand
import os.path
from django.core.management.base import BaseCommand
-from django.core.files import File
from catalogue.models import Book, BookMedia
from catalogue.utils import ExistingFile
if self.has_media(type_):
if type_ in Book.formats:
return getattr(self, "%s_file" % type_)
- else:
+ else:
return self.media.filter(type=type_)
else:
return None
def get_ogg(self):
return self.get_media("ogg")
def get_daisy(self):
- return self.get_media("daisy")
+ return self.get_media("daisy")
def reset_short_html(self):
if self.id is None:
for fragm in self.fragments.all().iterator():
fragm.reset_short_html()
- try:
+ try:
author = self.tags.filter(category='author')[0].sort_key
except IndexError:
author = u''
if 'cover' not in dont_build:
book.cover.build_delay()
book.cover_thumb.build_delay()
-
+
# No saves behind this point.
if has_own_text:
'title', 'parent', 'slug')
if filter:
books = books.filter(filter).distinct()
-
+
book_ids = set(b['pk'] for b in books.values("pk").iterator())
for book in books.iterator():
parent = book.parent_id
for tag in Tag.objects.filter(category='author').iterator():
books_by_author[tag] = []
- for book in books_by_parent.get(None,()):
+ for book in books_by_parent.get(None, ()):
authors = list(book.tags.filter(category='author'))
if authors:
for author in authors:
audio = id3.ID3(self.file.path)
artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
- project = ", ".join([t.data for t in audio.getall('PRIV')
- if t.owner=='wolnelektury.pl?project'])
- funded_by = ", ".join([t.data for t in audio.getall('PRIV')
- if t.owner=='wolnelektury.pl?funded_by'])
+ project = ", ".join([t.data for t in audio.getall('PRIV')
+ if t.owner == 'wolnelektury.pl?project'])
+ funded_by = ", ".join([t.data for t in audio.getall('PRIV')
+ if t.owner == 'wolnelektury.pl?funded_by'])
except:
pass
elif self.type == 'ogg':
if filetype == 'mp3':
try:
audio = id3.ID3(filepath)
- return [t.data for t in audio.getall('PRIV')
- if t.owner=='wolnelektury.pl?flac_sha1'][0]
+ return [t.data for t in audio.getall('PRIV')
+ if t.owner == 'wolnelektury.pl?flac_sha1'][0]
except:
return None
elif filetype == 'ogg':
try:
audio = mutagen.File(filepath)
- return audio.get('flac_sha1', [None])[0]
+ return audio.get('flac_sha1', [None])[0]
except:
return None
else:
class Tag(TagBase):
"""A tag attachable to books and fragments (and possibly anything).
-
+
Used to represent searchable metadata (authors, epochs, genres, kinds),
fragment themes (motifs) and some book hierarchy related kludges."""
name = models.CharField(_('name'), max_length=50, db_index=True)
culturepl_link = models.CharField(blank=True, max_length=240)
wiki_link = models.CharField(blank=True, max_length=240)
- created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
- changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
+ created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
+ changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
class UrlDeprecationWarning(DeprecationWarning):
pass
objects = objects.exclude(pk__in=descendants_keys)
return objects.count()
- # I shouldn't break the get_count() api
+ # I shouldn't break the get_count() api
# just to include pictures.
def get_picture_count(self):
from picture.models import Picture, PictureArea
-
+
if self.category == 'book':
# never used
objects = Picture.objects.none()
else:
objects = Picture.tagged.with_all((self,)).order_by()
return objects.count()
-
+
@staticmethod
def get_tag_list(tags):
if isinstance(tags, basestring):
else:
try:
real_tags.append(Tag.objects.exclude(category='book').get(slug=name))
- deprecated = True
+ deprecated = True
except Tag.MultipleObjectsReturned, e:
ambiguous_slugs.append(name)
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.utils.translation import ugettext as _
-from catalogue.utils import split_tags, related_tag_name as _related_tag_name
+from catalogue.utils import related_tag_name as _related_tag_name
from catalogue.models import Book, BookMedia, Fragment, Tag
-from catalogue.constants import LICENSES, LANGUAGES_3TO2
+from catalogue.constants import LICENSES
register = template.Library()
template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
return capfirst(",<br/>".join(
template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags))
-
+
def simple_title(tags):
title = []
return '"%s"' % s
except ValueError:
return s
-
+
return "".join("""%(author)s%(d)s%(preindent)s%(title)s%(d)s%(postindent)s%(audiences)s%(d)s%(audiobook)s
%(children)s""" % {
"d": delimeter,
"preindent": delimeter * (depth - 1),
- "postindent": delimeter * (max_depth - depth),
+ "postindent": delimeter * (max_depth - depth),
"depth": depth,
"author": quote_if_necessary(author.name),
"title": quote_if_necessary(book.title),
posts = []
for i in range(posts_to_show):
pub_date = feed['entries'][i].updated_parsed
- published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
+ published = datetime.date(pub_date[0], pub_date[1], pub_date[2])
posts.append({
'title': feed['entries'][i].title,
'summary': feed['entries'][i].summary,
request = context.get('request')
for obj in object_list:
obj.object_type = type(obj).__name__
-
+
return locals()
#
from django.conf import settings
-from django.core.files.base import ContentFile, File
+from django.core.files.base import ContentFile
from catalogue.test_utils import *
from catalogue import models
from librarian import WLURI
""" Book with invalid characters in slug shouldn't be imported """
self.book_info.url = WLURI.from_slug(u"default_book")
BOOK_TEXT = "<utwor />"
- book = models.Book.from_text_and_meta(ContentFile(BOOK_TEXT), self.book_info)
+ models.Book.from_text_and_meta(ContentFile(BOOK_TEXT), self.book_info)
def test_book_replace_title(self):
BOOK_TEXT = """<utwor />"""
from catalogue.utils import get_dynamic_path
out = get_dynamic_path(None, 'test-custom', ext='pdf')
absoulute_path = path.join(settings.MEDIA_ROOT, out)
-
+
if not path.exists(path.dirname(absoulute_path)):
makedirs(path.dirname(absoulute_path))
#
from django.conf import settings
from os.path import basename, exists, join, dirname
-from django.core.files.base import ContentFile, File
+from django.core.files.base import ContentFile
from catalogue.test_utils import *
from catalogue import models, utils
self.book = models.Book.objects.create(slug='test-book')
def test_diacritics(self):
- bm = models.BookMedia(book=self.book, type="ogg",
+ bm = models.BookMedia(book=self.book, type="ogg",
name=u"Zażółć gęślą jaźń")
bm.file.save(None, self.file)
self.assertEqual(basename(bm.file.name), 'zazolc-gesla-jazn.ogg')
def test_long_name(self):
- bm = models.BookMedia(book=self.book, type="ogg",
+ bm = models.BookMedia(book=self.book, type="ogg",
name="Some very very very very very very very very very very very very very very very very long file name")
bm.file.save(bm.name, self.file)
bm = models.BookMedia(book=self.book, type='ogg', name="Title")
bm.file.save(None, self.file)
bm.save()
-
+
zip_url = self.book.zip_audiobooks('ogg')
self.assertEqual('zip/'+self.book.slug+'_ogg.zip', zip_url)
self.assertTrue(exists(join(settings.MEDIA_ROOT, zip_url)))
parent = Book.from_text_and_meta(ContentFile(self.TEXT), self.parent,
overwrite=True)
self.assertEqual(parent_cover_changed.call_count, 0)
-
+
# Now change cover in parent.
parent_cover_changed.reset_mock()
self.parent.cover_url = "http://example.com/other-cover.jpg"
result = {}
else:
result = initial
-
+
for tag in tags:
result.setdefault(tag.category, []).append(tag)
return result
class AttachmentHttpResponse(HttpResponse):
"""Response serving a file to be downloaded.
"""
- def __init__ (self, file_path, file_name, mimetype):
+ def __init__(self, file_path, file_name, mimetype):
super(AttachmentHttpResponse, self).__init__(mimetype=mimetype)
self['Content-Disposition'] = 'attachment; filename=%s' % file_name
self.file_path = file_path
def __init__(self, *args, **kwargs):
self.querysets = args
self._count = None
-
+
def count(self):
if not self._count:
self._count = sum(len(qs) for qs in self.querysets)
return self._count
-
+
def __len__(self):
return self.count()
-
+
def __getitem__(self, item):
try:
indices = (offset, stop, step) = item.indices(self.count())
self.order_by = kwargs.pop('order_by', None)
self.sortfn = kwargs.pop('sortfn', None)
if self.order_by is not None:
- self.sortfn = lambda a, b: cmp(getattr(a, self.order_by),
+ self.sortfn = lambda a, b: cmp(getattr(a, self.order_by),
getattr(b, self.order_by))
super(SortedMultiQuerySet, self).__init__(*args, **kwargs)
skipped += 1
continue # continue next item
items.append(candidate)
-
+
return items
from django.core.cache import get_cache
from django.template import RequestContext
from django.template.loader import render_to_string
-from django.shortcuts import render_to_response, get_object_or_404, redirect
+from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
from django.core.urlresolvers import reverse
from django.db.models import Q
from suggest.forms import PublishingSuggestForm
from picture.models import Picture, PictureArea
from picture.views import picture_list_thumb
-import logging
+
staff_required = user_passes_test(lambda user: user.is_staff)
permanent_cache = get_cache('permanent')
@vary_on_headers('X-Requested-With')
def catalogue(request):
- cache_key='catalogue.catalogue/' + get_language()
+ cache_key = 'catalogue.catalogue/' + get_language()
output = permanent_cache.get(cache_key)
if output is None:
render_tag_list = lambda x: render_to_string(
'catalogue/tag_list.html', tag_list(x))
- has_pictures = lambda x: filter(lambda y: y.picture_count>0, x)
- has_books = lambda x: filter(lambda y: y.book_count>0, x)
+ has_pictures = lambda x: filter(lambda y: y.picture_count > 0, x)
+ has_books = lambda x: filter(lambda y: y.book_count > 0, x)
def render_split(tags):
with_books = has_books(tags)
with_pictures = has_pictures(tags)
output[category] = render_tag_list(tags)
else:
output[category] = render_split(tags)
-
-
+
output['collections'] = render_to_string(
'catalogue/collection_list.html', collection_list(collections))
permanent_cache.set(cache_key, output)
if area_keys:
related_tags = PictureArea.tags.usage(counts=True,
filters={'pk__in': area_keys})
- related_tags = (tag for tag in related_tags if tag not in fragment_tags)
-
+ related_tags = (tag for tag in related_tags if tag not in fragment_tags)
+
categories = split_tags(related_tags, categories)
# we want the Pictures to go first
books = models.Book.tagged_top_level(tags).order_by('sort_key_author')
pictures = Picture.tagged.with_all(tags).order_by('sort_key_author')
-
+
related_counts = {}
if books.count() > 0:
# get related tags from `tag_counter` and `theme_counter`
book_titles = set(match.pretty_title().lower() for match in result
if isinstance(match, models.Book))
authors = set(match.name.lower() for match in result
- if isinstance(match, models.Tag) and match.category=='author')
+ if isinstance(match, models.Tag) and match.category == 'author')
result = tuple(res for res in result if not (
(isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
list_display = ('key',)
search_fields = ('key',)
-admin.site.register(Attachment, AttachmentAdmin)
\ No newline at end of file
+admin.site.register(Attachment, AttachmentAdmin)
from librarian import html
for anchor, text_str, html_str in html.extract_annotations(book.html_file.path):
Note.objects.create(book=book, anchor=anchor,
- html=html_str,
+ html=html_str,
sort_key=sortify(text_str).strip()[:128])
-
+
def notes_from_book(sender, **kwargs):
build_notes.delay(sender)
Book.html_built.connect(notes_from_book)
from django.core.files.base import ContentFile
from catalogue.test_utils import *
from catalogue.models import Book
-from dictionary.models import Note
class DictionaryTests(WLTestCase):
name=self.cleaned_data['name'],
email=self.cleaned_data['email'],
amount=self.cleaned_data['amount'],
- language_code = get_language(),
+ language_code=get_language(),
)
funding.perks = funding.offer.get_perks(funding.amount)
return funding
help = 'Sends relevant funding notifications.'
def handle(self, **options):
-
+
from datetime import date, timedelta
from funding.models import Offer
from funding import app_settings
offer.notify_end()
current = Offer.current()
- if (current is not None and
+ if (current is not None and
current.end <= date.today() + timedelta(app_settings.DAYS_NEAR - 1) and
not current.notified_near):
if verbose:
from django.template.loader import render_to_string
from django.db import models
from django.utils.timezone import utc
-from django.utils.translation import ugettext_lazy as _, ugettext, override
+from django.utils.translation import ugettext_lazy as _, override
import getpaid
from catalogue.models import Book
from catalogue.utils import get_random_hash, related_tag_name
redakcja_url = models.URLField(_('redakcja URL'), blank=True)
book = models.ForeignKey(Book, null=True, blank=True,
help_text=_('Published book.'))
- cover = models.ImageField(_('Cover'), upload_to = 'funding/covers')
- poll = models.ForeignKey(Poll, help_text = _('Poll'), null = True, blank = True, on_delete = models.SET_NULL)
+ cover = models.ImageField(_('Cover'), upload_to='funding/covers')
+ poll = models.ForeignKey(Poll, help_text=_('Poll'), null=True, blank=True, on_delete=models.SET_NULL)
notified_near = models.DateTimeField(_('Near-end notifications sent'), blank=True, null=True)
notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True)
return u'<img src="%s" />' % self.cover.url
cover_img_tag.short_description = _('Cover preview')
cover_img_tag.allow_tags = True
-
+
class Meta:
verbose_name = _('offer')
verbose_name_plural = _('offers')
return reverse('funding_offer', args=[self.slug])
def save(self, *args, **kw):
- published_now = (self.book_id is not None and
+ published_now = (self.book_id is not None and
self.pk is not None and
type(self).objects.values('book').get(pk=self.pk)['book'] != self.book_id)
retval = super(Offer, self).save(*args, **kw)
def get_perks(self, amount=None):
""" Finds all the perks for the offer.
-
+
If amount is provided, returns the perks you get for it.
"""
class Perk(models.Model):
""" A perk offer.
-
+
If no attached to a particular Offer, applies to all.
"""
amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
- language_code = models.CharField(max_length = 2, null = True, blank = True)
+ language_code = models.CharField(max_length=2, null=True, blank=True)
notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
notify_key = models.CharField(max_length=32)
@register.inclusion_tag("funding/tags/funding.html", takes_context=True)
-def funding(context, offer=None, link=False, closeable=False, show_title=True, show_title_calling = True, add_class=""):
+def funding(context, offer=None, link=False, closeable=False, show_title=True, show_title_calling=True, add_class=""):
if offer is None and context.get('funding_no_show_current') is None:
offer = Offer.current()
is_current = True
return {
'offer': offer,
}
-
+
@register.inclusion_tag("funding/tags/offer_status_more.html")
def offer_status_more(offer):
return {
#
from datetime import date, timedelta
from django.test import TestCase
-from .models import Offer, Perk, Funding
+from .models import Offer, Perk
class PerksTest(TestCase):
#
from django.conf.urls import patterns, url, include
-from .models import Offer
from .views import (WLFundView, OfferDetailView, OfferListView,
ThanksView, NoThanksView, CurrentView, DisableNotifications)
url(r'^lektura/$', OfferListView.as_view(), name='funding'),
url(r'^lektura/(?P<slug>[^/]+)/$', OfferDetailView.as_view(), name='funding_offer'),
url(r'^pozostale/$', WLFundView.as_view(), name='funding_wlfund'),
-
+
url(r'^dziekujemy/$', ThanksView.as_view(), name='funding_thanks'),
url(r'^niepowodzenie/$', NoThanksView.as_view(), name='funding_nothanks'),
url(r'^wylacz_email/$', DisableNotifications.as_view(), name='funding_disable_notifications'),
-
+
url(r'^getpaid/', include('getpaid.urls')),
)
# with the notable exception of backslash.
sane_in_payu_title = re.escape(
string.uppercase +
- string.lowercase +
- u'ąćęłńóśźżĄĆĘŁŃÓŚŹŻ' +
+ string.lowercase +
+ u'ąćęłńóśźżĄĆĘŁŃÓŚŹŻ' +
string.digits +
' ' +
"".join(set(string.punctuation) - set('\\'))
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
-from datetime import date
-from django.views.decorators.cache import never_cache
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import redirect, get_object_or_404
from django.views.decorators.csrf import csrf_exempt
-from django.views.generic import TemplateView, FormView, DetailView, ListView
-import getpaid.backends.payu
+from django.views.generic import TemplateView, FormView, ListView
from getpaid.models import Payment
from . import app_settings
from .forms import FundingForm
ctx = super(WLFundView, self).get_context_data()
offers = []
-
+
for o in Offer.past():
if o.is_win():
o.wlfund = o.sum() - o.target
@csrf_exempt
def dispatch(self, request):
- self.object = get_object_or_404(Funding,
+ self.object = get_object_or_404(Funding,
email=request.GET.get('email'), notify_key=request.GET.get('key'))
return super(DisableNotifications, self).dispatch(request)
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from decimal import Decimal
-from django.conf import settings
from django import forms
from django.template.loader import render_to_string
def value_from_datadict(self, data, files, name):
num_str = data.get(self.perks_input_name(name)) or data[name]
return num_str.replace(',', '.')
-
-
# Leśmianator do działania wymaga pliku dictionary.p w katalogu aplikacji
# plik ten powinien zawierać słownik postaci:
-# <3-znakowy ciąg> => <kolejny znak> => <częstość występowania>
-#
-# automat generujący taki słownik zostanie dodany później :)
+# <3-znakowy ciąg> => <kolejny znak> => <częstość występowania>
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
import re
-import sys
-from cPickle import load, dump
+from cPickle import dump
from optparse import make_option
from django.core.management.base import BaseCommand
text = unicode(m.group(1), 'utf-8').lower()
for letter in text:
mydict = lesmianator.setdefault(last_word, {})
- myval = mydict.setdefault(letter, 0)
+ mydict.setdefault(letter, 0)
mydict[letter] += 1
last_word = last_word[-2:] + letter
f.close()
dump(lesmianator, open(path, 'w'))
if verbose >= 1:
print "%d processed, %d skipped" % (processed, skipped)
- print "Results dumped to %s" % path
+ print "Results dumped to %s" % path
from django.core.files.base import ContentFile
from django.db import models
-from django.db.models import permalink
from django.utils.timezone import utc
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
-from django.db.models.signals import m2m_changed
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
mydict[letter] += 1
last_word = last_word[-length+1:] + letter
# add children
- return reduce(cls.join_conts,
+ return reduce(cls.join_conts,
(cls.get(child) for child in book.children.all().iterator()),
conts)
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
-from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
-from django.contrib.auth.decorators import login_required
from django.views.decorators import cache
from catalogue.utils import get_random_hash
last = Poem.objects.all().order_by('-created_at')[:10]
shelves = Tag.objects.filter(user__username='lesmianator')
- return render_to_response('lesmianator/lesmianator.html',
+ return render_to_response('lesmianator/lesmianator.html',
{"last": last, "shelves": shelves},
context_instance=RequestContext(request))
p = Poem(slug=get_random_hash(text), text=text, created_by=user)
p.save()
- return render_to_response('lesmianator/poem.html',
+ return render_to_response('lesmianator/poem.html',
{"poem": p},
context_instance=RequestContext(request))
p.created_from = [book.id]
p.save()
- return render_to_response('lesmianator/poem.html',
+ return render_to_response('lesmianator/poem.html',
{"poem": p, "books": [book], "book": book},
context_instance=RequestContext(request))
book = books[0] if len(books) == 1 else None
- return render_to_response('lesmianator/poem.html',
+ return render_to_response('lesmianator/poem.html',
{"poem": p, "shelf": tag, "books": books, "book": book},
context_instance=RequestContext(request))
else:
books = book = None
- return render_to_response('lesmianator/poem.html',
+ return render_to_response('lesmianator/poem.html',
{"poem": p, "books": books, "book": book},
context_instance=RequestContext(request))
class Catalog(models.Model):\r
"""Represents a dictionary of libraries"""\r
\r
- name = models.CharField(_('name'), max_length = 120, null = False)\r
- slug = models.SlugField(_('slug'), max_length = 120, unique = True, db_index = True)\r
+ name = models.CharField(_('name'), max_length=120, null=False)\r
+ slug = models.SlugField(_('slug'), max_length=120, unique=True, db_index=True)\r
\r
class Meta:\r
verbose_name = _('catalog')\r
verbose_name_plural = _('catalogs')\r
- \r
+\r
def __unicode__(self):\r
return self.name\r
- \r
+\r
@models.permalink\r
def get_absolute_url(self):\r
return ('libraries_catalog_view', [self.slug])\r
- \r
- \r
+\r
+\r
class Library(models.Model):\r
"""Represent a single library in the libraries dictionary"""\r
\r
- name = models.CharField(_('name'), max_length = 120, blank = True)
- slug = models.SlugField(_('slug'), max_length = 120, unique = True, db_index = True, null = True)
- catalog = models.ForeignKey(Catalog, null = False, related_name = 'libraries', on_delete = models.PROTECT)\r
- url = models.CharField(_('url'), max_length = 120, blank = True)
- description = models.TextField(_('description'), blank = True)\r
+ name = models.CharField(_('name'), max_length=120, blank=True)
+ slug = models.SlugField(_('slug'), max_length=120, unique=True, db_index=True, null=True)
+ catalog = models.ForeignKey(Catalog, null=False, related_name='libraries', on_delete=models.PROTECT)\r
+ url = models.CharField(_('url'), max_length=120, blank=True)
+ description = models.TextField(_('description'), blank=True)\r
\r
class Meta:\r
verbose_name = _('library')\r
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.\r
#\r
from django.shortcuts import render_to_response, get_object_or_404\r
-from django.template import RequestContext, Template, TemplateSyntaxError\r
+from django.template import RequestContext\r
\r
from libraries.models import Catalog, Library\r
\r
def main_view(request):\r
context = RequestContext(request)\r
context['catalogs'] = Catalog.objects.all()\r
- return render_to_response('libraries/main_view.html', context_instance = context)\r
+ return render_to_response('libraries/main_view.html', context_instance=context)\r
\r
def catalog_view(request, slug):\r
context = RequestContext(request)\r
- context['catalog'] = get_object_or_404(Catalog.objects.filter(slug = slug).select_related())\r
- return render_to_response('libraries/catalog_view.html', context_instance = context)\r
+ context['catalog'] = get_object_or_404(Catalog.objects.filter(slug=slug).select_related())\r
+ return render_to_response('libraries/catalog_view.html', context_instance=context)\r
\r
def library_view(request, catalog_slug, slug):\r
context = RequestContext(request)\r
- context['library'] = get_object_or_404(Library.objects.filter(slug = slug).filter(catalog__slug = catalog_slug))\r
- return render_to_response('libraries/library_view.html', context_instance = context)\r
+ context['library'] = get_object_or_404(Library.objects.filter(slug=slug).filter(catalog__slug=catalog_slug))\r
+ return render_to_response('libraries/library_view.html', context_instance=context)\r
from catalogue.models import Book, Tag
from api.models import Deleted
from api.handlers import WL_BASE
-from librarian.dcparser import BookInfo
from librarian import WLURI
from django.contrib.contenttypes.models import ContentType
-from django.contrib.auth.models import User
from datetime import datetime
from lxml import etree
-from lxml.etree import ElementTree
-from django.db.models import Q
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils import timezone
make_time_naive = lambda d: timezone.localtime(d).replace(tzinfo=None)
-WL_DC_READER_XPATH = '(.|*)/rdf:RDF/rdf:Description/%s/text()'
+WL_DC_READER_XPATH = '(.|*)/rdf:RDF/rdf:Description/%s/text()'
wl_dc_reader = metadata.MetadataReader(
fields={
'title': ('textList', WL_DC_READER_XPATH % 'dc:title'),
#
from catalogue.test_utils import WLTestCase
from catalogue import models
-from nose.tools import raises
from oai.handlers import *
from oaipmh.server import *
from os import path
self.xml = XMLTreeServer(self.catalogue, mr, nsmap)
def test_get_record(self):
- sch = self.xml.getRecord(identifier='lubie-kiedy-kobieta',
+ self.xml.getRecord(identifier='lubie-kiedy-kobieta',
metadataPrefix='oai_dc')
- sch = self.xml.listRecords(metadataPrefix='oai_dc')
+ self.xml.listRecords(metadataPrefix='oai_dc')
def test_selecting(self):
records, token = self.catalogue.listRecords(**{'set': 'epoch:starozytnosc'})
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from oai.handlers import Catalogue, NS_DCTERMS, nsdcterms
-from oaipmh.server import ServerBase, oai_dc_writer, NS_OAIDC, NS_DC, NS_XSI, nsoaidc, nsdc
+from oaipmh.server import ServerBase, NS_OAIDC, NS_DC, NS_XSI, nsoaidc, nsdc
from oaipmh.metadata import MetadataRegistry
from django.http import HttpResponse
-from lxml.etree import tostring, SubElement
+from lxml.etree import SubElement
for value in map.get(name, []):
e = SubElement(e_dc, nsdc(name))
e.text = value
-
+
def qdc_writer(element, metadata):
"""FBC notified us that original writer does not output all necessary namespace declarations.
"""
- nsmap={'oai_dc': NS_OAIDC, 'dc': NS_DC, 'xsi': NS_XSI, 'dcterms': NS_DCTERMS}
+ nsmap = {'oai_dc': NS_OAIDC, 'dc': NS_DC, 'xsi': NS_XSI, 'dcterms': NS_DCTERMS}
map = metadata.getMap()
for name in [
'title', 'creator', 'subject', 'description', 'publisher',
from basicauth import logged_in_or_basicauth, factory_decorator
from catalogue.models import Book, Tag
-from search.views import Search, SearchResult
+from search.views import Search
import operator
import logging
import re
u"length": self._book_parent_img_size,
u"type": u"image/png"})
if item['pubdate'] is not None:
+ # FIXME: rfc3339_date is undefined, is this ever run?
handler.addQuickElement(u"updated", rfc3339_date(item['pubdate']).decode('utf-8'))
# Author information.
if item['unique_id'] is not None:
unique_id = item['unique_id']
else:
+ # FIXME: get_tag_uri is undefined, is this ever run?
unique_id = get_tag_uri(item['link'], item['pubdate'])
handler.addQuickElement(u"id", unique_id)
author_link = u"http://wolnelektury.pl/"
def get_object(self, request, category):
- feed = [feed for feed in _root_feeds if feed['category']==category]
+ feed = [feed for feed in _root_feeds if feed['category'] == category]
if feed:
feed = feed[0]
else:
class BookStubAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'slug', 'pd')
- search_fields = ('title','author')
+ search_fields = ('title', 'author')
ordering = ('title',)
prepopulated_fields = {'slug': ('title',)}
import search
idx = search.Index()
idx.index_tags(instance, remove_only=not 'created' in kwargs)
-
+
post_delete.connect(update_index, Author)
post_delete.connect(update_index, BookStub)
post_save.connect(update_index, Author)
"""
if day_end:
date += datetime.timedelta(1)
- localtime = datetime.datetime.combine(date, datetime.time(0,0))
+ localtime = datetime.datetime.combine(date, datetime.time(0, 0))
return timezone.utc.normalize(
pytz.timezone(settings.TIME_ZONE).localize(localtime)
)
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.core.cache import get_cache
-from catalogue.utils import split_tags, related_tag_name
-from django.utils.safestring import mark_safe
+from catalogue.utils import split_tags
from fnpdjango.utils.text.slughifi import slughifi
from picture import tasks
from StringIO import StringIO
import jsonfield
import itertools
import logging
-from sorl.thumbnail import get_thumbnail, default
-from .engine import CustomCroppingEngine
from PIL import Image
class PictureArea(models.Model):
picture = models.ForeignKey('picture.Picture', related_name='areas')
area = jsonfield.JSONField(_('area'), default={}, editable=False)
- kind = models.CharField(_('kind'), max_length=10, blank=False,
- null=False, db_index=True,
- choices=(('thing', _('thing')),
+ kind = models.CharField(_('kind'), max_length=10, blank=False,
+ null=False, db_index=True,
+ choices=(('thing', _('thing')),
('theme', _('theme'))))
objects = models.Manager()
short_html = permanent_cache.get(cache_key)
else:
short_html = None
-
+
if short_html is not None:
return mark_safe(short_html)
else:
if not isinstance(xml_file, File):
xml_file = File(open(xml_file))
close_xml_file = True
-
+
try:
# use librarian to parse meta-data
if image_store is None:
from PIL import ImageDraw, ImageFont
from librarian import get_resource
- annotated = Image.new(img.mode,
- (img.size[0], img.size[1] + 40),
+ annotated = Image.new(img.mode,
+ (img.size[0], img.size[1] + 40),
(255, 255, 255)
)
annotated.paste(img, (0, 0))
def reset_short_html(self):
if self.id is None:
return
-
+
type(self).objects.filter(pk=self.pk).update(_related_info=None)
for area in self.areas.all().iterator():
area.reset_short_html()
- try:
+ try:
author = self.tags.filter(category='author')[0].sort_key
except IndexError:
author = u''
tag_info["name_%s" % lc] = tag_name
cat.append(tag_info)
rel['tags'][category] = cat
-
+
if self.pk:
type(self).objects.filter(pk=self.pk).update(_related_info=rel)
return rel
- # copied from book.py, figure out
+ # copied from book.py, figure out
def related_themes(self):
# self.theme_counter hides a computation, so a line below actually makes sense
theme_counter = self.theme_counter
if tags is None:
tags = {}
for area in PictureArea.objects.filter(picture=self).order_by().iterator():
- for tag in area.tags.filter(category__in=('theme','thing')).order_by().iterator():
+ for tag in area.tags.filter(category__in=('theme', 'thing')).order_by().iterator():
tags[tag.pk] = tags.get(tag.pk, 0) + 1
if self.id:
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
-from datetime import datetime
-from traceback import print_exc
from celery.task import task
-from django.conf import settings
-import picture.models
from django.core.files.base import ContentFile
from django.template.loader import render_to_string
-import librarian.picture
@task
def generate_picture_html(picture_id):
+ import picture.models
pic = picture.models.Picture.objects.get(pk=picture_id)
-
html_text = unicode(render_to_string('picture/picture_info.html', {
- 'things': pic.areas_json['things'],
+ 'things': pic.areas_json['things'],
'themes': pic.areas_json['themes'],
}))
pic.html_file.save("%s.html" % pic.slug, ContentFile(html_text))
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django import template
-from django.template import Node, Variable, Template, Context
from catalogue.utils import split_tags
-from itertools import chain
from ..engine import CustomCroppingEngine
import sorl.thumbnail.default
-import logging
+import logging
register = template.Library()
'tags': split_tags(picture.tags),
})
return context
-
+
@register.inclusion_tag('picture/picture_wide.html', takes_context=True)
def picture_wide(context, picture):
context.update({
return [[coords[0][0], coords[0][1] + h/2 - w/2],
[coords[1][0], coords[1][1] - h/2 + w/2, ]]
- # so much for sorl extensibility. # what to do about this?
+ # so much for sorl extensibility.
+ # what to do about this?
_engine = sorl.thumbnail.default.engine
sorl.thumbnail.default.engine = cropper
coords = to_square(area.area)
sorl.thumbnail.default.engine = _engine
return th.url
-
-
-
-
class PictureTest(WLTestCase):
-
+
def test_import(self):
picture = Picture.from_xml_file(path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml"))
path.join(path.dirname(__file__), "files/kandinsky-composition-viii.png"))
picture.delete()
-
+
def test_import_2(self):
picture = Picture.from_xml_file(path.join(path.dirname(__file__), "files/pejzaz-i-miasto-krzyzanowski-chmury.xml"),
from django.utils.datastructures import SortedDict
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
-from django.core.paginator import Paginator
from picture.models import Picture
from catalogue.utils import split_tags
picture = get_object_or_404(Picture, slug=slug)
return render_to_response("picture/picture_viewer.html", locals(),
context_instance=RequestContext(request))
-
+
# =========
# = Admin =
#
from django.contrib import admin
-from models import Poll, PollItem
+from .models import Poll, PollItem
class PollItemInline(admin.TabularInline):
model = PollItem
extra = 0
readonly_fields = ('vote_count',)
-
-
+
+
class PollAdmin(admin.ModelAdmin):
inlines = [PollItemInline]
-
+
class PollItemAdmin(admin.ModelAdmin):
readonly_fields = ('vote_count',)
-
-
+
+
admin.site.register(Poll, PollAdmin)
admin.site.register(PollItem, PollItemAdmin)
\r
\r
class PollForm(forms.Form):\r
- vote = forms.ChoiceField(widget = forms.RadioSelect)\r
- \r
+ vote = forms.ChoiceField(widget=forms.RadioSelect)\r
+\r
def __init__(self, *args, **kwargs):
poll = kwargs.pop('poll', None)\r
super(PollForm, self).__init__(*args, **kwargs)\r
question = models.TextField(_('question'))
slug = models.SlugField(_('slug'))
- open = models.BooleanField(_('open'), default = False)
-
+ open = models.BooleanField(_('open'), default=False)
+
class Meta:
verbose_name = _('Poll')
verbose_name_plural = _('Polls')
-
+
def clean(self):
- if self.open and Poll.objects.exclude(pk = self.pk).filter(slug = self.slug).exists():
+ if self.open and Poll.objects.exclude(pk=self.pk).filter(slug=self.slug).exists():
raise ValidationError(_('Slug of an open poll needs to be unique'))
return super(Poll, self).clean()
-
+
def __unicode__(self):
return self.question[:100] + ' (' + self.slug + ')'
-
+
def get_absolute_url(self):
- return reverse('poll', args = [self.slug])
-
+ return reverse('poll', args=[self.slug])
+
@property
def vote_count(self):
return self.items.all().aggregate(models.Sum('vote_count'))['vote_count__sum']
-
+
def voted(self, session):
return self.id in session.get(USED_POLLS_KEY, set())
-
+
class PollItem(models.Model):
-
- poll = models.ForeignKey(Poll, related_name = 'items')
+
+ poll = models.ForeignKey(Poll, related_name='items')
content = models.TextField(_('content'))
- vote_count = models.IntegerField(_('vote count'), default = 0)
-
+ vote_count = models.IntegerField(_('vote count'), default=0)
+
class Meta:
verbose_name = _('vote item')
verbose_name_plural = _('vote items')
- \r
+\r
def __unicode__(self):
return self.content + ' @ ' + unicode(self.poll)
-
+
@property
def vote_ratio(self):
return (float(self.vote_count) / self.poll.vote_count) * 100 if self.poll.vote_count else 0
-
+
def vote(self, session):
self.vote_count = self.vote_count + 1
self.save()
register = template.Library()
-@register.inclusion_tag('polls/tags/poll.html', takes_context = True)
-def poll(context, poll, show_results = True, redirect_to = ''):
+@register.inclusion_tag('polls/tags/poll.html', takes_context=True)
+def poll(context, poll, show_results=True, redirect_to=''):
form = None
voted_already = poll.voted(context.get('request').session)
if not voted_already:
- form = PollForm(poll = poll, initial = dict(redirect_to = redirect_to))
- return dict(poll = poll,
- form = form,
- voted_already = voted_already,
- vote_count = poll.vote_count,
- show_results = show_results
+ form = PollForm(poll=poll, initial=dict(redirect_to=redirect_to))
+ return dict(poll=poll,
+ form=form,
+ voted_already=voted_already,
+ vote_count=poll.vote_count,
+ show_results=show_results
)
from django.core.urlresolvers import reverse\r
from django.template import RequestContext
-from models import Poll, PollItem\r
-from forms import PollForm
+from .models import Poll, PollItem\r
+from .forms import PollForm
\r
@require_http_methods(['GET', 'POST'])\r
def poll(request, slug):
-
- poll = get_object_or_404(Poll, slug = slug, open = True)
-
+
+ poll = get_object_or_404(Poll, slug=slug, open=True)
+
if request.method == 'POST':\r
redirect_to = reverse('poll', args = [slug])
form = PollForm(request.POST, poll = poll)\r
if form.is_valid():\r
if not poll.voted(request.session):\r
try:\r
- poll_item = PollItem.objects.filter(pk = form.cleaned_data['vote'], poll = poll).get()
+ poll_item = PollItem.objects.filter(pk=form.cleaned_data['vote'], poll=poll).get()
except PollItem.DoesNotExist:\r
pass\r
else:\r
context['poll'] = poll\r
context['voted_already'] = poll.voted(request.session)
return render_to_response('polls/poll.html', context)
-
- \r
-
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
-import feedparser
from functools import wraps
-import datetime
-
from django import template
-
-from catalogue.models import Book, BookMedia
+from catalogue.models import Book
register = template.Library()
rendered = render_to_string(template, context)
texml = StringIO(rendered.encode('utf-8'))
- tempdir = mkdtemp(prefix = "render_to_pdf-")
+ tempdir = mkdtemp(prefix="render_to_pdf-")
tex_path = os.path.join(tempdir, "doc.tex")
with open(tex_path, 'w') as tex_file:
Texml.processor.process(texml, tex_file, encoding="utf-8")
"""
from django.template.loader import render_to_string
-
+
try:
os.makedirs(os.path.dirname(output_path))
except:
rendered = render_to_string(template, context)
with open(output_path, 'w') as csv_file:
csv_file.write(rendered.encode('utf-8'))
-
+
def read_chunks(f, size=8192):
chunk = f.read(size)
def generated_file_view(file_name, mime_type, send_name=None, signals=None):
file_path = os.path.join(settings.MEDIA_ROOT, file_name)
- file_url = os.path.join(settings.MEDIA_URL, file_name)
if send_name is None:
send_name = os.path.basename(file_name)
locals(), context_instance=RequestContext(request))
-@generated_file_view('reports/katalog.pdf', 'application/pdf',
+@generated_file_view('reports/katalog.pdf', 'application/pdf',
send_name=lambda: 'wolnelektury_%s.pdf' % date.today(),
signals=[Book.published])
def catalogue_pdf(path):
})
-@generated_file_view('reports/katalog.csv', 'application/csv',
+@generated_file_view('reports/katalog.csv', 'application/csv',
send_name=lambda: 'wolnelektury_%s.csv' % date.today(),
signals=[Book.published])
def catalogue_csv(path):
assert request.user.is_staff
assert 'choose_cite' in request.GET
cite = Cite.objects.get(pk=request.GET['choose_cite'])
- except AssertionError, Cite.DoesNotExist:
+ except (AssertionError, Cite.DoesNotExist):
if ctx is None:
cites = Cite.objects.all()
elif isinstance(ctx, Book):
#~ url(r'^polki/(?P<slug>[a-zA-Z0-9-]+)/usun/$', 'delete_shelf', name='delete_shelf'),
#~ url(r'^polki/(?P<slug>[a-zA-Z0-9-]+)\.zip$', 'download_shelf', name='download_shelf'),
#~ url(r'^polki/nowa/$', 'new_set', name='new_set'),
-)
+)
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseForbidden
from django.contrib.auth.decorators import login_required
-#~ from django.utils.datastructures import SortedDict
from django.views.decorators.http import require_POST
-#~ from django.contrib import auth
-#~ from django.views.decorators import cache
-from django.utils.translation import ugettext as _
-from ajaxable.utils import LazyEncoder, JSONResponse, AjaxableFormView
+from ajaxable.utils import JSONResponse, AjaxableFormView
-from catalogue.models import Book, Tag
+from catalogue.models import Book
from social import forms
from social.utils import get_set, likes, set_sets
simg = Image.open(sponsors[sponsor_id].logo.path)
if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
size = (
- min(THUMB_WIDTH,
+ min(THUMB_WIDTH,
simg.size[0] * THUMB_HEIGHT / simg.size[1]),
min(THUMB_HEIGHT,
simg.size[1] * THUMB_WIDTH / simg.size[0])
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
-from django.contrib.sites.models import Site
from django.conf import settings
from datetime import datetime
import logging
@classmethod
def exists(cls, path):
"""Returns opened file or None.
-
+
`path` is relative to WAITER_ROOT.
Won't open a path leading outside of WAITER_ROOT.
"""
def is_stale(self):
if self.task is None:
- # Race; just let the other task roll.
+ # Race; just let the other task roll.
return False
if self.task.status not in (u'PENDING', u'STARTED', u'SUCCESS', u'RETRY'):
return True
abs_path = check_abspath(path)
if exists(abs_path):
rmtree(abs_path)
-
import shutil
import tempfile
import sys
-import zipfile
import allauth
"I can create a necessary dest directiories, yey!"
if not os.path.exists(os.path.dirname(to)):
os.makedirs(os.path.dirname(to))
- shutil.copyfile(frm,to)
+ shutil.copyfile(frm, to)
class AppLocale(Locale):
def __init__(self, appmod):
if not options['directory'] or not os.path.exists(options['directory']):
print "Directory not provided or does not exist, please use -d"
sys.exit(1)
-
+
if options['merge']: self.merge_setup(options['directory'])
self.load(options)
if options['merge']: self.merge_finish(options['message'])
merge_branch = 'wl-locale-merge'
last_branch = None
-
+
def merge_setup(self, directory):
self.last_branch = self.current_branch()
rev = open(os.path.join(directory, '.revision')).read()
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
import os
-import sys
import time
from optparse import make_option
from django.conf import settings
for lng in zip(*languages)[0]:
pofile = os.path.join(options['directory'], lng, options['poname'] + '.po')
- if not os.path.exists(pofile):
+ if not os.path.exists(pofile):
if options['keep_running']:
continue
else: