<commit_before>from flask import render_template, request, jsonify, json, send_file
from jinja2.filters import FILTERS
from maraschino.tools import get_setting_value, requires_auth
from maraschino import logger, app, WEBROOT
import urllib2
import StringIO
import base64

def couchpotato_http():
    if get_setting_value('couchpotato_https') == '1':
        return 'https://'
    else:
        return 'http://'


def couchpotato_url():
    port = get_setting_value('couchpotato_port')
    url_base = get_setting_value('couchpotato_ip')
    webroot = get_setting_value('couchpotato_webroot')
    
    if port:
        url_base = '%s:%s' % (url_base, port)

    if webroot:
        url_base = '%s/%s' % (url_base, webroot)
    
    url = '%s/api/%s' % (url_base, get_setting_value('couchpotato_api'))
    
    return couchpotato_http() + url


def couchpotato_url_no_api():
    port = get_setting_value('couchpotato_port')
    url_base = get_setting_value('couchpotato_ip')
    webroot = get_setting_value('couchpotato_webroot')

    if port:
        url_base = '%s:%s' % (url_base, port)

    if webroot:
        url_base = '%s/%s' % (url_base, webroot)
        
    return couchpotato_http() + url_base


def couchpotato_api(method, params=None, use_json=True, dev=False):
    username = get_setting_value('couchpotato_user')
    password = get_setting_value('couchpotato_password')

    if params:
        params = '/?%s' % params
    else:
        params = '/'

    url = '%s/%s%s' % (couchpotato_url(), method, params)
    request = urllib2.Request(url)

    if username and password:
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

    data = urllib2.urlopen(request).read()
    if dev:
        print url
        print data
    if use_json:
        data = json.JSONDecoder().decode(data)
    return data


def log_exception(e):
    logger.log('CouchPotato :: EXCEPTION -- %s' % e, 'DEBUG')


def couchpotato_image(path):
    if path.startswith('/'):
        path = path[1:]
    return '%s/xhr/couchpotato/image/%s' % (WEBROOT, path)


FILTERS['cp_img'] = couchpotato_image


@app.route('/xhr/couchpotato/image/<path:url>')
def couchpotato_proxy(url):
    username = get_setting_value('couchpotato_user')
    password = get_setting_value('<PASSWORD>')

    url = '%s/file.cache/%s' % (couchpotato_url(), url)
    request = urllib2.Request(url)

    if username and password:
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

    img = StringIO.StringIO(urllib2.urlopen(request).read())
    logger.log('CouchPotato :: Fetching image from %s' % (url), 'DEBUG')
    return send_file(img, mimetype='image/jpeg')


@app.route('/xhr/couchpotato/')
@app.route('/xhr/couchpotato/<status>/')
def xhr_couchpotato(status=False):
    if status:
        status_string = 'status=%s' % status
        template = 'couchpotato-all.html'
    else:
        status = 'wanted'
        status_string = False
        template = 'couchpotato.html'
    try:
        logger.log('CouchPotato :: Fetching "%s movies" list' % status, 'INFO')
        couchpotato = couchpotato_api('movie.list', params=status_string)
        if couchpotato['success'] and not couchpotato['empty']:
            couchpotato = couchpotato['movies']

    except Exception as e:
        log_exception(e)
        couchpotato = None

    logger.log('CouchPotato :: Fetching "%s movies" list (DONE)' % status, 'INFO')

    if status == 'wanted' and not type(couchpotato) is list:
        logger.log('CouchPotato :: Wanted movies list is empty', 'INFO')
        return cp_search('There are no movies is your wanted list.')

    return render_template(template,
        url=couchpotato_url(),
        couchpotato=couchpotato,
        compact_view=get_setting_value('couchpotato_compact') == '1',
    )


@app.route('/xhr/couchpotato/search/')
def cp_search(message=None):
    couchpotato = {}
    params = False
    profiles = {}

    try:
        params = 'q=' + request.args['name']
    except:
        pass

    if params:
        try:
            logger.log('CouchPotato :: Searching for movie: %s' % (params), 'INFO')
            couchpotato = couchpotato_api('movie.search', params=params)
            amount = len(couchpotato['movies'])
            logger.log('CouchPotato :: found %i movies for %s' % (amount, params), 'INFO')
            if couchpotato['success'] and amount != 0:
                couchpotato = couchpotato['movies']
                try:
                    logger.log('CouchPotato :: Getting quality profiles', 'INFO')
                    profiles = couchpotato_api('profile.list')
                except Exception as e:
                    log_exception(e)
            else:
                return render_template('couchpotato-search.html', error='No movies with "%s" were found' % (params[2:]), couchpotato='results')

        except Exception as e:<commit_msg>Fix spaces for CP search (again)<commit_after>from flask import render_template, request, jsonify, json, send_file
from jinja2.filters import FILTERS
from maraschino.tools import get_setting_value, requires_auth
from maraschino import logger, app, WEBROOT
import urllib2
import StringIO
import base64


def couchpotato_http():
    if get_setting_value('couchpotato_https') == '1':
        return 'https://'
    else:
        return 'http://'


def couchpotato_url():
    port = get_setting_value('couchpotato_port')
    url_base = get_setting_value('couchpotato_ip')
    webroot = get_setting_value('couchpotato_webroot')

    if port:
        url_base = '%s:%s' % (url_base, port)

    if webroot:
        url_base = '%s/%s' % (url_base, webroot)

    url = '%s/api/%s' % (url_base, get_setting_value('couchpotato_api'))

    return couchpotato_http() + url


def couchpotato_url_no_api():
    port = get_setting_value('couchpotato_port')
    url_base = get_setting_value('couchpotato_ip')
    webroot = get_setting_value('couchpotato_webroot')

    if port:
        url_base = '%s:%s' % (url_base, port)

    if webroot:
        url_base = '%s/%s' % (url_base, webroot)

    return couchpotato_http() + url_base


def couchpotato_api(method, params=None, use_json=True, dev=False):
    username = get_setting_value('couchpotato_user')
    password = <PASSWORD>_setting_value('<PASSWORD>')

    if params:
        params = '/?%s' % params
    else:
        params = '/'

    params = (params).replace(' ', '%20')
    url = '%s/%s%s' % (couchpotato_url(), method, params)
    request = urllib2.Request(url)

    if username and password:
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

    data = urllib2.urlopen(request).read()
    if dev:
        print url
        print data
    if use_json:
        data = json.JSONDecoder().decode(data)
    return data


def log_exception(e):
    logger.log('CouchPotato :: EXCEPTION -- %s' % e, 'DEBUG')


def couchpotato_image(path):
    if path.startswith('/'):
        path = path[1:]
    return '%s/xhr/couchpotato/image/%s' % (WEBROOT, path)


FILTERS['cp_img'] = couchpotato_image


@app.route('/xhr/couchpotato/image/<path:url>')
def couchpotato_proxy(url):
    username = get_setting_value('couchpotato_user')
    password = get_setting_value('<PASSWORD>')

    url = '%s/file.cache/%s' % (couchpotato_url(), url)
    request = urllib2.Request(url)

    if username and password:
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

    img = StringIO.StringIO(urllib2.urlopen(request).read())
    logger.log('CouchPotato :: Fetching image from %s' % (url), 'DEBUG')
    return send_file(img, mimetype='image/jpeg')


@app.route('/xhr/couchpotato/')
@app.route('/xhr/couchpotato/<status>/')
def xhr_couchpotato(status=False):
    if status:
        status_string = 'status=%s' % status
        template = 'couchpotato-all.html'
    else:
        status = 'wanted'
        status_string = False
        template = 'couchpotato.html'
    try:
        logger.log('CouchPotato :: Fetching "%s movies" list' % status, 'INFO')
        couchpotato = couchpotato_api('movie.list', params=status_string)
        if couchpotato['success'] and not couchpotato['empty']:
            couchpotato = couchpotato['movies']

    except Exception as e:
        log_exception(e)
        couchpotato = None

    logger.log('CouchPotato :: Fetching "%s movies" list (DONE)' % status, 'INFO')

    if status == 'wanted' and not type(couchpotato) is list:
        logger.log('CouchPotato :: Wanted movies list is empty', 'INFO')
        return cp_search('There are no movies is your wanted list.')

    return render_template(template,
        url=couchpotato_url(),
        couchpotato=couchpotato,
        compact_view=get_setting_value('couchpotato_compact') == '1',
    )


@app.route('/xhr/couchpotato/search/')
def cp_search(message=None):
    couchpotato = {}
    params = False
    profiles = {}

    try:
        query = request.args['name']
        params = 'q=' + query
    except:
        pass

    if params:
        try:
            logger.log('CouchPotato :: Searching for movie: %s' % (query), 'INFO')
            couchpotato = couchpotato_api('movie.search', params=params, dev=True)
            amount = len(couchpotato['movies'])
            logger.log('CouchPotato :: found %i movies for %s' % (amount, query), 'INFO')
            if couchpotato['success'] and amount != 0:
                couchpotato = couchpotato['movies']
                try:
                    # logger.log('CouchPotato :: Getting quality profiles', 'INFO')
                    profiles = couchpotato_api('profile.list')
                except Exception as e:
                    log_exception(e)
            else:
                return render_template('couchpotato-search.html', error='No movies with "%s" were found' % (query), couchpotato='results')

        except Exception as e:
{'fraction_non_alphanumeric': 0.1342420082369092, 'fraction_numerical': 0.0050009805844283195, 'mean_word_length': 3.0185185185185186, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '317867', 'n_tokens_mistral': 3416, 'n_tokens_neox': 3318, 'n_words': 704}