def on_get(self, req, resp, user): auth_user = try_logged_jwt(auth_backend, req, resp) if auth_user and auth_user.id == user: photos = Status.select().join(User).where(UserProfile.username == auth_user.username).order_by(Status.created_at.desc()) #Must to considerer the case of friends relation else: photos = Status.select().join(User).where(UserProfile.username == user).where(Status.public == True).order_by(Status.created_at.desc()) query = [photo.to_model() for photo in photos] resp.body = json.dumps(query, default=str) resp.status = falcon.HTTP_200
async def get(self, user): photos = await self.application.objects.execute(Status.select().where( Status.user == user).order_by(Status.created_at.desc())) query = [photo.to_json() for photo in photos] print(query) self.write(json.dumps(query, default=str))
async def get(self): number_of_users = await self.application.objects.count( UserProfile.select()) number_of_statuses = await self.application.objects.count( Status.select()) response = { "version": "2.0", "software": { "name": "Anfora", "version": "Anfora {}".format(VERSION), }, "protocols": ["activitypub"], "services": { "inbound": [], "outbound": [] }, "openRegistrations": False, "usage": { "users": { "total": number_of_users }, "localPosts": number_of_statuses }, "metadata": { "sourceCode": "https://github.com/anforaProject/anfora", "nodeName": NODENAME, }, } self.write(response)
def on_get(self, req, resp): resp.append_header("Content-Type","application/json; profile=http://nodeinfo.diaspora.software/ns/schema/2.0#") response = { "version": "2.0", "software": { "name": "Anfora", "version": "Anfora {}".format(VERSION), }, "protocols": ["activitypub"], "services": {"inbound": [], "outbound": []}, "openRegistrations": False, "usage": { "users": { "total": UserProfile.select().count() }, "localPosts": Status.select().count() }, "metadata": { "sourceCode": "https://github.com/anforaProject/anfora", "nodeName": NODENAME, }, } resp.body = json.dumps(response) resp.status = falcon.HTTP_200
def get_status_list(): status_list = Status.select() board_id = request.form["board_id"] result = [] for status in status_list: result.append(status.status) init_cell_list(board_id) return jsonify(result)
async def get(self): query = await self.application.objects.execute( Status.select().where(Status.in_reply_to == None).limit(15)) data = [n.to_json() for n in query] self.write(json.dumps(data, default=str)) self.set_status(200)
def create_status(): if not Status.select(): status = Status(status="new") status.save() status = Status(status="progress") status.save() status = Status(status="review") status.save() status = Status(status="done") status.save()
async def get(self, id): try: user = await self.application.objects.get(User, id=id) user = user.profile.get() photos = await self.application.objects.execute( Status.select().where(Status.user == user).order_by( Status.created_at.desc())) query = [photo.to_json() for photo in photos] self.write(json.dumps(query, default=str)) except User.DoesNotExist: self.write({"Error": "User not found"})
async def get(self, id): try: photos = await self.application.objects.execute( Status.select().join(UserProfile).where( (Status.user.id == id) & Status.in_reply_to_id.is_null()).order_by( Status.created_at.desc())) query = [photo.to_json() for photo in photos] self.write(json.dumps(query, default=str)) except User.DoesNotExist: self.write({"Error": "User not found"})
async def get(self): users = await self.application.objects.execute( UserProfile.select().limit(5)) posts = await self.application.objects.execute( Status.select().where(Status.in_reply_to == None).limit(15)) data = { 'users': [user.to_json() for user in users], 'statuses': [status.to_json() for status in posts] } self.write(json.dumps(data, default=str)) self.set_status(200)
def on_post(self, req, resp): image = req.get_param('image') public = bool(req.get_param('public')) #False if None user = req.context['user'] if image != None: try: #Search a valid name valid = False ident = "" while not valid: ident = str(uuid.uuid4()) valid = not Status.select().where( Status.media_name == ident).exists() #temp_file = file_path + '~' #open(temp_file, 'wb').write(image.file.read()) #Create the image and the thumbnail create_image(io.BytesIO(image.file.read()), ident) user = req.context['user'] filename = image.filename dimensions = (1080, 1080) photo = upload_image(user, req.get_param('message'), req.get_param('description'), ident, req.get_param('sensitive'), dimensions, filename) photo.save() spreadStatus(photo) resp.status = falcon.HTTP_200 resp.body = json.dumps(photo.to_json(), default=str) except IOError: print(e) photo.delete_instance() resp.body = json.dumps({"Error": "Couldn't store file"}) resp.status = falcon.HTTP_500 else: resp.status = falcon.HTTP_500 resp.body = json.dumps({"Error": "No photo attached"})
async def get(self, user): #r = await aioredis.create_connection( # f"redis://{os.environ.get('REDIS_HOST', 'localhost')}", # loop=IOLoop.current().asyncio_loop, # encoding='utf-8' #) local = self.get_argument('media_ids', False) max_id = self.get_argument('max_id', None) since_id = self.get_argument('since_id', None) limit = self.get_argument('limit', 20) statuses = [] errors = 0 """ for post in TimelineManager(user).query(since_id=since_id, max_id=max_id, local=True, limit=limit): try: status = self.application.objects.get(Status,id=int(post)) json_data = status.to_json() count = await self.application.objects.count(Like.select().join(UserProfile).switch(Like).join(Status).switch(Like).where(Like.user.id == user.id, Like.status.id == status)) if count: json_data["favourited"] = True statuses.append(json_data) except: pass """ ids = TimelineManager(user).query(since_id=since_id, max_id=max_id, local=True, limit=limit) statuses = await self.application.objects.execute(Status.select().where(Status.id << ids).order_by(Status.created_at)) hydratated = [] for status in statuses: json_data = status.to_json() count = await self.application.objects.count(Like.select().join(UserProfile).switch(Like).join(Status).switch(Like).where(Like.user.id == user.id, Like.status.id == status)) if count: json_data["favourited"] = True hydratated.append(json_data) self.write(json.dumps(hydratated[::-1], default=str))
async def get(self, username): user = User.get_or_none(username=username) pagination = ap_pagination(self) if user: user = user.profile.get() # Retrive statuses objects = await self.application.objects.execute( Status.select().where(Status.user == user).order_by( Status.id).paginate(pagination['page'], pagination['default_pagination'])) objects = map(lambda x: x.to_activitystream(), objects) # create collection page collectionPage = activities.OrderedCollectionPage( map(activities.Note, objects), **pagination) # create collection collection = activities.OrderedCollection([collectionPage]) self.write(json.dumps(collectionPage.to_json(context=True))) self.set_status(200)
def generate_feed(user, max_id=-1): limit = 10 """ max_id indicates that the new posts should be younger than this value. user represents an User in the db """ base = """<?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:activity="http://activitystrea.ms/spec/1.0/" xmlns:poco="http://portablecontacts.net/spec/1.0" xmlns:media="http://purl.org/syndication/atommedia" xmlns:ostatus="http://ostatus.org/schema/1.0" xmlns:mastodon="http://mastodon.social/schema/1.0"> <id>{atom}</id> <title>{username}</title> <subtitle>{bio}</subtitle> <updated>{update_date}</updated> <logo></logo> <author> <id>{author_url}</id> <activity:object-type>http://activitystrea.ms/schema/1.0/person</activity:object-type> <uri>{author_url}</uri> <name>{author_url}</name> <email>{author_acct}</email> <summary type="html">{bio}</summary> <link rel="alternate" type="text/html" href="{author_url}"/> <link rel="avatar" type="image/jpeg" media:width="120" media:height="120" href="{avatar_url}"/> <poco:preferredUsername>{username}</poco:preferredUsername> <poco:displayName>{name}</poco:displayName> <poco:note>{bio}</poco:note> <mastodon:scope>public</mastodon:scope> </author> <link rel="next" href="{next_url}" type="application/atom+xml" /> <link rel="alternate" type="text/html" href="{author_url}"/> <link rel="self" type="application/atom+xml" href="{atom}"/> """ post = """ <entry> <title>New note by {username}</title> <link rel="alternate" href="{post_url}" /> <id>{post_id}</id> <summary type="html"> <![CDATA[{caption}]]></summary> <published>{published}</published> <updated>{updated}</updated> </entry> """ end = """ </feed> """ #https://pleroma.soykaf.com/users/lain/feed.atom?max_id=11598025 if (max_id != -1): photos = (Status.select( Status, User).join(User).where((Status.user == user) & (Status.id < max_id)).order_by( Status.id.desc()).limit(limit)) else: photos = (Status.select(Status, User).join(User).where( (Status.user == user)).order_by(Status.id.desc()).limit(limit)) user_statuses = user.statuses() update_date = None try: update_date = user.statuses().get().created_at except: update_date = datetime.datetime.now() statuses = [] # Avoid to create multiple times this dict user_uris = user.uris last_id = 0 for photo in photos: data = { "username": user.username, "post_url": photo.uris.id, "caption": html.escape(photo.caption), "published": photo.created_at, "updated": photo.updated_at, "post_id": photo.uris.id, "id": photo.id } string = post.format(**data) statuses.append(string) last_id = photo.id statuses.append(end) user_data = { "username": user.username, "name": user.name, "bio": user.description, "author_url": user_uris.id, "atom": user_uris.atom, "author_acct": 'acct:{}@{}'.format(user.username, DOMAIN), "next_url": user_uris.atom + "?max_id=" + str(last_id), "update_date": update_date, "avatar_url": user_uris.avatar } return base.format(**user_data) + '\n'.join(statuses)
from manage_db import connect from models.followers import FollowerRelation from models.user import UserProfile, User from models.status import Status connect() a = FollowerRelation.select() print("Follows:") for u in a: print(u) print("====================") print("Users:") for u in UserProfile.select(): print(u.username, " con ap_id ", str(u.ap_id)) print(list(u.timeline())) print("----") print("====================") print(UserProfile.select().count()) print("========") print("Statuss") for p in Status.select(): print(p) print("========") print("Following test:") t = User.get(username="******").profile print(t.followers().count())