processing.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. import logging
  17. import json
  18. import traceback
  19. from six.moves.urllib import request, parse
  20. _log = logging.getLogger(__name__)
  21. TESTS_CALLBACKS = {}
  22. def create_post_request(url, data, **kw):
  23. '''
  24. Issue a HTTP POST request.
  25. Args:
  26. url: The URL to which the POST request should be issued
  27. data: The data to be send in the body of the request
  28. **kw:
  29. data_parser: The parser function that is used to parse the `data`
  30. argument
  31. '''
  32. data_parser = kw.get('data_parser', parse.urlencode)
  33. headers = kw.get('headers', {})
  34. return request.Request(url, data_parser(data), headers=headers)
  35. def json_processing_callback(entry):
  36. '''
  37. Send an HTTP post to the registered callback url, if any.
  38. '''
  39. if not entry.processing_metadata:
  40. _log.debug('No processing callback URL for {0}'.format(entry))
  41. return
  42. url = entry.processing_metadata[0].callback_url
  43. _log.debug('Sending processing callback for {0} to {1}'.format(
  44. entry,
  45. url))
  46. headers = {
  47. 'Content-Type': 'application/json'}
  48. data = {
  49. 'id': entry.id,
  50. 'state': entry.state}
  51. # Trigger testing mode, no callback will be sent
  52. if url.endswith('secrettestmediagoblinparam'):
  53. TESTS_CALLBACKS.update({url: data})
  54. return True
  55. request = create_post_request(
  56. url,
  57. data,
  58. headers=headers,
  59. data_parser=json.dumps)
  60. try:
  61. request.urlopen(request)
  62. _log.debug('Processing callback for {0} sent'.format(entry))
  63. return True
  64. except request.HTTPError:
  65. _log.error('Failed to send callback: {0}'.format(
  66. traceback.format_exc()))
  67. return False