6d4c8be38b2072a665a0744d3e2f961643ea4e2a
[mediagoblin.git] / mediagoblin / submit / views.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 from mediagoblin import messages
18 import mediagoblin.mg_globals as mg_globals
19 import uuid
20 from os.path import splitext
21
22 from celery import registry
23 import logging
24
25 _log = logging.getLogger(__name__)
26
27 from werkzeug.utils import secure_filename
28 from werkzeug.datastructures import FileStorage
29
30 from mediagoblin.tools.text import convert_to_tag_list_of_dicts
31 from mediagoblin.tools.translate import pass_to_ugettext as _
32 from mediagoblin.tools.response import render_to_response, redirect
33 from mediagoblin.decorators import require_active_login
34 from mediagoblin.submit import forms as submit_forms
35 from mediagoblin.processing import mark_entry_failed
36 from mediagoblin.processing.task import ProcessMedia
37 from mediagoblin.messages import add_message, SUCCESS
38 from mediagoblin.media_types import sniff_media, \
39 InvalidFileType, FileTypeNotSupported
40 from mediagoblin.submit.lib import handle_push_urls
41
42
43 @require_active_login
44 def submit_start(request):
45 """
46 First view for submitting a file.
47 """
48 submit_form = submit_forms.SubmitStartForm(request.form)
49
50 if request.method == 'POST' and submit_form.validate():
51 if not ('file' in request.files
52 and isinstance(request.files['file'], FileStorage)
53 and request.files['file'].stream):
54 submit_form.file.errors.append(
55 _(u'You must provide a file.'))
56 else:
57 try:
58 filename = request.files['file'].filename
59
60 # Sniff the submitted media to determine which
61 # media plugin should handle processing
62 media_type, media_manager = sniff_media(
63 request.files['file'])
64
65 # create entry and save in database
66 entry = request.db.MediaEntry()
67 entry.media_type = unicode(media_type)
68 entry.title = (
69 unicode(request.form['title'])
70 or unicode(splitext(filename)[0]))
71
72 entry.description = unicode(request.form.get('description'))
73
74 entry.license = unicode(request.form.get('license', "")) or None
75
76 entry.uploader = request.user.id
77
78 # Process the user's folksonomy "tags"
79 entry.tags = convert_to_tag_list_of_dicts(
80 request.form.get('tags'))
81
82 # Generate a slug from the title
83 entry.generate_slug()
84
85 # We generate this ourselves so we know what the taks id is for
86 # retrieval later.
87
88 # (If we got it off the task's auto-generation, there'd be
89 # a risk of a race condition when we'd save after sending
90 # off the task)
91 task_id = unicode(uuid.uuid4())
92
93 # Now store generate the queueing related filename
94 queue_filepath = request.app.queue_store.get_unique_filepath(
95 ['media_entries',
96 task_id,
97 secure_filename(filename)])
98
99 # queue appropriately
100 queue_file = request.app.queue_store.get_file(
101 queue_filepath, 'wb')
102
103 with queue_file:
104 queue_file.write(request.files['file'].stream.read())
105
106 # Add queued filename to the entry
107 entry.queued_media_file = queue_filepath
108
109 entry.queued_task_id = task_id
110
111 # Save now so we have this data before kicking off processing
112 entry.save()
113
114 # Pass off to processing
115 #
116 # (... don't change entry after this point to avoid race
117 # conditions with changes to the document via processing code)
118 process_media = registry.tasks[ProcessMedia.name]
119 try:
120 process_media.apply_async(
121 [unicode(entry.id)], {},
122 task_id=task_id)
123 except BaseException as exc:
124 # The purpose of this section is because when running in "lazy"
125 # or always-eager-with-exceptions-propagated celery mode that
126 # the failure handling won't happen on Celery end. Since we
127 # expect a lot of users to run things in this way we have to
128 # capture stuff here.
129 #
130 # ... not completely the diaper pattern because the
131 # exception is re-raised :)
132 mark_entry_failed(entry.id, exc)
133 # re-raise the exception
134 raise
135
136 handle_push_urls(request)
137
138 add_message(request, SUCCESS, _('Woohoo! Submitted!'))
139
140 return redirect(request, "mediagoblin.user_pages.user_home",
141 user=request.user.username)
142 except Exception as e:
143 '''
144 This section is intended to catch exceptions raised in
145 mediagoblin.media_types
146 '''
147 if isinstance(e, InvalidFileType) or \
148 isinstance(e, FileTypeNotSupported):
149 submit_form.file.errors.append(
150 e)
151 else:
152 raise
153
154 return render_to_response(
155 request,
156 'mediagoblin/submit/start.html',
157 {'submit_form': submit_form,
158 'app_config': mg_globals.app_config})
159
160 @require_active_login
161 def add_collection(request, media=None):
162 """
163 View to create a new collection
164 """
165 submit_form = submit_forms.AddCollectionForm(request.form)
166
167 if request.method == 'POST' and submit_form.validate():
168 try:
169 collection = request.db.Collection()
170
171 collection.title = unicode(request.form['title'])
172 collection.description = unicode(request.form.get('description'))
173 collection.creator = request.user.id
174 collection.generate_slug()
175
176 # Make sure this user isn't duplicating an existing collection
177 existing_collection = request.db.Collection.find_one({
178 'creator': request.user.id,
179 'title':collection.title})
180
181 if existing_collection:
182 messages.add_message(
183 request, messages.ERROR, _('You already have a collection called "%s"!' % collection.title))
184 else:
185 collection.save()
186
187 add_message(request, SUCCESS, _('Collection "%s" added!' % collection.title))
188
189 return redirect(request, "mediagoblin.user_pages.user_home",
190 user=request.user.username)
191
192 except Exception as e:
193 raise
194
195 return render_to_response(
196 request,
197 'mediagoblin/submit/collection.html',
198 {'submit_form': submit_form,
199 'app_config': mg_globals.app_config})