Merge branch '512_bump_video_js'
[mediagoblin.git] / mediagoblin / tools / processing.py
CommitLineData
5354f954
JW
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
17import logging
18import json
939d57a0 19import traceback
5354f954 20
939d57a0 21from urllib2 import urlopen, Request, HTTPError
5354f954
JW
22from urllib import urlencode
23
0df00eb6
JW
24from mediagoblin.tools.common import TESTS_ENABLED
25
5354f954
JW
26_log = logging.getLogger(__name__)
27
0df00eb6
JW
28TESTS_CALLBACKS = {}
29
5354f954
JW
30
31def create_post_request(url, data, **kw):
32 '''
33 Issue a HTTP POST request.
34
35 Args:
36 url: The URL to which the POST request should be issued
37 data: The data to be send in the body of the request
38 **kw:
39 data_parser: The parser function that is used to parse the `data`
40 argument
41 '''
42 data_parser = kw.get('data_parser', urlencode)
43 headers = kw.get('headers', {})
44
45 return Request(url, data_parser(data), headers=headers)
46
47
48def json_processing_callback(entry):
49 '''
50 Send an HTTP post to the registered callback url, if any.
51 '''
52 if not entry.processing_metadata:
53 _log.debug('No processing callback for {0}'.format(entry))
54 return
55
56 url = entry.processing_metadata[0].callback_url
57
58 _log.debug('Sending processing callback for {0} ({1})'.format(
59 entry,
60 url))
61
62 headers = {
63 'Content-Type': 'application/json'}
64
65 data = {
66 'id': entry.id,
67 'state': entry.state}
68
0df00eb6
JW
69 # Trigger testing mode, no callback will be sent
70 if url.endswith('secrettestmediagoblinparam'):
71 TESTS_CALLBACKS.update({url: data})
72 return True
73
5354f954
JW
74 request = create_post_request(
75 url,
76 data,
77 headers=headers,
78 data_parser=json.dumps)
79
939d57a0
JW
80 try:
81 urlopen(request)
82 _log.debug('Processing callback for {0} sent'.format(entry))
5354f954 83
939d57a0
JW
84 return True
85 except HTTPError:
86 _log.error('Failed to send callback: {0}'.format(
87 traceback.format_exc()))
88
89 return False