code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
w = cb.width - MENU_WIDTH - 1 h = cb.height - 1 params.plane_w = w params.plane_h = h params.resize(w, h) palette = PALETTES[params.palette][1] if params.reverse_palette: palette = palette[::-1] # draw_gradient(t, 1, 1, w, h, palette, params.dither_type) generated = 0 missing_coords = [] # Check for coordinates that have no value in current plane xs = range(params.plane_x0, params.plane_x0 + params.plane_w - 1) ys = range(params.plane_y0, params.plane_y0 + params.plane_h - 1) for x in xs: for y in ys: if plane[x, y] is None: missing_coords.append((x, y, params)) generated += 1 # Compute all missing values via multiprocessing n_processes = 0 if len(missing_coords) > 0: n_cores = pool._processes n_processes = len(missing_coords) // 256 if n_processes > n_cores: n_processes = n_cores start = time.time() for i, result in enumerate(pool.imap_unordered(compute, missing_coords, chunksize=256)): plane[result[0], result[1]] = result[2] if time.time() - start > 2: if i % 200 == 0: draw_progress_bar(cb, "Render is taking a longer time...", i, len(missing_coords)) cb.refresh() if generated > 0: params.log("Added %d missing cells" % generated) if n_processes > 1: params.log("(Used %d processes)" % n_processes) min_value = 0.0 max_value = params.max_iterations max_iterations = params.max_iterations if params.adaptive_palette: min_value, max_value = plane.extrema(params.plane_x0, params.plane_y0, params.plane_w, params.plane_h) crosshairs_coord = None if params.crosshairs: crosshairs_coord = params.crosshairs_coord # Draw all values in cursebox for x in xs: for y in ys: value = (plane[x, y] + params.palette_offset) % (params.max_iterations + 1) if params.adaptive_palette: # Remap values from (min_value, max_value) to (0, max_iterations) if max_value - min_value > 0: value = ((value - min_value) / (max_value - min_value)) * max_iterations else: value = max_iterations # Dithered mode if params.dither_type < 2: draw_dithered_color(cb, x - params.plane_x0 + 1, y - params.plane_y0 + 1, palette, params.dither_type, value, max_iterations, crosshairs_coord=crosshairs_coord) # 256 colors mode else: draw_color(cb, x - params.plane_x0 + 1, y - params.plane_y0 + 1, value, max_iterations, palette, crosshairs_coord=crosshairs_coord) # Draw bounding box draw_box(cb, 0, 0, w + 1, h + 1)
def draw_panel(cb, pool, params, plane)
Draws the application's main panel, displaying the current Mandelbrot view. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :param plane: Plane containing the current Mandelbrot values. :type plane: plane.Plane
2.838547
2.785504
1.019043
cb.clear() draw_panel(cb, pool, params, plane) update_position(params) # Update Mandelbrot-space coordinates before drawing them draw_menu(cb, params, qwertz) cb.refresh()
def update_display(cb, pool, params, plane, qwertz)
Draws everything. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :param plane: Plane containing the current Mandelbrot values. :type plane: plane.Plane :return:
7.754807
9.211398
0.841871
if is_python3(): import pickle cPickle = pickle else: import cPickle ts = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d_%H-%M-%S") if not os.path.exists("saves/"): os.makedirs("saves/") with open("saves/almonds_%s.params" % ts, "wb") as f: cPickle.dump(params, f) params.log("Current scene saved!")
def save(params)
Saves the current parameters to a file. :param params: Current application parameters. :return:
3.737296
4.00181
0.933901
w, h = screen_resolution() # Re-adapt dimensions to match current plane ratio old_ratio = w / h new_ratio = params.plane_ratio if old_ratio > new_ratio: w = int(h * new_ratio) else: h = int(w / new_ratio) image = Image.new("RGB", (w, h), "white") pixels = image.load() # FIXME: refactor common code to get_palette(params) palette = PALETTES[params.palette][1] if params.reverse_palette: palette = palette[::-1] # All coordinates to be computed as single arguments for processes coords = [(x, y, w, h, params) for x in range(w) for y in range(h)] results = [] # Dispatch work to pool and draw results as they come in for i, result in enumerate(pool.imap_unordered(compute_capture, coords, chunksize=256)): results.append(result) if i % 2000 == 0: draw_progress_bar(cb, "Capturing current scene...", i, w * h) cb.refresh() min_value = 0.0 max_value = params.max_iterations max_iterations = params.max_iterations if params.adaptive_palette: from operator import itemgetter min_value = min(results, key=itemgetter(2))[2] max_value = max(results, key=itemgetter(2))[2] # Draw pixels for result in results: value = result[2] if params.adaptive_palette: # Remap values from (min_value, max_value) to (0, max_iterations) if max_value - min_value > 0: value = ((value - min_value) / (max_value - min_value)) * max_iterations else: value = max_iterations pixels[result[0], result[1]] = get_color(value, params.max_iterations, palette) if not os.path.exists("captures/"): os.makedirs("captures/") ts = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d_%H-%M-%S") filename = "captures/almonds_%s.png" % ts image.save(filename, "PNG") params.log("Current scene captured!") params.log("(Used %d processes)" % pool._processes) open_file(filename)
def capture(cb, pool, params)
Renders and saves a screen-sized picture of the current position. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params
3.399529
3.436499
0.989242
step = params.max_iterations // 20 if step == 0: step = 1 for i in range(0, params.max_iterations, step): params.palette_offset = i draw_panel(cb, pool, params, plane) cb.refresh() params.palette_offset = 0
def cycle(cb, pool, params, plane)
Fun function to do a palette cycling animation. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :param plane: Plane containing the current Mandelbrot values. :type plane: plane.Plane :return:
3.878278
3.788282
1.023756
w = cb.width - MENU_WIDTH - 1 h = cb.height - 1 params.plane_w = w params.plane_h = h params.resize(w, h) zoom(params, 1)
def init_coords(cb, params)
Initializes coordinates and zoom for first use. Loads coordinates from Mandelbrot-space. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :return:
6.085976
6.876446
0.885047
if lower > upper: lower, upper = upper, lower return max(min(upper, n), lower)
def clamp(n, lower, upper)
Restricts the given number to a lower and upper bound (inclusive) :param n: input number :param lower: lower bound (inclusive) :param upper: upper bound (inclusive) :return: clamped number
3.287826
4.919063
0.668385
w = 0 h = 0 try: # Windows import ctypes user32 = ctypes.windll.user32 w, h = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1) except AttributeError: try: # Mac OS X import AppKit size = AppKit.NSScreen.screens()[0].frame().size w, h = int(size.width), int(size.height) except ImportError: try: # Linux import Xlib import Xlib.display display = Xlib.display.Display() root = display.screen().root size = root.get_geometry() w, h = size.width, size.height except ImportError: w = 1920 h = 1080 return w, h
def screen_resolution()
Returns the current screen's resolution. Should be multi-platform. :return: A tuple containing the width and height of the screen.
1.738742
1.755957
0.990196
if sys.platform.startswith("darwin"): subprocess.call(("open", filename)) elif sys.platform == "cygwin": subprocess.call(("cygstart", filename)) elif os.name == "nt": os.system("start %s" % filename) elif os.name == "posix": subprocess.call(("xdg-open", filename))
def open_file(filename)
Multi-platform way to make the OS open a file with its default application
1.876388
1.733148
1.082647
dither = DITHER_TYPES[dither][1] return dither[int(round(value * (len(dither) - 1)))]
def dither_symbol(value, dither)
Returns the appropriate block drawing symbol for the given intensity. :param value: intensity of the color, in the range [0.0, 1.0] :return: dithered symbol representing that intensity
4.348332
5.2286
0.831644
i = n * (len(palette) - 1) / n_max c1 = palette[int(math.floor(i))] c2 = palette[int(math.ceil(i))] value = i - int(math.floor(i)) symbol = dither_symbol(value, dither) if crosshairs_coord is not None: old_symbol = symbol symbol, crosshairs = get_crosshairs_symbol(x, y, old_symbol, crosshairs_coord) if crosshairs: sorted_palette = sort_palette(palette) if old_symbol == DITHER_TYPES[dither][1][0]: c2 = c1 sorted_index = sorted_palette.index(c2) if sorted_index > len(sorted_palette) // 2: c1 = sorted_palette[0] else: c1 = sorted_palette[-1] cb.put(x, y, symbol, c1(), c2())
def draw_dithered_color(cb, x, y, palette, dither, n, n_max, crosshairs_coord=None)
Draws a dithered color block on the terminal, given a palette. :type cb: cursebox.CurseBox
3.118499
3.460598
0.901145
w -= 1 h -= 1 corners = [(x0, y0), (x0 + w, y0), (x0, y0 + h), (x0 + w, y0 + h)] fg = fg() bg = bg() for i, c in enumerate(corners): cb.put(c[0], c[1], BOX_CORNERS[i], fg, bg) for s in h_seps + [0, h]: cb.put(x0 + 1, y0 + s, symbols["BOX_HORIZONTAL"] * (w - 1), fg, bg) for y in range(1, h): for s in v_seps + [0, w]: cb.put(x0 + s, y0 + y, symbols["BOX_VERTICAL"], fg, bg) for s in h_seps: cb.put(x0, y0 + s, symbols["BOX_X_LEFT"], fg, bg) cb.put(x0 + w, y0 + s, symbols["BOX_X_RIGHT"], fg, bg) for s in v_seps: cb.put(x0 + s, y0, symbols["BOX_X_TOP"], fg, bg) cb.put(x0 + s, y0 + h, symbols["BOX_X_BOTTOM"], fg, bg)
def draw_box(cb, x0, y0, w, h, fg=colors.default_fg, bg=colors.default_bg, h_seps=[], v_seps=[])
Draws a box in the given terminal. :type cb: cursebox.CurseBox
2.008811
2.068142
0.971312
m_x = cb.width // 2 m_y = cb.height // 2 w = len(message) + 4 h = 3 draw_box(cb, m_x - w // 2, m_y - 1, w, h) message = " %s " % message i = int((value / max_value) * (len(message) + 2)) message = "$" + message[:i] + "$" + message[i:] draw_text(cb, m_x - w // 2 + 1, m_y, message)
def draw_progress_bar(cb, message, value, max_value)
:type cb: cursebox.Cursebox
2.820565
2.723108
1.035789
z = c if julia_seed is not None: c = julia_seed for iterations in range(max_iterations): z = z * z + c if abs(z) > 1000: return z, iterations return z, max_iterations
def mandelbrot_iterate(c, max_iterations, julia_seed=None)
Returns the number of iterations before escaping the Mandelbrot fractal. :param c: Coordinates as a complex number :type c: complex :param max_iterations: Limit of how many tries are attempted. :return: Tuple containing the last complex number in the sequence and the number of iterations.
2.963381
3.226717
0.918389
n_x = x * 2.0 / params.plane_w * params.plane_ratio - 1.0 n_y = y * 2.0 / params.plane_h - 1.0 mb_x = params.zoom * n_x mb_y = params.zoom * n_y return mb_x, mb_y
def get_coords(x, y, params)
Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary). :param x: X coordinate on the plane. :param y: Y coordinate on the plane. :param params: Current application parameters. :type params: params.Params :return: Tuple containing the re-mapped coordinates in Mandelbrot-space.
3.489644
3.288277
1.061238
mb_x, mb_y = get_coords(x, y, params) mb = mandelbrot_iterate(mb_x + 1j * mb_y, params.max_iterations, params.julia_seed) return mb[1]
def mandelbrot(x, y, params)
Computes the number of iterations of the given plane-space coordinates. :param x: X coordinate on the plane. :param y: Y coordinate on the plane. :param params: Current application parameters. :type params: params.Params :return: Discrete number of iterations.
5.28529
5.935988
0.890381
# FIXME: Figure out why these corrections are necessary or how to make them perfect # Viewport is offset compared to window when capturing without these (found empirically) if params.plane_ratio >= 1.0: x -= params.plane_w else: x += 3.0 * params.plane_w ratio = w / h n_x = x * 2.0 / w * ratio - 1.0 n_y = y * 2.0 / h - 1.0 mb_x = params.zoom * n_x + params.mb_cx mb_y = params.zoom * n_y + params.mb_cy mb = mandelbrot_iterate(mb_x + 1j * mb_y, params.max_iterations, params.julia_seed) z, iterations = mb # Continuous iteration count for no banding # https://en.wikipedia.org/wiki/Mandelbrot_set#Continuous_.28smooth.29_coloring nu = params.max_iterations if iterations < params.max_iterations: nu = iterations + 2 - abs(cmath.log(cmath.log(abs(z)) / cmath.log(params.max_iterations), 2)) return clamp(nu, 0, params.max_iterations)
def mandelbrot_capture(x, y, w, h, params)
Computes the number of iterations of the given pixel-space coordinates, for high-res capture purposes. Contrary to :func:`mandelbrot`, this function returns a continuous number of iterations to avoid banding. :param x: X coordinate on the picture :param y: Y coordinate on the picture :param w: Width of the picture :param h: Height of the picture :param params: Current application parameters. :type params: params.Params :return: Continuous number of iterations.
5.621243
5.387621
1.043363
cx = params.plane_x0 + params.plane_w / 2.0 cy = params.plane_y0 + params.plane_h / 2.0 params.mb_cx, params.mb_cy = get_coords(cx, cy, params)
def update_position(params)
Computes the center of the viewport's Mandelbrot-space coordinates. :param params: Current application parameters. :type params: params.Params
4.060297
3.669543
1.106486
params.zoom /= factor n_x = params.mb_cx / params.zoom n_y = params.mb_cy / params.zoom params.plane_x0 = int((n_x + 1.0) * params.plane_w / (2.0 * params.plane_ratio)) - params.plane_w // 2 params.plane_y0 = int((n_y + 1.0) * params.plane_h / 2.0) - params.plane_h // 2
def zoom(params, factor)
Applies a zoom on the current parameters. Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates. :param params: Current application parameters. :param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom)
3.109484
3.141857
0.989696
self.plane_w = w self.plane_h = h self.plane_ratio = self.char_ratio * w / h if self.crosshairs: self.crosshairs_coord = ((w + 2) // 2, (h + 2) // 2)
def resize(self, w, h)
Used when resizing the plane, resets the plane ratio factor. :param w: New width of the visible section of the plane. :param h: New height of the visible section of the plane.
4.460327
3.893344
1.145629
if sender_handle != entity_handle: logger.warning("sender_handle and entity_handle don't match, aborting! sender_handle: %s, entity_handle: %s", sender_handle, entity_handle) return False return True
def check_sender_and_entity_handle_match(sender_handle, entity_handle)
Ensure that sender and entity handles match. Basically we've already verified the sender is who they say when receiving the payload. However, the sender might be trying to set another author in the payload itself, since Diaspora has the sender in both the payload headers AND the object. We must ensure they're the same.
2.583771
2.512495
1.028369
entities = [] cls = MAPPINGS.get(element.tag) if not cls: return [] attrs = xml_children_as_dict(element) transformed = transform_attributes(attrs, cls) if hasattr(cls, "fill_extra_attributes"): transformed = cls.fill_extra_attributes(transformed) entity = cls(**transformed) # Add protocol name entity._source_protocol = "diaspora" # Save element object to entity for possible later use entity._source_object = etree.tostring(element) # Save receiving id to object if user: entity._receiving_actor_id = user.id if issubclass(cls, DiasporaRelayableMixin): # If relayable, fetch sender key for validation entity._xml_tags = get_element_child_info(element, "tag") if sender_key_fetcher: entity._sender_key = sender_key_fetcher(entity.actor_id) else: profile = retrieve_and_parse_profile(entity.handle) if profile: entity._sender_key = profile.public_key else: # If not relayable, ensure handles match if not check_sender_and_entity_handle_match(sender, entity.handle): return [] try: entity.validate() except ValueError as ex: logger.error("Failed to validate entity %s: %s", entity, ex, extra={ "attrs": attrs, "transformed": transformed, }) return [] # Extract mentions entity._mentions = entity.extract_mentions() # Do child elements for child in element: entity._children.extend(element_to_objects(child, sender, user=user)) # Add to entities list entities.append(entity) return entities
def element_to_objects( element: etree.ElementTree, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None, ) -> List
Transform an Element to a list of entities recursively. Possible child entities are added to each entity ``_children`` list. :param tree: Element :param sender: Payload sender id :param sender_key_fetcher: Function to fetch sender public key. If not given, key will always be fetched over network. The function should take sender handle as the only parameter. :param user: Optional receiving user object. If given, should have an ``id``. :returns: list of entities
4.24306
4.24004
1.000712
doc = etree.fromstring(message) if doc.tag in TAGS: return element_to_objects(doc, sender, sender_key_fetcher, user) return []
def message_to_objects( message: str, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None, ) -> List
Takes in a message extracted by a protocol and maps it to entities. :param message: XML payload :type message: str :param sender: Payload sender id :type message: str :param sender_key_fetcher: Function to fetch sender public key. If not given, key will always be fetched over network. The function should take sender handle as the only parameter. :param user: Optional receiving user object. If given, should have a `handle`. :returns: list of entities
4.330764
4.594588
0.942579
transformed = {} for key, value in attrs.items(): if value is None: value = "" if key == "text": transformed["raw_content"] = value elif key == "author": if cls == DiasporaProfile: # Diaspora Profile XML message contains no GUID. We need the guid. Fetch it. profile = retrieve_and_parse_profile(value) transformed['id'] = value transformed["guid"] = profile.guid else: transformed["actor_id"] = value transformed["handle"] = value elif key == 'guid': if cls != DiasporaProfile: transformed["id"] = value transformed["guid"] = value elif key in ("root_author", "recipient"): transformed["target_id"] = value transformed["target_handle"] = value elif key in ("target_guid", "root_guid", "parent_guid"): transformed["target_id"] = value transformed["target_guid"] = value elif key in ("first_name", "last_name"): values = [attrs.get('first_name'), attrs.get('last_name')] values = [v for v in values if v] transformed["name"] = " ".join(values) elif key == "image_url": if "image_urls" not in transformed: transformed["image_urls"] = {} transformed["image_urls"]["large"] = value elif key == "image_url_small": if "image_urls" not in transformed: transformed["image_urls"] = {} transformed["image_urls"]["small"] = value elif key == "image_url_medium": if "image_urls" not in transformed: transformed["image_urls"] = {} transformed["image_urls"]["medium"] = value elif key == "tag_string": if value: transformed["tag_list"] = value.replace("#", "").split(" ") elif key == "bio": transformed["raw_content"] = value elif key == "searchable": transformed["public"] = True if value == "true" else False elif key in ["target_type"] and cls == DiasporaRetraction: transformed["entity_type"] = DiasporaRetraction.entity_type_from_remote(value) elif key == "remote_photo_path": transformed["remote_path"] = value elif key == "remote_photo_name": transformed["remote_name"] = value elif key == "status_message_guid": transformed["linked_guid"] = value transformed["linked_type"] = "Post" elif key == "author_signature": transformed["signature"] = value elif key in BOOLEAN_KEYS: transformed[key] = True if value == "true" else False elif key in DATETIME_KEYS: transformed[key] = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ") elif key in INTEGER_KEYS: transformed[key] = int(value) else: transformed[key] = value return transformed
def transform_attributes(attrs, cls)
Transform some attribute keys. :param attrs: Properties from the XML :type attrs: dict :param cls: Class of the entity :type cls: class
2.475648
2.516945
0.983592
if getattr(entity, "outbound_doc", None): # If the entity already has an outbound doc, just return the entity as is return entity outbound = None cls = entity.__class__ if cls in [DiasporaPost, DiasporaImage, DiasporaComment, DiasporaLike, DiasporaProfile, DiasporaRetraction, DiasporaContact, DiasporaReshare]: # Already fine outbound = entity elif cls == Post: outbound = DiasporaPost.from_base(entity) elif cls == Comment: outbound = DiasporaComment.from_base(entity) elif cls == Reaction: if entity.reaction == "like": outbound = DiasporaLike.from_base(entity) elif cls == Follow: outbound = DiasporaContact.from_base(entity) elif cls == Profile: outbound = DiasporaProfile.from_base(entity) elif cls == Retraction: outbound = DiasporaRetraction.from_base(entity) elif cls == Share: outbound = DiasporaReshare.from_base(entity) if not outbound: raise ValueError("Don't know how to convert this base entity to Diaspora protocol entities.") if isinstance(outbound, DiasporaRelayableMixin) and not outbound.signature: # Sign by author if not signed yet. We don't want to overwrite any existing signature in the case # that this is being sent by the parent author outbound.sign(private_key) # If missing, also add same signature to `parent_author_signature`. This is required at the moment # in all situations but is apparently being removed. # TODO: remove this once Diaspora removes the extra signature outbound.parent_signature = outbound.signature return outbound
def get_outbound_entity(entity: BaseEntity, private_key: RsaKey)
Get the correct outbound entity for this protocol. We might have to look at entity values to decide the correct outbound entity. If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol. Private key of author is needed to be passed for signing the outbound entity. :arg entity: An entity instance which can be of a base or protocol entity class. :arg private_key: Private key of sender as an RSA object :returns: Protocol specific entity class instance. :raises ValueError: If conversion cannot be done.
3.830079
3.6731
1.042738
props = [] for child in doc: if child.tag not in ["author_signature", "parent_author_signature"]: props.append(getattr(child, attr)) return props
def get_element_child_info(doc, attr)
Get information from child elements of this elementas a list since order is important. Don't include signature tags. :param doc: XML element :param attr: Attribute to get from the elements, for example "tag" or "text".
5.509977
5.905345
0.933049
sig_hash = _create_signature_hash(doc) cipher = PKCS1_v1_5.new(RSA.importKey(public_key)) return cipher.verify(sig_hash, b64decode(signature))
def verify_relayable_signature(public_key, doc, signature)
Verify the signed XML elements to have confidence that the claimed author did actually generate this message.
3.181701
3.14043
1.013142
resource = request.GET.get("resource") if not resource: return HttpResponseBadRequest("No resource found") if not resource.startswith("acct:"): return HttpResponseBadRequest("Invalid resource") handle = resource.replace("acct:", "").lower() profile_func = get_function_from_config("get_profile_function") try: profile = profile_func(handle=handle, request=request) except Exception as exc: logger.warning("rfc7033_webfinger_view - Failed to get profile by handle %s: %s", handle, exc) return HttpResponseNotFound() config = get_configuration() webfinger = RFC7033Webfinger( id=profile.id, handle=profile.handle, guid=profile.guid, base_url=config.get('base_url'), profile_path=get_path_from_url(profile.url), hcard_path=config.get('hcard_path'), atom_path=get_path_from_url(profile.atom_url), search_path=config.get('search_path'), ) return JsonResponse( webfinger.render(), content_type="application/jrd+json", )
def rfc7033_webfinger_view(request, *args, **kwargs)
Django view to generate an RFC7033 webfinger.
2.891956
2.851101
1.01433
webfinger = { "hcard_url": None, } try: doc = json.loads(document) for link in doc["links"]: if link["rel"] == "http://microformats.org/profile/hcard": webfinger["hcard_url"] = link["href"] break else: logger.warning("parse_diaspora_webfinger: found JSON webfinger but it has no hcard href") raise ValueError except Exception: try: xrd = XRD.parse_xrd(document) webfinger["hcard_url"] = xrd.find_link(rels="http://microformats.org/profile/hcard").href except xml.parsers.expat.ExpatError: logger.warning("parse_diaspora_webfinger: found XML webfinger but it fails to parse (ExpatError)") pass return webfinger
def parse_diaspora_webfinger(document)
Parse Diaspora webfinger which is either in JSON format (new) or XRD (old). https://diaspora.github.io/diaspora_federation/discovery/webfinger.html
2.74589
2.645767
1.037843
webfinger = retrieve_and_parse_diaspora_webfinger(handle) document, code, exception = fetch_document(webfinger.get("hcard_url")) if exception: return None return document
def retrieve_diaspora_hcard(handle)
Retrieve a remote Diaspora hCard document. :arg handle: Remote handle to retrieve :return: str (HTML document)
6.606971
7.42382
0.889969
try: host = handle.split("@")[1] except AttributeError: logger.warning("retrieve_and_parse_diaspora_webfinger: invalid handle given: %s", handle) return None document, code, exception = fetch_document( host=host, path="/.well-known/webfinger?resource=acct:%s" % quote(handle), ) if document: return parse_diaspora_webfinger(document) hostmeta = retrieve_diaspora_host_meta(host) if not hostmeta: return None url = hostmeta.find_link(rels="lrdd").template.replace("{uri}", quote(handle)) document, code, exception = fetch_document(url) if exception: return None return parse_diaspora_webfinger(document)
def retrieve_and_parse_diaspora_webfinger(handle)
Retrieve a and parse a remote Diaspora webfinger document. :arg handle: Remote handle to retrieve :returns: dict
3.492596
3.671314
0.951321
document, code, exception = fetch_document(host=host, path="/.well-known/host-meta") if exception: return None xrd = XRD.parse_xrd(document) return xrd
def retrieve_diaspora_host_meta(host)
Retrieve a remote Diaspora host-meta document. :arg host: Host to retrieve from :returns: ``XRD`` instance
6.990147
6.913632
1.011067
element = document.cssselect(selector) if element: return element[0].text return None
def _get_element_text_or_none(document, selector)
Using a CSS selector, get the element and return the text, or None if no element. :arg document: ``HTMLElement`` document :arg selector: CSS selector :returns: str or None
3.072755
5.098471
0.602682
element = document.cssselect(selector) if element: return element[0].get(attribute) return None
def _get_element_attr_or_none(document, selector, attribute)
Using a CSS selector, get the element and return the given attribute value, or None if no element. Args: document (HTMLElement) - HTMLElement document selector (str) - CSS selector attribute (str) - The attribute to get from the element
2.749472
5.609079
0.490182
from federation.entities.diaspora.entities import DiasporaProfile # Circulars doc = html.fromstring(hcard) profile = DiasporaProfile( name=_get_element_text_or_none(doc, ".fn"), image_urls={ "small": _get_element_attr_or_none(doc, ".entity_photo_small .photo", "src"), "medium": _get_element_attr_or_none(doc, ".entity_photo_medium .photo", "src"), "large": _get_element_attr_or_none(doc, ".entity_photo .photo", "src"), }, public=True if _get_element_text_or_none(doc, ".searchable") == "true" else False, id=handle, handle=handle, guid=_get_element_text_or_none(doc, ".uid"), public_key=_get_element_text_or_none(doc, ".key"), ) return profile
def parse_profile_from_hcard(hcard: str, handle: str)
Parse all the fields we can from a hCard document to get a Profile. :arg hcard: HTML hcard document (str) :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance
2.949608
2.734819
1.078539
if not validate_handle(handle): return _username, domain = handle.split("@") url = get_fetch_content_endpoint(domain, entity_type.lower(), guid) document, status_code, error = fetch_document(url) if status_code == 200: request = RequestType(body=document) _sender, _protocol, entities = handle_receive(request, sender_key_fetcher=sender_key_fetcher) if len(entities) > 1: logger.warning("retrieve_and_parse_content - more than one entity parsed from remote even though we" "expected only one! ID %s", guid) if entities: return entities[0] return elif status_code == 404: logger.warning("retrieve_and_parse_content - remote content %s not found", guid) return if error: raise error raise Exception("retrieve_and_parse_content - unknown problem when fetching document: %s, %s, %s" % ( document, status_code, error, ))
def retrieve_and_parse_content( guid: str, handle: str, entity_type: str, sender_key_fetcher: Callable[[str], str]=None, )
Retrieve remote content and return an Entity class instance. This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive". :param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used to fetch the profile and the key. Function must take handle as only parameter and return a public key. :returns: Entity object instance or ``None``
4.442579
4.27579
1.039008
hcard = retrieve_diaspora_hcard(handle) if not hcard: return None profile = parse_profile_from_hcard(hcard, handle) try: profile.validate() except ValueError as ex: logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s", profile, ex) return None return profile
def retrieve_and_parse_profile(handle)
Retrieve the remote user and return a Profile object. :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.Profile`` instance or None
4.160697
4.76439
0.873291
_username, domain = id.split("@") return "https://%s/receive/users/%s" % (domain, guid)
def get_private_endpoint(id: str, guid: str) -> str
Get remote endpoint for delivering private payloads.
12.037344
8.204505
1.467163
if dt.tzinfo is None: return dt.replace(tzinfo=tz or tzlocal()) else: return dt
def ensure_timezone(dt, tz=None)
Make sure the datetime <dt> has a timezone set, using timezone <tz> if it doesn't. <tz> defaults to the local timezone.
2.848695
2.934924
0.970619
for obj in struct: for k, v in obj.items(): etree.SubElement(node, k).text = v
def struct_to_xml(node, struct)
Turn a list of dicts into XML nodes with tag names taken from the dict keys and element text taken from dict values. This is a list of dicts so that the XML nodes can be ordered in the XML output.
4.00261
3.493994
1.145569
from federation.entities.diaspora.mappers import get_outbound_entity diaspora_entity = get_outbound_entity(entity, private_key) xml = diaspora_entity.to_xml() return "<XML><post>%s</post></XML>" % etree.tostring(xml).decode("utf-8")
def get_full_xml_representation(entity, private_key)
Get full XML representation of an entity. This contains the <XML><post>..</post></XML> wrapper. Accepts either a Base entity or a Diaspora entity. Author `private_key` must be given so that certain entities can be signed.
4.898499
3.712374
1.319506
element = doc.find(".//%s" % tag) if element is None: element = etree.SubElement(doc, tag) element.text = value
def add_element_to_doc(doc, tag, value)
Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist.
2.470879
1.97485
1.251173
if template == "diaspora": hostmeta = DiasporaHostMeta(*args, **kwargs) else: hostmeta = BaseHostMeta(*args, **kwargs) return hostmeta.render()
def generate_host_meta(template=None, *args, **kwargs)
Generate a host-meta XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document (str)
3.520036
3.235153
1.088059
if template == "diaspora": webfinger = DiasporaWebFinger(*args, **kwargs) else: webfinger = BaseLegacyWebFinger(*args, **kwargs) return webfinger.render()
def generate_legacy_webfinger(template=None, *args, **kwargs)
Generate a legacy webfinger XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document (str)
3.211378
2.978874
1.078051
return { "version": "1.0", "server": { "baseUrl": kwargs['server']['baseUrl'], "name": kwargs['server']['name'], "software": kwargs['server']['software'], "version": kwargs['server']['version'], }, "organization": { "name": kwargs.get('organization', {}).get('name', None), "contact": kwargs.get('organization', {}).get('contact', None), "account": kwargs.get('organization', {}).get('account', None), }, "protocols": kwargs.get('protocols', ["diaspora"]), "relay": kwargs.get('relay', ''), "services": { "inbound": kwargs.get('service', {}).get('inbound', []), "outbound": kwargs.get('service', {}).get('outbound', []), }, "openRegistrations": kwargs['openRegistrations'], "usage": { "users": { "total": kwargs.get('usage', {}).get('users', {}).get('total'), "activeHalfyear": kwargs.get('usage', {}).get('users', {}).get('activeHalfyear'), "activeMonth": kwargs.get('usage', {}).get('users', {}).get('activeMonth'), "activeWeek": kwargs.get('usage', {}).get('users', {}).get('activeWeek'), }, "localPosts": kwargs.get('usage', {}).get('localPosts'), "localComments": kwargs.get('usage', {}).get('localComments'), } }
def generate_nodeinfo2_document(**kwargs)
Generate a NodeInfo2 document. Pass in a dictionary as per NodeInfo2 1.0 schema: https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json Minimum required schema: {server: baseUrl name software version } openRegistrations Protocols default will match what this library supports, ie "diaspora" currently. :return: dict :raises: KeyError on missing required items
2.180421
1.865224
1.168986
if template == "diaspora": hcard = DiasporaHCard(**kwargs) else: raise NotImplementedError() return hcard.render()
def generate_hcard(template=None, **kwargs)
Generate a hCard document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: HTML document (str)
4.236336
4.286415
0.988317
# TODO add support for AP protocol_name = "diaspora" if not guid: guid = id utils = importlib.import_module("federation.utils.%s" % protocol_name) return utils.retrieve_and_parse_content( guid=guid, handle=handle, entity_type=entity_type, sender_key_fetcher=sender_key_fetcher, )
def retrieve_remote_content( id: str, guid: str=None, handle: str=None, entity_type: str=None, sender_key_fetcher: Callable[[str], str]=None, )
Retrieve remote content and return an Entity object. Currently, due to no other protocols supported, always use the Diaspora protocol. :param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used to fetch the profile and the key. Function must take handle as only parameter and return a public key. :returns: Entity class instance or ``None``
4.603902
4.447706
1.035118
protocol = identify_protocol_by_id(id) utils = importlib.import_module(f"federation.utils.{protocol.PROTOCOL_NAME}") return utils.retrieve_and_parse_profile(id)
def retrieve_remote_profile(id: str) -> Optional[Profile]
High level retrieve profile method. Retrieve the profile from a remote location, using protocol based on the given ID.
6.700922
6.262103
1.070075
logger.debug("handle_receive: processing request: %s", request) found_protocol = identify_protocol_by_request(request) logger.debug("handle_receive: using protocol %s", found_protocol.PROTOCOL_NAME) protocol = found_protocol.Protocol() sender, message = protocol.receive( request, user, sender_key_fetcher, skip_author_verification=skip_author_verification) logger.debug("handle_receive: sender %s, message %s", sender, message) mappers = importlib.import_module("federation.entities.%s.mappers" % found_protocol.PROTOCOL_NAME) entities = mappers.message_to_objects(message, sender, sender_key_fetcher, user) logger.debug("handle_receive: entities %s", entities) return sender, found_protocol.PROTOCOL_NAME, entities
def handle_receive( request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False ) -> Tuple[str, str, List]
Takes a request and passes it to the correct protocol. Returns a tuple of: - sender id - protocol name - list of entities NOTE! The returned sender is NOT necessarily the *author* of the entity. By sender here we're talking about the sender of the *request*. If this object is being relayed by the sender, the author could actually be a different identity. :arg request: Request object of type RequestType - note not a HTTP request even though the structure is similar :arg user: User that will be passed to `protocol.receive` (only required on private encrypted content) MUST have a `private_key` and `id` if given. :arg sender_key_fetcher: Function that accepts sender handle and returns public key (optional) :arg skip_author_verification: Don't verify sender (test purposes, false default) :returns: Tuple of sender id, protocol name and list of entity objects
3.153197
2.683699
1.174944
return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None
def identify_id(id: str) -> bool
Try to identify whether this is an ActivityPub ID.
4.938891
3.106537
1.589838
# noinspection PyBroadException try: data = json.loads(decode_if_bytes(request.body)) if "@context" in data: return True except Exception: pass return False
def identify_request(request: RequestType) -> bool
Try to identify whether this is an ActivityPub request.
4.332961
3.511626
1.23389
if hasattr(entity, "outbound_doc") and entity.outbound_doc is not None: # Use pregenerated outbound document rendered = entity.outbound_doc else: rendered = entity.to_as2() return rendered
def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]
Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties. :param to_user_key: (Optional) Public key of user we're sending a private payload to. :returns: dict or string depending on if private or public payload.
8.173697
9.078632
0.900323
self.user = user self.get_contact_key = sender_key_fetcher self.payload = json.loads(decode_if_bytes(request.body)) self.request = request self.extract_actor() # Verify the message is from who it claims to be if not skip_author_verification: self.verify_signature() return self.actor, self.payload
def receive( self, request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False) -> Tuple[str, dict]
Receive a request. For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified.
4.935153
4.810794
1.02585
configuration = { "get_object_function": None, "hcard_path": "/hcard/users/", "nodeinfo2_function": None, "process_payload_function": None, "search_path": None, # TODO remove or default to True once AP support is more ready "activitypub": False, } configuration.update(settings.FEDERATION) if not all([ "get_private_key_function" in configuration, "get_profile_function" in configuration, "base_url" in configuration, ]): raise ImproperlyConfigured("Missing required FEDERATION settings, please check documentation.") return configuration
def get_configuration()
Combine defaults with the Django configuration.
7.649868
7.334478
1.043001
config = get_configuration() func_path = config.get(item) module_path, func_name = func_path.rsplit(".", 1) module = importlib.import_module(module_path) func = getattr(module, func_name) return func
def get_function_from_config(item)
Import the function to get profile by handle.
2.23515
2.055894
1.087191
from federation.utils.activitypub import retrieve_and_parse_profile # Circulars try: from federation.utils.django import get_function_from_config except ImportError: logger.warning("ActivitypubFollow.post_receive - Unable to send automatic Accept back, only supported on " "Django currently") return get_private_key_function = get_function_from_config("get_private_key_function") key = get_private_key_function(self.target_id) if not key: logger.warning("ActivitypubFollow.post_receive - Failed to send automatic Accept back: could not find " "profile to sign it with") return accept = ActivitypubAccept( activity_id=f"{self.target_id}#accept-{uuid.uuid4()}", actor_id=self.target_id, target_id=self.activity_id, ) try: profile = retrieve_and_parse_profile(self.actor_id) except Exception: profile = None if not profile: logger.warning("ActivitypubFollow.post_receive - Failed to fetch remote profile for sending back Accept") return try: handle_send( accept, UserType(id=self.target_id, private_key=key), recipients=[{ "fid": profile.inboxes["private"], "protocol": "activitypub", "public": False, }], ) except Exception: logger.exception("ActivitypubFollow.post_receive - Failed to send Accept back")
def post_receive(self) -> None
Post receive hook - send back follow ack.
4.747478
4.559222
1.041291
document, status_code, ex = fetch_document(fid, extra_headers={'accept': 'application/activity+json'}) if document: document = json.loads(decode_if_bytes(document)) entities = message_to_objects(document, fid) if entities: return entities[0]
def retrieve_and_parse_document(fid: str) -> Optional[Any]
Retrieve remote document by ID and return the entity.
6.963616
6.104089
1.140812
profile = retrieve_and_parse_document(fid) if not profile: return try: profile.validate() except ValueError as ex: logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s", profile, ex) return return profile
def retrieve_and_parse_profile(fid: str) -> Optional[ActivitypubProfile]
Retrieve the remote fid and return a Profile object.
4.193529
4.011246
1.045443
# type: (str, Union[str, RequestType]) -> str for protocol_name in PROTOCOLS: protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol") if getattr(protocol, f"identify_{method}")(value): return protocol else: raise NoSuitableProtocolFoundError()
def identify_protocol(method, value)
Loop through protocols, import the protocol module and try to identify the id or request.
4.559424
4.122902
1.105877
# Private encrypted JSON payload try: data = json.loads(decode_if_bytes(request.body)) if "encrypted_magic_envelope" in data: return True except Exception: pass # Public XML payload try: xml = etree.fromstring(encode_if_text(request.body)) if xml.tag == MAGIC_ENV_TAG: return True except Exception: pass return False
def identify_request(request: RequestType)
Try to identify whether this is a Diaspora request. Try first public message. Then private message. The check if this is a legacy payload.
5.219907
4.481296
1.164821
private_key = self._get_user_key() return EncryptedPayload.decrypt(payload=payload, private_key=private_key)
def get_json_payload_magic_envelope(self, payload)
Encrypted JSON payload
7.228609
5.91897
1.221261
try: json_payload = json.loads(decode_if_bytes(payload)) except ValueError: # XML payload xml = unquote(decode_if_bytes(payload)) xml = xml.lstrip().encode("utf-8") logger.debug("diaspora.protocol.store_magic_envelope_doc: xml payload: %s", xml) self.doc = etree.fromstring(xml) else: logger.debug("diaspora.protocol.store_magic_envelope_doc: json payload: %s", json_payload) self.doc = self.get_json_payload_magic_envelope(json_payload)
def store_magic_envelope_doc(self, payload)
Get the Magic Envelope, trying JSON first.
3.040919
2.928366
1.038435
self.user = user self.get_contact_key = sender_key_fetcher self.store_magic_envelope_doc(request.body) # Open payload and get actual message self.content = self.get_message_content() # Get sender handle self.sender_handle = self.get_sender() # Verify the message is from who it claims to be if not skip_author_verification: self.verify_signature() return self.sender_handle, self.content
def receive( self, request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False) -> Tuple[str, str]
Receive a payload. For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified.
6.027648
5.917463
1.01862
body = self.doc.find( ".//{http://salmon-protocol.org/ns/magic-env}data").text body = urlsafe_b64decode(body.encode("ascii")) logger.debug("diaspora.protocol.get_message_content: %s", body) return body
def get_message_content(self)
Given the Slap XML, extract out the payload.
9.804121
8.134549
1.205245
if self.get_contact_key: sender_key = self.get_contact_key(self.sender_handle) else: sender_key = fetch_public_key(self.sender_handle) if not sender_key: raise NoSenderKeyFoundError("Could not find a sender contact to retrieve key") MagicEnvelope(doc=self.doc, public_key=sender_key, verify=True)
def verify_signature(self)
Verify the signed XML elements to have confidence that the claimed author did actually generate this message.
6.241685
5.719914
1.09122
if entity.outbound_doc is not None: # Use pregenerated outbound document xml = entity.outbound_doc else: xml = entity.to_xml() me = MagicEnvelope(etree.tostring(xml), private_key=from_user.private_key, author_handle=from_user.handle) rendered = me.render() if to_user_key: return EncryptedPayload.encrypt(rendered, to_user_key) return rendered
def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]
Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties. :param to_user_key: (Optional) Public key of user we're sending a private payload to. :returns: dict or string depending on if private or public payload.
6.179458
6.033902
1.024123
if self.reaction not in self._reaction_valid_values: raise ValueError("reaction should be one of: {valid}".format( valid=", ".join(self._reaction_valid_values) ))
def validate_reaction(self)
Ensure reaction is of a certain type. Mainly for future expansion.
3.865012
3.568503
1.083091
if self.relationship not in self._relationship_valid_values: raise ValueError("relationship should be one of: {valid}".format( valid=", ".join(self._relationship_valid_values) ))
def validate_relationship(self)
Ensure relationship is of a certain type.
3.588706
2.882423
1.245031
def inner(request, *args, **kwargs): def get(request, *args, **kwargs): # TODO remove once AP support is more ready config = get_configuration() if not config.get("activitypub"): return func(request, *args, **kwargs) fallback = True accept = request.META.get('HTTP_ACCEPT', '') for content_type in ( 'application/json', 'application/activity+json', 'application/ld+json', ): if accept.find(content_type) > -1: fallback = False break if fallback: return func(request, *args, **kwargs) get_object_function = get_function_from_config('get_object_function') obj = get_object_function(request) if not obj: return HttpResponseNotFound() as2_obj = obj.as_protocol('activitypub') return JsonResponse(as2_obj.to_as2(), content_type='application/activity+json') def post(request, *args, **kwargs): process_payload_function = get_function_from_config('process_payload_function') result = process_payload_function(request) if result: return JsonResponse({}, content_type='application/json', status=202) else: return JsonResponse({"result": "error"}, content_type='application/json', status=400) if request.method == 'GET': return get(request, *args, **kwargs) elif request.method == 'POST' and request.path.endswith('/inbox/'): return post(request, *args, **kwargs) return HttpResponse(status=405) return inner
def activitypub_object_view(func)
Generic ActivityPub object view decorator. Takes an ID and fetches it using the provided function. Renders the ActivityPub object in JSON if the object is found. Falls back to decorated view, if the content type doesn't match.
2.654415
2.70106
0.982731
entities = [] cls = MAPPINGS.get(payload.get('type')) if not cls: return [] transformed = transform_attributes(payload, cls) entity = cls(**transformed) if hasattr(entity, "post_receive"): entity.post_receive() entities.append(entity) return entities
def element_to_objects(payload: Dict) -> List
Transform an Element to a list of entities recursively.
5.170859
4.726573
1.093998
if getattr(entity, "outbound_doc", None): # If the entity already has an outbound doc, just return the entity as is return entity outbound = None cls = entity.__class__ if cls in [ActivitypubAccept, ActivitypubFollow, ActivitypubProfile]: # Already fine outbound = entity elif cls == Accept: outbound = ActivitypubAccept.from_base(entity) elif cls == Follow: outbound = ActivitypubFollow.from_base(entity) elif cls == Profile: outbound = ActivitypubProfile.from_base(entity) if not outbound: raise ValueError("Don't know how to convert this base entity to ActivityPub protocol entities.") # TODO LDS signing # if isinstance(outbound, DiasporaRelayableMixin) and not outbound.signature: # # Sign by author if not signed yet. We don't want to overwrite any existing signature in the case # # that this is being sent by the parent author # outbound.sign(private_key) # # If missing, also add same signature to `parent_author_signature`. This is required at the moment # # in all situations but is apparently being removed. # # TODO: remove this once Diaspora removes the extra signature # outbound.parent_signature = outbound.signature return outbound
def get_outbound_entity(entity: BaseEntity, private_key)
Get the correct outbound entity for this protocol. We might have to look at entity values to decide the correct outbound entity. If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol. Private key of author is needed to be passed for signing the outbound entity. :arg entity: An entity instance which can be of a base or protocol entity class. :arg private_key: Private key of sender in str format :returns: Protocol specific entity class instance. :raises ValueError: If conversion cannot be done.
6.421063
6.08176
1.05579
# We only really expect one element here for ActivityPub. return element_to_objects(message)
def message_to_objects( message: Dict, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None, ) -> List
Takes in a message extracted by a protocol and maps it to entities.
54.12751
41.565632
1.302218
attributes = [] validates = [] # Collect attributes and validation methods for attr in dir(self): if not attr.startswith("_"): attr_type = type(getattr(self, attr)) if attr_type != "method": if getattr(self, "validate_{attr}".format(attr=attr), None): validates.append(getattr(self, "validate_{attr}".format(attr=attr))) attributes.append(attr) self._validate_empty_attributes(attributes) self._validate_required(attributes) self._validate_attributes(validates) self._validate_children() self._validate_signatures()
def validate(self)
Do validation. 1) Check `_required` have been given 2) Make sure all attrs in required have a non-empty value 3) Loop through attributes and call their `validate_<attr>` methods, if any. 4) Validate allowed children 5) Validate signatures
3.20788
2.657452
1.207126
required_fulfilled = set(self._required).issubset(set(attributes)) if not required_fulfilled: raise ValueError( "Not all required attributes fulfilled. Required: {required}".format(required=set(self._required)) )
def _validate_required(self, attributes)
Ensure required attributes are present.
4.183239
3.736502
1.11956
attrs_to_check = set(self._required) & set(attributes) for attr in attrs_to_check: value = getattr(self, attr) # We should always have a value here if value is None or value == "": raise ValueError( "Attribute %s cannot be None or an empty string since it is required." % attr )
def _validate_empty_attributes(self, attributes)
Check that required attributes are not empty.
3.876076
3.446497
1.124642
for child in self._children: if child.__class__ not in self._allowed_children: raise ValueError( "Child %s is not allowed as a children for this %s type entity." % ( child, self.__class__ ) )
def _validate_children(self)
Check that the children we have are allowed here.
4.21513
3.362582
1.253539
if self.participation not in self._participation_valid_values: raise ValueError("participation should be one of: {valid}".format( valid=", ".join(self._participation_valid_values) ))
def validate_participation(self)
Ensure participation is of a certain type.
3.536795
2.831213
1.249215
if not self.raw_content: return set() return {word.strip("#").lower() for word in self.raw_content.split() if word.startswith("#") and len(word) > 1}
def tags(self)
Returns a `set` of unique tags contained in `raw_content`.
3.947916
2.433268
1.622475
mappers = importlib.import_module(f"federation.entities.{protocol_name}.mappers") protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol") protocol = protocol.Protocol() outbound_entity = mappers.get_outbound_entity(entity, author_user.private_key) if parent_user: outbound_entity.sign_with_parent(parent_user.private_key) send_as_user = parent_user if parent_user else author_user data = protocol.build_send(entity=outbound_entity, from_user=send_as_user, to_user_key=to_user_key) return data
def handle_create_payload( entity: BaseEntity, author_user: UserType, protocol_name: str, to_user_key: RsaKey = None, parent_user: UserType = None, ) -> str
Create a payload with the given protocol. Any given user arguments must have ``private_key`` and ``handle`` attributes. :arg entity: Entity object to send. Can be a base entity or a protocol specific one. :arg author_user: User authoring the object. :arg protocol_name: Protocol to create payload for. :arg to_user_key: Public key of user private payload is being sent to, required for private payloads. :arg parent_user: (Optional) User object of the parent object, if there is one. This must be given for the Diaspora protocol if a parent object exists, so that a proper ``parent_author_signature`` can be generated. If given, the payload will be sent as this user. :returns: Built payload message (str)
3.269735
3.097732
1.055525
key_id = doc.find(".//{%s}sig" % NAMESPACE).get("key_id") return urlsafe_b64decode(key_id).decode("utf-8")
def get_sender(doc)
Get the key_id from the `sig` element which contains urlsafe_b64encoded Diaspora handle. :param doc: ElementTree document :returns: Diaspora handle
7.303446
3.790582
1.926735
doc = etree.fromstring(self.message) self.payload = etree.tostring(doc, encoding="utf-8") self.payload = urlsafe_b64encode(self.payload).decode("ascii") return self.payload
def create_payload(self)
Create the payload doc. Returns: str
3.368608
4.010933
0.839856
sig_contents = \ self.payload + "." + \ b64encode(b"application/xml").decode("ascii") + "." + \ b64encode(b"base64url").decode("ascii") + "." + \ b64encode(b"RSA-SHA256").decode("ascii") sig_hash = SHA256.new(sig_contents.encode("ascii")) cipher = PKCS1_v1_5.new(self.private_key) sig = urlsafe_b64encode(cipher.sign(sig_hash)) key_id = urlsafe_b64encode(bytes(self.author_handle, encoding="utf-8")) return sig, key_id
def _build_signature(self)
Create the signature using the private key.
2.967874
2.84388
1.0436
if not self.public_key: self.fetch_public_key() data = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}data").text sig = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}sig").text sig_contents = '.'.join([ data, b64encode(b"application/xml").decode("ascii"), b64encode(b"base64url").decode("ascii"), b64encode(b"RSA-SHA256").decode("ascii") ]) sig_hash = SHA256.new(sig_contents.encode("ascii")) cipher = PKCS1_v1_5.new(RSA.importKey(self.public_key)) if not cipher.verify(sig_hash, urlsafe_b64decode(sig)): raise SignatureVerificationError("Signature cannot be verified using the given public key")
def verify(self)
Verify Magic Envelope document against public key.
3.250741
2.961211
1.097774
if not hasattr(self, "raw_content"): return set() mentions = re.findall(r'@{[^;]+; [\w.-]+@[^}]+}', self.raw_content) if not mentions: return set() mentions = {s.split(';')[1].strip(' }') for s in mentions} mentions = {s for s in mentions} return mentions
def extract_mentions(self)
Extract mentions from an entity with ``raw_content``. :return: set
4.635924
4.397446
1.054231
iplookup = ipdata.ipdata() data = iplookup.lookup(ip) if data.get('status') != 200: return '' return data.get('response', {}).get('country_code', '')
def fetch_country_by_ip(ip)
Fetches country code by IP Returns empty string if the request fails in non-200 code. Uses the ipdata.co service which has the following rules: * Max 1500 requests per day See: https://ipdata.co/docs.html#python-library
4.321236
3.580608
1.206844
if not url and not host: raise ValueError("Need url or host.") logger.debug("fetch_document: url=%s, host=%s, path=%s, timeout=%s, raise_ssl_errors=%s", url, host, path, timeout, raise_ssl_errors) headers = {'user-agent': USER_AGENT} if extra_headers: headers.update(extra_headers) if url: # Use url since it was given logger.debug("fetch_document: trying %s", url) try: response = requests.get(url, timeout=timeout, headers=headers) logger.debug("fetch_document: found document, code %s", response.status_code) return response.text, response.status_code, None except RequestException as ex: logger.debug("fetch_document: exception %s", ex) return None, None, ex # Build url with some little sanitizing host_string = host.replace("http://", "").replace("https://", "").strip("/") path_string = path if path.startswith("/") else "/%s" % path url = "https://%s%s" % (host_string, path_string) logger.debug("fetch_document: trying %s", url) try: response = requests.get(url, timeout=timeout, headers=headers) logger.debug("fetch_document: found document, code %s", response.status_code) response.raise_for_status() return response.text, response.status_code, None except (HTTPError, SSLError, ConnectionError) as ex: if isinstance(ex, SSLError) and raise_ssl_errors: logger.debug("fetch_document: exception %s", ex) return None, None, ex # Try http then url = url.replace("https://", "http://") logger.debug("fetch_document: trying %s", url) try: response = requests.get(url, timeout=timeout, headers=headers) logger.debug("fetch_document: found document, code %s", response.status_code) response.raise_for_status() return response.text, response.status_code, None except RequestException as ex: logger.debug("fetch_document: exception %s", ex) return None, None, ex except RequestException as ex: logger.debug("fetch_document: exception %s", ex) return None, None, ex
def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None)
Helper method to fetch remote document. Must be given either the ``url`` or ``host``. If ``url`` is given, only that will be tried without falling back to http from https. If ``host`` given, `path` will be added to it. Will fall back to http on non-success status code. :arg url: Full url to fetch, including protocol :arg host: Domain part only without path or protocol :arg path: Path without domain (defaults to "/") :arg timeout: Seconds to wait for response (defaults to 10) :arg raise_ssl_errors: Pass False if you want to try HTTP even for sites with SSL errors (default True) :returns: Tuple of document (str or None), status code (int or None) and error (an exception class instance or None) :raises ValueError: If neither url nor host are given as parameters
1.739863
1.693833
1.027175
try: ip = socket.gethostbyname(host) except socket.gaierror: return '' return ip
def fetch_host_ip(host: str) -> str
Fetch ip by host
3.48891
2.691251
1.296389
ip = fetch_host_ip(host) if not host: return '', '' country = fetch_country_by_ip(ip) return ip, country
def fetch_host_ip_and_country(host: str) -> Tuple
Fetch ip and country by host
4.646923
3.492777
1.330438
MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() __D = r'(?P<day>\d{2})' __D2 = r'(?P<day>[ \d]\d)' __M = r'(?P<mon>\w{3})' __Y = r'(?P<year>\d{4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) # email.utils.parsedate() does the job for RFC1123 dates; unfortunately # RFC7231 makes it mandatory to support RFC850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: year = int(m.group('year')) if year < 100: if year < 70: year += 2000 else: year += 1900 month = MONTHS.index(m.group('mon').lower()) + 1 day = int(m.group('day')) hour = int(m.group('hour')) min = int(m.group('min')) sec = int(m.group('sec')) result = datetime.datetime(year, month, day, hour, min, sec) return calendar.timegm(result.utctimetuple()) except Exception as exc: raise ValueError("%r is not a valid date" % date) from exc
def parse_http_date(date)
Parse a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC. Implementation copied from Django. https://github.com/django/django/blob/master/django/utils/http.py#L157 License: BSD 3-clause
2.049644
2.055692
0.997058
logger.debug("send_document: url=%s, data=%s, timeout=%s", url, data, timeout) headers = CaseInsensitiveDict({ 'User-Agent': USER_AGENT, }) if "headers" in kwargs: # Update from kwargs headers.update(kwargs.get("headers")) kwargs.update({ "data": data, "timeout": timeout, "headers": headers }) try: response = requests.post(url, *args, **kwargs) logger.debug("send_document: response status code %s", response.status_code) return response.status_code, None except RequestException as ex: logger.debug("send_document: exception %s", ex) return None, ex
def send_document(url, data, timeout=10, *args, **kwargs)
Helper method to send a document via POST. Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``. :arg url: Full url to send to, including protocol :arg data: Dictionary (will be form-encoded), bytes, or file-like object to send in the body :arg timeout: Seconds to wait for response (defaults to 10) :returns: Tuple of status code (int or None) and error (exception class instance or None)
2.368992
2.325772
1.018583
key = private_key.exportKey() return HTTPSignatureHeaderAuth( headers=["(request-target)", "user-agent", "host", "date"], algorithm="rsa-sha256", key=key, key_id=private_key_id, )
def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth
Get HTTP signature authentication for a request.
3.269014
3.211924
1.017774
key = encode_if_text(public_key) date_header = request.headers.get("Date") if not date_header: raise ValueError("Rquest Date header is missing") ts = parse_http_date(date_header) dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc) delta = datetime.timedelta(seconds=30) now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) if dt < now - delta or dt > now + delta: raise ValueError("Request Date is too far in future or past") HTTPSignatureHeaderAuth.verify(request, key_resolver=lambda **kwargs: key)
def verify_request_signature(request: RequestType, public_key: Union[str, bytes])
Verify HTTP signature in request against a public key.
3.548759
3.281456
1.081459
element = etree.Element(self._tag_name) struct_to_xml(element, [ {"text": self.raw_content}, {"guid": self.guid}, {"author": self.handle}, {"public": "true" if self.public else "false"}, {"created_at": format_dt(self.created_at)}, {"provider_display_name": self.provider_display_name}, ]) return element
def to_xml(self)
Convert to XML message.
4.565282
4.427685
1.031077
element = etree.Element(self._tag_name) struct_to_xml(element, [ {"author": self.handle}, {"recipient": self.target_handle}, {"following": "true" if self.following else "false"}, {"sharing": "true" if self.following else "false"}, ]) return element
def to_xml(self)
Convert to XML message.
6.197326
5.629129
1.100939
element = etree.Element(self._tag_name) struct_to_xml(element, [ {"author": self.handle}, {"first_name": self.name}, {"last_name": ""}, # We only have one field - splitting it would be artificial {"image_url": self.image_urls["large"]}, {"image_url_small": self.image_urls["small"]}, {"image_url_medium": self.image_urls["medium"]}, {"gender": self.gender}, {"bio": self.raw_content}, {"location": self.location}, {"searchable": "true" if self.public else "false"}, {"nsfw": "true" if self.nsfw else "false"}, {"tag_string": " ".join(["#%s" % tag for tag in self.tag_list])}, ]) return element
def to_xml(self)
Convert to XML message.
4.194446
4.139926
1.013169
element = etree.Element(self._tag_name) struct_to_xml(element, [ {"author": self.handle}, {"target_guid": self.target_guid}, {"target_type": DiasporaRetraction.entity_type_to_remote(self.entity_type)}, ]) return element
def to_xml(self)
Convert to XML message.
9.366492
8.998362
1.040911
if value in DiasporaRetraction.mapped.values(): values = list(DiasporaRetraction.mapped.values()) index = values.index(value) return list(DiasporaRetraction.mapped.keys())[index] return value
def entity_type_to_remote(value)
Convert entity type between our Entity names and Diaspora names.
4.962214
3.663752
1.354408
attributes = {} cls = entity.__class__ for attr, _ in inspect.getmembers(cls, lambda o: not isinstance(o, property) and not inspect.isroutine(o)): if not attr.startswith("_"): attributes[attr] = getattr(entity, attr) return attributes
def get_base_attributes(entity)
Build a dict of attributes of an entity. Returns attributes and their values, ignoring any properties, functions and anything that starts with an underscore.
2.680027
2.585156
1.036698
val = block_size - len(inp) % block_size if val == 0: return inp + (bytes([block_size]) * block_size) else: return inp + (bytes([val]) * val)
def pkcs7_pad(inp, block_size)
Using the PKCS#7 padding scheme, pad <inp> to be a multiple of <block_size> bytes. Ruby's AES encryption pads with this scheme, but pycrypto doesn't support it. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
2.522226
3.009272
0.838151
if isinstance(data, str): return data[0:-ord(data[-1])] else: return data[0:-data[-1]]
def pkcs7_unpad(data)
Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
2.530672
2.583324
0.979618