obsolete.computer

multistream/frontend/views.py

File Type: text/x-script.python

#views
import copy,re
from datetime import datetime
from itertools import islice

from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound, HttpResponseServerError
from django.template import loader

from twitchAPI.twitch import Twitch

from frontend import models, layouts
from frontend.context_processors import baseurl

if settings.DEBUG:
    import pprint
    pp = pprint.PrettyPrinter(indent=4)


def index(request, streams_url=''):

    has_blanks = False
    old_url_format = False

    if streams_url != '':
        streams = streams_from_url(streams_url)

    else:
        old_url_format = True
        streams = []
        has_blanks = False
        for x in range(layouts.MAX_STREAMS):
            stag = request.GET.get('s%d' % (x,), None)
            if stag is not None:
                stag = stag.strip()
                if stag == '':
                    has_blanks = True
                else:
                    streams.append(stag)

    if len(streams)!=len(set(streams)):
        has_duplicates = True
    else:
        has_duplicates = False

    if (streams and old_url_format) or has_duplicates:
        return HttpResponseRedirect('/edit/%s' % ('/'.join(remove_duplicates(streams)).lower()))

    #since we're using 'pop' in the template
    if streams:
        streams.reverse()

    if settings.RUNNING_ON_DEV:
        domain = request.GET.get('domain', settings.DEFAULT_DOMAIN)
    else:
        domain = request.get_host()

    if domain == settings.DEFAULT_DOMAIN:
        communities = models.Community.objects.filter(active=True,featured=True).order_by('index')
        community = None
    else:
        communities = models.Community.objects.filter(active=True,domain=domain).order_by('index')

        if len(communities) == 1:
            community = communities[0]
        else:
            return not_found(request, "No community found for the domain %s." % domain)

    channels = models.Channel.objects.filter(active=True,communities__in=communities).distinct().order_by('name')

    c = {
        'num_streams': range(layouts.MAX_STREAMS),
        'layout_groups': layouts.LAYOUT_GROUPS,
        'channels': channels,
        'communities': communities,
        'community': community,
        'streams': streams,
    }
    t = loader.get_template('index.html')
    return HttpResponse(t.render(c,request))



def view_streams(request, streams_url=''):

    has_blanks = False
    old_url_format = False

    if streams_url != '':
        streams = streams_from_url(streams_url)
        layout_index = layout_from_url(streams_url)
        if layout_index == -1:
            layout_index = default_layout(len(streams))
            has_blanks = True

    else:
        old_url_format=True
        streams = []
        layout_index = int(request.GET.get('layout', 0))

        for x in range(layouts.MAX_STREAMS):
            stag = request.GET.get('s%d' % (x,), None)
            print(stag)
            if stag is not None:
                stag = stag.strip()
                if stag == '':
                    has_blanks = True
                else:
                    streams.append(stag)

        if layout_index == '':
            layout_index = default_layout(len(streams))

    if len(streams)!=len(set(streams)):
        has_duplicates = True
    else:
        has_duplicates = False

    if not streams:
        return HttpResponseRedirect('/')
    if has_blanks or old_url_format or has_duplicates:
        return HttpResponseRedirect('/%s/layout%s/' % ('/'.join(remove_duplicates(streams)).lower(), layout_index))

    if len(streams) > layouts.MAX_STREAMS:
        num_streams = layouts.MAX_STREAMS
    else:
        num_streams = len(streams)

    layout_group = copy.deepcopy(layouts.LAYOUT_GROUPS[num_streams - 1])
    for layout in layout_group:
        layout.assign_tags(streams)

    if settings.RUNNING_ON_DEV:
        domain = request.GET.get('domain', settings.DEFAULT_DOMAIN)
    else:
        domain = request.get_host()

    communities = models.Community.objects.filter(active=True,domain=domain).order_by('index')

    if len(communities) == 1:
        community = communities[0]
    else:
        community = None

    c = {
        'layout_groups': layouts.LAYOUT_GROUPS,
        'layout_group': layout_group,
        'community': community,
        'edit_url': '/edit/%s/' % ('/'.join(streams).lower()),
    }
    t = loader.get_template('view.html')
    return HttpResponse(t.render(c,request))


def view_community(request, community = ''):
    community = community.rstrip('/').replace('-', ' ').lower()
    communities = models.Community.objects.filter(active=True,name__iexact=community)

    if len(communities) == 1:
        channels = [x.name for x in communities[0].channels.filter(active=True,live=True)][:layouts.MAX_STREAMS]

        if len(channels):
            return HttpResponseRedirect('/%s/layout%s/' % ('/'.join(channels).lower(), default_layout(len(channels))))
        else:
            return HttpResponseRedirect('/#community/' + community.replace(' ', '-') + '/')
    else:
        return not_found(request, '"%s": Community Not Found.' % community)


def live_now(request):
    channel_q = request.GET.get('channel',0)
    if not channel_q:
        kbmod_community = models.Community.objects.filter(name="KBMOD")[0]
        channels = models.Channel.objects.filter(tags=kbmod_tag,active=True,live=True)
        kbmod = models.Channel.objects.filter(name__iexact='kbmod')
        c = RequestContext(request, {
            'channels': channels,
            'kbmod' : kbmod[0],
        })
    else:
        try:
            channel = models.Channel.objects.get(name=channel_q)
        except:
            return not_found("'" + channel_q + "' channel not found")

        c = RequestContext(request, {
            'channel': channel,
        })

    t = loader.get_template('live_now.html')
    r = HttpResponse(t.render(c,request))
    r['Access-Control-Allow-Origin'] = '*'
    return r


def get_object(request,obj_type=None,obj_tag=None,obj_index=-1):

    if (obj_type == 'stream' or obj_type == 'chat' or obj_type == 'both') and obj_index >= 0 and obj_tag != '':
        t = loader.get_template('object.html')

        c = {
            'obj': {
                'objtype' : obj_type,
                'index' : obj_index,
                'tag' : obj_tag,
            },
        }
        return HttpResponse(t.render(c,request))

    else:
        return HttpResponse("Error: Object type, index, or tag missing or invalid.")



#error handlers
def not_found(request, message="That isn't a valid URL. Make sure you're not using any special characters in the channel names.", exception=None):
    c = {
        'message': message,
    }
    t = loader.get_template('error.html')
    return HttpResponseNotFound(t.render(c,request))

def server_error(request, message="An error occured."):
    c = {
        'message': message,
    }
    t = loader.get_template('error.html')
    return HttpResponseServerError(t.render(c,request))


#utility junk

def streams_from_url(streams_url):
    return [x for x in streams_url.split("/")[:layouts.MAX_STREAMS] if x != '' and x[:6] != 'layout']

def layout_from_url(streams_url):
    layout_pattern = re.compile(r"layout=?([0-9][0-9]?)", re.IGNORECASE)
    layout_matches = layout_pattern.search(streams_url)
    if layout_matches:
        layout_num = layout_matches.group(1)
    else:
        layout_num = -1

    return int(layout_num)

def default_layout(stream_count=1):
    return layouts.LAYOUT_GROUPS[stream_count - 1][0].index

def remove_duplicates(seq):
    seen = set()
    seen_add = seen.add
    return [ x for x in seq if not (x in seen or seen_add(x))]

Meta