Changeset View
Changeset View
Standalone View
Standalone View
swh/web/common/origin_visits.py
Show First 20 Lines • Show All 143 Lines • ▼ Show 20 Lines | def get_origin_visit(origin_info, visit_ts=None, visit_id=None, | ||||
if not visit_ts: | if not visit_ts: | ||||
# returns the latest full visit when no timestamp is provided | # returns the latest full visit when no timestamp is provided | ||||
for v in reversed(visits): | for v in reversed(visits): | ||||
if v['status'] == 'full': | if v['status'] == 'full': | ||||
return v | return v | ||||
return visits[-1] | return visits[-1] | ||||
parsed_visit_ts = math.floor(parse_timestamp(visit_ts).timestamp()) | target_visit_ts = math.floor(parse_timestamp(visit_ts).timestamp()) | ||||
visit_idx = None | # Find the visit with date closest to the target (in absolute value) | ||||
for i, visit in enumerate(visits): | (abs_time_delta, visit_idx) = min( | ||||
ts = math.floor(parse_timestamp(visit['date']).timestamp()) | ((math.floor(parse_timestamp(visit['date']).timestamp()), i) | ||||
if i == 0 and parsed_visit_ts <= ts: | for (i, visit) in enumerate(visits)), | ||||
return visit | key=lambda ts_and_i: abs(ts_and_i[0] - target_visit_ts)) | ||||
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 is not None: | if visit_idx is not None: | ||||
visit = visits[visit_idx] | visit = visits[visit_idx] | ||||
# If multiple visits have the same date, select the one with | |||||
# the largest id. | |||||
while visit_idx < len(visits) - 1 and \ | while visit_idx < len(visits) - 1 and \ | ||||
visit['date'] == visits[visit_idx+1]['date']: | visit['date'] == visits[visit_idx+1]['date']: | ||||
visit_idx = visit_idx + 1 | visit_idx = visit_idx + 1 | ||||
visit = visits[visit_idx] | visit = visits[visit_idx] | ||||
return visit | return visit | ||||
else: | else: | ||||
if 'type' in origin_info and 'url' in origin_info: | if 'type' in origin_info and 'url' in origin_info: | ||||
message = ('Visit with timestamp %s for origin with type %s ' | message = ('Visit with timestamp %s for origin with type %s ' | ||||
'and url %s not found!' % | 'and url %s not found!' % | ||||
(visit_ts, origin_info['type'], origin_info['url'])) | (visit_ts, origin_info['type'], origin_info['url'])) | ||||
else: | else: | ||||
message = ('Visit with timestamp %s for origin with id %s ' | message = ('Visit with timestamp %s for origin with id %s ' | ||||
'not found!' % (visit_ts, origin_info['id'])) | 'not found!' % (visit_ts, origin_info['id'])) | ||||
raise NotFoundExc(message) | raise NotFoundExc(message) |