def view_index(request): """ Render the landing page for /stats and show a general overview of all the stats. """ if not request.user.is_authenticated(): # Not authenticated, return the bad login page. No stats for you! return responses.clean_response( 'home/badlogin.html', context=context, request=request) # Build the stats page for all known models. modelinf = { file_tracker: { 'orderby': '-download_count', 'displayattr': 'shortname' }, wp_app: { 'orderby': '-view_count', 'displayattr': 'name' }, wp_blog: { 'orderby': '-view_count', 'displayattr': 'slug' }, wp_image: { 'orderby': '-view_count', 'displayattr': ('image_id', 'title', 'image.name'), 'displayformat': '{image_id} - {title} ({image-name})' }, wp_misc: { 'orderby': '-download_count', 'displayattr': 'name' }, wp_paste: { 'orderby': '-view_count', 'displayattr': ('paste_id', 'title'), 'displayformat': '{paste_id} - {title}' }, wp_project: { 'orderby': '-download_count', 'displayattr': 'name' } } context = { 'label': 'all models', 'stats': tools.get_models_info(modelinf), } return responses.clean_response( 'stats/index.html', context=context, request=request)
def view_index(request): """ Render the landing page for /stats and show a general overview of all the stats. """ if not request.user.is_authenticated(): # Not authenticated, return the bad login page. No stats for you! return responses.clean_response('home/badlogin.html', context=context, request=request) # Build the stats page for all known models. modelinf = { file_tracker: { 'orderby': '-download_count', 'displayattr': 'shortname' }, wp_app: { 'orderby': '-view_count', 'displayattr': 'name' }, wp_blog: { 'orderby': '-view_count', 'displayattr': 'slug' }, wp_image: { 'orderby': '-view_count', 'displayattr': ('image_id', 'title', 'image.name'), 'displayformat': '{image_id} - {title} ({image-name})' }, wp_misc: { 'orderby': '-download_count', 'displayattr': 'name' }, wp_paste: { 'orderby': '-view_count', 'displayattr': ('paste_id', 'title'), 'displayformat': '{paste_id} - {title}' }, wp_project: { 'orderby': '-download_count', 'displayattr': 'name' } } context = { 'label': 'all models', 'stats': tools.get_models_info(modelinf), } return responses.clean_response('stats/index.html', context=context, request=request)
def view_scriptkids(request): """ return my script kiddie view (for people trying to access wordpress-login pages and stuff like that.) """ # get ip if possible. ip_address = request.META.get("HTTP_X_FORWARDED_FOR", None) if ip_address is None: ip_address = request.META.get("REMOTE_ADDR", None) use_ip = (ip_address is not None) # get insulting image to display scriptkid_img = htools.get_scriptkid_image() if scriptkid_img is not None: scriptkid_img = utilities.get_relative_path(scriptkid_img) use_img = (scriptkid_img is not None) # return formatted template. return responses.clean_response("home/scriptkids.html", {'request': request, 'extra_style_link_list': [utilities.get_browser_style(request), "/static/css/highlighter.min.css"], 'use_img': use_img, 'scriptkid_img': scriptkid_img, 'use_ip': use_ip, 'ip_address': ip_address, })
def view_badlogin(request): """ show the bad login message """ return responses.clean_response("home/badlogin.html", {'request': request, 'extra_style_link_list': [utilities.get_browser_style(request)], })
def view_index(request): """ Landing page for wp apps listing. """ context = { 'apps': apptools.get_apps(admin_apps=request.user.is_staff), } if request.user.is_staff: context['agenttools'] = { 'IP': { 'url': '/ip.html', 'description': 'Show your user agent IP.', 'simple_url': '/ip', }, 'Text Mode': { 'url': '/textmode.html', 'description': 'Show whether your browser is in text mode.', 'simple_url': '/textmode', }, 'User Agent': { 'url': '/useragent.html', 'description': 'Show your user agent string.', 'simple_url': '/ua' } } return responses.clean_response( 'apps/index.html', context=context, request=request)
def view_index(request): """ Main Project Page (index/listing) [using template instead of hard-coded html] """ # If i can fix the template properly this will be much shorter # and probably faster. The old way was my very first Django view ever. # Hince the complication and mess. # get all projects if project is not disabled all_projects = wp_project.objects.filter(disabled=False).order_by('name') if len(all_projects) == 0: alertmsg = 'Sorry, no projects yet.' response = responses.alert_message(request, alert_msg=alertmsg) else: context = {'request': request, 'extra_style_link_list': [utilities.get_browser_style(request), "/static/css/projects.min.css"], 'projects': all_projects, } response = responses.clean_response("projects/index.html", context) return response
def view_image_id(request, imageid): """ View a single image by id. """ images = wp_image.objects.filter(disabled=False, image_id=imageid) if not images: return responses.error404( request, 'Image not found: {}'.format(imageid) ) image = images[0] image.view_count += 1 image.save() log.debug('Image view_count incremented to {}: {}'.format( image.view_count, image.filename)) # Reusing part of the index view template. # Needs to be more refined, in it's own template. context = { 'image': image, 'images': (image,), 'album': None, } return responses.clean_response( template_name='img/image.html', context=context, request=request)
def view_api(request): """ Landing page for api help. """ return responses.clean_response( 'paste/api.html', context=None, request=request )
def list_view(request, title=None, filterkw=None, orderby=None): """ A view that lists posts based on filter() kwargs, order_by() kwargs. """ filterkw = filterkw or {} title = title or 'Pastes' # Default behaviour is to not show disabled/private pastes. filterkw['disabled'] = filterkw.get('disabled', False) # Private pastes are only viewable directly, not in listings. filterkw['private'] = filterkw.get('private', False) try: p = wp_paste.objects.filter(**filterkw) if orderby is not None: p = p.order_by(orderby) # Expired pastes should not show up in the list for non-admins. if not request.user.is_staff: p = [paste for paste in p if not paste.is_expired()] except Exception as ex: errmsg = 'Unable to retrieve pastes for: {}\n{}' log.error(errmsg.format(title, ex)) p = [] if len(p) > LISTINGMAX: p = p[:LISTINGMAX] context = { 'pastes': p, 'listing_title': title, } return responses.clean_response('paste/listing.html', context=context, request=request)
def index(request): """ Serve up main page (home, index, landing) """ # Grab config on every request, to keep it fresh without restarting. homeconfig = home_config.objects.get() # Get latest tweet (if available.) if homeconfig.show_latest_tweet: latest_tweets = tweets.get_tweets('cjwelborn', count=1) latest_tweet = latest_tweets[0] if latest_tweets else None else: latest_tweet = None featuredblog = hometools.get_featured_blog(homeconfig) # render main page context = { 'featured_blog_post': featuredblog, 'featured_project': hometools.get_featured_project(homeconfig), 'featured_app': hometools.get_featured_app(homeconfig), 'welcome_message': homeconfig.welcome_message, 'latest_tweet': latest_tweet, } return responses.clean_response( 'home/index.html', context=context, request=request)
def view_replies(request): """ View all replies for a paste. """ pasteidarg = responses.get_request_arg(request, 'id') if pasteidarg is None: return responses.error404(request, 'No paste id given.') pasteobj = get_object( wp_paste.objects, paste_id=pasteidarg, disabled=False ) if pasteobj is None: # No paste found. errmsg = 'Paste not found: {}'.format(pasteidarg) return responses.error404(request, errmsg) replies = pastetools.get_paste_children(pasteobj) context = { 'paste': pasteobj, 'replies': replies, } return responses.clean_response( 'paste/replies.html', context=context, request=request)
def view_index(request): """ Main page for pastebin. Add a new paste. Arguments: request : Django's Request object. template_name : Template to render. """ # Update the view count for the paste app. app = get_object(wp_app.objects, alias='paste') if app: app.view_count += 1 app.save() # If the request has args pass it on down to view_paste() if request.GET or request.POST: return view_paste(request) # New Paste. context = { 'paste': None, 'replyto': None, 'replies': None, 'replycount': None, 'replymax': REPLYMAX, } return responses.clean_response( 'paste/index.html', context=context, request=request )
def view_index(request): """ Main page for pastebin. Add a new paste. Arguments: request : Django's Request object. template_name : Template to render. """ # Update the view count for the paste app. app = get_object(wp_app.objects, alias='paste') if app: app.view_count += 1 app.save() # If the request has args pass it on down to view_paste() if request.GET or request.POST: return view_paste(request) # New Paste. context = { 'paste': None, 'replyto': None, 'replies': None, 'replycount': None, 'replymax': REPLYMAX, } return responses.clean_response('paste/index.html', context=context, request=request)
def index_page(request): """ return a slice of all posts using start_id and max_posts to determine the location. """ # get overall total of all blog posts post_count = wp_blog.objects.count() # get request args. page_args = responses.get_paged_args(request, post_count) # retrieve blog posts slice try: post_slice = blogtools.get_post_list(starting_index=page_args['start_id'], max_posts=page_args.get('max_items', blogtools.DEFAULT_MAXPOSTS), _order_by=page_args.get('order_by', None)) except Exception as ex: _log.debug("Error getting blog posts slice:\n" + str(ex)) blog_posts = post_slice = end_id = False else: # fix posts for listing. blog_posts = blogtools.fix_post_list(post_slice) # get last index. end_id = str(page_args['start_id'] + len(post_slice)) return responses.clean_response("blogger/index_paged.html", {'request': request, "blog_posts": blog_posts, "start_id": (page_args['start_id'] + 1), "end_id": end_id, "post_count": post_count, "prev_page": page_args['prev_page'], "next_page": page_args['next_page'], "has_prev": (page_args['start_id'] > 0), "has_next": (page_args['start_id'] < (post_count - page_args['max_items'])), "extra_style_link_list": [utilities.get_browser_style(request)], })
def view_index(request): """ Landing page for the timekeeper app. """ return responses.clean_response( template_name='timekeeper/index.html', context={'jobsessions': tools.get_week_jobs()}, request=request )
def view_test(request): """ returns whatever tests are being conducted in test.html template. """ return responses.clean_response("home/test.html", {'request': request, 'extra_style_link_list': [utilities.get_browser_style(request)], })
def view_ip(request): """ returns the remote ip page. """ return responses.clean_response('home/ip.html', {'request': request, 'extra_style_link_list': [utilities.get_browser_style(request)], })
def view_results(request, query): """ searches welbornprod content and returns the findings. """ # search is okay until it's ran through our little 'gotcha' checker below. results_list, results_slice = ([], []) search_warning = searchtools.valid_query(query) if not search_warning: # search terms are okay, let's do it. results_list = searchtools.search_all(query) results_slice = utilities.slice_list( results_list, start=0, max_items=25) context = { 'search_warning': search_warning, 'results_list': results_slice, 'query_text': query, 'query_safe': mark_for_escaping(query), 'results_count': len(results_list) } return responses.clean_response( 'searcher/results.html', context=context, request=request)
def list_view(request, title=None, filterkw=None, orderby=None): """ A view that lists posts based on filter() kwargs, order_by() kwargs. """ filterkw = filterkw or {} title = title or 'Pastes' # Default behaviour is to not show disabled/private pastes. filterkw['disabled'] = filterkw.get('disabled', False) # Private pastes are only viewable directly, not in listings. filterkw['private'] = filterkw.get('private', False) try: p = wp_paste.objects.filter(**filterkw) if orderby is not None: p = p.order_by(orderby) # Expired pastes should not show up in the list for non-admins. if not request.user.is_staff: p = [paste for paste in p if not paste.is_expired()] except Exception as ex: errmsg = 'Unable to retrieve pastes for: {}\n{}' log.error(errmsg.format(title, ex)) p = [] if len(p) > LISTINGMAX: p = p[:LISTINGMAX] context = { 'pastes': p, 'listing_title': title, } return responses.clean_response( 'paste/listing.html', context=context, request=request)
def view_index(request): """ List all uploaded images, or an album's images (GET /img?album=<name>). Present the upload button to staff. """ alert_msg = None alert_class = None imagefilter = {'disabled': False} album = request.GET.get('album', None) if album: # Filter by album. TODO: This may need it's own view. if album == 'none': # Grab all image without an album set. album = '' if album == 'all': # Grab all images. album = None else: # Filter on user-specified album. imagefilter['album'] = album else: # View a single image by id. TODO: Needs it's own url pattern. imageid = request.GET.get('id', None) if imageid: return view_image_id(request, imageid) if request.user.is_staff: if request.FILES: # Handle file upload. alert_class, alert_msg = handle_files(request) else: if request.FILES: log.error('Non-staff tried to upload files: {}'.format( utilities.get_remote_ip(request))) # No private images for the public. imagefilter['private'] = False images = wp_image.objects.filter(**imagefilter) if album and (not images): alert_msg = 'No album by that name.' alert_class = 'error' album = None if images: images = images.order_by('-publish_date') # Allow user sort by album. if request.GET.get('sort', None) == 'album': images = images.order_by('album') context = { 'images': images, 'album': album, 'alert_message': alert_msg, 'alert_class': alert_class } return responses.clean_response(template_name='img/index.html', context=context, request=request)
def view_index(request): """ Main index for Misc objects. """ context = { 'miscobjects': misctools.get_visible_objects() } return responses.clean_response( 'misc/index.html', context=context, request=request)
def view_notice(request): """ Testing alert classes. """ context = { 'alert_message': 'Your karma has been updated.', 'alert_class': 'notice', } return responses.clean_response('sandbox/index.html', context=context, request=request)
def download(request, file_path): """ provides download of files, tracks download count of projects and possibly others by checking file's project owner, incrementing the count, and then redirecting to the actual file. """ # File path may be an incomplete path to the actual location. # /cedit/source is just as good as /static/files/cedit/source # so we must grab the real (absolute) path, and then convert # it to a valid static path. # location on disk absolute_path = utilities.get_absolute_path(file_path) # location relative to site if settings.SERVER_LOCATION == 'local': static_path = absolute_path.replace(settings.STATIC_PARENT, '') else: # remote, file is actually located at the static_server dir. # but we will need to forward the user to the /static url. static_path = absolute_path.replace(settings.STATIC_ROOT, '') if static_path.startswith('/'): static_path = '/static{}'.format(static_path) else: static_path = '/static/{}'.format(static_path) # used for local only. if (not static_path.startswith('/')): static_path = '/{}'.format(static_path) if not absolute_path: # File doesn't exist. Return an error. log.debug('file doesn\'t exist: {}'.format(file_path)) alert_message = 'Sorry, that file doesn\'t exist.' main_content = '\n'.join(( '<div class=\'wp-block\'>', '<a href=\'/\'><span>Click here to go home.</span></a>', '</div>' )) context = { 'main_content': mark_safe(main_content), 'alert_message': mark_safe(alert_message), } response = responses.clean_response( 'home/main.html', context=context, request=request) else: # redirect to actual file. # log.debug("redirecting to: " + static_path) response = responses.redirect_response(static_path) # File to track? (not a directory) if os.path.isfile(absolute_path): # see if its a trackable model's file, increment it's count. dltools.increment_dl_count(file_path, absolute_path) return response
def view_notice(request): """ Testing alert classes. """ context = { 'alert_message': 'Your karma has been updated.', 'alert_class': 'notice', } return responses.clean_response( 'sandbox/index.html', context=context, request=request)
def view_index(request): apps = apptools.get_apps() context = { 'request': request, 'extra_style_link_list': [ utilities.get_browser_style(request), '/static/css/apps.min.css'], 'apps': apps, } return responses.clean_response('apps/index.html', context)
def view_post(request, identifier): """ view a post by identifier. identifier can be: pk (id) slug title """ post = blogtools.get_post_byany(identifier) if post is None: # No post found with that identifier return responses.error404( request, 'Blog post not found: {}'.format(identifier) ) # build blog post. # get short title for window-text if len(post.title) > 20: post_title_short = '..{}'.format(post.title[len(post.title) - 30:]) else: post_title_short = post.title # no content found. if not blogtools.get_post_body(post): errmsg = 'Sorry, no content found for this post.' errlink = '\n'.join(( '<a href=\'/blog\'><span>', 'Click here to go back to the main blog page.', '</span></a>', )) return responses.alert_message(request, errmsg, body_message=errlink) # increment view count try: post.view_count += 1 post.save() except Exception as exsave: log.error('Unable to increment view_count for: ' '{}\n{}'.format(post, exsave)) # Build clean HttpResponse with post template... context = { 'post_title_short': post_title_short, 'enable_comments': post.enable_comments, 'blog_post': post, 'related_projects': post.get_projects(), } return responses.clean_response( 'blogger/post.html', context=context, request=request, )
def download(request, file_path): """ provides download of files, tracks download count of projects and possibly others by checking file's project owner, incrementing the count, and then redirecting to the actual file. """ # File path may be an incomplete path to the actual location. # /cedit/source is just as good as /static/files/cedit/source # so we must grab the real (absolute) path, and then convert # it to a valid static path. # location on disk absolute_path = utilities.get_absolute_path(file_path) # location relative to site if settings.SERVER_LOCATION == 'local': static_path = absolute_path.replace(settings.STATIC_PARENT, '') else: # remote, file is actually located at the static_server dir. # but we will need to forward the user to the /static url. static_path = absolute_path.replace(settings.STATIC_ROOT, '') if static_path.startswith('/'): static_path = '/static{}'.format(static_path) else: static_path = '/static/{}'.format(static_path) # used for local only. if (not static_path.startswith('/')): static_path = '/{}'.format(static_path) if not absolute_path: # File doesn't exist. Return an error. log.debug('file doesn\'t exist: {}'.format(file_path)) alert_message = 'Sorry, that file doesn\'t exist.' main_content = '\n'.join( ('<div class=\'wp-block\'>', '<a href=\'/\'><span>Click here to go home.</span></a>', '</div>')) context = { 'main_content': mark_safe(main_content), 'alert_message': mark_safe(alert_message), } response = responses.clean_response('home/main.html', context=context, request=request) else: # redirect to actual file. # log.debug("redirecting to: " + static_path) response = responses.redirect_response(static_path) # File to track? (not a directory) if os.path.isfile(absolute_path): # see if its a trackable model's file, increment it's count. dltools.increment_dl_count(file_path, absolute_path) return response
def view_tags(request): """ list all posts by tags (categories) """ # build list of tags and info for tags.html template tag_list = blogtools.get_tags() context = { 'tag_list': tag_list, 'tag_count': len(tag_list), } return responses.clean_response('blogger/tags.html', context=context, request=request)
def view_about(request): """ return the about page for welbornproductions. """ # Pass link list for the about page return responses.clean_response( 'home/about.html', context=None, request=request, link_list=htmltools.auto_link_list, auto_link_args={'target': '_blank'} )
def view_tags(request): """ list all posts by tags (categories) """ # build list of tags and info for tags.html template tag_list = blogtools.get_tags() context = { 'tag_list': tag_list, 'tag_count': len(tag_list), } return responses.clean_response( 'blogger/tags.html', context=context, request=request)
def view_debug(request): """ return the django debug info page. """ siteversion = settings.SITE_VERSION return responses.clean_response("home/debug.html", {'request': request, 'djangoversion': get_django_version(), 'sysversion': sysversion, 'siteversion': siteversion, 'extra_style_link_list': [utilities.get_browser_style(request), "/static/css/highlighter.min.css"], })
def view_post(request, identifier): """ view a post by identifier. identifier can be: pk (id) slug title """ post = blogtools.get_post_byany(identifier) if post is None: # No post found with that identifier return responses.error404(request, 'Blog post not found: {}'.format(identifier)) # build blog post. # get short title for window-text if len(post.title) > 20: post_title_short = '..{}'.format(post.title[len(post.title) - 30:]) else: post_title_short = post.title # no content found. if not blogtools.get_post_body(post): errmsg = 'Sorry, no content found for this post.' errlink = '\n'.join(( '<a href=\'/blog\'><span>', 'Click here to go back to the main blog page.', '</span></a>', )) return responses.alert_message(request, errmsg, body_message=errlink) # increment view count try: post.view_count += 1 post.save() except Exception as exsave: log.error('Unable to increment view_count for: ' '{}\n{}'.format(post, exsave)) # Build clean HttpResponse with post template... context = { 'post_title_short': post_title_short, 'enable_comments': post.enable_comments, 'blog_post': post, 'related_projects': post.get_projects(), } return responses.clean_response( 'blogger/post.html', context=context, request=request, )
def index(request): """ serve up main page (home, index, landing) """ # render main page return responses.clean_response("home/index.html", {'request': request, 'blog_post': htools.get_latest_blog(), 'featured_project': htools.get_featured_project(), # noqa 'extra_style_link_list': [utilities.get_browser_style(request), ], })
def view_debug(request): """ return the django debug info page. """ context = { 'djangoversion': get_django_version(), 'postgresversion': utilities.get_postgres_version(), 'sysversion': getattr(settings, 'SYSVERSION', ''), 'siteversion': getattr(settings, 'SITE_VERSION', ''), 'siteversionnum': getattr(settings, 'WPVERSION', ''), } return responses.clean_response( 'home/debug.html', context=context, request=request)
def view_about(request): """ return the about page for welbornproductions. """ # Pass link list for the about page return responses.clean_response("home/about.html", {'request': request, 'extra_style_link_list': ["/static/css/about.min.css", utilities.get_browser_style(request)], }, link_list=htmltools.auto_link_list, auto_link_args={"target": "_blank"} )
def view_alert(request): """ Testing the alert/notice/attention/approved system messages. """ link = """ <a href='/' title='Go home.'> <span class='alert_message'> That won't work. Click here to go back. </span> </a> """ context = {'alert_title': 'Major Error', 'alert_content': link} return responses.clean_response('sandbox/index.html', context=context, request=request)
def index_page(request): """ return a slice of all posts using start_id and max_posts to determine the location. """ # get overall total of all blog posts post_count = wp_blog.objects.count() # get request args. page_args = responses.get_paged_args(request, post_count) # Setup defaults incase of missing items/errors. startid = page_args.get('start_id', 0) maxposts = page_args.get('max_items', blogtools.DEFAULT_MAXPOSTS) orderby = page_args.get('order_by', None) prevpage = page_args.get('prev_page', None) nextpage = page_args.get('next_page', None) # retrieve blog posts slice try: sliceargs = { 'starting_index': startid, 'max_posts': maxposts, 'order_by': orderby, } post_slice = blogtools.get_post_list(**sliceargs) # fix posts for listing. blog_posts = blogtools.fix_post_list(post_slice) except Exception as ex: log.debug('Error getting blog posts slice:\n{}'.format(ex)) blog_posts = post_slice = [] end_id = 0 # get last index, 'has next page', and 'has prev page' end_id = startid + len(post_slice) hasnxt = startid < (post_count - maxposts) hasprv = startid > 0 # Template values. context = { 'blog_posts': blog_posts, 'start_id': (startid + 1), 'end_id': end_id if end_id >= 0 else 0, 'post_count': post_count, 'prev_page': prevpage, 'next_page': nextpage, 'has_prev': hasprv, 'has_next': hasnxt, } return responses.clean_response( 'blogger/index_paged.html', context=context, request=request, )
def view_stats(request): """ return stats info for projects, blog posts, and file trackers. should require admin permissions. """ def convert_line(line): return mark_safe(line.replace(' ', ' ') + '\n<br/>\n') def convert_pblock(pblock): if pblock is None: return [] if not pblock.keys(): return [] pblock_args = {'append_key': ': '} return [convert_line(line) for line in pblock.iterblock(**pblock_args)] # gather print_block stats from wpstats and convert to lists of strings. # for projects, misc objects, blog posts, and file trackers... projectinfo = htools.StatsInfo('Projects', convert_pblock(wpstats.get_projects_info(orderby='-download_count'))) miscinfo = htools.StatsInfo('Misc', convert_pblock(wpstats.get_misc_info(orderby='-download_count'))) postinfo = htools.StatsInfo('Posts', convert_pblock(wpstats.get_blogs_info(orderby='-view_count'))) fileinfo = htools.StatsInfo('File Trackers', convert_pblock(wpstats.get_files_info(orderby='-download_count'))) # Add them to a collection. stats = htools.StatsCollection(projectinfo, miscinfo, postinfo, fileinfo) if request.user.is_authenticated(): response = responses.clean_response("home/stats.html", {'request': request, 'extra_style_link_list': [utilities.get_browser_style(request), "/static/css/stats.min.css"], 'stats': stats, }) else: response = responses.clean_response("home/badlogin.html", {'request': request, 'extra_style_link_list': [utilities.get_browser_style(request)]}) return response
def view_paged(request): """ views page slice of results using GET args. """ # intialize results in case of failure... results_list, results_slice = ([], []) # get query query = responses.get_request_arg(request, ['q', 'query', 'search'], default="") query_safe = mark_for_escaping(query) # check query search_warning = searchtools.valid_query(query) # search okay? if search_warning == '': # get initial results results_list = searchtools.search_all(query, projects_first=True) # get overall total count results_count = len(results_list) # get args page_args = responses.get_paged_args(request, results_count) # results slice if results_count > 0: results_slice = utilities.slice_list(results_list, starting_index=page_args['start_id'], max_items=page_args['max_items']) else: results_slice = [] # get last index. end_id = str(page_args['start_id'] + len(results_slice)) return responses.clean_response("searcher/results_paged.html", {"request": request, "search_warning": search_warning, "results_list": results_slice, "query_text": query, "query_safe": query_safe, "start_id": (page_args['start_id'] + 1), "end_id": end_id, "results_count": results_count, "prev_page": page_args['prev_page'], "next_page": page_args['next_page'], "has_prev": (page_args['start_id'] > 0), "has_next": (page_args['start_id'] < (results_count - page_args['max_items'])), "extra_style_link_list": [utilities.get_browser_style(request), "/static/css/searcher.min.css", "/static/css/highlighter.min.css"], })
def view_misc_any(request, identifier): """ View a specific misc item. """ misc = misctools.get_by_identifier(identifier) if not misc: # No misc item found by that identifier return responses.error404( request, 'Misc. object not found: {}'.format(identifier)) context = { 'misc': misc, } return responses.clean_response('misc/misc.html', context=context, request=request)
def view_post(request, _identifier): """ view a post by identifier. identifier can be: pk (id) slug title """ post_ = blogtools.get_post_byany(_identifier) if post_ is None: _log.error("Post not found: " + _identifier) response = responses.alert_message(request, "Sorry, I can't find that post.", body_message="<a href='/blog'><span>Click here to go back to the blog index.</span></a>") # noqa else: # build blog post. # get short title for window-text if len(post_.title) > 20: post_title_short = ".." + post_.title[len(post_.title) - 30:] else: post_title_short = post_.title # no content found. if blogtools.get_post_body(post_) == "": response = responses.alert_message(request, "Sorry, no content found for this post.", # noqa body_message="<a href='/blog'><span>Click here to go back to the blog index.</span></a>") # noqa else: # increment view count post_.view_count += 1 post_.save() # enable comments. enable_comments = post_.enable_comments # grab related projects related_projects = post_.get_projects() # Build clean HttpResponse with post template... response = responses.clean_response("blogger/post.html", {'request': request, 'extra_style_link_list': [utilities.get_browser_style(request)], 'post_title_short': post_title_short, 'enable_comments': enable_comments, 'blog_post': post_, 'related_projects': related_projects, }) return response
def view_index(request): """ Main view for phone words. """ reqargs = responses.get_request_args(request) if reqargs: # This request came with args, send it to view_results() return view_results(request, args=reqargs) else: # Basic index view. context = { 'version': app_version, 'hasargs': False, } return responses.clean_response( 'phonewords/index.html', context=context, request=request)
def tag_page(request, tag): """ view all posts with this tag, paged. """ # fix tag name tag_name = utilities.trim_special(tag).replace(',', ' ') # get all found posts. no slice. all_posts = blogtools.get_posts_by_tag(tag_name, starting_index=0) # overall total of all blog posts with this tag. post_count = len(all_posts) # get request args. page_args = responses.get_paged_args(request, post_count) startid = page_args.get('start_id', 0) maxitems = page_args.get('max_items', None) orderby = page_args.get('order_by', None) prevpage = page_args.get('prev_page', None) nextpage = page_args.get('next_page', None) # retrieve blog posts slice post_slice = blogtools.get_posts_by_tag(tag_name, starting_index=startid, max_posts=maxitems, order_by=orderby) # fix posts for listing. blog_posts = blogtools.fix_post_list(post_slice) # number of items in this slice (to get the last index) end_id = startid + len(blog_posts) hasprv = startid > 0 hasnxt = startid < (post_count < maxitems) # build page. context = { 'blog_posts': blog_posts, 'tag_name': tag_name, 'start_id': (startid + 1), 'end_id': end_id, 'post_count': post_count, 'prev_page': prevpage, 'next_page': nextpage, 'has_prev': hasprv, 'has_next': hasnxt, } return responses.clean_response('blogger/tag_paged.html', context=context, request=request)
def view_tag(request, tag): """ list all posts with these tags """ tag_name = utilities.trim_special(tag).replace(',', ' ') found_posts = blogtools.get_posts_by_tag(tag_name, starting_index=0, max_posts=-1) post_count = len(found_posts) # Fix the list (shorten the body, trim to maxposts if needed) found_posts = blogtools.fix_post_list(found_posts) context = { 'tag_name': tag_name, 'post_count': post_count, 'item_count': len(found_posts), 'blog_posts': found_posts } return responses.clean_response('blogger/tag.html', context=context, request=request)
def view_project(request, project, requested_page, source=None): """ Returns project page for individual project. Project object must be passed (usually from request_any() which retrieves projects by name,alias,id) If a list/tuple of projects is passed as 'project' then it will be used as 'possible matches' for bad project name. """ # default flags use_screenshots = False # no project, no matches found (or error retrieving). if not project: return responses.error404( request, 'Project not found: {}'.format(requested_page)) # possible matches passed? matches = project if isinstance(project, set) else None if matches: project = None # Grab project info if project: # this will tell the template to add the screenshots javascript. use_screenshots = project.screenshot_dir != '' # keep track of how many times this has been viewed. project.view_count += 1 project.save() # Grab projects list for vertical menu all_projects = wp_project.objects.filter(disabled=False).order_by('name') context = { 'requested_page': requested_page, 'projects': all_projects, 'project': project, 'matches': matches, 'use_screenshots': use_screenshots, } return responses.clean_response('projects/project.html', context=context, request=request)
def view_error(request, error_number): """ returns appropriate error page when given the error code. """ request_path = request.META['PATH_INFO'] if request_path.startswith('/'): request_path = request_path[1:] # If its not one of these I don't have a template for it, # so it really would be a file-not-found error. if error_number not in (403, 404, 500): error_number = 404 context = { 'request_path': mark_for_escaping(request_path), } return responses.clean_response( 'home/{}.html'.format(error_number), context=context, request=request, status=error_number )
def view_scriptkids(request): """ return my script kiddie view for people trying to access wordpress-login pages and stuff like that. """ # get ip if possible. ip_address = utilities.get_remote_ip(request) try: path = request.path except AttributeError: path = '<error getting path>' log.error('ScriptKid Access from: {} -> {}'.format(ip_address, path)) # get insulting image to display scriptkid_img = hometools.get_scriptkid_image() if scriptkid_img is not None: scriptkid_img = utilities.get_relative_path(scriptkid_img) use_img = (scriptkid_img is not None) use_ip = (ip_address is not None) context = { 'use_img': use_img, 'scriptkid_img': scriptkid_img, 'use_ip': use_ip, 'ip_address': ip_address, } # Try banning the ip. ban_ip = use_ip and (ip_address != '127.0.0.1') if ban_ip: if utilities.ban_add(request): log.error('Banned script kid: {}'.format(ip_address)) else: log.error('Could not ban script kid: {}'.format(ip_address)) else: log.debug('Not banning scriptkid: {}'.format(ip_address)) # return formatted template. return responses.clean_response( 'home/scriptkids.html', context=context, request=request)
def index(request): """ index list of all blog posts """ # load blog posts... try: raw_posts = wp_blog.objects.order_by('-posted_datetime') post_count = len(raw_posts) blog_posts = blogtools.fix_post_list(raw_posts) except Exception as ex: log.error("Error getting blog posts!:\n" + str(ex)) blog_posts = False post_count = 0 context = { 'blog_posts': blog_posts, 'post_count': post_count, } return responses.clean_response( 'blogger/index.html', context=context, request=request, )
def view_loader(request): """ accepts GET/POST request containing a filename 'file'. uses ajax in loader.html to pass that filename to ajax_contents(). everything after that is handled in loader.html's javascript with the help of wpviewer.js. raises 404 on error or file not found.. """ rawpath = request.POST.get('file', request.GET.get('file', '')) if rawpath: file_path = utilities.strip_chars(rawpath, ('"', "'")) context = { 'file': file_path, } return responses.clean_response( 'viewer/loader.html', context=context, request=request) log.error('Empty file name given: {}'.format( utilities.get_remote_ip(request)) ) raise Http404('No file name given.')
def view_replies(request): """ View all replies for a paste. """ pasteidarg = responses.get_request_arg(request, 'id') if pasteidarg is None: return responses.error404(request, 'No paste id given.') pasteobj = get_object(wp_paste.objects, paste_id=pasteidarg, disabled=False) if pasteobj is None: # No paste found. errmsg = 'Paste not found: {}'.format(pasteidarg) return responses.error404(request, errmsg) replies = pastetools.get_paste_children(pasteobj) context = { 'paste': pasteobj, 'replies': replies, } return responses.clean_response('paste/replies.html', context=context, request=request)
def view_image_id(request, imageid): """ View a single image by id. """ images = wp_image.objects.filter(disabled=False, image_id=imageid) if not images: return responses.error404(request, 'Image not found: {}'.format(imageid)) image = images[0] image.view_count += 1 image.save() log.debug('Image view_count incremented to {}: {}'.format( image.view_count, image.filename)) # Reusing part of the index view template. # Needs to be more refined, in it's own template. context = { 'image': image, 'images': (image, ), 'album': None, } return responses.clean_response(template_name='img/image.html', context=context, request=request)
def view_index(request): """ Main Project Page (index/listing) [using template instead of hard-coded html] """ # If i can fix the template properly this will be much shorter # and probably faster. The old way was my very first Django view ever. # Hince the complication and mess. # get all projects if project is not disabled all_projects = wp_project.objects.filter(disabled=False).order_by('name') if not all_projects: alertmsg = 'Sorry, no projects yet.' response = responses.alert_message(request, alert_msg=alertmsg) else: context = { 'projects': all_projects, } response = responses.clean_response('projects/index.html', context=context, request=request) return response
def view_results(request, args=None): """ Process number/word given by request args. """ errors = None results = None total = None rawquery = args['query'] if not rawquery: return responses.error404(request, msgs=('Invalid url args.', )) lookupfunc, query, method = get_lookup_func(rawquery) cache_used = False # Try cached results first (for numbers only) if method == 'number': cachedresult = pwtools.lookup_results(query) if cachedresult: cache_used = True log.debug('Using cached result: {}'.format(cachedresult)) total = cachedresult.attempts results = pwtools.get_results(cachedresult) if results: # Cancel lookup, we have cached results. lookupfunc = None else: log.debug('No cached found for: {}'.format(query)) if lookupfunc: # Get wp words file. wordfile = os.path.join( settings.BASE_DIR, 'apps/phonewords/words' ) if os.path.isfile(wordfile): # Get results. try: rawresults = lookupfunc(query, wordfile=wordfile) except ValueError as exval: errors = exval except Exception as ex: log.error('Error looking up number: {}\n{}'.format(query, ex)) errors = ex else: # Good results, fix them. try: results, total = fix_results(rawresults) except Exception as ex: log.error('Error fixing results:\n{}'.format(ex)) errmsg = ( 'Sorry, there was an error parsing the results.<br>{}' ) errors = Exception(errmsg.format(ex)) # Cache these results for later if its a number. if method == 'number' and (not cache_used): pwtools.save_results(query, results, total) else: log.error('missing word file: {}'.format(wordfile)) errors = Exception('Can\'t find word file!') # Return response. context = { 'version': app_version, 'hasargs': True, 'query': args['query'], 'results': results, 'errors': errors, 'total': total, } return responses.clean_response( 'phonewords/index.html', context=context, request=request)
def view_index(request): """ Landing page for the sandbox. Nothing important. """ return responses.clean_response('sandbox/index.html', context=None, request=request)
def view_paste(request): """ View existing paste. """ pasteidarg = responses.get_request_arg(request, 'id') replytoidarg = responses.get_request_arg(request, 'replyto') if pasteidarg and replytoidarg: # Can't have both id and replyto. return responses.error404(request, 'Invalid url.') # These are all optional, the template decides what to show, # based on what is available. pasteobj = None replytoobj = None replylast = None replies = None replycount = None if pasteidarg is not None: # Check for id aliases. id_alias = {'top': view_top, 'latest': view_latest, 'all': view_latest} id_view = id_alias.get(pasteidarg, None) if id_view is not None: return id_view(request) # Lookup existing paste by id. pasteobj = get_object(wp_paste.objects, paste_id=pasteidarg, disabled=False) if pasteobj is None: # Return a 404, that paste cannot be found. errmsg = 'Paste not found: {}'.format(pasteidarg) return responses.error404(request, errmsg) elif (not request.user.is_staff) and pasteobj.is_expired(): errmsg = 'Paste is expired: {}'.format(pasteidarg) return responses.error404(request, errmsg) else: # Grab parent as the replyto object. replytoobj = pastetools.get_paste_parent(pasteobj) # Update some info about the paste. pasteobj.view_count += 1 # Save changes. pasteobj.save() if replytoidarg is not None: # Lookup parent paste by id. replytoobj = get_object(wp_paste.objects, paste_id=replytoidarg) if replytoobj is None: # Return a 404, user is trying to reply to a dead paste. errmsg = 'Paste not found: {}'.format(replytoidarg) return responses.error404(request, errmsg) elif replytoobj.disabled: errmsg = 'Paste is disabled: {}'.format(replytoidarg) return responses.error_response(request, errmsg) # If this paste has a parent, get it and use it as the replyto. if pasteobj is not None: parent = pastetools.get_paste_parent(pasteobj) if parent is not None: replytoobj = parent replies = pastetools.get_paste_children(pasteobj) if replies: # Grab latest reply to this paste. replylast = replies[0] # Trim replies if they are too long to fit on the page. replycount = len(replies) replies = replies[:REPLYMAX] context = { 'paste': pasteobj, 'replyto': replytoobj, 'replylast': replylast, 'replies': replies, 'replycount': replycount, 'replymax': REPLYMAX, } return responses.clean_response('paste/index.html', context=context, request=request)
def view_index(request): """ Main index for Misc objects. """ context = {'miscobjects': misctools.get_visible_objects()} return responses.clean_response('misc/index.html', context=context, request=request)