def save(self, *args, **kwargs): if not self.uuid: self.uuid = uuid4() if not self.pk and self.is_local: if not self.guid: self.guid = str(self.uuid) if not self.fid: self.fid = self.url if not self.fid and not self.handle: raise ValueError("Profile must have either a fid or a handle") if self.handle: # Ensure handle is *always* lowercase self.handle = self.handle.lower() if not validate_handle(self.handle): raise ValueError("Not a valid handle") # Set default pony images if image urls are empty if not self.image_url_small or not self.image_url_medium or not self.image_url_large: ponies = get_pony_urls() for idx, attr in enumerate(["image_url_large", "image_url_medium", "image_url_small"]): if not getattr(self, attr, None): setattr(self, attr, ponies[idx]) # Ensure keys are converted to str before saving self.rsa_private_key = decode_if_bytes(self.rsa_private_key) self.rsa_public_key = decode_if_bytes(self.rsa_public_key) super().save(*args, **kwargs)
def store_magic_envelope_doc(self, payload): """Get the Magic Envelope, trying JSON first.""" try: json_payload = json.loads(decode_if_bytes(payload)) except ValueError: # XML payload xml = unquote_plus(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 test_view_responds_stats_off(self): self.get(NODEINFO_DOCUMENT_PATH) self.response_200() self.assertEqual( json.loads(decode_if_bytes(self.last_response.content))["usage"], {"users": {}} )
def identify_payload(payload): """Try to identify whether this is a Diaspora payload. Try first public message. Then private message. The check if this is a legacy payload. """ # Private encrypted JSON payload try: data = json.loads(decode_if_bytes(payload)) if "encrypted_magic_envelope" in data: return True except Exception: pass # Public XML payload try: xml = etree.fromstring(encode_if_text(payload)) if xml.tag == MAGIC_ENV_TAG: return True except Exception: pass # Legacy XML payload try: xml = unquote_plus(payload) return xml.find('xmlns="%s"' % PROTOCOL_NS) > -1 except Exception: pass return False
def save(self, *args, **kwargs): if not self.uuid: self.uuid = uuid4() if not self.pk and self.is_local: if not self.guid: self.guid = str(self.uuid) if not self.fid: self.fid = self.user.url # Default protocol for all new profiles self.protocol = "activitypub" if not self.fid and not self.handle: raise ValueError("Profile must have either a fid or a handle") if self.handle: # Ensure handle is *always* lowercase self.handle = self.handle.lower() if not validate_handle(self.handle): raise ValueError("Not a valid handle") else: self.handle = None if self.guid == "": self.guid = None # Set default pony images if image urls are empty if not self.image_url_small or not self.image_url_medium or not self.image_url_large: ponies = get_pony_urls() for idx, attr in enumerate( ["image_url_large", "image_url_medium", "image_url_small"]): if not getattr(self, attr, None): setattr(self, attr, ponies[idx]) # Ensure keys are converted to str before saving self.rsa_private_key = decode_if_bytes(self.rsa_private_key) self.rsa_public_key = decode_if_bytes(self.rsa_public_key) # Set default federation endpoints for local users if self.is_local: if not self.inbox_private: self.inbox_private = f"{self.fid}inbox/" if not self.inbox_public: self.inbox_public = f"{settings.SOCIALHOME_URL}{reverse('federate:receive-public')}" super().save(*args, **kwargs)
def save(self, *args, **kwargs): # Protect against empty guids which the search indexing would crash on if not self.guid: raise ValueError("Profile must have a guid!") if not validate_handle(self.handle): raise ValueError("Not a valid handle") # Set default pony images if image urls are empty if not self.image_url_small or not self.image_url_medium or not self.image_url_large: ponies = get_pony_urls() for idx, attr in enumerate(["image_url_large", "image_url_medium", "image_url_small"]): if not getattr(self, attr, None): setattr(self, attr, ponies[idx]) # Ensure handle is *always* lowercase self.handle = self.handle.lower() # Ensure keys are converted to str before saving self.rsa_private_key = decode_if_bytes(self.rsa_private_key) self.rsa_public_key = decode_if_bytes(self.rsa_public_key) super().save(*args, **kwargs)
def identify_request(request: RequestType) -> bool: """ Try to identify whether this is an ActivityPub request. """ # noinspection PyBroadException try: data = json.loads(decode_if_bytes(request.body)) if "@context" in data: return True except Exception: pass return False
def retrieve_and_parse_document(fid: str) -> Optional[Any]: """ Retrieve remote document by ID and return the entity. """ 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) logger.info("retrieve_and_parse_document - found %s entities", len(entities)) if entities: logger.info("retrieve_and_parse_document - using first entity: %s", entities[0]) return entities[0]
def test_view_responds_stats_on(self): self.get(NODEINFO_DOCUMENT_PATH) self.response_200() self.assertEqual( json.loads(decode_if_bytes(self.last_response.content))["usage"], { "users": { "total": User.objects.count(), "activeHalfyear": User.objects.filter(last_login__gte=now() - datetime.timedelta(days=180)).count(), "activeMonth": User.objects.filter(last_login__gte=now() - datetime.timedelta(days=30)).count(), }, "localPosts": Content.objects.filter( author__user__isnull=False, content_type=ContentType.CONTENT).count(), "localComments": Content.objects.filter( author__user__isnull=False, content_type=ContentType.REPLY).count(), } )
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. """ 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 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. """ # 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 test_decode_if_bytes(): assert decode_if_bytes(b"foobar") == "foobar" assert decode_if_bytes("foobar") == "foobar"
def extract_payload(self): payload = decode_if_bytes(self.payload) payload = payload.lstrip().encode("utf-8") self.doc = etree.fromstring(payload) self.author_handle = self.get_sender(self.doc) self.message = self.message_from_doc()