import pygame #Impordime pygame'i

#Defineerime funktsiooni, mis joonistab ruudustiku
def draw_grid(screen, ruudu_suurus, read, veerud, joone_värv):
    for i in range(read): #Esimene tsükel, mis käib läbi kõik read
        for j in range(veerud): #Teine tsükel, mis käib läbi kõik veerud
            rect = pygame.Rect(j * ruudu_suurus, i * ruudu_suurus, ruudu_suurus, ruudu_suurus) #Loon rect objekti (x-koordinaat, y-koordinaat, laius ja kõrgus)
            pygame.draw.rect(screen, joone_värv, rect, 1) #Joonistab kasti (ekraani väärtus, joone värv, kast ja joone laius)

# Loome Pygame'i ekraani
pygame.init() #Algatan pygame'i
screen = pygame.display.set_mode((640, 480)) #Määrab akna suuruse
pygame.display.set_caption("Ruudustik") #Määrab praeguse akna pealkirja

# Määrame parameetrid
ruudu_suurus = 20 #Määrab ruudu suuruse
read = 24 #Määrab ridade arvu
veerud = 32 #Määrab veergude arvu
joone_värv = (255, 0, 0)  #Määrab joone värvi

#Ristist sulgemine
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    #Joonistame ekraani täis ruute
    screen.fill((150, 255, 150))  #Roheline värv taustaks
    draw_grid(screen, ruudu_suurus, read, veerud, joone_värv) #Joonistab ekraanile ruudustiku
    pygame.display.update() #Uuendab ekranni

#Lõpetame Pygame'i
pygame.quit()


# coding=utf-8
"""Unit tests for activitypub.py."""
from base64 import b64encode
import copy
from datetime import datetime, timedelta
from hashlib import sha256
import logging
from unittest import skip
from unittest.mock import patch

from flask import g
from google.cloud import ndb
from granary import as2, microformats2
from httpsig import HeaderSigner
from oauth_dropins.webutil.testutil import requests_response
from oauth_dropins.webutil.util import json_dumps, json_loads
import requests
from urllib3.exceptions import ReadTimeoutError
from werkzeug.exceptions import BadGateway

# import first so that Fake is defined before URL routes are registered
from .testutil import Fake, TestCase

import activitypub
from activitypub import ActivityPub, postprocess_as2
import common
from models import Follower, Object
import protocol
from web import Web

# have to import module, not attrs, to avoid circular import
from . import test_web

ACTOR = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'id': 'https://mas.to/users/swentel',
    'type': 'Person',
    'inbox': 'http://mas.to/inbox',
    'name': 'Mrs. ☕ Foo',
    'icon': {'type': 'Image', 'url': 'https://user.com/me.jpg'},
    'image': {'type': 'Image', 'url': 'https://user.com/me.jpg'},
}
ACTOR_BASE = {
    '@context': [
        'https://www.w3.org/ns/activitystreams',
        'https://w3id.org/security/v1',
    ],
    'type': 'Person',
    'id': 'http://localhost/user.com',
    'url': 'http://localhost/r/https://user.com/',
    'preferredUsername': 'user.com',
    'summary': '',
    'inbox': 'http://localhost/user.com/inbox',
    'outbox': 'http://localhost/user.com/outbox',
    'following': 'http://localhost/user.com/following',
    'followers': 'http://localhost/user.com/followers',
    'endpoints': {
        'sharedInbox': 'http://localhost/ap/sharedInbox',
    },
    'publicKey': {
        'id': 'http://localhost/user.com#key',
        'owner': 'http://localhost/user.com',
        'publicKeyPem': 'populated in setUp()',
    },
}
ACTOR_BASE_FULL = {
    **ACTOR_BASE,
    'name': 'Ms. ☕ Baz',
    'attachment': [{
        'name': 'Web site',
        'type': 'PropertyValue',
        'value': 'https://user.com/',
    }],
}
REPLY_OBJECT = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'type': 'Note',
    'content': 'A ☕ reply',
    'id': 'http://mas.to/reply/id',
    'url': 'http://mas.to/reply',
    'inReplyTo': 'https://user.com/post',
    'to': [as2.PUBLIC_AUDIENCE],
}
REPLY_OBJECT_WRAPPED = copy.deepcopy(REPLY_OBJECT)
REPLY_OBJECT_WRAPPED['inReplyTo'] = 'http://localhost/r/https://user.com/post'
REPLY = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'type': 'Create',
    'id': 'http://mas.to/reply/as2',
    'object': REPLY_OBJECT,
}
NOTE_OBJECT = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'type': 'Note',
    'content': '☕ just a normal post',
    'id': 'http://mas.to/note/id',
    'url': 'http://mas.to/note',
    'to': [as2.PUBLIC_AUDIENCE],
    'cc': [
        'https://mas.to/author/followers',
        'https://masto.foo/@other',
        'http://localhost/target',  # redirect-wrapped
    ],
}
NOTE = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'type': 'Create',
    'id': 'http://mas.to/note/as2',
    'actor': 'https://masto.foo/@author',
    'object': NOTE_OBJECT,
}
MENTION_OBJECT = copy.deepcopy(NOTE_OBJECT)
MENTION_OBJECT.update({
    'id': 'http://mas.to/mention/id',
    'url': 'http://mas.to/mention',
    'tag': [{
        'type': 'Mention',
        'href': 'https://masto.foo/@other',
        'name': '@other@masto.foo',
    }, {
        'type': 'Mention',
        'href': 'http://localhost/tar.get',  # redirect-wrapped
        'name': '@tar.get@tar.get',
    }],
})
MENTION = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'type': 'Create',
    'id': 'http://mas.to/mention/as2',
    'object': MENTION_OBJECT,
}
# based on example Mastodon like:
# https://github.com/snarfed/bridgy-fed/issues/4#issuecomment-334212362
# (reposts are very similar)
LIKE = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'id': 'http://mas.to/like#ok',
    'type': 'Like',
    'object': 'https://user.com/post',
    'actor': 'https://mas.to/actor',
}
LIKE_WRAPPED = copy.deepcopy(LIKE)
LIKE_WRAPPED['object'] = 'http://localhost/r/https://user.com/post'
LIKE_ACTOR = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'id': 'https://mas.to/actor',
    'type': 'Person',
    'name': 'Ms. Actor',
    'preferredUsername': 'msactor',
    'icon': {'type': 'Image', 'url': 'https://user.com/pic.jpg'},
    'image': [
        {'type': 'Image', 'url': 'https://user.com/thumb.jpg'},
        {'type': 'Image', 'url': 'https://user.com/pic.jpg'},
    ],
}
LIKE_WITH_ACTOR = {
    **LIKE,
    'actor': LIKE_ACTOR,
}

# repost, should be delivered to followers if object is a fediverse post,
# translated to webmention if object is an indieweb post
REPOST = {
  '@context': 'https://www.w3.org/ns/activitystreams',
  'id': 'https://mas.to/users/alice/statuses/654/activity',
  'type': 'Announce',
  'actor': ACTOR['id'],
  'object': NOTE_OBJECT['id'],
  'published': '2023-02-08T17:44:16Z',
  'to': ['https://www.w3.org/ns/activitystreams#Public'],
}
REPOST_FULL = {
    **REPOST,
    'actor': ACTOR,
    'object': NOTE_OBJECT,
}

FOLLOW = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'id': 'https://mas.to/6d1a',
    'type': 'Follow',
    'actor': ACTOR['id'],
    'object': 'https://user.com/',
}
FOLLOW_WRAPPED = copy.deepcopy(FOLLOW)
FOLLOW_WRAPPED['object'] = 'http://localhost/user.com'
FOLLOW_WITH_ACTOR = copy.deepcopy(FOLLOW)
FOLLOW_WITH_ACTOR['actor'] = ACTOR
FOLLOW_WRAPPED_WITH_ACTOR = copy.deepcopy(FOLLOW_WRAPPED)
FOLLOW_WRAPPED_WITH_ACTOR['actor'] = ACTOR
FOLLOW_WITH_OBJECT = copy.deepcopy(FOLLOW)
FOLLOW_WITH_OBJECT['object'] = ACTOR

ACCEPT_FOLLOW = copy.deepcopy(FOLLOW_WITH_ACTOR)
del ACCEPT_FOLLOW['@context']
del ACCEPT_FOLLOW['actor']['@context']
ACCEPT_FOLLOW['actor']['image'] = {'type': 'Image', 'url': 'https://user.com/me.jpg'}
ACCEPT_FOLLOW['object'] = 'http://localhost/user.com'
ACCEPT = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'type': 'Accept',
    'id': 'http://localhost/web/user.com/followers#accept-https://mas.to/6d1a',
    'actor': 'http://localhost/user.com',
    'object': {
        **ACCEPT_FOLLOW,
        'url': 'https://mas.to/users/swentel#followed-https://user.com/',
        'to': ['https://www.w3.org/ns/activitystreams#Public'],
    },
   'to': ['https://www.w3.org/ns/activitystreams#Public'],
}

UNDO_FOLLOW_WRAPPED = {
  '@context': 'https://www.w3.org/ns/activitystreams',
  'id': 'https://mas.to/6d1b',
  'type': 'Undo',
  'actor': 'https://mas.to/users/swentel',
  'object': FOLLOW_WRAPPED,
}

DELETE = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'id': 'https://mas.to/users/swentel#delete',
    'type': 'Delete',
    'actor': 'https://mas.to/users/swentel',
    'object': 'https://mas.to/users/swentel',
}

UPDATE_PERSON = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'id': 'https://a/person#update',
    'type': 'Update',
    'actor': 'https://mas.to/users/swentel',
    'object': {
        'type': 'Person',
        'id': 'https://a/person',
    },
}
UPDATE_NOTE = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    'id': 'https://a/note#update',
    'type': 'Update',
    'actor': 'https://mas.to/users/swentel',
    'object': {
        'type': 'Note',
        'id': 'https://a/note',
    },
}
WEBMENTION_DISCOVERY = requests_response(
    '<link rel="webmention" href="/webmention">')

HTML = requests_response('', headers={
    'Content-Type': common.CONTENT_TYPE_HTML,
})
HTML_WITH_AS2 = requests_response("""\
<meta>
<link href='http://as2' rel='alternate' type='application/activity+json'>
</meta>
""", headers={
    'Content-Type': common.CONTENT_TYPE_HTML,
})
AS2_OBJ = {'foo': ['bar']}
AS2 = requests_response(AS2_OBJ, headers={
    'Content-Type': as2.CONTENT_TYPE,
})
NOT_ACCEPTABLE = requests_response(status=406)

@patch('requests.post')
@patch('requests.get')
@patch('requests.head')
class ActivityPubTest(TestCase):

    def setUp(self):
        super().setUp()
        self.request_context.push()

        self.user = self.make_user('user.com', has_hcard=True, has_redirects=True,
                                   obj_as2={**ACTOR, 'id': 'https://user.com/'})
        self.swentel_key = ndb.Key(ActivityPub, 'https://mas.to/users/swentel')
        self.masto_actor_key = ndb.Key(ActivityPub, 'https://mas.to/actor')

        ACTOR_BASE['publicKey']['publicKeyPem'] = self.user.public_pem().decode()

        self.key_id_obj = Object(id='http://my/key/id', as2={
            **ACTOR,
            'publicKey': {
                'id': 'http://my/key/id#unused',
                'owner': 'http://own/er',
                'publicKeyPem': self.user.public_pem().decode(),
            },
        })
        self.key_id_obj.put()

    def assert_object(self, id, **props):
        props.setdefault('delivered_protocol', 'web')
        return super().assert_object(id, **props)

    def sign(self, path, body):
        """Constructs HTTP Signature, returns headers."""
        digest = b64encode(sha256(body.encode()).digest()).decode()
        headers = {
            'Date': 'Sun, 02 Jan 2022 03:04:05 GMT',
            'Host': 'localhost',
            'Content-Type': as2.CONTENT_TYPE,
            'Digest': f'SHA-256={digest}',
        }
        hs = HeaderSigner('http://my/key/id#unused', self.user.private_pem().decode(),
                          algorithm='rsa-sha256', sign_header='signature',
                          headers=('Date', 'Host', 'Digest', '(request-target)'))
        return hs.sign(headers, method='POST', path=path)

    def post(self, path, json=None):
        """Wrapper around self.client.post that adds signature."""
        body = json_dumps(json)
        return self.client.post(path, data=body, headers=self.sign(path, body))

    def test_actor_fake(self, *_):
        self.make_user('user.com', cls=Fake, obj_as2={
            'type': 'Person',
            'id': 'https://user.com/',
        })

        got = self.client.get('/ap/fake/user.com')
        self.assertEqual(200, got.status_code, got.get_data(as_text=True))
        type = got.headers['Content-Type']
        self.assertTrue(type.startswith(as2.CONTENT_TYPE), type)
        self.assertEqual({
            '@context': ['https://w3id.org/security/v1'],
            'type': 'Person',
            'id': 'http://bf/fake/user.com/ap',
            'preferredUsername': 'user.com',
            'url': 'http://localhost/r/user.com',
            'summary': '',
            'inbox': 'http://bf/fake/user.com/ap/inbox',
            'outbox': 'http://bf/fake/user.com/ap/outbox',
            'following': 'http://bf/fake/user.com/ap/following',
            'followers': 'http://bf/fake/user.com/ap/followers',
            'endpoints': {'sharedInbox': 'http://localhost/ap/sharedInbox'},
            'publicKey': {
                'id': 'http://localhost/user.com#key',
                'owner': 'http://localhost/user.com',
                'publicKeyPem': self.user.public_pem().decode(),
            },
        }, got.json)

    def test_actor_web(self, *_):
        """Web users are special cased to drop the /web/ prefix."""
        got = self.client.get('/user.com')
        self.assertEqual(200, got.status_code)
        type = got.headers['Content-Type']
        self.assertTrue(type.startswith(as2.CONTENT_TYPE), type)
        self.assertEqual({
            **ACTOR_BASE,
            'name': 'Mrs. ☕ Foo',
            'icon': {'type': 'Image', 'url': 'https://user.com/me.jpg'},
            'image': {'type': 'Image', 'url': 'https://user.com/me.jpg'},
        }, got.json)

    def test_actor_blocked_tld(self, _, __, ___):
        got = self.client.get('/foo.json')
        self.assertEqual(404, got.status_code)

    def test_actor_new_user_fetch(self, _, mock_get, __):
        self.user.obj_key.delete()
        self.user.key.delete()
        protocol.objects_cache.clear()

        mock_get.return_value = requests_response(test_web.ACTOR_HTML)

        got = self.client.get('/user.com')
        self.assertEqual(200, got.status_code)
        self.assert_equals(ACTOR_BASE_FULL, got.json, ignore=['publicKeyPem'])

    def test_actor_new_user_fetch_no_mf2(self, _, mock_get, __):
        self.user.obj_key.delete()
        self.user.key.delete()
        protocol.objects_cache.clear()

        mock_get.return_value = requests_response('')

        got = self.client.get('/user.com')
        self.assertEqual(200, got.status_code)
        self.assert_equals(ACTOR_BASE, got.json, ignore=['publicKeyPem'])

    def test_actor_new_user_fetch_fails(self, _, mock_get, __):
        mock_get.side_effect = ReadTimeoutError(None, None, None)
        got = self.client.get('/nope.com')
        self.assertEqual(504, got.status_code)

    def test_individual_inbox_no_user(self, mock_head, mock_get, mock_post):
        self.user.key.delete()

        mock_get.side_effect = [self.as2_resp(LIKE_ACTOR)]

        reply = {
            **REPLY,
            'actor': LIKE_ACTOR,
        }
        self._test_inbox_reply(reply, mock_head, mock_get, mock_post)

        self.assert_user(ActivityPub, 'https://mas.to/actor',
                         obj_as2=LIKE_ACTOR, direct=True)

    def test_inbox_activity_without_id(self, *_):
        note = copy.deepcopy(NOTE)
        del note['id']
        resp = self.post('/ap/sharedInbox', json=note)
        self.assertEqual(400, resp.status_code)

    def test_inbox_reply_object(self, mock_head, mock_get, mock_post):
        self._test_inbox_reply(REPLY_OBJECT, mock_head, mock_get, mock_post)

        self.assert_object('http://mas.to/reply/id',
                           source_protocol='activitypub',
                           our_as1=as2.to_as1(REPLY_OBJECT),
                           type='comment')
        # auto-generated post activity
        self.assert_object(
            'http://mas.to/reply/id#bridgy-fed-create',
            source_protocol='activitypub',
            our_as1={
                **as2.to_as1(REPLY),
                'id': 'http://mas.to/reply/id#bridgy-fed-create',
                'published': '2022-01-02T03:04:05+00:00',
            },
            status='complete',
            delivered=['https://user.com/post'],
            type='post',
            notify=[self.user.key],
        )

    def test_inbox_reply_object_wrapped(self, mock_head, mock_get, mock_post):
        self._test_inbox_reply(REPLY_OBJECT_WRAPPED, mock_head, mock_get, mock_post)

        self.assert_object('http://mas.to/reply/id',
                           source_protocol='activitypub',
                           our_as1=as2.to_as1(REPLY_OBJECT),
                           type='comment')
        # auto-generated post activity
        self.assert_object(
            'http://mas.to/reply/id#bridgy-fed-create',
            source_protocol='activitypub',
            our_as1={
                **as2.to_as1(REPLY),
                'id': 'http://mas.to/reply/id#bridgy-fed-create',
                'published': '2022-01-02T03:04:05+00:00',
            },
            status='complete',
            delivered=['https://user.com/post'],
            type='post',
            notify=[self.user.key],
        )

    def test_inbox_reply_create_activity(self, mock_head, mock_get, mock_post):
        self._test_inbox_reply(REPLY, mock_head, mock_get, mock_post)

        self.assert_object('http://mas.to/reply/id',
                           source_protocol='activitypub',
                           our_as1=as2.to_as1({
                               **REPLY_OBJECT,
                               'author': None,
                           }),
                           type='comment')
        # sent activity
        self.assert_object(
            'http://mas.to/reply/as2',
            source_protocol='activitypub',
            as2=REPLY,
            status='complete',
            delivered=['https://user.com/post'],
            type='post',
            notify=[self.user.key],
        )

    def _test_inbox_reply(self, reply, mock_head, mock_get, mock_post):
        mock_head.return_value = requests_response(url='https://user.com/post')
        mock_get.side_effect = (
            (list(mock_get.side_effect) if mock_get.side_effect else [])
            + [
                requests_response(test_web.NOTE_HTML),
                requests_response(test_web.NOTE_HTML),
                WEBMENTION_DISCOVERY,
            ])
        mock_post.return_value = requests_response()

        got = self.post('/ap/web/user.com/inbox', json=reply)
        self.assertEqual(200, got.status_code, got.get_data(as_text=True))
        self.assert_req(mock_get, 'https://user.com/post')

        convert_id = reply['id'].replace('://', ':/')
        if reply['type'] != 'Create':
            convert_id += '%23bridgy-fed-create'

        self.assert_req(
            mock_post,
            'https://user.com/webmention',
            headers={'Accept': '*/*'},
            allow_redirects=False,
            data={
                'source': f'https://ap.brid.gy/convert/web/{convert_id}',
                'target': 'https://user.com/post',
            },
        )

    def test_inbox_reply_to_self_domain(self, *mocks):
        self._test_inbox_ignore_reply_to('http://localhost/mas.to', *mocks)

    def test_inbox_reply_to_in_blocklist(self, *mocks):
        self._test_inbox_ignore_reply_to('https://twitter.com/foo', *mocks)

    def _test_inbox_ignore_reply_to(self, reply_to, mock_head, mock_get, mock_post):
        reply = copy.deepcopy(REPLY_OBJECT)
        reply['inReplyTo'] = reply_to

        mock_head.return_value = requests_response(url='http://mas.to/')
        mock_get.side_effect = [
            # actor fetch
            self.as2_resp(ACTOR),
            # protocol inference
            requests_response(test_web.NOTE_HTML),
            requests_response(test_web.NOTE_HTML),
        ]

        got = self.post('/user.com/inbox', json=reply)
        self.assertEqual(204, got.status_code, got.get_data(as_text=True))
        mock_post.assert_not_called()

    def test_individual_inbox_create_obj(self, *mocks):
        self._test_inbox_create_obj('/user.com/inbox', *mocks)

    def test_shared_inbox_create_obj(self, *mocks):
        self._test_inbox_create_obj('/inbox', *mocks)

    def _test_inbox_create_obj(self, path, mock_head, mock_get, mock_post):
        swentel = self.make_user('https://mas.to/users/swentel', cls=ActivityPub)
        Follower.get_or_create(to=swentel, from_=self.user)
        bar = self.make_user('fake:bar', cls=Fake, obj_id='fake:bar')
        Follower.get_or_create(to=self.make_user('https://other.actor',
                                                 cls=ActivityPub),
                               from_=bar)
        baz = self.make_user('fake:baz', cls=Fake, obj_id='fake:baz')
        Follower.get_or_create(to=swentel, from_=baz)
        baj = self.make_user('fake:baj', cls=Fake, obj_id='fake:baj')
        Follower.get_or_create(to=swentel, from_=baj, status='inactive')

        mock_head.return_value = requests_response(url='http://target')
        mock_get.return_value = self.as2_resp(ACTOR)  # source actor
        mock_post.return_value = requests_response()

        got = self.post(path, json=NOTE)
        self.assertEqual(200, got.status_code, got.get_data(as_text=True))

        expected_obj = {
            **as2.to_as1(NOTE_OBJECT),
            'author': {'id': 'https://masto.foo/@author'},
        }
        self.assert_object(NOTE_OBJECT['id'],
                           source_protocol='activitypub',
                           our_as1=expected_obj,
                           type='note',
                           feed=[self.user.key, baz.key])

        expected_create = as2.to_as1(common.redirect_unwrap(NOTE))
        expected_create.update({
            'actor': as2.to_as1(ACTOR),
            'object': expected_obj,
        })
        self.assert_object('http://mas.to/note/as2',
                           source_protocol='activitypub',
                           our_as1=expected_create,
                           users=[ndb.Key(ActivityPub, 'https://masto.foo/@author')],
                           type='post',
                           object_ids=[NOTE_OBJECT['id']],
                           status='complete',
                           delivered=['shared:target'],
                           delivered_protocol='fake')

    def test_repost_of_indieweb(self, mock_head, mock_get, mock_post):
        mock_head.return_value = requests_response(url='https://user.com/orig')
        mock_get.return_value = WEBMENTION_DISCOVERY
        mock_post.return_value = requests_response()  # webmention

        orig_url = 'https://user.com/orig'
        note = {
            **NOTE_OBJECT,
            'id': 'https://user.com/orig',
        }
        del note['url']
        Object(id=orig_url, mf2=microformats2.object_to_json(as2.to_as1(note)),
               source_protocol='web').put()

        repost = copy.deepcopy(REPOST_FULL)
        repost['object'] = f'http://localhost/r/{orig_url}'
        got = self.post('/user.com/inbox', json=repost)
        self.assertEqual(200, got.status_code, got.get_data(as_text=True))

        convert_id = REPOST['id'].replace('://', ':/')
        self.assert_req(
            mock_post,
            'https://user.com/webmention',
            headers={'Accept': '*/*'},
            allow_redirects=False,
            data={
                'source': f'https://ap.brid.gy/convert/web/{convert_id}',
                'target': orig_url,
            },
        )

        self.assert_object(REPOST_FULL['id'],
                           source_protocol='activitypub',
                           status='complete',
                           as2={
                               **REPOST,
                               'actor': ACTOR,
                               'object': orig_url,
                           },
                           users=[self.swentel_key],
                           delivered=['https://user.com/orig'],
                           type='share',
                           object_ids=['https://user.com/orig'])

    def test_shared_inbox_repost_of_fediverse(self, mock_head, mock_get, mock_post):
        Follower.get_or_create(to=ActivityPub.get_or_create(ACTOR['id']),
                               from_=self.user)
        baz = self.make_user('fake:baz', cls=Fake, obj_id='fake:baz')
        Follower.get_or_create(to=ActivityPub.get_or_create(ACTOR['id']), from_=baz)
        baj = self.make_user('fake:baj', cls=Fake, obj_id='fake:baj')
        Follower.get_or_create(to=ActivityPub.get_or_create(ACTOR['id']),
                               from_=baj, status='inactive')

        mock_head.return_value = requests_response(url='http://target')
        mock_get.side_effect = [
            self.as2_resp(ACTOR),  # source actor
            self.as2_resp(NOTE_OBJECT),  # object of repost
            # protocol inference
            requests_response(test_web.NOTE_HTML),
            requests_response(test_web.NOTE_HTML),
            HTML,  # no webmention endpoint
        ]

        got = self.post('/ap/sharedInbox', json=REPOST)
        self.assertEqual(200, got.status_code, got.get_data(as_text=True))

        mock_post.assert_not_called()  # no webmention

        self.assert_object(REPOST['id'],
                           source_protocol='activitypub',
                           status='complete',
                           our_as1=as2.to_as1({**REPOST, 'actor': ACTOR}),
                           users=[self.swentel_key],
                           feed=[self.user.key, baz.key],
                           delivered=['shared:target'],
                           delivered_protocol='fake',
                           type='share',
                           object_ids=[REPOST['object']])

    def test_inbox_no_user(self, mock_head, mock_get, mock_post):
        mock_get.side_effect = [
            # source actor
            self.as2_resp(LIKE_WITH_ACTOR['actor']),
            # protocol inference
            requests_response(test_web.NOTE_HTML),
            requests_response(test_web.NOTE_HTML),
            # target post webmention discovery
            HTML,
        ]

        got = self.post('/ap/sharedInbox', json={
            **LIKE,
            'object': 'http://nope.com/post',
        })
        self.assertEqual(204, got.status_code)

        self.assert_object('http://mas.to/like#ok',
                           # no nope.com Web user key since it didn't exist
                           source_protocol='activitypub',
                           status='ignored',
                           our_as1=as2.to_as1({
                               **LIKE_WITH_ACTOR,
                               'object': 'http://nope.com/post',
                           }),
                           type='like',
                           notify=[self.user.key],
                           users=[self.masto_actor_key],
                           object_ids=['http://nope.com/post'])

    def test_inbox_not_public(self, mock_head, mock_get, mock_post):
        Follower.get_or_create(to=ActivityPub.get_or_create(ACTOR['id']),
                               from_=self.user)

        mock_head.return_value = requests_response(url='http://target')
        mock_get.return_value = self.as2_resp(ACTOR)  # source actor

        not_public = copy.deepcopy(NOTE)
        del not_public['object']['to']

        got = self.post('/user.com/inbox', json=not_public)
        self.assertEqual(200, got.status_code, got.get_data(as_text=True))

        self.assertIsNone(Object.get_by_id(not_public['id']))
        self.assertIsNone(Object.get_by_id(not_public['object']['id']))

    def test_inbox_like(self, mock_head, mock_get, mock_post):
        mock_head.return_value = requests_response(url='https://user.com/post')
        mock_get.side_effect = [
            # source actor
            self.as2_resp(LIKE_WITH_ACTOR['actor']),
            requests_response(test_web.NOTE_HTML),
            requests_response(test_web.NOTE_HTML),
            WEBMENTION_DISCOVERY,
        ]
        mock_post.return_value = requests_response()

        got = self.post('/user.com/inbox', json=LIKE)
        self.assertEqual(200, got.status_code)

        self.assertIn(self.as2_req('https://mas.to/actor'), mock_get.mock_calls)
        self.assertIn(self.req('https://user.com/post'), mock_get.mock_calls)

        args, kwargs = mock_post.call_args
        self.assertEqual(('https://user.com/webmention',), args)
        self.assertEqual({
            'source': 'https://ap.brid.gy/convert/web/http:/mas.to/like%23ok',
            'target': 'https://user.com/post',
        }, kwargs['data'])

        self.assert_object('http://mas.to/like#ok',
                           notify=[self.user.key],
                           users=[self.masto_actor_key],
                           source_protocol='activitypub',
                           status='complete',
                           our_as1=as2.to_as1(LIKE_WITH_ACTOR),
                           delivered=['https://user.com/post'],
                           type='like',
                           object_ids=[LIKE['object']])

    def test_inbox_like_indirect_user_creates_User(self, mock_get, *_):
        self.user.direct = False
        self.user.put()

        mock_get.return_value = self.as2_resp(LIKE_ACTOR)

        self.test_inbox_like()
        self.assert_user(ActivityPub, 'https://mas.to/actor',
                         obj_as2=LIKE_ACTOR, direct=True)

    def test_inbox_follow_accept_with_id(self, *mocks):
        self._test_inbox_follow_accept(FOLLOW_WRAPPED, ACCEPT, 200, *mocks)

        follow = {
            **FOLLOW_WITH_ACTOR,
            'url': 'https://mas.to/users/swentel#followed-https://user.com/',
        }
        self.assert_object('https://mas.to/6d1a',
                           users=[self.swentel_key],
                           notify=[self.user.key],
                           source_protocol='activitypub',
                           status='complete',
                           our_as1=as2.to_as1(follow),
                           delivered=['https://user.com/'],
                           type='follow',
                           object_ids=[FOLLOW['object']])

    def test_inbox_follow_accept_with_object(self, *mocks):
        follow = {
            **FOLLOW,
            'object': {
                'id': FOLLOW['object'],
                'url': FOLLOW['object'],
            },
        }
        self._test_inbox_follow_accept(follow, ACCEPT, 200, *mocks)

        follow.update({
            'actor': ACTOR,
            'url': 'https://mas.to/users/swentel#followed-https://user.com/',
        })
        self.assert_object('https://mas.to/6d1a',
                           users=[self.swentel_key],
                           notify=[self.user.key],
                           source_protocol='activitypub',
                           status='complete',
                           our_as1=as2.to_as1(follow),
                           delivered=['https://user.com/'],
                           type='follow',
                           object_ids=[FOLLOW['object']])

    def test_inbox_follow_accept_shared_inbox(self, *mocks):
        self._test_inbox_follow_accept(FOLLOW_WRAPPED, ACCEPT, 200, *mocks,
                                       inbox_path='/ap/sharedInbox')

        url = 'https://mas.to/users/swentel#followed-https://user.com/'
        self.assert_object('https://mas.to/6d1a',
                           users=[self.swentel_key],
                           notify=[self.user.key],
                           source_protocol='activitypub',
                           status='complete',
                           our_as1=as2.to_as1({**FOLLOW_WITH_ACTOR, 'url': url}),
                           delivered=['https://user.com/'],
                           type='follow',
                           object_ids=[FOLLOW['object']])

    def test_inbox_follow_accept_webmention_fails(self, mock_head, mock_get,
                                                  mock_post):
        mock_post.side_effect = [
            requests_response(),         # AP Accept
            requests.ConnectionError(),  # webmention
        ]
        self._test_inbox_follow_accept(FOLLOW_WRAPPED, ACCEPT, 502,
                                       mock_head, mock_get, mock_post)

        url = 'https://mas.to/users/swentel#followed-https://user.com/'
        self.assert_object('https://mas.to/6d1a',
                           users=[self.swentel_key],
                           notify=[self.user.key],
                           source_protocol='activitypub',
                           status='failed',
                           our_as1=as2.to_as1({**FOLLOW_WITH_ACTOR, 'url': url}),
                           delivered=[],
                           failed=['https://user.com/'],
                           type='follow',
                           object_ids=[FOLLOW['object']])

    def _test_inbox_follow_accept(self, follow_as2, accept_as2, expected_status,
                                  mock_head, mock_get, mock_post,
                                  inbox_path='/user.com/inbox'):
        # this should makes us make the follower ActivityPub as direct=True
        self.user.direct = False
        self.user.put()

        mock_head.return_value = requests_response(url='https://user.com/')
        mock_get.side_effect = [
            # source actor
            self.as2_resp(ACTOR),
            WEBMENTION_DISCOVERY,
        ]
        if not mock_post.return_value and not mock_post.side_effect:
            mock_post.return_value = requests_response()

        got = self.post(inbox_path, json=follow_as2)
        self.assertEqual(expected_status, got.status_code)

        mock_get.assert_has_calls((
            self.as2_req(FOLLOW['actor']),
        ))

        # check AP Accept
        self.assertEqual(2, len(mock_post.call_args_list))
        args, kwargs = mock_post.call_args_list[0]
        self.assertEqual(('http://mas.to/inbox',), args)
        self.assertEqual(accept_as2, json_loads(kwargs['data']))

        # check webmention
        args, kwargs = mock_post.call_args_list[1]
        self.assertEqual(('https://user.com/webmention',), args)
        self.assertEqual({
            'source': 'https://ap.brid.gy/convert/web/https:/mas.to/6d1a',
            'target': 'https://user.com/',
        }, kwargs['data'])

        # check that we stored Follower and ActivityPub user for the follower
        self.assert_entities_equal(
            Follower(to=self.user.key,
                     from_=ActivityPub(id=ACTOR['id']).key,
                     status='active',
                     follow=Object(id=FOLLOW['id']).key),
            Follower.query().fetch(),
            ignore=['created', 'updated'])

        self.assert_user(ActivityPub, 'https://mas.to/users/swentel',
                         obj_as2=ACTOR, direct=True)
        self.assert_user(Web, 'user.com', direct=False,
                         has_hcard=True, has_redirects=True)

    def test_inbox_follow_use_instead_strip_www(self, mock_head, mock_get, mock_post):
        self.make_user('www.user.com', use_instead=self.user.key)

        mock_head.return_value = requests_response(url='https://www.user.com/')
        mock_get.side_effect = [
            # source actor
            self.as2_resp(ACTOR),
            # target post webmention discovery
            requests_response(''),
        ]
        mock_post.return_value = requests_response()

        got = self.post('/user.com/inbox', json=FOLLOW_WRAPPED)
        self.assertEqual(204, got.status_code)

        follower = Follower.query().get()
        self.assert_entities_equal(
            Follower(to=self.user.key,
                     from_=ActivityPub(id=ACTOR['id']).key,
                     status='active',
                     follow=Object(id=FOLLOW['id']).key),
            follower,
            ignore=['created', 'updated'])

        # double check that Follower doesn't have www
        self.assertEqual('user.com', follower.to.id())

        # double check that follow Object doesn't have www
        self.assertEqual('active', follower.status)
        self.assertEqual('https://mas.to/users/swentel#followed-https://user.com/',
                         follower.follow.get().as2['url'])

    def test_inbox_undo_follow(self, mock_head, mock_get, mock_post):
        follower = Follower(to=self.user.key,
                            from_=ActivityPub.get_or_create(ACTOR['id']).key,
                            status='active')
        follower.put()

        mock_get.side_effect = [
            self.as2_resp(ACTOR),
            WEBMENTION_DISCOVERY,
        ]
        mock_post.return_value = requests_response()

        got = self.post('/user.com/inbox', json=UNDO_FOLLOW_WRAPPED)
        self.assertEqual(200, got.status_code)

        # check that the Follower is now inactive
        self.assertEqual('inactive', follower.key.get().status)

    def test_inbox_follow_inactive(self, mock_head, mock_get, mock_post):
        follower = Follower.get_or_create(to=self.user,
                                          from_=ActivityPub.get_or_create(ACTOR['id']),
                                          status='inactive')

        mock_head.return_value = requests_response(url='https://user.com/')
        mock_get.side_effect = [
            # source actor
            self.as2_resp(FOLLOW_WITH_ACTOR['actor']),
            WEBMENTION_DISCOVERY,
        ]
        mock_post.return_value = requests_response()

        got = self.post('/user.com/inbox', json=FOLLOW_WRAPPED)
        self.assertEqual(200, got.status_code)

        # check that the Follower is now active
        self.assertEqual('active', follower.key.get().status)

    def test_inbox_undo_follow_doesnt_exist(self, mock_head, mock_get, mock_post):
        mock_head.return_value = requests_response(url='https://user.com/')
        mock_get.side_effect = [
            self.as2_resp(ACTOR),
            WEBMENTION_DISCOVERY,
        ]
        mock_post.return_value = requests_response()

        got = self.post('/user.com/inbox', json=UNDO_FOLLOW_WRAPPED)
        self.assertEqual(200, got.status_code)

    def test_inbox_undo_follow_inactive(self, mock_head, mock_get, mock_post):
        mock_head.return_value = requests_response(url='https://user.com/')
        mock_get.side_effect = [
            self.as2_resp(ACTOR),
            WEBMENTION_DISCOVERY,
        ]
        mock_post.return_value = requests_response()

        follower = Follower.get_or_create(to=self.user,
                                          from_=ActivityPub.get_or_create(ACTOR['id']),
                                          status='inactive')

        got = self.post('/user.com/inbox', json=UNDO_FOLLOW_WRAPPED)
        self.assertEqual(200, got.status_code)
        self.assertEqual('inactive', follower.key.get().status)

    def test_inbox_undo_follow_composite_object(self, mock_head, mock_get, mock_post):
        mock_head.return_value = requests_response(url='https://user.com/')
        mock_get.side_effect = [
            self.as2_resp(ACTOR),
            WEBMENTION_DISCOVERY,
        ]
        mock_post.return_value = requests_response()

        follower = Follower.get_or_create(to=self.user,
                                          from_=ActivityPub.get_or_create(ACTOR['id']),
                                          status='inactive')

        undo_follow = copy.deepcopy(UNDO_FOLLOW_WRAPPED)
        undo_follow['object']['object'] = {'id': undo_follow['object']['object']}
        got = self.post('/user.com/inbox', json=undo_follow)
        self.assertEqual(200, got.status_code)
        self.assertEqual('inactive', follower.key.get().status)

    def test_inbox_unsupported_type(self, *_):
        got = self.post('/user.com/inbox', json={
            '@context': ['https://www.w3.org/ns/activitystreams'],
            'id': 'https://xoxo.zone/users/aaronpk#follows/40',
            'type': 'Block',
            'actor': 'https://xoxo.zone/users/aaronpk',
            'object': 'http://snarfed.org/',
        })
        self.assertEqual(501, got.status_code)

    def test_inbox_bad_object_url(self, mock_head, mock_get, mock_post):
        # https://console.cloud.google.com/errors/detail/CMKn7tqbq-GIRA;time=P30D?project=bridgy-federated
        mock_get.return_value = self.as2_resp(ACTOR)  # source actor

        id = 'https://mas.to/users/tmichellemoore#likes/56486252'
        bad_url = 'http://localhost/r/Testing \u2013 Brid.gy \u2013 Post to Mastodon 3'
        bad = {
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': id,
            'type': 'Like',
            'actor': ACTOR['id'],
            'object': bad_url,
        }
        got = self.post('/user.com/inbox', json=bad)

        # bad object, should ignore activity
        self.assertEqual(204, got.status_code)
        mock_post.assert_not_called()

        self.assert_object(id,
                           our_as1={
                               **as2.to_as1(bad),
                               'actor': as2.to_as1(ACTOR),
                           },
                           users=[self.swentel_key],
                           source_protocol='activitypub',
                           status='ignored',
                           )
        self.assertIsNone(Object.get_by_id(bad_url))

    @patch('activitypub.logger.info', side_effect=logging.info)
    @patch('common.logger.info', side_effect=logging.info)
    @patch('oauth_dropins.webutil.appengine_info.DEBUG', False)
    def test_inbox_verify_http_signature(self, mock_common_log, mock_activitypub_log,
                                         _, mock_get, ___):
        # actor with a public key
        self.key_id_obj.key.delete()
        protocol.objects_cache.clear()
        actor_as2 = {
            **ACTOR,
            'publicKey': {
                'id': 'http://my/key/id#unused',
                'owner': 'http://own/er',
                'publicKeyPem': self.user.public_pem().decode(),
            },
        }
        mock_get.return_value = self.as2_resp(actor_as2)

        # valid signature
        body = json_dumps(NOTE)
        headers = self.sign('/ap/sharedInbox', json_dumps(NOTE))
        resp = self.client.post('/ap/sharedInbox', data=body, headers=headers)
        self.assertEqual(204, resp.status_code, resp.get_data(as_text=True))
        mock_get.assert_has_calls((
            self.as2_req('http://my/key/id'),
        ))
        mock_activitypub_log.assert_any_call('HTTP Signature verified!')

        # valid signature, Object has no key
        self.key_id_obj.as2 = ACTOR
        self.key_id_obj.put()
        resp = self.client.post('/ap/sharedInbox', data=body, headers=headers)
        self.assertEqual(401, resp.status_code, resp.get_data(as_text=True))

        # valid signature, Object has our_as1 instead of as2
        self.key_id_obj.clear()
        self.key_id_obj.our_as1 = as2.to_as1(actor_as2)
        self.key_id_obj.put()
        resp = self.client.post('/ap/sharedInbox', data=body, headers=headers)
        self.assertEqual(204, resp.status_code, resp.get_data(as_text=True))
        mock_activitypub_log.assert_any_call('HTTP Signature verified!')

        # invalid signature, missing keyId
        protocol.seen_ids.clear()
        obj_key = ndb.Key(Object, NOTE['id'])
        obj_key.delete()

        resp = self.client.post('/ap/sharedInbox', data=body, headers={
            **headers,
            'signature': headers['signature'].replace(
                'keyId="http://my/key/id#unused",', ''),
        })
        self.assertEqual(401, resp.status_code)
        self.assertEqual({'error': 'HTTP Signature missing keyId'}, resp.json)
        mock_common_log.assert_any_call('Returning 401: HTTP Signature missing keyId', exc_info=None)

        # invalid signature, content changed
        protocol.seen_ids.clear()
        obj_key = ndb.Key(Object, NOTE['id'])
        obj_key.delete()

        resp = self.client.post('/ap/sharedInbox', json={**NOTE, 'content': 'z'}, headers=headers)
        self.assertEqual(401, resp.status_code)
        self.assertEqual({'error': 'Invalid Digest header, required for HTTP Signature'},
                         resp.json)
        mock_common_log.assert_any_call('Returning 401: Invalid Digest header, required for HTTP Signature', exc_info=None)

        # invalid signature, header changed
        protocol.seen_ids.clear()
        obj_key.delete()

        resp = self.client.post('/ap/sharedInbox', data=body, headers={**headers, 'Date': 'X'})
        self.assertEqual(401, resp.status_code)
        self.assertEqual({'error': 'HTTP Signature verification failed'}, resp.json)
        mock_common_log.assert_any_call('Returning 401: HTTP Signature verification failed', exc_info=None)

        # no signature
        protocol.seen_ids.clear()
        obj_key.delete()
        resp = self.client.post('/ap/sharedInbox', json=NOTE)
        self.assertEqual(401, resp.status_code, resp.get_data(as_text=True))
        self.assertEqual({'error': 'No HTTP Signature'}, resp.json)
        mock_common_log.assert_any_call('Returning 401: No HTTP Signature', exc_info=None)

    def test_delete_actor(self, *mocks):
        follower = Follower.get_or_create(
            to=self.user, from_=ActivityPub.get_or_create(DELETE['actor']))
        followee = Follower.get_or_create(
            to=ActivityPub.get_or_create(DELETE['actor']),
            from_=Fake.get_or_create('snarfed.org'))
        # other unrelated follower
        other = Follower.get_or_create(
            to=self.user, from_=ActivityPub.get_or_create('https://mas.to/users/other'))
        self.assertEqual(3, Follower.query().count())

        got = self.post('/ap/sharedInbox', json=DELETE)
        self.assertEqual(204, got.status_code)
        self.assertEqual('inactive', follower.key.get().status)
        self.assertEqual('inactive', followee.key.get().status)
        self.assertEqual('active', other.key.get().status)

    def test_delete_actor_not_fetchable(self, _, mock_get, ___):
        self.key_id_obj.key.delete()
        protocol.objects_cache.clear()

        mock_get.return_value = requests_response(status=410)
        got = self.post('/ap/sharedInbox', json={**DELETE, 'object': 'http://my/key/id'})
        self.assertEqual(202, got.status_code)

    def test_delete_actor_empty_deleted_object(self, _, mock_get, ___):
        self.key_id_obj.as2 = None
        self.key_id_obj.deleted = True
        self.key_id_obj.put()
        protocol.objects_cache.clear()

        got = self.post('/ap/sharedInbox', json={**DELETE, 'object': 'http://my/key/id'})
        self.assertEqual(202, got.status_code)
        mock_get.assert_not_called()

    def test_delete_note(self, _, mock_get, ___):
        obj = Object(id='http://an/obj')
        obj.put()

        mock_get.side_effect = [
            self.as2_resp(ACTOR),
        ]

        delete = {
            **DELETE,
            'object': 'http://an/obj',
        }
        resp = self.post('/ap/sharedInbox', json=delete)
        self.assertEqual(204, resp.status_code)
        self.assertTrue(obj.key.get().deleted)
        self.assert_object(delete['id'],
                           our_as1={
                               **as2.to_as1(delete),
                               'actor': as2.to_as1(ACTOR),
                           },
                           type='delete',
                           source_protocol='activitypub',
                           status='ignored',
                           users=[ActivityPub(id='https://mas.to/users/swentel').key])

        obj.populate(deleted=True, as2=None)
        self.assert_entities_equal(obj,
                                   protocol.objects_cache['http://an/obj'],
                                   ignore=['expire', 'created', 'updated'])

    def test_update_note(self, *mocks):
        Object(id='https://a/note', as2={}).put()
        self._test_update(*mocks)

    def test_update_unknown(self, *mocks):
        self._test_update(*mocks)

    def _test_update(self, _, mock_get, ___):
        mock_get.side_effect = [
            self.as2_resp(ACTOR),
        ]

        resp = self.post('/ap/sharedInbox', json=UPDATE_NOTE)
        self.assertEqual(204, resp.status_code)

        note_as1 = as2.to_as1({
            **UPDATE_NOTE['object'],
            'author': {'id': 'https://mas.to/users/swentel'},
        })
        self.assert_object('https://a/note',
                           type='note',
                           our_as1=note_as1,
                           source_protocol='activitypub')

        update_as1 = {
            **as2.to_as1(UPDATE_NOTE),
            'object': note_as1,
            'actor': as2.to_as1(ACTOR),
        }
        self.assert_object(UPDATE_NOTE['id'],
                           source_protocol='activitypub',
                           type='update',
                           status='ignored',
                           our_as1=update_as1,
                           users=[self.swentel_key])

        self.assert_entities_equal(Object.get_by_id('https://a/note'),
                                   protocol.objects_cache['https://a/note'])

    def test_inbox_webmention_discovery_connection_fails(self, mock_head,
                                                         mock_get, mock_post):
        mock_get.side_effect = [
            # source actor
            self.as2_resp(LIKE_WITH_ACTOR['actor']),
            # protocol inference
            requests_response(test_web.NOTE_HTML),
            requests_response(test_web.NOTE_HTML),
            # target post webmention discovery
            ReadTimeoutError(None, None, None),
        ]

        got = self.post('/user.com/inbox', json=LIKE)
        self.assertEqual(502, got.status_code)

    def test_inbox_no_webmention_endpoint(self, mock_head, mock_get, mock_post):
        mock_get.side_effect = [
            # source actor
            self.as2_resp(LIKE_WITH_ACTOR['actor']),
            # protocol inference
            requests_response(test_web.NOTE_HTML),
            requests_response(test_web.NOTE_HTML),
            # target post webmention discovery
            HTML,
        ]

        got = self.post('/user.com/inbox', json=LIKE)
        self.assertEqual(204, got.status_code)

        self.assert_object('http://mas.to/like#ok',
                           notify=[self.user.key],
                           users=[self.masto_actor_key],
                           source_protocol='activitypub',
                           status='ignored',
                           our_as1=as2.to_as1(LIKE_WITH_ACTOR),
                           type='like',
                           object_ids=[LIKE['object']])

    def test_inbox_id_already_seen(self, *mocks):
        obj_key = Object(id=FOLLOW_WRAPPED['id'], as2={}).put()

        got = self.post('/user.com/inbox', json=FOLLOW_WRAPPED)
        self.assertEqual(204, got.status_code)
        self.assertEqual(0, Follower.query().count())

        # second time should use in memory cache
        obj_key.delete()
        got = self.post('/user.com/inbox', json=FOLLOW_WRAPPED)
        self.assertEqual(204, got.status_code)
        self.assertEqual(0, Follower.query().count())

    def test_followers_collection_unknown_user(self, *_):
        resp = self.client.get('/nope.com/followers')
        self.assertEqual(404, resp.status_code)

    def test_followers_collection_empty(self, *_):
        resp = self.client.get('/user.com/followers')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': 'http://localhost/user.com/followers',
            'type': 'Collection',
            'summary': "user.com's followers",
            'totalItems': 0,
            'first': {
                'type': 'CollectionPage',
                'partOf': 'http://localhost/user.com/followers',
                'items': [],
            },
        }, resp.json)

    def store_followers(self):
        follow = Object(id=FOLLOW_WITH_ACTOR['id'], as2=FOLLOW_WITH_ACTOR).put()

        Follower.get_or_create(
            to=self.user,
            from_=self.make_user('http://bar', cls=ActivityPub, obj_as2=ACTOR),
            follow=follow)
        Follower.get_or_create(
            to=self.make_user('https://other.actor', cls=ActivityPub),
            from_=self.user)
        Follower.get_or_create(
            to=self.user,
            from_=self.make_user('http://baz', cls=ActivityPub, obj_as2=ACTOR),
            follow=follow)
        Follower.get_or_create(
            to=self.user,
            from_=self.make_user('http://baj', cls=Fake),
            status='inactive')

    def test_followers_collection_fake(self, *_):
        self.make_user('foo.com', cls=Fake)

        resp = self.client.get('/ap/fake/foo.com/followers')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': 'http://localhost/ap/fake/foo.com/followers',
            'type': 'Collection',
            'summary': "foo.com's followers",
            'totalItems': 0,
            'first': {
                'type': 'CollectionPage',
                'partOf': 'http://localhost/ap/fake/foo.com/followers',
                'items': [],
            },
        }, resp.json)

    def test_followers_collection(self, *_):
        self.store_followers()

        resp = self.client.get('/user.com/followers')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': 'http://localhost/user.com/followers',
            'type': 'Collection',
            'summary': "user.com's followers",
            'totalItems': 2,
            'first': {
                'type': 'CollectionPage',
                'partOf': 'http://localhost/user.com/followers',
                'items': [ACTOR, ACTOR],
            },
        }, resp.json)

    @patch('models.PAGE_SIZE', 1)
    def test_followers_collection_page(self, *_):
        self.store_followers()
        before = (datetime.utcnow() + timedelta(seconds=1)).isoformat()
        next = Follower.query(Follower.from_ == ActivityPub(id='http://baz').key,
                              Follower.to == self.user.key,
                              ).get().updated.isoformat()

        resp = self.client.get(f'/user.com/followers?before={before}')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': f'http://localhost/user.com/followers?before={before}',
            'type': 'CollectionPage',
            'partOf': 'http://localhost/user.com/followers',
            'next': f'http://localhost/user.com/followers?before={next}',
            'prev': f'http://localhost/user.com/followers?after={before}',
            'items': [ACTOR],
        }, resp.json)

    def test_following_collection_unknown_user(self, *_):
        resp = self.client.get('/nope.com/following')
        self.assertEqual(404, resp.status_code)

    def test_following_collection_empty(self, *_):
        resp = self.client.get('/user.com/following')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': 'http://localhost/user.com/following',
            'summary': "user.com's following",
            'type': 'Collection',
            'totalItems': 0,
            'first': {
                'type': 'CollectionPage',
                'partOf': 'http://localhost/user.com/following',
                'items': [],
            },
        }, resp.json)

    def store_following(self):
        follow = Object(id=FOLLOW_WITH_ACTOR['id'], as2=FOLLOW_WITH_ACTOR).put()

        Follower.get_or_create(
            to=self.make_user('http://bar', cls=ActivityPub, obj_as2=ACTOR),
            from_=self.user,
            follow=follow)
        Follower.get_or_create(
            to=self.user,
            from_=self.make_user('https://other.actor', cls=ActivityPub))
        Follower.get_or_create(
            to=self.make_user('http://baz', cls=ActivityPub, obj_as2=ACTOR),
            from_=self.user, follow=follow)
        Follower.get_or_create(
            to=self.make_user('http://baj', cls=ActivityPub),
            from_=self.user,
            status='inactive')

    def test_following_collection(self, *_):
        self.store_following()

        resp = self.client.get('/user.com/following')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': 'http://localhost/user.com/following',
            'summary': "user.com's following",
            'type': 'Collection',
            'totalItems': 2,
            'first': {
                'type': 'CollectionPage',
                'partOf': 'http://localhost/user.com/following',
                'items': [ACTOR, ACTOR],
            },
        }, resp.json)

    @patch('models.PAGE_SIZE', 1)
    def test_following_collection_page(self, *_):
        self.store_following()
        after = datetime(1900, 1, 1).isoformat()
        prev = Follower.query(Follower.to == ActivityPub(id='http://baz').key,
                              Follower.from_ == self.user.key,
                              ).get().updated.isoformat()

        resp = self.client.get(f'/user.com/following?after={after}')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': f'http://localhost/user.com/following?after={after}',
            'type': 'CollectionPage',
            'partOf': 'http://localhost/user.com/following',
            'prev': f'http://localhost/user.com/following?after={prev}',
            'next': f'http://localhost/user.com/following?before={after}',
            'items': [ACTOR],
        }, resp.json)

    def test_outbox_fake(self, *_):
        self.make_user('foo.com', cls=Fake)
        resp = self.client.get(f'/ap/fake/foo.com/outbox')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': 'http://localhost/ap/fake/foo.com/outbox',
            'summary': "foo.com's outbox",
            'type': 'OrderedCollection',
            'totalItems': 0,
            'first': {
                'type': 'CollectionPage',
                'partOf': 'http://localhost/ap/fake/foo.com/outbox',
                'items': [],
            },
        }, resp.json)

    def test_outbox_web(self, *_):
        resp = self.client.get(f'/user.com/outbox')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({
            '@context': 'https://www.w3.org/ns/activitystreams',
            'id': 'http://localhost/user.com/outbox',
            'summary': "user.com's outbox",
            'type': 'OrderedCollection',
            'totalItems': 0,
            'first': {
                'type': 'CollectionPage',
                'partOf': 'http://localhost/user.com/outbox',
                'items': [],
            },
        }, resp.json)

class ActivityPubUtilsTest(TestCase):
    def setUp(self):
        super().setUp()
        g.user = self.make_user('user.com', has_hcard=True, obj_as2=ACTOR)

    def test_put_validates_id(self, *_):
        for bad in (
            '',
            'not a url',
            'ftp://not.web/url',
            'https:///no/domain',
            'https://fed.brid.gy/foo',
            'https://ap.brid.gy/foo',
            'http://localhost/foo',
        ):
            with self.assertRaises(AssertionError):
                ActivityPub(id=bad).put()

    def test_owns_id(self):
        self.assertIsNone(ActivityPub.owns_id('http://foo'))
        self.assertIsNone(ActivityPub.owns_id('https://bar/baz'))
        self.assertFalse(ActivityPub.owns_id('at://did:plc:foo/bar/123'))
        self.assertFalse(ActivityPub.owns_id('e45fab982'))

        self.assertFalse(ActivityPub.owns_id('https://twitter.com/foo'))
        self.assertFalse(ActivityPub.owns_id('https://fed.brid.gy/foo'))

    def test_postprocess_as2_multiple_in_reply_tos(self):
        self.assert_equals({
            'id': 'http://localhost/r/xyz',
            'inReplyTo': 'foo',
            'to': [as2.PUBLIC_AUDIENCE],
        }, postprocess_as2({
            'id': 'xyz',
            'inReplyTo': ['foo', 'bar'],
        }))

    def test_postprocess_as2_multiple_url(self):
        self.assert_equals({
            'id': 'http://localhost/r/xyz',
            'url': ['http://localhost/r/foo', 'http://localhost/r/bar'],
            'to': [as2.PUBLIC_AUDIENCE],
        }, postprocess_as2({
            'id': 'xyz',
            'url': ['foo', 'bar'],
        }))

    def test_postprocess_as2_multiple_image(self):
        self.assert_equals({
            'id': 'http://localhost/r/xyz',
            'attachment': [{'url': 'http://r/foo'}, {'url': 'http://r/bar'}],
            'image': [{'url': 'http://r/foo'}, {'url': 'http://r/bar'}],
            'to': [as2.PUBLIC_AUDIENCE],
        }, postprocess_as2({
            'id': 'xyz',
            'image': [{'url': 'http://r/foo'}, {'url': 'http://r/bar'}],
        }))

    def test_postprocess_as2_actor_attributedTo(self):
        g.user = Fake(id='site')
        self.assert_equals({
            'actor': {
                'id': 'baj',
                'preferredUsername': 'site',
                'url': 'http://localhost/r/site',
                'inbox': 'http://bf/fake/site/ap/inbox',
                'outbox': 'http://bf/fake/site/ap/outbox',
            },
            'attributedTo': [{
                'id': 'bar',
                'preferredUsername': 'site',
                'url': 'http://localhost/r/site',
                'inbox': 'http://bf/fake/site/ap/inbox',
                'outbox': 'http://bf/fake/site/ap/outbox',
            }, {
                'id': 'baz',
                'preferredUsername': 'site',
                'url': 'http://localhost/r/site',
                'inbox': 'http://bf/fake/site/ap/inbox',
                'outbox': 'http://bf/fake/site/ap/outbox',
            }],
            'to': [as2.PUBLIC_AUDIENCE],
        }, postprocess_as2({
            'attributedTo': [{'id': 'bar'}, {'id': 'baz'}],
            'actor': {'id': 'baj'},
        }))

    def test_postprocess_as2_note(self):
        self.assert_equals({
            'id': 'http://localhost/r/xyz',
            'type': 'Note',
            'to': [as2.PUBLIC_AUDIENCE],
        }, postprocess_as2({
            'id': 'xyz',
            'type': 'Note',
        }))

    def test_postprocess_as2_hashtag(self):
        """https://github.com/snarfed/bridgy-fed/issues/45"""
        self.assert_equals({
            'tag': [
                {'type': 'Hashtag', 'name': '#bar', 'href': 'bar'},
                {'type': 'Hashtag', 'name': '#baz', 'href': 'http://localhost/hashtag/baz'},
                {'type': 'Mention', 'href': 'foo'},
            ],
            'to': ['https://www.w3.org/ns/activitystreams#Public'],
        }, postprocess_as2({
            'tag': [
                {'name': 'bar', 'href': 'bar'},
                {'type': 'Tag', 'name': '#baz'},
                # should leave alone
                {'type': 'Mention', 'href': 'foo'},
            ],
        }))

    def test_postprocess_as2_url_attachments(self):
        got = postprocess_as2(as2.from_as1({
            'objectType': 'person',
            'urls': [
                {
                    'value': 'https://user.com/about-me',
                    'displayName': 'Mrs. \u2615 Foo',
                }, {
                    'value': 'https://user.com/',
                    'displayName': 'should be ignored',
                }, {
                    'value': 'http://one',
                    'displayName': 'one text',
                }, {
                    'value': 'https://two',
                    'displayName': 'two title',
                },
            ]
        }))

        self.assert_equals([{
            'type': 'PropertyValue',
            'name': 'Mrs. ☕ Foo',
            'value': 'https://user.com/about-me',

        }, {
            'type': 'PropertyValue',
            'name': 'Web site',
            'value': 'https://user.com/',
        }, {
            'type': 'PropertyValue',
            'name': 'one text',
            'value': 'http://one',
        }, {
            'type': 'PropertyValue',
            'name': 'two title',
            'value': 'https://two',
        }], got['attachment'])

    def test_postprocess_as2_preserves_preferredUsername(self):
        # preferredUsername stays y.z despite user's username. since Mastodon
        # queries Webfinger for preferredUsername@fed.brid.gy
        # https://github.com/snarfed/bridgy-fed/issues/77#issuecomment-949955109
        self.assertEqual('user.com', postprocess_as2({
            'type': 'Person',
            'url': 'https://user.com/about-me',
            'preferredUsername': 'nick',
            'attachment': [{
                'type': 'PropertyValue',
                'name': 'nick',
                'value': 'https://user.com/about-me',
            }],
        })['preferredUsername'])

    # TODO: make these generic and use Fake
    @patch('requests.get')
    def test_load_http(self, mock_get):
        mock_get.return_value = AS2

        id = 'http://the/id'
        self.assertIsNone(Object.get_by_id(id))

        # first time fetches over HTTP
        got = ActivityPub.load(id)
        self.assert_equals(id, got.key.id())
        self.assert_equals(AS2_OBJ, got.as2)
        mock_get.assert_has_calls([self.as2_req(id)])

        # second time is in cache
        got.key.delete()
        mock_get.reset_mock()

        got = ActivityPub.load(id)
        self.assert_equals(id, got.key.id())
        self.assert_equals(AS2_OBJ, got.as2)
        mock_get.assert_not_called()

    @patch('requests.get')
    def test_load_datastore(self, mock_get):
        id = 'http://the/id'
        stored = Object(id=id, as2=AS2_OBJ)
        stored.put()
        protocol.objects_cache.clear()

        # first time loads from datastore
        got = ActivityPub.load(id)
        self.assert_entities_equal(stored, got)
        mock_get.assert_not_called()

        # second time is in cache
        stored.key.delete()
        got = ActivityPub.load(id)
        self.assert_entities_equal(stored, got)
        mock_get.assert_not_called()

    @patch('requests.get')
    def test_load_preserves_fragment(self, mock_get):
        stored = Object(id='http://the/id#frag', as2=AS2_OBJ)
        stored.put()
        protocol.objects_cache.clear()

        got = ActivityPub.load('http://the/id#frag')
        self.assert_entities_equal(stored, got)
        mock_get.assert_not_called()

    @patch('requests.get')
    def test_load_datastore_no_as2(self, mock_get):
        """If the stored Object has no as2, we should fall back to HTTP."""
        id = 'http://the/id'
        stored = Object(id=id, as2={}, status='in progress')
        stored.put()
        protocol.objects_cache.clear()

        mock_get.return_value = AS2
        got = ActivityPub.load(id)
        mock_get.assert_has_calls([self.as2_req(id)])

        self.assert_equals(id, got.key.id())
        self.assert_equals(AS2_OBJ, got.as2)
        mock_get.assert_has_calls([self.as2_req(id)])

        self.assert_object(id,
                           as2=AS2_OBJ,
                           as1={**AS2_OBJ, 'id': id},
                           source_protocol='activitypub',
                           # check that it reused our original Object
                           status='in progress')

    @patch('requests.get')
    def test_signed_get_redirects_manually_with_new_sig_headers(self, mock_get):
        mock_get.side_effect = [
            requests_response(status=302, redirected_url='http://second',
                              allow_redirects=False),
            requests_response(status=200, allow_redirects=False),
        ]
        activitypub.signed_get('https://first')

        first = mock_get.call_args_list[0][1]
        second = mock_get.call_args_list[1][1]
        self.assertNotEqual(first['headers'], second['headers'])

    @patch('requests.get')
    def test_signed_get_redirects_to_relative_url(self, mock_get):
        mock_get.side_effect = [
            # redirected URL is relative, we have to resolve it
            requests_response(status=302, redirected_url='/second',
                              allow_redirects=False),
            requests_response(status=200, allow_redirects=False),
        ]
        activitypub.signed_get('https://first')

        self.assertEqual(('https://first/second',), mock_get.call_args_list[1][0])

        first = mock_get.call_args_list[0][1]
        second = mock_get.call_args_list[1][1]

        # headers are equal because host is the same
        self.assertEqual(first['headers'], second['headers'])
        self.assertEqual(
            first['auth'].header_signer.sign(first['headers'], method='GET', path='/'),
            second['auth'].header_signer.sign(second['headers'], method='GET', path='/'))

    @patch('requests.post')
    def test_signed_post_ignores_redirect(self, mock_post):
        mock_post.side_effect = [
            requests_response(status=302, redirected_url='http://second',
                              allow_redirects=False),
        ]

        resp = activitypub.signed_post('https://first')
        mock_post.assert_called_once()
        self.assertEqual(302, resp.status_code)

    @patch('requests.get')
    def test_fetch_direct(self, mock_get):
        mock_get.return_value = AS2
        obj = Object(id='http://orig')
        ActivityPub.fetch(obj)
        self.assertEqual(AS2_OBJ, obj.as2)

        mock_get.assert_has_calls((
            self.as2_req('http://orig'),
        ))

    @patch('requests.get')
    def test_fetch_direct_ld_content_type(self, mock_get):
        mock_get.return_value = requests_response(AS2_OBJ, headers={
            'Content-Type': 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
        })
        obj = Object(id='http://orig')
        ActivityPub.fetch(obj)
        self.assertEqual(AS2_OBJ, obj.as2)

        mock_get.assert_has_calls((
            self.as2_req('http://orig'),
        ))

    @patch('requests.get')
    def test_fetch_via_html(self, mock_get):
        mock_get.side_effect = [HTML_WITH_AS2, AS2]
        obj = Object(id='http://orig')
        ActivityPub.fetch(obj)
        self.assertEqual(AS2_OBJ, obj.as2)

        mock_get.assert_has_calls((
            self.as2_req('http://orig'),
            self.as2_req('http://as2', headers=as2.CONNEG_HEADERS),
        ))

    @patch('requests.get')
    def test_fetch_only_html(self, mock_get):
        mock_get.return_value = HTML

        obj = Object(id='http://orig')
        self.assertFalse(ActivityPub.fetch(obj))
        self.assertIsNone(obj.as1)

    @patch('requests.get')
    def test_fetch_not_acceptable(self, mock_get):
        mock_get.return_value = NOT_ACCEPTABLE

        obj = Object(id='http://orig')
        self.assertFalse(ActivityPub.fetch(obj))
        self.assertIsNone(obj.as1)

    @patch('requests.get')
    def test_fetch_ssl_error(self, mock_get):
        mock_get.side_effect = requests.exceptions.SSLError
        with self.assertRaises(BadGateway):
            ActivityPub.fetch(Object(id='http://orig'))

    @patch('requests.get')
    def test_fetch_no_content(self, mock_get):
        mock_get.return_value = self.as2_resp('')

        with self.assertRaises(BadGateway):
            ActivityPub.fetch(Object(id='http://the/id'))

        mock_get.assert_has_calls([self.as2_req('http://the/id')])

    @patch('requests.get')
    def test_fetch_not_json(self, mock_get):
        mock_get.return_value = self.as2_resp('XYZ not JSON')

        with self.assertRaises(BadGateway):
            ActivityPub.fetch(Object(id='http://the/id'))

        mock_get.assert_has_calls([self.as2_req('http://the/id')])

    def test_fetch_non_url(self):
        obj = Object(id='x y z')
        self.assertFalse(ActivityPub.fetch(obj))
        self.assertIsNone(obj.as1)

    @skip
    def test_serve(self):
        obj = Object(id='http://orig', as2=LIKE)
        self.assertEqual((LIKE_WRAPPED, {'Content-Type': 'application/activity+json'}),
                         ActivityPub.serve(obj))

    def test_postprocess_as2_idempotent(self):
        g.user = self.make_user('foo.com')

        for obj in (ACTOR, REPLY_OBJECT, REPLY_OBJECT_WRAPPED, REPLY,
                    NOTE_OBJECT, NOTE, MENTION_OBJECT, MENTION, LIKE,
                    LIKE_WRAPPED, REPOST, FOLLOW, FOLLOW_WRAPPED, ACCEPT,
                    UNDO_FOLLOW_WRAPPED, DELETE, UPDATE_NOTE,
                    # TODO: these currently fail
                    # LIKE_WITH_ACTOR, REPOST_FULL, FOLLOW_WITH_ACTOR,
                    # FOLLOW_WRAPPED_WITH_ACTOR, FOLLOW_WITH_OBJECT, UPDATE_PERSON,
                    ):
            with self.subTest(obj=obj):
                obj = copy.deepcopy(obj)
                self.assert_equals(postprocess_as2(obj),
                                   postprocess_as2(postprocess_as2(obj)),
                                   ignore=['to'])

    def test_ap_address(self):
        user = ActivityPub(obj=Object(id='a', as2={**ACTOR, 'preferredUsername': 'me'}))
        self.assertEqual('@me@mas.to', user.ap_address())
        self.assertEqual('@me@mas.to', user.readable_id)

        user.obj.as2 = ACTOR
        self.assertEqual('@swentel@mas.to', user.ap_address())
        self.assertEqual('@swentel@mas.to', user.readable_id)

        user = ActivityPub(id='https://mas.to/users/alice')
        self.assertEqual('@alice@mas.to', user.ap_address())
        self.assertEqual('@alice@mas.to', user.readable_id)

    def test_ap_actor(self):
        user = self.make_user('http://foo/actor', cls=ActivityPub)
        self.assertEqual('http://foo/actor', user.ap_actor())

    def test_web_url(self):
        user = self.make_user('http://foo/actor', cls=ActivityPub)
        self.assertEqual('http://foo/actor', user.web_url())

        user.obj = Object(id='a', as2=copy.deepcopy(ACTOR))  # no url
        self.assertEqual('http://foo/actor', user.web_url())

        user.obj.as2['url'] = ['http://my/url']
        self.assertEqual('http://my/url', user.web_url())

    def test_readable_id(self):
        user = self.make_user('http://foo', cls=ActivityPub)
        self.assertIsNone(user.readable_id)
        self.assertEqual('http://foo', user.readable_or_key_id())

        user.obj = Object(id='a', as2=ACTOR)
        self.assertEqual('@swentel@mas.to', user.readable_id)
        self.assertEqual('@swentel@mas.to', user.readable_or_key_id())

    @skip
    def test_target_for_not_activitypub(self):
        with self.assertRaises(AssertionError):
            ActivityPub.target_for(Object(source_protocol='web'))

    def test_target_for_actor(self):
        self.assertEqual(ACTOR['inbox'], ActivityPub.target_for(
            Object(source_protocol='ap', as2=ACTOR)))

        actor = copy.deepcopy(ACTOR)
        del actor['inbox']
        self.assertIsNone(ActivityPub.target_for(
            Object(source_protocol='ap', as2=actor)))

        actor['publicInbox'] = 'so-public'
        self.assertEqual('so-public', ActivityPub.target_for(
            Object(source_protocol='ap', as2=actor)))

        # sharedInbox
        self.assertEqual('so-public', ActivityPub.target_for(
            Object(source_protocol='ap', as2=actor), shared=True))
        actor['endpoints'] = {
            'sharedInbox': 'so-shared',
        }
        self.assertEqual('so-public', ActivityPub.target_for(
            Object(source_protocol='ap', as2=actor)))
        self.assertEqual('so-shared', ActivityPub.target_for(
            Object(source_protocol='ap', as2=actor), shared=True))

    def test_target_for_object(self):
        obj = Object(as2=NOTE_OBJECT, source_protocol='ap')
        self.assertIsNone(ActivityPub.target_for(obj))

        Object(id=ACTOR['id'], as2=ACTOR).put()
        obj.as2 = {
            **NOTE_OBJECT,
            'author': ACTOR['id'],
        }
        self.assertEqual('http://mas.to/inbox', ActivityPub.target_for(obj))

        del obj.as2['author']
        obj.as2['actor'] = copy.deepcopy(ACTOR)
        obj.as2['actor']['url'] = [obj.as2['actor'].pop('id')]
        self.assertEqual('http://mas.to/inbox', ActivityPub.target_for(obj))

    @patch('requests.get')
    def test_target_for_object_fetch(self, mock_get):
        mock_get.return_value = self.as2_resp(ACTOR)

        obj = Object(as2={
            **NOTE_OBJECT,
            'author': 'http://the/author',
        }, source_protocol='ap')
        self.assertEqual('http://mas.to/inbox', ActivityPub.target_for(obj))
        mock_get.assert_has_calls([self.as2_req('http://the/author')])

    @patch('requests.get')
    def test_target_for_author_is_object_id(self, mock_get):
        obj = self.store_object(id='http://the/author', our_as1={
            'author': 'http://the/author',
        })
        # test is that we short circuit out instead of infinite recursion
        self.assertIsNone(ActivityPub.target_for(obj))

    @patch('requests.post')
    def test_send_blocklisted(self, mock_post):
        self.assertFalse(ActivityPub.send(Object(as2=NOTE),
                                          'https://fed.brid.gy/ap/sharedInbox'))
        mock_post.assert_not_called()


# Things to show
# Name, Orbital Radius, Gravity, Mass, Distance, Planet Type, Goldilock, Discovery Date, Mass of hoststar
from flask import Flask, jsonify, make_response
from pandas import read_csv

app = Flask(__name__)

data = read_csv("csv/display.csv")

@app.get("/")
def index():
  to_send = []
  i = 1
  while True:
    res = get_data(i)
    if res[0] == False:
      break
    to_send.append(res[1])
    i += 1
  return cors(jsonify(to_send))

@app.route("/home")
def get_home():
  to_send = []
  columns = data.columns[1:]
  columns_to_share = ["name", "planet_type"]
  i = 0
  while True:
    try:
      planet_data = {}
      response = data.iloc[i].to_json(orient='records')[1:-1].split(",")[1:]
      for j, item in enumerate(response):
        if columns[j] in columns_to_share:
          planet_data.update({ columns[j]: item.replace("\"", "").replace("\"", "") })
      planet_data.update({ "index": i })
      to_send.append(planet_data)
    except:
      break
    i += 1
  return to_send

@app.route("/get/<int:i>")
def get_data_end_point(i):
  return cors(jsonify(get_data(i)))

def get_data(i):
  try:
    to_send = {}
    columns = data.columns[1:]
    response = data.iloc[i].to_json(orient='records')[1:-1].split(",")[1:]
    for j, item in enumerate(response):
      to_send.update({ columns[j]: item.replace("\"", "").replace("\"", "") })
    return [True, to_send]
  except:
    return [False, {}]

def cors(res):
  res.headers.add("Access-Control-Allow-Origin", "*")
  return res

if __name__ == "__main__":
  app.run()


import boto3
import uuid
import json
from jwcrypto import jwt, jwk

DDB_CLIENT = boto3.client('dynamodb')

ddb_table = "iowt-devices"

def create_new_device():
    id = str(uuid.uuid4())
    key = jwk.JWK(generate="oct", size=256)
    key_data = json.loads(key.export())['k']
    token = jwt.JWT(header={"alg": "A256KW", "enc": "A256CBC-HS512"},
                    claims={"device_id": id})
    token.make_encrypted_token(key)

    return id, key_data, token.serialize()

device_id, key, token = create_new_device()

db_item = dict()
db_item['id'] = {'S': device_id}
db_item['deviceLocation'] = {'S': "Not Set"}
db_item['deviceName'] = {'S': "Not Set"}
db_item['deviceKey'] = {'S': key}
db_item['deviceToken'] = {'S': token}
db_item['deviceStatus'] = {'S': "new"}
db_item['deviceOwner'] = {'S': "none"}

DDB_CLIENT.put_item(TableName=ddb_table,
                    Item=db_item)


import jax
import numpy as np
import pytest

import hilbert_sort.jax as jax_backend
import hilbert_sort.numba as np_backend

@pytest.fixture(scope="module", autouse=True)
def config_pytest():
    jax.config.update("jax_enable_x64", True)

@pytest.mark.parametrize("dim_x", [2, 3, 4])
@pytest.mark.parametrize("N", [150, 250])
@pytest.mark.parametrize("seed", [0, 42, 666])
def test_random_agree(dim_x, N, seed):
    np.random.seed(seed)
    x = np.random.randn(N, dim_x)
    np_res = np_backend.hilbert_sort(x)
    jax_res = jax_backend.hilbert_sort(x)
    np.testing.assert_allclose(np_res, jax_res)

@pytest.mark.parametrize("nDests", [2, 3, 4, 5])
@pytest.mark.parametrize("N", [150, 250])
@pytest.mark.parametrize("seed", [0, 42, 666])
def test_transpose_bits(nDests, N, seed):
    np.random.seed(seed)
    x = np.random.randint(0, 150021651, (5,))
    np_res = np_backend.transpose_bits(x, nDests)
    jax_res = jax_backend.transpose_bits(x, nDests)
    np.testing.assert_allclose(np_res, jax_res)

@pytest.mark.parametrize("nDests", [5, 7, 12])
@pytest.mark.parametrize("N", [150, 250])
@pytest.mark.parametrize("seed", [0, 42, 666])
def test_unpack_coords(nDests, N, seed):
    np.random.seed(seed)
    x = np.random.randint(0, 150021651, (nDests,))
    max_int = 150021651
    np_res = np_backend.unpack_coords(x)
    jax_res = jax_backend.unpack_coords(x, max_int)
    np.testing.assert_allclose(np_res, jax_res)

def test_gray_decode():
    for n in range(5, 1_000):
        np_res = np_backend.gray_decode(n)
        jax_res = jax_backend.gray_decode(n)
        np.testing.assert_allclose(np_res, jax_res)


import xml.etree.ElementTree as ET
from datetime import date
from pathlib import Path

def _convert_dict(temp_dict):
    """
    Convert one dict to a new one

    :param temp_dict: A temporary dict
    :type temp_dict: dict
    :return: The same dict in a new formate that fits with the database
    :rtype: dict
    """
    data_dict = {}
    for transferee in temp_dict:
        counter = 0
        for transferee_counter in temp_dict[transferee]["transferees"]:
            temp_name = f"{transferee}_{counter}"
            data_dict[temp_name] = {}

            # for info in data_dict[transferee]["transferees"][transferee_counter]:
            data_dict[temp_name]["SourceBarcode"] = temp_dict[transferee]["source"]
            data_dict[temp_name]["SourceWell"] = temp_dict[transferee]["transferees"][transferee_counter]["source_well"]
            data_dict[temp_name]["DestinationBarcode"] = temp_dict[transferee]["destination"]
            data_dict[temp_name]["DestinationWell"] = temp_dict[transferee]["transferees"][transferee_counter]["destination_well"]
            data_dict[temp_name]["Volume"] = temp_dict[transferee]["transferees"][transferee_counter]["transferee_volume"]
            counter += 1
    return data_dict

def _get_transferee_dict(file_list):
    """
    Translate XML file_lise in to two dict

    :param file_list: A list of files
    :type file_list: list
    :return:
        - transferee: what have been transfereed
        - destination_plates: What plate the transferee have gone to
    :rtype:
        - dict
        - dict

    """

    transferee = {}
    destination_plates = {}
    # source_plate = {}

    for i in file_list:
        doc = ET.parse(i)
        root = doc.getroot()

        for dates in root.iter("transfer"):
            date_running = dates.get("date")
            date_str = f"plate_production_{date_running}"
            transferee[date_str] = {}

        # finds barcode for source and destination
        for plates in root.iter("plate"):
            source_destination = plates.get("type")
            barcode = plates.get("barcode")
            transferee[date_str][source_destination] = barcode

            # if plates.get("type") == "source":
            #     source_plate[barcode] = {}
            #     source_plate[barcode]["SourceBarcode"] = barcode
            #     source_plate[barcode]["date"] = date.today()

            if plates.get("type") == "destination":
                destination_plates[barcode] = {}
                destination_plates[barcode]["DestinationBarcode"] = barcode
                destination_plates[barcode]["date"] = date.today()

        # find source, destination and volume for each transferee
        for wells_t in root.iter("printmap"):
            wells_transferee = int(wells_t.get("total"))
            transferee[date_str]["transferees"] = {}
            for counter in range(wells_transferee):
                temp_str = f"Transferee_{counter + 1}"
                transferee[date_str]["transferees"][temp_str] = {}

                wells_source = wells_t[counter].get("n")
                wells_destination = wells_t[counter].get("dn")
                transferee_volume = float(wells_t[counter].get("vt")) * 10e-6

                transferee[date_str]["transferees"][temp_str]["source_well"] = wells_source
                transferee[date_str]["transferees"][temp_str]["destination_well"] = wells_destination
                transferee[date_str]["transferees"][temp_str]["transferee_volume"] = transferee_volume

        # find source, destination and reason for each skipped well
        for wells in root.iter("skippedwells"):
            wells_skipped = int(wells.get("total"))
            transferee[date_str]["Skipped"] = {}

            # finds destination and source wells data
            for z in range(wells_skipped):
                temp_str = f"Skipped_{z + 1}"
                transferee[date_str]["Skipped"][temp_str] = {}
                wells_destination = wells[z].get("dn")
                wells_source = wells[z].get("n")
                reason = wells[z].get("reason")

                transferee[date_str]["Skipped"][temp_str]["source_well"] = wells_source
                transferee[date_str]["Skipped"][temp_str]["destination_well"] = wells_destination
                transferee[date_str]["Skipped"][temp_str]["reason"] = reason

    return transferee, destination_plates

def xml_controller(file_list):
    """
    Controls the XML reader

    :param file_list: List of files with XML data
    :type file_list: list
    :return:
        - transferee: what have been transfereed
        - destination_plates: What plate the transferee have gone to
    :rtype:
        - dict
        - dict
    """

    transferee_dict, destination_plates = _get_transferee_dict(file_list)
    data_dict = _convert_dict(transferee_dict)

    return data_dict, destination_plates

def convert_echo_to_db(files):

    echo_to_db = {}
    transfer_counter = 0
    for file_index, files in enumerate(files):
        files = Path(files)
        if files.name.startswith("Transfer"):
            doc = ET.parse(files)
            root = doc.getroot()
            # for counting plates and transferees
            for plates in root.iter("plate"):
                barcode = plates.get("barcode")
                source_destination = plates.get("type")

                if source_destination == "destination":
                    temp_d_barcode = barcode
                if source_destination == "source":
                    temp_s_barcode = barcode

            try:
                echo_to_db[temp_d_barcode]
            except KeyError:
                echo_to_db[temp_d_barcode] = {"skipped_wells": {},
                                              "transferred_wells": {}}
            for wells in root.iter("printmap"):
                wells_transferred = wells.get("total")
                if int(wells_transferred) != 0:
                    for z in range(int(wells_transferred)):
                        destination_well = wells[z].get("dn")
                        source_well = wells[z].get("n")
                        vol = wells[z].get("vt")
                        echo_to_db[temp_d_barcode]["transferred_wells"][destination_well] = {
                            "mp_source_plate": temp_s_barcode,
                            "mp_source_well": source_well,
                            "vol": vol}

            for wells in root.iter("skippedwells"):
                wells_skipped = wells.get("total")
                if int(wells_skipped) != 0:
                    transfer_counter += 1

                    for z in range(int(wells_skipped)):
                        destination_well = wells[z].get("dn")
                        source_well = wells[z].get("n")
                        reason = wells[z].get("reason")

                        reason = reason.split(":")[0]
                        echo_to_db[temp_d_barcode]["skipped_wells"][destination_well] = {
                            "mp_source_plate": temp_s_barcode,
                            "mp_source_well": source_well,
                            "reason": reason}

    return echo_to_db

if __name__ == "__main__":
    path = "2022-03-03"
    from file_handler import get_file_list

    file_list = get_file_list(path)

    data, test = xml_controller(file_list)

    print(data)


import csv
import MySQLdb

mydb= MySQLdb.connect(host='localhost',
    user='root',
    db='celebal')
cursor=mydb.cursor()

with open('dataset1.csv', 'r') as csvfile:
	csv_data1 = csv.reader(csvfile, delimiter=',')
	next(csv_data1)
	cursor.execute("TRUNCATE TABLE data1")
	for row in csv_data1:
		cursor.execute("INSERT INTO data1(ID,Cities,Pincode,Office_ID) VALUES(%s,%s,%s,%s)",row)
	mydb.commit()
with open('dataset2.csv','r') as csvfile2:
	csv_data2 = csv.reader(csvfile2,delimiter=',')
	next(csv_data2)
	cursor.execute("TRUNCATE TABLE data2")
	for row in csv_data2:
		cursor.execute("INSERT INTO data2(ID,Office_ID,Population) VALUES(%s,%s,%s)",row)
	mydb.commit()
cursor.execute("DROP TABLE new_records")
sql=("CREATE TABLE new_records AS SELECT d.ID,d.Office_ID,d.Cities,d.Pincode,dd.population from data1 d join data2 dd on d.Office_ID=dd.Office_ID;")
cursor.execute(sql)
cursor.close()
print("Done")


import tkinter as tk
from tkinter import ttk
from tkinter import *

import numpy as np
from PIL import ImageTk, Image
from os import listdir
from os.path import isfile, join

from PIL.Image import Resampling
from hopfield_clouds import HopfieldClouds

# root.columnconfigure(0, weight=1)
# root.columnconfigure(1, weight=3)

class GUI:
    def __init__(self):
        self.picture_size = 420
        self.network = HopfieldClouds(130 ** 2)
        self.root = tk.Tk()
        self.root.geometry('1280x500')
        self.root.title('Hopfield Clouds')

        self.next_button = ttk.Button(self.root, text='>', command=self.next_image)
        self.next_button.grid(row=1, column=0, sticky=tk.E)

        self.prev_button = ttk.Button(self.root, text='<', command=self.prev_image)
        self.prev_button.grid(row=1, column=0, sticky=tk.W)

        self.original_img = self.network.get_current_image()
        self.original_img = self.original_img.resize((self.picture_size, self.picture_size), Resampling.LANCZOS)
        self.img_tk = ImageTk.PhotoImage(self.original_img)

        original_frame = Frame(self.root, width=self.picture_size, height=self.picture_size)
        original_frame.grid(row=0, columnspan=1, sticky='we')
        self.original_image_label = Label(original_frame, image=self.img_tk)
        self.original_image_label.grid(row=1, column=0)

        self.cropped_img = Image.fromarray(np.uint8(np.zeros((self.picture_size, self.picture_size, 3))))
        self.cropped_img = ImageTk.PhotoImage(self.cropped_img)
        self.cropped_frame = Frame(self.root, width=self.picture_size, height=self.picture_size)
        self.cropped_frame.grid(row=0, column=1, sticky='we')
        self.cropped_image_label = Label(self.cropped_frame, image=self.cropped_img)
        self.cropped_image_label.grid(row=1, column=1)

        self.current_value = tk.DoubleVar()
        #  slider
        self.slider = ttk.Scale(self.root, from_=1, to=99, orient='horizontal', command=self.slider_changed,
                                variable=self.current_value)
        self.slider.set(50)
        self.slider.bind('<ButtonRelease-1>', self.slider_up)
        self.slider_label = Label(self.root, text='Percentage to crop:')
        self.slider_label.grid(row=1, column=1, columnspan=1, sticky='we')
        self.slider.grid(column=1, columnspan=1, row=2, sticky='we')

        self.value_label = ttk.Label(self.root, text=self.get_current_value())
        self.value_label.grid(row=3, column=1, columnspan=1, sticky='n')

        self.reconstructed_img = Image.fromarray(np.uint8(np.zeros((self.picture_size, self.picture_size, 3))))
        self.reconstructed_img = ImageTk.PhotoImage(self.reconstructed_img)
        self.reconstructed_frame = Frame(self.root, width=self.picture_size, height=self.picture_size)
        self.reconstructed_frame.grid(row=0, column=2, columnspan=1, sticky='n')
        self.reconstructed_image_label = Label(self.reconstructed_frame, image=self.reconstructed_img)
        self.reconstructed_image_label.grid(row=1, column=2, columnspan=1)
        self.reconstruct_button = ttk.Button(self.root, text='Reconstruct', command=self.reconstruct)
        self.reconstruct_button.grid(row=1, column=2, sticky='n')

        self.slider_up(None)
        self.root.mainloop()

    def slider_changed(self, event):
        self.value_label.configure(text=self.get_current_value())

    def get_current_value(self):
        return '{: .2f}'.format(self.current_value.get())

    def next_image(self):
        img = self.network.next_image()
        self.original_img = img.resize((self.picture_size, self.picture_size), Resampling.LANCZOS)
        self.img_tk = ImageTk.PhotoImage(self.original_img)
        self.original_image_label.configure(image=self.img_tk)
        self.slider_up(None)

    def prev_image(self):
        img = self.network.prev_image()
        self.original_img = img.resize((self.picture_size,self.picture_size), Resampling.LANCZOS)
        self.img_tk = ImageTk.PhotoImage(self.original_img)
        self.original_image_label.configure(image=self.img_tk)
        self.slider_up(None)

    def reconstruct(self):
        cropped, reconstructed = self.network.get_current_image_predictions(int(self.current_value.get()))
        self.reconstructed_img = reconstructed
        self.reconstructed_img = self.reconstructed_img.resize((self.picture_size, self.picture_size), Resampling.LANCZOS)
        self.reconstructed_img = ImageTk.PhotoImage(self.reconstructed_img)
        self.reconstructed_image_label.configure(image=self.reconstructed_img)

    def slider_up(self, event):
        cropped = self.network.get_current_cropped(int(self.current_value.get()))
        self.cropped_img = cropped
        self.cropped_img = self.cropped_img.resize((self.picture_size, self.picture_size), Resampling.LANCZOS)
        self.cropped_img = ImageTk.PhotoImage(self.cropped_img)
        self.cropped_image_label.configure(image=self.cropped_img)

gui = GUI()


import sys

sys.path.append('..')
import torch
from torch import nn
from torch.nn import functional as F

from ssd import config as cfg
from basenet.vgg import vgg_feat
from basenet.resnet import resnet101_feat
from ssd.utils_ssd.priorbox import PriorBox
from ssd.utils_ssd.L2Norm import L2Norm
from ssd.utils_ssd.detect import Detect

extras_vgg = {'300': [256, 'S', 512, 128, 'S', 256, 128, 256, 128, 256]}
extras_res = {'300': [256, 'S', 512, 128, 'S', 256, 128, 256, 128, 256]}
l_vgg = [23, 512]
l_res = [11, 512]
mbox_vgg = {'300': [(512, 4), (1024, 6), (512, 6), (256, 6), (256, 4), (256, 4)]}
mbox_res = {'300': [(512, 4), (2048, 6), (512, 6), (256, 6), (256, 4), (256, 4)]}

# extend vgg: 5 "additional" feature parts
def add_extras(i, cfg=extras_vgg, vgg=True):
    fc7 = [nn.MaxPool2d(3, 1, 1), nn.Conv2d(512, 1024, 3, 1, 6, 6), nn.ReLU(inplace=True),
           nn.Conv2d(1024, 1024, 1), nn.ReLU(inplace=True)] if vgg else []
    layers = []
    in_channels = i
    flag = False
    for k, v in enumerate(cfg):
        if in_channels != 'S':
            if v == 'S':
                layers += [nn.Conv2d(in_channels, cfg[k + 1],
                                     kernel_size=(1, 3)[flag], stride=2, padding=1)]
            else:
                layers += [nn.Conv2d(in_channels, v, kernel_size=(1, 3)[flag])]
            flag = not flag
        in_channels = v
    return fc7, layers

# feature map to loc+conf
def multibox(num_classes=21, cfg=mbox_vgg):
    loc_layers = []
    conf_layers = []
    for channel, n in cfg:
        loc_layers += [nn.Conv2d(channel, n * 4, 3, 1, 1)]
        conf_layers += [nn.Conv2d(channel, n * num_classes, 3, 1, 1)]
    return loc_layers, conf_layers

# single shot multibox detector
class SSD(nn.Module):
    def __init__(self, phase, base, extras, loc, conf, num_classes, l=l_vgg):
        super(SSD, self).__init__()
        self.phase = phase
        self.num_classes = num_classes
        self.priors = PriorBox(cfg.v2)()
        self.size = 300
        self.l = l[0]

        self.bone = nn.ModuleList(base)
        self.l2norm = L2Norm(l[1], 20)
        self.extras = nn.ModuleList(extras)
        self.loc, self.conf = nn.ModuleList(loc), nn.ModuleList(conf)

        if phase == 'test':
            self.detect = Detect(num_classes, cfg.top_k, cfg.conf_thresh, cfg.nms_thresh)

    def forward(self, x):
        source, loc, conf = list(), list(), list()
        for k in range(self.l):
            x = self.bone[k](x)
        source.append(self.l2norm(x))
        for k in range(self.l, len(self.bone)):
            x = self.bone[k](x)
        source.append(x)
        for k, v in enumerate(self.extras):
            x = F.relu(v(x), inplace=True)
            if k % 2 == 1:
                source.append(x)
        # apply multibox head to source layers
        for (x, l, c) in zip(source, self.loc, self.conf):
            loc.append(l(x).permute(0, 2, 3, 1).contiguous())
            conf.append(c(x).permute(0, 2, 3, 1).contiguous())
        loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)
        conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)
        if not self.priors.is_cuda and loc.is_cuda:
            self.priors = self.priors.cuda()
        if self.phase == 'test':
            output = self.detect(
                loc.view(loc.size(0), -1, 4),
                F.softmax(conf.view(conf.size(0), -1, self.num_classes), dim=2),
                self.priors
            )
        else:
            output = (
                loc.view(loc.size(0), -1, 4),
                conf.view(conf.size(0), -1, self.num_classes),
                self.priors
            )
        return output

def build_ssd(phase, size=300, num_classes=21, bone='vgg'):
    if phase != 'test' and phase != 'train':
        assert "Error: Phase not recognized"
    if size != 300:
        assert "Error: Only SSD300 us supported"
    if bone == 'vgg':
        base_ = vgg_feat()
        fc7_, extras_ = add_extras(1024, extras_vgg['300'])
        loc_, conf_ = multibox(num_classes, mbox_vgg['300'])
        l = l_vgg
    elif bone == 'res101':
        base_ = resnet101_feat()
        fc7_, extras_ = add_extras(2048, extras_res['300'], False)
        loc_, conf_ = multibox(num_classes, mbox_res['300'])
        l = l_res
    else:
        raise IOError("only vgg or res101")
    return SSD(phase, base_ + fc7_, extras_, loc_, conf_, num_classes, l)

if __name__ == '__main__':
    net = build_ssd('train', bone='vgg')
    img = torch.randn((1, 3, 300, 300))
    out = net(img)
    print(out[1])