diff --git a/swh/web/browse/utils.py b/swh/web/browse/utils.py index 21e93bf4b..3a114fbb8 100644 --- a/swh/web/browse/utils.py +++ b/swh/web/browse/utils.py @@ -1,733 +1,739 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import base64 import dateutil import magic import math import stat import textwrap from django.core.cache import cache from django.utils.safestring import mark_safe from swh.web.common import highlightjs, service from swh.web.common.exc import NotFoundExc from swh.web.common.utils import ( reverse, format_utc_iso_date, parse_timestamp ) def get_directory_entries(sha1_git): """Function that retrieves the content of a SWH directory from the SWH archive. The directories entries are first sorted in lexicographical order. Sub-directories and regular files are then extracted. Args: sha1_git: sha1_git identifier of the directory Returns: A tuple whose first member corresponds to the sub-directories list and second member the regular files list Raises: NotFoundExc if the directory is not found """ cache_entry_id = 'directory_entries_%s' % sha1_git cache_entry = cache.get(cache_entry_id) if cache_entry: return cache_entry entries = list(service.lookup_directory(sha1_git)) entries = sorted(entries, key=lambda e: e['name']) for entry in entries: entry['perms'] = stat.filemode(entry['perms']) dirs = [e for e in entries if e['type'] == 'dir'] files = [e for e in entries if e['type'] == 'file'] cache.set(cache_entry_id, (dirs, files)) return dirs, files def get_mimetype_and_encoding_for_content(content): """Function that returns the mime type and the encoding associated to a content buffer using the magic module under the hood. Args: content (bytes): a content buffer Returns: A tuple (mimetype, encoding), for instance ('text/plain', 'us-ascii'), associated to the provided content. """ magic_result = magic.detect_from_content(content) return magic_result.mime_type, magic_result.encoding def request_content(query_string): """Function that retrieves a SWH content from the SWH archive. Raw bytes content is first retrieved, then the content mime type. If the mime type is not stored in the archive, it will be computed using Python magic module. Args: query_string: a string of the form "[ALGO_HASH:]HASH" where optional ALGO_HASH can be either *sha1*, *sha1_git*, *sha256*, or *blake2s256* (default to *sha1*) and HASH the hexadecimal representation of the hash value Returns: A tuple whose first member corresponds to the content raw bytes and second member the content mime type Raises: NotFoundExc if the content is not found """ content_data = service.lookup_content(query_string) content_raw = service.lookup_content_raw(query_string) content_data['raw_data'] = content_raw['data'] - filetype = service.lookup_content_filetype(query_string) - language = service.lookup_content_language(query_string) - license = service.lookup_content_license(query_string) + # Temporarily disable synchronous requests to indexer storage + # to improve performance + filetype = None # service.lookup_content_filetype(query_string) + language = None # service.lookup_content_language(query_string) + license = None # service.lookup_content_license(query_string) if filetype: mimetype = filetype['mimetype'] encoding = filetype['encoding'] else: mimetype, encoding = \ get_mimetype_and_encoding_for_content(content_data['raw_data']) content_data['mimetype'] = mimetype content_data['encoding'] = encoding # encode textual content to utf-8 if needed if mimetype.startswith('text/') and 'ascii' not in encoding \ and 'utf-8' not in encoding: content_data['raw_data'] = \ content_data['raw_data'].decode(encoding).encode('utf-8') if language: content_data['language'] = language['lang'] else: - content_data['language'] = 'not detected' + content_data['language'] = 'request sent to SWH indexer' if license: content_data['licenses'] = ', '.join(license['licenses']) else: - content_data['licenses'] = 'not detected' + content_data['licenses'] = 'request sent to SWH indexer' + + content_data['metadata_url'] = \ + reverse('browse-content-metadata', + kwargs={'query_string': query_string}) return content_data _browsers_supported_image_mimes = set(['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/webp']) def prepare_content_for_display(content_data, mime_type, path): """Function that prepares a content for HTML display. The function tries to associate a programming language to a content in order to perform syntax highlighting client-side using highlightjs. The language is determined using either the content filename or its mime type. If the mime type corresponds to an image format supported by web browsers, the content will be encoded in base64 for displaying the image. Args: content_data (bytes): raw bytes of the content mime_type (string): mime type of the content path (string): path of the content including filename Returns: A dict containing the content bytes (possibly different from the one provided as parameter if it is an image) under the key 'content_data and the corresponding highlightjs language class under the key 'language'. """ language = highlightjs.get_hljs_language_from_filename(path) if not language: language = highlightjs.get_hljs_language_from_mime_type(mime_type) if not language: language = 'nohighlight-swh' elif mime_type.startswith('application/'): mime_type = mime_type.replace('application/', 'text/') if mime_type.startswith('image/'): if mime_type in _browsers_supported_image_mimes: content_data = base64.b64encode(content_data) else: content_data = None return {'content_data': content_data, 'language': language} def get_origin_visits(origin_info): """Function that returns the list of visits for a swh origin. That list is put in cache in order to speedup the navigation in the swh web browse ui. Args: origin_id (int): the id of the swh origin to fetch visits from Returns: A list of dict describing the origin visits:: [{'date': , 'origin': , 'status': <'full' | 'partial'>, 'visit': }, ... ] Raises: NotFoundExc if the origin is not found """ cache_entry_id = 'origin_%s_visits' % origin_info['id'] cache_entry = cache.get(cache_entry_id) if cache_entry: return cache_entry origin_visits = [] per_page = service.MAX_LIMIT last_visit = None while 1: visits = list(service.lookup_origin_visits(origin_info['id'], last_visit=last_visit, per_page=per_page)) origin_visits += visits if len(visits) < per_page: break else: if not last_visit: last_visit = per_page else: last_visit += per_page def _visit_sort_key(visit): ts = dateutil.parser.parse(visit['date']).timestamp() return ts + (float(visit['visit']) / 10e3) for v in origin_visits: if 'metadata' in v: del v['metadata'] origin_visits = [dict(t) for t in set([tuple(d.items()) for d in origin_visits])] origin_visits = sorted(origin_visits, key=lambda v: _visit_sort_key(v)) cache.set(cache_entry_id, origin_visits) return origin_visits def get_origin_visit(origin_info, visit_ts=None, visit_id=None): """Function that returns information about a SWH visit for a given origin. The visit is retrieved from a provided timestamp. The closest visit from that timestamp is selected. Args: origin_info (dict): a dict filled with origin information (id, url, type) visit_ts (int or str): an ISO date string or Unix timestamp to parse Returns: A dict containing the visit info as described below:: {'origin': 2, 'date': '2017-10-08T11:54:25.582463+00:00', 'metadata': {}, 'visit': 25, 'status': 'full'} """ visits = get_origin_visits(origin_info) if not visits: raise NotFoundExc('No SWH visit associated to origin with' ' type %s and url %s!' % (origin_info['type'], origin_info['url'])) if visit_id: visit = [v for v in visits if v['visit'] == int(visit_id)] if len(visit) == 0: raise NotFoundExc( 'Visit with id %s for origin with type %s' ' and url %s not found!' % (visit_id, origin_info['type'], origin_info['url'])) return visit[0] if not visit_ts: return visits[-1] parsed_visit_ts = math.floor(parse_timestamp(visit_ts).timestamp()) visit_idx = None for i, visit in enumerate(visits): ts = math.floor(parse_timestamp(visit['date']).timestamp()) if i == 0 and parsed_visit_ts <= ts: return visit elif i == len(visits) - 1: if parsed_visit_ts >= ts: return visit else: next_ts = math.floor( parse_timestamp(visits[i+1]['date']).timestamp()) if parsed_visit_ts >= ts and parsed_visit_ts < next_ts: if (parsed_visit_ts - ts) < (next_ts - parsed_visit_ts): visit_idx = i break else: visit_idx = i+1 break if visit_idx: visit = visits[visit_idx] while visit_idx < len(visits) - 1 and \ visit['date'] == visits[visit_idx+1]['date']: visit_idx = visit_idx + 1 visit = visits[visit_idx] return visit else: raise NotFoundExc( 'Visit with timestamp %s for origin with type %s and url %s not found!' % # noqa (visit_ts, origin_info['type'], origin_info['url'])) def get_origin_visit_occurrences(origin_info, visit_ts=None, visit_id=None): """Function that returns the lists of branches and releases associated to a swh origin for a given visit. The visit is expressed by a timestamp. In the latter case, the closest visit from the provided timestamp will be used. If no visit parameter is provided, it returns the list of branches found for the latest visit. That list is put in cache in order to speedup the navigation in the swh web browse ui. Args: origin_info (dict): a dict filled with origin information (id, url, type) visit_ts (int or str): an ISO date string or Unix timestamp to parse visit_id (int): optional visit id for desambiguation in case several visits have the same timestamp Returns: A tuple with two members. The first one is a list of dict describing the origin branches for the given visit:: [{'name': , 'revision': , 'directory': }, ... ] The second one is a list of dict describing the origin branches for the given visit. Raises: NotFoundExc if the origin or its visit are not found """ visit_info = get_origin_visit(origin_info, visit_ts, visit_id) visit = visit_info['visit'] cache_entry_id = 'origin_%s_visit_%s_occurrences' % (origin_info['id'], visit) cache_entry = cache.get(cache_entry_id) if cache_entry: return cache_entry['branches'], cache_entry['releases'] origin_visit_data = service.lookup_origin_visit(origin_info['id'], visit) branches = [] releases = [] revision_ids = [] releases_ids = [] occurrences = origin_visit_data['occurrences'] for key in sorted(occurrences.keys()): if occurrences[key]['target_type'] == 'revision': branches.append({'name': key, 'revision': occurrences[key]['target']}) revision_ids.append(occurrences[key]['target']) elif occurrences[key]['target_type'] == 'release': releases_ids.append(occurrences[key]['target']) releases_info = service.lookup_release_multiple(releases_ids) for release in releases_info: releases.append({'name': release['name'], 'date': format_utc_iso_date(release['date']), 'id': release['id'], 'message': release['message'], 'target_type': release['target_type'], 'target': release['target']}) revision_ids.append(release['target']) revisions = service.lookup_revision_multiple(revision_ids) branches_to_remove = [] for idx, revision in enumerate(revisions): if idx < len(branches): if revision: branches[idx]['directory'] = revision['directory'] branches[idx]['date'] = format_utc_iso_date(revision['date']) branches[idx]['message'] = revision['message'] else: branches_to_remove.append(branches[idx]) else: rel_idx = idx - len(branches) if revision: releases[rel_idx]['directory'] = revision['directory'] for b in branches_to_remove: branches.remove(b) cache.set(cache_entry_id, {'branches': branches, 'releases': releases}) return branches, releases def gen_link(url, link_text): """ Utility function for generating an HTML link to insert in Django templates. Args: url (str): an url link_text (str): the text for the produced link Returns: An HTML link in the form 'link_text' """ link = '%s' % (url, link_text) return mark_safe(link) def gen_person_link(person_id, person_name): """ Utility function for generating a link to a SWH person HTML view to insert in Django templates. Args: person_id (int): a SWH person id person_name (str): the associated person name Returns: An HTML link in the form 'person_name' """ person_url = reverse('browse-person', kwargs={'person_id': person_id}) return gen_link(person_url, person_name) def gen_revision_link(revision_id, shorten_id=False, origin_context=None): """ Utility function for generating a link to a SWH revision HTML view to insert in Django templates. Args: revision_id (int): a SWH revision id shorten_id (boolean): wheter to shorten the revision id to 7 characters for the link text Returns: An HTML link in the form 'revision_id' """ query_params = None if origin_context: origin_info = origin_context['origin_info'] query_params = {'origin_type': origin_info['type'], 'origin_url': origin_info['url']} if 'timestamp' in origin_context['url_args']: query_params['timestamp'] = \ origin_context['url_args']['timestamp'] if 'visit_id' in origin_context['query_params']: query_params['visit_id'] = \ origin_context['query_params']['visit_id'] revision_url = reverse('browse-revision', kwargs={'sha1_git': revision_id}, query_params=query_params) if shorten_id: return gen_link(revision_url, revision_id[:7]) else: return gen_link(revision_url, revision_id) def gen_origin_link(origin_info): """ Utility function for generating a link to a SWH origin HTML view to insert in Django templates. Args: origin_info (dict): a dicted filled with origin information (id, type, url) Returns: An HTML link in the form 'Origin: origin_url' """ # noqa origin_browse_url = reverse('browse-origin', kwargs={'origin_type': origin_info['type'], 'origin_url': origin_info['url']}) return gen_link(origin_browse_url, 'Origin: ' + origin_info['url']) def gen_directory_link(sha1_git, link_text=None): """ Utility function for generating a link to a SWH directory HTML view to insert in Django templates. Args: sha1_git (str): directory identifier link_text (str): optional text for the generated link (the generated url will be used by default) Returns: An HTML link in the form 'link_text' """ directory_url = reverse('browse-directory', kwargs={'sha1_git': sha1_git}) if not link_text: link_text = directory_url return gen_link(directory_url, link_text) def gen_origin_directory_link(origin_context, revision_id=None): """ Utility function for generating a link to a SWH directory HTML view in the context of an origin to insert in Django templates. Args: origin_info (dict): the origin information (type and url) revision_id (str): optional revision identifier in order to use the associated directory Returns: An HTML link in the form 'origin_directory_view_url' """ origin_info = origin_context['origin_info'] url_args = {'origin_type': origin_info['type'], 'origin_url': origin_info['url']} query_params = {'revision': revision_id} if 'timestamp' in origin_context['url_args']: url_args['timestamp'] = \ origin_context['url_args']['timestamp'] if 'visit_id' in origin_context['query_params']: query_params['visit_id'] = \ origin_context['query_params']['visit_id'] directory_url = reverse('browse-origin-directory', kwargs=url_args, query_params=query_params) return gen_link(directory_url, directory_url) def gen_revision_log_link(revision_id, origin_context=None, link_text=None): """ Utility function for generating a link to a SWH revision log HTML view (possibly in the context of an origin) to insert in Django templates. Args: revision_id (str): revision identifier the history heads to origin_info (dict): optional origin information link_text (str): optional text to use for the generated link Returns: An HTML link in the form 'link_text' """ if origin_context: origin_info = origin_context['origin_info'] url_args = {'origin_type': origin_info['type'], 'origin_url': origin_info['url']} query_params = {'revision': revision_id} if 'timestamp' in origin_context['url_args']: url_args['timestamp'] = \ origin_context['url_args']['timestamp'] if 'visit_id' in origin_context['query_params']: query_params['visit_id'] = \ origin_context['query_params']['visit_id'] revision_log_url = reverse('browse-origin-log', kwargs=url_args, query_params=query_params) else: revision_log_url = reverse('browse-revision-log', kwargs={'sha1_git': revision_id}) if not link_text: link_text = revision_log_url return gen_link(revision_log_url, link_text) def _format_log_entries(revision_log, per_page, origin_context=None): revision_log_data = [] for i, log in enumerate(revision_log): if i == per_page: break revision_log_data.append( {'author': gen_person_link(log['author']['id'], log['author']['name']), 'revision': gen_revision_link(log['id'], True, origin_context), 'message': log['message'], 'message_shorten': textwrap.shorten(log['message'], width=80, placeholder='...'), 'date': format_utc_iso_date(log['date']), 'directory': log['directory']}) return revision_log_data def prepare_revision_log_for_display(revision_log, per_page, revs_breadcrumb, origin_context=None): """ Utility functions that process raw revision log data for HTML display. Its purpose is to: * add links to relevant SWH browse views * format date in human readable format * truncate the message log It also computes the data needed to generate the links for navigating back and forth in the history log. Args: revision_log (list): raw revision log as returned by the SWH web api per_page (int): number of log entries per page revs_breadcrumb (str): breadcrumbs of revisions navigated so far, in the form 'rev1[/rev2/../revN]'. Each revision corresponds to the first one displayed in the HTML view for history log. origin_context (boolean): wheter or not the revision log is browsed from an origin view. """ current_rev = revision_log[0]['id'] next_rev = None prev_rev = None next_revs_breadcrumb = None prev_revs_breadcrumb = None if len(revision_log) == per_page + 1: prev_rev = revision_log[-1]['id'] prev_rev_bc = current_rev if origin_context: prev_rev_bc = prev_rev if revs_breadcrumb: revs = revs_breadcrumb.split('/') next_rev = revs[-1] if len(revs) > 1: next_revs_breadcrumb = '/'.join(revs[:-1]) if len(revision_log) == per_page + 1: prev_revs_breadcrumb = revs_breadcrumb + '/' + prev_rev_bc else: prev_revs_breadcrumb = prev_rev_bc return {'revision_log_data': _format_log_entries(revision_log, per_page, origin_context), 'prev_rev': prev_rev, 'prev_revs_breadcrumb': prev_revs_breadcrumb, 'next_rev': next_rev, 'next_revs_breadcrumb': next_revs_breadcrumb} def get_origin_context(origin_type, origin_url, timestamp, visit_id=None): """ Utility function to compute relevant information when navigating the SWH archive in an origin context. Args: origin_type (str): the origin type (git, svn, deposit, ...) origin_url (str): the origin_url (e.g. https://github.com//) timestamp (str): a datetime string for retrieving the closest SWH visit of the origin visit_id (int): optional visit id for disambiguation in case of several visits with the same timestamp Returns: A dict with the following entries: * origin_info: dict containing origin information * visit_info: dict containing SWH visit information * branches: the list of branches for the origin found during the visit * releases: the list of releases for the origin found during the visit * origin_browse_url: the url to browse the origin * origin_branches_url: the url to browse the origin branches * origin_releases_url': the url to browse the origin releases * origin_visit_url: the url to browse the snapshot of the origin found during the visit * url_args: dict containg url arguments to use when browsing in the context of the origin and its visit """ # noqa origin_info = service.lookup_origin({'type': origin_type, 'url': origin_url}) visit_info = get_origin_visit(origin_info, timestamp, visit_id) visit_info['fmt_date'] = format_utc_iso_date(visit_info['date']) # provided timestamp is not necessarily equals to the one # of the retrieved visit, so get the exact one in order # use it in the urls generated below if timestamp: timestamp = visit_info['date'] branches, releases = \ get_origin_visit_occurrences(origin_info, timestamp, visit_id) releases = list(reversed(releases)) url_args = {'origin_type': origin_info['type'], 'origin_url': origin_info['url']} if timestamp: url_args['timestamp'] = format_utc_iso_date(timestamp, '%Y-%m-%dT%H:%M:%S') origin_browse_url = reverse('browse-origin', kwargs={'origin_type': origin_info['type'], 'origin_url': origin_info['url']}) origin_visit_url = reverse('browse-origin-directory', kwargs=url_args, query_params={'visit_id': visit_id}) origin_branches_url = reverse('browse-origin-branches', kwargs=url_args, query_params={'visit_id': visit_id}) origin_releases_url = reverse('browse-origin-releases', kwargs=url_args, query_params={'visit_id': visit_id}) return { 'origin_info': origin_info, 'visit_info': visit_info, 'branches': branches, 'releases': releases, 'origin_browse_url': origin_browse_url, 'origin_branches_url': origin_branches_url, 'origin_releases_url': origin_releases_url, 'origin_visit_url': origin_visit_url, 'url_args': url_args, 'query_params': {'visit_id': visit_id} } diff --git a/swh/web/browse/views/content.py b/swh/web/browse/views/content.py index 0bcde9c5e..f3ee6aea3 100644 --- a/swh/web/browse/views/content.py +++ b/swh/web/browse/views/content.py @@ -1,157 +1,184 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information +import json + from django.http import HttpResponse from django.utils.safestring import mark_safe from django.shortcuts import render from django.template.defaultfilters import filesizeformat from swh.model.hashutil import hash_to_hex -from swh.web.common import query +from swh.web.common import query, service from swh.web.common.utils import reverse, gen_path_info from swh.web.common.exc import handle_view_exception from swh.web.browse.utils import ( request_content, prepare_content_for_display ) from swh.web.browse.browseurls import browse_route @browse_route(r'content/(?P.+)/raw/', view_name='browse-content-raw') def content_raw(request, query_string): """Django view that produces a raw display of a SWH content identified by its hash value. The url that points to it is :http:get:`/browse/content/[(algo_hash):](hash)/raw/` Args: request: input django http request query_string: a string of the form "[ALGO_HASH:]HASH" where optional ALGO_HASH can be either *sha1*, *sha1_git*, *sha256*, or *blake2s256* (default to *sha1*) and HASH the hexadecimal representation of the hash value Returns: The raw bytes of the content. """ # noqa try: algo, checksum = query.parse_hash(query_string) checksum = hash_to_hex(checksum) content_data = request_content(query_string) except Exception as exc: return handle_view_exception(request, exc) filename = request.GET.get('filename', None) if not filename: filename = '%s_%s' % (algo, checksum) if content_data['mimetype'].startswith('text/'): response = HttpResponse(content_data['raw_data'], content_type="text/plain") response['Content-disposition'] = 'filename=%s' % filename else: response = HttpResponse(content_data['raw_data'], content_type='application/octet-stream') response['Content-disposition'] = 'attachment; filename=%s' % filename return response +@browse_route(r'content/(?P.+)/metadata/', + view_name='browse-content-metadata') +def content_metadata(request, query_string): + """ + Endpoint used to query content metadata asynchronously client-side. + """ + language = service.lookup_content_language(query_string) + license = service.lookup_content_license(query_string) + + content_metadata = {} + if language: + content_metadata['language'] = language['lang'] + else: + content_metadata['language'] = 'not detected' + if license: + content_metadata['licenses'] = ', '.join(license['licenses']) + else: + content_metadata['licenses'] = 'not detected' + + content_metadata = json.dumps(content_metadata, separators=(',', ': ')) + + return HttpResponse(content_metadata, content_type='application/json') + + @browse_route(r'content/(?P.+)/', view_name='browse-content') def content_display(request, query_string): """Django view that produces an HTML display of a SWH content identified by its hash value. The url that points to it is :http:get:`/browse/content/[(algo_hash):](hash)/` Args: request: input django http request query_string: a string of the form "[ALGO_HASH:]HASH" where optional ALGO_HASH can be either *sha1*, *sha1_git*, *sha256*, or *blake2s256* (default to *sha1*) and HASH the hexadecimal representation of the hash value Returns: The HTML rendering of the requested content. """ # noqa try: algo, checksum = query.parse_hash(query_string) checksum = hash_to_hex(checksum) content_data = request_content(query_string) except Exception as exc: return handle_view_exception(request, exc) path = request.GET.get('path', None) content_display_data = prepare_content_for_display( content_data['raw_data'], content_data['mimetype'], path) root_dir = None filename = None path_info = None breadcrumbs = [] if path: split_path = path.split('/') root_dir = split_path[0] filename = split_path[-1] path = path.replace(root_dir + '/', '') path = path.replace(filename, '') path_info = gen_path_info(path) breadcrumbs.append({'name': root_dir[:7], 'url': reverse('browse-directory', kwargs={'sha1_git': root_dir})}) for pi in path_info: breadcrumbs.append({'name': pi['name'], 'url': reverse('browse-directory', kwargs={'sha1_git': root_dir, 'path': pi['path']})}) breadcrumbs.append({'name': filename, 'url': None}) query_params = None if filename: query_params = {'filename': filename} content_raw_url = reverse('browse-content-raw', kwargs={'query_string': query_string}, query_params=query_params) content_metadata = { 'sha1 checksum': content_data['checksums']['sha1'], 'sha1_git checksum': content_data['checksums']['sha1_git'], 'sha256 checksum': content_data['checksums']['sha256'], 'blake2s256 checksum': content_data['checksums']['blake2s256'], 'mime type': content_data['mimetype'], 'encoding': content_data['encoding'], 'size': filesizeformat(content_data['length']), 'language': content_data['language'], 'licenses': content_data['licenses'] } return render(request, 'content.html', {'empty_browse': False, 'heading': 'Content information', 'top_panel_visible': True, 'top_panel_collapsible': True, 'top_panel_text': 'SWH object: Content', 'swh_object_metadata': content_metadata, 'main_panel_visible': True, 'content': content_display_data['content_data'], + 'content_metadata_url': content_data['metadata_url'], 'mimetype': content_data['mimetype'], 'language': content_display_data['language'], 'breadcrumbs': breadcrumbs, 'top_right_link': content_raw_url, 'top_right_link_text': mark_safe( 'Raw File'), 'origin_context': None }) diff --git a/swh/web/browse/views/origin.py b/swh/web/browse/views/origin.py index f47032fce..0371b17aa 100644 --- a/swh/web/browse/views/origin.py +++ b/swh/web/browse/views/origin.py @@ -1,848 +1,849 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import dateutil import json from distutils.util import strtobool from django.http import HttpResponse from django.shortcuts import render from django.utils.safestring import mark_safe from django.template.defaultfilters import filesizeformat from swh.web.common import service from swh.web.common.utils import ( gen_path_info, reverse, format_utc_iso_date ) from swh.web.common.exc import NotFoundExc, handle_view_exception from swh.web.browse.utils import ( get_origin_visits, get_directory_entries, request_content, prepare_content_for_display, gen_link, prepare_revision_log_for_display, get_origin_context ) from swh.web.browse.browseurls import browse_route def _occurrence_not_found(origin_info, timestamp, branch_type, occurrence, occurrences, visit_id=None): """ Utility function to raise an exception when a specified branch/release can not be found. """ if branch_type: occ_type = 'Branch' occ_type_plural = 'branches' else: occ_type = 'Release' occ_type_plural = 'releases' if visit_id: if len(occurrences) == 0: raise NotFoundExc('Origin with type %s and url %s' ' for visit with id %s has an empty list' ' of %s!' % (origin_info['type'], origin_info['url'], visit_id, occ_type_plural)) else: raise NotFoundExc('%s %s associated to visit with' ' id %s for origin with type %s and url %s' ' not found!' % (occ_type, occurrence, visit_id, origin_info['type'], origin_info['url'])) else: if len(occurrences) == 0: raise NotFoundExc('Origin with type %s and url %s' ' for visit with timestamp %s has an empty list' ' of %s!' % (origin_info['type'], origin_info['url'], timestamp, occ_type_plural)) else: raise NotFoundExc('%s %s associated to visit with' ' timestamp %s for origin with type %s' ' and url %s not found!' % (occ_type, occurrence, timestamp, origin_info['type'], origin_info['url'])) def _get_branch(branches, branch_name): """ Utility function to get a specific branch from an origin branches list. Its purpose is to get the default HEAD branch as some SWH origin (e.g those with svn type) does not have it. In that latter case, check if there is a master branch instead and returns it. """ filtered_branches = \ [b for b in branches if b['name'].endswith(branch_name)] if len(filtered_branches) > 0: return filtered_branches[0] elif branch_name == 'HEAD': filtered_branches = \ [b for b in branches if b['name'].endswith('master')] if len(filtered_branches) > 0: return filtered_branches[0] elif len(branches) > 0: return branches[0] return None def _get_release(releases, release_name): filtered_releases = \ [r for r in releases if r['name'] == release_name] if len(filtered_releases) > 0: return filtered_releases[0] else: return None def _process_origin_request(request, origin_type, origin_url, timestamp, path, browse_view_name): """ Utility function to perform common input request processing for origin context views. """ visit_id = request.GET.get('visit_id', None) origin_context = get_origin_context(origin_type, origin_url, timestamp, visit_id) for b in origin_context['branches']: branch_url_args = dict(origin_context['url_args']) if path: b['path'] = path branch_url_args['path'] = path b['url'] = reverse(browse_view_name, kwargs=branch_url_args, query_params={'branch': b['name'], 'visit_id': visit_id}) for r in origin_context['releases']: release_url_args = dict(origin_context['url_args']) if path: r['path'] = path release_url_args['path'] = path r['url'] = reverse(browse_view_name, kwargs=release_url_args, query_params={'release': r['name'], 'visit_id': visit_id}) root_sha1_git = None query_params = origin_context['query_params'] revision_id = request.GET.get('revision', None) release_name = request.GET.get('release', None) branch_name = None if revision_id: revision = service.lookup_revision(revision_id) root_sha1_git = revision['directory'] origin_context['branches'].append({'name': revision_id, 'revision': revision_id, 'directory': root_sha1_git, 'url': None}) branch_name = revision_id query_params['revision'] = revision_id elif release_name: release = _get_release(origin_context['releases'], release_name) if release: root_sha1_git = release['directory'] query_params['release'] = release_name revision_id = release['target'] else: _occurrence_not_found(origin_context['origin_info'], timestamp, False, release_name, origin_context['releases'], visit_id) else: branch_name = request.GET.get('branch', None) if branch_name: query_params['branch'] = branch_name branch = _get_branch(origin_context['branches'], branch_name or 'HEAD') if branch: branch_name = branch['name'] root_sha1_git = branch['directory'] revision_id = branch['revision'] else: _occurrence_not_found(origin_context['origin_info'], timestamp, True, branch_name, origin_context['branches'], visit_id) origin_context['root_sha1_git'] = root_sha1_git origin_context['revision_id'] = revision_id origin_context['branch'] = branch_name origin_context['release'] = release_name return origin_context @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/directory/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/directory/(?P.+)/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/directory/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/directory/(?P.+)/', # noqa view_name='browse-origin-directory') def origin_directory_browse(request, origin_type, origin_url, timestamp=None, path=None): """Django view for browsing the content of a SWH directory associated to an origin for a given visit. The url scheme that points to it is the following: * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/directory/[(path)/]` * :http:get:`/browse/origin/(origin_type)/url/(origin_type)/visit/(timestamp)/directory/[(path)/]` Args: request: input django http request origin_type: the type of swh origin (git, svn, hg, ...) origin_url: the url of the swh origin timestamp: optional swh visit timestamp parameter (the last one will be used by default) path: optional path parameter used to navigate in directories reachable from the origin root one branch: optional query parameter that specifies the origin branch from which to retrieve the directory release: optional query parameter that specifies the origin release from which to retrieve the directory revision: optional query parameter to specify the origin revision from which to retrieve the directory Returns: The HTML rendering for the content of the directory associated to the provided origin and visit. """ # noqa try: origin_context = _process_origin_request( request, origin_type, origin_url, timestamp, path, 'browse-origin-directory') root_sha1_git = origin_context['root_sha1_git'] sha1_git = root_sha1_git if path: dir_info = service.lookup_directory_with_path(root_sha1_git, path) sha1_git = dir_info['target'] dirs, files = get_directory_entries(sha1_git) except Exception as exc: return handle_view_exception(request, exc) origin_info = origin_context['origin_info'] visit_info = origin_context['visit_info'] url_args = origin_context['url_args'] query_params = origin_context['query_params'] revision_id = origin_context['revision_id'] path_info = gen_path_info(path) breadcrumbs = [] breadcrumbs.append({'name': root_sha1_git[:7], 'url': reverse('browse-origin-directory', kwargs=url_args, query_params=query_params)}) for pi in path_info: bc_url_args = dict(url_args) bc_url_args['path'] = pi['path'] breadcrumbs.append({'name': pi['name'], 'url': reverse('browse-origin-directory', kwargs=bc_url_args, query_params=query_params)}) path = '' if path is None else (path + '/') for d in dirs: bc_url_args = dict(url_args) bc_url_args['path'] = path + d['name'] d['url'] = reverse('browse-origin-directory', kwargs=bc_url_args, query_params=query_params) sum_file_sizes = 0 readme_name = None readme_url = None for f in files: bc_url_args = dict(url_args) bc_url_args['path'] = path + f['name'] f['url'] = reverse('browse-origin-content', kwargs=bc_url_args, query_params=query_params) sum_file_sizes += f['length'] f['length'] = filesizeformat(f['length']) if f['name'].lower().startswith('readme'): readme_name = f['name'] readme_sha1 = f['checksums']['sha1'] readme_url = reverse('browse-content-raw', kwargs={'query_string': readme_sha1}) history_url = reverse('browse-origin-log', kwargs=url_args, query_params=query_params) sum_file_sizes = filesizeformat(sum_file_sizes) browse_dir_url = reverse('browse-directory', kwargs={'sha1_git': sha1_git}) browse_rev_url = reverse('browse-revision', kwargs={'sha1_git': revision_id}, query_params={'origin_type': origin_info['type'], 'origin_url': origin_info['url']}) dir_metadata = {'id': sha1_git, 'browse directory url': browse_dir_url, 'number of regular files': len(files), 'number of subdirectories': len(dirs), 'sum of regular file sizes': sum_file_sizes, 'origin id': origin_info['id'], 'origin type': origin_info['type'], 'origin url': origin_info['url'], 'origin visit date': format_utc_iso_date(visit_info['date']), # noqa 'origin visit id': visit_info['visit'], 'path': '/' + path, 'revision id': revision_id, 'browse revision url': browse_rev_url} return render(request, 'directory.html', {'empty_browse': False, 'heading': 'Directory information', 'top_panel_visible': True, 'top_panel_collapsible': True, 'top_panel_text': 'SWH object: Directory', 'swh_object_metadata': dir_metadata, 'main_panel_visible': True, 'dirs': dirs, 'files': files, 'breadcrumbs': breadcrumbs, 'top_right_link': history_url, 'top_right_link_text': mark_safe( '' 'History' ), 'readme_name': readme_name, 'readme_url': readme_url, 'origin_context': origin_context}) @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/content/(?P.+)/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/content/(?P.+)/', # noqa view_name='browse-origin-content') def origin_content_display(request, origin_type, origin_url, path, timestamp=None): """Django view that produces an HTML display of a SWH content associated to an origin for a given visit. The url scheme that points to it is the following: * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/content/(path)/` * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/visit/(timestamp)/content/(path)/` Args: request: input django http request origin_type: the type of swh origin (git, svn, hg, ...) origin_url: the url of the swh origin path: path of the content relative to the origin root directory timestamp: optional swh visit timestamp parameter (the last one will be used by default) branch: optional query parameter that specifies the origin branch from which to retrieve the content release: optional query parameter that specifies the origin release from which to retrieve the content revision: optional query parameter to specify the origin revision from which to retrieve the content Returns: The HTML rendering of the requested content associated to the provided origin and visit. """ # noqa try: origin_context = _process_origin_request( request, origin_type, origin_url, timestamp, path, 'browse-origin-content') root_sha1_git = origin_context['root_sha1_git'] content_info = service.lookup_directory_with_path(root_sha1_git, path) sha1_git = content_info['target'] query_string = 'sha1_git:' + sha1_git content_data = request_content(query_string) except Exception as exc: return handle_view_exception(request, exc) url_args = origin_context['url_args'] query_params = origin_context['query_params'] revision_id = origin_context['revision_id'] origin_info = origin_context['origin_info'] visit_info = origin_context['visit_info'] content_display_data = prepare_content_for_display( content_data['raw_data'], content_data['mimetype'], path) filename = None path_info = None breadcrumbs = [] split_path = path.split('/') filename = split_path[-1] path = path.replace(filename, '') path_info = gen_path_info(path) breadcrumbs.append({'name': root_sha1_git[:7], 'url': reverse('browse-origin-directory', kwargs=url_args, query_params=query_params)}) for pi in path_info: bc_url_args = dict(url_args) bc_url_args['path'] = pi['path'] breadcrumbs.append({'name': pi['name'], 'url': reverse('browse-origin-directory', kwargs=bc_url_args, query_params=query_params)}) breadcrumbs.append({'name': filename, 'url': None}) browse_content_url = reverse('browse-content', kwargs={'query_string': query_string}) content_raw_url = reverse('browse-content-raw', kwargs={'query_string': query_string}, query_params={'filename': filename}) browse_rev_url = reverse('browse-revision', kwargs={'sha1_git': revision_id}, query_params={'origin_type': origin_info['type'], 'origin_url': origin_info['url']}) content_metadata = { 'browse content url': browse_content_url, 'sha1 checksum': content_data['checksums']['sha1'], 'sha1_git checksum': content_data['checksums']['sha1_git'], 'sha256 checksum': content_data['checksums']['sha256'], 'blake2s256 checksum': content_data['checksums']['blake2s256'], 'mime type': content_data['mimetype'], 'encoding': content_data['encoding'], 'size': filesizeformat(content_data['length']), 'language': content_data['language'], 'licenses': content_data['licenses'], 'origin id': origin_info['id'], 'origin type': origin_info['type'], 'origin url': origin_info['url'], 'origin visit date': format_utc_iso_date(visit_info['date']), 'origin visit id': visit_info['visit'], 'path': '/' + path, 'filename': filename, 'revision id': revision_id, 'browse revision url': browse_rev_url } return render(request, 'content.html', {'empty_browse': False, 'heading': 'Content information', 'top_panel_visible': True, 'top_panel_collapsible': True, 'top_panel_text': 'SWH object: Content', 'swh_object_metadata': content_metadata, 'main_panel_visible': True, 'content': content_display_data['content_data'], + 'content_metadata_url': content_data['metadata_url'], 'mimetype': content_data['mimetype'], 'language': content_display_data['language'], 'breadcrumbs': breadcrumbs, 'top_right_link': content_raw_url, 'top_right_link_text': mark_safe( 'Raw File'), 'origin_context': origin_context}) def _gen_directory_link(url_args, query_params, link_text): directory_url = reverse('browse-origin-directory', kwargs=url_args, query_params=query_params) return gen_link(directory_url, link_text) PER_PAGE = 20 @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/log/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/log/', view_name='browse-origin-log') def origin_log_browse(request, origin_type, origin_url, timestamp=None): """Django view that produces an HTML display of revisions history (aka the commit log) associated to a SWH origin. The url scheme that points to it is the following: * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/log/` * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/visit/(timestamp)/log/` Args: request: input django http request origin_type: the type of swh origin (git, svn, hg, ...) origin_url: the url of the swh origin timestamp: optional visit timestamp parameter (the last one will be used by default) revs_breadcrumb: query parameter used internally to store the navigation breadcrumbs (i.e. the list of descendant revisions visited so far). per_page: optional query parameter used to specify the number of log entries per page branch: optional query parameter that specifies the origin branch from which to retrieve the commit log release: optional query parameter that specifies the origin release from which to retrieve the commit log revision: optional query parameter to specify the origin revision from which to retrieve the commit log Returns: The HTML rendering of revisions history for a given SWH visit. """ # noqa try: origin_context = _process_origin_request( request, origin_type, origin_url, timestamp, None, 'browse-origin-log') revision_id = origin_context['revision_id'] per_page = int(request.GET.get('per_page', PER_PAGE)) revision_log = service.lookup_revision_log(revision_id, limit=per_page+1) revision_log = list(revision_log) except Exception as exc: return handle_view_exception(request, exc) origin_info = origin_context['origin_info'] visit_info = origin_context['visit_info'] url_args = origin_context['url_args'] query_params = origin_context['query_params'] query_params['per_page'] = per_page revs_breadcrumb = request.GET.get('revs_breadcrumb', None) if revs_breadcrumb: revision_id = revs_breadcrumb.split('/')[-1] revision_log_display_data = prepare_revision_log_for_display( revision_log, per_page, revs_breadcrumb, origin_context) prev_rev = revision_log_display_data['prev_rev'] prev_revs_breadcrumb = revision_log_display_data['prev_revs_breadcrumb'] prev_log_url = None query_params['revs_breadcrumb'] = prev_revs_breadcrumb if prev_rev: prev_log_url = \ reverse('browse-origin-log', kwargs=url_args, query_params=query_params) next_rev = revision_log_display_data['next_rev'] next_revs_breadcrumb = revision_log_display_data['next_revs_breadcrumb'] next_log_url = None query_params['revs_breadcrumb'] = next_revs_breadcrumb if next_rev: next_log_url = \ reverse('browse-origin-log', kwargs=url_args, query_params=query_params) revision_log_data = revision_log_display_data['revision_log_data'] for i, log in enumerate(revision_log_data): params = { 'revision': revision_log[i]['id'], } if 'visit_id' in query_params: params['visit_id'] = query_params['visit_id'] log['directory'] = _gen_directory_link(url_args, params, 'Tree') browse_log_url = reverse('browse-revision-log', kwargs={'sha1_git': revision_id}) revision_metadata = { 'browse revision history url': browse_log_url, 'origin id': origin_info['id'], 'origin type': origin_info['type'], 'origin url': origin_info['url'], 'origin visit date': format_utc_iso_date(visit_info['date']), 'origin visit id': visit_info['visit'] } return render(request, 'revision-log.html', {'empty_browse': False, 'heading': 'Revision history information', 'top_panel_visible': True, 'top_panel_collapsible': True, 'top_panel_text': 'SWH object: Revision history', 'swh_object_metadata': revision_metadata, 'main_panel_visible': True, 'revision_log': revision_log_data, 'next_log_url': next_log_url, 'prev_log_url': prev_log_url, 'breadcrumbs': None, 'top_right_link': None, 'top_right_link_text': None, 'include_top_navigation': True, 'origin_context': origin_context}) @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/branches/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/branches/', # noqa view_name='browse-origin-branches') def origin_branches_browse(request, origin_type, origin_url, timestamp=None): """Django view that produces an HTML display of the list of branches associated to an origin for a given visit. The url scheme that points to it is the following: * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/branches/` * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/visit/(timestamp)/branches/` """ # noqa try: origin_context = _process_origin_request( request, origin_type, origin_url, timestamp, None, 'browse-origin-directory') except Exception as exc: return handle_view_exception(request, exc) branches_offset = int(request.GET.get('branches_offset', 0)) origin_info = origin_context['origin_info'] url_args = origin_context['url_args'] query_params = origin_context['query_params'] branches = origin_context['branches'] displayed_branches = \ branches[branches_offset:branches_offset+PER_PAGE] for branch in displayed_branches: revision_url = reverse( 'browse-revision', kwargs={'sha1_git': branch['revision']}, query_params={'origin_type': origin_info['type'], 'origin_url': origin_info['url']}) query_params['branch'] = branch['name'] directory_url = reverse('browse-origin-directory', kwargs=url_args, query_params=query_params) del query_params['branch'] branch['revision_url'] = revision_url branch['directory_url'] = directory_url prev_branches_url = None next_branches_url = None next_offset = branches_offset + PER_PAGE prev_offset = branches_offset - PER_PAGE if next_offset < len(branches): query_params['branches_offset'] = next_offset next_branches_url = reverse('browse-origin-branches', kwargs=url_args, query_params=query_params) query_params['branches_offset'] = None if prev_offset >= 0: if prev_offset != 0: query_params['branches_offset'] = prev_offset prev_branches_url = reverse('browse-origin-branches', kwargs=url_args, query_params=query_params) return render(request, 'branches.html', {'empty_browse': False, 'heading': 'Origin branches list', 'top_panel_visible': False, 'top_panel_collapsible': False, 'top_panel_text': 'SWH object: Origin branches list', 'swh_object_metadata': {}, 'main_panel_visible': True, 'top_right_link': None, 'top_right_link_text': None, 'include_top_navigation': True, 'displayed_branches': displayed_branches, 'prev_branches_url': prev_branches_url, 'next_branches_url': next_branches_url, 'origin_context': origin_context}) @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/releases/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/releases/', # noqa view_name='browse-origin-releases') def origin_releases_browse(request, origin_type, origin_url, timestamp=None): """Django view that produces an HTML display of the list of releases associated to an origin for a given visit. The url scheme that points to it is the following: * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/releases/` * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/visit/(timestamp)/releases/` """ # noqa try: origin_context = _process_origin_request( request, origin_type, origin_url, timestamp, None, 'browse-origin-directory') except Exception as exc: return handle_view_exception(request, exc) releases_offset = int(request.GET.get('releases_offset', 0)) origin_info = origin_context['origin_info'] url_args = origin_context['url_args'] query_params = origin_context['query_params'] releases = origin_context['releases'] displayed_releases = \ releases[releases_offset:releases_offset+PER_PAGE] for release in displayed_releases: release_url = reverse('browse-release', kwargs={'sha1_git': release['id']}, query_params={'origin_type': origin_info['type'], 'origin_url': origin_info['url']}) query_params['release'] = release['name'] del query_params['release'] release['release_url'] = release_url prev_releases_url = None next_releases_url = None next_offset = releases_offset + PER_PAGE prev_offset = releases_offset - PER_PAGE if next_offset < len(releases): query_params['releases_offset'] = next_offset next_releases_url = reverse('browse-origin-releases', kwargs=url_args, query_params=query_params) query_params['releases_offset'] = None if prev_offset >= 0: if prev_offset != 0: query_params['releases_offset'] = prev_offset prev_releases_url = reverse('browse-origin-releases', kwargs=url_args, query_params=query_params) return render(request, 'releases.html', {'empty_browse': False, 'heading': 'Origin releases list', 'top_panel_visible': False, 'top_panel_collapsible': False, 'top_panel_text': 'SWH object: Origin releases list', 'swh_object_metadata': {}, 'main_panel_visible': True, 'top_right_link': None, 'top_right_link_text': None, 'include_top_navigation': True, 'displayed_releases': displayed_releases, 'prev_releases_url': prev_releases_url, 'next_releases_url': next_releases_url, 'origin_context': origin_context}) @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/', view_name='browse-origin') def origin_browse(request, origin_type=None, origin_url=None): """Django view that produces an HTML display of a swh origin identified by its id or its url. The url scheme that points to it is :http:get:`/browse/origin/(origin_type)/url/(origin_url)/`. Args: request: input django http request origin_type: type of origin (git, svn, ...) origin_url: url of the origin (e.g. https://github.com//) Returns: The HMTL rendering for the metadata of the provided origin. """ # noqa try: origin_info = service.lookup_origin({ 'type': origin_type, 'url': origin_url }) origin_visits = get_origin_visits(origin_info) origin_visits.reverse() except Exception as exc: return handle_view_exception(request, exc) origin_info['last swh visit browse url'] = \ reverse('browse-origin-directory', kwargs={'origin_type': origin_type, 'origin_url': origin_url}) origin_visits_data = [] visits_splitted = [] visits_by_year = {} for i, visit in enumerate(origin_visits): visit_date = dateutil.parser.parse(visit['date']) visit_year = str(visit_date.year) url_date = format_utc_iso_date(visit['date'], '%Y-%m-%dT%H:%M:%S') visit['fmt_date'] = format_utc_iso_date(visit['date']) query_params = {} if i < len(origin_visits) - 1: if visit['date'] == origin_visits[i+1]['date']: query_params = {'visit_id': visit['visit']} if i > 0: if visit['date'] == origin_visits[i-1]['date']: query_params = {'visit_id': visit['visit']} visit['browse_url'] = reverse('browse-origin-directory', kwargs={'origin_type': origin_type, 'origin_url': origin_url, 'timestamp': url_date}, query_params=query_params) origin_visits_data.insert(0, {'date': visit_date.timestamp()}) if visit_year not in visits_by_year: # display 3 years by row in visits list view if len(visits_by_year) == 3: visits_splitted.insert(0, visits_by_year) visits_by_year = {} visits_by_year[visit_year] = [] visits_by_year[visit_year].append(visit) if len(visits_by_year) > 0: visits_splitted.insert(0, visits_by_year) return render(request, 'origin.html', {'empty_browse': False, 'heading': 'Origin information', 'top_panel_visible': False, 'top_panel_collapsible': False, 'top_panel_text': 'SWH object: Visits history', 'swh_object_metadata': origin_info, 'main_panel_visible': True, 'origin_visits_data': origin_visits_data, 'visits_splitted': visits_splitted, 'origin_info': origin_info, 'browse_url_base': '/browse/origin/%s/url/%s/' % (origin_type, origin_url)}) @browse_route(r'origin/search/(?P.+)/', view_name='browse-origin-search') def origin_search(request, url_pattern): """Search for origins whose urls contain a provided string pattern or match a provided regular expression. The search is performed in a case insensitive way. """ offset = int(request.GET.get('offset', '0')) limit = int(request.GET.get('limit', '50')) regexp = request.GET.get('regexp', 'false') results = service.search_origin(url_pattern, offset, limit, bool(strtobool(regexp))) results = json.dumps(list(results), sort_keys=True, indent=4, separators=(',', ': ')) return HttpResponse(results, content_type='application/json') diff --git a/swh/web/templates/content.html b/swh/web/templates/content.html index 552a6e3f0..1eb4980d3 100644 --- a/swh/web/templates/content.html +++ b/swh/web/templates/content.html @@ -1,140 +1,150 @@ {% extends "browse.html" %} {% load static %} {% block header %} {% endblock %} {% block swh-browse-before-panels %} {% if origin_context %} {% include "includes/origin-visit-snapshot.html" %} {% endif %} {% endblock %} {% block swh-browse-main-panel-content %} {% include "includes/top-navigation.html" %}
{% if "inode/x-empty" == mimetype %} File is empty {% elif "text/" in mimetype %}
     {{ content }}
   
{% elif "image/" in mimetype and content %} {% else %} Content with mime type {{ mimetype }} can not be displayed {% endif %}
{% endblock %} diff --git a/swh/web/tests/browse/views/data/content_test_data.py b/swh/web/tests/browse/views/data/content_test_data.py index cd98ac935..48532e174 100644 --- a/swh/web/tests/browse/views/data/content_test_data.py +++ b/swh/web/tests/browse/views/data/content_test_data.py @@ -1,202 +1,205 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information # flake8: noqa import os stub_content_root_dir = '08e8329257dad3a3ef7adea48aa6e576cd82de5b' stub_content_text_file = \ """ /* This file is part of the KDE project * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KATE_SESSION_TEST_H #define KATE_SESSION_TEST_H #include class KateSessionTest : public QObject { Q_OBJECT private Q_SLOTS: void init(); void cleanup(); void initTestCase(); void cleanupTestCase(); void create(); void createAnonymous(); void createAnonymousFrom(); void createFrom(); void documents(); void setFile(); void setName(); void timestamp(); private: class QTemporaryFile *m_tmpfile; }; #endif """ stub_content_text_file_no_highlight = \ """ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. """ stub_content_text_data = { 'checksums': { 'sha1': '5ecd9f37b7a2d2e9980d201acd6286116f2ba1f1', 'sha1_git': '537b47f68469c1c916c1bfbc072599133bfcbb21', 'sha256': 'b3057544f04e5821ab0e2a007e2ceabd7de2dfb1d42a764f1de8d0d2eff80006', 'blake2s256': '25117fa9f124d5b771a0a7dfca9c7a57247d81f8343334b4b41c782c7f7ed64d' }, 'length': 1317, 'raw_data': str.encode(stub_content_text_file), 'mimetype': 'text/x-c++', 'encoding': 'us-ascii', 'language': 'c++', - 'licenses': 'GPL' + 'licenses': 'GPL', + 'metadata_url': '' } stub_content_text_no_highlight_data = { 'checksums': { 'sha1': '8624bcdae55baeef00cd11d5dfcfa60f68710a02', 'sha1_git': '94a9ed024d3859793618152ea559a168bbcbb5e2', 'sha256': '8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903', 'blake2s256': '38702b7168c7785bfe748b51b45d9856070ba90f9dc6d90f2ea75d4356411ffe' }, 'length': 35147, 'raw_data': str.encode(stub_content_text_file_no_highlight), 'mimetype': 'text/plain', 'encoding': 'us-ascii', 'language': 'not detected', - 'licenses': 'GPL' + 'licenses': 'GPL', + 'metadata_url': '' } stub_content_text_path = 'kate/autotests/session_test.h' stub_content_text_path_with_root_dir = stub_content_root_dir + '/' + stub_content_text_path stub_content_bin_filename = 'swh-logo.png' png_file_path = os.path.dirname(__file__) + '/' + stub_content_bin_filename with open(png_file_path, 'rb') as png_file: stub_content_bin_data = { 'checksums': { 'sha1': 'd0cec0fc2d795f0077c18d51578cdb228eaf6a99', 'sha1_git': '02328b91cfad800e1d2808cfb379511b79679ebc', 'sha256': 'e290592e2cfa9767497011bda4b7e273b4cf29e7695d72ecacbd723008a29144', 'blake2s256': '7177cad95407952e362ee326a800a9d215ccd619fdbdb735bb51039be81ab9ce' }, 'length': 18063, 'raw_data': png_file.read(), 'mimetype': 'image/png', 'encoding': 'binary', 'language': 'not detected', - 'licenses': 'not detected' + 'licenses': 'not detected', + 'metadata_url': '' } _non_utf8_encoding_file_path = os.path.dirname(__file__) + '/iso-8859-1_encoded_content' non_utf8_encoded_content_data = { 'checksums': { 'sha1': '62cb71aa3534a03c12572157d20fa893753b03b6', 'sha1_git': '2f7470d0b26108130e71087e42a53c032473499c', 'sha256': 'aaf364ccd3acb546829ccc0e8e5e293e924c8a2e55a67cb739d249016e0034ed', 'blake2s256': 'b7564932460a7c2697c53bd55bd855272490da511d64b20c5a04f636dc9ac467' }, 'length': 111000 } non_utf8_encoding = 'iso-8859-1' with open(_non_utf8_encoding_file_path, 'rb') as iso88591_file: non_utf8_encoded_content = iso88591_file.read()