summaryrefslogtreecommitdiff
path: root/frontend/views.py
blob: f9dd1bfb7af7f478390081fa6ca46ed830cffa48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import re
import json
import time

from datetime import datetime
from datetime import date
from datetime import timedelta

from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render_to_response

from backend.models import SJLike
from backend.models import SJRoom
from backend.models import SJContent
from backend.models import SJSearch
from backend.models import SJUserProfile

from backend.views import is_number
from backend.views import is_image
from backend.views import videos_response_list
from backend.views import ROOM_VIDEO_LOG_SIZE

from django.db.models import Q, Count

LIMIT = 40

BLOCKED_DOMAINS = {
    'dvdbeaver.com': True,
    '4chan.org': True,
    'yahoo.com': True,
    'adultswim.com': True,
}


def bg(request):
    """ Backgrounds view
    """
    query = Q(content_type='background')
    if request.GET.get('start', None):
        if is_number(request.GET['start']):
            query &= Q(id__lt=int(request.GET['start']))
    limit = LIMIT
    if request.GET.get('limit', None):
        if is_number(request.GET['limit']):
            limit = int(request.GET['limit'])
    backgrounds = SJContent.objects.filter(query).order_by('-id')[0:limit]

    filtered_backgrounds = []
    for b in backgrounds:
        s = b.settings
        url = s['url']
        if not url.startswith('http:'):
            continue
        domain = ''
        try:
            domain = '.'.join(url.split('/')[2].split('.')[-2:])
        except:
            continue
        if domain in BLOCKED_DOMAINS:
            continue
        b.domain = domain
        filtered_backgrounds.append(b)

    return render_to_response(
        'backgrounds.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
             'lowest_id': backgrounds[limit - 1].id,
             'backgrounds': filtered_backgrounds,
             'domain': domain,
        }
    )

def topvideos(request):
    """ Top videos view
    """
    today = datetime.fromtimestamp(time.mktime(date.today().timetuple()))
    tomorrow = today + timedelta(days=1)
    yersterday = today - timedelta(days=1)
    videos = SJContent.objects.filter(content_type='video') 
    top_today = videos.filter(Q(datetime__gt=today) & Q(datetime__lt=tomorrow)).annotate(likes=Count('sjlike')).order_by('-likes')[0:ROOM_VIDEO_LOG_SIZE]
    top_yesterday = videos.filter(Q(datetime__gt=yersterday) & Q(datetime__lt=today)).annotate(likes=Count('sjlike')).order_by('-likes')[0:ROOM_VIDEO_LOG_SIZE]
    top_alltime = SJContent.objects.filter(content_type='video').annotate(likes=Count('sjlike')).order_by('-likes')[0:ROOM_VIDEO_LOG_SIZE]

    response = render_to_response(
        'topvideos.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
             'top_today': json.dumps(videos_response_list(top_today)),
             'top_yesterday': json.dumps(videos_response_list(top_yesterday)),
             'top_alltime': json.dumps(videos_response_list(top_alltime)),
        }
    )
    response['Pragma'] = 'no-cache'
    return response

def directory(request):
    """ Directory view
    """
    r = []
    for u in SJUserProfile.objects.order_by('-score'):
	r.append({ 'id': u.id, 'name': u.nickname, 'score': u.score })

    response = render_to_response(
        'directory.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
             'directory': json.dumps(r),
	}
    )
    response['Pragma'] = 'no-cache'
    return response

def get_thumbnail(user):
	STOCK_THUMBNAIL = 'http://scannerjammer.com/img/runner.gif'
	"""
	FIXME
	if user.access and 'http' in user.access: # what was those fields? 
		linez = user.access.split("\n")
		for l in linez:
			if "avatar" in l:
				pair = l.split("\t")
				if pair[1] is not None and "http" in pair[1]:
					if db.is_image(pair[1]):
						return pair[1]
	if user[8] and 'http' in user[8]:
		linez = user[8].split("\n")
		for l in linez:
			if "http" in l:
				wordz = l.split(" ")
				for word in wordz:
					if "http" in word:
						if db.is_image(word):
							return word
	"""
	return STOCK_THUMBNAIL


def profile(request, username):
    """ Directory view
    """

    userprofile = SJUserProfile.objects.filter(user__username=username)[0];
    thumbnail = get_thumbnail(userprofile)
    
    topz  = SJContent.objects.filter(user__id=userprofile.user.id, content_type='video').annotate(likes=Count('sjlike')).order_by('-likes')[:50]
    likez = SJContent.objects.filter(content_type='video', sjlike__user_id = userprofile.user.id ).order_by('-datetime')[:50]
    vidz  = SJContent.objects.filter(user__id=userprofile.user.id, content_type='video').order_by('-datetime')[:50]
    profile = [ userprofile.id, userprofile.nickname, userprofile.score, 3, 4, 5, userprofile.bio, json.loads(userprofile.settings_text) ]

    response = render_to_response(
        'profile.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
             'NAME': userprofile.nickname,
	     'UCNAME': userprofile.nickname.upper(),
	     'SCORE': userprofile.score,
	     'THUMBNAIL': thumbnail,
	     
	     'VIDZ': json.dumps(videos_response_list(vidz)),
	     'TOPZ': json.dumps(videos_response_list(topz)),
	     'LIKEZ': json.dumps(videos_response_list(likez)),
	     'PROFILE': json.dumps(profile),
	     
	     'NOW': str(int(time.time())),
	}
    )
    response['Pragma'] = 'no-cache'
    return response

def profile_own(request):
    return profile(request, request.user.username)

def roomlist(request):
    recenttime = datetime.fromtimestamp(time.time() - 86400)
    
    roomlist = []
    sjrooms = SJRoom.objects.all()
    for r in sjrooms:
    	s = json.loads(r.settings_text)
	video_count = r.sjcontent_set.filter(datetime__gt=recenttime).count()
	if 'bg' in s:
		roomlist.append([r.id, r.name, int(r.datetime.strftime("%s")), video_count, s["bg"]])	
 
    response = render_to_response(
        'roomlist.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
             'ROOM_LIST': json.dumps(roomlist),
	}
    )
    response['Pragma'] = 'no-cache'
    return response

def room(request, roomname):
    sjroom = SJRoom.objects.filter(name=roomname)[0];
    jsPath = "/js/sj6.js"
    
    title = sjroom.name.capitalize() + " room on ScannerJammer"
    thumbnail = "http://scannerjammer.com/img/plant.gif"
    if sjroom.name == "glitter":
        thumbnail = "http://scannerjammer.com/img/glitter_flower.gif"
    elif sjroom.name == "glasspopcorn":
        thumbnail = "http://scannerjammer.com/img/glasspopthumb.gif"
        title = "GlassPopcorn TV"
    elif room == "adult":
        #serverPort = 6969
        jsPath = "/js/sandbox/sj7.js"
    elif room != "main":
	s = json.loads(sjroom.settings_text)
	if "bg" in s:
		thumbnail = s["bg"]
    
    response = render_to_response(
        'room.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
             'JS_PATH': jsPath,
             'ROOM':    sjroom.name.lower(),
             'UCROOM':	sjroom.name.upper(),
	     'OPENGRAPH_IMAGE': thumbnail,
	     'OPENGRAPH_TITLE': title,
	}
    )
    response['Pragma'] = 'no-cache'
    return response

def faq(request):
    response = render_to_response(
        'faq.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
	}
    )
    response['Pragma'] = 'no-cache'
    return response

def calendar(request):
    response = render_to_response(
        'calendar.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
	}
    )
    response['Pragma'] = 'no-cache'
    return response

def register(request):
    response = render_to_response(
        'register.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
	}
    )
    response['Pragma'] = 'no-cache'
    return response

def admin(request, roomname):
    response = render_to_response(
        'admin.html',
        {
             'SERVER_HOST': request.get_host(),
             'SERVER_PORT': settings.SERVER_PORT,
	}
    )
    response['Pragma'] = 'no-cache'
    return response