possibly_localize_file->localized_file... a bit less terribly long.
[mediagoblin.git] / mediagoblin / process_media / __init__.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 Free Software Foundation, Inc
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 import Image
18 from mediagoblin.db.util import ObjectId
19 from celery.task import task
20
21 from mediagoblin import globals as mg_globals
22
23
24 THUMB_SIZE = 200, 200
25
26
27 @task
28 def process_media_initial(media_id):
29 workbench = mg_globals.workbench_manager.create_workbench()
30
31 entry = mg_globals.database.MediaEntry.one(
32 {'_id': ObjectId(media_id)})
33
34 queued_filepath = entry['queued_media_file']
35 queued_filename = mg_globals.workbench_manager.localized_file(
36 workbench, mg_globals.queue_store, queued_filepath,
37 'source')
38
39 queued_file = file(queued_filename, 'r')
40
41 with queued_file:
42 thumb = Image.open(queued_file)
43 thumb.thumbnail(THUMB_SIZE, Image.ANTIALIAS)
44
45 thumb_filepath = mg_globals.public_store.get_unique_filepath(
46 ['media_entries',
47 unicode(entry['_id']),
48 'thumbnail.jpg'])
49
50 thumb_file = mg_globals.public_store.get_file(thumb_filepath, 'w')
51 with thumb_file:
52 thumb.save(thumb_file, "JPEG")
53
54 # we have to re-read because unlike PIL, not everything reads
55 # things in string representation :)
56 queued_file = file(queued_filename, 'rb')
57
58 with queued_file:
59 main_filepath = mg_globals.public_store.get_unique_filepath(
60 ['media_entries',
61 unicode(entry['_id']),
62 queued_filepath[-1]])
63
64 with mg_globals.public_store.get_file(main_filepath, 'wb') as main_file:
65 main_file.write(queued_file.read())
66
67 mg_globals.queue_store.delete_file(queued_filepath)
68 media_files_dict = entry.setdefault('media_files', {})
69 media_files_dict['thumb'] = thumb_filepath
70 media_files_dict['main'] = main_filepath
71 entry['state'] = u'processed'
72 entry.save()
73
74 # clean up workbench
75 mg_globals.workbench_manager.destroy_workbench(workbench)