~widelands-dev/widelands-website/django_staticfiles

« back to all changes in this revision

Viewing changes to wlmaps/views.py

  • Committer: Holger Rapp
  • Date: 2010-09-26 13:30:30 UTC
  • Revision ID: sirver@gmx.de-20100926133030-ceirjf83vde91tyt
Added a simple events model to display dates on the homepage

Show diffs side-by-side

added added

removed removed

Lines of Context:
2
2
# encoding: utf-8
3
3
#
4
4
 
5
 
from forms import UploadMapForm, EditCommentForm
6
 
from django.shortcuts import render, get_object_or_404
 
5
from forms import UploadMapForm
 
6
from django.shortcuts import render_to_response, get_object_or_404
 
7
from django.template import RequestContext
7
8
from django.contrib.auth.decorators import login_required
8
9
from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponse, HttpResponseBadRequest
9
 
from django.urls import reverse
 
10
from django.core.urlresolvers import reverse
 
11
from django.utils import simplejson as json
 
12
from django.db import IntegrityError
 
13
import Image
10
14
import models
11
 
from settings import MAPS_PER_PAGE
12
 
from wl_utils import get_real_ip
 
15
 
 
16
from widelandslib.Map import WidelandsMap, WlMapLibraryException
 
17
 
13
18
import os
 
19
from cStringIO import StringIO
 
20
import zipfile
 
21
 
 
22
from settings import WIDELANDS_SVN_DIR, MEDIA_ROOT, MEDIA_URL
14
23
 
15
24
 
16
25
#########
17
26
# Views #
18
27
#########
19
 
def index(request):
20
 
    maps = models.Map.objects.all()
21
 
    return render(request, 'wlmaps/index.html',
22
 
                              {'maps': maps,
23
 
                               'maps_per_page': MAPS_PER_PAGE,
24
 
                               })
25
 
 
26
 
 
27
 
def download(request, map_slug):
28
 
    """Very simple view that just returns the binary data of this map and
29
 
    increases the download count."""
30
 
    m = get_object_or_404(models.Map, slug=map_slug)
31
 
 
32
 
    file = open(m.file.path, 'rb')
 
28
def index( request ):
 
29
    objects = models.Map.objects.all()
 
30
    return render_to_response("wlmaps/index.html",
 
31
                { "object_list": objects, },
 
32
                context_instance = RequestContext(request))
 
33
 
 
34
def rate( request, map_slug ):
 
35
    """
 
36
    Rate a given map
 
37
    """
 
38
    if request.method != "POST":
 
39
        return HttpResponseNotAllowed(["post"])
 
40
 
 
41
    m = get_object_or_404( models.Map, slug = map_slug )
 
42
 
 
43
    if not "vote" in request.POST:
 
44
        return HttpResponseBadRequest()
 
45
    try:
 
46
        val = int(request.POST["vote"])
 
47
    except ValueError:
 
48
        return HttpResponseBadRequest()
 
49
 
 
50
    if not (0 < val <= 10):
 
51
        return HttpResponseBadRequest()
 
52
 
 
53
    m.rating.add(score=val, user=request.user,
 
54
                 ip_address=request.META['REMOTE_ADDR'])
 
55
    # m.save() is not needed
 
56
 
 
57
    return HttpResponseRedirect(reverse("wlmaps_view", None, {"map_slug": m.slug }))
 
58
 
 
59
 
 
60
def download( request, map_slug ):
 
61
    """
 
62
    Very simple view that just returns the binary data of this map and increases
 
63
    the download count
 
64
    """
 
65
    m = get_object_or_404( models.Map, slug = map_slug )
 
66
 
 
67
    file = open(m.file.path,"rb")
33
68
    data = file.read()
34
 
    filename = os.path.basename('%s.wmf' % m.name)
 
69
 
 
70
    # We have to find the correct filename, widelands is quite
 
71
    # buggy. The Filename must be the same as the directory
 
72
    # packed in the zip.
 
73
    file.seek(0)
 
74
    zf = zipfile.ZipFile(file)
 
75
    probable_filenames = filter( len, [ i.filename.split('/')[0] for i in zf.filelist ])
 
76
    if not len(probable_filenames):
 
77
        probable_filename = os.path.basename("%s.wmf" % m.name)
 
78
    else:
 
79
        probable_filename = probable_filenames[0]
35
80
 
36
81
    # Remember that this has been downloaded
37
82
    m.nr_downloads += 1
38
 
    m.save(update_fields=['nr_downloads'])
 
83
    m.save()
39
84
 
40
 
    response = HttpResponse(data, content_type='application/octet-stream')
41
 
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename
 
85
    response =  HttpResponse( data, mimetype = "application/octet-stream")
 
86
    response['Content-Disposition'] = 'attachment; filename="%s"' % probable_filename
42
87
 
43
88
    return response
44
89
 
45
90
 
 
91
 
46
92
def view(request, map_slug):
47
 
    map = get_object_or_404(models.Map, slug=map_slug)
 
93
    m = get_object_or_404( models.Map, slug = map_slug )
 
94
 
 
95
    if m.rating.votes > 0:
 
96
        avg = "%.1f" %( float(m.rating.score) /m.rating.votes )
 
97
    else:
 
98
        avg = "0"
 
99
 
48
100
    context = {
49
 
        'map': map,
 
101
        "average_rating": avg,
 
102
        "object": m,
50
103
    }
51
 
    return render(request, 'wlmaps/map_detail.html',
52
 
                              context)
53
 
 
54
 
 
55
 
@login_required
56
 
def edit_comment(request, map_slug):
57
 
    map = get_object_or_404(models.Map, slug=map_slug)
58
 
    if request.method == 'POST':
59
 
        form = EditCommentForm(request.POST)
60
 
        if form.is_valid():
61
 
            map.uploader_comment = form.cleaned_data['uploader_comment']
62
 
            map.save(update_fields=['uploader_comment'])
63
 
            return HttpResponseRedirect(map.get_absolute_url())
64
 
    else:
65
 
        form = EditCommentForm(instance=map)
66
 
 
67
 
    context = {'form': form, 'map': map}
68
 
 
69
 
    return render(request, 'wlmaps/edit_comment.html',
70
 
                              context)
71
 
 
72
 
 
73
 
@login_required
74
 
def upload(request):
75
 
    if request.method == 'POST':
76
 
        form = UploadMapForm(request.POST, request.FILES)
77
 
        if form.is_valid():
78
 
            map = form.save(commit=False)
79
 
            map.uploader = request.user
80
 
            map.save()
81
 
            return HttpResponseRedirect(map.get_absolute_url())
82
 
    else:
83
 
        form = UploadMapForm()
84
 
 
85
 
    context = {'form': form, }
86
 
    return render(request, 'wlmaps/upload.html',
87
 
                              context)
 
104
    return render_to_response( "wlmaps/map_detail.html",
 
105
                              context,
 
106
                              context_instance=RequestContext(request))
 
107
 
 
108
@login_required
 
109
def upload( request ):
 
110
    """
 
111
    Uploads a map. This is an ajax post and returns an JSON object
 
112
    with the following values.
 
113
 
 
114
    success_code - integer (0 means success else error)
 
115
    error_msg - if success_code = 1 this contains an descriptive error
 
116
    map_id - id of newly uploaded map
 
117
    """
 
118
    def JsonReply( success_code, error_msg = None, **kwargs):
 
119
        d = kwargs
 
120
        d['success_code'] = success_code
 
121
        if error_msg != None:
 
122
            d['error_msg'] = error_msg
 
123
        return HttpResponse( json.dumps(d), mimetype="application/javascript" )
 
124
 
 
125
    if request.method != "POST":
 
126
        return HttpResponseNotAllowed(["post"])
 
127
 
 
128
    form = UploadMapForm( request.POST )
 
129
    test = request.POST.get("test", False)
 
130
    comment = request.POST.get("comment",u"")
 
131
 
 
132
    if "mapfile" in request.FILES:
 
133
        mf = request.FILES["mapfile"]
 
134
 
 
135
        mfdata = mf.read()
 
136
 
 
137
        m = WidelandsMap()
 
138
        try:
 
139
            m.load(StringIO(mfdata))
 
140
        except WlMapLibraryException:
 
141
            return JsonReply( 3, "Invalid Map File" )
 
142
 
 
143
        # Draw the minimaps
 
144
        mm = m.make_minimap(WIDELANDS_SVN_DIR)
 
145
        mm_path = "%s/wlmaps/minimaps/%s.png" % (MEDIA_ROOT,m.name)
 
146
        mm_url = "/wlmaps/minimaps/%s.png" % m.name
 
147
        file_path = "%s/wlmaps/maps/%s.wmf" % (MEDIA_ROOT,m.name)
 
148
 
 
149
        if not test:
 
150
            f = open(file_path,"wb")
 
151
            f.write(mfdata)
 
152
            f.close()
 
153
            i = Image.fromarray(mm)
 
154
            i.save(mm_path)
 
155
 
 
156
        # Create the map
 
157
        try:
 
158
            nm = models.Map.objects.create(
 
159
                name = m.name,
 
160
                author = m.author,
 
161
                w = m.w,
 
162
                h = m.h,
 
163
                nr_players = m.nr_players,
 
164
                descr = m.descr,
 
165
                minimap = mm_url,
 
166
                file = file_path,
 
167
                world_name = m.world_name,
 
168
 
 
169
                uploader = request.user,
 
170
                uploader_comment = comment,
 
171
            )
 
172
        except IntegrityError:
 
173
            return JsonReply(2, "Map with the same name already exists in database!")
 
174
 
 
175
        nm.save()
 
176
 
 
177
        return JsonReply(0, map_id = nm.pk )
 
178
 
 
179
    return JsonReply(1, "No mapfile in request!")