def test_get_unit_chat_link(self): """ Test that pages in the site get the correct ask a librarian link to their corresoinding AskPage and chat widget. Eckhart and SCRC are treated differently since they're circumstances are slightly different. """ ask_widgets = set(['law', 'crerar', 'ssa', 'uofc-ask', 'dissertation-office']) # Dictionary of tuples where the keys map to the ask_widget_name field # of AskPages. The firs item of the tuple is a mixed dictionary of # location/hours/unit information and the second item of the tuple is # a random url belonging to a page of a given section of the site. data = { 'law': (get_hours_and_location(StandardPage.objects.get(id=DANGELO_HOMEPAGE)), '/law/services/carrelslockers/'), 'crerar': (get_hours_and_location(StandardPage.objects.get(id=CRERAR_HOMEPAGE)), '/crerar/science-research-services/data-support-services/'), 'ssa': (get_hours_and_location(StandardPage.objects.get(id=SSA_HOMEPAGE)), '/ssa/about/'), 'uofc-ask': (get_hours_and_location(StandardPage.objects.get(id=PUBLIC_HOMEPAGE)), '/research/help/offcampus/'), 'dissertation-office': (get_hours_and_location(StandardPage.objects.get(id=DISSERTATION_HOMEPAGE)), '/research/scholar/phd/students/'), 'eck': (get_hours_and_location(StandardPage.objects.get(id=ECKHART_HOMEPAGE)), '/eck/mathematics-research-services/'), 'scrc': (get_hours_and_location(StandardPage.objects.get(id=SCRC_HOMEPAGE)), '/scrc/visiting/'), } # Normal chat links to regular AskPages for item in ask_widgets: request = HttpRequest() request.path = data[item][1] current_site = Site.find_for_request(request) a = get_unit_chat_link(data[item][0]['page_unit'], request) b = AskPage.objects.filter(ask_widget_name=item).first().relative_url(current_site) self.assertEqual(a, b) # Eckhart request_eck = HttpRequest() request_eck.path = data['eck'][1] current_site = Site.find_for_request(request_eck) eckurl = get_unit_chat_link(data['eck'][0]['page_unit'], request_eck) eckask = AskPage.objects.get(id=4646).relative_url(current_site) self.assertEqual(eckurl, eckask) # SCRC request_scrc = HttpRequest() request_scrc.path = data['scrc'][1] current_site = Site.find_for_request(request_scrc) scrcurl = get_unit_chat_link(data['scrc'][0]['page_unit'], request_scrc) scrcask = PublicRawHTMLPage.objects.get(id=4127).relative_url(current_site) self.assertEqual(scrcurl, scrcask)
def results(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: homepage = Site.objects.get(site_name="Public").root_page unit_index_page = UnitIndexPage.objects.first() search_results = Page.objects.live().descendant_of(homepage).not_descendant_of(unit_index_page, True).search(search_query) query = Query.get(search_query) # Record hit query.add_hit() # Get search picks search_picks = query.editors_picks.all() else: search_results = Page.objects.none() search_picks = SearchPromotion.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) # Page context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] return render(request, 'results/results.html', { 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'search_query': search_query, 'search_results': search_results, 'search_picks': search_picks, 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'self': { 'title': 'Search Results' } })
def results(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: homepage = Site.objects.get(site_name="Public").root_page search_results = Page.objects.live().descendant_of(homepage).search(search_query) query = Query.get(search_query) # Record hit query.add_hit() # Get search picks search_picks = query.editors_picks.all() else: search_results = Page.objects.none() search_picks = SearchPromotion.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) # Page context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] return render(request, 'results/results.html', { 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'search_query': search_query, 'search_results': search_results, 'search_picks': search_picks, 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'self': { 'title': 'Search Results' } })
def collections(request): # PARAMETERS default_cache = caches['default'] digital = request.GET.get('digital', None) if not digital == 'on': digital = None format = request.GET.get('format', None) if not Format.objects.filter(text=format).exists(): format = None location = request.GET.get('location', None) if not LocationPage.objects.live().filter(title=location).exists(): location = None search = request.GET.get('search', None) subject = request.GET.get('subject', None) if not Subject.objects.all().filter(name=subject).exists(): subject = None # broken... what does this even do??? unit = request.GET.get('unit', None) view = request.GET.get('view', 'collections') if view not in ['collections', 'exhibits', 'subjects', 'subjecttree']: view = 'collections' # filter collections. collections = [] if view == 'collections': filter_arguments = {} # format if format: filter_arguments['collection_placements__format__text'] = format # digital if digital: filter_arguments['collection_placements__format__text'] = 'Digital' # subject if subject: filter_arguments[ 'collection_subject_placements__subject__in'] = Subject.objects.get( name=subject).get_descendants() # search if search: filter_arguments['id__in'] = list( map(lambda s: s.id, CollectionPage.objects.live().search(search))) # unit if unit: filter_arguments['unit'] = UnitPage.objects.get(title=unit) collections = CollectionPage.objects.live().filter( **filter_arguments).distinct().select_related( 'thumbnail').prefetch_related('collection_subject_placements') # sort browses by title, omitting leading articles. if not search: collections = sorted( collections, key=lambda c: re.sub(r'^(A|An|The) ', '', c.title)) # fiter exhibits. exhibits = [] exhibits_current = [] if view == 'exhibits': filter_arguments = {} if location: filter_arguments['exhibit_location__title'] = location if subject: filter_arguments[ 'exhibit_subject_placements__subject__in'] = Subject.objects.get( name=subject).get_descendants() if unit: filter_arguments['unit'] = UnitPage.objects.get(title=unit) if digital: filter_arguments['web_exhibit'] = True exhibits = ExhibitPage.objects.live().filter( **filter_arguments).distinct().select_related( 'thumbnail', 'exhibit_location').prefetch_related( 'exhibit_subject_placements') exhibits_current = exhibits.filter( exhibit_open_date__lt=datetime.datetime.now().date(), exhibit_close_date__gt=datetime.datetime.now().date()).distinct() if search: exhibits = exhibits.search(search).results() exhibits_current = exhibits_current.search(search).results() if not search: exhibits = sorted( exhibits, key=lambda e: re.sub(r'^(A|An|The) ', '', e.title)) exhibits_current = sorted( exhibits_current, key=lambda e: re.sub('r^(A|An|The) ', '', e.title)) # locations locations = sorted( list( set( ExhibitPage.objects.exclude(exhibit_location=None).values_list( 'exhibit_location__title', flat=True)))) # formats. formats = Format.objects.all().values_list('text', flat=True) # the formats pulldown should skip 'Digital'. That shows up as a checkbox. formats_pulldown = [ 'Archives & Manuscripts', 'Audio', 'Books & Journals', 'Images', 'Maps', 'Microform', 'Music Scores', 'Photographs', 'Reference Works', 'Statistics & Datasets', 'Video' ] subjects = [] if view == 'subjects': # for the code below, list all subjects that are children of the # subjects in the list above, plus anything with a libguide # id. right now that is equal to business, medicine and law. See # DB's "collections subjects" lucid chart for more info. subjects_queryset = Subject.objects.all().prefetch_related('see_also') if search: s = get_search_backend() subjects_queryset = s.search(search, Subject) if subject: subject_ids = Subject.objects.get(name=subject).get_descendants() subjects_queryset = subjects_queryset.filter(id__in=subject_ids) subjects_with_collections = set( CollectionPageSubjectPlacement.objects.values_list('subject', flat=True)) subjects_with_exhibits = set( ExhibitPageSubjectPlacement.objects.all().values_list('subject', flat=True)) subjects_with_specialists = set( StaffPageSubjectPlacement.objects.values_list('subject', flat=True)) qs = SubjectParentRelations.objects.all().prefetch_related('panels') for s in subjects_queryset: if ('subject_id_%s' % s.id) in default_cache: subjects_list_entry = default_cache.get('subject_id_%s' % s.id) else: subject_descendants = default_cache.get('descendants_%s' % s.id) if not subject_descendants: subject_descendants = set(s.get_descendants().values_list( 'id', flat=True)) default_cache.set('descendants_%s' % s.id, subject_descendants, 60 * 5) parents = qs.filter( child=s).order_by('parent__name').values_list( 'parent__name', flat=True).prefetch_related('subject') has_collections = bool( subjects_with_collections.intersection( subject_descendants)) has_exhibits = bool( subjects_with_exhibits.intersection(subject_descendants)) collecting_area_url = s.get_collecting_area_page_url(request) has_collecting_area = bool(collecting_area_url) has_subject_specialists = s.id in subjects_with_specialists subjects_list_entry = { 'has_collections': has_collections, 'has_exhibits': has_exhibits, 'has_collecting_area': has_collecting_area, 'collecting_area_url': collecting_area_url, 'has_subject_specialists': has_subject_specialists, 'libguide_url': s.libguide_url, 'name': s.name, 'parents': parents, 'see_also': None } default_cache.set('subject_id_%s' % s.id, subjects_list_entry) subjects.append(subjects_list_entry) see_also_qs = s.see_also.all() if see_also_qs: for see_also in see_also_qs: subjects.append({ 'has_collections': False, 'has_exhibits': False, 'has_subject_specialists': False, 'libguide_url': None, 'name': see_also.alias, 'parents': [], 'see_also': see_also.snippet.name }) subjects = sorted(subjects, key=lambda s: s['name']) subjecttree = '' if view == 'subjecttree': subjecttree = call_command('report_subjects') subjecttree = subjecttree.replace('<html>', '') subjecttree = subjecttree.replace('</html>', '') subjecttree = subjecttree.replace('<body>', '') subjecttree = subjecttree.replace('</body>', '') # for the subject pulldown, find subjects that are first generation # children- their parents should have no parent. still need these: # Area Studies Social Sciences Biological Sciences Physical Sciences subjects_pulldown = [ 'Area Studies', 'Arts', 'Biological Sciences', 'Business', 'Humanities', 'Law', 'Literature', 'Medicine', 'Physical Sciences', 'Social Sciences', 'Social Services', 'Special Collections' ] default_image = None try: default_image = Image.objects.get(title="Default Placeholder Photo") except Image.DoesNotExist: pass # Set context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) page_location = str(location_and_hours['page_location']) page_unit = location_and_hours['page_unit'] current_site = Site.find_for_request(request) alert_data = get_browse_alerts(current_site) return render( request, 'lib_collections/collections_index_page.html', { 'collections': collections, 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'default_image': default_image, 'digital': digital, 'exhibits': exhibits, 'exhibits_current': exhibits_current, 'format': format, 'formats': formats, 'formats_pulldown': formats_pulldown, 'location': location, 'locations': locations, 'search': search, 'self': { 'title': 'Collections & Exhibits' }, 'subject': subject, 'subjects': subjects, 'subjects_pulldown': subjects_pulldown, 'subjecttree': subjecttree, 'view': view, 'page_unit': str(page_unit), 'page_location': page_location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(page_unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'has_alert': alert_data[0], 'alert_message': alert_data[1][0], 'alert_level': alert_data[1][1], 'alert_more_info': alert_data[1][2], 'alert_link': alert_data[1][3], })
def collections(request): # PARAMETERS digital = request.GET.get('digital', None) if not digital == 'on': digital = None format = request.GET.get('format', None) if not format in Format.objects.all().values_list('text', flat=True): format = None location = request.GET.get('location', None) if not location in LocationPage.objects.live().values_list('title', flat=True): location = None search = request.GET.get('search', None) subject = request.GET.get('subject', None) if not subject in Subject.objects.all().values_list('name', flat=True): subject = None unit = request.GET.get('unit', None) view = request.GET.get('view', 'collections') if not view in ['collections', 'exhibits', 'subjects']: view = 'collections' # filter collections. collections = [] if view == 'collections': filter_arguments = {} # format if format: filter_arguments['collection_placements__format__text'] = format # subject if subject: filter_arguments[ 'collection_subject_placements__subject__in'] = Subject.objects.get( name=subject).get_descendants() # search if search: filter_arguments['id__in'] = list( map(lambda s: s.id, CollectionPage.objects.live().search(search))) # unit if unit: filter_arguments['unit'] = UnitPage.objects.get(title=unit) collections = CollectionPage.objects.live().filter( **filter_arguments).distinct() # digital if digital: collections = collections.filter( collection_placements__format__text='Digital') # sort browses by title, omitting leading articles. if not search: collections = sorted( collections, key=lambda c: re.sub(r'^(A|An|The) ', '', c.title)) # fiter exhibits. exhibits = [] exhibits_current = [] if view == 'exhibits': filter_arguments = {} if location: filter_arguments['exhibit_location__title'] = location if subject: filter_arguments[ 'exhibit_subject_placements__subject__in'] = Subject.objects.get( name=subject).get_descendants() if unit: filter_arguments['unit'] = UnitPage.objects.get(title=unit) exhibits = ExhibitPage.objects.live().filter( **filter_arguments).distinct() exhibits_current = exhibits.filter( exhibit_open_date__lt=datetime.datetime.now().date(), exhibit_close_date__gt=datetime.datetime.now().date()).distinct() if digital: exhibits = exhibits.filter(web_exhibit=True) exhibits_current = exhibits_current.filter(web_exhibit=True) if search: exhibits = exhibits.search(search).results() exhibits_current = exhibits_current.search(search).results() if not search: exhibits = sorted( exhibits, key=lambda e: re.sub(r'^(A|An|The) ', '', e.title)) exhibits_current = sorted( exhibits_current, key=lambda e: re.sub('r^(A|An|The) ', '', e.title)) # formats. formats = Format.objects.all().values_list('text', flat=True) # the formats pulldown should skip 'Digital'. That shows up as a checkbox. formats_pulldown = ['Archives & Manuscripts', 'Audio', 'Books & Journals', \ 'Images', 'Maps', 'Microform', 'Music Scores', 'Photographs', 'Reference Works', \ 'Statistics & Datasets', 'Video'] # locations locations = sorted( list( set( ExhibitPage.objects.exclude(exhibit_location=None).values_list( 'exhibit_location__title', flat=True)))) subjects = [] # for the code below, list all subjects that are children of the subjects in the list # above, plus anything with a libguide id. right now that is equal to # business, medicine and law. See DB's "collections subjects" lucid chart for more # info. subjects_queryset = Subject.objects.all() if search: s = get_search_backend() subjects_queryset = s.search(search, Subject) if subject: subject_ids = Subject.objects.get(name=subject).get_descendants() subjects_queryset = subjects_queryset.filter(id__in=subject_ids) subjects_with_collections = set( CollectionPageSubjectPlacement.objects.values_list('subject', flat=True)) subjects_with_exhibits = set( ExhibitPageSubjectPlacement.objects.values_list('subject', flat=True)) subjects_with_specialists = set( StaffPageSubjectPlacement.objects.values_list('subject', flat=True)) for s in subjects_queryset: subject_descendants = set(s.get_descendants().values_list('id', flat=True)) parents = SubjectParentRelations.objects.filter( child=s).order_by('parent__name').values_list('parent__name', flat=True) has_collections = bool( subjects_with_collections.intersection(subject_descendants)) has_exhibits = bool( subjects_with_exhibits.intersection(subject_descendants)) has_subject_specialists = s.id in subjects_with_specialists subjects.append({ 'has_collections': has_collections, 'has_exhibits': has_exhibits, 'has_subject_specialists': has_subject_specialists, 'libguide_url': s.libguide_url, 'name': s.name, 'parents': parents, 'see_also': None }) for see_also in s.see_also.all(): subjects.append({ 'has_collections': False, 'has_exhibits': False, 'has_subject_specialists': False, 'libguide_url': None, 'name': see_also.alias, 'parents': [], 'see_also': see_also.snippet.name }) subjects = sorted(subjects, key=lambda s: s['name']) # for the subject pulldown, find subjects that are first generation children- their parents should have no parent. # still need these: # Area and Cultural Studies # Social Sciences # Biological Sciences # Physical Sciences subjects_pulldown = ['Area & Cultural Studies', 'Arts', \ 'Biological Sciences', 'Business', 'Humanities', 'Law', 'Literature', \ 'Medicine', 'Physical Sciences', 'Social Sciences', 'Social Services', \ 'Special Collections'] default_image = None try: default_image = Image.objects.get(title="Default Placeholder Photo") except: pass # Set context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) page_location = str(location_and_hours['page_location']) page_unit = location_and_hours['page_unit'] return render( request, 'lib_collections/collections_index_page.html', { 'collections': collections, 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'default_image': default_image, 'digital': digital, 'exhibits': exhibits, 'exhibits_current': exhibits_current, 'format': format, 'formats': formats, 'formats_pulldown': formats_pulldown, 'location': location, 'locations': locations, 'search': search, 'self': { 'title': 'Collections & Exhibits' }, 'subject': subject, 'subjects': subjects, 'subjects_pulldown': subjects_pulldown, 'view': view, 'page_unit': str(page_unit), 'page_location': page_location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(page_unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), })
def units(request): def get_unit_info_from_unit_page(unit_page): h = '' # phone number if unit_page.phone_number: if unit_page.phone_label: h = h + '<em>' + unit_page.phone_label + ':' + '</em> ' h = h + "<a href='tel:" + unit_page.phone_number.replace('-', '') + "'>" + unit_page.phone_number + "</a>" h = h + '<br/>' # fax_number if unit_page.fax_number: h = h + 'Fax: ' + unit_page.fax_number + '<br/>' # email_label, email if unit_page.email: if unit_page.email_label: h = h + "<a href='mailto:" + unit_page.email + "'>" + unit_page.email_label + "</a><br/>" else: h = h + "<a href='mailto:" + unit_page.email + "'>" + unit_page.email + "</a><br/>" # link_text, link_external if unit_page.link_external: if unit_page.link_text: h = h + "<a href='" + unit_page.link_external + "'>" + unit_page.link_text + "</a><br/>" else: h = h + "<a href='" + unit_page.link_external + "'>" + unit_page.link_external + "</a><br/>" return h def get_unit_info(t): h = '' # intercept this in the future to link to unit pages. staff_link = '' if t.unit_page.directory_unit: staff_link = " <a href='/about/directory/?" + urllib.parse.urlencode({'view': 'staff', 'department': t.unit_page.directory_unit.fullName}) + "'>staff</a>" room_number = '' if t.unit_page.room_number: room_number = " (" + t.unit_page.room_number + ") " if t.name: directory_name = t.name if t.unit_page.public_web_page: directory_name = '<a href="' + t.unit_page.public_web_page.url + '">' + directory_name + '</a>' h = h + "<strong>" + directory_name + room_number + staff_link + "</strong><br/>" if t.unit_page: h = h + get_unit_info_from_unit_page(t.unit_page) if h: h = '<p>' + h + '</p>' return h # hierarchical html. e.g., # <ul> # <li>Administration</li> # <li>Collection Services # <ul> # <li>Administration</li> # ... def get_html(tree): if not tree: return '' else: return "<ul>" + "".join(list(map(lambda t: "<li>" + get_unit_info(t) + get_html(t) + "</li>", tree.children))) + "</ul>" # # MAIN # hierarchical_html = '' department = request.GET.get('department', None) library = request.GET.get('library', None) page = request.GET.get('page', 1) query = request.GET.get('query', None) sort = request.GET.get('sort', 'hierarchical') subject = request.GET.get('subject', None) view = request.GET.get('view', 'department') if view == 'department' and query: sort = 'alphabetical' department_label = '' if department: department_label = department.split(' - ').pop() # staff pages staff_pages_all = [] staff_pages = [] if view == 'staff': # returns all staff pages if library is None. # otherwise, returns staff pages for the given library. staff_pages_all = get_staff_pages_for_library(library) # departments. if department: staff_pages_all = sorted(list(set(staff_pages_all.filter(vcards__in=get_vcards_for_department(department)))), key=lambda s: s.last_name if s.last_name else '') # search staff pages. if query: staff_pages_all = staff_pages_all.search(query) # subjects. if subject: if subject == 'All Subject Specialists': staff_pages_all = staff_pages_all.filter(id__in=StaffPageSubjectPlacement.objects.all().values_list('page', flat=True).distinct()) else: # get a subject and all it's descendants. subject_and_descendants = Subject.objects.get(name=subject).get_descendants() # from staff page subject placements, get all of the staff that match those subjects. subject_staff_ids = StaffPageSubjectPlacement.objects.filter(subject__in=subject_and_descendants).values_list('page', flat=True) # filter staff_pages_all to only include those staff pages. staff_pages_all = staff_pages_all.filter(id__in=subject_staff_ids).order_by('last_name') # add paging. paginator = Paginator(staff_pages_all, 100) try: staff_pages = paginator.page(page) except PageNotAnInteger: staff_pages = paginator.page(1) except EmptyPage: staff_pages = paginator.page(paginator.num_pages) elif view == 'department': hierarchical_html = '' if query: units = UnitPage.objects.filter(display_in_directory=True).search(query) h = [] for u in units: h.append(get_unit_info(Tree(u.title, u))) hierarchical_html = ''.join(h) else: hierarchical_html = get_html(UnitPage.hierarchical_units()) # replace first ul. if len(hierarchical_html) > 4: hierarchical_html = "<ul class='directory'>" + hierarchical_html[4:] default_image = Image.objects.get(title="Default Placeholder Photo") # Page context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] return render(request, 'units/unit_index_page.html', { 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'department': department, 'department_label': department_label, 'departments': get_departments(library), 'default_image': default_image, 'hierarchical_units': hierarchical_html, 'libraries': [str(p) for p in LocationPage.objects.live().filter(is_building=True)], 'library': library, 'query': query, 'sort': sort, 'staff_pages': staff_pages, 'subjects': get_subjects(None), 'subject': subject, 'view': view, 'self': { 'title': 'Library Directory' }, 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'quick_nums': get_quick_nums_for_library_or_dept(request), })
def external_include(request): """ CSS, headers and footers for external sites like guides.lib or sfx.lib. Make hrefs absolute. """ callback = request.GET.get('callback', None) include = request.GET.get('include', None) # Variables to use in context home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) llid = home_page.get_granular_libcal_lid(home_page.unit) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] if include in ('css', 'js', 'header', 'footer'): response = render( request, 'base/includes/{}.html'.format(include), { 'prefix': '{}://{}'.format(request.scheme, request.get_host), 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'libcalid': llid, 'page_unit': str(location_and_hours['page_unit']), 'page_location': location, 'site_url': request.scheme + '://' + request.get_host(), }, ) def absolute_url(href): """ Helper function to make links absolute. """ protocol = '{}://'.format(request.scheme) if href.startswith('http://') or href.startswith('https://'): protocol = '' domain = request.get_host() if not href.startswith('/'): domain = '' return '{}{}{}'.format(protocol, domain, href) soup = BeautifulSoup(response.content, 'html.parser') for a in soup.find_all('a'): a['href'] = absolute_url(a['href']) for img in soup.find_all('img'): img['src'] = absolute_url(img['src']) for link in soup.find_all('link'): link['href'] = absolute_url(link['href']) for sc in soup.find_all('script'): sc['src'] = absolute_url(sc['src']) response.content = str(soup) if callback: return HttpResponse( '{}({});'.format(callback, json.dumps(response.content.decode('utf-8'))), 'application/javascript') else: return response else: raise ValueError
def units(request): divisions = [] department = request.GET.get('department', None) library = request.GET.get('library', None) page = request.GET.get('page', 1) query = request.GET.get('query', None) subject = request.GET.get('subject', None) view = request.GET.get('view', 'staff') if library == 'The University of Chicago Library': library = None if query: view = None staff_pages = [] departments = [] if query: staff_pages = StaffPage.objects.live().search(query) departments = UnitPage.objects.filter( display_in_library_directory=True, live=True).search(query) elif view == 'staff': if library == None: staff_pages = StaffPage.objects.live() else: staff_pages = StaffPage.get_staff_by_building(library) # departments. if department: staff_pages = get_staff_pages_for_unit(department, True, True) # subjects. if subject: if subject == 'All Subject Specialists': staff_pages = staff_pages.filter( id__in=StaffPageSubjectPlacement.objects.all().values_list( 'page', flat=True).distinct()) else: # get a subject and all it's descendants. subject_and_descendants = Subject.objects.get( name=subject).get_descendants() # from staff page subject placements, get all of the staff that match those subjects. subject_staff_ids = StaffPageSubjectPlacement.objects.filter( subject__in=subject_and_descendants).values_list('page', flat=True) # filter staff_pages to only include those staff pages. staff_pages = staff_pages.filter( id__in=subject_staff_ids).order_by('last_name') elif view == 'department': divisions = [] for division in UnitIndexPage.objects.first().get_children().specific( ).type(UnitPage).filter( live=True, unitpage__display_in_library_directory=True).order_by('title'): divisions.append({ 'unit': division, 'descendants': division.get_descendants().specific().type(UnitPage).filter( live=True, unitpage__display_in_library_directory=True).order_by( 'title') }) default_image = Image.objects.get(title="Default Placeholder Photo") try: org_chart_image = Image.objects.get(title="Org Chart") except: org_chart_image = None # Page context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] current_site = Site.find_for_request(request) alert_data = get_browse_alerts(current_site) title = '' if query: title = 'Search Results' elif view == 'staff': title = 'Library Directory: Staff' elif view == 'department': title = 'Library Directory: Departments' elif view == 'org': title = 'Library Directory: Org Chart' quick_nums = get_quick_nums_for_library_or_dept(request).replace( '<td>', '<li>').replace('</td>', '</li>') subjects = Subject.objects.filter(display_in_dropdown=True).values_list( 'name', flat=True), return render( request, 'units/unit_index_page.html', { 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container directory col-xs-12 col-lg-11 col-lg-offset-1', 'department': department, 'departments': departments, 'default_image': default_image, 'divisions': divisions, 'libraries': get_libraries(), 'library': library, 'org_chart_image': org_chart_image, 'query': query, 'staff_pages': staff_pages, 'subjects': subjects[0], 'subject': subject, 'view': view, 'self': { 'title': title }, 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'quick_nums': quick_nums, 'has_alert': alert_data[0], 'alert_message': alert_data[1][0], 'alert_level': alert_data[1][1], 'alert_more_info': alert_data[1][2], 'alert_link': alert_data[1][3], })
def results(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: homepage = Site.objects.get(site_name="Public").root_page unit_index_page = UnitIndexPage.objects.first() restricted = StandardPage.objects.live().get(id=RESTRICTED) search_results1 = Page.objects.live().descendant_of( homepage).not_descendant_of( unit_index_page, True).not_descendant_of(restricted, True).search( search_query, operator="and").annotate_score('score') search_backend = get_search_backend() search_results2 = search_backend.search( search_query, LibGuidesSearchableContent.objects.all(), operator="and").annotate_score('score') r = 0 while r < len(search_results2): search_results2[r].score = search_results2[r].score * 1.5 r += 1 r = 0 while r < len(search_results2): search_results2[r].searchable_content = 'guides' r += 1 search_results3 = search_backend.search( search_query, LibGuidesAssetsSearchableContent.objects.all(), operator="and").annotate_score('score') r = 0 while r < len(search_results3): search_results3[r].searchable_content = 'assets' r += 1 search_results = list( chain(search_results1, search_results2, search_results3)) try: search_results.sort(key=lambda r: r.score, reverse=True) except (TypeError): pass query = Query.get(search_query) # Record hit query.add_hit() # Get search picks search_picks = query.editors_picks.all() else: search_results = Page.objects.none() search_picks = SearchPromotion.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) # Page context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] return render( request, 'results/results.html', { 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'search_query': search_query, 'search_results': search_results, 'search_picks': search_picks, 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'self': { 'title': 'Search Results' } })
def get_context(self, request): context = super(PublicBasePage, self).get_context(request) self.location_and_hours = get_hours_and_location(self) unit = self.location_and_hours['page_unit'] current_site = Site.find_for_request(request) url_filter = '~()*!.\'' try: location = str(self.location_and_hours['page_location']) context['page_unit'] = str(unit) context['page_location'] = location context['page_location_id'] = self.location_and_hours['page_location'].id #context['current_building_hours'] = self.location_and_hours['hours'] context['address'] = self.location_and_hours['address'] #context['all_building_hours'] = get_all_building_hours() context['chat_url'] = get_unit_chat_link(unit, request) context['directory_link'] = self.get_directory_link_by_location(location, True) except(AttributeError): logger = logging.getLogger(__name__) logger.error('Context variables not set in PublicBasePage.') context['libcalid'] = self.location_and_hours['libcalid'] context['granular_libcalid'] = self.get_granular_libcal_lid(self.unit) context['libcaliid'] = LIBCAL_IID context['has_granular_hours'] = self.has_granular_hours() context['all_spaces_link'], \ context['quiet_spaces_link'], \ context['collaborative_spaces_link'] = self.get_spaces_links(self.location_and_hours) sidebar = self.has_left_sidebar(context) section_info = self.get_banner(current_site) branch_name = section_info[4] has_alert = False if not get_alert(current_site) else True context['has_left_sidebar'] = sidebar context['content_div_css'] = self.get_conditional_css_classes('content', sidebar) context['breadcrumb_div_css'] = self.get_conditional_css_classes('breadcrumbs', sidebar) context['sidebartitle'] = self.get_sidebar_title()[0] context['sidebartitleurl'] = self.get_sidebar_title()[1] context['branch_lib_css'] = self.get_branch_lib_css_class() context['hours_page_url'] = self.get_hours_page(request) context['is_hours_page'] = self.id == HOURS_PAGE context['has_banner'] = section_info[0] context['banner'] = section_info[1] context['banner_feature'] = section_info[2] context['banner_title'] = section_info[3] context['banner_subtitle'] = section_info[4] context['banner_url'] = section_info[5] context['branch_title'] = branch_name if branch_name is not self.title else '' context['page_type'] = str(self.specific.__class__.__name__) context['events_feed'] = urllib.parse.quote(self.events_feed_url, safe=url_filter) context['news_feed'] = urllib.parse.quote(self.news_feed_url, safe=url_filter) context['unfriendly_a'] = True if self.friendly_name.strip() in UNFRIENDLY_ARTICLES else False context['has_alert'] = has_alert if has_alert: context['alert_message'], \ context['alert_level'], \ context['alert_more_info'], \ context['alert_link'] = get_alert(current_site) try: context['news_page'] = self.external_news_page if self.external_news_page else self.internal_news_page.relative_url(current_site) except(AttributeError): context['news_page'] = '' try: carousel = self.carousel_items.all() except(AttributeError): carousel = [] context['carousel_items'] = carousel context['carousel_multi'] = len(carousel) > 1 # Data structure for generating a # sitemap display of child pages index_pages = [{ 'title': self.title, 'url': self.relative_url(current_site), 'children': [], }] # Build sitemap listing of child pages # in html format. if self.enable_index and self.display_hierarchical_listing: index_pages[0]['children'] = list(map(lambda p: recursively_add_children(p, current_site), self.get_children().live())) elif self.enable_index: index_pages[0]['children'] = list(map(lambda p: {'title': p.title, 'url': p.relative_url(current_site), 'children': []}, self.get_children().live())) index_pages_html = get_index_html(index_pages[0]['children']) context['index_pages_html'] = index_pages_html return context
def spaces(request): building = request.GET.get('building', None) feature = request.GET.get('feature', None) floor = request.GET.get('floor', None) space_type = request.GET.get('space_type', 'is_study_space') possible_features = get_features() # validate form input. if not building in LocationPage.objects.filter(is_building=True).values_list('title', flat=True): building = None if not has_feature(feature): feature = None if not space_type in ['is_study_space', 'is_teaching_space', 'is_event_space']: space_type = None # get the feature label. feature_label = '' if feature: for f in possible_features: if f[0] == feature: feature_label = f[1] # get spaces. spaces = LocationPage.objects.live() if building: spaces = spaces.filter(parent_building = LocationPage.objects.get(title=building)) if feature: spaces = spaces.filter(**{feature: True}) if floor: location_ids = LocationPageFloorPlacement.objects.filter(floor__title=floor).values_list('parent', flat=True) spaces = spaces.filter(id__in=location_ids) if space_type: spaces = spaces.filter(**{space_type: True}) # Narrow down list of buildings from all buildings by using feature # and space_type, create list of libraries for display in dropdown # from parent_building of filtered all_spaces. Use set to remove # duplicates and sort_buildings to organize resulting list of libraries all_spaces = LocationPage.objects.live() if feature: all_spaces = all_spaces.filter(**{feature: True}) if space_type: all_spaces = all_spaces.filter(**{space_type: True}) buildings = sort_buildings(all_spaces) # make sure all features have at least one LocationPage for the current space_type. features = list(filter(lambda f: spaces.filter(**{f[0]: True}), possible_features)) # if a library building has been set, get floors that are appropriate for # the parameters that have been set. floors = [] if building: # Changed spaces to all_spaces in id_list to bypass filtering in spaces. # get all locations that are descendants of this building. id_list = all_spaces.filter(parent_building__title=building).values_list('pk', flat=True) # get a unique, sorted list of the available floors here. floors = sorted(list(set(LocationPageFloorPlacement.objects.filter(parent__in=id_list).exclude(floor=None).values_list('floor__title', flat=True)))) default_image = Image.objects.get(title="Default Placeholder Photo") #If building is selected pass respective page id to page context variables, #else pass PUBLIC_HOMEPAGE, llid passed to render correct hours in js script, unfriendly_a = False PAGE_ID = PUBLIC_HOMEPAGE if building: if building == 'Social Service Administration Library': PAGE_ID = SSA_HOMEPAGE elif building == 'The Joe and Rika Mansueto Library': PAGE_ID = MANSUETO_HOMEPAGE elif building == 'The John Crerar Library': PAGE_ID = CRERAR_HOMEPAGE elif building == 'Eckhart Library': PAGE_ID = ECKHART_HOMEPAGE elif building == 'The D\'Angelo Law Library': PAGE_ID = DANGELO_HOMEPAGE elif building == 'Special Collections Research Center': PAGE_ID = SCRC_HOMEPAGE # Page context variables for templates home_page = StandardPage.objects.live().get(id=PAGE_ID) friendly_name = home_page.friendly_name llid = home_page.get_granular_libcal_lid(home_page.unit) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] # Find banner for given home_page and add to context current_site = Site.find_for_request(request) section_info = home_page.get_banner(current_site) branch_name = section_info[4] return render(request, 'public/spaces_index_page.html', { 'building': building, 'buildings': buildings, 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'default_image': default_image, 'feature': feature, 'feature_label': feature_label, 'features': features, 'floor': floor, 'floors': floors, 'self': { 'title': 'Library Spaces', 'friendly_name': friendly_name }, 'spaces': spaces, 'space_type': space_type, 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'unfriendly_a': True if friendly_name.strip() in UNFRIENDLY_ARTICLES else False, 'libcalid': llid, 'has_banner': section_info[0], 'banner': section_info[1], 'banner_feature': section_info[2], 'banner_title': section_info[3], 'banner_subtitle': section_info[4], 'banner_url': section_info[5], 'branch_lib_css': home_page.get_branch_lib_css_class(), })
def test_get_unit_chat_link(self): """ Test that pages in the site get the correct ask a librarian link to their corresoinding AskPage and chat widget. Eckhart and SCRC are treated differently since they're circumstances are slightly different. """ ask_widgets = set( ['law', 'crerar', 'ssa', 'uofc-ask', 'dissertation-office']) # Dictionary of tuples where the keys map to the ask_widget_name field # of AskPages. The firs item of the tuple is a mixed dictionary of # location/hours/unit information and the second item of the tuple is # a random url belonging to a page of a given section of the site. data = { 'law': (get_hours_and_location( StandardPage.objects.get(id=DANGELO_HOMEPAGE)), '/law/services/carrelslockers/'), 'crerar': (get_hours_and_location( StandardPage.objects.get(id=CRERAR_HOMEPAGE)), '/crerar/science-research-services/data-support-services/'), 'ssa': (get_hours_and_location(StandardPage.objects.get(id=SSA_HOMEPAGE)), '/ssa/about/'), 'uofc-ask': (get_hours_and_location( StandardPage.objects.get(id=PUBLIC_HOMEPAGE)), '/research/help/offcampus/'), 'dissertation-office': (get_hours_and_location( StandardPage.objects.get(id=DISSERTATION_HOMEPAGE)), '/research/scholar/phd/students/'), 'eck': (get_hours_and_location( StandardPage.objects.get(id=ECKHART_HOMEPAGE)), '/eck/mathematics-research-services/'), 'scrc': (get_hours_and_location( StandardPage.objects.get(id=SCRC_HOMEPAGE)), '/scrc/visiting/'), } # Normal chat links to regular AskPages for item in ask_widgets: request = HttpRequest() request.path = data[item][1] add_generic_request_meta_fields(request) current_site = Site.find_for_request(request) a = get_unit_chat_link(data[item][0]['page_unit'], request) b = AskPage.objects.filter( ask_widget_name=item).first().relative_url(current_site) self.assertEqual(a, b) # Eckhart request_eck = HttpRequest() add_generic_request_meta_fields(request_eck) request_eck.path = data['eck'][1] current_site = Site.find_for_request(request_eck) eckurl = get_unit_chat_link(data['eck'][0]['page_unit'], request_eck) eckask = AskPage.objects.get(id=4646).relative_url(current_site) self.assertEqual(eckurl, eckask) # SCRC request_scrc = HttpRequest() add_generic_request_meta_fields(request_scrc) request_scrc.path = data['scrc'][1] current_site = Site.find_for_request(request_scrc) scrcurl = get_unit_chat_link(data['scrc'][0]['page_unit'], request_scrc) scrcask = PublicRawHTMLPage.objects.get( id=4127).relative_url(current_site) self.assertEqual(scrcurl, scrcask)
def events(request): start_str = request.GET.get('start', None) if start_str: start = datetime.datetime.strptime(start_str, '%Y-%m-%d').date() else: start = datetime.date.today() start_str = start.strftime('%Y-%m-%d') # if the date was in the past, set it to today. if start < datetime.datetime.now().date(): start = datetime.datetime.now().date() start_str = start.strftime('%Y-%m-%d') # get start and stop dates, along with previous start and next start dates. number_of_days_this_month = calendar.monthrange(start.year, start.month)[1] stop = start + datetime.timedelta(days=number_of_days_this_month - 1) stop_str = stop.strftime('%Y-%m-%d') if start.month == 1: number_of_days_last_month = calendar.monthrange(start.year - 1, 12)[1] else: number_of_days_last_month = calendar.monthrange(start.year, start.month - 1)[1] previous_start = start - datetime.timedelta(days=number_of_days_last_month) next_start = stop + datetime.timedelta(days=1) university_url = 'http://events.uchicago.edu/widgets/rss.php?key=47866f880d62a4f4517a44381f4a990d&id=48' ttrss_url = 'http://www3.lib.uchicago.edu/tt-rss/public.php?op=rss&id=-3&key=8idjnk57e2a0063541d' entries = get_events(university_url, ttrss_url, start, stop) # remove multiday events. d = len(entries) - 1 while d >= 0: date_label = entries[d][0] e = len(entries[d][1]) - 1 while e >= 0: if entries[d][1][e]['start_date'] != entries[d][1][e]['end_date']: del(entries[d][1][e]) if not entries[d][1]: del(entries[d]) e = e - 1 d = d - 1 # separate multiday events out into their own section. # multiday_events aren't arranged into something with start dates. tmp = get_events(university_url, ttrss_url, None, None) multiday_entries = [] for event_list in [e[1] for e in tmp]: for e in event_list: if e['start_date'] != e['end_date']: if e['sortable_date'] <= stop_str and e['sortable_end_date'] >= start_str: multiday_entries.append(e) # Page context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] next_link = next_start.strftime('%Y-%m-%d') previous_link = previous_start.strftime('%Y-%m-%d') # don't allow browsing into the past. if start == datetime.datetime.now().date(): previous_link = '' return render(request, 'events/events_index_page.html', { 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'entries': entries, 'multiday_entries': multiday_entries, 'next_link': next_link, 'previous_link': previous_link, 'start': start.strftime('%Y-%m-%d'), 'start_label': start.strftime('%B %d, %Y').replace(' 0', ' '), 'stop': stop.strftime('%Y-%m-%d'), 'stop_label': stop.strftime('%B %d, %Y').replace(' 0', ' '), 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'self': { 'title': 'Library Events' }, })
def spaces(request): building = request.GET.get('building', None) feature = request.GET.get('feature', None) floor = request.GET.get('floor', None) space_type = request.GET.get('space_type', 'is_study_space') possible_features = get_features() # validate form input. if not building in LocationPage.objects.filter( is_building=True).values_list('title', flat=True): building = None if not has_feature(feature): feature = None if not space_type in [ 'is_study_space', 'is_teaching_space', 'is_event_space' ]: space_type = None # get the feature label. feature_label = '' if feature: for f in possible_features: if f[0] == feature: feature_label = f[1] # get spaces. spaces = LocationPage.objects.live() if building: spaces = spaces.filter(parent_building=LocationPage.objects.get( title=building)) if feature: spaces = spaces.filter(**{feature: True}) if floor: location_ids = LocationPageFloorPlacement.objects.filter( floor__title=floor).values_list('parent', flat=True) spaces = spaces.filter(id__in=location_ids) if space_type: spaces = spaces.filter(**{space_type: True}) # Narrow down list of buildings from all buildings by using feature # and space_type, create list of libraries for display in dropdown # from parent_building of filtered all_spaces. Use set to remove # duplicates and sort_buildings to organize resulting list of libraries all_spaces = LocationPage.objects.live() if feature: all_spaces = all_spaces.filter(**{feature: True}) if space_type: all_spaces = all_spaces.filter(**{space_type: True}) buildings = sort_buildings(all_spaces) # make sure all features have at least one LocationPage for the current space_type. features = list( filter(lambda f: spaces.filter(**{f[0]: True}), possible_features)) # if a library building has been set, get floors that are appropriate for # the parameters that have been set. floors = [] if building: # Changed spaces to all_spaces in id_list to bypass filtering in spaces. # get all locations that are descendants of this building. id_list = all_spaces.filter( parent_building__title=building).values_list('pk', flat=True) # get a unique, sorted list of the available floors here. floors = sorted( list( set( LocationPageFloorPlacement.objects.filter( parent__in=id_list).exclude(floor=None).values_list( 'floor__title', flat=True)))) default_image = Image.objects.get(title="Default Placeholder Photo") #If building is selected pass respective page id to page context variables, #else pass PUBLIC_HOMEPAGE, llid passed to render correct hours in js script, unfriendly_a = False PAGE_ID = PUBLIC_HOMEPAGE if building: if building == 'Social Service Administration Library': PAGE_ID = SSA_HOMEPAGE elif building == 'The Joe and Rika Mansueto Library': PAGE_ID = MANSUETO_HOMEPAGE elif building == 'The John Crerar Library': PAGE_ID = CRERAR_HOMEPAGE elif building == 'Eckhart Library': PAGE_ID = ECKHART_HOMEPAGE elif building == 'The D\'Angelo Law Library': PAGE_ID = DANGELO_HOMEPAGE elif building == 'Special Collections Research Center': PAGE_ID = SCRC_HOMEPAGE # Page context variables for templates home_page = StandardPage.objects.live().get(id=PAGE_ID) friendly_name = home_page.friendly_name llid = home_page.get_granular_libcal_lid(home_page.unit) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] # Find banner for given home_page and add to context current_site = Site.find_for_request(request) section_info = home_page.get_banner(current_site) branch_name = section_info[4] return render( request, 'public/spaces_index_page.html', { 'building': building, 'buildings': buildings, 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'default_image': default_image, 'feature': feature, 'feature_label': feature_label, 'features': features, 'floor': floor, 'floors': floors, 'self': { 'title': 'Library Spaces', 'friendly_name': friendly_name }, 'spaces': spaces, 'space_type': space_type, 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'unfriendly_a': True if friendly_name.strip() in UNFRIENDLY_ARTICLES else False, 'libcalid': llid, 'has_banner': section_info[0], 'banner': section_info[1], 'banner_feature': section_info[2], 'banner_title': section_info[3], 'banner_subtitle': section_info[4], 'banner_url': section_info[5], 'branch_lib_css': home_page.get_branch_lib_css_class(), })
def events(request): start_str = request.GET.get('start', None) if start_str: start = datetime.datetime.strptime(start_str, '%Y-%m-%d').date() else: start = datetime.date.today() start_str = start.strftime('%Y-%m-%d') # if the date was in the past, set it to today. if start < datetime.datetime.now().date(): start = datetime.datetime.now().date() start_str = start.strftime('%Y-%m-%d') # get start and stop dates, along with previous start and next start dates. number_of_days_this_month = calendar.monthrange(start.year, start.month)[1] stop = start + datetime.timedelta(days=number_of_days_this_month - 1) stop_str = stop.strftime('%Y-%m-%d') if start.month == 1: number_of_days_last_month = calendar.monthrange(start.year - 1, 12)[1] else: number_of_days_last_month = calendar.monthrange( start.year, start.month - 1)[1] previous_start = start - datetime.timedelta(days=number_of_days_last_month) next_start = stop + datetime.timedelta(days=1) university_url = 'http://events.uchicago.edu/widgets/rss.php?key=47866f880d62a4f4517a44381f4a990d&id=48' ttrss_url = 'http://www3.lib.uchicago.edu/tt-rss/public.php?op=rss&id=-3&key=8idjnk57e2a0063541d' entries = get_events(university_url, ttrss_url, start, stop) # remove multiday events. d = len(entries) - 1 while d >= 0: date_label = entries[d][0] e = len(entries[d][1]) - 1 while e >= 0: if entries[d][1][e]['start_date'] != entries[d][1][e]['end_date']: del (entries[d][1][e]) if not entries[d][1]: del (entries[d]) e = e - 1 d = d - 1 # separate multiday events out into their own section. # multiday_events aren't arranged into something with start dates. tmp = get_events(university_url, ttrss_url, None, None) multiday_entries = [] for event_list in [e[1] for e in tmp]: for e in event_list: if e['start_date'] != e['end_date']: if e['sortable_date'] <= stop_str and e[ 'sortable_end_date'] >= start_str: multiday_entries.append(e) # Page context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] next_link = next_start.strftime('%Y-%m-%d') previous_link = previous_start.strftime('%Y-%m-%d') # don't allow browsing into the past. if start == datetime.datetime.now().date(): previous_link = '' return render( request, 'events/events_index_page.html', { 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'entries': entries, 'multiday_entries': multiday_entries, 'next_link': next_link, 'previous_link': previous_link, 'start': start.strftime('%Y-%m-%d'), 'start_label': start.strftime('%B %d, %Y').replace(' 0', ' '), 'stop': stop.strftime('%Y-%m-%d'), 'stop_label': stop.strftime('%B %d, %Y').replace(' 0', ' '), 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'self': { 'title': 'Library Events' }, })
def collections(request): # PARAMETERS digital = request.GET.get('digital', None) if not digital == 'on': digital = None format = request.GET.get('format', None) if not format in Format.objects.all().values_list('text', flat=True): format = None location = request.GET.get('location', None) if not location in LocationPage.objects.live().values_list('title', flat=True): location = None search = request.GET.get('search', None) subject = request.GET.get('subject', None) if not subject in Subject.objects.all().values_list('name', flat=True): subject = None unit = request.GET.get('unit', None) view = request.GET.get('view', 'collections') if not view in ['collections', 'exhibits', 'subjects']: view = 'collections' # filter collections. collections = [] if view == 'collections': filter_arguments = {} # format if format: filter_arguments['collection_placements__format__text'] = format # subject if subject: filter_arguments['collection_subject_placements__subject__in'] = Subject.objects.get(name=subject).get_descendants() # search if search: filter_arguments['id__in'] = list(map(lambda s: s.id, CollectionPage.objects.live().search(search))) # unit if unit: filter_arguments['unit'] = UnitPage.objects.get(title=unit) collections = CollectionPage.objects.live().filter(**filter_arguments).distinct() # digital if digital: collections = collections.filter(collection_placements__format__text='Digital') # sort browses by title, omitting leading articles. if not search: collections = sorted(collections, key=lambda c: re.sub(r'^(A|An|The) ', '', c.title)) # fiter exhibits. exhibits = [] exhibits_current = [] if view == 'exhibits': filter_arguments = {} if location: filter_arguments['exhibit_location__title'] = location if subject: filter_arguments['exhibit_subject_placements__subject__in'] = Subject.objects.get(name=subject).get_descendants() if unit: filter_arguments['unit'] = UnitPage.objects.get(title=unit) exhibits = ExhibitPage.objects.live().filter(**filter_arguments).distinct() exhibits_current = exhibits.filter(exhibit_open_date__lt=datetime.datetime.now().date(), exhibit_close_date__gt=datetime.datetime.now().date()).distinct() if digital: exhibits = exhibits.exclude(web_exhibit_url = '') exhibits_current = exhibits_current.exclude(web_exhibit_url = '') if search: exhibits = exhibits.search(search).results() exhibits_current = exhibits_current.search(search).results() if not search: exhibits = sorted(exhibits, key=lambda e: re.sub(r'^(A|An|The) ', '', e.title)) exhibits_current = sorted(exhibits_current, key=lambda e: re.sub('r^(A|An|The) ', '', e.title)) # formats. formats = Format.objects.all().values_list('text', flat=True) # the formats pulldown should skip 'Digital'. That shows up as a checkbox. formats_pulldown = ['Archives & Manuscripts', 'Audio', 'Books & Journals', \ 'Images', 'Maps', 'Microform', 'Music Scores', 'Photographs', 'Reference Works', \ 'Statistics & Datasets', 'Video'] # locations locations = sorted(list(set(ExhibitPage.objects.exclude(exhibit_location=None).values_list('exhibit_location__title', flat=True)))) subjects = [] # for the code below, list all subjects that are children of the subjects in the list # above, plus anything with a libguide id. right now that is equal to # business, medicine and law. See DB's "collections subjects" lucid chart for more # info. subjects_queryset = Subject.objects.all() if search: s = get_search_backend() subjects_queryset = s.search(search, Subject) if subject: subject_ids = Subject.objects.get(name=subject).get_descendants() subjects_queryset = subjects_queryset.filter(id__in=subject_ids) subjects_with_collections = set(CollectionPageSubjectPlacement.objects.values_list('subject', flat=True)) subjects_with_exhibits = set(ExhibitPageSubjectPlacement.objects.values_list('subject', flat=True)) subjects_with_specialists = set(StaffPageSubjectPlacement.objects.values_list('subject', flat=True)) for s in subjects_queryset: subject_descendants = set(s.get_descendants().values_list('id', flat=True)) parents = SubjectParentRelations.objects.filter(child=s).order_by('parent__name').values_list('parent__name', flat=True) has_collections = bool(subjects_with_collections.intersection(subject_descendants)) has_exhibits = bool(subjects_with_exhibits.intersection(subject_descendants)) has_subject_specialists = s.id in subjects_with_specialists subjects.append({ 'has_collections': has_collections, 'has_exhibits': has_exhibits, 'has_subject_specialists': has_subject_specialists, 'libguide_url': s.libguide_url, 'name': s.name, 'parents': parents, 'see_also': None }) for see_also in s.see_also.all(): subjects.append({ 'has_collections': False, 'has_exhibits': False, 'has_subject_specialists': False, 'libguide_url': None, 'name': see_also.alias, 'parents': [], 'see_also': see_also.snippet.name }) subjects = sorted(subjects, key=lambda s: s['name']) # for the subject pulldown, find subjects that are first generation children- their parents should have no parent. # still need these: # Area and Cultural Studies # Social Sciences # Biological Sciences # Physical Sciences subjects_pulldown = ['Area & Cultural Studies', 'Arts', \ 'Biological Sciences', 'Business', 'Humanities', 'Law', 'Literature', \ 'Medicine', 'Physical Sciences', 'Social Sciences', 'Social Services', \ 'Special Collections'] default_image = None try: default_image = Image.objects.get(title="Default Placeholder Photo") except: pass # Set context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) page_location = str(location_and_hours['page_location']) page_unit = location_and_hours['page_unit'] return render(request, 'lib_collections/collections_index_page.html', { 'collections': collections, 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'default_image': default_image, 'digital': digital, 'exhibits': exhibits, 'exhibits_current': exhibits_current, 'format': format, 'formats': formats, 'formats_pulldown': formats_pulldown, 'location': location, 'locations': locations, 'search': search, 'self': { 'title': 'Collections & Exhibits' }, 'subject': subject, 'subjects': subjects, 'subjects_pulldown': subjects_pulldown, 'view': view, 'page_unit': str(page_unit), 'page_location': page_location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(page_unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), })
def events(request): start_str = request.GET.get('start', None) if start_str: start = datetime.datetime.strptime(start_str, '%Y-%m-%d').date() else: start = datetime.date.today() start_str = start.strftime('%Y-%m-%d') # if the date was in the past, set it to today. if start < datetime.datetime.now().date(): start = datetime.datetime.now().date() start_str = start.strftime('%Y-%m-%d') # get start and stop dates, along with previous start and next start dates. number_of_days_this_month = calendar.monthrange(start.year, start.month)[1] stop = start + datetime.timedelta(days=number_of_days_this_month - 1) stop_str = stop.strftime('%Y-%m-%d') if start.month == 1: number_of_days_last_month = calendar.monthrange(start.year - 1, 12)[1] else: number_of_days_last_month = calendar.monthrange( start.year, start.month - 1)[1] previous_start = start - datetime.timedelta(days=number_of_days_last_month) next_start = stop + datetime.timedelta(days=1) entries = get_events(UC_EVENTS_FEED, TTRSS_FEED, start, stop) # remove multiday events. d = len(entries) - 1 while d >= 0: e = len(entries[d][1]) - 1 while e >= 0: end_date = entries[d][1][e]['end_date'] if entries[d][1][e]['start_date'] != end_date and end_date != '': del (entries[d][1][e]) if not entries[d][1]: del (entries[d]) e = e - 1 d = d - 1 # separate multiday events out into their own section. # multiday_events aren't arranged into something with start dates. tmp = get_events(UC_EVENTS_FEED, TTRSS_FEED, None, None) multiday_entries = [] for event_list in [ev[1] for ev in tmp]: for e in event_list: if e['start_date'] != e['end_date']: if e['sortable_date'] <= stop_str and e[ 'sortable_end_date'] >= start_str: multiday_entries.append(e) # Page context variables for templates home_page = StandardPage.objects.live().get(id=PUBLIC_HOMEPAGE) location_and_hours = get_hours_and_location(home_page) location = str(location_and_hours['page_location']) unit = location_and_hours['page_unit'] current_site = Site.find_for_request(request) alert_data = get_browse_alerts(current_site) next_link = next_start.strftime('%Y-%m-%d') previous_link = previous_start.strftime('%Y-%m-%d') # don't allow browsing into the past. if start == datetime.datetime.now().date(): previous_link = '' return render( request, 'events/events_index_page.html', { 'breadcrumb_div_css': 'col-md-12 breadcrumbs hidden-xs hidden-sm', 'content_div_css': 'container body-container col-xs-12 col-lg-11 col-lg-offset-1', 'entries': entries, 'multiday_entries': multiday_entries, 'next_link': next_link, 'previous_link': previous_link, 'start': start.strftime('%Y-%m-%d'), 'start_label': start.strftime('%B %d, %Y').replace(' 0', ' '), 'stop': stop.strftime('%Y-%m-%d'), 'stop_label': stop.strftime('%B %d, %Y').replace(' 0', ' '), 'page_unit': str(unit), 'page_location': location, 'address': location_and_hours['address'], 'chat_url': get_unit_chat_link(unit, request), 'chat_status': get_chat_status('uofc-ask'), 'chat_status_css': get_chat_status_css('uofc-ask'), 'hours_page_url': home_page.get_hours_page(request), 'self': { 'title': 'Library Events' }, 'has_alert': alert_data[0], 'alert_message': alert_data[1][0], 'alert_level': alert_data[1][1], 'alert_more_info': alert_data[1][2], 'alert_link': alert_data[1][3], })