'Execute task and stream results'

@api.response(NotFoundError)
@api.response(BadRequest)
@api.response(200, model=task_api_execute_schema)
@api.validate(task_execution_schema)
def post(self, session=None):

    data = request.json
    for task in data.get(u'tasks'):
        if (task.lower() not in [t.lower() for t in self.manager.user_config.get(u'tasks', {}).keys()]):
            raise NotFoundError((u'task    %s    does    not    exist' % task))
    queue = ExecuteLog()
    output = (queue if data.get(u'loglevel') else None)
    stream = (True if any(((arg[0] in [u'progress', u'summary', u'loglevel', u'entry_dump']) for arg in data.items() if arg[1])) else False)
    loglevel = data.pop(u'loglevel', None)
    options = {u'interval_ignore': data.pop(u'now', None), u'nocache': data.pop(u'no_cache', None), u'allow_manual': True}
    for (option, value) in data.items():
        options[option] = value
    if data.get(u'inject'):
        entries = []
        for item in data.get(u'inject'):
            entry = Entry()
            entry[u'url'] = item[u'url']
            if (not item.get(u'title')):
                try:
                    (value, params) = cgi.parse_header(requests.head(item[u'url']).headers[u'Content-Disposition'])
                    entry[u'title'] = params[u'filename']
                except KeyError:
                    raise BadRequest(u"No    title    given,    and    couldn't    get    one    from    the    URL's    HTTP    response")
            else:
                entry[u'title'] = item.get(u'title')
            if item.get(u'force'):
                entry[u'immortal'] = True
            if item.get(u'accept'):
                entry.accept(reason=u'accepted    by    API    inject')
            if item.get(u'fields'):
                for (key, value) in item.get(u'fields').items():
                    entry[key] = value
            entries.append(entry)
        options[u'inject'] = entries
    executed_tasks = self.manager.execute(options=options, output=output, loglevel=loglevel)
    tasks_queued = []
    for (task_id, task_name, task_event) in executed_tasks:
        tasks_queued.append({u'id': task_id, u'name': task_name, u'event': task_event})
        _streams[task_id] = {u'queue': queue, u'last_update': datetime.now(), u'args': data}
    if (not stream):
        return jsonify({u'tasks': [{u'id': task[u'id'], u'name': task[u'name']} for task in tasks_queued]})
    def stream_response():
        (yield u'{"stream":    [')
        (yield (json.dumps({u'tasks': [{u'id': task[u'id'], u'name': task[u'name']} for task in tasks_queued]}) + u',\n'))
        while True:
            try:
                (yield (queue.get(timeout=1) + u',\n'))
                continue
            except Empty:
                pass
            if (queue.empty() and all([task[u'event'].is_set() for task in tasks_queued])):
                for task in tasks_queued:
                    del _streams[task[u'id']]
                break
        (yield u'{}]}')
    return Response(stream_response(), mimetype=u'text/event-stream')
