# Path: pyca/config.py
# def config(*args):
#     '''Get a specific configuration value or the whole configuration, loading
#     the configuration file if it was not before.
# 
#     :param key: optional configuration key to return
#     :type key: string
#     :return: Part of the configuration object containing the configuration
#              or configuration value.
#              If a part of the configuration object (e.g. configobj.Section) is
#              returned, it can be treated like a dictionary.
#              Returning None, if the configuration value is not found.
#     '''
#     cfg = __config or update_configuration()
#     for key in args:
#         if cfg is None:
#             return
#         cfg = cfg.get(key)
#     return cfg
# 
# Path: pyca/utils.py
# def http_request(url, post_data=None):
#     '''Make an HTTP request to a given URL with optional parameters.
#     '''
#     logger.debug('Requesting URL: %s', url)
#     buf = bio()
#     curl = pycurl.Curl()
#     curl.setopt(curl.URL, url.encode('ascii', 'ignore'))
# 
#     # More verbose curl calls in debug mode
#     if logger.getEffectiveLevel() == logging.DEBUG:
#         curl.setopt(pycurl.VERBOSE, True)
# 
#     # Disable HTTPS verification methods if insecure is set
#     if config('server', 'insecure'):
#         curl.setopt(curl.SSL_VERIFYPEER, 0)
#         curl.setopt(curl.SSL_VERIFYHOST, 0)
# 
#     if config('server', 'certificate'):
#         # Make sure verification methods are turned on
#         curl.setopt(curl.SSL_VERIFYPEER, 1)
#         curl.setopt(curl.SSL_VERIFYHOST, 2)
#         # Import your certificates
#         curl.setopt(pycurl.CAINFO, config('server', 'certificate'))
# 
#     if config('ingest', 'upload_rate') > 0:
#         curl.setopt(
#             curl.MAX_SEND_SPEED_LARGE,
#             config('ingest', 'upload_rate'))
# 
#     if post_data:
#         curl.setopt(curl.HTTPPOST, post_data)
#     curl.setopt(curl.WRITEFUNCTION, buf.write)
#     logger.debug('Using authentication method %s',
#                  config('server')['auth_method'])
#     if config('server')['auth_method'] == 'digest':
#         curl.setopt(curl.HTTPHEADER, ['X-Requested-Auth: Digest'])
#         curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_DIGEST)
#     curl.setopt(pycurl.USERPWD, ':'.join([config('server', 'username'),
#                                           config('server', 'password')]))
#     curl.setopt(curl.FAILONERROR, True)
#     curl.setopt(curl.FOLLOWLOCATION, True)
#     curl.perform()
#     curl.close()
#     result = buf.getvalue()
#     buf.close()
#     return result
# 
# def service(service_name, force_update=False):
#     '''Get the location of a given service from Opencast and add it to the
#     current configuration.
# 
#     :param service_name: Name of the service type to request locations for
#     :param force_update: Force an update, possibly wait for a service to
#                          become available if none is available right now.
#     :return: List of service locations
#     '''
#     service_id = f'org.opencastproject.{service_name}'
#     service_url = config('services', service_id)
#     logger.debug('Cached service URLs for %s: %s', service_name, service_url)
#     if service_url and not force_update:
#         return service_url
# 
#     # Get service from Opencast server
#     config('services')[service_id] = []
#     while not config('services', service_id) and not terminate():
#         try:
#             config('services')[service_id] = get_service(service_id)
#             logger.debug('Updates service URL for %s: %s',
#                          service_name,
#                          config('services', service_id))
#         except pycurl.error:
#             logger.exception('Could not get %s endpoint. Retry in 5s',
#                              service_name)
#             time.sleep(5.0)
#     return config('services', service_id)


from xml.sax.saxutils import escape as xml_escape
from pyca.config import config
from pyca.utils import http_request, service
from datetime import datetime, timedelta
import logging
import random
    :type creator: int
    '''
    if not creator:
        creator = config('ui', 'username')

    # Select ingest service
    # The ingest service to use is selected at random from the available
    # ingest services to ensure that not every capture agent uses the same
    # service at the same time
    service_url = service('ingest', force_update=True)
    service_url = service_url[random.randrange(0, len(service_url))]
    logger.info('Selecting ingest service for scheduling: ' + service_url)

    # create media package
    logger.info('Creating new media package')
    mediapackage = http_request(service_url + '/createMediaPackage')

    # add dublin core catalog
    start = datetime.utcnow() + timedelta(seconds=10)
    end = start + timedelta(seconds=duration)
    dublincore = DUBLINCORE.format(
            agent_name=xml_escape(config('agent', 'name')),
            start=start.strftime('%Y-%m-%dT%H:%M:%SZ'),
            end=end.strftime('%Y-%m-%dT%H:%M:%SZ'),
            title=xml_escape(title),
            creator=xml_escape(creator))
    logger.info('Adding Dublin Core catalog for scheduling')
    fields = [('mediaPackage', mediapackage),
              ('flavor', 'dublincore/episode'),
              ('dublinCore', dublincore)]

# Path: pyca/config.py
# def config(*args):
#     '''Get a specific configuration value or the whole configuration, loading
#     the configuration file if it was not before.
# 
#     :param key: optional configuration key to return
#     :type key: string
#     :return: Part of the configuration object containing the configuration
#              or configuration value.
#              If a part of the configuration object (e.g. configobj.Section) is
#              returned, it can be treated like a dictionary.
#              Returning None, if the configuration value is not found.
#     '''
#     cfg = __config or update_configuration()
#     for key in args:
#         if cfg is None:
#             return
#         cfg = cfg.get(key)
#     return cfg
# 
# Path: pyca/utils.py
# def http_request(url, post_data=None):
#     '''Make an HTTP request to a given URL with optional parameters.
#     '''
#     logger.debug('Requesting URL: %s', url)
#     buf = bio()
#     curl = pycurl.Curl()
#     curl.setopt(curl.URL, url.encode('ascii', 'ignore'))
# 
#     # More verbose curl calls in debug mode
#     if logger.getEffectiveLevel() == logging.DEBUG:
#         curl.setopt(pycurl.VERBOSE, True)
# 
#     # Disable HTTPS verification methods if insecure is set
#     if config('server', 'insecure'):
#         curl.setopt(curl.SSL_VERIFYPEER, 0)
#         curl.setopt(curl.SSL_VERIFYHOST, 0)
# 
#     if config('server', 'certificate'):
#         # Make sure verification methods are turned on
#         curl.setopt(curl.SSL_VERIFYPEER, 1)
#         curl.setopt(curl.SSL_VERIFYHOST, 2)
#         # Import your certificates
#         curl.setopt(pycurl.CAINFO, config('server', 'certificate'))
# 
#     if config('ingest', 'upload_rate') > 0:
#         curl.setopt(
#             curl.MAX_SEND_SPEED_LARGE,
#             config('ingest', 'upload_rate'))
# 
#     if post_data:
#         curl.setopt(curl.HTTPPOST, post_data)
#     curl.setopt(curl.WRITEFUNCTION, buf.write)
#     logger.debug('Using authentication method %s',
#                  config('server')['auth_method'])
#     if config('server')['auth_method'] == 'digest':
#         curl.setopt(curl.HTTPHEADER, ['X-Requested-Auth: Digest'])
#         curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_DIGEST)
#     curl.setopt(pycurl.USERPWD, ':'.join([config('server', 'username'),
#                                           config('server', 'password')]))
#     curl.setopt(curl.FAILONERROR, True)
#     curl.setopt(curl.FOLLOWLOCATION, True)
#     curl.perform()
#     curl.close()
#     result = buf.getvalue()
#     buf.close()
#     return result
# 
# def service(service_name, force_update=False):
#     '''Get the location of a given service from Opencast and add it to the
#     current configuration.
# 
#     :param service_name: Name of the service type to request locations for
#     :param force_update: Force an update, possibly wait for a service to
#                          become available if none is available right now.
#     :return: List of service locations
#     '''
#     service_id = f'org.opencastproject.{service_name}'
#     service_url = config('services', service_id)
#     logger.debug('Cached service URLs for %s: %s', service_name, service_url)
#     if service_url and not force_update:
#         return service_url
# 
#     # Get service from Opencast server
#     config('services')[service_id] = []
#     while not config('services', service_id) and not terminate():
#         try:
#             config('services')[service_id] = get_service(service_id)
#             logger.debug('Updates service URL for %s: %s',
#                          service_name,
#                          config('services', service_id))
#         except pycurl.error:
#             logger.exception('Could not get %s endpoint. Retry in 5s',
#                              service_name)
#             time.sleep(5.0)
#     return config('services', service_id)


# Path: pyca/ui/opencast_commands.py
from xml.sax.saxutils import escape as xml_escape
from pyca.config import config
from pyca.utils import http_request, service
from datetime import datetime, timedelta
import logging
import random

    :type creator: int
    '''
    if not creator:
        creator = config('ui', 'username')

    # Select ingest service
    # The ingest service to use is selected at random from the available
    # ingest services to ensure that not every capture agent uses the same
    # service at the same time
    service_url = service('ingest', force_update=True)
    service_url = service_url[random.randrange(0, len(service_url))]
    logger.info('Selecting ingest service for scheduling: ' + service_url)

    # create media package
    logger.info('Creating new media package')
    mediapackage = http_request(service_url + '/createMediaPackage')

    # add dublin core catalog
    start = datetime.utcnow() + timedelta(seconds=10)
    end = start + timedelta(seconds=duration)
    dublincore = DUBLINCORE.format(
            agent_name=xml_escape(config('agent', 'name')),
            start=start.strftime('%Y-%m-%dT%H:%M:%SZ'),
            end=end.strftime('%Y-%m-%dT%H:%M:%SZ'),
            title=xml_escape(title),
            creator=xml_escape(creator))
    logger.info('Adding Dublin Core catalog for scheduling')
    fields = [('mediaPackage', mediapackage),
              ('flavor', 'dublincore/episode'),
              ('dublinCore', dublincore)]

    mediapackage = http_request(service_url + '/addDCCatalog', fields)