label
class label
6 classes
code_before
stringlengths
75
187k
code_after
stringlengths
75
187k
label_text
stringclasses
6 values
deleted
dict
added
dict
normalized_code_before
stringlengths
75
152k
normalized_code_after
stringlengths
75
152k
before_doc_string_pos
sequence
after_doc_string_pos
sequence
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2017 Vector Creations Ltd # Copyright 2018-2019 New Vector Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests REST events for /rooms paths.""" import json from urllib import parse as urlparse from mock import Mock import synapse.rest.admin from synapse.api.constants import EventContentFields, EventTypes, Membership from synapse.handlers.pagination import PurgeStatus from synapse.rest.client.v1 import directory, login, profile, room from synapse.rest.client.v2_alpha import account from synapse.types import JsonDict, RoomAlias, UserID from synapse.util.stringutils import random_string from tests import unittest from tests.test_utils import make_awaitable PATH_PREFIX = b"/_matrix/client/api/v1" class RoomBase(unittest.HomeserverTestCase): rmcreator_id = None servlets = [room.register_servlets, room.register_deprecated_servlets] def make_homeserver(self, reactor, clock): self.hs = self.setup_test_homeserver( "red", http_client=None, federation_client=Mock(), ) self.hs.get_federation_handler = Mock() self.hs.get_federation_handler.return_value.maybe_backfill = Mock( return_value=make_awaitable(None) ) async def _insert_client_ip(*args, **kwargs): return None self.hs.get_datastore().insert_client_ip = _insert_client_ip return self.hs class RoomPermissionsTestCase(RoomBase): """ Tests room permissions. """ user_id = "@sid1:red" rmcreator_id = "@notme:red" def prepare(self, reactor, clock, hs): self.helper.auth_user_id = self.rmcreator_id # create some rooms under the name rmcreator_id self.uncreated_rmid = "!aa:test" self.created_rmid = self.helper.create_room_as( self.rmcreator_id, is_public=False ) self.created_public_rmid = self.helper.create_room_as( self.rmcreator_id, is_public=True ) # send a message in one of the rooms self.created_rmid_msg_path = ( "rooms/%s/send/m.room.message/a1" % (self.created_rmid) ).encode("ascii") request, channel = self.make_request( "PUT", self.created_rmid_msg_path, b'{"msgtype":"m.text","body":"test msg"}' ) self.assertEquals(200, channel.code, channel.result) # set topic for public room request, channel = self.make_request( "PUT", ("rooms/%s/state/m.room.topic" % self.created_public_rmid).encode("ascii"), b'{"topic":"Public Room Topic"}', ) self.assertEquals(200, channel.code, channel.result) # auth as user_id now self.helper.auth_user_id = self.user_id def test_can_do_action(self): msg_content = b'{"msgtype":"m.text","body":"hello"}' seq = iter(range(100)) def send_msg_path(): return "/rooms/%s/send/m.room.message/mid%s" % ( self.created_rmid, str(next(seq)), ) # send message in uncreated room, expect 403 request, channel = self.make_request( "PUT", "/rooms/%s/send/m.room.message/mid2" % (self.uncreated_rmid,), msg_content, ) self.assertEquals(403, channel.code, msg=channel.result["body"]) # send message in created room not joined (no state), expect 403 request, channel = self.make_request("PUT", send_msg_path(), msg_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) # send message in created room and invited, expect 403 self.helper.invite( room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id ) request, channel = self.make_request("PUT", send_msg_path(), msg_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) # send message in created room and joined, expect 200 self.helper.join(room=self.created_rmid, user=self.user_id) request, channel = self.make_request("PUT", send_msg_path(), msg_content) self.assertEquals(200, channel.code, msg=channel.result["body"]) # send message in created room and left, expect 403 self.helper.leave(room=self.created_rmid, user=self.user_id) request, channel = self.make_request("PUT", send_msg_path(), msg_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) def test_topic_perms(self): topic_content = b'{"topic":"My Topic Name"}' topic_path = "/rooms/%s/state/m.room.topic" % self.created_rmid # set/get topic in uncreated room, expect 403 request, channel = self.make_request( "PUT", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid, topic_content ) self.assertEquals(403, channel.code, msg=channel.result["body"]) request, channel = self.make_request( "GET", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid ) self.assertEquals(403, channel.code, msg=channel.result["body"]) # set/get topic in created PRIVATE room not joined, expect 403 request, channel = self.make_request("PUT", topic_path, topic_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", topic_path) self.assertEquals(403, channel.code, msg=channel.result["body"]) # set topic in created PRIVATE room and invited, expect 403 self.helper.invite( room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id ) request, channel = self.make_request("PUT", topic_path, topic_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) # get topic in created PRIVATE room and invited, expect 403 request, channel = self.make_request("GET", topic_path) self.assertEquals(403, channel.code, msg=channel.result["body"]) # set/get topic in created PRIVATE room and joined, expect 200 self.helper.join(room=self.created_rmid, user=self.user_id) # Only room ops can set topic by default self.helper.auth_user_id = self.rmcreator_id request, channel = self.make_request("PUT", topic_path, topic_content) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.helper.auth_user_id = self.user_id request, channel = self.make_request("GET", topic_path) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assert_dict(json.loads(topic_content.decode("utf8")), channel.json_body) # set/get topic in created PRIVATE room and left, expect 403 self.helper.leave(room=self.created_rmid, user=self.user_id) request, channel = self.make_request("PUT", topic_path, topic_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", topic_path) self.assertEquals(200, channel.code, msg=channel.result["body"]) # get topic in PUBLIC room, not joined, expect 403 request, channel = self.make_request( "GET", "/rooms/%s/state/m.room.topic" % self.created_public_rmid ) self.assertEquals(403, channel.code, msg=channel.result["body"]) # set topic in PUBLIC room, not joined, expect 403 request, channel = self.make_request( "PUT", "/rooms/%s/state/m.room.topic" % self.created_public_rmid, topic_content, ) self.assertEquals(403, channel.code, msg=channel.result["body"]) def _test_get_membership(self, room=None, members=[], expect_code=None): for member in members: path = "/rooms/%s/state/m.room.member/%s" % (room, member) request, channel = self.make_request("GET", path) self.assertEquals(expect_code, channel.code) def test_membership_basic_room_perms(self): # === room does not exist === room = self.uncreated_rmid # get membership of self, get membership of other, uncreated room # expect all 403s self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=403 ) # trying to invite people to this room should 403 self.helper.invite( room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403 ) # set [invite/join/left] of self, set [invite/join/left] of other, # expect all 404s because room doesn't exist on any server for usr in [self.user_id, self.rmcreator_id]: self.helper.join(room=room, user=usr, expect_code=404) self.helper.leave(room=room, user=usr, expect_code=404) def test_membership_private_room_perms(self): room = self.created_rmid # get membership of self, get membership of other, private room + invite # expect all 403s self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=403 ) # get membership of self, get membership of other, private room + joined # expect all 200s self.helper.join(room=room, user=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=200 ) # get membership of self, get membership of other, private room + left # expect all 200s self.helper.leave(room=room, user=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=200 ) def test_membership_public_room_perms(self): room = self.created_public_rmid # get membership of self, get membership of other, public room + invite # expect 403 self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=403 ) # get membership of self, get membership of other, public room + joined # expect all 200s self.helper.join(room=room, user=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=200 ) # get membership of self, get membership of other, public room + left # expect 200. self.helper.leave(room=room, user=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=200 ) def test_invited_permissions(self): room = self.created_rmid self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) # set [invite/join/left] of other user, expect 403s self.helper.invite( room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403 ) self.helper.change_membership( room=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.JOIN, expect_code=403, ) self.helper.change_membership( room=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.LEAVE, expect_code=403, ) def test_joined_permissions(self): room = self.created_rmid self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) self.helper.join(room=room, user=self.user_id) # set invited of self, expect 403 self.helper.invite( room=room, src=self.user_id, targ=self.user_id, expect_code=403 ) # set joined of self, expect 200 (NOOP) self.helper.join(room=room, user=self.user_id) other = "@burgundy:red" # set invited of other, expect 200 self.helper.invite(room=room, src=self.user_id, targ=other, expect_code=200) # set joined of other, expect 403 self.helper.change_membership( room=room, src=self.user_id, targ=other, membership=Membership.JOIN, expect_code=403, ) # set left of other, expect 403 self.helper.change_membership( room=room, src=self.user_id, targ=other, membership=Membership.LEAVE, expect_code=403, ) # set left of self, expect 200 self.helper.leave(room=room, user=self.user_id) def test_leave_permissions(self): room = self.created_rmid self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) self.helper.join(room=room, user=self.user_id) self.helper.leave(room=room, user=self.user_id) # set [invite/join/left] of self, set [invite/join/left] of other, # expect all 403s for usr in [self.user_id, self.rmcreator_id]: self.helper.change_membership( room=room, src=self.user_id, targ=usr, membership=Membership.INVITE, expect_code=403, ) self.helper.change_membership( room=room, src=self.user_id, targ=usr, membership=Membership.JOIN, expect_code=403, ) # It is always valid to LEAVE if you've already left (currently.) self.helper.change_membership( room=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.LEAVE, expect_code=403, ) class RoomsMemberListTestCase(RoomBase): """ Tests /rooms/$room_id/members/list REST events.""" user_id = "@sid1:red" def test_get_member_list(self): room_id = self.helper.create_room_as(self.user_id) request, channel = self.make_request("GET", "/rooms/%s/members" % room_id) self.assertEquals(200, channel.code, msg=channel.result["body"]) def test_get_member_list_no_room(self): request, channel = self.make_request("GET", "/rooms/roomdoesnotexist/members") self.assertEquals(403, channel.code, msg=channel.result["body"]) def test_get_member_list_no_permission(self): room_id = self.helper.create_room_as("@some_other_guy:red") request, channel = self.make_request("GET", "/rooms/%s/members" % room_id) self.assertEquals(403, channel.code, msg=channel.result["body"]) def test_get_member_list_mixed_memberships(self): room_creator = "@some_other_guy:red" room_id = self.helper.create_room_as(room_creator) room_path = "/rooms/%s/members" % room_id self.helper.invite(room=room_id, src=room_creator, targ=self.user_id) # can't see list if you're just invited. request, channel = self.make_request("GET", room_path) self.assertEquals(403, channel.code, msg=channel.result["body"]) self.helper.join(room=room_id, user=self.user_id) # can see list now joined request, channel = self.make_request("GET", room_path) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.helper.leave(room=room_id, user=self.user_id) # can see old list once left request, channel = self.make_request("GET", room_path) self.assertEquals(200, channel.code, msg=channel.result["body"]) class RoomsCreateTestCase(RoomBase): """ Tests /rooms and /rooms/$room_id REST events. """ user_id = "@sid1:red" def test_post_room_no_keys(self): # POST with no config keys, expect new room id request, channel = self.make_request("POST", "/createRoom", "{}") self.assertEquals(200, channel.code, channel.result) self.assertTrue("room_id" in channel.json_body) def test_post_room_visibility_key(self): # POST with visibility config key, expect new room id request, channel = self.make_request( "POST", "/createRoom", b'{"visibility":"private"}' ) self.assertEquals(200, channel.code) self.assertTrue("room_id" in channel.json_body) def test_post_room_custom_key(self): # POST with custom config keys, expect new room id request, channel = self.make_request( "POST", "/createRoom", b'{"custom":"stuff"}' ) self.assertEquals(200, channel.code) self.assertTrue("room_id" in channel.json_body) def test_post_room_known_and_unknown_keys(self): # POST with custom + known config keys, expect new room id request, channel = self.make_request( "POST", "/createRoom", b'{"visibility":"private","custom":"things"}' ) self.assertEquals(200, channel.code) self.assertTrue("room_id" in channel.json_body) def test_post_room_invalid_content(self): # POST with invalid content / paths, expect 400 request, channel = self.make_request("POST", "/createRoom", b'{"visibili') self.assertEquals(400, channel.code) request, channel = self.make_request("POST", "/createRoom", b'["hello"]') self.assertEquals(400, channel.code) def test_post_room_invitees_invalid_mxid(self): # POST with invalid invitee, see https://github.com/matrix-org/synapse/issues/4088 # Note the trailing space in the MXID here! request, channel = self.make_request( "POST", "/createRoom", b'{"invite":["@alice:example.com "]}' ) self.assertEquals(400, channel.code) class RoomTopicTestCase(RoomBase): """ Tests /rooms/$room_id/topic REST events. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): # create the room self.room_id = self.helper.create_room_as(self.user_id) self.path = "/rooms/%s/state/m.room.topic" % (self.room_id,) def test_invalid_puts(self): # missing keys or invalid json request, channel = self.make_request("PUT", self.path, "{}") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", self.path, '{"_name":"bo"}') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", self.path, '{"nao') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request( "PUT", self.path, '[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", self.path, "text only") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", self.path, "") self.assertEquals(400, channel.code, msg=channel.result["body"]) # valid key, wrong type content = '{"topic":["Topic name"]}' request, channel = self.make_request("PUT", self.path, content) self.assertEquals(400, channel.code, msg=channel.result["body"]) def test_rooms_topic(self): # nothing should be there request, channel = self.make_request("GET", self.path) self.assertEquals(404, channel.code, msg=channel.result["body"]) # valid put content = '{"topic":"Topic name"}' request, channel = self.make_request("PUT", self.path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) # valid get request, channel = self.make_request("GET", self.path) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assert_dict(json.loads(content), channel.json_body) def test_rooms_topic_with_extra_keys(self): # valid put with extra keys content = '{"topic":"Seasons","subtopic":"Summer"}' request, channel = self.make_request("PUT", self.path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) # valid get request, channel = self.make_request("GET", self.path) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assert_dict(json.loads(content), channel.json_body) class RoomMemberStateTestCase(RoomBase): """ Tests /rooms/$room_id/members/$user_id/state REST events. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): self.room_id = self.helper.create_room_as(self.user_id) def test_invalid_puts(self): path = "/rooms/%s/state/m.room.member/%s" % (self.room_id, self.user_id) # missing keys or invalid json request, channel = self.make_request("PUT", path, "{}") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, '{"_name":"bo"}') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, '{"nao') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request( "PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, "text only") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, "") self.assertEquals(400, channel.code, msg=channel.result["body"]) # valid keys, wrong types content = '{"membership":["%s","%s","%s"]}' % ( Membership.INVITE, Membership.JOIN, Membership.LEAVE, ) request, channel = self.make_request("PUT", path, content.encode("ascii")) self.assertEquals(400, channel.code, msg=channel.result["body"]) def test_rooms_members_self(self): path = "/rooms/%s/state/m.room.member/%s" % ( urlparse.quote(self.room_id), self.user_id, ) # valid join message (NOOP since we made the room) content = '{"membership":"%s"}' % Membership.JOIN request, channel = self.make_request("PUT", path, content.encode("ascii")) self.assertEquals(200, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", path, None) self.assertEquals(200, channel.code, msg=channel.result["body"]) expected_response = {"membership": Membership.JOIN} self.assertEquals(expected_response, channel.json_body) def test_rooms_members_other(self): self.other_id = "@zzsid1:red" path = "/rooms/%s/state/m.room.member/%s" % ( urlparse.quote(self.room_id), self.other_id, ) # valid invite message content = '{"membership":"%s"}' % Membership.INVITE request, channel = self.make_request("PUT", path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", path, None) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assertEquals(json.loads(content), channel.json_body) def test_rooms_members_other_custom_keys(self): self.other_id = "@zzsid1:red" path = "/rooms/%s/state/m.room.member/%s" % ( urlparse.quote(self.room_id), self.other_id, ) # valid invite message with custom key content = '{"membership":"%s","invite_text":"%s"}' % ( Membership.INVITE, "Join us!", ) request, channel = self.make_request("PUT", path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", path, None) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assertEquals(json.loads(content), channel.json_body) class RoomJoinRatelimitTestCase(RoomBase): user_id = "@sid1:red" servlets = [ profile.register_servlets, room.register_servlets, ] @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def test_join_local_ratelimit(self): """Tests that local joins are actually rate-limited.""" for i in range(3): self.helper.create_room_as(self.user_id) self.helper.create_room_as(self.user_id, expect_code=429) @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def test_join_local_ratelimit_profile_change(self): """Tests that sending a profile update into all of the user's joined rooms isn't rate-limited by the rate-limiter on joins.""" # Create and join as many rooms as the rate-limiting config allows in a second. room_ids = [ self.helper.create_room_as(self.user_id), self.helper.create_room_as(self.user_id), self.helper.create_room_as(self.user_id), ] # Let some time for the rate-limiter to forget about our multi-join. self.reactor.advance(2) # Add one to make sure we're joined to more rooms than the config allows us to # join in a second. room_ids.append(self.helper.create_room_as(self.user_id)) # Create a profile for the user, since it hasn't been done on registration. store = self.hs.get_datastore() self.get_success( store.create_profile(UserID.from_string(self.user_id).localpart) ) # Update the display name for the user. path = "/_matrix/client/r0/profile/%s/displayname" % self.user_id request, channel = self.make_request("PUT", path, {"displayname": "John Doe"}) self.assertEquals(channel.code, 200, channel.json_body) # Check that all the rooms have been sent a profile update into. for room_id in room_ids: path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % ( room_id, self.user_id, ) request, channel = self.make_request("GET", path) self.assertEquals(channel.code, 200) self.assertIn("displayname", channel.json_body) self.assertEquals(channel.json_body["displayname"], "John Doe") @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def test_join_local_ratelimit_idempotent(self): """Tests that the room join endpoints remain idempotent despite rate-limiting on room joins.""" room_id = self.helper.create_room_as(self.user_id) # Let's test both paths to be sure. paths_to_test = [ "/_matrix/client/r0/rooms/%s/join", "/_matrix/client/r0/join/%s", ] for path in paths_to_test: # Make sure we send more requests than the rate-limiting config would allow # if all of these requests ended up joining the user to a room. for i in range(4): request, channel = self.make_request("POST", path % room_id, {}) self.assertEquals(channel.code, 200) class RoomMessagesTestCase(RoomBase): """ Tests /rooms/$room_id/messages/$user_id/$msg_id REST events. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): self.room_id = self.helper.create_room_as(self.user_id) def test_invalid_puts(self): path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id)) # missing keys or invalid json request, channel = self.make_request("PUT", path, b"{}") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, b'{"_name":"bo"}') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, b'{"nao') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request( "PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, b"text only") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, b"") self.assertEquals(400, channel.code, msg=channel.result["body"]) def test_rooms_messages_sent(self): path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id)) content = b'{"body":"test","msgtype":{"type":"a"}}' request, channel = self.make_request("PUT", path, content) self.assertEquals(400, channel.code, msg=channel.result["body"]) # custom message types content = b'{"body":"test","msgtype":"test.custom.text"}' request, channel = self.make_request("PUT", path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) # m.text message type path = "/rooms/%s/send/m.room.message/mid2" % (urlparse.quote(self.room_id)) content = b'{"body":"test2","msgtype":"m.text"}' request, channel = self.make_request("PUT", path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) class RoomInitialSyncTestCase(RoomBase): """ Tests /rooms/$room_id/initialSync. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): # create the room self.room_id = self.helper.create_room_as(self.user_id) def test_initial_sync(self): request, channel = self.make_request( "GET", "/rooms/%s/initialSync" % self.room_id ) self.assertEquals(200, channel.code) self.assertEquals(self.room_id, channel.json_body["room_id"]) self.assertEquals("join", channel.json_body["membership"]) # Room state is easier to assert on if we unpack it into a dict state = {} for event in channel.json_body["state"]: if "state_key" not in event: continue t = event["type"] if t not in state: state[t] = [] state[t].append(event) self.assertTrue("m.room.create" in state) self.assertTrue("messages" in channel.json_body) self.assertTrue("chunk" in channel.json_body["messages"]) self.assertTrue("end" in channel.json_body["messages"]) self.assertTrue("presence" in channel.json_body) presence_by_user = { e["content"]["user_id"]: e for e in channel.json_body["presence"] } self.assertTrue(self.user_id in presence_by_user) self.assertEquals("m.presence", presence_by_user[self.user_id]["type"]) class RoomMessageListTestCase(RoomBase): """ Tests /rooms/$room_id/messages REST events. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): self.room_id = self.helper.create_room_as(self.user_id) def test_topo_token_is_accepted(self): token = "t1-0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token) ) self.assertEquals(200, channel.code) self.assertTrue("start" in channel.json_body) self.assertEquals(token, channel.json_body["start"]) self.assertTrue("chunk" in channel.json_body) self.assertTrue("end" in channel.json_body) def test_stream_token_is_accepted_for_fwd_pagianation(self): token = "s0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token) ) self.assertEquals(200, channel.code) self.assertTrue("start" in channel.json_body) self.assertEquals(token, channel.json_body["start"]) self.assertTrue("chunk" in channel.json_body) self.assertTrue("end" in channel.json_body) def test_room_messages_purge(self): store = self.hs.get_datastore() pagination_handler = self.hs.get_pagination_handler() # Send a first message in the room, which will be removed by the purge. first_event_id = self.helper.send(self.room_id, "message 1")["event_id"] first_token = self.get_success( store.get_topological_token_for_event(first_event_id) ) first_token_str = self.get_success(first_token.to_string(store)) # Send a second message in the room, which won't be removed, and which we'll # use as the marker to purge events before. second_event_id = self.helper.send(self.room_id, "message 2")["event_id"] second_token = self.get_success( store.get_topological_token_for_event(second_event_id) ) second_token_str = self.get_success(second_token.to_string(store)) # Send a third event in the room to ensure we don't fall under any edge case # due to our marker being the latest forward extremity in the room. self.helper.send(self.room_id, "message 3") # Check that we get the first and second message when querying /messages. request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s" % ( self.room_id, second_token_str, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(channel.code, 200, channel.json_body) chunk = channel.json_body["chunk"] self.assertEqual(len(chunk), 2, [event["content"] for event in chunk]) # Purge every event before the second event. purge_id = random_string(16) pagination_handler._purges_by_id[purge_id] = PurgeStatus() self.get_success( pagination_handler._purge_history( purge_id=purge_id, room_id=self.room_id, token=second_token_str, delete_local_events=True, ) ) # Check that we only get the second message through /message now that the first # has been purged. request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s" % ( self.room_id, second_token_str, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(channel.code, 200, channel.json_body) chunk = channel.json_body["chunk"] self.assertEqual(len(chunk), 1, [event["content"] for event in chunk]) # Check that we get no event, but also no error, when querying /messages with # the token that was pointing at the first event, because we don't have it # anymore. request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s" % ( self.room_id, first_token_str, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(channel.code, 200, channel.json_body) chunk = channel.json_body["chunk"] self.assertEqual(len(chunk), 0, [event["content"] for event in chunk]) class RoomSearchTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, ] user_id = True hijack_auth = False def prepare(self, reactor, clock, hs): # Register the user who does the searching self.user_id = self.register_user("user", "pass") self.access_token = self.login("user", "pass") # Register the user who sends the message self.other_user_id = self.register_user("otheruser", "pass") self.other_access_token = self.login("otheruser", "pass") # Create a room self.room = self.helper.create_room_as(self.user_id, tok=self.access_token) # Invite the other person self.helper.invite( room=self.room, src=self.user_id, tok=self.access_token, targ=self.other_user_id, ) # The other user joins self.helper.join( room=self.room, user=self.other_user_id, tok=self.other_access_token ) def test_finds_message(self): """ The search functionality will search for content in messages if asked to do so. """ # The other user sends some messages self.helper.send(self.room, body="Hi!", tok=self.other_access_token) self.helper.send(self.room, body="There!", tok=self.other_access_token) request, channel = self.make_request( "POST", "/search?access_token=%s" % (self.access_token,), { "search_categories": { "room_events": {"keys": ["content.body"], "search_term": "Hi"} } }, ) # Check we get the results we expect -- one search result, of the sent # messages self.assertEqual(channel.code, 200) results = channel.json_body["search_categories"]["room_events"] self.assertEqual(results["count"], 1) self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!") # No context was requested, so we should get none. self.assertEqual(results["results"][0]["context"], {}) def test_include_context(self): """ When event_context includes include_profile, profile information will be included in the search response. """ # The other user sends some messages self.helper.send(self.room, body="Hi!", tok=self.other_access_token) self.helper.send(self.room, body="There!", tok=self.other_access_token) request, channel = self.make_request( "POST", "/search?access_token=%s" % (self.access_token,), { "search_categories": { "room_events": { "keys": ["content.body"], "search_term": "Hi", "event_context": {"include_profile": True}, } } }, ) # Check we get the results we expect -- one search result, of the sent # messages self.assertEqual(channel.code, 200) results = channel.json_body["search_categories"]["room_events"] self.assertEqual(results["count"], 1) self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!") # We should get context info, like the two users, and the display names. context = results["results"][0]["context"] self.assertEqual(len(context["profile_info"].keys()), 2) self.assertEqual( context["profile_info"][self.other_user_id]["displayname"], "otheruser" ) class PublicRoomsRestrictedTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, ] def make_homeserver(self, reactor, clock): self.url = b"/_matrix/client/r0/publicRooms" config = self.default_config() config["allow_public_rooms_without_auth"] = False self.hs = self.setup_test_homeserver(config=config) return self.hs def test_restricted_no_auth(self): request, channel = self.make_request("GET", self.url) self.assertEqual(channel.code, 401, channel.result) def test_restricted_auth(self): self.register_user("user", "pass") tok = self.login("user", "pass") request, channel = self.make_request("GET", self.url, access_token=tok) self.assertEqual(channel.code, 200, channel.result) class PerRoomProfilesForbiddenTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, profile.register_servlets, ] def make_homeserver(self, reactor, clock): config = self.default_config() config["allow_per_room_profiles"] = False self.hs = self.setup_test_homeserver(config=config) return self.hs def prepare(self, reactor, clock, homeserver): self.user_id = self.register_user("test", "test") self.tok = self.login("test", "test") # Set a profile for the test user self.displayname = "test user" data = {"displayname": self.displayname} request_data = json.dumps(data) request, channel = self.make_request( "PUT", "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,), request_data, access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok) def test_per_room_profile_forbidden(self): data = {"membership": "join", "displayname": "other test user"} request_data = json.dumps(data) request, channel = self.make_request( "PUT", "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (self.room_id, self.user_id), request_data, access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) event_id = channel.json_body["event_id"] request, channel = self.make_request( "GET", "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) res_displayname = channel.json_body["content"]["displayname"] self.assertEqual(res_displayname, self.displayname, channel.result) class RoomMembershipReasonTestCase(unittest.HomeserverTestCase): """Tests that clients can add a "reason" field to membership events and that they get correctly added to the generated events and propagated. """ servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, ] def prepare(self, reactor, clock, homeserver): self.creator = self.register_user("creator", "test") self.creator_tok = self.login("creator", "test") self.second_user_id = self.register_user("second", "test") self.second_tok = self.login("second", "test") self.room_id = self.helper.create_room_as(self.creator, tok=self.creator_tok) def test_join_reason(self): reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/join".format(self.room_id), content={"reason": reason}, access_token=self.second_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_leave_reason(self): self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok) reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/leave".format(self.room_id), content={"reason": reason}, access_token=self.second_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_kick_reason(self): self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok) reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/kick".format(self.room_id), content={"reason": reason, "user_id": self.second_user_id}, access_token=self.second_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_ban_reason(self): self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok) reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/ban".format(self.room_id), content={"reason": reason, "user_id": self.second_user_id}, access_token=self.creator_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_unban_reason(self): reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/unban".format(self.room_id), content={"reason": reason, "user_id": self.second_user_id}, access_token=self.creator_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_invite_reason(self): reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/invite".format(self.room_id), content={"reason": reason, "user_id": self.second_user_id}, access_token=self.creator_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_reject_invite_reason(self): self.helper.invite( self.room_id, src=self.creator, targ=self.second_user_id, tok=self.creator_tok, ) reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/leave".format(self.room_id), content={"reason": reason}, access_token=self.second_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def _check_for_reason(self, reason): request, channel = self.make_request( "GET", "/_matrix/client/r0/rooms/{}/state/m.room.member/{}".format( self.room_id, self.second_user_id ), access_token=self.creator_tok, ) self.assertEqual(channel.code, 200, channel.result) event_content = channel.json_body self.assertEqual(event_content.get("reason"), reason, channel.result) class LabelsTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, profile.register_servlets, ] # Filter that should only catch messages with the label "#fun". FILTER_LABELS = { "types": [EventTypes.Message], "org.matrix.labels": ["#fun"], } # Filter that should only catch messages without the label "#fun". FILTER_NOT_LABELS = { "types": [EventTypes.Message], "org.matrix.not_labels": ["#fun"], } # Filter that should only catch messages with the label "#work" but without the label # "#notfun". FILTER_LABELS_NOT_LABELS = { "types": [EventTypes.Message], "org.matrix.labels": ["#work"], "org.matrix.not_labels": ["#notfun"], } def prepare(self, reactor, clock, homeserver): self.user_id = self.register_user("test", "test") self.tok = self.login("test", "test") self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok) def test_context_filter_labels(self): """Test that we can filter by a label on a /context request.""" event_id = self._send_labelled_messages_in_room() request, channel = self.make_request( "GET", "/rooms/%s/context/%s?filter=%s" % (self.room_id, event_id, json.dumps(self.FILTER_LABELS)), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual( len(events_before), 1, [event["content"] for event in events_before] ) self.assertEqual( events_before[0]["content"]["body"], "with right label", events_before[0] ) events_after = channel.json_body["events_before"] self.assertEqual( len(events_after), 1, [event["content"] for event in events_after] ) self.assertEqual( events_after[0]["content"]["body"], "with right label", events_after[0] ) def test_context_filter_not_labels(self): """Test that we can filter by the absence of a label on a /context request.""" event_id = self._send_labelled_messages_in_room() request, channel = self.make_request( "GET", "/rooms/%s/context/%s?filter=%s" % (self.room_id, event_id, json.dumps(self.FILTER_NOT_LABELS)), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual( len(events_before), 1, [event["content"] for event in events_before] ) self.assertEqual( events_before[0]["content"]["body"], "without label", events_before[0] ) events_after = channel.json_body["events_after"] self.assertEqual( len(events_after), 2, [event["content"] for event in events_after] ) self.assertEqual( events_after[0]["content"]["body"], "with wrong label", events_after[0] ) self.assertEqual( events_after[1]["content"]["body"], "with two wrong labels", events_after[1] ) def test_context_filter_labels_not_labels(self): """Test that we can filter by both a label and the absence of another label on a /context request. """ event_id = self._send_labelled_messages_in_room() request, channel = self.make_request( "GET", "/rooms/%s/context/%s?filter=%s" % (self.room_id, event_id, json.dumps(self.FILTER_LABELS_NOT_LABELS)), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual( len(events_before), 0, [event["content"] for event in events_before] ) events_after = channel.json_body["events_after"] self.assertEqual( len(events_after), 1, [event["content"] for event in events_after] ) self.assertEqual( events_after[0]["content"]["body"], "with wrong label", events_after[0] ) def test_messages_filter_labels(self): """Test that we can filter by a label on a /messages request.""" self._send_labelled_messages_in_room() token = "s0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=%s&from=%s&filter=%s" % (self.room_id, self.tok, token, json.dumps(self.FILTER_LABELS)), ) events = channel.json_body["chunk"] self.assertEqual(len(events), 2, [event["content"] for event in events]) self.assertEqual(events[0]["content"]["body"], "with right label", events[0]) self.assertEqual(events[1]["content"]["body"], "with right label", events[1]) def test_messages_filter_not_labels(self): """Test that we can filter by the absence of a label on a /messages request.""" self._send_labelled_messages_in_room() token = "s0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=%s&from=%s&filter=%s" % (self.room_id, self.tok, token, json.dumps(self.FILTER_NOT_LABELS)), ) events = channel.json_body["chunk"] self.assertEqual(len(events), 4, [event["content"] for event in events]) self.assertEqual(events[0]["content"]["body"], "without label", events[0]) self.assertEqual(events[1]["content"]["body"], "without label", events[1]) self.assertEqual(events[2]["content"]["body"], "with wrong label", events[2]) self.assertEqual( events[3]["content"]["body"], "with two wrong labels", events[3] ) def test_messages_filter_labels_not_labels(self): """Test that we can filter by both a label and the absence of another label on a /messages request. """ self._send_labelled_messages_in_room() token = "s0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=%s&from=%s&filter=%s" % ( self.room_id, self.tok, token, json.dumps(self.FILTER_LABELS_NOT_LABELS), ), ) events = channel.json_body["chunk"] self.assertEqual(len(events), 1, [event["content"] for event in events]) self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0]) def test_search_filter_labels(self): """Test that we can filter by a label on a /search request.""" request_data = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_LABELS, } } } ) self._send_labelled_messages_in_room() request, channel = self.make_request( "POST", "/search?access_token=%s" % self.tok, request_data ) results = channel.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(results), 2, [result["result"]["content"] for result in results], ) self.assertEqual( results[0]["result"]["content"]["body"], "with right label", results[0]["result"]["content"]["body"], ) self.assertEqual( results[1]["result"]["content"]["body"], "with right label", results[1]["result"]["content"]["body"], ) def test_search_filter_not_labels(self): """Test that we can filter by the absence of a label on a /search request.""" request_data = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_NOT_LABELS, } } } ) self._send_labelled_messages_in_room() request, channel = self.make_request( "POST", "/search?access_token=%s" % self.tok, request_data ) results = channel.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(results), 4, [result["result"]["content"] for result in results], ) self.assertEqual( results[0]["result"]["content"]["body"], "without label", results[0]["result"]["content"]["body"], ) self.assertEqual( results[1]["result"]["content"]["body"], "without label", results[1]["result"]["content"]["body"], ) self.assertEqual( results[2]["result"]["content"]["body"], "with wrong label", results[2]["result"]["content"]["body"], ) self.assertEqual( results[3]["result"]["content"]["body"], "with two wrong labels", results[3]["result"]["content"]["body"], ) def test_search_filter_labels_not_labels(self): """Test that we can filter by both a label and the absence of another label on a /search request. """ request_data = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_LABELS_NOT_LABELS, } } } ) self._send_labelled_messages_in_room() request, channel = self.make_request( "POST", "/search?access_token=%s" % self.tok, request_data ) results = channel.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(results), 1, [result["result"]["content"] for result in results], ) self.assertEqual( results[0]["result"]["content"]["body"], "with wrong label", results[0]["result"]["content"]["body"], ) def _send_labelled_messages_in_room(self): """Sends several messages to a room with different labels (or without any) to test filtering by label. Returns: The ID of the event to use if we're testing filtering on /context. """ self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={ "msgtype": "m.text", "body": "with right label", EventContentFields.LABELS: ["#fun"], }, tok=self.tok, ) self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={"msgtype": "m.text", "body": "without label"}, tok=self.tok, ) res = self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={"msgtype": "m.text", "body": "without label"}, tok=self.tok, ) # Return this event's ID when we test filtering in /context requests. event_id = res["event_id"] self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={ "msgtype": "m.text", "body": "with wrong label", EventContentFields.LABELS: ["#work"], }, tok=self.tok, ) self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={ "msgtype": "m.text", "body": "with two wrong labels", EventContentFields.LABELS: ["#work", "#notfun"], }, tok=self.tok, ) self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={ "msgtype": "m.text", "body": "with right label", EventContentFields.LABELS: ["#fun"], }, tok=self.tok, ) return event_id class ContextTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, account.register_servlets, ] def prepare(self, reactor, clock, homeserver): self.user_id = self.register_user("user", "password") self.tok = self.login("user", "password") self.room_id = self.helper.create_room_as( self.user_id, tok=self.tok, is_public=False ) self.other_user_id = self.register_user("user2", "password") self.other_tok = self.login("user2", "password") self.helper.invite(self.room_id, self.user_id, self.other_user_id, tok=self.tok) self.helper.join(self.room_id, self.other_user_id, tok=self.other_tok) def test_erased_sender(self): """Test that an erasure request results in the requester's events being hidden from any new member of the room. """ # Send a bunch of events in the room. self.helper.send(self.room_id, "message 1", tok=self.tok) self.helper.send(self.room_id, "message 2", tok=self.tok) event_id = self.helper.send(self.room_id, "message 3", tok=self.tok)["event_id"] self.helper.send(self.room_id, "message 4", tok=self.tok) self.helper.send(self.room_id, "message 5", tok=self.tok) # Check that we can still see the messages before the erasure request. request, channel = self.make_request( "GET", '/rooms/%s/context/%s?filter={"types":["m.room.message"]}' % (self.room_id, event_id), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual(len(events_before), 2, events_before) self.assertEqual( events_before[0].get("content", {}).get("body"), "message 2", events_before[0], ) self.assertEqual( events_before[1].get("content", {}).get("body"), "message 1", events_before[1], ) self.assertEqual( channel.json_body["event"].get("content", {}).get("body"), "message 3", channel.json_body["event"], ) events_after = channel.json_body["events_after"] self.assertEqual(len(events_after), 2, events_after) self.assertEqual( events_after[0].get("content", {}).get("body"), "message 4", events_after[0], ) self.assertEqual( events_after[1].get("content", {}).get("body"), "message 5", events_after[1], ) # Deactivate the first account and erase the user's data. deactivate_account_handler = self.hs.get_deactivate_account_handler() self.get_success( deactivate_account_handler.deactivate_account(self.user_id, erase_data=True) ) # Invite another user in the room. This is needed because messages will be # pruned only if the user wasn't a member of the room when the messages were # sent. invited_user_id = self.register_user("user3", "password") invited_tok = self.login("user3", "password") self.helper.invite( self.room_id, self.other_user_id, invited_user_id, tok=self.other_tok ) self.helper.join(self.room_id, invited_user_id, tok=invited_tok) # Check that a user that joined the room after the erasure request can't see # the messages anymore. request, channel = self.make_request( "GET", '/rooms/%s/context/%s?filter={"types":["m.room.message"]}' % (self.room_id, event_id), access_token=invited_tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual(len(events_before), 2, events_before) self.assertDictEqual(events_before[0].get("content"), {}, events_before[0]) self.assertDictEqual(events_before[1].get("content"), {}, events_before[1]) self.assertDictEqual( channel.json_body["event"].get("content"), {}, channel.json_body["event"] ) events_after = channel.json_body["events_after"] self.assertEqual(len(events_after), 2, events_after) self.assertDictEqual(events_after[0].get("content"), {}, events_after[0]) self.assertEqual(events_after[1].get("content"), {}, events_after[1]) class RoomAliasListTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, directory.register_servlets, login.register_servlets, room.register_servlets, ] def prepare(self, reactor, clock, homeserver): self.room_owner = self.register_user("room_owner", "test") self.room_owner_tok = self.login("room_owner", "test") self.room_id = self.helper.create_room_as( self.room_owner, tok=self.room_owner_tok ) def test_no_aliases(self): res = self._get_aliases(self.room_owner_tok) self.assertEqual(res["aliases"], []) def test_not_in_room(self): self.register_user("user", "test") user_tok = self.login("user", "test") res = self._get_aliases(user_tok, expected_code=403) self.assertEqual(res["errcode"], "M_FORBIDDEN") def test_admin_user(self): alias1 = self._random_alias() self._set_alias_via_directory(alias1) self.register_user("user", "test", admin=True) user_tok = self.login("user", "test") res = self._get_aliases(user_tok) self.assertEqual(res["aliases"], [alias1]) def test_with_aliases(self): alias1 = self._random_alias() alias2 = self._random_alias() self._set_alias_via_directory(alias1) self._set_alias_via_directory(alias2) res = self._get_aliases(self.room_owner_tok) self.assertEqual(set(res["aliases"]), {alias1, alias2}) def test_peekable_room(self): alias1 = self._random_alias() self._set_alias_via_directory(alias1) self.helper.send_state( self.room_id, EventTypes.RoomHistoryVisibility, body={"history_visibility": "world_readable"}, tok=self.room_owner_tok, ) self.register_user("user", "test") user_tok = self.login("user", "test") res = self._get_aliases(user_tok) self.assertEqual(res["aliases"], [alias1]) def _get_aliases(self, access_token: str, expected_code: int = 200) -> JsonDict: """Calls the endpoint under test. returns the json response object.""" request, channel = self.make_request( "GET", "/_matrix/client/unstable/org.matrix.msc2432/rooms/%s/aliases" % (self.room_id,), access_token=access_token, ) self.assertEqual(channel.code, expected_code, channel.result) res = channel.json_body self.assertIsInstance(res, dict) if expected_code == 200: self.assertIsInstance(res["aliases"], list) return res def _random_alias(self) -> str: return RoomAlias(random_string(5), self.hs.hostname).to_string() def _set_alias_via_directory(self, alias: str, expected_code: int = 200): url = "/_matrix/client/r0/directory/room/" + alias data = {"room_id": self.room_id} request_data = json.dumps(data) request, channel = self.make_request( "PUT", url, request_data, access_token=self.room_owner_tok ) self.assertEqual(channel.code, expected_code, channel.result) class RoomCanonicalAliasTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, directory.register_servlets, login.register_servlets, room.register_servlets, ] def prepare(self, reactor, clock, homeserver): self.room_owner = self.register_user("room_owner", "test") self.room_owner_tok = self.login("room_owner", "test") self.room_id = self.helper.create_room_as( self.room_owner, tok=self.room_owner_tok ) self.alias = "#alias:test" self._set_alias_via_directory(self.alias) def _set_alias_via_directory(self, alias: str, expected_code: int = 200): url = "/_matrix/client/r0/directory/room/" + alias data = {"room_id": self.room_id} request_data = json.dumps(data) request, channel = self.make_request( "PUT", url, request_data, access_token=self.room_owner_tok ) self.assertEqual(channel.code, expected_code, channel.result) def _get_canonical_alias(self, expected_code: int = 200) -> JsonDict: """Calls the endpoint under test. returns the json response object.""" request, channel = self.make_request( "GET", "rooms/%s/state/m.room.canonical_alias" % (self.room_id,), access_token=self.room_owner_tok, ) self.assertEqual(channel.code, expected_code, channel.result) res = channel.json_body self.assertIsInstance(res, dict) return res def _set_canonical_alias(self, content: str, expected_code: int = 200) -> JsonDict: """Calls the endpoint under test. returns the json response object.""" request, channel = self.make_request( "PUT", "rooms/%s/state/m.room.canonical_alias" % (self.room_id,), json.dumps(content), access_token=self.room_owner_tok, ) self.assertEqual(channel.code, expected_code, channel.result) res = channel.json_body self.assertIsInstance(res, dict) return res def test_canonical_alias(self): """Test a basic alias message.""" # There is no canonical alias to start with. self._get_canonical_alias(expected_code=404) # Create an alias. self._set_canonical_alias({"alias": self.alias}) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual(res, {"alias": self.alias}) # Now remove the alias. self._set_canonical_alias({}) # There is an alias event, but it is empty. res = self._get_canonical_alias() self.assertEqual(res, {}) def test_alt_aliases(self): """Test a canonical alias message with alt_aliases.""" # Create an alias. self._set_canonical_alias({"alt_aliases": [self.alias]}) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual(res, {"alt_aliases": [self.alias]}) # Now remove the alt_aliases. self._set_canonical_alias({}) # There is an alias event, but it is empty. res = self._get_canonical_alias() self.assertEqual(res, {}) def test_alias_alt_aliases(self): """Test a canonical alias message with an alias and alt_aliases.""" # Create an alias. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]}) # Now remove the alias and alt_aliases. self._set_canonical_alias({}) # There is an alias event, but it is empty. res = self._get_canonical_alias() self.assertEqual(res, {}) def test_partial_modify(self): """Test removing only the alt_aliases.""" # Create an alias. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]}) # Now remove the alt_aliases. self._set_canonical_alias({"alias": self.alias}) # There is an alias event, but it is empty. res = self._get_canonical_alias() self.assertEqual(res, {"alias": self.alias}) def test_add_alias(self): """Test removing only the alt_aliases.""" # Create an additional alias. second_alias = "#second:test" self._set_alias_via_directory(second_alias) # Add the canonical alias. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) # Then add the second alias. self._set_canonical_alias( {"alias": self.alias, "alt_aliases": [self.alias, second_alias]} ) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual( res, {"alias": self.alias, "alt_aliases": [self.alias, second_alias]} ) def test_bad_data(self): """Invalid data for alt_aliases should cause errors.""" self._set_canonical_alias({"alt_aliases": "@bad:test"}, expected_code=400) self._set_canonical_alias({"alt_aliases": None}, expected_code=400) self._set_canonical_alias({"alt_aliases": 0}, expected_code=400) self._set_canonical_alias({"alt_aliases": 1}, expected_code=400) self._set_canonical_alias({"alt_aliases": False}, expected_code=400) self._set_canonical_alias({"alt_aliases": True}, expected_code=400) self._set_canonical_alias({"alt_aliases": {}}, expected_code=400) def test_bad_alias(self): """An alias which does not point to the room raises a SynapseError.""" self._set_canonical_alias({"alias": "@unknown:test"}, expected_code=400) self._set_canonical_alias({"alt_aliases": ["@unknown:test"]}, expected_code=400)
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2017 Vector Creations Ltd # Copyright 2018-2019 New Vector Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests REST events for /rooms paths.""" import json from urllib import parse as urlparse from mock import Mock import synapse.rest.admin from synapse.api.constants import EventContentFields, EventTypes, Membership from synapse.handlers.pagination import PurgeStatus from synapse.rest.client.v1 import directory, login, profile, room from synapse.rest.client.v2_alpha import account from synapse.types import JsonDict, RoomAlias, UserID from synapse.util.stringutils import random_string from tests import unittest from tests.test_utils import make_awaitable PATH_PREFIX = b"/_matrix/client/api/v1" class RoomBase(unittest.HomeserverTestCase): rmcreator_id = None servlets = [room.register_servlets, room.register_deprecated_servlets] def make_homeserver(self, reactor, clock): self.hs = self.setup_test_homeserver( "red", federation_http_client=None, federation_client=Mock(), ) self.hs.get_federation_handler = Mock() self.hs.get_federation_handler.return_value.maybe_backfill = Mock( return_value=make_awaitable(None) ) async def _insert_client_ip(*args, **kwargs): return None self.hs.get_datastore().insert_client_ip = _insert_client_ip return self.hs class RoomPermissionsTestCase(RoomBase): """ Tests room permissions. """ user_id = "@sid1:red" rmcreator_id = "@notme:red" def prepare(self, reactor, clock, hs): self.helper.auth_user_id = self.rmcreator_id # create some rooms under the name rmcreator_id self.uncreated_rmid = "!aa:test" self.created_rmid = self.helper.create_room_as( self.rmcreator_id, is_public=False ) self.created_public_rmid = self.helper.create_room_as( self.rmcreator_id, is_public=True ) # send a message in one of the rooms self.created_rmid_msg_path = ( "rooms/%s/send/m.room.message/a1" % (self.created_rmid) ).encode("ascii") request, channel = self.make_request( "PUT", self.created_rmid_msg_path, b'{"msgtype":"m.text","body":"test msg"}' ) self.assertEquals(200, channel.code, channel.result) # set topic for public room request, channel = self.make_request( "PUT", ("rooms/%s/state/m.room.topic" % self.created_public_rmid).encode("ascii"), b'{"topic":"Public Room Topic"}', ) self.assertEquals(200, channel.code, channel.result) # auth as user_id now self.helper.auth_user_id = self.user_id def test_can_do_action(self): msg_content = b'{"msgtype":"m.text","body":"hello"}' seq = iter(range(100)) def send_msg_path(): return "/rooms/%s/send/m.room.message/mid%s" % ( self.created_rmid, str(next(seq)), ) # send message in uncreated room, expect 403 request, channel = self.make_request( "PUT", "/rooms/%s/send/m.room.message/mid2" % (self.uncreated_rmid,), msg_content, ) self.assertEquals(403, channel.code, msg=channel.result["body"]) # send message in created room not joined (no state), expect 403 request, channel = self.make_request("PUT", send_msg_path(), msg_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) # send message in created room and invited, expect 403 self.helper.invite( room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id ) request, channel = self.make_request("PUT", send_msg_path(), msg_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) # send message in created room and joined, expect 200 self.helper.join(room=self.created_rmid, user=self.user_id) request, channel = self.make_request("PUT", send_msg_path(), msg_content) self.assertEquals(200, channel.code, msg=channel.result["body"]) # send message in created room and left, expect 403 self.helper.leave(room=self.created_rmid, user=self.user_id) request, channel = self.make_request("PUT", send_msg_path(), msg_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) def test_topic_perms(self): topic_content = b'{"topic":"My Topic Name"}' topic_path = "/rooms/%s/state/m.room.topic" % self.created_rmid # set/get topic in uncreated room, expect 403 request, channel = self.make_request( "PUT", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid, topic_content ) self.assertEquals(403, channel.code, msg=channel.result["body"]) request, channel = self.make_request( "GET", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid ) self.assertEquals(403, channel.code, msg=channel.result["body"]) # set/get topic in created PRIVATE room not joined, expect 403 request, channel = self.make_request("PUT", topic_path, topic_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", topic_path) self.assertEquals(403, channel.code, msg=channel.result["body"]) # set topic in created PRIVATE room and invited, expect 403 self.helper.invite( room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id ) request, channel = self.make_request("PUT", topic_path, topic_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) # get topic in created PRIVATE room and invited, expect 403 request, channel = self.make_request("GET", topic_path) self.assertEquals(403, channel.code, msg=channel.result["body"]) # set/get topic in created PRIVATE room and joined, expect 200 self.helper.join(room=self.created_rmid, user=self.user_id) # Only room ops can set topic by default self.helper.auth_user_id = self.rmcreator_id request, channel = self.make_request("PUT", topic_path, topic_content) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.helper.auth_user_id = self.user_id request, channel = self.make_request("GET", topic_path) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assert_dict(json.loads(topic_content.decode("utf8")), channel.json_body) # set/get topic in created PRIVATE room and left, expect 403 self.helper.leave(room=self.created_rmid, user=self.user_id) request, channel = self.make_request("PUT", topic_path, topic_content) self.assertEquals(403, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", topic_path) self.assertEquals(200, channel.code, msg=channel.result["body"]) # get topic in PUBLIC room, not joined, expect 403 request, channel = self.make_request( "GET", "/rooms/%s/state/m.room.topic" % self.created_public_rmid ) self.assertEquals(403, channel.code, msg=channel.result["body"]) # set topic in PUBLIC room, not joined, expect 403 request, channel = self.make_request( "PUT", "/rooms/%s/state/m.room.topic" % self.created_public_rmid, topic_content, ) self.assertEquals(403, channel.code, msg=channel.result["body"]) def _test_get_membership(self, room=None, members=[], expect_code=None): for member in members: path = "/rooms/%s/state/m.room.member/%s" % (room, member) request, channel = self.make_request("GET", path) self.assertEquals(expect_code, channel.code) def test_membership_basic_room_perms(self): # === room does not exist === room = self.uncreated_rmid # get membership of self, get membership of other, uncreated room # expect all 403s self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=403 ) # trying to invite people to this room should 403 self.helper.invite( room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403 ) # set [invite/join/left] of self, set [invite/join/left] of other, # expect all 404s because room doesn't exist on any server for usr in [self.user_id, self.rmcreator_id]: self.helper.join(room=room, user=usr, expect_code=404) self.helper.leave(room=room, user=usr, expect_code=404) def test_membership_private_room_perms(self): room = self.created_rmid # get membership of self, get membership of other, private room + invite # expect all 403s self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=403 ) # get membership of self, get membership of other, private room + joined # expect all 200s self.helper.join(room=room, user=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=200 ) # get membership of self, get membership of other, private room + left # expect all 200s self.helper.leave(room=room, user=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=200 ) def test_membership_public_room_perms(self): room = self.created_public_rmid # get membership of self, get membership of other, public room + invite # expect 403 self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=403 ) # get membership of self, get membership of other, public room + joined # expect all 200s self.helper.join(room=room, user=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=200 ) # get membership of self, get membership of other, public room + left # expect 200. self.helper.leave(room=room, user=self.user_id) self._test_get_membership( members=[self.user_id, self.rmcreator_id], room=room, expect_code=200 ) def test_invited_permissions(self): room = self.created_rmid self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) # set [invite/join/left] of other user, expect 403s self.helper.invite( room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403 ) self.helper.change_membership( room=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.JOIN, expect_code=403, ) self.helper.change_membership( room=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.LEAVE, expect_code=403, ) def test_joined_permissions(self): room = self.created_rmid self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) self.helper.join(room=room, user=self.user_id) # set invited of self, expect 403 self.helper.invite( room=room, src=self.user_id, targ=self.user_id, expect_code=403 ) # set joined of self, expect 200 (NOOP) self.helper.join(room=room, user=self.user_id) other = "@burgundy:red" # set invited of other, expect 200 self.helper.invite(room=room, src=self.user_id, targ=other, expect_code=200) # set joined of other, expect 403 self.helper.change_membership( room=room, src=self.user_id, targ=other, membership=Membership.JOIN, expect_code=403, ) # set left of other, expect 403 self.helper.change_membership( room=room, src=self.user_id, targ=other, membership=Membership.LEAVE, expect_code=403, ) # set left of self, expect 200 self.helper.leave(room=room, user=self.user_id) def test_leave_permissions(self): room = self.created_rmid self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id) self.helper.join(room=room, user=self.user_id) self.helper.leave(room=room, user=self.user_id) # set [invite/join/left] of self, set [invite/join/left] of other, # expect all 403s for usr in [self.user_id, self.rmcreator_id]: self.helper.change_membership( room=room, src=self.user_id, targ=usr, membership=Membership.INVITE, expect_code=403, ) self.helper.change_membership( room=room, src=self.user_id, targ=usr, membership=Membership.JOIN, expect_code=403, ) # It is always valid to LEAVE if you've already left (currently.) self.helper.change_membership( room=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.LEAVE, expect_code=403, ) class RoomsMemberListTestCase(RoomBase): """ Tests /rooms/$room_id/members/list REST events.""" user_id = "@sid1:red" def test_get_member_list(self): room_id = self.helper.create_room_as(self.user_id) request, channel = self.make_request("GET", "/rooms/%s/members" % room_id) self.assertEquals(200, channel.code, msg=channel.result["body"]) def test_get_member_list_no_room(self): request, channel = self.make_request("GET", "/rooms/roomdoesnotexist/members") self.assertEquals(403, channel.code, msg=channel.result["body"]) def test_get_member_list_no_permission(self): room_id = self.helper.create_room_as("@some_other_guy:red") request, channel = self.make_request("GET", "/rooms/%s/members" % room_id) self.assertEquals(403, channel.code, msg=channel.result["body"]) def test_get_member_list_mixed_memberships(self): room_creator = "@some_other_guy:red" room_id = self.helper.create_room_as(room_creator) room_path = "/rooms/%s/members" % room_id self.helper.invite(room=room_id, src=room_creator, targ=self.user_id) # can't see list if you're just invited. request, channel = self.make_request("GET", room_path) self.assertEquals(403, channel.code, msg=channel.result["body"]) self.helper.join(room=room_id, user=self.user_id) # can see list now joined request, channel = self.make_request("GET", room_path) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.helper.leave(room=room_id, user=self.user_id) # can see old list once left request, channel = self.make_request("GET", room_path) self.assertEquals(200, channel.code, msg=channel.result["body"]) class RoomsCreateTestCase(RoomBase): """ Tests /rooms and /rooms/$room_id REST events. """ user_id = "@sid1:red" def test_post_room_no_keys(self): # POST with no config keys, expect new room id request, channel = self.make_request("POST", "/createRoom", "{}") self.assertEquals(200, channel.code, channel.result) self.assertTrue("room_id" in channel.json_body) def test_post_room_visibility_key(self): # POST with visibility config key, expect new room id request, channel = self.make_request( "POST", "/createRoom", b'{"visibility":"private"}' ) self.assertEquals(200, channel.code) self.assertTrue("room_id" in channel.json_body) def test_post_room_custom_key(self): # POST with custom config keys, expect new room id request, channel = self.make_request( "POST", "/createRoom", b'{"custom":"stuff"}' ) self.assertEquals(200, channel.code) self.assertTrue("room_id" in channel.json_body) def test_post_room_known_and_unknown_keys(self): # POST with custom + known config keys, expect new room id request, channel = self.make_request( "POST", "/createRoom", b'{"visibility":"private","custom":"things"}' ) self.assertEquals(200, channel.code) self.assertTrue("room_id" in channel.json_body) def test_post_room_invalid_content(self): # POST with invalid content / paths, expect 400 request, channel = self.make_request("POST", "/createRoom", b'{"visibili') self.assertEquals(400, channel.code) request, channel = self.make_request("POST", "/createRoom", b'["hello"]') self.assertEquals(400, channel.code) def test_post_room_invitees_invalid_mxid(self): # POST with invalid invitee, see https://github.com/matrix-org/synapse/issues/4088 # Note the trailing space in the MXID here! request, channel = self.make_request( "POST", "/createRoom", b'{"invite":["@alice:example.com "]}' ) self.assertEquals(400, channel.code) class RoomTopicTestCase(RoomBase): """ Tests /rooms/$room_id/topic REST events. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): # create the room self.room_id = self.helper.create_room_as(self.user_id) self.path = "/rooms/%s/state/m.room.topic" % (self.room_id,) def test_invalid_puts(self): # missing keys or invalid json request, channel = self.make_request("PUT", self.path, "{}") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", self.path, '{"_name":"bo"}') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", self.path, '{"nao') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request( "PUT", self.path, '[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", self.path, "text only") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", self.path, "") self.assertEquals(400, channel.code, msg=channel.result["body"]) # valid key, wrong type content = '{"topic":["Topic name"]}' request, channel = self.make_request("PUT", self.path, content) self.assertEquals(400, channel.code, msg=channel.result["body"]) def test_rooms_topic(self): # nothing should be there request, channel = self.make_request("GET", self.path) self.assertEquals(404, channel.code, msg=channel.result["body"]) # valid put content = '{"topic":"Topic name"}' request, channel = self.make_request("PUT", self.path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) # valid get request, channel = self.make_request("GET", self.path) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assert_dict(json.loads(content), channel.json_body) def test_rooms_topic_with_extra_keys(self): # valid put with extra keys content = '{"topic":"Seasons","subtopic":"Summer"}' request, channel = self.make_request("PUT", self.path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) # valid get request, channel = self.make_request("GET", self.path) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assert_dict(json.loads(content), channel.json_body) class RoomMemberStateTestCase(RoomBase): """ Tests /rooms/$room_id/members/$user_id/state REST events. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): self.room_id = self.helper.create_room_as(self.user_id) def test_invalid_puts(self): path = "/rooms/%s/state/m.room.member/%s" % (self.room_id, self.user_id) # missing keys or invalid json request, channel = self.make_request("PUT", path, "{}") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, '{"_name":"bo"}') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, '{"nao') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request( "PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, "text only") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, "") self.assertEquals(400, channel.code, msg=channel.result["body"]) # valid keys, wrong types content = '{"membership":["%s","%s","%s"]}' % ( Membership.INVITE, Membership.JOIN, Membership.LEAVE, ) request, channel = self.make_request("PUT", path, content.encode("ascii")) self.assertEquals(400, channel.code, msg=channel.result["body"]) def test_rooms_members_self(self): path = "/rooms/%s/state/m.room.member/%s" % ( urlparse.quote(self.room_id), self.user_id, ) # valid join message (NOOP since we made the room) content = '{"membership":"%s"}' % Membership.JOIN request, channel = self.make_request("PUT", path, content.encode("ascii")) self.assertEquals(200, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", path, None) self.assertEquals(200, channel.code, msg=channel.result["body"]) expected_response = {"membership": Membership.JOIN} self.assertEquals(expected_response, channel.json_body) def test_rooms_members_other(self): self.other_id = "@zzsid1:red" path = "/rooms/%s/state/m.room.member/%s" % ( urlparse.quote(self.room_id), self.other_id, ) # valid invite message content = '{"membership":"%s"}' % Membership.INVITE request, channel = self.make_request("PUT", path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", path, None) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assertEquals(json.loads(content), channel.json_body) def test_rooms_members_other_custom_keys(self): self.other_id = "@zzsid1:red" path = "/rooms/%s/state/m.room.member/%s" % ( urlparse.quote(self.room_id), self.other_id, ) # valid invite message with custom key content = '{"membership":"%s","invite_text":"%s"}' % ( Membership.INVITE, "Join us!", ) request, channel = self.make_request("PUT", path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) request, channel = self.make_request("GET", path, None) self.assertEquals(200, channel.code, msg=channel.result["body"]) self.assertEquals(json.loads(content), channel.json_body) class RoomJoinRatelimitTestCase(RoomBase): user_id = "@sid1:red" servlets = [ profile.register_servlets, room.register_servlets, ] @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def test_join_local_ratelimit(self): """Tests that local joins are actually rate-limited.""" for i in range(3): self.helper.create_room_as(self.user_id) self.helper.create_room_as(self.user_id, expect_code=429) @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def test_join_local_ratelimit_profile_change(self): """Tests that sending a profile update into all of the user's joined rooms isn't rate-limited by the rate-limiter on joins.""" # Create and join as many rooms as the rate-limiting config allows in a second. room_ids = [ self.helper.create_room_as(self.user_id), self.helper.create_room_as(self.user_id), self.helper.create_room_as(self.user_id), ] # Let some time for the rate-limiter to forget about our multi-join. self.reactor.advance(2) # Add one to make sure we're joined to more rooms than the config allows us to # join in a second. room_ids.append(self.helper.create_room_as(self.user_id)) # Create a profile for the user, since it hasn't been done on registration. store = self.hs.get_datastore() self.get_success( store.create_profile(UserID.from_string(self.user_id).localpart) ) # Update the display name for the user. path = "/_matrix/client/r0/profile/%s/displayname" % self.user_id request, channel = self.make_request("PUT", path, {"displayname": "John Doe"}) self.assertEquals(channel.code, 200, channel.json_body) # Check that all the rooms have been sent a profile update into. for room_id in room_ids: path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % ( room_id, self.user_id, ) request, channel = self.make_request("GET", path) self.assertEquals(channel.code, 200) self.assertIn("displayname", channel.json_body) self.assertEquals(channel.json_body["displayname"], "John Doe") @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def test_join_local_ratelimit_idempotent(self): """Tests that the room join endpoints remain idempotent despite rate-limiting on room joins.""" room_id = self.helper.create_room_as(self.user_id) # Let's test both paths to be sure. paths_to_test = [ "/_matrix/client/r0/rooms/%s/join", "/_matrix/client/r0/join/%s", ] for path in paths_to_test: # Make sure we send more requests than the rate-limiting config would allow # if all of these requests ended up joining the user to a room. for i in range(4): request, channel = self.make_request("POST", path % room_id, {}) self.assertEquals(channel.code, 200) class RoomMessagesTestCase(RoomBase): """ Tests /rooms/$room_id/messages/$user_id/$msg_id REST events. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): self.room_id = self.helper.create_room_as(self.user_id) def test_invalid_puts(self): path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id)) # missing keys or invalid json request, channel = self.make_request("PUT", path, b"{}") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, b'{"_name":"bo"}') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, b'{"nao') self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request( "PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, b"text only") self.assertEquals(400, channel.code, msg=channel.result["body"]) request, channel = self.make_request("PUT", path, b"") self.assertEquals(400, channel.code, msg=channel.result["body"]) def test_rooms_messages_sent(self): path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id)) content = b'{"body":"test","msgtype":{"type":"a"}}' request, channel = self.make_request("PUT", path, content) self.assertEquals(400, channel.code, msg=channel.result["body"]) # custom message types content = b'{"body":"test","msgtype":"test.custom.text"}' request, channel = self.make_request("PUT", path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) # m.text message type path = "/rooms/%s/send/m.room.message/mid2" % (urlparse.quote(self.room_id)) content = b'{"body":"test2","msgtype":"m.text"}' request, channel = self.make_request("PUT", path, content) self.assertEquals(200, channel.code, msg=channel.result["body"]) class RoomInitialSyncTestCase(RoomBase): """ Tests /rooms/$room_id/initialSync. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): # create the room self.room_id = self.helper.create_room_as(self.user_id) def test_initial_sync(self): request, channel = self.make_request( "GET", "/rooms/%s/initialSync" % self.room_id ) self.assertEquals(200, channel.code) self.assertEquals(self.room_id, channel.json_body["room_id"]) self.assertEquals("join", channel.json_body["membership"]) # Room state is easier to assert on if we unpack it into a dict state = {} for event in channel.json_body["state"]: if "state_key" not in event: continue t = event["type"] if t not in state: state[t] = [] state[t].append(event) self.assertTrue("m.room.create" in state) self.assertTrue("messages" in channel.json_body) self.assertTrue("chunk" in channel.json_body["messages"]) self.assertTrue("end" in channel.json_body["messages"]) self.assertTrue("presence" in channel.json_body) presence_by_user = { e["content"]["user_id"]: e for e in channel.json_body["presence"] } self.assertTrue(self.user_id in presence_by_user) self.assertEquals("m.presence", presence_by_user[self.user_id]["type"]) class RoomMessageListTestCase(RoomBase): """ Tests /rooms/$room_id/messages REST events. """ user_id = "@sid1:red" def prepare(self, reactor, clock, hs): self.room_id = self.helper.create_room_as(self.user_id) def test_topo_token_is_accepted(self): token = "t1-0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token) ) self.assertEquals(200, channel.code) self.assertTrue("start" in channel.json_body) self.assertEquals(token, channel.json_body["start"]) self.assertTrue("chunk" in channel.json_body) self.assertTrue("end" in channel.json_body) def test_stream_token_is_accepted_for_fwd_pagianation(self): token = "s0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token) ) self.assertEquals(200, channel.code) self.assertTrue("start" in channel.json_body) self.assertEquals(token, channel.json_body["start"]) self.assertTrue("chunk" in channel.json_body) self.assertTrue("end" in channel.json_body) def test_room_messages_purge(self): store = self.hs.get_datastore() pagination_handler = self.hs.get_pagination_handler() # Send a first message in the room, which will be removed by the purge. first_event_id = self.helper.send(self.room_id, "message 1")["event_id"] first_token = self.get_success( store.get_topological_token_for_event(first_event_id) ) first_token_str = self.get_success(first_token.to_string(store)) # Send a second message in the room, which won't be removed, and which we'll # use as the marker to purge events before. second_event_id = self.helper.send(self.room_id, "message 2")["event_id"] second_token = self.get_success( store.get_topological_token_for_event(second_event_id) ) second_token_str = self.get_success(second_token.to_string(store)) # Send a third event in the room to ensure we don't fall under any edge case # due to our marker being the latest forward extremity in the room. self.helper.send(self.room_id, "message 3") # Check that we get the first and second message when querying /messages. request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s" % ( self.room_id, second_token_str, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(channel.code, 200, channel.json_body) chunk = channel.json_body["chunk"] self.assertEqual(len(chunk), 2, [event["content"] for event in chunk]) # Purge every event before the second event. purge_id = random_string(16) pagination_handler._purges_by_id[purge_id] = PurgeStatus() self.get_success( pagination_handler._purge_history( purge_id=purge_id, room_id=self.room_id, token=second_token_str, delete_local_events=True, ) ) # Check that we only get the second message through /message now that the first # has been purged. request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s" % ( self.room_id, second_token_str, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(channel.code, 200, channel.json_body) chunk = channel.json_body["chunk"] self.assertEqual(len(chunk), 1, [event["content"] for event in chunk]) # Check that we get no event, but also no error, when querying /messages with # the token that was pointing at the first event, because we don't have it # anymore. request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s" % ( self.room_id, first_token_str, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(channel.code, 200, channel.json_body) chunk = channel.json_body["chunk"] self.assertEqual(len(chunk), 0, [event["content"] for event in chunk]) class RoomSearchTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, ] user_id = True hijack_auth = False def prepare(self, reactor, clock, hs): # Register the user who does the searching self.user_id = self.register_user("user", "pass") self.access_token = self.login("user", "pass") # Register the user who sends the message self.other_user_id = self.register_user("otheruser", "pass") self.other_access_token = self.login("otheruser", "pass") # Create a room self.room = self.helper.create_room_as(self.user_id, tok=self.access_token) # Invite the other person self.helper.invite( room=self.room, src=self.user_id, tok=self.access_token, targ=self.other_user_id, ) # The other user joins self.helper.join( room=self.room, user=self.other_user_id, tok=self.other_access_token ) def test_finds_message(self): """ The search functionality will search for content in messages if asked to do so. """ # The other user sends some messages self.helper.send(self.room, body="Hi!", tok=self.other_access_token) self.helper.send(self.room, body="There!", tok=self.other_access_token) request, channel = self.make_request( "POST", "/search?access_token=%s" % (self.access_token,), { "search_categories": { "room_events": {"keys": ["content.body"], "search_term": "Hi"} } }, ) # Check we get the results we expect -- one search result, of the sent # messages self.assertEqual(channel.code, 200) results = channel.json_body["search_categories"]["room_events"] self.assertEqual(results["count"], 1) self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!") # No context was requested, so we should get none. self.assertEqual(results["results"][0]["context"], {}) def test_include_context(self): """ When event_context includes include_profile, profile information will be included in the search response. """ # The other user sends some messages self.helper.send(self.room, body="Hi!", tok=self.other_access_token) self.helper.send(self.room, body="There!", tok=self.other_access_token) request, channel = self.make_request( "POST", "/search?access_token=%s" % (self.access_token,), { "search_categories": { "room_events": { "keys": ["content.body"], "search_term": "Hi", "event_context": {"include_profile": True}, } } }, ) # Check we get the results we expect -- one search result, of the sent # messages self.assertEqual(channel.code, 200) results = channel.json_body["search_categories"]["room_events"] self.assertEqual(results["count"], 1) self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!") # We should get context info, like the two users, and the display names. context = results["results"][0]["context"] self.assertEqual(len(context["profile_info"].keys()), 2) self.assertEqual( context["profile_info"][self.other_user_id]["displayname"], "otheruser" ) class PublicRoomsRestrictedTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, ] def make_homeserver(self, reactor, clock): self.url = b"/_matrix/client/r0/publicRooms" config = self.default_config() config["allow_public_rooms_without_auth"] = False self.hs = self.setup_test_homeserver(config=config) return self.hs def test_restricted_no_auth(self): request, channel = self.make_request("GET", self.url) self.assertEqual(channel.code, 401, channel.result) def test_restricted_auth(self): self.register_user("user", "pass") tok = self.login("user", "pass") request, channel = self.make_request("GET", self.url, access_token=tok) self.assertEqual(channel.code, 200, channel.result) class PerRoomProfilesForbiddenTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, profile.register_servlets, ] def make_homeserver(self, reactor, clock): config = self.default_config() config["allow_per_room_profiles"] = False self.hs = self.setup_test_homeserver(config=config) return self.hs def prepare(self, reactor, clock, homeserver): self.user_id = self.register_user("test", "test") self.tok = self.login("test", "test") # Set a profile for the test user self.displayname = "test user" data = {"displayname": self.displayname} request_data = json.dumps(data) request, channel = self.make_request( "PUT", "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,), request_data, access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok) def test_per_room_profile_forbidden(self): data = {"membership": "join", "displayname": "other test user"} request_data = json.dumps(data) request, channel = self.make_request( "PUT", "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (self.room_id, self.user_id), request_data, access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) event_id = channel.json_body["event_id"] request, channel = self.make_request( "GET", "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) res_displayname = channel.json_body["content"]["displayname"] self.assertEqual(res_displayname, self.displayname, channel.result) class RoomMembershipReasonTestCase(unittest.HomeserverTestCase): """Tests that clients can add a "reason" field to membership events and that they get correctly added to the generated events and propagated. """ servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, ] def prepare(self, reactor, clock, homeserver): self.creator = self.register_user("creator", "test") self.creator_tok = self.login("creator", "test") self.second_user_id = self.register_user("second", "test") self.second_tok = self.login("second", "test") self.room_id = self.helper.create_room_as(self.creator, tok=self.creator_tok) def test_join_reason(self): reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/join".format(self.room_id), content={"reason": reason}, access_token=self.second_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_leave_reason(self): self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok) reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/leave".format(self.room_id), content={"reason": reason}, access_token=self.second_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_kick_reason(self): self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok) reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/kick".format(self.room_id), content={"reason": reason, "user_id": self.second_user_id}, access_token=self.second_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_ban_reason(self): self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok) reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/ban".format(self.room_id), content={"reason": reason, "user_id": self.second_user_id}, access_token=self.creator_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_unban_reason(self): reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/unban".format(self.room_id), content={"reason": reason, "user_id": self.second_user_id}, access_token=self.creator_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_invite_reason(self): reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/invite".format(self.room_id), content={"reason": reason, "user_id": self.second_user_id}, access_token=self.creator_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def test_reject_invite_reason(self): self.helper.invite( self.room_id, src=self.creator, targ=self.second_user_id, tok=self.creator_tok, ) reason = "hello" request, channel = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/leave".format(self.room_id), content={"reason": reason}, access_token=self.second_tok, ) self.assertEqual(channel.code, 200, channel.result) self._check_for_reason(reason) def _check_for_reason(self, reason): request, channel = self.make_request( "GET", "/_matrix/client/r0/rooms/{}/state/m.room.member/{}".format( self.room_id, self.second_user_id ), access_token=self.creator_tok, ) self.assertEqual(channel.code, 200, channel.result) event_content = channel.json_body self.assertEqual(event_content.get("reason"), reason, channel.result) class LabelsTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, profile.register_servlets, ] # Filter that should only catch messages with the label "#fun". FILTER_LABELS = { "types": [EventTypes.Message], "org.matrix.labels": ["#fun"], } # Filter that should only catch messages without the label "#fun". FILTER_NOT_LABELS = { "types": [EventTypes.Message], "org.matrix.not_labels": ["#fun"], } # Filter that should only catch messages with the label "#work" but without the label # "#notfun". FILTER_LABELS_NOT_LABELS = { "types": [EventTypes.Message], "org.matrix.labels": ["#work"], "org.matrix.not_labels": ["#notfun"], } def prepare(self, reactor, clock, homeserver): self.user_id = self.register_user("test", "test") self.tok = self.login("test", "test") self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok) def test_context_filter_labels(self): """Test that we can filter by a label on a /context request.""" event_id = self._send_labelled_messages_in_room() request, channel = self.make_request( "GET", "/rooms/%s/context/%s?filter=%s" % (self.room_id, event_id, json.dumps(self.FILTER_LABELS)), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual( len(events_before), 1, [event["content"] for event in events_before] ) self.assertEqual( events_before[0]["content"]["body"], "with right label", events_before[0] ) events_after = channel.json_body["events_before"] self.assertEqual( len(events_after), 1, [event["content"] for event in events_after] ) self.assertEqual( events_after[0]["content"]["body"], "with right label", events_after[0] ) def test_context_filter_not_labels(self): """Test that we can filter by the absence of a label on a /context request.""" event_id = self._send_labelled_messages_in_room() request, channel = self.make_request( "GET", "/rooms/%s/context/%s?filter=%s" % (self.room_id, event_id, json.dumps(self.FILTER_NOT_LABELS)), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual( len(events_before), 1, [event["content"] for event in events_before] ) self.assertEqual( events_before[0]["content"]["body"], "without label", events_before[0] ) events_after = channel.json_body["events_after"] self.assertEqual( len(events_after), 2, [event["content"] for event in events_after] ) self.assertEqual( events_after[0]["content"]["body"], "with wrong label", events_after[0] ) self.assertEqual( events_after[1]["content"]["body"], "with two wrong labels", events_after[1] ) def test_context_filter_labels_not_labels(self): """Test that we can filter by both a label and the absence of another label on a /context request. """ event_id = self._send_labelled_messages_in_room() request, channel = self.make_request( "GET", "/rooms/%s/context/%s?filter=%s" % (self.room_id, event_id, json.dumps(self.FILTER_LABELS_NOT_LABELS)), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual( len(events_before), 0, [event["content"] for event in events_before] ) events_after = channel.json_body["events_after"] self.assertEqual( len(events_after), 1, [event["content"] for event in events_after] ) self.assertEqual( events_after[0]["content"]["body"], "with wrong label", events_after[0] ) def test_messages_filter_labels(self): """Test that we can filter by a label on a /messages request.""" self._send_labelled_messages_in_room() token = "s0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=%s&from=%s&filter=%s" % (self.room_id, self.tok, token, json.dumps(self.FILTER_LABELS)), ) events = channel.json_body["chunk"] self.assertEqual(len(events), 2, [event["content"] for event in events]) self.assertEqual(events[0]["content"]["body"], "with right label", events[0]) self.assertEqual(events[1]["content"]["body"], "with right label", events[1]) def test_messages_filter_not_labels(self): """Test that we can filter by the absence of a label on a /messages request.""" self._send_labelled_messages_in_room() token = "s0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=%s&from=%s&filter=%s" % (self.room_id, self.tok, token, json.dumps(self.FILTER_NOT_LABELS)), ) events = channel.json_body["chunk"] self.assertEqual(len(events), 4, [event["content"] for event in events]) self.assertEqual(events[0]["content"]["body"], "without label", events[0]) self.assertEqual(events[1]["content"]["body"], "without label", events[1]) self.assertEqual(events[2]["content"]["body"], "with wrong label", events[2]) self.assertEqual( events[3]["content"]["body"], "with two wrong labels", events[3] ) def test_messages_filter_labels_not_labels(self): """Test that we can filter by both a label and the absence of another label on a /messages request. """ self._send_labelled_messages_in_room() token = "s0_0_0_0_0_0_0_0_0" request, channel = self.make_request( "GET", "/rooms/%s/messages?access_token=%s&from=%s&filter=%s" % ( self.room_id, self.tok, token, json.dumps(self.FILTER_LABELS_NOT_LABELS), ), ) events = channel.json_body["chunk"] self.assertEqual(len(events), 1, [event["content"] for event in events]) self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0]) def test_search_filter_labels(self): """Test that we can filter by a label on a /search request.""" request_data = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_LABELS, } } } ) self._send_labelled_messages_in_room() request, channel = self.make_request( "POST", "/search?access_token=%s" % self.tok, request_data ) results = channel.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(results), 2, [result["result"]["content"] for result in results], ) self.assertEqual( results[0]["result"]["content"]["body"], "with right label", results[0]["result"]["content"]["body"], ) self.assertEqual( results[1]["result"]["content"]["body"], "with right label", results[1]["result"]["content"]["body"], ) def test_search_filter_not_labels(self): """Test that we can filter by the absence of a label on a /search request.""" request_data = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_NOT_LABELS, } } } ) self._send_labelled_messages_in_room() request, channel = self.make_request( "POST", "/search?access_token=%s" % self.tok, request_data ) results = channel.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(results), 4, [result["result"]["content"] for result in results], ) self.assertEqual( results[0]["result"]["content"]["body"], "without label", results[0]["result"]["content"]["body"], ) self.assertEqual( results[1]["result"]["content"]["body"], "without label", results[1]["result"]["content"]["body"], ) self.assertEqual( results[2]["result"]["content"]["body"], "with wrong label", results[2]["result"]["content"]["body"], ) self.assertEqual( results[3]["result"]["content"]["body"], "with two wrong labels", results[3]["result"]["content"]["body"], ) def test_search_filter_labels_not_labels(self): """Test that we can filter by both a label and the absence of another label on a /search request. """ request_data = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_LABELS_NOT_LABELS, } } } ) self._send_labelled_messages_in_room() request, channel = self.make_request( "POST", "/search?access_token=%s" % self.tok, request_data ) results = channel.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(results), 1, [result["result"]["content"] for result in results], ) self.assertEqual( results[0]["result"]["content"]["body"], "with wrong label", results[0]["result"]["content"]["body"], ) def _send_labelled_messages_in_room(self): """Sends several messages to a room with different labels (or without any) to test filtering by label. Returns: The ID of the event to use if we're testing filtering on /context. """ self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={ "msgtype": "m.text", "body": "with right label", EventContentFields.LABELS: ["#fun"], }, tok=self.tok, ) self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={"msgtype": "m.text", "body": "without label"}, tok=self.tok, ) res = self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={"msgtype": "m.text", "body": "without label"}, tok=self.tok, ) # Return this event's ID when we test filtering in /context requests. event_id = res["event_id"] self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={ "msgtype": "m.text", "body": "with wrong label", EventContentFields.LABELS: ["#work"], }, tok=self.tok, ) self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={ "msgtype": "m.text", "body": "with two wrong labels", EventContentFields.LABELS: ["#work", "#notfun"], }, tok=self.tok, ) self.helper.send_event( room_id=self.room_id, type=EventTypes.Message, content={ "msgtype": "m.text", "body": "with right label", EventContentFields.LABELS: ["#fun"], }, tok=self.tok, ) return event_id class ContextTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, account.register_servlets, ] def prepare(self, reactor, clock, homeserver): self.user_id = self.register_user("user", "password") self.tok = self.login("user", "password") self.room_id = self.helper.create_room_as( self.user_id, tok=self.tok, is_public=False ) self.other_user_id = self.register_user("user2", "password") self.other_tok = self.login("user2", "password") self.helper.invite(self.room_id, self.user_id, self.other_user_id, tok=self.tok) self.helper.join(self.room_id, self.other_user_id, tok=self.other_tok) def test_erased_sender(self): """Test that an erasure request results in the requester's events being hidden from any new member of the room. """ # Send a bunch of events in the room. self.helper.send(self.room_id, "message 1", tok=self.tok) self.helper.send(self.room_id, "message 2", tok=self.tok) event_id = self.helper.send(self.room_id, "message 3", tok=self.tok)["event_id"] self.helper.send(self.room_id, "message 4", tok=self.tok) self.helper.send(self.room_id, "message 5", tok=self.tok) # Check that we can still see the messages before the erasure request. request, channel = self.make_request( "GET", '/rooms/%s/context/%s?filter={"types":["m.room.message"]}' % (self.room_id, event_id), access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual(len(events_before), 2, events_before) self.assertEqual( events_before[0].get("content", {}).get("body"), "message 2", events_before[0], ) self.assertEqual( events_before[1].get("content", {}).get("body"), "message 1", events_before[1], ) self.assertEqual( channel.json_body["event"].get("content", {}).get("body"), "message 3", channel.json_body["event"], ) events_after = channel.json_body["events_after"] self.assertEqual(len(events_after), 2, events_after) self.assertEqual( events_after[0].get("content", {}).get("body"), "message 4", events_after[0], ) self.assertEqual( events_after[1].get("content", {}).get("body"), "message 5", events_after[1], ) # Deactivate the first account and erase the user's data. deactivate_account_handler = self.hs.get_deactivate_account_handler() self.get_success( deactivate_account_handler.deactivate_account(self.user_id, erase_data=True) ) # Invite another user in the room. This is needed because messages will be # pruned only if the user wasn't a member of the room when the messages were # sent. invited_user_id = self.register_user("user3", "password") invited_tok = self.login("user3", "password") self.helper.invite( self.room_id, self.other_user_id, invited_user_id, tok=self.other_tok ) self.helper.join(self.room_id, invited_user_id, tok=invited_tok) # Check that a user that joined the room after the erasure request can't see # the messages anymore. request, channel = self.make_request( "GET", '/rooms/%s/context/%s?filter={"types":["m.room.message"]}' % (self.room_id, event_id), access_token=invited_tok, ) self.assertEqual(channel.code, 200, channel.result) events_before = channel.json_body["events_before"] self.assertEqual(len(events_before), 2, events_before) self.assertDictEqual(events_before[0].get("content"), {}, events_before[0]) self.assertDictEqual(events_before[1].get("content"), {}, events_before[1]) self.assertDictEqual( channel.json_body["event"].get("content"), {}, channel.json_body["event"] ) events_after = channel.json_body["events_after"] self.assertEqual(len(events_after), 2, events_after) self.assertDictEqual(events_after[0].get("content"), {}, events_after[0]) self.assertEqual(events_after[1].get("content"), {}, events_after[1]) class RoomAliasListTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, directory.register_servlets, login.register_servlets, room.register_servlets, ] def prepare(self, reactor, clock, homeserver): self.room_owner = self.register_user("room_owner", "test") self.room_owner_tok = self.login("room_owner", "test") self.room_id = self.helper.create_room_as( self.room_owner, tok=self.room_owner_tok ) def test_no_aliases(self): res = self._get_aliases(self.room_owner_tok) self.assertEqual(res["aliases"], []) def test_not_in_room(self): self.register_user("user", "test") user_tok = self.login("user", "test") res = self._get_aliases(user_tok, expected_code=403) self.assertEqual(res["errcode"], "M_FORBIDDEN") def test_admin_user(self): alias1 = self._random_alias() self._set_alias_via_directory(alias1) self.register_user("user", "test", admin=True) user_tok = self.login("user", "test") res = self._get_aliases(user_tok) self.assertEqual(res["aliases"], [alias1]) def test_with_aliases(self): alias1 = self._random_alias() alias2 = self._random_alias() self._set_alias_via_directory(alias1) self._set_alias_via_directory(alias2) res = self._get_aliases(self.room_owner_tok) self.assertEqual(set(res["aliases"]), {alias1, alias2}) def test_peekable_room(self): alias1 = self._random_alias() self._set_alias_via_directory(alias1) self.helper.send_state( self.room_id, EventTypes.RoomHistoryVisibility, body={"history_visibility": "world_readable"}, tok=self.room_owner_tok, ) self.register_user("user", "test") user_tok = self.login("user", "test") res = self._get_aliases(user_tok) self.assertEqual(res["aliases"], [alias1]) def _get_aliases(self, access_token: str, expected_code: int = 200) -> JsonDict: """Calls the endpoint under test. returns the json response object.""" request, channel = self.make_request( "GET", "/_matrix/client/unstable/org.matrix.msc2432/rooms/%s/aliases" % (self.room_id,), access_token=access_token, ) self.assertEqual(channel.code, expected_code, channel.result) res = channel.json_body self.assertIsInstance(res, dict) if expected_code == 200: self.assertIsInstance(res["aliases"], list) return res def _random_alias(self) -> str: return RoomAlias(random_string(5), self.hs.hostname).to_string() def _set_alias_via_directory(self, alias: str, expected_code: int = 200): url = "/_matrix/client/r0/directory/room/" + alias data = {"room_id": self.room_id} request_data = json.dumps(data) request, channel = self.make_request( "PUT", url, request_data, access_token=self.room_owner_tok ) self.assertEqual(channel.code, expected_code, channel.result) class RoomCanonicalAliasTestCase(unittest.HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, directory.register_servlets, login.register_servlets, room.register_servlets, ] def prepare(self, reactor, clock, homeserver): self.room_owner = self.register_user("room_owner", "test") self.room_owner_tok = self.login("room_owner", "test") self.room_id = self.helper.create_room_as( self.room_owner, tok=self.room_owner_tok ) self.alias = "#alias:test" self._set_alias_via_directory(self.alias) def _set_alias_via_directory(self, alias: str, expected_code: int = 200): url = "/_matrix/client/r0/directory/room/" + alias data = {"room_id": self.room_id} request_data = json.dumps(data) request, channel = self.make_request( "PUT", url, request_data, access_token=self.room_owner_tok ) self.assertEqual(channel.code, expected_code, channel.result) def _get_canonical_alias(self, expected_code: int = 200) -> JsonDict: """Calls the endpoint under test. returns the json response object.""" request, channel = self.make_request( "GET", "rooms/%s/state/m.room.canonical_alias" % (self.room_id,), access_token=self.room_owner_tok, ) self.assertEqual(channel.code, expected_code, channel.result) res = channel.json_body self.assertIsInstance(res, dict) return res def _set_canonical_alias(self, content: str, expected_code: int = 200) -> JsonDict: """Calls the endpoint under test. returns the json response object.""" request, channel = self.make_request( "PUT", "rooms/%s/state/m.room.canonical_alias" % (self.room_id,), json.dumps(content), access_token=self.room_owner_tok, ) self.assertEqual(channel.code, expected_code, channel.result) res = channel.json_body self.assertIsInstance(res, dict) return res def test_canonical_alias(self): """Test a basic alias message.""" # There is no canonical alias to start with. self._get_canonical_alias(expected_code=404) # Create an alias. self._set_canonical_alias({"alias": self.alias}) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual(res, {"alias": self.alias}) # Now remove the alias. self._set_canonical_alias({}) # There is an alias event, but it is empty. res = self._get_canonical_alias() self.assertEqual(res, {}) def test_alt_aliases(self): """Test a canonical alias message with alt_aliases.""" # Create an alias. self._set_canonical_alias({"alt_aliases": [self.alias]}) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual(res, {"alt_aliases": [self.alias]}) # Now remove the alt_aliases. self._set_canonical_alias({}) # There is an alias event, but it is empty. res = self._get_canonical_alias() self.assertEqual(res, {}) def test_alias_alt_aliases(self): """Test a canonical alias message with an alias and alt_aliases.""" # Create an alias. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]}) # Now remove the alias and alt_aliases. self._set_canonical_alias({}) # There is an alias event, but it is empty. res = self._get_canonical_alias() self.assertEqual(res, {}) def test_partial_modify(self): """Test removing only the alt_aliases.""" # Create an alias. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]}) # Now remove the alt_aliases. self._set_canonical_alias({"alias": self.alias}) # There is an alias event, but it is empty. res = self._get_canonical_alias() self.assertEqual(res, {"alias": self.alias}) def test_add_alias(self): """Test removing only the alt_aliases.""" # Create an additional alias. second_alias = "#second:test" self._set_alias_via_directory(second_alias) # Add the canonical alias. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) # Then add the second alias. self._set_canonical_alias( {"alias": self.alias, "alt_aliases": [self.alias, second_alias]} ) # Canonical alias now exists! res = self._get_canonical_alias() self.assertEqual( res, {"alias": self.alias, "alt_aliases": [self.alias, second_alias]} ) def test_bad_data(self): """Invalid data for alt_aliases should cause errors.""" self._set_canonical_alias({"alt_aliases": "@bad:test"}, expected_code=400) self._set_canonical_alias({"alt_aliases": None}, expected_code=400) self._set_canonical_alias({"alt_aliases": 0}, expected_code=400) self._set_canonical_alias({"alt_aliases": 1}, expected_code=400) self._set_canonical_alias({"alt_aliases": False}, expected_code=400) self._set_canonical_alias({"alt_aliases": True}, expected_code=400) self._set_canonical_alias({"alt_aliases": {}}, expected_code=400) def test_bad_alias(self): """An alias which does not point to the room raises a SynapseError.""" self._set_canonical_alias({"alias": "@unknown:test"}, expected_code=400) self._set_canonical_alias({"alt_aliases": ["@unknown:test"]}, expected_code=400)
open_redirect
{ "code": [ " \"red\", http_client=None, federation_client=Mock()," ], "line_no": [ 48 ] }
{ "code": [ " \"red\", federation_http_client=None, federation_client=Mock()," ], "line_no": [ 48 ] }
import json from urllib import parse as urlparse from mock import Mock import synapse.rest.admin from synapse.api.constants import EventContentFields, EventTypes, Membership from synapse.handlers.pagination import PurgeStatus from synapse.rest.client.v1 import directory, login, profile, VAR_7 from synapse.rest.client.v2_alpha import account from synapse.types import JsonDict, RoomAlias, UserID from synapse.util.stringutils import random_string from tests import unittest from tests.test_utils import make_awaitable VAR_0 = b"/_matrix/client/api/v1" class CLASS_0(unittest.HomeserverTestCase): VAR_1 = None VAR_2 = [VAR_7.register_servlets, VAR_7.register_deprecated_servlets] def FUNC_0(self, VAR_3, VAR_4): self.hs = self.setup_test_homeserver( "red", http_client=None, federation_client=Mock(), ) self.hs.get_federation_handler = Mock() self.hs.get_federation_handler.return_value.maybe_backfill = Mock( return_value=make_awaitable(None) ) async def FUNC_76(*VAR_20, **VAR_21): return None self.hs.get_datastore().insert_client_ip = FUNC_76 return self.hs class CLASS_1(CLASS_0): VAR_5 = "@sid1:red" VAR_1 = "@notme:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.helper.auth_user_id = self.rmcreator_id self.uncreated_rmid = "!aa:test" self.created_rmid = self.helper.create_room_as( self.rmcreator_id, is_public=False ) self.created_public_rmid = self.helper.create_room_as( self.rmcreator_id, is_public=True ) self.created_rmid_msg_path = ( "rooms/%s/send/m.room.message/a1" % (self.created_rmid) ).encode("ascii") VAR_22, VAR_23 = self.make_request( "PUT", self.created_rmid_msg_path, b'{"msgtype":"m.text","body":"test msg"}' ) self.assertEquals(200, VAR_23.code, VAR_23.result) VAR_22, VAR_23 = self.make_request( "PUT", ("rooms/%s/VAR_37/m.room.topic" % self.created_public_rmid).encode("ascii"), b'{"topic":"Public Room Topic"}', ) self.assertEquals(200, VAR_23.code, VAR_23.result) self.helper.auth_user_id = self.user_id def FUNC_2(self): VAR_24 = b'{"msgtype":"m.text","body":"hello"}' VAR_25 = iter(range(100)) def FUNC_77(): return "/rooms/%s/send/m.room.message/mid%s" % ( self.created_rmid, str(next(VAR_25)), ) VAR_22, VAR_23 = self.make_request( "PUT", "/rooms/%s/send/m.room.message/mid2" % (self.uncreated_rmid,), VAR_24, ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", FUNC_77(), VAR_24) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.invite( VAR_7=self.created_rmid, src=self.rmcreator_id, targ=self.user_id ) VAR_22, VAR_23 = self.make_request("PUT", FUNC_77(), VAR_24) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.join(VAR_7=self.created_rmid, user=self.user_id) VAR_22, VAR_23 = self.make_request("PUT", FUNC_77(), VAR_24) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.helper.leave(VAR_7=self.created_rmid, user=self.user_id) VAR_22, VAR_23 = self.make_request("PUT", FUNC_77(), VAR_24) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_3(self): VAR_26 = b'{"topic":"My Topic Name"}' VAR_27 = "/rooms/%s/VAR_37/m.room.topic" % self.created_rmid VAR_22, VAR_23 = self.make_request( "PUT", "/rooms/%s/VAR_37/m.room.topic" % self.uncreated_rmid, VAR_26 ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_37/m.room.topic" % self.uncreated_rmid ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_27, VAR_26) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_27) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.invite( VAR_7=self.created_rmid, src=self.rmcreator_id, targ=self.user_id ) VAR_22, VAR_23 = self.make_request("PUT", VAR_27, VAR_26) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_27) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.join(VAR_7=self.created_rmid, user=self.user_id) self.helper.auth_user_id = self.rmcreator_id VAR_22, VAR_23 = self.make_request("PUT", VAR_27, VAR_26) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.helper.auth_user_id = self.user_id VAR_22, VAR_23 = self.make_request("GET", VAR_27) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assert_dict(json.loads(VAR_26.decode("utf8")), VAR_23.json_body) self.helper.leave(VAR_7=self.created_rmid, user=self.user_id) VAR_22, VAR_23 = self.make_request("PUT", VAR_27, VAR_26) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_27) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_37/m.room.topic" % self.created_public_rmid ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "PUT", "/rooms/%s/VAR_37/m.room.topic" % self.created_public_rmid, VAR_26, ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_4(self, VAR_7=None, VAR_8=[], VAR_9=None): for member in VAR_8: VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % (VAR_7, member) VAR_22, VAR_23 = self.make_request("GET", VAR_32) self.assertEquals(VAR_9, VAR_23.code) def FUNC_5(self): VAR_7 = self.uncreated_rmid self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=403 ) self.helper.invite( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, VAR_9=403 ) for usr in [self.user_id, self.rmcreator_id]: self.helper.join(VAR_7=room, user=usr, VAR_9=404) self.helper.leave(VAR_7=room, user=usr, VAR_9=404) def FUNC_6(self): VAR_7 = self.created_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=403 ) self.helper.join(VAR_7=room, user=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=200 ) self.helper.leave(VAR_7=room, user=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=200 ) def FUNC_7(self): VAR_7 = self.created_public_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=403 ) self.helper.join(VAR_7=room, user=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=200 ) self.helper.leave(VAR_7=room, user=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=200 ) def FUNC_8(self): VAR_7 = self.created_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self.helper.invite( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, VAR_9=403 ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.JOIN, VAR_9=403, ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.LEAVE, VAR_9=403, ) def FUNC_9(self): VAR_7 = self.created_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self.helper.join(VAR_7=room, user=self.user_id) self.helper.invite( VAR_7=room, src=self.user_id, targ=self.user_id, VAR_9=403 ) self.helper.join(VAR_7=room, user=self.user_id) VAR_28 = "@burgundy:red" self.helper.invite(VAR_7=room, src=self.user_id, targ=VAR_28, VAR_9=200) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=VAR_28, membership=Membership.JOIN, VAR_9=403, ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=VAR_28, membership=Membership.LEAVE, VAR_9=403, ) self.helper.leave(VAR_7=room, user=self.user_id) def FUNC_10(self): VAR_7 = self.created_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self.helper.join(VAR_7=room, user=self.user_id) self.helper.leave(VAR_7=room, user=self.user_id) for usr in [self.user_id, self.rmcreator_id]: self.helper.change_membership( VAR_7=room, src=self.user_id, targ=usr, membership=Membership.INVITE, VAR_9=403, ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=usr, membership=Membership.JOIN, VAR_9=403, ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.LEAVE, VAR_9=403, ) class CLASS_2(CLASS_0): VAR_5 = "@sid1:red" def FUNC_11(self): VAR_29 = self.helper.create_room_as(self.user_id) VAR_22, VAR_23 = self.make_request("GET", "/rooms/%s/members" % VAR_29) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_12(self): VAR_22, VAR_23 = self.make_request("GET", "/rooms/roomdoesnotexist/members") self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_13(self): VAR_29 = self.helper.create_room_as("@some_other_guy:red") VAR_22, VAR_23 = self.make_request("GET", "/rooms/%s/members" % VAR_29) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_14(self): VAR_30 = "@some_other_guy:red" VAR_29 = self.helper.create_room_as(VAR_30) VAR_31 = "/rooms/%s/members" % VAR_29 self.helper.invite(VAR_7=VAR_29, src=VAR_30, targ=self.user_id) VAR_22, VAR_23 = self.make_request("GET", VAR_31) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.join(VAR_7=VAR_29, user=self.user_id) VAR_22, VAR_23 = self.make_request("GET", VAR_31) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.helper.leave(VAR_7=VAR_29, user=self.user_id) VAR_22, VAR_23 = self.make_request("GET", VAR_31) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) class CLASS_3(CLASS_0): VAR_5 = "@sid1:red" def FUNC_15(self): VAR_22, VAR_23 = self.make_request("POST", "/createRoom", "{}") self.assertEquals(200, VAR_23.code, VAR_23.result) self.assertTrue("room_id" in VAR_23.json_body) def FUNC_16(self): VAR_22, VAR_23 = self.make_request( "POST", "/createRoom", b'{"visibility":"private"}' ) self.assertEquals(200, VAR_23.code) self.assertTrue("room_id" in VAR_23.json_body) def FUNC_17(self): VAR_22, VAR_23 = self.make_request( "POST", "/createRoom", b'{"custom":"stuff"}' ) self.assertEquals(200, VAR_23.code) self.assertTrue("room_id" in VAR_23.json_body) def FUNC_18(self): VAR_22, VAR_23 = self.make_request( "POST", "/createRoom", b'{"visibility":"private","custom":"things"}' ) self.assertEquals(200, VAR_23.code) self.assertTrue("room_id" in VAR_23.json_body) def FUNC_19(self): VAR_22, VAR_23 = self.make_request("POST", "/createRoom", b'{"visibili') self.assertEquals(400, VAR_23.code) VAR_22, VAR_23 = self.make_request("POST", "/createRoom", b'["hello"]') self.assertEquals(400, VAR_23.code) def FUNC_20(self): VAR_22, VAR_23 = self.make_request( "POST", "/createRoom", b'{"invite":["@alice:example.com "]}' ) self.assertEquals(400, VAR_23.code) class CLASS_4(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) self.path = "/rooms/%s/VAR_37/m.room.topic" % (self.room_id,) def FUNC_21(self): VAR_22, VAR_23 = self.make_request("PUT", self.path, "{}") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", self.path, '{"_name":"bo"}') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", self.path, '{"nao') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "PUT", self.path, '[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", self.path, "text only") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", self.path, "") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_19 = '{"topic":["Topic name"]}' VAR_22, VAR_23 = self.make_request("PUT", self.path, VAR_19) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_22(self): VAR_22, VAR_23 = self.make_request("GET", self.path) self.assertEquals(404, VAR_23.code, msg=VAR_23.result["body"]) VAR_19 = '{"topic":"Topic name"}' VAR_22, VAR_23 = self.make_request("PUT", self.path, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", self.path) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assert_dict(json.loads(VAR_19), VAR_23.json_body) def FUNC_23(self): VAR_19 = '{"topic":"Seasons","subtopic":"Summer"}' VAR_22, VAR_23 = self.make_request("PUT", self.path, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", self.path) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assert_dict(json.loads(VAR_19), VAR_23.json_body) class CLASS_5(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) def FUNC_21(self): VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % (self.room_id, self.user_id) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, "{}") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, '{"_name":"bo"}') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, '{"nao') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "PUT", VAR_32, b'[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, "text only") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, "") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_19 = '{"membership":["%s","%s","%s"]}' % ( Membership.INVITE, Membership.JOIN, Membership.LEAVE, ) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19.encode("ascii")) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_24(self): VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % ( urlparse.quote(self.room_id), self.user_id, ) VAR_19 = '{"membership":"%s"}' % Membership.JOIN VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19.encode("ascii")) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_32, None) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_33 = {"membership": Membership.JOIN} self.assertEquals(VAR_33, VAR_23.json_body) def FUNC_25(self): self.other_id = "@zzsid1:red" VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % ( urlparse.quote(self.room_id), self.other_id, ) VAR_19 = '{"membership":"%s"}' % Membership.INVITE VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_32, None) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assertEquals(json.loads(VAR_19), VAR_23.json_body) def FUNC_26(self): self.other_id = "@zzsid1:red" VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % ( urlparse.quote(self.room_id), self.other_id, ) VAR_19 = '{"membership":"%s","invite_text":"%s"}' % ( Membership.INVITE, "Join us!", ) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_32, None) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assertEquals(json.loads(VAR_19), VAR_23.json_body) class CLASS_6(CLASS_0): VAR_5 = "@sid1:red" VAR_2 = [ profile.register_servlets, VAR_7.register_servlets, ] @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def FUNC_27(self): for i in range(3): self.helper.create_room_as(self.user_id) self.helper.create_room_as(self.user_id, VAR_9=429) @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def FUNC_28(self): VAR_34 = [ self.helper.create_room_as(self.user_id), self.helper.create_room_as(self.user_id), self.helper.create_room_as(self.user_id), ] self.reactor.advance(2) VAR_34.append(self.helper.create_room_as(self.user_id)) VAR_35 = self.hs.get_datastore() self.get_success( VAR_35.create_profile(UserID.from_string(self.user_id).localpart) ) VAR_32 = "/_matrix/client/r0/profile/%s/displayname" % self.user_id VAR_22, VAR_23 = self.make_request("PUT", VAR_32, {"displayname": "John Doe"}) self.assertEquals(VAR_23.code, 200, VAR_23.json_body) for VAR_29 in VAR_34: VAR_32 = "/_matrix/client/r0/rooms/%s/VAR_37/m.room.member/%s" % ( VAR_29, self.user_id, ) VAR_22, VAR_23 = self.make_request("GET", VAR_32) self.assertEquals(VAR_23.code, 200) self.assertIn("displayname", VAR_23.json_body) self.assertEquals(VAR_23.json_body["displayname"], "John Doe") @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def FUNC_29(self): VAR_29 = self.helper.create_room_as(self.user_id) VAR_36 = [ "/_matrix/client/r0/rooms/%s/join", "/_matrix/client/r0/join/%s", ] for VAR_32 in VAR_36: for i in range(4): VAR_22, VAR_23 = self.make_request("POST", VAR_32 % VAR_29, {}) self.assertEquals(VAR_23.code, 200) class CLASS_7(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) def FUNC_21(self): VAR_32 = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id)) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b"{}") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b'{"_name":"bo"}') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b'{"nao') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "PUT", VAR_32, b'[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b"text only") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b"") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_30(self): VAR_32 = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id)) VAR_19 = b'{"body":"test","msgtype":{"type":"a"}}' VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_19 = b'{"body":"test","msgtype":"test.custom.text"}' VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_32 = "/rooms/%s/send/m.room.message/mid2" % (urlparse.quote(self.room_id)) VAR_19 = b'{"body":"test2","msgtype":"m.text"}' VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) class CLASS_8(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) def FUNC_31(self): VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/initialSync" % self.room_id ) self.assertEquals(200, VAR_23.code) self.assertEquals(self.room_id, VAR_23.json_body["room_id"]) self.assertEquals("join", VAR_23.json_body["membership"]) VAR_37 = {} for event in VAR_23.json_body["state"]: if "state_key" not in event: continue VAR_70 = event["type"] if VAR_70 not in VAR_37: state[VAR_70] = [] VAR_37[VAR_70].append(event) self.assertTrue("m.room.create" in VAR_37) self.assertTrue("messages" in VAR_23.json_body) self.assertTrue("chunk" in VAR_23.json_body["messages"]) self.assertTrue("end" in VAR_23.json_body["messages"]) self.assertTrue("presence" in VAR_23.json_body) VAR_38 = { e["content"]["user_id"]: e for e in VAR_23.json_body["presence"] } self.assertTrue(self.user_id in VAR_38) self.assertEquals("m.presence", VAR_38[self.user_id]["type"]) class CLASS_9(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) def FUNC_32(self): VAR_39 = "t1-0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s" % (self.room_id, VAR_39) ) self.assertEquals(200, VAR_23.code) self.assertTrue("start" in VAR_23.json_body) self.assertEquals(VAR_39, VAR_23.json_body["start"]) self.assertTrue("chunk" in VAR_23.json_body) self.assertTrue("end" in VAR_23.json_body) def FUNC_33(self): VAR_39 = "s0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s" % (self.room_id, VAR_39) ) self.assertEquals(200, VAR_23.code) self.assertTrue("start" in VAR_23.json_body) self.assertEquals(VAR_39, VAR_23.json_body["start"]) self.assertTrue("chunk" in VAR_23.json_body) self.assertTrue("end" in VAR_23.json_body) def FUNC_34(self): VAR_35 = self.hs.get_datastore() VAR_40 = self.hs.get_pagination_handler() VAR_41 = self.helper.send(self.room_id, "message 1")["event_id"] VAR_42 = self.get_success( VAR_35.get_topological_token_for_event(VAR_41) ) VAR_43 = self.get_success(VAR_42.to_string(VAR_35)) VAR_44 = self.helper.send(self.room_id, "message 2")["event_id"] VAR_45 = self.get_success( VAR_35.get_topological_token_for_event(VAR_44) ) VAR_46 = self.get_success(VAR_45.to_string(VAR_35)) self.helper.send(self.room_id, "message 3") VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s&dir=b&filter=%s" % ( self.room_id, VAR_46, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(VAR_23.code, 200, VAR_23.json_body) VAR_47 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_47), 2, [event["content"] for event in VAR_47]) VAR_48 = random_string(16) VAR_40._purges_by_id[VAR_48] = PurgeStatus() self.get_success( VAR_40._purge_history( VAR_48=purge_id, VAR_29=self.room_id, VAR_39=VAR_46, delete_local_events=True, ) ) VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s&dir=b&filter=%s" % ( self.room_id, VAR_46, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(VAR_23.code, 200, VAR_23.json_body) VAR_47 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_47), 1, [event["content"] for event in VAR_47]) VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s&dir=b&filter=%s" % ( self.room_id, VAR_43, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(VAR_23.code, 200, VAR_23.json_body) VAR_47 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_47), 0, [event["content"] for event in VAR_47]) class CLASS_10(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, ] VAR_5 = True VAR_10 = False def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.user_id = self.register_user("user", "pass") self.access_token = self.login("user", "pass") self.other_user_id = self.register_user("otheruser", "pass") self.other_access_token = self.login("otheruser", "pass") self.room = self.helper.create_room_as(self.user_id, VAR_52=self.access_token) self.helper.invite( VAR_7=self.room, src=self.user_id, VAR_52=self.access_token, targ=self.other_user_id, ) self.helper.join( VAR_7=self.room, user=self.other_user_id, VAR_52=self.other_access_token ) def FUNC_35(self): self.helper.send(self.room, body="Hi!", VAR_52=self.other_access_token) self.helper.send(self.room, body="There!", VAR_52=self.other_access_token) VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % (self.access_token,), { "search_categories": { "room_events": {"keys": ["content.body"], "search_term": "Hi"} } }, ) self.assertEqual(VAR_23.code, 200) VAR_49 = VAR_23.json_body["search_categories"]["room_events"] self.assertEqual(VAR_49["count"], 1) self.assertEqual(VAR_49["results"][0]["result"]["content"]["body"], "Hi!") self.assertEqual(VAR_49["results"][0]["context"], {}) def FUNC_36(self): self.helper.send(self.room, body="Hi!", VAR_52=self.other_access_token) self.helper.send(self.room, body="There!", VAR_52=self.other_access_token) VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % (self.access_token,), { "search_categories": { "room_events": { "keys": ["content.body"], "search_term": "Hi", "event_context": {"include_profile": True}, } } }, ) self.assertEqual(VAR_23.code, 200) VAR_49 = VAR_23.json_body["search_categories"]["room_events"] self.assertEqual(VAR_49["count"], 1) self.assertEqual(VAR_49["results"][0]["result"]["content"]["body"], "Hi!") VAR_50 = VAR_49["results"][0]["context"] self.assertEqual(len(VAR_50["profile_info"].keys()), 2) self.assertEqual( VAR_50["profile_info"][self.other_user_id]["displayname"], "otheruser" ) class CLASS_11(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, ] def FUNC_0(self, VAR_3, VAR_4): self.url = b"/_matrix/client/r0/publicRooms" VAR_51 = self.default_config() VAR_51["allow_public_rooms_without_auth"] = False self.hs = self.setup_test_homeserver(VAR_51=config) return self.hs def FUNC_37(self): VAR_22, VAR_23 = self.make_request("GET", self.url) self.assertEqual(VAR_23.code, 401, VAR_23.result) def FUNC_38(self): self.register_user("user", "pass") VAR_52 = self.login("user", "pass") VAR_22, VAR_23 = self.make_request("GET", self.url, VAR_16=VAR_52) self.assertEqual(VAR_23.code, 200, VAR_23.result) class CLASS_12(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, profile.register_servlets, ] def FUNC_0(self, VAR_3, VAR_4): VAR_51 = self.default_config() VAR_51["allow_per_room_profiles"] = False self.hs = self.setup_test_homeserver(VAR_51=config) return self.hs def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.user_id = self.register_user("test", "test") self.tok = self.login("test", "test") self.displayname = "test user" VAR_53 = {"displayname": self.displayname} VAR_54 = json.dumps(VAR_53) VAR_22, VAR_23 = self.make_request( "PUT", "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,), VAR_54, VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self.room_id = self.helper.create_room_as(self.user_id, VAR_52=self.tok) def FUNC_39(self): VAR_53 = {"membership": "join", "displayname": "other test user"} VAR_54 = json.dumps(VAR_53) VAR_22, VAR_23 = self.make_request( "PUT", "/_matrix/client/r0/rooms/%s/VAR_37/m.room.member/%s" % (self.room_id, self.user_id), VAR_54, VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_55 = VAR_23.json_body["event_id"] VAR_22, VAR_23 = self.make_request( "GET", "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, VAR_55), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_56 = VAR_23.json_body["content"]["displayname"] self.assertEqual(VAR_56, self.displayname, VAR_23.result) class CLASS_13(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, ] def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.creator = self.register_user("creator", "test") self.creator_tok = self.login("creator", "test") self.second_user_id = self.register_user("second", "test") self.second_tok = self.login("second", "test") self.room_id = self.helper.create_room_as(self.creator, VAR_52=self.creator_tok) def FUNC_40(self): VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/join".format(self.room_id), VAR_19={"reason": VAR_12}, VAR_16=self.second_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_41(self): self.helper.join(self.room_id, user=self.second_user_id, VAR_52=self.second_tok) VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/leave".format(self.room_id), VAR_19={"reason": VAR_12}, VAR_16=self.second_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_42(self): self.helper.join(self.room_id, user=self.second_user_id, VAR_52=self.second_tok) VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/kick".format(self.room_id), VAR_19={"reason": VAR_12, "user_id": self.second_user_id}, VAR_16=self.second_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_43(self): self.helper.join(self.room_id, user=self.second_user_id, VAR_52=self.second_tok) VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/ban".format(self.room_id), VAR_19={"reason": VAR_12, "user_id": self.second_user_id}, VAR_16=self.creator_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_44(self): VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/unban".format(self.room_id), VAR_19={"reason": VAR_12, "user_id": self.second_user_id}, VAR_16=self.creator_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_45(self): VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/invite".format(self.room_id), VAR_19={"reason": VAR_12, "user_id": self.second_user_id}, VAR_16=self.creator_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_46(self): self.helper.invite( self.room_id, src=self.creator, targ=self.second_user_id, VAR_52=self.creator_tok, ) VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/leave".format(self.room_id), VAR_19={"reason": VAR_12}, VAR_16=self.second_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_47(self, VAR_12): VAR_22, VAR_23 = self.make_request( "GET", "/_matrix/client/r0/rooms/{}/VAR_37/m.room.member/{}".format( self.room_id, self.second_user_id ), VAR_16=self.creator_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_57 = VAR_23.json_body self.assertEqual(VAR_57.get("reason"), VAR_12, VAR_23.result) class CLASS_14(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, profile.register_servlets, ] VAR_13 = { "types": [EventTypes.Message], "org.matrix.labels": ["#fun"], } VAR_14 = { "types": [EventTypes.Message], "org.matrix.not_labels": ["#fun"], } VAR_15 = { "types": [EventTypes.Message], "org.matrix.labels": ["#work"], "org.matrix.not_labels": ["#notfun"], } def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.user_id = self.register_user("test", "test") self.tok = self.login("test", "test") self.room_id = self.helper.create_room_as(self.user_id, VAR_52=self.tok) def FUNC_48(self): VAR_55 = self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_50/%s?filter=%s" % (self.room_id, VAR_55, json.dumps(self.FILTER_LABELS)), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual( len(VAR_58), 1, [event["content"] for event in VAR_58] ) self.assertEqual( VAR_58[0]["content"]["body"], "with right label", VAR_58[0] ) VAR_59 = VAR_23.json_body["events_before"] self.assertEqual( len(VAR_59), 1, [event["content"] for event in VAR_59] ) self.assertEqual( VAR_59[0]["content"]["body"], "with right label", VAR_59[0] ) def FUNC_49(self): VAR_55 = self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_50/%s?filter=%s" % (self.room_id, VAR_55, json.dumps(self.FILTER_NOT_LABELS)), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual( len(VAR_58), 1, [event["content"] for event in VAR_58] ) self.assertEqual( VAR_58[0]["content"]["body"], "without label", VAR_58[0] ) VAR_59 = VAR_23.json_body["events_after"] self.assertEqual( len(VAR_59), 2, [event["content"] for event in VAR_59] ) self.assertEqual( VAR_59[0]["content"]["body"], "with wrong label", VAR_59[0] ) self.assertEqual( VAR_59[1]["content"]["body"], "with two wrong labels", VAR_59[1] ) def FUNC_50(self): VAR_55 = self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_50/%s?filter=%s" % (self.room_id, VAR_55, json.dumps(self.FILTER_LABELS_NOT_LABELS)), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual( len(VAR_58), 0, [event["content"] for event in VAR_58] ) VAR_59 = VAR_23.json_body["events_after"] self.assertEqual( len(VAR_59), 1, [event["content"] for event in VAR_59] ) self.assertEqual( VAR_59[0]["content"]["body"], "with wrong label", VAR_59[0] ) def FUNC_51(self): self._send_labelled_messages_in_room() VAR_39 = "s0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=%s&from=%s&filter=%s" % (self.room_id, self.tok, VAR_39, json.dumps(self.FILTER_LABELS)), ) VAR_60 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_60), 2, [event["content"] for event in VAR_60]) self.assertEqual(VAR_60[0]["content"]["body"], "with right label", VAR_60[0]) self.assertEqual(VAR_60[1]["content"]["body"], "with right label", VAR_60[1]) def FUNC_52(self): self._send_labelled_messages_in_room() VAR_39 = "s0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=%s&from=%s&filter=%s" % (self.room_id, self.tok, VAR_39, json.dumps(self.FILTER_NOT_LABELS)), ) VAR_60 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_60), 4, [event["content"] for event in VAR_60]) self.assertEqual(VAR_60[0]["content"]["body"], "without label", VAR_60[0]) self.assertEqual(VAR_60[1]["content"]["body"], "without label", VAR_60[1]) self.assertEqual(VAR_60[2]["content"]["body"], "with wrong label", VAR_60[2]) self.assertEqual( VAR_60[3]["content"]["body"], "with two wrong labels", VAR_60[3] ) def FUNC_53(self): self._send_labelled_messages_in_room() VAR_39 = "s0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=%s&from=%s&filter=%s" % ( self.room_id, self.tok, VAR_39, json.dumps(self.FILTER_LABELS_NOT_LABELS), ), ) VAR_60 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_60), 1, [event["content"] for event in VAR_60]) self.assertEqual(VAR_60[0]["content"]["body"], "with wrong label", VAR_60[0]) def FUNC_54(self): VAR_54 = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_LABELS, } } } ) self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % self.tok, VAR_54 ) VAR_49 = VAR_23.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(VAR_49), 2, [result["result"]["content"] for result in VAR_49], ) self.assertEqual( VAR_49[0]["result"]["content"]["body"], "with right label", VAR_49[0]["result"]["content"]["body"], ) self.assertEqual( VAR_49[1]["result"]["content"]["body"], "with right label", VAR_49[1]["result"]["content"]["body"], ) def FUNC_55(self): VAR_54 = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_NOT_LABELS, } } } ) self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % self.tok, VAR_54 ) VAR_49 = VAR_23.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(VAR_49), 4, [result["result"]["content"] for result in VAR_49], ) self.assertEqual( VAR_49[0]["result"]["content"]["body"], "without label", VAR_49[0]["result"]["content"]["body"], ) self.assertEqual( VAR_49[1]["result"]["content"]["body"], "without label", VAR_49[1]["result"]["content"]["body"], ) self.assertEqual( VAR_49[2]["result"]["content"]["body"], "with wrong label", VAR_49[2]["result"]["content"]["body"], ) self.assertEqual( VAR_49[3]["result"]["content"]["body"], "with two wrong labels", VAR_49[3]["result"]["content"]["body"], ) def FUNC_56(self): VAR_54 = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_LABELS_NOT_LABELS, } } } ) self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % self.tok, VAR_54 ) VAR_49 = VAR_23.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(VAR_49), 1, [result["result"]["content"] for result in VAR_49], ) self.assertEqual( VAR_49[0]["result"]["content"]["body"], "with wrong label", VAR_49[0]["result"]["content"]["body"], ) def FUNC_57(self): self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={ "msgtype": "m.text", "body": "with right label", EventContentFields.LABELS: ["#fun"], }, VAR_52=self.tok, ) self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={"msgtype": "m.text", "body": "without label"}, VAR_52=self.tok, ) VAR_61 = self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={"msgtype": "m.text", "body": "without label"}, VAR_52=self.tok, ) VAR_55 = VAR_61["event_id"] self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={ "msgtype": "m.text", "body": "with wrong label", EventContentFields.LABELS: ["#work"], }, VAR_52=self.tok, ) self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={ "msgtype": "m.text", "body": "with two wrong labels", EventContentFields.LABELS: ["#work", "#notfun"], }, VAR_52=self.tok, ) self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={ "msgtype": "m.text", "body": "with right label", EventContentFields.LABELS: ["#fun"], }, VAR_52=self.tok, ) return VAR_55 class CLASS_15(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, account.register_servlets, ] def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.user_id = self.register_user("user", "password") self.tok = self.login("user", "password") self.room_id = self.helper.create_room_as( self.user_id, VAR_52=self.tok, is_public=False ) self.other_user_id = self.register_user("user2", "password") self.other_tok = self.login("user2", "password") self.helper.invite(self.room_id, self.user_id, self.other_user_id, VAR_52=self.tok) self.helper.join(self.room_id, self.other_user_id, VAR_52=self.other_tok) def FUNC_58(self): self.helper.send(self.room_id, "message 1", VAR_52=self.tok) self.helper.send(self.room_id, "message 2", VAR_52=self.tok) VAR_55 = self.helper.send(self.room_id, "message 3", VAR_52=self.tok)["event_id"] self.helper.send(self.room_id, "message 4", VAR_52=self.tok) self.helper.send(self.room_id, "message 5", VAR_52=self.tok) VAR_22, VAR_23 = self.make_request( "GET", '/rooms/%s/VAR_50/%s?filter={"types":["m.room.message"]}' % (self.room_id, VAR_55), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual(len(VAR_58), 2, VAR_58) self.assertEqual( VAR_58[0].get("content", {}).get("body"), "message 2", VAR_58[0], ) self.assertEqual( VAR_58[1].get("content", {}).get("body"), "message 1", VAR_58[1], ) self.assertEqual( VAR_23.json_body["event"].get("content", {}).get("body"), "message 3", VAR_23.json_body["event"], ) VAR_59 = VAR_23.json_body["events_after"] self.assertEqual(len(VAR_59), 2, VAR_59) self.assertEqual( VAR_59[0].get("content", {}).get("body"), "message 4", VAR_59[0], ) self.assertEqual( VAR_59[1].get("content", {}).get("body"), "message 5", VAR_59[1], ) VAR_62 = self.hs.get_deactivate_account_handler() self.get_success( VAR_62.deactivate_account(self.user_id, erase_data=True) ) VAR_63 = self.register_user("user3", "password") VAR_64 = self.login("user3", "password") self.helper.invite( self.room_id, self.other_user_id, VAR_63, VAR_52=self.other_tok ) self.helper.join(self.room_id, VAR_63, VAR_52=VAR_64) VAR_22, VAR_23 = self.make_request( "GET", '/rooms/%s/VAR_50/%s?filter={"types":["m.room.message"]}' % (self.room_id, VAR_55), VAR_16=VAR_64, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual(len(VAR_58), 2, VAR_58) self.assertDictEqual(VAR_58[0].get("content"), {}, VAR_58[0]) self.assertDictEqual(VAR_58[1].get("content"), {}, VAR_58[1]) self.assertDictEqual( VAR_23.json_body["event"].get("content"), {}, VAR_23.json_body["event"] ) VAR_59 = VAR_23.json_body["events_after"] self.assertEqual(len(VAR_59), 2, VAR_59) self.assertDictEqual(VAR_59[0].get("content"), {}, VAR_59[0]) self.assertEqual(VAR_59[1].get("content"), {}, VAR_59[1]) class CLASS_16(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, directory.register_servlets, login.register_servlets, VAR_7.register_servlets, ] def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.room_owner = self.register_user("room_owner", "test") self.room_owner_tok = self.login("room_owner", "test") self.room_id = self.helper.create_room_as( self.room_owner, VAR_52=self.room_owner_tok ) def FUNC_59(self): VAR_61 = self._get_aliases(self.room_owner_tok) self.assertEqual(VAR_61["aliases"], []) def FUNC_60(self): self.register_user("user", "test") VAR_65 = self.login("user", "test") VAR_61 = self._get_aliases(VAR_65, VAR_17=403) self.assertEqual(VAR_61["errcode"], "M_FORBIDDEN") def FUNC_61(self): VAR_66 = self._random_alias() self._set_alias_via_directory(VAR_66) self.register_user("user", "test", admin=True) VAR_65 = self.login("user", "test") VAR_61 = self._get_aliases(VAR_65) self.assertEqual(VAR_61["aliases"], [VAR_66]) def FUNC_62(self): VAR_66 = self._random_alias() VAR_67 = self._random_alias() self._set_alias_via_directory(VAR_66) self._set_alias_via_directory(VAR_67) VAR_61 = self._get_aliases(self.room_owner_tok) self.assertEqual(set(VAR_61["aliases"]), {VAR_66, VAR_67}) def FUNC_63(self): VAR_66 = self._random_alias() self._set_alias_via_directory(VAR_66) self.helper.send_state( self.room_id, EventTypes.RoomHistoryVisibility, body={"history_visibility": "world_readable"}, VAR_52=self.room_owner_tok, ) self.register_user("user", "test") VAR_65 = self.login("user", "test") VAR_61 = self._get_aliases(VAR_65) self.assertEqual(VAR_61["aliases"], [VAR_66]) def FUNC_64(self, VAR_16: str, VAR_17: int = 200) -> JsonDict: VAR_22, VAR_23 = self.make_request( "GET", "/_matrix/client/unstable/org.matrix.msc2432/rooms/%s/aliases" % (self.room_id,), VAR_16=access_token, ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) VAR_61 = VAR_23.json_body self.assertIsInstance(VAR_61, dict) if VAR_17 == 200: self.assertIsInstance(VAR_61["aliases"], list) return VAR_61 def FUNC_65(self) -> str: return RoomAlias(random_string(5), self.hs.hostname).to_string() def FUNC_66(self, VAR_18: str, VAR_17: int = 200): VAR_68 = "/_matrix/client/r0/directory/VAR_7/" + VAR_18 VAR_53 = {"room_id": self.room_id} VAR_54 = json.dumps(VAR_53) VAR_22, VAR_23 = self.make_request( "PUT", VAR_68, VAR_54, VAR_16=self.room_owner_tok ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) class CLASS_17(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, directory.register_servlets, login.register_servlets, VAR_7.register_servlets, ] def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.room_owner = self.register_user("room_owner", "test") self.room_owner_tok = self.login("room_owner", "test") self.room_id = self.helper.create_room_as( self.room_owner, VAR_52=self.room_owner_tok ) self.alias = "#VAR_18:test" self._set_alias_via_directory(self.alias) def FUNC_66(self, VAR_18: str, VAR_17: int = 200): VAR_68 = "/_matrix/client/r0/directory/VAR_7/" + VAR_18 VAR_53 = {"room_id": self.room_id} VAR_54 = json.dumps(VAR_53) VAR_22, VAR_23 = self.make_request( "PUT", VAR_68, VAR_54, VAR_16=self.room_owner_tok ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) def FUNC_67(self, VAR_17: int = 200) -> JsonDict: VAR_22, VAR_23 = self.make_request( "GET", "rooms/%s/VAR_37/m.room.canonical_alias" % (self.room_id,), VAR_16=self.room_owner_tok, ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) VAR_61 = VAR_23.json_body self.assertIsInstance(VAR_61, dict) return VAR_61 def FUNC_68(self, VAR_19: str, VAR_17: int = 200) -> JsonDict: VAR_22, VAR_23 = self.make_request( "PUT", "rooms/%s/VAR_37/m.room.canonical_alias" % (self.room_id,), json.dumps(VAR_19), VAR_16=self.room_owner_tok, ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) VAR_61 = VAR_23.json_body self.assertIsInstance(VAR_61, dict) return VAR_61 def FUNC_69(self): self._get_canonical_alias(VAR_17=404) self._set_canonical_alias({"alias": self.alias}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alias": self.alias}) self._set_canonical_alias({}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {}) def FUNC_70(self): self._set_canonical_alias({"alt_aliases": [self.alias]}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alt_aliases": [self.alias]}) self._set_canonical_alias({}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {}) def FUNC_71(self): self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alias": self.alias, "alt_aliases": [self.alias]}) self._set_canonical_alias({}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {}) def FUNC_72(self): self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alias": self.alias, "alt_aliases": [self.alias]}) self._set_canonical_alias({"alias": self.alias}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alias": self.alias}) def FUNC_73(self): VAR_69 = "#second:test" self._set_alias_via_directory(VAR_69) self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) self._set_canonical_alias( {"alias": self.alias, "alt_aliases": [self.alias, VAR_69]} ) VAR_61 = self._get_canonical_alias() self.assertEqual( VAR_61, {"alias": self.alias, "alt_aliases": [self.alias, VAR_69]} ) def FUNC_74(self): self._set_canonical_alias({"alt_aliases": "@bad:test"}, VAR_17=400) self._set_canonical_alias({"alt_aliases": None}, VAR_17=400) self._set_canonical_alias({"alt_aliases": 0}, VAR_17=400) self._set_canonical_alias({"alt_aliases": 1}, VAR_17=400) self._set_canonical_alias({"alt_aliases": False}, VAR_17=400) self._set_canonical_alias({"alt_aliases": True}, VAR_17=400) self._set_canonical_alias({"alt_aliases": {}}, VAR_17=400) def FUNC_75(self): self._set_canonical_alias({"alias": "@unknown:test"}, VAR_17=400) self._set_canonical_alias({"alt_aliases": ["@unknown:test"]}, VAR_17=400)
import json from urllib import parse as urlparse from mock import Mock import synapse.rest.admin from synapse.api.constants import EventContentFields, EventTypes, Membership from synapse.handlers.pagination import PurgeStatus from synapse.rest.client.v1 import directory, login, profile, VAR_7 from synapse.rest.client.v2_alpha import account from synapse.types import JsonDict, RoomAlias, UserID from synapse.util.stringutils import random_string from tests import unittest from tests.test_utils import make_awaitable VAR_0 = b"/_matrix/client/api/v1" class CLASS_0(unittest.HomeserverTestCase): VAR_1 = None VAR_2 = [VAR_7.register_servlets, VAR_7.register_deprecated_servlets] def FUNC_0(self, VAR_3, VAR_4): self.hs = self.setup_test_homeserver( "red", federation_http_client=None, federation_client=Mock(), ) self.hs.get_federation_handler = Mock() self.hs.get_federation_handler.return_value.maybe_backfill = Mock( return_value=make_awaitable(None) ) async def FUNC_76(*VAR_20, **VAR_21): return None self.hs.get_datastore().insert_client_ip = FUNC_76 return self.hs class CLASS_1(CLASS_0): VAR_5 = "@sid1:red" VAR_1 = "@notme:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.helper.auth_user_id = self.rmcreator_id self.uncreated_rmid = "!aa:test" self.created_rmid = self.helper.create_room_as( self.rmcreator_id, is_public=False ) self.created_public_rmid = self.helper.create_room_as( self.rmcreator_id, is_public=True ) self.created_rmid_msg_path = ( "rooms/%s/send/m.room.message/a1" % (self.created_rmid) ).encode("ascii") VAR_22, VAR_23 = self.make_request( "PUT", self.created_rmid_msg_path, b'{"msgtype":"m.text","body":"test msg"}' ) self.assertEquals(200, VAR_23.code, VAR_23.result) VAR_22, VAR_23 = self.make_request( "PUT", ("rooms/%s/VAR_37/m.room.topic" % self.created_public_rmid).encode("ascii"), b'{"topic":"Public Room Topic"}', ) self.assertEquals(200, VAR_23.code, VAR_23.result) self.helper.auth_user_id = self.user_id def FUNC_2(self): VAR_24 = b'{"msgtype":"m.text","body":"hello"}' VAR_25 = iter(range(100)) def FUNC_77(): return "/rooms/%s/send/m.room.message/mid%s" % ( self.created_rmid, str(next(VAR_25)), ) VAR_22, VAR_23 = self.make_request( "PUT", "/rooms/%s/send/m.room.message/mid2" % (self.uncreated_rmid,), VAR_24, ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", FUNC_77(), VAR_24) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.invite( VAR_7=self.created_rmid, src=self.rmcreator_id, targ=self.user_id ) VAR_22, VAR_23 = self.make_request("PUT", FUNC_77(), VAR_24) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.join(VAR_7=self.created_rmid, user=self.user_id) VAR_22, VAR_23 = self.make_request("PUT", FUNC_77(), VAR_24) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.helper.leave(VAR_7=self.created_rmid, user=self.user_id) VAR_22, VAR_23 = self.make_request("PUT", FUNC_77(), VAR_24) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_3(self): VAR_26 = b'{"topic":"My Topic Name"}' VAR_27 = "/rooms/%s/VAR_37/m.room.topic" % self.created_rmid VAR_22, VAR_23 = self.make_request( "PUT", "/rooms/%s/VAR_37/m.room.topic" % self.uncreated_rmid, VAR_26 ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_37/m.room.topic" % self.uncreated_rmid ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_27, VAR_26) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_27) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.invite( VAR_7=self.created_rmid, src=self.rmcreator_id, targ=self.user_id ) VAR_22, VAR_23 = self.make_request("PUT", VAR_27, VAR_26) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_27) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.join(VAR_7=self.created_rmid, user=self.user_id) self.helper.auth_user_id = self.rmcreator_id VAR_22, VAR_23 = self.make_request("PUT", VAR_27, VAR_26) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.helper.auth_user_id = self.user_id VAR_22, VAR_23 = self.make_request("GET", VAR_27) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assert_dict(json.loads(VAR_26.decode("utf8")), VAR_23.json_body) self.helper.leave(VAR_7=self.created_rmid, user=self.user_id) VAR_22, VAR_23 = self.make_request("PUT", VAR_27, VAR_26) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_27) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_37/m.room.topic" % self.created_public_rmid ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "PUT", "/rooms/%s/VAR_37/m.room.topic" % self.created_public_rmid, VAR_26, ) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_4(self, VAR_7=None, VAR_8=[], VAR_9=None): for member in VAR_8: VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % (VAR_7, member) VAR_22, VAR_23 = self.make_request("GET", VAR_32) self.assertEquals(VAR_9, VAR_23.code) def FUNC_5(self): VAR_7 = self.uncreated_rmid self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=403 ) self.helper.invite( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, VAR_9=403 ) for usr in [self.user_id, self.rmcreator_id]: self.helper.join(VAR_7=room, user=usr, VAR_9=404) self.helper.leave(VAR_7=room, user=usr, VAR_9=404) def FUNC_6(self): VAR_7 = self.created_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=403 ) self.helper.join(VAR_7=room, user=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=200 ) self.helper.leave(VAR_7=room, user=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=200 ) def FUNC_7(self): VAR_7 = self.created_public_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=403 ) self.helper.join(VAR_7=room, user=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=200 ) self.helper.leave(VAR_7=room, user=self.user_id) self._test_get_membership( VAR_8=[self.user_id, self.rmcreator_id], VAR_7=room, VAR_9=200 ) def FUNC_8(self): VAR_7 = self.created_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self.helper.invite( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, VAR_9=403 ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.JOIN, VAR_9=403, ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.LEAVE, VAR_9=403, ) def FUNC_9(self): VAR_7 = self.created_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self.helper.join(VAR_7=room, user=self.user_id) self.helper.invite( VAR_7=room, src=self.user_id, targ=self.user_id, VAR_9=403 ) self.helper.join(VAR_7=room, user=self.user_id) VAR_28 = "@burgundy:red" self.helper.invite(VAR_7=room, src=self.user_id, targ=VAR_28, VAR_9=200) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=VAR_28, membership=Membership.JOIN, VAR_9=403, ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=VAR_28, membership=Membership.LEAVE, VAR_9=403, ) self.helper.leave(VAR_7=room, user=self.user_id) def FUNC_10(self): VAR_7 = self.created_rmid self.helper.invite(VAR_7=room, src=self.rmcreator_id, targ=self.user_id) self.helper.join(VAR_7=room, user=self.user_id) self.helper.leave(VAR_7=room, user=self.user_id) for usr in [self.user_id, self.rmcreator_id]: self.helper.change_membership( VAR_7=room, src=self.user_id, targ=usr, membership=Membership.INVITE, VAR_9=403, ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=usr, membership=Membership.JOIN, VAR_9=403, ) self.helper.change_membership( VAR_7=room, src=self.user_id, targ=self.rmcreator_id, membership=Membership.LEAVE, VAR_9=403, ) class CLASS_2(CLASS_0): VAR_5 = "@sid1:red" def FUNC_11(self): VAR_29 = self.helper.create_room_as(self.user_id) VAR_22, VAR_23 = self.make_request("GET", "/rooms/%s/members" % VAR_29) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_12(self): VAR_22, VAR_23 = self.make_request("GET", "/rooms/roomdoesnotexist/members") self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_13(self): VAR_29 = self.helper.create_room_as("@some_other_guy:red") VAR_22, VAR_23 = self.make_request("GET", "/rooms/%s/members" % VAR_29) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_14(self): VAR_30 = "@some_other_guy:red" VAR_29 = self.helper.create_room_as(VAR_30) VAR_31 = "/rooms/%s/members" % VAR_29 self.helper.invite(VAR_7=VAR_29, src=VAR_30, targ=self.user_id) VAR_22, VAR_23 = self.make_request("GET", VAR_31) self.assertEquals(403, VAR_23.code, msg=VAR_23.result["body"]) self.helper.join(VAR_7=VAR_29, user=self.user_id) VAR_22, VAR_23 = self.make_request("GET", VAR_31) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.helper.leave(VAR_7=VAR_29, user=self.user_id) VAR_22, VAR_23 = self.make_request("GET", VAR_31) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) class CLASS_3(CLASS_0): VAR_5 = "@sid1:red" def FUNC_15(self): VAR_22, VAR_23 = self.make_request("POST", "/createRoom", "{}") self.assertEquals(200, VAR_23.code, VAR_23.result) self.assertTrue("room_id" in VAR_23.json_body) def FUNC_16(self): VAR_22, VAR_23 = self.make_request( "POST", "/createRoom", b'{"visibility":"private"}' ) self.assertEquals(200, VAR_23.code) self.assertTrue("room_id" in VAR_23.json_body) def FUNC_17(self): VAR_22, VAR_23 = self.make_request( "POST", "/createRoom", b'{"custom":"stuff"}' ) self.assertEquals(200, VAR_23.code) self.assertTrue("room_id" in VAR_23.json_body) def FUNC_18(self): VAR_22, VAR_23 = self.make_request( "POST", "/createRoom", b'{"visibility":"private","custom":"things"}' ) self.assertEquals(200, VAR_23.code) self.assertTrue("room_id" in VAR_23.json_body) def FUNC_19(self): VAR_22, VAR_23 = self.make_request("POST", "/createRoom", b'{"visibili') self.assertEquals(400, VAR_23.code) VAR_22, VAR_23 = self.make_request("POST", "/createRoom", b'["hello"]') self.assertEquals(400, VAR_23.code) def FUNC_20(self): VAR_22, VAR_23 = self.make_request( "POST", "/createRoom", b'{"invite":["@alice:example.com "]}' ) self.assertEquals(400, VAR_23.code) class CLASS_4(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) self.path = "/rooms/%s/VAR_37/m.room.topic" % (self.room_id,) def FUNC_21(self): VAR_22, VAR_23 = self.make_request("PUT", self.path, "{}") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", self.path, '{"_name":"bo"}') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", self.path, '{"nao') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "PUT", self.path, '[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", self.path, "text only") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", self.path, "") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_19 = '{"topic":["Topic name"]}' VAR_22, VAR_23 = self.make_request("PUT", self.path, VAR_19) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_22(self): VAR_22, VAR_23 = self.make_request("GET", self.path) self.assertEquals(404, VAR_23.code, msg=VAR_23.result["body"]) VAR_19 = '{"topic":"Topic name"}' VAR_22, VAR_23 = self.make_request("PUT", self.path, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", self.path) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assert_dict(json.loads(VAR_19), VAR_23.json_body) def FUNC_23(self): VAR_19 = '{"topic":"Seasons","subtopic":"Summer"}' VAR_22, VAR_23 = self.make_request("PUT", self.path, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", self.path) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assert_dict(json.loads(VAR_19), VAR_23.json_body) class CLASS_5(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) def FUNC_21(self): VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % (self.room_id, self.user_id) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, "{}") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, '{"_name":"bo"}') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, '{"nao') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "PUT", VAR_32, b'[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, "text only") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, "") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_19 = '{"membership":["%s","%s","%s"]}' % ( Membership.INVITE, Membership.JOIN, Membership.LEAVE, ) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19.encode("ascii")) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_24(self): VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % ( urlparse.quote(self.room_id), self.user_id, ) VAR_19 = '{"membership":"%s"}' % Membership.JOIN VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19.encode("ascii")) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_32, None) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_33 = {"membership": Membership.JOIN} self.assertEquals(VAR_33, VAR_23.json_body) def FUNC_25(self): self.other_id = "@zzsid1:red" VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % ( urlparse.quote(self.room_id), self.other_id, ) VAR_19 = '{"membership":"%s"}' % Membership.INVITE VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_32, None) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assertEquals(json.loads(VAR_19), VAR_23.json_body) def FUNC_26(self): self.other_id = "@zzsid1:red" VAR_32 = "/rooms/%s/VAR_37/m.room.member/%s" % ( urlparse.quote(self.room_id), self.other_id, ) VAR_19 = '{"membership":"%s","invite_text":"%s"}' % ( Membership.INVITE, "Join us!", ) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("GET", VAR_32, None) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) self.assertEquals(json.loads(VAR_19), VAR_23.json_body) class CLASS_6(CLASS_0): VAR_5 = "@sid1:red" VAR_2 = [ profile.register_servlets, VAR_7.register_servlets, ] @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def FUNC_27(self): for i in range(3): self.helper.create_room_as(self.user_id) self.helper.create_room_as(self.user_id, VAR_9=429) @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def FUNC_28(self): VAR_34 = [ self.helper.create_room_as(self.user_id), self.helper.create_room_as(self.user_id), self.helper.create_room_as(self.user_id), ] self.reactor.advance(2) VAR_34.append(self.helper.create_room_as(self.user_id)) VAR_35 = self.hs.get_datastore() self.get_success( VAR_35.create_profile(UserID.from_string(self.user_id).localpart) ) VAR_32 = "/_matrix/client/r0/profile/%s/displayname" % self.user_id VAR_22, VAR_23 = self.make_request("PUT", VAR_32, {"displayname": "John Doe"}) self.assertEquals(VAR_23.code, 200, VAR_23.json_body) for VAR_29 in VAR_34: VAR_32 = "/_matrix/client/r0/rooms/%s/VAR_37/m.room.member/%s" % ( VAR_29, self.user_id, ) VAR_22, VAR_23 = self.make_request("GET", VAR_32) self.assertEquals(VAR_23.code, 200) self.assertIn("displayname", VAR_23.json_body) self.assertEquals(VAR_23.json_body["displayname"], "John Doe") @unittest.override_config( {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}} ) def FUNC_29(self): VAR_29 = self.helper.create_room_as(self.user_id) VAR_36 = [ "/_matrix/client/r0/rooms/%s/join", "/_matrix/client/r0/join/%s", ] for VAR_32 in VAR_36: for i in range(4): VAR_22, VAR_23 = self.make_request("POST", VAR_32 % VAR_29, {}) self.assertEquals(VAR_23.code, 200) class CLASS_7(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) def FUNC_21(self): VAR_32 = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id)) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b"{}") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b'{"_name":"bo"}') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b'{"nao') self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request( "PUT", VAR_32, b'[{"_name":"bo"},{"_name":"jill"}]' ) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b"text only") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_22, VAR_23 = self.make_request("PUT", VAR_32, b"") self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) def FUNC_30(self): VAR_32 = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id)) VAR_19 = b'{"body":"test","msgtype":{"type":"a"}}' VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(400, VAR_23.code, msg=VAR_23.result["body"]) VAR_19 = b'{"body":"test","msgtype":"test.custom.text"}' VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) VAR_32 = "/rooms/%s/send/m.room.message/mid2" % (urlparse.quote(self.room_id)) VAR_19 = b'{"body":"test2","msgtype":"m.text"}' VAR_22, VAR_23 = self.make_request("PUT", VAR_32, VAR_19) self.assertEquals(200, VAR_23.code, msg=VAR_23.result["body"]) class CLASS_8(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) def FUNC_31(self): VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/initialSync" % self.room_id ) self.assertEquals(200, VAR_23.code) self.assertEquals(self.room_id, VAR_23.json_body["room_id"]) self.assertEquals("join", VAR_23.json_body["membership"]) VAR_37 = {} for event in VAR_23.json_body["state"]: if "state_key" not in event: continue VAR_70 = event["type"] if VAR_70 not in VAR_37: state[VAR_70] = [] VAR_37[VAR_70].append(event) self.assertTrue("m.room.create" in VAR_37) self.assertTrue("messages" in VAR_23.json_body) self.assertTrue("chunk" in VAR_23.json_body["messages"]) self.assertTrue("end" in VAR_23.json_body["messages"]) self.assertTrue("presence" in VAR_23.json_body) VAR_38 = { e["content"]["user_id"]: e for e in VAR_23.json_body["presence"] } self.assertTrue(self.user_id in VAR_38) self.assertEquals("m.presence", VAR_38[self.user_id]["type"]) class CLASS_9(CLASS_0): VAR_5 = "@sid1:red" def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.room_id = self.helper.create_room_as(self.user_id) def FUNC_32(self): VAR_39 = "t1-0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s" % (self.room_id, VAR_39) ) self.assertEquals(200, VAR_23.code) self.assertTrue("start" in VAR_23.json_body) self.assertEquals(VAR_39, VAR_23.json_body["start"]) self.assertTrue("chunk" in VAR_23.json_body) self.assertTrue("end" in VAR_23.json_body) def FUNC_33(self): VAR_39 = "s0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s" % (self.room_id, VAR_39) ) self.assertEquals(200, VAR_23.code) self.assertTrue("start" in VAR_23.json_body) self.assertEquals(VAR_39, VAR_23.json_body["start"]) self.assertTrue("chunk" in VAR_23.json_body) self.assertTrue("end" in VAR_23.json_body) def FUNC_34(self): VAR_35 = self.hs.get_datastore() VAR_40 = self.hs.get_pagination_handler() VAR_41 = self.helper.send(self.room_id, "message 1")["event_id"] VAR_42 = self.get_success( VAR_35.get_topological_token_for_event(VAR_41) ) VAR_43 = self.get_success(VAR_42.to_string(VAR_35)) VAR_44 = self.helper.send(self.room_id, "message 2")["event_id"] VAR_45 = self.get_success( VAR_35.get_topological_token_for_event(VAR_44) ) VAR_46 = self.get_success(VAR_45.to_string(VAR_35)) self.helper.send(self.room_id, "message 3") VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s&dir=b&filter=%s" % ( self.room_id, VAR_46, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(VAR_23.code, 200, VAR_23.json_body) VAR_47 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_47), 2, [event["content"] for event in VAR_47]) VAR_48 = random_string(16) VAR_40._purges_by_id[VAR_48] = PurgeStatus() self.get_success( VAR_40._purge_history( VAR_48=purge_id, VAR_29=self.room_id, VAR_39=VAR_46, delete_local_events=True, ) ) VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s&dir=b&filter=%s" % ( self.room_id, VAR_46, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(VAR_23.code, 200, VAR_23.json_body) VAR_47 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_47), 1, [event["content"] for event in VAR_47]) VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=x&from=%s&dir=b&filter=%s" % ( self.room_id, VAR_43, json.dumps({"types": [EventTypes.Message]}), ), ) self.assertEqual(VAR_23.code, 200, VAR_23.json_body) VAR_47 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_47), 0, [event["content"] for event in VAR_47]) class CLASS_10(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, ] VAR_5 = True VAR_10 = False def FUNC_1(self, VAR_3, VAR_4, VAR_6): self.user_id = self.register_user("user", "pass") self.access_token = self.login("user", "pass") self.other_user_id = self.register_user("otheruser", "pass") self.other_access_token = self.login("otheruser", "pass") self.room = self.helper.create_room_as(self.user_id, VAR_52=self.access_token) self.helper.invite( VAR_7=self.room, src=self.user_id, VAR_52=self.access_token, targ=self.other_user_id, ) self.helper.join( VAR_7=self.room, user=self.other_user_id, VAR_52=self.other_access_token ) def FUNC_35(self): self.helper.send(self.room, body="Hi!", VAR_52=self.other_access_token) self.helper.send(self.room, body="There!", VAR_52=self.other_access_token) VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % (self.access_token,), { "search_categories": { "room_events": {"keys": ["content.body"], "search_term": "Hi"} } }, ) self.assertEqual(VAR_23.code, 200) VAR_49 = VAR_23.json_body["search_categories"]["room_events"] self.assertEqual(VAR_49["count"], 1) self.assertEqual(VAR_49["results"][0]["result"]["content"]["body"], "Hi!") self.assertEqual(VAR_49["results"][0]["context"], {}) def FUNC_36(self): self.helper.send(self.room, body="Hi!", VAR_52=self.other_access_token) self.helper.send(self.room, body="There!", VAR_52=self.other_access_token) VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % (self.access_token,), { "search_categories": { "room_events": { "keys": ["content.body"], "search_term": "Hi", "event_context": {"include_profile": True}, } } }, ) self.assertEqual(VAR_23.code, 200) VAR_49 = VAR_23.json_body["search_categories"]["room_events"] self.assertEqual(VAR_49["count"], 1) self.assertEqual(VAR_49["results"][0]["result"]["content"]["body"], "Hi!") VAR_50 = VAR_49["results"][0]["context"] self.assertEqual(len(VAR_50["profile_info"].keys()), 2) self.assertEqual( VAR_50["profile_info"][self.other_user_id]["displayname"], "otheruser" ) class CLASS_11(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, ] def FUNC_0(self, VAR_3, VAR_4): self.url = b"/_matrix/client/r0/publicRooms" VAR_51 = self.default_config() VAR_51["allow_public_rooms_without_auth"] = False self.hs = self.setup_test_homeserver(VAR_51=config) return self.hs def FUNC_37(self): VAR_22, VAR_23 = self.make_request("GET", self.url) self.assertEqual(VAR_23.code, 401, VAR_23.result) def FUNC_38(self): self.register_user("user", "pass") VAR_52 = self.login("user", "pass") VAR_22, VAR_23 = self.make_request("GET", self.url, VAR_16=VAR_52) self.assertEqual(VAR_23.code, 200, VAR_23.result) class CLASS_12(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, profile.register_servlets, ] def FUNC_0(self, VAR_3, VAR_4): VAR_51 = self.default_config() VAR_51["allow_per_room_profiles"] = False self.hs = self.setup_test_homeserver(VAR_51=config) return self.hs def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.user_id = self.register_user("test", "test") self.tok = self.login("test", "test") self.displayname = "test user" VAR_53 = {"displayname": self.displayname} VAR_54 = json.dumps(VAR_53) VAR_22, VAR_23 = self.make_request( "PUT", "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,), VAR_54, VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self.room_id = self.helper.create_room_as(self.user_id, VAR_52=self.tok) def FUNC_39(self): VAR_53 = {"membership": "join", "displayname": "other test user"} VAR_54 = json.dumps(VAR_53) VAR_22, VAR_23 = self.make_request( "PUT", "/_matrix/client/r0/rooms/%s/VAR_37/m.room.member/%s" % (self.room_id, self.user_id), VAR_54, VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_55 = VAR_23.json_body["event_id"] VAR_22, VAR_23 = self.make_request( "GET", "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, VAR_55), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_56 = VAR_23.json_body["content"]["displayname"] self.assertEqual(VAR_56, self.displayname, VAR_23.result) class CLASS_13(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, ] def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.creator = self.register_user("creator", "test") self.creator_tok = self.login("creator", "test") self.second_user_id = self.register_user("second", "test") self.second_tok = self.login("second", "test") self.room_id = self.helper.create_room_as(self.creator, VAR_52=self.creator_tok) def FUNC_40(self): VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/join".format(self.room_id), VAR_19={"reason": VAR_12}, VAR_16=self.second_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_41(self): self.helper.join(self.room_id, user=self.second_user_id, VAR_52=self.second_tok) VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/leave".format(self.room_id), VAR_19={"reason": VAR_12}, VAR_16=self.second_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_42(self): self.helper.join(self.room_id, user=self.second_user_id, VAR_52=self.second_tok) VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/kick".format(self.room_id), VAR_19={"reason": VAR_12, "user_id": self.second_user_id}, VAR_16=self.second_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_43(self): self.helper.join(self.room_id, user=self.second_user_id, VAR_52=self.second_tok) VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/ban".format(self.room_id), VAR_19={"reason": VAR_12, "user_id": self.second_user_id}, VAR_16=self.creator_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_44(self): VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/unban".format(self.room_id), VAR_19={"reason": VAR_12, "user_id": self.second_user_id}, VAR_16=self.creator_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_45(self): VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/invite".format(self.room_id), VAR_19={"reason": VAR_12, "user_id": self.second_user_id}, VAR_16=self.creator_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_46(self): self.helper.invite( self.room_id, src=self.creator, targ=self.second_user_id, VAR_52=self.creator_tok, ) VAR_12 = "hello" VAR_22, VAR_23 = self.make_request( "POST", "/_matrix/client/r0/rooms/{}/leave".format(self.room_id), VAR_19={"reason": VAR_12}, VAR_16=self.second_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) self._check_for_reason(VAR_12) def FUNC_47(self, VAR_12): VAR_22, VAR_23 = self.make_request( "GET", "/_matrix/client/r0/rooms/{}/VAR_37/m.room.member/{}".format( self.room_id, self.second_user_id ), VAR_16=self.creator_tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_57 = VAR_23.json_body self.assertEqual(VAR_57.get("reason"), VAR_12, VAR_23.result) class CLASS_14(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, profile.register_servlets, ] VAR_13 = { "types": [EventTypes.Message], "org.matrix.labels": ["#fun"], } VAR_14 = { "types": [EventTypes.Message], "org.matrix.not_labels": ["#fun"], } VAR_15 = { "types": [EventTypes.Message], "org.matrix.labels": ["#work"], "org.matrix.not_labels": ["#notfun"], } def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.user_id = self.register_user("test", "test") self.tok = self.login("test", "test") self.room_id = self.helper.create_room_as(self.user_id, VAR_52=self.tok) def FUNC_48(self): VAR_55 = self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_50/%s?filter=%s" % (self.room_id, VAR_55, json.dumps(self.FILTER_LABELS)), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual( len(VAR_58), 1, [event["content"] for event in VAR_58] ) self.assertEqual( VAR_58[0]["content"]["body"], "with right label", VAR_58[0] ) VAR_59 = VAR_23.json_body["events_before"] self.assertEqual( len(VAR_59), 1, [event["content"] for event in VAR_59] ) self.assertEqual( VAR_59[0]["content"]["body"], "with right label", VAR_59[0] ) def FUNC_49(self): VAR_55 = self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_50/%s?filter=%s" % (self.room_id, VAR_55, json.dumps(self.FILTER_NOT_LABELS)), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual( len(VAR_58), 1, [event["content"] for event in VAR_58] ) self.assertEqual( VAR_58[0]["content"]["body"], "without label", VAR_58[0] ) VAR_59 = VAR_23.json_body["events_after"] self.assertEqual( len(VAR_59), 2, [event["content"] for event in VAR_59] ) self.assertEqual( VAR_59[0]["content"]["body"], "with wrong label", VAR_59[0] ) self.assertEqual( VAR_59[1]["content"]["body"], "with two wrong labels", VAR_59[1] ) def FUNC_50(self): VAR_55 = self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/VAR_50/%s?filter=%s" % (self.room_id, VAR_55, json.dumps(self.FILTER_LABELS_NOT_LABELS)), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual( len(VAR_58), 0, [event["content"] for event in VAR_58] ) VAR_59 = VAR_23.json_body["events_after"] self.assertEqual( len(VAR_59), 1, [event["content"] for event in VAR_59] ) self.assertEqual( VAR_59[0]["content"]["body"], "with wrong label", VAR_59[0] ) def FUNC_51(self): self._send_labelled_messages_in_room() VAR_39 = "s0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=%s&from=%s&filter=%s" % (self.room_id, self.tok, VAR_39, json.dumps(self.FILTER_LABELS)), ) VAR_60 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_60), 2, [event["content"] for event in VAR_60]) self.assertEqual(VAR_60[0]["content"]["body"], "with right label", VAR_60[0]) self.assertEqual(VAR_60[1]["content"]["body"], "with right label", VAR_60[1]) def FUNC_52(self): self._send_labelled_messages_in_room() VAR_39 = "s0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=%s&from=%s&filter=%s" % (self.room_id, self.tok, VAR_39, json.dumps(self.FILTER_NOT_LABELS)), ) VAR_60 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_60), 4, [event["content"] for event in VAR_60]) self.assertEqual(VAR_60[0]["content"]["body"], "without label", VAR_60[0]) self.assertEqual(VAR_60[1]["content"]["body"], "without label", VAR_60[1]) self.assertEqual(VAR_60[2]["content"]["body"], "with wrong label", VAR_60[2]) self.assertEqual( VAR_60[3]["content"]["body"], "with two wrong labels", VAR_60[3] ) def FUNC_53(self): self._send_labelled_messages_in_room() VAR_39 = "s0_0_0_0_0_0_0_0_0" VAR_22, VAR_23 = self.make_request( "GET", "/rooms/%s/messages?VAR_16=%s&from=%s&filter=%s" % ( self.room_id, self.tok, VAR_39, json.dumps(self.FILTER_LABELS_NOT_LABELS), ), ) VAR_60 = VAR_23.json_body["chunk"] self.assertEqual(len(VAR_60), 1, [event["content"] for event in VAR_60]) self.assertEqual(VAR_60[0]["content"]["body"], "with wrong label", VAR_60[0]) def FUNC_54(self): VAR_54 = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_LABELS, } } } ) self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % self.tok, VAR_54 ) VAR_49 = VAR_23.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(VAR_49), 2, [result["result"]["content"] for result in VAR_49], ) self.assertEqual( VAR_49[0]["result"]["content"]["body"], "with right label", VAR_49[0]["result"]["content"]["body"], ) self.assertEqual( VAR_49[1]["result"]["content"]["body"], "with right label", VAR_49[1]["result"]["content"]["body"], ) def FUNC_55(self): VAR_54 = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_NOT_LABELS, } } } ) self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % self.tok, VAR_54 ) VAR_49 = VAR_23.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(VAR_49), 4, [result["result"]["content"] for result in VAR_49], ) self.assertEqual( VAR_49[0]["result"]["content"]["body"], "without label", VAR_49[0]["result"]["content"]["body"], ) self.assertEqual( VAR_49[1]["result"]["content"]["body"], "without label", VAR_49[1]["result"]["content"]["body"], ) self.assertEqual( VAR_49[2]["result"]["content"]["body"], "with wrong label", VAR_49[2]["result"]["content"]["body"], ) self.assertEqual( VAR_49[3]["result"]["content"]["body"], "with two wrong labels", VAR_49[3]["result"]["content"]["body"], ) def FUNC_56(self): VAR_54 = json.dumps( { "search_categories": { "room_events": { "search_term": "label", "filter": self.FILTER_LABELS_NOT_LABELS, } } } ) self._send_labelled_messages_in_room() VAR_22, VAR_23 = self.make_request( "POST", "/search?VAR_16=%s" % self.tok, VAR_54 ) VAR_49 = VAR_23.json_body["search_categories"]["room_events"]["results"] self.assertEqual( len(VAR_49), 1, [result["result"]["content"] for result in VAR_49], ) self.assertEqual( VAR_49[0]["result"]["content"]["body"], "with wrong label", VAR_49[0]["result"]["content"]["body"], ) def FUNC_57(self): self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={ "msgtype": "m.text", "body": "with right label", EventContentFields.LABELS: ["#fun"], }, VAR_52=self.tok, ) self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={"msgtype": "m.text", "body": "without label"}, VAR_52=self.tok, ) VAR_61 = self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={"msgtype": "m.text", "body": "without label"}, VAR_52=self.tok, ) VAR_55 = VAR_61["event_id"] self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={ "msgtype": "m.text", "body": "with wrong label", EventContentFields.LABELS: ["#work"], }, VAR_52=self.tok, ) self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={ "msgtype": "m.text", "body": "with two wrong labels", EventContentFields.LABELS: ["#work", "#notfun"], }, VAR_52=self.tok, ) self.helper.send_event( VAR_29=self.room_id, type=EventTypes.Message, VAR_19={ "msgtype": "m.text", "body": "with right label", EventContentFields.LABELS: ["#fun"], }, VAR_52=self.tok, ) return VAR_55 class CLASS_15(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_7.register_servlets, login.register_servlets, account.register_servlets, ] def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.user_id = self.register_user("user", "password") self.tok = self.login("user", "password") self.room_id = self.helper.create_room_as( self.user_id, VAR_52=self.tok, is_public=False ) self.other_user_id = self.register_user("user2", "password") self.other_tok = self.login("user2", "password") self.helper.invite(self.room_id, self.user_id, self.other_user_id, VAR_52=self.tok) self.helper.join(self.room_id, self.other_user_id, VAR_52=self.other_tok) def FUNC_58(self): self.helper.send(self.room_id, "message 1", VAR_52=self.tok) self.helper.send(self.room_id, "message 2", VAR_52=self.tok) VAR_55 = self.helper.send(self.room_id, "message 3", VAR_52=self.tok)["event_id"] self.helper.send(self.room_id, "message 4", VAR_52=self.tok) self.helper.send(self.room_id, "message 5", VAR_52=self.tok) VAR_22, VAR_23 = self.make_request( "GET", '/rooms/%s/VAR_50/%s?filter={"types":["m.room.message"]}' % (self.room_id, VAR_55), VAR_16=self.tok, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual(len(VAR_58), 2, VAR_58) self.assertEqual( VAR_58[0].get("content", {}).get("body"), "message 2", VAR_58[0], ) self.assertEqual( VAR_58[1].get("content", {}).get("body"), "message 1", VAR_58[1], ) self.assertEqual( VAR_23.json_body["event"].get("content", {}).get("body"), "message 3", VAR_23.json_body["event"], ) VAR_59 = VAR_23.json_body["events_after"] self.assertEqual(len(VAR_59), 2, VAR_59) self.assertEqual( VAR_59[0].get("content", {}).get("body"), "message 4", VAR_59[0], ) self.assertEqual( VAR_59[1].get("content", {}).get("body"), "message 5", VAR_59[1], ) VAR_62 = self.hs.get_deactivate_account_handler() self.get_success( VAR_62.deactivate_account(self.user_id, erase_data=True) ) VAR_63 = self.register_user("user3", "password") VAR_64 = self.login("user3", "password") self.helper.invite( self.room_id, self.other_user_id, VAR_63, VAR_52=self.other_tok ) self.helper.join(self.room_id, VAR_63, VAR_52=VAR_64) VAR_22, VAR_23 = self.make_request( "GET", '/rooms/%s/VAR_50/%s?filter={"types":["m.room.message"]}' % (self.room_id, VAR_55), VAR_16=VAR_64, ) self.assertEqual(VAR_23.code, 200, VAR_23.result) VAR_58 = VAR_23.json_body["events_before"] self.assertEqual(len(VAR_58), 2, VAR_58) self.assertDictEqual(VAR_58[0].get("content"), {}, VAR_58[0]) self.assertDictEqual(VAR_58[1].get("content"), {}, VAR_58[1]) self.assertDictEqual( VAR_23.json_body["event"].get("content"), {}, VAR_23.json_body["event"] ) VAR_59 = VAR_23.json_body["events_after"] self.assertEqual(len(VAR_59), 2, VAR_59) self.assertDictEqual(VAR_59[0].get("content"), {}, VAR_59[0]) self.assertEqual(VAR_59[1].get("content"), {}, VAR_59[1]) class CLASS_16(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, directory.register_servlets, login.register_servlets, VAR_7.register_servlets, ] def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.room_owner = self.register_user("room_owner", "test") self.room_owner_tok = self.login("room_owner", "test") self.room_id = self.helper.create_room_as( self.room_owner, VAR_52=self.room_owner_tok ) def FUNC_59(self): VAR_61 = self._get_aliases(self.room_owner_tok) self.assertEqual(VAR_61["aliases"], []) def FUNC_60(self): self.register_user("user", "test") VAR_65 = self.login("user", "test") VAR_61 = self._get_aliases(VAR_65, VAR_17=403) self.assertEqual(VAR_61["errcode"], "M_FORBIDDEN") def FUNC_61(self): VAR_66 = self._random_alias() self._set_alias_via_directory(VAR_66) self.register_user("user", "test", admin=True) VAR_65 = self.login("user", "test") VAR_61 = self._get_aliases(VAR_65) self.assertEqual(VAR_61["aliases"], [VAR_66]) def FUNC_62(self): VAR_66 = self._random_alias() VAR_67 = self._random_alias() self._set_alias_via_directory(VAR_66) self._set_alias_via_directory(VAR_67) VAR_61 = self._get_aliases(self.room_owner_tok) self.assertEqual(set(VAR_61["aliases"]), {VAR_66, VAR_67}) def FUNC_63(self): VAR_66 = self._random_alias() self._set_alias_via_directory(VAR_66) self.helper.send_state( self.room_id, EventTypes.RoomHistoryVisibility, body={"history_visibility": "world_readable"}, VAR_52=self.room_owner_tok, ) self.register_user("user", "test") VAR_65 = self.login("user", "test") VAR_61 = self._get_aliases(VAR_65) self.assertEqual(VAR_61["aliases"], [VAR_66]) def FUNC_64(self, VAR_16: str, VAR_17: int = 200) -> JsonDict: VAR_22, VAR_23 = self.make_request( "GET", "/_matrix/client/unstable/org.matrix.msc2432/rooms/%s/aliases" % (self.room_id,), VAR_16=access_token, ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) VAR_61 = VAR_23.json_body self.assertIsInstance(VAR_61, dict) if VAR_17 == 200: self.assertIsInstance(VAR_61["aliases"], list) return VAR_61 def FUNC_65(self) -> str: return RoomAlias(random_string(5), self.hs.hostname).to_string() def FUNC_66(self, VAR_18: str, VAR_17: int = 200): VAR_68 = "/_matrix/client/r0/directory/VAR_7/" + VAR_18 VAR_53 = {"room_id": self.room_id} VAR_54 = json.dumps(VAR_53) VAR_22, VAR_23 = self.make_request( "PUT", VAR_68, VAR_54, VAR_16=self.room_owner_tok ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) class CLASS_17(unittest.HomeserverTestCase): VAR_2 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, directory.register_servlets, login.register_servlets, VAR_7.register_servlets, ] def FUNC_1(self, VAR_3, VAR_4, VAR_11): self.room_owner = self.register_user("room_owner", "test") self.room_owner_tok = self.login("room_owner", "test") self.room_id = self.helper.create_room_as( self.room_owner, VAR_52=self.room_owner_tok ) self.alias = "#VAR_18:test" self._set_alias_via_directory(self.alias) def FUNC_66(self, VAR_18: str, VAR_17: int = 200): VAR_68 = "/_matrix/client/r0/directory/VAR_7/" + VAR_18 VAR_53 = {"room_id": self.room_id} VAR_54 = json.dumps(VAR_53) VAR_22, VAR_23 = self.make_request( "PUT", VAR_68, VAR_54, VAR_16=self.room_owner_tok ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) def FUNC_67(self, VAR_17: int = 200) -> JsonDict: VAR_22, VAR_23 = self.make_request( "GET", "rooms/%s/VAR_37/m.room.canonical_alias" % (self.room_id,), VAR_16=self.room_owner_tok, ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) VAR_61 = VAR_23.json_body self.assertIsInstance(VAR_61, dict) return VAR_61 def FUNC_68(self, VAR_19: str, VAR_17: int = 200) -> JsonDict: VAR_22, VAR_23 = self.make_request( "PUT", "rooms/%s/VAR_37/m.room.canonical_alias" % (self.room_id,), json.dumps(VAR_19), VAR_16=self.room_owner_tok, ) self.assertEqual(VAR_23.code, VAR_17, VAR_23.result) VAR_61 = VAR_23.json_body self.assertIsInstance(VAR_61, dict) return VAR_61 def FUNC_69(self): self._get_canonical_alias(VAR_17=404) self._set_canonical_alias({"alias": self.alias}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alias": self.alias}) self._set_canonical_alias({}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {}) def FUNC_70(self): self._set_canonical_alias({"alt_aliases": [self.alias]}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alt_aliases": [self.alias]}) self._set_canonical_alias({}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {}) def FUNC_71(self): self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alias": self.alias, "alt_aliases": [self.alias]}) self._set_canonical_alias({}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {}) def FUNC_72(self): self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alias": self.alias, "alt_aliases": [self.alias]}) self._set_canonical_alias({"alias": self.alias}) VAR_61 = self._get_canonical_alias() self.assertEqual(VAR_61, {"alias": self.alias}) def FUNC_73(self): VAR_69 = "#second:test" self._set_alias_via_directory(VAR_69) self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]}) self._set_canonical_alias( {"alias": self.alias, "alt_aliases": [self.alias, VAR_69]} ) VAR_61 = self._get_canonical_alias() self.assertEqual( VAR_61, {"alias": self.alias, "alt_aliases": [self.alias, VAR_69]} ) def FUNC_74(self): self._set_canonical_alias({"alt_aliases": "@bad:test"}, VAR_17=400) self._set_canonical_alias({"alt_aliases": None}, VAR_17=400) self._set_canonical_alias({"alt_aliases": 0}, VAR_17=400) self._set_canonical_alias({"alt_aliases": 1}, VAR_17=400) self._set_canonical_alias({"alt_aliases": False}, VAR_17=400) self._set_canonical_alias({"alt_aliases": True}, VAR_17=400) self._set_canonical_alias({"alt_aliases": {}}, VAR_17=400) def FUNC_75(self): self._set_canonical_alias({"alias": "@unknown:test"}, VAR_17=400) self._set_canonical_alias({"alt_aliases": ["@unknown:test"]}, VAR_17=400)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 23, 25, 33, 36, 38, 39, 42, 44, 46, 50, 55, 58, 60, 62, 63, 66, 69, 71, 73, 81, 82, 90, 91, 98, 99, 101, 104, 106, 112, 113, 120, 121, 124, 125, 131, 132, 136, 137, 141, 145, 146, 155, 156, 161, 162, 168, 169, 172, 173, 175, 176, 181, 185, 186, 192, 193, 198, 199, 206, 212, 214, 216, 217, 221, 222, 226, 227, 228, 232, 235, 236, 241, 242, 243, 248, 249, 250, 255, 258, 259, 264, 265, 266, 271, 272, 273, 278, 282, 283, 301, 306, 307, 311, 312, 314, 316, 318, 319, 327, 328, 336, 337, 339, 345, 346, 347, 356, 364, 365, 373, 374, 377, 379, 384, 388, 393, 399, 402, 404, 407, 409, 412, 413, 416, 418, 420, 422, 425, 427, 433, 435, 441, 443, 449, 451, 454, 457, 459, 460, 465, 466, 469, 471, 473, 476, 478, 481, 484, 487, 492, 495, 498, 499, 503, 505, 508, 509, 513, 514, 518, 520, 524, 525, 529, 530, 533, 535, 538, 541, 544, 547, 550, 555, 558, 561, 562, 570, 576, 577, 581, 584, 587, 594, 595, 599, 603, 610, 611, 618, 622, 623, 626, 631, 639, 641, 648, 649, 655, 657, 658, 660, 661, 666, 667, 671, 672, 678, 681, 684, 692, 693, 698, 700, 701, 705, 706, 709, 711, 714, 717, 720, 723, 726, 731, 734, 737, 740, 744, 745, 749, 750, 755, 756, 759, 761, 763, 765, 771, 774, 775, 784, 786, 790, 792, 798, 799, 802, 804, 807, 818, 829, 833, 834, 840, 841, 842, 848, 849, 850, 852, 853, 864, 867, 868, 879, 880, 881, 892, 895, 896, 897, 898, 909, 912, 913, 922, 924, 925, 928, 929, 932, 933, 935, 936, 943, 944, 948, 954, 957, 967, 968, 969, 974, 975, 977, 983, 986, 1000, 1001, 1002, 1007, 1008, 1014, 1015, 1017, 1023, 1025, 1027, 1031, 1033, 1037, 1041, 1044, 1045, 1047, 1054, 1059, 1061, 1065, 1066, 1077, 1079, 1092, 1099, 1102, 1103, 1108, 1114, 1118, 1121, 1123, 1133, 1135, 1138, 1147, 1149, 1152, 1161, 1163, 1166, 1175, 1177, 1187, 1189, 1199, 1201, 1209, 1218, 1220, 1230, 1232, 1234, 1235, 1243, 1244, 1249, 1254, 1255, 1261, 1266, 1270, 1278, 1280, 1287, 1289, 1296, 1300, 1308, 1310, 1317, 1319, 1329, 1335, 1343, 1345, 1349, 1351, 1358, 1362, 1369, 1371, 1375, 1379, 1386, 1388, 1396, 1402, 1414, 1416, 1419, 1432, 1434, 1438, 1440, 1454, 1467, 1469, 1473, 1475, 1499, 1514, 1516, 1520, 1522, 1531, 1548, 1555, 1562, 1564, 1575, 1586, 1597, 1599, 1600, 1602, 1609, 1616, 1619, 1622, 1627, 1628, 1629, 1635, 1636, 1637, 1645, 1647, 1659, 1665, 1667, 1679, 1680, 1681, 1686, 1687, 1688, 1689, 1690, 1693, 1698, 1699, 1700, 1701, 1709, 1711, 1715, 1719, 1721, 1725, 1726, 1734, 1738, 1742, 1746, 1752, 1756, 1759, 1762, 1766, 1769, 1772, 1776, 1783, 1786, 1789, 1804, 1807, 1812, 1817, 1818, 1826, 1830, 1834, 1837, 1842, 1847, 1859, 1872, 1875, 1877, 1878, 1880, 1881, 1884, 1885, 1887, 1888, 1891, 1894, 1896, 1897, 1900, 1901, 1903, 1904, 1907, 1910, 1912, 1913, 1916, 1917, 1919, 1920, 1923, 1926, 1928, 1929, 1932, 1933, 1935, 1936, 1939, 1942, 1945, 1946, 1948, 1949, 1953, 1954, 1959, 1969, 1974, 19, 65, 376, 415, 468, 532, 708, 758, 801, 1105, 1106, 1107, 636, 646, 647, 689, 690, 950, 951, 952, 953, 979, 980, 981, 982, 1268, 1298, 1331, 1332, 1333, 1360, 1377, 1398, 1399, 1400, 1421, 1456, 1501, 1502, 1503, 1533, 1534, 1535, 1536, 1537, 1624, 1625, 1626, 1791, 1849, 1861, 1874, 1893, 1909, 1925, 1941, 1961, 1971 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 23, 25, 33, 36, 38, 39, 42, 44, 46, 50, 55, 58, 60, 62, 63, 66, 69, 71, 73, 81, 82, 90, 91, 98, 99, 101, 104, 106, 112, 113, 120, 121, 124, 125, 131, 132, 136, 137, 141, 145, 146, 155, 156, 161, 162, 168, 169, 172, 173, 175, 176, 181, 185, 186, 192, 193, 198, 199, 206, 212, 214, 216, 217, 221, 222, 226, 227, 228, 232, 235, 236, 241, 242, 243, 248, 249, 250, 255, 258, 259, 264, 265, 266, 271, 272, 273, 278, 282, 283, 301, 306, 307, 311, 312, 314, 316, 318, 319, 327, 328, 336, 337, 339, 345, 346, 347, 356, 364, 365, 373, 374, 377, 379, 384, 388, 393, 399, 402, 404, 407, 409, 412, 413, 416, 418, 420, 422, 425, 427, 433, 435, 441, 443, 449, 451, 454, 457, 459, 460, 465, 466, 469, 471, 473, 476, 478, 481, 484, 487, 492, 495, 498, 499, 503, 505, 508, 509, 513, 514, 518, 520, 524, 525, 529, 530, 533, 535, 538, 541, 544, 547, 550, 555, 558, 561, 562, 570, 576, 577, 581, 584, 587, 594, 595, 599, 603, 610, 611, 618, 622, 623, 626, 631, 639, 641, 648, 649, 655, 657, 658, 660, 661, 666, 667, 671, 672, 678, 681, 684, 692, 693, 698, 700, 701, 705, 706, 709, 711, 714, 717, 720, 723, 726, 731, 734, 737, 740, 744, 745, 749, 750, 755, 756, 759, 761, 763, 765, 771, 774, 775, 784, 786, 790, 792, 798, 799, 802, 804, 807, 818, 829, 833, 834, 840, 841, 842, 848, 849, 850, 852, 853, 864, 867, 868, 879, 880, 881, 892, 895, 896, 897, 898, 909, 912, 913, 922, 924, 925, 928, 929, 932, 933, 935, 936, 943, 944, 948, 954, 957, 967, 968, 969, 974, 975, 977, 983, 986, 1000, 1001, 1002, 1007, 1008, 1014, 1015, 1017, 1023, 1025, 1027, 1031, 1033, 1037, 1041, 1044, 1045, 1047, 1054, 1059, 1061, 1065, 1066, 1077, 1079, 1092, 1099, 1102, 1103, 1108, 1114, 1118, 1121, 1123, 1133, 1135, 1138, 1147, 1149, 1152, 1161, 1163, 1166, 1175, 1177, 1187, 1189, 1199, 1201, 1209, 1218, 1220, 1230, 1232, 1234, 1235, 1243, 1244, 1249, 1254, 1255, 1261, 1266, 1270, 1278, 1280, 1287, 1289, 1296, 1300, 1308, 1310, 1317, 1319, 1329, 1335, 1343, 1345, 1349, 1351, 1358, 1362, 1369, 1371, 1375, 1379, 1386, 1388, 1396, 1402, 1414, 1416, 1419, 1432, 1434, 1438, 1440, 1454, 1467, 1469, 1473, 1475, 1499, 1514, 1516, 1520, 1522, 1531, 1548, 1555, 1562, 1564, 1575, 1586, 1597, 1599, 1600, 1602, 1609, 1616, 1619, 1622, 1627, 1628, 1629, 1635, 1636, 1637, 1645, 1647, 1659, 1665, 1667, 1679, 1680, 1681, 1686, 1687, 1688, 1689, 1690, 1693, 1698, 1699, 1700, 1701, 1709, 1711, 1715, 1719, 1721, 1725, 1726, 1734, 1738, 1742, 1746, 1752, 1756, 1759, 1762, 1766, 1769, 1772, 1776, 1783, 1786, 1789, 1804, 1807, 1812, 1817, 1818, 1826, 1830, 1834, 1837, 1842, 1847, 1859, 1872, 1875, 1877, 1878, 1880, 1881, 1884, 1885, 1887, 1888, 1891, 1894, 1896, 1897, 1900, 1901, 1903, 1904, 1907, 1910, 1912, 1913, 1916, 1917, 1919, 1920, 1923, 1926, 1928, 1929, 1932, 1933, 1935, 1936, 1939, 1942, 1945, 1946, 1948, 1949, 1953, 1954, 1959, 1969, 1974, 19, 65, 376, 415, 468, 532, 708, 758, 801, 1105, 1106, 1107, 636, 646, 647, 689, 690, 950, 951, 952, 953, 979, 980, 981, 982, 1268, 1298, 1331, 1332, 1333, 1360, 1377, 1398, 1399, 1400, 1421, 1456, 1501, 1502, 1503, 1533, 1534, 1535, 1536, 1537, 1624, 1625, 1626, 1791, 1849, 1861, 1874, 1893, 1909, 1925, 1941, 1961, 1971 ]
5CWE-94
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Argument Parsing within Lightning Components.""" import inspect import os from abc import ABC from argparse import _ArgumentGroup, ArgumentParser, Namespace from contextlib import suppress from functools import wraps from typing import Any, Callable, cast, Dict, List, Tuple, Type, TypeVar, Union import pytorch_lightning as pl from pytorch_lightning.utilities.parsing import str_to_bool, str_to_bool_or_int, str_to_bool_or_str _T = TypeVar("_T", bound=Callable[..., Any]) class ParseArgparserDataType(ABC): def __init__(self, *_: Any, **__: Any) -> None: pass @classmethod def parse_argparser(cls, args: "ArgumentParser") -> Any: pass def from_argparse_args( cls: Type[ParseArgparserDataType], args: Union[Namespace, ArgumentParser], **kwargs: Any ) -> ParseArgparserDataType: """Create an instance from CLI arguments. Eventually use variables from OS environment which are defined as ``"PL_<CLASS-NAME>_<CLASS_ARUMENT_NAME>"``. Args: cls: Lightning class args: The parser or namespace to take arguments from. Only known arguments will be parsed and passed to the :class:`Trainer`. **kwargs: Additional keyword arguments that may override ones in the parser or namespace. These must be valid Trainer arguments. Examples: >>> from pytorch_lightning import Trainer >>> parser = ArgumentParser(add_help=False) >>> parser = Trainer.add_argparse_args(parser) >>> parser.add_argument('--my_custom_arg', default='something') # doctest: +SKIP >>> args = Trainer.parse_argparser(parser.parse_args("")) >>> trainer = Trainer.from_argparse_args(args, logger=False) """ if isinstance(args, ArgumentParser): args = cls.parse_argparser(args) params = vars(args) # we only want to pass in valid Trainer args, the rest may be user specific valid_kwargs = inspect.signature(cls.__init__).parameters trainer_kwargs = {name: params[name] for name in valid_kwargs if name in params} trainer_kwargs.update(**kwargs) return cls(**trainer_kwargs) def parse_argparser(cls: Type["pl.Trainer"], arg_parser: Union[ArgumentParser, Namespace]) -> Namespace: """Parse CLI arguments, required for custom bool types.""" args = arg_parser.parse_args() if isinstance(arg_parser, ArgumentParser) else arg_parser types_default = {arg: (arg_types, arg_default) for arg, arg_types, arg_default in get_init_arguments_and_types(cls)} modified_args = {} for k, v in vars(args).items(): if k in types_default and v is None: # We need to figure out if the None is due to using nargs="?" or if it comes from the default value arg_types, arg_default = types_default[k] if bool in arg_types and isinstance(arg_default, bool): # Value has been passed as a flag => It is currently None, so we need to set it to True # We always set to True, regardless of the default value. # Users must pass False directly, but when passing nothing True is assumed. # i.e. the only way to disable something that defaults to True is to use the long form: # "--a_default_true_arg False" becomes False, while "--a_default_false_arg" becomes None, # which then becomes True here. v = True modified_args[k] = v return Namespace(**modified_args) def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace: """Parse environment arguments if they are defined. Examples: >>> from pytorch_lightning import Trainer >>> parse_env_variables(Trainer) Namespace() >>> import os >>> os.environ["PL_TRAINER_GPUS"] = '42' >>> os.environ["PL_TRAINER_BLABLABLA"] = '1.23' >>> parse_env_variables(Trainer) Namespace(gpus=42) >>> del os.environ["PL_TRAINER_GPUS"] """ cls_arg_defaults = get_init_arguments_and_types(cls) env_args = {} for arg_name, _, _ in cls_arg_defaults: env = template % {"cls_name": cls.__name__.upper(), "cls_argument": arg_name.upper()} val = os.environ.get(env) if not (val is None or val == ""): # todo: specify the possible exception with suppress(Exception): # converting to native types like int/float/bool val = eval(val) env_args[arg_name] = val return Namespace(**env_args) def get_init_arguments_and_types(cls: Any) -> List[Tuple[str, Tuple, Any]]: r"""Scans the class signature and returns argument names, types and default values. Returns: List with tuples of 3 values: (argument name, set with argument types, argument default value). Examples: >>> from pytorch_lightning import Trainer >>> args = get_init_arguments_and_types(Trainer) """ cls_default_params = inspect.signature(cls).parameters name_type_default = [] for arg in cls_default_params: arg_type = cls_default_params[arg].annotation arg_default = cls_default_params[arg].default try: arg_types = tuple(arg_type.__args__) except (AttributeError, TypeError): arg_types = (arg_type,) name_type_default.append((arg, arg_types, arg_default)) return name_type_default def _get_abbrev_qualified_cls_name(cls: Any) -> str: assert isinstance(cls, type), repr(cls) if cls.__module__.startswith("pytorch_lightning."): # Abbreviate. return f"pl.{cls.__name__}" # Fully qualified. return f"{cls.__module__}.{cls.__qualname__}" def add_argparse_args( cls: Type["pl.Trainer"], parent_parser: ArgumentParser, *, use_argument_group: bool = True ) -> Union[_ArgumentGroup, ArgumentParser]: r"""Extends existing argparse by default attributes for ``cls``. Args: cls: Lightning class parent_parser: The custom cli arguments parser, which will be extended by the class's default arguments. use_argument_group: By default, this is True, and uses ``add_argument_group`` to add a new group. If False, this will use old behavior. Returns: If use_argument_group is True, returns ``parent_parser`` to keep old workflows. If False, will return the new ArgumentParser object. Only arguments of the allowed types (str, float, int, bool) will extend the ``parent_parser``. Raises: RuntimeError: If ``parent_parser`` is not an ``ArgumentParser`` instance Examples: >>> # Option 1: Default usage. >>> import argparse >>> from pytorch_lightning import Trainer >>> parser = argparse.ArgumentParser() >>> parser = Trainer.add_argparse_args(parser) >>> args = parser.parse_args([]) >>> # Option 2: Disable use_argument_group (old behavior). >>> import argparse >>> from pytorch_lightning import Trainer >>> parser = argparse.ArgumentParser() >>> parser = Trainer.add_argparse_args(parser, use_argument_group=False) >>> args = parser.parse_args([]) """ if isinstance(parent_parser, _ArgumentGroup): raise RuntimeError("Please only pass an ArgumentParser instance.") if use_argument_group: group_name = _get_abbrev_qualified_cls_name(cls) parser: Union[_ArgumentGroup, ArgumentParser] = parent_parser.add_argument_group(group_name) else: parser = ArgumentParser(parents=[parent_parser], add_help=False) ignore_arg_names = ["self", "args", "kwargs"] if hasattr(cls, "get_deprecated_arg_names"): ignore_arg_names += cls.get_deprecated_arg_names() allowed_types = (str, int, float, bool) # Get symbols from cls or init function. for symbol in (cls, cls.__init__): args_and_types = get_init_arguments_and_types(symbol) args_and_types = [x for x in args_and_types if x[0] not in ignore_arg_names] if len(args_and_types) > 0: break args_help = _parse_args_from_docstring(cls.__init__.__doc__ or cls.__doc__ or "") for arg, arg_types, arg_default in args_and_types: arg_types = tuple(at for at in allowed_types if at in arg_types) if not arg_types: # skip argument with not supported type continue arg_kwargs: Dict[str, Any] = {} if bool in arg_types: arg_kwargs.update(nargs="?", const=True) # if the only arg type is bool if len(arg_types) == 1: use_type: Callable[[str], Union[bool, int, float, str]] = str_to_bool elif int in arg_types: use_type = str_to_bool_or_int elif str in arg_types: use_type = str_to_bool_or_str else: # filter out the bool as we need to use more general use_type = [at for at in arg_types if at is not bool][0] else: use_type = arg_types[0] if arg == "gpus" or arg == "tpu_cores": use_type = _gpus_allowed_type # hack for types in (int, float) if len(arg_types) == 2 and int in set(arg_types) and float in set(arg_types): use_type = _int_or_float_type # hack for track_grad_norm if arg == "track_grad_norm": use_type = float # hack for precision if arg == "precision": use_type = _precision_allowed_type parser.add_argument( f"--{arg}", dest=arg, default=arg_default, type=use_type, help=args_help.get(arg), **arg_kwargs ) if use_argument_group: return parent_parser return parser def _parse_args_from_docstring(docstring: str) -> Dict[str, str]: arg_block_indent = None current_arg = "" parsed = {} for line in docstring.split("\n"): stripped = line.lstrip() if not stripped: continue line_indent = len(line) - len(stripped) if stripped.startswith(("Args:", "Arguments:", "Parameters:")): arg_block_indent = line_indent + 4 elif arg_block_indent is None: continue elif line_indent < arg_block_indent: break elif line_indent == arg_block_indent: current_arg, arg_description = stripped.split(":", maxsplit=1) parsed[current_arg] = arg_description.lstrip() elif line_indent > arg_block_indent: parsed[current_arg] += f" {stripped}" return parsed def _gpus_allowed_type(x: str) -> Union[int, str]: if "," in x: return str(x) return int(x) def _int_or_float_type(x: Union[int, float, str]) -> Union[int, float]: if "." in str(x): return float(x) return int(x) def _precision_allowed_type(x: Union[int, str]) -> Union[int, str]: """ >>> _precision_allowed_type("32") 32 >>> _precision_allowed_type("bf16") 'bf16' """ try: return int(x) except ValueError: return x def _defaults_from_env_vars(fn: _T) -> _T: @wraps(fn) def insert_env_defaults(self: Any, *args: Any, **kwargs: Any) -> Any: cls = self.__class__ # get the class if args: # in case any args passed move them to kwargs # parse only the argument names cls_arg_names = [arg[0] for arg in get_init_arguments_and_types(cls)] # convert args to kwargs kwargs.update(dict(zip(cls_arg_names, args))) env_variables = vars(parse_env_variables(cls)) # update the kwargs by env variables kwargs = dict(list(env_variables.items()) + list(kwargs.items())) # all args were already moved to kwargs return fn(self, **kwargs) return cast(_T, insert_env_defaults)
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Argument Parsing within Lightning Components.""" import inspect import os from abc import ABC from argparse import _ArgumentGroup, ArgumentParser, Namespace from ast import literal_eval from contextlib import suppress from functools import wraps from typing import Any, Callable, cast, Dict, List, Tuple, Type, TypeVar, Union import pytorch_lightning as pl from pytorch_lightning.utilities.parsing import str_to_bool, str_to_bool_or_int, str_to_bool_or_str _T = TypeVar("_T", bound=Callable[..., Any]) class ParseArgparserDataType(ABC): def __init__(self, *_: Any, **__: Any) -> None: pass @classmethod def parse_argparser(cls, args: "ArgumentParser") -> Any: pass def from_argparse_args( cls: Type[ParseArgparserDataType], args: Union[Namespace, ArgumentParser], **kwargs: Any ) -> ParseArgparserDataType: """Create an instance from CLI arguments. Eventually use variables from OS environment which are defined as ``"PL_<CLASS-NAME>_<CLASS_ARUMENT_NAME>"``. Args: cls: Lightning class args: The parser or namespace to take arguments from. Only known arguments will be parsed and passed to the :class:`Trainer`. **kwargs: Additional keyword arguments that may override ones in the parser or namespace. These must be valid Trainer arguments. Examples: >>> from pytorch_lightning import Trainer >>> parser = ArgumentParser(add_help=False) >>> parser = Trainer.add_argparse_args(parser) >>> parser.add_argument('--my_custom_arg', default='something') # doctest: +SKIP >>> args = Trainer.parse_argparser(parser.parse_args("")) >>> trainer = Trainer.from_argparse_args(args, logger=False) """ if isinstance(args, ArgumentParser): args = cls.parse_argparser(args) params = vars(args) # we only want to pass in valid Trainer args, the rest may be user specific valid_kwargs = inspect.signature(cls.__init__).parameters trainer_kwargs = {name: params[name] for name in valid_kwargs if name in params} trainer_kwargs.update(**kwargs) return cls(**trainer_kwargs) def parse_argparser(cls: Type["pl.Trainer"], arg_parser: Union[ArgumentParser, Namespace]) -> Namespace: """Parse CLI arguments, required for custom bool types.""" args = arg_parser.parse_args() if isinstance(arg_parser, ArgumentParser) else arg_parser types_default = {arg: (arg_types, arg_default) for arg, arg_types, arg_default in get_init_arguments_and_types(cls)} modified_args = {} for k, v in vars(args).items(): if k in types_default and v is None: # We need to figure out if the None is due to using nargs="?" or if it comes from the default value arg_types, arg_default = types_default[k] if bool in arg_types and isinstance(arg_default, bool): # Value has been passed as a flag => It is currently None, so we need to set it to True # We always set to True, regardless of the default value. # Users must pass False directly, but when passing nothing True is assumed. # i.e. the only way to disable something that defaults to True is to use the long form: # "--a_default_true_arg False" becomes False, while "--a_default_false_arg" becomes None, # which then becomes True here. v = True modified_args[k] = v return Namespace(**modified_args) def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace: """Parse environment arguments if they are defined. Examples: >>> from pytorch_lightning import Trainer >>> parse_env_variables(Trainer) Namespace() >>> import os >>> os.environ["PL_TRAINER_GPUS"] = '42' >>> os.environ["PL_TRAINER_BLABLABLA"] = '1.23' >>> parse_env_variables(Trainer) Namespace(gpus=42) >>> del os.environ["PL_TRAINER_GPUS"] """ cls_arg_defaults = get_init_arguments_and_types(cls) env_args = {} for arg_name, _, _ in cls_arg_defaults: env = template % {"cls_name": cls.__name__.upper(), "cls_argument": arg_name.upper()} val = os.environ.get(env) if not (val is None or val == ""): # todo: specify the possible exception with suppress(Exception): # converting to native types like int/float/bool val = literal_eval(val) env_args[arg_name] = val return Namespace(**env_args) def get_init_arguments_and_types(cls: Any) -> List[Tuple[str, Tuple, Any]]: r"""Scans the class signature and returns argument names, types and default values. Returns: List with tuples of 3 values: (argument name, set with argument types, argument default value). Examples: >>> from pytorch_lightning import Trainer >>> args = get_init_arguments_and_types(Trainer) """ cls_default_params = inspect.signature(cls).parameters name_type_default = [] for arg in cls_default_params: arg_type = cls_default_params[arg].annotation arg_default = cls_default_params[arg].default try: arg_types = tuple(arg_type.__args__) except (AttributeError, TypeError): arg_types = (arg_type,) name_type_default.append((arg, arg_types, arg_default)) return name_type_default def _get_abbrev_qualified_cls_name(cls: Any) -> str: assert isinstance(cls, type), repr(cls) if cls.__module__.startswith("pytorch_lightning."): # Abbreviate. return f"pl.{cls.__name__}" # Fully qualified. return f"{cls.__module__}.{cls.__qualname__}" def add_argparse_args( cls: Type["pl.Trainer"], parent_parser: ArgumentParser, *, use_argument_group: bool = True ) -> Union[_ArgumentGroup, ArgumentParser]: r"""Extends existing argparse by default attributes for ``cls``. Args: cls: Lightning class parent_parser: The custom cli arguments parser, which will be extended by the class's default arguments. use_argument_group: By default, this is True, and uses ``add_argument_group`` to add a new group. If False, this will use old behavior. Returns: If use_argument_group is True, returns ``parent_parser`` to keep old workflows. If False, will return the new ArgumentParser object. Only arguments of the allowed types (str, float, int, bool) will extend the ``parent_parser``. Raises: RuntimeError: If ``parent_parser`` is not an ``ArgumentParser`` instance Examples: >>> # Option 1: Default usage. >>> import argparse >>> from pytorch_lightning import Trainer >>> parser = argparse.ArgumentParser() >>> parser = Trainer.add_argparse_args(parser) >>> args = parser.parse_args([]) >>> # Option 2: Disable use_argument_group (old behavior). >>> import argparse >>> from pytorch_lightning import Trainer >>> parser = argparse.ArgumentParser() >>> parser = Trainer.add_argparse_args(parser, use_argument_group=False) >>> args = parser.parse_args([]) """ if isinstance(parent_parser, _ArgumentGroup): raise RuntimeError("Please only pass an ArgumentParser instance.") if use_argument_group: group_name = _get_abbrev_qualified_cls_name(cls) parser: Union[_ArgumentGroup, ArgumentParser] = parent_parser.add_argument_group(group_name) else: parser = ArgumentParser(parents=[parent_parser], add_help=False) ignore_arg_names = ["self", "args", "kwargs"] if hasattr(cls, "get_deprecated_arg_names"): ignore_arg_names += cls.get_deprecated_arg_names() allowed_types = (str, int, float, bool) # Get symbols from cls or init function. for symbol in (cls, cls.__init__): args_and_types = get_init_arguments_and_types(symbol) args_and_types = [x for x in args_and_types if x[0] not in ignore_arg_names] if len(args_and_types) > 0: break args_help = _parse_args_from_docstring(cls.__init__.__doc__ or cls.__doc__ or "") for arg, arg_types, arg_default in args_and_types: arg_types = tuple(at for at in allowed_types if at in arg_types) if not arg_types: # skip argument with not supported type continue arg_kwargs: Dict[str, Any] = {} if bool in arg_types: arg_kwargs.update(nargs="?", const=True) # if the only arg type is bool if len(arg_types) == 1: use_type: Callable[[str], Union[bool, int, float, str]] = str_to_bool elif int in arg_types: use_type = str_to_bool_or_int elif str in arg_types: use_type = str_to_bool_or_str else: # filter out the bool as we need to use more general use_type = [at for at in arg_types if at is not bool][0] else: use_type = arg_types[0] if arg == "gpus" or arg == "tpu_cores": use_type = _gpus_allowed_type # hack for types in (int, float) if len(arg_types) == 2 and int in set(arg_types) and float in set(arg_types): use_type = _int_or_float_type # hack for track_grad_norm if arg == "track_grad_norm": use_type = float # hack for precision if arg == "precision": use_type = _precision_allowed_type parser.add_argument( f"--{arg}", dest=arg, default=arg_default, type=use_type, help=args_help.get(arg), **arg_kwargs ) if use_argument_group: return parent_parser return parser def _parse_args_from_docstring(docstring: str) -> Dict[str, str]: arg_block_indent = None current_arg = "" parsed = {} for line in docstring.split("\n"): stripped = line.lstrip() if not stripped: continue line_indent = len(line) - len(stripped) if stripped.startswith(("Args:", "Arguments:", "Parameters:")): arg_block_indent = line_indent + 4 elif arg_block_indent is None: continue elif line_indent < arg_block_indent: break elif line_indent == arg_block_indent: current_arg, arg_description = stripped.split(":", maxsplit=1) parsed[current_arg] = arg_description.lstrip() elif line_indent > arg_block_indent: parsed[current_arg] += f" {stripped}" return parsed def _gpus_allowed_type(x: str) -> Union[int, str]: if "," in x: return str(x) return int(x) def _int_or_float_type(x: Union[int, float, str]) -> Union[int, float]: if "." in str(x): return float(x) return int(x) def _precision_allowed_type(x: Union[int, str]) -> Union[int, str]: """ >>> _precision_allowed_type("32") 32 >>> _precision_allowed_type("bf16") 'bf16' """ try: return int(x) except ValueError: return x def _defaults_from_env_vars(fn: _T) -> _T: @wraps(fn) def insert_env_defaults(self: Any, *args: Any, **kwargs: Any) -> Any: cls = self.__class__ # get the class if args: # in case any args passed move them to kwargs # parse only the argument names cls_arg_names = [arg[0] for arg in get_init_arguments_and_types(cls)] # convert args to kwargs kwargs.update(dict(zip(cls_arg_names, args))) env_variables = vars(parse_env_variables(cls)) # update the kwargs by env variables kwargs = dict(list(env_variables.items()) + list(kwargs.items())) # all args were already moved to kwargs return fn(self, **kwargs) return cast(_T, insert_env_defaults)
remote_code_execution
{ "code": [ " val = eval(val)" ], "line_no": [ 124 ] }
{ "code": [ "from ast import literal_eval", " val = literal_eval(val)" ], "line_no": [ 20, 125 ] }
import inspect import os from abc import ABC from argparse import ._ArgumentGroup, ArgumentParser, Namespace from contextlib import suppress from functools import wraps from typing import Any, Callable, cast, Dict, List, Tuple, Type, TypeVar, Union import pytorch_lightning as pl from pytorch_lightning.utilities.parsing import str_to_bool, str_to_bool_or_int, str_to_bool_or_str VAR_0 = TypeVar("_T", bound=Callable[..., Any]) class CLASS_0(ABC): def __init__(self, *VAR_11: Any, **VAR_12: Any) -> None: pass @classmethod def FUNC_1(VAR_1, VAR_2: "ArgumentParser") -> Any: pass def FUNC_0( VAR_1: Type[CLASS_0], VAR_2: Union[Namespace, ArgumentParser], **VAR_3: Any ) -> CLASS_0: if isinstance(VAR_2, ArgumentParser): VAR_2 = VAR_1.parse_argparser(VAR_2) VAR_13 = vars(VAR_2) VAR_14 = inspect.signature(VAR_1.__init__).parameters VAR_15 = {name: VAR_13[name] for name in VAR_14 if name in VAR_13} VAR_15.update(**VAR_3) return VAR_1(**VAR_15) def FUNC_1(VAR_1: Type["pl.Trainer"], VAR_4: Union[ArgumentParser, Namespace]) -> Namespace: VAR_2 = VAR_4.parse_args() if isinstance(VAR_4, ArgumentParser) else VAR_4 VAR_16 = {arg: (VAR_36, VAR_32) for arg, VAR_36, VAR_32 in FUNC_3(VAR_1)} VAR_17 = {} for VAR_28, VAR_43 in vars(VAR_2).items(): if VAR_28 in VAR_16 and VAR_43 is None: VAR_36, VAR_32 = VAR_16[VAR_28] if bool in VAR_36 and isinstance(VAR_32, bool): VAR_43 = True VAR_17[VAR_28] = VAR_43 return Namespace(**VAR_17) def FUNC_2(VAR_1: Type["pl.Trainer"], VAR_5: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace: VAR_18 = FUNC_3(VAR_1) VAR_19 = {} for VAR_40, VAR_11, _ in VAR_18: VAR_29 = VAR_5 % {"cls_name": VAR_1.__name__.upper(), "cls_argument": VAR_40.upper()} VAR_30 = os.environ.get(VAR_29) if not (VAR_30 is None or VAR_30 == ""): with suppress(Exception): VAR_30 = eval(VAR_30) VAR_19[VAR_40] = VAR_30 return Namespace(**VAR_19) def FUNC_3(VAR_1: Any) -> List[Tuple[str, Tuple, Any]]: VAR_20 = inspect.signature(VAR_1).parameters VAR_21 = [] for arg in VAR_20: VAR_31 = VAR_20[arg].annotation VAR_32 = VAR_20[arg].default try: VAR_36 = tuple(VAR_31.__args__) except (AttributeError, TypeError): VAR_36 = (VAR_31,) VAR_21.append((arg, VAR_36, VAR_32)) return VAR_21 def FUNC_4(VAR_1: Any) -> str: assert isinstance(VAR_1, type), repr(VAR_1) if VAR_1.__module__.startswith("pytorch_lightning."): return f"pl.{VAR_1.__name__}" return f"{VAR_1.__module__}.{VAR_1.__qualname__}" def FUNC_5( VAR_1: Type["pl.Trainer"], VAR_6: ArgumentParser, *, VAR_7: bool = True ) -> Union[_ArgumentGroup, ArgumentParser]: if isinstance(VAR_6, _ArgumentGroup): raise RuntimeError("Please only pass an ArgumentParser instance.") if VAR_7: VAR_33 = FUNC_4(VAR_1) VAR_34: Union[_ArgumentGroup, ArgumentParser] = VAR_6.add_argument_group(VAR_33) else: VAR_34 = ArgumentParser(parents=[VAR_6], add_help=False) VAR_22 = ["self", "args", "kwargs"] if hasattr(VAR_1, "get_deprecated_arg_names"): VAR_22 += VAR_1.get_deprecated_arg_names() VAR_23 = (str, int, float, bool) for symbol in (VAR_1, VAR_1.__init__): VAR_35 = FUNC_3(symbol) VAR_35 = [VAR_9 for VAR_9 in VAR_35 if VAR_9[0] not in VAR_22] if len(VAR_35) > 0: break VAR_24 = FUNC_6(VAR_1.__init__.__doc__ or VAR_1.__doc__ or "") for arg, VAR_36, VAR_32 in VAR_35: VAR_36 = tuple(at for at in VAR_23 if at in VAR_36) if not VAR_36: continue arg_kwargs: Dict[str, Any] = {} if bool in VAR_36: arg_kwargs.update(nargs="?", const=True) if len(VAR_36) == 1: VAR_41: Callable[[str], Union[bool, int, float, str]] = str_to_bool elif int in VAR_36: VAR_41 = str_to_bool_or_int elif str in VAR_36: VAR_41 = str_to_bool_or_str else: VAR_41 = [at for at in VAR_36 if at is not bool][0] else: VAR_41 = VAR_36[0] if arg == "gpus" or arg == "tpu_cores": VAR_41 = FUNC_7 if len(VAR_36) == 2 and int in set(VAR_36) and float in set(VAR_36): VAR_41 = FUNC_8 if arg == "track_grad_norm": VAR_41 = float if arg == "precision": VAR_41 = FUNC_9 VAR_34.add_argument( f"--{arg}", dest=arg, default=VAR_32, type=VAR_41, help=VAR_24.get(arg), **arg_kwargs ) if VAR_7: return VAR_6 return VAR_34 def FUNC_6(VAR_8: str) -> Dict[str, str]: VAR_25 = None VAR_26 = "" VAR_27 = {} for line in VAR_8.split("\n"): VAR_37 = line.lstrip() if not VAR_37: continue VAR_38 = len(line) - len(VAR_37) if VAR_37.startswith(("Args:", "Arguments:", "Parameters:")): VAR_25 = VAR_38 + 4 elif VAR_25 is None: continue elif VAR_38 < VAR_25: break elif VAR_38 == VAR_25: VAR_26, VAR_44 = VAR_37.split(":", maxsplit=1) VAR_27[VAR_26] = VAR_44.lstrip() elif VAR_38 > VAR_25: VAR_27[VAR_26] += f" {VAR_37}" return VAR_27 def FUNC_7(VAR_9: str) -> Union[int, str]: if "," in VAR_9: return str(VAR_9) return int(VAR_9) def FUNC_8(VAR_9: Union[int, float, str]) -> Union[int, float]: if "." in str(VAR_9): return float(VAR_9) return int(VAR_9) def FUNC_9(VAR_9: Union[int, str]) -> Union[int, str]: try: return int(VAR_9) except ValueError: return VAR_9 def FUNC_10(VAR_10: VAR_0) -> _T: @wraps(VAR_10) def FUNC_11(self: Any, *VAR_2: Any, **VAR_3: Any) -> Any: VAR_1 = self.__class__ # get the class if VAR_2: # in case any VAR_2 passed move them to VAR_3 VAR_42 = [arg[0] for arg in FUNC_3(VAR_1)] kwargs.update(dict(zip(VAR_42, VAR_2))) VAR_39 = vars(FUNC_2(VAR_1)) VAR_3 = dict(list(VAR_39.items()) + list(VAR_3.items())) return VAR_10(self, **VAR_3) return cast(VAR_0, FUNC_11)
import inspect import os from abc import ABC from argparse import ._ArgumentGroup, ArgumentParser, Namespace from ast import literal_eval from contextlib import suppress from functools import wraps from typing import Any, Callable, cast, Dict, List, Tuple, Type, TypeVar, Union import pytorch_lightning as pl from pytorch_lightning.utilities.parsing import str_to_bool, str_to_bool_or_int, str_to_bool_or_str VAR_0 = TypeVar("_T", bound=Callable[..., Any]) class CLASS_0(ABC): def __init__(self, *VAR_11: Any, **VAR_12: Any) -> None: pass @classmethod def FUNC_1(VAR_1, VAR_2: "ArgumentParser") -> Any: pass def FUNC_0( VAR_1: Type[CLASS_0], VAR_2: Union[Namespace, ArgumentParser], **VAR_3: Any ) -> CLASS_0: if isinstance(VAR_2, ArgumentParser): VAR_2 = VAR_1.parse_argparser(VAR_2) VAR_13 = vars(VAR_2) VAR_14 = inspect.signature(VAR_1.__init__).parameters VAR_15 = {name: VAR_13[name] for name in VAR_14 if name in VAR_13} VAR_15.update(**VAR_3) return VAR_1(**VAR_15) def FUNC_1(VAR_1: Type["pl.Trainer"], VAR_4: Union[ArgumentParser, Namespace]) -> Namespace: VAR_2 = VAR_4.parse_args() if isinstance(VAR_4, ArgumentParser) else VAR_4 VAR_16 = {arg: (VAR_36, VAR_32) for arg, VAR_36, VAR_32 in FUNC_3(VAR_1)} VAR_17 = {} for VAR_28, VAR_43 in vars(VAR_2).items(): if VAR_28 in VAR_16 and VAR_43 is None: VAR_36, VAR_32 = VAR_16[VAR_28] if bool in VAR_36 and isinstance(VAR_32, bool): VAR_43 = True VAR_17[VAR_28] = VAR_43 return Namespace(**VAR_17) def FUNC_2(VAR_1: Type["pl.Trainer"], VAR_5: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace: VAR_18 = FUNC_3(VAR_1) VAR_19 = {} for VAR_40, VAR_11, _ in VAR_18: VAR_29 = VAR_5 % {"cls_name": VAR_1.__name__.upper(), "cls_argument": VAR_40.upper()} VAR_30 = os.environ.get(VAR_29) if not (VAR_30 is None or VAR_30 == ""): with suppress(Exception): VAR_30 = literal_eval(VAR_30) VAR_19[VAR_40] = VAR_30 return Namespace(**VAR_19) def FUNC_3(VAR_1: Any) -> List[Tuple[str, Tuple, Any]]: VAR_20 = inspect.signature(VAR_1).parameters VAR_21 = [] for arg in VAR_20: VAR_31 = VAR_20[arg].annotation VAR_32 = VAR_20[arg].default try: VAR_36 = tuple(VAR_31.__args__) except (AttributeError, TypeError): VAR_36 = (VAR_31,) VAR_21.append((arg, VAR_36, VAR_32)) return VAR_21 def FUNC_4(VAR_1: Any) -> str: assert isinstance(VAR_1, type), repr(VAR_1) if VAR_1.__module__.startswith("pytorch_lightning."): return f"pl.{VAR_1.__name__}" return f"{VAR_1.__module__}.{VAR_1.__qualname__}" def FUNC_5( VAR_1: Type["pl.Trainer"], VAR_6: ArgumentParser, *, VAR_7: bool = True ) -> Union[_ArgumentGroup, ArgumentParser]: if isinstance(VAR_6, _ArgumentGroup): raise RuntimeError("Please only pass an ArgumentParser instance.") if VAR_7: VAR_33 = FUNC_4(VAR_1) VAR_34: Union[_ArgumentGroup, ArgumentParser] = VAR_6.add_argument_group(VAR_33) else: VAR_34 = ArgumentParser(parents=[VAR_6], add_help=False) VAR_22 = ["self", "args", "kwargs"] if hasattr(VAR_1, "get_deprecated_arg_names"): VAR_22 += VAR_1.get_deprecated_arg_names() VAR_23 = (str, int, float, bool) for symbol in (VAR_1, VAR_1.__init__): VAR_35 = FUNC_3(symbol) VAR_35 = [VAR_9 for VAR_9 in VAR_35 if VAR_9[0] not in VAR_22] if len(VAR_35) > 0: break VAR_24 = FUNC_6(VAR_1.__init__.__doc__ or VAR_1.__doc__ or "") for arg, VAR_36, VAR_32 in VAR_35: VAR_36 = tuple(at for at in VAR_23 if at in VAR_36) if not VAR_36: continue arg_kwargs: Dict[str, Any] = {} if bool in VAR_36: arg_kwargs.update(nargs="?", const=True) if len(VAR_36) == 1: VAR_41: Callable[[str], Union[bool, int, float, str]] = str_to_bool elif int in VAR_36: VAR_41 = str_to_bool_or_int elif str in VAR_36: VAR_41 = str_to_bool_or_str else: VAR_41 = [at for at in VAR_36 if at is not bool][0] else: VAR_41 = VAR_36[0] if arg == "gpus" or arg == "tpu_cores": VAR_41 = FUNC_7 if len(VAR_36) == 2 and int in set(VAR_36) and float in set(VAR_36): VAR_41 = FUNC_8 if arg == "track_grad_norm": VAR_41 = float if arg == "precision": VAR_41 = FUNC_9 VAR_34.add_argument( f"--{arg}", dest=arg, default=VAR_32, type=VAR_41, help=VAR_24.get(arg), **arg_kwargs ) if VAR_7: return VAR_6 return VAR_34 def FUNC_6(VAR_8: str) -> Dict[str, str]: VAR_25 = None VAR_26 = "" VAR_27 = {} for line in VAR_8.split("\n"): VAR_37 = line.lstrip() if not VAR_37: continue VAR_38 = len(line) - len(VAR_37) if VAR_37.startswith(("Args:", "Arguments:", "Parameters:")): VAR_25 = VAR_38 + 4 elif VAR_25 is None: continue elif VAR_38 < VAR_25: break elif VAR_38 == VAR_25: VAR_26, VAR_44 = VAR_37.split(":", maxsplit=1) VAR_27[VAR_26] = VAR_44.lstrip() elif VAR_38 > VAR_25: VAR_27[VAR_26] += f" {VAR_37}" return VAR_27 def FUNC_7(VAR_9: str) -> Union[int, str]: if "," in VAR_9: return str(VAR_9) return int(VAR_9) def FUNC_8(VAR_9: Union[int, float, str]) -> Union[int, float]: if "." in str(VAR_9): return float(VAR_9) return int(VAR_9) def FUNC_9(VAR_9: Union[int, str]) -> Union[int, str]: try: return int(VAR_9) except ValueError: return VAR_9 def FUNC_10(VAR_10: VAR_0) -> _T: @wraps(VAR_10) def FUNC_11(self: Any, *VAR_2: Any, **VAR_3: Any) -> Any: VAR_1 = self.__class__ # get the class if VAR_2: # in case any VAR_2 passed move them to VAR_3 VAR_42 = [arg[0] for arg in FUNC_3(VAR_1)] kwargs.update(dict(zip(VAR_42, VAR_2))) VAR_39 = vars(FUNC_2(VAR_1)) VAR_3 = dict(list(VAR_39.items()) + list(VAR_3.items())) return VAR_10(self, **VAR_3) return cast(VAR_0, FUNC_11)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 23, 26, 28, 29, 33, 37, 38, 44, 51, 53, 63, 65, 66, 70, 72, 73, 77, 79, 83, 86, 87, 88, 89, 90, 91, 92, 94, 97, 98, 101, 103, 115, 121, 123, 127, 128, 131, 135, 137, 140, 151, 153, 155, 156, 160, 162, 164, 165, 170, 180, 184, 187, 191, 193, 200, 215, 219, 221, 222, 228, 230, 234, 239, 247, 251, 254, 255, 258, 259, 262, 263, 266, 270, 274, 275, 297, 298, 303, 304, 309, 310, 322, 323, 329, 331, 334, 336, 337, 339, 341, 14, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 75, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 312, 313, 314, 315, 316, 317 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 24, 27, 29, 30, 34, 38, 39, 45, 52, 54, 64, 66, 67, 71, 73, 74, 78, 80, 84, 87, 88, 89, 90, 91, 92, 93, 95, 98, 99, 102, 104, 116, 122, 124, 128, 129, 132, 136, 138, 141, 152, 154, 156, 157, 161, 163, 165, 166, 171, 181, 185, 188, 192, 194, 201, 216, 220, 222, 223, 229, 231, 235, 240, 248, 252, 255, 256, 259, 260, 263, 264, 267, 271, 275, 276, 298, 299, 304, 305, 310, 311, 323, 324, 330, 332, 335, 337, 338, 340, 342, 14, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 76, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 313, 314, 315, 316, 317, 318 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from mock import ANY, Mock, call from twisted.internet import defer from synapse.api.errors import AuthError from synapse.types import UserID, create_requester from tests import unittest from tests.test_utils import make_awaitable from tests.unittest import override_config from tests.utils import register_federation_servlets # Some local users to test with U_APPLE = UserID.from_string("@apple:test") U_BANANA = UserID.from_string("@banana:test") # Remote user U_ONION = UserID.from_string("@onion:farm") # Test room id ROOM_ID = "a-room" def _expect_edu_transaction(edu_type, content, origin="test"): return { "origin": origin, "origin_server_ts": 1000000, "pdus": [], "edus": [{"edu_type": edu_type, "content": content}], } def _make_edu_transaction_json(edu_type, content): return json.dumps(_expect_edu_transaction(edu_type, content)).encode("utf8") class TypingNotificationsTestCase(unittest.HomeserverTestCase): servlets = [register_federation_servlets] def make_homeserver(self, reactor, clock): # we mock out the keyring so as to skip the authentication check on the # federation API call. mock_keyring = Mock(spec=["verify_json_for_server"]) mock_keyring.verify_json_for_server.return_value = defer.succeed(True) # we mock out the federation client too mock_federation_client = Mock(spec=["put_json"]) mock_federation_client.put_json.return_value = defer.succeed((200, "OK")) # the tests assume that we are starting at unix time 1000 reactor.pump((1000,)) hs = self.setup_test_homeserver( notifier=Mock(), http_client=mock_federation_client, keyring=mock_keyring, replication_streams={}, ) return hs def prepare(self, reactor, clock, hs): mock_notifier = hs.get_notifier() self.on_new_event = mock_notifier.on_new_event self.handler = hs.get_typing_handler() self.event_source = hs.get_event_sources().sources["typing"] self.datastore = hs.get_datastore() retry_timings_res = { "destination": "", "retry_last_ts": 0, "retry_interval": 0, "failure_ts": None, } self.datastore.get_destination_retry_timings = Mock( return_value=defer.succeed(retry_timings_res) ) self.datastore.get_device_updates_by_remote = Mock( return_value=make_awaitable((0, [])) ) self.datastore.get_destination_last_successful_stream_ordering = Mock( return_value=make_awaitable(None) ) def get_received_txn_response(*args): return defer.succeed(None) self.datastore.get_received_txn_response = get_received_txn_response self.room_members = [] async def check_user_in_room(room_id, user_id): if user_id not in [u.to_string() for u in self.room_members]: raise AuthError(401, "User is not in the room") return None hs.get_auth().check_user_in_room = check_user_in_room def get_joined_hosts_for_room(room_id): return {member.domain for member in self.room_members} self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room async def get_users_in_room(room_id): return {str(u) for u in self.room_members} self.datastore.get_users_in_room = get_users_in_room self.datastore.get_user_directory_stream_pos = Mock( side_effect=( # we deliberately return a non-None stream pos to avoid doing an initial_spam lambda: make_awaitable(1) ) ) self.datastore.get_current_state_deltas = Mock(return_value=(0, None)) self.datastore.get_to_device_stream_token = lambda: 0 self.datastore.get_new_device_msgs_for_remote = lambda *args, **kargs: make_awaitable( ([], 0) ) self.datastore.delete_device_msgs_for_remote = lambda *args, **kargs: make_awaitable( None ) self.datastore.set_received_txn_response = lambda *args, **kwargs: make_awaitable( None ) def test_started_typing_local(self): self.room_members = [U_APPLE, U_BANANA] self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=20000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [ { "type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": [U_APPLE.to_string()]}, } ], ) @override_config({"send_federation": True}) def test_started_typing_remote_send(self): self.room_members = [U_APPLE, U_ONION] self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=20000, ) ) put_json = self.hs.get_http_client().put_json put_json.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=_expect_edu_transaction( "m.typing", content={ "room_id": ROOM_ID, "user_id": U_APPLE.to_string(), "typing": True, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) def test_started_typing_remote_recv(self): self.room_members = [U_APPLE, U_ONION] self.assertEquals(self.event_source.get_current_key(), 0) (request, channel) = self.make_request( "PUT", "/_matrix/federation/v1/send/1000000", _make_edu_transaction_json( "m.typing", content={ "room_id": ROOM_ID, "user_id": U_ONION.to_string(), "typing": True, }, ), federation_auth_origin=b"farm", ) self.assertEqual(channel.code, 200) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [ { "type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": [U_ONION.to_string()]}, } ], ) @override_config({"send_federation": True}) def test_stopped_typing(self): self.room_members = [U_APPLE, U_BANANA, U_ONION] # Gut-wrenching from synapse.handlers.typing import RoomMember member = RoomMember(ROOM_ID, U_APPLE.to_string()) self.handler._member_typing_until[member] = 1002000 self.handler._room_typing[ROOM_ID] = {U_APPLE.to_string()} self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.stopped_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) put_json = self.hs.get_http_client().put_json put_json.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=_expect_edu_transaction( "m.typing", content={ "room_id": ROOM_ID, "user_id": U_APPLE.to_string(), "typing": False, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}], ) def test_typing_timeout(self): self.room_members = [U_APPLE, U_BANANA] self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=10000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) self.on_new_event.reset_mock() self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [ { "type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": [U_APPLE.to_string()]}, } ], ) self.reactor.pump([16]) self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[ROOM_ID])]) self.assertEquals(self.event_source.get_current_key(), 2) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=1) ) self.assertEquals( events[0], [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}], ) # SYN-230 - see if we can still set after timeout self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=10000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[ROOM_ID])]) self.on_new_event.reset_mock() self.assertEquals(self.event_source.get_current_key(), 3) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [ { "type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": [U_APPLE.to_string()]}, } ], )
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from mock import ANY, Mock, call from twisted.internet import defer from synapse.api.errors import AuthError from synapse.types import UserID, create_requester from tests import unittest from tests.test_utils import make_awaitable from tests.unittest import override_config from tests.utils import register_federation_servlets # Some local users to test with U_APPLE = UserID.from_string("@apple:test") U_BANANA = UserID.from_string("@banana:test") # Remote user U_ONION = UserID.from_string("@onion:farm") # Test room id ROOM_ID = "a-room" def _expect_edu_transaction(edu_type, content, origin="test"): return { "origin": origin, "origin_server_ts": 1000000, "pdus": [], "edus": [{"edu_type": edu_type, "content": content}], } def _make_edu_transaction_json(edu_type, content): return json.dumps(_expect_edu_transaction(edu_type, content)).encode("utf8") class TypingNotificationsTestCase(unittest.HomeserverTestCase): servlets = [register_federation_servlets] def make_homeserver(self, reactor, clock): # we mock out the keyring so as to skip the authentication check on the # federation API call. mock_keyring = Mock(spec=["verify_json_for_server"]) mock_keyring.verify_json_for_server.return_value = defer.succeed(True) # we mock out the federation client too mock_federation_client = Mock(spec=["put_json"]) mock_federation_client.put_json.return_value = defer.succeed((200, "OK")) # the tests assume that we are starting at unix time 1000 reactor.pump((1000,)) hs = self.setup_test_homeserver( notifier=Mock(), federation_http_client=mock_federation_client, keyring=mock_keyring, replication_streams={}, ) return hs def prepare(self, reactor, clock, hs): mock_notifier = hs.get_notifier() self.on_new_event = mock_notifier.on_new_event self.handler = hs.get_typing_handler() self.event_source = hs.get_event_sources().sources["typing"] self.datastore = hs.get_datastore() retry_timings_res = { "destination": "", "retry_last_ts": 0, "retry_interval": 0, "failure_ts": None, } self.datastore.get_destination_retry_timings = Mock( return_value=defer.succeed(retry_timings_res) ) self.datastore.get_device_updates_by_remote = Mock( return_value=make_awaitable((0, [])) ) self.datastore.get_destination_last_successful_stream_ordering = Mock( return_value=make_awaitable(None) ) def get_received_txn_response(*args): return defer.succeed(None) self.datastore.get_received_txn_response = get_received_txn_response self.room_members = [] async def check_user_in_room(room_id, user_id): if user_id not in [u.to_string() for u in self.room_members]: raise AuthError(401, "User is not in the room") return None hs.get_auth().check_user_in_room = check_user_in_room def get_joined_hosts_for_room(room_id): return {member.domain for member in self.room_members} self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room async def get_users_in_room(room_id): return {str(u) for u in self.room_members} self.datastore.get_users_in_room = get_users_in_room self.datastore.get_user_directory_stream_pos = Mock( side_effect=( # we deliberately return a non-None stream pos to avoid doing an initial_spam lambda: make_awaitable(1) ) ) self.datastore.get_current_state_deltas = Mock(return_value=(0, None)) self.datastore.get_to_device_stream_token = lambda: 0 self.datastore.get_new_device_msgs_for_remote = lambda *args, **kargs: make_awaitable( ([], 0) ) self.datastore.delete_device_msgs_for_remote = lambda *args, **kargs: make_awaitable( None ) self.datastore.set_received_txn_response = lambda *args, **kwargs: make_awaitable( None ) def test_started_typing_local(self): self.room_members = [U_APPLE, U_BANANA] self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=20000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [ { "type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": [U_APPLE.to_string()]}, } ], ) @override_config({"send_federation": True}) def test_started_typing_remote_send(self): self.room_members = [U_APPLE, U_ONION] self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=20000, ) ) put_json = self.hs.get_federation_http_client().put_json put_json.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=_expect_edu_transaction( "m.typing", content={ "room_id": ROOM_ID, "user_id": U_APPLE.to_string(), "typing": True, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) def test_started_typing_remote_recv(self): self.room_members = [U_APPLE, U_ONION] self.assertEquals(self.event_source.get_current_key(), 0) (request, channel) = self.make_request( "PUT", "/_matrix/federation/v1/send/1000000", _make_edu_transaction_json( "m.typing", content={ "room_id": ROOM_ID, "user_id": U_ONION.to_string(), "typing": True, }, ), federation_auth_origin=b"farm", ) self.assertEqual(channel.code, 200) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [ { "type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": [U_ONION.to_string()]}, } ], ) @override_config({"send_federation": True}) def test_stopped_typing(self): self.room_members = [U_APPLE, U_BANANA, U_ONION] # Gut-wrenching from synapse.handlers.typing import RoomMember member = RoomMember(ROOM_ID, U_APPLE.to_string()) self.handler._member_typing_until[member] = 1002000 self.handler._room_typing[ROOM_ID] = {U_APPLE.to_string()} self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.stopped_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) put_json = self.hs.get_federation_http_client().put_json put_json.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=_expect_edu_transaction( "m.typing", content={ "room_id": ROOM_ID, "user_id": U_APPLE.to_string(), "typing": False, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}], ) def test_typing_timeout(self): self.room_members = [U_APPLE, U_BANANA] self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=10000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) self.on_new_event.reset_mock() self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [ { "type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": [U_APPLE.to_string()]}, } ], ) self.reactor.pump([16]) self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[ROOM_ID])]) self.assertEquals(self.event_source.get_current_key(), 2) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=1) ) self.assertEquals( events[0], [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}], ) # SYN-230 - see if we can still set after timeout self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=10000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[ROOM_ID])]) self.on_new_event.reset_mock() self.assertEquals(self.event_source.get_current_key(), 3) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [ { "type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": [U_APPLE.to_string()]}, } ], )
open_redirect
{ "code": [ " http_client=mock_federation_client,", " put_json = self.hs.get_http_client().put_json", " put_json = self.hs.get_http_client().put_json" ], "line_no": [ 73, 195, 273 ] }
{ "code": [ " federation_http_client=mock_federation_client,", " put_json = self.hs.get_federation_http_client().put_json", " put_json = self.hs.get_federation_http_client().put_json" ], "line_no": [ 73, 195, 273 ] }
import json from mock import ANY, Mock, call from twisted.internet import defer from synapse.api.errors import AuthError from synapse.types import UserID, create_requester from tests import unittest from tests.test_utils import make_awaitable from tests.unittest import override_config from tests.utils import register_federation_servlets VAR_0 = UserID.from_string("@apple:test") VAR_1 = UserID.from_string("@banana:test") VAR_2 = UserID.from_string("@onion:farm") VAR_3 = "a-room" def FUNC_0(VAR_4, VAR_5, VAR_6="test"): return { "origin": VAR_6, "origin_server_ts": 1000000, "pdus": [], "edus": [{"edu_type": VAR_4, "content": VAR_5}], } def FUNC_1(VAR_4, VAR_5): return json.dumps(FUNC_0(VAR_4, VAR_5)).encode("utf8") class CLASS_0(unittest.HomeserverTestCase): VAR_7 = [register_federation_servlets] def FUNC_2(self, VAR_8, VAR_9): VAR_11 = Mock(spec=["verify_json_for_server"]) VAR_11.verify_json_for_server.return_value = defer.succeed(True) VAR_12 = Mock(spec=["put_json"]) VAR_12.put_json.return_value = defer.succeed((200, "OK")) VAR_8.pump((1000,)) VAR_10 = self.setup_test_homeserver( notifier=Mock(), http_client=VAR_12, keyring=VAR_11, replication_streams={}, ) return VAR_10 def FUNC_3(self, VAR_8, VAR_9, VAR_10): VAR_13 = VAR_10.get_notifier() self.on_new_event = VAR_13.on_new_event self.handler = VAR_10.get_typing_handler() self.event_source = VAR_10.get_event_sources().sources["typing"] self.datastore = VAR_10.get_datastore() VAR_14 = { "destination": "", "retry_last_ts": 0, "retry_interval": 0, "failure_ts": None, } self.datastore.get_destination_retry_timings = Mock( return_value=defer.succeed(VAR_14) ) self.datastore.get_device_updates_by_remote = Mock( return_value=make_awaitable((0, [])) ) self.datastore.get_destination_last_successful_stream_ordering = Mock( return_value=make_awaitable(None) ) def FUNC_9(*VAR_15): return defer.succeed(None) self.datastore.get_received_txn_response = FUNC_9 self.room_members = [] async def FUNC_10(VAR_16, VAR_17): if VAR_17 not in [u.to_string() for u in self.room_members]: raise AuthError(401, "User is not in the room") return None VAR_10.get_auth().check_user_in_room = FUNC_10 def FUNC_11(VAR_16): return {VAR_22.domain for VAR_22 in self.room_members} self.datastore.get_joined_hosts_for_room = FUNC_11 async def FUNC_12(VAR_16): return {str(u) for u in self.room_members} self.datastore.get_users_in_room = FUNC_12 self.datastore.get_user_directory_stream_pos = Mock( side_effect=( lambda: make_awaitable(1) ) ) self.datastore.get_current_state_deltas = Mock(return_value=(0, None)) self.datastore.get_to_device_stream_token = lambda: 0 self.datastore.get_new_device_msgs_for_remote = lambda *VAR_15, **kargs: make_awaitable( ([], 0) ) self.datastore.delete_device_msgs_for_remote = lambda *VAR_15, **kargs: make_awaitable( None ) self.datastore.set_received_txn_response = lambda *VAR_15, **kwargs: make_awaitable( None ) def FUNC_4(self): self.room_members = [VAR_0, VAR_1] self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.started_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, timeout=20000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[VAR_3])]) self.assertEquals(self.event_source.get_current_key(), 1) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [ { "type": "m.typing", "room_id": VAR_3, "content": {"user_ids": [VAR_0.to_string()]}, } ], ) @override_config({"send_federation": True}) def FUNC_5(self): self.room_members = [VAR_0, VAR_2] self.get_success( self.handler.started_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, timeout=20000, ) ) VAR_19 = self.hs.get_http_client().put_json VAR_19.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=FUNC_0( "m.typing", VAR_5={ "room_id": VAR_3, "user_id": VAR_0.to_string(), "typing": True, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) def FUNC_6(self): self.room_members = [VAR_0, VAR_2] self.assertEquals(self.event_source.get_current_key(), 0) (VAR_20, VAR_21) = self.make_request( "PUT", "/_matrix/federation/v1/send/1000000", FUNC_1( "m.typing", VAR_5={ "room_id": VAR_3, "user_id": VAR_2.to_string(), "typing": True, }, ), federation_auth_origin=b"farm", ) self.assertEqual(VAR_21.code, 200) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[VAR_3])]) self.assertEquals(self.event_source.get_current_key(), 1) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [ { "type": "m.typing", "room_id": VAR_3, "content": {"user_ids": [VAR_2.to_string()]}, } ], ) @override_config({"send_federation": True}) def FUNC_7(self): self.room_members = [VAR_0, VAR_1, VAR_2] from synapse.handlers.typing import RoomMember VAR_22 = RoomMember(VAR_3, VAR_0.to_string()) self.handler._member_typing_until[VAR_22] = 1002000 self.handler._room_typing[VAR_3] = {VAR_0.to_string()} self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.stopped_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[VAR_3])]) VAR_19 = self.hs.get_http_client().put_json VAR_19.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=FUNC_0( "m.typing", VAR_5={ "room_id": VAR_3, "user_id": VAR_0.to_string(), "typing": False, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) self.assertEquals(self.event_source.get_current_key(), 1) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [{"type": "m.typing", "room_id": VAR_3, "content": {"user_ids": []}}], ) def FUNC_8(self): self.room_members = [VAR_0, VAR_1] self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.started_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, timeout=10000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[VAR_3])]) self.on_new_event.reset_mock() self.assertEquals(self.event_source.get_current_key(), 1) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [ { "type": "m.typing", "room_id": VAR_3, "content": {"user_ids": [VAR_0.to_string()]}, } ], ) self.reactor.pump([16]) self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[VAR_3])]) self.assertEquals(self.event_source.get_current_key(), 2) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=1) ) self.assertEquals( VAR_18[0], [{"type": "m.typing", "room_id": VAR_3, "content": {"user_ids": []}}], ) self.get_success( self.handler.started_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, timeout=10000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[VAR_3])]) self.on_new_event.reset_mock() self.assertEquals(self.event_source.get_current_key(), 3) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [ { "type": "m.typing", "room_id": VAR_3, "content": {"user_ids": [VAR_0.to_string()]}, } ], )
import json from mock import ANY, Mock, call from twisted.internet import defer from synapse.api.errors import AuthError from synapse.types import UserID, create_requester from tests import unittest from tests.test_utils import make_awaitable from tests.unittest import override_config from tests.utils import register_federation_servlets VAR_0 = UserID.from_string("@apple:test") VAR_1 = UserID.from_string("@banana:test") VAR_2 = UserID.from_string("@onion:farm") VAR_3 = "a-room" def FUNC_0(VAR_4, VAR_5, VAR_6="test"): return { "origin": VAR_6, "origin_server_ts": 1000000, "pdus": [], "edus": [{"edu_type": VAR_4, "content": VAR_5}], } def FUNC_1(VAR_4, VAR_5): return json.dumps(FUNC_0(VAR_4, VAR_5)).encode("utf8") class CLASS_0(unittest.HomeserverTestCase): VAR_7 = [register_federation_servlets] def FUNC_2(self, VAR_8, VAR_9): VAR_11 = Mock(spec=["verify_json_for_server"]) VAR_11.verify_json_for_server.return_value = defer.succeed(True) VAR_12 = Mock(spec=["put_json"]) VAR_12.put_json.return_value = defer.succeed((200, "OK")) VAR_8.pump((1000,)) VAR_10 = self.setup_test_homeserver( notifier=Mock(), federation_http_client=VAR_12, keyring=VAR_11, replication_streams={}, ) return VAR_10 def FUNC_3(self, VAR_8, VAR_9, VAR_10): VAR_13 = VAR_10.get_notifier() self.on_new_event = VAR_13.on_new_event self.handler = VAR_10.get_typing_handler() self.event_source = VAR_10.get_event_sources().sources["typing"] self.datastore = VAR_10.get_datastore() VAR_14 = { "destination": "", "retry_last_ts": 0, "retry_interval": 0, "failure_ts": None, } self.datastore.get_destination_retry_timings = Mock( return_value=defer.succeed(VAR_14) ) self.datastore.get_device_updates_by_remote = Mock( return_value=make_awaitable((0, [])) ) self.datastore.get_destination_last_successful_stream_ordering = Mock( return_value=make_awaitable(None) ) def FUNC_9(*VAR_15): return defer.succeed(None) self.datastore.get_received_txn_response = FUNC_9 self.room_members = [] async def FUNC_10(VAR_16, VAR_17): if VAR_17 not in [u.to_string() for u in self.room_members]: raise AuthError(401, "User is not in the room") return None VAR_10.get_auth().check_user_in_room = FUNC_10 def FUNC_11(VAR_16): return {VAR_22.domain for VAR_22 in self.room_members} self.datastore.get_joined_hosts_for_room = FUNC_11 async def FUNC_12(VAR_16): return {str(u) for u in self.room_members} self.datastore.get_users_in_room = FUNC_12 self.datastore.get_user_directory_stream_pos = Mock( side_effect=( lambda: make_awaitable(1) ) ) self.datastore.get_current_state_deltas = Mock(return_value=(0, None)) self.datastore.get_to_device_stream_token = lambda: 0 self.datastore.get_new_device_msgs_for_remote = lambda *VAR_15, **kargs: make_awaitable( ([], 0) ) self.datastore.delete_device_msgs_for_remote = lambda *VAR_15, **kargs: make_awaitable( None ) self.datastore.set_received_txn_response = lambda *VAR_15, **kwargs: make_awaitable( None ) def FUNC_4(self): self.room_members = [VAR_0, VAR_1] self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.started_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, timeout=20000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[VAR_3])]) self.assertEquals(self.event_source.get_current_key(), 1) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [ { "type": "m.typing", "room_id": VAR_3, "content": {"user_ids": [VAR_0.to_string()]}, } ], ) @override_config({"send_federation": True}) def FUNC_5(self): self.room_members = [VAR_0, VAR_2] self.get_success( self.handler.started_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, timeout=20000, ) ) VAR_19 = self.hs.get_federation_http_client().put_json VAR_19.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=FUNC_0( "m.typing", VAR_5={ "room_id": VAR_3, "user_id": VAR_0.to_string(), "typing": True, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) def FUNC_6(self): self.room_members = [VAR_0, VAR_2] self.assertEquals(self.event_source.get_current_key(), 0) (VAR_20, VAR_21) = self.make_request( "PUT", "/_matrix/federation/v1/send/1000000", FUNC_1( "m.typing", VAR_5={ "room_id": VAR_3, "user_id": VAR_2.to_string(), "typing": True, }, ), federation_auth_origin=b"farm", ) self.assertEqual(VAR_21.code, 200) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[VAR_3])]) self.assertEquals(self.event_source.get_current_key(), 1) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [ { "type": "m.typing", "room_id": VAR_3, "content": {"user_ids": [VAR_2.to_string()]}, } ], ) @override_config({"send_federation": True}) def FUNC_7(self): self.room_members = [VAR_0, VAR_1, VAR_2] from synapse.handlers.typing import RoomMember VAR_22 = RoomMember(VAR_3, VAR_0.to_string()) self.handler._member_typing_until[VAR_22] = 1002000 self.handler._room_typing[VAR_3] = {VAR_0.to_string()} self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.stopped_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[VAR_3])]) VAR_19 = self.hs.get_federation_http_client().put_json VAR_19.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=FUNC_0( "m.typing", VAR_5={ "room_id": VAR_3, "user_id": VAR_0.to_string(), "typing": False, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) self.assertEquals(self.event_source.get_current_key(), 1) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [{"type": "m.typing", "room_id": VAR_3, "content": {"user_ids": []}}], ) def FUNC_8(self): self.room_members = [VAR_0, VAR_1] self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.started_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, timeout=10000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[VAR_3])]) self.on_new_event.reset_mock() self.assertEquals(self.event_source.get_current_key(), 1) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [ { "type": "m.typing", "room_id": VAR_3, "content": {"user_ids": [VAR_0.to_string()]}, } ], ) self.reactor.pump([16]) self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[VAR_3])]) self.assertEquals(self.event_source.get_current_key(), 2) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=1) ) self.assertEquals( VAR_18[0], [{"type": "m.typing", "room_id": VAR_3, "content": {"user_ids": []}}], ) self.get_success( self.handler.started_typing( target_user=VAR_0, requester=create_requester(VAR_0), VAR_16=VAR_3, timeout=10000, ) ) self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[VAR_3])]) self.on_new_event.reset_mock() self.assertEquals(self.event_source.get_current_key(), 3) VAR_18 = self.get_success( self.event_source.get_new_events(room_ids=[VAR_3], from_key=0) ) self.assertEquals( VAR_18[0], [ { "type": "m.typing", "room_id": VAR_3, "content": {"user_ids": [VAR_0.to_string()]}, } ], )
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 25, 30, 31, 34, 35, 37, 38, 40, 41, 49, 50, 53, 54, 57, 59, 60, 63, 64, 67, 68, 70, 77, 79, 83, 85, 87, 98, 102, 106, 109, 111, 113, 118, 120, 123, 125, 128, 130, 133, 137, 139, 150, 153, 155, 164, 166, 181, 185, 194, 212, 215, 217, 232, 234, 249, 253, 254, 256, 260, 262, 270, 272, 290, 299, 302, 304, 313, 316, 331, 333, 335, 344, 345, 346, 355, 358, 373 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 25, 30, 31, 34, 35, 37, 38, 40, 41, 49, 50, 53, 54, 57, 59, 60, 63, 64, 67, 68, 70, 77, 79, 83, 85, 87, 98, 102, 106, 109, 111, 113, 118, 120, 123, 125, 128, 130, 133, 137, 139, 150, 153, 155, 164, 166, 181, 185, 194, 212, 215, 217, 232, 234, 249, 253, 254, 256, 260, 262, 270, 272, 290, 299, 302, 304, 313, 316, 331, 333, 335, 344, 345, 346, 355, 358, 373 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # Copyright 2017 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from prometheus_client import Counter from twisted.internet.error import AlreadyCalled, AlreadyCancelled from synapse.api.constants import EventTypes from synapse.logging import opentracing from synapse.metrics.background_process_metrics import run_as_background_process from synapse.push import PusherConfigException from synapse.types import RoomStreamToken from . import push_rule_evaluator, push_tools logger = logging.getLogger(__name__) http_push_processed_counter = Counter( "synapse_http_httppusher_http_pushes_processed", "Number of push notifications successfully sent", ) http_push_failed_counter = Counter( "synapse_http_httppusher_http_pushes_failed", "Number of push notifications which failed", ) http_badges_processed_counter = Counter( "synapse_http_httppusher_badge_updates_processed", "Number of badge updates successfully sent", ) http_badges_failed_counter = Counter( "synapse_http_httppusher_badge_updates_failed", "Number of badge updates which failed", ) class HttpPusher: INITIAL_BACKOFF_SEC = 1 # in seconds because that's what Twisted takes MAX_BACKOFF_SEC = 60 * 60 # This one's in ms because we compare it against the clock GIVE_UP_AFTER_MS = 24 * 60 * 60 * 1000 def __init__(self, hs, pusherdict): self.hs = hs self.store = self.hs.get_datastore() self.storage = self.hs.get_storage() self.clock = self.hs.get_clock() self.state_handler = self.hs.get_state_handler() self.user_id = pusherdict["user_name"] self.app_id = pusherdict["app_id"] self.app_display_name = pusherdict["app_display_name"] self.device_display_name = pusherdict["device_display_name"] self.pushkey = pusherdict["pushkey"] self.pushkey_ts = pusherdict["ts"] self.data = pusherdict["data"] self.last_stream_ordering = pusherdict["last_stream_ordering"] self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC self.failing_since = pusherdict["failing_since"] self.timed_call = None self._is_processing = False self._group_unread_count_by_room = hs.config.push_group_unread_count_by_room # This is the highest stream ordering we know it's safe to process. # When new events arrive, we'll be given a window of new events: we # should honour this rather than just looking for anything higher # because of potential out-of-order event serialisation. This starts # off as None though as we don't know any better. self.max_stream_ordering = None if "data" not in pusherdict: raise PusherConfigException("No 'data' key for HTTP pusher") self.data = pusherdict["data"] self.name = "%s/%s/%s" % ( pusherdict["user_name"], pusherdict["app_id"], pusherdict["pushkey"], ) if self.data is None: raise PusherConfigException("data can not be null for HTTP pusher") if "url" not in self.data: raise PusherConfigException("'url' required in data for HTTP pusher") self.url = self.data["url"] self.http_client = hs.get_proxied_http_client() self.data_minus_url = {} self.data_minus_url.update(self.data) del self.data_minus_url["url"] def on_started(self, should_check_for_notifs): """Called when this pusher has been started. Args: should_check_for_notifs (bool): Whether we should immediately check for push to send. Set to False only if it's known there is nothing to send """ if should_check_for_notifs: self._start_processing() def on_new_notifications(self, max_token: RoomStreamToken): # We just use the minimum stream ordering and ignore the vector clock # component. This is safe to do as long as we *always* ignore the vector # clock components. max_stream_ordering = max_token.stream self.max_stream_ordering = max( max_stream_ordering, self.max_stream_ordering or 0 ) self._start_processing() def on_new_receipts(self, min_stream_id, max_stream_id): # Note that the min here shouldn't be relied upon to be accurate. # We could check the receipts are actually m.read receipts here, # but currently that's the only type of receipt anyway... run_as_background_process("http_pusher.on_new_receipts", self._update_badge) async def _update_badge(self): # XXX as per https://github.com/matrix-org/matrix-doc/issues/2627, this seems # to be largely redundant. perhaps we can remove it. badge = await push_tools.get_badge_count( self.hs.get_datastore(), self.user_id, group_by_room=self._group_unread_count_by_room, ) await self._send_badge(badge) def on_timer(self): self._start_processing() def on_stop(self): if self.timed_call: try: self.timed_call.cancel() except (AlreadyCalled, AlreadyCancelled): pass self.timed_call = None def _start_processing(self): if self._is_processing: return run_as_background_process("httppush.process", self._process) async def _process(self): # we should never get here if we are already processing assert not self._is_processing try: self._is_processing = True # if the max ordering changes while we're running _unsafe_process, # call it again, and so on until we've caught up. while True: starting_max_ordering = self.max_stream_ordering try: await self._unsafe_process() except Exception: logger.exception("Exception processing notifs") if self.max_stream_ordering == starting_max_ordering: break finally: self._is_processing = False async def _unsafe_process(self): """ Looks for unset notifications and dispatch them, in order Never call this directly: use _process which will only allow this to run once per pusher. """ fn = self.store.get_unread_push_actions_for_user_in_range_for_http unprocessed = await fn( self.user_id, self.last_stream_ordering, self.max_stream_ordering ) logger.info( "Processing %i unprocessed push actions for %s starting at " "stream_ordering %s", len(unprocessed), self.name, self.last_stream_ordering, ) for push_action in unprocessed: with opentracing.start_active_span( "http-push", tags={ "authenticated_entity": self.user_id, "event_id": push_action["event_id"], "app_id": self.app_id, "app_display_name": self.app_display_name, }, ): processed = await self._process_one(push_action) if processed: http_push_processed_counter.inc() self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC self.last_stream_ordering = push_action["stream_ordering"] pusher_still_exists = await self.store.update_pusher_last_stream_ordering_and_success( self.app_id, self.pushkey, self.user_id, self.last_stream_ordering, self.clock.time_msec(), ) if not pusher_still_exists: # The pusher has been deleted while we were processing, so # lets just stop and return. self.on_stop() return if self.failing_since: self.failing_since = None await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) else: http_push_failed_counter.inc() if not self.failing_since: self.failing_since = self.clock.time_msec() await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) if ( self.failing_since and self.failing_since < self.clock.time_msec() - HttpPusher.GIVE_UP_AFTER_MS ): # we really only give up so that if the URL gets # fixed, we don't suddenly deliver a load # of old notifications. logger.warning( "Giving up on a notification to user %s, pushkey %s", self.user_id, self.pushkey, ) self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC self.last_stream_ordering = push_action["stream_ordering"] pusher_still_exists = await self.store.update_pusher_last_stream_ordering( self.app_id, self.pushkey, self.user_id, self.last_stream_ordering, ) if not pusher_still_exists: # The pusher has been deleted while we were processing, so # lets just stop and return. self.on_stop() return self.failing_since = None await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) else: logger.info("Push failed: delaying for %ds", self.backoff_delay) self.timed_call = self.hs.get_reactor().callLater( self.backoff_delay, self.on_timer ) self.backoff_delay = min( self.backoff_delay * 2, self.MAX_BACKOFF_SEC ) break async def _process_one(self, push_action): if "notify" not in push_action["actions"]: return True tweaks = push_rule_evaluator.tweaks_for_actions(push_action["actions"]) badge = await push_tools.get_badge_count( self.hs.get_datastore(), self.user_id, group_by_room=self._group_unread_count_by_room, ) event = await self.store.get_event(push_action["event_id"], allow_none=True) if event is None: return True # It's been redacted rejected = await self.dispatch_push(event, tweaks, badge) if rejected is False: return False if isinstance(rejected, list) or isinstance(rejected, tuple): for pk in rejected: if pk != self.pushkey: # for sanity, we only remove the pushkey if it # was the one we actually sent... logger.warning( ("Ignoring rejected pushkey %s because we didn't send it"), pk, ) else: logger.info("Pushkey %s was rejected: removing", pk) await self.hs.remove_pusher(self.app_id, pk, self.user_id) return True async def _build_notification_dict(self, event, tweaks, badge): priority = "low" if ( event.type == EventTypes.Encrypted or tweaks.get("highlight") or tweaks.get("sound") ): # HACK send our push as high priority only if it generates a sound, highlight # or may do so (i.e. is encrypted so has unknown effects). priority = "high" if self.data.get("format") == "event_id_only": d = { "notification": { "event_id": event.event_id, "room_id": event.room_id, "counts": {"unread": badge}, "prio": priority, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, } ], } } return d ctx = await push_tools.get_context_for_event( self.storage, self.state_handler, event, self.user_id ) d = { "notification": { "id": event.event_id, # deprecated: remove soon "event_id": event.event_id, "room_id": event.room_id, "type": event.type, "sender": event.user_id, "prio": priority, "counts": { "unread": badge, # 'missed_calls': 2 }, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, "tweaks": tweaks, } ], } } if event.type == "m.room.member" and event.is_state(): d["notification"]["membership"] = event.content["membership"] d["notification"]["user_is_target"] = event.state_key == self.user_id if self.hs.config.push_include_content and event.content: d["notification"]["content"] = event.content # We no longer send aliases separately, instead, we send the human # readable name of the room, which may be an alias. if "sender_display_name" in ctx and len(ctx["sender_display_name"]) > 0: d["notification"]["sender_display_name"] = ctx["sender_display_name"] if "name" in ctx and len(ctx["name"]) > 0: d["notification"]["room_name"] = ctx["name"] return d async def dispatch_push(self, event, tweaks, badge): notification_dict = await self._build_notification_dict(event, tweaks, badge) if not notification_dict: return [] try: resp = await self.http_client.post_json_get_json( self.url, notification_dict ) except Exception as e: logger.warning( "Failed to push event %s to %s: %s %s", event.event_id, self.name, type(e), e, ) return False rejected = [] if "rejected" in resp: rejected = resp["rejected"] return rejected async def _send_badge(self, badge): """ Args: badge (int): number of unread messages """ logger.debug("Sending updated badge count %d to %s", badge, self.name) d = { "notification": { "id": "", "type": None, "sender": "", "counts": {"unread": badge}, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, } ], } } try: await self.http_client.post_json_get_json(self.url, d) http_badges_processed_counter.inc() except Exception as e: logger.warning( "Failed to send badge count to %s: %s %s", self.name, type(e), e ) http_badges_failed_counter.inc()
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # Copyright 2017 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from prometheus_client import Counter from twisted.internet.error import AlreadyCalled, AlreadyCancelled from synapse.api.constants import EventTypes from synapse.logging import opentracing from synapse.metrics.background_process_metrics import run_as_background_process from synapse.push import PusherConfigException from synapse.types import RoomStreamToken from . import push_rule_evaluator, push_tools logger = logging.getLogger(__name__) http_push_processed_counter = Counter( "synapse_http_httppusher_http_pushes_processed", "Number of push notifications successfully sent", ) http_push_failed_counter = Counter( "synapse_http_httppusher_http_pushes_failed", "Number of push notifications which failed", ) http_badges_processed_counter = Counter( "synapse_http_httppusher_badge_updates_processed", "Number of badge updates successfully sent", ) http_badges_failed_counter = Counter( "synapse_http_httppusher_badge_updates_failed", "Number of badge updates which failed", ) class HttpPusher: INITIAL_BACKOFF_SEC = 1 # in seconds because that's what Twisted takes MAX_BACKOFF_SEC = 60 * 60 # This one's in ms because we compare it against the clock GIVE_UP_AFTER_MS = 24 * 60 * 60 * 1000 def __init__(self, hs, pusherdict): self.hs = hs self.store = self.hs.get_datastore() self.storage = self.hs.get_storage() self.clock = self.hs.get_clock() self.state_handler = self.hs.get_state_handler() self.user_id = pusherdict["user_name"] self.app_id = pusherdict["app_id"] self.app_display_name = pusherdict["app_display_name"] self.device_display_name = pusherdict["device_display_name"] self.pushkey = pusherdict["pushkey"] self.pushkey_ts = pusherdict["ts"] self.data = pusherdict["data"] self.last_stream_ordering = pusherdict["last_stream_ordering"] self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC self.failing_since = pusherdict["failing_since"] self.timed_call = None self._is_processing = False self._group_unread_count_by_room = hs.config.push_group_unread_count_by_room # This is the highest stream ordering we know it's safe to process. # When new events arrive, we'll be given a window of new events: we # should honour this rather than just looking for anything higher # because of potential out-of-order event serialisation. This starts # off as None though as we don't know any better. self.max_stream_ordering = None if "data" not in pusherdict: raise PusherConfigException("No 'data' key for HTTP pusher") self.data = pusherdict["data"] self.name = "%s/%s/%s" % ( pusherdict["user_name"], pusherdict["app_id"], pusherdict["pushkey"], ) if self.data is None: raise PusherConfigException("data can not be null for HTTP pusher") if "url" not in self.data: raise PusherConfigException("'url' required in data for HTTP pusher") self.url = self.data["url"] self.http_client = hs.get_proxied_blacklisted_http_client() self.data_minus_url = {} self.data_minus_url.update(self.data) del self.data_minus_url["url"] def on_started(self, should_check_for_notifs): """Called when this pusher has been started. Args: should_check_for_notifs (bool): Whether we should immediately check for push to send. Set to False only if it's known there is nothing to send """ if should_check_for_notifs: self._start_processing() def on_new_notifications(self, max_token: RoomStreamToken): # We just use the minimum stream ordering and ignore the vector clock # component. This is safe to do as long as we *always* ignore the vector # clock components. max_stream_ordering = max_token.stream self.max_stream_ordering = max( max_stream_ordering, self.max_stream_ordering or 0 ) self._start_processing() def on_new_receipts(self, min_stream_id, max_stream_id): # Note that the min here shouldn't be relied upon to be accurate. # We could check the receipts are actually m.read receipts here, # but currently that's the only type of receipt anyway... run_as_background_process("http_pusher.on_new_receipts", self._update_badge) async def _update_badge(self): # XXX as per https://github.com/matrix-org/matrix-doc/issues/2627, this seems # to be largely redundant. perhaps we can remove it. badge = await push_tools.get_badge_count( self.hs.get_datastore(), self.user_id, group_by_room=self._group_unread_count_by_room, ) await self._send_badge(badge) def on_timer(self): self._start_processing() def on_stop(self): if self.timed_call: try: self.timed_call.cancel() except (AlreadyCalled, AlreadyCancelled): pass self.timed_call = None def _start_processing(self): if self._is_processing: return run_as_background_process("httppush.process", self._process) async def _process(self): # we should never get here if we are already processing assert not self._is_processing try: self._is_processing = True # if the max ordering changes while we're running _unsafe_process, # call it again, and so on until we've caught up. while True: starting_max_ordering = self.max_stream_ordering try: await self._unsafe_process() except Exception: logger.exception("Exception processing notifs") if self.max_stream_ordering == starting_max_ordering: break finally: self._is_processing = False async def _unsafe_process(self): """ Looks for unset notifications and dispatch them, in order Never call this directly: use _process which will only allow this to run once per pusher. """ fn = self.store.get_unread_push_actions_for_user_in_range_for_http unprocessed = await fn( self.user_id, self.last_stream_ordering, self.max_stream_ordering ) logger.info( "Processing %i unprocessed push actions for %s starting at " "stream_ordering %s", len(unprocessed), self.name, self.last_stream_ordering, ) for push_action in unprocessed: with opentracing.start_active_span( "http-push", tags={ "authenticated_entity": self.user_id, "event_id": push_action["event_id"], "app_id": self.app_id, "app_display_name": self.app_display_name, }, ): processed = await self._process_one(push_action) if processed: http_push_processed_counter.inc() self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC self.last_stream_ordering = push_action["stream_ordering"] pusher_still_exists = await self.store.update_pusher_last_stream_ordering_and_success( self.app_id, self.pushkey, self.user_id, self.last_stream_ordering, self.clock.time_msec(), ) if not pusher_still_exists: # The pusher has been deleted while we were processing, so # lets just stop and return. self.on_stop() return if self.failing_since: self.failing_since = None await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) else: http_push_failed_counter.inc() if not self.failing_since: self.failing_since = self.clock.time_msec() await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) if ( self.failing_since and self.failing_since < self.clock.time_msec() - HttpPusher.GIVE_UP_AFTER_MS ): # we really only give up so that if the URL gets # fixed, we don't suddenly deliver a load # of old notifications. logger.warning( "Giving up on a notification to user %s, pushkey %s", self.user_id, self.pushkey, ) self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC self.last_stream_ordering = push_action["stream_ordering"] pusher_still_exists = await self.store.update_pusher_last_stream_ordering( self.app_id, self.pushkey, self.user_id, self.last_stream_ordering, ) if not pusher_still_exists: # The pusher has been deleted while we were processing, so # lets just stop and return. self.on_stop() return self.failing_since = None await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) else: logger.info("Push failed: delaying for %ds", self.backoff_delay) self.timed_call = self.hs.get_reactor().callLater( self.backoff_delay, self.on_timer ) self.backoff_delay = min( self.backoff_delay * 2, self.MAX_BACKOFF_SEC ) break async def _process_one(self, push_action): if "notify" not in push_action["actions"]: return True tweaks = push_rule_evaluator.tweaks_for_actions(push_action["actions"]) badge = await push_tools.get_badge_count( self.hs.get_datastore(), self.user_id, group_by_room=self._group_unread_count_by_room, ) event = await self.store.get_event(push_action["event_id"], allow_none=True) if event is None: return True # It's been redacted rejected = await self.dispatch_push(event, tweaks, badge) if rejected is False: return False if isinstance(rejected, list) or isinstance(rejected, tuple): for pk in rejected: if pk != self.pushkey: # for sanity, we only remove the pushkey if it # was the one we actually sent... logger.warning( ("Ignoring rejected pushkey %s because we didn't send it"), pk, ) else: logger.info("Pushkey %s was rejected: removing", pk) await self.hs.remove_pusher(self.app_id, pk, self.user_id) return True async def _build_notification_dict(self, event, tweaks, badge): priority = "low" if ( event.type == EventTypes.Encrypted or tweaks.get("highlight") or tweaks.get("sound") ): # HACK send our push as high priority only if it generates a sound, highlight # or may do so (i.e. is encrypted so has unknown effects). priority = "high" if self.data.get("format") == "event_id_only": d = { "notification": { "event_id": event.event_id, "room_id": event.room_id, "counts": {"unread": badge}, "prio": priority, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, } ], } } return d ctx = await push_tools.get_context_for_event( self.storage, self.state_handler, event, self.user_id ) d = { "notification": { "id": event.event_id, # deprecated: remove soon "event_id": event.event_id, "room_id": event.room_id, "type": event.type, "sender": event.user_id, "prio": priority, "counts": { "unread": badge, # 'missed_calls': 2 }, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, "tweaks": tweaks, } ], } } if event.type == "m.room.member" and event.is_state(): d["notification"]["membership"] = event.content["membership"] d["notification"]["user_is_target"] = event.state_key == self.user_id if self.hs.config.push_include_content and event.content: d["notification"]["content"] = event.content # We no longer send aliases separately, instead, we send the human # readable name of the room, which may be an alias. if "sender_display_name" in ctx and len(ctx["sender_display_name"]) > 0: d["notification"]["sender_display_name"] = ctx["sender_display_name"] if "name" in ctx and len(ctx["name"]) > 0: d["notification"]["room_name"] = ctx["name"] return d async def dispatch_push(self, event, tweaks, badge): notification_dict = await self._build_notification_dict(event, tweaks, badge) if not notification_dict: return [] try: resp = await self.http_client.post_json_get_json( self.url, notification_dict ) except Exception as e: logger.warning( "Failed to push event %s to %s: %s %s", event.event_id, self.name, type(e), e, ) return False rejected = [] if "rejected" in resp: rejected = resp["rejected"] return rejected async def _send_badge(self, badge): """ Args: badge (int): number of unread messages """ logger.debug("Sending updated badge count %d to %s", badge, self.name) d = { "notification": { "id": "", "type": None, "sender": "", "counts": {"unread": badge}, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, } ], } } try: await self.http_client.post_json_get_json(self.url, d) http_badges_processed_counter.inc() except Exception as e: logger.warning( "Failed to send badge count to %s: %s %s", self.name, type(e), e ) http_badges_failed_counter.inc()
open_redirect
{ "code": [ " self.http_client = hs.get_proxied_http_client()" ], "line_no": [ 103 ] }
{ "code": [ " self.http_client = hs.get_proxied_blacklisted_http_client()" ], "line_no": [ 103 ] }
import logging from prometheus_client import Counter from twisted.internet.error import AlreadyCalled, AlreadyCancelled from synapse.api.constants import EventTypes from synapse.logging import opentracing from synapse.metrics.background_process_metrics import run_as_background_process from synapse.push import PusherConfigException from synapse.types import RoomStreamToken from . import push_rule_evaluator, push_tools VAR_0 = logging.getLogger(__name__) VAR_1 = Counter( "synapse_http_httppusher_http_pushes_processed", "Number of push notifications successfully sent", ) VAR_2 = Counter( "synapse_http_httppusher_http_pushes_failed", "Number of push notifications which failed", ) VAR_3 = Counter( "synapse_http_httppusher_badge_updates_processed", "Number of VAR_17 updates successfully sent", ) VAR_4 = Counter( "synapse_http_httppusher_badge_updates_failed", "Number of VAR_17 updates which failed", ) class CLASS_0: VAR_5 = 1 # in seconds because that's what Twisted takes VAR_6 = 60 * 60 VAR_7 = 24 * 60 * 60 * 1000 def __init__(self, VAR_8, VAR_9): self.hs = VAR_8 self.store = self.hs.get_datastore() self.storage = self.hs.get_storage() self.clock = self.hs.get_clock() self.state_handler = self.hs.get_state_handler() self.user_id = VAR_9["user_name"] self.app_id = VAR_9["app_id"] self.app_display_name = VAR_9["app_display_name"] self.device_display_name = VAR_9["device_display_name"] self.pushkey = VAR_9["pushkey"] self.pushkey_ts = VAR_9["ts"] self.data = VAR_9["data"] self.last_stream_ordering = VAR_9["last_stream_ordering"] self.backoff_delay = CLASS_0.INITIAL_BACKOFF_SEC self.failing_since = VAR_9["failing_since"] self.timed_call = None self._is_processing = False self._group_unread_count_by_room = VAR_8.config.push_group_unread_count_by_room self.max_stream_ordering = None if "data" not in VAR_9: raise PusherConfigException("No 'data' key for HTTP pusher") self.data = VAR_9["data"] self.name = "%s/%s/%s" % ( VAR_9["user_name"], VAR_9["app_id"], VAR_9["pushkey"], ) if self.data is None: raise PusherConfigException("data can not be null for HTTP pusher") if "url" not in self.data: raise PusherConfigException("'url' required in data for HTTP pusher") self.url = self.data["url"] self.http_client = VAR_8.get_proxied_http_client() self.data_minus_url = {} self.data_minus_url.update(self.data) del self.data_minus_url["url"] def FUNC_0(self, VAR_10): if VAR_10: self._start_processing() def FUNC_1(self, VAR_11: RoomStreamToken): VAR_18 = VAR_11.stream self.max_stream_ordering = max( VAR_18, self.max_stream_ordering or 0 ) self._start_processing() def FUNC_2(self, VAR_12, VAR_13): run_as_background_process("http_pusher.on_new_receipts", self._update_badge) async def FUNC_3(self): VAR_17 = await push_tools.get_badge_count( self.hs.get_datastore(), self.user_id, group_by_room=self._group_unread_count_by_room, ) await self._send_badge(VAR_17) def FUNC_4(self): self._start_processing() def FUNC_5(self): if self.timed_call: try: self.timed_call.cancel() except (AlreadyCalled, AlreadyCancelled): pass self.timed_call = None def FUNC_6(self): if self._is_processing: return run_as_background_process("httppush.process", self._process) async def FUNC_7(self): assert not self._is_processing try: self._is_processing = True while True: VAR_27 = self.max_stream_ordering try: await self._unsafe_process() except Exception: VAR_0.exception("Exception processing notifs") if self.max_stream_ordering == VAR_27: break finally: self._is_processing = False async def FUNC_8(self): VAR_19 = self.store.get_unread_push_actions_for_user_in_range_for_http VAR_20 = await VAR_19( self.user_id, self.last_stream_ordering, self.max_stream_ordering ) VAR_0.info( "Processing %i VAR_20 push actions for %s starting at " "stream_ordering %s", len(VAR_20), self.name, self.last_stream_ordering, ) for VAR_14 in VAR_20: with opentracing.start_active_span( "http-push", tags={ "authenticated_entity": self.user_id, "event_id": VAR_14["event_id"], "app_id": self.app_id, "app_display_name": self.app_display_name, }, ): VAR_28 = await self._process_one(VAR_14) if VAR_28: VAR_1.inc() self.backoff_delay = CLASS_0.INITIAL_BACKOFF_SEC self.last_stream_ordering = VAR_14["stream_ordering"] VAR_29 = await self.store.update_pusher_last_stream_ordering_and_success( self.app_id, self.pushkey, self.user_id, self.last_stream_ordering, self.clock.time_msec(), ) if not VAR_29: self.on_stop() return if self.failing_since: self.failing_since = None await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) else: VAR_2.inc() if not self.failing_since: self.failing_since = self.clock.time_msec() await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) if ( self.failing_since and self.failing_since < self.clock.time_msec() - CLASS_0.GIVE_UP_AFTER_MS ): VAR_0.warning( "Giving up on a notification to user %s, pushkey %s", self.user_id, self.pushkey, ) self.backoff_delay = CLASS_0.INITIAL_BACKOFF_SEC self.last_stream_ordering = VAR_14["stream_ordering"] VAR_29 = await self.store.update_pusher_last_stream_ordering( self.app_id, self.pushkey, self.user_id, self.last_stream_ordering, ) if not VAR_29: self.on_stop() return self.failing_since = None await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) else: VAR_0.info("Push failed: delaying for %ds", self.backoff_delay) self.timed_call = self.hs.get_reactor().callLater( self.backoff_delay, self.on_timer ) self.backoff_delay = min( self.backoff_delay * 2, self.MAX_BACKOFF_SEC ) break async def FUNC_9(self, VAR_14): if "notify" not in VAR_14["actions"]: return True VAR_16 = push_rule_evaluator.tweaks_for_actions(VAR_14["actions"]) VAR_17 = await push_tools.get_badge_count( self.hs.get_datastore(), self.user_id, group_by_room=self._group_unread_count_by_room, ) VAR_15 = await self.store.get_event(VAR_14["event_id"], allow_none=True) if VAR_15 is None: return True # It's been redacted VAR_21 = await self.dispatch_push(VAR_15, VAR_16, VAR_17) if VAR_21 is False: return False if isinstance(VAR_21, list) or isinstance(VAR_21, tuple): for pk in VAR_21: if pk != self.pushkey: VAR_0.warning( ("Ignoring VAR_21 pushkey %s because we didn't send it"), pk, ) else: VAR_0.info("Pushkey %s was VAR_21: removing", pk) await self.hs.remove_pusher(self.app_id, pk, self.user_id) return True async def FUNC_10(self, VAR_15, VAR_16, VAR_17): VAR_22 = "low" if ( VAR_15.type == EventTypes.Encrypted or VAR_16.get("highlight") or VAR_16.get("sound") ): VAR_22 = "high" if self.data.get("format") == "event_id_only": VAR_24 = { "notification": { "event_id": VAR_15.event_id, "room_id": VAR_15.room_id, "counts": {"unread": VAR_17}, "prio": VAR_22, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, } ], } } return VAR_24 VAR_23 = await push_tools.get_context_for_event( self.storage, self.state_handler, VAR_15, self.user_id ) VAR_24 = { "notification": { "id": VAR_15.event_id, # deprecated: remove soon "event_id": VAR_15.event_id, "room_id": VAR_15.room_id, "type": VAR_15.type, "sender": VAR_15.user_id, "prio": VAR_22, "counts": { "unread": VAR_17, }, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, "tweaks": VAR_16, } ], } } if VAR_15.type == "m.room.member" and VAR_15.is_state(): VAR_24["notification"]["membership"] = VAR_15.content["membership"] VAR_24["notification"]["user_is_target"] = VAR_15.state_key == self.user_id if self.hs.config.push_include_content and VAR_15.content: VAR_24["notification"]["content"] = VAR_15.content if "sender_display_name" in VAR_23 and len(VAR_23["sender_display_name"]) > 0: VAR_24["notification"]["sender_display_name"] = VAR_23["sender_display_name"] if "name" in VAR_23 and len(VAR_23["name"]) > 0: VAR_24["notification"]["room_name"] = VAR_23["name"] return VAR_24 async def FUNC_11(self, VAR_15, VAR_16, VAR_17): VAR_25 = await self._build_notification_dict(VAR_15, VAR_16, VAR_17) if not VAR_25: return [] try: VAR_26 = await self.http_client.post_json_get_json( self.url, VAR_25 ) except Exception as e: VAR_0.warning( "Failed to push VAR_15 %s to %s: %s %s", VAR_15.event_id, self.name, type(e), e, ) return False VAR_21 = [] if "rejected" in VAR_26: VAR_21 = VAR_26["rejected"] return VAR_21 async def FUNC_12(self, VAR_17): VAR_0.debug("Sending updated VAR_17 count %VAR_24 to %s", VAR_17, self.name) VAR_24 = { "notification": { "id": "", "type": None, "sender": "", "counts": {"unread": VAR_17}, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, } ], } } try: await self.http_client.post_json_get_json(self.url, VAR_24) VAR_3.inc() except Exception as e: VAR_0.warning( "Failed to send VAR_17 count to %s: %s %s", self.name, type(e), e ) VAR_4.inc()
import logging from prometheus_client import Counter from twisted.internet.error import AlreadyCalled, AlreadyCancelled from synapse.api.constants import EventTypes from synapse.logging import opentracing from synapse.metrics.background_process_metrics import run_as_background_process from synapse.push import PusherConfigException from synapse.types import RoomStreamToken from . import push_rule_evaluator, push_tools VAR_0 = logging.getLogger(__name__) VAR_1 = Counter( "synapse_http_httppusher_http_pushes_processed", "Number of push notifications successfully sent", ) VAR_2 = Counter( "synapse_http_httppusher_http_pushes_failed", "Number of push notifications which failed", ) VAR_3 = Counter( "synapse_http_httppusher_badge_updates_processed", "Number of VAR_17 updates successfully sent", ) VAR_4 = Counter( "synapse_http_httppusher_badge_updates_failed", "Number of VAR_17 updates which failed", ) class CLASS_0: VAR_5 = 1 # in seconds because that's what Twisted takes VAR_6 = 60 * 60 VAR_7 = 24 * 60 * 60 * 1000 def __init__(self, VAR_8, VAR_9): self.hs = VAR_8 self.store = self.hs.get_datastore() self.storage = self.hs.get_storage() self.clock = self.hs.get_clock() self.state_handler = self.hs.get_state_handler() self.user_id = VAR_9["user_name"] self.app_id = VAR_9["app_id"] self.app_display_name = VAR_9["app_display_name"] self.device_display_name = VAR_9["device_display_name"] self.pushkey = VAR_9["pushkey"] self.pushkey_ts = VAR_9["ts"] self.data = VAR_9["data"] self.last_stream_ordering = VAR_9["last_stream_ordering"] self.backoff_delay = CLASS_0.INITIAL_BACKOFF_SEC self.failing_since = VAR_9["failing_since"] self.timed_call = None self._is_processing = False self._group_unread_count_by_room = VAR_8.config.push_group_unread_count_by_room self.max_stream_ordering = None if "data" not in VAR_9: raise PusherConfigException("No 'data' key for HTTP pusher") self.data = VAR_9["data"] self.name = "%s/%s/%s" % ( VAR_9["user_name"], VAR_9["app_id"], VAR_9["pushkey"], ) if self.data is None: raise PusherConfigException("data can not be null for HTTP pusher") if "url" not in self.data: raise PusherConfigException("'url' required in data for HTTP pusher") self.url = self.data["url"] self.http_client = VAR_8.get_proxied_blacklisted_http_client() self.data_minus_url = {} self.data_minus_url.update(self.data) del self.data_minus_url["url"] def FUNC_0(self, VAR_10): if VAR_10: self._start_processing() def FUNC_1(self, VAR_11: RoomStreamToken): VAR_18 = VAR_11.stream self.max_stream_ordering = max( VAR_18, self.max_stream_ordering or 0 ) self._start_processing() def FUNC_2(self, VAR_12, VAR_13): run_as_background_process("http_pusher.on_new_receipts", self._update_badge) async def FUNC_3(self): VAR_17 = await push_tools.get_badge_count( self.hs.get_datastore(), self.user_id, group_by_room=self._group_unread_count_by_room, ) await self._send_badge(VAR_17) def FUNC_4(self): self._start_processing() def FUNC_5(self): if self.timed_call: try: self.timed_call.cancel() except (AlreadyCalled, AlreadyCancelled): pass self.timed_call = None def FUNC_6(self): if self._is_processing: return run_as_background_process("httppush.process", self._process) async def FUNC_7(self): assert not self._is_processing try: self._is_processing = True while True: VAR_27 = self.max_stream_ordering try: await self._unsafe_process() except Exception: VAR_0.exception("Exception processing notifs") if self.max_stream_ordering == VAR_27: break finally: self._is_processing = False async def FUNC_8(self): VAR_19 = self.store.get_unread_push_actions_for_user_in_range_for_http VAR_20 = await VAR_19( self.user_id, self.last_stream_ordering, self.max_stream_ordering ) VAR_0.info( "Processing %i VAR_20 push actions for %s starting at " "stream_ordering %s", len(VAR_20), self.name, self.last_stream_ordering, ) for VAR_14 in VAR_20: with opentracing.start_active_span( "http-push", tags={ "authenticated_entity": self.user_id, "event_id": VAR_14["event_id"], "app_id": self.app_id, "app_display_name": self.app_display_name, }, ): VAR_28 = await self._process_one(VAR_14) if VAR_28: VAR_1.inc() self.backoff_delay = CLASS_0.INITIAL_BACKOFF_SEC self.last_stream_ordering = VAR_14["stream_ordering"] VAR_29 = await self.store.update_pusher_last_stream_ordering_and_success( self.app_id, self.pushkey, self.user_id, self.last_stream_ordering, self.clock.time_msec(), ) if not VAR_29: self.on_stop() return if self.failing_since: self.failing_since = None await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) else: VAR_2.inc() if not self.failing_since: self.failing_since = self.clock.time_msec() await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) if ( self.failing_since and self.failing_since < self.clock.time_msec() - CLASS_0.GIVE_UP_AFTER_MS ): VAR_0.warning( "Giving up on a notification to user %s, pushkey %s", self.user_id, self.pushkey, ) self.backoff_delay = CLASS_0.INITIAL_BACKOFF_SEC self.last_stream_ordering = VAR_14["stream_ordering"] VAR_29 = await self.store.update_pusher_last_stream_ordering( self.app_id, self.pushkey, self.user_id, self.last_stream_ordering, ) if not VAR_29: self.on_stop() return self.failing_since = None await self.store.update_pusher_failing_since( self.app_id, self.pushkey, self.user_id, self.failing_since ) else: VAR_0.info("Push failed: delaying for %ds", self.backoff_delay) self.timed_call = self.hs.get_reactor().callLater( self.backoff_delay, self.on_timer ) self.backoff_delay = min( self.backoff_delay * 2, self.MAX_BACKOFF_SEC ) break async def FUNC_9(self, VAR_14): if "notify" not in VAR_14["actions"]: return True VAR_16 = push_rule_evaluator.tweaks_for_actions(VAR_14["actions"]) VAR_17 = await push_tools.get_badge_count( self.hs.get_datastore(), self.user_id, group_by_room=self._group_unread_count_by_room, ) VAR_15 = await self.store.get_event(VAR_14["event_id"], allow_none=True) if VAR_15 is None: return True # It's been redacted VAR_21 = await self.dispatch_push(VAR_15, VAR_16, VAR_17) if VAR_21 is False: return False if isinstance(VAR_21, list) or isinstance(VAR_21, tuple): for pk in VAR_21: if pk != self.pushkey: VAR_0.warning( ("Ignoring VAR_21 pushkey %s because we didn't send it"), pk, ) else: VAR_0.info("Pushkey %s was VAR_21: removing", pk) await self.hs.remove_pusher(self.app_id, pk, self.user_id) return True async def FUNC_10(self, VAR_15, VAR_16, VAR_17): VAR_22 = "low" if ( VAR_15.type == EventTypes.Encrypted or VAR_16.get("highlight") or VAR_16.get("sound") ): VAR_22 = "high" if self.data.get("format") == "event_id_only": VAR_24 = { "notification": { "event_id": VAR_15.event_id, "room_id": VAR_15.room_id, "counts": {"unread": VAR_17}, "prio": VAR_22, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, } ], } } return VAR_24 VAR_23 = await push_tools.get_context_for_event( self.storage, self.state_handler, VAR_15, self.user_id ) VAR_24 = { "notification": { "id": VAR_15.event_id, # deprecated: remove soon "event_id": VAR_15.event_id, "room_id": VAR_15.room_id, "type": VAR_15.type, "sender": VAR_15.user_id, "prio": VAR_22, "counts": { "unread": VAR_17, }, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, "tweaks": VAR_16, } ], } } if VAR_15.type == "m.room.member" and VAR_15.is_state(): VAR_24["notification"]["membership"] = VAR_15.content["membership"] VAR_24["notification"]["user_is_target"] = VAR_15.state_key == self.user_id if self.hs.config.push_include_content and VAR_15.content: VAR_24["notification"]["content"] = VAR_15.content if "sender_display_name" in VAR_23 and len(VAR_23["sender_display_name"]) > 0: VAR_24["notification"]["sender_display_name"] = VAR_23["sender_display_name"] if "name" in VAR_23 and len(VAR_23["name"]) > 0: VAR_24["notification"]["room_name"] = VAR_23["name"] return VAR_24 async def FUNC_11(self, VAR_15, VAR_16, VAR_17): VAR_25 = await self._build_notification_dict(VAR_15, VAR_16, VAR_17) if not VAR_25: return [] try: VAR_26 = await self.http_client.post_json_get_json( self.url, VAR_25 ) except Exception as e: VAR_0.warning( "Failed to push VAR_15 %s to %s: %s %s", VAR_15.event_id, self.name, type(e), e, ) return False VAR_21 = [] if "rejected" in VAR_26: VAR_21 = VAR_26["rejected"] return VAR_21 async def FUNC_12(self, VAR_17): VAR_0.debug("Sending updated VAR_17 count %VAR_24 to %s", VAR_17, self.name) VAR_24 = { "notification": { "id": "", "type": None, "sender": "", "counts": {"unread": VAR_17}, "devices": [ { "app_id": self.app_id, "pushkey": self.pushkey, "pushkey_ts": int(self.pushkey_ts / 1000), "data": self.data_minus_url, } ], } } try: await self.http_client.post_json_get_json(self.url, VAR_24) VAR_3.inc() except Exception as e: VAR_0.warning( "Failed to send VAR_17 count to %s: %s %s", self.name, type(e), e ) VAR_4.inc()
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 27, 29, 31, 36, 41, 46, 51, 52, 56, 57, 59, 79, 80, 81, 82, 83, 84, 86, 90, 96, 99, 107, 110, 118, 120, 121, 122, 124, 129, 131, 132, 133, 134, 136, 138, 139, 146, 149, 157, 161, 163, 165, 167, 170, 171, 182, 189, 194, 202, 214, 227, 228, 231, 244, 250, 251, 252, 267, 268, 271, 285, 289, 296, 303, 307, 308, 316, 324, 325, 327, 346, 350, 361, 379, 380, 381, 386, 388, 410, 441, 109, 110, 111, 112, 113, 114, 115, 184, 185, 186, 187, 188, 412, 413, 414, 415 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 27, 29, 31, 36, 41, 46, 51, 52, 56, 57, 59, 79, 80, 81, 82, 83, 84, 86, 90, 96, 99, 107, 110, 118, 120, 121, 122, 124, 129, 131, 132, 133, 134, 136, 138, 139, 146, 149, 157, 161, 163, 165, 167, 170, 171, 182, 189, 194, 202, 214, 227, 228, 231, 244, 250, 251, 252, 267, 268, 271, 285, 289, 296, 303, 307, 308, 316, 324, 325, 327, 346, 350, 361, 379, 380, 381, 386, 388, 410, 441, 109, 110, 111, 112, 113, 114, 115, 184, 185, 186, 187, 188, 412, 413, 414, 415 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2020 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from mock import Mock from twisted.internet import defer from synapse.rest import admin from synapse.rest.client.v1 import login, room from tests.replication._base import BaseMultiWorkerStreamTestCase logger = logging.getLogger(__name__) class PusherShardTestCase(BaseMultiWorkerStreamTestCase): """Checks pusher sharding works """ servlets = [ admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, ] def prepare(self, reactor, clock, hs): # Register a user who sends a message that we'll get notified about self.other_user_id = self.register_user("otheruser", "pass") self.other_access_token = self.login("otheruser", "pass") def default_config(self): conf = super().default_config() conf["start_pushers"] = False return conf def _create_pusher_and_send_msg(self, localpart): # Create a user that will get push notifications user_id = self.register_user(localpart, "pass") access_token = self.login(localpart, "pass") # Register a pusher user_dict = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_dict.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "https://push.example.com/push"}, ) ) self.pump() # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other user joins self.helper.join( room=room, user=self.other_user_id, tok=self.other_access_token ) # The other user sends some messages response = self.helper.send(room, body="Hi!", tok=self.other_access_token) event_id = response["event_id"] return event_id def test_send_push_single_worker(self): """Test that registration works when using a pusher worker. """ http_client_mock = Mock(spec_set=["post_json_get_json"]) http_client_mock.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", {"start_pushers": True}, proxied_http_client=http_client_mock, ) event_id = self._create_pusher_and_send_msg("user") # Advance time a bit, so the pusher will register something has happened self.pump() http_client_mock.post_json_get_json.assert_called_once() self.assertEqual( http_client_mock.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( event_id, http_client_mock.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], ) def test_send_push_multiple_workers(self): """Test that registration works when using sharded pusher workers. """ http_client_mock1 = Mock(spec_set=["post_json_get_json"]) http_client_mock1.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", { "start_pushers": True, "worker_name": "pusher1", "pusher_instances": ["pusher1", "pusher2"], }, proxied_http_client=http_client_mock1, ) http_client_mock2 = Mock(spec_set=["post_json_get_json"]) http_client_mock2.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", { "start_pushers": True, "worker_name": "pusher2", "pusher_instances": ["pusher1", "pusher2"], }, proxied_http_client=http_client_mock2, ) # We choose a user name that we know should go to pusher1. event_id = self._create_pusher_and_send_msg("user2") # Advance time a bit, so the pusher will register something has happened self.pump() http_client_mock1.post_json_get_json.assert_called_once() http_client_mock2.post_json_get_json.assert_not_called() self.assertEqual( http_client_mock1.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( event_id, http_client_mock1.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], ) http_client_mock1.post_json_get_json.reset_mock() http_client_mock2.post_json_get_json.reset_mock() # Now we choose a user name that we know should go to pusher2. event_id = self._create_pusher_and_send_msg("user4") # Advance time a bit, so the pusher will register something has happened self.pump() http_client_mock1.post_json_get_json.assert_not_called() http_client_mock2.post_json_get_json.assert_called_once() self.assertEqual( http_client_mock2.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( event_id, http_client_mock2.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], )
# -*- coding: utf-8 -*- # Copyright 2020 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from mock import Mock from twisted.internet import defer from synapse.rest import admin from synapse.rest.client.v1 import login, room from tests.replication._base import BaseMultiWorkerStreamTestCase logger = logging.getLogger(__name__) class PusherShardTestCase(BaseMultiWorkerStreamTestCase): """Checks pusher sharding works """ servlets = [ admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, ] def prepare(self, reactor, clock, hs): # Register a user who sends a message that we'll get notified about self.other_user_id = self.register_user("otheruser", "pass") self.other_access_token = self.login("otheruser", "pass") def default_config(self): conf = super().default_config() conf["start_pushers"] = False return conf def _create_pusher_and_send_msg(self, localpart): # Create a user that will get push notifications user_id = self.register_user(localpart, "pass") access_token = self.login(localpart, "pass") # Register a pusher user_dict = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_dict.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "https://push.example.com/push"}, ) ) self.pump() # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other user joins self.helper.join( room=room, user=self.other_user_id, tok=self.other_access_token ) # The other user sends some messages response = self.helper.send(room, body="Hi!", tok=self.other_access_token) event_id = response["event_id"] return event_id def test_send_push_single_worker(self): """Test that registration works when using a pusher worker. """ http_client_mock = Mock(spec_set=["post_json_get_json"]) http_client_mock.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", {"start_pushers": True}, proxied_blacklisted_http_client=http_client_mock, ) event_id = self._create_pusher_and_send_msg("user") # Advance time a bit, so the pusher will register something has happened self.pump() http_client_mock.post_json_get_json.assert_called_once() self.assertEqual( http_client_mock.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( event_id, http_client_mock.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], ) def test_send_push_multiple_workers(self): """Test that registration works when using sharded pusher workers. """ http_client_mock1 = Mock(spec_set=["post_json_get_json"]) http_client_mock1.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", { "start_pushers": True, "worker_name": "pusher1", "pusher_instances": ["pusher1", "pusher2"], }, proxied_blacklisted_http_client=http_client_mock1, ) http_client_mock2 = Mock(spec_set=["post_json_get_json"]) http_client_mock2.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", { "start_pushers": True, "worker_name": "pusher2", "pusher_instances": ["pusher1", "pusher2"], }, proxied_blacklisted_http_client=http_client_mock2, ) # We choose a user name that we know should go to pusher1. event_id = self._create_pusher_and_send_msg("user2") # Advance time a bit, so the pusher will register something has happened self.pump() http_client_mock1.post_json_get_json.assert_called_once() http_client_mock2.post_json_get_json.assert_not_called() self.assertEqual( http_client_mock1.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( event_id, http_client_mock1.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], ) http_client_mock1.post_json_get_json.reset_mock() http_client_mock2.post_json_get_json.reset_mock() # Now we choose a user name that we know should go to pusher2. event_id = self._create_pusher_and_send_msg("user4") # Advance time a bit, so the pusher will register something has happened self.pump() http_client_mock1.post_json_get_json.assert_not_called() http_client_mock2.post_json_get_json.assert_called_once() self.assertEqual( http_client_mock2.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( event_id, http_client_mock2.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], )
open_redirect
{ "code": [ " proxied_http_client=http_client_mock,", " proxied_http_client=http_client_mock1,", " proxied_http_client=http_client_mock2," ], "line_no": [ 101, 136, 151 ] }
{ "code": [ " proxied_blacklisted_http_client=http_client_mock,", " proxied_blacklisted_http_client=http_client_mock1,", " proxied_blacklisted_http_client=http_client_mock2," ], "line_no": [ 101, 136, 151 ] }
import logging from mock import Mock from twisted.internet import defer from synapse.rest import admin from synapse.rest.client.v1 import login, VAR_11 from tests.replication._base import BaseMultiWorkerStreamTestCase VAR_0 = logging.getLogger(__name__) class CLASS_0(BaseMultiWorkerStreamTestCase): VAR_1 = [ admin.register_servlets_for_client_rest_resource, VAR_11.register_servlets, login.register_servlets, ] def FUNC_0(self, VAR_2, VAR_3, VAR_4): self.other_user_id = self.register_user("otheruser", "pass") self.other_access_token = self.login("otheruser", "pass") def FUNC_1(self): VAR_6 = super().default_config() VAR_6["start_pushers"] = False return VAR_6 def FUNC_2(self, VAR_5): VAR_7 = self.register_user(VAR_5, "pass") VAR_8 = self.login(VAR_5, "pass") VAR_9 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_8) ) VAR_10 = VAR_9.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_7=user_id, VAR_8=VAR_10, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "https://push.example.com/push"}, ) ) self.pump() room = self.helper.create_room_as(VAR_7, tok=VAR_8) self.helper.join( VAR_11=room, user=self.other_user_id, tok=self.other_access_token ) VAR_12 = self.helper.send(VAR_11, body="Hi!", tok=self.other_access_token) VAR_13 = VAR_12["event_id"] return VAR_13 def FUNC_3(self): VAR_14 = Mock(spec_set=["post_json_get_json"]) VAR_14.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", {"start_pushers": True}, proxied_http_client=VAR_14, ) VAR_13 = self._create_pusher_and_send_msg("user") self.pump() VAR_14.post_json_get_json.assert_called_once() self.assertEqual( VAR_14.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( VAR_13, VAR_14.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], ) def FUNC_4(self): VAR_15 = Mock(spec_set=["post_json_get_json"]) VAR_15.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", { "start_pushers": True, "worker_name": "pusher1", "pusher_instances": ["pusher1", "pusher2"], }, proxied_http_client=VAR_15, ) VAR_16 = Mock(spec_set=["post_json_get_json"]) VAR_16.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", { "start_pushers": True, "worker_name": "pusher2", "pusher_instances": ["pusher1", "pusher2"], }, proxied_http_client=VAR_16, ) VAR_13 = self._create_pusher_and_send_msg("user2") self.pump() VAR_15.post_json_get_json.assert_called_once() VAR_16.post_json_get_json.assert_not_called() self.assertEqual( VAR_15.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( VAR_13, VAR_15.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], ) VAR_15.post_json_get_json.reset_mock() VAR_16.post_json_get_json.reset_mock() VAR_13 = self._create_pusher_and_send_msg("user4") self.pump() VAR_15.post_json_get_json.assert_not_called() VAR_16.post_json_get_json.assert_called_once() self.assertEqual( VAR_16.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( VAR_13, VAR_16.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], )
import logging from mock import Mock from twisted.internet import defer from synapse.rest import admin from synapse.rest.client.v1 import login, VAR_11 from tests.replication._base import BaseMultiWorkerStreamTestCase VAR_0 = logging.getLogger(__name__) class CLASS_0(BaseMultiWorkerStreamTestCase): VAR_1 = [ admin.register_servlets_for_client_rest_resource, VAR_11.register_servlets, login.register_servlets, ] def FUNC_0(self, VAR_2, VAR_3, VAR_4): self.other_user_id = self.register_user("otheruser", "pass") self.other_access_token = self.login("otheruser", "pass") def FUNC_1(self): VAR_6 = super().default_config() VAR_6["start_pushers"] = False return VAR_6 def FUNC_2(self, VAR_5): VAR_7 = self.register_user(VAR_5, "pass") VAR_8 = self.login(VAR_5, "pass") VAR_9 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_8) ) VAR_10 = VAR_9.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_7=user_id, VAR_8=VAR_10, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "https://push.example.com/push"}, ) ) self.pump() room = self.helper.create_room_as(VAR_7, tok=VAR_8) self.helper.join( VAR_11=room, user=self.other_user_id, tok=self.other_access_token ) VAR_12 = self.helper.send(VAR_11, body="Hi!", tok=self.other_access_token) VAR_13 = VAR_12["event_id"] return VAR_13 def FUNC_3(self): VAR_14 = Mock(spec_set=["post_json_get_json"]) VAR_14.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", {"start_pushers": True}, proxied_blacklisted_http_client=VAR_14, ) VAR_13 = self._create_pusher_and_send_msg("user") self.pump() VAR_14.post_json_get_json.assert_called_once() self.assertEqual( VAR_14.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( VAR_13, VAR_14.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], ) def FUNC_4(self): VAR_15 = Mock(spec_set=["post_json_get_json"]) VAR_15.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", { "start_pushers": True, "worker_name": "pusher1", "pusher_instances": ["pusher1", "pusher2"], }, proxied_blacklisted_http_client=VAR_15, ) VAR_16 = Mock(spec_set=["post_json_get_json"]) VAR_16.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", { "start_pushers": True, "worker_name": "pusher2", "pusher_instances": ["pusher1", "pusher2"], }, proxied_blacklisted_http_client=VAR_16, ) VAR_13 = self._create_pusher_and_send_msg("user2") self.pump() VAR_15.post_json_get_json.assert_called_once() VAR_16.post_json_get_json.assert_not_called() self.assertEqual( VAR_15.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( VAR_13, VAR_15.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], ) VAR_15.post_json_get_json.reset_mock() VAR_16.post_json_get_json.reset_mock() VAR_13 = self._create_pusher_and_send_msg("user4") self.pump() VAR_15.post_json_get_json.assert_not_called() VAR_16.post_json_get_json.assert_called_once() self.assertEqual( VAR_16.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( VAR_13, VAR_16.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], )
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 23, 25, 27, 28, 32, 38, 40, 43, 48, 50, 53, 54, 59, 73, 75, 76, 78, 79, 83, 84, 87, 89, 97, 103, 105, 106, 108, 120, 128, 138, 143, 153, 154, 156, 157, 159, 172, 175, 176, 178, 179, 181, 194, 30, 31, 91, 92, 122, 123 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 23, 25, 27, 28, 32, 38, 40, 43, 48, 50, 53, 54, 59, 73, 75, 76, 78, 79, 83, 84, 87, 89, 97, 103, 105, 106, 108, 120, 128, 138, 143, 153, 154, 156, 157, 159, 172, 175, 176, 178, 179, 181, 194, 30, 31, 91, 92, 122, 123 ]
4CWE-601
#!/usr/bin/env python # -*- coding: utf-8 -*- # # webgateway/views.py - django application view handling functions # # Copyright (c) 2007-2020 Glencoe Software, Inc. All rights reserved. # # This software is distributed under the terms described by the LICENCE file # you can find at the root of the distribution bundle, which states you are # free to use it only for non commercial purposes. # If the file is missing please request a copy by contacting # jason@glencoesoftware.com. # # Author: Carlos Neves <carlos(at)glencoesoftware.com> import re import json import base64 import warnings from functools import wraps import omero import omero.clients from past.builtins import unicode from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseServerError, JsonResponse, HttpResponseForbidden, ) from django.http import ( HttpResponseRedirect, HttpResponseNotAllowed, Http404, StreamingHttpResponse, HttpResponseNotFound, ) from django.views.decorators.http import require_POST from django.views.decorators.debug import sensitive_post_parameters from django.utils.decorators import method_decorator from django.core.urlresolvers import reverse, NoReverseMatch from django.conf import settings from wsgiref.util import FileWrapper from omero.rtypes import rlong, unwrap from omero.constants.namespaces import NSBULKANNOTATIONS from .util import points_string_to_XY_list, xy_list_to_bbox from .plategrid import PlateGrid from omeroweb.version import omeroweb_buildyear as build_year from .marshal import imageMarshal, shapeMarshal, rgb_int2rgba from django.contrib.staticfiles.templatetags.staticfiles import static from django.views.generic import View from django.shortcuts import render from omeroweb.webadmin.forms import LoginForm from omeroweb.decorators import get_client_ip, is_public_user from omeroweb.webadmin.webadmin_utils import upgradeCheck try: from hashlib import md5 except Exception: from md5 import md5 try: import long except ImportError: long = int from io import BytesIO import tempfile from omero import ApiUsageException from omero.util.decorators import timeit, TimeIt from omeroweb.httprsp import HttpJavascriptResponse, HttpJavascriptResponseServerError from omeroweb.connector import Server import glob # from models import StoredConnection from omeroweb.webgateway.webgateway_cache import ( webgateway_cache, CacheBase, webgateway_tempfile, ) import logging import os import traceback import time import zipfile import shutil from omeroweb.decorators import login_required, ConnCleaningHttpResponse from omeroweb.connector import Connector from omeroweb.webgateway.util import zip_archived_files, LUTS_IN_PNG from omeroweb.webgateway.util import get_longs, getIntOrDefault cache = CacheBase() logger = logging.getLogger(__name__) try: from PIL import Image from PIL import ImageDraw except Exception: # pragma: nocover try: import Image import ImageDraw except Exception: logger.error("No Pillow installed") try: import numpy numpyInstalled = True except ImportError: logger.error("No numpy installed") numpyInstalled = False def index(request): """ /webgateway/ index placeholder """ return HttpResponse("Welcome to webgateway") def _safestr(s): return unicode(s).encode("utf-8") class UserProxy(object): """ Represents the current user of the connection, with methods delegating to the connection itself. """ def __init__(self, blitzcon): """ Initialises the User proxy with the L{omero.gateway.BlitzGateway} connection @param blitzcon: connection @type blitzcon: L{omero.gateway.BlitzGateway} """ self._blitzcon = blitzcon self.loggedIn = False def logIn(self): """ Sets the loggedIn Flag to True """ self.loggedIn = True def isAdmin(self): """ True if the current user is an admin @return: True if the current user is an admin @rtype: Boolean """ return self._blitzcon.isAdmin() def canBeAdmin(self): """ True if the current user can be admin @return: True if the current user can be admin @rtype: Boolean """ return self._blitzcon.canBeAdmin() def getId(self): """ Returns the ID of the current user @return: User ID @rtype: Long """ return self._blitzcon.getUserId() def getName(self): """ Returns the Name of the current user @return: User Name @rtype: String """ return self._blitzcon.getUser().omeName def getFirstName(self): """ Returns the first name of the current user @return: First Name @rtype: String """ return self._blitzcon.getUser().firstName or self.getName() # def getPreferences (self): # return self._blitzcon._user.getPreferences() # # def getUserObj (self): # return self._blitzcon._user # # class SessionCB (object): # def _log (self, what, c): # logger.debug('CONN:%s %s:%d:%s' % (what, c._user, os.getpid(), # c._sessionUuid)) # # def create (self, c): # self._log('create',c) # # def join (self, c): # self._log('join',c) # # def close (self, c): # self._log('close',c) # _session_cb = SessionCB() def _split_channel_info(rchannels): """ Splits the request query channel information for images into a sequence of channels, window ranges and channel colors. @param rchannels: The request string with channel info. E.g 1|100:505$0000FF,-2,3|620:3879$FF0000 @type rchannels: String @return: E.g. [1, -2, 3] [[100.0, 505.0], (None, None), [620.0, 3879.0]] [u'0000FF', None, u'FF0000'] @rtype: tuple of 3 lists """ channels = [] windows = [] colors = [] for chan in rchannels.split(","): # chan 1|12:1386r$0000FF chan = chan.split("|", 1) # chan ['1', '12:1386r$0000FF'] t = chan[0].strip() # t = '1' color = None # Not normally used... if t.find("$") >= 0: t, color = t.split("$") try: channels.append(int(t)) ch_window = (None, None) if len(chan) > 1: t = chan[1].strip() # t = '12:1386r$0000FF' if t.find("$") >= 0: t, color = t.split("$", 1) # color = '0000FF' # t = 12:1386 t = t.split(":") if len(t) == 2: try: ch_window = [float(x) for x in t] except ValueError: pass windows.append(ch_window) colors.append(color) except ValueError: pass logger.debug(str(channels) + "," + str(windows) + "," + str(colors)) return channels, windows, colors def getImgDetailsFromReq(request, as_string=False): """ Break the GET information from the request object into details on how to render the image. The following keys are recognized: z - Z axis position t - T axis position q - Quality set (0,0..1,0) m - Model (g for greyscale, c for color) p - Projection (see blitz_gateway.ImageWrapper.PROJECTIONS for keys) x - X position (for now based on top/left offset on the browser window) y - Y position (same as above) c - a comma separated list of channels to be rendered (start index 1) - format for each entry [-]ID[|wndst:wndend][#HEXCOLOR][,...] zm - the zoom setting (as a percentual value) @param request: http request with keys above @param as_string: If True, return a string representation of the rendering details @return: A dict or String representation of rendering details above. @rtype: Dict or String """ r = request.GET rv = {} for k in ("z", "t", "q", "m", "zm", "x", "y", "p"): if k in r: rv[k] = r[k] if "c" in r: rv["c"] = [] ci = _split_channel_info(r["c"]) logger.debug(ci) for i in range(len(ci[0])): # a = abs channel, i = channel, s = window start, e = window end, # c = color rv["c"].append( { "a": abs(ci[0][i]), "i": ci[0][i], "s": ci[1][i][0], "e": ci[1][i][1], "c": ci[2][i], } ) if as_string: return "&".join(["%s=%s" % (x[0], x[1]) for x in rv.items()]) return rv @login_required() def render_birds_eye_view(request, iid, size=None, conn=None, **kwargs): """ Returns an HttpResponse wrapped jpeg with the rendered bird's eye view for image 'iid'. We now use a thumbnail for performance. #10626 @param request: http request @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} connection @param size: Maximum size of the longest side of the resulting bird's eye view. @return: http response containing jpeg """ return render_thumbnail(request, iid, w=size, **kwargs) def _render_thumbnail(request, iid, w=None, h=None, conn=None, _defcb=None, **kwargs): """ Returns a jpeg with the rendered thumbnail for image 'iid' @param request: http request @param iid: Image ID @param w: Thumbnail max width. 96 by default @param h: Thumbnail max height @return: http response containing jpeg """ server_id = request.session["connector"].server_id server_settings = request.session.get("server_settings", {}).get("browser", {}) defaultSize = server_settings.get("thumb_default_size", 96) direct = True if w is None: size = (defaultSize,) else: if h is None: size = (int(w),) else: size = (int(w), int(h)) if size == (defaultSize,): direct = False user_id = conn.getUserId() z = getIntOrDefault(request, "z", None) t = getIntOrDefault(request, "t", None) rdefId = getIntOrDefault(request, "rdefId", None) # TODO - cache handles rdefId jpeg_data = webgateway_cache.getThumb(request, server_id, user_id, iid, size) if jpeg_data is None: prevent_cache = False img = conn.getObject("Image", iid) if img is None: logger.debug("(b)Image %s not found..." % (str(iid))) if _defcb: jpeg_data = _defcb(size=size) prevent_cache = True else: raise Http404("Failed to render thumbnail") else: jpeg_data = img.getThumbnail( size=size, direct=direct, rdefId=rdefId, z=z, t=t ) if jpeg_data is None: logger.debug("(c)Image %s not found..." % (str(iid))) if _defcb: jpeg_data = _defcb(size=size) prevent_cache = True else: raise Http404("Failed to render thumbnail") else: prevent_cache = img._thumbInProgress if not prevent_cache: webgateway_cache.setThumb(request, server_id, user_id, iid, jpeg_data, size) else: pass return jpeg_data @login_required() def render_thumbnail(request, iid, w=None, h=None, conn=None, _defcb=None, **kwargs): """ Returns an HttpResponse wrapped jpeg with the rendered thumbnail for image 'iid' @param request: http request @param iid: Image ID @param w: Thumbnail max width. 96 by default @param h: Thumbnail max height @return: http response containing jpeg """ jpeg_data = _render_thumbnail( request=request, iid=iid, w=w, h=h, conn=conn, _defcb=_defcb, **kwargs ) rsp = HttpResponse(jpeg_data, content_type="image/jpeg") return rsp @login_required() def render_roi_thumbnail(request, roiId, w=None, h=None, conn=None, **kwargs): """ For the given ROI, choose the shape to render (first time-point, mid z-section) then render a region around that shape, scale to width and height (or default size) and draw the shape on to the region """ server_id = request.session["connector"].server_id # need to find the z indices of the first shape in T result = conn.getRoiService().findByRoi(long(roiId), None, conn.SERVICE_OPTS) if result is None or result.rois is None or len(result.rois) == 0: raise Http404 for roi in result.rois: imageId = roi.image.id.val shapes = roi.copyShapes() shapes = [s for s in shapes if s is not None] if len(shapes) == 0: raise Http404("No Shapes found for ROI %s" % roiId) pi = _get_prepared_image(request, imageId, server_id=server_id, conn=conn) if pi is None: raise Http404 image, compress_quality = pi shape = None # if only single shape, use it... if len(shapes) == 1: shape = shapes[0] else: default_t = image.getDefaultT() default_z = image.getDefaultZ() # find shapes on default Z/T plane def_shapes = [ s for s in shapes if unwrap(s.getTheT()) is None or unwrap(s.getTheT()) == default_t ] if len(def_shapes) == 1: shape = def_shapes[0] else: def_shapes = [ s for s in def_shapes if unwrap(s.getTheZ()) is None or unwrap(s.getTheZ()) == default_z ] if len(def_shapes) > 0: shape = def_shapes[0] # otherwise pick first shape if shape is None and len(shapes) > 0: shape = shapes[0] return get_shape_thumbnail(request, conn, image, shape, compress_quality) @login_required() def render_shape_thumbnail(request, shapeId, w=None, h=None, conn=None, **kwargs): """ For the given Shape, redner a region around that shape, scale to width and height (or default size) and draw the shape on to the region. """ server_id = request.session["connector"].server_id # need to find the z indices of the first shape in T params = omero.sys.Parameters() params.map = {"id": rlong(shapeId)} shape = conn.getQueryService().findByQuery( "select s from Shape s join fetch s.roi where s.id = :id", params, conn.SERVICE_OPTS, ) if shape is None: raise Http404 imageId = shape.roi.image.id.val pi = _get_prepared_image(request, imageId, server_id=server_id, conn=conn) if pi is None: raise Http404 image, compress_quality = pi return get_shape_thumbnail(request, conn, image, shape, compress_quality) def get_shape_thumbnail(request, conn, image, s, compress_quality): """ Render a region around the specified Shape, scale to width and height (or default size) and draw the shape on to the region. Returns jpeg data. @param image: ImageWrapper @param s: omero.model.Shape """ MAX_WIDTH = 250 color = request.GET.get("color", "fff") colours = { "f00": (255, 0, 0), "0f0": (0, 255, 0), "00f": (0, 0, 255), "ff0": (255, 255, 0), "fff": (255, 255, 255), "000": (0, 0, 0), } lineColour = colours["f00"] if color in colours: lineColour = colours[color] # used for padding if we go outside the image area bg_color = (221, 221, 221) bBox = None # bounding box: (x, y, w, h) shape = {} theT = unwrap(s.getTheT()) theT = theT if theT is not None else image.getDefaultT() theZ = unwrap(s.getTheZ()) theZ = theZ if theZ is not None else image.getDefaultZ() if type(s) == omero.model.RectangleI: shape["type"] = "Rectangle" shape["x"] = s.getX().getValue() shape["y"] = s.getY().getValue() shape["width"] = s.getWidth().getValue() shape["height"] = s.getHeight().getValue() bBox = (shape["x"], shape["y"], shape["width"], shape["height"]) elif type(s) == omero.model.MaskI: shape["type"] = "Mask" shape["x"] = s.getX().getValue() shape["y"] = s.getY().getValue() shape["width"] = s.getWidth().getValue() shape["height"] = s.getHeight().getValue() bBox = (shape["x"], shape["y"], shape["width"], shape["height"]) # TODO: support for mask elif type(s) == omero.model.EllipseI: shape["type"] = "Ellipse" shape["x"] = int(s.getX().getValue()) shape["y"] = int(s.getY().getValue()) shape["radiusX"] = int(s.getRadiusX().getValue()) shape["radiusY"] = int(s.getRadiusY().getValue()) bBox = ( shape["x"] - shape["radiusX"], shape["y"] - shape["radiusY"], 2 * shape["radiusX"], 2 * shape["radiusY"], ) elif type(s) == omero.model.PolylineI: shape["type"] = "PolyLine" shape["xyList"] = points_string_to_XY_list(s.getPoints().getValue()) bBox = xy_list_to_bbox(shape["xyList"]) elif type(s) == omero.model.LineI: shape["type"] = "Line" shape["x1"] = int(s.getX1().getValue()) shape["x2"] = int(s.getX2().getValue()) shape["y1"] = int(s.getY1().getValue()) shape["y2"] = int(s.getY2().getValue()) x = min(shape["x1"], shape["x2"]) y = min(shape["y1"], shape["y2"]) bBox = ( x, y, max(shape["x1"], shape["x2"]) - x, max(shape["y1"], shape["y2"]) - y, ) elif type(s) == omero.model.PointI: shape["type"] = "Point" shape["x"] = s.getX().getValue() shape["y"] = s.getY().getValue() bBox = (shape["x"] - 50, shape["y"] - 50, 100, 100) elif type(s) == omero.model.PolygonI: shape["type"] = "Polygon" shape["xyList"] = points_string_to_XY_list(s.getPoints().getValue()) bBox = xy_list_to_bbox(shape["xyList"]) elif type(s) == omero.model.LabelI: shape["type"] = "Label" shape["x"] = s.getX().getValue() shape["y"] = s.getY().getValue() bBox = (shape["x"] - 50, shape["y"] - 50, 100, 100) else: logger.debug("Shape type not supported: %s" % str(type(s))) # we want to render a region larger than the bounding box x, y, w, h = bBox # make the aspect ratio (w/h) = 3/2 requiredWidth = max(w, h * 3 // 2) requiredHeight = requiredWidth * 2 // 3 # make the rendered region 1.5 times larger than the bounding box newW = int(requiredWidth * 1.5) newH = int(requiredHeight * 1.5) # Don't want the region to be smaller than the thumbnail dimensions if newW < MAX_WIDTH: newW = MAX_WIDTH newH = newW * 2 // 3 # Don't want the region to be bigger than a 'Big Image'! def getConfigValue(key): try: return conn.getConfigService().getConfigValue(key) except Exception: logger.warn( "webgateway: get_shape_thumbnail() could not get" " Config-Value for %s" % key ) pass max_plane_width = getConfigValue("omero.pixeldata.max_plane_width") max_plane_height = getConfigValue("omero.pixeldata.max_plane_height") if ( max_plane_width is None or max_plane_height is None or (newW > int(max_plane_width)) or (newH > int(max_plane_height)) ): # generate dummy image to return dummy = Image.new("RGB", (MAX_WIDTH, MAX_WIDTH * 2 // 3), bg_color) draw = ImageDraw.Draw(dummy) draw.text((10, 30), "Shape too large to \ngenerate thumbnail", fill=(255, 0, 0)) rv = BytesIO() dummy.save(rv, "jpeg", quality=90) return HttpResponse(rv.getvalue(), content_type="image/jpeg") xOffset = (newW - w) // 2 yOffset = (newH - h) // 2 newX = int(x - xOffset) newY = int(y - yOffset) # Need to check if any part of our region is outside the image. (assume # that SOME of the region is within the image!) sizeX = image.getSizeX() sizeY = image.getSizeY() left_xs, right_xs, top_xs, bottom_xs = 0, 0, 0, 0 if newX < 0: newW = newW + newX left_xs = abs(newX) newX = 0 if newY < 0: newH = newH + newY top_xs = abs(newY) newY = 0 if newW + newX > sizeX: right_xs = (newW + newX) - sizeX newW = newW - right_xs if newH + newY > sizeY: bottom_xs = (newH + newY) - sizeY newH = newH - bottom_xs # now we should be getting the correct region jpeg_data = image.renderJpegRegion( theZ, theT, newX, newY, newW, newH, level=None, compression=compress_quality ) img = Image.open(BytesIO(jpeg_data)) # add back on the xs we were forced to trim if left_xs != 0 or right_xs != 0 or top_xs != 0 or bottom_xs != 0: jpg_w, jpg_h = img.size xs_w = jpg_w + right_xs + left_xs xs_h = jpg_h + bottom_xs + top_xs xs_image = Image.new("RGB", (xs_w, xs_h), bg_color) xs_image.paste(img, (left_xs, top_xs)) img = xs_image # we have our full-sized region. Need to resize to thumbnail. current_w, current_h = img.size factor = float(MAX_WIDTH) / current_w resizeH = int(current_h * factor) img = img.resize((MAX_WIDTH, resizeH)) draw = ImageDraw.Draw(img) if shape["type"] == "Rectangle": rectX = int(xOffset * factor) rectY = int(yOffset * factor) rectW = int((w + xOffset) * factor) rectH = int((h + yOffset) * factor) draw.rectangle((rectX, rectY, rectW, rectH), outline=lineColour) # hack to get line width of 2 draw.rectangle((rectX - 1, rectY - 1, rectW + 1, rectH + 1), outline=lineColour) elif shape["type"] == "Line": lineX1 = (shape["x1"] - newX + left_xs) * factor lineX2 = (shape["x2"] - newX + left_xs) * factor lineY1 = (shape["y1"] - newY + top_xs) * factor lineY2 = (shape["y2"] - newY + top_xs) * factor draw.line((lineX1, lineY1, lineX2, lineY2), fill=lineColour, width=2) elif shape["type"] == "Ellipse": rectX = int(xOffset * factor) rectY = int(yOffset * factor) rectW = int((w + xOffset) * factor) rectH = int((h + yOffset) * factor) draw.ellipse((rectX, rectY, rectW, rectH), outline=lineColour) # hack to get line width of 2 draw.ellipse((rectX - 1, rectY - 1, rectW + 1, rectH + 1), outline=lineColour) elif shape["type"] == "Point": point_radius = 2 rectX = (MAX_WIDTH // 2) - point_radius rectY = int(resizeH // 2) - point_radius rectW = rectX + (point_radius * 2) rectH = rectY + (point_radius * 2) draw.ellipse((rectX, rectY, rectW, rectH), outline=lineColour) # hack to get line width of 2 draw.ellipse((rectX - 1, rectY - 1, rectW + 1, rectH + 1), outline=lineColour) elif "xyList" in shape: # resizedXY = [(int(x*factor), int(y*factor)) # for (x,y) in shape['xyList']] def resizeXY(xy): x, y = xy return ( int((x - newX + left_xs) * factor), int((y - newY + top_xs) * factor), ) resizedXY = [resizeXY(xy) for xy in shape["xyList"]] # doesn't support 'width' of line # draw.polygon(resizedXY, outline=lineColour) x2 = y2 = None for line in range(1, len(resizedXY)): x1, y1 = resizedXY[line - 1] x2, y2 = resizedXY[line] draw.line((x1, y1, x2, y2), fill=lineColour, width=2) start_x, start_y = resizedXY[0] if shape["type"] != "PolyLine": # Seems possible to have Polygon with only 1 point! if x2 is None: x2 = start_x + 1 # This will create a visible dot if y2 is None: y2 = start_y + 1 draw.line((x2, y2, start_x, start_y), fill=lineColour, width=2) rv = BytesIO() compression = 0.9 try: img.save(rv, "jpeg", quality=int(compression * 100)) jpeg = rv.getvalue() finally: rv.close() return HttpResponse(jpeg, content_type="image/jpeg") @login_required() def render_shape_mask(request, shapeId, conn=None, **kwargs): """ Returns mask as a png (supports transparency) """ if not numpyInstalled: raise NotImplementedError("numpy not installed") params = omero.sys.Parameters() params.map = {"id": rlong(shapeId)} shape = conn.getQueryService().findByQuery( "select s from Shape s where s.id = :id", params, conn.SERVICE_OPTS ) if shape is None: raise Http404("Shape ID: %s not found" % shapeId) width = int(shape.getWidth().getValue()) height = int(shape.getHeight().getValue()) color = unwrap(shape.getFillColor()) fill = (255, 255, 0, 255) if color is not None: color = rgb_int2rgba(color) fill = (color[0], color[1], color[2], int(color[3] * 255)) mask_packed = shape.getBytes() # convert bytearray into something we can use intarray = numpy.fromstring(mask_packed, dtype=numpy.uint8) binarray = numpy.unpackbits(intarray) # Couldn't get the 'proper' way of doing this to work, # TODO: look at this again later. Faster than simple way below: # E.g. takes ~2 seconds for 1984 x 1984 mask # pixels = "" # steps = len(binarray) / 8 # for i in range(steps): # b = binarray[i*8: (i+1)*8] # pixels += struct.pack("8B", b[0], b[1], b[2], b[3], b[4], # b[5], b[6], b[7]) # for b in binarray: # pixels += struct.pack("1B", b) # im = Image.frombytes("1", size=(width, height), data=pixels) # Simple approach - Just set each pixel in turn # E.g. takes ~12 seconds for 1984 x 1984 mask with most pixels '1' # Or ~5 seconds for same size mask with most pixels "0" img = Image.new("RGBA", size=(width, height), color=(0, 0, 0, 0)) x = 0 y = 0 for pix in binarray: if pix == 1: img.putpixel((x, y), fill) x += 1 if x > width - 1: x = 0 y += 1 rv = BytesIO() # return a png (supports transparency) img.save(rv, "png", quality=int(100)) png = rv.getvalue() return HttpResponse(png, content_type="image/png") def _get_signature_from_request(request): """ returns a string that identifies this image, along with the settings passed on the request. Useful for using as img identifier key, for prepared image. @param request: http request @return: String """ r = request.GET rv = r.get("m", "_") + r.get("p", "_") + r.get("c", "_") + r.get("q", "_") return rv def _get_maps_enabled(request, name, sizeC=0): """ Parses 'maps' query string from request """ codomains = None if "maps" in request: map_json = request["maps"] codomains = [] try: # If coming from request string, need to load -> json if isinstance(map_json, (unicode, str)): map_json = json.loads(map_json) sizeC = max(len(map_json), sizeC) for c in range(sizeC): enabled = None if len(map_json) > c: m = map_json[c].get(name) # If None, no change to saved status if m is not None: enabled = m.get("enabled") in (True, "true") codomains.append(enabled) except Exception: logger.debug("Invalid json for query ?maps=%s" % map_json) codomains = None return codomains def _get_prepared_image( request, iid, server_id=None, conn=None, saveDefs=False, retry=True ): """ Fetches the Image object for image 'iid' and prepares it according to the request query, setting the channels, rendering model and projection arguments. The compression level is parsed and returned too. For parameters in request, see L{getImgDetailsFromReq} @param request: http request @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} connection @param saveDefs: Try to save the rendering settings, default z and t. @param retry: Try an extra attempt at this method @return: Tuple (L{omero.gateway.ImageWrapper} image, quality) """ r = request.GET logger.debug( "Preparing Image:%r saveDefs=%r " "retry=%r request=%r conn=%s" % (iid, saveDefs, retry, r, str(conn)) ) img = conn.getObject("Image", iid) if img is None: return invert_flags = None if "maps" in r: reverses = _get_maps_enabled(r, "reverse", img.getSizeC()) # 'reverse' is now deprecated (5.4.0). Also check for 'invert' invert_flags = _get_maps_enabled(r, "inverted", img.getSizeC()) # invert is True if 'invert' OR 'reverse' is enabled if reverses is not None and invert_flags is not None: invert_flags = [ z[0] if z[0] is not None else z[1] for z in zip(invert_flags, reverses) ] try: # quantization maps (just applied, not saved at the moment) qm = [m.get("quantization") for m in json.loads(r["maps"])] img.setQuantizationMaps(qm) except Exception: logger.debug("Failed to set quantization maps") if "c" in r: logger.debug("c=" + r["c"]) activechannels, windows, colors = _split_channel_info(r["c"]) allchannels = range(1, img.getSizeC() + 1) # If saving, apply to all channels if saveDefs and not img.setActiveChannels( allchannels, windows, colors, invert_flags ): logger.debug("Something bad happened while setting the active channels...") # Save the active/inactive state of the channels if not img.setActiveChannels(activechannels, windows, colors, invert_flags): logger.debug("Something bad happened while setting the active channels...") if r.get("m", None) == "g": img.setGreyscaleRenderingModel() elif r.get("m", None) == "c": img.setColorRenderingModel() # projection 'intmax' OR 'intmax|5:25' p = r.get("p", None) pStart, pEnd = None, None if p is not None and len(p.split("|")) > 1: p, startEnd = p.split("|", 1) try: pStart, pEnd = [int(s) for s in startEnd.split(":")] except ValueError: pass img.setProjection(p) img.setProjectionRange(pStart, pEnd) img.setInvertedAxis(bool(r.get("ia", "0") == "1")) compress_quality = r.get("q", None) if saveDefs: "z" in r and img.setDefaultZ(long(r["z"]) - 1) "t" in r and img.setDefaultT(long(r["t"]) - 1) img.saveDefaults() return (img, compress_quality) @login_required() def render_image_region(request, iid, z, t, conn=None, **kwargs): """ Returns a jpeg of the OMERO image, rendering only a region specified in query string as region=x,y,width,height. E.g. region=0,512,256,256 Rendering settings can be specified in the request parameters. @param request: http request @param iid: image ID @param z: Z index @param t: T index @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping jpeg """ server_id = request.session["connector"].server_id # if the region=x,y,w,h is not parsed correctly to give 4 ints then we # simply provide whole image plane. # alternatively, could return a 404? # if h == None: # return render_image(request, iid, z, t, server_id=None, _conn=None, # **kwargs) pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn) if pi is None: raise Http404 img, compress_quality = pi tile = request.GET.get("tile", None) region = request.GET.get("region", None) level = None if tile: try: img._prepareRenderingEngine() w, h = img._re.getTileSize() levels = img._re.getResolutionLevels() - 1 zxyt = tile.split(",") # if tile size is given respect it if len(zxyt) > 4: tile_size = [int(zxyt[3]), int(zxyt[4])] tile_defaults = [w, h] max_tile_length = 1024 try: max_tile_length = int( conn.getConfigService().getConfigValue( "omero.pixeldata.max_tile_length" ) ) except Exception: pass for i, tile_length in enumerate(tile_size): # use default tile size if <= 0 if tile_length <= 0: tile_size[i] = tile_defaults[i] # allow no bigger than max_tile_length if tile_length > max_tile_length: tile_size[i] = max_tile_length w, h = tile_size v = int(zxyt[0]) if v < 0: msg = "Invalid resolution level %s < 0" % v logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) if levels == 0: # non pyramid file if v > 0: msg = "Invalid resolution level %s, non pyramid file" % v logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) else: level = None else: level = levels - v if level < 0: msg = ( "Invalid resolution level, \ %s > number of available levels %s " % (v, levels) ) logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) x = int(zxyt[1]) * w y = int(zxyt[2]) * h except Exception: msg = "malformed tile argument, tile=%s" % tile logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) elif region: try: xywh = region.split(",") x = int(xywh[0]) y = int(xywh[1]) w = int(xywh[2]) h = int(xywh[3]) except Exception: msg = "malformed region argument, region=%s" % region logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) else: return HttpResponseBadRequest("tile or region argument required") # region details in request are used as key for caching. jpeg_data = webgateway_cache.getImage(request, server_id, img, z, t) if jpeg_data is None: jpeg_data = img.renderJpegRegion( z, t, x, y, w, h, level=level, compression=compress_quality ) if jpeg_data is None: raise Http404 webgateway_cache.setImage(request, server_id, img, z, t, jpeg_data) rsp = HttpResponse(jpeg_data, content_type="image/jpeg") return rsp @login_required() def render_image(request, iid, z=None, t=None, conn=None, **kwargs): """ Renders the image with id {{iid}} at {{z}} and {{t}} as jpeg. Many options are available from the request dict. See L{getImgDetailsFromReq} for list. I am assuming a single Pixels object on image with image-Id='iid'. May be wrong @param request: http request @param iid: image ID @param z: Z index @param t: T index @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping jpeg """ server_id = request.session["connector"].server_id pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn) if pi is None: raise Http404 img, compress_quality = pi jpeg_data = webgateway_cache.getImage(request, server_id, img, z, t) if jpeg_data is None: jpeg_data = img.renderJpeg(z, t, compression=compress_quality) if jpeg_data is None: raise Http404 webgateway_cache.setImage(request, server_id, img, z, t, jpeg_data) format = request.GET.get("format", "jpeg") rsp = HttpResponse(jpeg_data, content_type="image/jpeg") if "download" in kwargs and kwargs["download"]: if format == "png": # convert jpeg data to png... i = Image.open(BytesIO(jpeg_data)) output = BytesIO() i.save(output, "png") jpeg_data = output.getvalue() output.close() rsp = HttpResponse(jpeg_data, content_type="image/png") elif format == "tif": # convert jpeg data to TIFF i = Image.open(BytesIO(jpeg_data)) output = BytesIO() i.save(output, "tiff") jpeg_data = output.getvalue() output.close() rsp = HttpResponse(jpeg_data, content_type="image/tiff") fileName = img.getName() try: fileName = fileName.decode("utf8") except AttributeError: pass # python 3 fileName = fileName.replace(",", ".").replace(" ", "_") rsp["Content-Type"] = "application/force-download" rsp["Content-Length"] = len(jpeg_data) rsp["Content-Disposition"] = "attachment; filename=%s.%s" % (fileName, format) return rsp @login_required() def render_ome_tiff(request, ctx, cid, conn=None, **kwargs): """ Renders the OME-TIFF representation of the image(s) with id cid in ctx (i)mage, (d)ataset, or (p)roject. For multiple images export, images that require pixels pyramid (big images) will be silently skipped. If exporting a single big image or if all images in a multple image export are big, a 404 will be triggered. A request parameter dryrun can be passed to return the count of images that would actually be exported. @param request: http request @param ctx: 'p' or 'd' or 'i' @param cid: Project, Dataset or Image ID @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping the tiff (or zip for multiple files), or redirect to temp file/zip if dryrun is True, returns count of images that would be exported """ server_id = request.session["connector"].server_id imgs = [] if ctx == "p": obj = conn.getObject("Project", cid) if obj is None: raise Http404 for d in obj.listChildren(): imgs.extend(list(d.listChildren())) name = obj.getName() elif ctx == "d": obj = conn.getObject("Dataset", cid) if obj is None: raise Http404 imgs.extend(list(obj.listChildren())) selection = list(filter(None, request.GET.get("selection", "").split(","))) if len(selection) > 0: logger.debug(selection) logger.debug(imgs) imgs = [x for x in imgs if str(x.getId()) in selection] logger.debug(imgs) if len(imgs) == 0: raise Http404 name = "%s-%s" % (obj.getParent().getName(), obj.getName()) elif ctx == "w": obj = conn.getObject("Well", cid) if obj is None: raise Http404 imgs.extend([x.getImage() for x in obj.listChildren()]) plate = obj.getParent() coord = "%s%s" % ( plate.getRowLabels()[obj.row], plate.getColumnLabels()[obj.column], ) name = "%s-%s-%s" % (plate.getParent().getName(), plate.getName(), coord) else: obj = conn.getObject("Image", cid) if obj is None: raise Http404 imgs.append(obj) imgs = [x for x in imgs if not x.requiresPixelsPyramid()] if request.GET.get("dryrun", False): rv = json.dumps(len(imgs)) c = request.GET.get("callback", None) if c is not None and not kwargs.get("_internal", False): rv = "%s(%s)" % (c, rv) return HttpJavascriptResponse(rv) if len(imgs) == 0: raise Http404 if len(imgs) == 1: obj = imgs[0] key = ( "_".join((str(x.getId()) for x in obj.getAncestry())) + "_" + str(obj.getId()) + "_ome_tiff" ) # total name len <= 255, 9 is for .ome.tiff fnamemax = 255 - len(str(obj.getId())) - 10 objname = obj.getName()[:fnamemax] fpath, rpath, fobj = webgateway_tempfile.new( str(obj.getId()) + "-" + objname + ".ome.tiff", key=key ) if fobj is True: # already exists return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) tiff_data = webgateway_cache.getOmeTiffImage(request, server_id, imgs[0]) if tiff_data is None: try: tiff_data = imgs[0].exportOmeTiff() except Exception: logger.debug("Failed to export image (2)", exc_info=True) tiff_data = None if tiff_data is None: webgateway_tempfile.abort(fpath) raise Http404 webgateway_cache.setOmeTiffImage(request, server_id, imgs[0], tiff_data) if fobj is None: rsp = HttpResponse(tiff_data, content_type="image/tiff") rsp["Content-Disposition"] = 'attachment; filename="%s.ome.tiff"' % ( str(obj.getId()) + "-" + objname ) rsp["Content-Length"] = len(tiff_data) return rsp else: fobj.write(tiff_data) fobj.close() return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) else: try: img_ids = "+".join((str(x.getId()) for x in imgs)).encode("utf-8") key = ( "_".join((str(x.getId()) for x in imgs[0].getAncestry())) + "_" + md5(img_ids).hexdigest() + "_ome_tiff_zip" ) fpath, rpath, fobj = webgateway_tempfile.new(name + ".zip", key=key) if fobj is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) logger.debug(fpath) if fobj is None: fobj = BytesIO() zobj = zipfile.ZipFile(fobj, "w", zipfile.ZIP_STORED) for obj in imgs: tiff_data = webgateway_cache.getOmeTiffImage(request, server_id, obj) if tiff_data is None: tiff_data = obj.exportOmeTiff() if tiff_data is None: continue webgateway_cache.setOmeTiffImage(request, server_id, obj, tiff_data) # While ZIP itself doesn't have the 255 char limit for # filenames, the FS where these get unarchived might, so trim # names # total name len <= 255, 9 is for .ome.tiff fnamemax = 255 - len(str(obj.getId())) - 10 objname = obj.getName()[:fnamemax] zobj.writestr(str(obj.getId()) + "-" + objname + ".ome.tiff", tiff_data) zobj.close() if fpath is None: zip_data = fobj.getvalue() rsp = HttpResponse(zip_data, content_type="application/zip") rsp["Content-Disposition"] = 'attachment; filename="%s.zip"' % name rsp["Content-Length"] = len(zip_data) return rsp except Exception: logger.debug(traceback.format_exc()) raise return HttpResponseRedirect(settings.STATIC_URL + "webgateway/tfiles/" + rpath) @login_required() def render_movie(request, iid, axis, pos, conn=None, **kwargs): """ Renders a movie from the image with id iid @param request: http request @param iid: Image ID @param axis: Movie frames are along 'z' or 't' dimension. String @param pos: The T index (for z axis) or Z index (for t axis) @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping the file, or redirect to temp file """ server_id = request.session["connector"].server_id try: # Prepare a filename we'll use for temp cache, and check if file is # already there opts = {} opts["format"] = "video/" + request.GET.get("format", "quicktime") opts["fps"] = int(request.GET.get("fps", 4)) opts["minsize"] = (512, 512, "Black") ext = ".avi" key = "%s-%s-%s-%d-%s-%s" % ( iid, axis, pos, opts["fps"], _get_signature_from_request(request), request.GET.get("format", "quicktime"), ) pos = int(pos) pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn) if pi is None: raise Http404 img, compress_quality = pi fpath, rpath, fobj = webgateway_tempfile.new(img.getName() + ext, key=key) logger.debug(fpath, rpath, fobj) if fobj is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) # os.path.join(rpath, img.getName() + ext)) if "optsCB" in kwargs: opts.update(kwargs["optsCB"](img)) opts.update(kwargs.get("opts", {})) logger.debug( "rendering movie for img %s with axis %s, pos %i and opts %s" % (iid, axis, pos, opts) ) # fpath, rpath = webgateway_tempfile.newdir() if fpath is None: fo, fn = tempfile.mkstemp() else: fn = fpath # os.path.join(fpath, img.getName()) if axis.lower() == "z": dext, mimetype = img.createMovie( fn, 0, img.getSizeZ() - 1, pos - 1, pos - 1, opts ) else: dext, mimetype = img.createMovie( fn, pos - 1, pos - 1, 0, img.getSizeT() - 1, opts ) if dext is None and mimetype is None: # createMovie is currently only available on 4.1_custom # https://trac.openmicroscopy.org/ome/ticket/3857 raise Http404 if fpath is None: movie = open(fn).read() os.close(fo) rsp = HttpResponse(movie, content_type=mimetype) rsp["Content-Disposition"] = 'attachment; filename="%s"' % ( img.getName() + ext ) rsp["Content-Length"] = len(movie) return rsp else: fobj.close() # shutil.move(fn, fn + ext) return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) # os.path.join(rpath, img.getName() + ext)) except Exception: logger.debug(traceback.format_exc()) raise @login_required() def render_split_channel(request, iid, z, t, conn=None, **kwargs): """ Renders a split channel view of the image with id {{iid}} at {{z}} and {{t}} as jpeg. Many options are available from the request dict. Requires Pillow to be installed on the server. @param request: http request @param iid: Image ID @param z: Z index @param t: T index @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping a jpeg """ server_id = request.session["connector"].server_id pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn) if pi is None: raise Http404 img, compress_quality = pi compress_quality = compress_quality and float(compress_quality) or 0.9 jpeg_data = webgateway_cache.getSplitChannelImage(request, server_id, img, z, t) if jpeg_data is None: jpeg_data = img.renderSplitChannel(z, t, compression=compress_quality) if jpeg_data is None: raise Http404 webgateway_cache.setSplitChannelImage(request, server_id, img, z, t, jpeg_data) rsp = HttpResponse(jpeg_data, content_type="image/jpeg") return rsp def debug(f): """ Decorator for adding debugging functionality to methods. @param f: The function to wrap @return: The wrapped function """ @wraps(f) def wrap(request, *args, **kwargs): debug = request.GET.getlist("debug") if "slow" in debug: time.sleep(5) if "fail" in debug: raise Http404 if "error" in debug: raise AttributeError("Debug requested error") return f(request, *args, **kwargs) return wrap def jsonp(f): """ Decorator for adding connection debugging and returning function result as json, depending on values in kwargs @param f: The function to wrap @return: The wrapped function, which will return json """ @wraps(f) def wrap(request, *args, **kwargs): logger.debug("jsonp") try: server_id = kwargs.get("server_id", None) if server_id is None and request.session.get("connector"): server_id = request.session["connector"].server_id kwargs["server_id"] = server_id rv = f(request, *args, **kwargs) if kwargs.get("_raw", False): return rv if isinstance(rv, HttpResponse): return rv c = request.GET.get("callback", None) if c is not None and not kwargs.get("_internal", False): rv = json.dumps(rv) rv = "%s(%s)" % (c, rv) # mimetype for JSONP is application/javascript return HttpJavascriptResponse(rv) if kwargs.get("_internal", False): return rv # mimetype for JSON is application/json # NB: To support old api E.g. /get_rois_json/ # We need to support lists safe = type(rv) is dict return JsonResponse(rv, safe=safe) except Exception as ex: # Default status is 500 'server error' # But we try to handle all 'expected' errors appropriately # TODO: handle omero.ConcurrencyException status = 500 if isinstance(ex, omero.SecurityViolation): status = 403 elif isinstance(ex, omero.ApiUsageException): status = 400 trace = traceback.format_exc() logger.debug(trace) if kwargs.get("_raw", False) or kwargs.get("_internal", False): raise return JsonResponse( {"message": str(ex), "stacktrace": trace}, status=status ) return wrap @debug @login_required() def render_row_plot(request, iid, z, t, y, conn=None, w=1, **kwargs): """ Renders the line plot for the image with id {{iid}} at {{z}} and {{t}} as gif with transparent background. Many options are available from the request dict. I am assuming a single Pixels object on image with Image ID='iid'. May be wrong TODO: cache @param request: http request @param iid: Image ID @param z: Z index @param t: T index @param y: Y position of row to measure @param conn: L{omero.gateway.BlitzGateway} connection @param w: Line width @return: http response wrapping a gif """ if not w: w = 1 pi = _get_prepared_image(request, iid, conn=conn) if pi is None: raise Http404 img, compress_quality = pi try: gif_data = img.renderRowLinePlotGif(int(z), int(t), int(y), int(w)) except Exception: logger.debug("a", exc_info=True) raise if gif_data is None: raise Http404 rsp = HttpResponse(gif_data, content_type="image/gif") return rsp @debug @login_required() def render_col_plot(request, iid, z, t, x, w=1, conn=None, **kwargs): """ Renders the line plot for the image with id {{iid}} at {{z}} and {{t}} as gif with transparent background. Many options are available from the request dict. I am assuming a single Pixels object on image with id='iid'. May be wrong TODO: cache @param request: http request @param iid: Image ID @param z: Z index @param t: T index @param x: X position of column to measure @param conn: L{omero.gateway.BlitzGateway} connection @param w: Line width @return: http response wrapping a gif """ if not w: w = 1 pi = _get_prepared_image(request, iid, conn=conn) if pi is None: raise Http404 img, compress_quality = pi gif_data = img.renderColLinePlotGif(int(z), int(t), int(x), int(w)) if gif_data is None: raise Http404 rsp = HttpResponse(gif_data, content_type="image/gif") return rsp @login_required() @jsonp def imageData_json(request, conn=None, _internal=False, **kwargs): """ Get a dict with image information TODO: cache @param request: http request @param conn: L{omero.gateway.BlitzGateway} @param _internal: TODO: ? @return: Dict """ iid = kwargs["iid"] key = kwargs.get("key", None) image = conn.getObject("Image", iid) if image is None: if is_public_user(request): # 403 - Should try logging in return HttpResponseForbidden() else: return HttpResponseNotFound("Image:%s not found" % iid) if request.GET.get("getDefaults") == "true": image.resetDefaults(save=False) rv = imageMarshal(image, key=key, request=request) return rv @login_required() @jsonp def wellData_json(request, conn=None, _internal=False, **kwargs): """ Get a dict with image information TODO: cache @param request: http request @param conn: L{omero.gateway.BlitzGateway} @param _internal: TODO: ? @return: Dict """ wid = kwargs["wid"] well = conn.getObject("Well", wid) if well is None: return HttpJavascriptResponseServerError('""') prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") def urlprefix(iid): return reverse(prefix, args=(iid,)) xtra = {"thumbUrlPrefix": kwargs.get("urlprefix", urlprefix)} rv = well.simpleMarshal(xtra=xtra) return rv @login_required() @jsonp def plateGrid_json(request, pid, field=0, conn=None, **kwargs): """""" try: field = long(field or 0) except ValueError: field = 0 prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") thumbsize = getIntOrDefault(request, "size", None) logger.debug(thumbsize) server_id = kwargs["server_id"] def get_thumb_url(iid): if thumbsize is not None: return reverse(prefix, args=(iid, thumbsize)) return reverse(prefix, args=(iid,)) plateGrid = PlateGrid(conn, pid, field, kwargs.get("urlprefix", get_thumb_url)) plate = plateGrid.plate if plate is None: return Http404 cache_key = "plategrid-%d-%s" % (field, thumbsize) rv = webgateway_cache.getJson(request, server_id, plate, cache_key) if rv is None: rv = plateGrid.metadata webgateway_cache.setJson(request, server_id, plate, json.dumps(rv), cache_key) else: rv = json.loads(rv) return rv @login_required() @jsonp def get_thumbnails_json(request, w=None, conn=None, **kwargs): """ Returns base64 encoded jpeg with the rendered thumbnail for images 'id' @param request: http request @param w: Thumbnail max width. 96 by default @return: http response containing base64 encoded thumbnails """ server_settings = request.session.get("server_settings", {}).get("browser", {}) defaultSize = server_settings.get("thumb_default_size", 96) if w is None: w = defaultSize image_ids = get_longs(request, "id") image_ids = list(set(image_ids)) # remove any duplicates # If we only have a single ID, simply use getThumbnail() if len(image_ids) == 1: iid = image_ids[0] try: data = _render_thumbnail(request, iid, w=w, conn=conn) return { iid: "data:image/jpeg;base64,%s" % base64.b64encode(data).decode("utf-8") } except Exception: return {iid: None} logger.debug("Image ids: %r" % image_ids) if len(image_ids) > settings.THUMBNAILS_BATCH: return HttpJavascriptResponseServerError( "Max %s thumbnails at a time." % settings.THUMBNAILS_BATCH ) thumbnails = conn.getThumbnailSet([rlong(i) for i in image_ids], w) rv = dict() for i in image_ids: rv[i] = None try: t = thumbnails[i] if len(t) > 0: # replace thumbnail urls by base64 encoded image rv[i] = "data:image/jpeg;base64,%s" % base64.b64encode(t).decode( "utf-8" ) except KeyError: logger.error("Thumbnail not available. (img id: %d)" % i) except Exception: logger.error(traceback.format_exc()) return rv @login_required() @jsonp def get_thumbnail_json(request, iid, w=None, h=None, conn=None, _defcb=None, **kwargs): """ Returns an HttpResponse base64 encoded jpeg with the rendered thumbnail for image 'iid' @param request: http request @param iid: Image ID @param w: Thumbnail max width. 96 by default @param h: Thumbnail max height @return: http response containing base64 encoded thumbnail """ jpeg_data = _render_thumbnail( request=request, iid=iid, w=w, h=h, conn=conn, _defcb=_defcb, **kwargs ) rv = "data:image/jpeg;base64,%s" % base64.b64encode(jpeg_data).decode("utf-8") return rv @login_required() @jsonp def listImages_json(request, did, conn=None, **kwargs): """ lists all Images in a Dataset, as json TODO: cache @param request: http request @param did: Dataset ID @param conn: L{omero.gateway.BlitzGateway} @return: list of image json. """ dataset = conn.getObject("Dataset", did) if dataset is None: return HttpJavascriptResponseServerError('""') prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") def urlprefix(iid): return reverse(prefix, args=(iid,)) xtra = { "thumbUrlPrefix": kwargs.get("urlprefix", urlprefix), "tiled": request.GET.get("tiled", False), } return [x.simpleMarshal(xtra=xtra) for x in dataset.listChildren()] @login_required() @jsonp def listWellImages_json(request, did, conn=None, **kwargs): """ lists all Images in a Well, as json TODO: cache @param request: http request @param did: Well ID @param conn: L{omero.gateway.BlitzGateway} @return: list of image json. """ well = conn.getObject("Well", did) acq = getIntOrDefault(request, "run", None) if well is None: return HttpJavascriptResponseServerError('""') prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") def urlprefix(iid): return reverse(prefix, args=(iid,)) xtra = {"thumbUrlPrefix": kwargs.get("urlprefix", urlprefix)} def marshal_pos(w): d = {} for x, p in (["x", w.getPosX()], ["y", w.getPosY()]): if p is not None: d[x] = {"value": p.getValue(), "unit": str(p.getUnit())} return d wellImgs = [] for ws in well.listChildren(): # optionally filter by acquisition 'run' if ( acq is not None and ws.plateAcquisition is not None and ws.plateAcquisition.id.val != acq ): continue img = ws.getImage() if img is not None: m = img.simpleMarshal(xtra=xtra) pos = marshal_pos(ws) if len(pos.keys()) > 0: m["position"] = pos wellImgs.append(m) return wellImgs @login_required() @jsonp def listDatasets_json(request, pid, conn=None, **kwargs): """ lists all Datasets in a Project, as json TODO: cache @param request: http request @param pid: Project ID @param conn: L{omero.gateway.BlitzGateway} @return: list of dataset json. """ project = conn.getObject("Project", pid) if project is None: return HttpJavascriptResponse("[]") return [x.simpleMarshal(xtra={"childCount": 0}) for x in project.listChildren()] @login_required() @jsonp def datasetDetail_json(request, did, conn=None, **kwargs): """ return json encoded details for a dataset TODO: cache """ ds = conn.getObject("Dataset", did) return ds.simpleMarshal() @login_required() @jsonp def listProjects_json(request, conn=None, **kwargs): """ lists all Projects, as json TODO: cache @param request: http request @param conn: L{omero.gateway.BlitzGateway} @return: list of project json. """ rv = [] for pr in conn.listProjects(): rv.append({"id": pr.id, "name": pr.name, "description": pr.description or ""}) return rv @login_required() @jsonp def projectDetail_json(request, pid, conn=None, **kwargs): """ grab details from one specific project TODO: cache @param request: http request @param pid: Project ID @param conn: L{omero.gateway.BlitzGateway} @return: project details as dict. """ pr = conn.getObject("Project", pid) rv = pr.simpleMarshal() return rv @jsonp def open_with_options(request, **kwargs): """ Make the settings.OPEN_WITH available via JSON """ open_with = settings.OPEN_WITH viewers = [] for ow in open_with: if len(ow) < 2: continue viewer = {} viewer["id"] = ow[0] try: viewer["url"] = reverse(ow[1]) except NoReverseMatch: viewer["url"] = ow[1] # try non-essential parameters... # NB: Need supported_objects OR script_url to enable plugin try: if len(ow) > 2: if "supported_objects" in ow[2]: viewer["supported_objects"] = ow[2]["supported_objects"] if "target" in ow[2]: viewer["target"] = ow[2]["target"] if "script_url" in ow[2]: # If we have an absolute url, use it... if ow[2]["script_url"].startswith("http"): viewer["script_url"] = ow[2]["script_url"] else: # ...otherwise, assume within static viewer["script_url"] = static(ow[2]["script_url"]) if "label" in ow[2]: viewer["label"] = ow[2]["label"] except Exception: # ignore invalid params pass viewers.append(viewer) return {"open_with_options": viewers} def searchOptFromRequest(request): """ Returns a dict of options for searching, based on parameters in the http request Request keys include: - ctx: (http request) 'imgs' to search only images - text: (http request) the actual text phrase - start: starting index (0 based) for result - limit: nr of results to retuen (0 == unlimited) - author: - grabData: - parents: @param request: http request @return: Dict of options """ try: r = request.GET opts = { "search": unicode(r.get("text", "")).encode("utf8"), "ctx": r.get("ctx", ""), "grabData": not not r.get("grabData", False), "parents": not not bool(r.get("parents", False)), "start": int(r.get("start", 0)), "limit": int(r.get("limit", 0)), "key": r.get("key", None), } author = r.get("author", "") if author: opts["search"] += " author:" + author return opts except Exception: logger.error(traceback.format_exc()) return {} @TimeIt(logging.INFO) @login_required() @jsonp def search_json(request, conn=None, **kwargs): """ Search for objects in blitz. Returns json encoded list of marshalled objects found by the search query Request keys include: - text: The text to search for - ctx: (http request) 'imgs' to search only images - text: (http request) the actual text phrase - start: starting index (0 based) for result - limit: nr of results to retuen (0 == unlimited) - author: - grabData: - parents: @param request: http request @param conn: L{omero.gateway.BlitzGateway} @return: json search results TODO: cache """ server_id = request.session["connector"].server_id opts = searchOptFromRequest(request) rv = [] logger.debug("searchObjects(%s)" % (opts["search"])) # search returns blitz_connector wrapper objects def urlprefix(iid): return reverse("webgateway_render_thumbnail", args=(iid,)) xtra = {"thumbUrlPrefix": kwargs.get("urlprefix", urlprefix)} try: if opts["ctx"] == "imgs": sr = conn.searchObjects(["image"], opts["search"], conn.SERVICE_OPTS) else: # searches P/D/I sr = conn.searchObjects(None, opts["search"], conn.SERVICE_OPTS) except ApiUsageException: return HttpJavascriptResponseServerError('"parse exception"') def marshal(): rv = [] if opts["grabData"] and opts["ctx"] == "imgs": bottom = min(opts["start"], len(sr) - 1) if opts["limit"] == 0: top = len(sr) else: top = min(len(sr), bottom + opts["limit"]) for i in range(bottom, top): e = sr[i] # for e in sr: try: rv.append( imageData_json( request, server_id, iid=e.id, key=opts["key"], conn=conn, _internal=True, ) ) except AttributeError as x: logger.debug( "(iid %i) ignoring Attribute Error: %s" % (e.id, str(x)) ) pass except omero.ServerError as x: logger.debug("(iid %i) ignoring Server Error: %s" % (e.id, str(x))) return rv else: return [x.simpleMarshal(xtra=xtra, parents=opts["parents"]) for x in sr] rv = timeit(marshal)() logger.debug(rv) return rv @require_POST @login_required() def save_image_rdef_json(request, iid, conn=None, **kwargs): """ Requests that the rendering defs passed in the request be set as the default for this image. Rendering defs in request listed at L{getImgDetailsFromReq} TODO: jsonp @param request: http request @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} @return: http response 'true' or 'false' """ server_id = request.session["connector"].server_id pi = _get_prepared_image( request, iid, server_id=server_id, conn=conn, saveDefs=True ) if pi is None: json_data = "false" else: user_id = pi[0]._conn.getEventContext().userId webgateway_cache.invalidateObject(server_id, user_id, pi[0]) pi[0].getThumbnail() json_data = "true" if request.GET.get("callback", None): json_data = "%s(%s)" % (request.GET["callback"], json_data) return HttpJavascriptResponse(json_data) @login_required() @jsonp def listLuts_json(request, conn=None, **kwargs): """ Lists lookup tables 'LUTs' availble for rendering This list is dynamic and will change if users add LUTs to their server. We include 'png_index' which is the index of each LUT within the static/webgateway/img/luts_10.png or -1 if LUT is not found. """ scriptService = conn.getScriptService() luts = scriptService.getScriptsByMimetype("text/x-lut") rv = [] for lut in luts: lutsrc = lut.path.val + lut.name.val png_index = LUTS_IN_PNG.index(lutsrc) if lutsrc in LUTS_IN_PNG else -1 rv.append( { "id": lut.id.val, "path": lut.path.val, "name": lut.name.val, "size": unwrap(lut.size), "png_index": png_index, } ) rv.sort(key=lambda x: x["name"].lower()) return {"luts": rv, "png_luts": LUTS_IN_PNG} @login_required() def list_compatible_imgs_json(request, iid, conn=None, **kwargs): """ Lists the images on the same project that would be viable targets for copying rendering settings. TODO: change method to: list_compatible_imgs_json (request, iid, server_id=None, conn=None, **kwargs): @param request: http request @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} @return: json list of image IDs """ json_data = "false" r = request.GET if conn is None: img = None else: img = conn.getObject("Image", iid) if img is not None: # List all images in project imgs = [] for ds in img.getProject().listChildren(): imgs.extend(ds.listChildren()) # Filter the ones that would pass the applySettingsToImages call img_ptype = img.getPrimaryPixels().getPixelsType().getValue() img_ccount = img.getSizeC() img_ew = [x.getLabel() for x in img.getChannels()] img_ew.sort() def compat(i): if long(i.getId()) == long(iid): return False pp = i.getPrimaryPixels() if ( pp is None or i.getPrimaryPixels().getPixelsType().getValue() != img_ptype or i.getSizeC() != img_ccount ): return False ew = [x.getLabel() for x in i.getChannels()] ew.sort() if ew != img_ew: return False return True imgs = filter(compat, imgs) json_data = json.dumps([x.getId() for x in imgs]) if r.get("callback", None): json_data = "%s(%s)" % (r["callback"], json_data) return HttpJavascriptResponse(json_data) @require_POST @login_required() @jsonp def reset_rdef_json(request, toOwners=False, conn=None, **kwargs): """ Simply takes request 'to_type' and 'toids' and delegates to Rendering Settings service to reset settings accordings. @param toOwners: if True, default to the owner's settings. """ r = request.POST toids = r.getlist("toids") to_type = str(r.get("to_type", "image")) to_type = to_type.title() if to_type == "Acquisition": to_type = "PlateAcquisition" if len(toids) == 0: raise Http404( "Need to specify objects in request, E.g." " ?totype=dataset&toids=1&toids=2" ) toids = [int(id) for id in toids] rss = conn.getRenderingSettingsService() # get the first object and set the group to match conn.SERVICE_OPTS.setOmeroGroup("-1") o = conn.getObject(to_type, toids[0]) if o is not None: gid = o.getDetails().group.id.val conn.SERVICE_OPTS.setOmeroGroup(gid) if toOwners: rv = rss.resetDefaultsByOwnerInSet(to_type, toids, conn.SERVICE_OPTS) else: rv = rss.resetDefaultsInSet(to_type, toids, conn.SERVICE_OPTS) return rv @login_required() @jsonp def copy_image_rdef_json(request, conn=None, **kwargs): """ If 'fromid' is in request, copy the image ID to session, for applying later using this same method. If list of 'toids' is in request, paste the image ID from the session to the specified images. If 'fromid' AND 'toids' are in the reqest, we simply apply settings and don't save anything to request. If 'to_type' is in request, this can be 'dataset', 'plate', 'acquisition' Returns json dict of Boolean:[Image-IDs] for images that have successfully had the rendering settings applied, or not. @param request: http request @param server_id: @param conn: L{omero.gateway.BlitzGateway} @return: json dict of Boolean:[Image-IDs] """ server_id = request.session["connector"].server_id json_data = False fromid = request.GET.get("fromid", None) toids = request.POST.getlist("toids") to_type = str(request.POST.get("to_type", "image")) rdef = None if to_type not in ("dataset", "plate", "acquisition"): to_type = "Image" # default is image # Only 'fromid' is given, simply save to session if fromid is not None and len(toids) == 0: request.session.modified = True request.session["fromid"] = fromid if request.session.get("rdef") is not None: del request.session["rdef"] return True # If we've got an rdef encoded in request instead of ImageId... r = request.GET or request.POST if r.get("c") is not None: # make a map of settings we need rdef = {"c": str(r.get("c"))} # channels if r.get("maps"): try: rdef["maps"] = json.loads(r.get("maps")) except Exception: pass if r.get("pixel_range"): rdef["pixel_range"] = str(r.get("pixel_range")) if r.get("m"): rdef["m"] = str(r.get("m")) # model (grey) if r.get("z"): rdef["z"] = str(r.get("z")) # z & t pos if r.get("t"): rdef["t"] = str(r.get("t")) imageId = request.GET.get("imageId", request.POST.get("imageId", None)) if imageId: rdef["imageId"] = int(imageId) if request.method == "GET": request.session.modified = True request.session["rdef"] = rdef # remove any previous rdef we may have via 'fromId' if request.session.get("fromid") is not None: del request.session["fromid"] return True # Check session for 'fromid' if fromid is None: fromid = request.session.get("fromid", None) # maybe these pair of methods should be on ImageWrapper?? def getRenderingSettings(image): rv = {} chs = [] maps = [] for i, ch in enumerate(image.getChannels()): act = "" if ch.isActive() else "-" start = ch.getWindowStart() end = ch.getWindowEnd() color = ch.getLut() maps.append({"inverted": {"enabled": ch.isInverted()}}) if not color or len(color) == 0: color = ch.getColor().getHtml() chs.append("%s%s|%s:%s$%s" % (act, i + 1, start, end, color)) rv["c"] = ",".join(chs) rv["maps"] = maps rv["m"] = "g" if image.isGreyscaleRenderingModel() else "c" rv["z"] = image.getDefaultZ() + 1 rv["t"] = image.getDefaultT() + 1 return rv def applyRenderingSettings(image, rdef): invert_flags = _get_maps_enabled(rdef, "inverted", image.getSizeC()) channels, windows, colors = _split_channel_info(rdef["c"]) # also prepares _re image.setActiveChannels(channels, windows, colors, invert_flags) if rdef["m"] == "g": image.setGreyscaleRenderingModel() else: image.setColorRenderingModel() if "z" in rdef: image._re.setDefaultZ(long(rdef["z"]) - 1) if "t" in rdef: image._re.setDefaultT(long(rdef["t"]) - 1) image.saveDefaults() # Use rdef from above or previously saved one... if rdef is None: rdef = request.session.get("rdef") if request.method == "POST": originalSettings = None fromImage = None if fromid is None: # if we have rdef, save to source image, then use that image as # 'fromId', then revert. if rdef is not None and len(toids) > 0: fromImage = conn.getObject("Image", rdef["imageId"]) if fromImage is not None: # copy orig settings originalSettings = getRenderingSettings(fromImage) applyRenderingSettings(fromImage, rdef) fromid = fromImage.getId() # If we have both, apply settings... try: fromid = long(fromid) toids = [long(x) for x in toids] except TypeError: fromid = None except ValueError: fromid = None if fromid is not None and len(toids) > 0: fromimg = conn.getObject("Image", fromid) userid = fromimg.getOwner().getId() json_data = conn.applySettingsToSet(fromid, to_type, toids) if json_data and True in json_data: for iid in json_data[True]: img = conn.getObject("Image", iid) img is not None and webgateway_cache.invalidateObject( server_id, userid, img ) # finally - if we temporarily saved rdef to original image, revert # if we're sure that from-image is not in the target set (Dataset etc) if to_type == "Image" and fromid not in toids: if originalSettings is not None and fromImage is not None: applyRenderingSettings(fromImage, originalSettings) return json_data else: return HttpResponseNotAllowed(["POST"]) @login_required() @jsonp def get_image_rdef_json(request, conn=None, **kwargs): """ Gets any 'rdef' dict from the request.session and returns it as json """ rdef = request.session.get("rdef") image = None if rdef is None: fromid = request.session.get("fromid", None) if fromid is not None: # We only have an Image to copy rdefs from image = conn.getObject("Image", fromid) if image is not None: rv = imageMarshal(image, request=request) chs = [] maps = [] for i, ch in enumerate(rv["channels"]): act = ch["active"] and str(i + 1) or "-%s" % (i + 1) color = ch.get("lut") or ch["color"] chs.append( "%s|%s:%s$%s" % (act, ch["window"]["start"], ch["window"]["end"], color) ) maps.append( { "inverted": {"enabled": ch["inverted"]}, "quantization": { "coefficient": ch["coefficient"], "family": ch["family"], }, } ) rdef = { "c": (",".join(chs)), "m": rv["rdefs"]["model"], "pixel_range": "%s:%s" % (rv["pixel_range"][0], rv["pixel_range"][1]), "maps": maps, } return {"rdef": rdef} @login_required() def full_viewer(request, iid, conn=None, **kwargs): """ This view is responsible for showing the omero_image template Image rendering options in request are used in the display page. See L{getImgDetailsFromReq}. @param request: http request. @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: Can be used to specify the html 'template' for rendering @return: html page of image and metadata """ server_id = request.session["connector"].server_id server_name = Server.get(server_id).server rid = getImgDetailsFromReq(request) server_settings = request.session.get("server_settings", {}).get("viewer", {}) interpolate = server_settings.get("interpolate_pixels", True) roiLimit = server_settings.get("roi_limit", 2000) try: image = conn.getObject("Image", iid) if image is None: logger.debug("(a)Image %s not found..." % (str(iid))) raise Http404 opengraph = None twitter = None image_preview = None page_url = None if hasattr(settings, "SHARING_OPENGRAPH"): opengraph = settings.SHARING_OPENGRAPH.get(server_name) logger.debug("Open Graph enabled: %s", opengraph) if hasattr(settings, "SHARING_TWITTER"): twitter = settings.SHARING_TWITTER.get(server_name) logger.debug("Twitter enabled: %s", twitter) if opengraph or twitter: urlargs = {"iid": iid} prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") image_preview = request.build_absolute_uri(reverse(prefix, kwargs=urlargs)) page_url = request.build_absolute_uri( reverse("webgateway_full_viewer", kwargs=urlargs) ) d = { "blitzcon": conn, "image": image, "opts": rid, "interpolate": interpolate, "build_year": build_year, "roiLimit": roiLimit, "roiCount": image.getROICount(), "viewport_server": kwargs.get( # remove any trailing slash "viewport_server", reverse("webgateway"), ).rstrip("/"), "opengraph": opengraph, "twitter": twitter, "image_preview": image_preview, "page_url": page_url, "object": "image:%i" % int(iid), } template = kwargs.get("template", "webgateway/viewport/omero_image.html") rsp = render(request, template, d) except omero.SecurityViolation: logger.warn("SecurityViolation in Image:%s", iid) logger.warn(traceback.format_exc()) raise Http404 return HttpResponse(rsp) @login_required() def download_as(request, iid=None, conn=None, **kwargs): """ Downloads the image as a single jpeg/png/tiff or as a zip (if more than one image) """ format = request.GET.get("format", "png") if format not in ("jpeg", "png", "tif"): format = "png" imgIds = [] wellIds = [] if iid is None: imgIds = request.GET.getlist("image") if len(imgIds) == 0: wellIds = request.GET.getlist("well") if len(wellIds) == 0: return HttpResponseServerError( "No images or wells specified in request." " Use ?image=123 or ?well=123" ) else: imgIds = [iid] images = [] if imgIds: images = list(conn.getObjects("Image", imgIds)) elif wellIds: try: index = int(request.GET.get("index", 0)) except ValueError: index = 0 for w in conn.getObjects("Well", wellIds): images.append(w.getWellSample(index).image()) if len(images) == 0: msg = "Cannot download as %s. Images (ids: %s) not found." % (format, imgIds) logger.debug(msg) return HttpResponseServerError(msg) if len(images) == 1: jpeg_data = images[0].renderJpeg() if jpeg_data is None: raise Http404 rsp = HttpResponse(jpeg_data, mimetype="image/jpeg") rsp["Content-Length"] = len(jpeg_data) rsp["Content-Disposition"] = "attachment; filename=%s.jpg" % ( images[0].getName().replace(" ", "_") ) else: temp = tempfile.NamedTemporaryFile(suffix=".download_as") def makeImageName(originalName, extension, folder_name): name = os.path.basename(originalName) imgName = "%s.%s" % (name, extension) imgName = os.path.join(folder_name, imgName) # check we don't overwrite existing file i = 1 name = imgName[: -(len(extension) + 1)] while os.path.exists(imgName): imgName = "%s_(%d).%s" % (name, i, extension) i += 1 return imgName try: temp_zip_dir = tempfile.mkdtemp() logger.debug("download_as dir: %s" % temp_zip_dir) try: for img in images: z = t = None try: pilImg = img.renderImage(z, t) imgPathName = makeImageName(img.getName(), format, temp_zip_dir) pilImg.save(imgPathName) finally: # Close RenderingEngine img._re.close() # create zip zip_file = zipfile.ZipFile(temp, "w", zipfile.ZIP_DEFLATED) try: a_files = os.path.join(temp_zip_dir, "*") for name in glob.glob(a_files): zip_file.write(name, os.path.basename(name)) finally: zip_file.close() finally: shutil.rmtree(temp_zip_dir, ignore_errors=True) zipName = request.GET.get("zipname", "Download_as_%s" % format) zipName = zipName.replace(" ", "_") if not zipName.endswith(".zip"): zipName = "%s.zip" % zipName # return the zip or single file rsp = StreamingHttpResponse(FileWrapper(temp)) rsp["Content-Length"] = temp.tell() rsp["Content-Disposition"] = "attachment; filename=%s" % zipName temp.seek(0) except Exception: temp.close() stack = traceback.format_exc() logger.error(stack) return HttpResponseServerError("Cannot download file (id:%s)" % iid) rsp["Content-Type"] = "application/force-download" return rsp @login_required(doConnectionCleanup=False) def archived_files(request, iid=None, conn=None, **kwargs): """ Downloads the archived file(s) as a single file or as a zip (if more than one file) """ imgIds = [] wellIds = [] imgIds = request.GET.getlist("image") wellIds = request.GET.getlist("well") if iid is None: if len(imgIds) == 0 and len(wellIds) == 0: return HttpResponseServerError( "No images or wells specified in request." " Use ?image=123 or ?well=123" ) else: imgIds = [iid] images = list() wells = list() if imgIds: images = list(conn.getObjects("Image", imgIds)) elif wellIds: try: index = int(request.GET.get("index", 0)) except ValueError: index = 0 wells = conn.getObjects("Well", wellIds) for w in wells: images.append(w.getWellSample(index).image()) if len(images) == 0: message = ( "Cannot download archived file because Images not " "found (ids: %s)" % (imgIds) ) logger.debug(message) return HttpResponseServerError(message) # Test permissions on images and weels for ob in wells: if hasattr(ob, "canDownload"): if not ob.canDownload(): return HttpResponseNotFound() for ob in images: well = None try: well = ob.getParent().getParent() except Exception: if hasattr(ob, "canDownload"): if not ob.canDownload(): return HttpResponseNotFound() else: if well and isinstance(well, omero.gateway.WellWrapper): if hasattr(well, "canDownload"): if not well.canDownload(): return HttpResponseNotFound() # make list of all files, removing duplicates fileMap = {} for image in images: for f in image.getImportedImageFiles(): fileMap[f.getId()] = f files = list(fileMap.values()) if len(files) == 0: message = ( "Tried downloading archived files from image with no" " files archived." ) logger.debug(message) return HttpResponseServerError(message) if len(files) == 1: orig_file = files[0] rsp = ConnCleaningHttpResponse( orig_file.getFileInChunks(buf=settings.CHUNK_SIZE) ) rsp.conn = conn rsp["Content-Length"] = orig_file.getSize() # ',' in name causes duplicate headers fname = orig_file.getName().replace(" ", "_").replace(",", ".") rsp["Content-Disposition"] = "attachment; filename=%s" % (fname) else: total_size = sum(f.size for f in files) if total_size > settings.MAXIMUM_MULTIFILE_DOWNLOAD_ZIP_SIZE: message = ( "Total size of files %d is larger than %d. " "Try requesting fewer files." % (total_size, settings.MAXIMUM_MULTIFILE_DOWNLOAD_ZIP_SIZE) ) logger.warn(message) return HttpResponseForbidden(message) temp = tempfile.NamedTemporaryFile(suffix=".archive") zipName = request.GET.get("zipname", image.getName()) try: zipName = zip_archived_files(images, temp, zipName, buf=settings.CHUNK_SIZE) # return the zip or single file archivedFile_data = FileWrapper(temp) rsp = ConnCleaningHttpResponse(archivedFile_data) rsp.conn = conn rsp["Content-Length"] = temp.tell() rsp["Content-Disposition"] = "attachment; filename=%s" % zipName temp.seek(0) except Exception: temp.close() message = "Cannot download file (id:%s)" % (iid) logger.error(message, exc_info=True) return HttpResponseServerError(message) rsp["Content-Type"] = "application/force-download" return rsp @login_required() @jsonp def original_file_paths(request, iid, conn=None, **kwargs): """ Get a list of path/name strings for original files associated with the image """ image = conn.getObject("Image", iid) if image is None: raise Http404 paths = image.getImportedImageFilePaths() return {"repo": paths["server_paths"], "client": paths["client_paths"]} @login_required() @jsonp def get_shape_json(request, roiId, shapeId, conn=None, **kwargs): roiId = int(roiId) shapeId = int(shapeId) shape = conn.getQueryService().findByQuery( "select shape from Roi as roi " "join roi.shapes as shape " "where roi.id = %d and shape.id = %d" % (roiId, shapeId), None, ) logger.debug("Shape: %r" % shape) if shape is None: logger.debug("No such shape: %r" % shapeId) raise Http404 return JsonResponse(shapeMarshal(shape)) @login_required() @jsonp def get_rois_json(request, imageId, conn=None, **kwargs): """ Returns json data of the ROIs in the specified image. """ rois = [] roiService = conn.getRoiService() # rois = webfigure_utils.getRoiShapes(roiService, long(imageId)) # gets a # whole json list of ROIs result = roiService.findByImage(long(imageId), None, conn.SERVICE_OPTS) for r in result.rois: roi = {} roi["id"] = r.getId().getValue() # go through all the shapes of the ROI shapes = [] for s in r.copyShapes(): if s is None: # seems possible in some situations continue shapes.append(shapeMarshal(s)) # sort shapes by Z, then T. shapes.sort(key=lambda x: "%03d%03d" % (x.get("theZ", -1), x.get("theT", -1))) roi["shapes"] = shapes rois.append(roi) # sort by ID - same as in measurement tool. rois.sort(key=lambda x: x["id"]) return rois @login_required() def histogram_json(request, iid, theC, conn=None, **kwargs): """ Returns a histogram for a single channel as a list of 256 values as json """ image = conn.getObject("Image", iid) if image is None: raise Http404 maxW, maxH = conn.getMaxPlaneSize() sizeX = image.getSizeX() sizeY = image.getSizeY() if (sizeX * sizeY) > (maxW * maxH): msg = "Histogram not supported for 'big' images (over %s * %s pixels)" % ( maxW, maxH, ) return JsonResponse({"error": msg}) theZ = int(request.GET.get("theZ", 0)) theT = int(request.GET.get("theT", 0)) theC = int(theC) binCount = int(request.GET.get("bins", 256)) # TODO: handle projection when supported by OMERO data = image.getHistogram([theC], binCount, theZ=theZ, theT=theT) histogram = data[theC] return JsonResponse({"data": histogram}) @login_required(isAdmin=True) @jsonp def su(request, user, conn=None, **kwargs): """ If current user is admin, switch the session to a new connection owned by 'user' (puts the new session ID in the request.session) Return False if not possible @param request: http request. @param user: Username of new connection owner @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: Can be used to specify the html 'template' for rendering @return: Boolean """ if request.method == "POST": conn.setGroupNameForSession("system") connector = request.session["connector"] connector = Connector(connector.server_id, connector.is_secure) session = conn.getSessionService().getSession(conn._sessionUuid) ttl = session.getTimeToIdle().val connector.omero_session_key = conn.suConn(user, ttl=ttl)._sessionUuid request.session["connector"] = connector conn.revertGroupForSession() conn.close() return True else: context = { "url": reverse("webgateway_su", args=[user]), "submit": "Do you want to su to %s" % user, } template = "webgateway/base/includes/post_form.html" return render(request, template, context) def _annotations(request, objtype, objid, conn=None, **kwargs): warnings.warn("Deprecated. Use _bulk_file_annotations()", DeprecationWarning) return _bulk_file_annotations(request, objtype, objid, conn, **kwargs) def _bulk_file_annotations(request, objtype, objid, conn=None, **kwargs): """ Retrieve Bulk FileAnnotations for object specified by object type and identifier optionally traversing object model graph. Returns dictionary containing annotations in NSBULKANNOTATIONS namespace if successful, otherwise returns error information. If the graph has multiple parents, we return annotations from all parents. Example: /annotations/Plate/1/ retrieves annotations for plate with identifier 1 Example: /annotations/Plate.wells/1/ retrieves annotations for plate that contains well with identifier 1 Example: /annotations/Screen.plateLinks.child.wells/22/ retrieves annotations for screen that contains plate with well with identifier 22 @param request: http request. @param objtype: Type of target object, or type of target object followed by a slash-separated list of properties to resolve @param objid: Identifier of target object, or identifier of object reached by resolving given properties @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: unused @return: A dictionary with key 'error' with an error message or with key 'data' containing an array of dictionaries with keys 'id' and 'file' of the retrieved annotations """ q = conn.getQueryService() # If more than one objtype is specified, use all in query to # traverse object model graph # Example: /annotations/Plate/wells/1/ # retrieves annotations from Plate that contains Well 1 objtype = objtype.split(".") params = omero.sys.ParametersI() params.addId(objid) params.addString("ns", NSBULKANNOTATIONS) params.addString("mt", "OMERO.tables") query = "select obj0 from %s obj0\n" % objtype[0] for i, t in enumerate(objtype[1:]): query += "join fetch obj%d.%s obj%d\n" % (i, t, i + 1) query += """ left outer join fetch obj0.annotationLinks links left outer join fetch links.child as f left outer join fetch links.parent left outer join fetch f.file join fetch links.details.owner join fetch links.details.creationEvent where obj%d.id=:id and (f.ns=:ns or f.file.mimetype=:mt)""" % ( len(objtype) - 1 ) ctx = conn.createServiceOptsDict() ctx.setOmeroGroup("-1") try: objs = q.findAllByQuery(query, params, ctx) except omero.QueryException: return dict(error="%s cannot be queried" % objtype, query=query) data = [] # Process all annotations from all objects... links = [link for obj in objs for link in obj.copyAnnotationLinks()] for link in links: annotation = link.child if not isinstance(annotation, omero.model.FileAnnotation): continue owner = annotation.details.owner ownerName = "%s %s" % (unwrap(owner.firstName), unwrap(owner.lastName)) addedBy = link.details.owner addedByName = "%s %s" % (unwrap(addedBy.firstName), unwrap(addedBy.lastName)) data.append( dict( id=annotation.id.val, file=annotation.file.id.val, parentType=objtype[0], parentId=link.parent.id.val, owner=ownerName, addedBy=addedByName, addedOn=unwrap(link.details.creationEvent._time), ) ) return dict(data=data) annotations = login_required()(jsonp(_bulk_file_annotations)) def _table_query(request, fileid, conn=None, query=None, lazy=False, **kwargs): """ Query a table specified by fileid Returns a dictionary with query result if successful, error information otherwise @param request: http request; querystring must contain key 'query' with query to be executed, or '*' to retrieve all rows. If query is in the format word-number, e.g. "Well-7", if will be run as (word==number), e.g. "(Well==7)". This is supported to allow more readable query strings. @param fileid: Numeric identifier of file containing the table @param query: The table query. If None, use request.GET.get('query') E.g. '*' to return all rows. If in the form 'colname-1', query will be (colname==1) @param lazy: If True, instead of returning a 'rows' list, 'lazy_rows' will be a generator. Each gen.next() will return a list of row data AND 'table' returned MUST be closed. @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: offset, limit @return: A dictionary with key 'error' with an error message or with key 'data' containing a dictionary with keys 'columns' (an array of column names) and 'rows' (an array of rows, each an array of values) """ if query is None: query = request.GET.get("query") if not query: return dict(error="Must specify query parameter, use * to retrieve all") col_names = request.GET.getlist("col_names") ctx = conn.createServiceOptsDict() ctx.setOmeroGroup("-1") r = conn.getSharedResources() t = r.openTable(omero.model.OriginalFileI(fileid), ctx) if not t: return dict(error="Table %s not found" % fileid) try: cols = t.getHeaders() col_indices = range(len(cols)) if col_names: enumerated_columns = ( [(i, j) for (i, j) in enumerate(cols) if j.name in col_names] if col_names else [(i, j) for (i, j) in enumerate(cols)] ) cols = [] col_indices = [] for col_name in col_names: for (i, j) in enumerated_columns: if col_name == j.name: col_indices.append(i) cols.append(j) break rows = t.getNumberOfRows() offset = kwargs.get("offset", 0) limit = kwargs.get("limit", None) if not offset: offset = int(request.GET.get("offset", 0)) if not limit: limit = ( int(request.GET.get("limit")) if request.GET.get("limit") is not None else None ) range_start = offset range_size = kwargs.get("limit", rows) range_end = min(rows, range_start + range_size) if query == "*": hits = range(range_start, range_end) totalCount = rows else: match = re.match(r"^(\w+)-(\d+)", query) if match: query = "(%s==%s)" % (match.group(1), match.group(2)) try: logger.info(query) hits = t.getWhereList(query, None, 0, rows, 1) totalCount = len(hits) # paginate the hits hits = hits[range_start:range_end] except Exception: return dict(error="Error executing query: %s" % query) def row_generator(table, h): # hits are all consecutive rows - can load them in batches idx = 0 batch = 1000 while idx < len(h): batch = min(batch, len(h) - idx) res = table.slice(col_indices, h[idx : idx + batch]) idx += batch # yield a list of rows yield [ [col.values[row] for col in res.columns] for row in range(0, len(res.rowNumbers)) ] row_gen = row_generator(t, hits) rsp_data = { "data": { "column_types": [col.__class__.__name__ for col in cols], "columns": [col.name for col in cols], }, "meta": { "rowCount": rows, "totalCount": totalCount, "limit": limit, "offset": offset, }, } if not lazy: row_data = [] # Use the generator to add all rows in batches for rows in list(row_gen): row_data.extend(rows) rsp_data["data"]["rows"] = row_data else: rsp_data["data"]["lazy_rows"] = row_gen rsp_data["table"] = t return rsp_data finally: if not lazy: t.close() table_query = login_required()(jsonp(_table_query)) def _table_metadata(request, fileid, conn=None, query=None, lazy=False, **kwargs): ctx = conn.createServiceOptsDict() ctx.setOmeroGroup("-1") r = conn.getSharedResources() t = r.openTable(omero.model.OriginalFileI(fileid), ctx) if not t: return dict(error="Table %s not found" % fileid) try: cols = t.getHeaders() rows = t.getNumberOfRows() rsp_data = { "columns": [ { "name": col.name, "description": col.description, "type": col.__class__.__name__, } for col in cols ], "totalCount": rows, } return rsp_data finally: if not lazy: t.close() table_metadata = login_required()(jsonp(_table_metadata)) @login_required() @jsonp def object_table_query(request, objtype, objid, conn=None, **kwargs): """ Query bulk annotations table attached to an object specified by object type and identifier, optionally traversing object model graph. Returns a dictionary with query result if successful, error information otherwise Example: /table/Plate/1/query/?query=* queries bulk annotations table for plate with identifier 1 Example: /table/Plate.wells/1/query/?query=* queries bulk annotations table for plate that contains well with identifier 1 Example: /table/Screen.plateLinks.child.wells/22/query/?query=Well-22 queries bulk annotations table for screen that contains plate with well with identifier 22 @param request: http request. @param objtype: Type of target object, or type of target object followed by a slash-separated list of properties to resolve @param objid: Identifier of target object, or identifier of object reached by resolving given properties @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: unused @return: A dictionary with key 'error' with an error message or with key 'data' containing a dictionary with keys 'columns' (an array of column names) and 'rows' (an array of rows, each an array of values) """ a = _bulk_file_annotations(request, objtype, objid, conn, **kwargs) if "error" in a: return a if len(a["data"]) < 1: return dict(error="Could not retrieve bulk annotations table") # multiple bulk annotations files could be attached, use the most recent # one (= the one with the highest identifier) fileId = 0 ann = None annList = sorted(a["data"], key=lambda x: x["file"], reverse=True) tableData = None for annotation in annList: tableData = _table_query(request, annotation["file"], conn, **kwargs) if "error" not in tableData: ann = annotation fileId = annotation["file"] break if ann is None: return dict( error=tableData.get( "error", "Could not retrieve matching bulk annotation table" ) ) tableData["id"] = fileId tableData["annId"] = ann["id"] tableData["owner"] = ann["owner"] tableData["addedBy"] = ann["addedBy"] tableData["parentType"] = ann["parentType"] tableData["parentId"] = ann["parentId"] tableData["addedOn"] = ann["addedOn"] return tableData class LoginView(View): """Webgateway Login - Subclassed by WebclientLoginView.""" form_class = LoginForm useragent = "OMERO.webapi" @method_decorator(sensitive_post_parameters("password", "csrfmiddlewaretoken")) def dispatch(self, *args, **kwargs): """Wrap other methods to add decorators.""" return super(LoginView, self).dispatch(*args, **kwargs) def get(self, request, api_version=None): """Simply return a message to say GET not supported.""" return JsonResponse( {"message": ("POST only with username, password, " "server and csrftoken")}, status=405, ) def handle_logged_in(self, request, conn, connector): """Return a response for successful login.""" c = conn.getEventContext() ctx = {} for a in [ "sessionId", "sessionUuid", "userId", "userName", "groupId", "groupName", "isAdmin", "eventId", "eventType", "memberOfGroups", "leaderOfGroups", ]: if hasattr(c, a): ctx[a] = getattr(c, a) return JsonResponse({"success": True, "eventContext": ctx}) def handle_not_logged_in(self, request, error=None, form=None): """ Return a response for failed login. Reason for failure may be due to server 'error' or because of form validation errors. @param request: http request @param error: Error message @param form: Instance of Login Form, populated with data """ if error is None and form is not None: # If no error from server, maybe form wasn't valid formErrors = [] for field in form: for e in field.errors: formErrors.append("%s: %s" % (field.label, e)) error = " ".join(formErrors) elif error is None: # Just in case no error or invalid form is given error = "Login failed. Reason unknown." return JsonResponse({"message": error}, status=403) def post(self, request, api_version=None): """ Here we handle the main login logic, creating a connection to OMERO. and store that on the request.session OR handling login failures """ error = None form = self.form_class(request.POST.copy()) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] server_id = form.cleaned_data["server"] is_secure = settings.SECURE connector = Connector(server_id, is_secure) # TODO: version check should be done on the low level, see #5983 compatible = True if settings.CHECK_VERSION: compatible = connector.check_version(self.useragent) if ( server_id is not None and username is not None and password is not None and compatible ): conn = connector.create_connection( self.useragent, username, password, userip=get_client_ip(request) ) if conn is not None: try: request.session["connector"] = connector # UpgradeCheck URL should be loaded from the server or # loaded omero.web.upgrades.url allows to customize web # only try: upgrades_url = settings.UPGRADES_URL except Exception: upgrades_url = conn.getUpgradesUrl() upgradeCheck(url=upgrades_url) return self.handle_logged_in(request, conn, connector) finally: conn.close(hard=False) # Once here, we are not logged in... # Need correct error message if not connector.is_server_up(self.useragent): error = "Server is not responding," " please contact administrator." elif not settings.CHECK_VERSION: error = ( "Connection not available, please check your" " credentials and version compatibility." ) else: if not compatible: error = ( "Client version does not match server," " please contact administrator." ) else: error = settings.LOGIN_INCORRECT_CREDENTIALS_TEXT return self.handle_not_logged_in(request, error, form) @login_required() @jsonp def get_image_rdefs_json(request, img_id=None, conn=None, **kwargs): """ Retrieves all rendering definitions for a given image (id). Example: /get_image_rdefs_json/1 Returns all rdefs for image with id 1 @param request: http request. @param img_id: the id of the image in question @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: unused @return: A dictionary with key 'rdefs' in the success case, one with key 'error' if something went wrong """ try: img = conn.getObject("Image", img_id) if img is None: return {"error": "No image with id " + str(img_id)} return {"rdefs": img.getAllRenderingDefs()} except Exception: logger.debug(traceback.format_exc()) return {"error": "Failed to retrieve rdefs"}
#!/usr/bin/env python # -*- coding: utf-8 -*- # # webgateway/views.py - django application view handling functions # # Copyright (c) 2007-2020 Glencoe Software, Inc. All rights reserved. # # This software is distributed under the terms described by the LICENCE file # you can find at the root of the distribution bundle, which states you are # free to use it only for non commercial purposes. # If the file is missing please request a copy by contacting # jason@glencoesoftware.com. # # Author: Carlos Neves <carlos(at)glencoesoftware.com> import re import json import base64 import warnings from functools import wraps import omero import omero.clients from past.builtins import unicode from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseServerError, JsonResponse, HttpResponseForbidden, ) from django.http import ( HttpResponseRedirect, HttpResponseNotAllowed, Http404, StreamingHttpResponse, HttpResponseNotFound, ) from django.views.decorators.http import require_POST from django.views.decorators.debug import sensitive_post_parameters from django.utils.decorators import method_decorator from django.core.urlresolvers import reverse, NoReverseMatch from django.conf import settings from wsgiref.util import FileWrapper from omero.rtypes import rlong, unwrap from omero.constants.namespaces import NSBULKANNOTATIONS from .util import points_string_to_XY_list, xy_list_to_bbox from .plategrid import PlateGrid from omeroweb.version import omeroweb_buildyear as build_year from .marshal import imageMarshal, shapeMarshal, rgb_int2rgba from django.contrib.staticfiles.templatetags.staticfiles import static from django.views.generic import View from django.shortcuts import render from omeroweb.webadmin.forms import LoginForm from omeroweb.decorators import get_client_ip, is_public_user from omeroweb.webadmin.webadmin_utils import upgradeCheck try: from hashlib import md5 except Exception: from md5 import md5 try: import long except ImportError: long = int from io import BytesIO import tempfile from omero import ApiUsageException from omero.util.decorators import timeit, TimeIt from omeroweb.httprsp import HttpJavascriptResponse, HttpJavascriptResponseServerError from omeroweb.connector import Server import glob # from models import StoredConnection from omeroweb.webgateway.webgateway_cache import ( webgateway_cache, CacheBase, webgateway_tempfile, ) import logging import os import traceback import time import zipfile import shutil from omeroweb.decorators import login_required, ConnCleaningHttpResponse from omeroweb.connector import Connector from omeroweb.webgateway.util import zip_archived_files, LUTS_IN_PNG from omeroweb.webgateway.util import get_longs, getIntOrDefault cache = CacheBase() logger = logging.getLogger(__name__) try: from PIL import Image from PIL import ImageDraw except Exception: # pragma: nocover try: import Image import ImageDraw except Exception: logger.error("No Pillow installed") try: import numpy numpyInstalled = True except ImportError: logger.error("No numpy installed") numpyInstalled = False def index(request): """ /webgateway/ index placeholder """ return HttpResponse("Welcome to webgateway") def _safestr(s): return unicode(s).encode("utf-8") class UserProxy(object): """ Represents the current user of the connection, with methods delegating to the connection itself. """ def __init__(self, blitzcon): """ Initialises the User proxy with the L{omero.gateway.BlitzGateway} connection @param blitzcon: connection @type blitzcon: L{omero.gateway.BlitzGateway} """ self._blitzcon = blitzcon self.loggedIn = False def logIn(self): """ Sets the loggedIn Flag to True """ self.loggedIn = True def isAdmin(self): """ True if the current user is an admin @return: True if the current user is an admin @rtype: Boolean """ return self._blitzcon.isAdmin() def canBeAdmin(self): """ True if the current user can be admin @return: True if the current user can be admin @rtype: Boolean """ return self._blitzcon.canBeAdmin() def getId(self): """ Returns the ID of the current user @return: User ID @rtype: Long """ return self._blitzcon.getUserId() def getName(self): """ Returns the Name of the current user @return: User Name @rtype: String """ return self._blitzcon.getUser().omeName def getFirstName(self): """ Returns the first name of the current user @return: First Name @rtype: String """ return self._blitzcon.getUser().firstName or self.getName() # def getPreferences (self): # return self._blitzcon._user.getPreferences() # # def getUserObj (self): # return self._blitzcon._user # # class SessionCB (object): # def _log (self, what, c): # logger.debug('CONN:%s %s:%d:%s' % (what, c._user, os.getpid(), # c._sessionUuid)) # # def create (self, c): # self._log('create',c) # # def join (self, c): # self._log('join',c) # # def close (self, c): # self._log('close',c) # _session_cb = SessionCB() def _split_channel_info(rchannels): """ Splits the request query channel information for images into a sequence of channels, window ranges and channel colors. @param rchannels: The request string with channel info. E.g 1|100:505$0000FF,-2,3|620:3879$FF0000 @type rchannels: String @return: E.g. [1, -2, 3] [[100.0, 505.0], (None, None), [620.0, 3879.0]] [u'0000FF', None, u'FF0000'] @rtype: tuple of 3 lists """ channels = [] windows = [] colors = [] for chan in rchannels.split(","): # chan 1|12:1386r$0000FF chan = chan.split("|", 1) # chan ['1', '12:1386r$0000FF'] t = chan[0].strip() # t = '1' color = None # Not normally used... if t.find("$") >= 0: t, color = t.split("$") try: channels.append(int(t)) ch_window = (None, None) if len(chan) > 1: t = chan[1].strip() # t = '12:1386r$0000FF' if t.find("$") >= 0: t, color = t.split("$", 1) # color = '0000FF' # t = 12:1386 t = t.split(":") if len(t) == 2: try: ch_window = [float(x) for x in t] except ValueError: pass windows.append(ch_window) colors.append(color) except ValueError: pass logger.debug(str(channels) + "," + str(windows) + "," + str(colors)) return channels, windows, colors def getImgDetailsFromReq(request, as_string=False): """ Break the GET information from the request object into details on how to render the image. The following keys are recognized: z - Z axis position t - T axis position q - Quality set (0,0..1,0) m - Model (g for greyscale, c for color) p - Projection (see blitz_gateway.ImageWrapper.PROJECTIONS for keys) x - X position (for now based on top/left offset on the browser window) y - Y position (same as above) c - a comma separated list of channels to be rendered (start index 1) - format for each entry [-]ID[|wndst:wndend][#HEXCOLOR][,...] zm - the zoom setting (as a percentual value) @param request: http request with keys above @param as_string: If True, return a string representation of the rendering details @return: A dict or String representation of rendering details above. @rtype: Dict or String """ r = request.GET rv = {} for k in ("z", "t", "q", "m", "zm", "x", "y", "p"): if k in r: rv[k] = r[k] if "c" in r: rv["c"] = [] ci = _split_channel_info(r["c"]) logger.debug(ci) for i in range(len(ci[0])): # a = abs channel, i = channel, s = window start, e = window end, # c = color rv["c"].append( { "a": abs(ci[0][i]), "i": ci[0][i], "s": ci[1][i][0], "e": ci[1][i][1], "c": ci[2][i], } ) if as_string: return "&".join(["%s=%s" % (x[0], x[1]) for x in rv.items()]) return rv @login_required() def render_birds_eye_view(request, iid, size=None, conn=None, **kwargs): """ Returns an HttpResponse wrapped jpeg with the rendered bird's eye view for image 'iid'. We now use a thumbnail for performance. #10626 @param request: http request @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} connection @param size: Maximum size of the longest side of the resulting bird's eye view. @return: http response containing jpeg """ return render_thumbnail(request, iid, w=size, **kwargs) def _render_thumbnail(request, iid, w=None, h=None, conn=None, _defcb=None, **kwargs): """ Returns a jpeg with the rendered thumbnail for image 'iid' @param request: http request @param iid: Image ID @param w: Thumbnail max width. 96 by default @param h: Thumbnail max height @return: http response containing jpeg """ server_id = request.session["connector"].server_id server_settings = request.session.get("server_settings", {}).get("browser", {}) defaultSize = server_settings.get("thumb_default_size", 96) direct = True if w is None: size = (defaultSize,) else: if h is None: size = (int(w),) else: size = (int(w), int(h)) if size == (defaultSize,): direct = False user_id = conn.getUserId() z = getIntOrDefault(request, "z", None) t = getIntOrDefault(request, "t", None) rdefId = getIntOrDefault(request, "rdefId", None) # TODO - cache handles rdefId jpeg_data = webgateway_cache.getThumb(request, server_id, user_id, iid, size) if jpeg_data is None: prevent_cache = False img = conn.getObject("Image", iid) if img is None: logger.debug("(b)Image %s not found..." % (str(iid))) if _defcb: jpeg_data = _defcb(size=size) prevent_cache = True else: raise Http404("Failed to render thumbnail") else: jpeg_data = img.getThumbnail( size=size, direct=direct, rdefId=rdefId, z=z, t=t ) if jpeg_data is None: logger.debug("(c)Image %s not found..." % (str(iid))) if _defcb: jpeg_data = _defcb(size=size) prevent_cache = True else: raise Http404("Failed to render thumbnail") else: prevent_cache = img._thumbInProgress if not prevent_cache: webgateway_cache.setThumb(request, server_id, user_id, iid, jpeg_data, size) else: pass return jpeg_data @login_required() def render_thumbnail(request, iid, w=None, h=None, conn=None, _defcb=None, **kwargs): """ Returns an HttpResponse wrapped jpeg with the rendered thumbnail for image 'iid' @param request: http request @param iid: Image ID @param w: Thumbnail max width. 96 by default @param h: Thumbnail max height @return: http response containing jpeg """ jpeg_data = _render_thumbnail( request=request, iid=iid, w=w, h=h, conn=conn, _defcb=_defcb, **kwargs ) rsp = HttpResponse(jpeg_data, content_type="image/jpeg") return rsp @login_required() def render_roi_thumbnail(request, roiId, w=None, h=None, conn=None, **kwargs): """ For the given ROI, choose the shape to render (first time-point, mid z-section) then render a region around that shape, scale to width and height (or default size) and draw the shape on to the region """ server_id = request.session["connector"].server_id # need to find the z indices of the first shape in T result = conn.getRoiService().findByRoi(long(roiId), None, conn.SERVICE_OPTS) if result is None or result.rois is None or len(result.rois) == 0: raise Http404 for roi in result.rois: imageId = roi.image.id.val shapes = roi.copyShapes() shapes = [s for s in shapes if s is not None] if len(shapes) == 0: raise Http404("No Shapes found for ROI %s" % roiId) pi = _get_prepared_image(request, imageId, server_id=server_id, conn=conn) if pi is None: raise Http404 image, compress_quality = pi shape = None # if only single shape, use it... if len(shapes) == 1: shape = shapes[0] else: default_t = image.getDefaultT() default_z = image.getDefaultZ() # find shapes on default Z/T plane def_shapes = [ s for s in shapes if unwrap(s.getTheT()) is None or unwrap(s.getTheT()) == default_t ] if len(def_shapes) == 1: shape = def_shapes[0] else: def_shapes = [ s for s in def_shapes if unwrap(s.getTheZ()) is None or unwrap(s.getTheZ()) == default_z ] if len(def_shapes) > 0: shape = def_shapes[0] # otherwise pick first shape if shape is None and len(shapes) > 0: shape = shapes[0] return get_shape_thumbnail(request, conn, image, shape, compress_quality) @login_required() def render_shape_thumbnail(request, shapeId, w=None, h=None, conn=None, **kwargs): """ For the given Shape, redner a region around that shape, scale to width and height (or default size) and draw the shape on to the region. """ server_id = request.session["connector"].server_id # need to find the z indices of the first shape in T params = omero.sys.Parameters() params.map = {"id": rlong(shapeId)} shape = conn.getQueryService().findByQuery( "select s from Shape s join fetch s.roi where s.id = :id", params, conn.SERVICE_OPTS, ) if shape is None: raise Http404 imageId = shape.roi.image.id.val pi = _get_prepared_image(request, imageId, server_id=server_id, conn=conn) if pi is None: raise Http404 image, compress_quality = pi return get_shape_thumbnail(request, conn, image, shape, compress_quality) def get_shape_thumbnail(request, conn, image, s, compress_quality): """ Render a region around the specified Shape, scale to width and height (or default size) and draw the shape on to the region. Returns jpeg data. @param image: ImageWrapper @param s: omero.model.Shape """ MAX_WIDTH = 250 color = request.GET.get("color", "fff") colours = { "f00": (255, 0, 0), "0f0": (0, 255, 0), "00f": (0, 0, 255), "ff0": (255, 255, 0), "fff": (255, 255, 255), "000": (0, 0, 0), } lineColour = colours["f00"] if color in colours: lineColour = colours[color] # used for padding if we go outside the image area bg_color = (221, 221, 221) bBox = None # bounding box: (x, y, w, h) shape = {} theT = unwrap(s.getTheT()) theT = theT if theT is not None else image.getDefaultT() theZ = unwrap(s.getTheZ()) theZ = theZ if theZ is not None else image.getDefaultZ() if type(s) == omero.model.RectangleI: shape["type"] = "Rectangle" shape["x"] = s.getX().getValue() shape["y"] = s.getY().getValue() shape["width"] = s.getWidth().getValue() shape["height"] = s.getHeight().getValue() bBox = (shape["x"], shape["y"], shape["width"], shape["height"]) elif type(s) == omero.model.MaskI: shape["type"] = "Mask" shape["x"] = s.getX().getValue() shape["y"] = s.getY().getValue() shape["width"] = s.getWidth().getValue() shape["height"] = s.getHeight().getValue() bBox = (shape["x"], shape["y"], shape["width"], shape["height"]) # TODO: support for mask elif type(s) == omero.model.EllipseI: shape["type"] = "Ellipse" shape["x"] = int(s.getX().getValue()) shape["y"] = int(s.getY().getValue()) shape["radiusX"] = int(s.getRadiusX().getValue()) shape["radiusY"] = int(s.getRadiusY().getValue()) bBox = ( shape["x"] - shape["radiusX"], shape["y"] - shape["radiusY"], 2 * shape["radiusX"], 2 * shape["radiusY"], ) elif type(s) == omero.model.PolylineI: shape["type"] = "PolyLine" shape["xyList"] = points_string_to_XY_list(s.getPoints().getValue()) bBox = xy_list_to_bbox(shape["xyList"]) elif type(s) == omero.model.LineI: shape["type"] = "Line" shape["x1"] = int(s.getX1().getValue()) shape["x2"] = int(s.getX2().getValue()) shape["y1"] = int(s.getY1().getValue()) shape["y2"] = int(s.getY2().getValue()) x = min(shape["x1"], shape["x2"]) y = min(shape["y1"], shape["y2"]) bBox = ( x, y, max(shape["x1"], shape["x2"]) - x, max(shape["y1"], shape["y2"]) - y, ) elif type(s) == omero.model.PointI: shape["type"] = "Point" shape["x"] = s.getX().getValue() shape["y"] = s.getY().getValue() bBox = (shape["x"] - 50, shape["y"] - 50, 100, 100) elif type(s) == omero.model.PolygonI: shape["type"] = "Polygon" shape["xyList"] = points_string_to_XY_list(s.getPoints().getValue()) bBox = xy_list_to_bbox(shape["xyList"]) elif type(s) == omero.model.LabelI: shape["type"] = "Label" shape["x"] = s.getX().getValue() shape["y"] = s.getY().getValue() bBox = (shape["x"] - 50, shape["y"] - 50, 100, 100) else: logger.debug("Shape type not supported: %s" % str(type(s))) # we want to render a region larger than the bounding box x, y, w, h = bBox # make the aspect ratio (w/h) = 3/2 requiredWidth = max(w, h * 3 // 2) requiredHeight = requiredWidth * 2 // 3 # make the rendered region 1.5 times larger than the bounding box newW = int(requiredWidth * 1.5) newH = int(requiredHeight * 1.5) # Don't want the region to be smaller than the thumbnail dimensions if newW < MAX_WIDTH: newW = MAX_WIDTH newH = newW * 2 // 3 # Don't want the region to be bigger than a 'Big Image'! def getConfigValue(key): try: return conn.getConfigService().getConfigValue(key) except Exception: logger.warn( "webgateway: get_shape_thumbnail() could not get" " Config-Value for %s" % key ) pass max_plane_width = getConfigValue("omero.pixeldata.max_plane_width") max_plane_height = getConfigValue("omero.pixeldata.max_plane_height") if ( max_plane_width is None or max_plane_height is None or (newW > int(max_plane_width)) or (newH > int(max_plane_height)) ): # generate dummy image to return dummy = Image.new("RGB", (MAX_WIDTH, MAX_WIDTH * 2 // 3), bg_color) draw = ImageDraw.Draw(dummy) draw.text((10, 30), "Shape too large to \ngenerate thumbnail", fill=(255, 0, 0)) rv = BytesIO() dummy.save(rv, "jpeg", quality=90) return HttpResponse(rv.getvalue(), content_type="image/jpeg") xOffset = (newW - w) // 2 yOffset = (newH - h) // 2 newX = int(x - xOffset) newY = int(y - yOffset) # Need to check if any part of our region is outside the image. (assume # that SOME of the region is within the image!) sizeX = image.getSizeX() sizeY = image.getSizeY() left_xs, right_xs, top_xs, bottom_xs = 0, 0, 0, 0 if newX < 0: newW = newW + newX left_xs = abs(newX) newX = 0 if newY < 0: newH = newH + newY top_xs = abs(newY) newY = 0 if newW + newX > sizeX: right_xs = (newW + newX) - sizeX newW = newW - right_xs if newH + newY > sizeY: bottom_xs = (newH + newY) - sizeY newH = newH - bottom_xs # now we should be getting the correct region jpeg_data = image.renderJpegRegion( theZ, theT, newX, newY, newW, newH, level=None, compression=compress_quality ) img = Image.open(BytesIO(jpeg_data)) # add back on the xs we were forced to trim if left_xs != 0 or right_xs != 0 or top_xs != 0 or bottom_xs != 0: jpg_w, jpg_h = img.size xs_w = jpg_w + right_xs + left_xs xs_h = jpg_h + bottom_xs + top_xs xs_image = Image.new("RGB", (xs_w, xs_h), bg_color) xs_image.paste(img, (left_xs, top_xs)) img = xs_image # we have our full-sized region. Need to resize to thumbnail. current_w, current_h = img.size factor = float(MAX_WIDTH) / current_w resizeH = int(current_h * factor) img = img.resize((MAX_WIDTH, resizeH)) draw = ImageDraw.Draw(img) if shape["type"] == "Rectangle": rectX = int(xOffset * factor) rectY = int(yOffset * factor) rectW = int((w + xOffset) * factor) rectH = int((h + yOffset) * factor) draw.rectangle((rectX, rectY, rectW, rectH), outline=lineColour) # hack to get line width of 2 draw.rectangle((rectX - 1, rectY - 1, rectW + 1, rectH + 1), outline=lineColour) elif shape["type"] == "Line": lineX1 = (shape["x1"] - newX + left_xs) * factor lineX2 = (shape["x2"] - newX + left_xs) * factor lineY1 = (shape["y1"] - newY + top_xs) * factor lineY2 = (shape["y2"] - newY + top_xs) * factor draw.line((lineX1, lineY1, lineX2, lineY2), fill=lineColour, width=2) elif shape["type"] == "Ellipse": rectX = int(xOffset * factor) rectY = int(yOffset * factor) rectW = int((w + xOffset) * factor) rectH = int((h + yOffset) * factor) draw.ellipse((rectX, rectY, rectW, rectH), outline=lineColour) # hack to get line width of 2 draw.ellipse((rectX - 1, rectY - 1, rectW + 1, rectH + 1), outline=lineColour) elif shape["type"] == "Point": point_radius = 2 rectX = (MAX_WIDTH // 2) - point_radius rectY = int(resizeH // 2) - point_radius rectW = rectX + (point_radius * 2) rectH = rectY + (point_radius * 2) draw.ellipse((rectX, rectY, rectW, rectH), outline=lineColour) # hack to get line width of 2 draw.ellipse((rectX - 1, rectY - 1, rectW + 1, rectH + 1), outline=lineColour) elif "xyList" in shape: # resizedXY = [(int(x*factor), int(y*factor)) # for (x,y) in shape['xyList']] def resizeXY(xy): x, y = xy return ( int((x - newX + left_xs) * factor), int((y - newY + top_xs) * factor), ) resizedXY = [resizeXY(xy) for xy in shape["xyList"]] # doesn't support 'width' of line # draw.polygon(resizedXY, outline=lineColour) x2 = y2 = None for line in range(1, len(resizedXY)): x1, y1 = resizedXY[line - 1] x2, y2 = resizedXY[line] draw.line((x1, y1, x2, y2), fill=lineColour, width=2) start_x, start_y = resizedXY[0] if shape["type"] != "PolyLine": # Seems possible to have Polygon with only 1 point! if x2 is None: x2 = start_x + 1 # This will create a visible dot if y2 is None: y2 = start_y + 1 draw.line((x2, y2, start_x, start_y), fill=lineColour, width=2) rv = BytesIO() compression = 0.9 try: img.save(rv, "jpeg", quality=int(compression * 100)) jpeg = rv.getvalue() finally: rv.close() return HttpResponse(jpeg, content_type="image/jpeg") @login_required() def render_shape_mask(request, shapeId, conn=None, **kwargs): """ Returns mask as a png (supports transparency) """ if not numpyInstalled: raise NotImplementedError("numpy not installed") params = omero.sys.Parameters() params.map = {"id": rlong(shapeId)} shape = conn.getQueryService().findByQuery( "select s from Shape s where s.id = :id", params, conn.SERVICE_OPTS ) if shape is None: raise Http404("Shape ID: %s not found" % shapeId) width = int(shape.getWidth().getValue()) height = int(shape.getHeight().getValue()) color = unwrap(shape.getFillColor()) fill = (255, 255, 0, 255) if color is not None: color = rgb_int2rgba(color) fill = (color[0], color[1], color[2], int(color[3] * 255)) mask_packed = shape.getBytes() # convert bytearray into something we can use intarray = numpy.fromstring(mask_packed, dtype=numpy.uint8) binarray = numpy.unpackbits(intarray) # Couldn't get the 'proper' way of doing this to work, # TODO: look at this again later. Faster than simple way below: # E.g. takes ~2 seconds for 1984 x 1984 mask # pixels = "" # steps = len(binarray) / 8 # for i in range(steps): # b = binarray[i*8: (i+1)*8] # pixels += struct.pack("8B", b[0], b[1], b[2], b[3], b[4], # b[5], b[6], b[7]) # for b in binarray: # pixels += struct.pack("1B", b) # im = Image.frombytes("1", size=(width, height), data=pixels) # Simple approach - Just set each pixel in turn # E.g. takes ~12 seconds for 1984 x 1984 mask with most pixels '1' # Or ~5 seconds for same size mask with most pixels "0" img = Image.new("RGBA", size=(width, height), color=(0, 0, 0, 0)) x = 0 y = 0 for pix in binarray: if pix == 1: img.putpixel((x, y), fill) x += 1 if x > width - 1: x = 0 y += 1 rv = BytesIO() # return a png (supports transparency) img.save(rv, "png", quality=int(100)) png = rv.getvalue() return HttpResponse(png, content_type="image/png") def _get_signature_from_request(request): """ returns a string that identifies this image, along with the settings passed on the request. Useful for using as img identifier key, for prepared image. @param request: http request @return: String """ r = request.GET rv = r.get("m", "_") + r.get("p", "_") + r.get("c", "_") + r.get("q", "_") return rv def _get_maps_enabled(request, name, sizeC=0): """ Parses 'maps' query string from request """ codomains = None if "maps" in request: map_json = request["maps"] codomains = [] try: # If coming from request string, need to load -> json if isinstance(map_json, (unicode, str)): map_json = json.loads(map_json) sizeC = max(len(map_json), sizeC) for c in range(sizeC): enabled = None if len(map_json) > c: m = map_json[c].get(name) # If None, no change to saved status if m is not None: enabled = m.get("enabled") in (True, "true") codomains.append(enabled) except Exception: logger.debug("Invalid json for query ?maps=%s" % map_json) codomains = None return codomains def _get_prepared_image( request, iid, server_id=None, conn=None, saveDefs=False, retry=True ): """ Fetches the Image object for image 'iid' and prepares it according to the request query, setting the channels, rendering model and projection arguments. The compression level is parsed and returned too. For parameters in request, see L{getImgDetailsFromReq} @param request: http request @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} connection @param saveDefs: Try to save the rendering settings, default z and t. @param retry: Try an extra attempt at this method @return: Tuple (L{omero.gateway.ImageWrapper} image, quality) """ r = request.GET logger.debug( "Preparing Image:%r saveDefs=%r " "retry=%r request=%r conn=%s" % (iid, saveDefs, retry, r, str(conn)) ) img = conn.getObject("Image", iid) if img is None: return invert_flags = None if "maps" in r: reverses = _get_maps_enabled(r, "reverse", img.getSizeC()) # 'reverse' is now deprecated (5.4.0). Also check for 'invert' invert_flags = _get_maps_enabled(r, "inverted", img.getSizeC()) # invert is True if 'invert' OR 'reverse' is enabled if reverses is not None and invert_flags is not None: invert_flags = [ z[0] if z[0] is not None else z[1] for z in zip(invert_flags, reverses) ] try: # quantization maps (just applied, not saved at the moment) qm = [m.get("quantization") for m in json.loads(r["maps"])] img.setQuantizationMaps(qm) except Exception: logger.debug("Failed to set quantization maps") if "c" in r: logger.debug("c=" + r["c"]) activechannels, windows, colors = _split_channel_info(r["c"]) allchannels = range(1, img.getSizeC() + 1) # If saving, apply to all channels if saveDefs and not img.setActiveChannels( allchannels, windows, colors, invert_flags ): logger.debug("Something bad happened while setting the active channels...") # Save the active/inactive state of the channels if not img.setActiveChannels(activechannels, windows, colors, invert_flags): logger.debug("Something bad happened while setting the active channels...") if r.get("m", None) == "g": img.setGreyscaleRenderingModel() elif r.get("m", None) == "c": img.setColorRenderingModel() # projection 'intmax' OR 'intmax|5:25' p = r.get("p", None) pStart, pEnd = None, None if p is not None and len(p.split("|")) > 1: p, startEnd = p.split("|", 1) try: pStart, pEnd = [int(s) for s in startEnd.split(":")] except ValueError: pass img.setProjection(p) img.setProjectionRange(pStart, pEnd) img.setInvertedAxis(bool(r.get("ia", "0") == "1")) compress_quality = r.get("q", None) if saveDefs: "z" in r and img.setDefaultZ(long(r["z"]) - 1) "t" in r and img.setDefaultT(long(r["t"]) - 1) img.saveDefaults() return (img, compress_quality) @login_required() def render_image_region(request, iid, z, t, conn=None, **kwargs): """ Returns a jpeg of the OMERO image, rendering only a region specified in query string as region=x,y,width,height. E.g. region=0,512,256,256 Rendering settings can be specified in the request parameters. @param request: http request @param iid: image ID @param z: Z index @param t: T index @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping jpeg """ server_id = request.session["connector"].server_id # if the region=x,y,w,h is not parsed correctly to give 4 ints then we # simply provide whole image plane. # alternatively, could return a 404? # if h == None: # return render_image(request, iid, z, t, server_id=None, _conn=None, # **kwargs) pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn) if pi is None: raise Http404 img, compress_quality = pi tile = request.GET.get("tile", None) region = request.GET.get("region", None) level = None if tile: try: img._prepareRenderingEngine() w, h = img._re.getTileSize() levels = img._re.getResolutionLevels() - 1 zxyt = tile.split(",") # if tile size is given respect it if len(zxyt) > 4: tile_size = [int(zxyt[3]), int(zxyt[4])] tile_defaults = [w, h] max_tile_length = 1024 try: max_tile_length = int( conn.getConfigService().getConfigValue( "omero.pixeldata.max_tile_length" ) ) except Exception: pass for i, tile_length in enumerate(tile_size): # use default tile size if <= 0 if tile_length <= 0: tile_size[i] = tile_defaults[i] # allow no bigger than max_tile_length if tile_length > max_tile_length: tile_size[i] = max_tile_length w, h = tile_size v = int(zxyt[0]) if v < 0: msg = "Invalid resolution level %s < 0" % v logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) if levels == 0: # non pyramid file if v > 0: msg = "Invalid resolution level %s, non pyramid file" % v logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) else: level = None else: level = levels - v if level < 0: msg = ( "Invalid resolution level, \ %s > number of available levels %s " % (v, levels) ) logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) x = int(zxyt[1]) * w y = int(zxyt[2]) * h except Exception: msg = "malformed tile argument, tile=%s" % tile logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) elif region: try: xywh = region.split(",") x = int(xywh[0]) y = int(xywh[1]) w = int(xywh[2]) h = int(xywh[3]) except Exception: msg = "malformed region argument, region=%s" % region logger.debug(msg, exc_info=True) return HttpResponseBadRequest(msg) else: return HttpResponseBadRequest("tile or region argument required") # region details in request are used as key for caching. jpeg_data = webgateway_cache.getImage(request, server_id, img, z, t) if jpeg_data is None: jpeg_data = img.renderJpegRegion( z, t, x, y, w, h, level=level, compression=compress_quality ) if jpeg_data is None: raise Http404 webgateway_cache.setImage(request, server_id, img, z, t, jpeg_data) rsp = HttpResponse(jpeg_data, content_type="image/jpeg") return rsp @login_required() def render_image(request, iid, z=None, t=None, conn=None, **kwargs): """ Renders the image with id {{iid}} at {{z}} and {{t}} as jpeg. Many options are available from the request dict. See L{getImgDetailsFromReq} for list. I am assuming a single Pixels object on image with image-Id='iid'. May be wrong @param request: http request @param iid: image ID @param z: Z index @param t: T index @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping jpeg """ server_id = request.session["connector"].server_id pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn) if pi is None: raise Http404 img, compress_quality = pi jpeg_data = webgateway_cache.getImage(request, server_id, img, z, t) if jpeg_data is None: jpeg_data = img.renderJpeg(z, t, compression=compress_quality) if jpeg_data is None: raise Http404 webgateway_cache.setImage(request, server_id, img, z, t, jpeg_data) format = request.GET.get("format", "jpeg") rsp = HttpResponse(jpeg_data, content_type="image/jpeg") if "download" in kwargs and kwargs["download"]: if format == "png": # convert jpeg data to png... i = Image.open(BytesIO(jpeg_data)) output = BytesIO() i.save(output, "png") jpeg_data = output.getvalue() output.close() rsp = HttpResponse(jpeg_data, content_type="image/png") elif format == "tif": # convert jpeg data to TIFF i = Image.open(BytesIO(jpeg_data)) output = BytesIO() i.save(output, "tiff") jpeg_data = output.getvalue() output.close() rsp = HttpResponse(jpeg_data, content_type="image/tiff") fileName = img.getName() try: fileName = fileName.decode("utf8") except AttributeError: pass # python 3 fileName = fileName.replace(",", ".").replace(" ", "_") rsp["Content-Type"] = "application/force-download" rsp["Content-Length"] = len(jpeg_data) rsp["Content-Disposition"] = "attachment; filename=%s.%s" % (fileName, format) return rsp @login_required() def render_ome_tiff(request, ctx, cid, conn=None, **kwargs): """ Renders the OME-TIFF representation of the image(s) with id cid in ctx (i)mage, (d)ataset, or (p)roject. For multiple images export, images that require pixels pyramid (big images) will be silently skipped. If exporting a single big image or if all images in a multple image export are big, a 404 will be triggered. A request parameter dryrun can be passed to return the count of images that would actually be exported. @param request: http request @param ctx: 'p' or 'd' or 'i' @param cid: Project, Dataset or Image ID @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping the tiff (or zip for multiple files), or redirect to temp file/zip if dryrun is True, returns count of images that would be exported """ server_id = request.session["connector"].server_id imgs = [] if ctx == "p": obj = conn.getObject("Project", cid) if obj is None: raise Http404 for d in obj.listChildren(): imgs.extend(list(d.listChildren())) name = obj.getName() elif ctx == "d": obj = conn.getObject("Dataset", cid) if obj is None: raise Http404 imgs.extend(list(obj.listChildren())) selection = list(filter(None, request.GET.get("selection", "").split(","))) if len(selection) > 0: logger.debug(selection) logger.debug(imgs) imgs = [x for x in imgs if str(x.getId()) in selection] logger.debug(imgs) if len(imgs) == 0: raise Http404 name = "%s-%s" % (obj.getParent().getName(), obj.getName()) elif ctx == "w": obj = conn.getObject("Well", cid) if obj is None: raise Http404 imgs.extend([x.getImage() for x in obj.listChildren()]) plate = obj.getParent() coord = "%s%s" % ( plate.getRowLabels()[obj.row], plate.getColumnLabels()[obj.column], ) name = "%s-%s-%s" % (plate.getParent().getName(), plate.getName(), coord) else: obj = conn.getObject("Image", cid) if obj is None: raise Http404 imgs.append(obj) imgs = [x for x in imgs if not x.requiresPixelsPyramid()] if request.GET.get("dryrun", False): rv = json.dumps(len(imgs)) c = request.GET.get("callback", None) if c is not None and not kwargs.get("_internal", False): rv = "%s(%s)" % (c, rv) return HttpJavascriptResponse(rv) if len(imgs) == 0: raise Http404 if len(imgs) == 1: obj = imgs[0] key = ( "_".join((str(x.getId()) for x in obj.getAncestry())) + "_" + str(obj.getId()) + "_ome_tiff" ) # total name len <= 255, 9 is for .ome.tiff fnamemax = 255 - len(str(obj.getId())) - 10 objname = obj.getName()[:fnamemax] fpath, rpath, fobj = webgateway_tempfile.new( str(obj.getId()) + "-" + objname + ".ome.tiff", key=key ) if fobj is True: # already exists return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) tiff_data = webgateway_cache.getOmeTiffImage(request, server_id, imgs[0]) if tiff_data is None: try: tiff_data = imgs[0].exportOmeTiff() except Exception: logger.debug("Failed to export image (2)", exc_info=True) tiff_data = None if tiff_data is None: webgateway_tempfile.abort(fpath) raise Http404 webgateway_cache.setOmeTiffImage(request, server_id, imgs[0], tiff_data) if fobj is None: rsp = HttpResponse(tiff_data, content_type="image/tiff") rsp["Content-Disposition"] = 'attachment; filename="%s.ome.tiff"' % ( str(obj.getId()) + "-" + objname ) rsp["Content-Length"] = len(tiff_data) return rsp else: fobj.write(tiff_data) fobj.close() return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) else: try: img_ids = "+".join((str(x.getId()) for x in imgs)).encode("utf-8") key = ( "_".join((str(x.getId()) for x in imgs[0].getAncestry())) + "_" + md5(img_ids).hexdigest() + "_ome_tiff_zip" ) fpath, rpath, fobj = webgateway_tempfile.new(name + ".zip", key=key) if fobj is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) logger.debug(fpath) if fobj is None: fobj = BytesIO() zobj = zipfile.ZipFile(fobj, "w", zipfile.ZIP_STORED) for obj in imgs: tiff_data = webgateway_cache.getOmeTiffImage(request, server_id, obj) if tiff_data is None: tiff_data = obj.exportOmeTiff() if tiff_data is None: continue webgateway_cache.setOmeTiffImage(request, server_id, obj, tiff_data) # While ZIP itself doesn't have the 255 char limit for # filenames, the FS where these get unarchived might, so trim # names # total name len <= 255, 9 is for .ome.tiff fnamemax = 255 - len(str(obj.getId())) - 10 objname = obj.getName()[:fnamemax] zobj.writestr(str(obj.getId()) + "-" + objname + ".ome.tiff", tiff_data) zobj.close() if fpath is None: zip_data = fobj.getvalue() rsp = HttpResponse(zip_data, content_type="application/zip") rsp["Content-Disposition"] = 'attachment; filename="%s.zip"' % name rsp["Content-Length"] = len(zip_data) return rsp except Exception: logger.debug(traceback.format_exc()) raise return HttpResponseRedirect(settings.STATIC_URL + "webgateway/tfiles/" + rpath) @login_required() def render_movie(request, iid, axis, pos, conn=None, **kwargs): """ Renders a movie from the image with id iid @param request: http request @param iid: Image ID @param axis: Movie frames are along 'z' or 't' dimension. String @param pos: The T index (for z axis) or Z index (for t axis) @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping the file, or redirect to temp file """ server_id = request.session["connector"].server_id try: # Prepare a filename we'll use for temp cache, and check if file is # already there opts = {} opts["format"] = "video/" + request.GET.get("format", "quicktime") opts["fps"] = int(request.GET.get("fps", 4)) opts["minsize"] = (512, 512, "Black") ext = ".avi" key = "%s-%s-%s-%d-%s-%s" % ( iid, axis, pos, opts["fps"], _get_signature_from_request(request), request.GET.get("format", "quicktime"), ) pos = int(pos) pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn) if pi is None: raise Http404 img, compress_quality = pi fpath, rpath, fobj = webgateway_tempfile.new(img.getName() + ext, key=key) logger.debug(fpath, rpath, fobj) if fobj is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) # os.path.join(rpath, img.getName() + ext)) if "optsCB" in kwargs: opts.update(kwargs["optsCB"](img)) opts.update(kwargs.get("opts", {})) logger.debug( "rendering movie for img %s with axis %s, pos %i and opts %s" % (iid, axis, pos, opts) ) # fpath, rpath = webgateway_tempfile.newdir() if fpath is None: fo, fn = tempfile.mkstemp() else: fn = fpath # os.path.join(fpath, img.getName()) if axis.lower() == "z": dext, mimetype = img.createMovie( fn, 0, img.getSizeZ() - 1, pos - 1, pos - 1, opts ) else: dext, mimetype = img.createMovie( fn, pos - 1, pos - 1, 0, img.getSizeT() - 1, opts ) if dext is None and mimetype is None: # createMovie is currently only available on 4.1_custom # https://trac.openmicroscopy.org/ome/ticket/3857 raise Http404 if fpath is None: movie = open(fn).read() os.close(fo) rsp = HttpResponse(movie, content_type=mimetype) rsp["Content-Disposition"] = 'attachment; filename="%s"' % ( img.getName() + ext ) rsp["Content-Length"] = len(movie) return rsp else: fobj.close() # shutil.move(fn, fn + ext) return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + rpath ) # os.path.join(rpath, img.getName() + ext)) except Exception: logger.debug(traceback.format_exc()) raise @login_required() def render_split_channel(request, iid, z, t, conn=None, **kwargs): """ Renders a split channel view of the image with id {{iid}} at {{z}} and {{t}} as jpeg. Many options are available from the request dict. Requires Pillow to be installed on the server. @param request: http request @param iid: Image ID @param z: Z index @param t: T index @param conn: L{omero.gateway.BlitzGateway} connection @return: http response wrapping a jpeg """ server_id = request.session["connector"].server_id pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn) if pi is None: raise Http404 img, compress_quality = pi compress_quality = compress_quality and float(compress_quality) or 0.9 jpeg_data = webgateway_cache.getSplitChannelImage(request, server_id, img, z, t) if jpeg_data is None: jpeg_data = img.renderSplitChannel(z, t, compression=compress_quality) if jpeg_data is None: raise Http404 webgateway_cache.setSplitChannelImage(request, server_id, img, z, t, jpeg_data) rsp = HttpResponse(jpeg_data, content_type="image/jpeg") return rsp def debug(f): """ Decorator for adding debugging functionality to methods. @param f: The function to wrap @return: The wrapped function """ @wraps(f) def wrap(request, *args, **kwargs): debug = request.GET.getlist("debug") if "slow" in debug: time.sleep(5) if "fail" in debug: raise Http404 if "error" in debug: raise AttributeError("Debug requested error") return f(request, *args, **kwargs) return wrap def jsonp(f): """ Decorator for adding connection debugging and returning function result as json, depending on values in kwargs @param f: The function to wrap @return: The wrapped function, which will return json """ @wraps(f) def wrap(request, *args, **kwargs): logger.debug("jsonp") try: server_id = kwargs.get("server_id", None) if server_id is None and request.session.get("connector"): server_id = request.session["connector"].server_id kwargs["server_id"] = server_id rv = f(request, *args, **kwargs) if kwargs.get("_raw", False): return rv if isinstance(rv, HttpResponse): return rv c = request.GET.get("callback", None) if c is not None and not kwargs.get("_internal", False): rv = json.dumps(rv) rv = "%s(%s)" % (c, rv) # mimetype for JSONP is application/javascript return HttpJavascriptResponse(rv) if kwargs.get("_internal", False): return rv # mimetype for JSON is application/json # NB: To support old api E.g. /get_rois_json/ # We need to support lists safe = type(rv) is dict return JsonResponse(rv, safe=safe) except Exception as ex: # Default status is 500 'server error' # But we try to handle all 'expected' errors appropriately # TODO: handle omero.ConcurrencyException status = 500 if isinstance(ex, omero.SecurityViolation): status = 403 elif isinstance(ex, omero.ApiUsageException): status = 400 trace = traceback.format_exc() logger.debug(trace) if kwargs.get("_raw", False) or kwargs.get("_internal", False): raise return JsonResponse( {"message": str(ex), "stacktrace": trace}, status=status ) return wrap @debug @login_required() def render_row_plot(request, iid, z, t, y, conn=None, w=1, **kwargs): """ Renders the line plot for the image with id {{iid}} at {{z}} and {{t}} as gif with transparent background. Many options are available from the request dict. I am assuming a single Pixels object on image with Image ID='iid'. May be wrong TODO: cache @param request: http request @param iid: Image ID @param z: Z index @param t: T index @param y: Y position of row to measure @param conn: L{omero.gateway.BlitzGateway} connection @param w: Line width @return: http response wrapping a gif """ if not w: w = 1 pi = _get_prepared_image(request, iid, conn=conn) if pi is None: raise Http404 img, compress_quality = pi try: gif_data = img.renderRowLinePlotGif(int(z), int(t), int(y), int(w)) except Exception: logger.debug("a", exc_info=True) raise if gif_data is None: raise Http404 rsp = HttpResponse(gif_data, content_type="image/gif") return rsp @debug @login_required() def render_col_plot(request, iid, z, t, x, w=1, conn=None, **kwargs): """ Renders the line plot for the image with id {{iid}} at {{z}} and {{t}} as gif with transparent background. Many options are available from the request dict. I am assuming a single Pixels object on image with id='iid'. May be wrong TODO: cache @param request: http request @param iid: Image ID @param z: Z index @param t: T index @param x: X position of column to measure @param conn: L{omero.gateway.BlitzGateway} connection @param w: Line width @return: http response wrapping a gif """ if not w: w = 1 pi = _get_prepared_image(request, iid, conn=conn) if pi is None: raise Http404 img, compress_quality = pi gif_data = img.renderColLinePlotGif(int(z), int(t), int(x), int(w)) if gif_data is None: raise Http404 rsp = HttpResponse(gif_data, content_type="image/gif") return rsp @login_required() @jsonp def imageData_json(request, conn=None, _internal=False, **kwargs): """ Get a dict with image information TODO: cache @param request: http request @param conn: L{omero.gateway.BlitzGateway} @param _internal: TODO: ? @return: Dict """ iid = kwargs["iid"] key = kwargs.get("key", None) image = conn.getObject("Image", iid) if image is None: if is_public_user(request): # 403 - Should try logging in return HttpResponseForbidden() else: return HttpResponseNotFound("Image:%s not found" % iid) if request.GET.get("getDefaults") == "true": image.resetDefaults(save=False) rv = imageMarshal(image, key=key, request=request) return rv @login_required() @jsonp def wellData_json(request, conn=None, _internal=False, **kwargs): """ Get a dict with image information TODO: cache @param request: http request @param conn: L{omero.gateway.BlitzGateway} @param _internal: TODO: ? @return: Dict """ wid = kwargs["wid"] well = conn.getObject("Well", wid) if well is None: return HttpJavascriptResponseServerError('""') prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") def urlprefix(iid): return reverse(prefix, args=(iid,)) xtra = {"thumbUrlPrefix": kwargs.get("urlprefix", urlprefix)} rv = well.simpleMarshal(xtra=xtra) return rv @login_required() @jsonp def plateGrid_json(request, pid, field=0, conn=None, **kwargs): """""" try: field = long(field or 0) except ValueError: field = 0 prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") thumbsize = getIntOrDefault(request, "size", None) logger.debug(thumbsize) server_id = kwargs["server_id"] def get_thumb_url(iid): if thumbsize is not None: return reverse(prefix, args=(iid, thumbsize)) return reverse(prefix, args=(iid,)) plateGrid = PlateGrid(conn, pid, field, kwargs.get("urlprefix", get_thumb_url)) plate = plateGrid.plate if plate is None: return Http404 cache_key = "plategrid-%d-%s" % (field, thumbsize) rv = webgateway_cache.getJson(request, server_id, plate, cache_key) if rv is None: rv = plateGrid.metadata webgateway_cache.setJson(request, server_id, plate, json.dumps(rv), cache_key) else: rv = json.loads(rv) return rv @login_required() @jsonp def get_thumbnails_json(request, w=None, conn=None, **kwargs): """ Returns base64 encoded jpeg with the rendered thumbnail for images 'id' @param request: http request @param w: Thumbnail max width. 96 by default @return: http response containing base64 encoded thumbnails """ server_settings = request.session.get("server_settings", {}).get("browser", {}) defaultSize = server_settings.get("thumb_default_size", 96) if w is None: w = defaultSize image_ids = get_longs(request, "id") image_ids = list(set(image_ids)) # remove any duplicates # If we only have a single ID, simply use getThumbnail() if len(image_ids) == 1: iid = image_ids[0] try: data = _render_thumbnail(request, iid, w=w, conn=conn) return { iid: "data:image/jpeg;base64,%s" % base64.b64encode(data).decode("utf-8") } except Exception: return {iid: None} logger.debug("Image ids: %r" % image_ids) if len(image_ids) > settings.THUMBNAILS_BATCH: return HttpJavascriptResponseServerError( "Max %s thumbnails at a time." % settings.THUMBNAILS_BATCH ) thumbnails = conn.getThumbnailSet([rlong(i) for i in image_ids], w) rv = dict() for i in image_ids: rv[i] = None try: t = thumbnails[i] if len(t) > 0: # replace thumbnail urls by base64 encoded image rv[i] = "data:image/jpeg;base64,%s" % base64.b64encode(t).decode( "utf-8" ) except KeyError: logger.error("Thumbnail not available. (img id: %d)" % i) except Exception: logger.error(traceback.format_exc()) return rv @login_required() @jsonp def get_thumbnail_json(request, iid, w=None, h=None, conn=None, _defcb=None, **kwargs): """ Returns an HttpResponse base64 encoded jpeg with the rendered thumbnail for image 'iid' @param request: http request @param iid: Image ID @param w: Thumbnail max width. 96 by default @param h: Thumbnail max height @return: http response containing base64 encoded thumbnail """ jpeg_data = _render_thumbnail( request=request, iid=iid, w=w, h=h, conn=conn, _defcb=_defcb, **kwargs ) rv = "data:image/jpeg;base64,%s" % base64.b64encode(jpeg_data).decode("utf-8") return rv @login_required() @jsonp def listImages_json(request, did, conn=None, **kwargs): """ lists all Images in a Dataset, as json TODO: cache @param request: http request @param did: Dataset ID @param conn: L{omero.gateway.BlitzGateway} @return: list of image json. """ dataset = conn.getObject("Dataset", did) if dataset is None: return HttpJavascriptResponseServerError('""') prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") def urlprefix(iid): return reverse(prefix, args=(iid,)) xtra = { "thumbUrlPrefix": kwargs.get("urlprefix", urlprefix), "tiled": request.GET.get("tiled", False), } return [x.simpleMarshal(xtra=xtra) for x in dataset.listChildren()] @login_required() @jsonp def listWellImages_json(request, did, conn=None, **kwargs): """ lists all Images in a Well, as json TODO: cache @param request: http request @param did: Well ID @param conn: L{omero.gateway.BlitzGateway} @return: list of image json. """ well = conn.getObject("Well", did) acq = getIntOrDefault(request, "run", None) if well is None: return HttpJavascriptResponseServerError('""') prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") def urlprefix(iid): return reverse(prefix, args=(iid,)) xtra = {"thumbUrlPrefix": kwargs.get("urlprefix", urlprefix)} def marshal_pos(w): d = {} for x, p in (["x", w.getPosX()], ["y", w.getPosY()]): if p is not None: d[x] = {"value": p.getValue(), "unit": str(p.getUnit())} return d wellImgs = [] for ws in well.listChildren(): # optionally filter by acquisition 'run' if ( acq is not None and ws.plateAcquisition is not None and ws.plateAcquisition.id.val != acq ): continue img = ws.getImage() if img is not None: m = img.simpleMarshal(xtra=xtra) pos = marshal_pos(ws) if len(pos.keys()) > 0: m["position"] = pos wellImgs.append(m) return wellImgs @login_required() @jsonp def listDatasets_json(request, pid, conn=None, **kwargs): """ lists all Datasets in a Project, as json TODO: cache @param request: http request @param pid: Project ID @param conn: L{omero.gateway.BlitzGateway} @return: list of dataset json. """ project = conn.getObject("Project", pid) if project is None: return HttpJavascriptResponse("[]") return [x.simpleMarshal(xtra={"childCount": 0}) for x in project.listChildren()] @login_required() @jsonp def datasetDetail_json(request, did, conn=None, **kwargs): """ return json encoded details for a dataset TODO: cache """ ds = conn.getObject("Dataset", did) return ds.simpleMarshal() @login_required() @jsonp def listProjects_json(request, conn=None, **kwargs): """ lists all Projects, as json TODO: cache @param request: http request @param conn: L{omero.gateway.BlitzGateway} @return: list of project json. """ rv = [] for pr in conn.listProjects(): rv.append({"id": pr.id, "name": pr.name, "description": pr.description or ""}) return rv @login_required() @jsonp def projectDetail_json(request, pid, conn=None, **kwargs): """ grab details from one specific project TODO: cache @param request: http request @param pid: Project ID @param conn: L{omero.gateway.BlitzGateway} @return: project details as dict. """ pr = conn.getObject("Project", pid) rv = pr.simpleMarshal() return rv @jsonp def open_with_options(request, **kwargs): """ Make the settings.OPEN_WITH available via JSON """ open_with = settings.OPEN_WITH viewers = [] for ow in open_with: if len(ow) < 2: continue viewer = {} viewer["id"] = ow[0] try: viewer["url"] = reverse(ow[1]) except NoReverseMatch: viewer["url"] = ow[1] # try non-essential parameters... # NB: Need supported_objects OR script_url to enable plugin try: if len(ow) > 2: if "supported_objects" in ow[2]: viewer["supported_objects"] = ow[2]["supported_objects"] if "target" in ow[2]: viewer["target"] = ow[2]["target"] if "script_url" in ow[2]: # If we have an absolute url, use it... if ow[2]["script_url"].startswith("http"): viewer["script_url"] = ow[2]["script_url"] else: # ...otherwise, assume within static viewer["script_url"] = static(ow[2]["script_url"]) if "label" in ow[2]: viewer["label"] = ow[2]["label"] except Exception: # ignore invalid params pass viewers.append(viewer) return {"open_with_options": viewers} def searchOptFromRequest(request): """ Returns a dict of options for searching, based on parameters in the http request Request keys include: - ctx: (http request) 'imgs' to search only images - text: (http request) the actual text phrase - start: starting index (0 based) for result - limit: nr of results to retuen (0 == unlimited) - author: - grabData: - parents: @param request: http request @return: Dict of options """ try: r = request.GET opts = { "search": unicode(r.get("text", "")).encode("utf8"), "ctx": r.get("ctx", ""), "grabData": not not r.get("grabData", False), "parents": not not bool(r.get("parents", False)), "start": int(r.get("start", 0)), "limit": int(r.get("limit", 0)), "key": r.get("key", None), } author = r.get("author", "") if author: opts["search"] += " author:" + author return opts except Exception: logger.error(traceback.format_exc()) return {} @TimeIt(logging.INFO) @login_required() @jsonp def search_json(request, conn=None, **kwargs): """ Search for objects in blitz. Returns json encoded list of marshalled objects found by the search query Request keys include: - text: The text to search for - ctx: (http request) 'imgs' to search only images - text: (http request) the actual text phrase - start: starting index (0 based) for result - limit: nr of results to retuen (0 == unlimited) - author: - grabData: - parents: @param request: http request @param conn: L{omero.gateway.BlitzGateway} @return: json search results TODO: cache """ server_id = request.session["connector"].server_id opts = searchOptFromRequest(request) rv = [] logger.debug("searchObjects(%s)" % (opts["search"])) # search returns blitz_connector wrapper objects def urlprefix(iid): return reverse("webgateway_render_thumbnail", args=(iid,)) xtra = {"thumbUrlPrefix": kwargs.get("urlprefix", urlprefix)} try: if opts["ctx"] == "imgs": sr = conn.searchObjects(["image"], opts["search"], conn.SERVICE_OPTS) else: # searches P/D/I sr = conn.searchObjects(None, opts["search"], conn.SERVICE_OPTS) except ApiUsageException: return HttpJavascriptResponseServerError('"parse exception"') def marshal(): rv = [] if opts["grabData"] and opts["ctx"] == "imgs": bottom = min(opts["start"], len(sr) - 1) if opts["limit"] == 0: top = len(sr) else: top = min(len(sr), bottom + opts["limit"]) for i in range(bottom, top): e = sr[i] # for e in sr: try: rv.append( imageData_json( request, server_id, iid=e.id, key=opts["key"], conn=conn, _internal=True, ) ) except AttributeError as x: logger.debug( "(iid %i) ignoring Attribute Error: %s" % (e.id, str(x)) ) pass except omero.ServerError as x: logger.debug("(iid %i) ignoring Server Error: %s" % (e.id, str(x))) return rv else: return [x.simpleMarshal(xtra=xtra, parents=opts["parents"]) for x in sr] rv = timeit(marshal)() logger.debug(rv) return rv @require_POST @login_required() def save_image_rdef_json(request, iid, conn=None, **kwargs): """ Requests that the rendering defs passed in the request be set as the default for this image. Rendering defs in request listed at L{getImgDetailsFromReq} TODO: jsonp @param request: http request @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} @return: http response 'true' or 'false' """ server_id = request.session["connector"].server_id pi = _get_prepared_image( request, iid, server_id=server_id, conn=conn, saveDefs=True ) if pi is None: json_data = "false" else: user_id = pi[0]._conn.getEventContext().userId webgateway_cache.invalidateObject(server_id, user_id, pi[0]) pi[0].getThumbnail() json_data = "true" if request.GET.get("callback", None): json_data = "%s(%s)" % (request.GET["callback"], json_data) return HttpJavascriptResponse(json_data) @login_required() @jsonp def listLuts_json(request, conn=None, **kwargs): """ Lists lookup tables 'LUTs' availble for rendering This list is dynamic and will change if users add LUTs to their server. We include 'png_index' which is the index of each LUT within the static/webgateway/img/luts_10.png or -1 if LUT is not found. """ scriptService = conn.getScriptService() luts = scriptService.getScriptsByMimetype("text/x-lut") rv = [] for lut in luts: lutsrc = lut.path.val + lut.name.val png_index = LUTS_IN_PNG.index(lutsrc) if lutsrc in LUTS_IN_PNG else -1 rv.append( { "id": lut.id.val, "path": lut.path.val, "name": lut.name.val, "size": unwrap(lut.size), "png_index": png_index, } ) rv.sort(key=lambda x: x["name"].lower()) return {"luts": rv, "png_luts": LUTS_IN_PNG} @login_required() def list_compatible_imgs_json(request, iid, conn=None, **kwargs): """ Lists the images on the same project that would be viable targets for copying rendering settings. TODO: change method to: list_compatible_imgs_json (request, iid, server_id=None, conn=None, **kwargs): @param request: http request @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} @return: json list of image IDs """ json_data = "false" r = request.GET if conn is None: img = None else: img = conn.getObject("Image", iid) if img is not None: # List all images in project imgs = [] for ds in img.getProject().listChildren(): imgs.extend(ds.listChildren()) # Filter the ones that would pass the applySettingsToImages call img_ptype = img.getPrimaryPixels().getPixelsType().getValue() img_ccount = img.getSizeC() img_ew = [x.getLabel() for x in img.getChannels()] img_ew.sort() def compat(i): if long(i.getId()) == long(iid): return False pp = i.getPrimaryPixels() if ( pp is None or i.getPrimaryPixels().getPixelsType().getValue() != img_ptype or i.getSizeC() != img_ccount ): return False ew = [x.getLabel() for x in i.getChannels()] ew.sort() if ew != img_ew: return False return True imgs = filter(compat, imgs) json_data = json.dumps([x.getId() for x in imgs]) if r.get("callback", None): json_data = "%s(%s)" % (r["callback"], json_data) return HttpJavascriptResponse(json_data) @require_POST @login_required() @jsonp def reset_rdef_json(request, toOwners=False, conn=None, **kwargs): """ Simply takes request 'to_type' and 'toids' and delegates to Rendering Settings service to reset settings accordings. @param toOwners: if True, default to the owner's settings. """ r = request.POST toids = r.getlist("toids") to_type = str(r.get("to_type", "image")) to_type = to_type.title() if to_type == "Acquisition": to_type = "PlateAcquisition" if len(toids) == 0: raise Http404( "Need to specify objects in request, E.g." " ?totype=dataset&toids=1&toids=2" ) toids = [int(id) for id in toids] rss = conn.getRenderingSettingsService() # get the first object and set the group to match conn.SERVICE_OPTS.setOmeroGroup("-1") o = conn.getObject(to_type, toids[0]) if o is not None: gid = o.getDetails().group.id.val conn.SERVICE_OPTS.setOmeroGroup(gid) if toOwners: rv = rss.resetDefaultsByOwnerInSet(to_type, toids, conn.SERVICE_OPTS) else: rv = rss.resetDefaultsInSet(to_type, toids, conn.SERVICE_OPTS) return rv @login_required() @jsonp def copy_image_rdef_json(request, conn=None, **kwargs): """ If 'fromid' is in request, copy the image ID to session, for applying later using this same method. If list of 'toids' is in request, paste the image ID from the session to the specified images. If 'fromid' AND 'toids' are in the reqest, we simply apply settings and don't save anything to request. If 'to_type' is in request, this can be 'dataset', 'plate', 'acquisition' Returns json dict of Boolean:[Image-IDs] for images that have successfully had the rendering settings applied, or not. @param request: http request @param server_id: @param conn: L{omero.gateway.BlitzGateway} @return: json dict of Boolean:[Image-IDs] """ server_id = request.session["connector"].server_id json_data = False fromid = request.GET.get("fromid", None) toids = request.POST.getlist("toids") to_type = str(request.POST.get("to_type", "image")) rdef = None if to_type not in ("dataset", "plate", "acquisition"): to_type = "Image" # default is image # Only 'fromid' is given, simply save to session if fromid is not None and len(toids) == 0: request.session.modified = True request.session["fromid"] = fromid if request.session.get("rdef") is not None: del request.session["rdef"] return True # If we've got an rdef encoded in request instead of ImageId... r = request.GET or request.POST if r.get("c") is not None: # make a map of settings we need rdef = {"c": str(r.get("c"))} # channels if r.get("maps"): try: rdef["maps"] = json.loads(r.get("maps")) except Exception: pass if r.get("pixel_range"): rdef["pixel_range"] = str(r.get("pixel_range")) if r.get("m"): rdef["m"] = str(r.get("m")) # model (grey) if r.get("z"): rdef["z"] = str(r.get("z")) # z & t pos if r.get("t"): rdef["t"] = str(r.get("t")) imageId = request.GET.get("imageId", request.POST.get("imageId", None)) if imageId: rdef["imageId"] = int(imageId) if request.method == "GET": request.session.modified = True request.session["rdef"] = rdef # remove any previous rdef we may have via 'fromId' if request.session.get("fromid") is not None: del request.session["fromid"] return True # Check session for 'fromid' if fromid is None: fromid = request.session.get("fromid", None) # maybe these pair of methods should be on ImageWrapper?? def getRenderingSettings(image): rv = {} chs = [] maps = [] for i, ch in enumerate(image.getChannels()): act = "" if ch.isActive() else "-" start = ch.getWindowStart() end = ch.getWindowEnd() color = ch.getLut() maps.append({"inverted": {"enabled": ch.isInverted()}}) if not color or len(color) == 0: color = ch.getColor().getHtml() chs.append("%s%s|%s:%s$%s" % (act, i + 1, start, end, color)) rv["c"] = ",".join(chs) rv["maps"] = maps rv["m"] = "g" if image.isGreyscaleRenderingModel() else "c" rv["z"] = image.getDefaultZ() + 1 rv["t"] = image.getDefaultT() + 1 return rv def applyRenderingSettings(image, rdef): invert_flags = _get_maps_enabled(rdef, "inverted", image.getSizeC()) channels, windows, colors = _split_channel_info(rdef["c"]) # also prepares _re image.setActiveChannels(channels, windows, colors, invert_flags) if rdef["m"] == "g": image.setGreyscaleRenderingModel() else: image.setColorRenderingModel() if "z" in rdef: image._re.setDefaultZ(long(rdef["z"]) - 1) if "t" in rdef: image._re.setDefaultT(long(rdef["t"]) - 1) image.saveDefaults() # Use rdef from above or previously saved one... if rdef is None: rdef = request.session.get("rdef") if request.method == "POST": originalSettings = None fromImage = None if fromid is None: # if we have rdef, save to source image, then use that image as # 'fromId', then revert. if rdef is not None and len(toids) > 0: fromImage = conn.getObject("Image", rdef["imageId"]) if fromImage is not None: # copy orig settings originalSettings = getRenderingSettings(fromImage) applyRenderingSettings(fromImage, rdef) fromid = fromImage.getId() # If we have both, apply settings... try: fromid = long(fromid) toids = [long(x) for x in toids] except TypeError: fromid = None except ValueError: fromid = None if fromid is not None and len(toids) > 0: fromimg = conn.getObject("Image", fromid) userid = fromimg.getOwner().getId() json_data = conn.applySettingsToSet(fromid, to_type, toids) if json_data and True in json_data: for iid in json_data[True]: img = conn.getObject("Image", iid) img is not None and webgateway_cache.invalidateObject( server_id, userid, img ) # finally - if we temporarily saved rdef to original image, revert # if we're sure that from-image is not in the target set (Dataset etc) if to_type == "Image" and fromid not in toids: if originalSettings is not None and fromImage is not None: applyRenderingSettings(fromImage, originalSettings) return json_data else: return HttpResponseNotAllowed(["POST"]) @login_required() @jsonp def get_image_rdef_json(request, conn=None, **kwargs): """ Gets any 'rdef' dict from the request.session and returns it as json """ rdef = request.session.get("rdef") image = None if rdef is None: fromid = request.session.get("fromid", None) if fromid is not None: # We only have an Image to copy rdefs from image = conn.getObject("Image", fromid) if image is not None: rv = imageMarshal(image, request=request) chs = [] maps = [] for i, ch in enumerate(rv["channels"]): act = ch["active"] and str(i + 1) or "-%s" % (i + 1) color = ch.get("lut") or ch["color"] chs.append( "%s|%s:%s$%s" % (act, ch["window"]["start"], ch["window"]["end"], color) ) maps.append( { "inverted": {"enabled": ch["inverted"]}, "quantization": { "coefficient": ch["coefficient"], "family": ch["family"], }, } ) rdef = { "c": (",".join(chs)), "m": rv["rdefs"]["model"], "pixel_range": "%s:%s" % (rv["pixel_range"][0], rv["pixel_range"][1]), "maps": maps, } return {"rdef": rdef} @login_required() def full_viewer(request, iid, conn=None, **kwargs): """ This view is responsible for showing the omero_image template Image rendering options in request are used in the display page. See L{getImgDetailsFromReq}. @param request: http request. @param iid: Image ID @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: Can be used to specify the html 'template' for rendering @return: html page of image and metadata """ server_id = request.session["connector"].server_id server_name = Server.get(server_id).server rid = getImgDetailsFromReq(request) server_settings = request.session.get("server_settings", {}).get("viewer", {}) interpolate = server_settings.get("interpolate_pixels", True) roiLimit = server_settings.get("roi_limit", 2000) try: image = conn.getObject("Image", iid) if image is None: logger.debug("(a)Image %s not found..." % (str(iid))) raise Http404 opengraph = None twitter = None image_preview = None page_url = None if hasattr(settings, "SHARING_OPENGRAPH"): opengraph = settings.SHARING_OPENGRAPH.get(server_name) logger.debug("Open Graph enabled: %s", opengraph) if hasattr(settings, "SHARING_TWITTER"): twitter = settings.SHARING_TWITTER.get(server_name) logger.debug("Twitter enabled: %s", twitter) if opengraph or twitter: urlargs = {"iid": iid} prefix = kwargs.get("thumbprefix", "webgateway_render_thumbnail") image_preview = request.build_absolute_uri(reverse(prefix, kwargs=urlargs)) page_url = request.build_absolute_uri( reverse("webgateway_full_viewer", kwargs=urlargs) ) d = { "blitzcon": conn, "image": image, "opts": rid, "interpolate": interpolate, "build_year": build_year, "roiLimit": roiLimit, "roiCount": image.getROICount(), "viewport_server": kwargs.get( # remove any trailing slash "viewport_server", reverse("webgateway"), ).rstrip("/"), "opengraph": opengraph, "twitter": twitter, "image_preview": image_preview, "page_url": page_url, "object": "image:%i" % int(iid), } template = kwargs.get("template", "webgateway/viewport/omero_image.html") rsp = render(request, template, d) except omero.SecurityViolation: logger.warn("SecurityViolation in Image:%s", iid) logger.warn(traceback.format_exc()) raise Http404 return HttpResponse(rsp) @login_required() def download_as(request, iid=None, conn=None, **kwargs): """ Downloads the image as a single jpeg/png/tiff or as a zip (if more than one image) """ format = request.GET.get("format", "png") if format not in ("jpeg", "png", "tif"): format = "png" imgIds = [] wellIds = [] if iid is None: imgIds = request.GET.getlist("image") if len(imgIds) == 0: wellIds = request.GET.getlist("well") if len(wellIds) == 0: return HttpResponseServerError( "No images or wells specified in request." " Use ?image=123 or ?well=123" ) else: imgIds = [iid] images = [] if imgIds: images = list(conn.getObjects("Image", imgIds)) elif wellIds: try: index = int(request.GET.get("index", 0)) except ValueError: index = 0 for w in conn.getObjects("Well", wellIds): images.append(w.getWellSample(index).image()) if len(images) == 0: msg = "Cannot download as %s. Images (ids: %s) not found." % (format, imgIds) logger.debug(msg) return HttpResponseServerError(msg) if len(images) == 1: jpeg_data = images[0].renderJpeg() if jpeg_data is None: raise Http404 rsp = HttpResponse(jpeg_data, mimetype="image/jpeg") rsp["Content-Length"] = len(jpeg_data) rsp["Content-Disposition"] = "attachment; filename=%s.jpg" % ( images[0].getName().replace(" ", "_") ) else: temp = tempfile.NamedTemporaryFile(suffix=".download_as") def makeImageName(originalName, extension, folder_name): name = os.path.basename(originalName) imgName = "%s.%s" % (name, extension) imgName = os.path.join(folder_name, imgName) # check we don't overwrite existing file i = 1 name = imgName[: -(len(extension) + 1)] while os.path.exists(imgName): imgName = "%s_(%d).%s" % (name, i, extension) i += 1 return imgName try: temp_zip_dir = tempfile.mkdtemp() logger.debug("download_as dir: %s" % temp_zip_dir) try: for img in images: z = t = None try: pilImg = img.renderImage(z, t) imgPathName = makeImageName(img.getName(), format, temp_zip_dir) pilImg.save(imgPathName) finally: # Close RenderingEngine img._re.close() # create zip zip_file = zipfile.ZipFile(temp, "w", zipfile.ZIP_DEFLATED) try: a_files = os.path.join(temp_zip_dir, "*") for name in glob.glob(a_files): zip_file.write(name, os.path.basename(name)) finally: zip_file.close() finally: shutil.rmtree(temp_zip_dir, ignore_errors=True) zipName = request.GET.get("zipname", "Download_as_%s" % format) zipName = zipName.replace(" ", "_") if not zipName.endswith(".zip"): zipName = "%s.zip" % zipName # return the zip or single file rsp = StreamingHttpResponse(FileWrapper(temp)) rsp["Content-Length"] = temp.tell() rsp["Content-Disposition"] = "attachment; filename=%s" % zipName temp.seek(0) except Exception: temp.close() stack = traceback.format_exc() logger.error(stack) return HttpResponseServerError("Cannot download file (id:%s)" % iid) rsp["Content-Type"] = "application/force-download" return rsp @login_required(doConnectionCleanup=False) def archived_files(request, iid=None, conn=None, **kwargs): """ Downloads the archived file(s) as a single file or as a zip (if more than one file) """ imgIds = [] wellIds = [] imgIds = request.GET.getlist("image") wellIds = request.GET.getlist("well") if iid is None: if len(imgIds) == 0 and len(wellIds) == 0: return HttpResponseServerError( "No images or wells specified in request." " Use ?image=123 or ?well=123" ) else: imgIds = [iid] images = list() wells = list() if imgIds: images = list(conn.getObjects("Image", imgIds)) elif wellIds: try: index = int(request.GET.get("index", 0)) except ValueError: index = 0 wells = conn.getObjects("Well", wellIds) for w in wells: images.append(w.getWellSample(index).image()) if len(images) == 0: message = ( "Cannot download archived file because Images not " "found (ids: %s)" % (imgIds) ) logger.debug(message) return HttpResponseServerError(message) # Test permissions on images and weels for ob in wells: if hasattr(ob, "canDownload"): if not ob.canDownload(): return HttpResponseNotFound() for ob in images: well = None try: well = ob.getParent().getParent() except Exception: if hasattr(ob, "canDownload"): if not ob.canDownload(): return HttpResponseNotFound() else: if well and isinstance(well, omero.gateway.WellWrapper): if hasattr(well, "canDownload"): if not well.canDownload(): return HttpResponseNotFound() # make list of all files, removing duplicates fileMap = {} for image in images: for f in image.getImportedImageFiles(): fileMap[f.getId()] = f files = list(fileMap.values()) if len(files) == 0: message = ( "Tried downloading archived files from image with no" " files archived." ) logger.debug(message) return HttpResponseServerError(message) if len(files) == 1: orig_file = files[0] rsp = ConnCleaningHttpResponse( orig_file.getFileInChunks(buf=settings.CHUNK_SIZE) ) rsp.conn = conn rsp["Content-Length"] = orig_file.getSize() # ',' in name causes duplicate headers fname = orig_file.getName().replace(" ", "_").replace(",", ".") rsp["Content-Disposition"] = "attachment; filename=%s" % (fname) else: total_size = sum(f.size for f in files) if total_size > settings.MAXIMUM_MULTIFILE_DOWNLOAD_ZIP_SIZE: message = ( "Total size of files %d is larger than %d. " "Try requesting fewer files." % (total_size, settings.MAXIMUM_MULTIFILE_DOWNLOAD_ZIP_SIZE) ) logger.warn(message) return HttpResponseForbidden(message) temp = tempfile.NamedTemporaryFile(suffix=".archive") zipName = request.GET.get("zipname", image.getName()) try: zipName = zip_archived_files(images, temp, zipName, buf=settings.CHUNK_SIZE) # return the zip or single file archivedFile_data = FileWrapper(temp) rsp = ConnCleaningHttpResponse(archivedFile_data) rsp.conn = conn rsp["Content-Length"] = temp.tell() rsp["Content-Disposition"] = "attachment; filename=%s" % zipName temp.seek(0) except Exception: temp.close() message = "Cannot download file (id:%s)" % (iid) logger.error(message, exc_info=True) return HttpResponseServerError(message) rsp["Content-Type"] = "application/force-download" return rsp @login_required() @jsonp def original_file_paths(request, iid, conn=None, **kwargs): """ Get a list of path/name strings for original files associated with the image """ image = conn.getObject("Image", iid) if image is None: raise Http404 paths = image.getImportedImageFilePaths() return {"repo": paths["server_paths"], "client": paths["client_paths"]} @login_required() @jsonp def get_shape_json(request, roiId, shapeId, conn=None, **kwargs): roiId = int(roiId) shapeId = int(shapeId) shape = conn.getQueryService().findByQuery( "select shape from Roi as roi " "join roi.shapes as shape " "where roi.id = %d and shape.id = %d" % (roiId, shapeId), None, ) logger.debug("Shape: %r" % shape) if shape is None: logger.debug("No such shape: %r" % shapeId) raise Http404 return JsonResponse(shapeMarshal(shape)) @login_required() @jsonp def get_rois_json(request, imageId, conn=None, **kwargs): """ Returns json data of the ROIs in the specified image. """ rois = [] roiService = conn.getRoiService() # rois = webfigure_utils.getRoiShapes(roiService, long(imageId)) # gets a # whole json list of ROIs result = roiService.findByImage(long(imageId), None, conn.SERVICE_OPTS) for r in result.rois: roi = {} roi["id"] = r.getId().getValue() # go through all the shapes of the ROI shapes = [] for s in r.copyShapes(): if s is None: # seems possible in some situations continue shapes.append(shapeMarshal(s)) # sort shapes by Z, then T. shapes.sort(key=lambda x: "%03d%03d" % (x.get("theZ", -1), x.get("theT", -1))) roi["shapes"] = shapes rois.append(roi) # sort by ID - same as in measurement tool. rois.sort(key=lambda x: x["id"]) return rois @login_required() def histogram_json(request, iid, theC, conn=None, **kwargs): """ Returns a histogram for a single channel as a list of 256 values as json """ image = conn.getObject("Image", iid) if image is None: raise Http404 maxW, maxH = conn.getMaxPlaneSize() sizeX = image.getSizeX() sizeY = image.getSizeY() if (sizeX * sizeY) > (maxW * maxH): msg = "Histogram not supported for 'big' images (over %s * %s pixels)" % ( maxW, maxH, ) return JsonResponse({"error": msg}) theZ = int(request.GET.get("theZ", 0)) theT = int(request.GET.get("theT", 0)) theC = int(theC) binCount = int(request.GET.get("bins", 256)) # TODO: handle projection when supported by OMERO data = image.getHistogram([theC], binCount, theZ=theZ, theT=theT) histogram = data[theC] return JsonResponse({"data": histogram}) @login_required(isAdmin=True) @jsonp def su(request, user, conn=None, **kwargs): """ If current user is admin, switch the session to a new connection owned by 'user' (puts the new session ID in the request.session) Return False if not possible @param request: http request. @param user: Username of new connection owner @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: Can be used to specify the html 'template' for rendering @return: Boolean """ if request.method == "POST": conn.setGroupNameForSession("system") connector = request.session["connector"] connector = Connector(connector.server_id, connector.is_secure) session = conn.getSessionService().getSession(conn._sessionUuid) ttl = session.getTimeToIdle().val connector.omero_session_key = conn.suConn(user, ttl=ttl)._sessionUuid request.session["connector"] = connector conn.revertGroupForSession() conn.close() return True else: context = { "url": reverse("webgateway_su", args=[user]), "submit": "Do you want to su to %s" % user, } template = "webgateway/base/includes/post_form.html" return render(request, template, context) def _annotations(request, objtype, objid, conn=None, **kwargs): warnings.warn("Deprecated. Use _bulk_file_annotations()", DeprecationWarning) return _bulk_file_annotations(request, objtype, objid, conn, **kwargs) def _bulk_file_annotations(request, objtype, objid, conn=None, **kwargs): """ Retrieve Bulk FileAnnotations for object specified by object type and identifier optionally traversing object model graph. Returns dictionary containing annotations in NSBULKANNOTATIONS namespace if successful, otherwise returns error information. If the graph has multiple parents, we return annotations from all parents. Example: /annotations/Plate/1/ retrieves annotations for plate with identifier 1 Example: /annotations/Plate.wells/1/ retrieves annotations for plate that contains well with identifier 1 Example: /annotations/Screen.plateLinks.child.wells/22/ retrieves annotations for screen that contains plate with well with identifier 22 @param request: http request. @param objtype: Type of target object, or type of target object followed by a slash-separated list of properties to resolve @param objid: Identifier of target object, or identifier of object reached by resolving given properties @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: unused @return: A dictionary with key 'error' with an error message or with key 'data' containing an array of dictionaries with keys 'id' and 'file' of the retrieved annotations """ q = conn.getQueryService() # If more than one objtype is specified, use all in query to # traverse object model graph # Example: /annotations/Plate/wells/1/ # retrieves annotations from Plate that contains Well 1 objtype = objtype.split(".") params = omero.sys.ParametersI() params.addId(objid) params.addString("ns", NSBULKANNOTATIONS) params.addString("mt", "OMERO.tables") query = "select obj0 from %s obj0\n" % objtype[0] for i, t in enumerate(objtype[1:]): query += "join fetch obj%d.%s obj%d\n" % (i, t, i + 1) query += """ left outer join fetch obj0.annotationLinks links left outer join fetch links.child as f left outer join fetch links.parent left outer join fetch f.file join fetch links.details.owner join fetch links.details.creationEvent where obj%d.id=:id and (f.ns=:ns or f.file.mimetype=:mt)""" % ( len(objtype) - 1 ) ctx = conn.createServiceOptsDict() ctx.setOmeroGroup("-1") try: objs = q.findAllByQuery(query, params, ctx) except omero.QueryException: return dict(error="%s cannot be queried" % objtype, query=query) data = [] # Process all annotations from all objects... links = [link for obj in objs for link in obj.copyAnnotationLinks()] for link in links: annotation = link.child if not isinstance(annotation, omero.model.FileAnnotation): continue owner = annotation.details.owner ownerName = "%s %s" % (unwrap(owner.firstName), unwrap(owner.lastName)) addedBy = link.details.owner addedByName = "%s %s" % (unwrap(addedBy.firstName), unwrap(addedBy.lastName)) data.append( dict( id=annotation.id.val, file=annotation.file.id.val, parentType=objtype[0], parentId=link.parent.id.val, owner=ownerName, addedBy=addedByName, addedOn=unwrap(link.details.creationEvent._time), ) ) return dict(data=data) annotations = login_required()(jsonp(_bulk_file_annotations)) def _table_query(request, fileid, conn=None, query=None, lazy=False, **kwargs): """ Query a table specified by fileid Returns a dictionary with query result if successful, error information otherwise @param request: http request; querystring must contain key 'query' with query to be executed, or '*' to retrieve all rows. If query is in the format word-number, e.g. "Well-7", if will be run as (word==number), e.g. "(Well==7)". This is supported to allow more readable query strings. @param fileid: Numeric identifier of file containing the table @param query: The table query. If None, use request.GET.get('query') E.g. '*' to return all rows. If in the form 'colname-1', query will be (colname==1) @param lazy: If True, instead of returning a 'rows' list, 'lazy_rows' will be a generator. Each gen.next() will return a list of row data AND 'table' returned MUST be closed. @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: offset, limit @return: A dictionary with key 'error' with an error message or with key 'data' containing a dictionary with keys 'columns' (an array of column names) and 'rows' (an array of rows, each an array of values) """ if query is None: query = request.GET.get("query") if not query: return dict(error="Must specify query parameter, use * to retrieve all") col_names = request.GET.getlist("col_names") ctx = conn.createServiceOptsDict() ctx.setOmeroGroup("-1") r = conn.getSharedResources() t = r.openTable(omero.model.OriginalFileI(fileid), ctx) if not t: return dict(error="Table %s not found" % fileid) try: cols = t.getHeaders() col_indices = range(len(cols)) if col_names: enumerated_columns = ( [(i, j) for (i, j) in enumerate(cols) if j.name in col_names] if col_names else [(i, j) for (i, j) in enumerate(cols)] ) cols = [] col_indices = [] for col_name in col_names: for (i, j) in enumerated_columns: if col_name == j.name: col_indices.append(i) cols.append(j) break rows = t.getNumberOfRows() offset = kwargs.get("offset", 0) limit = kwargs.get("limit", None) if not offset: offset = int(request.GET.get("offset", 0)) if not limit: limit = ( int(request.GET.get("limit")) if request.GET.get("limit") is not None else rows ) range_start = offset range_size = limit range_end = min(rows, range_start + range_size) if query == "*": hits = range(range_start, range_end) totalCount = rows else: match = re.match(r"^(\w+)-(\d+)", query) if match: query = "(%s==%s)" % (match.group(1), match.group(2)) try: logger.info(query) hits = t.getWhereList(query, None, 0, rows, 1) totalCount = len(hits) # paginate the hits hits = hits[range_start:range_end] except Exception: return dict(error="Error executing query: %s" % query) def row_generator(table, h): # hits are all consecutive rows - can load them in batches idx = 0 batch = 1000 while idx < len(h): batch = min(batch, len(h) - idx) res = table.slice(col_indices, h[idx : idx + batch]) idx += batch # yield a list of rows yield [ [col.values[row] for col in res.columns] for row in range(0, len(res.rowNumbers)) ] row_gen = row_generator(t, hits) rsp_data = { "data": { "column_types": [col.__class__.__name__ for col in cols], "columns": [col.name for col in cols], }, "meta": { "rowCount": rows, "totalCount": totalCount, "limit": limit, "offset": offset, }, } if not lazy: row_data = [] # Use the generator to add all rows in batches for rows in list(row_gen): row_data.extend(rows) rsp_data["data"]["rows"] = row_data else: rsp_data["data"]["lazy_rows"] = row_gen rsp_data["table"] = t return rsp_data finally: if not lazy: t.close() table_query = login_required()(jsonp(_table_query)) def _table_metadata(request, fileid, conn=None, query=None, lazy=False, **kwargs): ctx = conn.createServiceOptsDict() ctx.setOmeroGroup("-1") r = conn.getSharedResources() t = r.openTable(omero.model.OriginalFileI(fileid), ctx) if not t: return dict(error="Table %s not found" % fileid) try: cols = t.getHeaders() rows = t.getNumberOfRows() rsp_data = { "columns": [ { "name": col.name, "description": col.description, "type": col.__class__.__name__, } for col in cols ], "totalCount": rows, } return rsp_data finally: if not lazy: t.close() table_metadata = login_required()(jsonp(_table_metadata)) @login_required() @jsonp def object_table_query(request, objtype, objid, conn=None, **kwargs): """ Query bulk annotations table attached to an object specified by object type and identifier, optionally traversing object model graph. Returns a dictionary with query result if successful, error information otherwise Example: /table/Plate/1/query/?query=* queries bulk annotations table for plate with identifier 1 Example: /table/Plate.wells/1/query/?query=* queries bulk annotations table for plate that contains well with identifier 1 Example: /table/Screen.plateLinks.child.wells/22/query/?query=Well-22 queries bulk annotations table for screen that contains plate with well with identifier 22 @param request: http request. @param objtype: Type of target object, or type of target object followed by a slash-separated list of properties to resolve @param objid: Identifier of target object, or identifier of object reached by resolving given properties @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: unused @return: A dictionary with key 'error' with an error message or with key 'data' containing a dictionary with keys 'columns' (an array of column names) and 'rows' (an array of rows, each an array of values) """ a = _bulk_file_annotations(request, objtype, objid, conn, **kwargs) if "error" in a: return a if len(a["data"]) < 1: return dict(error="Could not retrieve bulk annotations table") # multiple bulk annotations files could be attached, use the most recent # one (= the one with the highest identifier) fileId = 0 ann = None annList = sorted(a["data"], key=lambda x: x["file"], reverse=True) tableData = None for annotation in annList: tableData = _table_query(request, annotation["file"], conn, **kwargs) if "error" not in tableData: ann = annotation fileId = annotation["file"] break if ann is None: return dict( error=tableData.get( "error", "Could not retrieve matching bulk annotation table" ) ) tableData["id"] = fileId tableData["annId"] = ann["id"] tableData["owner"] = ann["owner"] tableData["addedBy"] = ann["addedBy"] tableData["parentType"] = ann["parentType"] tableData["parentId"] = ann["parentId"] tableData["addedOn"] = ann["addedOn"] return tableData class LoginView(View): """Webgateway Login - Subclassed by WebclientLoginView.""" form_class = LoginForm useragent = "OMERO.webapi" @method_decorator(sensitive_post_parameters("password", "csrfmiddlewaretoken")) def dispatch(self, *args, **kwargs): """Wrap other methods to add decorators.""" return super(LoginView, self).dispatch(*args, **kwargs) def get(self, request, api_version=None): """Simply return a message to say GET not supported.""" return JsonResponse( {"message": ("POST only with username, password, " "server and csrftoken")}, status=405, ) def handle_logged_in(self, request, conn, connector): """Return a response for successful login.""" c = conn.getEventContext() ctx = {} for a in [ "sessionId", "sessionUuid", "userId", "userName", "groupId", "groupName", "isAdmin", "eventId", "eventType", "memberOfGroups", "leaderOfGroups", ]: if hasattr(c, a): ctx[a] = getattr(c, a) return JsonResponse({"success": True, "eventContext": ctx}) def handle_not_logged_in(self, request, error=None, form=None): """ Return a response for failed login. Reason for failure may be due to server 'error' or because of form validation errors. @param request: http request @param error: Error message @param form: Instance of Login Form, populated with data """ if error is None and form is not None: # If no error from server, maybe form wasn't valid formErrors = [] for field in form: for e in field.errors: formErrors.append("%s: %s" % (field.label, e)) error = " ".join(formErrors) elif error is None: # Just in case no error or invalid form is given error = "Login failed. Reason unknown." return JsonResponse({"message": error}, status=403) def post(self, request, api_version=None): """ Here we handle the main login logic, creating a connection to OMERO. and store that on the request.session OR handling login failures """ error = None form = self.form_class(request.POST.copy()) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] server_id = form.cleaned_data["server"] is_secure = settings.SECURE connector = Connector(server_id, is_secure) # TODO: version check should be done on the low level, see #5983 compatible = True if settings.CHECK_VERSION: compatible = connector.check_version(self.useragent) if ( server_id is not None and username is not None and password is not None and compatible ): conn = connector.create_connection( self.useragent, username, password, userip=get_client_ip(request) ) if conn is not None: try: request.session["connector"] = connector # UpgradeCheck URL should be loaded from the server or # loaded omero.web.upgrades.url allows to customize web # only try: upgrades_url = settings.UPGRADES_URL except Exception: upgrades_url = conn.getUpgradesUrl() upgradeCheck(url=upgrades_url) return self.handle_logged_in(request, conn, connector) finally: conn.close(hard=False) # Once here, we are not logged in... # Need correct error message if not connector.is_server_up(self.useragent): error = "Server is not responding," " please contact administrator." elif not settings.CHECK_VERSION: error = ( "Connection not available, please check your" " credentials and version compatibility." ) else: if not compatible: error = ( "Client version does not match server," " please contact administrator." ) else: error = settings.LOGIN_INCORRECT_CREDENTIALS_TEXT return self.handle_not_logged_in(request, error, form) @login_required() @jsonp def get_image_rdefs_json(request, img_id=None, conn=None, **kwargs): """ Retrieves all rendering definitions for a given image (id). Example: /get_image_rdefs_json/1 Returns all rdefs for image with id 1 @param request: http request. @param img_id: the id of the image in question @param conn: L{omero.gateway.BlitzGateway} @param **kwargs: unused @return: A dictionary with key 'rdefs' in the success case, one with key 'error' if something went wrong """ try: img = conn.getObject("Image", img_id) if img is None: return {"error": "No image with id " + str(img_id)} return {"rdefs": img.getAllRenderingDefs()} except Exception: logger.debug(traceback.format_exc()) return {"error": "Failed to retrieve rdefs"}
open_redirect
{ "code": [ " else None", " range_size = kwargs.get(\"limit\", rows)" ], "line_no": [ 2963, 2966 ] }
{ "code": [ " else rows", " range_size = limit" ], "line_no": [ 2963, 2966 ] }
import .re import json import base64 import .warnings from functools import .wraps import .omero import .omero.clients from past.builtins import unicode from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseServerError, JsonResponse, HttpResponseForbidden, ) from django.http import ( HttpResponseRedirect, HttpResponseNotAllowed, Http404, StreamingHttpResponse, HttpResponseNotFound, ) from django.views.decorators.http import .require_POST from django.views.decorators.debug import .sensitive_post_parameters from django.utils.decorators import .method_decorator from django.core.urlresolvers import .reverse, NoReverseMatch from django.conf import .settings from wsgiref.util import FileWrapper from omero.rtypes import .rlong, unwrap from omero.constants.namespaces import NSBULKANNOTATIONS from .util import .points_string_to_XY_list, xy_list_to_bbox from .plategrid import PlateGrid from omeroweb.version import .omeroweb_buildyear as build_year from .marshal import .imageMarshal, shapeMarshal, rgb_int2rgba from django.contrib.staticfiles.templatetags.staticfiles import .static from django.views.generic import View from django.shortcuts import .render from omeroweb.webadmin.forms import LoginForm from omeroweb.decorators import .get_client_ip, is_public_user from omeroweb.webadmin.webadmin_utils import upgradeCheck try: from hashlib import .md5 except Exception: from md5 import .md5 try: import .long except ImportError: VAR_178 = int from io import BytesIO import .tempfile from omero import ApiUsageException from omero.util.decorators import .timeit, TimeIt from omeroweb.httprsp import HttpJavascriptResponse, HttpJavascriptResponseServerError from omeroweb.connector import Server import glob from omeroweb.webgateway.webgateway_cache import ( webgateway_cache, CacheBase, webgateway_tempfile, ) import logging import .os import .traceback import .time import .zipfile import .shutil from omeroweb.decorators import login_required, ConnCleaningHttpResponse from omeroweb.connector import Connector from omeroweb.webgateway.util import .zip_archived_files, LUTS_IN_PNG from omeroweb.webgateway.util import .get_longs, getIntOrDefault VAR_0 = CacheBase() VAR_1 = logging.getLogger(__name__) try: from PIL import Image from PIL import ImageDraw except Exception: # pragma: nocover try: import Image import ImageDraw except Exception: VAR_1.error("No Pillow installed") try: import numpy VAR_48 = True except ImportError: VAR_1.error("No numpy installed") VAR_48 = False def VAR_319(VAR_2): return HttpResponse("Welcome to webgateway") def FUNC_1(VAR_3): return unicode(VAR_3).encode("utf-8") class CLASS_0(object): def __init__(self, VAR_49): self._blitzcon = VAR_49 self.loggedIn = False def FUNC_57(self): self.loggedIn = True def FUNC_58(self): return self._blitzcon.isAdmin() def FUNC_59(self): return self._blitzcon.canBeAdmin() def FUNC_60(self): return self._blitzcon.getUserId() def FUNC_61(self): return self._blitzcon.getUser().omeName def FUNC_62(self): return self._blitzcon.getUser().firstName or self.getName() def FUNC_2(VAR_4): VAR_50 = [] VAR_51 = [] VAR_52 = [] for VAR_179 in VAR_4.split(","): VAR_179 = chan.split("|", 1) VAR_23 = VAR_179[0].strip() VAR_68 = None if VAR_23.find("$") >= 0: VAR_23, VAR_68 = VAR_23.split("$") try: VAR_50.append(int(VAR_23)) VAR_262 = (None, None) if len(VAR_179) > 1: VAR_23 = VAR_179[1].strip() if VAR_23.find("$") >= 0: VAR_23, VAR_68 = VAR_23.split("$", 1) VAR_23 = VAR_23.split(":") if len(VAR_23) == 2: try: VAR_262 = [float(VAR_30) for VAR_30 in VAR_23] except ValueError: pass VAR_51.append(VAR_262) VAR_52.append(VAR_68) except ValueError: pass VAR_1.debug(str(VAR_50) + "," + str(VAR_51) + "," + str(VAR_52)) return VAR_50, VAR_51, VAR_52 def FUNC_3(VAR_2, VAR_5=False): VAR_53 = VAR_2.GET VAR_54 = {} for VAR_263 in ("z", "t", "q", "m", "zm", "x", "y", "p"): if VAR_263 in VAR_53: VAR_54[VAR_263] = VAR_53[VAR_263] if "c" in VAR_53: VAR_54["c"] = [] VAR_180 = FUNC_2(VAR_53["c"]) VAR_1.debug(VAR_180) for VAR_212 in range(len(VAR_180[0])): VAR_54["c"].append( { "a": abs(VAR_180[0][VAR_212]), "i": VAR_180[0][VAR_212], "s": VAR_180[1][VAR_212][0], "e": VAR_180[1][VAR_212][1], "c": VAR_180[2][VAR_212], } ) if VAR_5: return "&".join(["%VAR_3=%s" % (VAR_30[0], VAR_30[1]) for VAR_30 in VAR_54.items()]) return VAR_54 @login_required() def FUNC_4(VAR_2, VAR_6, VAR_7=None, VAR_8=None, **VAR_9): return FUNC_6(VAR_2, VAR_6, VAR_10=VAR_7, **VAR_9) def FUNC_5(VAR_2, VAR_6, VAR_10=None, VAR_11=None, VAR_8=None, VAR_12=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_55 = VAR_2.session.get("server_settings", {}).get("browser", {}) VAR_56 = VAR_55.get("thumb_default_size", 96) VAR_57 = True if VAR_10 is None: VAR_7 = (VAR_56,) else: if VAR_11 is None: VAR_7 = (int(VAR_10),) else: VAR_7 = (int(VAR_10), int(VAR_11)) if VAR_7 == (VAR_56,): VAR_57 = False VAR_58 = VAR_8.getUserId() VAR_22 = getIntOrDefault(VAR_2, "z", None) VAR_23 = getIntOrDefault(VAR_2, "t", None) VAR_59 = getIntOrDefault(VAR_2, "rdefId", None) VAR_60 = webgateway_cache.getThumb(VAR_2, VAR_19, VAR_58, VAR_6, VAR_7) if VAR_60 is None: VAR_181 = False VAR_92 = VAR_8.getObject("Image", VAR_6) if VAR_92 is None: VAR_1.debug("(b)Image %VAR_3 not found..." % (str(VAR_6))) if VAR_12: VAR_60 = VAR_12(VAR_7=size) VAR_181 = True else: raise Http404("Failed to render thumbnail") else: VAR_60 = VAR_92.getThumbnail( VAR_7=size, VAR_57=direct, VAR_59=rdefId, VAR_22=z, VAR_23=t ) if VAR_60 is None: VAR_1.debug("(VAR_203)Image %VAR_3 not found..." % (str(VAR_6))) if VAR_12: VAR_60 = VAR_12(VAR_7=size) VAR_181 = True else: raise Http404("Failed to render thumbnail") else: VAR_181 = VAR_92._thumbInProgress if not VAR_181: webgateway_cache.setThumb(VAR_2, VAR_19, VAR_58, VAR_6, VAR_60, VAR_7) else: pass return VAR_60 @login_required() def FUNC_6(VAR_2, VAR_6, VAR_10=None, VAR_11=None, VAR_8=None, VAR_12=None, **VAR_9): VAR_60 = FUNC_5( VAR_2=request, VAR_6=iid, VAR_10=w, VAR_11=h, VAR_8=conn, VAR_12=_defcb, **VAR_9 ) VAR_61 = HttpResponse(VAR_60, content_type="image/jpeg") return VAR_61 @login_required() def FUNC_7(VAR_2, VAR_13, VAR_10=None, VAR_11=None, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_62 = VAR_8.getRoiService().findByRoi(VAR_178(VAR_13), None, VAR_8.SERVICE_OPTS) if VAR_62 is None or VAR_62.rois is None or len(VAR_62.rois) == 0: raise Http404 for VAR_241 in VAR_62.rois: VAR_36 = VAR_241.image.id.val VAR_63 = VAR_241.copyShapes() VAR_63 = [VAR_3 for VAR_3 in VAR_63 if VAR_3 is not None] if len(VAR_63) == 0: raise Http404("No Shapes found for ROI %s" % VAR_13) VAR_64 = FUNC_13(VAR_2, VAR_36, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_15, VAR_16 = VAR_64 VAR_65 = None if len(VAR_63) == 1: VAR_65 = VAR_63[0] else: VAR_182 = VAR_15.getDefaultT() VAR_183 = VAR_15.getDefaultZ() VAR_184 = [ VAR_3 for VAR_3 in VAR_63 if unwrap(VAR_3.getTheT()) is None or unwrap(VAR_3.getTheT()) == VAR_182 ] if len(VAR_184) == 1: VAR_65 = VAR_184[0] else: VAR_184 = [ VAR_3 for VAR_3 in VAR_184 if unwrap(VAR_3.getTheZ()) is None or unwrap(VAR_3.getTheZ()) == VAR_183 ] if len(VAR_184) > 0: VAR_65 = VAR_184[0] if VAR_65 is None and len(VAR_63) > 0: VAR_65 = VAR_63[0] return FUNC_9(VAR_2, VAR_8, VAR_15, VAR_65, VAR_16) @login_required() def FUNC_8(VAR_2, VAR_14, VAR_10=None, VAR_11=None, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_66 = omero.sys.Parameters() VAR_66.map = {"id": rlong(VAR_14)} VAR_65 = VAR_8.getQueryService().findByQuery( "select VAR_3 from Shape VAR_3 join fetch VAR_3.roi where VAR_3.id = :id", VAR_66, VAR_8.SERVICE_OPTS, ) if VAR_65 is None: raise Http404 VAR_36 = VAR_65.roi.image.id.val VAR_64 = FUNC_13(VAR_2, VAR_36, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_15, VAR_16 = VAR_64 return FUNC_9(VAR_2, VAR_8, VAR_15, VAR_65, VAR_16) def FUNC_9(VAR_2, VAR_8, VAR_15, VAR_3, VAR_16): VAR_67 = 250 VAR_68 = VAR_2.GET.get("color", "fff") VAR_69 = { "f00": (255, 0, 0), "0f0": (0, 255, 0), "00f": (0, 0, 255), "ff0": (255, 255, 0), "fff": (255, 255, 255), "000": (0, 0, 0), } VAR_70 = VAR_69["f00"] if VAR_68 in VAR_69: VAR_70 = VAR_69[VAR_68] VAR_71 = (221, 221, 221) VAR_72 = None # bounding box: (VAR_30, VAR_29, VAR_10, VAR_11) VAR_65 = {} VAR_73 = unwrap(VAR_3.getTheT()) VAR_73 = VAR_73 if VAR_73 is not None else VAR_15.getDefaultT() VAR_74 = unwrap(VAR_3.getTheZ()) VAR_74 = VAR_74 if VAR_74 is not None else VAR_15.getDefaultZ() if type(VAR_3) == omero.model.RectangleI: VAR_65["type"] = "Rectangle" VAR_65["x"] = VAR_3.getX().getValue() VAR_65["y"] = VAR_3.getY().getValue() VAR_65["width"] = VAR_3.getWidth().getValue() VAR_65["height"] = VAR_3.getHeight().getValue() VAR_72 = (VAR_65["x"], VAR_65["y"], VAR_65["width"], VAR_65["height"]) elif type(VAR_3) == omero.model.MaskI: VAR_65["type"] = "Mask" VAR_65["x"] = VAR_3.getX().getValue() VAR_65["y"] = VAR_3.getY().getValue() VAR_65["width"] = VAR_3.getWidth().getValue() VAR_65["height"] = VAR_3.getHeight().getValue() VAR_72 = (VAR_65["x"], VAR_65["y"], VAR_65["width"], VAR_65["height"]) elif type(VAR_3) == omero.model.EllipseI: VAR_65["type"] = "Ellipse" VAR_65["x"] = int(VAR_3.getX().getValue()) VAR_65["y"] = int(VAR_3.getY().getValue()) VAR_65["radiusX"] = int(VAR_3.getRadiusX().getValue()) VAR_65["radiusY"] = int(VAR_3.getRadiusY().getValue()) VAR_72 = ( VAR_65["x"] - VAR_65["radiusX"], VAR_65["y"] - VAR_65["radiusY"], 2 * VAR_65["radiusX"], 2 * VAR_65["radiusY"], ) elif type(VAR_3) == omero.model.PolylineI: VAR_65["type"] = "PolyLine" VAR_65["xyList"] = points_string_to_XY_list(VAR_3.getPoints().getValue()) VAR_72 = xy_list_to_bbox(VAR_65["xyList"]) elif type(VAR_3) == omero.model.LineI: VAR_65["type"] = "Line" VAR_65["x1"] = int(VAR_3.getX1().getValue()) VAR_65["x2"] = int(VAR_3.getX2().getValue()) VAR_65["y1"] = int(VAR_3.getY1().getValue()) VAR_65["y2"] = int(VAR_3.getY2().getValue()) VAR_30 = min(VAR_65["x1"], VAR_65["x2"]) VAR_29 = min(VAR_65["y1"], VAR_65["y2"]) VAR_72 = ( VAR_30, VAR_29, max(VAR_65["x1"], VAR_65["x2"]) - VAR_30, max(VAR_65["y1"], VAR_65["y2"]) - VAR_29, ) elif type(VAR_3) == omero.model.PointI: VAR_65["type"] = "Point" VAR_65["x"] = VAR_3.getX().getValue() VAR_65["y"] = VAR_3.getY().getValue() VAR_72 = (VAR_65["x"] - 50, VAR_65["y"] - 50, 100, 100) elif type(VAR_3) == omero.model.PolygonI: VAR_65["type"] = "Polygon" VAR_65["xyList"] = points_string_to_XY_list(VAR_3.getPoints().getValue()) VAR_72 = xy_list_to_bbox(VAR_65["xyList"]) elif type(VAR_3) == omero.model.LabelI: VAR_65["type"] = "Label" VAR_65["x"] = VAR_3.getX().getValue() VAR_65["y"] = VAR_3.getY().getValue() VAR_72 = (VAR_65["x"] - 50, VAR_65["y"] - 50, 100, 100) else: VAR_1.debug("Shape type not supported: %s" % str(type(VAR_3))) VAR_30, VAR_29, VAR_10, VAR_11 = VAR_72 VAR_75 = max(VAR_10, VAR_11 * 3 // 2) VAR_76 = VAR_75 * 2 // 3 VAR_77 = int(VAR_75 * 1.5) VAR_78 = int(VAR_76 * 1.5) if VAR_77 < VAR_67: VAR_77 = VAR_67 VAR_78 = VAR_77 * 2 // 3 def FUNC_63(VAR_79): try: return VAR_8.getConfigService().getConfigValue(VAR_79) except Exception: VAR_1.warn( "webgateway: FUNC_9() could not get" " Config-Value for %s" % VAR_79 ) pass VAR_80 = FUNC_63("omero.pixeldata.max_plane_width") VAR_81 = FUNC_63("omero.pixeldata.max_plane_height") if ( VAR_80 is None or VAR_81 is None or (VAR_77 > int(VAR_80)) or (VAR_78 > int(VAR_81)) ): VAR_185 = Image.new("RGB", (VAR_67, MAX_WIDTH * 2 // 3), VAR_71) VAR_97 = ImageDraw.Draw(VAR_185) VAR_97.text((10, 30), "Shape too large to \ngenerate thumbnail", VAR_101=(255, 0, 0)) VAR_54 = BytesIO() VAR_185.save(VAR_54, "jpeg", quality=90) return HttpResponse(VAR_54.getvalue(), content_type="image/jpeg") VAR_82 = (VAR_77 - VAR_10) // 2 VAR_83 = (VAR_78 - VAR_11) // 2 VAR_84 = int(VAR_30 - VAR_82) VAR_85 = int(VAR_29 - VAR_83) VAR_86 = VAR_15.getSizeX() VAR_87 = VAR_15.getSizeY() VAR_88, VAR_89, VAR_90, VAR_91 = 0, 0, 0, 0 if VAR_84 < 0: VAR_77 = VAR_77 + VAR_84 VAR_88 = abs(VAR_84) newX = 0 if VAR_85 < 0: VAR_78 = VAR_78 + VAR_85 VAR_90 = abs(VAR_85) newY = 0 if VAR_77 + VAR_84 > VAR_86: VAR_89 = (VAR_77 + VAR_84) - VAR_86 VAR_77 = newW - VAR_89 if VAR_78 + VAR_85 > VAR_87: VAR_91 = (VAR_78 + VAR_85) - VAR_87 VAR_78 = newH - VAR_91 VAR_60 = VAR_15.renderJpegRegion( VAR_74, VAR_73, VAR_84, VAR_85, VAR_77, VAR_78, VAR_113=None, VAR_98=VAR_16 ) VAR_92 = Image.open(BytesIO(VAR_60)) if VAR_88 != 0 or VAR_89 != 0 or VAR_90 != 0 or VAR_91 != 0: VAR_186, VAR_187 = VAR_92.size VAR_188 = VAR_186 + VAR_89 + VAR_88 VAR_189 = VAR_187 + VAR_91 + VAR_90 VAR_190 = Image.new("RGB", (VAR_188, VAR_189), VAR_71) VAR_190.paste(VAR_92, (VAR_88, VAR_90)) VAR_92 = VAR_190 VAR_93, VAR_94 = VAR_92.size VAR_95 = float(VAR_67) / VAR_93 VAR_96 = int(VAR_94 * VAR_95) VAR_92 = VAR_92.resize((VAR_67, VAR_96)) VAR_97 = ImageDraw.Draw(VAR_92) if VAR_65["type"] == "Rectangle": VAR_191 = int(VAR_82 * VAR_95) VAR_192 = int(VAR_83 * VAR_95) VAR_193 = int((VAR_10 + VAR_82) * VAR_95) VAR_194 = int((VAR_11 + VAR_83) * VAR_95) VAR_97.rectangle((VAR_191, VAR_192, VAR_193, VAR_194), outline=VAR_70) VAR_97.rectangle((VAR_191 - 1, VAR_192 - 1, VAR_193 + 1, VAR_194 + 1), outline=VAR_70) elif VAR_65["type"] == "Line": VAR_264 = (VAR_65["x1"] - VAR_84 + VAR_88) * VAR_95 VAR_265 = (VAR_65["x2"] - VAR_84 + VAR_88) * VAR_95 VAR_266 = (VAR_65["y1"] - VAR_85 + VAR_90) * VAR_95 VAR_267 = (VAR_65["y2"] - VAR_85 + VAR_90) * VAR_95 VAR_97.line((VAR_264, VAR_266, VAR_265, VAR_267), VAR_101=VAR_70, VAR_99=2) elif VAR_65["type"] == "Ellipse": VAR_191 = int(VAR_82 * VAR_95) VAR_192 = int(VAR_83 * VAR_95) VAR_193 = int((VAR_10 + VAR_82) * VAR_95) VAR_194 = int((VAR_11 + VAR_83) * VAR_95) VAR_97.ellipse((VAR_191, VAR_192, VAR_193, VAR_194), outline=VAR_70) VAR_97.ellipse((VAR_191 - 1, VAR_192 - 1, VAR_193 + 1, VAR_194 + 1), outline=VAR_70) elif VAR_65["type"] == "Point": VAR_323 = 2 VAR_191 = (VAR_67 // 2) - VAR_323 VAR_192 = int(VAR_96 // 2) - VAR_323 VAR_193 = VAR_191 + (VAR_323 * 2) VAR_194 = VAR_192 + (VAR_323 * 2) VAR_97.ellipse((VAR_191, VAR_192, VAR_193, VAR_194), outline=VAR_70) VAR_97.ellipse((VAR_191 - 1, VAR_192 - 1, VAR_193 + 1, VAR_194 + 1), outline=VAR_70) elif "xyList" in VAR_65: def FUNC_79(VAR_325): VAR_30, VAR_29 = VAR_325 return ( int((VAR_30 - VAR_84 + VAR_88) * VAR_95), int((VAR_29 - VAR_85 + VAR_90) * VAR_95), ) VAR_326 = [FUNC_79(VAR_325) for VAR_325 in VAR_65["xyList"]] VAR_327 = VAR_328 = None for line in range(1, len(VAR_326)): VAR_333, VAR_334 = VAR_326[line - 1] VAR_327, VAR_328 = VAR_326[line] VAR_97.line((VAR_333, VAR_334, VAR_327, VAR_328), VAR_101=VAR_70, VAR_99=2) VAR_329, VAR_330 = VAR_326[0] if VAR_65["type"] != "PolyLine": if VAR_327 is None: VAR_327 = VAR_329 + 1 # This will create VAR_167 visible dot if VAR_328 is None: VAR_328 = VAR_330 + 1 VAR_97.line((VAR_327, VAR_328, VAR_329, VAR_330), VAR_101=VAR_70, VAR_99=2) VAR_54 = BytesIO() VAR_98 = 0.9 try: VAR_92.save(VAR_54, "jpeg", quality=int(VAR_98 * 100)) VAR_195 = VAR_54.getvalue() finally: VAR_54.close() return HttpResponse(VAR_195, content_type="image/jpeg") @login_required() def FUNC_10(VAR_2, VAR_14, VAR_8=None, **VAR_9): if not VAR_48: raise NotImplementedError("numpy not installed") VAR_66 = omero.sys.Parameters() VAR_66.map = {"id": rlong(VAR_14)} VAR_65 = VAR_8.getQueryService().findByQuery( "select VAR_3 from Shape VAR_3 where VAR_3.id = :id", VAR_66, VAR_8.SERVICE_OPTS ) if VAR_65 is None: raise Http404("Shape ID: %VAR_3 not found" % VAR_14) VAR_99 = int(VAR_65.getWidth().getValue()) VAR_100 = int(VAR_65.getHeight().getValue()) VAR_68 = unwrap(VAR_65.getFillColor()) VAR_101 = (255, 255, 0, 255) if VAR_68 is not None: VAR_68 = rgb_int2rgba(VAR_68) VAR_101 = (VAR_68[0], VAR_68[1], VAR_68[2], int(VAR_68[3] * 255)) VAR_102 = VAR_65.getBytes() VAR_103 = numpy.fromstring(VAR_102, dtype=numpy.uint8) VAR_104 = numpy.unpackbits(VAR_103) VAR_92 = Image.new("RGBA", VAR_7=(VAR_99, VAR_100), VAR_68=(0, 0, 0, 0)) VAR_30 = 0 VAR_29 = 0 for pix in VAR_104: if pix == 1: VAR_92.putpixel((VAR_30, VAR_29), VAR_101) VAR_30 += 1 if VAR_30 > VAR_99 - 1: VAR_30 = 0 VAR_29 += 1 VAR_54 = BytesIO() VAR_92.save(VAR_54, "png", quality=int(100)) VAR_105 = VAR_54.getvalue() return HttpResponse(VAR_105, content_type="image/png") def FUNC_11(VAR_2): VAR_53 = VAR_2.GET VAR_54 = VAR_53.get("m", "_") + VAR_53.get("p", "_") + VAR_53.get("c", "_") + VAR_53.get("q", "_") return VAR_54 def FUNC_12(VAR_2, VAR_17, VAR_18=0): VAR_106 = None if "maps" in VAR_2: VAR_196 = VAR_2["maps"] VAR_106 = [] try: if isinstance(VAR_196, (unicode, str)): VAR_196 = json.loads(VAR_196) VAR_18 = max(len(VAR_196), VAR_18) for VAR_203 in range(VAR_18): VAR_308 = None if len(VAR_196) > VAR_203: VAR_282 = VAR_196[VAR_203].get(VAR_17) if VAR_282 is not None: VAR_308 = VAR_282.get("enabled") in (True, "true") VAR_106.append(VAR_308) except Exception: VAR_1.debug("Invalid json for VAR_43 ?VAR_223=%s" % VAR_196) VAR_106 = None return VAR_106 def FUNC_13( VAR_2, VAR_6, VAR_19=None, VAR_8=None, VAR_20=False, VAR_21=True ): VAR_53 = VAR_2.GET VAR_1.debug( "Preparing Image:%VAR_53 VAR_20=%VAR_53 " "retry=%VAR_53 VAR_2=%VAR_53 VAR_8=%s" % (VAR_6, VAR_20, VAR_21, VAR_53, str(VAR_8)) ) VAR_92 = VAR_8.getObject("Image", VAR_6) if VAR_92 is None: return VAR_107 = None if "maps" in VAR_53: VAR_197 = FUNC_12(VAR_53, "reverse", VAR_92.getSizeC()) VAR_107 = FUNC_12(VAR_53, "inverted", VAR_92.getSizeC()) if VAR_197 is not None and VAR_107 is not None: VAR_107 = [ VAR_22[0] if VAR_22[0] is not None else VAR_22[1] for VAR_22 in zip(VAR_107, VAR_197) ] try: VAR_268 = [VAR_282.get("quantization") for VAR_282 in json.loads(VAR_53["maps"])] VAR_92.setQuantizationMaps(VAR_268) except Exception: VAR_1.debug("Failed to set quantization maps") if "c" in VAR_53: VAR_1.debug("c=" + VAR_53["c"]) VAR_198, VAR_51, VAR_52 = FUNC_2(VAR_53["c"]) VAR_199 = range(1, VAR_92.getSizeC() + 1) if VAR_20 and not VAR_92.setActiveChannels( VAR_199, VAR_51, VAR_52, VAR_107 ): VAR_1.debug("Something bad happened while setting the active VAR_50...") if not VAR_92.setActiveChannels(VAR_198, VAR_51, VAR_52, VAR_107): VAR_1.debug("Something bad happened while setting the active VAR_50...") if VAR_53.get("m", None) == "g": VAR_92.setGreyscaleRenderingModel() elif VAR_53.get("m", None) == "c": VAR_92.setColorRenderingModel() VAR_108 = VAR_53.get("p", None) VAR_109, VAR_110 = None, None if VAR_108 is not None and len(VAR_108.split("|")) > 1: VAR_108, VAR_200 = VAR_108.split("|", 1) try: VAR_109, VAR_110 = [int(VAR_3) for VAR_3 in VAR_200.split(":")] except ValueError: pass VAR_92.setProjection(VAR_108) VAR_92.setProjectionRange(VAR_109, VAR_110) VAR_92.setInvertedAxis(bool(VAR_53.get("ia", "0") == "1")) VAR_16 = VAR_53.get("q", None) if VAR_20: "z" in VAR_53 and VAR_92.setDefaultZ(VAR_178(VAR_53["z"]) - 1) "t" in VAR_53 and VAR_92.setDefaultT(VAR_178(VAR_53["t"]) - 1) VAR_92.saveDefaults() return (VAR_92, VAR_16) @login_required() def FUNC_14(VAR_2, VAR_6, VAR_22, VAR_23, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_111 = VAR_2.GET.get("tile", None) VAR_112 = VAR_2.GET.get("region", None) VAR_113 = None if VAR_111: try: VAR_92._prepareRenderingEngine() VAR_10, VAR_11 = VAR_92._re.getTileSize() VAR_269 = VAR_92._re.getResolutionLevels() - 1 VAR_270 = VAR_111.split(",") if len(VAR_270) > 4: VAR_309 = [int(VAR_270[3]), int(VAR_270[4])] VAR_310 = [VAR_10, VAR_11] VAR_311 = 1024 try: VAR_311 = int( VAR_8.getConfigService().getConfigValue( "omero.pixeldata.max_tile_length" ) ) except Exception: pass for VAR_212, tile_length in enumerate(VAR_309): if tile_length <= 0: VAR_309[VAR_212] = VAR_310[VAR_212] if tile_length > VAR_311: VAR_309[VAR_212] = VAR_311 VAR_10, VAR_11 = VAR_309 VAR_271 = int(VAR_270[0]) if VAR_271 < 0: VAR_231 = "Invalid resolution VAR_113 %VAR_3 < 0" % VAR_271 VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) if VAR_269 == 0: # non pyramid file if VAR_271 > 0: VAR_231 = "Invalid resolution VAR_113 %VAR_3, non pyramid file" % VAR_271 VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) else: VAR_113 = None else: VAR_113 = VAR_269 - VAR_271 if VAR_113 < 0: VAR_231 = ( "Invalid resolution VAR_113, \ %VAR_3 > number of available VAR_269 %VAR_3 " % (VAR_271, VAR_269) ) VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) VAR_30 = int(VAR_270[1]) * VAR_10 VAR_29 = int(VAR_270[2]) * VAR_11 except Exception: VAR_231 = "malformed VAR_111 argument, VAR_111=%s" % VAR_111 VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) elif VAR_112: try: VAR_312 = VAR_112.split(",") VAR_30 = int(VAR_312[0]) VAR_29 = int(VAR_312[1]) VAR_10 = int(VAR_312[2]) VAR_11 = int(VAR_312[3]) except Exception: VAR_231 = "malformed VAR_112 argument, VAR_112=%s" % VAR_112 VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) else: return HttpResponseBadRequest("tile or VAR_112 argument required") VAR_60 = webgateway_cache.getImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23) if VAR_60 is None: VAR_60 = VAR_92.renderJpegRegion( VAR_22, VAR_23, VAR_30, VAR_29, VAR_10, VAR_11, VAR_113=level, VAR_98=VAR_16 ) if VAR_60 is None: raise Http404 webgateway_cache.setImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23, VAR_60) VAR_61 = HttpResponse(VAR_60, content_type="image/jpeg") return VAR_61 @login_required() def FUNC_15(VAR_2, VAR_6, VAR_22=None, VAR_23=None, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_60 = webgateway_cache.getImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23) if VAR_60 is None: VAR_60 = VAR_92.renderJpeg(VAR_22, VAR_23, VAR_98=VAR_16) if VAR_60 is None: raise Http404 webgateway_cache.setImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23, VAR_60) VAR_114 = VAR_2.GET.get("format", "jpeg") VAR_61 = HttpResponse(VAR_60, content_type="image/jpeg") if "download" in VAR_9 and VAR_9["download"]: if VAR_114 == "png": VAR_212 = Image.open(BytesIO(VAR_60)) VAR_272 = BytesIO() VAR_212.save(VAR_272, "png") VAR_60 = VAR_272.getvalue() VAR_272.close() VAR_61 = HttpResponse(VAR_60, content_type="image/png") elif VAR_114 == "tif": VAR_212 = Image.open(BytesIO(VAR_60)) VAR_272 = BytesIO() VAR_212.save(VAR_272, "tiff") VAR_60 = VAR_272.getvalue() VAR_272.close() VAR_61 = HttpResponse(VAR_60, content_type="image/tiff") VAR_201 = VAR_92.getName() try: VAR_201 = fileName.decode("utf8") except AttributeError: pass # python 3 VAR_201 = fileName.replace(",", ".").replace(" ", "_") VAR_61["Content-Type"] = "application/force-download" VAR_61["Content-Length"] = len(VAR_60) VAR_61["Content-Disposition"] = "attachment; filename=%VAR_3.%s" % (VAR_201, VAR_114) return VAR_61 @login_required() def FUNC_16(VAR_2, VAR_24, VAR_25, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_115 = [] if VAR_24 == "p": VAR_202 = VAR_8.getObject("Project", VAR_25) if VAR_202 is None: raise Http404 for VAR_213 in VAR_202.listChildren(): VAR_115.extend(list(VAR_213.listChildren())) VAR_17 = VAR_202.getName() elif VAR_24 == "d": VAR_202 = VAR_8.getObject("Dataset", VAR_25) if VAR_202 is None: raise Http404 VAR_115.extend(list(VAR_202.listChildren())) VAR_273 = list(filter(None, VAR_2.GET.get("selection", "").split(","))) if len(VAR_273) > 0: VAR_1.debug(VAR_273) VAR_1.debug(VAR_115) VAR_115 = [VAR_30 for VAR_30 in VAR_115 if str(VAR_30.getId()) in VAR_273] VAR_1.debug(VAR_115) if len(VAR_115) == 0: raise Http404 VAR_17 = "%VAR_3-%s" % (VAR_202.getParent().getName(), VAR_202.getName()) elif VAR_24 == "w": VAR_202 = VAR_8.getObject("Well", VAR_25) if VAR_202 is None: raise Http404 VAR_115.extend([VAR_30.getImage() for VAR_30 in VAR_202.listChildren()]) VAR_124 = VAR_202.getParent() VAR_313 = "%VAR_3%s" % ( VAR_124.getRowLabels()[VAR_202.row], VAR_124.getColumnLabels()[VAR_202.column], ) VAR_17 = "%VAR_3-%VAR_3-%s" % (VAR_124.getParent().getName(), VAR_124.getName(), VAR_313) else: VAR_202 = VAR_8.getObject("Image", VAR_25) if VAR_202 is None: raise Http404 VAR_115.append(VAR_202) VAR_115 = [VAR_30 for VAR_30 in VAR_115 if not VAR_30.requiresPixelsPyramid()] if VAR_2.GET.get("dryrun", False): VAR_54 = json.dumps(len(VAR_115)) VAR_203 = VAR_2.GET.get("callback", None) if VAR_203 is not None and not VAR_9.get("_internal", False): VAR_54 = "%VAR_3(%VAR_3)" % (VAR_203, VAR_54) return HttpJavascriptResponse(VAR_54) if len(VAR_115) == 0: raise Http404 if len(VAR_115) == 1: VAR_202 = VAR_115[0] VAR_79 = ( "_".join((str(VAR_30.getId()) for VAR_30 in VAR_202.getAncestry())) + "_" + str(VAR_202.getId()) + "_ome_tiff" ) VAR_204 = 255 - len(str(VAR_202.getId())) - 10 VAR_205 = VAR_202.getName()[:VAR_204] VAR_206, VAR_207, VAR_208 = webgateway_tempfile.new( str(VAR_202.getId()) + "-" + VAR_205 + ".ome.tiff", VAR_79=key ) if VAR_208 is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) VAR_209 = webgateway_cache.getOmeTiffImage(VAR_2, VAR_19, VAR_115[0]) if VAR_209 is None: try: VAR_209 = VAR_115[0].exportOmeTiff() except Exception: VAR_1.debug("Failed to export VAR_15 (2)", exc_info=True) VAR_209 = None if VAR_209 is None: webgateway_tempfile.abort(VAR_206) raise Http404 webgateway_cache.setOmeTiffImage(VAR_2, VAR_19, VAR_115[0], VAR_209) if VAR_208 is None: VAR_61 = HttpResponse(VAR_209, content_type="image/tiff") VAR_61["Content-Disposition"] = 'attachment; filename="%VAR_3.ome.tiff"' % ( str(VAR_202.getId()) + "-" + VAR_205 ) VAR_61["Content-Length"] = len(VAR_209) return VAR_61 else: VAR_208.write(VAR_209) VAR_208.close() return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) else: try: VAR_274 = "+".join((str(VAR_30.getId()) for VAR_30 in VAR_115)).encode("utf-8") VAR_79 = ( "_".join((str(VAR_30.getId()) for VAR_30 in VAR_115[0].getAncestry())) + "_" + md5(VAR_274).hexdigest() + "_ome_tiff_zip" ) VAR_206, VAR_207, VAR_208 = webgateway_tempfile.new(VAR_17 + ".zip", VAR_79=key) if VAR_208 is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) VAR_1.debug(VAR_206) if VAR_208 is None: VAR_208 = BytesIO() VAR_275 = zipfile.ZipFile(VAR_208, "w", zipfile.ZIP_STORED) for VAR_202 in VAR_115: VAR_209 = webgateway_cache.getOmeTiffImage(VAR_2, VAR_19, VAR_202) if VAR_209 is None: VAR_209 = VAR_202.exportOmeTiff() if VAR_209 is None: continue webgateway_cache.setOmeTiffImage(VAR_2, VAR_19, VAR_202, VAR_209) VAR_204 = 255 - len(str(VAR_202.getId())) - 10 VAR_205 = VAR_202.getName()[:VAR_204] VAR_275.writestr(str(VAR_202.getId()) + "-" + VAR_205 + ".ome.tiff", VAR_209) VAR_275.close() if VAR_206 is None: VAR_314 = VAR_208.getvalue() VAR_61 = HttpResponse(VAR_314, content_type="application/zip") VAR_61["Content-Disposition"] = 'attachment; filename="%VAR_3.zip"' % VAR_17 VAR_61["Content-Length"] = len(VAR_314) return VAR_61 except Exception: VAR_1.debug(traceback.format_exc()) raise return HttpResponseRedirect(settings.STATIC_URL + "webgateway/tfiles/" + VAR_207) @login_required() def FUNC_17(VAR_2, VAR_6, VAR_26, VAR_27, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id try: VAR_136 = {} VAR_136["format"] = "video/" + VAR_2.GET.get("format", "quicktime") VAR_136["fps"] = int(VAR_2.GET.get("fps", 4)) VAR_136["minsize"] = (512, 512, "Black") VAR_210 = ".avi" VAR_79 = "%VAR_3-%VAR_3-%VAR_3-%VAR_213-%VAR_3-%s" % ( VAR_6, VAR_26, VAR_27, VAR_136["fps"], FUNC_11(VAR_2), VAR_2.GET.get("format", "quicktime"), ) VAR_27 = int(VAR_27) VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_206, VAR_207, VAR_208 = webgateway_tempfile.new(VAR_92.getName() + VAR_210, VAR_79=key) VAR_1.debug(VAR_206, VAR_207, VAR_208) if VAR_208 is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) if "optsCB" in VAR_9: VAR_136.update(VAR_9["optsCB"](VAR_92)) VAR_136.update(VAR_9.get("opts", {})) VAR_1.debug( "rendering VAR_280 for VAR_92 %VAR_3 with VAR_26 %VAR_3, VAR_27 %VAR_212 and VAR_136 %s" % (VAR_6, VAR_26, VAR_27, VAR_136) ) if VAR_206 is None: VAR_276, VAR_277 = tempfile.mkstemp() else: VAR_277 = VAR_206 # os.path.join(VAR_206, VAR_92.getName()) if VAR_26.lower() == "z": VAR_278, VAR_279 = VAR_92.createMovie( VAR_277, 0, VAR_92.getSizeZ() - 1, VAR_27 - 1, VAR_27 - 1, VAR_136 ) else: VAR_278, VAR_279 = VAR_92.createMovie( VAR_277, VAR_27 - 1, VAR_27 - 1, 0, VAR_92.getSizeT() - 1, VAR_136 ) if VAR_278 is None and VAR_279 is None: raise Http404 if VAR_206 is None: VAR_280 = open(VAR_277).read() os.close(VAR_276) VAR_61 = HttpResponse(VAR_280, content_type=VAR_279) VAR_61["Content-Disposition"] = 'attachment; filename="%s"' % ( VAR_92.getName() + VAR_210 ) VAR_61["Content-Length"] = len(VAR_280) return VAR_61 else: VAR_208.close() return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) except Exception: VAR_1.debug(traceback.format_exc()) raise @login_required() def FUNC_18(VAR_2, VAR_6, VAR_22, VAR_23, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_16 = compress_quality and float(VAR_16) or 0.9 VAR_60 = webgateway_cache.getSplitChannelImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23) if VAR_60 is None: VAR_60 = VAR_92.renderSplitChannel(VAR_22, VAR_23, VAR_98=VAR_16) if VAR_60 is None: raise Http404 webgateway_cache.setSplitChannelImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23, VAR_60) VAR_61 = HttpResponse(VAR_60, content_type="image/jpeg") return VAR_61 def VAR_211(VAR_28): @wraps(VAR_28) def FUNC_64(VAR_2, *VAR_116, **VAR_9): VAR_211 = VAR_2.GET.getlist("debug") if "slow" in VAR_211: time.sleep(5) if "fail" in VAR_211: raise Http404 if "error" in VAR_211: raise AttributeError("Debug requested error") return VAR_28(VAR_2, *VAR_116, **VAR_9) return FUNC_64 def FUNC_20(VAR_28): @wraps(VAR_28) def FUNC_64(VAR_2, *VAR_116, **VAR_9): VAR_1.debug("jsonp") try: VAR_19 = VAR_9.get("server_id", None) if VAR_19 is None and VAR_2.session.get("connector"): VAR_19 = VAR_2.session["connector"].server_id VAR_9["server_id"] = VAR_19 VAR_54 = VAR_28(VAR_2, *VAR_116, **VAR_9) if VAR_9.get("_raw", False): return VAR_54 if isinstance(VAR_54, HttpResponse): return VAR_54 VAR_203 = VAR_2.GET.get("callback", None) if VAR_203 is not None and not VAR_9.get("_internal", False): VAR_54 = json.dumps(VAR_54) VAR_54 = "%VAR_3(%VAR_3)" % (VAR_203, VAR_54) return HttpJavascriptResponse(VAR_54) if VAR_9.get("_internal", False): return VAR_54 VAR_281 = type(VAR_54) is dict return JsonResponse(VAR_54, VAR_281=safe) except Exception as ex: VAR_315 = 500 if isinstance(ex, omero.SecurityViolation): VAR_315 = 403 elif isinstance(ex, omero.ApiUsageException): VAR_315 = 400 VAR_316 = traceback.format_exc() VAR_1.debug(VAR_316) if VAR_9.get("_raw", False) or VAR_9.get("_internal", False): raise return JsonResponse( {"message": str(ex), "stacktrace": VAR_316}, VAR_315=status ) return FUNC_64 @VAR_211 @login_required() def FUNC_21(VAR_2, VAR_6, VAR_22, VAR_23, VAR_29, VAR_8=None, VAR_10=1, **VAR_9): if not VAR_10: VAR_10 = 1 VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 try: VAR_117 = VAR_92.renderRowLinePlotGif(int(VAR_22), int(VAR_23), int(VAR_29), int(VAR_10)) except Exception: VAR_1.debug("a", exc_info=True) raise if VAR_117 is None: raise Http404 VAR_61 = HttpResponse(VAR_117, content_type="image/gif") return VAR_61 @VAR_211 @login_required() def FUNC_22(VAR_2, VAR_6, VAR_22, VAR_23, VAR_30, VAR_10=1, VAR_8=None, **VAR_9): if not VAR_10: VAR_10 = 1 VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_117 = VAR_92.renderColLinePlotGif(int(VAR_22), int(VAR_23), int(VAR_30), int(VAR_10)) if VAR_117 is None: raise Http404 VAR_61 = HttpResponse(VAR_117, content_type="image/gif") return VAR_61 @login_required() @FUNC_20 def FUNC_23(VAR_2, VAR_8=None, VAR_31=False, **VAR_9): VAR_6 = VAR_9["iid"] VAR_79 = VAR_9.get("key", None) VAR_15 = VAR_8.getObject("Image", VAR_6) if VAR_15 is None: if is_public_user(VAR_2): return HttpResponseForbidden() else: return HttpResponseNotFound("Image:%VAR_3 not found" % VAR_6) if VAR_2.GET.get("getDefaults") == "true": VAR_15.resetDefaults(save=False) VAR_54 = imageMarshal(VAR_15, VAR_79=key, VAR_2=request) return VAR_54 @login_required() @FUNC_20 def FUNC_24(VAR_2, VAR_8=None, VAR_31=False, **VAR_9): VAR_118 = VAR_9["wid"] VAR_119 = VAR_8.getObject("Well", VAR_118) if VAR_119 is None: return HttpJavascriptResponseServerError('""') VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") def FUNC_65(VAR_6): return reverse(VAR_120, VAR_116=(VAR_6,)) VAR_121 = {"thumbUrlPrefix": VAR_9.get("urlprefix", FUNC_65)} VAR_54 = VAR_119.simpleMarshal(VAR_121=xtra) return VAR_54 @login_required() @FUNC_20 def FUNC_25(VAR_2, VAR_32, VAR_33=0, VAR_8=None, **VAR_9): try: VAR_33 = VAR_178(VAR_33 or 0) except ValueError: VAR_33 = 0 VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") VAR_122 = getIntOrDefault(VAR_2, "size", None) VAR_1.debug(VAR_122) VAR_19 = VAR_9["server_id"] def FUNC_66(VAR_6): if VAR_122 is not None: return reverse(VAR_120, VAR_116=(VAR_6, VAR_122)) return reverse(VAR_120, VAR_116=(VAR_6,)) VAR_123 = PlateGrid(VAR_8, VAR_32, VAR_33, VAR_9.get("urlprefix", FUNC_66)) VAR_124 = VAR_123.plate if VAR_124 is None: return Http404 VAR_125 = "plategrid-%VAR_213-%s" % (VAR_33, VAR_122) VAR_54 = webgateway_cache.getJson(VAR_2, VAR_19, VAR_124, VAR_125) if VAR_54 is None: VAR_54 = VAR_123.metadata webgateway_cache.setJson(VAR_2, VAR_19, VAR_124, json.dumps(VAR_54), VAR_125) else: VAR_54 = json.loads(VAR_54) return VAR_54 @login_required() @FUNC_20 def FUNC_26(VAR_2, VAR_10=None, VAR_8=None, **VAR_9): VAR_55 = VAR_2.session.get("server_settings", {}).get("browser", {}) VAR_56 = VAR_55.get("thumb_default_size", 96) if VAR_10 is None: VAR_10 = VAR_56 VAR_126 = get_longs(VAR_2, "id") VAR_126 = list(set(VAR_126)) # remove any duplicates if len(VAR_126) == 1: VAR_6 = VAR_126[0] try: VAR_162 = FUNC_5(VAR_2, VAR_6, VAR_10=w, VAR_8=conn) return { VAR_6: "data:VAR_15/VAR_195;base64,%s" % base64.b64encode(VAR_162).decode("utf-8") } except Exception: return {VAR_6: None} VAR_1.debug("Image ids: %r" % VAR_126) if len(VAR_126) > settings.THUMBNAILS_BATCH: return HttpJavascriptResponseServerError( "Max %VAR_3 VAR_127 at VAR_167 time." % settings.THUMBNAILS_BATCH ) VAR_127 = VAR_8.getThumbnailSet([rlong(VAR_212) for VAR_212 in VAR_126], VAR_10) VAR_54 = dict() for VAR_212 in VAR_126: VAR_54[VAR_212] = None try: VAR_23 = VAR_127[VAR_212] if len(VAR_23) > 0: VAR_54[VAR_212] = "data:VAR_15/VAR_195;base64,%s" % base64.b64encode(VAR_23).decode( "utf-8" ) except KeyError: VAR_1.error("Thumbnail not available. (VAR_92 id: %VAR_213)" % VAR_212) except Exception: VAR_1.error(traceback.format_exc()) return VAR_54 @login_required() @FUNC_20 def FUNC_27(VAR_2, VAR_6, VAR_10=None, VAR_11=None, VAR_8=None, VAR_12=None, **VAR_9): VAR_60 = FUNC_5( VAR_2=request, VAR_6=iid, VAR_10=w, VAR_11=h, VAR_8=conn, VAR_12=_defcb, **VAR_9 ) VAR_54 = "data:VAR_15/VAR_195;base64,%s" % base64.b64encode(VAR_60).decode("utf-8") return VAR_54 @login_required() @FUNC_20 def FUNC_28(VAR_2, VAR_34, VAR_8=None, **VAR_9): VAR_128 = VAR_8.getObject("Dataset", VAR_34) if VAR_128 is None: return HttpJavascriptResponseServerError('""') VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") def FUNC_65(VAR_6): return reverse(VAR_120, VAR_116=(VAR_6,)) VAR_121 = { "thumbUrlPrefix": VAR_9.get("urlprefix", FUNC_65), "tiled": VAR_2.GET.get("tiled", False), } return [VAR_30.simpleMarshal(VAR_121=xtra) for VAR_30 in VAR_128.listChildren()] @login_required() @FUNC_20 def FUNC_29(VAR_2, VAR_34, VAR_8=None, **VAR_9): VAR_119 = VAR_8.getObject("Well", VAR_34) VAR_129 = getIntOrDefault(VAR_2, "run", None) if VAR_119 is None: return HttpJavascriptResponseServerError('""') VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") def FUNC_65(VAR_6): return reverse(VAR_120, VAR_116=(VAR_6,)) VAR_121 = {"thumbUrlPrefix": VAR_9.get("urlprefix", FUNC_65)} def FUNC_67(VAR_10): VAR_213 = {} for VAR_30, VAR_108 in (["x", VAR_10.getPosX()], ["y", VAR_10.getPosY()]): if VAR_108 is not None: VAR_213[VAR_30] = {"value": VAR_108.getValue(), "unit": str(VAR_108.getUnit())} return VAR_213 VAR_130 = [] for ws in VAR_119.listChildren(): if ( VAR_129 is not None and ws.plateAcquisition is not None and ws.plateAcquisition.id.val != VAR_129 ): continue VAR_92 = ws.getImage() if VAR_92 is not None: VAR_282 = VAR_92.simpleMarshal(VAR_121=xtra) VAR_27 = FUNC_67(ws) if len(VAR_27.keys()) > 0: VAR_282["position"] = VAR_27 VAR_130.append(VAR_282) return VAR_130 @login_required() @FUNC_20 def FUNC_30(VAR_2, VAR_32, VAR_8=None, **VAR_9): VAR_131 = VAR_8.getObject("Project", VAR_32) if VAR_131 is None: return HttpJavascriptResponse("[]") return [VAR_30.simpleMarshal(VAR_121={"childCount": 0}) for VAR_30 in VAR_131.listChildren()] @login_required() @FUNC_20 def FUNC_31(VAR_2, VAR_34, VAR_8=None, **VAR_9): VAR_132 = VAR_8.getObject("Dataset", VAR_34) return VAR_132.simpleMarshal() @login_required() @FUNC_20 def FUNC_32(VAR_2, VAR_8=None, **VAR_9): VAR_54 = [] for VAR_133 in VAR_8.listProjects(): VAR_54.append({"id": VAR_133.id, "name": VAR_133.name, "description": VAR_133.description or ""}) return VAR_54 @login_required() @FUNC_20 def FUNC_33(VAR_2, VAR_32, VAR_8=None, **VAR_9): VAR_133 = VAR_8.getObject("Project", VAR_32) VAR_54 = VAR_133.simpleMarshal() return VAR_54 @FUNC_20 def FUNC_34(VAR_2, **VAR_9): VAR_134 = settings.OPEN_WITH VAR_135 = [] for ow in VAR_134: if len(ow) < 2: continue VAR_214 = {} viewer["id"] = ow[0] try: VAR_214["url"] = reverse(ow[1]) except NoReverseMatch: VAR_214["url"] = ow[1] try: if len(ow) > 2: if "supported_objects" in ow[2]: VAR_214["supported_objects"] = ow[2]["supported_objects"] if "target" in ow[2]: VAR_214["target"] = ow[2]["target"] if "script_url" in ow[2]: if ow[2]["script_url"].startswith("http"): VAR_214["script_url"] = ow[2]["script_url"] else: VAR_214["script_url"] = static(ow[2]["script_url"]) if "label" in ow[2]: VAR_214["label"] = ow[2]["label"] except Exception: pass VAR_135.append(VAR_214) return {"open_with_options": VAR_135} def FUNC_35(VAR_2): try: VAR_53 = VAR_2.GET VAR_136 = { "search": unicode(VAR_53.get("text", "")).encode("utf8"), "ctx": VAR_53.get("ctx", ""), "grabData": not not VAR_53.get("grabData", False), "parents": not not bool(VAR_53.get("parents", False)), "start": int(VAR_53.get("start", 0)), "limit": int(VAR_53.get("limit", 0)), "key": VAR_53.get("key", None), } VAR_215 = VAR_53.get("author", "") if VAR_215: VAR_136["search"] += " VAR_215:" + VAR_215 return VAR_136 except Exception: VAR_1.error(traceback.format_exc()) return {} @TimeIt(logging.INFO) @login_required() @FUNC_20 def FUNC_36(VAR_2, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_136 = FUNC_35(VAR_2) VAR_54 = [] VAR_1.debug("searchObjects(%VAR_3)" % (VAR_136["search"])) def FUNC_65(VAR_6): return reverse("webgateway_render_thumbnail", VAR_116=(VAR_6,)) VAR_121 = {"thumbUrlPrefix": VAR_9.get("urlprefix", FUNC_65)} try: if VAR_136["ctx"] == "imgs": VAR_283 = VAR_8.searchObjects(["image"], VAR_136["search"], VAR_8.SERVICE_OPTS) else: VAR_283 = VAR_8.searchObjects(None, VAR_136["search"], VAR_8.SERVICE_OPTS) except ApiUsageException: return HttpJavascriptResponseServerError('"parse exception"') def FUNC_68(): VAR_54 = [] if VAR_136["grabData"] and VAR_136["ctx"] == "imgs": VAR_284 = min(VAR_136["start"], len(VAR_283) - 1) if VAR_136["limit"] == 0: VAR_317 = len(VAR_283) else: VAR_317 = min(len(VAR_283), VAR_284 + VAR_136["limit"]) for VAR_212 in range(VAR_284, VAR_317): VAR_318 = VAR_283[VAR_212] try: VAR_54.append( FUNC_23( VAR_2, VAR_19, VAR_6=VAR_318.id, VAR_79=VAR_136["key"], VAR_8=conn, VAR_31=True, ) ) except AttributeError as VAR_30: VAR_1.debug( "(VAR_6 %VAR_212) ignoring Attribute Error: %s" % (VAR_318.id, str(VAR_30)) ) pass except omero.ServerError as VAR_30: VAR_1.debug("(VAR_6 %VAR_212) ignoring Server Error: %s" % (VAR_318.id, str(VAR_30))) return VAR_54 else: return [VAR_30.simpleMarshal(VAR_121=xtra, parents=VAR_136["parents"]) for VAR_30 in VAR_283] VAR_54 = timeit(FUNC_68)() VAR_1.debug(VAR_54) return VAR_54 @require_POST @login_required() def FUNC_37(VAR_2, VAR_6, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_64 = FUNC_13( VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn, VAR_20=True ) if VAR_64 is None: VAR_139 = "false" else: VAR_58 = VAR_64[0]._conn.getEventContext().userId webgateway_cache.invalidateObject(VAR_19, VAR_58, VAR_64[0]) VAR_64[0].getThumbnail() VAR_139 = "true" if VAR_2.GET.get("callback", None): VAR_139 = "%VAR_3(%VAR_3)" % (VAR_2.GET["callback"], VAR_139) return HttpJavascriptResponse(VAR_139) @login_required() @FUNC_20 def FUNC_38(VAR_2, VAR_8=None, **VAR_9): VAR_137 = VAR_8.getScriptService() VAR_138 = VAR_137.getScriptsByMimetype("text/VAR_30-lut") VAR_54 = [] for lut in VAR_138: VAR_216 = lut.path.val + lut.name.val VAR_217 = LUTS_IN_PNG.index(VAR_216) if VAR_216 in LUTS_IN_PNG else -1 VAR_54.append( { "id": lut.id.val, "path": lut.path.val, "name": lut.name.val, "size": unwrap(lut.size), "png_index": VAR_217, } ) VAR_54.sort(VAR_79=lambda VAR_30: x["name"].lower()) return {"luts": VAR_54, "png_luts": LUTS_IN_PNG} @login_required() def FUNC_39(VAR_2, VAR_6, VAR_8=None, **VAR_9): VAR_139 = "false" VAR_53 = VAR_2.GET if VAR_8 is None: VAR_92 = None else: VAR_92 = VAR_8.getObject("Image", VAR_6) if VAR_92 is not None: VAR_115 = [] for VAR_132 in VAR_92.getProject().listChildren(): VAR_115.extend(VAR_132.listChildren()) VAR_218 = VAR_92.getPrimaryPixels().getPixelsType().getValue() VAR_219 = VAR_92.getSizeC() VAR_220 = [VAR_30.getLabel() for VAR_30 in VAR_92.getChannels()] VAR_220.sort() def FUNC_76(VAR_212): if VAR_178(VAR_212.getId()) == VAR_178(VAR_6): return False VAR_285 = VAR_212.getPrimaryPixels() if ( VAR_285 is None or VAR_212.getPrimaryPixels().getPixelsType().getValue() != VAR_218 or VAR_212.getSizeC() != VAR_219 ): return False VAR_286 = [VAR_30.getLabel() for VAR_30 in VAR_212.getChannels()] VAR_286.sort() if VAR_286 != VAR_220: return False return True VAR_115 = filter(FUNC_76, VAR_115) VAR_139 = json.dumps([VAR_30.getId() for VAR_30 in VAR_115]) if VAR_53.get("callback", None): VAR_139 = "%VAR_3(%VAR_3)" % (VAR_53["callback"], VAR_139) return HttpJavascriptResponse(VAR_139) @require_POST @login_required() @FUNC_20 def FUNC_40(VAR_2, VAR_35=False, VAR_8=None, **VAR_9): VAR_53 = VAR_2.POST VAR_140 = VAR_53.getlist("toids") VAR_141 = str(VAR_53.get("to_type", "image")) VAR_141 = to_type.title() if VAR_141 == "Acquisition": VAR_141 = "PlateAcquisition" if len(VAR_140) == 0: raise Http404( "Need to specify objects in VAR_2, E.g." " ?totype=VAR_128&VAR_140=1&VAR_140=2" ) VAR_140 = [int(id) for id in VAR_140] VAR_142 = VAR_8.getRenderingSettingsService() VAR_8.SERVICE_OPTS.setOmeroGroup("-1") VAR_143 = VAR_8.getObject(VAR_141, VAR_140[0]) if VAR_143 is not None: VAR_221 = VAR_143.getDetails().group.id.val VAR_8.SERVICE_OPTS.setOmeroGroup(VAR_221) if VAR_35: VAR_54 = VAR_142.resetDefaultsByOwnerInSet(VAR_141, VAR_140, VAR_8.SERVICE_OPTS) else: VAR_54 = VAR_142.resetDefaultsInSet(VAR_141, VAR_140, VAR_8.SERVICE_OPTS) return VAR_54 @login_required() @FUNC_20 def FUNC_41(VAR_2, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_139 = False VAR_144 = VAR_2.GET.get("fromid", None) VAR_140 = VAR_2.POST.getlist("toids") VAR_141 = str(VAR_2.POST.get("to_type", "image")) VAR_145 = None if VAR_141 not in ("dataset", "plate", "acquisition"): VAR_141 = "Image" # default is VAR_15 if VAR_144 is not None and len(VAR_140) == 0: VAR_2.session.modified = True VAR_2.session["fromid"] = VAR_144 if VAR_2.session.get("rdef") is not None: del VAR_2.session["rdef"] return True VAR_53 = VAR_2.GET or VAR_2.POST if VAR_53.get("c") is not None: VAR_145 = {"c": str(VAR_53.get("c"))} # VAR_50 if VAR_53.get("maps"): try: VAR_145["maps"] = json.loads(VAR_53.get("maps")) except Exception: pass if VAR_53.get("pixel_range"): VAR_145["pixel_range"] = str(VAR_53.get("pixel_range")) if VAR_53.get("m"): VAR_145["m"] = str(VAR_53.get("m")) # model (grey) if VAR_53.get("z"): VAR_145["z"] = str(VAR_53.get("z")) # VAR_22 & VAR_23 VAR_27 if VAR_53.get("t"): VAR_145["t"] = str(VAR_53.get("t")) VAR_36 = VAR_2.GET.get("imageId", VAR_2.POST.get("imageId", None)) if VAR_36: VAR_145["imageId"] = int(VAR_36) if VAR_2.method == "GET": VAR_2.session.modified = True VAR_2.session["rdef"] = VAR_145 if VAR_2.session.get("fromid") is not None: del VAR_2.session["fromid"] return True if VAR_144 is None: VAR_144 = VAR_2.session.get("fromid", None) def FUNC_69(VAR_15): VAR_54 = {} VAR_222 = [] VAR_223 = [] for VAR_212, ch in enumerate(VAR_15.getChannels()): VAR_287 = "" if ch.isActive() else "-" VAR_288 = ch.getWindowStart() VAR_289 = ch.getWindowEnd() VAR_68 = ch.getLut() VAR_223.append({"inverted": {"enabled": ch.isInverted()}}) if not VAR_68 or len(VAR_68) == 0: VAR_68 = ch.getColor().getHtml() VAR_222.append("%VAR_3%VAR_3|%VAR_3:%VAR_3$%s" % (VAR_287, VAR_212 + 1, VAR_288, VAR_289, VAR_68)) VAR_54["c"] = ",".join(VAR_222) VAR_54["maps"] = VAR_223 VAR_54["m"] = "g" if VAR_15.isGreyscaleRenderingModel() else "c" VAR_54["z"] = VAR_15.getDefaultZ() + 1 VAR_54["t"] = VAR_15.getDefaultT() + 1 return VAR_54 def FUNC_70(VAR_15, VAR_145): VAR_107 = FUNC_12(VAR_145, "inverted", VAR_15.getSizeC()) VAR_50, VAR_51, VAR_52 = FUNC_2(VAR_145["c"]) VAR_15.setActiveChannels(VAR_50, VAR_51, VAR_52, VAR_107) if VAR_145["m"] == "g": VAR_15.setGreyscaleRenderingModel() else: VAR_15.setColorRenderingModel() if "z" in VAR_145: VAR_15._re.setDefaultZ(VAR_178(VAR_145["z"]) - 1) if "t" in VAR_145: VAR_15._re.setDefaultT(VAR_178(VAR_145["t"]) - 1) VAR_15.saveDefaults() if VAR_145 is None: VAR_145 = VAR_2.session.get("rdef") if VAR_2.method == "POST": VAR_224 = None VAR_225 = None if VAR_144 is None: if VAR_145 is not None and len(VAR_140) > 0: VAR_225 = VAR_8.getObject("Image", VAR_145["imageId"]) if VAR_225 is not None: VAR_224 = FUNC_69(VAR_225) FUNC_70(VAR_225, VAR_145) VAR_144 = VAR_225.getId() try: VAR_144 = VAR_178(VAR_144) VAR_140 = [VAR_178(VAR_30) for VAR_30 in VAR_140] except TypeError: VAR_144 = None except ValueError: VAR_144 = None if VAR_144 is not None and len(VAR_140) > 0: VAR_290 = VAR_8.getObject("Image", VAR_144) VAR_291 = VAR_290.getOwner().getId() VAR_139 = VAR_8.applySettingsToSet(VAR_144, VAR_141, VAR_140) if VAR_139 and True in VAR_139: for VAR_6 in VAR_139[True]: VAR_92 = VAR_8.getObject("Image", VAR_6) VAR_92 is not None and webgateway_cache.invalidateObject( VAR_19, VAR_291, VAR_92 ) if VAR_141 == "Image" and VAR_144 not in VAR_140: if VAR_224 is not None and VAR_225 is not None: FUNC_70(VAR_225, VAR_224) return VAR_139 else: return HttpResponseNotAllowed(["POST"]) @login_required() @FUNC_20 def FUNC_42(VAR_2, VAR_8=None, **VAR_9): VAR_145 = VAR_2.session.get("rdef") VAR_15 = None if VAR_145 is None: VAR_144 = VAR_2.session.get("fromid", None) if VAR_144 is not None: VAR_15 = VAR_8.getObject("Image", VAR_144) if VAR_15 is not None: VAR_54 = imageMarshal(VAR_15, VAR_2=request) VAR_222 = [] VAR_223 = [] for VAR_212, ch in enumerate(VAR_54["channels"]): VAR_287 = ch["active"] and str(VAR_212 + 1) or "-%s" % (VAR_212 + 1) VAR_68 = ch.get("lut") or ch["color"] VAR_222.append( "%VAR_3|%VAR_3:%VAR_3$%s" % (VAR_287, ch["window"]["start"], ch["window"]["end"], VAR_68) ) VAR_223.append( { "inverted": {"enabled": ch["inverted"]}, "quantization": { "coefficient": ch["coefficient"], "family": ch["family"], }, } ) VAR_145 = { "c": (",".join(VAR_222)), "m": VAR_54["rdefs"]["model"], "pixel_range": "%VAR_3:%s" % (VAR_54["pixel_range"][0], VAR_54["pixel_range"][1]), "maps": VAR_223, } return {"rdef": VAR_145} @login_required() def FUNC_43(VAR_2, VAR_6, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_146 = Server.get(VAR_19).server VAR_147 = FUNC_3(VAR_2) VAR_55 = VAR_2.session.get("server_settings", {}).get("viewer", {}) VAR_148 = VAR_55.get("interpolate_pixels", True) VAR_149 = VAR_55.get("roi_limit", 2000) try: VAR_15 = VAR_8.getObject("Image", VAR_6) if VAR_15 is None: VAR_1.debug("(VAR_167)Image %VAR_3 not found..." % (str(VAR_6))) raise Http404 VAR_226 = None VAR_227 = None VAR_228 = None VAR_229 = None if hasattr(settings, "SHARING_OPENGRAPH"): VAR_226 = settings.SHARING_OPENGRAPH.get(VAR_146) VAR_1.debug("Open Graph VAR_308: %s", VAR_226) if hasattr(settings, "SHARING_TWITTER"): VAR_227 = settings.SHARING_TWITTER.get(VAR_146) VAR_1.debug("Twitter VAR_308: %s", VAR_227) if VAR_226 or VAR_227: VAR_292 = {"iid": VAR_6} VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") VAR_228 = VAR_2.build_absolute_uri(reverse(VAR_120, VAR_9=VAR_292)) VAR_229 = VAR_2.build_absolute_uri( reverse("webgateway_full_viewer", VAR_9=VAR_292) ) VAR_213 = { "blitzcon": VAR_8, "image": VAR_15, "opts": VAR_147, "interpolate": VAR_148, "build_year": build_year, "roiLimit": VAR_149, "roiCount": VAR_15.getROICount(), "viewport_server": VAR_9.get( "viewport_server", reverse("webgateway"), ).rstrip("/"), "opengraph": VAR_226, "twitter": VAR_227, "image_preview": VAR_228, "page_url": VAR_229, "object": "image:%i" % int(VAR_6), } VAR_230 = VAR_9.get("template", "webgateway/viewport/omero_image.html") VAR_61 = render(VAR_2, VAR_230, VAR_213) except omero.SecurityViolation: VAR_1.warn("SecurityViolation in Image:%s", VAR_6) VAR_1.warn(traceback.format_exc()) raise Http404 return HttpResponse(VAR_61) @login_required() def FUNC_44(VAR_2, VAR_6=None, VAR_8=None, **VAR_9): VAR_114 = VAR_2.GET.get("format", "png") if VAR_114 not in ("jpeg", "png", "tif"): VAR_114 = "png" VAR_150 = [] VAR_151 = [] if VAR_6 is None: VAR_150 = VAR_2.GET.getlist("image") if len(VAR_150) == 0: VAR_151 = VAR_2.GET.getlist("well") if len(VAR_151) == 0: return HttpResponseServerError( "No VAR_152 or VAR_153 specified in VAR_2." " Use ?VAR_15=123 or ?VAR_119=123" ) else: VAR_150 = [VAR_6] VAR_152 = [] if VAR_150: VAR_152 = list(VAR_8.getObjects("Image", VAR_150)) elif VAR_151: try: VAR_319 = int(VAR_2.GET.get("index", 0)) except ValueError: VAR_319 = 0 for VAR_10 in VAR_8.getObjects("Well", VAR_151): VAR_152.append(VAR_10.getWellSample(VAR_319).image()) if len(VAR_152) == 0: VAR_231 = "Cannot download as %VAR_3. Images (ids: %VAR_3) not found." % (VAR_114, VAR_150) VAR_1.debug(VAR_231) return HttpResponseServerError(VAR_231) if len(VAR_152) == 1: VAR_60 = VAR_152[0].renderJpeg() if VAR_60 is None: raise Http404 VAR_61 = HttpResponse(VAR_60, VAR_279="image/jpeg") VAR_61["Content-Length"] = len(VAR_60) VAR_61["Content-Disposition"] = "attachment; filename=%VAR_3.jpg" % ( VAR_152[0].getName().replace(" ", "_") ) else: VAR_232 = tempfile.NamedTemporaryFile(suffix=".download_as") def FUNC_77(VAR_233, VAR_234, VAR_235): VAR_17 = os.path.basename(VAR_233) VAR_293 = "%VAR_3.%s" % (VAR_17, VAR_234) VAR_293 = os.path.join(VAR_235, VAR_293) VAR_212 = 1 VAR_17 = VAR_293[: -(len(VAR_234) + 1)] while os.path.exists(VAR_293): imgName = "%s_(%VAR_213).%s" % (VAR_17, VAR_212, VAR_234) VAR_212 += 1 return VAR_293 try: VAR_294 = tempfile.mkdtemp() VAR_1.debug("download_as dir: %s" % VAR_294) try: for VAR_92 in VAR_152: VAR_22 = VAR_23 = None try: VAR_331 = VAR_92.renderImage(VAR_22, VAR_23) VAR_332 = FUNC_77(VAR_92.getName(), VAR_114, VAR_294) VAR_331.save(VAR_332) finally: VAR_92._re.close() VAR_320 = zipfile.ZipFile(VAR_232, "w", zipfile.ZIP_DEFLATED) try: VAR_324 = os.path.join(VAR_294, "*") for VAR_17 in glob.glob(VAR_324): VAR_320.write(VAR_17, os.path.basename(VAR_17)) finally: VAR_320.close() finally: shutil.rmtree(VAR_294, ignore_errors=True) VAR_240 = VAR_2.GET.get("zipname", "Download_as_%s" % VAR_114) VAR_240 = VAR_240.replace(" ", "_") if not VAR_240.endswith(".zip"): VAR_240 = "%VAR_3.zip" % VAR_240 VAR_61 = StreamingHttpResponse(FileWrapper(VAR_232)) VAR_61["Content-Length"] = VAR_232.tell() VAR_61["Content-Disposition"] = "attachment; filename=%s" % VAR_240 VAR_232.seek(0) except Exception: VAR_232.close() VAR_321 = traceback.format_exc() VAR_1.error(VAR_321) return HttpResponseServerError("Cannot download file (id:%VAR_3)" % VAR_6) VAR_61["Content-Type"] = "application/force-download" return VAR_61 @login_required(doConnectionCleanup=False) def FUNC_45(VAR_2, VAR_6=None, VAR_8=None, **VAR_9): VAR_150 = [] VAR_151 = [] VAR_150 = VAR_2.GET.getlist("image") VAR_151 = VAR_2.GET.getlist("well") if VAR_6 is None: if len(VAR_150) == 0 and len(VAR_151) == 0: return HttpResponseServerError( "No VAR_152 or VAR_153 specified in VAR_2." " Use ?VAR_15=123 or ?VAR_119=123" ) else: VAR_150 = [VAR_6] VAR_152 = list() VAR_153 = list() if VAR_150: VAR_152 = list(VAR_8.getObjects("Image", VAR_150)) elif VAR_151: try: VAR_319 = int(VAR_2.GET.get("index", 0)) except ValueError: VAR_319 = 0 VAR_153 = VAR_8.getObjects("Well", VAR_151) for VAR_10 in VAR_153: VAR_152.append(VAR_10.getWellSample(VAR_319).image()) if len(VAR_152) == 0: VAR_236 = ( "Cannot download archived file because Images not " "found (ids: %VAR_3)" % (VAR_150) ) VAR_1.debug(VAR_236) return HttpResponseServerError(VAR_236) for ob in VAR_153: if hasattr(ob, "canDownload"): if not ob.canDownload(): return HttpResponseNotFound() for ob in VAR_152: VAR_119 = None try: VAR_119 = ob.getParent().getParent() except Exception: if hasattr(ob, "canDownload"): if not ob.canDownload(): return HttpResponseNotFound() else: if VAR_119 and isinstance(VAR_119, omero.gateway.WellWrapper): if hasattr(VAR_119, "canDownload"): if not VAR_119.canDownload(): return HttpResponseNotFound() VAR_154 = {} for VAR_15 in VAR_152: for VAR_28 in VAR_15.getImportedImageFiles(): VAR_154[VAR_28.getId()] = VAR_28 VAR_155 = list(VAR_154.values()) if len(VAR_155) == 0: VAR_236 = ( "Tried downloading archived VAR_155 from VAR_15 with no" " VAR_155 archived." ) VAR_1.debug(VAR_236) return HttpResponseServerError(VAR_236) if len(VAR_155) == 1: VAR_237 = VAR_155[0] VAR_61 = ConnCleaningHttpResponse( VAR_237.getFileInChunks(buf=settings.CHUNK_SIZE) ) VAR_61.conn = VAR_8 VAR_61["Content-Length"] = VAR_237.getSize() VAR_238 = VAR_237.getName().replace(" ", "_").replace(",", ".") VAR_61["Content-Disposition"] = "attachment; filename=%s" % (VAR_238) else: VAR_239 = sum(VAR_28.size for VAR_28 in VAR_155) if VAR_239 > settings.MAXIMUM_MULTIFILE_DOWNLOAD_ZIP_SIZE: VAR_236 = ( "Total VAR_7 of VAR_155 %VAR_213 is larger than %VAR_213. " "Try requesting fewer VAR_155." % (VAR_239, settings.MAXIMUM_MULTIFILE_DOWNLOAD_ZIP_SIZE) ) VAR_1.warn(VAR_236) return HttpResponseForbidden(VAR_236) VAR_232 = tempfile.NamedTemporaryFile(suffix=".archive") VAR_240 = VAR_2.GET.get("zipname", VAR_15.getName()) try: VAR_240 = zip_archived_files(VAR_152, VAR_232, VAR_240, buf=settings.CHUNK_SIZE) VAR_295 = FileWrapper(VAR_232) VAR_61 = ConnCleaningHttpResponse(VAR_295) VAR_61.conn = VAR_8 VAR_61["Content-Length"] = VAR_232.tell() VAR_61["Content-Disposition"] = "attachment; filename=%s" % VAR_240 VAR_232.seek(0) except Exception: VAR_232.close() VAR_236 = "Cannot download file (id:%VAR_3)" % (VAR_6) VAR_1.error(VAR_236, exc_info=True) return HttpResponseServerError(VAR_236) VAR_61["Content-Type"] = "application/force-download" return VAR_61 @login_required() @FUNC_20 def FUNC_46(VAR_2, VAR_6, VAR_8=None, **VAR_9): VAR_15 = VAR_8.getObject("Image", VAR_6) if VAR_15 is None: raise Http404 VAR_156 = VAR_15.getImportedImageFilePaths() return {"repo": VAR_156["server_paths"], "client": VAR_156["client_paths"]} @login_required() @FUNC_20 def FUNC_47(VAR_2, VAR_13, VAR_14, VAR_8=None, **VAR_9): VAR_13 = int(VAR_13) VAR_14 = int(VAR_14) VAR_65 = VAR_8.getQueryService().findByQuery( "select VAR_65 from Roi as VAR_241 " "join VAR_241.shapes as VAR_65 " "where VAR_241.id = %VAR_213 and VAR_65.id = %d" % (VAR_13, VAR_14), None, ) VAR_1.debug("Shape: %r" % VAR_65) if VAR_65 is None: VAR_1.debug("No such VAR_65: %r" % VAR_14) raise Http404 return JsonResponse(shapeMarshal(VAR_65)) @login_required() @FUNC_20 def FUNC_48(VAR_2, VAR_36, VAR_8=None, **VAR_9): VAR_157 = [] VAR_158 = VAR_8.getRoiService() VAR_62 = VAR_158.findByImage(VAR_178(VAR_36), None, VAR_8.SERVICE_OPTS) for VAR_53 in VAR_62.rois: VAR_241 = {} roi["id"] = VAR_53.getId().getValue() VAR_63 = [] for VAR_3 in VAR_53.copyShapes(): if VAR_3 is None: # seems possible in some situations continue VAR_63.append(shapeMarshal(VAR_3)) VAR_63.sort(VAR_79=lambda VAR_30: "%03d%03d" % (VAR_30.get("theZ", -1), VAR_30.get("theT", -1))) VAR_241["shapes"] = VAR_63 VAR_157.append(VAR_241) VAR_157.sort(VAR_79=lambda VAR_30: x["id"]) return VAR_157 @login_required() def FUNC_49(VAR_2, VAR_6, VAR_37, VAR_8=None, **VAR_9): VAR_15 = VAR_8.getObject("Image", VAR_6) if VAR_15 is None: raise Http404 VAR_159, VAR_160 = VAR_8.getMaxPlaneSize() VAR_86 = VAR_15.getSizeX() VAR_87 = VAR_15.getSizeY() if (VAR_86 * VAR_87) > (VAR_159 * VAR_160): VAR_231 = "Histogram not supported for 'big' VAR_152 (over %VAR_3 * %VAR_3 pixels)" % ( VAR_159, VAR_160, ) return JsonResponse({"error": VAR_231}) VAR_74 = int(VAR_2.GET.get("theZ", 0)) VAR_73 = int(VAR_2.GET.get("theT", 0)) VAR_37 = int(VAR_37) VAR_161 = int(VAR_2.GET.get("bins", 256)) VAR_162 = VAR_15.getHistogram([VAR_37], VAR_161, VAR_74=theZ, VAR_73=theT) VAR_163 = VAR_162[VAR_37] return JsonResponse({"data": VAR_163}) @login_required(FUNC_58=True) @FUNC_20 def FUNC_50(VAR_2, VAR_38, VAR_8=None, **VAR_9): if VAR_2.method == "POST": VAR_8.setGroupNameForSession("system") VAR_175 = VAR_2.session["connector"] VAR_175 = Connector(VAR_175.server_id, VAR_175.is_secure) VAR_242 = VAR_8.getSessionService().getSession(VAR_8._sessionUuid) VAR_243 = VAR_242.getTimeToIdle().val VAR_175.omero_session_key = VAR_8.suConn(VAR_38, VAR_243=ttl)._sessionUuid VAR_2.session["connector"] = VAR_175 VAR_8.revertGroupForSession() VAR_8.close() return True else: VAR_244 = { "url": reverse("webgateway_su", VAR_116=[VAR_38]), "submit": "Do you want to FUNC_50 to %s" % VAR_38, } VAR_230 = "webgateway/base/includes/post_form.html" return render(VAR_2, VAR_230, VAR_244) def FUNC_51(VAR_2, VAR_39, VAR_40, VAR_8=None, **VAR_9): warnings.warn("Deprecated. Use FUNC_52()", DeprecationWarning) return FUNC_52(VAR_2, VAR_39, VAR_40, VAR_8, **VAR_9) def FUNC_52(VAR_2, VAR_39, VAR_40, VAR_8=None, **VAR_9): VAR_164 = VAR_8.getQueryService() VAR_39 = objtype.split(".") VAR_66 = omero.sys.ParametersI() VAR_66.addId(VAR_40) VAR_66.addString("ns", NSBULKANNOTATIONS) VAR_66.addString("mt", "OMERO.tables") VAR_43 = "select obj0 from %VAR_3 obj0\n" % VAR_39[0] for VAR_212, VAR_23 in enumerate(VAR_39[1:]): VAR_43 += "join fetch VAR_202%VAR_213.%VAR_3 VAR_202%VAR_213\n" % (VAR_212, VAR_23, VAR_212 + 1) VAR_43 += """ left outer join fetch obj0.annotationLinks VAR_165 left outer join fetch VAR_165.child as VAR_28 left outer join fetch VAR_165.parent left outer join fetch VAR_28.file join fetch VAR_165.details.owner join fetch VAR_165.details.creationEvent where VAR_202%VAR_213.id=:id and (VAR_28.ns=:ns or VAR_28.file.mimetype=:mt)""" % ( len(VAR_39) - 1 ) VAR_24 = VAR_8.createServiceOptsDict() VAR_24.setOmeroGroup("-1") try: VAR_245 = VAR_164.findAllByQuery(VAR_43, VAR_66, VAR_24) except omero.QueryException: return dict(VAR_176="%VAR_3 cannot be queried" % VAR_39, VAR_43=query) VAR_162 = [] VAR_165 = [link for VAR_202 in VAR_245 for link in VAR_202.copyAnnotationLinks()] for link in VAR_165: VAR_246 = link.child if not isinstance(VAR_246, omero.model.FileAnnotation): continue VAR_247 = VAR_246.details.owner VAR_248 = "%VAR_3 %s" % (unwrap(VAR_247.firstName), unwrap(VAR_247.lastName)) VAR_249 = link.details.owner VAR_250 = "%VAR_3 %s" % (unwrap(VAR_249.firstName), unwrap(VAR_249.lastName)) VAR_162.append( dict( id=VAR_246.id.val, file=VAR_246.file.id.val, parentType=VAR_39[0], parentId=link.parent.id.val, VAR_247=VAR_248, VAR_249=VAR_250, addedOn=unwrap(link.details.creationEvent._time), ) ) return dict(VAR_162=data) VAR_41 = login_required()(FUNC_20(FUNC_52)) def FUNC_53(VAR_2, VAR_42, VAR_8=None, VAR_43=None, VAR_44=False, **VAR_9): if VAR_43 is None: VAR_43 = VAR_2.GET.get("query") if not VAR_43: return dict(VAR_176="Must specify VAR_43 parameter, use * to retrieve all") VAR_166 = VAR_2.GET.getlist("col_names") VAR_24 = VAR_8.createServiceOptsDict() VAR_24.setOmeroGroup("-1") VAR_53 = VAR_8.getSharedResources() VAR_23 = VAR_53.openTable(omero.model.OriginalFileI(VAR_42), VAR_24) if not VAR_23: return dict(VAR_176="Table %VAR_3 not found" % VAR_42) try: VAR_251 = VAR_23.getHeaders() VAR_252 = range(len(VAR_251)) if VAR_166: VAR_296 = ( [(VAR_212, j) for (VAR_212, j) in enumerate(VAR_251) if j.name in VAR_166] if VAR_166 else [(VAR_212, j) for (VAR_212, j) in enumerate(VAR_251)] ) cols = [] VAR_252 = [] for col_name in VAR_166: for (VAR_212, j) in VAR_296: if col_name == j.name: VAR_252.append(VAR_212) VAR_251.append(j) break VAR_253 = VAR_23.getNumberOfRows() VAR_254 = VAR_9.get("offset", 0) VAR_255 = VAR_9.get("limit", None) if not VAR_254: VAR_254 = int(VAR_2.GET.get("offset", 0)) if not VAR_255: VAR_255 = ( int(VAR_2.GET.get("limit")) if VAR_2.GET.get("limit") is not None else None ) VAR_256 = VAR_254 VAR_257 = VAR_9.get("limit", VAR_253) VAR_258 = min(VAR_253, VAR_256 + VAR_257) if VAR_43 == "*": VAR_297 = range(VAR_256, VAR_258) VAR_298 = VAR_253 else: VAR_299 = re.match(r"^(\VAR_10+)-(\VAR_213+)", VAR_43) if VAR_299: VAR_43 = "(%VAR_3==%s)" % (VAR_299.group(1), VAR_299.group(2)) try: VAR_1.info(VAR_43) VAR_297 = VAR_23.getWhereList(VAR_43, None, 0, VAR_253, 1) VAR_298 = len(VAR_297) hits = VAR_297[VAR_256:VAR_258] except Exception: return dict(VAR_176="Error executing VAR_43: %s" % VAR_43) def FUNC_78(VAR_259, VAR_11): VAR_300 = 0 VAR_301 = 1000 while VAR_300 < len(VAR_11): VAR_301 = min(VAR_301, len(VAR_11) - VAR_300) VAR_322 = VAR_259.slice(VAR_252, VAR_11[VAR_300 : idx + VAR_301]) VAR_300 += VAR_301 yield [ [col.values[row] for col in VAR_322.columns] for row in range(0, len(VAR_322.rowNumbers)) ] VAR_260 = FUNC_78(VAR_23, VAR_297) VAR_261 = { "data": { "column_types": [col.__class__.__name__ for col in VAR_251], "columns": [col.name for col in VAR_251], }, "meta": { "rowCount": VAR_253, "totalCount": VAR_298, "limit": VAR_255, "offset": VAR_254, }, } if not VAR_44: VAR_302 = [] for VAR_253 in list(VAR_260): VAR_302.extend(VAR_253) VAR_261["data"]["rows"] = VAR_302 else: VAR_261["data"]["lazy_rows"] = VAR_260 VAR_261["table"] = VAR_23 return VAR_261 finally: if not VAR_44: VAR_23.close() VAR_45 = login_required()(FUNC_20(FUNC_53)) def FUNC_54(VAR_2, VAR_42, VAR_8=None, VAR_43=None, VAR_44=False, **VAR_9): VAR_24 = VAR_8.createServiceOptsDict() VAR_24.setOmeroGroup("-1") VAR_53 = VAR_8.getSharedResources() VAR_23 = VAR_53.openTable(omero.model.OriginalFileI(VAR_42), VAR_24) if not VAR_23: return dict(VAR_176="Table %VAR_3 not found" % VAR_42) try: VAR_251 = VAR_23.getHeaders() VAR_253 = VAR_23.getNumberOfRows() VAR_261 = { "columns": [ { "name": col.name, "description": col.description, "type": col.__class__.__name__, } for col in VAR_251 ], "totalCount": VAR_253, } return VAR_261 finally: if not VAR_44: VAR_23.close() VAR_46 = login_required()(FUNC_20(FUNC_54)) @login_required() @FUNC_20 def FUNC_55(VAR_2, VAR_39, VAR_40, VAR_8=None, **VAR_9): VAR_167 = FUNC_52(VAR_2, VAR_39, VAR_40, VAR_8, **VAR_9) if "error" in VAR_167: return VAR_167 if len(VAR_167["data"]) < 1: return dict(VAR_176="Could not retrieve bulk VAR_41 table") VAR_168 = 0 VAR_169 = None VAR_170 = sorted(VAR_167["data"], VAR_79=lambda VAR_30: x["file"], reverse=True) VAR_171 = None for VAR_246 in VAR_170: VAR_171 = FUNC_53(VAR_2, VAR_246["file"], VAR_8, **VAR_9) if "error" not in VAR_171: VAR_169 = VAR_246 VAR_168 = VAR_246["file"] break if VAR_169 is None: return dict( VAR_176=VAR_171.get( "error", "Could not retrieve matching bulk VAR_246 table" ) ) VAR_171["id"] = VAR_168 VAR_171["annId"] = VAR_169["id"] VAR_171["owner"] = VAR_169["owner"] VAR_171["addedBy"] = VAR_169["addedBy"] VAR_171["parentType"] = VAR_169["parentType"] VAR_171["parentId"] = VAR_169["parentId"] VAR_171["addedOn"] = VAR_169["addedOn"] return VAR_171 class CLASS_1(View): VAR_172 = LoginForm VAR_173 = "OMERO.webapi" @method_decorator(sensitive_post_parameters("password", "csrfmiddlewaretoken")) def FUNC_71(self, *VAR_116, **VAR_9): return super(CLASS_1, self).dispatch(*VAR_116, **VAR_9) def FUNC_72(self, VAR_2, VAR_174=None): return JsonResponse( {"message": ("POST only with VAR_304, VAR_305, " "server and csrftoken")}, VAR_315=405, ) def FUNC_73(self, VAR_2, VAR_8, VAR_175): VAR_203 = VAR_8.getEventContext() VAR_24 = {} for VAR_167 in [ "sessionId", "sessionUuid", "userId", "userName", "groupId", "groupName", "isAdmin", "eventId", "eventType", "memberOfGroups", "leaderOfGroups", ]: if hasattr(VAR_203, VAR_167): VAR_24[VAR_167] = getattr(VAR_203, VAR_167) return JsonResponse({"success": True, "eventContext": VAR_24}) def FUNC_74(self, VAR_2, VAR_176=None, VAR_177=None): if VAR_176 is None and VAR_177 is not None: VAR_303 = [] for VAR_33 in VAR_177: for VAR_318 in VAR_33.errors: VAR_303.append("%VAR_3: %s" % (VAR_33.label, VAR_318)) VAR_176 = " ".join(VAR_303) elif VAR_176 is None: VAR_176 = "Login failed. Reason unknown." return JsonResponse({"message": VAR_176}, VAR_315=403) def FUNC_75(self, VAR_2, VAR_174=None): VAR_176 = None VAR_177 = self.form_class(VAR_2.POST.copy()) if VAR_177.is_valid(): VAR_304 = VAR_177.cleaned_data["username"] VAR_305 = VAR_177.cleaned_data["password"] VAR_19 = VAR_177.cleaned_data["server"] VAR_306 = settings.SECURE VAR_175 = Connector(VAR_19, VAR_306) VAR_307 = True if settings.CHECK_VERSION: VAR_307 = VAR_175.check_version(self.useragent) if ( VAR_19 is not None and VAR_304 is not None and VAR_305 is not None and VAR_307 ): VAR_8 = VAR_175.create_connection( self.useragent, VAR_304, VAR_305, userip=get_client_ip(VAR_2) ) if VAR_8 is not None: try: VAR_2.session["connector"] = VAR_175 try: VAR_335 = settings.UPGRADES_URL except Exception: VAR_335 = VAR_8.getUpgradesUrl() upgradeCheck(url=VAR_335) return self.handle_logged_in(VAR_2, VAR_8, VAR_175) finally: VAR_8.close(hard=False) if not VAR_175.is_server_up(self.useragent): VAR_176 = "Server is not responding," " please contact administrator." elif not settings.CHECK_VERSION: VAR_176 = ( "Connection not available, please check your" " credentials and version compatibility." ) else: if not VAR_307: VAR_176 = ( "Client version does not VAR_299 server," " please contact administrator." ) else: VAR_176 = settings.LOGIN_INCORRECT_CREDENTIALS_TEXT return self.handle_not_logged_in(VAR_2, VAR_176, VAR_177) @login_required() @FUNC_20 def FUNC_56(VAR_2, VAR_47=None, VAR_8=None, **VAR_9): try: VAR_92 = VAR_8.getObject("Image", VAR_47) if VAR_92 is None: return {"error": "No VAR_15 with id " + str(VAR_47)} return {"rdefs": VAR_92.getAllRenderingDefs()} except Exception: VAR_1.debug(traceback.format_exc()) return {"error": "Failed to retrieve rdefs"}
import .re import json import base64 import .warnings from functools import .wraps import .omero import .omero.clients from past.builtins import unicode from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseServerError, JsonResponse, HttpResponseForbidden, ) from django.http import ( HttpResponseRedirect, HttpResponseNotAllowed, Http404, StreamingHttpResponse, HttpResponseNotFound, ) from django.views.decorators.http import .require_POST from django.views.decorators.debug import .sensitive_post_parameters from django.utils.decorators import .method_decorator from django.core.urlresolvers import .reverse, NoReverseMatch from django.conf import .settings from wsgiref.util import FileWrapper from omero.rtypes import .rlong, unwrap from omero.constants.namespaces import NSBULKANNOTATIONS from .util import .points_string_to_XY_list, xy_list_to_bbox from .plategrid import PlateGrid from omeroweb.version import .omeroweb_buildyear as build_year from .marshal import .imageMarshal, shapeMarshal, rgb_int2rgba from django.contrib.staticfiles.templatetags.staticfiles import .static from django.views.generic import View from django.shortcuts import .render from omeroweb.webadmin.forms import LoginForm from omeroweb.decorators import .get_client_ip, is_public_user from omeroweb.webadmin.webadmin_utils import upgradeCheck try: from hashlib import .md5 except Exception: from md5 import .md5 try: import .long except ImportError: VAR_178 = int from io import BytesIO import .tempfile from omero import ApiUsageException from omero.util.decorators import .timeit, TimeIt from omeroweb.httprsp import HttpJavascriptResponse, HttpJavascriptResponseServerError from omeroweb.connector import Server import glob from omeroweb.webgateway.webgateway_cache import ( webgateway_cache, CacheBase, webgateway_tempfile, ) import logging import .os import .traceback import .time import .zipfile import .shutil from omeroweb.decorators import login_required, ConnCleaningHttpResponse from omeroweb.connector import Connector from omeroweb.webgateway.util import .zip_archived_files, LUTS_IN_PNG from omeroweb.webgateway.util import .get_longs, getIntOrDefault VAR_0 = CacheBase() VAR_1 = logging.getLogger(__name__) try: from PIL import Image from PIL import ImageDraw except Exception: # pragma: nocover try: import Image import ImageDraw except Exception: VAR_1.error("No Pillow installed") try: import numpy VAR_48 = True except ImportError: VAR_1.error("No numpy installed") VAR_48 = False def VAR_319(VAR_2): return HttpResponse("Welcome to webgateway") def FUNC_1(VAR_3): return unicode(VAR_3).encode("utf-8") class CLASS_0(object): def __init__(self, VAR_49): self._blitzcon = VAR_49 self.loggedIn = False def FUNC_57(self): self.loggedIn = True def FUNC_58(self): return self._blitzcon.isAdmin() def FUNC_59(self): return self._blitzcon.canBeAdmin() def FUNC_60(self): return self._blitzcon.getUserId() def FUNC_61(self): return self._blitzcon.getUser().omeName def FUNC_62(self): return self._blitzcon.getUser().firstName or self.getName() def FUNC_2(VAR_4): VAR_50 = [] VAR_51 = [] VAR_52 = [] for VAR_179 in VAR_4.split(","): VAR_179 = chan.split("|", 1) VAR_23 = VAR_179[0].strip() VAR_68 = None if VAR_23.find("$") >= 0: VAR_23, VAR_68 = VAR_23.split("$") try: VAR_50.append(int(VAR_23)) VAR_262 = (None, None) if len(VAR_179) > 1: VAR_23 = VAR_179[1].strip() if VAR_23.find("$") >= 0: VAR_23, VAR_68 = VAR_23.split("$", 1) VAR_23 = VAR_23.split(":") if len(VAR_23) == 2: try: VAR_262 = [float(VAR_30) for VAR_30 in VAR_23] except ValueError: pass VAR_51.append(VAR_262) VAR_52.append(VAR_68) except ValueError: pass VAR_1.debug(str(VAR_50) + "," + str(VAR_51) + "," + str(VAR_52)) return VAR_50, VAR_51, VAR_52 def FUNC_3(VAR_2, VAR_5=False): VAR_53 = VAR_2.GET VAR_54 = {} for VAR_263 in ("z", "t", "q", "m", "zm", "x", "y", "p"): if VAR_263 in VAR_53: VAR_54[VAR_263] = VAR_53[VAR_263] if "c" in VAR_53: VAR_54["c"] = [] VAR_180 = FUNC_2(VAR_53["c"]) VAR_1.debug(VAR_180) for VAR_212 in range(len(VAR_180[0])): VAR_54["c"].append( { "a": abs(VAR_180[0][VAR_212]), "i": VAR_180[0][VAR_212], "s": VAR_180[1][VAR_212][0], "e": VAR_180[1][VAR_212][1], "c": VAR_180[2][VAR_212], } ) if VAR_5: return "&".join(["%VAR_3=%s" % (VAR_30[0], VAR_30[1]) for VAR_30 in VAR_54.items()]) return VAR_54 @login_required() def FUNC_4(VAR_2, VAR_6, VAR_7=None, VAR_8=None, **VAR_9): return FUNC_6(VAR_2, VAR_6, VAR_10=VAR_7, **VAR_9) def FUNC_5(VAR_2, VAR_6, VAR_10=None, VAR_11=None, VAR_8=None, VAR_12=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_55 = VAR_2.session.get("server_settings", {}).get("browser", {}) VAR_56 = VAR_55.get("thumb_default_size", 96) VAR_57 = True if VAR_10 is None: VAR_7 = (VAR_56,) else: if VAR_11 is None: VAR_7 = (int(VAR_10),) else: VAR_7 = (int(VAR_10), int(VAR_11)) if VAR_7 == (VAR_56,): VAR_57 = False VAR_58 = VAR_8.getUserId() VAR_22 = getIntOrDefault(VAR_2, "z", None) VAR_23 = getIntOrDefault(VAR_2, "t", None) VAR_59 = getIntOrDefault(VAR_2, "rdefId", None) VAR_60 = webgateway_cache.getThumb(VAR_2, VAR_19, VAR_58, VAR_6, VAR_7) if VAR_60 is None: VAR_181 = False VAR_92 = VAR_8.getObject("Image", VAR_6) if VAR_92 is None: VAR_1.debug("(b)Image %VAR_3 not found..." % (str(VAR_6))) if VAR_12: VAR_60 = VAR_12(VAR_7=size) VAR_181 = True else: raise Http404("Failed to render thumbnail") else: VAR_60 = VAR_92.getThumbnail( VAR_7=size, VAR_57=direct, VAR_59=rdefId, VAR_22=z, VAR_23=t ) if VAR_60 is None: VAR_1.debug("(VAR_203)Image %VAR_3 not found..." % (str(VAR_6))) if VAR_12: VAR_60 = VAR_12(VAR_7=size) VAR_181 = True else: raise Http404("Failed to render thumbnail") else: VAR_181 = VAR_92._thumbInProgress if not VAR_181: webgateway_cache.setThumb(VAR_2, VAR_19, VAR_58, VAR_6, VAR_60, VAR_7) else: pass return VAR_60 @login_required() def FUNC_6(VAR_2, VAR_6, VAR_10=None, VAR_11=None, VAR_8=None, VAR_12=None, **VAR_9): VAR_60 = FUNC_5( VAR_2=request, VAR_6=iid, VAR_10=w, VAR_11=h, VAR_8=conn, VAR_12=_defcb, **VAR_9 ) VAR_61 = HttpResponse(VAR_60, content_type="image/jpeg") return VAR_61 @login_required() def FUNC_7(VAR_2, VAR_13, VAR_10=None, VAR_11=None, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_62 = VAR_8.getRoiService().findByRoi(VAR_178(VAR_13), None, VAR_8.SERVICE_OPTS) if VAR_62 is None or VAR_62.rois is None or len(VAR_62.rois) == 0: raise Http404 for VAR_241 in VAR_62.rois: VAR_36 = VAR_241.image.id.val VAR_63 = VAR_241.copyShapes() VAR_63 = [VAR_3 for VAR_3 in VAR_63 if VAR_3 is not None] if len(VAR_63) == 0: raise Http404("No Shapes found for ROI %s" % VAR_13) VAR_64 = FUNC_13(VAR_2, VAR_36, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_15, VAR_16 = VAR_64 VAR_65 = None if len(VAR_63) == 1: VAR_65 = VAR_63[0] else: VAR_182 = VAR_15.getDefaultT() VAR_183 = VAR_15.getDefaultZ() VAR_184 = [ VAR_3 for VAR_3 in VAR_63 if unwrap(VAR_3.getTheT()) is None or unwrap(VAR_3.getTheT()) == VAR_182 ] if len(VAR_184) == 1: VAR_65 = VAR_184[0] else: VAR_184 = [ VAR_3 for VAR_3 in VAR_184 if unwrap(VAR_3.getTheZ()) is None or unwrap(VAR_3.getTheZ()) == VAR_183 ] if len(VAR_184) > 0: VAR_65 = VAR_184[0] if VAR_65 is None and len(VAR_63) > 0: VAR_65 = VAR_63[0] return FUNC_9(VAR_2, VAR_8, VAR_15, VAR_65, VAR_16) @login_required() def FUNC_8(VAR_2, VAR_14, VAR_10=None, VAR_11=None, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_66 = omero.sys.Parameters() VAR_66.map = {"id": rlong(VAR_14)} VAR_65 = VAR_8.getQueryService().findByQuery( "select VAR_3 from Shape VAR_3 join fetch VAR_3.roi where VAR_3.id = :id", VAR_66, VAR_8.SERVICE_OPTS, ) if VAR_65 is None: raise Http404 VAR_36 = VAR_65.roi.image.id.val VAR_64 = FUNC_13(VAR_2, VAR_36, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_15, VAR_16 = VAR_64 return FUNC_9(VAR_2, VAR_8, VAR_15, VAR_65, VAR_16) def FUNC_9(VAR_2, VAR_8, VAR_15, VAR_3, VAR_16): VAR_67 = 250 VAR_68 = VAR_2.GET.get("color", "fff") VAR_69 = { "f00": (255, 0, 0), "0f0": (0, 255, 0), "00f": (0, 0, 255), "ff0": (255, 255, 0), "fff": (255, 255, 255), "000": (0, 0, 0), } VAR_70 = VAR_69["f00"] if VAR_68 in VAR_69: VAR_70 = VAR_69[VAR_68] VAR_71 = (221, 221, 221) VAR_72 = None # bounding box: (VAR_30, VAR_29, VAR_10, VAR_11) VAR_65 = {} VAR_73 = unwrap(VAR_3.getTheT()) VAR_73 = VAR_73 if VAR_73 is not None else VAR_15.getDefaultT() VAR_74 = unwrap(VAR_3.getTheZ()) VAR_74 = VAR_74 if VAR_74 is not None else VAR_15.getDefaultZ() if type(VAR_3) == omero.model.RectangleI: VAR_65["type"] = "Rectangle" VAR_65["x"] = VAR_3.getX().getValue() VAR_65["y"] = VAR_3.getY().getValue() VAR_65["width"] = VAR_3.getWidth().getValue() VAR_65["height"] = VAR_3.getHeight().getValue() VAR_72 = (VAR_65["x"], VAR_65["y"], VAR_65["width"], VAR_65["height"]) elif type(VAR_3) == omero.model.MaskI: VAR_65["type"] = "Mask" VAR_65["x"] = VAR_3.getX().getValue() VAR_65["y"] = VAR_3.getY().getValue() VAR_65["width"] = VAR_3.getWidth().getValue() VAR_65["height"] = VAR_3.getHeight().getValue() VAR_72 = (VAR_65["x"], VAR_65["y"], VAR_65["width"], VAR_65["height"]) elif type(VAR_3) == omero.model.EllipseI: VAR_65["type"] = "Ellipse" VAR_65["x"] = int(VAR_3.getX().getValue()) VAR_65["y"] = int(VAR_3.getY().getValue()) VAR_65["radiusX"] = int(VAR_3.getRadiusX().getValue()) VAR_65["radiusY"] = int(VAR_3.getRadiusY().getValue()) VAR_72 = ( VAR_65["x"] - VAR_65["radiusX"], VAR_65["y"] - VAR_65["radiusY"], 2 * VAR_65["radiusX"], 2 * VAR_65["radiusY"], ) elif type(VAR_3) == omero.model.PolylineI: VAR_65["type"] = "PolyLine" VAR_65["xyList"] = points_string_to_XY_list(VAR_3.getPoints().getValue()) VAR_72 = xy_list_to_bbox(VAR_65["xyList"]) elif type(VAR_3) == omero.model.LineI: VAR_65["type"] = "Line" VAR_65["x1"] = int(VAR_3.getX1().getValue()) VAR_65["x2"] = int(VAR_3.getX2().getValue()) VAR_65["y1"] = int(VAR_3.getY1().getValue()) VAR_65["y2"] = int(VAR_3.getY2().getValue()) VAR_30 = min(VAR_65["x1"], VAR_65["x2"]) VAR_29 = min(VAR_65["y1"], VAR_65["y2"]) VAR_72 = ( VAR_30, VAR_29, max(VAR_65["x1"], VAR_65["x2"]) - VAR_30, max(VAR_65["y1"], VAR_65["y2"]) - VAR_29, ) elif type(VAR_3) == omero.model.PointI: VAR_65["type"] = "Point" VAR_65["x"] = VAR_3.getX().getValue() VAR_65["y"] = VAR_3.getY().getValue() VAR_72 = (VAR_65["x"] - 50, VAR_65["y"] - 50, 100, 100) elif type(VAR_3) == omero.model.PolygonI: VAR_65["type"] = "Polygon" VAR_65["xyList"] = points_string_to_XY_list(VAR_3.getPoints().getValue()) VAR_72 = xy_list_to_bbox(VAR_65["xyList"]) elif type(VAR_3) == omero.model.LabelI: VAR_65["type"] = "Label" VAR_65["x"] = VAR_3.getX().getValue() VAR_65["y"] = VAR_3.getY().getValue() VAR_72 = (VAR_65["x"] - 50, VAR_65["y"] - 50, 100, 100) else: VAR_1.debug("Shape type not supported: %s" % str(type(VAR_3))) VAR_30, VAR_29, VAR_10, VAR_11 = VAR_72 VAR_75 = max(VAR_10, VAR_11 * 3 // 2) VAR_76 = VAR_75 * 2 // 3 VAR_77 = int(VAR_75 * 1.5) VAR_78 = int(VAR_76 * 1.5) if VAR_77 < VAR_67: VAR_77 = VAR_67 VAR_78 = VAR_77 * 2 // 3 def FUNC_63(VAR_79): try: return VAR_8.getConfigService().getConfigValue(VAR_79) except Exception: VAR_1.warn( "webgateway: FUNC_9() could not get" " Config-Value for %s" % VAR_79 ) pass VAR_80 = FUNC_63("omero.pixeldata.max_plane_width") VAR_81 = FUNC_63("omero.pixeldata.max_plane_height") if ( VAR_80 is None or VAR_81 is None or (VAR_77 > int(VAR_80)) or (VAR_78 > int(VAR_81)) ): VAR_185 = Image.new("RGB", (VAR_67, MAX_WIDTH * 2 // 3), VAR_71) VAR_97 = ImageDraw.Draw(VAR_185) VAR_97.text((10, 30), "Shape too large to \ngenerate thumbnail", VAR_101=(255, 0, 0)) VAR_54 = BytesIO() VAR_185.save(VAR_54, "jpeg", quality=90) return HttpResponse(VAR_54.getvalue(), content_type="image/jpeg") VAR_82 = (VAR_77 - VAR_10) // 2 VAR_83 = (VAR_78 - VAR_11) // 2 VAR_84 = int(VAR_30 - VAR_82) VAR_85 = int(VAR_29 - VAR_83) VAR_86 = VAR_15.getSizeX() VAR_87 = VAR_15.getSizeY() VAR_88, VAR_89, VAR_90, VAR_91 = 0, 0, 0, 0 if VAR_84 < 0: VAR_77 = VAR_77 + VAR_84 VAR_88 = abs(VAR_84) newX = 0 if VAR_85 < 0: VAR_78 = VAR_78 + VAR_85 VAR_90 = abs(VAR_85) newY = 0 if VAR_77 + VAR_84 > VAR_86: VAR_89 = (VAR_77 + VAR_84) - VAR_86 VAR_77 = newW - VAR_89 if VAR_78 + VAR_85 > VAR_87: VAR_91 = (VAR_78 + VAR_85) - VAR_87 VAR_78 = newH - VAR_91 VAR_60 = VAR_15.renderJpegRegion( VAR_74, VAR_73, VAR_84, VAR_85, VAR_77, VAR_78, VAR_113=None, VAR_98=VAR_16 ) VAR_92 = Image.open(BytesIO(VAR_60)) if VAR_88 != 0 or VAR_89 != 0 or VAR_90 != 0 or VAR_91 != 0: VAR_186, VAR_187 = VAR_92.size VAR_188 = VAR_186 + VAR_89 + VAR_88 VAR_189 = VAR_187 + VAR_91 + VAR_90 VAR_190 = Image.new("RGB", (VAR_188, VAR_189), VAR_71) VAR_190.paste(VAR_92, (VAR_88, VAR_90)) VAR_92 = VAR_190 VAR_93, VAR_94 = VAR_92.size VAR_95 = float(VAR_67) / VAR_93 VAR_96 = int(VAR_94 * VAR_95) VAR_92 = VAR_92.resize((VAR_67, VAR_96)) VAR_97 = ImageDraw.Draw(VAR_92) if VAR_65["type"] == "Rectangle": VAR_191 = int(VAR_82 * VAR_95) VAR_192 = int(VAR_83 * VAR_95) VAR_193 = int((VAR_10 + VAR_82) * VAR_95) VAR_194 = int((VAR_11 + VAR_83) * VAR_95) VAR_97.rectangle((VAR_191, VAR_192, VAR_193, VAR_194), outline=VAR_70) VAR_97.rectangle((VAR_191 - 1, VAR_192 - 1, VAR_193 + 1, VAR_194 + 1), outline=VAR_70) elif VAR_65["type"] == "Line": VAR_264 = (VAR_65["x1"] - VAR_84 + VAR_88) * VAR_95 VAR_265 = (VAR_65["x2"] - VAR_84 + VAR_88) * VAR_95 VAR_266 = (VAR_65["y1"] - VAR_85 + VAR_90) * VAR_95 VAR_267 = (VAR_65["y2"] - VAR_85 + VAR_90) * VAR_95 VAR_97.line((VAR_264, VAR_266, VAR_265, VAR_267), VAR_101=VAR_70, VAR_99=2) elif VAR_65["type"] == "Ellipse": VAR_191 = int(VAR_82 * VAR_95) VAR_192 = int(VAR_83 * VAR_95) VAR_193 = int((VAR_10 + VAR_82) * VAR_95) VAR_194 = int((VAR_11 + VAR_83) * VAR_95) VAR_97.ellipse((VAR_191, VAR_192, VAR_193, VAR_194), outline=VAR_70) VAR_97.ellipse((VAR_191 - 1, VAR_192 - 1, VAR_193 + 1, VAR_194 + 1), outline=VAR_70) elif VAR_65["type"] == "Point": VAR_323 = 2 VAR_191 = (VAR_67 // 2) - VAR_323 VAR_192 = int(VAR_96 // 2) - VAR_323 VAR_193 = VAR_191 + (VAR_323 * 2) VAR_194 = VAR_192 + (VAR_323 * 2) VAR_97.ellipse((VAR_191, VAR_192, VAR_193, VAR_194), outline=VAR_70) VAR_97.ellipse((VAR_191 - 1, VAR_192 - 1, VAR_193 + 1, VAR_194 + 1), outline=VAR_70) elif "xyList" in VAR_65: def FUNC_79(VAR_325): VAR_30, VAR_29 = VAR_325 return ( int((VAR_30 - VAR_84 + VAR_88) * VAR_95), int((VAR_29 - VAR_85 + VAR_90) * VAR_95), ) VAR_326 = [FUNC_79(VAR_325) for VAR_325 in VAR_65["xyList"]] VAR_327 = VAR_328 = None for line in range(1, len(VAR_326)): VAR_333, VAR_334 = VAR_326[line - 1] VAR_327, VAR_328 = VAR_326[line] VAR_97.line((VAR_333, VAR_334, VAR_327, VAR_328), VAR_101=VAR_70, VAR_99=2) VAR_329, VAR_330 = VAR_326[0] if VAR_65["type"] != "PolyLine": if VAR_327 is None: VAR_327 = VAR_329 + 1 # This will create VAR_167 visible dot if VAR_328 is None: VAR_328 = VAR_330 + 1 VAR_97.line((VAR_327, VAR_328, VAR_329, VAR_330), VAR_101=VAR_70, VAR_99=2) VAR_54 = BytesIO() VAR_98 = 0.9 try: VAR_92.save(VAR_54, "jpeg", quality=int(VAR_98 * 100)) VAR_195 = VAR_54.getvalue() finally: VAR_54.close() return HttpResponse(VAR_195, content_type="image/jpeg") @login_required() def FUNC_10(VAR_2, VAR_14, VAR_8=None, **VAR_9): if not VAR_48: raise NotImplementedError("numpy not installed") VAR_66 = omero.sys.Parameters() VAR_66.map = {"id": rlong(VAR_14)} VAR_65 = VAR_8.getQueryService().findByQuery( "select VAR_3 from Shape VAR_3 where VAR_3.id = :id", VAR_66, VAR_8.SERVICE_OPTS ) if VAR_65 is None: raise Http404("Shape ID: %VAR_3 not found" % VAR_14) VAR_99 = int(VAR_65.getWidth().getValue()) VAR_100 = int(VAR_65.getHeight().getValue()) VAR_68 = unwrap(VAR_65.getFillColor()) VAR_101 = (255, 255, 0, 255) if VAR_68 is not None: VAR_68 = rgb_int2rgba(VAR_68) VAR_101 = (VAR_68[0], VAR_68[1], VAR_68[2], int(VAR_68[3] * 255)) VAR_102 = VAR_65.getBytes() VAR_103 = numpy.fromstring(VAR_102, dtype=numpy.uint8) VAR_104 = numpy.unpackbits(VAR_103) VAR_92 = Image.new("RGBA", VAR_7=(VAR_99, VAR_100), VAR_68=(0, 0, 0, 0)) VAR_30 = 0 VAR_29 = 0 for pix in VAR_104: if pix == 1: VAR_92.putpixel((VAR_30, VAR_29), VAR_101) VAR_30 += 1 if VAR_30 > VAR_99 - 1: VAR_30 = 0 VAR_29 += 1 VAR_54 = BytesIO() VAR_92.save(VAR_54, "png", quality=int(100)) VAR_105 = VAR_54.getvalue() return HttpResponse(VAR_105, content_type="image/png") def FUNC_11(VAR_2): VAR_53 = VAR_2.GET VAR_54 = VAR_53.get("m", "_") + VAR_53.get("p", "_") + VAR_53.get("c", "_") + VAR_53.get("q", "_") return VAR_54 def FUNC_12(VAR_2, VAR_17, VAR_18=0): VAR_106 = None if "maps" in VAR_2: VAR_196 = VAR_2["maps"] VAR_106 = [] try: if isinstance(VAR_196, (unicode, str)): VAR_196 = json.loads(VAR_196) VAR_18 = max(len(VAR_196), VAR_18) for VAR_203 in range(VAR_18): VAR_308 = None if len(VAR_196) > VAR_203: VAR_282 = VAR_196[VAR_203].get(VAR_17) if VAR_282 is not None: VAR_308 = VAR_282.get("enabled") in (True, "true") VAR_106.append(VAR_308) except Exception: VAR_1.debug("Invalid json for VAR_43 ?VAR_223=%s" % VAR_196) VAR_106 = None return VAR_106 def FUNC_13( VAR_2, VAR_6, VAR_19=None, VAR_8=None, VAR_20=False, VAR_21=True ): VAR_53 = VAR_2.GET VAR_1.debug( "Preparing Image:%VAR_53 VAR_20=%VAR_53 " "retry=%VAR_53 VAR_2=%VAR_53 VAR_8=%s" % (VAR_6, VAR_20, VAR_21, VAR_53, str(VAR_8)) ) VAR_92 = VAR_8.getObject("Image", VAR_6) if VAR_92 is None: return VAR_107 = None if "maps" in VAR_53: VAR_197 = FUNC_12(VAR_53, "reverse", VAR_92.getSizeC()) VAR_107 = FUNC_12(VAR_53, "inverted", VAR_92.getSizeC()) if VAR_197 is not None and VAR_107 is not None: VAR_107 = [ VAR_22[0] if VAR_22[0] is not None else VAR_22[1] for VAR_22 in zip(VAR_107, VAR_197) ] try: VAR_268 = [VAR_282.get("quantization") for VAR_282 in json.loads(VAR_53["maps"])] VAR_92.setQuantizationMaps(VAR_268) except Exception: VAR_1.debug("Failed to set quantization maps") if "c" in VAR_53: VAR_1.debug("c=" + VAR_53["c"]) VAR_198, VAR_51, VAR_52 = FUNC_2(VAR_53["c"]) VAR_199 = range(1, VAR_92.getSizeC() + 1) if VAR_20 and not VAR_92.setActiveChannels( VAR_199, VAR_51, VAR_52, VAR_107 ): VAR_1.debug("Something bad happened while setting the active VAR_50...") if not VAR_92.setActiveChannels(VAR_198, VAR_51, VAR_52, VAR_107): VAR_1.debug("Something bad happened while setting the active VAR_50...") if VAR_53.get("m", None) == "g": VAR_92.setGreyscaleRenderingModel() elif VAR_53.get("m", None) == "c": VAR_92.setColorRenderingModel() VAR_108 = VAR_53.get("p", None) VAR_109, VAR_110 = None, None if VAR_108 is not None and len(VAR_108.split("|")) > 1: VAR_108, VAR_200 = VAR_108.split("|", 1) try: VAR_109, VAR_110 = [int(VAR_3) for VAR_3 in VAR_200.split(":")] except ValueError: pass VAR_92.setProjection(VAR_108) VAR_92.setProjectionRange(VAR_109, VAR_110) VAR_92.setInvertedAxis(bool(VAR_53.get("ia", "0") == "1")) VAR_16 = VAR_53.get("q", None) if VAR_20: "z" in VAR_53 and VAR_92.setDefaultZ(VAR_178(VAR_53["z"]) - 1) "t" in VAR_53 and VAR_92.setDefaultT(VAR_178(VAR_53["t"]) - 1) VAR_92.saveDefaults() return (VAR_92, VAR_16) @login_required() def FUNC_14(VAR_2, VAR_6, VAR_22, VAR_23, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_111 = VAR_2.GET.get("tile", None) VAR_112 = VAR_2.GET.get("region", None) VAR_113 = None if VAR_111: try: VAR_92._prepareRenderingEngine() VAR_10, VAR_11 = VAR_92._re.getTileSize() VAR_269 = VAR_92._re.getResolutionLevels() - 1 VAR_270 = VAR_111.split(",") if len(VAR_270) > 4: VAR_309 = [int(VAR_270[3]), int(VAR_270[4])] VAR_310 = [VAR_10, VAR_11] VAR_311 = 1024 try: VAR_311 = int( VAR_8.getConfigService().getConfigValue( "omero.pixeldata.max_tile_length" ) ) except Exception: pass for VAR_212, tile_length in enumerate(VAR_309): if tile_length <= 0: VAR_309[VAR_212] = VAR_310[VAR_212] if tile_length > VAR_311: VAR_309[VAR_212] = VAR_311 VAR_10, VAR_11 = VAR_309 VAR_271 = int(VAR_270[0]) if VAR_271 < 0: VAR_231 = "Invalid resolution VAR_113 %VAR_3 < 0" % VAR_271 VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) if VAR_269 == 0: # non pyramid file if VAR_271 > 0: VAR_231 = "Invalid resolution VAR_113 %VAR_3, non pyramid file" % VAR_271 VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) else: VAR_113 = None else: VAR_113 = VAR_269 - VAR_271 if VAR_113 < 0: VAR_231 = ( "Invalid resolution VAR_113, \ %VAR_3 > number of available VAR_269 %VAR_3 " % (VAR_271, VAR_269) ) VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) VAR_30 = int(VAR_270[1]) * VAR_10 VAR_29 = int(VAR_270[2]) * VAR_11 except Exception: VAR_231 = "malformed VAR_111 argument, VAR_111=%s" % VAR_111 VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) elif VAR_112: try: VAR_312 = VAR_112.split(",") VAR_30 = int(VAR_312[0]) VAR_29 = int(VAR_312[1]) VAR_10 = int(VAR_312[2]) VAR_11 = int(VAR_312[3]) except Exception: VAR_231 = "malformed VAR_112 argument, VAR_112=%s" % VAR_112 VAR_1.debug(VAR_231, exc_info=True) return HttpResponseBadRequest(VAR_231) else: return HttpResponseBadRequest("tile or VAR_112 argument required") VAR_60 = webgateway_cache.getImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23) if VAR_60 is None: VAR_60 = VAR_92.renderJpegRegion( VAR_22, VAR_23, VAR_30, VAR_29, VAR_10, VAR_11, VAR_113=level, VAR_98=VAR_16 ) if VAR_60 is None: raise Http404 webgateway_cache.setImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23, VAR_60) VAR_61 = HttpResponse(VAR_60, content_type="image/jpeg") return VAR_61 @login_required() def FUNC_15(VAR_2, VAR_6, VAR_22=None, VAR_23=None, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_60 = webgateway_cache.getImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23) if VAR_60 is None: VAR_60 = VAR_92.renderJpeg(VAR_22, VAR_23, VAR_98=VAR_16) if VAR_60 is None: raise Http404 webgateway_cache.setImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23, VAR_60) VAR_114 = VAR_2.GET.get("format", "jpeg") VAR_61 = HttpResponse(VAR_60, content_type="image/jpeg") if "download" in VAR_9 and VAR_9["download"]: if VAR_114 == "png": VAR_212 = Image.open(BytesIO(VAR_60)) VAR_272 = BytesIO() VAR_212.save(VAR_272, "png") VAR_60 = VAR_272.getvalue() VAR_272.close() VAR_61 = HttpResponse(VAR_60, content_type="image/png") elif VAR_114 == "tif": VAR_212 = Image.open(BytesIO(VAR_60)) VAR_272 = BytesIO() VAR_212.save(VAR_272, "tiff") VAR_60 = VAR_272.getvalue() VAR_272.close() VAR_61 = HttpResponse(VAR_60, content_type="image/tiff") VAR_201 = VAR_92.getName() try: VAR_201 = fileName.decode("utf8") except AttributeError: pass # python 3 VAR_201 = fileName.replace(",", ".").replace(" ", "_") VAR_61["Content-Type"] = "application/force-download" VAR_61["Content-Length"] = len(VAR_60) VAR_61["Content-Disposition"] = "attachment; filename=%VAR_3.%s" % (VAR_201, VAR_114) return VAR_61 @login_required() def FUNC_16(VAR_2, VAR_24, VAR_25, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_115 = [] if VAR_24 == "p": VAR_202 = VAR_8.getObject("Project", VAR_25) if VAR_202 is None: raise Http404 for VAR_213 in VAR_202.listChildren(): VAR_115.extend(list(VAR_213.listChildren())) VAR_17 = VAR_202.getName() elif VAR_24 == "d": VAR_202 = VAR_8.getObject("Dataset", VAR_25) if VAR_202 is None: raise Http404 VAR_115.extend(list(VAR_202.listChildren())) VAR_273 = list(filter(None, VAR_2.GET.get("selection", "").split(","))) if len(VAR_273) > 0: VAR_1.debug(VAR_273) VAR_1.debug(VAR_115) VAR_115 = [VAR_30 for VAR_30 in VAR_115 if str(VAR_30.getId()) in VAR_273] VAR_1.debug(VAR_115) if len(VAR_115) == 0: raise Http404 VAR_17 = "%VAR_3-%s" % (VAR_202.getParent().getName(), VAR_202.getName()) elif VAR_24 == "w": VAR_202 = VAR_8.getObject("Well", VAR_25) if VAR_202 is None: raise Http404 VAR_115.extend([VAR_30.getImage() for VAR_30 in VAR_202.listChildren()]) VAR_124 = VAR_202.getParent() VAR_313 = "%VAR_3%s" % ( VAR_124.getRowLabels()[VAR_202.row], VAR_124.getColumnLabels()[VAR_202.column], ) VAR_17 = "%VAR_3-%VAR_3-%s" % (VAR_124.getParent().getName(), VAR_124.getName(), VAR_313) else: VAR_202 = VAR_8.getObject("Image", VAR_25) if VAR_202 is None: raise Http404 VAR_115.append(VAR_202) VAR_115 = [VAR_30 for VAR_30 in VAR_115 if not VAR_30.requiresPixelsPyramid()] if VAR_2.GET.get("dryrun", False): VAR_54 = json.dumps(len(VAR_115)) VAR_203 = VAR_2.GET.get("callback", None) if VAR_203 is not None and not VAR_9.get("_internal", False): VAR_54 = "%VAR_3(%VAR_3)" % (VAR_203, VAR_54) return HttpJavascriptResponse(VAR_54) if len(VAR_115) == 0: raise Http404 if len(VAR_115) == 1: VAR_202 = VAR_115[0] VAR_79 = ( "_".join((str(VAR_30.getId()) for VAR_30 in VAR_202.getAncestry())) + "_" + str(VAR_202.getId()) + "_ome_tiff" ) VAR_204 = 255 - len(str(VAR_202.getId())) - 10 VAR_205 = VAR_202.getName()[:VAR_204] VAR_206, VAR_207, VAR_208 = webgateway_tempfile.new( str(VAR_202.getId()) + "-" + VAR_205 + ".ome.tiff", VAR_79=key ) if VAR_208 is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) VAR_209 = webgateway_cache.getOmeTiffImage(VAR_2, VAR_19, VAR_115[0]) if VAR_209 is None: try: VAR_209 = VAR_115[0].exportOmeTiff() except Exception: VAR_1.debug("Failed to export VAR_15 (2)", exc_info=True) VAR_209 = None if VAR_209 is None: webgateway_tempfile.abort(VAR_206) raise Http404 webgateway_cache.setOmeTiffImage(VAR_2, VAR_19, VAR_115[0], VAR_209) if VAR_208 is None: VAR_61 = HttpResponse(VAR_209, content_type="image/tiff") VAR_61["Content-Disposition"] = 'attachment; filename="%VAR_3.ome.tiff"' % ( str(VAR_202.getId()) + "-" + VAR_205 ) VAR_61["Content-Length"] = len(VAR_209) return VAR_61 else: VAR_208.write(VAR_209) VAR_208.close() return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) else: try: VAR_274 = "+".join((str(VAR_30.getId()) for VAR_30 in VAR_115)).encode("utf-8") VAR_79 = ( "_".join((str(VAR_30.getId()) for VAR_30 in VAR_115[0].getAncestry())) + "_" + md5(VAR_274).hexdigest() + "_ome_tiff_zip" ) VAR_206, VAR_207, VAR_208 = webgateway_tempfile.new(VAR_17 + ".zip", VAR_79=key) if VAR_208 is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) VAR_1.debug(VAR_206) if VAR_208 is None: VAR_208 = BytesIO() VAR_275 = zipfile.ZipFile(VAR_208, "w", zipfile.ZIP_STORED) for VAR_202 in VAR_115: VAR_209 = webgateway_cache.getOmeTiffImage(VAR_2, VAR_19, VAR_202) if VAR_209 is None: VAR_209 = VAR_202.exportOmeTiff() if VAR_209 is None: continue webgateway_cache.setOmeTiffImage(VAR_2, VAR_19, VAR_202, VAR_209) VAR_204 = 255 - len(str(VAR_202.getId())) - 10 VAR_205 = VAR_202.getName()[:VAR_204] VAR_275.writestr(str(VAR_202.getId()) + "-" + VAR_205 + ".ome.tiff", VAR_209) VAR_275.close() if VAR_206 is None: VAR_314 = VAR_208.getvalue() VAR_61 = HttpResponse(VAR_314, content_type="application/zip") VAR_61["Content-Disposition"] = 'attachment; filename="%VAR_3.zip"' % VAR_17 VAR_61["Content-Length"] = len(VAR_314) return VAR_61 except Exception: VAR_1.debug(traceback.format_exc()) raise return HttpResponseRedirect(settings.STATIC_URL + "webgateway/tfiles/" + VAR_207) @login_required() def FUNC_17(VAR_2, VAR_6, VAR_26, VAR_27, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id try: VAR_136 = {} VAR_136["format"] = "video/" + VAR_2.GET.get("format", "quicktime") VAR_136["fps"] = int(VAR_2.GET.get("fps", 4)) VAR_136["minsize"] = (512, 512, "Black") VAR_210 = ".avi" VAR_79 = "%VAR_3-%VAR_3-%VAR_3-%VAR_213-%VAR_3-%s" % ( VAR_6, VAR_26, VAR_27, VAR_136["fps"], FUNC_11(VAR_2), VAR_2.GET.get("format", "quicktime"), ) VAR_27 = int(VAR_27) VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_206, VAR_207, VAR_208 = webgateway_tempfile.new(VAR_92.getName() + VAR_210, VAR_79=key) VAR_1.debug(VAR_206, VAR_207, VAR_208) if VAR_208 is True: return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) if "optsCB" in VAR_9: VAR_136.update(VAR_9["optsCB"](VAR_92)) VAR_136.update(VAR_9.get("opts", {})) VAR_1.debug( "rendering VAR_280 for VAR_92 %VAR_3 with VAR_26 %VAR_3, VAR_27 %VAR_212 and VAR_136 %s" % (VAR_6, VAR_26, VAR_27, VAR_136) ) if VAR_206 is None: VAR_276, VAR_277 = tempfile.mkstemp() else: VAR_277 = VAR_206 # os.path.join(VAR_206, VAR_92.getName()) if VAR_26.lower() == "z": VAR_278, VAR_279 = VAR_92.createMovie( VAR_277, 0, VAR_92.getSizeZ() - 1, VAR_27 - 1, VAR_27 - 1, VAR_136 ) else: VAR_278, VAR_279 = VAR_92.createMovie( VAR_277, VAR_27 - 1, VAR_27 - 1, 0, VAR_92.getSizeT() - 1, VAR_136 ) if VAR_278 is None and VAR_279 is None: raise Http404 if VAR_206 is None: VAR_280 = open(VAR_277).read() os.close(VAR_276) VAR_61 = HttpResponse(VAR_280, content_type=VAR_279) VAR_61["Content-Disposition"] = 'attachment; filename="%s"' % ( VAR_92.getName() + VAR_210 ) VAR_61["Content-Length"] = len(VAR_280) return VAR_61 else: VAR_208.close() return HttpResponseRedirect( settings.STATIC_URL + "webgateway/tfiles/" + VAR_207 ) except Exception: VAR_1.debug(traceback.format_exc()) raise @login_required() def FUNC_18(VAR_2, VAR_6, VAR_22, VAR_23, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_16 = compress_quality and float(VAR_16) or 0.9 VAR_60 = webgateway_cache.getSplitChannelImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23) if VAR_60 is None: VAR_60 = VAR_92.renderSplitChannel(VAR_22, VAR_23, VAR_98=VAR_16) if VAR_60 is None: raise Http404 webgateway_cache.setSplitChannelImage(VAR_2, VAR_19, VAR_92, VAR_22, VAR_23, VAR_60) VAR_61 = HttpResponse(VAR_60, content_type="image/jpeg") return VAR_61 def VAR_211(VAR_28): @wraps(VAR_28) def FUNC_64(VAR_2, *VAR_116, **VAR_9): VAR_211 = VAR_2.GET.getlist("debug") if "slow" in VAR_211: time.sleep(5) if "fail" in VAR_211: raise Http404 if "error" in VAR_211: raise AttributeError("Debug requested error") return VAR_28(VAR_2, *VAR_116, **VAR_9) return FUNC_64 def FUNC_20(VAR_28): @wraps(VAR_28) def FUNC_64(VAR_2, *VAR_116, **VAR_9): VAR_1.debug("jsonp") try: VAR_19 = VAR_9.get("server_id", None) if VAR_19 is None and VAR_2.session.get("connector"): VAR_19 = VAR_2.session["connector"].server_id VAR_9["server_id"] = VAR_19 VAR_54 = VAR_28(VAR_2, *VAR_116, **VAR_9) if VAR_9.get("_raw", False): return VAR_54 if isinstance(VAR_54, HttpResponse): return VAR_54 VAR_203 = VAR_2.GET.get("callback", None) if VAR_203 is not None and not VAR_9.get("_internal", False): VAR_54 = json.dumps(VAR_54) VAR_54 = "%VAR_3(%VAR_3)" % (VAR_203, VAR_54) return HttpJavascriptResponse(VAR_54) if VAR_9.get("_internal", False): return VAR_54 VAR_281 = type(VAR_54) is dict return JsonResponse(VAR_54, VAR_281=safe) except Exception as ex: VAR_315 = 500 if isinstance(ex, omero.SecurityViolation): VAR_315 = 403 elif isinstance(ex, omero.ApiUsageException): VAR_315 = 400 VAR_316 = traceback.format_exc() VAR_1.debug(VAR_316) if VAR_9.get("_raw", False) or VAR_9.get("_internal", False): raise return JsonResponse( {"message": str(ex), "stacktrace": VAR_316}, VAR_315=status ) return FUNC_64 @VAR_211 @login_required() def FUNC_21(VAR_2, VAR_6, VAR_22, VAR_23, VAR_29, VAR_8=None, VAR_10=1, **VAR_9): if not VAR_10: VAR_10 = 1 VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 try: VAR_117 = VAR_92.renderRowLinePlotGif(int(VAR_22), int(VAR_23), int(VAR_29), int(VAR_10)) except Exception: VAR_1.debug("a", exc_info=True) raise if VAR_117 is None: raise Http404 VAR_61 = HttpResponse(VAR_117, content_type="image/gif") return VAR_61 @VAR_211 @login_required() def FUNC_22(VAR_2, VAR_6, VAR_22, VAR_23, VAR_30, VAR_10=1, VAR_8=None, **VAR_9): if not VAR_10: VAR_10 = 1 VAR_64 = FUNC_13(VAR_2, VAR_6, VAR_8=conn) if VAR_64 is None: raise Http404 VAR_92, VAR_16 = VAR_64 VAR_117 = VAR_92.renderColLinePlotGif(int(VAR_22), int(VAR_23), int(VAR_30), int(VAR_10)) if VAR_117 is None: raise Http404 VAR_61 = HttpResponse(VAR_117, content_type="image/gif") return VAR_61 @login_required() @FUNC_20 def FUNC_23(VAR_2, VAR_8=None, VAR_31=False, **VAR_9): VAR_6 = VAR_9["iid"] VAR_79 = VAR_9.get("key", None) VAR_15 = VAR_8.getObject("Image", VAR_6) if VAR_15 is None: if is_public_user(VAR_2): return HttpResponseForbidden() else: return HttpResponseNotFound("Image:%VAR_3 not found" % VAR_6) if VAR_2.GET.get("getDefaults") == "true": VAR_15.resetDefaults(save=False) VAR_54 = imageMarshal(VAR_15, VAR_79=key, VAR_2=request) return VAR_54 @login_required() @FUNC_20 def FUNC_24(VAR_2, VAR_8=None, VAR_31=False, **VAR_9): VAR_118 = VAR_9["wid"] VAR_119 = VAR_8.getObject("Well", VAR_118) if VAR_119 is None: return HttpJavascriptResponseServerError('""') VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") def FUNC_65(VAR_6): return reverse(VAR_120, VAR_116=(VAR_6,)) VAR_121 = {"thumbUrlPrefix": VAR_9.get("urlprefix", FUNC_65)} VAR_54 = VAR_119.simpleMarshal(VAR_121=xtra) return VAR_54 @login_required() @FUNC_20 def FUNC_25(VAR_2, VAR_32, VAR_33=0, VAR_8=None, **VAR_9): try: VAR_33 = VAR_178(VAR_33 or 0) except ValueError: VAR_33 = 0 VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") VAR_122 = getIntOrDefault(VAR_2, "size", None) VAR_1.debug(VAR_122) VAR_19 = VAR_9["server_id"] def FUNC_66(VAR_6): if VAR_122 is not None: return reverse(VAR_120, VAR_116=(VAR_6, VAR_122)) return reverse(VAR_120, VAR_116=(VAR_6,)) VAR_123 = PlateGrid(VAR_8, VAR_32, VAR_33, VAR_9.get("urlprefix", FUNC_66)) VAR_124 = VAR_123.plate if VAR_124 is None: return Http404 VAR_125 = "plategrid-%VAR_213-%s" % (VAR_33, VAR_122) VAR_54 = webgateway_cache.getJson(VAR_2, VAR_19, VAR_124, VAR_125) if VAR_54 is None: VAR_54 = VAR_123.metadata webgateway_cache.setJson(VAR_2, VAR_19, VAR_124, json.dumps(VAR_54), VAR_125) else: VAR_54 = json.loads(VAR_54) return VAR_54 @login_required() @FUNC_20 def FUNC_26(VAR_2, VAR_10=None, VAR_8=None, **VAR_9): VAR_55 = VAR_2.session.get("server_settings", {}).get("browser", {}) VAR_56 = VAR_55.get("thumb_default_size", 96) if VAR_10 is None: VAR_10 = VAR_56 VAR_126 = get_longs(VAR_2, "id") VAR_126 = list(set(VAR_126)) # remove any duplicates if len(VAR_126) == 1: VAR_6 = VAR_126[0] try: VAR_162 = FUNC_5(VAR_2, VAR_6, VAR_10=w, VAR_8=conn) return { VAR_6: "data:VAR_15/VAR_195;base64,%s" % base64.b64encode(VAR_162).decode("utf-8") } except Exception: return {VAR_6: None} VAR_1.debug("Image ids: %r" % VAR_126) if len(VAR_126) > settings.THUMBNAILS_BATCH: return HttpJavascriptResponseServerError( "Max %VAR_3 VAR_127 at VAR_167 time." % settings.THUMBNAILS_BATCH ) VAR_127 = VAR_8.getThumbnailSet([rlong(VAR_212) for VAR_212 in VAR_126], VAR_10) VAR_54 = dict() for VAR_212 in VAR_126: VAR_54[VAR_212] = None try: VAR_23 = VAR_127[VAR_212] if len(VAR_23) > 0: VAR_54[VAR_212] = "data:VAR_15/VAR_195;base64,%s" % base64.b64encode(VAR_23).decode( "utf-8" ) except KeyError: VAR_1.error("Thumbnail not available. (VAR_92 id: %VAR_213)" % VAR_212) except Exception: VAR_1.error(traceback.format_exc()) return VAR_54 @login_required() @FUNC_20 def FUNC_27(VAR_2, VAR_6, VAR_10=None, VAR_11=None, VAR_8=None, VAR_12=None, **VAR_9): VAR_60 = FUNC_5( VAR_2=request, VAR_6=iid, VAR_10=w, VAR_11=h, VAR_8=conn, VAR_12=_defcb, **VAR_9 ) VAR_54 = "data:VAR_15/VAR_195;base64,%s" % base64.b64encode(VAR_60).decode("utf-8") return VAR_54 @login_required() @FUNC_20 def FUNC_28(VAR_2, VAR_34, VAR_8=None, **VAR_9): VAR_128 = VAR_8.getObject("Dataset", VAR_34) if VAR_128 is None: return HttpJavascriptResponseServerError('""') VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") def FUNC_65(VAR_6): return reverse(VAR_120, VAR_116=(VAR_6,)) VAR_121 = { "thumbUrlPrefix": VAR_9.get("urlprefix", FUNC_65), "tiled": VAR_2.GET.get("tiled", False), } return [VAR_30.simpleMarshal(VAR_121=xtra) for VAR_30 in VAR_128.listChildren()] @login_required() @FUNC_20 def FUNC_29(VAR_2, VAR_34, VAR_8=None, **VAR_9): VAR_119 = VAR_8.getObject("Well", VAR_34) VAR_129 = getIntOrDefault(VAR_2, "run", None) if VAR_119 is None: return HttpJavascriptResponseServerError('""') VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") def FUNC_65(VAR_6): return reverse(VAR_120, VAR_116=(VAR_6,)) VAR_121 = {"thumbUrlPrefix": VAR_9.get("urlprefix", FUNC_65)} def FUNC_67(VAR_10): VAR_213 = {} for VAR_30, VAR_108 in (["x", VAR_10.getPosX()], ["y", VAR_10.getPosY()]): if VAR_108 is not None: VAR_213[VAR_30] = {"value": VAR_108.getValue(), "unit": str(VAR_108.getUnit())} return VAR_213 VAR_130 = [] for ws in VAR_119.listChildren(): if ( VAR_129 is not None and ws.plateAcquisition is not None and ws.plateAcquisition.id.val != VAR_129 ): continue VAR_92 = ws.getImage() if VAR_92 is not None: VAR_282 = VAR_92.simpleMarshal(VAR_121=xtra) VAR_27 = FUNC_67(ws) if len(VAR_27.keys()) > 0: VAR_282["position"] = VAR_27 VAR_130.append(VAR_282) return VAR_130 @login_required() @FUNC_20 def FUNC_30(VAR_2, VAR_32, VAR_8=None, **VAR_9): VAR_131 = VAR_8.getObject("Project", VAR_32) if VAR_131 is None: return HttpJavascriptResponse("[]") return [VAR_30.simpleMarshal(VAR_121={"childCount": 0}) for VAR_30 in VAR_131.listChildren()] @login_required() @FUNC_20 def FUNC_31(VAR_2, VAR_34, VAR_8=None, **VAR_9): VAR_132 = VAR_8.getObject("Dataset", VAR_34) return VAR_132.simpleMarshal() @login_required() @FUNC_20 def FUNC_32(VAR_2, VAR_8=None, **VAR_9): VAR_54 = [] for VAR_133 in VAR_8.listProjects(): VAR_54.append({"id": VAR_133.id, "name": VAR_133.name, "description": VAR_133.description or ""}) return VAR_54 @login_required() @FUNC_20 def FUNC_33(VAR_2, VAR_32, VAR_8=None, **VAR_9): VAR_133 = VAR_8.getObject("Project", VAR_32) VAR_54 = VAR_133.simpleMarshal() return VAR_54 @FUNC_20 def FUNC_34(VAR_2, **VAR_9): VAR_134 = settings.OPEN_WITH VAR_135 = [] for ow in VAR_134: if len(ow) < 2: continue VAR_214 = {} viewer["id"] = ow[0] try: VAR_214["url"] = reverse(ow[1]) except NoReverseMatch: VAR_214["url"] = ow[1] try: if len(ow) > 2: if "supported_objects" in ow[2]: VAR_214["supported_objects"] = ow[2]["supported_objects"] if "target" in ow[2]: VAR_214["target"] = ow[2]["target"] if "script_url" in ow[2]: if ow[2]["script_url"].startswith("http"): VAR_214["script_url"] = ow[2]["script_url"] else: VAR_214["script_url"] = static(ow[2]["script_url"]) if "label" in ow[2]: VAR_214["label"] = ow[2]["label"] except Exception: pass VAR_135.append(VAR_214) return {"open_with_options": VAR_135} def FUNC_35(VAR_2): try: VAR_53 = VAR_2.GET VAR_136 = { "search": unicode(VAR_53.get("text", "")).encode("utf8"), "ctx": VAR_53.get("ctx", ""), "grabData": not not VAR_53.get("grabData", False), "parents": not not bool(VAR_53.get("parents", False)), "start": int(VAR_53.get("start", 0)), "limit": int(VAR_53.get("limit", 0)), "key": VAR_53.get("key", None), } VAR_215 = VAR_53.get("author", "") if VAR_215: VAR_136["search"] += " VAR_215:" + VAR_215 return VAR_136 except Exception: VAR_1.error(traceback.format_exc()) return {} @TimeIt(logging.INFO) @login_required() @FUNC_20 def FUNC_36(VAR_2, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_136 = FUNC_35(VAR_2) VAR_54 = [] VAR_1.debug("searchObjects(%VAR_3)" % (VAR_136["search"])) def FUNC_65(VAR_6): return reverse("webgateway_render_thumbnail", VAR_116=(VAR_6,)) VAR_121 = {"thumbUrlPrefix": VAR_9.get("urlprefix", FUNC_65)} try: if VAR_136["ctx"] == "imgs": VAR_283 = VAR_8.searchObjects(["image"], VAR_136["search"], VAR_8.SERVICE_OPTS) else: VAR_283 = VAR_8.searchObjects(None, VAR_136["search"], VAR_8.SERVICE_OPTS) except ApiUsageException: return HttpJavascriptResponseServerError('"parse exception"') def FUNC_68(): VAR_54 = [] if VAR_136["grabData"] and VAR_136["ctx"] == "imgs": VAR_284 = min(VAR_136["start"], len(VAR_283) - 1) if VAR_136["limit"] == 0: VAR_317 = len(VAR_283) else: VAR_317 = min(len(VAR_283), VAR_284 + VAR_136["limit"]) for VAR_212 in range(VAR_284, VAR_317): VAR_318 = VAR_283[VAR_212] try: VAR_54.append( FUNC_23( VAR_2, VAR_19, VAR_6=VAR_318.id, VAR_79=VAR_136["key"], VAR_8=conn, VAR_31=True, ) ) except AttributeError as VAR_30: VAR_1.debug( "(VAR_6 %VAR_212) ignoring Attribute Error: %s" % (VAR_318.id, str(VAR_30)) ) pass except omero.ServerError as VAR_30: VAR_1.debug("(VAR_6 %VAR_212) ignoring Server Error: %s" % (VAR_318.id, str(VAR_30))) return VAR_54 else: return [VAR_30.simpleMarshal(VAR_121=xtra, parents=VAR_136["parents"]) for VAR_30 in VAR_283] VAR_54 = timeit(FUNC_68)() VAR_1.debug(VAR_54) return VAR_54 @require_POST @login_required() def FUNC_37(VAR_2, VAR_6, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_64 = FUNC_13( VAR_2, VAR_6, VAR_19=server_id, VAR_8=conn, VAR_20=True ) if VAR_64 is None: VAR_139 = "false" else: VAR_58 = VAR_64[0]._conn.getEventContext().userId webgateway_cache.invalidateObject(VAR_19, VAR_58, VAR_64[0]) VAR_64[0].getThumbnail() VAR_139 = "true" if VAR_2.GET.get("callback", None): VAR_139 = "%VAR_3(%VAR_3)" % (VAR_2.GET["callback"], VAR_139) return HttpJavascriptResponse(VAR_139) @login_required() @FUNC_20 def FUNC_38(VAR_2, VAR_8=None, **VAR_9): VAR_137 = VAR_8.getScriptService() VAR_138 = VAR_137.getScriptsByMimetype("text/VAR_30-lut") VAR_54 = [] for lut in VAR_138: VAR_216 = lut.path.val + lut.name.val VAR_217 = LUTS_IN_PNG.index(VAR_216) if VAR_216 in LUTS_IN_PNG else -1 VAR_54.append( { "id": lut.id.val, "path": lut.path.val, "name": lut.name.val, "size": unwrap(lut.size), "png_index": VAR_217, } ) VAR_54.sort(VAR_79=lambda VAR_30: x["name"].lower()) return {"luts": VAR_54, "png_luts": LUTS_IN_PNG} @login_required() def FUNC_39(VAR_2, VAR_6, VAR_8=None, **VAR_9): VAR_139 = "false" VAR_53 = VAR_2.GET if VAR_8 is None: VAR_92 = None else: VAR_92 = VAR_8.getObject("Image", VAR_6) if VAR_92 is not None: VAR_115 = [] for VAR_132 in VAR_92.getProject().listChildren(): VAR_115.extend(VAR_132.listChildren()) VAR_218 = VAR_92.getPrimaryPixels().getPixelsType().getValue() VAR_219 = VAR_92.getSizeC() VAR_220 = [VAR_30.getLabel() for VAR_30 in VAR_92.getChannels()] VAR_220.sort() def FUNC_76(VAR_212): if VAR_178(VAR_212.getId()) == VAR_178(VAR_6): return False VAR_285 = VAR_212.getPrimaryPixels() if ( VAR_285 is None or VAR_212.getPrimaryPixels().getPixelsType().getValue() != VAR_218 or VAR_212.getSizeC() != VAR_219 ): return False VAR_286 = [VAR_30.getLabel() for VAR_30 in VAR_212.getChannels()] VAR_286.sort() if VAR_286 != VAR_220: return False return True VAR_115 = filter(FUNC_76, VAR_115) VAR_139 = json.dumps([VAR_30.getId() for VAR_30 in VAR_115]) if VAR_53.get("callback", None): VAR_139 = "%VAR_3(%VAR_3)" % (VAR_53["callback"], VAR_139) return HttpJavascriptResponse(VAR_139) @require_POST @login_required() @FUNC_20 def FUNC_40(VAR_2, VAR_35=False, VAR_8=None, **VAR_9): VAR_53 = VAR_2.POST VAR_140 = VAR_53.getlist("toids") VAR_141 = str(VAR_53.get("to_type", "image")) VAR_141 = to_type.title() if VAR_141 == "Acquisition": VAR_141 = "PlateAcquisition" if len(VAR_140) == 0: raise Http404( "Need to specify objects in VAR_2, E.g." " ?totype=VAR_128&VAR_140=1&VAR_140=2" ) VAR_140 = [int(id) for id in VAR_140] VAR_142 = VAR_8.getRenderingSettingsService() VAR_8.SERVICE_OPTS.setOmeroGroup("-1") VAR_143 = VAR_8.getObject(VAR_141, VAR_140[0]) if VAR_143 is not None: VAR_221 = VAR_143.getDetails().group.id.val VAR_8.SERVICE_OPTS.setOmeroGroup(VAR_221) if VAR_35: VAR_54 = VAR_142.resetDefaultsByOwnerInSet(VAR_141, VAR_140, VAR_8.SERVICE_OPTS) else: VAR_54 = VAR_142.resetDefaultsInSet(VAR_141, VAR_140, VAR_8.SERVICE_OPTS) return VAR_54 @login_required() @FUNC_20 def FUNC_41(VAR_2, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_139 = False VAR_144 = VAR_2.GET.get("fromid", None) VAR_140 = VAR_2.POST.getlist("toids") VAR_141 = str(VAR_2.POST.get("to_type", "image")) VAR_145 = None if VAR_141 not in ("dataset", "plate", "acquisition"): VAR_141 = "Image" # default is VAR_15 if VAR_144 is not None and len(VAR_140) == 0: VAR_2.session.modified = True VAR_2.session["fromid"] = VAR_144 if VAR_2.session.get("rdef") is not None: del VAR_2.session["rdef"] return True VAR_53 = VAR_2.GET or VAR_2.POST if VAR_53.get("c") is not None: VAR_145 = {"c": str(VAR_53.get("c"))} # VAR_50 if VAR_53.get("maps"): try: VAR_145["maps"] = json.loads(VAR_53.get("maps")) except Exception: pass if VAR_53.get("pixel_range"): VAR_145["pixel_range"] = str(VAR_53.get("pixel_range")) if VAR_53.get("m"): VAR_145["m"] = str(VAR_53.get("m")) # model (grey) if VAR_53.get("z"): VAR_145["z"] = str(VAR_53.get("z")) # VAR_22 & VAR_23 VAR_27 if VAR_53.get("t"): VAR_145["t"] = str(VAR_53.get("t")) VAR_36 = VAR_2.GET.get("imageId", VAR_2.POST.get("imageId", None)) if VAR_36: VAR_145["imageId"] = int(VAR_36) if VAR_2.method == "GET": VAR_2.session.modified = True VAR_2.session["rdef"] = VAR_145 if VAR_2.session.get("fromid") is not None: del VAR_2.session["fromid"] return True if VAR_144 is None: VAR_144 = VAR_2.session.get("fromid", None) def FUNC_69(VAR_15): VAR_54 = {} VAR_222 = [] VAR_223 = [] for VAR_212, ch in enumerate(VAR_15.getChannels()): VAR_287 = "" if ch.isActive() else "-" VAR_288 = ch.getWindowStart() VAR_289 = ch.getWindowEnd() VAR_68 = ch.getLut() VAR_223.append({"inverted": {"enabled": ch.isInverted()}}) if not VAR_68 or len(VAR_68) == 0: VAR_68 = ch.getColor().getHtml() VAR_222.append("%VAR_3%VAR_3|%VAR_3:%VAR_3$%s" % (VAR_287, VAR_212 + 1, VAR_288, VAR_289, VAR_68)) VAR_54["c"] = ",".join(VAR_222) VAR_54["maps"] = VAR_223 VAR_54["m"] = "g" if VAR_15.isGreyscaleRenderingModel() else "c" VAR_54["z"] = VAR_15.getDefaultZ() + 1 VAR_54["t"] = VAR_15.getDefaultT() + 1 return VAR_54 def FUNC_70(VAR_15, VAR_145): VAR_107 = FUNC_12(VAR_145, "inverted", VAR_15.getSizeC()) VAR_50, VAR_51, VAR_52 = FUNC_2(VAR_145["c"]) VAR_15.setActiveChannels(VAR_50, VAR_51, VAR_52, VAR_107) if VAR_145["m"] == "g": VAR_15.setGreyscaleRenderingModel() else: VAR_15.setColorRenderingModel() if "z" in VAR_145: VAR_15._re.setDefaultZ(VAR_178(VAR_145["z"]) - 1) if "t" in VAR_145: VAR_15._re.setDefaultT(VAR_178(VAR_145["t"]) - 1) VAR_15.saveDefaults() if VAR_145 is None: VAR_145 = VAR_2.session.get("rdef") if VAR_2.method == "POST": VAR_224 = None VAR_225 = None if VAR_144 is None: if VAR_145 is not None and len(VAR_140) > 0: VAR_225 = VAR_8.getObject("Image", VAR_145["imageId"]) if VAR_225 is not None: VAR_224 = FUNC_69(VAR_225) FUNC_70(VAR_225, VAR_145) VAR_144 = VAR_225.getId() try: VAR_144 = VAR_178(VAR_144) VAR_140 = [VAR_178(VAR_30) for VAR_30 in VAR_140] except TypeError: VAR_144 = None except ValueError: VAR_144 = None if VAR_144 is not None and len(VAR_140) > 0: VAR_290 = VAR_8.getObject("Image", VAR_144) VAR_291 = VAR_290.getOwner().getId() VAR_139 = VAR_8.applySettingsToSet(VAR_144, VAR_141, VAR_140) if VAR_139 and True in VAR_139: for VAR_6 in VAR_139[True]: VAR_92 = VAR_8.getObject("Image", VAR_6) VAR_92 is not None and webgateway_cache.invalidateObject( VAR_19, VAR_291, VAR_92 ) if VAR_141 == "Image" and VAR_144 not in VAR_140: if VAR_224 is not None and VAR_225 is not None: FUNC_70(VAR_225, VAR_224) return VAR_139 else: return HttpResponseNotAllowed(["POST"]) @login_required() @FUNC_20 def FUNC_42(VAR_2, VAR_8=None, **VAR_9): VAR_145 = VAR_2.session.get("rdef") VAR_15 = None if VAR_145 is None: VAR_144 = VAR_2.session.get("fromid", None) if VAR_144 is not None: VAR_15 = VAR_8.getObject("Image", VAR_144) if VAR_15 is not None: VAR_54 = imageMarshal(VAR_15, VAR_2=request) VAR_222 = [] VAR_223 = [] for VAR_212, ch in enumerate(VAR_54["channels"]): VAR_287 = ch["active"] and str(VAR_212 + 1) or "-%s" % (VAR_212 + 1) VAR_68 = ch.get("lut") or ch["color"] VAR_222.append( "%VAR_3|%VAR_3:%VAR_3$%s" % (VAR_287, ch["window"]["start"], ch["window"]["end"], VAR_68) ) VAR_223.append( { "inverted": {"enabled": ch["inverted"]}, "quantization": { "coefficient": ch["coefficient"], "family": ch["family"], }, } ) VAR_145 = { "c": (",".join(VAR_222)), "m": VAR_54["rdefs"]["model"], "pixel_range": "%VAR_3:%s" % (VAR_54["pixel_range"][0], VAR_54["pixel_range"][1]), "maps": VAR_223, } return {"rdef": VAR_145} @login_required() def FUNC_43(VAR_2, VAR_6, VAR_8=None, **VAR_9): VAR_19 = VAR_2.session["connector"].server_id VAR_146 = Server.get(VAR_19).server VAR_147 = FUNC_3(VAR_2) VAR_55 = VAR_2.session.get("server_settings", {}).get("viewer", {}) VAR_148 = VAR_55.get("interpolate_pixels", True) VAR_149 = VAR_55.get("roi_limit", 2000) try: VAR_15 = VAR_8.getObject("Image", VAR_6) if VAR_15 is None: VAR_1.debug("(VAR_167)Image %VAR_3 not found..." % (str(VAR_6))) raise Http404 VAR_226 = None VAR_227 = None VAR_228 = None VAR_229 = None if hasattr(settings, "SHARING_OPENGRAPH"): VAR_226 = settings.SHARING_OPENGRAPH.get(VAR_146) VAR_1.debug("Open Graph VAR_308: %s", VAR_226) if hasattr(settings, "SHARING_TWITTER"): VAR_227 = settings.SHARING_TWITTER.get(VAR_146) VAR_1.debug("Twitter VAR_308: %s", VAR_227) if VAR_226 or VAR_227: VAR_292 = {"iid": VAR_6} VAR_120 = VAR_9.get("thumbprefix", "webgateway_render_thumbnail") VAR_228 = VAR_2.build_absolute_uri(reverse(VAR_120, VAR_9=VAR_292)) VAR_229 = VAR_2.build_absolute_uri( reverse("webgateway_full_viewer", VAR_9=VAR_292) ) VAR_213 = { "blitzcon": VAR_8, "image": VAR_15, "opts": VAR_147, "interpolate": VAR_148, "build_year": build_year, "roiLimit": VAR_149, "roiCount": VAR_15.getROICount(), "viewport_server": VAR_9.get( "viewport_server", reverse("webgateway"), ).rstrip("/"), "opengraph": VAR_226, "twitter": VAR_227, "image_preview": VAR_228, "page_url": VAR_229, "object": "image:%i" % int(VAR_6), } VAR_230 = VAR_9.get("template", "webgateway/viewport/omero_image.html") VAR_61 = render(VAR_2, VAR_230, VAR_213) except omero.SecurityViolation: VAR_1.warn("SecurityViolation in Image:%s", VAR_6) VAR_1.warn(traceback.format_exc()) raise Http404 return HttpResponse(VAR_61) @login_required() def FUNC_44(VAR_2, VAR_6=None, VAR_8=None, **VAR_9): VAR_114 = VAR_2.GET.get("format", "png") if VAR_114 not in ("jpeg", "png", "tif"): VAR_114 = "png" VAR_150 = [] VAR_151 = [] if VAR_6 is None: VAR_150 = VAR_2.GET.getlist("image") if len(VAR_150) == 0: VAR_151 = VAR_2.GET.getlist("well") if len(VAR_151) == 0: return HttpResponseServerError( "No VAR_152 or VAR_153 specified in VAR_2." " Use ?VAR_15=123 or ?VAR_119=123" ) else: VAR_150 = [VAR_6] VAR_152 = [] if VAR_150: VAR_152 = list(VAR_8.getObjects("Image", VAR_150)) elif VAR_151: try: VAR_319 = int(VAR_2.GET.get("index", 0)) except ValueError: VAR_319 = 0 for VAR_10 in VAR_8.getObjects("Well", VAR_151): VAR_152.append(VAR_10.getWellSample(VAR_319).image()) if len(VAR_152) == 0: VAR_231 = "Cannot download as %VAR_3. Images (ids: %VAR_3) not found." % (VAR_114, VAR_150) VAR_1.debug(VAR_231) return HttpResponseServerError(VAR_231) if len(VAR_152) == 1: VAR_60 = VAR_152[0].renderJpeg() if VAR_60 is None: raise Http404 VAR_61 = HttpResponse(VAR_60, VAR_279="image/jpeg") VAR_61["Content-Length"] = len(VAR_60) VAR_61["Content-Disposition"] = "attachment; filename=%VAR_3.jpg" % ( VAR_152[0].getName().replace(" ", "_") ) else: VAR_232 = tempfile.NamedTemporaryFile(suffix=".download_as") def FUNC_77(VAR_233, VAR_234, VAR_235): VAR_17 = os.path.basename(VAR_233) VAR_293 = "%VAR_3.%s" % (VAR_17, VAR_234) VAR_293 = os.path.join(VAR_235, VAR_293) VAR_212 = 1 VAR_17 = VAR_293[: -(len(VAR_234) + 1)] while os.path.exists(VAR_293): imgName = "%s_(%VAR_213).%s" % (VAR_17, VAR_212, VAR_234) VAR_212 += 1 return VAR_293 try: VAR_294 = tempfile.mkdtemp() VAR_1.debug("download_as dir: %s" % VAR_294) try: for VAR_92 in VAR_152: VAR_22 = VAR_23 = None try: VAR_331 = VAR_92.renderImage(VAR_22, VAR_23) VAR_332 = FUNC_77(VAR_92.getName(), VAR_114, VAR_294) VAR_331.save(VAR_332) finally: VAR_92._re.close() VAR_320 = zipfile.ZipFile(VAR_232, "w", zipfile.ZIP_DEFLATED) try: VAR_324 = os.path.join(VAR_294, "*") for VAR_17 in glob.glob(VAR_324): VAR_320.write(VAR_17, os.path.basename(VAR_17)) finally: VAR_320.close() finally: shutil.rmtree(VAR_294, ignore_errors=True) VAR_240 = VAR_2.GET.get("zipname", "Download_as_%s" % VAR_114) VAR_240 = VAR_240.replace(" ", "_") if not VAR_240.endswith(".zip"): VAR_240 = "%VAR_3.zip" % VAR_240 VAR_61 = StreamingHttpResponse(FileWrapper(VAR_232)) VAR_61["Content-Length"] = VAR_232.tell() VAR_61["Content-Disposition"] = "attachment; filename=%s" % VAR_240 VAR_232.seek(0) except Exception: VAR_232.close() VAR_321 = traceback.format_exc() VAR_1.error(VAR_321) return HttpResponseServerError("Cannot download file (id:%VAR_3)" % VAR_6) VAR_61["Content-Type"] = "application/force-download" return VAR_61 @login_required(doConnectionCleanup=False) def FUNC_45(VAR_2, VAR_6=None, VAR_8=None, **VAR_9): VAR_150 = [] VAR_151 = [] VAR_150 = VAR_2.GET.getlist("image") VAR_151 = VAR_2.GET.getlist("well") if VAR_6 is None: if len(VAR_150) == 0 and len(VAR_151) == 0: return HttpResponseServerError( "No VAR_152 or VAR_153 specified in VAR_2." " Use ?VAR_15=123 or ?VAR_119=123" ) else: VAR_150 = [VAR_6] VAR_152 = list() VAR_153 = list() if VAR_150: VAR_152 = list(VAR_8.getObjects("Image", VAR_150)) elif VAR_151: try: VAR_319 = int(VAR_2.GET.get("index", 0)) except ValueError: VAR_319 = 0 VAR_153 = VAR_8.getObjects("Well", VAR_151) for VAR_10 in VAR_153: VAR_152.append(VAR_10.getWellSample(VAR_319).image()) if len(VAR_152) == 0: VAR_236 = ( "Cannot download archived file because Images not " "found (ids: %VAR_3)" % (VAR_150) ) VAR_1.debug(VAR_236) return HttpResponseServerError(VAR_236) for ob in VAR_153: if hasattr(ob, "canDownload"): if not ob.canDownload(): return HttpResponseNotFound() for ob in VAR_152: VAR_119 = None try: VAR_119 = ob.getParent().getParent() except Exception: if hasattr(ob, "canDownload"): if not ob.canDownload(): return HttpResponseNotFound() else: if VAR_119 and isinstance(VAR_119, omero.gateway.WellWrapper): if hasattr(VAR_119, "canDownload"): if not VAR_119.canDownload(): return HttpResponseNotFound() VAR_154 = {} for VAR_15 in VAR_152: for VAR_28 in VAR_15.getImportedImageFiles(): VAR_154[VAR_28.getId()] = VAR_28 VAR_155 = list(VAR_154.values()) if len(VAR_155) == 0: VAR_236 = ( "Tried downloading archived VAR_155 from VAR_15 with no" " VAR_155 archived." ) VAR_1.debug(VAR_236) return HttpResponseServerError(VAR_236) if len(VAR_155) == 1: VAR_237 = VAR_155[0] VAR_61 = ConnCleaningHttpResponse( VAR_237.getFileInChunks(buf=settings.CHUNK_SIZE) ) VAR_61.conn = VAR_8 VAR_61["Content-Length"] = VAR_237.getSize() VAR_238 = VAR_237.getName().replace(" ", "_").replace(",", ".") VAR_61["Content-Disposition"] = "attachment; filename=%s" % (VAR_238) else: VAR_239 = sum(VAR_28.size for VAR_28 in VAR_155) if VAR_239 > settings.MAXIMUM_MULTIFILE_DOWNLOAD_ZIP_SIZE: VAR_236 = ( "Total VAR_7 of VAR_155 %VAR_213 is larger than %VAR_213. " "Try requesting fewer VAR_155." % (VAR_239, settings.MAXIMUM_MULTIFILE_DOWNLOAD_ZIP_SIZE) ) VAR_1.warn(VAR_236) return HttpResponseForbidden(VAR_236) VAR_232 = tempfile.NamedTemporaryFile(suffix=".archive") VAR_240 = VAR_2.GET.get("zipname", VAR_15.getName()) try: VAR_240 = zip_archived_files(VAR_152, VAR_232, VAR_240, buf=settings.CHUNK_SIZE) VAR_295 = FileWrapper(VAR_232) VAR_61 = ConnCleaningHttpResponse(VAR_295) VAR_61.conn = VAR_8 VAR_61["Content-Length"] = VAR_232.tell() VAR_61["Content-Disposition"] = "attachment; filename=%s" % VAR_240 VAR_232.seek(0) except Exception: VAR_232.close() VAR_236 = "Cannot download file (id:%VAR_3)" % (VAR_6) VAR_1.error(VAR_236, exc_info=True) return HttpResponseServerError(VAR_236) VAR_61["Content-Type"] = "application/force-download" return VAR_61 @login_required() @FUNC_20 def FUNC_46(VAR_2, VAR_6, VAR_8=None, **VAR_9): VAR_15 = VAR_8.getObject("Image", VAR_6) if VAR_15 is None: raise Http404 VAR_156 = VAR_15.getImportedImageFilePaths() return {"repo": VAR_156["server_paths"], "client": VAR_156["client_paths"]} @login_required() @FUNC_20 def FUNC_47(VAR_2, VAR_13, VAR_14, VAR_8=None, **VAR_9): VAR_13 = int(VAR_13) VAR_14 = int(VAR_14) VAR_65 = VAR_8.getQueryService().findByQuery( "select VAR_65 from Roi as VAR_241 " "join VAR_241.shapes as VAR_65 " "where VAR_241.id = %VAR_213 and VAR_65.id = %d" % (VAR_13, VAR_14), None, ) VAR_1.debug("Shape: %r" % VAR_65) if VAR_65 is None: VAR_1.debug("No such VAR_65: %r" % VAR_14) raise Http404 return JsonResponse(shapeMarshal(VAR_65)) @login_required() @FUNC_20 def FUNC_48(VAR_2, VAR_36, VAR_8=None, **VAR_9): VAR_157 = [] VAR_158 = VAR_8.getRoiService() VAR_62 = VAR_158.findByImage(VAR_178(VAR_36), None, VAR_8.SERVICE_OPTS) for VAR_53 in VAR_62.rois: VAR_241 = {} roi["id"] = VAR_53.getId().getValue() VAR_63 = [] for VAR_3 in VAR_53.copyShapes(): if VAR_3 is None: # seems possible in some situations continue VAR_63.append(shapeMarshal(VAR_3)) VAR_63.sort(VAR_79=lambda VAR_30: "%03d%03d" % (VAR_30.get("theZ", -1), VAR_30.get("theT", -1))) VAR_241["shapes"] = VAR_63 VAR_157.append(VAR_241) VAR_157.sort(VAR_79=lambda VAR_30: x["id"]) return VAR_157 @login_required() def FUNC_49(VAR_2, VAR_6, VAR_37, VAR_8=None, **VAR_9): VAR_15 = VAR_8.getObject("Image", VAR_6) if VAR_15 is None: raise Http404 VAR_159, VAR_160 = VAR_8.getMaxPlaneSize() VAR_86 = VAR_15.getSizeX() VAR_87 = VAR_15.getSizeY() if (VAR_86 * VAR_87) > (VAR_159 * VAR_160): VAR_231 = "Histogram not supported for 'big' VAR_152 (over %VAR_3 * %VAR_3 pixels)" % ( VAR_159, VAR_160, ) return JsonResponse({"error": VAR_231}) VAR_74 = int(VAR_2.GET.get("theZ", 0)) VAR_73 = int(VAR_2.GET.get("theT", 0)) VAR_37 = int(VAR_37) VAR_161 = int(VAR_2.GET.get("bins", 256)) VAR_162 = VAR_15.getHistogram([VAR_37], VAR_161, VAR_74=theZ, VAR_73=theT) VAR_163 = VAR_162[VAR_37] return JsonResponse({"data": VAR_163}) @login_required(FUNC_58=True) @FUNC_20 def FUNC_50(VAR_2, VAR_38, VAR_8=None, **VAR_9): if VAR_2.method == "POST": VAR_8.setGroupNameForSession("system") VAR_175 = VAR_2.session["connector"] VAR_175 = Connector(VAR_175.server_id, VAR_175.is_secure) VAR_242 = VAR_8.getSessionService().getSession(VAR_8._sessionUuid) VAR_243 = VAR_242.getTimeToIdle().val VAR_175.omero_session_key = VAR_8.suConn(VAR_38, VAR_243=ttl)._sessionUuid VAR_2.session["connector"] = VAR_175 VAR_8.revertGroupForSession() VAR_8.close() return True else: VAR_244 = { "url": reverse("webgateway_su", VAR_116=[VAR_38]), "submit": "Do you want to FUNC_50 to %s" % VAR_38, } VAR_230 = "webgateway/base/includes/post_form.html" return render(VAR_2, VAR_230, VAR_244) def FUNC_51(VAR_2, VAR_39, VAR_40, VAR_8=None, **VAR_9): warnings.warn("Deprecated. Use FUNC_52()", DeprecationWarning) return FUNC_52(VAR_2, VAR_39, VAR_40, VAR_8, **VAR_9) def FUNC_52(VAR_2, VAR_39, VAR_40, VAR_8=None, **VAR_9): VAR_164 = VAR_8.getQueryService() VAR_39 = objtype.split(".") VAR_66 = omero.sys.ParametersI() VAR_66.addId(VAR_40) VAR_66.addString("ns", NSBULKANNOTATIONS) VAR_66.addString("mt", "OMERO.tables") VAR_43 = "select obj0 from %VAR_3 obj0\n" % VAR_39[0] for VAR_212, VAR_23 in enumerate(VAR_39[1:]): VAR_43 += "join fetch VAR_202%VAR_213.%VAR_3 VAR_202%VAR_213\n" % (VAR_212, VAR_23, VAR_212 + 1) VAR_43 += """ left outer join fetch obj0.annotationLinks VAR_165 left outer join fetch VAR_165.child as VAR_28 left outer join fetch VAR_165.parent left outer join fetch VAR_28.file join fetch VAR_165.details.owner join fetch VAR_165.details.creationEvent where VAR_202%VAR_213.id=:id and (VAR_28.ns=:ns or VAR_28.file.mimetype=:mt)""" % ( len(VAR_39) - 1 ) VAR_24 = VAR_8.createServiceOptsDict() VAR_24.setOmeroGroup("-1") try: VAR_245 = VAR_164.findAllByQuery(VAR_43, VAR_66, VAR_24) except omero.QueryException: return dict(VAR_176="%VAR_3 cannot be queried" % VAR_39, VAR_43=query) VAR_162 = [] VAR_165 = [link for VAR_202 in VAR_245 for link in VAR_202.copyAnnotationLinks()] for link in VAR_165: VAR_246 = link.child if not isinstance(VAR_246, omero.model.FileAnnotation): continue VAR_247 = VAR_246.details.owner VAR_248 = "%VAR_3 %s" % (unwrap(VAR_247.firstName), unwrap(VAR_247.lastName)) VAR_249 = link.details.owner VAR_250 = "%VAR_3 %s" % (unwrap(VAR_249.firstName), unwrap(VAR_249.lastName)) VAR_162.append( dict( id=VAR_246.id.val, file=VAR_246.file.id.val, parentType=VAR_39[0], parentId=link.parent.id.val, VAR_247=VAR_248, VAR_249=VAR_250, addedOn=unwrap(link.details.creationEvent._time), ) ) return dict(VAR_162=data) VAR_41 = login_required()(FUNC_20(FUNC_52)) def FUNC_53(VAR_2, VAR_42, VAR_8=None, VAR_43=None, VAR_44=False, **VAR_9): if VAR_43 is None: VAR_43 = VAR_2.GET.get("query") if not VAR_43: return dict(VAR_176="Must specify VAR_43 parameter, use * to retrieve all") VAR_166 = VAR_2.GET.getlist("col_names") VAR_24 = VAR_8.createServiceOptsDict() VAR_24.setOmeroGroup("-1") VAR_53 = VAR_8.getSharedResources() VAR_23 = VAR_53.openTable(omero.model.OriginalFileI(VAR_42), VAR_24) if not VAR_23: return dict(VAR_176="Table %VAR_3 not found" % VAR_42) try: VAR_251 = VAR_23.getHeaders() VAR_252 = range(len(VAR_251)) if VAR_166: VAR_296 = ( [(VAR_212, j) for (VAR_212, j) in enumerate(VAR_251) if j.name in VAR_166] if VAR_166 else [(VAR_212, j) for (VAR_212, j) in enumerate(VAR_251)] ) cols = [] VAR_252 = [] for col_name in VAR_166: for (VAR_212, j) in VAR_296: if col_name == j.name: VAR_252.append(VAR_212) VAR_251.append(j) break VAR_253 = VAR_23.getNumberOfRows() VAR_254 = VAR_9.get("offset", 0) VAR_255 = VAR_9.get("limit", None) if not VAR_254: VAR_254 = int(VAR_2.GET.get("offset", 0)) if not VAR_255: VAR_255 = ( int(VAR_2.GET.get("limit")) if VAR_2.GET.get("limit") is not None else VAR_253 ) VAR_256 = VAR_254 VAR_257 = VAR_255 VAR_258 = min(VAR_253, VAR_256 + VAR_257) if VAR_43 == "*": VAR_297 = range(VAR_256, VAR_258) VAR_298 = VAR_253 else: VAR_299 = re.match(r"^(\VAR_10+)-(\VAR_213+)", VAR_43) if VAR_299: VAR_43 = "(%VAR_3==%s)" % (VAR_299.group(1), VAR_299.group(2)) try: VAR_1.info(VAR_43) VAR_297 = VAR_23.getWhereList(VAR_43, None, 0, VAR_253, 1) VAR_298 = len(VAR_297) hits = VAR_297[VAR_256:VAR_258] except Exception: return dict(VAR_176="Error executing VAR_43: %s" % VAR_43) def FUNC_78(VAR_259, VAR_11): VAR_300 = 0 VAR_301 = 1000 while VAR_300 < len(VAR_11): VAR_301 = min(VAR_301, len(VAR_11) - VAR_300) VAR_322 = VAR_259.slice(VAR_252, VAR_11[VAR_300 : idx + VAR_301]) VAR_300 += VAR_301 yield [ [col.values[row] for col in VAR_322.columns] for row in range(0, len(VAR_322.rowNumbers)) ] VAR_260 = FUNC_78(VAR_23, VAR_297) VAR_261 = { "data": { "column_types": [col.__class__.__name__ for col in VAR_251], "columns": [col.name for col in VAR_251], }, "meta": { "rowCount": VAR_253, "totalCount": VAR_298, "limit": VAR_255, "offset": VAR_254, }, } if not VAR_44: VAR_302 = [] for VAR_253 in list(VAR_260): VAR_302.extend(VAR_253) VAR_261["data"]["rows"] = VAR_302 else: VAR_261["data"]["lazy_rows"] = VAR_260 VAR_261["table"] = VAR_23 return VAR_261 finally: if not VAR_44: VAR_23.close() VAR_45 = login_required()(FUNC_20(FUNC_53)) def FUNC_54(VAR_2, VAR_42, VAR_8=None, VAR_43=None, VAR_44=False, **VAR_9): VAR_24 = VAR_8.createServiceOptsDict() VAR_24.setOmeroGroup("-1") VAR_53 = VAR_8.getSharedResources() VAR_23 = VAR_53.openTable(omero.model.OriginalFileI(VAR_42), VAR_24) if not VAR_23: return dict(VAR_176="Table %VAR_3 not found" % VAR_42) try: VAR_251 = VAR_23.getHeaders() VAR_253 = VAR_23.getNumberOfRows() VAR_261 = { "columns": [ { "name": col.name, "description": col.description, "type": col.__class__.__name__, } for col in VAR_251 ], "totalCount": VAR_253, } return VAR_261 finally: if not VAR_44: VAR_23.close() VAR_46 = login_required()(FUNC_20(FUNC_54)) @login_required() @FUNC_20 def FUNC_55(VAR_2, VAR_39, VAR_40, VAR_8=None, **VAR_9): VAR_167 = FUNC_52(VAR_2, VAR_39, VAR_40, VAR_8, **VAR_9) if "error" in VAR_167: return VAR_167 if len(VAR_167["data"]) < 1: return dict(VAR_176="Could not retrieve bulk VAR_41 table") VAR_168 = 0 VAR_169 = None VAR_170 = sorted(VAR_167["data"], VAR_79=lambda VAR_30: x["file"], reverse=True) VAR_171 = None for VAR_246 in VAR_170: VAR_171 = FUNC_53(VAR_2, VAR_246["file"], VAR_8, **VAR_9) if "error" not in VAR_171: VAR_169 = VAR_246 VAR_168 = VAR_246["file"] break if VAR_169 is None: return dict( VAR_176=VAR_171.get( "error", "Could not retrieve matching bulk VAR_246 table" ) ) VAR_171["id"] = VAR_168 VAR_171["annId"] = VAR_169["id"] VAR_171["owner"] = VAR_169["owner"] VAR_171["addedBy"] = VAR_169["addedBy"] VAR_171["parentType"] = VAR_169["parentType"] VAR_171["parentId"] = VAR_169["parentId"] VAR_171["addedOn"] = VAR_169["addedOn"] return VAR_171 class CLASS_1(View): VAR_172 = LoginForm VAR_173 = "OMERO.webapi" @method_decorator(sensitive_post_parameters("password", "csrfmiddlewaretoken")) def FUNC_71(self, *VAR_116, **VAR_9): return super(CLASS_1, self).dispatch(*VAR_116, **VAR_9) def FUNC_72(self, VAR_2, VAR_174=None): return JsonResponse( {"message": ("POST only with VAR_304, VAR_305, " "server and csrftoken")}, VAR_315=405, ) def FUNC_73(self, VAR_2, VAR_8, VAR_175): VAR_203 = VAR_8.getEventContext() VAR_24 = {} for VAR_167 in [ "sessionId", "sessionUuid", "userId", "userName", "groupId", "groupName", "isAdmin", "eventId", "eventType", "memberOfGroups", "leaderOfGroups", ]: if hasattr(VAR_203, VAR_167): VAR_24[VAR_167] = getattr(VAR_203, VAR_167) return JsonResponse({"success": True, "eventContext": VAR_24}) def FUNC_74(self, VAR_2, VAR_176=None, VAR_177=None): if VAR_176 is None and VAR_177 is not None: VAR_303 = [] for VAR_33 in VAR_177: for VAR_318 in VAR_33.errors: VAR_303.append("%VAR_3: %s" % (VAR_33.label, VAR_318)) VAR_176 = " ".join(VAR_303) elif VAR_176 is None: VAR_176 = "Login failed. Reason unknown." return JsonResponse({"message": VAR_176}, VAR_315=403) def FUNC_75(self, VAR_2, VAR_174=None): VAR_176 = None VAR_177 = self.form_class(VAR_2.POST.copy()) if VAR_177.is_valid(): VAR_304 = VAR_177.cleaned_data["username"] VAR_305 = VAR_177.cleaned_data["password"] VAR_19 = VAR_177.cleaned_data["server"] VAR_306 = settings.SECURE VAR_175 = Connector(VAR_19, VAR_306) VAR_307 = True if settings.CHECK_VERSION: VAR_307 = VAR_175.check_version(self.useragent) if ( VAR_19 is not None and VAR_304 is not None and VAR_305 is not None and VAR_307 ): VAR_8 = VAR_175.create_connection( self.useragent, VAR_304, VAR_305, userip=get_client_ip(VAR_2) ) if VAR_8 is not None: try: VAR_2.session["connector"] = VAR_175 try: VAR_335 = settings.UPGRADES_URL except Exception: VAR_335 = VAR_8.getUpgradesUrl() upgradeCheck(url=VAR_335) return self.handle_logged_in(VAR_2, VAR_8, VAR_175) finally: VAR_8.close(hard=False) if not VAR_175.is_server_up(self.useragent): VAR_176 = "Server is not responding," " please contact administrator." elif not settings.CHECK_VERSION: VAR_176 = ( "Connection not available, please check your" " credentials and version compatibility." ) else: if not VAR_307: VAR_176 = ( "Client version does not VAR_299 server," " please contact administrator." ) else: VAR_176 = settings.LOGIN_INCORRECT_CREDENTIALS_TEXT return self.handle_not_logged_in(VAR_2, VAR_176, VAR_177) @login_required() @FUNC_20 def FUNC_56(VAR_2, VAR_47=None, VAR_8=None, **VAR_9): try: VAR_92 = VAR_8.getObject("Image", VAR_47) if VAR_92 is None: return {"error": "No VAR_15 with id " + str(VAR_47)} return {"rdefs": VAR_92.getAllRenderingDefs()} except Exception: VAR_1.debug(traceback.format_exc()) return {"error": "Failed to retrieve rdefs"}
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 24, 39, 58, 63, 68, 71, 76, 78, 79, 80, 81, 87, 94, 99, 102, 112, 115, 120, 121, 125, 126, 129, 130, 136, 141, 145, 148, 151, 153, 157, 161, 163, 167, 171, 173, 177, 181, 183, 187, 191, 193, 197, 201, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 231, 239, 244, 246, 248, 250, 258, 261, 262, 275, 276, 292, 300, 311, 312, 325, 326, 332, 341, 342, 346, 354, 357, 372, 402, 403, 409, 421, 422, 431, 432, 436, 441, 444, 449, 451, 457, 473, 476, 478, 479, 487, 488, 496, 499, 501, 506, 508, 509, 514, 518, 532, 534, 555, 602, 603, 605, 608, 611, 615, 616, 626, 635, 642, 647, 648, 649, 667, 668, 673, 674, 682, 683, 688, 696, 710, 719, 722, 723, 730, 732, 733, 741, 747, 756, 757, 761, 779, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 810, 814, 815, 821, 825, 829, 830, 840, 848, 856, 857, 866, 885, 887, 893, 898, 903, 908, 911, 916, 934, 935, 942, 951, 952, 953, 954, 955, 956, 958, 962, 966, 972, 974, 988, 991, 1000, 1027, 1038, 1039, 1048, 1051, 1052, 1061, 1080, 1085, 1093, 1110, 1111, 1123, 1172, 1174, 1191, 1198, 1251, 1252, 1253, 1254, 1269, 1270, 1275, 1286, 1287, 1301, 1307, 1314, 1315, 1323, 1337, 1338, 1351, 1355, 1359, 1360, 1368, 1390, 1391, 1395, 1399, 1410, 1412, 1413, 1418, 1422, 1440, 1444, 1445, 1446, 1450, 1451, 1452, 1465, 1467, 1468, 1479, 1489, 1505, 1506, 1516, 1526, 1538, 1539, 1546, 1552, 1558, 1566, 1567, 1574, 1580, 1586, 1589, 1593, 1594, 1607, 1612, 1614, 1618, 1621, 1628, 1629, 1636, 1647, 1670, 1679, 1680, 1687, 1699, 1700, 1707, 1713, 1718, 1721, 1727, 1728, 1735, 1741, 1747, 1750, 1752, 1759, 1762, 1777, 1778, 1785, 1791, 1796, 1797, 1807, 1808, 1815, 1820, 1825, 1826, 1833, 1839, 1843, 1844, 1861, 1862, 1870, 1874, 1879, 1883, 1884, 1897, 1901, 1920, 1921, 1938, 1948, 1949, 1952, 1958, 1962, 1973, 1995, 1999, 2000, 2009, 2029, 2030, 2036, 2058, 2059, 2068, 2074, 2081, 2083, 2087, 2092, 2108, 2111, 2115, 2116, 2125, 2128, 2135, 2141, 2143, 2145, 2146, 2152, 2157, 2159, 2160, 2174, 2180, 2183, 2188, 2191, 2192, 2199, 2200, 2203, 2221, 2225, 2229, 2230, 2233, 2234, 2254, 2258, 2269, 2270, 2277, 2278, 2282, 2286, 2287, 2305, 2306, 2307, 2312, 2315, 2316, 2329, 2357, 2359, 2360, 2367, 2375, 2378, 2383, 2389, 2394, 2398, 2402, 2410, 2420, 2430, 2438, 2439, 2449, 2463, 2474, 2479, 2491, 2496, 2503, 2515, 2517, 2527, 2532, 2533, 2538, 2544, 2547, 2548, 2555, 2568, 2588, 2589, 2594, 2608, 2609, 2615, 2622, 2630, 2643, 2646, 2649, 2650, 2662, 2665, 2666, 2674, 2680, 2681, 2698, 2699, 2708, 2709, 2711, 2715, 2721, 2725, 2726, 2728, 2730, 2731, 2750, 2755, 2756, 2759, 2761, 2762, 2770, 2796, 2797, 2801, 2802, 2810, 2819, 2833, 2834, 2835, 2836, 2838, 2843, 2858, 2861, 2866, 2868, 2890, 2891, 2893, 2894, 2900, 2926, 2929, 2934, 2952, 2954, 2968, 2980, 2984, 2986, 2993, 2998, 3000, 3013, 3016, 3023, 3028, 3029, 3031, 3032, 3036, 3041, 3045, 3061, 3062, 3064, 3065, 3074, 3083, 3100, 3103, 3104, 3105, 3130, 3131, 3134, 3137, 3142, 3149, 3170, 3174, 3177, 3183, 3190, 3193, 3197, 3207, 3209, 3210, 3226, 3227, 3228, 3237, 3238, 3255, 3256, 3262, 3265, 3275, 3278, 3283, 123, 132, 133, 134, 135, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 344, 345, 346, 347, 348, 349, 350, 351, 352, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 425, 426, 427, 428, 429, 482, 483, 484, 485, 511, 512, 513, 514, 515, 516, 517, 760, 817, 818, 819, 820, 821, 822, 823, 824, 832, 833, 834, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1393, 1394, 1395, 1396, 1397, 1398, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1472, 1473, 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521, 1522, 1523, 1524, 1525, 1543, 1544, 1545, 1546, 1547, 1548, 1549, 1550, 1551, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1598, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1684, 1685, 1686, 1687, 1688, 1689, 1690, 1691, 1692, 1693, 1704, 1705, 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1801, 1802, 1803, 1804, 1812, 1813, 1814, 1815, 1816, 1817, 1818, 1819, 1830, 1831, 1832, 1833, 1834, 1835, 1836, 1837, 1838, 1847, 1848, 1849, 1886, 1887, 1888, 1889, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2121, 2122, 2123, 2124, 2125, 2126, 2127, 2164, 2165, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, 2175, 2176, 2177, 2178, 2179, 2320, 2321, 2322, 2323, 2363, 2364, 2365, 2366, 2367, 2368, 2369, 2370, 2371, 2372, 2373, 2374, 2442, 2443, 2444, 2445, 2551, 2552, 2553, 2554, 2670, 2671, 2672, 2673, 2703, 2704, 2705, 2734, 2735, 2736, 2737, 2766, 2767, 2768, 2769, 2770, 2771, 2772, 2773, 2774, 2775, 2776, 2777, 2804, 2805, 2806, 2807, 2808, 2809, 2810, 2811, 2812, 2813, 2814, 2815, 2816, 2817, 2818, 2819, 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2896, 2897, 2898, 2899, 2900, 2901, 2902, 2903, 2904, 2905, 2906, 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 3069, 3070, 3071, 3072, 3073, 3074, 3075, 3076, 3077, 3078, 3079, 3080, 3081, 3082, 3083, 3084, 3085, 3086, 3087, 3088, 3089, 3090, 3091, 3092, 3093, 3094, 3095, 3096, 3133, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 138, 139, 140, 141, 142, 143, 144, 150, 155, 156, 157, 158, 159, 160, 165, 166, 167, 168, 169, 170, 175, 176, 177, 178, 179, 180, 185, 186, 187, 188, 189, 190, 195, 196, 197, 198, 199, 200, 3140, 3144, 3151, 3172, 3173, 3174, 3175, 3176, 3177, 3178, 3179, 3180, 3181, 3195, 3196, 3197, 3198, 3199 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 24, 39, 58, 63, 68, 71, 76, 78, 79, 80, 81, 87, 94, 99, 102, 112, 115, 120, 121, 125, 126, 129, 130, 136, 141, 145, 148, 151, 153, 157, 161, 163, 167, 171, 173, 177, 181, 183, 187, 191, 193, 197, 201, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 231, 239, 244, 246, 248, 250, 258, 261, 262, 275, 276, 292, 300, 311, 312, 325, 326, 332, 341, 342, 346, 354, 357, 372, 402, 403, 409, 421, 422, 431, 432, 436, 441, 444, 449, 451, 457, 473, 476, 478, 479, 487, 488, 496, 499, 501, 506, 508, 509, 514, 518, 532, 534, 555, 602, 603, 605, 608, 611, 615, 616, 626, 635, 642, 647, 648, 649, 667, 668, 673, 674, 682, 683, 688, 696, 710, 719, 722, 723, 730, 732, 733, 741, 747, 756, 757, 761, 779, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 810, 814, 815, 821, 825, 829, 830, 840, 848, 856, 857, 866, 885, 887, 893, 898, 903, 908, 911, 916, 934, 935, 942, 951, 952, 953, 954, 955, 956, 958, 962, 966, 972, 974, 988, 991, 1000, 1027, 1038, 1039, 1048, 1051, 1052, 1061, 1080, 1085, 1093, 1110, 1111, 1123, 1172, 1174, 1191, 1198, 1251, 1252, 1253, 1254, 1269, 1270, 1275, 1286, 1287, 1301, 1307, 1314, 1315, 1323, 1337, 1338, 1351, 1355, 1359, 1360, 1368, 1390, 1391, 1395, 1399, 1410, 1412, 1413, 1418, 1422, 1440, 1444, 1445, 1446, 1450, 1451, 1452, 1465, 1467, 1468, 1479, 1489, 1505, 1506, 1516, 1526, 1538, 1539, 1546, 1552, 1558, 1566, 1567, 1574, 1580, 1586, 1589, 1593, 1594, 1607, 1612, 1614, 1618, 1621, 1628, 1629, 1636, 1647, 1670, 1679, 1680, 1687, 1699, 1700, 1707, 1713, 1718, 1721, 1727, 1728, 1735, 1741, 1747, 1750, 1752, 1759, 1762, 1777, 1778, 1785, 1791, 1796, 1797, 1807, 1808, 1815, 1820, 1825, 1826, 1833, 1839, 1843, 1844, 1861, 1862, 1870, 1874, 1879, 1883, 1884, 1897, 1901, 1920, 1921, 1938, 1948, 1949, 1952, 1958, 1962, 1973, 1995, 1999, 2000, 2009, 2029, 2030, 2036, 2058, 2059, 2068, 2074, 2081, 2083, 2087, 2092, 2108, 2111, 2115, 2116, 2125, 2128, 2135, 2141, 2143, 2145, 2146, 2152, 2157, 2159, 2160, 2174, 2180, 2183, 2188, 2191, 2192, 2199, 2200, 2203, 2221, 2225, 2229, 2230, 2233, 2234, 2254, 2258, 2269, 2270, 2277, 2278, 2282, 2286, 2287, 2305, 2306, 2307, 2312, 2315, 2316, 2329, 2357, 2359, 2360, 2367, 2375, 2378, 2383, 2389, 2394, 2398, 2402, 2410, 2420, 2430, 2438, 2439, 2449, 2463, 2474, 2479, 2491, 2496, 2503, 2515, 2517, 2527, 2532, 2533, 2538, 2544, 2547, 2548, 2555, 2568, 2588, 2589, 2594, 2608, 2609, 2615, 2622, 2630, 2643, 2646, 2649, 2650, 2662, 2665, 2666, 2674, 2680, 2681, 2698, 2699, 2708, 2709, 2711, 2715, 2721, 2725, 2726, 2728, 2730, 2731, 2750, 2755, 2756, 2759, 2761, 2762, 2770, 2796, 2797, 2801, 2802, 2810, 2819, 2833, 2834, 2835, 2836, 2838, 2843, 2858, 2861, 2866, 2868, 2890, 2891, 2893, 2894, 2900, 2926, 2929, 2934, 2952, 2954, 2968, 2980, 2984, 2986, 2993, 2998, 3000, 3013, 3016, 3023, 3028, 3029, 3031, 3032, 3036, 3041, 3045, 3061, 3062, 3064, 3065, 3074, 3083, 3100, 3103, 3104, 3105, 3130, 3131, 3134, 3137, 3142, 3149, 3170, 3174, 3177, 3183, 3190, 3193, 3197, 3207, 3209, 3210, 3226, 3227, 3228, 3237, 3238, 3255, 3256, 3262, 3265, 3275, 3278, 3283, 123, 132, 133, 134, 135, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 344, 345, 346, 347, 348, 349, 350, 351, 352, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 425, 426, 427, 428, 429, 482, 483, 484, 485, 511, 512, 513, 514, 515, 516, 517, 760, 817, 818, 819, 820, 821, 822, 823, 824, 832, 833, 834, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1393, 1394, 1395, 1396, 1397, 1398, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1472, 1473, 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521, 1522, 1523, 1524, 1525, 1543, 1544, 1545, 1546, 1547, 1548, 1549, 1550, 1551, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1598, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1684, 1685, 1686, 1687, 1688, 1689, 1690, 1691, 1692, 1693, 1704, 1705, 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1801, 1802, 1803, 1804, 1812, 1813, 1814, 1815, 1816, 1817, 1818, 1819, 1830, 1831, 1832, 1833, 1834, 1835, 1836, 1837, 1838, 1847, 1848, 1849, 1886, 1887, 1888, 1889, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2121, 2122, 2123, 2124, 2125, 2126, 2127, 2164, 2165, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, 2175, 2176, 2177, 2178, 2179, 2320, 2321, 2322, 2323, 2363, 2364, 2365, 2366, 2367, 2368, 2369, 2370, 2371, 2372, 2373, 2374, 2442, 2443, 2444, 2445, 2551, 2552, 2553, 2554, 2670, 2671, 2672, 2673, 2703, 2704, 2705, 2734, 2735, 2736, 2737, 2766, 2767, 2768, 2769, 2770, 2771, 2772, 2773, 2774, 2775, 2776, 2777, 2804, 2805, 2806, 2807, 2808, 2809, 2810, 2811, 2812, 2813, 2814, 2815, 2816, 2817, 2818, 2819, 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2896, 2897, 2898, 2899, 2900, 2901, 2902, 2903, 2904, 2905, 2906, 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 3069, 3070, 3071, 3072, 3073, 3074, 3075, 3076, 3077, 3078, 3079, 3080, 3081, 3082, 3083, 3084, 3085, 3086, 3087, 3088, 3089, 3090, 3091, 3092, 3093, 3094, 3095, 3096, 3133, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 138, 139, 140, 141, 142, 143, 144, 150, 155, 156, 157, 158, 159, 160, 165, 166, 167, 168, 169, 170, 175, 176, 177, 178, 179, 180, 185, 186, 187, 188, 189, 190, 195, 196, 197, 198, 199, 200, 3140, 3144, 3151, 3172, 3173, 3174, 3175, 3176, 3177, 3178, 3179, 3180, 3181, 3195, 3196, 3197, 3198, 3199 ]
1CWE-79
# encoding: utf-8 from __future__ import unicode_literals import unittest from django.template import Context, Template from django.test import TestCase from rest_framework.compat import coreapi, coreschema from rest_framework.relations import Hyperlink from rest_framework.templatetags import rest_framework from rest_framework.templatetags.rest_framework import ( add_nested_class, add_query_param, as_string, break_long_headers, format_value, get_pagination_html, schema_links, urlize_quoted_links ) from rest_framework.test import APIRequestFactory factory = APIRequestFactory() def format_html(html): """ Helper function that formats HTML in order for easier comparison :param html: raw HTML text to be formatted :return: Cleaned HTML with no newlines or spaces """ return html.replace('\n', '').replace(' ', '') class TemplateTagTests(TestCase): def test_add_query_param_with_non_latin_character(self): # Ensure we don't double-escape non-latin characters # that are present in the querystring. # See #1314. request = factory.get("/", {'q': '查询'}) json_url = add_query_param(request, "format", "json") self.assertIn("q=%E6%9F%A5%E8%AF%A2", json_url) self.assertIn("format=json", json_url) def test_format_value_boolean_or_none(self): """ Tests format_value with booleans and None """ self.assertEqual(format_value(True), '<code>true</code>') self.assertEqual(format_value(False), '<code>false</code>') self.assertEqual(format_value(None), '<code>null</code>') def test_format_value_hyperlink(self): """ Tests format_value with a URL """ url = 'http://url.com' name = 'name_of_url' hyperlink = Hyperlink(url, name) self.assertEqual(format_value(hyperlink), '<a href=%s>%s</a>' % (url, name)) def test_format_value_list(self): """ Tests format_value with a list of strings """ list_items = ['item1', 'item2', 'item3'] self.assertEqual(format_value(list_items), '\n item1, item2, item3\n') self.assertEqual(format_value([]), '\n\n') def test_format_value_dict(self): """ Tests format_value with a dict """ test_dict = {'a': 'b'} expected_dict_format = """ <table class="table table-striped"> <tbody> <tr> <th>a</th> <td>b</td> </tr> </tbody> </table>""" self.assertEqual( format_html(format_value(test_dict)), format_html(expected_dict_format) ) def test_format_value_table(self): """ Tests format_value with a list of lists/dicts """ list_of_lists = [['list1'], ['list2'], ['list3']] expected_list_format = """ <tableclass="tabletable-striped"> <tbody> <tr> <th>0</th> <td>list1</td> </tr> <tr> <th>1</th> <td>list2</td> </tr> <tr> <th>2</th> <td>list3</td> </tr> </tbody> </table>""" self.assertEqual( format_html(format_value(list_of_lists)), format_html(expected_list_format) ) expected_dict_format = """ <tableclass="tabletable-striped"> <tbody> <tr> <th>0</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item1</th> <td>value1</td> </tr> </tbody> </table> </td> </tr> <tr> <th>1</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item2</th> <td>value2</td> </tr> </tbody> </table> </td> </tr> <tr> <th>2</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item3</th> <td>value3</td> </tr> </tbody> </table> </td> </tr> </tbody> </table>""" list_of_dicts = [{'item1': 'value1'}, {'item2': 'value2'}, {'item3': 'value3'}] self.assertEqual( format_html(format_value(list_of_dicts)), format_html(expected_dict_format) ) def test_format_value_simple_string(self): """ Tests format_value with a simple string """ simple_string = 'this is an example of a string' self.assertEqual(format_value(simple_string), simple_string) def test_format_value_string_hyperlink(self): """ Tests format_value with a url """ url = 'http://www.example.com' self.assertEqual(format_value(url), '<a href="http://www.example.com">http://www.example.com</a>') def test_format_value_string_email(self): """ Tests format_value with an email address """ email = 'something@somewhere.com' self.assertEqual(format_value(email), '<a href="mailto:something@somewhere.com">something@somewhere.com</a>') def test_format_value_string_newlines(self): """ Tests format_value with a string with newline characters :return: """ text = 'Dear user, \n this is a message \n from,\nsomeone' self.assertEqual(format_value(text), '<pre>Dear user, \n this is a message \n from,\nsomeone</pre>') def test_format_value_object(self): """ Tests that format_value with a object returns the object's __str__ method """ obj = object() self.assertEqual(format_value(obj), obj.__str__()) def test_add_nested_class(self): """ Tests that add_nested_class returns the proper class """ positive_cases = [ [['item']], [{'item1': 'value1'}], {'item1': 'value1'} ] negative_cases = [ ['list'], '', None, True, False ] for case in positive_cases: self.assertEqual(add_nested_class(case), 'class=nested') for case in negative_cases: self.assertEqual(add_nested_class(case), '') def test_as_string_with_none(self): result = as_string(None) assert result == '' def test_get_pagination_html(self): class MockPager(object): def __init__(self): self.called = False def to_html(self): self.called = True pager = MockPager() get_pagination_html(pager) assert pager.called is True def test_break_long_lines(self): header = 'long test header,' * 20 expected_header = '<br> ' + ', <br>'.join(header.split(',')) assert break_long_headers(header) == expected_header class Issue1386Tests(TestCase): """ Covers #1386 """ def test_issue_1386(self): """ Test function urlize_quoted_links with different args """ correct_urls = [ "asdf.com", "asdf.net", "www.as_df.org", "as.d8f.ghj8.gov", ] for i in correct_urls: res = urlize_quoted_links(i) self.assertNotEqual(res, i) self.assertIn(i, res) incorrect_urls = [ "mailto://asdf@fdf.com", "asdf.netnet", ] for i in incorrect_urls: res = urlize_quoted_links(i) self.assertEqual(i, res) # example from issue #1386, this shouldn't raise an exception urlize_quoted_links("asdf:[/p]zxcv.com") def test_smart_urlquote_wrapper_handles_value_error(self): def mock_smart_urlquote(url): raise ValueError old = rest_framework.smart_urlquote rest_framework.smart_urlquote = mock_smart_urlquote assert rest_framework.smart_urlquote_wrapper('test') is None rest_framework.smart_urlquote = old class URLizerTests(TestCase): """ Test if JSON URLs are transformed into links well """ def _urlize_dict_check(self, data): """ For all items in dict test assert that the value is urlized key """ for original, urlized in data.items(): assert urlize_quoted_links(original, nofollow=False) == urlized def test_json_with_url(self): """ Test if JSON URLs are transformed into links well """ data = {} data['"url": "http://api/users/1/", '] = \ '&quot;url&quot;: &quot;<a href="http://api/users/1/">http://api/users/1/</a>&quot;, ' data['"foo_set": [\n "http://api/foos/1/"\n], '] = \ '&quot;foo_set&quot;: [\n &quot;<a href="http://api/foos/1/">http://api/foos/1/</a>&quot;\n], ' self._urlize_dict_check(data) def test_template_render_with_noautoescape(self): """ Test if the autoescape value is getting passed to urlize_quoted_links filter. """ template = Template("{% load rest_framework %}" "{% autoescape off %}{{ content|urlize_quoted_links }}" "{% endautoescape %}") rendered = template.render(Context({'content': '"http://example.com"'})) assert rendered == '"<a href="http://example.com" rel="nofollow">http://example.com</a>"' @unittest.skipUnless(coreapi, 'coreapi is not installed') class SchemaLinksTests(TestCase): def test_schema_with_empty_links(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'list': {} } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 0 def test_single_action(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'list': coreapi.Link( url='/users/', action='get', fields=[] ) } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 1 assert 'list' in flat_links def test_default_actions(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'create': coreapi.Link( url='/users/', action='post', fields=[] ), 'list': coreapi.Link( url='/users/', action='get', fields=[] ), 'read': coreapi.Link( url='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'update': coreapi.Link( url='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 4 assert 'list' in flat_links assert 'create' in flat_links assert 'read' in flat_links assert 'update' in flat_links def test_default_actions_and_single_custom_action(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'create': coreapi.Link( url='/users/', action='post', fields=[] ), 'list': coreapi.Link( url='/users/', action='get', fields=[] ), 'read': coreapi.Link( url='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'update': coreapi.Link( url='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'friends': coreapi.Link( url='/users/{id}/friends', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 5 assert 'list' in flat_links assert 'create' in flat_links assert 'read' in flat_links assert 'update' in flat_links assert 'friends' in flat_links def test_default_actions_and_single_custom_action_two_methods(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'create': coreapi.Link( url='/users/', action='post', fields=[] ), 'list': coreapi.Link( url='/users/', action='get', fields=[] ), 'read': coreapi.Link( url='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'update': coreapi.Link( url='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'friends': { 'list': coreapi.Link( url='/users/{id}/friends', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'create': coreapi.Link( url='/users/{id}/friends', action='post', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 6 assert 'list' in flat_links assert 'create' in flat_links assert 'read' in flat_links assert 'update' in flat_links assert 'friends > list' in flat_links assert 'friends > create' in flat_links def test_multiple_nested_routes(self): schema = coreapi.Document( url='', title='Example API', content={ 'animals': { 'dog': { 'vet': { 'list': coreapi.Link( url='/animals/dog/{id}/vet', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'read': coreapi.Link( url='/animals/dog/{id}', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'cat': { 'list': coreapi.Link( url='/animals/cat/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'create': coreapi.Link( url='/aniamls/cat', action='post', fields=[] ) } } } ) section = schema['animals'] flat_links = schema_links(section) assert len(flat_links) is 4 assert 'cat > create' in flat_links assert 'cat > list' in flat_links assert 'dog > read' in flat_links assert 'dog > vet > list' in flat_links def test_multiple_resources_with_multiple_nested_routes(self): schema = coreapi.Document( url='', title='Example API', content={ 'animals': { 'dog': { 'vet': { 'list': coreapi.Link( url='/animals/dog/{id}/vet', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'read': coreapi.Link( url='/animals/dog/{id}', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'cat': { 'list': coreapi.Link( url='/animals/cat/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'create': coreapi.Link( url='/aniamls/cat', action='post', fields=[] ) } }, 'farmers': { 'silo': { 'soy': { 'list': coreapi.Link( url='/farmers/silo/{id}/soy', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'list': coreapi.Link( url='/farmers/silo', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } } ) section = schema['animals'] flat_links = schema_links(section) assert len(flat_links) is 4 assert 'cat > create' in flat_links assert 'cat > list' in flat_links assert 'dog > read' in flat_links assert 'dog > vet > list' in flat_links section = schema['farmers'] flat_links = schema_links(section) assert len(flat_links) is 2 assert 'silo > list' in flat_links assert 'silo > soy > list' in flat_links
# encoding: utf-8 from __future__ import unicode_literals import unittest from django.template import Context, Template from django.test import TestCase from rest_framework.compat import coreapi, coreschema from rest_framework.relations import Hyperlink from rest_framework.templatetags import rest_framework from rest_framework.templatetags.rest_framework import ( add_nested_class, add_query_param, as_string, break_long_headers, format_value, get_pagination_html, schema_links, urlize_quoted_links ) from rest_framework.test import APIRequestFactory factory = APIRequestFactory() def format_html(html): """ Helper function that formats HTML in order for easier comparison :param html: raw HTML text to be formatted :return: Cleaned HTML with no newlines or spaces """ return html.replace('\n', '').replace(' ', '') class TemplateTagTests(TestCase): def test_add_query_param_with_non_latin_character(self): # Ensure we don't double-escape non-latin characters # that are present in the querystring. # See #1314. request = factory.get("/", {'q': '查询'}) json_url = add_query_param(request, "format", "json") self.assertIn("q=%E6%9F%A5%E8%AF%A2", json_url) self.assertIn("format=json", json_url) def test_format_value_boolean_or_none(self): """ Tests format_value with booleans and None """ self.assertEqual(format_value(True), '<code>true</code>') self.assertEqual(format_value(False), '<code>false</code>') self.assertEqual(format_value(None), '<code>null</code>') def test_format_value_hyperlink(self): """ Tests format_value with a URL """ url = 'http://url.com' name = 'name_of_url' hyperlink = Hyperlink(url, name) self.assertEqual(format_value(hyperlink), '<a href=%s>%s</a>' % (url, name)) def test_format_value_list(self): """ Tests format_value with a list of strings """ list_items = ['item1', 'item2', 'item3'] self.assertEqual(format_value(list_items), '\n item1, item2, item3\n') self.assertEqual(format_value([]), '\n\n') def test_format_value_dict(self): """ Tests format_value with a dict """ test_dict = {'a': 'b'} expected_dict_format = """ <table class="table table-striped"> <tbody> <tr> <th>a</th> <td>b</td> </tr> </tbody> </table>""" self.assertEqual( format_html(format_value(test_dict)), format_html(expected_dict_format) ) def test_format_value_table(self): """ Tests format_value with a list of lists/dicts """ list_of_lists = [['list1'], ['list2'], ['list3']] expected_list_format = """ <tableclass="tabletable-striped"> <tbody> <tr> <th>0</th> <td>list1</td> </tr> <tr> <th>1</th> <td>list2</td> </tr> <tr> <th>2</th> <td>list3</td> </tr> </tbody> </table>""" self.assertEqual( format_html(format_value(list_of_lists)), format_html(expected_list_format) ) expected_dict_format = """ <tableclass="tabletable-striped"> <tbody> <tr> <th>0</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item1</th> <td>value1</td> </tr> </tbody> </table> </td> </tr> <tr> <th>1</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item2</th> <td>value2</td> </tr> </tbody> </table> </td> </tr> <tr> <th>2</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item3</th> <td>value3</td> </tr> </tbody> </table> </td> </tr> </tbody> </table>""" list_of_dicts = [{'item1': 'value1'}, {'item2': 'value2'}, {'item3': 'value3'}] self.assertEqual( format_html(format_value(list_of_dicts)), format_html(expected_dict_format) ) def test_format_value_simple_string(self): """ Tests format_value with a simple string """ simple_string = 'this is an example of a string' self.assertEqual(format_value(simple_string), simple_string) def test_format_value_string_hyperlink(self): """ Tests format_value with a url """ url = 'http://www.example.com' self.assertEqual(format_value(url), '<a href="http://www.example.com">http://www.example.com</a>') def test_format_value_string_email(self): """ Tests format_value with an email address """ email = 'something@somewhere.com' self.assertEqual(format_value(email), '<a href="mailto:something@somewhere.com">something@somewhere.com</a>') def test_format_value_string_newlines(self): """ Tests format_value with a string with newline characters :return: """ text = 'Dear user, \n this is a message \n from,\nsomeone' self.assertEqual(format_value(text), '<pre>Dear user, \n this is a message \n from,\nsomeone</pre>') def test_format_value_object(self): """ Tests that format_value with a object returns the object's __str__ method """ obj = object() self.assertEqual(format_value(obj), obj.__str__()) def test_add_nested_class(self): """ Tests that add_nested_class returns the proper class """ positive_cases = [ [['item']], [{'item1': 'value1'}], {'item1': 'value1'} ] negative_cases = [ ['list'], '', None, True, False ] for case in positive_cases: self.assertEqual(add_nested_class(case), 'class=nested') for case in negative_cases: self.assertEqual(add_nested_class(case), '') def test_as_string_with_none(self): result = as_string(None) assert result == '' def test_get_pagination_html(self): class MockPager(object): def __init__(self): self.called = False def to_html(self): self.called = True pager = MockPager() get_pagination_html(pager) assert pager.called is True def test_break_long_lines(self): header = 'long test header,' * 20 expected_header = '<br> ' + ', <br>'.join(header.split(',')) assert break_long_headers(header) == expected_header class Issue1386Tests(TestCase): """ Covers #1386 """ def test_issue_1386(self): """ Test function urlize_quoted_links with different args """ correct_urls = [ "asdf.com", "asdf.net", "www.as_df.org", "as.d8f.ghj8.gov", ] for i in correct_urls: res = urlize_quoted_links(i) self.assertNotEqual(res, i) self.assertIn(i, res) incorrect_urls = [ "mailto://asdf@fdf.com", "asdf.netnet", ] for i in incorrect_urls: res = urlize_quoted_links(i) self.assertEqual(i, res) # example from issue #1386, this shouldn't raise an exception urlize_quoted_links("asdf:[/p]zxcv.com") def test_smart_urlquote_wrapper_handles_value_error(self): def mock_smart_urlquote(url): raise ValueError old = rest_framework.smart_urlquote rest_framework.smart_urlquote = mock_smart_urlquote assert rest_framework.smart_urlquote_wrapper('test') is None rest_framework.smart_urlquote = old class URLizerTests(TestCase): """ Test if JSON URLs are transformed into links well """ def _urlize_dict_check(self, data): """ For all items in dict test assert that the value is urlized key """ for original, urlized in data.items(): assert urlize_quoted_links(original, nofollow=False) == urlized def test_json_with_url(self): """ Test if JSON URLs are transformed into links well """ data = {} data['"url": "http://api/users/1/", '] = \ '&quot;url&quot;: &quot;<a href="http://api/users/1/">http://api/users/1/</a>&quot;, ' data['"foo_set": [\n "http://api/foos/1/"\n], '] = \ '&quot;foo_set&quot;: [\n &quot;<a href="http://api/foos/1/">http://api/foos/1/</a>&quot;\n], ' self._urlize_dict_check(data) def test_template_render_with_autoescape(self): """ Test that HTML is correctly escaped in Browsable API views. """ template = Template("{% load rest_framework %}{{ content|urlize_quoted_links }}") rendered = template.render(Context({'content': '<script>alert()</script> http://example.com'})) assert rendered == '&lt;script&gt;alert()&lt;/script&gt;' \ ' <a href="http://example.com" rel="nofollow">http://example.com</a>' def test_template_render_with_noautoescape(self): """ Test if the autoescape value is getting passed to urlize_quoted_links filter. """ template = Template("{% load rest_framework %}" "{% autoescape off %}{{ content|urlize_quoted_links }}" "{% endautoescape %}") rendered = template.render(Context({'content': '<b> "http://example.com" </b>'})) assert rendered == '<b> "<a href="http://example.com" rel="nofollow">http://example.com</a>" </b>' @unittest.skipUnless(coreapi, 'coreapi is not installed') class SchemaLinksTests(TestCase): def test_schema_with_empty_links(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'list': {} } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 0 def test_single_action(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'list': coreapi.Link( url='/users/', action='get', fields=[] ) } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 1 assert 'list' in flat_links def test_default_actions(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'create': coreapi.Link( url='/users/', action='post', fields=[] ), 'list': coreapi.Link( url='/users/', action='get', fields=[] ), 'read': coreapi.Link( url='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'update': coreapi.Link( url='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 4 assert 'list' in flat_links assert 'create' in flat_links assert 'read' in flat_links assert 'update' in flat_links def test_default_actions_and_single_custom_action(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'create': coreapi.Link( url='/users/', action='post', fields=[] ), 'list': coreapi.Link( url='/users/', action='get', fields=[] ), 'read': coreapi.Link( url='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'update': coreapi.Link( url='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'friends': coreapi.Link( url='/users/{id}/friends', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 5 assert 'list' in flat_links assert 'create' in flat_links assert 'read' in flat_links assert 'update' in flat_links assert 'friends' in flat_links def test_default_actions_and_single_custom_action_two_methods(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'create': coreapi.Link( url='/users/', action='post', fields=[] ), 'list': coreapi.Link( url='/users/', action='get', fields=[] ), 'read': coreapi.Link( url='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'update': coreapi.Link( url='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'friends': { 'list': coreapi.Link( url='/users/{id}/friends', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'create': coreapi.Link( url='/users/{id}/friends', action='post', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 6 assert 'list' in flat_links assert 'create' in flat_links assert 'read' in flat_links assert 'update' in flat_links assert 'friends > list' in flat_links assert 'friends > create' in flat_links def test_multiple_nested_routes(self): schema = coreapi.Document( url='', title='Example API', content={ 'animals': { 'dog': { 'vet': { 'list': coreapi.Link( url='/animals/dog/{id}/vet', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'read': coreapi.Link( url='/animals/dog/{id}', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'cat': { 'list': coreapi.Link( url='/animals/cat/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'create': coreapi.Link( url='/aniamls/cat', action='post', fields=[] ) } } } ) section = schema['animals'] flat_links = schema_links(section) assert len(flat_links) is 4 assert 'cat > create' in flat_links assert 'cat > list' in flat_links assert 'dog > read' in flat_links assert 'dog > vet > list' in flat_links def test_multiple_resources_with_multiple_nested_routes(self): schema = coreapi.Document( url='', title='Example API', content={ 'animals': { 'dog': { 'vet': { 'list': coreapi.Link( url='/animals/dog/{id}/vet', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'read': coreapi.Link( url='/animals/dog/{id}', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'cat': { 'list': coreapi.Link( url='/animals/cat/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'create': coreapi.Link( url='/aniamls/cat', action='post', fields=[] ) } }, 'farmers': { 'silo': { 'soy': { 'list': coreapi.Link( url='/farmers/silo/{id}/soy', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) }, 'list': coreapi.Link( url='/farmers/silo', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } } ) section = schema['animals'] flat_links = schema_links(section) assert len(flat_links) is 4 assert 'cat > create' in flat_links assert 'cat > list' in flat_links assert 'dog > read' in flat_links assert 'dog > vet > list' in flat_links section = schema['farmers'] flat_links = schema_links(section) assert len(flat_links) is 2 assert 'silo > list' in flat_links assert 'silo > soy > list' in flat_links
xss
{ "code": [ " rendered = template.render(Context({'content': '\"http://example.com\"'}))", " assert rendered == '\"<a href=\"http://example.com\" rel=\"nofollow\">http://example.com</a>\"'" ], "line_no": [ 315, 316 ] }
{ "code": [ " def test_template_render_with_autoescape(self):", " Test that HTML is correctly escaped in Browsable API views.", " template = Template(\"{% load rest_framework %}{{ content|urlize_quoted_links }}\")", " rendered = template.render(Context({'content': '<script>alert()</script> http://example.com'}))", " assert rendered == '&lt;script&gt;alert()&lt;/script&gt;' \\", " ' <a href=\"http://example.com\" rel=\"nofollow\">http://example.com</a>'", " rendered = template.render(Context({'content': '<b> \"http://example.com\" </b>'}))", " assert rendered == '<b> \"<a href=\"http://example.com\" rel=\"nofollow\">http://example.com</a>\" </b>'" ], "line_no": [ 308, 310, 312, 313, 314, 315, 324, 325 ] }
from __future__ import unicode_literals import unittest from django.template import Context, Template from django.test import TestCase from rest_framework.compat import coreapi, coreschema from rest_framework.relations import Hyperlink from rest_framework.templatetags import .rest_framework from rest_framework.templatetags.rest_framework import ( add_nested_class, add_query_param, as_string, break_long_headers, format_value, get_pagination_html, schema_links, urlize_quoted_links ) from rest_framework.test import APIRequestFactory VAR_0 = APIRequestFactory() def FUNC_0(VAR_1): return VAR_1.replace('\n', '').replace(' ', '') class CLASS_0(TestCase): def FUNC_1(self): VAR_3 = VAR_0.get("/", {'q': '查询'}) VAR_4 = add_query_param(VAR_3, "format", "json") self.assertIn("q=%E6%9F%A5%E8%AF%A2", VAR_4) self.assertIn("format=json", VAR_4) def FUNC_2(self): self.assertEqual(format_value(True), '<code>true</code>') self.assertEqual(format_value(False), '<code>false</code>') self.assertEqual(format_value(None), '<code>null</code>') def FUNC_3(self): VAR_5 = 'http://VAR_5.com' VAR_6 = 'name_of_url' VAR_7 = Hyperlink(VAR_5, VAR_6) self.assertEqual(format_value(VAR_7), '<a href=%s>%s</a>' % (VAR_5, VAR_6)) def FUNC_4(self): VAR_8 = ['item1', 'item2', 'item3'] self.assertEqual(format_value(VAR_8), '\n item1, item2, item3\n') self.assertEqual(format_value([]), '\n\n') def FUNC_5(self): VAR_9 = {'a': 'b'} VAR_10 = """ <table class="table table-striped"> <tbody> <tr> <th>a</th> <td>b</td> </tr> </tbody> </table>""" self.assertEqual( FUNC_0(format_value(VAR_9)), FUNC_0(VAR_10) ) def FUNC_6(self): VAR_11 = [['list1'], ['list2'], ['list3']] VAR_12 = """ <tableclass="tabletable-striped"> <tbody> <tr> <th>0</th> <td>list1</td> </tr> <tr> <th>1</th> <td>list2</td> </tr> <tr> <th>2</th> <td>list3</td> </tr> </tbody> </table>""" self.assertEqual( FUNC_0(format_value(VAR_11)), FUNC_0(VAR_12) ) VAR_10 = """ <tableclass="tabletable-striped"> <tbody> <tr> <th>0</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item1</th> <td>value1</td> </tr> </tbody> </table> </td> </tr> <tr> <th>1</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item2</th> <td>value2</td> </tr> </tbody> </table> </td> </tr> <tr> <th>2</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item3</th> <td>value3</td> </tr> </tbody> </table> </td> </tr> </tbody> </table>""" VAR_13 = [{'item1': 'value1'}, {'item2': 'value2'}, {'item3': 'value3'}] self.assertEqual( FUNC_0(format_value(VAR_13)), FUNC_0(VAR_10) ) def FUNC_7(self): VAR_14 = 'this is an example of a string' self.assertEqual(format_value(VAR_14), simple_string) def FUNC_8(self): VAR_5 = 'http://www.example.com' self.assertEqual(format_value(VAR_5), '<a href="http://www.example.com">http://www.example.com</a>') def FUNC_9(self): VAR_15 = 'something@somewhere.com' self.assertEqual(format_value(VAR_15), '<a href="mailto:something@somewhere.com">something@somewhere.com</a>') def FUNC_10(self): VAR_16 = 'Dear user, \n this is a message \n from,\nsomeone' self.assertEqual(format_value(VAR_16), '<pre>Dear user, \n this is a message \n from,\nsomeone</pre>') def FUNC_11(self): VAR_17 = object() self.assertEqual(format_value(VAR_17), obj.__str__()) def FUNC_12(self): VAR_18 = [ [['item']], [{'item1': 'value1'}], {'item1': 'value1'} ] VAR_19 = [ ['list'], '', None, True, False ] for case in VAR_18: self.assertEqual(add_nested_class(case), 'class=nested') for case in VAR_19: self.assertEqual(add_nested_class(case), '') def FUNC_13(self): VAR_20 = as_string(None) assert VAR_20 == '' def FUNC_14(self): class CLASS_4(object): def __init__(self): self.called = False def FUNC_29(self): self.called = True VAR_21 = CLASS_4() get_pagination_html(VAR_21) assert VAR_21.called is True def FUNC_15(self): VAR_22 = 'long test VAR_22,' * 20 VAR_23 = '<br> ' + ', <br>'.join(VAR_22.split(',')) assert break_long_headers(VAR_22) == VAR_23 class CLASS_1(TestCase): def FUNC_16(self): VAR_24 = [ "asdf.com", "asdf.net", "www.as_df.org", "as.d8f.ghj8.gov", ] for i in VAR_24: VAR_32 = urlize_quoted_links(i) self.assertNotEqual(VAR_32, i) self.assertIn(i, VAR_32) VAR_25 = [ "mailto://asdf@fdf.com", "asdf.netnet", ] for i in VAR_25: VAR_32 = urlize_quoted_links(i) self.assertEqual(i, VAR_32) urlize_quoted_links("asdf:[/p]zxcv.com") def FUNC_17(self): def FUNC_28(VAR_5): raise ValueError VAR_26 = rest_framework.smart_urlquote rest_framework.smart_urlquote = FUNC_28 assert rest_framework.smart_urlquote_wrapper('test') is None rest_framework.smart_urlquote = VAR_26 class CLASS_2(TestCase): def FUNC_18(self, VAR_2): for original, urlized in VAR_2.items(): assert urlize_quoted_links(original, nofollow=False) == urlized def FUNC_19(self): VAR_2 = {} VAR_2['"url": "http://api/users/1/", '] = \ '&quot;VAR_5&quot;: &quot;<a href="http://api/users/1/">http://api/users/1/</a>&quot;, ' VAR_2['"foo_set": [\n "http://api/foos/1/"\n], '] = \ '&quot;foo_set&quot;: [\n &quot;<a href="http://api/foos/1/">http://api/foos/1/</a>&quot;\n], ' self._urlize_dict_check(VAR_2) def FUNC_20(self): VAR_27 = Template("{% load rest_framework %}" "{% autoescape off %}{{ content|urlize_quoted_links }}" "{% endautoescape %}") VAR_28 = VAR_27.render(Context({'content': '"http://example.com"'})) assert VAR_28 == '"<a href="http://example.com" rel="nofollow">http://example.com</a>"' @unittest.skipUnless(coreapi, 'coreapi is not installed') class CLASS_3(TestCase): def FUNC_21(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'list': {} } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 0 def FUNC_22(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'list': coreapi.Link( VAR_5='/users/', action='get', fields=[] ) } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 1 assert 'list' in VAR_31 def FUNC_23(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'create': coreapi.Link( VAR_5='/users/', action='post', fields=[] ), 'list': coreapi.Link( VAR_5='/users/', action='get', fields=[] ), 'read': coreapi.Link( VAR_5='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'update': coreapi.Link( VAR_5='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 4 assert 'list' in VAR_31 assert 'create' in VAR_31 assert 'read' in VAR_31 assert 'update' in VAR_31 def FUNC_24(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'create': coreapi.Link( VAR_5='/users/', action='post', fields=[] ), 'list': coreapi.Link( VAR_5='/users/', action='get', fields=[] ), 'read': coreapi.Link( VAR_5='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'update': coreapi.Link( VAR_5='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'friends': coreapi.Link( VAR_5='/users/{id}/friends', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 5 assert 'list' in VAR_31 assert 'create' in VAR_31 assert 'read' in VAR_31 assert 'update' in VAR_31 assert 'friends' in VAR_31 def FUNC_25(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'create': coreapi.Link( VAR_5='/users/', action='post', fields=[] ), 'list': coreapi.Link( VAR_5='/users/', action='get', fields=[] ), 'read': coreapi.Link( VAR_5='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'update': coreapi.Link( VAR_5='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'friends': { 'list': coreapi.Link( VAR_5='/users/{id}/friends', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'create': coreapi.Link( VAR_5='/users/{id}/friends', action='post', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) } } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 6 assert 'list' in VAR_31 assert 'create' in VAR_31 assert 'read' in VAR_31 assert 'update' in VAR_31 assert 'friends > list' in VAR_31 assert 'friends > create' in VAR_31 def FUNC_26(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'animals': { 'dog': { 'vet': { 'list': coreapi.Link( VAR_5='/animals/dog/{id}/vet', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'read': coreapi.Link( VAR_5='/animals/dog/{id}', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'cat': { 'list': coreapi.Link( VAR_5='/animals/cat/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'create': coreapi.Link( VAR_5='/aniamls/cat', action='post', fields=[] ) } } } ) VAR_30 = VAR_29['animals'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 4 assert 'cat > create' in VAR_31 assert 'cat > list' in VAR_31 assert 'dog > read' in VAR_31 assert 'dog > vet > list' in VAR_31 def FUNC_27(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'animals': { 'dog': { 'vet': { 'list': coreapi.Link( VAR_5='/animals/dog/{id}/vet', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'read': coreapi.Link( VAR_5='/animals/dog/{id}', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'cat': { 'list': coreapi.Link( VAR_5='/animals/cat/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'create': coreapi.Link( VAR_5='/aniamls/cat', action='post', fields=[] ) } }, 'farmers': { 'silo': { 'soy': { 'list': coreapi.Link( VAR_5='/farmers/silo/{id}/soy', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'list': coreapi.Link( VAR_5='/farmers/silo', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) } } } ) VAR_30 = VAR_29['animals'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 4 assert 'cat > create' in VAR_31 assert 'cat > list' in VAR_31 assert 'dog > read' in VAR_31 assert 'dog > vet > list' in VAR_31 VAR_30 = VAR_29['farmers'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 2 assert 'silo > list' in VAR_31 assert 'silo > soy > list' in VAR_31
from __future__ import unicode_literals import unittest from django.template import Context, Template from django.test import TestCase from rest_framework.compat import coreapi, coreschema from rest_framework.relations import Hyperlink from rest_framework.templatetags import .rest_framework from rest_framework.templatetags.rest_framework import ( add_nested_class, add_query_param, as_string, break_long_headers, format_value, get_pagination_html, schema_links, urlize_quoted_links ) from rest_framework.test import APIRequestFactory VAR_0 = APIRequestFactory() def FUNC_0(VAR_1): return VAR_1.replace('\n', '').replace(' ', '') class CLASS_0(TestCase): def FUNC_1(self): VAR_3 = VAR_0.get("/", {'q': '查询'}) VAR_4 = add_query_param(VAR_3, "format", "json") self.assertIn("q=%E6%9F%A5%E8%AF%A2", VAR_4) self.assertIn("format=json", VAR_4) def FUNC_2(self): self.assertEqual(format_value(True), '<code>true</code>') self.assertEqual(format_value(False), '<code>false</code>') self.assertEqual(format_value(None), '<code>null</code>') def FUNC_3(self): VAR_5 = 'http://VAR_5.com' VAR_6 = 'name_of_url' VAR_7 = Hyperlink(VAR_5, VAR_6) self.assertEqual(format_value(VAR_7), '<a href=%s>%s</a>' % (VAR_5, VAR_6)) def FUNC_4(self): VAR_8 = ['item1', 'item2', 'item3'] self.assertEqual(format_value(VAR_8), '\n item1, item2, item3\n') self.assertEqual(format_value([]), '\n\n') def FUNC_5(self): VAR_9 = {'a': 'b'} VAR_10 = """ <table class="table table-striped"> <tbody> <tr> <th>a</th> <td>b</td> </tr> </tbody> </table>""" self.assertEqual( FUNC_0(format_value(VAR_9)), FUNC_0(VAR_10) ) def FUNC_6(self): VAR_11 = [['list1'], ['list2'], ['list3']] VAR_12 = """ <tableclass="tabletable-striped"> <tbody> <tr> <th>0</th> <td>list1</td> </tr> <tr> <th>1</th> <td>list2</td> </tr> <tr> <th>2</th> <td>list3</td> </tr> </tbody> </table>""" self.assertEqual( FUNC_0(format_value(VAR_11)), FUNC_0(VAR_12) ) VAR_10 = """ <tableclass="tabletable-striped"> <tbody> <tr> <th>0</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item1</th> <td>value1</td> </tr> </tbody> </table> </td> </tr> <tr> <th>1</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item2</th> <td>value2</td> </tr> </tbody> </table> </td> </tr> <tr> <th>2</th> <td> <tableclass="tabletable-striped"> <tbody> <tr> <th>item3</th> <td>value3</td> </tr> </tbody> </table> </td> </tr> </tbody> </table>""" VAR_13 = [{'item1': 'value1'}, {'item2': 'value2'}, {'item3': 'value3'}] self.assertEqual( FUNC_0(format_value(VAR_13)), FUNC_0(VAR_10) ) def FUNC_7(self): VAR_14 = 'this is an example of a string' self.assertEqual(format_value(VAR_14), simple_string) def FUNC_8(self): VAR_5 = 'http://www.example.com' self.assertEqual(format_value(VAR_5), '<a href="http://www.example.com">http://www.example.com</a>') def FUNC_9(self): VAR_15 = 'something@somewhere.com' self.assertEqual(format_value(VAR_15), '<a href="mailto:something@somewhere.com">something@somewhere.com</a>') def FUNC_10(self): VAR_16 = 'Dear user, \n this is a message \n from,\nsomeone' self.assertEqual(format_value(VAR_16), '<pre>Dear user, \n this is a message \n from,\nsomeone</pre>') def FUNC_11(self): VAR_17 = object() self.assertEqual(format_value(VAR_17), obj.__str__()) def FUNC_12(self): VAR_18 = [ [['item']], [{'item1': 'value1'}], {'item1': 'value1'} ] VAR_19 = [ ['list'], '', None, True, False ] for case in VAR_18: self.assertEqual(add_nested_class(case), 'class=nested') for case in VAR_19: self.assertEqual(add_nested_class(case), '') def FUNC_13(self): VAR_20 = as_string(None) assert VAR_20 == '' def FUNC_14(self): class CLASS_4(object): def __init__(self): self.called = False def FUNC_30(self): self.called = True VAR_21 = CLASS_4() get_pagination_html(VAR_21) assert VAR_21.called is True def FUNC_15(self): VAR_22 = 'long test VAR_22,' * 20 VAR_23 = '<br> ' + ', <br>'.join(VAR_22.split(',')) assert break_long_headers(VAR_22) == VAR_23 class CLASS_1(TestCase): def FUNC_16(self): VAR_24 = [ "asdf.com", "asdf.net", "www.as_df.org", "as.d8f.ghj8.gov", ] for i in VAR_24: VAR_32 = urlize_quoted_links(i) self.assertNotEqual(VAR_32, i) self.assertIn(i, VAR_32) VAR_25 = [ "mailto://asdf@fdf.com", "asdf.netnet", ] for i in VAR_25: VAR_32 = urlize_quoted_links(i) self.assertEqual(i, VAR_32) urlize_quoted_links("asdf:[/p]zxcv.com") def FUNC_17(self): def FUNC_29(VAR_5): raise ValueError VAR_26 = rest_framework.smart_urlquote rest_framework.smart_urlquote = FUNC_29 assert rest_framework.smart_urlquote_wrapper('test') is None rest_framework.smart_urlquote = VAR_26 class CLASS_2(TestCase): def FUNC_18(self, VAR_2): for original, urlized in VAR_2.items(): assert urlize_quoted_links(original, nofollow=False) == urlized def FUNC_19(self): VAR_2 = {} VAR_2['"url": "http://api/users/1/", '] = \ '&quot;VAR_5&quot;: &quot;<a href="http://api/users/1/">http://api/users/1/</a>&quot;, ' VAR_2['"foo_set": [\n "http://api/foos/1/"\n], '] = \ '&quot;foo_set&quot;: [\n &quot;<a href="http://api/foos/1/">http://api/foos/1/</a>&quot;\n], ' self._urlize_dict_check(VAR_2) def FUNC_20(self): VAR_27 = Template("{% load rest_framework %}{{ content|urlize_quoted_links }}") VAR_28 = VAR_27.render(Context({'content': '<script>alert()</script> http://example.com'})) assert VAR_28 == '&lt;script&gt;alert()&lt;/script&gt;' \ ' <a href="http://example.com" rel="nofollow">http://example.com</a>' def FUNC_21(self): VAR_27 = Template("{% load rest_framework %}" "{% autoescape off %}{{ content|urlize_quoted_links }}" "{% endautoescape %}") VAR_28 = VAR_27.render(Context({'content': '<b> "http://example.com" </b>'})) assert VAR_28 == '<b> "<a href="http://example.com" rel="nofollow">http://example.com</a>" </b>' @unittest.skipUnless(coreapi, 'coreapi is not installed') class CLASS_3(TestCase): def FUNC_22(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'list': {} } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 0 def FUNC_23(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'list': coreapi.Link( VAR_5='/users/', action='get', fields=[] ) } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 1 assert 'list' in VAR_31 def FUNC_24(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'create': coreapi.Link( VAR_5='/users/', action='post', fields=[] ), 'list': coreapi.Link( VAR_5='/users/', action='get', fields=[] ), 'read': coreapi.Link( VAR_5='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'update': coreapi.Link( VAR_5='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 4 assert 'list' in VAR_31 assert 'create' in VAR_31 assert 'read' in VAR_31 assert 'update' in VAR_31 def FUNC_25(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'create': coreapi.Link( VAR_5='/users/', action='post', fields=[] ), 'list': coreapi.Link( VAR_5='/users/', action='get', fields=[] ), 'read': coreapi.Link( VAR_5='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'update': coreapi.Link( VAR_5='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'friends': coreapi.Link( VAR_5='/users/{id}/friends', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 5 assert 'list' in VAR_31 assert 'create' in VAR_31 assert 'read' in VAR_31 assert 'update' in VAR_31 assert 'friends' in VAR_31 def FUNC_26(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'users': { 'create': coreapi.Link( VAR_5='/users/', action='post', fields=[] ), 'list': coreapi.Link( VAR_5='/users/', action='get', fields=[] ), 'read': coreapi.Link( VAR_5='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'update': coreapi.Link( VAR_5='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'friends': { 'list': coreapi.Link( VAR_5='/users/{id}/friends', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'create': coreapi.Link( VAR_5='/users/{id}/friends', action='post', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) } } } ) VAR_30 = VAR_29['users'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 6 assert 'list' in VAR_31 assert 'create' in VAR_31 assert 'read' in VAR_31 assert 'update' in VAR_31 assert 'friends > list' in VAR_31 assert 'friends > create' in VAR_31 def FUNC_27(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'animals': { 'dog': { 'vet': { 'list': coreapi.Link( VAR_5='/animals/dog/{id}/vet', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'read': coreapi.Link( VAR_5='/animals/dog/{id}', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'cat': { 'list': coreapi.Link( VAR_5='/animals/cat/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'create': coreapi.Link( VAR_5='/aniamls/cat', action='post', fields=[] ) } } } ) VAR_30 = VAR_29['animals'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 4 assert 'cat > create' in VAR_31 assert 'cat > list' in VAR_31 assert 'dog > read' in VAR_31 assert 'dog > vet > list' in VAR_31 def FUNC_28(self): VAR_29 = coreapi.Document( VAR_5='', title='Example API', content={ 'animals': { 'dog': { 'vet': { 'list': coreapi.Link( VAR_5='/animals/dog/{id}/vet', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'read': coreapi.Link( VAR_5='/animals/dog/{id}', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'cat': { 'list': coreapi.Link( VAR_5='/animals/cat/', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ), 'create': coreapi.Link( VAR_5='/aniamls/cat', action='post', fields=[] ) } }, 'farmers': { 'silo': { 'soy': { 'list': coreapi.Link( VAR_5='/farmers/silo/{id}/soy', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) }, 'list': coreapi.Link( VAR_5='/farmers/silo', action='get', fields=[ coreapi.Field('id', required=True, location='path', VAR_29=coreschema.String()) ] ) } } } ) VAR_30 = VAR_29['animals'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 4 assert 'cat > create' in VAR_31 assert 'cat > list' in VAR_31 assert 'dog > read' in VAR_31 assert 'dog > vet > list' in VAR_31 VAR_30 = VAR_29['farmers'] VAR_31 = schema_links(VAR_30) assert len(VAR_31) is 2 assert 'silo > list' in VAR_31 assert 'silo > soy > list' in VAR_31
[ 1, 3, 5, 8, 17, 19, 20, 28, 29, 31, 33, 34, 35, 40, 48, 57, 65, 84, 111, 156, 162, 169, 176, 183, 191, 198, 208, 216, 219, 222, 226, 231, 234, 238, 243, 244, 249, 264, 272, 273, 275, 279, 284, 285, 296, 307, 317, 318, 321, 335, 354, 395, 444, 503, 552, 621, 627, 22, 23, 24, 25, 26, 246, 247, 248, 287, 288, 289, 42, 43, 44, 50, 51, 52, 59, 60, 61, 67, 68, 69, 86, 87, 88, 164, 165, 166, 171, 172, 173, 178, 179, 180, 185, 186, 187, 188, 193, 194, 195, 200, 201, 202, 251, 252, 253, 291, 292, 293, 298, 299, 300, 309, 310, 311 ]
[ 1, 3, 5, 8, 17, 19, 20, 28, 29, 31, 33, 34, 35, 40, 48, 57, 65, 84, 111, 156, 162, 169, 176, 183, 191, 198, 208, 216, 219, 222, 226, 231, 234, 238, 243, 244, 249, 264, 272, 273, 275, 279, 284, 285, 296, 307, 316, 326, 327, 330, 344, 363, 404, 453, 512, 561, 630, 636, 22, 23, 24, 25, 26, 246, 247, 248, 287, 288, 289, 42, 43, 44, 50, 51, 52, 59, 60, 61, 67, 68, 69, 86, 87, 88, 164, 165, 166, 171, 172, 173, 178, 179, 180, 185, 186, 187, 188, 193, 194, 195, 200, 201, 202, 251, 252, 253, 291, 292, 293, 298, 299, 300, 309, 310, 311, 318, 319, 320 ]
1CWE-79
from __future__ import unicode_literals import base64 import calendar import datetime import re import sys try: from urllib import parse as urllib_parse except ImportError: # Python 2 import urllib as urllib_parse import urlparse urllib_parse.urlparse = urlparse.urlparse from binascii import Error as BinasciiError from email.utils import formatdate from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str, force_text from django.utils.functional import allow_lazy from django.utils import six ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"') MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() __D = r'(?P<day>\d{2})' __D2 = r'(?P<day>[ \d]\d)' __M = r'(?P<mon>\w{3})' __Y = r'(?P<year>\d{4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) def urlquote(url, safe='/'): """ A version of Python's urllib.quote() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(urllib_parse.quote(force_str(url), force_str(safe))) urlquote = allow_lazy(urlquote, six.text_type) def urlquote_plus(url, safe=''): """ A version of Python's urllib.quote_plus() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(urllib_parse.quote_plus(force_str(url), force_str(safe))) urlquote_plus = allow_lazy(urlquote_plus, six.text_type) def urlunquote(quoted_url): """ A wrapper for Python's urllib.unquote() function that can operate on the result of django.utils.http.urlquote(). """ return force_text(urllib_parse.unquote(force_str(quoted_url))) urlunquote = allow_lazy(urlunquote, six.text_type) def urlunquote_plus(quoted_url): """ A wrapper for Python's urllib.unquote_plus() function that can operate on the result of django.utils.http.urlquote_plus(). """ return force_text(urllib_parse.unquote_plus(force_str(quoted_url))) urlunquote_plus = allow_lazy(urlunquote_plus, six.text_type) def urlencode(query, doseq=0): """ A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasattr(query, 'items'): query = query.items() return urllib_parse.urlencode( [(force_str(k), [force_str(i) for i in v] if isinstance(v, (list,tuple)) else force_str(v)) for k, v in query], doseq) def cookie_date(epoch_seconds=None): """ Formats the time to ensure compatibility with Netscape's cookie standard. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy, DD-Mon-YYYY HH:MM:SS GMT'. """ rfcdate = formatdate(epoch_seconds) return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25]) def http_date(epoch_seconds=None): """ Formats the time to match the RFC1123 date format as specified by HTTP RFC2616 section 3.3.1. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'. """ return formatdate(epoch_seconds, usegmt=True) def parse_http_date(date): """ Parses a date format as specified by HTTP RFC2616 section 3.3.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Returns an integer expressed in seconds since the epoch, in UTC. """ # emails.Util.parsedate does the job for RFC1123 dates; unfortunately # RFC2616 makes it mandatory to support RFC850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: year = int(m.group('year')) if year < 100: if year < 70: year += 2000 else: year += 1900 month = MONTHS.index(m.group('mon').lower()) + 1 day = int(m.group('day')) hour = int(m.group('hour')) min = int(m.group('min')) sec = int(m.group('sec')) result = datetime.datetime(year, month, day, hour, min, sec) return calendar.timegm(result.utctimetuple()) except Exception: six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2]) def parse_http_date_safe(date): """ Same as parse_http_date, but returns None if the input is invalid. """ try: return parse_http_date(date) except Exception: pass # Base 36 functions: useful for generating compact URLs def base36_to_int(s): """ Converts a base 36 string to an ``int``. Raises ``ValueError` if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is long than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-bit integer) if len(s) > 13: raise ValueError("Base36 input too large") value = int(s, 36) # ... then do a final check that the value will fit into an int to avoid # returning a long (#15067). The long type was removed in Python 3. if not six.PY3 and value > sys.maxint: raise ValueError("Base36 input too large") return value def int_to_base36(i): """ Converts an integer to a base36 string """ digits = "0123456789abcdefghijklmnopqrstuvwxyz" factor = 0 if i < 0: raise ValueError("Negative base36 conversion input.") if not six.PY3: if not isinstance(i, six.integer_types): raise TypeError("Non-integer base36 conversion input.") if i > sys.maxint: raise ValueError("Base36 conversion input too large.") # Find starting factor while True: factor += 1 if i < 36 ** factor: factor -= 1 break base36 = [] # Construct base36 representation while factor >= 0: j = 36 ** factor base36.append(digits[i // j]) i = i % j factor -= 1 return ''.join(base36) def urlsafe_base64_encode(s): """ Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b'\n=') def urlsafe_base64_decode(s): """ Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped. """ s = s.encode('utf-8') # base64encode should only return ASCII. try: return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'=')) except (LookupError, BinasciiError) as e: raise ValueError(e) def parse_etags(etag_str): """ Parses a string with one or several etags passed in If-None-Match and If-Match headers by the rules in RFC 2616. Returns a list of etags without surrounding double quotes (") and unescaped from \<CHAR>. """ etags = ETAG_MATCH.findall(etag_str) if not etags: # etag_str has wrong format, treat it as an opaque string then return [etag_str] etags = [e.encode('ascii').decode('unicode_escape') for e in etags] return etags def quote_etag(etag): """ Wraps a string in double quotes escaping contents as necessary. """ return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"') def same_origin(url1, url2): """ Checks if two URLs are 'same-origin' """ p1, p2 = urllib_parse.urlparse(url1), urllib_parse.urlparse(url2) try: return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port) except ValueError: return False def is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host). Always returns ``False`` on an empty url. """ if not url: return False netloc = urllib_parse.urlparse(url)[1] return not netloc or netloc == host
from __future__ import unicode_literals import base64 import calendar import datetime import re import sys try: from urllib import parse as urllib_parse except ImportError: # Python 2 import urllib as urllib_parse import urlparse urllib_parse.urlparse = urlparse.urlparse from binascii import Error as BinasciiError from email.utils import formatdate from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str, force_text from django.utils.functional import allow_lazy from django.utils import six ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"') MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() __D = r'(?P<day>\d{2})' __D2 = r'(?P<day>[ \d]\d)' __M = r'(?P<mon>\w{3})' __Y = r'(?P<year>\d{4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) def urlquote(url, safe='/'): """ A version of Python's urllib.quote() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(urllib_parse.quote(force_str(url), force_str(safe))) urlquote = allow_lazy(urlquote, six.text_type) def urlquote_plus(url, safe=''): """ A version of Python's urllib.quote_plus() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(urllib_parse.quote_plus(force_str(url), force_str(safe))) urlquote_plus = allow_lazy(urlquote_plus, six.text_type) def urlunquote(quoted_url): """ A wrapper for Python's urllib.unquote() function that can operate on the result of django.utils.http.urlquote(). """ return force_text(urllib_parse.unquote(force_str(quoted_url))) urlunquote = allow_lazy(urlunquote, six.text_type) def urlunquote_plus(quoted_url): """ A wrapper for Python's urllib.unquote_plus() function that can operate on the result of django.utils.http.urlquote_plus(). """ return force_text(urllib_parse.unquote_plus(force_str(quoted_url))) urlunquote_plus = allow_lazy(urlunquote_plus, six.text_type) def urlencode(query, doseq=0): """ A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasattr(query, 'items'): query = query.items() return urllib_parse.urlencode( [(force_str(k), [force_str(i) for i in v] if isinstance(v, (list,tuple)) else force_str(v)) for k, v in query], doseq) def cookie_date(epoch_seconds=None): """ Formats the time to ensure compatibility with Netscape's cookie standard. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy, DD-Mon-YYYY HH:MM:SS GMT'. """ rfcdate = formatdate(epoch_seconds) return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25]) def http_date(epoch_seconds=None): """ Formats the time to match the RFC1123 date format as specified by HTTP RFC2616 section 3.3.1. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'. """ return formatdate(epoch_seconds, usegmt=True) def parse_http_date(date): """ Parses a date format as specified by HTTP RFC2616 section 3.3.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Returns an integer expressed in seconds since the epoch, in UTC. """ # emails.Util.parsedate does the job for RFC1123 dates; unfortunately # RFC2616 makes it mandatory to support RFC850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: year = int(m.group('year')) if year < 100: if year < 70: year += 2000 else: year += 1900 month = MONTHS.index(m.group('mon').lower()) + 1 day = int(m.group('day')) hour = int(m.group('hour')) min = int(m.group('min')) sec = int(m.group('sec')) result = datetime.datetime(year, month, day, hour, min, sec) return calendar.timegm(result.utctimetuple()) except Exception: six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2]) def parse_http_date_safe(date): """ Same as parse_http_date, but returns None if the input is invalid. """ try: return parse_http_date(date) except Exception: pass # Base 36 functions: useful for generating compact URLs def base36_to_int(s): """ Converts a base 36 string to an ``int``. Raises ``ValueError` if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is long than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-bit integer) if len(s) > 13: raise ValueError("Base36 input too large") value = int(s, 36) # ... then do a final check that the value will fit into an int to avoid # returning a long (#15067). The long type was removed in Python 3. if not six.PY3 and value > sys.maxint: raise ValueError("Base36 input too large") return value def int_to_base36(i): """ Converts an integer to a base36 string """ digits = "0123456789abcdefghijklmnopqrstuvwxyz" factor = 0 if i < 0: raise ValueError("Negative base36 conversion input.") if not six.PY3: if not isinstance(i, six.integer_types): raise TypeError("Non-integer base36 conversion input.") if i > sys.maxint: raise ValueError("Base36 conversion input too large.") # Find starting factor while True: factor += 1 if i < 36 ** factor: factor -= 1 break base36 = [] # Construct base36 representation while factor >= 0: j = 36 ** factor base36.append(digits[i // j]) i = i % j factor -= 1 return ''.join(base36) def urlsafe_base64_encode(s): """ Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b'\n=') def urlsafe_base64_decode(s): """ Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped. """ s = s.encode('utf-8') # base64encode should only return ASCII. try: return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'=')) except (LookupError, BinasciiError) as e: raise ValueError(e) def parse_etags(etag_str): """ Parses a string with one or several etags passed in If-None-Match and If-Match headers by the rules in RFC 2616. Returns a list of etags without surrounding double quotes (") and unescaped from \<CHAR>. """ etags = ETAG_MATCH.findall(etag_str) if not etags: # etag_str has wrong format, treat it as an opaque string then return [etag_str] etags = [e.encode('ascii').decode('unicode_escape') for e in etags] return etags def quote_etag(etag): """ Wraps a string in double quotes escaping contents as necessary. """ return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"') def same_origin(url1, url2): """ Checks if two URLs are 'same-origin' """ p1, p2 = urllib_parse.urlparse(url1), urllib_parse.urlparse(url2) try: return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port) except ValueError: return False def is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """ if not url: return False url_info = urllib_parse.urlparse(url) return (not url_info.netloc or url_info.netloc == host) and \ (not url_info.scheme or url_info.scheme in ['http', 'https'])
xss
{ "code": [ " netloc = urllib_parse.urlparse(url)[1]", " return not netloc or netloc == host" ], "line_no": [ 261, 262 ] }
{ "code": [ " url_info = urllib_parse.urlparse(url)", " return (not url_info.netloc or url_info.netloc == host) and \\" ], "line_no": [ 261, 262 ] }
from __future__ import unicode_literals import base64 import calendar import .datetime import re import .sys try: from urllib import parse as urllib_parse except ImportError: # Python 2 import .urllib as urllib_parse import .urlparse urllib_parse.urlparse = urlparse.urlparse from binascii import Error as BinasciiError from email.utils import formatdate from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str, force_text from django.utils.functional import allow_lazy from django.utils import .six VAR_0 = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"') VAR_1 = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() VAR_2 = r'(?P<VAR_41>\d{2})' VAR_3 = r'(?P<VAR_41>[ \d]\d)' VAR_4 = r'(?P<mon>\w{3})' VAR_5 = r'(?P<VAR_39>\d{4})' VAR_6 = r'(?P<VAR_39>\d{2})' VAR_7 = r'(?P<VAR_42>\d{2}):(?P<VAR_43>\d{2}):(?P<VAR_44>\d{2})' VAR_8 = re.compile(r'^\w{3}, %VAR_22 %VAR_22 %VAR_22 %s GMT$' % (VAR_2, VAR_4, VAR_5, VAR_7)) VAR_9 = re.compile(r'^\w{6,9}, %VAR_22-%VAR_22-%VAR_22 %s GMT$' % (VAR_2, VAR_4, VAR_6, VAR_7)) VAR_10 = re.compile(r'^\w{3} %VAR_22 %VAR_22 %VAR_22 %s$' % (VAR_4, VAR_3, VAR_7, VAR_5)) def VAR_13(VAR_11, VAR_12='/'): return force_text(urllib_parse.quote(force_str(VAR_11), force_str(VAR_12))) VAR_13 = allow_lazy(VAR_13, six.text_type) def VAR_14(VAR_11, VAR_12=''): return force_text(urllib_parse.quote_plus(force_str(VAR_11), force_str(VAR_12))) VAR_14 = allow_lazy(VAR_14, six.text_type) def VAR_16(VAR_15): return force_text(urllib_parse.unquote(force_str(VAR_15))) VAR_16 = allow_lazy(VAR_16, six.text_type) def VAR_17(VAR_15): return force_text(urllib_parse.unquote_plus(force_str(VAR_15))) VAR_17 = allow_lazy(VAR_17, six.text_type) def FUNC_4(VAR_18, VAR_19=0): if isinstance(VAR_18, MultiValueDict): VAR_18 = query.lists() elif hasattr(VAR_18, 'items'): VAR_18 = query.items() return urllib_parse.urlencode( [(force_str(k), [force_str(VAR_23) for VAR_23 in v] if isinstance(v, (list,tuple)) else force_str(v)) for k, v in VAR_18], VAR_19) def FUNC_5(VAR_20=None): VAR_29 = formatdate(VAR_20) return '%VAR_22-%s-%VAR_22 GMT' % (VAR_29[:7], VAR_29[8:11], VAR_29[12:25]) def FUNC_6(VAR_20=None): return formatdate(VAR_20, usegmt=True) def FUNC_7(VAR_21): for regex in VAR_8, VAR_9, VAR_10: VAR_38 = regex.match(VAR_21) if VAR_38 is not None: break else: raise ValueError("%r is not in a valid HTTP VAR_21 format" % VAR_21) try: VAR_39 = int(VAR_38.group('year')) if VAR_39 < 100: if VAR_39 < 70: VAR_39 += 2000 else: VAR_39 += 1900 VAR_40 = VAR_1.index(VAR_38.group('mon').lower()) + 1 VAR_41 = int(VAR_38.group('day')) VAR_42 = int(VAR_38.group('hour')) VAR_43 = int(VAR_38.group('min')) VAR_44 = int(VAR_38.group('sec')) VAR_45 = datetime.datetime(VAR_39, VAR_40, VAR_41, VAR_42, VAR_43, VAR_44) return calendar.timegm(VAR_45.utctimetuple()) except Exception: six.reraise(ValueError, ValueError("%r is not a valid date" % VAR_21), sys.exc_info()[2]) def FUNC_8(VAR_21): try: return FUNC_7(VAR_21) except Exception: pass def FUNC_9(VAR_22): if len(VAR_22) > 13: raise ValueError("Base36 input too large") VAR_30 = int(VAR_22, 36) if not six.PY3 and VAR_30 > sys.maxint: raise ValueError("Base36 input too large") return VAR_30 def FUNC_10(VAR_23): VAR_31 = "0123456789abcdefghijklmnopqrstuvwxyz" VAR_32 = 0 if VAR_23 < 0: raise ValueError("Negative VAR_33 conversion input.") if not six.PY3: if not isinstance(VAR_23, six.integer_types): raise TypeError("Non-integer VAR_33 conversion input.") if VAR_23 > sys.maxint: raise ValueError("Base36 conversion input too large.") while True: VAR_32 += 1 if VAR_23 < 36 ** VAR_32: factor -= 1 break VAR_33 = [] while VAR_32 >= 0: VAR_46 = 36 ** VAR_32 VAR_33.append(VAR_31[VAR_23 // VAR_46]) VAR_23 = VAR_23 % VAR_46 VAR_32 -= 1 return ''.join(VAR_33) def FUNC_11(VAR_22): return base64.urlsafe_b64encode(VAR_22).rstrip(b'\n=') def FUNC_12(VAR_22): VAR_22 = s.encode('utf-8') # base64encode should only return ASCII. try: return base64.urlsafe_b64decode(VAR_22.ljust(len(VAR_22) + len(VAR_22) % 4, b'=')) except (LookupError, BinasciiError) as e: raise ValueError(e) def FUNC_13(VAR_24): VAR_34 = VAR_0.findall(VAR_24) if not VAR_34: return [VAR_24] VAR_34 = [e.encode('ascii').decode('unicode_escape') for e in VAR_34] return VAR_34 def FUNC_14(VAR_25): return '"%s"' % VAR_25.replace('\\', '\\\\').replace('"', '\\"') def FUNC_15(VAR_26, VAR_27): VAR_35, VAR_36 = urllib_parse.urlparse(VAR_26), urllib_parse.urlparse(VAR_27) try: return (VAR_35.scheme, VAR_35.hostname, VAR_35.port) == (VAR_36.scheme, VAR_36.hostname, VAR_36.port) except ValueError: return False def FUNC_16(VAR_11, VAR_28=None): if not VAR_11: return False VAR_37 = urllib_parse.urlparse(VAR_11)[1] return not VAR_37 or VAR_37 == VAR_28
from __future__ import unicode_literals import base64 import calendar import .datetime import re import .sys try: from urllib import parse as urllib_parse except ImportError: # Python 2 import .urllib as urllib_parse import .urlparse urllib_parse.urlparse = urlparse.urlparse from binascii import Error as BinasciiError from email.utils import formatdate from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str, force_text from django.utils.functional import allow_lazy from django.utils import .six VAR_0 = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"') VAR_1 = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() VAR_2 = r'(?P<VAR_41>\d{2})' VAR_3 = r'(?P<VAR_41>[ \d]\d)' VAR_4 = r'(?P<mon>\w{3})' VAR_5 = r'(?P<VAR_39>\d{4})' VAR_6 = r'(?P<VAR_39>\d{2})' VAR_7 = r'(?P<VAR_42>\d{2}):(?P<VAR_43>\d{2}):(?P<VAR_44>\d{2})' VAR_8 = re.compile(r'^\w{3}, %VAR_22 %VAR_22 %VAR_22 %s GMT$' % (VAR_2, VAR_4, VAR_5, VAR_7)) VAR_9 = re.compile(r'^\w{6,9}, %VAR_22-%VAR_22-%VAR_22 %s GMT$' % (VAR_2, VAR_4, VAR_6, VAR_7)) VAR_10 = re.compile(r'^\w{3} %VAR_22 %VAR_22 %VAR_22 %s$' % (VAR_4, VAR_3, VAR_7, VAR_5)) def VAR_13(VAR_11, VAR_12='/'): return force_text(urllib_parse.quote(force_str(VAR_11), force_str(VAR_12))) VAR_13 = allow_lazy(VAR_13, six.text_type) def VAR_14(VAR_11, VAR_12=''): return force_text(urllib_parse.quote_plus(force_str(VAR_11), force_str(VAR_12))) VAR_14 = allow_lazy(VAR_14, six.text_type) def VAR_16(VAR_15): return force_text(urllib_parse.unquote(force_str(VAR_15))) VAR_16 = allow_lazy(VAR_16, six.text_type) def VAR_17(VAR_15): return force_text(urllib_parse.unquote_plus(force_str(VAR_15))) VAR_17 = allow_lazy(VAR_17, six.text_type) def FUNC_4(VAR_18, VAR_19=0): if isinstance(VAR_18, MultiValueDict): VAR_18 = query.lists() elif hasattr(VAR_18, 'items'): VAR_18 = query.items() return urllib_parse.urlencode( [(force_str(k), [force_str(VAR_23) for VAR_23 in v] if isinstance(v, (list,tuple)) else force_str(v)) for k, v in VAR_18], VAR_19) def FUNC_5(VAR_20=None): VAR_29 = formatdate(VAR_20) return '%VAR_22-%s-%VAR_22 GMT' % (VAR_29[:7], VAR_29[8:11], VAR_29[12:25]) def FUNC_6(VAR_20=None): return formatdate(VAR_20, usegmt=True) def FUNC_7(VAR_21): for regex in VAR_8, VAR_9, VAR_10: VAR_38 = regex.match(VAR_21) if VAR_38 is not None: break else: raise ValueError("%r is not in a valid HTTP VAR_21 format" % VAR_21) try: VAR_39 = int(VAR_38.group('year')) if VAR_39 < 100: if VAR_39 < 70: VAR_39 += 2000 else: VAR_39 += 1900 VAR_40 = VAR_1.index(VAR_38.group('mon').lower()) + 1 VAR_41 = int(VAR_38.group('day')) VAR_42 = int(VAR_38.group('hour')) VAR_43 = int(VAR_38.group('min')) VAR_44 = int(VAR_38.group('sec')) VAR_45 = datetime.datetime(VAR_39, VAR_40, VAR_41, VAR_42, VAR_43, VAR_44) return calendar.timegm(VAR_45.utctimetuple()) except Exception: six.reraise(ValueError, ValueError("%r is not a valid date" % VAR_21), sys.exc_info()[2]) def FUNC_8(VAR_21): try: return FUNC_7(VAR_21) except Exception: pass def FUNC_9(VAR_22): if len(VAR_22) > 13: raise ValueError("Base36 input too large") VAR_30 = int(VAR_22, 36) if not six.PY3 and VAR_30 > sys.maxint: raise ValueError("Base36 input too large") return VAR_30 def FUNC_10(VAR_23): VAR_31 = "0123456789abcdefghijklmnopqrstuvwxyz" VAR_32 = 0 if VAR_23 < 0: raise ValueError("Negative VAR_33 conversion input.") if not six.PY3: if not isinstance(VAR_23, six.integer_types): raise TypeError("Non-integer VAR_33 conversion input.") if VAR_23 > sys.maxint: raise ValueError("Base36 conversion input too large.") while True: VAR_32 += 1 if VAR_23 < 36 ** VAR_32: factor -= 1 break VAR_33 = [] while VAR_32 >= 0: VAR_46 = 36 ** VAR_32 VAR_33.append(VAR_31[VAR_23 // VAR_46]) VAR_23 = VAR_23 % VAR_46 VAR_32 -= 1 return ''.join(VAR_33) def FUNC_11(VAR_22): return base64.urlsafe_b64encode(VAR_22).rstrip(b'\n=') def FUNC_12(VAR_22): VAR_22 = s.encode('utf-8') # base64encode should only return ASCII. try: return base64.urlsafe_b64decode(VAR_22.ljust(len(VAR_22) + len(VAR_22) % 4, b'=')) except (LookupError, BinasciiError) as e: raise ValueError(e) def FUNC_13(VAR_24): VAR_34 = VAR_0.findall(VAR_24) if not VAR_34: return [VAR_24] VAR_34 = [e.encode('ascii').decode('unicode_escape') for e in VAR_34] return VAR_34 def FUNC_14(VAR_25): return '"%s"' % VAR_25.replace('\\', '\\\\').replace('"', '\\"') def FUNC_15(VAR_26, VAR_27): VAR_35, VAR_36 = urllib_parse.urlparse(VAR_26), urllib_parse.urlparse(VAR_27) try: return (VAR_35.scheme, VAR_35.hostname, VAR_35.port) == (VAR_36.scheme, VAR_36.hostname, VAR_36.port) except ValueError: return False def FUNC_16(VAR_11, VAR_28=None): if not VAR_11: return False VAR_37 = urllib_parse.urlparse(VAR_11) return (not VAR_37.netloc or VAR_37.netloc == VAR_28) and \ (not VAR_37.scheme or VAR_37.scheme in ['http', 'https'])
[ 2, 14, 17, 22, 24, 35, 45, 55, 63, 71, 87, 91, 95, 100, 105, 109, 113, 117, 120, 123, 124, 125, 148, 157, 158, 159, 165, 166, 167, 171, 172, 176, 190, 197, 204, 211, 222, 231, 235, 241, 251, 256, 263, 37, 38, 39, 40, 41, 42, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 65, 66, 67, 68, 73, 74, 75, 76, 77, 89, 90, 91, 92, 93, 94, 95, 96, 97, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 115, 116, 117, 118, 119, 120, 121, 122, 150, 151, 152, 161, 162, 163, 164, 178, 179, 180, 206, 207, 208, 209, 213, 214, 215, 216, 224, 225, 226, 227, 228, 237, 238, 239, 243, 244, 245, 253, 254, 255, 256, 257, 258 ]
[ 2, 14, 17, 22, 24, 35, 45, 55, 63, 71, 87, 91, 95, 100, 105, 109, 113, 117, 120, 123, 124, 125, 148, 157, 158, 159, 165, 166, 167, 171, 172, 176, 190, 197, 204, 211, 222, 231, 235, 241, 251, 256, 264, 37, 38, 39, 40, 41, 42, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 65, 66, 67, 68, 73, 74, 75, 76, 77, 89, 90, 91, 92, 93, 94, 95, 96, 97, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 115, 116, 117, 118, 119, 120, 121, 122, 150, 151, 152, 161, 162, 163, 164, 178, 179, 180, 206, 207, 208, 209, 213, 214, 215, 216, 224, 225, 226, 227, 228, 237, 238, 239, 243, 244, 245, 253, 254, 255, 256, 257, 258 ]
5CWE-94
import sys import os from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand def _read(fname): here = os.path.dirname(os.path.abspath(__file__)) return open(os.path.join(here, fname)).read() class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] if len(sys.argv) == 2: self.pytest_args = ['ansible_vault'] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest sys.exit(pytest.main(self.pytest_args)) setup( name='ansible-vault', version='1.0.4', author='Tomohiro NAKAMURA', author_email='quickness.net@gmail.com', url='https://github.com/jptomo/ansible-vault', description='R/W an ansible-vault yaml file', long_description=_read('README.rst'), packages=find_packages(), install_requires=['ansible'], tests_require=['pytest', 'testfixtures'], cmdclass={'test': PyTest}, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', ], license='GPLv3', )
import sys import os from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand def _read(fname): here = os.path.dirname(os.path.abspath(__file__)) return open(os.path.join(here, fname)).read() class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] if len(sys.argv) == 2: self.pytest_args = ['ansible_vault'] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest sys.exit(pytest.main(self.pytest_args)) setup( name='ansible-vault', version='1.0.5', author='Tomohiro NAKAMURA', author_email='quickness.net@gmail.com', url='https://github.com/tomoh1r/ansible-vault', description='R/W an ansible-vault yaml file', long_description=_read('README.rst'), packages=find_packages(), install_requires=['ansible'], cmdclass={'test': PyTest}, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', ], license='GPLv3', extras_require = { 'test': ['pytest', 'testfixtures'], } )
remote_code_execution
{ "code": [ " version='1.0.4',", " url='https://github.com/jptomo/ansible-vault',", " tests_require=['pytest', 'testfixtures']," ], "line_no": [ 35, 38, 43 ] }
{ "code": [ " version='1.0.5',", " url='https://github.com/tomoh1r/ansible-vault',", " extras_require = {", " 'test': ['pytest', 'testfixtures']," ], "line_no": [ 35, 38, 49, 50 ] }
import sys import os from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand def FUNC_0(VAR_0): VAR_1 = os.path.dirname(os.path.abspath(__file__)) return open(os.path.join(VAR_1, VAR_0)).read() class CLASS_0(TestCommand): VAR_2 = [('pytest-args=', 'a', "Arguments to pass to py.test")] def FUNC_1(self): TestCommand.initialize_options(self) self.pytest_args = [] if len(sys.argv) == 2: self.pytest_args = ['ansible_vault'] def FUNC_2(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def FUNC_3(self): import pytest sys.exit(pytest.main(self.pytest_args)) setup( name='ansible-vault', version='1.0.4', author='Tomohiro NAKAMURA', author_email='quickness.net@gmail.com', url='https://github.com/jptomo/ansible-vault', description='R/W an ansible-vault yaml file', long_description=FUNC_0('README.rst'), packages=find_packages(), install_requires=['ansible'], tests_require=['pytest', 'testfixtures'], cmdclass={'test': CLASS_0}, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', ], license='GPLv3', )
import sys import os from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand def FUNC_0(VAR_0): VAR_1 = os.path.dirname(os.path.abspath(__file__)) return open(os.path.join(VAR_1, VAR_0)).read() class CLASS_0(TestCommand): VAR_2 = [('pytest-args=', 'a', "Arguments to pass to py.test")] def FUNC_1(self): TestCommand.initialize_options(self) self.pytest_args = [] if len(sys.argv) == 2: self.pytest_args = ['ansible_vault'] def FUNC_2(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def FUNC_3(self): import pytest sys.exit(pytest.main(self.pytest_args)) setup( name='ansible-vault', version='1.0.5', author='Tomohiro NAKAMURA', author_email='quickness.net@gmail.com', url='https://github.com/tomoh1r/ansible-vault', description='R/W an ansible-vault yaml file', long_description=FUNC_0('README.rst'), packages=find_packages(), install_requires=['ansible'], cmdclass={'test': CLASS_0}, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', ], license='GPLv3', extras_require = { 'test': ['pytest', 'testfixtures'], } )
[ 3, 6, 7, 11, 12, 15, 21, 26, 28, 31, 32, 51 ]
[ 3, 6, 7, 11, 12, 15, 21, 26, 28, 31, 32, 53 ]
3CWE-352
# -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, # andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, # falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, # ruben-herold, marblepebble, JackED42, SiphonSquirrel, # apetresc, nanu-c, mutschler # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os from datetime import datetime import json import mimetypes import chardet # dependency of requests import copy from babel.dates import format_date from babel import Locale as LC from flask import Blueprint, jsonify from flask import request, redirect, send_from_directory, make_response, flash, abort, url_for from flask import session as flask_session from flask_babel import gettext as _ from flask_login import login_user, logout_user, login_required, current_user from sqlalchemy.exc import IntegrityError, InvalidRequestError, OperationalError from sqlalchemy.sql.expression import text, func, false, not_, and_, or_ from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.sql.functions import coalesce from .services.worker import WorkerThread from werkzeug.datastructures import Headers from werkzeug.security import generate_password_hash, check_password_hash from . import constants, logger, isoLanguages, services from . import babel, db, ub, config, get_locale, app from . import calibre_db, kobo_sync_status from .gdriveutils import getFileFromEbooksFolder, do_gdrive_download from .helper import check_valid_domain, render_task_status, check_email, check_username, \ get_cc_columns, get_book_cover, get_download_link, send_mail, generate_random_password, \ send_registration_mail, check_send_to_kindle, check_read_formats, tags_filters, reset_password, valid_email from .pagination import Pagination from .redirect import redirect_back from .usermanagement import login_required_if_no_ano from .kobo_sync_status import remove_synced_book from .render_template import render_title_template from .kobo_sync_status import change_archived_books feature_support = { 'ldap': bool(services.ldap), 'goodreads': bool(services.goodreads_support), 'kobo': bool(services.kobo) } try: from .oauth_bb import oauth_check, register_user_with_oauth, logout_oauth_user, get_oauth_status feature_support['oauth'] = True except ImportError: feature_support['oauth'] = False oauth_check = {} try: from functools import wraps except ImportError: pass # We're not using Python 3 try: from natsort import natsorted as sort except ImportError: sort = sorted # Just use regular sort then, may cause issues with badly named pages in cbz/cbr files @app.after_request def add_security_headers(resp): resp.headers['Content-Security-Policy'] = "default-src 'self'" + ''.join([' '+host for host in config.config_trustedhosts.strip().split(',')]) + " 'unsafe-inline' 'unsafe-eval'; font-src 'self' data:; img-src 'self' data:" if request.endpoint == "editbook.edit_book" or config.config_use_google_drive: resp.headers['Content-Security-Policy'] += " *" elif request.endpoint == "web.read_book": resp.headers['Content-Security-Policy'] += " blob:;style-src-elem 'self' blob: 'unsafe-inline';" resp.headers['X-Content-Type-Options'] = 'nosniff' resp.headers['X-Frame-Options'] = 'SAMEORIGIN' resp.headers['X-XSS-Protection'] = '1; mode=block' resp.headers['Strict-Transport-Security'] = 'max-age=31536000;' return resp web = Blueprint('web', __name__) log = logger.create() # ################################### Login logic and rights management ############################################### def download_required(f): @wraps(f) def inner(*args, **kwargs): if current_user.role_download(): return f(*args, **kwargs) abort(403) return inner def viewer_required(f): @wraps(f) def inner(*args, **kwargs): if current_user.role_viewer(): return f(*args, **kwargs) abort(403) return inner # ################################### data provider functions ######################################################### @web.route("/ajax/emailstat") @login_required def get_email_status_json(): tasks = WorkerThread.getInstance().tasks return jsonify(render_task_status(tasks)) @web.route("/ajax/bookmark/<int:book_id>/<book_format>", methods=['POST']) @login_required def bookmark(book_id, book_format): bookmark_key = request.form["bookmark"] ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id), ub.Bookmark.book_id == book_id, ub.Bookmark.format == book_format)).delete() if not bookmark_key: ub.session_commit() return "", 204 lbookmark = ub.Bookmark(user_id=current_user.id, book_id=book_id, format=book_format, bookmark_key=bookmark_key) ub.session.merge(lbookmark) ub.session_commit("Bookmark for user {} in book {} created".format(current_user.id, book_id)) return "", 201 @web.route("/ajax/toggleread/<int:book_id>", methods=['POST']) @login_required def toggle_read(book_id): if not config.config_read_column: book = ub.session.query(ub.ReadBook).filter(and_(ub.ReadBook.user_id == int(current_user.id), ub.ReadBook.book_id == book_id)).first() if book: if book.read_status == ub.ReadBook.STATUS_FINISHED: book.read_status = ub.ReadBook.STATUS_UNREAD else: book.read_status = ub.ReadBook.STATUS_FINISHED else: readBook = ub.ReadBook(user_id=current_user.id, book_id = book_id) readBook.read_status = ub.ReadBook.STATUS_FINISHED book = readBook if not book.kobo_reading_state: kobo_reading_state = ub.KoboReadingState(user_id=current_user.id, book_id=book_id) kobo_reading_state.current_bookmark = ub.KoboBookmark() kobo_reading_state.statistics = ub.KoboStatistics() book.kobo_reading_state = kobo_reading_state ub.session.merge(book) ub.session_commit("Book {} readbit toggled".format(book_id)) else: try: calibre_db.update_title_sort(config) book = calibre_db.get_filtered_book(book_id) read_status = getattr(book, 'custom_column_' + str(config.config_read_column)) if len(read_status): read_status[0].value = not read_status[0].value calibre_db.session.commit() else: cc_class = db.cc_classes[config.config_read_column] new_cc = cc_class(value=1, book=book_id) calibre_db.session.add(new_cc) calibre_db.session.commit() except (KeyError, AttributeError): log.error(u"Custom Column No.%d is not existing in calibre database", config.config_read_column) return "Custom Column No.{} is not existing in calibre database".format(config.config_read_column), 400 except (OperationalError, InvalidRequestError) as e: calibre_db.session.rollback() log.error(u"Read status could not set: {}".format(e)) return "Read status could not set: {}".format(e), 400 return "" @web.route("/ajax/togglearchived/<int:book_id>", methods=['POST']) @login_required def toggle_archived(book_id): is_archived = change_archived_books(book_id, message="Book {} archivebit toggled".format(book_id)) if is_archived: remove_synced_book(book_id) return "" @web.route("/ajax/view", methods=["POST"]) @login_required_if_no_ano def update_view(): to_save = request.get_json() try: for element in to_save: for param in to_save[element]: current_user.set_view_property(element, param, to_save[element][param]) except Exception as ex: log.error("Could not save view_settings: %r %r: %e", request, to_save, ex) return "Invalid request", 400 return "1", 200 ''' @web.route("/ajax/getcomic/<int:book_id>/<book_format>/<int:page>") @login_required def get_comic_book(book_id, book_format, page): book = calibre_db.get_book(book_id) if not book: return "", 204 else: for bookformat in book.data: if bookformat.format.lower() == book_format.lower(): cbr_file = os.path.join(config.config_calibre_dir, book.path, bookformat.name) + "." + book_format if book_format in ("cbr", "rar"): if feature_support['rar'] == True: rarfile.UNRAR_TOOL = config.config_rarfile_location try: rf = rarfile.RarFile(cbr_file) names = sort(rf.namelist()) extract = lambda page: rf.read(names[page]) except: # rarfile not valid log.error('Unrar binary not found, or unable to decompress file %s', cbr_file) return "", 204 else: log.info('Unrar is not supported please install python rarfile extension') # no support means return nothing return "", 204 elif book_format in ("cbz", "zip"): zf = zipfile.ZipFile(cbr_file) names=sort(zf.namelist()) extract = lambda page: zf.read(names[page]) elif book_format in ("cbt", "tar"): tf = tarfile.TarFile(cbr_file) names=sort(tf.getnames()) extract = lambda page: tf.extractfile(names[page]).read() else: log.error('unsupported comic format') return "", 204 b64 = codecs.encode(extract(page), 'base64').decode() ext = names[page].rpartition('.')[-1] if ext not in ('png', 'gif', 'jpg', 'jpeg', 'webp'): ext = 'png' extractedfile="data:image/" + ext + ";base64," + b64 fileData={"name": names[page], "page":page, "last":len(names)-1, "content": extractedfile} return make_response(json.dumps(fileData)) return "", 204 ''' # ################################### Typeahead ################################################################## @web.route("/get_authors_json", methods=['GET']) @login_required_if_no_ano def get_authors_json(): return calibre_db.get_typeahead(db.Authors, request.args.get('q'), ('|', ',')) @web.route("/get_publishers_json", methods=['GET']) @login_required_if_no_ano def get_publishers_json(): return calibre_db.get_typeahead(db.Publishers, request.args.get('q'), ('|', ',')) @web.route("/get_tags_json", methods=['GET']) @login_required_if_no_ano def get_tags_json(): return calibre_db.get_typeahead(db.Tags, request.args.get('q'), tag_filter=tags_filters()) @web.route("/get_series_json", methods=['GET']) @login_required_if_no_ano def get_series_json(): return calibre_db.get_typeahead(db.Series, request.args.get('q')) @web.route("/get_languages_json", methods=['GET']) @login_required_if_no_ano def get_languages_json(): query = (request.args.get('q') or '').lower() language_names = isoLanguages.get_language_names(get_locale()) entries_start = [s for key, s in language_names.items() if s.lower().startswith(query.lower())] if len(entries_start) < 5: entries = [s for key, s in language_names.items() if query in s.lower()] entries_start.extend(entries[0:(5 - len(entries_start))]) entries_start = list(set(entries_start)) json_dumps = json.dumps([dict(name=r) for r in entries_start[0:5]]) return json_dumps @web.route("/get_matching_tags", methods=['GET']) @login_required_if_no_ano def get_matching_tags(): tag_dict = {'tags': []} q = calibre_db.session.query(db.Books).filter(calibre_db.common_filters(True)) calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase) author_input = request.args.get('author_name') or '' title_input = request.args.get('book_title') or '' include_tag_inputs = request.args.getlist('include_tag') or '' exclude_tag_inputs = request.args.getlist('exclude_tag') or '' q = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + author_input + "%")), func.lower(db.Books.title).ilike("%" + title_input + "%")) if len(include_tag_inputs) > 0: for tag in include_tag_inputs: q = q.filter(db.Books.tags.any(db.Tags.id == tag)) if len(exclude_tag_inputs) > 0: for tag in exclude_tag_inputs: q = q.filter(not_(db.Books.tags.any(db.Tags.id == tag))) for book in q: for tag in book.tags: if tag.id not in tag_dict['tags']: tag_dict['tags'].append(tag.id) json_dumps = json.dumps(tag_dict) return json_dumps def get_sort_function(sort, data): order = [db.Books.timestamp.desc()] if sort == 'stored': sort = current_user.get_view_property(data, 'stored') else: current_user.set_view_property(data, 'stored', sort) if sort == 'pubnew': order = [db.Books.pubdate.desc()] if sort == 'pubold': order = [db.Books.pubdate] if sort == 'abc': order = [db.Books.sort] if sort == 'zyx': order = [db.Books.sort.desc()] if sort == 'new': order = [db.Books.timestamp.desc()] if sort == 'old': order = [db.Books.timestamp] if sort == 'authaz': order = [db.Books.author_sort.asc(), db.Series.name, db.Books.series_index] if sort == 'authza': order = [db.Books.author_sort.desc(), db.Series.name.desc(), db.Books.series_index.desc()] if sort == 'seriesasc': order = [db.Books.series_index.asc()] if sort == 'seriesdesc': order = [db.Books.series_index.desc()] if sort == 'hotdesc': order = [func.count(ub.Downloads.book_id).desc()] if sort == 'hotasc': order = [func.count(ub.Downloads.book_id).asc()] if sort is None: sort = "new" return order, sort def render_books_list(data, sort, book_id, page): order = get_sort_function(sort, data) if data == "rated": return render_rated_books(page, book_id, order=order) elif data == "discover": return render_discover_books(page, book_id) elif data == "unread": return render_read_books(page, False, order=order) elif data == "read": return render_read_books(page, True, order=order) elif data == "hot": return render_hot_books(page, order) elif data == "download": return render_downloaded_books(page, order, book_id) elif data == "author": return render_author_books(page, book_id, order) elif data == "publisher": return render_publisher_books(page, book_id, order) elif data == "series": return render_series_books(page, book_id, order) elif data == "ratings": return render_ratings_books(page, book_id, order) elif data == "formats": return render_formats_books(page, book_id, order) elif data == "category": return render_category_books(page, book_id, order) elif data == "language": return render_language_books(page, book_id, order) elif data == "archived": return render_archived_books(page, order) elif data == "search": term = (request.args.get('query') or '') offset = int(int(config.config_books_per_page) * (page - 1)) return render_search_results(term, offset, order, config.config_books_per_page) elif data == "advsearch": term = json.loads(flask_session['query']) offset = int(int(config.config_books_per_page) * (page - 1)) return render_adv_search_results(term, offset, order, config.config_books_per_page) else: website = data or "newest" entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, True, order[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=_(u"Books"), page=website, order=order[1]) def render_rated_books(page, book_id, order): if current_user.check_visibility(constants.SIDEBAR_BEST_RATED): entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.ratings.any(db.Ratings.rating > 9), order[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=book_id, title=_(u"Top Rated Books"), page="rated", order=order[1]) else: abort(404) def render_discover_books(page, book_id): if current_user.check_visibility(constants.SIDEBAR_RANDOM): entries, __, pagination = calibre_db.fill_indexpage(page, 0, db.Books, True, [func.randomblob(2)]) pagination = Pagination(1, config.config_books_per_page, config.config_books_per_page) return render_title_template('discover.html', entries=entries, pagination=pagination, id=book_id, title=_(u"Discover (Random Books)"), page="discover") else: abort(404) def render_hot_books(page, order): if current_user.check_visibility(constants.SIDEBAR_HOT): if order[1] not in ['hotasc', 'hotdesc']: # Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+ #if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or # order[0][0].compare(func.count(ub.Downloads.book_id).asc())): order = [func.count(ub.Downloads.book_id).desc()], 'hotdesc' if current_user.show_detail_random(): random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: random = false() off = int(int(config.config_books_per_page) * (page - 1)) all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\ .order_by(*order[0]).group_by(ub.Downloads.book_id) hot_books = all_books.offset(off).limit(config.config_books_per_page) entries = list() for book in hot_books: downloadBook = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter( db.Books.id == book.Downloads.book_id).first() if downloadBook: entries.append(downloadBook) else: ub.delete_download(book.Downloads.book_id) numBooks = entries.__len__() pagination = Pagination(page, config.config_books_per_page, numBooks) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=_(u"Hot Books (Most Downloaded)"), page="hot", order=order[1]) else: abort(404) def render_downloaded_books(page, order, user_id): if current_user.role_admin(): user_id = int(user_id) else: user_id = current_user.id if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD): if current_user.show_detail_random(): random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: random = false() entries, __, pagination = calibre_db.fill_indexpage(page, 0, db.Books, ub.Downloads.user_id == user_id, order[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, ub.Downloads, db.Books.id == ub.Downloads.book_id) for book in entries: if not calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .filter(db.Books.id == book.id).first(): ub.delete_download(book.id) user = ub.session.query(ub.User).filter(ub.User.id == user_id).first() return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=user_id, title=_(u"Downloaded books by %(user)s",user=user.name), page="download", order=order[1]) else: abort(404) def render_author_books(page, author_id, order): entries, __, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.authors.any(db.Authors.id == author_id), [order[0][0], db.Series.name, db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) if entries is None or not len(entries): flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) if constants.sqlalchemy_version2: author = calibre_db.session.get(db.Authors, author_id) else: author = calibre_db.session.query(db.Authors).get(author_id) author_name = author.name.replace('|', ',') author_info = None other_books = [] if services.goodreads_support and config.config_use_goodreads: author_info = services.goodreads_support.get_author_info(author_name) other_books = services.goodreads_support.get_other_books(author_info, entries) return render_title_template('author.html', entries=entries, pagination=pagination, id=author_id, title=_(u"Author: %(name)s", name=author_name), author=author_info, other_books=other_books, page="author", order=order[1]) def render_publisher_books(page, book_id, order): publisher = calibre_db.session.query(db.Publishers).filter(db.Publishers.id == book_id).first() if publisher: entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.publishers.any(db.Publishers.id == book_id), [db.Series.name, order[0][0], db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=book_id, title=_(u"Publisher: %(name)s", name=publisher.name), page="publisher", order=order[1]) else: abort(404) def render_series_books(page, book_id, order): name = calibre_db.session.query(db.Series).filter(db.Series.id == book_id).first() if name: entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.series.any(db.Series.id == book_id), [order[0][0]]) return render_title_template('index.html', random=random, pagination=pagination, entries=entries, id=book_id, title=_(u"Series: %(serie)s", serie=name.name), page="series", order=order[1]) else: abort(404) def render_ratings_books(page, book_id, order): name = calibre_db.session.query(db.Ratings).filter(db.Ratings.id == book_id).first() entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.ratings.any(db.Ratings.id == book_id), [order[0][0]]) if name and name.rating <= 10: return render_title_template('index.html', random=random, pagination=pagination, entries=entries, id=book_id, title=_(u"Rating: %(rating)s stars", rating=int(name.rating / 2)), page="ratings", order=order[1]) else: abort(404) def render_formats_books(page, book_id, order): name = calibre_db.session.query(db.Data).filter(db.Data.format == book_id.upper()).first() if name: entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.data.any(db.Data.format == book_id.upper()), [order[0][0]]) return render_title_template('index.html', random=random, pagination=pagination, entries=entries, id=book_id, title=_(u"File format: %(format)s", format=name.format), page="formats", order=order[1]) else: abort(404) def render_category_books(page, book_id, order): name = calibre_db.session.query(db.Tags).filter(db.Tags.id == book_id).first() if name: entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.tags.any(db.Tags.id == book_id), [order[0][0], db.Series.name, db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=book_id, title=_(u"Category: %(name)s", name=name.name), page="category", order=order[1]) else: abort(404) def render_language_books(page, name, order): try: lang_name = isoLanguages.get_language_name(get_locale(), name) except KeyError: abort(404) entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.languages.any(db.Languages.lang_code == name), [order[0][0]]) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=name, title=_(u"Language: %(name)s", name=lang_name), page="language", order=order[1]) def render_read_books(page, are_read, as_xml=False, order=None): sort = order[0] if order else [] if not config.config_read_column: if are_read: db_filter = and_(ub.ReadBook.user_id == int(current_user.id), ub.ReadBook.read_status == ub.ReadBook.STATUS_FINISHED) else: db_filter = coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db_filter, sort, db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, ub.ReadBook, db.Books.id == ub.ReadBook.book_id) else: try: if are_read: db_filter = db.cc_classes[config.config_read_column].value == True else: db_filter = coalesce(db.cc_classes[config.config_read_column].value, False) != True entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db_filter, sort, db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, db.cc_classes[config.config_read_column]) except (KeyError, AttributeError): log.error("Custom Column No.%d is not existing in calibre database", config.config_read_column) if not as_xml: flash(_("Custom Column No.%(column)d is not existing in calibre database", column=config.config_read_column), category="error") return redirect(url_for("web.index")) # ToDo: Handle error Case for opds if as_xml: return entries, pagination else: if are_read: name = _(u'Read Books') + ' (' + str(pagination.total_count) + ')' pagename = "read" else: name = _(u'Unread Books') + ' (' + str(pagination.total_count) + ')' pagename = "unread" return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=name, page=pagename, order=order[1]) def render_archived_books(page, sort): order = sort[0] or [] archived_books = ( ub.session.query(ub.ArchivedBook) .filter(ub.ArchivedBook.user_id == int(current_user.id)) .filter(ub.ArchivedBook.is_archived == True) .all() ) archived_book_ids = [archived_book.book_id for archived_book in archived_books] archived_filter = db.Books.id.in_(archived_book_ids) entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page, 0, db.Books, archived_filter, order, allow_show_archived=True) name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')' pagename = "archived" return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=name, page=pagename, order=sort[1]) def render_prepare_search_form(cc): # prepare data for search-form tags = calibre_db.session.query(db.Tags)\ .join(db.books_tags_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag'))\ .order_by(db.Tags.name).all() series = calibre_db.session.query(db.Series)\ .join(db.books_series_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series'))\ .order_by(db.Series.name)\ .filter(calibre_db.common_filters()).all() shelves = ub.session.query(ub.Shelf)\ .filter(or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == int(current_user.id)))\ .order_by(ub.Shelf.name).all() extensions = calibre_db.session.query(db.Data)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(db.Data.format)\ .order_by(db.Data.format).all() if current_user.filter_language() == u"all": languages = calibre_db.speaking_language() else: languages = None return render_title_template('search_form.html', tags=tags, languages=languages, extensions=extensions, series=series,shelves=shelves, title=_(u"Advanced Search"), cc=cc, page="advsearch") def render_search_results(term, offset=None, order=None, limit=None): join = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series entries, result_count, pagination = calibre_db.get_search_results(term, offset, order, limit, *join) return render_title_template('search.html', searchterm=term, pagination=pagination, query=term, adv_searchterm=term, entries=entries, result_count=result_count, title=_(u"Search"), page="search", order=order[1]) # ################################### View Books list ################################################################## @web.route("/", defaults={'page': 1}) @web.route('/page/<int:page>') @login_required_if_no_ano def index(page): sort_param = (request.args.get('sort') or 'stored').lower() return render_books_list("newest", sort_param, 1, page) @web.route('/<data>/<sort_param>', defaults={'page': 1, 'book_id': 1}) @web.route('/<data>/<sort_param>/', defaults={'page': 1, 'book_id': 1}) @web.route('/<data>/<sort_param>/<book_id>', defaults={'page': 1}) @web.route('/<data>/<sort_param>/<book_id>/<int:page>') @login_required_if_no_ano def books_list(data, sort_param, book_id, page): return render_books_list(data, sort_param, book_id, page) @web.route("/table") @login_required def books_table(): visibility = current_user.view_settings.get('table', {}) cc = get_cc_columns(filter_config_custom_read=True) return render_title_template('book_table.html', title=_(u"Books List"), cc=cc, page="book_table", visiblility=visibility) @web.route("/ajax/listbooks") @login_required def list_books(): off = int(request.args.get("offset") or 0) limit = int(request.args.get("limit") or config.config_books_per_page) search = request.args.get("search") sort = request.args.get("sort", "id") order = request.args.get("order", "").lower() state = None join = tuple() if sort == "state": state = json.loads(request.args.get("state", "[]")) elif sort == "tags": order = [db.Tags.name.asc()] if order == "asc" else [db.Tags.name.desc()] join = db.books_tags_link,db.Books.id == db.books_tags_link.c.book, db.Tags elif sort == "series": order = [db.Series.name.asc()] if order == "asc" else [db.Series.name.desc()] join = db.books_series_link,db.Books.id == db.books_series_link.c.book, db.Series elif sort == "publishers": order = [db.Publishers.name.asc()] if order == "asc" else [db.Publishers.name.desc()] join = db.books_publishers_link,db.Books.id == db.books_publishers_link.c.book, db.Publishers elif sort == "authors": order = [db.Authors.name.asc(), db.Series.name, db.Books.series_index] if order == "asc" \ else [db.Authors.name.desc(), db.Series.name.desc(), db.Books.series_index.desc()] join = db.books_authors_link, db.Books.id == db.books_authors_link.c.book, db.Authors, \ db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series elif sort == "languages": order = [db.Languages.lang_code.asc()] if order == "asc" else [db.Languages.lang_code.desc()] join = db.books_languages_link, db.Books.id == db.books_languages_link.c.book, db.Languages elif order and sort in ["sort", "title", "authors_sort", "series_index"]: order = [text(sort + " " + order)] elif not state: order = [db.Books.timestamp.desc()] total_count = filtered_count = calibre_db.session.query(db.Books).filter(calibre_db.common_filters(False)).count() if state is not None: if search: books = calibre_db.search_query(search).all() filtered_count = len(books) else: books = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).all() entries = calibre_db.get_checkbox_sorted(books, state, off, limit, order) elif search: entries, filtered_count, __ = calibre_db.get_search_results(search, off, [order,''], limit, *join) else: entries, __, __ = calibre_db.fill_indexpage((int(off) / (int(limit)) + 1), limit, db.Books, True, order, *join) for entry in entries: for index in range(0, len(entry.languages)): entry.languages[index].language_name = isoLanguages.get_language_name(get_locale(), entry.languages[ index].lang_code) table_entries = {'totalNotFiltered': total_count, 'total': filtered_count, "rows": entries} js_list = json.dumps(table_entries, cls=db.AlchemyEncoder) response = make_response(js_list) response.headers["Content-Type"] = "application/json; charset=utf-8" return response @web.route("/ajax/table_settings", methods=['POST']) @login_required def update_table_settings(): # vals = request.get_json() # ToDo: Save table settings current_user.view_settings['table'] = json.loads(request.data) try: try: flag_modified(current_user, "view_settings") except AttributeError: pass ub.session.commit() except (InvalidRequestError, OperationalError): log.error("Invalid request received: %r ", request, ) return "Invalid request", 400 return "" @web.route("/author") @login_required_if_no_ano def author_list(): if current_user.check_visibility(constants.SIDEBAR_AUTHOR): if current_user.get_view_property('author', 'dir') == 'desc': order = db.Authors.sort.desc() order_no = 0 else: order = db.Authors.sort.asc() order_no = 1 entries = calibre_db.session.query(db.Authors, func.count('books_authors_link.book').label('count')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_authors_link.author')).order_by(order).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('char')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all() # If not creating a copy, readonly databases can not display authornames with "|" in it as changing the name # starts a change session autor_copy = copy.deepcopy(entries) for entry in autor_copy: entry.Authors.name = entry.Authors.name.replace('|', ',') return render_title_template('list.html', entries=autor_copy, folder='web.books_list', charlist=charlist, title=u"Authors", page="authorlist", data='author', order=order_no) else: abort(404) @web.route("/downloadlist") @login_required_if_no_ano def download_list(): if current_user.get_view_property('download', 'dir') == 'desc': order = ub.User.name.desc() order_no = 0 else: order = ub.User.name.asc() order_no = 1 if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin(): entries = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count'))\ .join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(order).all() charlist = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \ .filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \ .group_by(func.upper(func.substr(ub.User.name, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Downloads"), page="downloadlist", data="download", order=order_no) else: abort(404) @web.route("/publisher") @login_required_if_no_ano def publisher_list(): if current_user.get_view_property('publisher', 'dir') == 'desc': order = db.Publishers.name.desc() order_no = 0 else: order = db.Publishers.name.asc() order_no = 1 if current_user.check_visibility(constants.SIDEBAR_PUBLISHER): entries = calibre_db.session.query(db.Publishers, func.count('books_publishers_link.book').label('count')) \ .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_publishers_link.publisher')).order_by(order).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Publishers.name, 1, 1)).label('char')) \ .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Publishers.name, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Publishers"), page="publisherlist", data="publisher", order=order_no) else: abort(404) @web.route("/series") @login_required_if_no_ano def series_list(): if current_user.check_visibility(constants.SIDEBAR_SERIES): if current_user.get_view_property('series', 'dir') == 'desc': order = db.Series.sort.desc() order_no = 0 else: order = db.Series.sort.asc() order_no = 1 if current_user.get_view_property('series', 'series_view') == 'list': entries = calibre_db.session.query(db.Series, func.count('books_series_link.book').label('count')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series')).order_by(order).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Series"), page="serieslist", data="series", order=order_no) else: entries = calibre_db.session.query(db.Books, func.count('books_series_link').label('count'), func.max(db.Books.series_index), db.Books.id) \ .join(db.books_series_link).join(db.Series).filter(calibre_db.common_filters())\ .group_by(text('books_series_link.series')).order_by(order).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all() return render_title_template('grid.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Series"), page="serieslist", data="series", bodyClass="grid-view", order=order_no) else: abort(404) @web.route("/ratings") @login_required_if_no_ano def ratings_list(): if current_user.check_visibility(constants.SIDEBAR_RATING): if current_user.get_view_property('ratings', 'dir') == 'desc': order = db.Ratings.rating.desc() order_no = 0 else: order = db.Ratings.rating.asc() order_no = 1 entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_ratings_link.rating')).order_by(order).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(), title=_(u"Ratings list"), page="ratingslist", data="ratings", order=order_no) else: abort(404) @web.route("/formats") @login_required_if_no_ano def formats_list(): if current_user.check_visibility(constants.SIDEBAR_FORMAT): if current_user.get_view_property('ratings', 'dir') == 'desc': order = db.Data.format.desc() order_no = 0 else: order = db.Data.format.asc() order_no = 1 entries = calibre_db.session.query(db.Data, func.count('data.book').label('count'), db.Data.format.label('format')) \ .join(db.Books).filter(calibre_db.common_filters()) \ .group_by(db.Data.format).order_by(order).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(), title=_(u"File formats list"), page="formatslist", data="formats", order=order_no) else: abort(404) @web.route("/language") @login_required_if_no_ano def language_overview(): if current_user.check_visibility(constants.SIDEBAR_LANGUAGE) and current_user.filter_language() == u"all": order_no = 0 if current_user.get_view_property('language', 'dir') == 'desc' else 1 charlist = list() languages = calibre_db.speaking_language(reverse_order=not order_no, with_count=True) for lang in languages: upper_lang = lang[0].name[0].upper() if upper_lang not in charlist: charlist.append(upper_lang) return render_title_template('languages.html', languages=languages, charlist=charlist, title=_(u"Languages"), page="langlist", data="language", order=order_no) else: abort(404) @web.route("/category") @login_required_if_no_ano def category_list(): if current_user.check_visibility(constants.SIDEBAR_CATEGORY): if current_user.get_view_property('category', 'dir') == 'desc': order = db.Tags.name.desc() order_no = 0 else: order = db.Tags.name.asc() order_no = 1 entries = calibre_db.session.query(db.Tags, func.count('books_tags_link.book').label('count')) \ .join(db.books_tags_link).join(db.Books).order_by(order).filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag')).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('char')) \ .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Categories"), page="catlist", data="category", order=order_no) else: abort(404) # ################################### Task functions ################################################################ @web.route("/tasks") @login_required def get_tasks_status(): # if current user admin, show all email, otherwise only own emails tasks = WorkerThread.getInstance().tasks answer = render_task_status(tasks) return render_title_template('tasks.html', entries=answer, title=_(u"Tasks"), page="tasks") @app.route("/reconnect") def reconnect(): calibre_db.reconnect_db(config, ub.app_DB_path) return json.dumps({}) # ################################### Search functions ################################################################ @web.route("/search", methods=["GET"]) @login_required_if_no_ano def search(): term = request.args.get("query") if term: return redirect(url_for('web.books_list', data="search", sort_param='stored', query=term)) else: return render_title_template('search.html', searchterm="", result_count=0, title=_(u"Search"), page="search") @web.route("/advsearch", methods=['POST']) @login_required_if_no_ano def advanced_search(): values = dict(request.form) params = ['include_tag', 'exclude_tag', 'include_serie', 'exclude_serie', 'include_shelf', 'exclude_shelf', 'include_language', 'exclude_language', 'include_extension', 'exclude_extension'] for param in params: values[param] = list(request.form.getlist(param)) flask_session['query'] = json.dumps(values) return redirect(url_for('web.books_list', data="advsearch", sort_param='stored', query="")) def adv_search_custom_columns(cc, term, q): for c in cc: if c.datatype == "datetime": custom_start = term.get('custom_column_' + str(c.id) + '_start') custom_end = term.get('custom_column_' + str(c.id) + '_end') if custom_start: q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.datetime(db.cc_classes[c.id].value) >= func.datetime(custom_start))) if custom_end: q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.datetime(db.cc_classes[c.id].value) <= func.datetime(custom_end))) else: custom_query = term.get('custom_column_' + str(c.id)) if custom_query != '' and custom_query is not None: if c.datatype == 'bool': q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == (custom_query == "True"))) elif c.datatype == 'int' or c.datatype == 'float': q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == custom_query)) elif c.datatype == 'rating': q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == int(float(custom_query) * 2))) else: q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.lower(db.cc_classes[c.id].value).ilike("%" + custom_query + "%"))) return q def adv_search_language(q, include_languages_inputs, exclude_languages_inputs): if current_user.filter_language() != "all": q = q.filter(db.Books.languages.any(db.Languages.lang_code == current_user.filter_language())) else: for language in include_languages_inputs: q = q.filter(db.Books.languages.any(db.Languages.id == language)) for language in exclude_languages_inputs: q = q.filter(not_(db.Books.series.any(db.Languages.id == language))) return q def adv_search_ratings(q, rating_high, rating_low): if rating_high: rating_high = int(rating_high) * 2 q = q.filter(db.Books.ratings.any(db.Ratings.rating <= rating_high)) if rating_low: rating_low = int(rating_low) * 2 q = q.filter(db.Books.ratings.any(db.Ratings.rating >= rating_low)) return q def adv_search_read_status(q, read_status): if read_status: if config.config_read_column: try: if read_status == "True": q = q.join(db.cc_classes[config.config_read_column], isouter=True) \ .filter(db.cc_classes[config.config_read_column].value == True) else: q = q.join(db.cc_classes[config.config_read_column], isouter=True) \ .filter(coalesce(db.cc_classes[config.config_read_column].value, False) != True) except (KeyError, AttributeError): log.error(u"Custom Column No.%d is not existing in calibre database", config.config_read_column) flash(_("Custom Column No.%(column)d is not existing in calibre database", column=config.config_read_column), category="error") return q else: if read_status == "True": q = q.join(ub.ReadBook, db.Books.id == ub.ReadBook.book_id, isouter=True) \ .filter(ub.ReadBook.user_id == int(current_user.id), ub.ReadBook.read_status == ub.ReadBook.STATUS_FINISHED) else: q = q.join(ub.ReadBook, db.Books.id == ub.ReadBook.book_id, isouter=True) \ .filter(ub.ReadBook.user_id == int(current_user.id), coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED) return q def adv_search_extension(q, include_extension_inputs, exclude_extension_inputs): for extension in include_extension_inputs: q = q.filter(db.Books.data.any(db.Data.format == extension)) for extension in exclude_extension_inputs: q = q.filter(not_(db.Books.data.any(db.Data.format == extension))) return q def adv_search_tag(q, include_tag_inputs, exclude_tag_inputs): for tag in include_tag_inputs: q = q.filter(db.Books.tags.any(db.Tags.id == tag)) for tag in exclude_tag_inputs: q = q.filter(not_(db.Books.tags.any(db.Tags.id == tag))) return q def adv_search_serie(q, include_series_inputs, exclude_series_inputs): for serie in include_series_inputs: q = q.filter(db.Books.series.any(db.Series.id == serie)) for serie in exclude_series_inputs: q = q.filter(not_(db.Books.series.any(db.Series.id == serie))) return q def adv_search_shelf(q, include_shelf_inputs, exclude_shelf_inputs): q = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\ .filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(exclude_shelf_inputs))) if len(include_shelf_inputs) > 0: q = q.filter(ub.BookShelf.shelf.in_(include_shelf_inputs)) return q def extend_search_term(searchterm, author_name, book_title, publisher, pub_start, pub_end, tags, rating_high, rating_low, read_status, ): searchterm.extend((author_name.replace('|', ','), book_title, publisher)) if pub_start: try: searchterm.extend([_(u"Published after ") + format_date(datetime.strptime(pub_start, "%Y-%m-%d"), format='medium', locale=get_locale())]) except ValueError: pub_start = u"" if pub_end: try: searchterm.extend([_(u"Published before ") + format_date(datetime.strptime(pub_end, "%Y-%m-%d"), format='medium', locale=get_locale())]) except ValueError: pub_end = u"" elements = {'tag': db.Tags, 'serie':db.Series, 'shelf':ub.Shelf} for key, db_element in elements.items(): tag_names = calibre_db.session.query(db_element).filter(db_element.id.in_(tags['include_' + key])).all() searchterm.extend(tag.name for tag in tag_names) tag_names = calibre_db.session.query(db_element).filter(db_element.id.in_(tags['exclude_' + key])).all() searchterm.extend(tag.name for tag in tag_names) language_names = calibre_db.session.query(db.Languages). \ filter(db.Languages.id.in_(tags['include_language'])).all() if language_names: language_names = calibre_db.speaking_language(language_names) searchterm.extend(language.name for language in language_names) language_names = calibre_db.session.query(db.Languages). \ filter(db.Languages.id.in_(tags['exclude_language'])).all() if language_names: language_names = calibre_db.speaking_language(language_names) searchterm.extend(language.name for language in language_names) if rating_high: searchterm.extend([_(u"Rating <= %(rating)s", rating=rating_high)]) if rating_low: searchterm.extend([_(u"Rating >= %(rating)s", rating=rating_low)]) if read_status: searchterm.extend([_(u"Read Status = %(status)s", status=read_status)]) searchterm.extend(ext for ext in tags['include_extension']) searchterm.extend(ext for ext in tags['exclude_extension']) # handle custom columns searchterm = " + ".join(filter(None, searchterm)) return searchterm, pub_start, pub_end def render_adv_search_results(term, offset=None, order=None, limit=None): sort = order[0] if order else [db.Books.sort] pagination = None cc = get_cc_columns(filter_config_custom_read=True) calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase) q = calibre_db.session.query(db.Books).outerjoin(db.books_series_link, db.Books.id == db.books_series_link.c.book)\ .outerjoin(db.Series)\ .filter(calibre_db.common_filters(True)) # parse multiselects to a complete dict tags = dict() elements = ['tag', 'serie', 'shelf', 'language', 'extension'] for element in elements: tags['include_' + element] = term.get('include_' + element) tags['exclude_' + element] = term.get('exclude_' + element) author_name = term.get("author_name") book_title = term.get("book_title") publisher = term.get("publisher") pub_start = term.get("publishstart") pub_end = term.get("publishend") rating_low = term.get("ratinghigh") rating_high = term.get("ratinglow") description = term.get("comment") read_status = term.get("read_status") if author_name: author_name = author_name.strip().lower().replace(',', '|') if book_title: book_title = book_title.strip().lower() if publisher: publisher = publisher.strip().lower() searchterm = [] cc_present = False for c in cc: if c.datatype == "datetime": column_start = term.get('custom_column_' + str(c.id) + '_start') column_end = term.get('custom_column_' + str(c.id) + '_end') if column_start: searchterm.extend([u"{} >= {}".format(c.name, format_date(datetime.strptime(column_start, "%Y-%m-%d").date(), format='medium', locale=get_locale()) )]) cc_present = True if column_end: searchterm.extend([u"{} <= {}".format(c.name, format_date(datetime.strptime(column_end, "%Y-%m-%d").date(), format='medium', locale=get_locale()) )]) cc_present = True elif term.get('custom_column_' + str(c.id)): searchterm.extend([(u"{}: {}".format(c.name, term.get('custom_column_' + str(c.id))))]) cc_present = True if any(tags.values()) or author_name or book_title or publisher or pub_start or pub_end or rating_low \ or rating_high or description or cc_present or read_status: searchterm, pub_start, pub_end = extend_search_term(searchterm, author_name, book_title, publisher, pub_start, pub_end, tags, rating_high, rating_low, read_status) q = q.filter() if author_name: q = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + author_name + "%"))) if book_title: q = q.filter(func.lower(db.Books.title).ilike("%" + book_title + "%")) if pub_start: q = q.filter(func.datetime(db.Books.pubdate) > func.datetime(pub_start)) if pub_end: q = q.filter(func.datetime(db.Books.pubdate) < func.datetime(pub_end)) q = adv_search_read_status(q, read_status) if publisher: q = q.filter(db.Books.publishers.any(func.lower(db.Publishers.name).ilike("%" + publisher + "%"))) q = adv_search_tag(q, tags['include_tag'], tags['exclude_tag']) q = adv_search_serie(q, tags['include_serie'], tags['exclude_serie']) q = adv_search_shelf(q, tags['include_shelf'], tags['exclude_shelf']) q = adv_search_extension(q, tags['include_extension'], tags['exclude_extension']) q = adv_search_language(q, tags['include_language'], tags['exclude_language']) q = adv_search_ratings(q, rating_high, rating_low) if description: q = q.filter(db.Books.comments.any(func.lower(db.Comments.text).ilike("%" + description + "%"))) # search custom culumns try: q = adv_search_custom_columns(cc, term, q) except AttributeError as ex: log.debug_or_exception(ex) flash(_("Error on search for custom columns, please restart Calibre-Web"), category="error") q = q.order_by(*sort).all() flask_session['query'] = json.dumps(term) ub.store_ids(q) result_count = len(q) if offset is not None and limit is not None: offset = int(offset) limit_all = offset + int(limit) pagination = Pagination((offset / (int(limit)) + 1), limit, result_count) else: offset = 0 limit_all = result_count return render_title_template('search.html', adv_searchterm=searchterm, pagination=pagination, entries=q[offset:limit_all], result_count=result_count, title=_(u"Advanced Search"), page="advsearch", order=order[1]) @web.route("/advsearch", methods=['GET']) @login_required_if_no_ano def advanced_search_form(): # Build custom columns names cc = get_cc_columns(filter_config_custom_read=True) return render_prepare_search_form(cc) # ################################### Download/Send ################################################################## @web.route("/cover/<int:book_id>") @login_required_if_no_ano def get_cover(book_id): return get_book_cover(book_id) @web.route("/robots.txt") def get_robots(): return send_from_directory(constants.STATIC_DIR, "robots.txt") @web.route("/show/<int:book_id>/<book_format>", defaults={'anyname': 'None'}) @web.route("/show/<int:book_id>/<book_format>/<anyname>") @login_required_if_no_ano @viewer_required def serve_book(book_id, book_format, anyname): book_format = book_format.split(".")[0] book = calibre_db.get_book(book_id) data = calibre_db.get_book_format(book_id, book_format.upper()) if not data: return "File not in Database" log.info('Serving book: %s', data.name) if config.config_use_google_drive: try: headers = Headers() headers["Content-Type"] = mimetypes.types_map.get('.' + book_format, "application/octet-stream") df = getFileFromEbooksFolder(book.path, data.name + "." + book_format) return do_gdrive_download(df, headers, (book_format.upper() == 'TXT')) except AttributeError as ex: log.debug_or_exception(ex) return "File Not Found" else: if book_format.upper() == 'TXT': try: rawdata = open(os.path.join(config.config_calibre_dir, book.path, data.name + "." + book_format), "rb").read() result = chardet.detect(rawdata) return make_response( rawdata.decode(result['encoding'], 'surrogatepass').encode('utf-8', 'surrogatepass')) except FileNotFoundError: log.error("File Not Found") return "File Not Found" return send_from_directory(os.path.join(config.config_calibre_dir, book.path), data.name + "." + book_format) @web.route("/download/<int:book_id>/<book_format>", defaults={'anyname': 'None'}) @web.route("/download/<int:book_id>/<book_format>/<anyname>") @login_required_if_no_ano @download_required def download_link(book_id, book_format, anyname): client = "kobo" if "Kobo" in request.headers.get('User-Agent') else "" return get_download_link(book_id, book_format, client) @web.route('/send/<int:book_id>/<book_format>/<int:convert>') @login_required @download_required def send_to_kindle(book_id, book_format, convert): if not config.get_mail_server_configured(): flash(_(u"Please configure the SMTP mail settings first..."), category="error") elif current_user.kindle_mail: result = send_mail(book_id, book_format, convert, current_user.kindle_mail, config.config_calibre_dir, current_user.name) if result is None: flash(_(u"Book successfully queued for sending to %(kindlemail)s", kindlemail=current_user.kindle_mail), category="success") ub.update_download(book_id, int(current_user.id)) else: flash(_(u"Oops! There was an error sending this book: %(res)s", res=result), category="error") else: flash(_(u"Please update your profile with a valid Send to Kindle E-mail Address."), category="error") if "HTTP_REFERER" in request.environ: return redirect(request.environ["HTTP_REFERER"]) else: return redirect(url_for('web.index')) # ################################### Login Logout ################################################################## @web.route('/register', methods=['GET', 'POST']) def register(): if not config.config_public_reg: abort(404) if current_user is not None and current_user.is_authenticated: return redirect(url_for('web.index')) if not config.get_mail_server_configured(): flash(_(u"E-Mail server is not configured, please contact your administrator!"), category="error") return render_title_template('register.html', title=_("Register"), page="register") if request.method == "POST": to_save = request.form.to_dict() nickname = to_save["email"].strip() if config.config_register_email else to_save.get('name') if not nickname or not to_save.get("email"): flash(_(u"Please fill out all fields!"), category="error") return render_title_template('register.html', title=_("Register"), page="register") try: nickname = check_username(nickname) email = check_email(to_save["email"]) except Exception as ex: flash(str(ex), category="error") return render_title_template('register.html', title=_("Register"), page="register") content = ub.User() if check_valid_domain(email): content.name = nickname content.email = email password = generate_random_password() content.password = generate_password_hash(password) content.role = config.config_default_role content.sidebar_view = config.config_default_show try: ub.session.add(content) ub.session.commit() if feature_support['oauth']: register_user_with_oauth(content) send_registration_mail(to_save["email"].strip(), nickname, password) except Exception: ub.session.rollback() flash(_(u"An unknown error occurred. Please try again later."), category="error") return render_title_template('register.html', title=_("Register"), page="register") else: flash(_(u"Your e-mail is not allowed to register"), category="error") log.warning('Registering failed for user "%s" e-mail address: %s', nickname, to_save["email"]) return render_title_template('register.html', title=_("Register"), page="register") flash(_(u"Confirmation e-mail was send to your e-mail account."), category="success") return redirect(url_for('web.login')) if feature_support['oauth']: register_user_with_oauth() return render_title_template('register.html', config=config, title=_("Register"), page="register") @web.route('/login', methods=['GET', 'POST']) def login(): if current_user is not None and current_user.is_authenticated: return redirect(url_for('web.index')) if config.config_login_type == constants.LOGIN_LDAP and not services.ldap: log.error(u"Cannot activate LDAP authentication") flash(_(u"Cannot activate LDAP authentication"), category="error") if request.method == "POST": form = request.form.to_dict() user = ub.session.query(ub.User).filter(func.lower(ub.User.name) == form['username'].strip().lower()) \ .first() if config.config_login_type == constants.LOGIN_LDAP and services.ldap and user and form['password'] != "": login_result, error = services.ldap.bind_user(form['username'], form['password']) if login_result: login_user(user, remember=bool(form.get('remember_me'))) ub.store_user_session() log.debug(u"You are now logged in as: '%s'", user.name) flash(_(u"you are now logged in as: '%(nickname)s'", nickname=user.name), category="success") return redirect_back(url_for("web.index")) elif login_result is None and user and check_password_hash(str(user.password), form['password']) \ and user.name != "Guest": login_user(user, remember=bool(form.get('remember_me'))) ub.store_user_session() log.info("Local Fallback Login as: '%s'", user.name) flash(_(u"Fallback Login as: '%(nickname)s', LDAP Server not reachable, or user not known", nickname=user.name), category="warning") return redirect_back(url_for("web.index")) elif login_result is None: log.info(error) flash(_(u"Could not login: %(message)s", message=error), category="error") else: ip_Address = request.headers.get('X-Forwarded-For', request.remote_addr) log.warning('LDAP Login failed for user "%s" IP-address: %s', form['username'], ip_Address) flash(_(u"Wrong Username or Password"), category="error") else: ip_Address = request.headers.get('X-Forwarded-For', request.remote_addr) if 'forgot' in form and form['forgot'] == 'forgot': if user is not None and user.name != "Guest": ret, __ = reset_password(user.id) if ret == 1: flash(_(u"New Password was send to your email address"), category="info") log.info('Password reset for user "%s" IP-address: %s', form['username'], ip_Address) else: log.error(u"An unknown error occurred. Please try again later") flash(_(u"An unknown error occurred. Please try again later."), category="error") else: flash(_(u"Please enter valid username to reset password"), category="error") log.warning('Username missing for password reset IP-address: %s', ip_Address) else: if user and check_password_hash(str(user.password), form['password']) and user.name != "Guest": login_user(user, remember=bool(form.get('remember_me'))) ub.store_user_session() log.debug(u"You are now logged in as: '%s'", user.name) flash(_(u"You are now logged in as: '%(nickname)s'", nickname=user.name), category="success") config.config_is_initial = False return redirect_back(url_for("web.index")) else: log.warning('Login failed for user "%s" IP-address: %s', form['username'], ip_Address) flash(_(u"Wrong Username or Password"), category="error") next_url = request.args.get('next', default=url_for("web.index"), type=str) if url_for("web.logout") == next_url: next_url = url_for("web.index") return render_title_template('login.html', title=_(u"Login"), next_url=next_url, config=config, oauth_check=oauth_check, mail=config.get_mail_server_configured(), page="login") @web.route('/logout') @login_required def logout(): if current_user is not None and current_user.is_authenticated: ub.delete_user_session(current_user.id, flask_session.get('_id',"")) logout_user() if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3): logout_oauth_user() log.debug(u"User logged out") return redirect(url_for('web.login')) # ################################### Users own configuration ######################################################### def change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages): to_save = request.form.to_dict() current_user.random_books = 0 if current_user.role_passwd() or current_user.role_admin(): if to_save.get("password"): current_user.password = generate_password_hash(to_save["password"]) try: if to_save.get("kindle_mail", current_user.kindle_mail) != current_user.kindle_mail: current_user.kindle_mail = valid_email(to_save["kindle_mail"]) if to_save.get("email", current_user.email) != current_user.email: current_user.email = check_email(to_save["email"]) if current_user.role_admin(): if to_save.get("name", current_user.name) != current_user.name: # Query User name, if not existing, change current_user.name = check_username(to_save["name"]) current_user.random_books = 1 if to_save.get("show_random") == "on" else 0 if to_save.get("default_language"): current_user.default_language = to_save["default_language"] if to_save.get("locale"): current_user.locale = to_save["locale"] old_state = current_user.kobo_only_shelves_sync # 1 -> 0: nothing has to be done # 0 -> 1: all synced books have to be added to archived books, + currently synced shelfs which # don't have to be synced have to be removed (added to Shelf archive) current_user.kobo_only_shelves_sync = int(to_save.get("kobo_only_shelves_sync") == "on") or 0 if old_state == 0 and current_user.kobo_only_shelves_sync == 1: kobo_sync_status.update_on_sync_shelfs(current_user.id) except Exception as ex: flash(str(ex), category="error") return render_title_template("user_edit.html", content=current_user, translations=translations, profile=1, languages=languages, title=_(u"%(name)s's profile", name=current_user.name), page="me", kobo_support=kobo_support, registered_oauth=local_oauth_check, oauth_status=oauth_status) val = 0 for key, __ in to_save.items(): if key.startswith('show'): val += int(key[5:]) current_user.sidebar_view = val if to_save.get("Show_detail_random"): current_user.sidebar_view += constants.DETAIL_RANDOM try: ub.session.commit() flash(_(u"Profile updated"), category="success") log.debug(u"Profile updated") except IntegrityError: ub.session.rollback() flash(_(u"Found an existing account for this e-mail address"), category="error") log.debug(u"Found an existing account for this e-mail address") except OperationalError as e: ub.session.rollback() log.error("Database error: %s", e) flash(_(u"Database error: %(error)s.", error=e), category="error") @web.route("/me", methods=["GET", "POST"]) @login_required def profile(): languages = calibre_db.speaking_language() translations = babel.list_translations() + [LC('en')] kobo_support = feature_support['kobo'] and config.config_kobo_sync if feature_support['oauth'] and config.config_login_type == 2: oauth_status = get_oauth_status() local_oauth_check = oauth_check else: oauth_status = None local_oauth_check = {} if request.method == "POST": change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages) return render_title_template("user_edit.html", translations=translations, profile=1, languages=languages, content=current_user, kobo_support=kobo_support, title=_(u"%(name)s's profile", name=current_user.name), page="me", registered_oauth=local_oauth_check, oauth_status=oauth_status) # ###################################Show single book ################################################################## @web.route("/read/<int:book_id>/<book_format>") @login_required_if_no_ano @viewer_required def read_book(book_id, book_format): book = calibre_db.get_filtered_book(book_id) if not book: flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible") return redirect(url_for("web.index")) # check if book has bookmark bookmark = None if current_user.is_authenticated: bookmark = ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id), ub.Bookmark.book_id == book_id, ub.Bookmark.format == book_format.upper())).first() if book_format.lower() == "epub": log.debug(u"Start epub reader for %d", book_id) return render_title_template('read.html', bookid=book_id, title=book.title, bookmark=bookmark) elif book_format.lower() == "pdf": log.debug(u"Start pdf reader for %d", book_id) return render_title_template('readpdf.html', pdffile=book_id, title=book.title) elif book_format.lower() == "txt": log.debug(u"Start txt reader for %d", book_id) return render_title_template('readtxt.html', txtfile=book_id, title=book.title) elif book_format.lower() == "djvu": log.debug(u"Start djvu reader for %d", book_id) return render_title_template('readdjvu.html', djvufile=book_id, title=book.title) else: for fileExt in constants.EXTENSIONS_AUDIO: if book_format.lower() == fileExt: entries = calibre_db.get_filtered_book(book_id) log.debug(u"Start mp3 listening for %d", book_id) return render_title_template('listenmp3.html', mp3file=book_id, audioformat=book_format.lower(), entry=entries, bookmark=bookmark) for fileExt in ["cbr", "cbt", "cbz"]: if book_format.lower() == fileExt: all_name = str(book_id) title = book.title if len(book.series): title = title + " - " + book.series[0].name if book.series_index: title = title + " #" + '{0:.2f}'.format(book.series_index).rstrip('0').rstrip('.') log.debug(u"Start comic reader for %d", book_id) return render_title_template('readcbr.html', comicfile=all_name, title=title, extension=fileExt) log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) @web.route("/book/<int:book_id>") @login_required_if_no_ano def show_book(book_id): entries = calibre_db.get_filtered_book(book_id, allow_show_archived=True) if entries: for index in range(0, len(entries.languages)): entries.languages[index].language_name = isoLanguages.get_language_name(get_locale(), entries.languages[ index].lang_code) cc = get_cc_columns(filter_config_custom_read=True) book_in_shelfs = [] shelfs = ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).all() for entry in shelfs: book_in_shelfs.append(entry.shelf) if not current_user.is_anonymous: if not config.config_read_column: matching_have_read_book = ub.session.query(ub.ReadBook). \ filter(and_(ub.ReadBook.user_id == int(current_user.id), ub.ReadBook.book_id == book_id)).all() have_read = len( matching_have_read_book) > 0 and matching_have_read_book[0].read_status == ub.ReadBook.STATUS_FINISHED else: try: matching_have_read_book = getattr(entries, 'custom_column_' + str(config.config_read_column)) have_read = len(matching_have_read_book) > 0 and matching_have_read_book[0].value except (KeyError, AttributeError): log.error("Custom Column No.%d is not existing in calibre database", config.config_read_column) have_read = None archived_book = ub.session.query(ub.ArchivedBook).\ filter(and_(ub.ArchivedBook.user_id == int(current_user.id), ub.ArchivedBook.book_id == book_id)).first() is_archived = archived_book and archived_book.is_archived else: have_read = None is_archived = None entries.tags = sort(entries.tags, key=lambda tag: tag.name) entries = calibre_db.order_authors(entries) kindle_list = check_send_to_kindle(entries) reader_list = check_read_formats(entries) audioentries = [] for media_format in entries.data: if media_format.format.lower() in constants.EXTENSIONS_AUDIO: audioentries.append(media_format.format.lower()) return render_title_template('detail.html', entry=entries, audioentries=audioentries, cc=cc, is_xhr=request.headers.get('X-Requested-With')=='XMLHttpRequest', title=entries.title, books_shelfs=book_in_shelfs, have_read=have_read, is_archived=is_archived, kindle_list=kindle_list, reader_list=reader_list, page="book") else: log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index"))
# -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, # andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, # falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, # ruben-herold, marblepebble, JackED42, SiphonSquirrel, # apetresc, nanu-c, mutschler # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os from datetime import datetime import json import mimetypes import chardet # dependency of requests import copy from babel.dates import format_date from babel import Locale as LC from flask import Blueprint, jsonify from flask import request, redirect, send_from_directory, make_response, flash, abort, url_for from flask import session as flask_session from flask_babel import gettext as _ from flask_login import login_user, logout_user, login_required, current_user from sqlalchemy.exc import IntegrityError, InvalidRequestError, OperationalError from sqlalchemy.sql.expression import text, func, false, not_, and_, or_ from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.sql.functions import coalesce from .services.worker import WorkerThread from werkzeug.datastructures import Headers from werkzeug.security import generate_password_hash, check_password_hash from . import constants, logger, isoLanguages, services from . import babel, db, ub, config, get_locale, app from . import calibre_db, kobo_sync_status from .gdriveutils import getFileFromEbooksFolder, do_gdrive_download from .helper import check_valid_domain, render_task_status, check_email, check_username, \ get_cc_columns, get_book_cover, get_download_link, send_mail, generate_random_password, \ send_registration_mail, check_send_to_kindle, check_read_formats, tags_filters, reset_password, valid_email from .pagination import Pagination from .redirect import redirect_back from .usermanagement import login_required_if_no_ano from .kobo_sync_status import remove_synced_book from .render_template import render_title_template from .kobo_sync_status import change_archived_books feature_support = { 'ldap': bool(services.ldap), 'goodreads': bool(services.goodreads_support), 'kobo': bool(services.kobo) } try: from .oauth_bb import oauth_check, register_user_with_oauth, logout_oauth_user, get_oauth_status feature_support['oauth'] = True except ImportError: feature_support['oauth'] = False oauth_check = {} try: from functools import wraps except ImportError: pass # We're not using Python 3 try: from natsort import natsorted as sort except ImportError: sort = sorted # Just use regular sort then, may cause issues with badly named pages in cbz/cbr files @app.after_request def add_security_headers(resp): resp.headers['Content-Security-Policy'] = "default-src 'self'" + ''.join([' '+host for host in config.config_trustedhosts.strip().split(',')]) + " 'unsafe-inline' 'unsafe-eval'; font-src 'self' data:; img-src 'self' data:" if request.endpoint == "editbook.edit_book" or config.config_use_google_drive: resp.headers['Content-Security-Policy'] += " *" elif request.endpoint == "web.read_book": resp.headers['Content-Security-Policy'] += " blob:;style-src-elem 'self' blob: 'unsafe-inline';" resp.headers['X-Content-Type-Options'] = 'nosniff' resp.headers['X-Frame-Options'] = 'SAMEORIGIN' resp.headers['X-XSS-Protection'] = '1; mode=block' resp.headers['Strict-Transport-Security'] = 'max-age=31536000;' return resp web = Blueprint('web', __name__) log = logger.create() # ################################### Login logic and rights management ############################################### def download_required(f): @wraps(f) def inner(*args, **kwargs): if current_user.role_download(): return f(*args, **kwargs) abort(403) return inner def viewer_required(f): @wraps(f) def inner(*args, **kwargs): if current_user.role_viewer(): return f(*args, **kwargs) abort(403) return inner # ################################### data provider functions ######################################################### @web.route("/ajax/emailstat") @login_required def get_email_status_json(): tasks = WorkerThread.getInstance().tasks return jsonify(render_task_status(tasks)) @web.route("/ajax/bookmark/<int:book_id>/<book_format>", methods=['POST']) @login_required def bookmark(book_id, book_format): bookmark_key = request.form["bookmark"] ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id), ub.Bookmark.book_id == book_id, ub.Bookmark.format == book_format)).delete() if not bookmark_key: ub.session_commit() return "", 204 lbookmark = ub.Bookmark(user_id=current_user.id, book_id=book_id, format=book_format, bookmark_key=bookmark_key) ub.session.merge(lbookmark) ub.session_commit("Bookmark for user {} in book {} created".format(current_user.id, book_id)) return "", 201 @web.route("/ajax/toggleread/<int:book_id>", methods=['POST']) @login_required def toggle_read(book_id): if not config.config_read_column: book = ub.session.query(ub.ReadBook).filter(and_(ub.ReadBook.user_id == int(current_user.id), ub.ReadBook.book_id == book_id)).first() if book: if book.read_status == ub.ReadBook.STATUS_FINISHED: book.read_status = ub.ReadBook.STATUS_UNREAD else: book.read_status = ub.ReadBook.STATUS_FINISHED else: readBook = ub.ReadBook(user_id=current_user.id, book_id = book_id) readBook.read_status = ub.ReadBook.STATUS_FINISHED book = readBook if not book.kobo_reading_state: kobo_reading_state = ub.KoboReadingState(user_id=current_user.id, book_id=book_id) kobo_reading_state.current_bookmark = ub.KoboBookmark() kobo_reading_state.statistics = ub.KoboStatistics() book.kobo_reading_state = kobo_reading_state ub.session.merge(book) ub.session_commit("Book {} readbit toggled".format(book_id)) else: try: calibre_db.update_title_sort(config) book = calibre_db.get_filtered_book(book_id) read_status = getattr(book, 'custom_column_' + str(config.config_read_column)) if len(read_status): read_status[0].value = not read_status[0].value calibre_db.session.commit() else: cc_class = db.cc_classes[config.config_read_column] new_cc = cc_class(value=1, book=book_id) calibre_db.session.add(new_cc) calibre_db.session.commit() except (KeyError, AttributeError): log.error(u"Custom Column No.%d is not existing in calibre database", config.config_read_column) return "Custom Column No.{} is not existing in calibre database".format(config.config_read_column), 400 except (OperationalError, InvalidRequestError) as e: calibre_db.session.rollback() log.error(u"Read status could not set: {}".format(e)) return "Read status could not set: {}".format(e), 400 return "" @web.route("/ajax/togglearchived/<int:book_id>", methods=['POST']) @login_required def toggle_archived(book_id): is_archived = change_archived_books(book_id, message="Book {} archivebit toggled".format(book_id)) if is_archived: remove_synced_book(book_id) return "" @web.route("/ajax/view", methods=["POST"]) @login_required_if_no_ano def update_view(): to_save = request.get_json() try: for element in to_save: for param in to_save[element]: current_user.set_view_property(element, param, to_save[element][param]) except Exception as ex: log.error("Could not save view_settings: %r %r: %e", request, to_save, ex) return "Invalid request", 400 return "1", 200 ''' @web.route("/ajax/getcomic/<int:book_id>/<book_format>/<int:page>") @login_required def get_comic_book(book_id, book_format, page): book = calibre_db.get_book(book_id) if not book: return "", 204 else: for bookformat in book.data: if bookformat.format.lower() == book_format.lower(): cbr_file = os.path.join(config.config_calibre_dir, book.path, bookformat.name) + "." + book_format if book_format in ("cbr", "rar"): if feature_support['rar'] == True: rarfile.UNRAR_TOOL = config.config_rarfile_location try: rf = rarfile.RarFile(cbr_file) names = sort(rf.namelist()) extract = lambda page: rf.read(names[page]) except: # rarfile not valid log.error('Unrar binary not found, or unable to decompress file %s', cbr_file) return "", 204 else: log.info('Unrar is not supported please install python rarfile extension') # no support means return nothing return "", 204 elif book_format in ("cbz", "zip"): zf = zipfile.ZipFile(cbr_file) names=sort(zf.namelist()) extract = lambda page: zf.read(names[page]) elif book_format in ("cbt", "tar"): tf = tarfile.TarFile(cbr_file) names=sort(tf.getnames()) extract = lambda page: tf.extractfile(names[page]).read() else: log.error('unsupported comic format') return "", 204 b64 = codecs.encode(extract(page), 'base64').decode() ext = names[page].rpartition('.')[-1] if ext not in ('png', 'gif', 'jpg', 'jpeg', 'webp'): ext = 'png' extractedfile="data:image/" + ext + ";base64," + b64 fileData={"name": names[page], "page":page, "last":len(names)-1, "content": extractedfile} return make_response(json.dumps(fileData)) return "", 204 ''' # ################################### Typeahead ################################################################## @web.route("/get_authors_json", methods=['GET']) @login_required_if_no_ano def get_authors_json(): return calibre_db.get_typeahead(db.Authors, request.args.get('q'), ('|', ',')) @web.route("/get_publishers_json", methods=['GET']) @login_required_if_no_ano def get_publishers_json(): return calibre_db.get_typeahead(db.Publishers, request.args.get('q'), ('|', ',')) @web.route("/get_tags_json", methods=['GET']) @login_required_if_no_ano def get_tags_json(): return calibre_db.get_typeahead(db.Tags, request.args.get('q'), tag_filter=tags_filters()) @web.route("/get_series_json", methods=['GET']) @login_required_if_no_ano def get_series_json(): return calibre_db.get_typeahead(db.Series, request.args.get('q')) @web.route("/get_languages_json", methods=['GET']) @login_required_if_no_ano def get_languages_json(): query = (request.args.get('q') or '').lower() language_names = isoLanguages.get_language_names(get_locale()) entries_start = [s for key, s in language_names.items() if s.lower().startswith(query.lower())] if len(entries_start) < 5: entries = [s for key, s in language_names.items() if query in s.lower()] entries_start.extend(entries[0:(5 - len(entries_start))]) entries_start = list(set(entries_start)) json_dumps = json.dumps([dict(name=r) for r in entries_start[0:5]]) return json_dumps @web.route("/get_matching_tags", methods=['GET']) @login_required_if_no_ano def get_matching_tags(): tag_dict = {'tags': []} q = calibre_db.session.query(db.Books).filter(calibre_db.common_filters(True)) calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase) author_input = request.args.get('author_name') or '' title_input = request.args.get('book_title') or '' include_tag_inputs = request.args.getlist('include_tag') or '' exclude_tag_inputs = request.args.getlist('exclude_tag') or '' q = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + author_input + "%")), func.lower(db.Books.title).ilike("%" + title_input + "%")) if len(include_tag_inputs) > 0: for tag in include_tag_inputs: q = q.filter(db.Books.tags.any(db.Tags.id == tag)) if len(exclude_tag_inputs) > 0: for tag in exclude_tag_inputs: q = q.filter(not_(db.Books.tags.any(db.Tags.id == tag))) for book in q: for tag in book.tags: if tag.id not in tag_dict['tags']: tag_dict['tags'].append(tag.id) json_dumps = json.dumps(tag_dict) return json_dumps def get_sort_function(sort, data): order = [db.Books.timestamp.desc()] if sort == 'stored': sort = current_user.get_view_property(data, 'stored') else: current_user.set_view_property(data, 'stored', sort) if sort == 'pubnew': order = [db.Books.pubdate.desc()] if sort == 'pubold': order = [db.Books.pubdate] if sort == 'abc': order = [db.Books.sort] if sort == 'zyx': order = [db.Books.sort.desc()] if sort == 'new': order = [db.Books.timestamp.desc()] if sort == 'old': order = [db.Books.timestamp] if sort == 'authaz': order = [db.Books.author_sort.asc(), db.Series.name, db.Books.series_index] if sort == 'authza': order = [db.Books.author_sort.desc(), db.Series.name.desc(), db.Books.series_index.desc()] if sort == 'seriesasc': order = [db.Books.series_index.asc()] if sort == 'seriesdesc': order = [db.Books.series_index.desc()] if sort == 'hotdesc': order = [func.count(ub.Downloads.book_id).desc()] if sort == 'hotasc': order = [func.count(ub.Downloads.book_id).asc()] if sort is None: sort = "new" return order, sort def render_books_list(data, sort, book_id, page): order = get_sort_function(sort, data) if data == "rated": return render_rated_books(page, book_id, order=order) elif data == "discover": return render_discover_books(page, book_id) elif data == "unread": return render_read_books(page, False, order=order) elif data == "read": return render_read_books(page, True, order=order) elif data == "hot": return render_hot_books(page, order) elif data == "download": return render_downloaded_books(page, order, book_id) elif data == "author": return render_author_books(page, book_id, order) elif data == "publisher": return render_publisher_books(page, book_id, order) elif data == "series": return render_series_books(page, book_id, order) elif data == "ratings": return render_ratings_books(page, book_id, order) elif data == "formats": return render_formats_books(page, book_id, order) elif data == "category": return render_category_books(page, book_id, order) elif data == "language": return render_language_books(page, book_id, order) elif data == "archived": return render_archived_books(page, order) elif data == "search": term = (request.args.get('query') or '') offset = int(int(config.config_books_per_page) * (page - 1)) return render_search_results(term, offset, order, config.config_books_per_page) elif data == "advsearch": term = json.loads(flask_session['query']) offset = int(int(config.config_books_per_page) * (page - 1)) return render_adv_search_results(term, offset, order, config.config_books_per_page) else: website = data or "newest" entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, True, order[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=_(u"Books"), page=website, order=order[1]) def render_rated_books(page, book_id, order): if current_user.check_visibility(constants.SIDEBAR_BEST_RATED): entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.ratings.any(db.Ratings.rating > 9), order[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=book_id, title=_(u"Top Rated Books"), page="rated", order=order[1]) else: abort(404) def render_discover_books(page, book_id): if current_user.check_visibility(constants.SIDEBAR_RANDOM): entries, __, pagination = calibre_db.fill_indexpage(page, 0, db.Books, True, [func.randomblob(2)]) pagination = Pagination(1, config.config_books_per_page, config.config_books_per_page) return render_title_template('discover.html', entries=entries, pagination=pagination, id=book_id, title=_(u"Discover (Random Books)"), page="discover") else: abort(404) def render_hot_books(page, order): if current_user.check_visibility(constants.SIDEBAR_HOT): if order[1] not in ['hotasc', 'hotdesc']: # Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+ #if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or # order[0][0].compare(func.count(ub.Downloads.book_id).asc())): order = [func.count(ub.Downloads.book_id).desc()], 'hotdesc' if current_user.show_detail_random(): random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: random = false() off = int(int(config.config_books_per_page) * (page - 1)) all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\ .order_by(*order[0]).group_by(ub.Downloads.book_id) hot_books = all_books.offset(off).limit(config.config_books_per_page) entries = list() for book in hot_books: downloadBook = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter( db.Books.id == book.Downloads.book_id).first() if downloadBook: entries.append(downloadBook) else: ub.delete_download(book.Downloads.book_id) numBooks = entries.__len__() pagination = Pagination(page, config.config_books_per_page, numBooks) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=_(u"Hot Books (Most Downloaded)"), page="hot", order=order[1]) else: abort(404) def render_downloaded_books(page, order, user_id): if current_user.role_admin(): user_id = int(user_id) else: user_id = current_user.id if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD): if current_user.show_detail_random(): random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: random = false() entries, __, pagination = calibre_db.fill_indexpage(page, 0, db.Books, ub.Downloads.user_id == user_id, order[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, ub.Downloads, db.Books.id == ub.Downloads.book_id) for book in entries: if not calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .filter(db.Books.id == book.id).first(): ub.delete_download(book.id) user = ub.session.query(ub.User).filter(ub.User.id == user_id).first() return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=user_id, title=_(u"Downloaded books by %(user)s",user=user.name), page="download", order=order[1]) else: abort(404) def render_author_books(page, author_id, order): entries, __, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.authors.any(db.Authors.id == author_id), [order[0][0], db.Series.name, db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) if entries is None or not len(entries): flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) if constants.sqlalchemy_version2: author = calibre_db.session.get(db.Authors, author_id) else: author = calibre_db.session.query(db.Authors).get(author_id) author_name = author.name.replace('|', ',') author_info = None other_books = [] if services.goodreads_support and config.config_use_goodreads: author_info = services.goodreads_support.get_author_info(author_name) other_books = services.goodreads_support.get_other_books(author_info, entries) return render_title_template('author.html', entries=entries, pagination=pagination, id=author_id, title=_(u"Author: %(name)s", name=author_name), author=author_info, other_books=other_books, page="author", order=order[1]) def render_publisher_books(page, book_id, order): publisher = calibre_db.session.query(db.Publishers).filter(db.Publishers.id == book_id).first() if publisher: entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.publishers.any(db.Publishers.id == book_id), [db.Series.name, order[0][0], db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=book_id, title=_(u"Publisher: %(name)s", name=publisher.name), page="publisher", order=order[1]) else: abort(404) def render_series_books(page, book_id, order): name = calibre_db.session.query(db.Series).filter(db.Series.id == book_id).first() if name: entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.series.any(db.Series.id == book_id), [order[0][0]]) return render_title_template('index.html', random=random, pagination=pagination, entries=entries, id=book_id, title=_(u"Series: %(serie)s", serie=name.name), page="series", order=order[1]) else: abort(404) def render_ratings_books(page, book_id, order): name = calibre_db.session.query(db.Ratings).filter(db.Ratings.id == book_id).first() entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.ratings.any(db.Ratings.id == book_id), [order[0][0]]) if name and name.rating <= 10: return render_title_template('index.html', random=random, pagination=pagination, entries=entries, id=book_id, title=_(u"Rating: %(rating)s stars", rating=int(name.rating / 2)), page="ratings", order=order[1]) else: abort(404) def render_formats_books(page, book_id, order): name = calibre_db.session.query(db.Data).filter(db.Data.format == book_id.upper()).first() if name: entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.data.any(db.Data.format == book_id.upper()), [order[0][0]]) return render_title_template('index.html', random=random, pagination=pagination, entries=entries, id=book_id, title=_(u"File format: %(format)s", format=name.format), page="formats", order=order[1]) else: abort(404) def render_category_books(page, book_id, order): name = calibre_db.session.query(db.Tags).filter(db.Tags.id == book_id).first() if name: entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.tags.any(db.Tags.id == book_id), [order[0][0], db.Series.name, db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=book_id, title=_(u"Category: %(name)s", name=name.name), page="category", order=order[1]) else: abort(404) def render_language_books(page, name, order): try: lang_name = isoLanguages.get_language_name(get_locale(), name) except KeyError: abort(404) entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db.Books.languages.any(db.Languages.lang_code == name), [order[0][0]]) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=name, title=_(u"Language: %(name)s", name=lang_name), page="language", order=order[1]) def render_read_books(page, are_read, as_xml=False, order=None): sort = order[0] if order else [] if not config.config_read_column: if are_read: db_filter = and_(ub.ReadBook.user_id == int(current_user.id), ub.ReadBook.read_status == ub.ReadBook.STATUS_FINISHED) else: db_filter = coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db_filter, sort, db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, ub.ReadBook, db.Books.id == ub.ReadBook.book_id) else: try: if are_read: db_filter = db.cc_classes[config.config_read_column].value == True else: db_filter = coalesce(db.cc_classes[config.config_read_column].value, False) != True entries, random, pagination = calibre_db.fill_indexpage(page, 0, db.Books, db_filter, sort, db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, db.cc_classes[config.config_read_column]) except (KeyError, AttributeError): log.error("Custom Column No.%d is not existing in calibre database", config.config_read_column) if not as_xml: flash(_("Custom Column No.%(column)d is not existing in calibre database", column=config.config_read_column), category="error") return redirect(url_for("web.index")) # ToDo: Handle error Case for opds if as_xml: return entries, pagination else: if are_read: name = _(u'Read Books') + ' (' + str(pagination.total_count) + ')' pagename = "read" else: name = _(u'Unread Books') + ' (' + str(pagination.total_count) + ')' pagename = "unread" return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=name, page=pagename, order=order[1]) def render_archived_books(page, sort): order = sort[0] or [] archived_books = ( ub.session.query(ub.ArchivedBook) .filter(ub.ArchivedBook.user_id == int(current_user.id)) .filter(ub.ArchivedBook.is_archived == True) .all() ) archived_book_ids = [archived_book.book_id for archived_book in archived_books] archived_filter = db.Books.id.in_(archived_book_ids) entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page, 0, db.Books, archived_filter, order, allow_show_archived=True) name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')' pagename = "archived" return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=name, page=pagename, order=sort[1]) def render_prepare_search_form(cc): # prepare data for search-form tags = calibre_db.session.query(db.Tags)\ .join(db.books_tags_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag'))\ .order_by(db.Tags.name).all() series = calibre_db.session.query(db.Series)\ .join(db.books_series_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series'))\ .order_by(db.Series.name)\ .filter(calibre_db.common_filters()).all() shelves = ub.session.query(ub.Shelf)\ .filter(or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == int(current_user.id)))\ .order_by(ub.Shelf.name).all() extensions = calibre_db.session.query(db.Data)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(db.Data.format)\ .order_by(db.Data.format).all() if current_user.filter_language() == u"all": languages = calibre_db.speaking_language() else: languages = None return render_title_template('search_form.html', tags=tags, languages=languages, extensions=extensions, series=series,shelves=shelves, title=_(u"Advanced Search"), cc=cc, page="advsearch") def render_search_results(term, offset=None, order=None, limit=None): join = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series entries, result_count, pagination = calibre_db.get_search_results(term, offset, order, limit, *join) return render_title_template('search.html', searchterm=term, pagination=pagination, query=term, adv_searchterm=term, entries=entries, result_count=result_count, title=_(u"Search"), page="search", order=order[1]) # ################################### View Books list ################################################################## @web.route("/", defaults={'page': 1}) @web.route('/page/<int:page>') @login_required_if_no_ano def index(page): sort_param = (request.args.get('sort') or 'stored').lower() return render_books_list("newest", sort_param, 1, page) @web.route('/<data>/<sort_param>', defaults={'page': 1, 'book_id': 1}) @web.route('/<data>/<sort_param>/', defaults={'page': 1, 'book_id': 1}) @web.route('/<data>/<sort_param>/<book_id>', defaults={'page': 1}) @web.route('/<data>/<sort_param>/<book_id>/<int:page>') @login_required_if_no_ano def books_list(data, sort_param, book_id, page): return render_books_list(data, sort_param, book_id, page) @web.route("/table") @login_required def books_table(): visibility = current_user.view_settings.get('table', {}) cc = get_cc_columns(filter_config_custom_read=True) return render_title_template('book_table.html', title=_(u"Books List"), cc=cc, page="book_table", visiblility=visibility) @web.route("/ajax/listbooks") @login_required def list_books(): off = int(request.args.get("offset") or 0) limit = int(request.args.get("limit") or config.config_books_per_page) search = request.args.get("search") sort = request.args.get("sort", "id") order = request.args.get("order", "").lower() state = None join = tuple() if sort == "state": state = json.loads(request.args.get("state", "[]")) elif sort == "tags": order = [db.Tags.name.asc()] if order == "asc" else [db.Tags.name.desc()] join = db.books_tags_link,db.Books.id == db.books_tags_link.c.book, db.Tags elif sort == "series": order = [db.Series.name.asc()] if order == "asc" else [db.Series.name.desc()] join = db.books_series_link,db.Books.id == db.books_series_link.c.book, db.Series elif sort == "publishers": order = [db.Publishers.name.asc()] if order == "asc" else [db.Publishers.name.desc()] join = db.books_publishers_link,db.Books.id == db.books_publishers_link.c.book, db.Publishers elif sort == "authors": order = [db.Authors.name.asc(), db.Series.name, db.Books.series_index] if order == "asc" \ else [db.Authors.name.desc(), db.Series.name.desc(), db.Books.series_index.desc()] join = db.books_authors_link, db.Books.id == db.books_authors_link.c.book, db.Authors, \ db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series elif sort == "languages": order = [db.Languages.lang_code.asc()] if order == "asc" else [db.Languages.lang_code.desc()] join = db.books_languages_link, db.Books.id == db.books_languages_link.c.book, db.Languages elif order and sort in ["sort", "title", "authors_sort", "series_index"]: order = [text(sort + " " + order)] elif not state: order = [db.Books.timestamp.desc()] total_count = filtered_count = calibre_db.session.query(db.Books).filter(calibre_db.common_filters(False)).count() if state is not None: if search: books = calibre_db.search_query(search).all() filtered_count = len(books) else: books = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).all() entries = calibre_db.get_checkbox_sorted(books, state, off, limit, order) elif search: entries, filtered_count, __ = calibre_db.get_search_results(search, off, [order,''], limit, *join) else: entries, __, __ = calibre_db.fill_indexpage((int(off) / (int(limit)) + 1), limit, db.Books, True, order, *join) for entry in entries: for index in range(0, len(entry.languages)): entry.languages[index].language_name = isoLanguages.get_language_name(get_locale(), entry.languages[ index].lang_code) table_entries = {'totalNotFiltered': total_count, 'total': filtered_count, "rows": entries} js_list = json.dumps(table_entries, cls=db.AlchemyEncoder) response = make_response(js_list) response.headers["Content-Type"] = "application/json; charset=utf-8" return response @web.route("/ajax/table_settings", methods=['POST']) @login_required def update_table_settings(): # vals = request.get_json() # ToDo: Save table settings current_user.view_settings['table'] = json.loads(request.data) try: try: flag_modified(current_user, "view_settings") except AttributeError: pass ub.session.commit() except (InvalidRequestError, OperationalError): log.error("Invalid request received: %r ", request, ) return "Invalid request", 400 return "" @web.route("/author") @login_required_if_no_ano def author_list(): if current_user.check_visibility(constants.SIDEBAR_AUTHOR): if current_user.get_view_property('author', 'dir') == 'desc': order = db.Authors.sort.desc() order_no = 0 else: order = db.Authors.sort.asc() order_no = 1 entries = calibre_db.session.query(db.Authors, func.count('books_authors_link.book').label('count')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_authors_link.author')).order_by(order).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('char')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all() # If not creating a copy, readonly databases can not display authornames with "|" in it as changing the name # starts a change session autor_copy = copy.deepcopy(entries) for entry in autor_copy: entry.Authors.name = entry.Authors.name.replace('|', ',') return render_title_template('list.html', entries=autor_copy, folder='web.books_list', charlist=charlist, title=u"Authors", page="authorlist", data='author', order=order_no) else: abort(404) @web.route("/downloadlist") @login_required_if_no_ano def download_list(): if current_user.get_view_property('download', 'dir') == 'desc': order = ub.User.name.desc() order_no = 0 else: order = ub.User.name.asc() order_no = 1 if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin(): entries = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count'))\ .join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(order).all() charlist = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \ .filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \ .group_by(func.upper(func.substr(ub.User.name, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Downloads"), page="downloadlist", data="download", order=order_no) else: abort(404) @web.route("/publisher") @login_required_if_no_ano def publisher_list(): if current_user.get_view_property('publisher', 'dir') == 'desc': order = db.Publishers.name.desc() order_no = 0 else: order = db.Publishers.name.asc() order_no = 1 if current_user.check_visibility(constants.SIDEBAR_PUBLISHER): entries = calibre_db.session.query(db.Publishers, func.count('books_publishers_link.book').label('count')) \ .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_publishers_link.publisher')).order_by(order).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Publishers.name, 1, 1)).label('char')) \ .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Publishers.name, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Publishers"), page="publisherlist", data="publisher", order=order_no) else: abort(404) @web.route("/series") @login_required_if_no_ano def series_list(): if current_user.check_visibility(constants.SIDEBAR_SERIES): if current_user.get_view_property('series', 'dir') == 'desc': order = db.Series.sort.desc() order_no = 0 else: order = db.Series.sort.asc() order_no = 1 if current_user.get_view_property('series', 'series_view') == 'list': entries = calibre_db.session.query(db.Series, func.count('books_series_link.book').label('count')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series')).order_by(order).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Series"), page="serieslist", data="series", order=order_no) else: entries = calibre_db.session.query(db.Books, func.count('books_series_link').label('count'), func.max(db.Books.series_index), db.Books.id) \ .join(db.books_series_link).join(db.Series).filter(calibre_db.common_filters())\ .group_by(text('books_series_link.series')).order_by(order).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all() return render_title_template('grid.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Series"), page="serieslist", data="series", bodyClass="grid-view", order=order_no) else: abort(404) @web.route("/ratings") @login_required_if_no_ano def ratings_list(): if current_user.check_visibility(constants.SIDEBAR_RATING): if current_user.get_view_property('ratings', 'dir') == 'desc': order = db.Ratings.rating.desc() order_no = 0 else: order = db.Ratings.rating.asc() order_no = 1 entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_ratings_link.rating')).order_by(order).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(), title=_(u"Ratings list"), page="ratingslist", data="ratings", order=order_no) else: abort(404) @web.route("/formats") @login_required_if_no_ano def formats_list(): if current_user.check_visibility(constants.SIDEBAR_FORMAT): if current_user.get_view_property('ratings', 'dir') == 'desc': order = db.Data.format.desc() order_no = 0 else: order = db.Data.format.asc() order_no = 1 entries = calibre_db.session.query(db.Data, func.count('data.book').label('count'), db.Data.format.label('format')) \ .join(db.Books).filter(calibre_db.common_filters()) \ .group_by(db.Data.format).order_by(order).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(), title=_(u"File formats list"), page="formatslist", data="formats", order=order_no) else: abort(404) @web.route("/language") @login_required_if_no_ano def language_overview(): if current_user.check_visibility(constants.SIDEBAR_LANGUAGE) and current_user.filter_language() == u"all": order_no = 0 if current_user.get_view_property('language', 'dir') == 'desc' else 1 charlist = list() languages = calibre_db.speaking_language(reverse_order=not order_no, with_count=True) for lang in languages: upper_lang = lang[0].name[0].upper() if upper_lang not in charlist: charlist.append(upper_lang) return render_title_template('languages.html', languages=languages, charlist=charlist, title=_(u"Languages"), page="langlist", data="language", order=order_no) else: abort(404) @web.route("/category") @login_required_if_no_ano def category_list(): if current_user.check_visibility(constants.SIDEBAR_CATEGORY): if current_user.get_view_property('category', 'dir') == 'desc': order = db.Tags.name.desc() order_no = 0 else: order = db.Tags.name.asc() order_no = 1 entries = calibre_db.session.query(db.Tags, func.count('books_tags_link.book').label('count')) \ .join(db.books_tags_link).join(db.Books).order_by(order).filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag')).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('char')) \ .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Categories"), page="catlist", data="category", order=order_no) else: abort(404) # ################################### Task functions ################################################################ @web.route("/tasks") @login_required def get_tasks_status(): # if current user admin, show all email, otherwise only own emails tasks = WorkerThread.getInstance().tasks answer = render_task_status(tasks) return render_title_template('tasks.html', entries=answer, title=_(u"Tasks"), page="tasks") # method is available without login and not protected by CSRF to make it easy reachable @app.route("/reconnect", methods=['GET']) def reconnect(): calibre_db.reconnect_db(config, ub.app_DB_path) return json.dumps({}) # ################################### Search functions ################################################################ @web.route("/search", methods=["GET"]) @login_required_if_no_ano def search(): term = request.args.get("query") if term: return redirect(url_for('web.books_list', data="search", sort_param='stored', query=term)) else: return render_title_template('search.html', searchterm="", result_count=0, title=_(u"Search"), page="search") @web.route("/advsearch", methods=['POST']) @login_required_if_no_ano def advanced_search(): values = dict(request.form) params = ['include_tag', 'exclude_tag', 'include_serie', 'exclude_serie', 'include_shelf', 'exclude_shelf', 'include_language', 'exclude_language', 'include_extension', 'exclude_extension'] for param in params: values[param] = list(request.form.getlist(param)) flask_session['query'] = json.dumps(values) return redirect(url_for('web.books_list', data="advsearch", sort_param='stored', query="")) def adv_search_custom_columns(cc, term, q): for c in cc: if c.datatype == "datetime": custom_start = term.get('custom_column_' + str(c.id) + '_start') custom_end = term.get('custom_column_' + str(c.id) + '_end') if custom_start: q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.datetime(db.cc_classes[c.id].value) >= func.datetime(custom_start))) if custom_end: q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.datetime(db.cc_classes[c.id].value) <= func.datetime(custom_end))) else: custom_query = term.get('custom_column_' + str(c.id)) if custom_query != '' and custom_query is not None: if c.datatype == 'bool': q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == (custom_query == "True"))) elif c.datatype == 'int' or c.datatype == 'float': q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == custom_query)) elif c.datatype == 'rating': q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == int(float(custom_query) * 2))) else: q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.lower(db.cc_classes[c.id].value).ilike("%" + custom_query + "%"))) return q def adv_search_language(q, include_languages_inputs, exclude_languages_inputs): if current_user.filter_language() != "all": q = q.filter(db.Books.languages.any(db.Languages.lang_code == current_user.filter_language())) else: for language in include_languages_inputs: q = q.filter(db.Books.languages.any(db.Languages.id == language)) for language in exclude_languages_inputs: q = q.filter(not_(db.Books.series.any(db.Languages.id == language))) return q def adv_search_ratings(q, rating_high, rating_low): if rating_high: rating_high = int(rating_high) * 2 q = q.filter(db.Books.ratings.any(db.Ratings.rating <= rating_high)) if rating_low: rating_low = int(rating_low) * 2 q = q.filter(db.Books.ratings.any(db.Ratings.rating >= rating_low)) return q def adv_search_read_status(q, read_status): if read_status: if config.config_read_column: try: if read_status == "True": q = q.join(db.cc_classes[config.config_read_column], isouter=True) \ .filter(db.cc_classes[config.config_read_column].value == True) else: q = q.join(db.cc_classes[config.config_read_column], isouter=True) \ .filter(coalesce(db.cc_classes[config.config_read_column].value, False) != True) except (KeyError, AttributeError): log.error(u"Custom Column No.%d is not existing in calibre database", config.config_read_column) flash(_("Custom Column No.%(column)d is not existing in calibre database", column=config.config_read_column), category="error") return q else: if read_status == "True": q = q.join(ub.ReadBook, db.Books.id == ub.ReadBook.book_id, isouter=True) \ .filter(ub.ReadBook.user_id == int(current_user.id), ub.ReadBook.read_status == ub.ReadBook.STATUS_FINISHED) else: q = q.join(ub.ReadBook, db.Books.id == ub.ReadBook.book_id, isouter=True) \ .filter(ub.ReadBook.user_id == int(current_user.id), coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED) return q def adv_search_extension(q, include_extension_inputs, exclude_extension_inputs): for extension in include_extension_inputs: q = q.filter(db.Books.data.any(db.Data.format == extension)) for extension in exclude_extension_inputs: q = q.filter(not_(db.Books.data.any(db.Data.format == extension))) return q def adv_search_tag(q, include_tag_inputs, exclude_tag_inputs): for tag in include_tag_inputs: q = q.filter(db.Books.tags.any(db.Tags.id == tag)) for tag in exclude_tag_inputs: q = q.filter(not_(db.Books.tags.any(db.Tags.id == tag))) return q def adv_search_serie(q, include_series_inputs, exclude_series_inputs): for serie in include_series_inputs: q = q.filter(db.Books.series.any(db.Series.id == serie)) for serie in exclude_series_inputs: q = q.filter(not_(db.Books.series.any(db.Series.id == serie))) return q def adv_search_shelf(q, include_shelf_inputs, exclude_shelf_inputs): q = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\ .filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(exclude_shelf_inputs))) if len(include_shelf_inputs) > 0: q = q.filter(ub.BookShelf.shelf.in_(include_shelf_inputs)) return q def extend_search_term(searchterm, author_name, book_title, publisher, pub_start, pub_end, tags, rating_high, rating_low, read_status, ): searchterm.extend((author_name.replace('|', ','), book_title, publisher)) if pub_start: try: searchterm.extend([_(u"Published after ") + format_date(datetime.strptime(pub_start, "%Y-%m-%d"), format='medium', locale=get_locale())]) except ValueError: pub_start = u"" if pub_end: try: searchterm.extend([_(u"Published before ") + format_date(datetime.strptime(pub_end, "%Y-%m-%d"), format='medium', locale=get_locale())]) except ValueError: pub_end = u"" elements = {'tag': db.Tags, 'serie':db.Series, 'shelf':ub.Shelf} for key, db_element in elements.items(): tag_names = calibre_db.session.query(db_element).filter(db_element.id.in_(tags['include_' + key])).all() searchterm.extend(tag.name for tag in tag_names) tag_names = calibre_db.session.query(db_element).filter(db_element.id.in_(tags['exclude_' + key])).all() searchterm.extend(tag.name for tag in tag_names) language_names = calibre_db.session.query(db.Languages). \ filter(db.Languages.id.in_(tags['include_language'])).all() if language_names: language_names = calibre_db.speaking_language(language_names) searchterm.extend(language.name for language in language_names) language_names = calibre_db.session.query(db.Languages). \ filter(db.Languages.id.in_(tags['exclude_language'])).all() if language_names: language_names = calibre_db.speaking_language(language_names) searchterm.extend(language.name for language in language_names) if rating_high: searchterm.extend([_(u"Rating <= %(rating)s", rating=rating_high)]) if rating_low: searchterm.extend([_(u"Rating >= %(rating)s", rating=rating_low)]) if read_status: searchterm.extend([_(u"Read Status = %(status)s", status=read_status)]) searchterm.extend(ext for ext in tags['include_extension']) searchterm.extend(ext for ext in tags['exclude_extension']) # handle custom columns searchterm = " + ".join(filter(None, searchterm)) return searchterm, pub_start, pub_end def render_adv_search_results(term, offset=None, order=None, limit=None): sort = order[0] if order else [db.Books.sort] pagination = None cc = get_cc_columns(filter_config_custom_read=True) calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase) q = calibre_db.session.query(db.Books).outerjoin(db.books_series_link, db.Books.id == db.books_series_link.c.book)\ .outerjoin(db.Series)\ .filter(calibre_db.common_filters(True)) # parse multiselects to a complete dict tags = dict() elements = ['tag', 'serie', 'shelf', 'language', 'extension'] for element in elements: tags['include_' + element] = term.get('include_' + element) tags['exclude_' + element] = term.get('exclude_' + element) author_name = term.get("author_name") book_title = term.get("book_title") publisher = term.get("publisher") pub_start = term.get("publishstart") pub_end = term.get("publishend") rating_low = term.get("ratinghigh") rating_high = term.get("ratinglow") description = term.get("comment") read_status = term.get("read_status") if author_name: author_name = author_name.strip().lower().replace(',', '|') if book_title: book_title = book_title.strip().lower() if publisher: publisher = publisher.strip().lower() searchterm = [] cc_present = False for c in cc: if c.datatype == "datetime": column_start = term.get('custom_column_' + str(c.id) + '_start') column_end = term.get('custom_column_' + str(c.id) + '_end') if column_start: searchterm.extend([u"{} >= {}".format(c.name, format_date(datetime.strptime(column_start, "%Y-%m-%d").date(), format='medium', locale=get_locale()) )]) cc_present = True if column_end: searchterm.extend([u"{} <= {}".format(c.name, format_date(datetime.strptime(column_end, "%Y-%m-%d").date(), format='medium', locale=get_locale()) )]) cc_present = True elif term.get('custom_column_' + str(c.id)): searchterm.extend([(u"{}: {}".format(c.name, term.get('custom_column_' + str(c.id))))]) cc_present = True if any(tags.values()) or author_name or book_title or publisher or pub_start or pub_end or rating_low \ or rating_high or description or cc_present or read_status: searchterm, pub_start, pub_end = extend_search_term(searchterm, author_name, book_title, publisher, pub_start, pub_end, tags, rating_high, rating_low, read_status) q = q.filter() if author_name: q = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + author_name + "%"))) if book_title: q = q.filter(func.lower(db.Books.title).ilike("%" + book_title + "%")) if pub_start: q = q.filter(func.datetime(db.Books.pubdate) > func.datetime(pub_start)) if pub_end: q = q.filter(func.datetime(db.Books.pubdate) < func.datetime(pub_end)) q = adv_search_read_status(q, read_status) if publisher: q = q.filter(db.Books.publishers.any(func.lower(db.Publishers.name).ilike("%" + publisher + "%"))) q = adv_search_tag(q, tags['include_tag'], tags['exclude_tag']) q = adv_search_serie(q, tags['include_serie'], tags['exclude_serie']) q = adv_search_shelf(q, tags['include_shelf'], tags['exclude_shelf']) q = adv_search_extension(q, tags['include_extension'], tags['exclude_extension']) q = adv_search_language(q, tags['include_language'], tags['exclude_language']) q = adv_search_ratings(q, rating_high, rating_low) if description: q = q.filter(db.Books.comments.any(func.lower(db.Comments.text).ilike("%" + description + "%"))) # search custom culumns try: q = adv_search_custom_columns(cc, term, q) except AttributeError as ex: log.debug_or_exception(ex) flash(_("Error on search for custom columns, please restart Calibre-Web"), category="error") q = q.order_by(*sort).all() flask_session['query'] = json.dumps(term) ub.store_ids(q) result_count = len(q) if offset is not None and limit is not None: offset = int(offset) limit_all = offset + int(limit) pagination = Pagination((offset / (int(limit)) + 1), limit, result_count) else: offset = 0 limit_all = result_count return render_title_template('search.html', adv_searchterm=searchterm, pagination=pagination, entries=q[offset:limit_all], result_count=result_count, title=_(u"Advanced Search"), page="advsearch", order=order[1]) @web.route("/advsearch", methods=['GET']) @login_required_if_no_ano def advanced_search_form(): # Build custom columns names cc = get_cc_columns(filter_config_custom_read=True) return render_prepare_search_form(cc) # ################################### Download/Send ################################################################## @web.route("/cover/<int:book_id>") @login_required_if_no_ano def get_cover(book_id): return get_book_cover(book_id) @web.route("/robots.txt") def get_robots(): return send_from_directory(constants.STATIC_DIR, "robots.txt") @web.route("/show/<int:book_id>/<book_format>", defaults={'anyname': 'None'}) @web.route("/show/<int:book_id>/<book_format>/<anyname>") @login_required_if_no_ano @viewer_required def serve_book(book_id, book_format, anyname): book_format = book_format.split(".")[0] book = calibre_db.get_book(book_id) data = calibre_db.get_book_format(book_id, book_format.upper()) if not data: return "File not in Database" log.info('Serving book: %s', data.name) if config.config_use_google_drive: try: headers = Headers() headers["Content-Type"] = mimetypes.types_map.get('.' + book_format, "application/octet-stream") df = getFileFromEbooksFolder(book.path, data.name + "." + book_format) return do_gdrive_download(df, headers, (book_format.upper() == 'TXT')) except AttributeError as ex: log.debug_or_exception(ex) return "File Not Found" else: if book_format.upper() == 'TXT': try: rawdata = open(os.path.join(config.config_calibre_dir, book.path, data.name + "." + book_format), "rb").read() result = chardet.detect(rawdata) return make_response( rawdata.decode(result['encoding'], 'surrogatepass').encode('utf-8', 'surrogatepass')) except FileNotFoundError: log.error("File Not Found") return "File Not Found" return send_from_directory(os.path.join(config.config_calibre_dir, book.path), data.name + "." + book_format) @web.route("/download/<int:book_id>/<book_format>", defaults={'anyname': 'None'}) @web.route("/download/<int:book_id>/<book_format>/<anyname>") @login_required_if_no_ano @download_required def download_link(book_id, book_format, anyname): client = "kobo" if "Kobo" in request.headers.get('User-Agent') else "" return get_download_link(book_id, book_format, client) @web.route('/send/<int:book_id>/<book_format>/<int:convert>', methods=["POST"]) @login_required @download_required def send_to_kindle(book_id, book_format, convert): if not config.get_mail_server_configured(): flash(_(u"Please configure the SMTP mail settings first..."), category="error") elif current_user.kindle_mail: result = send_mail(book_id, book_format, convert, current_user.kindle_mail, config.config_calibre_dir, current_user.name) if result is None: flash(_(u"Book successfully queued for sending to %(kindlemail)s", kindlemail=current_user.kindle_mail), category="success") ub.update_download(book_id, int(current_user.id)) else: flash(_(u"Oops! There was an error sending this book: %(res)s", res=result), category="error") else: flash(_(u"Please update your profile with a valid Send to Kindle E-mail Address."), category="error") if "HTTP_REFERER" in request.environ: return redirect(request.environ["HTTP_REFERER"]) else: return redirect(url_for('web.index')) # ################################### Login Logout ################################################################## @web.route('/register', methods=['GET', 'POST']) def register(): if not config.config_public_reg: abort(404) if current_user is not None and current_user.is_authenticated: return redirect(url_for('web.index')) if not config.get_mail_server_configured(): flash(_(u"E-Mail server is not configured, please contact your administrator!"), category="error") return render_title_template('register.html', title=_("Register"), page="register") if request.method == "POST": to_save = request.form.to_dict() nickname = to_save["email"].strip() if config.config_register_email else to_save.get('name') if not nickname or not to_save.get("email"): flash(_(u"Please fill out all fields!"), category="error") return render_title_template('register.html', title=_("Register"), page="register") try: nickname = check_username(nickname) email = check_email(to_save["email"]) except Exception as ex: flash(str(ex), category="error") return render_title_template('register.html', title=_("Register"), page="register") content = ub.User() if check_valid_domain(email): content.name = nickname content.email = email password = generate_random_password() content.password = generate_password_hash(password) content.role = config.config_default_role content.sidebar_view = config.config_default_show try: ub.session.add(content) ub.session.commit() if feature_support['oauth']: register_user_with_oauth(content) send_registration_mail(to_save["email"].strip(), nickname, password) except Exception: ub.session.rollback() flash(_(u"An unknown error occurred. Please try again later."), category="error") return render_title_template('register.html', title=_("Register"), page="register") else: flash(_(u"Your e-mail is not allowed to register"), category="error") log.warning('Registering failed for user "%s" e-mail address: %s', nickname, to_save["email"]) return render_title_template('register.html', title=_("Register"), page="register") flash(_(u"Confirmation e-mail was send to your e-mail account."), category="success") return redirect(url_for('web.login')) if feature_support['oauth']: register_user_with_oauth() return render_title_template('register.html', config=config, title=_("Register"), page="register") @web.route('/login', methods=['GET', 'POST']) def login(): if current_user is not None and current_user.is_authenticated: return redirect(url_for('web.index')) if config.config_login_type == constants.LOGIN_LDAP and not services.ldap: log.error(u"Cannot activate LDAP authentication") flash(_(u"Cannot activate LDAP authentication"), category="error") if request.method == "POST": form = request.form.to_dict() user = ub.session.query(ub.User).filter(func.lower(ub.User.name) == form['username'].strip().lower()) \ .first() if config.config_login_type == constants.LOGIN_LDAP and services.ldap and user and form['password'] != "": login_result, error = services.ldap.bind_user(form['username'], form['password']) if login_result: login_user(user, remember=bool(form.get('remember_me'))) ub.store_user_session() log.debug(u"You are now logged in as: '%s'", user.name) flash(_(u"you are now logged in as: '%(nickname)s'", nickname=user.name), category="success") return redirect_back(url_for("web.index")) elif login_result is None and user and check_password_hash(str(user.password), form['password']) \ and user.name != "Guest": login_user(user, remember=bool(form.get('remember_me'))) ub.store_user_session() log.info("Local Fallback Login as: '%s'", user.name) flash(_(u"Fallback Login as: '%(nickname)s', LDAP Server not reachable, or user not known", nickname=user.name), category="warning") return redirect_back(url_for("web.index")) elif login_result is None: log.info(error) flash(_(u"Could not login: %(message)s", message=error), category="error") else: ip_Address = request.headers.get('X-Forwarded-For', request.remote_addr) log.warning('LDAP Login failed for user "%s" IP-address: %s', form['username'], ip_Address) flash(_(u"Wrong Username or Password"), category="error") else: ip_Address = request.headers.get('X-Forwarded-For', request.remote_addr) if 'forgot' in form and form['forgot'] == 'forgot': if user is not None and user.name != "Guest": ret, __ = reset_password(user.id) if ret == 1: flash(_(u"New Password was send to your email address"), category="info") log.info('Password reset for user "%s" IP-address: %s', form['username'], ip_Address) else: log.error(u"An unknown error occurred. Please try again later") flash(_(u"An unknown error occurred. Please try again later."), category="error") else: flash(_(u"Please enter valid username to reset password"), category="error") log.warning('Username missing for password reset IP-address: %s', ip_Address) else: if user and check_password_hash(str(user.password), form['password']) and user.name != "Guest": login_user(user, remember=bool(form.get('remember_me'))) ub.store_user_session() log.debug(u"You are now logged in as: '%s'", user.name) flash(_(u"You are now logged in as: '%(nickname)s'", nickname=user.name), category="success") config.config_is_initial = False return redirect_back(url_for("web.index")) else: log.warning('Login failed for user "%s" IP-address: %s', form['username'], ip_Address) flash(_(u"Wrong Username or Password"), category="error") next_url = request.args.get('next', default=url_for("web.index"), type=str) if url_for("web.logout") == next_url: next_url = url_for("web.index") return render_title_template('login.html', title=_(u"Login"), next_url=next_url, config=config, oauth_check=oauth_check, mail=config.get_mail_server_configured(), page="login") @web.route('/logout') @login_required def logout(): if current_user is not None and current_user.is_authenticated: ub.delete_user_session(current_user.id, flask_session.get('_id',"")) logout_user() if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3): logout_oauth_user() log.debug(u"User logged out") return redirect(url_for('web.login')) # ################################### Users own configuration ######################################################### def change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages): to_save = request.form.to_dict() current_user.random_books = 0 if current_user.role_passwd() or current_user.role_admin(): if to_save.get("password"): current_user.password = generate_password_hash(to_save["password"]) try: if to_save.get("kindle_mail", current_user.kindle_mail) != current_user.kindle_mail: current_user.kindle_mail = valid_email(to_save["kindle_mail"]) if to_save.get("email", current_user.email) != current_user.email: current_user.email = check_email(to_save["email"]) if current_user.role_admin(): if to_save.get("name", current_user.name) != current_user.name: # Query User name, if not existing, change current_user.name = check_username(to_save["name"]) current_user.random_books = 1 if to_save.get("show_random") == "on" else 0 if to_save.get("default_language"): current_user.default_language = to_save["default_language"] if to_save.get("locale"): current_user.locale = to_save["locale"] old_state = current_user.kobo_only_shelves_sync # 1 -> 0: nothing has to be done # 0 -> 1: all synced books have to be added to archived books, + currently synced shelfs which # don't have to be synced have to be removed (added to Shelf archive) current_user.kobo_only_shelves_sync = int(to_save.get("kobo_only_shelves_sync") == "on") or 0 if old_state == 0 and current_user.kobo_only_shelves_sync == 1: kobo_sync_status.update_on_sync_shelfs(current_user.id) except Exception as ex: flash(str(ex), category="error") return render_title_template("user_edit.html", content=current_user, translations=translations, profile=1, languages=languages, title=_(u"%(name)s's profile", name=current_user.name), page="me", kobo_support=kobo_support, registered_oauth=local_oauth_check, oauth_status=oauth_status) val = 0 for key, __ in to_save.items(): if key.startswith('show'): val += int(key[5:]) current_user.sidebar_view = val if to_save.get("Show_detail_random"): current_user.sidebar_view += constants.DETAIL_RANDOM try: ub.session.commit() flash(_(u"Profile updated"), category="success") log.debug(u"Profile updated") except IntegrityError: ub.session.rollback() flash(_(u"Found an existing account for this e-mail address"), category="error") log.debug(u"Found an existing account for this e-mail address") except OperationalError as e: ub.session.rollback() log.error("Database error: %s", e) flash(_(u"Database error: %(error)s.", error=e), category="error") @web.route("/me", methods=["GET", "POST"]) @login_required def profile(): languages = calibre_db.speaking_language() translations = babel.list_translations() + [LC('en')] kobo_support = feature_support['kobo'] and config.config_kobo_sync if feature_support['oauth'] and config.config_login_type == 2: oauth_status = get_oauth_status() local_oauth_check = oauth_check else: oauth_status = None local_oauth_check = {} if request.method == "POST": change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages) return render_title_template("user_edit.html", translations=translations, profile=1, languages=languages, content=current_user, kobo_support=kobo_support, title=_(u"%(name)s's profile", name=current_user.name), page="me", registered_oauth=local_oauth_check, oauth_status=oauth_status) # ###################################Show single book ################################################################## @web.route("/read/<int:book_id>/<book_format>") @login_required_if_no_ano @viewer_required def read_book(book_id, book_format): book = calibre_db.get_filtered_book(book_id) if not book: flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible") return redirect(url_for("web.index")) # check if book has bookmark bookmark = None if current_user.is_authenticated: bookmark = ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id), ub.Bookmark.book_id == book_id, ub.Bookmark.format == book_format.upper())).first() if book_format.lower() == "epub": log.debug(u"Start epub reader for %d", book_id) return render_title_template('read.html', bookid=book_id, title=book.title, bookmark=bookmark) elif book_format.lower() == "pdf": log.debug(u"Start pdf reader for %d", book_id) return render_title_template('readpdf.html', pdffile=book_id, title=book.title) elif book_format.lower() == "txt": log.debug(u"Start txt reader for %d", book_id) return render_title_template('readtxt.html', txtfile=book_id, title=book.title) elif book_format.lower() == "djvu": log.debug(u"Start djvu reader for %d", book_id) return render_title_template('readdjvu.html', djvufile=book_id, title=book.title) else: for fileExt in constants.EXTENSIONS_AUDIO: if book_format.lower() == fileExt: entries = calibre_db.get_filtered_book(book_id) log.debug(u"Start mp3 listening for %d", book_id) return render_title_template('listenmp3.html', mp3file=book_id, audioformat=book_format.lower(), entry=entries, bookmark=bookmark) for fileExt in ["cbr", "cbt", "cbz"]: if book_format.lower() == fileExt: all_name = str(book_id) title = book.title if len(book.series): title = title + " - " + book.series[0].name if book.series_index: title = title + " #" + '{0:.2f}'.format(book.series_index).rstrip('0').rstrip('.') log.debug(u"Start comic reader for %d", book_id) return render_title_template('readcbr.html', comicfile=all_name, title=title, extension=fileExt) log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) @web.route("/book/<int:book_id>") @login_required_if_no_ano def show_book(book_id): entries = calibre_db.get_filtered_book(book_id, allow_show_archived=True) if entries: for index in range(0, len(entries.languages)): entries.languages[index].language_name = isoLanguages.get_language_name(get_locale(), entries.languages[ index].lang_code) cc = get_cc_columns(filter_config_custom_read=True) book_in_shelfs = [] shelfs = ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).all() for entry in shelfs: book_in_shelfs.append(entry.shelf) if not current_user.is_anonymous: if not config.config_read_column: matching_have_read_book = ub.session.query(ub.ReadBook). \ filter(and_(ub.ReadBook.user_id == int(current_user.id), ub.ReadBook.book_id == book_id)).all() have_read = len( matching_have_read_book) > 0 and matching_have_read_book[0].read_status == ub.ReadBook.STATUS_FINISHED else: try: matching_have_read_book = getattr(entries, 'custom_column_' + str(config.config_read_column)) have_read = len(matching_have_read_book) > 0 and matching_have_read_book[0].value except (KeyError, AttributeError): log.error("Custom Column No.%d is not existing in calibre database", config.config_read_column) have_read = None archived_book = ub.session.query(ub.ArchivedBook).\ filter(and_(ub.ArchivedBook.user_id == int(current_user.id), ub.ArchivedBook.book_id == book_id)).first() is_archived = archived_book and archived_book.is_archived else: have_read = None is_archived = None entries.tags = sort(entries.tags, key=lambda tag: tag.name) entries = calibre_db.order_authors(entries) kindle_list = check_send_to_kindle(entries) reader_list = check_read_formats(entries) audioentries = [] for media_format in entries.data: if media_format.format.lower() in constants.EXTENSIONS_AUDIO: audioentries.append(media_format.format.lower()) return render_title_template('detail.html', entry=entries, audioentries=audioentries, cc=cc, is_xhr=request.headers.get('X-Requested-With')=='XMLHttpRequest', title=entries.title, books_shelfs=book_in_shelfs, have_read=have_read, is_archived=is_archived, kindle_list=kindle_list, reader_list=reader_list, page="book") else: log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index"))
xsrf
{ "code": [ "@app.route(\"/reconnect\")", "@web.route('/send/<int:book_id>/<book_format>/<int:convert>')" ], "line_no": [ 1058, 1438 ] }
{ "code": [ "@app.route(\"/reconnect\", methods=['GET'])", "@web.route('/send/<int:book_id>/<book_format>/<int:convert>', methods=[\"POST\"])" ], "line_no": [ 1059, 1439 ] }
import os from datetime import datetime import json import mimetypes import chardet # dependency of requests import copy from babel.dates import .format_date from babel import Locale as LC from flask import Blueprint, jsonify from flask import request, redirect, send_from_directory, make_response, flash, abort, url_for from flask import session as VAR_91 from flask_babel import gettext as _ from flask_login import .login_user, logout_user, login_required, VAR_87 from sqlalchemy.exc import IntegrityError, InvalidRequestError, OperationalError from sqlalchemy.sql.expression import text, func, false, not_, and_, or_ from sqlalchemy.orm.attributes import .flag_modified from sqlalchemy.sql.functions import coalesce from .services.worker import WorkerThread from werkzeug.datastructures import Headers from werkzeug.security import generate_password_hash, check_password_hash from . import constants, logger, isoLanguages, services from . import babel, db, ub, config, get_locale, app from . import calibre_db, kobo_sync_status from .gdriveutils import getFileFromEbooksFolder, do_gdrive_download from .helper import check_valid_domain, render_task_status, check_email, check_username, \ get_cc_columns, get_book_cover, get_download_link, send_mail, generate_random_password, \ send_registration_mail, check_send_to_kindle, check_read_formats, tags_filters, reset_password, valid_email from .pagination import Pagination from .redirect import redirect_back from .usermanagement import .login_required_if_no_ano from .kobo_sync_status import remove_synced_book from .render_template import render_title_template from .kobo_sync_status import change_archived_books VAR_0 = { 'ldap': bool(services.ldap), 'goodreads': bool(services.goodreads_support), 'kobo': bool(services.kobo) } try: from .oauth_bb import .oauth_check, register_user_with_oauth, logout_oauth_user, get_oauth_status VAR_0['oauth'] = True except ImportError: VAR_0['oauth'] = False VAR_100 = {} try: from functools import wraps except ImportError: pass # We're not using Python 3 try: from natsort import natsorted as VAR_7 except ImportError: VAR_7 = sorted # Just use regular VAR_7 then, may cause issues with badly named pages in cbz/cbr files @app.after_request def FUNC_0(VAR_1): VAR_1.headers['Content-Security-Policy'] = "default-src 'self'" + ''.join([' '+host for host in config.config_trustedhosts.strip().split(',')]) + " 'unsafe-inline' 'unsafe-eval'; font-src 'self' VAR_8:; img-src 'self' VAR_8:" if request.endpoint == "editbook.edit_book" or config.config_use_google_drive: VAR_1.headers['Content-Security-Policy'] += " *" elif request.endpoint == "web.read_book": VAR_1.headers['Content-Security-Policy'] += " blob:;style-src-elem 'self' blob: 'unsafe-inline';" VAR_1.headers['X-Content-Type-Options'] = 'nosniff' VAR_1.headers['X-Frame-Options'] = 'SAMEORIGIN' VAR_1.headers['X-XSS-Protection'] = '1; mode=block' VAR_1.headers['Strict-Transport-Security'] = 'max-age=31536000;' return VAR_1 VAR_2 = Blueprint('web', __name__) VAR_3 = logger.create() def FUNC_1(VAR_4): @wraps(VAR_4) def FUNC_71(*VAR_49, **VAR_50): if VAR_87.role_download(): return VAR_4(*VAR_49, **VAR_50) abort(403) return FUNC_71 def FUNC_2(VAR_4): @wraps(VAR_4) def FUNC_71(*VAR_49, **VAR_50): if VAR_87.role_viewer(): return VAR_4(*VAR_49, **VAR_50) abort(403) return FUNC_71 @VAR_2.route("/ajax/emailstat") @login_required def FUNC_3(): VAR_51 = WorkerThread.getInstance().tasks return jsonify(render_task_status(VAR_51)) @VAR_2.route("/ajax/VAR_99/<int:VAR_5>/<VAR_6>", methods=['POST']) @login_required def VAR_99(VAR_5, VAR_6): VAR_52 = request.form["bookmark"] ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(VAR_87.id), ub.Bookmark.book_id == VAR_5, ub.Bookmark.format == VAR_6)).delete() if not VAR_52: ub.session_commit() return "", 204 VAR_53 = ub.Bookmark(VAR_11=VAR_87.id, VAR_5=book_id, format=VAR_6, VAR_52=bookmark_key) ub.session.merge(VAR_53) ub.session_commit("Bookmark for VAR_104 {} in VAR_95 {} created".format(VAR_87.id, VAR_5)) return "", 201 @VAR_2.route("/ajax/toggleread/<int:VAR_5>", methods=['POST']) @login_required def FUNC_5(VAR_5): if not config.config_read_column: VAR_95 = ub.session.query(ub.ReadBook).filter(and_(ub.ReadBook.user_id == int(VAR_87.id), ub.ReadBook.book_id == VAR_5)).first() if VAR_95: if VAR_95.read_status == ub.ReadBook.STATUS_FINISHED: VAR_95.read_status = ub.ReadBook.STATUS_UNREAD else: VAR_95.read_status = ub.ReadBook.STATUS_FINISHED else: VAR_123 = ub.ReadBook(VAR_11=VAR_87.id, VAR_5 = book_id) VAR_123.read_status = ub.ReadBook.STATUS_FINISHED VAR_95 = VAR_123 if not VAR_95.kobo_reading_state: VAR_124 = ub.KoboReadingState(VAR_11=VAR_87.id, VAR_5=book_id) VAR_124.current_bookmark = ub.KoboBookmark() VAR_124.statistics = ub.KoboStatistics() VAR_95.kobo_reading_state = VAR_124 ub.session.merge(VAR_95) ub.session_commit("Book {} readbit toggled".format(VAR_5)) else: try: calibre_db.update_title_sort(config) VAR_95 = calibre_db.get_filtered_book(VAR_5) VAR_26 = getattr(VAR_95, 'custom_column_' + str(config.config_read_column)) if len(VAR_26): VAR_26[0].value = not VAR_26[0].value calibre_db.session.commit() else: VAR_144 = db.cc_classes[config.config_read_column] VAR_145 = VAR_144(value=1, VAR_95=VAR_5) calibre_db.session.add(VAR_145) calibre_db.session.commit() except (KeyError, AttributeError): VAR_3.error(u"Custom Column No.%d is not existing in calibre database", config.config_read_column) return "Custom Column No.{} is not existing in calibre database".format(config.config_read_column), 400 except (OperationalError, InvalidRequestError) as e: calibre_db.session.rollback() VAR_3.error(u"Read status could not set: {}".format(e)) return "Read status could not set: {}".format(e), 400 return "" @VAR_2.route("/ajax/togglearchived/<int:VAR_5>", methods=['POST']) @login_required def FUNC_6(VAR_5): VAR_54 = change_archived_books(VAR_5, message="Book {} archivebit toggled".format(VAR_5)) if VAR_54: remove_synced_book(VAR_5) return "" @VAR_2.route("/ajax/view", methods=["POST"]) @login_required_if_no_ano def FUNC_7(): VAR_55 = request.get_json() try: for VAR_112 in VAR_55: for VAR_110 in VAR_55[VAR_112]: VAR_87.set_view_property(VAR_112, VAR_110, VAR_55[VAR_112][VAR_110]) except Exception as ex: VAR_3.error("Could not save view_settings: %r %r: %e", request, VAR_55, ex) return "Invalid request", 400 return "1", 200 ''' @VAR_2.route("/ajax/getcomic/<int:VAR_5>/<VAR_6>/<int:VAR_9>") @login_required def get_comic_book(VAR_5, VAR_6, VAR_9): VAR_95 = calibre_db.get_book(VAR_5) if not VAR_95: return "", 204 else: for bookformat in VAR_95.data: if bookformat.format.lower() == VAR_6.lower(): cbr_file = os.path.join(config.config_calibre_dir, VAR_95.path, bookformat.name) + "." + VAR_6 if VAR_6 in ("cbr", "rar"): if VAR_0['rar'] == True: rarfile.UNRAR_TOOL = config.config_rarfile_location try: rf = rarfile.RarFile(cbr_file) names = VAR_7(rf.namelist()) extract = lambda VAR_9: rf.read(names[VAR_9]) except: VAR_3.error('Unrar binary not found, or unable to decompress file %s', cbr_file) return "", 204 else: VAR_3.info('Unrar is not supported please install python rarfile extension') return "", 204 elif VAR_6 in ("cbz", "zip"): zf = zipfile.ZipFile(cbr_file) names=VAR_7(zf.namelist()) extract = lambda VAR_9: zf.read(names[VAR_9]) elif VAR_6 in ("cbt", "tar"): tf = tarfile.TarFile(cbr_file) names=VAR_7(tf.getnames()) extract = lambda VAR_9: tf.extractfile(names[VAR_9]).read() else: VAR_3.error('unsupported comic format') return "", 204 b64 = codecs.encode(extract(VAR_9), 'base64').decode() ext = names[VAR_9].rpartition('.')[-1] if ext not in ('png', 'gif', 'jpg', 'jpeg', 'webp'): ext = 'png' extractedfile="data:image/" + ext + ";base64," + b64 fileData={"name": names[VAR_9], "page":VAR_9, "last":len(names)-1, "content": extractedfile} return make_response(json.dumps(fileData)) return "", 204 ''' @VAR_2.route("/get_authors_json", methods=['GET']) @login_required_if_no_ano def FUNC_8(): return calibre_db.get_typeahead(db.Authors, request.args.get('q'), ('|', ',')) @VAR_2.route("/get_publishers_json", methods=['GET']) @login_required_if_no_ano def FUNC_9(): return calibre_db.get_typeahead(db.Publishers, request.args.get('q'), ('|', ',')) @VAR_2.route("/get_tags_json", methods=['GET']) @login_required_if_no_ano def FUNC_10(): return calibre_db.get_typeahead(db.Tags, request.args.get('q'), tag_filter=tags_filters()) @VAR_2.route("/get_series_json", methods=['GET']) @login_required_if_no_ano def FUNC_11(): return calibre_db.get_typeahead(db.Series, request.args.get('q')) @VAR_2.route("/get_languages_json", methods=['GET']) @login_required_if_no_ano def FUNC_12(): VAR_56 = (request.args.get('q') or '').lower() VAR_57 = isoLanguages.get_language_names(get_locale()) VAR_58 = [s for key, s in VAR_57.items() if s.lower().startswith(VAR_56.lower())] if len(VAR_58) < 5: VAR_63 = [s for key, s in VAR_57.items() if VAR_56 in s.lower()] VAR_58.extend(VAR_63[0:(5 - len(VAR_58))]) entries_start = list(set(VAR_58)) VAR_59 = json.dumps([dict(VAR_13=r) for r in VAR_58[0:5]]) return VAR_59 @VAR_2.route("/get_matching_tags", methods=['GET']) @login_required_if_no_ano def FUNC_13(): VAR_60 = {'tags': []} VAR_21 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters(True)) calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase) VAR_61 = request.args.get('author_name') or '' VAR_62 = request.args.get('book_title') or '' VAR_29 = request.args.getlist('include_tag') or '' VAR_30 = request.args.getlist('exclude_tag') or '' VAR_21 = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + VAR_61 + "%")), func.lower(db.Books.title).ilike("%" + VAR_62 + "%")) if len(VAR_29) > 0: for tag in VAR_29: VAR_21 = q.filter(db.Books.tags.any(db.Tags.id == tag)) if len(VAR_30) > 0: for tag in VAR_30: VAR_21 = q.filter(not_(db.Books.tags.any(db.Tags.id == tag))) for VAR_95 in VAR_21: for tag in VAR_95.tags: if tag.id not in VAR_60['tags']: VAR_60['tags'].append(tag.id) VAR_59 = json.dumps(VAR_60) return VAR_59 def FUNC_14(VAR_7, VAR_8): VAR_10 = [db.Books.timestamp.desc()] if VAR_7 == 'stored': VAR_7 = VAR_87.get_view_property(VAR_8, 'stored') else: VAR_87.set_view_property(VAR_8, 'stored', VAR_7) if VAR_7 == 'pubnew': VAR_10 = [db.Books.pubdate.desc()] if VAR_7 == 'pubold': VAR_10 = [db.Books.pubdate] if VAR_7 == 'abc': VAR_10 = [db.Books.sort] if VAR_7 == 'zyx': VAR_10 = [db.Books.sort.desc()] if VAR_7 == 'new': VAR_10 = [db.Books.timestamp.desc()] if VAR_7 == 'old': VAR_10 = [db.Books.timestamp] if VAR_7 == 'authaz': VAR_10 = [db.Books.author_sort.asc(), db.Series.name, db.Books.series_index] if VAR_7 == 'authza': VAR_10 = [db.Books.author_sort.desc(), db.Series.name.desc(), db.Books.series_index.desc()] if VAR_7 == 'seriesasc': VAR_10 = [db.Books.series_index.asc()] if VAR_7 == 'seriesdesc': VAR_10 = [db.Books.series_index.desc()] if VAR_7 == 'hotdesc': VAR_10 = [func.count(ub.Downloads.book_id).desc()] if VAR_7 == 'hotasc': VAR_10 = [func.count(ub.Downloads.book_id).asc()] if VAR_7 is None: VAR_7 = "new" return VAR_10, VAR_7 def FUNC_15(VAR_8, VAR_7, VAR_5, VAR_9): VAR_10 = FUNC_14(VAR_7, VAR_8) if VAR_8 == "rated": return FUNC_16(VAR_9, VAR_5, VAR_10=order) elif VAR_8 == "discover": return FUNC_17(VAR_9, VAR_5) elif VAR_8 == "unread": return FUNC_27(VAR_9, False, VAR_10=order) elif VAR_8 == "read": return FUNC_27(VAR_9, True, VAR_10=order) elif VAR_8 == "hot": return FUNC_18(VAR_9, VAR_10) elif VAR_8 == "download": return FUNC_19(VAR_9, VAR_10, VAR_5) elif VAR_8 == "author": return FUNC_20(VAR_9, VAR_5, VAR_10) elif VAR_8 == "publisher": return FUNC_21(VAR_9, VAR_5, VAR_10) elif VAR_8 == "series": return FUNC_22(VAR_9, VAR_5, VAR_10) elif VAR_8 == "ratings": return FUNC_23(VAR_9, VAR_5, VAR_10) elif VAR_8 == "formats": return FUNC_24(VAR_9, VAR_5, VAR_10) elif VAR_8 == "category": return FUNC_25(VAR_9, VAR_5, VAR_10) elif VAR_8 == "language": return FUNC_26(VAR_9, VAR_5, VAR_10) elif VAR_8 == "archived": return FUNC_28(VAR_9, VAR_10) elif VAR_8 == "search": VAR_17 = (request.args.get('query') or '') VAR_18 = int(int(config.config_books_per_page) * (VAR_9 - 1)) return FUNC_30(VAR_17, VAR_18, VAR_10, config.config_books_per_page) elif VAR_8 == "advsearch": VAR_17 = json.loads(VAR_91['query']) VAR_18 = int(int(config.config_books_per_page) * (VAR_9 - 1)) return FUNC_57(VAR_17, VAR_18, VAR_10, config.config_books_per_page) else: VAR_151 = VAR_8 or "newest" VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, True, VAR_10[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, VAR_150=_(u"Books"), VAR_9=VAR_151, VAR_10=order[1]) def FUNC_16(VAR_9, VAR_5, VAR_10): if VAR_87.check_visibility(constants.SIDEBAR_BEST_RATED): VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.ratings.any(db.Ratings.rating > 9), VAR_10[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_5, VAR_150=_(u"Top Rated Books"), VAR_9="rated", VAR_10=order[1]) else: abort(404) def FUNC_17(VAR_9, VAR_5): if VAR_87.check_visibility(constants.SIDEBAR_RANDOM): VAR_63, VAR_64, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, True, [func.randomblob(2)]) VAR_65 = Pagination(1, config.config_books_per_page, config.config_books_per_page) return render_title_template('discover.html', VAR_63=VAR_63, VAR_65=pagination, id=VAR_5, VAR_150=_(u"Discover (Random Books)"), VAR_9="discover") else: abort(404) def FUNC_18(VAR_9, VAR_10): if VAR_87.check_visibility(constants.SIDEBAR_HOT): if VAR_10[1] not in ['hotasc', 'hotdesc']: VAR_10 = [func.count(ub.Downloads.book_id).desc()], 'hotdesc' if VAR_87.show_detail_random(): VAR_68 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: VAR_68 = false() VAR_79 = int(int(config.config_books_per_page) * (VAR_9 - 1)) VAR_101 = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\ .order_by(*VAR_10[0]).group_by(ub.Downloads.book_id) VAR_102 = VAR_101.offset(VAR_79).limit(config.config_books_per_page) VAR_63 = list() for VAR_95 in VAR_102: VAR_125 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter( db.Books.id == VAR_95.Downloads.book_id).first() if VAR_125: VAR_63.append(VAR_125) else: ub.delete_download(VAR_95.Downloads.book_id) VAR_103 = VAR_63.__len__() VAR_65 = Pagination(VAR_9, config.config_books_per_page, VAR_103) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, VAR_150=_(u"Hot Books (Most Downloaded)"), VAR_9="hot", VAR_10=order[1]) else: abort(404) def FUNC_19(VAR_9, VAR_10, VAR_11): if VAR_87.role_admin(): VAR_11 = int(VAR_11) else: VAR_11 = VAR_87.id if VAR_87.check_visibility(constants.SIDEBAR_DOWNLOAD): if VAR_87.show_detail_random(): VAR_68 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: VAR_68 = false() VAR_63, VAR_64, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, ub.Downloads.user_id == VAR_11, VAR_10[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, ub.Downloads, db.Books.id == ub.Downloads.book_id) for VAR_95 in VAR_63: if not calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .filter(db.Books.id == VAR_95.id).first(): ub.delete_download(VAR_95.id) VAR_104 = ub.session.query(ub.User).filter(ub.User.id == VAR_11).first() return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_11, VAR_150=_(u"Downloaded VAR_127 by %(VAR_104)s",VAR_104=VAR_104.name), VAR_9="download", VAR_10=order[1]) else: abort(404) def FUNC_20(VAR_9, VAR_12, VAR_10): VAR_63, VAR_64, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.authors.any(db.Authors.id == VAR_12), [VAR_10[0][0], db.Series.name, db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) if VAR_63 is None or not len(VAR_63): flash(_(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) if constants.sqlalchemy_version2: VAR_105 = calibre_db.session.get(db.Authors, VAR_12) else: VAR_105 = calibre_db.session.query(db.Authors).get(VAR_12) VAR_36 = VAR_105.name.replace('|', ',') VAR_66 = None VAR_67 = [] if services.goodreads_support and config.config_use_goodreads: VAR_66 = services.goodreads_support.get_author_info(VAR_36) VAR_67 = services.goodreads_support.get_other_books(VAR_66, VAR_63) return render_title_template('author.html', VAR_63=VAR_63, VAR_65=pagination, id=VAR_12, VAR_150=_(u"Author: %(VAR_13)s", VAR_13=VAR_36), VAR_105=VAR_66, VAR_67=other_books, VAR_9="author", VAR_10=order[1]) def FUNC_21(VAR_9, VAR_5, VAR_10): VAR_38 = calibre_db.session.query(db.Publishers).filter(db.Publishers.id == VAR_5).first() if VAR_38: VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.publishers.any(db.Publishers.id == VAR_5), [db.Series.name, VAR_10[0][0], db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_5, VAR_150=_(u"Publisher: %(VAR_13)s", VAR_13=VAR_38.name), VAR_9="publisher", VAR_10=order[1]) else: abort(404) def FUNC_22(VAR_9, VAR_5, VAR_10): VAR_13 = calibre_db.session.query(db.Series).filter(db.Series.id == VAR_5).first() if VAR_13: VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.series.any(db.Series.id == VAR_5), [VAR_10[0][0]]) return render_title_template('index.html', VAR_68=random, VAR_65=pagination, VAR_63=VAR_63, id=VAR_5, VAR_150=_(u"Series: %(serie)s", serie=VAR_13.name), VAR_9="series", VAR_10=order[1]) else: abort(404) def FUNC_23(VAR_9, VAR_5, VAR_10): VAR_13 = calibre_db.session.query(db.Ratings).filter(db.Ratings.id == VAR_5).first() VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.ratings.any(db.Ratings.id == VAR_5), [VAR_10[0][0]]) if VAR_13 and VAR_13.rating <= 10: return render_title_template('index.html', VAR_68=random, VAR_65=pagination, VAR_63=VAR_63, id=VAR_5, VAR_150=_(u"Rating: %(rating)s stars", rating=int(VAR_13.rating / 2)), VAR_9="ratings", VAR_10=order[1]) else: abort(404) def FUNC_24(VAR_9, VAR_5, VAR_10): VAR_13 = calibre_db.session.query(db.Data).filter(db.Data.format == VAR_5.upper()).first() if VAR_13: VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.data.any(db.Data.format == VAR_5.upper()), [VAR_10[0][0]]) return render_title_template('index.html', VAR_68=random, VAR_65=pagination, VAR_63=VAR_63, id=VAR_5, VAR_150=_(u"File format: %(format)s", format=VAR_13.format), VAR_9="formats", VAR_10=order[1]) else: abort(404) def FUNC_25(VAR_9, VAR_5, VAR_10): VAR_13 = calibre_db.session.query(db.Tags).filter(db.Tags.id == VAR_5).first() if VAR_13: VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.tags.any(db.Tags.id == VAR_5), [VAR_10[0][0], db.Series.name, db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_5, VAR_150=_(u"Category: %(VAR_13)s", VAR_13=VAR_13.name), VAR_9="category", VAR_10=order[1]) else: abort(404) def FUNC_26(VAR_9, VAR_13, VAR_10): try: VAR_106 = isoLanguages.get_language_name(get_locale(), VAR_13) except KeyError: abort(404) VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.languages.any(db.Languages.lang_code == VAR_13), [VAR_10[0][0]]) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_13, VAR_150=_(u"Language: %(VAR_13)s", VAR_13=VAR_106), VAR_9="language", VAR_10=order[1]) def FUNC_27(VAR_9, VAR_14, VAR_15=False, VAR_10=None): VAR_7 = VAR_10[0] if VAR_10 else [] if not config.config_read_column: if VAR_14: VAR_126 = and_(ub.ReadBook.user_id == int(VAR_87.id), ub.ReadBook.read_status == ub.ReadBook.STATUS_FINISHED) else: VAR_126 = coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, VAR_126, VAR_7, db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, ub.ReadBook, db.Books.id == ub.ReadBook.book_id) else: try: if VAR_14: VAR_126 = db.cc_classes[config.config_read_column].value == True else: VAR_126 = coalesce(db.cc_classes[config.config_read_column].value, False) != True VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, VAR_126, VAR_7, db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, db.cc_classes[config.config_read_column]) except (KeyError, AttributeError): VAR_3.error("Custom Column No.%d is not existing in calibre database", config.config_read_column) if not VAR_15: flash(_("Custom Column No.%(column)d is not existing in calibre database", column=config.config_read_column), category="error") return redirect(url_for("web.index")) if VAR_15: return VAR_63, VAR_65 else: if VAR_14: VAR_13 = _(u'Read Books') + ' (' + str(VAR_65.total_count) + ')' VAR_72 = "read" else: VAR_13 = _(u'Unread Books') + ' (' + str(VAR_65.total_count) + ')' VAR_72 = "unread" return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, VAR_150=VAR_13, VAR_9=VAR_72, VAR_10=order[1]) def FUNC_28(VAR_9, VAR_7): VAR_10 = VAR_7[0] or [] VAR_69 = ( ub.session.query(ub.ArchivedBook) .filter(ub.ArchivedBook.user_id == int(VAR_87.id)) .filter(ub.ArchivedBook.is_archived == True) .all() ) VAR_70 = [VAR_142.book_id for VAR_142 in VAR_69] VAR_71 = db.Books.id.in_(VAR_70) VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage_with_archived_books(VAR_9, 0, db.Books, VAR_71, VAR_10, allow_show_archived=True) VAR_13 = _(u'Archived Books') + ' (' + str(len(VAR_70)) + ')' VAR_72 = "archived" return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, VAR_150=VAR_13, VAR_9=VAR_72, VAR_10=VAR_7[1]) def FUNC_29(VAR_16): VAR_41 = calibre_db.session.query(db.Tags)\ .join(db.books_tags_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag'))\ .order_by(db.Tags.name).all() VAR_73 = calibre_db.session.query(db.Series)\ .join(db.books_series_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series'))\ .order_by(db.Series.name)\ .filter(calibre_db.common_filters()).all() VAR_74 = ub.session.query(ub.Shelf)\ .filter(or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == int(VAR_87.id)))\ .order_by(ub.Shelf.name).all() VAR_75 = calibre_db.session.query(db.Data)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(db.Data.format)\ .order_by(db.Data.format).all() if VAR_87.filter_language() == u"all": VAR_48 = calibre_db.speaking_language() else: VAR_48 = None return render_title_template('search_form.html', VAR_41=tags, VAR_48=languages, VAR_75=extensions, VAR_73=series,VAR_74=shelves, VAR_150=_(u"Advanced Search"), VAR_16=cc, VAR_9="advsearch") def FUNC_30(VAR_17, VAR_18=None, VAR_10=None, VAR_19=None): VAR_76 = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series VAR_63, VAR_77, VAR_65 = calibre_db.get_search_results(VAR_17, VAR_18, VAR_10, VAR_19, *VAR_76) return render_title_template('search.html', VAR_35=VAR_17, VAR_65=pagination, VAR_56=VAR_17, adv_searchterm=VAR_17, VAR_63=entries, VAR_77=result_count, VAR_150=_(u"Search"), VAR_9="search", VAR_10=order[1]) @VAR_2.route("/", defaults={'page': 1}) @VAR_2.route('/VAR_9/<int:VAR_9>') @login_required_if_no_ano def FUNC_31(VAR_9): VAR_20 = (request.args.get('sort') or 'stored').lower() return FUNC_15("newest", VAR_20, 1, VAR_9) @VAR_2.route('/<VAR_8>/<VAR_20>', defaults={'page': 1, 'book_id': 1}) @VAR_2.route('/<VAR_8>/<VAR_20>/', defaults={'page': 1, 'book_id': 1}) @VAR_2.route('/<VAR_8>/<VAR_20>/<VAR_5>', defaults={'page': 1}) @VAR_2.route('/<VAR_8>/<VAR_20>/<VAR_5>/<int:VAR_9>') @login_required_if_no_ano def FUNC_32(VAR_8, VAR_20, VAR_5, VAR_9): return FUNC_15(VAR_8, VAR_20, VAR_5, VAR_9) @VAR_2.route("/table") @login_required def FUNC_33(): VAR_78 = VAR_87.view_settings.get('table', {}) VAR_16 = get_cc_columns(filter_config_custom_read=True) return render_title_template('book_table.html', VAR_150=_(u"Books List"), VAR_16=cc, VAR_9="book_table", visiblility=VAR_78) @VAR_2.route("/ajax/listbooks") @login_required def FUNC_34(): VAR_79 = int(request.args.get("offset") or 0) VAR_19 = int(request.args.get("limit") or config.config_books_per_page) VAR_80 = request.args.get("search") VAR_7 = request.args.get("sort", "id") VAR_10 = request.args.get("order", "").lower() VAR_81 = None VAR_76 = tuple() if VAR_7 == "state": VAR_81 = json.loads(request.args.get("state", "[]")) elif VAR_7 == "tags": VAR_10 = [db.Tags.name.asc()] if VAR_10 == "asc" else [db.Tags.name.desc()] VAR_76 = db.books_tags_link,db.Books.id == db.books_tags_link.c.book, db.Tags elif VAR_7 == "series": VAR_10 = [db.Series.name.asc()] if VAR_10 == "asc" else [db.Series.name.desc()] VAR_76 = db.books_series_link,db.Books.id == db.books_series_link.c.book, db.Series elif VAR_7 == "publishers": VAR_10 = [db.Publishers.name.asc()] if VAR_10 == "asc" else [db.Publishers.name.desc()] VAR_76 = db.books_publishers_link,db.Books.id == db.books_publishers_link.c.book, db.Publishers elif VAR_7 == "authors": VAR_10 = [db.Authors.name.asc(), db.Series.name, db.Books.series_index] if VAR_10 == "asc" \ else [db.Authors.name.desc(), db.Series.name.desc(), db.Books.series_index.desc()] VAR_76 = db.books_authors_link, db.Books.id == db.books_authors_link.c.book, db.Authors, \ db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series elif VAR_7 == "languages": VAR_10 = [db.Languages.lang_code.asc()] if VAR_10 == "asc" else [db.Languages.lang_code.desc()] VAR_76 = db.books_languages_link, db.Books.id == db.books_languages_link.c.book, db.Languages elif VAR_10 and VAR_7 in ["sort", "title", "authors_sort", "series_index"]: VAR_10 = [text(VAR_7 + " " + VAR_10)] elif not VAR_81: VAR_10 = [db.Books.timestamp.desc()] VAR_82 = VAR_83 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters(False)).count() if VAR_81 is not None: if VAR_80: VAR_127 = calibre_db.search_query(VAR_80).all() VAR_83 = len(VAR_127) else: VAR_127 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).all() VAR_63 = calibre_db.get_checkbox_sorted(VAR_127, VAR_81, VAR_79, VAR_19, VAR_10) elif VAR_80: VAR_63, VAR_83, VAR_64 = calibre_db.get_search_results(VAR_80, VAR_79, [VAR_10,''], VAR_19, *VAR_76) else: VAR_63, VAR_64, VAR_64 = calibre_db.fill_indexpage((int(VAR_79) / (int(VAR_19)) + 1), VAR_19, db.Books, True, VAR_10, *VAR_76) for entry in VAR_63: for FUNC_31 in range(0, len(entry.languages)): entry.languages[FUNC_31].language_name = isoLanguages.get_language_name(get_locale(), entry.languages[ FUNC_31].lang_code) VAR_84 = {'totalNotFiltered': VAR_82, 'total': VAR_83, "rows": VAR_63} VAR_85 = json.dumps(VAR_84, cls=db.AlchemyEncoder) VAR_86 = make_response(VAR_85) VAR_86.headers["Content-Type"] = "application/json; charset=utf-8" return VAR_86 @VAR_2.route("/ajax/table_settings", methods=['POST']) @login_required def FUNC_35(): VAR_87.view_settings['table'] = json.loads(request.data) try: try: flag_modified(VAR_87, "view_settings") except AttributeError: pass ub.session.commit() except (InvalidRequestError, OperationalError): VAR_3.error("Invalid request received: %r ", request, ) return "Invalid request", 400 return "" @VAR_2.route("/author") @login_required_if_no_ano def FUNC_36(): if VAR_87.check_visibility(constants.SIDEBAR_AUTHOR): if VAR_87.get_view_property('author', 'dir') == 'desc': VAR_10 = db.Authors.sort.desc() VAR_109 = 0 else: VAR_10 = db.Authors.sort.asc() VAR_109 = 1 VAR_63 = calibre_db.session.query(db.Authors, func.count('books_authors_link.book').label('count')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_authors_link.author')).order_by(VAR_10).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('char')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all() VAR_108 = copy.deepcopy(VAR_63) for entry in VAR_108: entry.Authors.name = entry.Authors.name.replace('|', ',') return render_title_template('list.html', VAR_63=VAR_108, folder='web.books_list', VAR_107=charlist, VAR_150=u"Authors", VAR_9="authorlist", VAR_8='author', VAR_10=VAR_109) else: abort(404) @VAR_2.route("/downloadlist") @login_required_if_no_ano def FUNC_37(): if VAR_87.get_view_property('download', 'dir') == 'desc': VAR_10 = ub.User.name.desc() VAR_109 = 0 else: VAR_10 = ub.User.name.asc() VAR_109 = 1 if VAR_87.check_visibility(constants.SIDEBAR_DOWNLOAD) and VAR_87.role_admin(): VAR_63 = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count'))\ .join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(VAR_10).all() VAR_107 = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \ .filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \ .group_by(func.upper(func.substr(ub.User.name, 1, 1))).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Downloads"), VAR_9="downloadlist", VAR_8="download", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/publisher") @login_required_if_no_ano def FUNC_38(): if VAR_87.get_view_property('publisher', 'dir') == 'desc': VAR_10 = db.Publishers.name.desc() VAR_109 = 0 else: VAR_10 = db.Publishers.name.asc() VAR_109 = 1 if VAR_87.check_visibility(constants.SIDEBAR_PUBLISHER): VAR_63 = calibre_db.session.query(db.Publishers, func.count('books_publishers_link.book').label('count')) \ .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_publishers_link.publisher')).order_by(VAR_10).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Publishers.name, 1, 1)).label('char')) \ .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Publishers.name, 1, 1))).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Publishers"), VAR_9="publisherlist", VAR_8="publisher", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/series") @login_required_if_no_ano def FUNC_39(): if VAR_87.check_visibility(constants.SIDEBAR_SERIES): if VAR_87.get_view_property('series', 'dir') == 'desc': VAR_10 = db.Series.sort.desc() VAR_109 = 0 else: VAR_10 = db.Series.sort.asc() VAR_109 = 1 if VAR_87.get_view_property('series', 'series_view') == 'list': VAR_63 = calibre_db.session.query(db.Series, func.count('books_series_link.book').label('count')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series')).order_by(VAR_10).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Series"), VAR_9="serieslist", VAR_8="series", VAR_10=VAR_109) else: VAR_63 = calibre_db.session.query(db.Books, func.count('books_series_link').label('count'), func.max(db.Books.series_index), db.Books.id) \ .join(db.books_series_link).join(db.Series).filter(calibre_db.common_filters())\ .group_by(text('books_series_link.series')).order_by(VAR_10).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all() return render_title_template('grid.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Series"), VAR_9="serieslist", VAR_8="series", bodyClass="grid-view", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/ratings") @login_required_if_no_ano def FUNC_40(): if VAR_87.check_visibility(constants.SIDEBAR_RATING): if VAR_87.get_view_property('ratings', 'dir') == 'desc': VAR_10 = db.Ratings.rating.desc() VAR_109 = 0 else: VAR_10 = db.Ratings.rating.asc() VAR_109 = 1 VAR_63 = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_ratings_link.rating')).order_by(VAR_10).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=list(), VAR_150=_(u"Ratings list"), VAR_9="ratingslist", VAR_8="ratings", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/formats") @login_required_if_no_ano def FUNC_41(): if VAR_87.check_visibility(constants.SIDEBAR_FORMAT): if VAR_87.get_view_property('ratings', 'dir') == 'desc': VAR_10 = db.Data.format.desc() VAR_109 = 0 else: VAR_10 = db.Data.format.asc() VAR_109 = 1 VAR_63 = calibre_db.session.query(db.Data, func.count('data.book').label('count'), db.Data.format.label('format')) \ .join(db.Books).filter(calibre_db.common_filters()) \ .group_by(db.Data.format).order_by(VAR_10).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=list(), VAR_150=_(u"File formats list"), VAR_9="formatslist", VAR_8="formats", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/language") @login_required_if_no_ano def FUNC_42(): if VAR_87.check_visibility(constants.SIDEBAR_LANGUAGE) and VAR_87.filter_language() == u"all": VAR_109 = 0 if VAR_87.get_view_property('language', 'dir') == 'desc' else 1 VAR_107 = list() VAR_48 = calibre_db.speaking_language(reverse_order=not VAR_109, with_count=True) for lang in VAR_48: VAR_128 = lang[0].name[0].upper() if VAR_128 not in VAR_107: charlist.append(VAR_128) return render_title_template('languages.html', VAR_48=languages, VAR_107=charlist, VAR_150=_(u"Languages"), VAR_9="langlist", VAR_8="language", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/category") @login_required_if_no_ano def FUNC_43(): if VAR_87.check_visibility(constants.SIDEBAR_CATEGORY): if VAR_87.get_view_property('category', 'dir') == 'desc': VAR_10 = db.Tags.name.desc() VAR_109 = 0 else: VAR_10 = db.Tags.name.asc() VAR_109 = 1 VAR_63 = calibre_db.session.query(db.Tags, func.count('books_tags_link.book').label('count')) \ .join(db.books_tags_link).join(db.Books).order_by(VAR_10).filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag')).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('char')) \ .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Categories"), VAR_9="catlist", VAR_8="category", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/tasks") @login_required def FUNC_44(): VAR_51 = WorkerThread.getInstance().tasks VAR_88 = render_task_status(VAR_51) return render_title_template('tasks.html', VAR_63=VAR_88, VAR_150=_(u"Tasks"), VAR_9="tasks") @app.route("/reconnect") def FUNC_45(): calibre_db.reconnect_db(config, ub.app_DB_path) return json.dumps({}) @VAR_2.route("/search", methods=["GET"]) @login_required_if_no_ano def VAR_80(): VAR_17 = request.args.get("query") if VAR_17: return redirect(url_for('web.books_list', VAR_8="search", VAR_20='stored', VAR_56=VAR_17)) else: return render_title_template('search.html', VAR_35="", VAR_77=0, VAR_150=_(u"Search"), VAR_9="search") @VAR_2.route("/advsearch", methods=['POST']) @login_required_if_no_ano def FUNC_47(): VAR_89 = dict(request.form) VAR_90 = ['include_tag', 'exclude_tag', 'include_serie', 'exclude_serie', 'include_shelf', 'exclude_shelf', 'include_language', 'exclude_language', 'include_extension', 'exclude_extension'] for VAR_110 in VAR_90: VAR_89[VAR_110] = list(request.form.getlist(VAR_110)) VAR_91['query'] = json.dumps(VAR_89) return redirect(url_for('web.books_list', VAR_8="advsearch", VAR_20='stored', VAR_56="")) def FUNC_48(VAR_16, VAR_17, VAR_21): for c in VAR_16: if c.datatype == "datetime": VAR_129 = VAR_17.get('custom_column_' + str(c.id) + '_start') VAR_130 = VAR_17.get('custom_column_' + str(c.id) + '_end') if VAR_129: VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.datetime(db.cc_classes[c.id].value) >= func.datetime(VAR_129))) if VAR_130: VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.datetime(db.cc_classes[c.id].value) <= func.datetime(VAR_130))) else: VAR_131 = VAR_17.get('custom_column_' + str(c.id)) if VAR_131 != '' and VAR_131 is not None: if c.datatype == 'bool': VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == (VAR_131 == "True"))) elif c.datatype == 'int' or c.datatype == 'float': VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == VAR_131)) elif c.datatype == 'rating': VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == int(float(VAR_131) * 2))) else: VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.lower(db.cc_classes[c.id].value).ilike("%" + VAR_131 + "%"))) return VAR_21 def FUNC_49(VAR_21, VAR_22, VAR_23): if VAR_87.filter_language() != "all": VAR_21 = q.filter(db.Books.languages.any(db.Languages.lang_code == VAR_87.filter_language())) else: for language in VAR_22: VAR_21 = q.filter(db.Books.languages.any(db.Languages.id == language)) for language in VAR_23: VAR_21 = q.filter(not_(db.Books.series.any(db.Languages.id == language))) return VAR_21 def FUNC_50(VAR_21, VAR_24, VAR_25): if VAR_24: VAR_24 = int(VAR_24) * 2 VAR_21 = q.filter(db.Books.ratings.any(db.Ratings.rating <= VAR_24)) if VAR_25: rating_low = int(VAR_25) * 2 VAR_21 = q.filter(db.Books.ratings.any(db.Ratings.rating >= VAR_25)) return VAR_21 def FUNC_51(VAR_21, VAR_26): if VAR_26: if config.config_read_column: try: if VAR_26 == "True": VAR_21 = q.join(db.cc_classes[config.config_read_column], isouter=True) \ .filter(db.cc_classes[config.config_read_column].value == True) else: VAR_21 = q.join(db.cc_classes[config.config_read_column], isouter=True) \ .filter(coalesce(db.cc_classes[config.config_read_column].value, False) != True) except (KeyError, AttributeError): VAR_3.error(u"Custom Column No.%d is not existing in calibre database", config.config_read_column) flash(_("Custom Column No.%(column)d is not existing in calibre database", column=config.config_read_column), category="error") return VAR_21 else: if VAR_26 == "True": VAR_21 = q.join(ub.ReadBook, db.Books.id == ub.ReadBook.book_id, isouter=True) \ .filter(ub.ReadBook.user_id == int(VAR_87.id), ub.ReadBook.read_status == ub.ReadBook.STATUS_FINISHED) else: VAR_21 = q.join(ub.ReadBook, db.Books.id == ub.ReadBook.book_id, isouter=True) \ .filter(ub.ReadBook.user_id == int(VAR_87.id), coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED) return VAR_21 def FUNC_52(VAR_21, VAR_27, VAR_28): for extension in VAR_27: VAR_21 = q.filter(db.Books.data.any(db.Data.format == extension)) for extension in VAR_28: VAR_21 = q.filter(not_(db.Books.data.any(db.Data.format == extension))) return VAR_21 def FUNC_53(VAR_21, VAR_29, VAR_30): for tag in VAR_29: VAR_21 = q.filter(db.Books.tags.any(db.Tags.id == tag)) for tag in VAR_30: VAR_21 = q.filter(not_(db.Books.tags.any(db.Tags.id == tag))) return VAR_21 def FUNC_54(VAR_21, VAR_31, VAR_32): for serie in VAR_31: VAR_21 = q.filter(db.Books.series.any(db.Series.id == serie)) for serie in VAR_32: VAR_21 = q.filter(not_(db.Books.series.any(db.Series.id == serie))) return VAR_21 def FUNC_55(VAR_21, VAR_33, VAR_34): VAR_21 = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\ .filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(VAR_34))) if len(VAR_33) > 0: VAR_21 = q.filter(ub.BookShelf.shelf.in_(VAR_33)) return VAR_21 def FUNC_56(VAR_35, VAR_36, VAR_37, VAR_38, VAR_39, VAR_40, VAR_41, VAR_24, VAR_25, VAR_26, ): VAR_35.extend((VAR_36.replace('|', ','), VAR_37, VAR_38)) if VAR_39: try: VAR_35.extend([_(u"Published after ") + format_date(datetime.strptime(VAR_39, "%Y-%m-%d"), format='medium', locale=get_locale())]) except ValueError: VAR_39 = u"" if VAR_40: try: VAR_35.extend([_(u"Published before ") + format_date(datetime.strptime(VAR_40, "%Y-%m-%d"), format='medium', locale=get_locale())]) except ValueError: VAR_40 = u"" VAR_92 = {'tag': db.Tags, 'serie':db.Series, 'shelf':ub.Shelf} for key, db_element in VAR_92.items(): VAR_111 = calibre_db.session.query(db_element).filter(db_element.id.in_(VAR_41['include_' + key])).all() VAR_35.extend(tag.name for tag in VAR_111) tag_names = calibre_db.session.query(db_element).filter(db_element.id.in_(VAR_41['exclude_' + key])).all() VAR_35.extend(tag.name for tag in VAR_111) VAR_57 = calibre_db.session.query(db.Languages). \ filter(db.Languages.id.in_(VAR_41['include_language'])).all() if VAR_57: language_names = calibre_db.speaking_language(VAR_57) VAR_35.extend(language.name for language in VAR_57) VAR_57 = calibre_db.session.query(db.Languages). \ filter(db.Languages.id.in_(VAR_41['exclude_language'])).all() if VAR_57: language_names = calibre_db.speaking_language(VAR_57) VAR_35.extend(language.name for language in VAR_57) if VAR_24: VAR_35.extend([_(u"Rating <= %(rating)s", rating=VAR_24)]) if VAR_25: VAR_35.extend([_(u"Rating >= %(rating)s", rating=VAR_25)]) if VAR_26: VAR_35.extend([_(u"Read Status = %(status)s", status=VAR_26)]) VAR_35.extend(ext for ext in VAR_41['include_extension']) VAR_35.extend(ext for ext in VAR_41['exclude_extension']) VAR_35 = " + ".join(filter(None, VAR_35)) return VAR_35, VAR_39, VAR_40 def FUNC_57(VAR_17, VAR_18=None, VAR_10=None, VAR_19=None): VAR_7 = VAR_10[0] if VAR_10 else [db.Books.sort] VAR_65 = None VAR_16 = get_cc_columns(filter_config_custom_read=True) calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase) VAR_21 = calibre_db.session.query(db.Books).outerjoin(db.books_series_link, db.Books.id == db.books_series_link.c.book)\ .outerjoin(db.Series)\ .filter(calibre_db.common_filters(True)) VAR_41 = dict() VAR_92 = ['tag', 'serie', 'shelf', 'language', 'extension'] for VAR_112 in VAR_92: VAR_41['include_' + VAR_112] = VAR_17.get('include_' + VAR_112) VAR_41['exclude_' + VAR_112] = VAR_17.get('exclude_' + VAR_112) VAR_36 = VAR_17.get("author_name") VAR_37 = VAR_17.get("book_title") VAR_38 = VAR_17.get("publisher") VAR_39 = VAR_17.get("publishstart") VAR_40 = VAR_17.get("publishend") VAR_25 = VAR_17.get("ratinghigh") VAR_24 = VAR_17.get("ratinglow") VAR_93 = VAR_17.get("comment") VAR_26 = VAR_17.get("read_status") if VAR_36: VAR_36 = VAR_36.strip().lower().replace(',', '|') if VAR_37: VAR_37 = VAR_37.strip().lower() if VAR_38: VAR_38 = VAR_38.strip().lower() VAR_35 = [] VAR_94 = False for c in VAR_16: if c.datatype == "datetime": VAR_132 = VAR_17.get('custom_column_' + str(c.id) + '_start') VAR_133 = VAR_17.get('custom_column_' + str(c.id) + '_end') if VAR_132: VAR_35.extend([u"{} >= {}".format(c.name, format_date(datetime.strptime(VAR_132, "%Y-%m-%d").date(), format='medium', locale=get_locale()) )]) VAR_94 = True if VAR_133: VAR_35.extend([u"{} <= {}".format(c.name, format_date(datetime.strptime(VAR_133, "%Y-%m-%d").date(), format='medium', locale=get_locale()) )]) VAR_94 = True elif VAR_17.get('custom_column_' + str(c.id)): VAR_35.extend([(u"{}: {}".format(c.name, VAR_17.get('custom_column_' + str(c.id))))]) VAR_94 = True if any(VAR_41.values()) or VAR_36 or VAR_37 or VAR_38 or VAR_39 or VAR_40 or VAR_25 \ or VAR_24 or VAR_93 or VAR_94 or VAR_26: VAR_35, VAR_39, VAR_40 = FUNC_56(VAR_35, VAR_36, VAR_37, VAR_38, VAR_39, VAR_40, VAR_41, VAR_24, VAR_25, VAR_26) VAR_21 = q.filter() if VAR_36: VAR_21 = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + VAR_36 + "%"))) if VAR_37: VAR_21 = q.filter(func.lower(db.Books.title).ilike("%" + VAR_37 + "%")) if VAR_39: VAR_21 = q.filter(func.datetime(db.Books.pubdate) > func.datetime(VAR_39)) if VAR_40: VAR_21 = q.filter(func.datetime(db.Books.pubdate) < func.datetime(VAR_40)) VAR_21 = FUNC_51(VAR_21, VAR_26) if VAR_38: VAR_21 = q.filter(db.Books.publishers.any(func.lower(db.Publishers.name).ilike("%" + VAR_38 + "%"))) VAR_21 = FUNC_53(VAR_21, VAR_41['include_tag'], VAR_41['exclude_tag']) VAR_21 = FUNC_54(VAR_21, VAR_41['include_serie'], VAR_41['exclude_serie']) VAR_21 = FUNC_55(VAR_21, VAR_41['include_shelf'], VAR_41['exclude_shelf']) VAR_21 = FUNC_52(VAR_21, VAR_41['include_extension'], VAR_41['exclude_extension']) VAR_21 = FUNC_49(VAR_21, VAR_41['include_language'], VAR_41['exclude_language']) VAR_21 = FUNC_50(VAR_21, VAR_24, VAR_25) if VAR_93: VAR_21 = q.filter(db.Books.comments.any(func.lower(db.Comments.text).ilike("%" + VAR_93 + "%"))) try: VAR_21 = FUNC_48(VAR_16, VAR_17, VAR_21) except AttributeError as ex: VAR_3.debug_or_exception(ex) flash(_("Error on VAR_80 for custom columns, please restart Calibre-Web"), category="error") VAR_21 = q.order_by(*VAR_7).all() VAR_91['query'] = json.dumps(VAR_17) ub.store_ids(VAR_21) VAR_77 = len(VAR_21) if VAR_18 is not None and VAR_19 is not None: VAR_18 = int(VAR_18) VAR_113 = VAR_18 + int(VAR_19) VAR_65 = Pagination((VAR_18 / (int(VAR_19)) + 1), VAR_19, VAR_77) else: VAR_18 = 0 VAR_113 = VAR_77 return render_title_template('search.html', adv_searchterm=VAR_35, VAR_65=pagination, VAR_63=VAR_21[VAR_18:VAR_113], VAR_77=result_count, VAR_150=_(u"Advanced Search"), VAR_9="advsearch", VAR_10=order[1]) @VAR_2.route("/advsearch", methods=['GET']) @login_required_if_no_ano def FUNC_58(): VAR_16 = get_cc_columns(filter_config_custom_read=True) return FUNC_29(VAR_16) @VAR_2.route("/cover/<int:VAR_5>") @login_required_if_no_ano def FUNC_59(VAR_5): return get_book_cover(VAR_5) @VAR_2.route("/robots.txt") def FUNC_60(): return send_from_directory(constants.STATIC_DIR, "robots.txt") @VAR_2.route("/show/<int:VAR_5>/<VAR_6>", defaults={'anyname': 'None'}) @VAR_2.route("/show/<int:VAR_5>/<VAR_6>/<VAR_42>") @login_required_if_no_ano @FUNC_2 def FUNC_61(VAR_5, VAR_6, VAR_42): VAR_6 = VAR_6.split(".")[0] VAR_95 = calibre_db.get_book(VAR_5) VAR_8 = calibre_db.get_book_format(VAR_5, VAR_6.upper()) if not VAR_8: return "File not in Database" VAR_3.info('Serving VAR_95: %s', VAR_8.name) if config.config_use_google_drive: try: VAR_134 = Headers() VAR_134["Content-Type"] = mimetypes.types_map.get('.' + VAR_6, "application/octet-stream") VAR_135 = getFileFromEbooksFolder(VAR_95.path, VAR_8.name + "." + VAR_6) return do_gdrive_download(VAR_135, VAR_134, (VAR_6.upper() == 'TXT')) except AttributeError as ex: VAR_3.debug_or_exception(ex) return "File Not Found" else: if VAR_6.upper() == 'TXT': try: VAR_146 = open(os.path.join(config.config_calibre_dir, VAR_95.path, VAR_8.name + "." + VAR_6), "rb").read() VAR_136 = chardet.detect(VAR_146) return make_response( VAR_146.decode(VAR_136['encoding'], 'surrogatepass').encode('utf-8', 'surrogatepass')) except FileNotFoundError: VAR_3.error("File Not Found") return "File Not Found" return send_from_directory(os.path.join(config.config_calibre_dir, VAR_95.path), VAR_8.name + "." + VAR_6) @VAR_2.route("/download/<int:VAR_5>/<VAR_6>", defaults={'anyname': 'None'}) @VAR_2.route("/download/<int:VAR_5>/<VAR_6>/<VAR_42>") @login_required_if_no_ano @FUNC_1 def FUNC_62(VAR_5, VAR_6, VAR_42): VAR_96 = "kobo" if "Kobo" in request.headers.get('User-Agent') else "" return get_download_link(VAR_5, VAR_6, VAR_96) @VAR_2.route('/send/<int:VAR_5>/<VAR_6>/<int:VAR_43>') @login_required @FUNC_1 def FUNC_63(VAR_5, VAR_6, VAR_43): if not config.get_mail_server_configured(): flash(_(u"Please configure the SMTP mail settings first..."), category="error") elif VAR_87.kindle_mail: VAR_136 = send_mail(VAR_5, VAR_6, VAR_43, VAR_87.kindle_mail, config.config_calibre_dir, VAR_87.name) if VAR_136 is None: flash(_(u"Book successfully queued for sending to %(kindlemail)s", kindlemail=VAR_87.kindle_mail), category="success") ub.update_download(VAR_5, int(VAR_87.id)) else: flash(_(u"Oops! There was an VAR_140 sending this VAR_95: %(res)s", res=VAR_136), category="error") else: flash(_(u"Please update your FUNC_68 with a valid Send to Kindle E-mail Address."), category="error") if "HTTP_REFERER" in request.environ: return redirect(request.environ["HTTP_REFERER"]) else: return redirect(url_for('web.index')) @VAR_2.route('/register', methods=['GET', 'POST']) def FUNC_64(): if not config.config_public_reg: abort(404) if VAR_87 is not None and VAR_87.is_authenticated: return redirect(url_for('web.index')) if not config.get_mail_server_configured(): flash(_(u"E-Mail server is not configured, please contact your administrator!"), category="error") return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") if request.method == "POST": VAR_55 = request.form.to_dict() VAR_114 = VAR_55["email"].strip() if config.config_register_email else VAR_55.get('name') if not VAR_114 or not VAR_55.get("email"): flash(_(u"Please fill out all fields!"), category="error") return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") try: VAR_114 = check_username(VAR_114) VAR_137 = check_email(VAR_55["email"]) except Exception as ex: flash(str(ex), category="error") return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") VAR_115 = ub.User() if check_valid_domain(VAR_137): VAR_115.name = VAR_114 VAR_115.email = VAR_137 VAR_138 = generate_random_password() VAR_115.password = generate_password_hash(VAR_138) VAR_115.role = config.config_default_role VAR_115.sidebar_view = config.config_default_show try: ub.session.add(VAR_115) ub.session.commit() if VAR_0['oauth']: register_user_with_oauth(VAR_115) send_registration_mail(VAR_55["email"].strip(), VAR_114, VAR_138) except Exception: ub.session.rollback() flash(_(u"An unknown VAR_140 occurred. Please try again later."), category="error") return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") else: flash(_(u"Your e-mail is not allowed to register"), category="error") VAR_3.warning('Registering failed for VAR_104 "%s" e-mail address: %s', VAR_114, VAR_55["email"]) return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") flash(_(u"Confirmation e-mail was send to your e-mail account."), category="success") return redirect(url_for('web.login')) if VAR_0['oauth']: register_user_with_oauth() return render_title_template('register.html', config=config, VAR_150=_("Register"), VAR_9="register") @VAR_2.route('/login', methods=['GET', 'POST']) def FUNC_65(): if VAR_87 is not None and VAR_87.is_authenticated: return redirect(url_for('web.index')) if config.config_login_type == constants.LOGIN_LDAP and not services.ldap: VAR_3.error(u"Cannot activate LDAP authentication") flash(_(u"Cannot activate LDAP authentication"), category="error") if request.method == "POST": VAR_116 = request.form.to_dict() VAR_104 = ub.session.query(ub.User).filter(func.lower(ub.User.name) == VAR_116['username'].strip().lower()) \ .first() if config.config_login_type == constants.LOGIN_LDAP and services.ldap and VAR_104 and VAR_116['password'] != "": VAR_139, VAR_140 = services.ldap.bind_user(VAR_116['username'], VAR_116['password']) if VAR_139: login_user(VAR_104, remember=bool(VAR_116.get('remember_me'))) ub.store_user_session() VAR_3.debug(u"You are now logged in as: '%s'", VAR_104.name) flash(_(u"you are now logged in as: '%(VAR_114)s'", VAR_114=VAR_104.name), category="success") return redirect_back(url_for("web.index")) elif VAR_139 is None and VAR_104 and check_password_hash(str(VAR_104.password), VAR_116['password']) \ and VAR_104.name != "Guest": login_user(VAR_104, remember=bool(VAR_116.get('remember_me'))) ub.store_user_session() VAR_3.info("Local Fallback Login as: '%s'", VAR_104.name) flash(_(u"Fallback Login as: '%(VAR_114)s', LDAP Server not reachable, or VAR_104 not known", VAR_114=VAR_104.name), category="warning") return redirect_back(url_for("web.index")) elif VAR_139 is None: VAR_3.info(VAR_140) flash(_(u"Could not FUNC_65: %(message)s", message=VAR_140), category="error") else: VAR_141 = request.headers.get('X-Forwarded-For', request.remote_addr) VAR_3.warning('LDAP Login failed for VAR_104 "%s" IP-address: %s', VAR_116['username'], VAR_141) flash(_(u"Wrong Username or Password"), category="error") else: VAR_141 = request.headers.get('X-Forwarded-For', request.remote_addr) if 'forgot' in VAR_116 and VAR_116['forgot'] == 'forgot': if VAR_104 is not None and VAR_104.name != "Guest": VAR_148, VAR_64 = reset_password(VAR_104.id) if VAR_148 == 1: flash(_(u"New Password was send to your VAR_137 address"), category="info") VAR_3.info('Password reset for VAR_104 "%s" IP-address: %s', VAR_116['username'], VAR_141) else: VAR_3.error(u"An unknown VAR_140 occurred. Please try again later") flash(_(u"An unknown VAR_140 occurred. Please try again later."), category="error") else: flash(_(u"Please enter valid username to reset password"), category="error") VAR_3.warning('Username missing for VAR_138 reset IP-address: %s', VAR_141) else: if VAR_104 and check_password_hash(str(VAR_104.password), VAR_116['password']) and VAR_104.name != "Guest": login_user(VAR_104, remember=bool(VAR_116.get('remember_me'))) ub.store_user_session() VAR_3.debug(u"You are now logged in as: '%s'", VAR_104.name) flash(_(u"You are now logged in as: '%(VAR_114)s'", VAR_114=VAR_104.name), category="success") config.config_is_initial = False return redirect_back(url_for("web.index")) else: VAR_3.warning('Login failed for VAR_104 "%s" IP-address: %s', VAR_116['username'], VAR_141) flash(_(u"Wrong Username or Password"), category="error") VAR_97 = request.args.get('next', default=url_for("web.index"), type=str) if url_for("web.logout") == VAR_97: next_url = url_for("web.index") return render_title_template('login.html', VAR_150=_(u"Login"), VAR_97=next_url, config=config, VAR_100=oauth_check, mail=config.get_mail_server_configured(), VAR_9="login") @VAR_2.route('/logout') @login_required def FUNC_66(): if VAR_87 is not None and VAR_87.is_authenticated: ub.delete_user_session(VAR_87.id, VAR_91.get('_id',"")) logout_user() if VAR_0['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3): logout_oauth_user() VAR_3.debug(u"User logged out") return redirect(url_for('web.login')) def FUNC_67(VAR_44, VAR_45, VAR_46, VAR_47, VAR_48): VAR_55 = request.form.to_dict() VAR_87.random_books = 0 if VAR_87.role_passwd() or VAR_87.role_admin(): if VAR_55.get("password"): VAR_87.password = generate_password_hash(VAR_55["password"]) try: if VAR_55.get("kindle_mail", VAR_87.kindle_mail) != VAR_87.kindle_mail: VAR_87.kindle_mail = valid_email(VAR_55["kindle_mail"]) if VAR_55.get("email", VAR_87.email) != VAR_87.email: VAR_87.email = check_email(VAR_55["email"]) if VAR_87.role_admin(): if VAR_55.get("name", VAR_87.name) != VAR_87.name: VAR_87.name = check_username(VAR_55["name"]) VAR_87.random_books = 1 if VAR_55.get("show_random") == "on" else 0 if VAR_55.get("default_language"): VAR_87.default_language = VAR_55["default_language"] if VAR_55.get("locale"): VAR_87.locale = VAR_55["locale"] VAR_117 = VAR_87.kobo_only_shelves_sync VAR_87.kobo_only_shelves_sync = int(VAR_55.get("kobo_only_shelves_sync") == "on") or 0 if VAR_117 == 0 and VAR_87.kobo_only_shelves_sync == 1: kobo_sync_status.update_on_sync_shelfs(VAR_87.id) except Exception as ex: flash(str(ex), category="error") return render_title_template("user_edit.html", VAR_115=VAR_87, VAR_47=translations, FUNC_68=1, VAR_48=languages, VAR_150=_(u"%(VAR_13)s's profile", VAR_13=VAR_87.name), VAR_9="me", VAR_44=kobo_support, registered_oauth=VAR_45, VAR_46=oauth_status) VAR_98 = 0 for key, VAR_64 in VAR_55.items(): if key.startswith('show'): VAR_98 += int(key[5:]) VAR_87.sidebar_view = VAR_98 if VAR_55.get("Show_detail_random"): VAR_87.sidebar_view += constants.DETAIL_RANDOM try: ub.session.commit() flash(_(u"Profile updated"), category="success") VAR_3.debug(u"Profile updated") except IntegrityError: ub.session.rollback() flash(_(u"Found an existing account for this e-mail address"), category="error") VAR_3.debug(u"Found an existing account for this e-mail address") except OperationalError as e: ub.session.rollback() VAR_3.error("Database VAR_140: %s", e) flash(_(u"Database VAR_140: %(error)s.", VAR_140=e), category="error") @VAR_2.route("/me", methods=["GET", "POST"]) @login_required def FUNC_68(): VAR_48 = calibre_db.speaking_language() VAR_47 = babel.list_translations() + [LC('en')] VAR_44 = VAR_0['kobo'] and config.config_kobo_sync if VAR_0['oauth'] and config.config_login_type == 2: VAR_46 = get_oauth_status() VAR_45 = VAR_100 else: VAR_46 = None VAR_45 = {} if request.method == "POST": FUNC_67(VAR_44, VAR_45, VAR_46, VAR_47, VAR_48) return render_title_template("user_edit.html", VAR_47=translations, FUNC_68=1, VAR_48=languages, VAR_115=VAR_87, VAR_44=kobo_support, VAR_150=_(u"%(VAR_13)s's profile", VAR_13=VAR_87.name), VAR_9="me", registered_oauth=VAR_45, VAR_46=oauth_status) @VAR_2.route("/read/<int:VAR_5>/<VAR_6>") @login_required_if_no_ano @FUNC_2 def FUNC_69(VAR_5, VAR_6): VAR_95 = calibre_db.get_filtered_book(VAR_5) if not VAR_95: flash(_(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible"), category="error") VAR_3.debug(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible") return redirect(url_for("web.index")) FUNC_4 = None if VAR_87.is_authenticated: VAR_99 = ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(VAR_87.id), ub.Bookmark.book_id == VAR_5, ub.Bookmark.format == VAR_6.upper())).first() if VAR_6.lower() == "epub": VAR_3.debug(u"Start epub reader for %d", VAR_5) return render_title_template('read.html', bookid=VAR_5, VAR_150=VAR_95.title, VAR_99=FUNC_4) elif VAR_6.lower() == "pdf": VAR_3.debug(u"Start pdf reader for %d", VAR_5) return render_title_template('readpdf.html', pdffile=VAR_5, VAR_150=VAR_95.title) elif VAR_6.lower() == "txt": VAR_3.debug(u"Start txt reader for %d", VAR_5) return render_title_template('readtxt.html', txtfile=VAR_5, VAR_150=VAR_95.title) elif VAR_6.lower() == "djvu": VAR_3.debug(u"Start djvu reader for %d", VAR_5) return render_title_template('readdjvu.html', djvufile=VAR_5, VAR_150=VAR_95.title) else: for fileExt in constants.EXTENSIONS_AUDIO: if VAR_6.lower() == fileExt: VAR_63 = calibre_db.get_filtered_book(VAR_5) VAR_3.debug(u"Start mp3 listening for %d", VAR_5) return render_title_template('listenmp3.html', mp3file=VAR_5, audioformat=VAR_6.lower(), entry=VAR_63, VAR_99=FUNC_4) for fileExt in ["cbr", "cbt", "cbz"]: if VAR_6.lower() == fileExt: VAR_149 = str(VAR_5) VAR_150 = VAR_95.title if len(VAR_95.series): VAR_150 = VAR_150 + " - " + VAR_95.series[0].name if VAR_95.series_index: VAR_150 = VAR_150 + " #" + '{0:.2f}'.format(VAR_95.series_index).rstrip('0').rstrip('.') VAR_3.debug(u"Start comic reader for %d", VAR_5) return render_title_template('readcbr.html', comicfile=VAR_149, VAR_150=title, extension=fileExt) VAR_3.debug(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) @VAR_2.route("/VAR_95/<int:VAR_5>") @login_required_if_no_ano def FUNC_70(VAR_5): VAR_63 = calibre_db.get_filtered_book(VAR_5, allow_show_archived=True) if VAR_63: for FUNC_31 in range(0, len(VAR_63.languages)): VAR_63.languages[FUNC_31].language_name = isoLanguages.get_language_name(get_locale(), VAR_63.languages[ FUNC_31].lang_code) VAR_16 = get_cc_columns(filter_config_custom_read=True) VAR_118 = [] VAR_119 = ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == VAR_5).all() for entry in VAR_119: VAR_118.append(entry.shelf) if not VAR_87.is_anonymous: if not config.config_read_column: VAR_147 = ub.session.query(ub.ReadBook). \ filter(and_(ub.ReadBook.user_id == int(VAR_87.id), ub.ReadBook.book_id == VAR_5)).all() VAR_143 = len( VAR_147) > 0 and VAR_147[0].read_status == ub.ReadBook.STATUS_FINISHED else: try: VAR_147 = getattr(VAR_63, 'custom_column_' + str(config.config_read_column)) VAR_143 = len(VAR_147) > 0 and VAR_147[0].value except (KeyError, AttributeError): VAR_3.error("Custom Column No.%d is not existing in calibre database", config.config_read_column) VAR_143 = None VAR_142 = ub.session.query(ub.ArchivedBook).\ filter(and_(ub.ArchivedBook.user_id == int(VAR_87.id), ub.ArchivedBook.book_id == VAR_5)).first() VAR_54 = VAR_142 and VAR_142.is_archived else: VAR_143 = None VAR_54 = None VAR_63.tags = VAR_7(VAR_63.tags, key=lambda tag: tag.name) VAR_63 = calibre_db.order_authors(VAR_63) VAR_120 = check_send_to_kindle(VAR_63) VAR_121 = check_read_formats(VAR_63) VAR_122 = [] for media_format in VAR_63.data: if media_format.format.lower() in constants.EXTENSIONS_AUDIO: VAR_122.append(media_format.format.lower()) return render_title_template('detail.html', entry=VAR_63, VAR_122=audioentries, VAR_16=cc, is_xhr=request.headers.get('X-Requested-With')=='XMLHttpRequest', VAR_150=VAR_63.title, books_shelfs=VAR_118, VAR_143=have_read, VAR_54=is_archived, VAR_120=kindle_list, VAR_121=reader_list, VAR_9="book") else: VAR_3.debug(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index"))
import os from datetime import datetime import json import mimetypes import chardet # dependency of requests import copy from babel.dates import .format_date from babel import Locale as LC from flask import Blueprint, jsonify from flask import request, redirect, send_from_directory, make_response, flash, abort, url_for from flask import session as VAR_91 from flask_babel import gettext as _ from flask_login import .login_user, logout_user, login_required, VAR_87 from sqlalchemy.exc import IntegrityError, InvalidRequestError, OperationalError from sqlalchemy.sql.expression import text, func, false, not_, and_, or_ from sqlalchemy.orm.attributes import .flag_modified from sqlalchemy.sql.functions import coalesce from .services.worker import WorkerThread from werkzeug.datastructures import Headers from werkzeug.security import generate_password_hash, check_password_hash from . import constants, logger, isoLanguages, services from . import babel, db, ub, config, get_locale, app from . import calibre_db, kobo_sync_status from .gdriveutils import getFileFromEbooksFolder, do_gdrive_download from .helper import check_valid_domain, render_task_status, check_email, check_username, \ get_cc_columns, get_book_cover, get_download_link, send_mail, generate_random_password, \ send_registration_mail, check_send_to_kindle, check_read_formats, tags_filters, reset_password, valid_email from .pagination import Pagination from .redirect import redirect_back from .usermanagement import .login_required_if_no_ano from .kobo_sync_status import remove_synced_book from .render_template import render_title_template from .kobo_sync_status import change_archived_books VAR_0 = { 'ldap': bool(services.ldap), 'goodreads': bool(services.goodreads_support), 'kobo': bool(services.kobo) } try: from .oauth_bb import .oauth_check, register_user_with_oauth, logout_oauth_user, get_oauth_status VAR_0['oauth'] = True except ImportError: VAR_0['oauth'] = False VAR_100 = {} try: from functools import wraps except ImportError: pass # We're not using Python 3 try: from natsort import natsorted as VAR_7 except ImportError: VAR_7 = sorted # Just use regular VAR_7 then, may cause issues with badly named pages in cbz/cbr files @app.after_request def FUNC_0(VAR_1): VAR_1.headers['Content-Security-Policy'] = "default-src 'self'" + ''.join([' '+host for host in config.config_trustedhosts.strip().split(',')]) + " 'unsafe-inline' 'unsafe-eval'; font-src 'self' VAR_8:; img-src 'self' VAR_8:" if request.endpoint == "editbook.edit_book" or config.config_use_google_drive: VAR_1.headers['Content-Security-Policy'] += " *" elif request.endpoint == "web.read_book": VAR_1.headers['Content-Security-Policy'] += " blob:;style-src-elem 'self' blob: 'unsafe-inline';" VAR_1.headers['X-Content-Type-Options'] = 'nosniff' VAR_1.headers['X-Frame-Options'] = 'SAMEORIGIN' VAR_1.headers['X-XSS-Protection'] = '1; mode=block' VAR_1.headers['Strict-Transport-Security'] = 'max-age=31536000;' return VAR_1 VAR_2 = Blueprint('web', __name__) VAR_3 = logger.create() def FUNC_1(VAR_4): @wraps(VAR_4) def FUNC_71(*VAR_49, **VAR_50): if VAR_87.role_download(): return VAR_4(*VAR_49, **VAR_50) abort(403) return FUNC_71 def FUNC_2(VAR_4): @wraps(VAR_4) def FUNC_71(*VAR_49, **VAR_50): if VAR_87.role_viewer(): return VAR_4(*VAR_49, **VAR_50) abort(403) return FUNC_71 @VAR_2.route("/ajax/emailstat") @login_required def FUNC_3(): VAR_51 = WorkerThread.getInstance().tasks return jsonify(render_task_status(VAR_51)) @VAR_2.route("/ajax/VAR_99/<int:VAR_5>/<VAR_6>", methods=['POST']) @login_required def VAR_99(VAR_5, VAR_6): VAR_52 = request.form["bookmark"] ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(VAR_87.id), ub.Bookmark.book_id == VAR_5, ub.Bookmark.format == VAR_6)).delete() if not VAR_52: ub.session_commit() return "", 204 VAR_53 = ub.Bookmark(VAR_11=VAR_87.id, VAR_5=book_id, format=VAR_6, VAR_52=bookmark_key) ub.session.merge(VAR_53) ub.session_commit("Bookmark for VAR_104 {} in VAR_95 {} created".format(VAR_87.id, VAR_5)) return "", 201 @VAR_2.route("/ajax/toggleread/<int:VAR_5>", methods=['POST']) @login_required def FUNC_5(VAR_5): if not config.config_read_column: VAR_95 = ub.session.query(ub.ReadBook).filter(and_(ub.ReadBook.user_id == int(VAR_87.id), ub.ReadBook.book_id == VAR_5)).first() if VAR_95: if VAR_95.read_status == ub.ReadBook.STATUS_FINISHED: VAR_95.read_status = ub.ReadBook.STATUS_UNREAD else: VAR_95.read_status = ub.ReadBook.STATUS_FINISHED else: VAR_123 = ub.ReadBook(VAR_11=VAR_87.id, VAR_5 = book_id) VAR_123.read_status = ub.ReadBook.STATUS_FINISHED VAR_95 = VAR_123 if not VAR_95.kobo_reading_state: VAR_124 = ub.KoboReadingState(VAR_11=VAR_87.id, VAR_5=book_id) VAR_124.current_bookmark = ub.KoboBookmark() VAR_124.statistics = ub.KoboStatistics() VAR_95.kobo_reading_state = VAR_124 ub.session.merge(VAR_95) ub.session_commit("Book {} readbit toggled".format(VAR_5)) else: try: calibre_db.update_title_sort(config) VAR_95 = calibre_db.get_filtered_book(VAR_5) VAR_26 = getattr(VAR_95, 'custom_column_' + str(config.config_read_column)) if len(VAR_26): VAR_26[0].value = not VAR_26[0].value calibre_db.session.commit() else: VAR_144 = db.cc_classes[config.config_read_column] VAR_145 = VAR_144(value=1, VAR_95=VAR_5) calibre_db.session.add(VAR_145) calibre_db.session.commit() except (KeyError, AttributeError): VAR_3.error(u"Custom Column No.%d is not existing in calibre database", config.config_read_column) return "Custom Column No.{} is not existing in calibre database".format(config.config_read_column), 400 except (OperationalError, InvalidRequestError) as e: calibre_db.session.rollback() VAR_3.error(u"Read status could not set: {}".format(e)) return "Read status could not set: {}".format(e), 400 return "" @VAR_2.route("/ajax/togglearchived/<int:VAR_5>", methods=['POST']) @login_required def FUNC_6(VAR_5): VAR_54 = change_archived_books(VAR_5, message="Book {} archivebit toggled".format(VAR_5)) if VAR_54: remove_synced_book(VAR_5) return "" @VAR_2.route("/ajax/view", methods=["POST"]) @login_required_if_no_ano def FUNC_7(): VAR_55 = request.get_json() try: for VAR_112 in VAR_55: for VAR_110 in VAR_55[VAR_112]: VAR_87.set_view_property(VAR_112, VAR_110, VAR_55[VAR_112][VAR_110]) except Exception as ex: VAR_3.error("Could not save view_settings: %r %r: %e", request, VAR_55, ex) return "Invalid request", 400 return "1", 200 ''' @VAR_2.route("/ajax/getcomic/<int:VAR_5>/<VAR_6>/<int:VAR_9>") @login_required def get_comic_book(VAR_5, VAR_6, VAR_9): VAR_95 = calibre_db.get_book(VAR_5) if not VAR_95: return "", 204 else: for bookformat in VAR_95.data: if bookformat.format.lower() == VAR_6.lower(): cbr_file = os.path.join(config.config_calibre_dir, VAR_95.path, bookformat.name) + "." + VAR_6 if VAR_6 in ("cbr", "rar"): if VAR_0['rar'] == True: rarfile.UNRAR_TOOL = config.config_rarfile_location try: rf = rarfile.RarFile(cbr_file) names = VAR_7(rf.namelist()) extract = lambda VAR_9: rf.read(names[VAR_9]) except: VAR_3.error('Unrar binary not found, or unable to decompress file %s', cbr_file) return "", 204 else: VAR_3.info('Unrar is not supported please install python rarfile extension') return "", 204 elif VAR_6 in ("cbz", "zip"): zf = zipfile.ZipFile(cbr_file) names=VAR_7(zf.namelist()) extract = lambda VAR_9: zf.read(names[VAR_9]) elif VAR_6 in ("cbt", "tar"): tf = tarfile.TarFile(cbr_file) names=VAR_7(tf.getnames()) extract = lambda VAR_9: tf.extractfile(names[VAR_9]).read() else: VAR_3.error('unsupported comic format') return "", 204 b64 = codecs.encode(extract(VAR_9), 'base64').decode() ext = names[VAR_9].rpartition('.')[-1] if ext not in ('png', 'gif', 'jpg', 'jpeg', 'webp'): ext = 'png' extractedfile="data:image/" + ext + ";base64," + b64 fileData={"name": names[VAR_9], "page":VAR_9, "last":len(names)-1, "content": extractedfile} return make_response(json.dumps(fileData)) return "", 204 ''' @VAR_2.route("/get_authors_json", methods=['GET']) @login_required_if_no_ano def FUNC_8(): return calibre_db.get_typeahead(db.Authors, request.args.get('q'), ('|', ',')) @VAR_2.route("/get_publishers_json", methods=['GET']) @login_required_if_no_ano def FUNC_9(): return calibre_db.get_typeahead(db.Publishers, request.args.get('q'), ('|', ',')) @VAR_2.route("/get_tags_json", methods=['GET']) @login_required_if_no_ano def FUNC_10(): return calibre_db.get_typeahead(db.Tags, request.args.get('q'), tag_filter=tags_filters()) @VAR_2.route("/get_series_json", methods=['GET']) @login_required_if_no_ano def FUNC_11(): return calibre_db.get_typeahead(db.Series, request.args.get('q')) @VAR_2.route("/get_languages_json", methods=['GET']) @login_required_if_no_ano def FUNC_12(): VAR_56 = (request.args.get('q') or '').lower() VAR_57 = isoLanguages.get_language_names(get_locale()) VAR_58 = [s for key, s in VAR_57.items() if s.lower().startswith(VAR_56.lower())] if len(VAR_58) < 5: VAR_63 = [s for key, s in VAR_57.items() if VAR_56 in s.lower()] VAR_58.extend(VAR_63[0:(5 - len(VAR_58))]) entries_start = list(set(VAR_58)) VAR_59 = json.dumps([dict(VAR_13=r) for r in VAR_58[0:5]]) return VAR_59 @VAR_2.route("/get_matching_tags", methods=['GET']) @login_required_if_no_ano def FUNC_13(): VAR_60 = {'tags': []} VAR_21 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters(True)) calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase) VAR_61 = request.args.get('author_name') or '' VAR_62 = request.args.get('book_title') or '' VAR_29 = request.args.getlist('include_tag') or '' VAR_30 = request.args.getlist('exclude_tag') or '' VAR_21 = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + VAR_61 + "%")), func.lower(db.Books.title).ilike("%" + VAR_62 + "%")) if len(VAR_29) > 0: for tag in VAR_29: VAR_21 = q.filter(db.Books.tags.any(db.Tags.id == tag)) if len(VAR_30) > 0: for tag in VAR_30: VAR_21 = q.filter(not_(db.Books.tags.any(db.Tags.id == tag))) for VAR_95 in VAR_21: for tag in VAR_95.tags: if tag.id not in VAR_60['tags']: VAR_60['tags'].append(tag.id) VAR_59 = json.dumps(VAR_60) return VAR_59 def FUNC_14(VAR_7, VAR_8): VAR_10 = [db.Books.timestamp.desc()] if VAR_7 == 'stored': VAR_7 = VAR_87.get_view_property(VAR_8, 'stored') else: VAR_87.set_view_property(VAR_8, 'stored', VAR_7) if VAR_7 == 'pubnew': VAR_10 = [db.Books.pubdate.desc()] if VAR_7 == 'pubold': VAR_10 = [db.Books.pubdate] if VAR_7 == 'abc': VAR_10 = [db.Books.sort] if VAR_7 == 'zyx': VAR_10 = [db.Books.sort.desc()] if VAR_7 == 'new': VAR_10 = [db.Books.timestamp.desc()] if VAR_7 == 'old': VAR_10 = [db.Books.timestamp] if VAR_7 == 'authaz': VAR_10 = [db.Books.author_sort.asc(), db.Series.name, db.Books.series_index] if VAR_7 == 'authza': VAR_10 = [db.Books.author_sort.desc(), db.Series.name.desc(), db.Books.series_index.desc()] if VAR_7 == 'seriesasc': VAR_10 = [db.Books.series_index.asc()] if VAR_7 == 'seriesdesc': VAR_10 = [db.Books.series_index.desc()] if VAR_7 == 'hotdesc': VAR_10 = [func.count(ub.Downloads.book_id).desc()] if VAR_7 == 'hotasc': VAR_10 = [func.count(ub.Downloads.book_id).asc()] if VAR_7 is None: VAR_7 = "new" return VAR_10, VAR_7 def FUNC_15(VAR_8, VAR_7, VAR_5, VAR_9): VAR_10 = FUNC_14(VAR_7, VAR_8) if VAR_8 == "rated": return FUNC_16(VAR_9, VAR_5, VAR_10=order) elif VAR_8 == "discover": return FUNC_17(VAR_9, VAR_5) elif VAR_8 == "unread": return FUNC_27(VAR_9, False, VAR_10=order) elif VAR_8 == "read": return FUNC_27(VAR_9, True, VAR_10=order) elif VAR_8 == "hot": return FUNC_18(VAR_9, VAR_10) elif VAR_8 == "download": return FUNC_19(VAR_9, VAR_10, VAR_5) elif VAR_8 == "author": return FUNC_20(VAR_9, VAR_5, VAR_10) elif VAR_8 == "publisher": return FUNC_21(VAR_9, VAR_5, VAR_10) elif VAR_8 == "series": return FUNC_22(VAR_9, VAR_5, VAR_10) elif VAR_8 == "ratings": return FUNC_23(VAR_9, VAR_5, VAR_10) elif VAR_8 == "formats": return FUNC_24(VAR_9, VAR_5, VAR_10) elif VAR_8 == "category": return FUNC_25(VAR_9, VAR_5, VAR_10) elif VAR_8 == "language": return FUNC_26(VAR_9, VAR_5, VAR_10) elif VAR_8 == "archived": return FUNC_28(VAR_9, VAR_10) elif VAR_8 == "search": VAR_17 = (request.args.get('query') or '') VAR_18 = int(int(config.config_books_per_page) * (VAR_9 - 1)) return FUNC_30(VAR_17, VAR_18, VAR_10, config.config_books_per_page) elif VAR_8 == "advsearch": VAR_17 = json.loads(VAR_91['query']) VAR_18 = int(int(config.config_books_per_page) * (VAR_9 - 1)) return FUNC_57(VAR_17, VAR_18, VAR_10, config.config_books_per_page) else: VAR_151 = VAR_8 or "newest" VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, True, VAR_10[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, VAR_150=_(u"Books"), VAR_9=VAR_151, VAR_10=order[1]) def FUNC_16(VAR_9, VAR_5, VAR_10): if VAR_87.check_visibility(constants.SIDEBAR_BEST_RATED): VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.ratings.any(db.Ratings.rating > 9), VAR_10[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_5, VAR_150=_(u"Top Rated Books"), VAR_9="rated", VAR_10=order[1]) else: abort(404) def FUNC_17(VAR_9, VAR_5): if VAR_87.check_visibility(constants.SIDEBAR_RANDOM): VAR_63, VAR_64, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, True, [func.randomblob(2)]) VAR_65 = Pagination(1, config.config_books_per_page, config.config_books_per_page) return render_title_template('discover.html', VAR_63=VAR_63, VAR_65=pagination, id=VAR_5, VAR_150=_(u"Discover (Random Books)"), VAR_9="discover") else: abort(404) def FUNC_18(VAR_9, VAR_10): if VAR_87.check_visibility(constants.SIDEBAR_HOT): if VAR_10[1] not in ['hotasc', 'hotdesc']: VAR_10 = [func.count(ub.Downloads.book_id).desc()], 'hotdesc' if VAR_87.show_detail_random(): VAR_68 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: VAR_68 = false() VAR_79 = int(int(config.config_books_per_page) * (VAR_9 - 1)) VAR_101 = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\ .order_by(*VAR_10[0]).group_by(ub.Downloads.book_id) VAR_102 = VAR_101.offset(VAR_79).limit(config.config_books_per_page) VAR_63 = list() for VAR_95 in VAR_102: VAR_125 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter( db.Books.id == VAR_95.Downloads.book_id).first() if VAR_125: VAR_63.append(VAR_125) else: ub.delete_download(VAR_95.Downloads.book_id) VAR_103 = VAR_63.__len__() VAR_65 = Pagination(VAR_9, config.config_books_per_page, VAR_103) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, VAR_150=_(u"Hot Books (Most Downloaded)"), VAR_9="hot", VAR_10=order[1]) else: abort(404) def FUNC_19(VAR_9, VAR_10, VAR_11): if VAR_87.role_admin(): VAR_11 = int(VAR_11) else: VAR_11 = VAR_87.id if VAR_87.check_visibility(constants.SIDEBAR_DOWNLOAD): if VAR_87.show_detail_random(): VAR_68 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: VAR_68 = false() VAR_63, VAR_64, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, ub.Downloads.user_id == VAR_11, VAR_10[0], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, ub.Downloads, db.Books.id == ub.Downloads.book_id) for VAR_95 in VAR_63: if not calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .filter(db.Books.id == VAR_95.id).first(): ub.delete_download(VAR_95.id) VAR_104 = ub.session.query(ub.User).filter(ub.User.id == VAR_11).first() return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_11, VAR_150=_(u"Downloaded VAR_127 by %(VAR_104)s",VAR_104=VAR_104.name), VAR_9="download", VAR_10=order[1]) else: abort(404) def FUNC_20(VAR_9, VAR_12, VAR_10): VAR_63, VAR_64, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.authors.any(db.Authors.id == VAR_12), [VAR_10[0][0], db.Series.name, db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) if VAR_63 is None or not len(VAR_63): flash(_(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) if constants.sqlalchemy_version2: VAR_105 = calibre_db.session.get(db.Authors, VAR_12) else: VAR_105 = calibre_db.session.query(db.Authors).get(VAR_12) VAR_36 = VAR_105.name.replace('|', ',') VAR_66 = None VAR_67 = [] if services.goodreads_support and config.config_use_goodreads: VAR_66 = services.goodreads_support.get_author_info(VAR_36) VAR_67 = services.goodreads_support.get_other_books(VAR_66, VAR_63) return render_title_template('author.html', VAR_63=VAR_63, VAR_65=pagination, id=VAR_12, VAR_150=_(u"Author: %(VAR_13)s", VAR_13=VAR_36), VAR_105=VAR_66, VAR_67=other_books, VAR_9="author", VAR_10=order[1]) def FUNC_21(VAR_9, VAR_5, VAR_10): VAR_38 = calibre_db.session.query(db.Publishers).filter(db.Publishers.id == VAR_5).first() if VAR_38: VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.publishers.any(db.Publishers.id == VAR_5), [db.Series.name, VAR_10[0][0], db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_5, VAR_150=_(u"Publisher: %(VAR_13)s", VAR_13=VAR_38.name), VAR_9="publisher", VAR_10=order[1]) else: abort(404) def FUNC_22(VAR_9, VAR_5, VAR_10): VAR_13 = calibre_db.session.query(db.Series).filter(db.Series.id == VAR_5).first() if VAR_13: VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.series.any(db.Series.id == VAR_5), [VAR_10[0][0]]) return render_title_template('index.html', VAR_68=random, VAR_65=pagination, VAR_63=VAR_63, id=VAR_5, VAR_150=_(u"Series: %(serie)s", serie=VAR_13.name), VAR_9="series", VAR_10=order[1]) else: abort(404) def FUNC_23(VAR_9, VAR_5, VAR_10): VAR_13 = calibre_db.session.query(db.Ratings).filter(db.Ratings.id == VAR_5).first() VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.ratings.any(db.Ratings.id == VAR_5), [VAR_10[0][0]]) if VAR_13 and VAR_13.rating <= 10: return render_title_template('index.html', VAR_68=random, VAR_65=pagination, VAR_63=VAR_63, id=VAR_5, VAR_150=_(u"Rating: %(rating)s stars", rating=int(VAR_13.rating / 2)), VAR_9="ratings", VAR_10=order[1]) else: abort(404) def FUNC_24(VAR_9, VAR_5, VAR_10): VAR_13 = calibre_db.session.query(db.Data).filter(db.Data.format == VAR_5.upper()).first() if VAR_13: VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.data.any(db.Data.format == VAR_5.upper()), [VAR_10[0][0]]) return render_title_template('index.html', VAR_68=random, VAR_65=pagination, VAR_63=VAR_63, id=VAR_5, VAR_150=_(u"File format: %(format)s", format=VAR_13.format), VAR_9="formats", VAR_10=order[1]) else: abort(404) def FUNC_25(VAR_9, VAR_5, VAR_10): VAR_13 = calibre_db.session.query(db.Tags).filter(db.Tags.id == VAR_5).first() if VAR_13: VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.tags.any(db.Tags.id == VAR_5), [VAR_10[0][0], db.Series.name, db.Books.series_index], db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_5, VAR_150=_(u"Category: %(VAR_13)s", VAR_13=VAR_13.name), VAR_9="category", VAR_10=order[1]) else: abort(404) def FUNC_26(VAR_9, VAR_13, VAR_10): try: VAR_106 = isoLanguages.get_language_name(get_locale(), VAR_13) except KeyError: abort(404) VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, db.Books.languages.any(db.Languages.lang_code == VAR_13), [VAR_10[0][0]]) return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, id=VAR_13, VAR_150=_(u"Language: %(VAR_13)s", VAR_13=VAR_106), VAR_9="language", VAR_10=order[1]) def FUNC_27(VAR_9, VAR_14, VAR_15=False, VAR_10=None): VAR_7 = VAR_10[0] if VAR_10 else [] if not config.config_read_column: if VAR_14: VAR_126 = and_(ub.ReadBook.user_id == int(VAR_87.id), ub.ReadBook.read_status == ub.ReadBook.STATUS_FINISHED) else: VAR_126 = coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, VAR_126, VAR_7, db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, ub.ReadBook, db.Books.id == ub.ReadBook.book_id) else: try: if VAR_14: VAR_126 = db.cc_classes[config.config_read_column].value == True else: VAR_126 = coalesce(db.cc_classes[config.config_read_column].value, False) != True VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage(VAR_9, 0, db.Books, VAR_126, VAR_7, db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series, db.cc_classes[config.config_read_column]) except (KeyError, AttributeError): VAR_3.error("Custom Column No.%d is not existing in calibre database", config.config_read_column) if not VAR_15: flash(_("Custom Column No.%(column)d is not existing in calibre database", column=config.config_read_column), category="error") return redirect(url_for("web.index")) if VAR_15: return VAR_63, VAR_65 else: if VAR_14: VAR_13 = _(u'Read Books') + ' (' + str(VAR_65.total_count) + ')' VAR_72 = "read" else: VAR_13 = _(u'Unread Books') + ' (' + str(VAR_65.total_count) + ')' VAR_72 = "unread" return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, VAR_150=VAR_13, VAR_9=VAR_72, VAR_10=order[1]) def FUNC_28(VAR_9, VAR_7): VAR_10 = VAR_7[0] or [] VAR_69 = ( ub.session.query(ub.ArchivedBook) .filter(ub.ArchivedBook.user_id == int(VAR_87.id)) .filter(ub.ArchivedBook.is_archived == True) .all() ) VAR_70 = [VAR_142.book_id for VAR_142 in VAR_69] VAR_71 = db.Books.id.in_(VAR_70) VAR_63, VAR_68, VAR_65 = calibre_db.fill_indexpage_with_archived_books(VAR_9, 0, db.Books, VAR_71, VAR_10, allow_show_archived=True) VAR_13 = _(u'Archived Books') + ' (' + str(len(VAR_70)) + ')' VAR_72 = "archived" return render_title_template('index.html', VAR_68=random, VAR_63=VAR_63, VAR_65=pagination, VAR_150=VAR_13, VAR_9=VAR_72, VAR_10=VAR_7[1]) def FUNC_29(VAR_16): VAR_41 = calibre_db.session.query(db.Tags)\ .join(db.books_tags_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag'))\ .order_by(db.Tags.name).all() VAR_73 = calibre_db.session.query(db.Series)\ .join(db.books_series_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series'))\ .order_by(db.Series.name)\ .filter(calibre_db.common_filters()).all() VAR_74 = ub.session.query(ub.Shelf)\ .filter(or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == int(VAR_87.id)))\ .order_by(ub.Shelf.name).all() VAR_75 = calibre_db.session.query(db.Data)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(db.Data.format)\ .order_by(db.Data.format).all() if VAR_87.filter_language() == u"all": VAR_48 = calibre_db.speaking_language() else: VAR_48 = None return render_title_template('search_form.html', VAR_41=tags, VAR_48=languages, VAR_75=extensions, VAR_73=series,VAR_74=shelves, VAR_150=_(u"Advanced Search"), VAR_16=cc, VAR_9="advsearch") def FUNC_30(VAR_17, VAR_18=None, VAR_10=None, VAR_19=None): VAR_76 = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series VAR_63, VAR_77, VAR_65 = calibre_db.get_search_results(VAR_17, VAR_18, VAR_10, VAR_19, *VAR_76) return render_title_template('search.html', VAR_35=VAR_17, VAR_65=pagination, VAR_56=VAR_17, adv_searchterm=VAR_17, VAR_63=entries, VAR_77=result_count, VAR_150=_(u"Search"), VAR_9="search", VAR_10=order[1]) @VAR_2.route("/", defaults={'page': 1}) @VAR_2.route('/VAR_9/<int:VAR_9>') @login_required_if_no_ano def FUNC_31(VAR_9): VAR_20 = (request.args.get('sort') or 'stored').lower() return FUNC_15("newest", VAR_20, 1, VAR_9) @VAR_2.route('/<VAR_8>/<VAR_20>', defaults={'page': 1, 'book_id': 1}) @VAR_2.route('/<VAR_8>/<VAR_20>/', defaults={'page': 1, 'book_id': 1}) @VAR_2.route('/<VAR_8>/<VAR_20>/<VAR_5>', defaults={'page': 1}) @VAR_2.route('/<VAR_8>/<VAR_20>/<VAR_5>/<int:VAR_9>') @login_required_if_no_ano def FUNC_32(VAR_8, VAR_20, VAR_5, VAR_9): return FUNC_15(VAR_8, VAR_20, VAR_5, VAR_9) @VAR_2.route("/table") @login_required def FUNC_33(): VAR_78 = VAR_87.view_settings.get('table', {}) VAR_16 = get_cc_columns(filter_config_custom_read=True) return render_title_template('book_table.html', VAR_150=_(u"Books List"), VAR_16=cc, VAR_9="book_table", visiblility=VAR_78) @VAR_2.route("/ajax/listbooks") @login_required def FUNC_34(): VAR_79 = int(request.args.get("offset") or 0) VAR_19 = int(request.args.get("limit") or config.config_books_per_page) VAR_80 = request.args.get("search") VAR_7 = request.args.get("sort", "id") VAR_10 = request.args.get("order", "").lower() VAR_81 = None VAR_76 = tuple() if VAR_7 == "state": VAR_81 = json.loads(request.args.get("state", "[]")) elif VAR_7 == "tags": VAR_10 = [db.Tags.name.asc()] if VAR_10 == "asc" else [db.Tags.name.desc()] VAR_76 = db.books_tags_link,db.Books.id == db.books_tags_link.c.book, db.Tags elif VAR_7 == "series": VAR_10 = [db.Series.name.asc()] if VAR_10 == "asc" else [db.Series.name.desc()] VAR_76 = db.books_series_link,db.Books.id == db.books_series_link.c.book, db.Series elif VAR_7 == "publishers": VAR_10 = [db.Publishers.name.asc()] if VAR_10 == "asc" else [db.Publishers.name.desc()] VAR_76 = db.books_publishers_link,db.Books.id == db.books_publishers_link.c.book, db.Publishers elif VAR_7 == "authors": VAR_10 = [db.Authors.name.asc(), db.Series.name, db.Books.series_index] if VAR_10 == "asc" \ else [db.Authors.name.desc(), db.Series.name.desc(), db.Books.series_index.desc()] VAR_76 = db.books_authors_link, db.Books.id == db.books_authors_link.c.book, db.Authors, \ db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series elif VAR_7 == "languages": VAR_10 = [db.Languages.lang_code.asc()] if VAR_10 == "asc" else [db.Languages.lang_code.desc()] VAR_76 = db.books_languages_link, db.Books.id == db.books_languages_link.c.book, db.Languages elif VAR_10 and VAR_7 in ["sort", "title", "authors_sort", "series_index"]: VAR_10 = [text(VAR_7 + " " + VAR_10)] elif not VAR_81: VAR_10 = [db.Books.timestamp.desc()] VAR_82 = VAR_83 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters(False)).count() if VAR_81 is not None: if VAR_80: VAR_127 = calibre_db.search_query(VAR_80).all() VAR_83 = len(VAR_127) else: VAR_127 = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).all() VAR_63 = calibre_db.get_checkbox_sorted(VAR_127, VAR_81, VAR_79, VAR_19, VAR_10) elif VAR_80: VAR_63, VAR_83, VAR_64 = calibre_db.get_search_results(VAR_80, VAR_79, [VAR_10,''], VAR_19, *VAR_76) else: VAR_63, VAR_64, VAR_64 = calibre_db.fill_indexpage((int(VAR_79) / (int(VAR_19)) + 1), VAR_19, db.Books, True, VAR_10, *VAR_76) for entry in VAR_63: for FUNC_31 in range(0, len(entry.languages)): entry.languages[FUNC_31].language_name = isoLanguages.get_language_name(get_locale(), entry.languages[ FUNC_31].lang_code) VAR_84 = {'totalNotFiltered': VAR_82, 'total': VAR_83, "rows": VAR_63} VAR_85 = json.dumps(VAR_84, cls=db.AlchemyEncoder) VAR_86 = make_response(VAR_85) VAR_86.headers["Content-Type"] = "application/json; charset=utf-8" return VAR_86 @VAR_2.route("/ajax/table_settings", methods=['POST']) @login_required def FUNC_35(): VAR_87.view_settings['table'] = json.loads(request.data) try: try: flag_modified(VAR_87, "view_settings") except AttributeError: pass ub.session.commit() except (InvalidRequestError, OperationalError): VAR_3.error("Invalid request received: %r ", request, ) return "Invalid request", 400 return "" @VAR_2.route("/author") @login_required_if_no_ano def FUNC_36(): if VAR_87.check_visibility(constants.SIDEBAR_AUTHOR): if VAR_87.get_view_property('author', 'dir') == 'desc': VAR_10 = db.Authors.sort.desc() VAR_109 = 0 else: VAR_10 = db.Authors.sort.asc() VAR_109 = 1 VAR_63 = calibre_db.session.query(db.Authors, func.count('books_authors_link.book').label('count')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_authors_link.author')).order_by(VAR_10).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('char')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all() VAR_108 = copy.deepcopy(VAR_63) for entry in VAR_108: entry.Authors.name = entry.Authors.name.replace('|', ',') return render_title_template('list.html', VAR_63=VAR_108, folder='web.books_list', VAR_107=charlist, VAR_150=u"Authors", VAR_9="authorlist", VAR_8='author', VAR_10=VAR_109) else: abort(404) @VAR_2.route("/downloadlist") @login_required_if_no_ano def FUNC_37(): if VAR_87.get_view_property('download', 'dir') == 'desc': VAR_10 = ub.User.name.desc() VAR_109 = 0 else: VAR_10 = ub.User.name.asc() VAR_109 = 1 if VAR_87.check_visibility(constants.SIDEBAR_DOWNLOAD) and VAR_87.role_admin(): VAR_63 = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count'))\ .join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(VAR_10).all() VAR_107 = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \ .filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \ .group_by(func.upper(func.substr(ub.User.name, 1, 1))).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Downloads"), VAR_9="downloadlist", VAR_8="download", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/publisher") @login_required_if_no_ano def FUNC_38(): if VAR_87.get_view_property('publisher', 'dir') == 'desc': VAR_10 = db.Publishers.name.desc() VAR_109 = 0 else: VAR_10 = db.Publishers.name.asc() VAR_109 = 1 if VAR_87.check_visibility(constants.SIDEBAR_PUBLISHER): VAR_63 = calibre_db.session.query(db.Publishers, func.count('books_publishers_link.book').label('count')) \ .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_publishers_link.publisher')).order_by(VAR_10).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Publishers.name, 1, 1)).label('char')) \ .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Publishers.name, 1, 1))).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Publishers"), VAR_9="publisherlist", VAR_8="publisher", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/series") @login_required_if_no_ano def FUNC_39(): if VAR_87.check_visibility(constants.SIDEBAR_SERIES): if VAR_87.get_view_property('series', 'dir') == 'desc': VAR_10 = db.Series.sort.desc() VAR_109 = 0 else: VAR_10 = db.Series.sort.asc() VAR_109 = 1 if VAR_87.get_view_property('series', 'series_view') == 'list': VAR_63 = calibre_db.session.query(db.Series, func.count('books_series_link.book').label('count')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series')).order_by(VAR_10).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Series"), VAR_9="serieslist", VAR_8="series", VAR_10=VAR_109) else: VAR_63 = calibre_db.session.query(db.Books, func.count('books_series_link').label('count'), func.max(db.Books.series_index), db.Books.id) \ .join(db.books_series_link).join(db.Series).filter(calibre_db.common_filters())\ .group_by(text('books_series_link.series')).order_by(VAR_10).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all() return render_title_template('grid.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Series"), VAR_9="serieslist", VAR_8="series", bodyClass="grid-view", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/ratings") @login_required_if_no_ano def FUNC_40(): if VAR_87.check_visibility(constants.SIDEBAR_RATING): if VAR_87.get_view_property('ratings', 'dir') == 'desc': VAR_10 = db.Ratings.rating.desc() VAR_109 = 0 else: VAR_10 = db.Ratings.rating.asc() VAR_109 = 1 VAR_63 = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_ratings_link.rating')).order_by(VAR_10).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=list(), VAR_150=_(u"Ratings list"), VAR_9="ratingslist", VAR_8="ratings", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/formats") @login_required_if_no_ano def FUNC_41(): if VAR_87.check_visibility(constants.SIDEBAR_FORMAT): if VAR_87.get_view_property('ratings', 'dir') == 'desc': VAR_10 = db.Data.format.desc() VAR_109 = 0 else: VAR_10 = db.Data.format.asc() VAR_109 = 1 VAR_63 = calibre_db.session.query(db.Data, func.count('data.book').label('count'), db.Data.format.label('format')) \ .join(db.Books).filter(calibre_db.common_filters()) \ .group_by(db.Data.format).order_by(VAR_10).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=list(), VAR_150=_(u"File formats list"), VAR_9="formatslist", VAR_8="formats", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/language") @login_required_if_no_ano def FUNC_42(): if VAR_87.check_visibility(constants.SIDEBAR_LANGUAGE) and VAR_87.filter_language() == u"all": VAR_109 = 0 if VAR_87.get_view_property('language', 'dir') == 'desc' else 1 VAR_107 = list() VAR_48 = calibre_db.speaking_language(reverse_order=not VAR_109, with_count=True) for lang in VAR_48: VAR_128 = lang[0].name[0].upper() if VAR_128 not in VAR_107: charlist.append(VAR_128) return render_title_template('languages.html', VAR_48=languages, VAR_107=charlist, VAR_150=_(u"Languages"), VAR_9="langlist", VAR_8="language", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/category") @login_required_if_no_ano def FUNC_43(): if VAR_87.check_visibility(constants.SIDEBAR_CATEGORY): if VAR_87.get_view_property('category', 'dir') == 'desc': VAR_10 = db.Tags.name.desc() VAR_109 = 0 else: VAR_10 = db.Tags.name.asc() VAR_109 = 1 VAR_63 = calibre_db.session.query(db.Tags, func.count('books_tags_link.book').label('count')) \ .join(db.books_tags_link).join(db.Books).order_by(VAR_10).filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag')).all() VAR_107 = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('char')) \ .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all() return render_title_template('list.html', VAR_63=VAR_63, folder='web.books_list', VAR_107=charlist, VAR_150=_(u"Categories"), VAR_9="catlist", VAR_8="category", VAR_10=VAR_109) else: abort(404) @VAR_2.route("/tasks") @login_required def FUNC_44(): VAR_51 = WorkerThread.getInstance().tasks VAR_88 = render_task_status(VAR_51) return render_title_template('tasks.html', VAR_63=VAR_88, VAR_150=_(u"Tasks"), VAR_9="tasks") @app.route("/reconnect", methods=['GET']) def FUNC_45(): calibre_db.reconnect_db(config, ub.app_DB_path) return json.dumps({}) @VAR_2.route("/search", methods=["GET"]) @login_required_if_no_ano def VAR_80(): VAR_17 = request.args.get("query") if VAR_17: return redirect(url_for('web.books_list', VAR_8="search", VAR_20='stored', VAR_56=VAR_17)) else: return render_title_template('search.html', VAR_35="", VAR_77=0, VAR_150=_(u"Search"), VAR_9="search") @VAR_2.route("/advsearch", methods=['POST']) @login_required_if_no_ano def FUNC_47(): VAR_89 = dict(request.form) VAR_90 = ['include_tag', 'exclude_tag', 'include_serie', 'exclude_serie', 'include_shelf', 'exclude_shelf', 'include_language', 'exclude_language', 'include_extension', 'exclude_extension'] for VAR_110 in VAR_90: VAR_89[VAR_110] = list(request.form.getlist(VAR_110)) VAR_91['query'] = json.dumps(VAR_89) return redirect(url_for('web.books_list', VAR_8="advsearch", VAR_20='stored', VAR_56="")) def FUNC_48(VAR_16, VAR_17, VAR_21): for c in VAR_16: if c.datatype == "datetime": VAR_129 = VAR_17.get('custom_column_' + str(c.id) + '_start') VAR_130 = VAR_17.get('custom_column_' + str(c.id) + '_end') if VAR_129: VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.datetime(db.cc_classes[c.id].value) >= func.datetime(VAR_129))) if VAR_130: VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.datetime(db.cc_classes[c.id].value) <= func.datetime(VAR_130))) else: VAR_131 = VAR_17.get('custom_column_' + str(c.id)) if VAR_131 != '' and VAR_131 is not None: if c.datatype == 'bool': VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == (VAR_131 == "True"))) elif c.datatype == 'int' or c.datatype == 'float': VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == VAR_131)) elif c.datatype == 'rating': VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( db.cc_classes[c.id].value == int(float(VAR_131) * 2))) else: VAR_21 = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any( func.lower(db.cc_classes[c.id].value).ilike("%" + VAR_131 + "%"))) return VAR_21 def FUNC_49(VAR_21, VAR_22, VAR_23): if VAR_87.filter_language() != "all": VAR_21 = q.filter(db.Books.languages.any(db.Languages.lang_code == VAR_87.filter_language())) else: for language in VAR_22: VAR_21 = q.filter(db.Books.languages.any(db.Languages.id == language)) for language in VAR_23: VAR_21 = q.filter(not_(db.Books.series.any(db.Languages.id == language))) return VAR_21 def FUNC_50(VAR_21, VAR_24, VAR_25): if VAR_24: VAR_24 = int(VAR_24) * 2 VAR_21 = q.filter(db.Books.ratings.any(db.Ratings.rating <= VAR_24)) if VAR_25: rating_low = int(VAR_25) * 2 VAR_21 = q.filter(db.Books.ratings.any(db.Ratings.rating >= VAR_25)) return VAR_21 def FUNC_51(VAR_21, VAR_26): if VAR_26: if config.config_read_column: try: if VAR_26 == "True": VAR_21 = q.join(db.cc_classes[config.config_read_column], isouter=True) \ .filter(db.cc_classes[config.config_read_column].value == True) else: VAR_21 = q.join(db.cc_classes[config.config_read_column], isouter=True) \ .filter(coalesce(db.cc_classes[config.config_read_column].value, False) != True) except (KeyError, AttributeError): VAR_3.error(u"Custom Column No.%d is not existing in calibre database", config.config_read_column) flash(_("Custom Column No.%(column)d is not existing in calibre database", column=config.config_read_column), category="error") return VAR_21 else: if VAR_26 == "True": VAR_21 = q.join(ub.ReadBook, db.Books.id == ub.ReadBook.book_id, isouter=True) \ .filter(ub.ReadBook.user_id == int(VAR_87.id), ub.ReadBook.read_status == ub.ReadBook.STATUS_FINISHED) else: VAR_21 = q.join(ub.ReadBook, db.Books.id == ub.ReadBook.book_id, isouter=True) \ .filter(ub.ReadBook.user_id == int(VAR_87.id), coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED) return VAR_21 def FUNC_52(VAR_21, VAR_27, VAR_28): for extension in VAR_27: VAR_21 = q.filter(db.Books.data.any(db.Data.format == extension)) for extension in VAR_28: VAR_21 = q.filter(not_(db.Books.data.any(db.Data.format == extension))) return VAR_21 def FUNC_53(VAR_21, VAR_29, VAR_30): for tag in VAR_29: VAR_21 = q.filter(db.Books.tags.any(db.Tags.id == tag)) for tag in VAR_30: VAR_21 = q.filter(not_(db.Books.tags.any(db.Tags.id == tag))) return VAR_21 def FUNC_54(VAR_21, VAR_31, VAR_32): for serie in VAR_31: VAR_21 = q.filter(db.Books.series.any(db.Series.id == serie)) for serie in VAR_32: VAR_21 = q.filter(not_(db.Books.series.any(db.Series.id == serie))) return VAR_21 def FUNC_55(VAR_21, VAR_33, VAR_34): VAR_21 = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\ .filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(VAR_34))) if len(VAR_33) > 0: VAR_21 = q.filter(ub.BookShelf.shelf.in_(VAR_33)) return VAR_21 def FUNC_56(VAR_35, VAR_36, VAR_37, VAR_38, VAR_39, VAR_40, VAR_41, VAR_24, VAR_25, VAR_26, ): VAR_35.extend((VAR_36.replace('|', ','), VAR_37, VAR_38)) if VAR_39: try: VAR_35.extend([_(u"Published after ") + format_date(datetime.strptime(VAR_39, "%Y-%m-%d"), format='medium', locale=get_locale())]) except ValueError: VAR_39 = u"" if VAR_40: try: VAR_35.extend([_(u"Published before ") + format_date(datetime.strptime(VAR_40, "%Y-%m-%d"), format='medium', locale=get_locale())]) except ValueError: VAR_40 = u"" VAR_92 = {'tag': db.Tags, 'serie':db.Series, 'shelf':ub.Shelf} for key, db_element in VAR_92.items(): VAR_111 = calibre_db.session.query(db_element).filter(db_element.id.in_(VAR_41['include_' + key])).all() VAR_35.extend(tag.name for tag in VAR_111) tag_names = calibre_db.session.query(db_element).filter(db_element.id.in_(VAR_41['exclude_' + key])).all() VAR_35.extend(tag.name for tag in VAR_111) VAR_57 = calibre_db.session.query(db.Languages). \ filter(db.Languages.id.in_(VAR_41['include_language'])).all() if VAR_57: language_names = calibre_db.speaking_language(VAR_57) VAR_35.extend(language.name for language in VAR_57) VAR_57 = calibre_db.session.query(db.Languages). \ filter(db.Languages.id.in_(VAR_41['exclude_language'])).all() if VAR_57: language_names = calibre_db.speaking_language(VAR_57) VAR_35.extend(language.name for language in VAR_57) if VAR_24: VAR_35.extend([_(u"Rating <= %(rating)s", rating=VAR_24)]) if VAR_25: VAR_35.extend([_(u"Rating >= %(rating)s", rating=VAR_25)]) if VAR_26: VAR_35.extend([_(u"Read Status = %(status)s", status=VAR_26)]) VAR_35.extend(ext for ext in VAR_41['include_extension']) VAR_35.extend(ext for ext in VAR_41['exclude_extension']) VAR_35 = " + ".join(filter(None, VAR_35)) return VAR_35, VAR_39, VAR_40 def FUNC_57(VAR_17, VAR_18=None, VAR_10=None, VAR_19=None): VAR_7 = VAR_10[0] if VAR_10 else [db.Books.sort] VAR_65 = None VAR_16 = get_cc_columns(filter_config_custom_read=True) calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase) VAR_21 = calibre_db.session.query(db.Books).outerjoin(db.books_series_link, db.Books.id == db.books_series_link.c.book)\ .outerjoin(db.Series)\ .filter(calibre_db.common_filters(True)) VAR_41 = dict() VAR_92 = ['tag', 'serie', 'shelf', 'language', 'extension'] for VAR_112 in VAR_92: VAR_41['include_' + VAR_112] = VAR_17.get('include_' + VAR_112) VAR_41['exclude_' + VAR_112] = VAR_17.get('exclude_' + VAR_112) VAR_36 = VAR_17.get("author_name") VAR_37 = VAR_17.get("book_title") VAR_38 = VAR_17.get("publisher") VAR_39 = VAR_17.get("publishstart") VAR_40 = VAR_17.get("publishend") VAR_25 = VAR_17.get("ratinghigh") VAR_24 = VAR_17.get("ratinglow") VAR_93 = VAR_17.get("comment") VAR_26 = VAR_17.get("read_status") if VAR_36: VAR_36 = VAR_36.strip().lower().replace(',', '|') if VAR_37: VAR_37 = VAR_37.strip().lower() if VAR_38: VAR_38 = VAR_38.strip().lower() VAR_35 = [] VAR_94 = False for c in VAR_16: if c.datatype == "datetime": VAR_132 = VAR_17.get('custom_column_' + str(c.id) + '_start') VAR_133 = VAR_17.get('custom_column_' + str(c.id) + '_end') if VAR_132: VAR_35.extend([u"{} >= {}".format(c.name, format_date(datetime.strptime(VAR_132, "%Y-%m-%d").date(), format='medium', locale=get_locale()) )]) VAR_94 = True if VAR_133: VAR_35.extend([u"{} <= {}".format(c.name, format_date(datetime.strptime(VAR_133, "%Y-%m-%d").date(), format='medium', locale=get_locale()) )]) VAR_94 = True elif VAR_17.get('custom_column_' + str(c.id)): VAR_35.extend([(u"{}: {}".format(c.name, VAR_17.get('custom_column_' + str(c.id))))]) VAR_94 = True if any(VAR_41.values()) or VAR_36 or VAR_37 or VAR_38 or VAR_39 or VAR_40 or VAR_25 \ or VAR_24 or VAR_93 or VAR_94 or VAR_26: VAR_35, VAR_39, VAR_40 = FUNC_56(VAR_35, VAR_36, VAR_37, VAR_38, VAR_39, VAR_40, VAR_41, VAR_24, VAR_25, VAR_26) VAR_21 = q.filter() if VAR_36: VAR_21 = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + VAR_36 + "%"))) if VAR_37: VAR_21 = q.filter(func.lower(db.Books.title).ilike("%" + VAR_37 + "%")) if VAR_39: VAR_21 = q.filter(func.datetime(db.Books.pubdate) > func.datetime(VAR_39)) if VAR_40: VAR_21 = q.filter(func.datetime(db.Books.pubdate) < func.datetime(VAR_40)) VAR_21 = FUNC_51(VAR_21, VAR_26) if VAR_38: VAR_21 = q.filter(db.Books.publishers.any(func.lower(db.Publishers.name).ilike("%" + VAR_38 + "%"))) VAR_21 = FUNC_53(VAR_21, VAR_41['include_tag'], VAR_41['exclude_tag']) VAR_21 = FUNC_54(VAR_21, VAR_41['include_serie'], VAR_41['exclude_serie']) VAR_21 = FUNC_55(VAR_21, VAR_41['include_shelf'], VAR_41['exclude_shelf']) VAR_21 = FUNC_52(VAR_21, VAR_41['include_extension'], VAR_41['exclude_extension']) VAR_21 = FUNC_49(VAR_21, VAR_41['include_language'], VAR_41['exclude_language']) VAR_21 = FUNC_50(VAR_21, VAR_24, VAR_25) if VAR_93: VAR_21 = q.filter(db.Books.comments.any(func.lower(db.Comments.text).ilike("%" + VAR_93 + "%"))) try: VAR_21 = FUNC_48(VAR_16, VAR_17, VAR_21) except AttributeError as ex: VAR_3.debug_or_exception(ex) flash(_("Error on VAR_80 for custom columns, please restart Calibre-Web"), category="error") VAR_21 = q.order_by(*VAR_7).all() VAR_91['query'] = json.dumps(VAR_17) ub.store_ids(VAR_21) VAR_77 = len(VAR_21) if VAR_18 is not None and VAR_19 is not None: VAR_18 = int(VAR_18) VAR_113 = VAR_18 + int(VAR_19) VAR_65 = Pagination((VAR_18 / (int(VAR_19)) + 1), VAR_19, VAR_77) else: VAR_18 = 0 VAR_113 = VAR_77 return render_title_template('search.html', adv_searchterm=VAR_35, VAR_65=pagination, VAR_63=VAR_21[VAR_18:VAR_113], VAR_77=result_count, VAR_150=_(u"Advanced Search"), VAR_9="advsearch", VAR_10=order[1]) @VAR_2.route("/advsearch", methods=['GET']) @login_required_if_no_ano def FUNC_58(): VAR_16 = get_cc_columns(filter_config_custom_read=True) return FUNC_29(VAR_16) @VAR_2.route("/cover/<int:VAR_5>") @login_required_if_no_ano def FUNC_59(VAR_5): return get_book_cover(VAR_5) @VAR_2.route("/robots.txt") def FUNC_60(): return send_from_directory(constants.STATIC_DIR, "robots.txt") @VAR_2.route("/show/<int:VAR_5>/<VAR_6>", defaults={'anyname': 'None'}) @VAR_2.route("/show/<int:VAR_5>/<VAR_6>/<VAR_42>") @login_required_if_no_ano @FUNC_2 def FUNC_61(VAR_5, VAR_6, VAR_42): VAR_6 = VAR_6.split(".")[0] VAR_95 = calibre_db.get_book(VAR_5) VAR_8 = calibre_db.get_book_format(VAR_5, VAR_6.upper()) if not VAR_8: return "File not in Database" VAR_3.info('Serving VAR_95: %s', VAR_8.name) if config.config_use_google_drive: try: VAR_134 = Headers() VAR_134["Content-Type"] = mimetypes.types_map.get('.' + VAR_6, "application/octet-stream") VAR_135 = getFileFromEbooksFolder(VAR_95.path, VAR_8.name + "." + VAR_6) return do_gdrive_download(VAR_135, VAR_134, (VAR_6.upper() == 'TXT')) except AttributeError as ex: VAR_3.debug_or_exception(ex) return "File Not Found" else: if VAR_6.upper() == 'TXT': try: VAR_146 = open(os.path.join(config.config_calibre_dir, VAR_95.path, VAR_8.name + "." + VAR_6), "rb").read() VAR_136 = chardet.detect(VAR_146) return make_response( VAR_146.decode(VAR_136['encoding'], 'surrogatepass').encode('utf-8', 'surrogatepass')) except FileNotFoundError: VAR_3.error("File Not Found") return "File Not Found" return send_from_directory(os.path.join(config.config_calibre_dir, VAR_95.path), VAR_8.name + "." + VAR_6) @VAR_2.route("/download/<int:VAR_5>/<VAR_6>", defaults={'anyname': 'None'}) @VAR_2.route("/download/<int:VAR_5>/<VAR_6>/<VAR_42>") @login_required_if_no_ano @FUNC_1 def FUNC_62(VAR_5, VAR_6, VAR_42): VAR_96 = "kobo" if "Kobo" in request.headers.get('User-Agent') else "" return get_download_link(VAR_5, VAR_6, VAR_96) @VAR_2.route('/send/<int:VAR_5>/<VAR_6>/<int:VAR_43>', methods=["POST"]) @login_required @FUNC_1 def FUNC_63(VAR_5, VAR_6, VAR_43): if not config.get_mail_server_configured(): flash(_(u"Please configure the SMTP mail settings first..."), category="error") elif VAR_87.kindle_mail: VAR_136 = send_mail(VAR_5, VAR_6, VAR_43, VAR_87.kindle_mail, config.config_calibre_dir, VAR_87.name) if VAR_136 is None: flash(_(u"Book successfully queued for sending to %(kindlemail)s", kindlemail=VAR_87.kindle_mail), category="success") ub.update_download(VAR_5, int(VAR_87.id)) else: flash(_(u"Oops! There was an VAR_140 sending this VAR_95: %(res)s", res=VAR_136), category="error") else: flash(_(u"Please update your FUNC_68 with a valid Send to Kindle E-mail Address."), category="error") if "HTTP_REFERER" in request.environ: return redirect(request.environ["HTTP_REFERER"]) else: return redirect(url_for('web.index')) @VAR_2.route('/register', methods=['GET', 'POST']) def FUNC_64(): if not config.config_public_reg: abort(404) if VAR_87 is not None and VAR_87.is_authenticated: return redirect(url_for('web.index')) if not config.get_mail_server_configured(): flash(_(u"E-Mail server is not configured, please contact your administrator!"), category="error") return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") if request.method == "POST": VAR_55 = request.form.to_dict() VAR_114 = VAR_55["email"].strip() if config.config_register_email else VAR_55.get('name') if not VAR_114 or not VAR_55.get("email"): flash(_(u"Please fill out all fields!"), category="error") return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") try: VAR_114 = check_username(VAR_114) VAR_137 = check_email(VAR_55["email"]) except Exception as ex: flash(str(ex), category="error") return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") VAR_115 = ub.User() if check_valid_domain(VAR_137): VAR_115.name = VAR_114 VAR_115.email = VAR_137 VAR_138 = generate_random_password() VAR_115.password = generate_password_hash(VAR_138) VAR_115.role = config.config_default_role VAR_115.sidebar_view = config.config_default_show try: ub.session.add(VAR_115) ub.session.commit() if VAR_0['oauth']: register_user_with_oauth(VAR_115) send_registration_mail(VAR_55["email"].strip(), VAR_114, VAR_138) except Exception: ub.session.rollback() flash(_(u"An unknown VAR_140 occurred. Please try again later."), category="error") return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") else: flash(_(u"Your e-mail is not allowed to register"), category="error") VAR_3.warning('Registering failed for VAR_104 "%s" e-mail address: %s', VAR_114, VAR_55["email"]) return render_title_template('register.html', VAR_150=_("Register"), VAR_9="register") flash(_(u"Confirmation e-mail was send to your e-mail account."), category="success") return redirect(url_for('web.login')) if VAR_0['oauth']: register_user_with_oauth() return render_title_template('register.html', config=config, VAR_150=_("Register"), VAR_9="register") @VAR_2.route('/login', methods=['GET', 'POST']) def FUNC_65(): if VAR_87 is not None and VAR_87.is_authenticated: return redirect(url_for('web.index')) if config.config_login_type == constants.LOGIN_LDAP and not services.ldap: VAR_3.error(u"Cannot activate LDAP authentication") flash(_(u"Cannot activate LDAP authentication"), category="error") if request.method == "POST": VAR_116 = request.form.to_dict() VAR_104 = ub.session.query(ub.User).filter(func.lower(ub.User.name) == VAR_116['username'].strip().lower()) \ .first() if config.config_login_type == constants.LOGIN_LDAP and services.ldap and VAR_104 and VAR_116['password'] != "": VAR_139, VAR_140 = services.ldap.bind_user(VAR_116['username'], VAR_116['password']) if VAR_139: login_user(VAR_104, remember=bool(VAR_116.get('remember_me'))) ub.store_user_session() VAR_3.debug(u"You are now logged in as: '%s'", VAR_104.name) flash(_(u"you are now logged in as: '%(VAR_114)s'", VAR_114=VAR_104.name), category="success") return redirect_back(url_for("web.index")) elif VAR_139 is None and VAR_104 and check_password_hash(str(VAR_104.password), VAR_116['password']) \ and VAR_104.name != "Guest": login_user(VAR_104, remember=bool(VAR_116.get('remember_me'))) ub.store_user_session() VAR_3.info("Local Fallback Login as: '%s'", VAR_104.name) flash(_(u"Fallback Login as: '%(VAR_114)s', LDAP Server not reachable, or VAR_104 not known", VAR_114=VAR_104.name), category="warning") return redirect_back(url_for("web.index")) elif VAR_139 is None: VAR_3.info(VAR_140) flash(_(u"Could not FUNC_65: %(message)s", message=VAR_140), category="error") else: VAR_141 = request.headers.get('X-Forwarded-For', request.remote_addr) VAR_3.warning('LDAP Login failed for VAR_104 "%s" IP-address: %s', VAR_116['username'], VAR_141) flash(_(u"Wrong Username or Password"), category="error") else: VAR_141 = request.headers.get('X-Forwarded-For', request.remote_addr) if 'forgot' in VAR_116 and VAR_116['forgot'] == 'forgot': if VAR_104 is not None and VAR_104.name != "Guest": VAR_148, VAR_64 = reset_password(VAR_104.id) if VAR_148 == 1: flash(_(u"New Password was send to your VAR_137 address"), category="info") VAR_3.info('Password reset for VAR_104 "%s" IP-address: %s', VAR_116['username'], VAR_141) else: VAR_3.error(u"An unknown VAR_140 occurred. Please try again later") flash(_(u"An unknown VAR_140 occurred. Please try again later."), category="error") else: flash(_(u"Please enter valid username to reset password"), category="error") VAR_3.warning('Username missing for VAR_138 reset IP-address: %s', VAR_141) else: if VAR_104 and check_password_hash(str(VAR_104.password), VAR_116['password']) and VAR_104.name != "Guest": login_user(VAR_104, remember=bool(VAR_116.get('remember_me'))) ub.store_user_session() VAR_3.debug(u"You are now logged in as: '%s'", VAR_104.name) flash(_(u"You are now logged in as: '%(VAR_114)s'", VAR_114=VAR_104.name), category="success") config.config_is_initial = False return redirect_back(url_for("web.index")) else: VAR_3.warning('Login failed for VAR_104 "%s" IP-address: %s', VAR_116['username'], VAR_141) flash(_(u"Wrong Username or Password"), category="error") VAR_97 = request.args.get('next', default=url_for("web.index"), type=str) if url_for("web.logout") == VAR_97: next_url = url_for("web.index") return render_title_template('login.html', VAR_150=_(u"Login"), VAR_97=next_url, config=config, VAR_100=oauth_check, mail=config.get_mail_server_configured(), VAR_9="login") @VAR_2.route('/logout') @login_required def FUNC_66(): if VAR_87 is not None and VAR_87.is_authenticated: ub.delete_user_session(VAR_87.id, VAR_91.get('_id',"")) logout_user() if VAR_0['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3): logout_oauth_user() VAR_3.debug(u"User logged out") return redirect(url_for('web.login')) def FUNC_67(VAR_44, VAR_45, VAR_46, VAR_47, VAR_48): VAR_55 = request.form.to_dict() VAR_87.random_books = 0 if VAR_87.role_passwd() or VAR_87.role_admin(): if VAR_55.get("password"): VAR_87.password = generate_password_hash(VAR_55["password"]) try: if VAR_55.get("kindle_mail", VAR_87.kindle_mail) != VAR_87.kindle_mail: VAR_87.kindle_mail = valid_email(VAR_55["kindle_mail"]) if VAR_55.get("email", VAR_87.email) != VAR_87.email: VAR_87.email = check_email(VAR_55["email"]) if VAR_87.role_admin(): if VAR_55.get("name", VAR_87.name) != VAR_87.name: VAR_87.name = check_username(VAR_55["name"]) VAR_87.random_books = 1 if VAR_55.get("show_random") == "on" else 0 if VAR_55.get("default_language"): VAR_87.default_language = VAR_55["default_language"] if VAR_55.get("locale"): VAR_87.locale = VAR_55["locale"] VAR_117 = VAR_87.kobo_only_shelves_sync VAR_87.kobo_only_shelves_sync = int(VAR_55.get("kobo_only_shelves_sync") == "on") or 0 if VAR_117 == 0 and VAR_87.kobo_only_shelves_sync == 1: kobo_sync_status.update_on_sync_shelfs(VAR_87.id) except Exception as ex: flash(str(ex), category="error") return render_title_template("user_edit.html", VAR_115=VAR_87, VAR_47=translations, FUNC_68=1, VAR_48=languages, VAR_150=_(u"%(VAR_13)s's profile", VAR_13=VAR_87.name), VAR_9="me", VAR_44=kobo_support, registered_oauth=VAR_45, VAR_46=oauth_status) VAR_98 = 0 for key, VAR_64 in VAR_55.items(): if key.startswith('show'): VAR_98 += int(key[5:]) VAR_87.sidebar_view = VAR_98 if VAR_55.get("Show_detail_random"): VAR_87.sidebar_view += constants.DETAIL_RANDOM try: ub.session.commit() flash(_(u"Profile updated"), category="success") VAR_3.debug(u"Profile updated") except IntegrityError: ub.session.rollback() flash(_(u"Found an existing account for this e-mail address"), category="error") VAR_3.debug(u"Found an existing account for this e-mail address") except OperationalError as e: ub.session.rollback() VAR_3.error("Database VAR_140: %s", e) flash(_(u"Database VAR_140: %(error)s.", VAR_140=e), category="error") @VAR_2.route("/me", methods=["GET", "POST"]) @login_required def FUNC_68(): VAR_48 = calibre_db.speaking_language() VAR_47 = babel.list_translations() + [LC('en')] VAR_44 = VAR_0['kobo'] and config.config_kobo_sync if VAR_0['oauth'] and config.config_login_type == 2: VAR_46 = get_oauth_status() VAR_45 = VAR_100 else: VAR_46 = None VAR_45 = {} if request.method == "POST": FUNC_67(VAR_44, VAR_45, VAR_46, VAR_47, VAR_48) return render_title_template("user_edit.html", VAR_47=translations, FUNC_68=1, VAR_48=languages, VAR_115=VAR_87, VAR_44=kobo_support, VAR_150=_(u"%(VAR_13)s's profile", VAR_13=VAR_87.name), VAR_9="me", registered_oauth=VAR_45, VAR_46=oauth_status) @VAR_2.route("/read/<int:VAR_5>/<VAR_6>") @login_required_if_no_ano @FUNC_2 def FUNC_69(VAR_5, VAR_6): VAR_95 = calibre_db.get_filtered_book(VAR_5) if not VAR_95: flash(_(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible"), category="error") VAR_3.debug(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible") return redirect(url_for("web.index")) FUNC_4 = None if VAR_87.is_authenticated: VAR_99 = ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(VAR_87.id), ub.Bookmark.book_id == VAR_5, ub.Bookmark.format == VAR_6.upper())).first() if VAR_6.lower() == "epub": VAR_3.debug(u"Start epub reader for %d", VAR_5) return render_title_template('read.html', bookid=VAR_5, VAR_150=VAR_95.title, VAR_99=FUNC_4) elif VAR_6.lower() == "pdf": VAR_3.debug(u"Start pdf reader for %d", VAR_5) return render_title_template('readpdf.html', pdffile=VAR_5, VAR_150=VAR_95.title) elif VAR_6.lower() == "txt": VAR_3.debug(u"Start txt reader for %d", VAR_5) return render_title_template('readtxt.html', txtfile=VAR_5, VAR_150=VAR_95.title) elif VAR_6.lower() == "djvu": VAR_3.debug(u"Start djvu reader for %d", VAR_5) return render_title_template('readdjvu.html', djvufile=VAR_5, VAR_150=VAR_95.title) else: for fileExt in constants.EXTENSIONS_AUDIO: if VAR_6.lower() == fileExt: VAR_63 = calibre_db.get_filtered_book(VAR_5) VAR_3.debug(u"Start mp3 listening for %d", VAR_5) return render_title_template('listenmp3.html', mp3file=VAR_5, audioformat=VAR_6.lower(), entry=VAR_63, VAR_99=FUNC_4) for fileExt in ["cbr", "cbt", "cbz"]: if VAR_6.lower() == fileExt: VAR_149 = str(VAR_5) VAR_150 = VAR_95.title if len(VAR_95.series): VAR_150 = VAR_150 + " - " + VAR_95.series[0].name if VAR_95.series_index: VAR_150 = VAR_150 + " #" + '{0:.2f}'.format(VAR_95.series_index).rstrip('0').rstrip('.') VAR_3.debug(u"Start comic reader for %d", VAR_5) return render_title_template('readcbr.html', comicfile=VAR_149, VAR_150=title, extension=fileExt) VAR_3.debug(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) @VAR_2.route("/VAR_95/<int:VAR_5>") @login_required_if_no_ano def FUNC_70(VAR_5): VAR_63 = calibre_db.get_filtered_book(VAR_5, allow_show_archived=True) if VAR_63: for FUNC_31 in range(0, len(VAR_63.languages)): VAR_63.languages[FUNC_31].language_name = isoLanguages.get_language_name(get_locale(), VAR_63.languages[ FUNC_31].lang_code) VAR_16 = get_cc_columns(filter_config_custom_read=True) VAR_118 = [] VAR_119 = ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == VAR_5).all() for entry in VAR_119: VAR_118.append(entry.shelf) if not VAR_87.is_anonymous: if not config.config_read_column: VAR_147 = ub.session.query(ub.ReadBook). \ filter(and_(ub.ReadBook.user_id == int(VAR_87.id), ub.ReadBook.book_id == VAR_5)).all() VAR_143 = len( VAR_147) > 0 and VAR_147[0].read_status == ub.ReadBook.STATUS_FINISHED else: try: VAR_147 = getattr(VAR_63, 'custom_column_' + str(config.config_read_column)) VAR_143 = len(VAR_147) > 0 and VAR_147[0].value except (KeyError, AttributeError): VAR_3.error("Custom Column No.%d is not existing in calibre database", config.config_read_column) VAR_143 = None VAR_142 = ub.session.query(ub.ArchivedBook).\ filter(and_(ub.ArchivedBook.user_id == int(VAR_87.id), ub.ArchivedBook.book_id == VAR_5)).first() VAR_54 = VAR_142 and VAR_142.is_archived else: VAR_143 = None VAR_54 = None VAR_63.tags = VAR_7(VAR_63.tags, key=lambda tag: tag.name) VAR_63 = calibre_db.order_authors(VAR_63) VAR_120 = check_send_to_kindle(VAR_63) VAR_121 = check_read_formats(VAR_63) VAR_122 = [] for media_format in VAR_63.data: if media_format.format.lower() in constants.EXTENSIONS_AUDIO: VAR_122.append(media_format.format.lower()) return render_title_template('detail.html', entry=VAR_63, VAR_122=audioentries, VAR_16=cc, is_xhr=request.headers.get('X-Requested-With')=='XMLHttpRequest', VAR_150=VAR_63.title, books_shelfs=VAR_118, VAR_143=have_read, VAR_54=is_archived, VAR_120=kindle_list, VAR_121=reader_list, VAR_9="book") else: VAR_3.debug(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected VAR_95 VAR_150 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index"))
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 29, 41, 43, 46, 60, 66, 73, 78, 83, 84, 97, 100, 101, 102, 103, 104, 111, 113, 114, 121, 123, 124, 125, 126, 132, 133, 144, 152, 153, 197, 205, 206, 219, 220, 240, 245, 258, 268, 269, 270, 271, 276, 277, 282, 283, 288, 289, 294, 295, 308, 309, 334, 335, 369, 370, 417, 418, 428, 433, 434, 443, 447, 448, 449, 474, 475, 487, 512, 513, 531, 537, 541, 542, 559, 560, 572, 573, 587, 588, 602, 603, 618, 619, 625, 632, 633, 671, 683, 684, 694, 696, 702, 707, 708, 710, 738, 739, 753, 754, 755, 756, 757, 764, 765, 773, 774, 782, 793, 817, 819, 831, 838, 842, 846, 847, 859, 860, 877, 878, 886, 906, 907, 928, 929, 957, 963, 964, 983, 984, 1004, 1005, 1022, 1023, 1044, 1045, 1046, 1047, 1048, 1052, 1056, 1057, 1062, 1063, 1064, 1065, 1078, 1079, 1090, 1091, 1119, 1120, 1130, 1131, 1140, 1141, 1168, 1169, 1176, 1177, 1184, 1185, 1192, 1199, 1250, 1253, 1254, 1258, 1264, 1265, 1271, 1287, 1311, 1312, 1343, 1346, 1347, 1353, 1372, 1373, 1374, 1378, 1381, 1382, 1383, 1384, 1385, 1390, 1394, 1427, 1428, 1436, 1437, 1459, 1460, 1461, 1462, 1463, 1473, 1486, 1511, 1515, 1516, 1578, 1588, 1589, 1600, 1601, 1602, 1616, 1624, 1625, 1626, 1630, 1643, 1651, 1664, 1665, 1678, 1691, 1692, 1693, 1694, 1695, 1705, 1706, 1745, 1746, 1760, 1774, 1779, 1783, 1785, 1787, 1790, 1795, 1813 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 29, 41, 43, 46, 60, 66, 73, 78, 83, 84, 97, 100, 101, 102, 103, 104, 111, 113, 114, 121, 123, 124, 125, 126, 132, 133, 144, 152, 153, 197, 205, 206, 219, 220, 240, 245, 258, 268, 269, 270, 271, 276, 277, 282, 283, 288, 289, 294, 295, 308, 309, 334, 335, 369, 370, 417, 418, 428, 433, 434, 443, 447, 448, 449, 474, 475, 487, 512, 513, 531, 537, 541, 542, 559, 560, 572, 573, 587, 588, 602, 603, 618, 619, 625, 632, 633, 671, 683, 684, 694, 696, 702, 707, 708, 710, 738, 739, 753, 754, 755, 756, 757, 764, 765, 773, 774, 782, 793, 817, 819, 831, 838, 842, 846, 847, 859, 860, 877, 878, 886, 906, 907, 928, 929, 957, 963, 964, 983, 984, 1004, 1005, 1022, 1023, 1044, 1045, 1046, 1047, 1048, 1052, 1056, 1057, 1058, 1063, 1064, 1065, 1066, 1079, 1080, 1091, 1092, 1120, 1121, 1131, 1132, 1141, 1142, 1169, 1170, 1177, 1178, 1185, 1186, 1193, 1200, 1251, 1254, 1255, 1259, 1265, 1266, 1272, 1288, 1312, 1313, 1344, 1347, 1348, 1354, 1373, 1374, 1375, 1379, 1382, 1383, 1384, 1385, 1386, 1391, 1395, 1428, 1429, 1437, 1438, 1460, 1461, 1462, 1463, 1464, 1474, 1487, 1512, 1516, 1517, 1579, 1589, 1590, 1601, 1602, 1603, 1617, 1625, 1626, 1627, 1631, 1644, 1652, 1665, 1666, 1679, 1692, 1693, 1694, 1695, 1696, 1706, 1707, 1746, 1747, 1761, 1775, 1780, 1784, 1786, 1788, 1791, 1796, 1814 ]
0CWE-22
import logging import pathlib from s3file.storages import local_dev, storage from . import views logger = logging.getLogger("s3file") class S3FileMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): file_fields = request.POST.getlist("s3file") for field_name in file_fields: paths = request.POST.getlist(field_name) request.FILES.setlist(field_name, list(self.get_files_from_storage(paths))) if local_dev and request.path == "/__s3_mock__/": return views.S3MockView.as_view()(request) return self.get_response(request) @staticmethod def get_files_from_storage(paths): """Return S3 file where the name does not include the path.""" for path in paths: path = pathlib.PurePosixPath(path) try: location = storage.aws_location except AttributeError: location = storage.location try: f = storage.open(str(path.relative_to(location))) f.name = path.name yield f except (OSError, ValueError): logger.exception("File not found: %s", path)
import logging import pathlib from django.core import signing from django.core.exceptions import PermissionDenied, SuspiciousFileOperation from django.utils.crypto import constant_time_compare from . import views from .forms import S3FileInputMixin from .storages import local_dev, storage logger = logging.getLogger("s3file") class S3FileMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): file_fields = request.POST.getlist("s3file") for field_name in file_fields: paths = request.POST.getlist(field_name) if paths: try: signature = request.POST[f"{field_name}-s3f-signature"] except KeyError: raise PermissionDenied("No signature provided.") try: request.FILES.setlist( field_name, list(self.get_files_from_storage(paths, signature)) ) except SuspiciousFileOperation as e: raise PermissionDenied("Illegal file name!") from e if local_dev and request.path == "/__s3_mock__/": return views.S3MockView.as_view()(request) return self.get_response(request) @staticmethod def get_files_from_storage(paths, signature): """Return S3 file where the name does not include the path.""" try: location = storage.aws_location except AttributeError: location = storage.location signer = signing.Signer( salt=f"{S3FileInputMixin.__module__}.{S3FileInputMixin.__name__}" ) for path in paths: path = pathlib.PurePosixPath(path) print(path) print(signer.signature(path.parent), signature) if not constant_time_compare(signer.signature(path.parent), signature): raise PermissionDenied("Illegal signature!") try: relative_path = str(path.relative_to(location)) except ValueError as e: raise SuspiciousFileOperation( f"Path is not inside the designated upload location: {path}" ) from e try: f = storage.open(relative_path) f.name = path.name yield f except (OSError, ValueError): logger.exception("File not found: %s", path)
path_disclosure
{ "code": [ "from s3file.storages import local_dev, storage", " request.FILES.setlist(field_name, list(self.get_files_from_storage(paths)))", " def get_files_from_storage(paths):", " location = storage.aws_location", " except AttributeError:", " location = storage.location", " f = storage.open(str(path.relative_to(location)))" ], "line_no": [ 4, 19, 27, 32, 33, 34, 36 ] }
{ "code": [ "from django.core import signing", "from django.utils.crypto import constant_time_compare", "from .storages import local_dev, storage", " if paths:", " signature = request.POST[f\"{field_name}-s3f-signature\"]", " except KeyError:", " try:", " request.FILES.setlist(", " field_name, list(self.get_files_from_storage(paths, signature))", " )", " except SuspiciousFileOperation as e:", " raise PermissionDenied(\"Illegal file name!\") from e", " def get_files_from_storage(paths, signature):", " try:", " location = storage.aws_location", " except AttributeError:", " location = storage.location", " signer = signing.Signer(", " salt=f\"{S3FileInputMixin.__module__}.{S3FileInputMixin.__name__}\"", " )", " print(path)", " print(signer.signature(path.parent), signature)", " if not constant_time_compare(signer.signature(path.parent), signature):", " raise PermissionDenied(\"Illegal signature!\")", " relative_path = str(path.relative_to(location))", " except ValueError as e:", " raise SuspiciousFileOperation(", " f\"Path is not inside the designated upload location: {path}\"", " ) from e", " f = storage.open(relative_path)" ], "line_no": [ 4, 6, 10, 24, 26, 27, 29, 30, 31, 32, 33, 34, 42, 44, 45, 46, 47, 48, 49, 50, 53, 54, 55, 56, 58, 59, 60, 61, 62, 65 ] }
import logging import .pathlib from s3file.storages import local_dev, storage from . import views VAR_0 = logging.getLogger("s3file") class CLASS_0: def __init__(self, VAR_1): self.get_response = VAR_1 def __call__(self, VAR_2): VAR_4 = VAR_2.POST.getlist("s3file") for field_name in VAR_4: VAR_3 = VAR_2.POST.getlist(field_name) VAR_2.FILES.setlist(field_name, list(self.get_files_from_storage(VAR_3))) if local_dev and VAR_2.path == "/__s3_mock__/": return views.S3MockView.as_view()(VAR_2) return self.get_response(VAR_2) @staticmethod def FUNC_0(VAR_3): for VAR_5 in VAR_3: VAR_5 = pathlib.PurePosixPath(VAR_5) try: VAR_6 = storage.aws_location except AttributeError: VAR_6 = storage.location try: VAR_7 = storage.open(str(VAR_5.relative_to(VAR_6))) VAR_7.name = VAR_5.name yield VAR_7 except (OSError, ValueError): VAR_0.exception("File not found: %s", VAR_5)
import logging import .pathlib from django.core import signing from django.core.exceptions import PermissionDenied, SuspiciousFileOperation from django.utils.crypto import constant_time_compare from . import views from .forms import S3FileInputMixin from .storages import local_dev, storage VAR_0 = logging.getLogger("s3file") class CLASS_0: def __init__(self, VAR_1): self.get_response = VAR_1 def __call__(self, VAR_2): VAR_5 = VAR_2.POST.getlist("s3file") for field_name in VAR_5: VAR_3 = VAR_2.POST.getlist(field_name) if VAR_3: try: VAR_4 = VAR_2.POST[f"{field_name}-s3f-signature"] except KeyError: raise PermissionDenied("No VAR_4 provided.") try: VAR_2.FILES.setlist( field_name, list(self.get_files_from_storage(VAR_3, VAR_4)) ) except SuspiciousFileOperation as e: raise PermissionDenied("Illegal file name!") from e if local_dev and VAR_2.path == "/__s3_mock__/": return views.S3MockView.as_view()(VAR_2) return self.get_response(VAR_2) @staticmethod def FUNC_0(VAR_3, VAR_4): try: VAR_7 = storage.aws_location except AttributeError: VAR_7 = storage.location VAR_6 = signing.Signer( salt=f"{S3FileInputMixin.__module__}.{S3FileInputMixin.__name__}" ) for VAR_8 in VAR_3: VAR_8 = pathlib.PurePosixPath(VAR_8) print(VAR_8) print(VAR_6.signature(VAR_8.parent), VAR_4) if not constant_time_compare(VAR_6.signature(VAR_8.parent), VAR_4): raise PermissionDenied("Illegal VAR_4!") try: VAR_9 = str(VAR_8.relative_to(VAR_7)) except ValueError as e: raise SuspiciousFileOperation( f"Path is not inside the designated upload VAR_7: {VAR_8}" ) from e try: VAR_10 = storage.open(VAR_9) VAR_10.name = VAR_8.name yield VAR_10 except (OSError, ValueError): VAR_0.exception("File not found: %s", VAR_8)
[ 3, 5, 7, 9, 10, 14, 20, 23, 25, 41, 28 ]
[ 3, 7, 11, 13, 14, 18, 22, 35, 38, 40, 63, 70, 43 ]
1CWE-79
"""Fava's main WSGI application. when using Fava's WSGI app, make sure to set ``app.config['BEANCOUNT_FILES']``. To start a simple server:: from fava.application import app app.config['BEANCOUNT_FILES'] = ['/path/to/file.beancount'] app.run('localhost', 5000) Attributes: app: An instance of :class:`flask.Flask`, this is Fava's WSGI application. """ from __future__ import annotations import datetime import functools import threading from io import BytesIO from typing import Any import flask import markdown2 # type: ignore import werkzeug.urls from beancount import __version__ as beancount_version from beancount.core.account import ACCOUNT_RE from beancount.utils.text_utils import replace_numbers from flask import abort from flask import Flask from flask import redirect from flask import render_template from flask import render_template_string from flask import request from flask import send_file from flask.wrappers import Response from flask_babel import Babel # type: ignore from flask_babel import get_translations from werkzeug.utils import secure_filename from fava import __version__ as fava_version from fava import LANGUAGES from fava import template_filters from fava.context import g from fava.core import FavaLedger from fava.core.charts import FavaJSONEncoder from fava.core.documents import is_document_or_import_file from fava.help import HELP_PAGES from fava.helpers import FavaAPIException from fava.json_api import json_api from fava.serialisation import serialise from fava.util import next_key from fava.util import resource_path from fava.util import send_file_inline from fava.util import setup_logging from fava.util import slugify from fava.util.date import Interval from fava.util.excel import HAVE_EXCEL STATIC_FOLDER = resource_path("static") setup_logging() app = Flask( # pylint: disable=invalid-name __name__, template_folder=str(resource_path("templates")), static_folder=str(STATIC_FOLDER), ) app.register_blueprint(json_api, url_prefix="/<bfile>/api") app.json_encoder = FavaJSONEncoder # type: ignore jinja_extensions = app.jinja_options.setdefault("extensions", []) jinja_extensions.append("jinja2.ext.do") jinja_extensions.append("jinja2.ext.loopcontrols") app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.config["HAVE_EXCEL"] = HAVE_EXCEL app.config["ACCOUNT_RE"] = ACCOUNT_RE REPORTS = [ "balance_sheet", "commodities", "documents", "events", "editor", "errors", "holdings", "import", "income_statement", "journal", "options", "query", "statistics", "trial_balance", ] LOAD_FILE_LOCK = threading.Lock() def ledger_slug(ledger: FavaLedger) -> str: """Generate URL slug for a ledger.""" title_slug = slugify(ledger.options["title"]) return title_slug or slugify(ledger.beancount_file_path) def update_ledger_slugs(ledgers: list[FavaLedger]) -> None: """Update the dictionary mapping URL slugs to ledgers.""" ledgers_by_slug: dict[str, FavaLedger] = {} for ledger in ledgers: slug = ledger_slug(ledger) unique_key = next_key(slug, ledgers_by_slug) ledgers_by_slug[unique_key] = ledger app.config["LEDGERS"] = ledgers_by_slug def _load_file() -> None: """Load Beancount files. This is run automatically on the first request. """ ledgers = [ FavaLedger(filepath) for filepath in app.config["BEANCOUNT_FILES"] ] update_ledger_slugs(ledgers) def get_locale() -> str | None: """Get locale. Returns: The locale that should be used for Babel. If not given as an option to Fava, guess from browser. """ lang = g.ledger.fava_options.language if lang is not None: return lang return request.accept_languages.best_match(["en"] + LANGUAGES) BABEL = Babel(app) BABEL.localeselector(get_locale) for function in template_filters.FILTERS: app.add_template_filter(function) # type: ignore app.add_template_filter(serialise) @app.url_defaults def _inject_filters(endpoint: str, values: dict[str, str | None]) -> None: if "bfile" not in values and app.url_map.is_endpoint_expecting( endpoint, "bfile" ): values["bfile"] = g.beancount_file_slug if endpoint in ["static", "index"]: return for name in ["conversion", "interval", "account", "filter", "time"]: if name not in values: values[name] = request.args.get(name) def static_url(filename: str) -> str: """Return a static url with an mtime query string for cache busting.""" file_path = STATIC_FOLDER / filename try: mtime = int(file_path.stat().st_mtime) except FileNotFoundError: mtime = 0 return url_for("static", filename=filename, mtime=mtime) CACHED_URL_FOR = functools.lru_cache(2048)(flask.url_for) def url_for(endpoint: str, **values: str | int) -> str: """A wrapper around flask.url_for that uses a cache.""" _inject_filters(endpoint, values) return CACHED_URL_FOR(endpoint, **values) def url_for_source(**kwargs: str) -> str: """URL to source file (possibly link to external editor).""" if g.ledger.fava_options.use_external_editor: return ( f"beancount://{kwargs.get('file_path')}" + f"?lineno={kwargs.get('line', 1)}" ) return url_for("report", report_name="editor", **kwargs) def translations() -> Any: """Get translations catalog.""" # pylint: disable=protected-access return get_translations()._catalog app.add_template_global(static_url, "static_url") app.add_template_global(datetime.date.today, "today") app.add_template_global(url_for, "url_for") app.add_template_global(url_for_source, "url_for_source") app.add_template_global(translations, "translations") @app.context_processor def template_context() -> dict[str, FavaLedger]: """Inject variables into the template context.""" return dict(ledger=g.ledger) @app.before_request def _perform_global_filters() -> None: if request.endpoint in ("json_api.get_changed", "json_api.get_errors"): return ledger = getattr(g, "ledger", None) if ledger: # check (and possibly reload) source file if request.blueprint != "json_api": ledger.changed() g.filtered = ledger.get_filtered( account=request.args.get("account"), filter=request.args.get("filter"), time=request.args.get("time"), ) @app.after_request def _incognito( response: werkzeug.wrappers.Response, ) -> werkzeug.wrappers.Response: """Replace all numbers with 'X'.""" if app.config.get("INCOGNITO") and response.content_type.startswith( "text/html" ): is_editor = ( request.endpoint == "report" and request.view_args is not None and request.view_args["report_name"] == "editor" ) if not is_editor: original_text = response.get_data(as_text=True) response.set_data(replace_numbers(original_text)) return response @app.url_value_preprocessor def _pull_beancount_file(_: str | None, values: dict[str, str] | None) -> None: g.beancount_file_slug = values.pop("bfile", None) if values else None with LOAD_FILE_LOCK: if not app.config.get("LEDGERS"): _load_file() if g.beancount_file_slug: if g.beancount_file_slug not in app.config["LEDGERS"]: if not any( g.beancount_file_slug == ledger_slug(ledger) for ledger in app.config["LEDGERS"].values() ): abort(404) # one of the file slugs changed, update the mapping update_ledger_slugs(app.config["LEDGERS"].values()) g.ledger = app.config["LEDGERS"][g.beancount_file_slug] g.conversion = request.args.get("conversion", "at_cost") g.interval = Interval.get(request.args.get("interval", "month")) @app.errorhandler(FavaAPIException) def fava_api_exception(error: FavaAPIException) -> str: """Handle API errors.""" return render_template( "_layout.html", page_title="Error", content=error.message ) @app.route("/") @app.route("/<bfile>/") def index() -> werkzeug.wrappers.Response: """Redirect to the Income Statement (of the given or first file).""" if not g.beancount_file_slug: g.beancount_file_slug = next(iter(app.config["LEDGERS"])) index_url = url_for("index") default_path = app.config["LEDGERS"][ g.beancount_file_slug ].fava_options.default_page return redirect(f"{index_url}{default_path}") @app.route("/<bfile>/account/<name>/") @app.route("/<bfile>/account/<name>/<subreport>/") def account(name: str, subreport: str = "journal") -> str: """The account report.""" if subreport in ["journal", "balances", "changes"]: return render_template( "account.html", account_name=name, subreport=subreport ) return abort(404) @app.route("/<bfile>/document/", methods=["GET"]) def document() -> Response: """Download a document.""" filename = request.args.get("filename") if filename is None: return abort(404) if is_document_or_import_file(filename, g.ledger): return send_file_inline(filename) return abort(404) @app.route("/<bfile>/statement/", methods=["GET"]) def statement() -> Response: """Download a statement file.""" entry_hash = request.args.get("entry_hash", "") key = request.args.get("key", "") document_path = g.ledger.statement_path(entry_hash, key) return send_file_inline(document_path) @app.route("/<bfile>/holdings/by_<aggregation_key>/") def holdings_by(aggregation_key: str) -> str: """The holdings report.""" if aggregation_key in ["account", "currency", "cost_currency"]: return render_template( "_layout.html", active_page="holdings", aggregation_key=aggregation_key, ) return abort(404) @app.route("/<bfile>/<report_name>/") def report(report_name: str) -> str: """Endpoint for most reports.""" if report_name in REPORTS: return render_template("_layout.html", active_page=report_name) return abort(404) @app.route("/<bfile>/extension/<report_name>/") def extension_report(report_name: str) -> str: """Endpoint for extension reports.""" try: template, extension = g.ledger.extensions.template_and_extension( report_name ) content = render_template_string(template, extension=extension) return render_template( "_layout.html", content=content, page_title=extension.report_title ) except LookupError: return abort(404) @app.route("/<bfile>/download-query/query_result.<result_format>") def download_query(result_format: str) -> Any: """Download a query result.""" name, data = g.ledger.query_shell.query_to_file( g.filtered.entries, request.args.get("query_string", ""), result_format ) filename = f"{secure_filename(name.strip())}.{result_format}" return send_file(data, as_attachment=True, download_name=filename) @app.route("/<bfile>/download-journal/") def download_journal() -> Any: """Download a Journal file.""" now = datetime.datetime.now().replace(microsecond=0) filename = f"journal_{now.isoformat()}.beancount" data = BytesIO(bytes(render_template("beancount_file"), "utf8")) return send_file(data, as_attachment=True, download_name=filename) @app.route("/<bfile>/help/", defaults={"page_slug": "_index"}) @app.route("/<bfile>/help/<string:page_slug>") def help_page(page_slug: str) -> str: """Fava's included documentation.""" if page_slug not in HELP_PAGES: abort(404) html = markdown2.markdown_path( (resource_path("help") / (page_slug + ".md")), extras=["fenced-code-blocks", "tables", "header-ids"], ) return render_template( "_layout.html", active_page="help", page_slug=page_slug, help_html=render_template_string( html, beancount_version=beancount_version, fava_version=fava_version, ), HELP_PAGES=HELP_PAGES, ) @app.route("/jump") def jump() -> werkzeug.wrappers.Response: """Redirect back to the referer, replacing some parameters. This is useful for sidebar links, e.g. a link ``/jump?time=year`` would set the time filter to `year` on the current page. When accessing ``/jump?param1=abc`` from ``/example/page?param1=123&param2=456``, this view should redirect to ``/example/page?param1=abc&param2=456``. """ url = werkzeug.urls.url_parse(request.referrer) qs_dict = url.decode_query() for key, values in request.args.lists(): if values == [""]: try: del qs_dict[key] except KeyError: pass else: qs_dict.setlist(key, values) redirect_url = url.replace( query=werkzeug.urls.url_encode(qs_dict, sort=True) ) return redirect(werkzeug.urls.url_unparse(redirect_url))
"""Fava's main WSGI application. when using Fava's WSGI app, make sure to set ``app.config['BEANCOUNT_FILES']``. To start a simple server:: from fava.application import app app.config['BEANCOUNT_FILES'] = ['/path/to/file.beancount'] app.run('localhost', 5000) Attributes: app: An instance of :class:`flask.Flask`, this is Fava's WSGI application. """ from __future__ import annotations import datetime import functools import threading from io import BytesIO from typing import Any import flask import markdown2 # type: ignore import werkzeug.urls from beancount import __version__ as beancount_version from beancount.core.account import ACCOUNT_RE from beancount.utils.text_utils import replace_numbers from flask import abort from flask import Flask from flask import redirect from flask import render_template from flask import render_template_string from flask import request from flask import send_file from flask.wrappers import Response from flask_babel import Babel # type: ignore from flask_babel import get_translations from markupsafe import Markup from werkzeug.utils import secure_filename from fava import __version__ as fava_version from fava import LANGUAGES from fava import template_filters from fava.context import g from fava.core import FavaLedger from fava.core.charts import FavaJSONEncoder from fava.core.documents import is_document_or_import_file from fava.help import HELP_PAGES from fava.helpers import FavaAPIException from fava.json_api import json_api from fava.serialisation import serialise from fava.util import next_key from fava.util import resource_path from fava.util import send_file_inline from fava.util import setup_logging from fava.util import slugify from fava.util.date import Interval from fava.util.excel import HAVE_EXCEL STATIC_FOLDER = resource_path("static") setup_logging() app = Flask( # pylint: disable=invalid-name __name__, template_folder=str(resource_path("templates")), static_folder=str(STATIC_FOLDER), ) app.register_blueprint(json_api, url_prefix="/<bfile>/api") app.json_encoder = FavaJSONEncoder # type: ignore jinja_extensions = app.jinja_options.setdefault("extensions", []) jinja_extensions.append("jinja2.ext.do") jinja_extensions.append("jinja2.ext.loopcontrols") app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.config["HAVE_EXCEL"] = HAVE_EXCEL app.config["ACCOUNT_RE"] = ACCOUNT_RE REPORTS = [ "balance_sheet", "commodities", "documents", "events", "editor", "errors", "holdings", "import", "income_statement", "journal", "options", "query", "statistics", "trial_balance", ] LOAD_FILE_LOCK = threading.Lock() def ledger_slug(ledger: FavaLedger) -> str: """Generate URL slug for a ledger.""" title_slug = slugify(ledger.options["title"]) return title_slug or slugify(ledger.beancount_file_path) def update_ledger_slugs(ledgers: list[FavaLedger]) -> None: """Update the dictionary mapping URL slugs to ledgers.""" ledgers_by_slug: dict[str, FavaLedger] = {} for ledger in ledgers: slug = ledger_slug(ledger) unique_key = next_key(slug, ledgers_by_slug) ledgers_by_slug[unique_key] = ledger app.config["LEDGERS"] = ledgers_by_slug def _load_file() -> None: """Load Beancount files. This is run automatically on the first request. """ ledgers = [ FavaLedger(filepath) for filepath in app.config["BEANCOUNT_FILES"] ] update_ledger_slugs(ledgers) def get_locale() -> str | None: """Get locale. Returns: The locale that should be used for Babel. If not given as an option to Fava, guess from browser. """ lang = g.ledger.fava_options.language if lang is not None: return lang return request.accept_languages.best_match(["en"] + LANGUAGES) BABEL = Babel(app) BABEL.localeselector(get_locale) for function in template_filters.FILTERS: app.add_template_filter(function) # type: ignore app.add_template_filter(serialise) @app.url_defaults def _inject_filters(endpoint: str, values: dict[str, str | None]) -> None: if "bfile" not in values and app.url_map.is_endpoint_expecting( endpoint, "bfile" ): values["bfile"] = g.beancount_file_slug if endpoint in ["static", "index"]: return for name in ["conversion", "interval", "account", "filter", "time"]: if name not in values: values[name] = request.args.get(name) def static_url(filename: str) -> str: """Return a static url with an mtime query string for cache busting.""" file_path = STATIC_FOLDER / filename try: mtime = int(file_path.stat().st_mtime) except FileNotFoundError: mtime = 0 return url_for("static", filename=filename, mtime=mtime) CACHED_URL_FOR = functools.lru_cache(2048)(flask.url_for) def url_for(endpoint: str, **values: str | int) -> str: """A wrapper around flask.url_for that uses a cache.""" _inject_filters(endpoint, values) return CACHED_URL_FOR(endpoint, **values) def url_for_source(**kwargs: str) -> str: """URL to source file (possibly link to external editor).""" if g.ledger.fava_options.use_external_editor: return ( f"beancount://{kwargs.get('file_path')}" + f"?lineno={kwargs.get('line', 1)}" ) return url_for("report", report_name="editor", **kwargs) def translations() -> Any: """Get translations catalog.""" # pylint: disable=protected-access return get_translations()._catalog app.add_template_global(static_url, "static_url") app.add_template_global(datetime.date.today, "today") app.add_template_global(url_for, "url_for") app.add_template_global(url_for_source, "url_for_source") app.add_template_global(translations, "translations") @app.context_processor def template_context() -> dict[str, FavaLedger]: """Inject variables into the template context.""" return dict(ledger=g.ledger) @app.before_request def _perform_global_filters() -> None: if request.endpoint in ("json_api.get_changed", "json_api.get_errors"): return ledger = getattr(g, "ledger", None) if ledger: # check (and possibly reload) source file if request.blueprint != "json_api": ledger.changed() g.filtered = ledger.get_filtered( account=request.args.get("account"), filter=request.args.get("filter"), time=request.args.get("time"), ) @app.after_request def _incognito( response: werkzeug.wrappers.Response, ) -> werkzeug.wrappers.Response: """Replace all numbers with 'X'.""" if app.config.get("INCOGNITO") and response.content_type.startswith( "text/html" ): is_editor = ( request.endpoint == "report" and request.view_args is not None and request.view_args["report_name"] == "editor" ) if not is_editor: original_text = response.get_data(as_text=True) response.set_data(replace_numbers(original_text)) return response @app.url_value_preprocessor def _pull_beancount_file(_: str | None, values: dict[str, str] | None) -> None: g.beancount_file_slug = values.pop("bfile", None) if values else None with LOAD_FILE_LOCK: if not app.config.get("LEDGERS"): _load_file() if g.beancount_file_slug: if g.beancount_file_slug not in app.config["LEDGERS"]: if not any( g.beancount_file_slug == ledger_slug(ledger) for ledger in app.config["LEDGERS"].values() ): abort(404) # one of the file slugs changed, update the mapping update_ledger_slugs(app.config["LEDGERS"].values()) g.ledger = app.config["LEDGERS"][g.beancount_file_slug] g.conversion = request.args.get("conversion", "at_cost") g.interval = Interval.get(request.args.get("interval", "month")) @app.errorhandler(FavaAPIException) def fava_api_exception(error: FavaAPIException) -> str: """Handle API errors.""" return render_template( "_layout.html", page_title="Error", content=error.message ) @app.route("/") @app.route("/<bfile>/") def index() -> werkzeug.wrappers.Response: """Redirect to the Income Statement (of the given or first file).""" if not g.beancount_file_slug: g.beancount_file_slug = next(iter(app.config["LEDGERS"])) index_url = url_for("index") default_path = app.config["LEDGERS"][ g.beancount_file_slug ].fava_options.default_page return redirect(f"{index_url}{default_path}") @app.route("/<bfile>/account/<name>/") @app.route("/<bfile>/account/<name>/<subreport>/") def account(name: str, subreport: str = "journal") -> str: """The account report.""" if subreport in ["journal", "balances", "changes"]: return render_template( "account.html", account_name=name, subreport=subreport ) return abort(404) @app.route("/<bfile>/document/", methods=["GET"]) def document() -> Response: """Download a document.""" filename = request.args.get("filename") if filename is None: return abort(404) if is_document_or_import_file(filename, g.ledger): return send_file_inline(filename) return abort(404) @app.route("/<bfile>/statement/", methods=["GET"]) def statement() -> Response: """Download a statement file.""" entry_hash = request.args.get("entry_hash", "") key = request.args.get("key", "") document_path = g.ledger.statement_path(entry_hash, key) return send_file_inline(document_path) @app.route("/<bfile>/holdings/by_<aggregation_key>/") def holdings_by(aggregation_key: str) -> str: """The holdings report.""" if aggregation_key in ["account", "currency", "cost_currency"]: return render_template( "_layout.html", active_page="holdings", aggregation_key=aggregation_key, ) return abort(404) @app.route("/<bfile>/<report_name>/") def report(report_name: str) -> str: """Endpoint for most reports.""" if report_name in REPORTS: return render_template("_layout.html", active_page=report_name) return abort(404) @app.route("/<bfile>/extension/<report_name>/") def extension_report(report_name: str) -> str: """Endpoint for extension reports.""" try: template, extension = g.ledger.extensions.template_and_extension( report_name ) content = render_template_string(template, extension=extension) return render_template( "_layout.html", content=content, page_title=extension.report_title ) except LookupError: return abort(404) @app.route("/<bfile>/download-query/query_result.<result_format>") def download_query(result_format: str) -> Any: """Download a query result.""" name, data = g.ledger.query_shell.query_to_file( g.filtered.entries, request.args.get("query_string", ""), result_format ) filename = f"{secure_filename(name.strip())}.{result_format}" return send_file(data, as_attachment=True, download_name=filename) @app.route("/<bfile>/download-journal/") def download_journal() -> Any: """Download a Journal file.""" now = datetime.datetime.now().replace(microsecond=0) filename = f"journal_{now.isoformat()}.beancount" data = BytesIO(bytes(render_template("beancount_file"), "utf8")) return send_file(data, as_attachment=True, download_name=filename) @app.route("/<bfile>/help/", defaults={"page_slug": "_index"}) @app.route("/<bfile>/help/<string:page_slug>") def help_page(page_slug: str) -> str: """Fava's included documentation.""" if page_slug not in HELP_PAGES: abort(404) html = markdown2.markdown_path( (resource_path("help") / (page_slug + ".md")), extras=["fenced-code-blocks", "tables", "header-ids"], ) return render_template( "_layout.html", active_page="help", page_slug=page_slug, help_html=Markup( render_template_string( html, beancount_version=beancount_version, fava_version=fava_version, ) ), HELP_PAGES=HELP_PAGES, ) @app.route("/jump") def jump() -> werkzeug.wrappers.Response: """Redirect back to the referer, replacing some parameters. This is useful for sidebar links, e.g. a link ``/jump?time=year`` would set the time filter to `year` on the current page. When accessing ``/jump?param1=abc`` from ``/example/page?param1=123&param2=456``, this view should redirect to ``/example/page?param1=abc&param2=456``. """ url = werkzeug.urls.url_parse(request.referrer) qs_dict = url.decode_query() for key, values in request.args.lists(): if values == [""]: try: del qs_dict[key] except KeyError: pass else: qs_dict.setlist(key, values) redirect_url = url.replace( query=werkzeug.urls.url_encode(qs_dict, sort=True) ) return redirect(werkzeug.urls.url_unparse(redirect_url))
xss
{ "code": [ " help_html=render_template_string(", " html,", " beancount_version=beancount_version,", " fava_version=fava_version," ], "line_no": [ 387, 388, 389, 390 ] }
{ "code": [ "from markupsafe import Markup", " help_html=Markup(", " render_template_string(", " html,", " beancount_version=beancount_version,", " fava_version=fava_version,", " )" ], "line_no": [ 38, 388, 389, 390, 391, 392, 393 ] }
from __future__ import annotations import datetime import functools import threading from io import BytesIO from typing import Any import flask import markdown2 # type: ignore import werkzeug.urls from beancount import .__version__ as beancount_version from beancount.core.account import ACCOUNT_RE from beancount.utils.text_utils import replace_numbers from flask import abort from flask import Flask from flask import redirect from flask import render_template from flask import render_template_string from flask import request from flask import send_file from flask.wrappers import Response from flask_babel import Babel # type: ignore from flask_babel import get_translations from werkzeug.utils import secure_filename from fava import .__version__ as fava_version from fava import LANGUAGES from fava import .template_filters from fava.context import g from fava.core import FavaLedger from fava.core.charts import FavaJSONEncoder from fava.core.documents import is_document_or_import_file from fava.help import HELP_PAGES from fava.helpers import FavaAPIException from fava.json_api import json_api from fava.serialisation import serialise from fava.util import next_key from fava.util import resource_path from fava.util import send_file_inline from fava.util import setup_logging from fava.util import .slugify from fava.util.date import Interval from fava.util.excel import HAVE_EXCEL VAR_0 = resource_path("static") setup_logging() VAR_1 = Flask( # pylint: disable=invalid-VAR_16 __name__, template_folder=str(resource_path("templates")), static_folder=str(VAR_0), ) VAR_1.register_blueprint(json_api, url_prefix="/<bfile>/api") VAR_1.json_encoder = FavaJSONEncoder # type: ignore VAR_2 = VAR_1.jinja_options.setdefault("extensions", []) VAR_2.append("jinja2.ext.do") VAR_2.append("jinja2.ext.loopcontrols") VAR_1.jinja_env.trim_blocks = True VAR_1.jinja_env.lstrip_blocks = True VAR_1.config["HAVE_EXCEL"] = HAVE_EXCEL VAR_1.config["ACCOUNT_RE"] = ACCOUNT_RE VAR_3 = [ "balance_sheet", "commodities", "documents", "events", "editor", "errors", "holdings", "import", "income_statement", "journal", "options", "query", "statistics", "trial_balance", ] VAR_4 = threading.Lock() def FUNC_0(VAR_5: FavaLedger) -> str: VAR_22 = slugify(VAR_5.options["title"]) return VAR_22 or slugify(VAR_5.beancount_file_path) def FUNC_1(VAR_6: list[FavaLedger]) -> None: VAR_38: dict[str, FavaLedger] = {} for VAR_5 in VAR_6: VAR_36 = FUNC_0(VAR_5) VAR_37 = next_key(VAR_36, VAR_38) ledgers_by_slug[VAR_37] = VAR_5 VAR_1.config["LEDGERS"] = VAR_38 def FUNC_2() -> None: VAR_6 = [ FavaLedger(filepath) for filepath in VAR_1.config["BEANCOUNT_FILES"] ] FUNC_1(VAR_6) def FUNC_3() -> str | None: VAR_23 = g.ledger.fava_options.language if VAR_23 is not None: return VAR_23 return request.accept_languages.best_match(["en"] + LANGUAGES) VAR_7 = Babel(VAR_1) VAR_7.localeselector(FUNC_3) for function in template_filters.FILTERS: VAR_1.add_template_filter(function) # type: ignore VAR_1.add_template_filter(serialise) @VAR_1.url_defaults def FUNC_4(VAR_8: str, VAR_9: dict[str, str | None]) -> None: if "bfile" not in VAR_9 and VAR_1.url_map.is_endpoint_expecting( VAR_8, "bfile" ): VAR_9["bfile"] = g.beancount_file_slug if VAR_8 in ["static", "index"]: return for VAR_16 in ["conversion", "interval", "account", "filter", "time"]: if VAR_16 not in VAR_9: values[VAR_16] = request.args.get(VAR_16) def FUNC_5(VAR_10: str) -> str: VAR_24 = VAR_0 / VAR_10 try: VAR_39 = int(VAR_24.stat().st_mtime) except FileNotFoundError: VAR_39 = 0 return FUNC_6("static", VAR_10=filename, VAR_39=mtime) VAR_11 = functools.lru_cache(2048)(flask.url_for) def FUNC_6(VAR_8: str, **VAR_9: str | int) -> str: FUNC_4(VAR_8, VAR_9) return VAR_11(VAR_8, **VAR_9) def FUNC_7(**VAR_12: str) -> str: if g.ledger.fava_options.use_external_editor: return ( f"beancount://{VAR_12.get('file_path')}" + f"?lineno={VAR_12.get('line', 1)}" ) return FUNC_6("report", VAR_19="editor", **VAR_12) def FUNC_8() -> Any: return get_translations()._catalog VAR_1.add_template_global(FUNC_5, "static_url") VAR_1.add_template_global(datetime.date.today, "today") VAR_1.add_template_global(FUNC_6, "url_for") VAR_1.add_template_global(FUNC_7, "url_for_source") VAR_1.add_template_global(FUNC_8, "translations") @VAR_1.context_processor def FUNC_9() -> dict[str, FavaLedger]: return dict(VAR_5=g.ledger) @VAR_1.before_request def FUNC_10() -> None: if request.endpoint in ("json_api.get_changed", "json_api.get_errors"): return VAR_5 = getattr(g, "ledger", None) if VAR_5: if request.blueprint != "json_api": VAR_5.changed() g.filtered = VAR_5.get_filtered( FUNC_15=request.args.get("account"), filter=request.args.get("filter"), time=request.args.get("time"), ) @VAR_1.after_request def FUNC_11( VAR_13: werkzeug.wrappers.Response, ) -> werkzeug.wrappers.Response: if VAR_1.config.get("INCOGNITO") and VAR_13.content_type.startswith( "text/html" ): VAR_40 = ( request.endpoint == "report" and request.view_args is not None and request.view_args["report_name"] == "editor" ) if not VAR_40: VAR_44 = VAR_13.get_data(as_text=True) VAR_13.set_data(replace_numbers(VAR_44)) return VAR_13 @VAR_1.url_value_preprocessor def FUNC_12(VAR_14: str | None, VAR_9: dict[str, str] | None) -> None: g.beancount_file_slug = VAR_9.pop("bfile", None) if VAR_9 else None with VAR_4: if not VAR_1.config.get("LEDGERS"): FUNC_2() if g.beancount_file_slug: if g.beancount_file_slug not in VAR_1.config["LEDGERS"]: if not any( g.beancount_file_slug == FUNC_0(VAR_5) for VAR_5 in VAR_1.config["LEDGERS"].values() ): abort(404) FUNC_1(VAR_1.config["LEDGERS"].values()) g.ledger = VAR_1.config["LEDGERS"][g.beancount_file_slug] g.conversion = request.args.get("conversion", "at_cost") g.interval = Interval.get(request.args.get("interval", "month")) @VAR_1.errorhandler(FavaAPIException) def FUNC_13(VAR_15: FavaAPIException) -> str: return render_template( "_layout.html", page_title="Error", VAR_43=VAR_15.message ) @VAR_1.route("/") @VAR_1.route("/<bfile>/") def FUNC_14() -> werkzeug.wrappers.Response: if not g.beancount_file_slug: g.beancount_file_slug = next(iter(VAR_1.config["LEDGERS"])) VAR_25 = FUNC_6("index") VAR_26 = VAR_1.config["LEDGERS"][ g.beancount_file_slug ].fava_options.default_page return redirect(f"{VAR_25}{VAR_26}") @VAR_1.route("/<bfile>/FUNC_15/<VAR_16>/") @VAR_1.route("/<bfile>/FUNC_15/<VAR_16>/<VAR_17>/") def FUNC_15(VAR_16: str, VAR_17: str = "journal") -> str: if VAR_17 in ["journal", "balances", "changes"]: return render_template( "account.html", account_name=VAR_16, VAR_17=subreport ) return abort(404) @VAR_1.route("/<bfile>/FUNC_16/", methods=["GET"]) def FUNC_16() -> Response: VAR_10 = request.args.get("filename") if VAR_10 is None: return abort(404) if is_document_or_import_file(VAR_10, g.ledger): return send_file_inline(VAR_10) return abort(404) @VAR_1.route("/<bfile>/FUNC_17/", methods=["GET"]) def FUNC_17() -> Response: VAR_27 = request.args.get("entry_hash", "") VAR_28 = request.args.get("key", "") VAR_29 = g.ledger.statement_path(VAR_27, VAR_28) return send_file_inline(VAR_29) @VAR_1.route("/<bfile>/holdings/by_<VAR_18>/") def FUNC_18(VAR_18: str) -> str: if VAR_18 in ["account", "currency", "cost_currency"]: return render_template( "_layout.html", active_page="holdings", VAR_18=aggregation_key, ) return abort(404) @VAR_1.route("/<bfile>/<VAR_19>/") def FUNC_19(VAR_19: str) -> str: if VAR_19 in VAR_3: return render_template("_layout.html", active_page=VAR_19) return abort(404) @VAR_1.route("/<bfile>/VAR_42/<VAR_19>/") def FUNC_20(VAR_19: str) -> str: try: VAR_41, VAR_42 = g.ledger.extensions.template_and_extension( VAR_19 ) VAR_43 = render_template_string(VAR_41, VAR_42=extension) return render_template( "_layout.html", VAR_43=content, page_title=VAR_42.report_title ) except LookupError: return abort(404) @VAR_1.route("/<bfile>/download-query/query_result.<VAR_20>") def FUNC_21(VAR_20: str) -> Any: VAR_16, VAR_30 = g.ledger.query_shell.query_to_file( g.filtered.entries, request.args.get("query_string", ""), VAR_20 ) VAR_10 = f"{secure_filename(VAR_16.strip())}.{VAR_20}" return send_file(VAR_30, as_attachment=True, download_name=VAR_10) @VAR_1.route("/<bfile>/download-journal/") def FUNC_22() -> Any: VAR_31 = datetime.datetime.now().replace(microsecond=0) VAR_10 = f"journal_{VAR_31.isoformat()}.beancount" VAR_30 = BytesIO(bytes(render_template("beancount_file"), "utf8")) return send_file(VAR_30, as_attachment=True, download_name=VAR_10) @VAR_1.route("/<bfile>/help/", defaults={"page_slug": "_index"}) @VAR_1.route("/<bfile>/help/<string:VAR_21>") def FUNC_23(VAR_21: str) -> str: if VAR_21 not in HELP_PAGES: abort(404) VAR_32 = markdown2.markdown_path( (resource_path("help") / (VAR_21 + ".md")), extras=["fenced-code-blocks", "tables", "header-ids"], ) return render_template( "_layout.html", active_page="help", VAR_21=page_slug, help_html=render_template_string( VAR_32, beancount_version=beancount_version, fava_version=fava_version, ), HELP_PAGES=HELP_PAGES, ) @VAR_1.route("/jump") def FUNC_24() -> werkzeug.wrappers.Response: VAR_33 = werkzeug.urls.url_parse(request.referrer) VAR_34 = VAR_33.decode_query() for VAR_28, VAR_9 in request.args.lists(): if VAR_9 == [""]: try: del VAR_34[VAR_28] except KeyError: pass else: VAR_34.setlist(VAR_28, VAR_9) VAR_35 = VAR_33.replace( query=werkzeug.urls.url_encode(VAR_34, sort=True) ) return redirect(werkzeug.urls.url_unparse(VAR_35))
from __future__ import annotations import datetime import functools import threading from io import BytesIO from typing import Any import flask import markdown2 # type: ignore import werkzeug.urls from beancount import .__version__ as beancount_version from beancount.core.account import ACCOUNT_RE from beancount.utils.text_utils import replace_numbers from flask import abort from flask import Flask from flask import redirect from flask import render_template from flask import render_template_string from flask import request from flask import send_file from flask.wrappers import Response from flask_babel import Babel # type: ignore from flask_babel import get_translations from markupsafe import Markup from werkzeug.utils import secure_filename from fava import .__version__ as fava_version from fava import LANGUAGES from fava import .template_filters from fava.context import g from fava.core import FavaLedger from fava.core.charts import FavaJSONEncoder from fava.core.documents import is_document_or_import_file from fava.help import HELP_PAGES from fava.helpers import FavaAPIException from fava.json_api import json_api from fava.serialisation import serialise from fava.util import next_key from fava.util import resource_path from fava.util import send_file_inline from fava.util import setup_logging from fava.util import .slugify from fava.util.date import Interval from fava.util.excel import HAVE_EXCEL VAR_0 = resource_path("static") setup_logging() VAR_1 = Flask( # pylint: disable=invalid-VAR_16 __name__, template_folder=str(resource_path("templates")), static_folder=str(VAR_0), ) VAR_1.register_blueprint(json_api, url_prefix="/<bfile>/api") VAR_1.json_encoder = FavaJSONEncoder # type: ignore VAR_2 = VAR_1.jinja_options.setdefault("extensions", []) VAR_2.append("jinja2.ext.do") VAR_2.append("jinja2.ext.loopcontrols") VAR_1.jinja_env.trim_blocks = True VAR_1.jinja_env.lstrip_blocks = True VAR_1.config["HAVE_EXCEL"] = HAVE_EXCEL VAR_1.config["ACCOUNT_RE"] = ACCOUNT_RE VAR_3 = [ "balance_sheet", "commodities", "documents", "events", "editor", "errors", "holdings", "import", "income_statement", "journal", "options", "query", "statistics", "trial_balance", ] VAR_4 = threading.Lock() def FUNC_0(VAR_5: FavaLedger) -> str: VAR_22 = slugify(VAR_5.options["title"]) return VAR_22 or slugify(VAR_5.beancount_file_path) def FUNC_1(VAR_6: list[FavaLedger]) -> None: VAR_38: dict[str, FavaLedger] = {} for VAR_5 in VAR_6: VAR_36 = FUNC_0(VAR_5) VAR_37 = next_key(VAR_36, VAR_38) ledgers_by_slug[VAR_37] = VAR_5 VAR_1.config["LEDGERS"] = VAR_38 def FUNC_2() -> None: VAR_6 = [ FavaLedger(filepath) for filepath in VAR_1.config["BEANCOUNT_FILES"] ] FUNC_1(VAR_6) def FUNC_3() -> str | None: VAR_23 = g.ledger.fava_options.language if VAR_23 is not None: return VAR_23 return request.accept_languages.best_match(["en"] + LANGUAGES) VAR_7 = Babel(VAR_1) VAR_7.localeselector(FUNC_3) for function in template_filters.FILTERS: VAR_1.add_template_filter(function) # type: ignore VAR_1.add_template_filter(serialise) @VAR_1.url_defaults def FUNC_4(VAR_8: str, VAR_9: dict[str, str | None]) -> None: if "bfile" not in VAR_9 and VAR_1.url_map.is_endpoint_expecting( VAR_8, "bfile" ): VAR_9["bfile"] = g.beancount_file_slug if VAR_8 in ["static", "index"]: return for VAR_16 in ["conversion", "interval", "account", "filter", "time"]: if VAR_16 not in VAR_9: values[VAR_16] = request.args.get(VAR_16) def FUNC_5(VAR_10: str) -> str: VAR_24 = VAR_0 / VAR_10 try: VAR_39 = int(VAR_24.stat().st_mtime) except FileNotFoundError: VAR_39 = 0 return FUNC_6("static", VAR_10=filename, VAR_39=mtime) VAR_11 = functools.lru_cache(2048)(flask.url_for) def FUNC_6(VAR_8: str, **VAR_9: str | int) -> str: FUNC_4(VAR_8, VAR_9) return VAR_11(VAR_8, **VAR_9) def FUNC_7(**VAR_12: str) -> str: if g.ledger.fava_options.use_external_editor: return ( f"beancount://{VAR_12.get('file_path')}" + f"?lineno={VAR_12.get('line', 1)}" ) return FUNC_6("report", VAR_19="editor", **VAR_12) def FUNC_8() -> Any: return get_translations()._catalog VAR_1.add_template_global(FUNC_5, "static_url") VAR_1.add_template_global(datetime.date.today, "today") VAR_1.add_template_global(FUNC_6, "url_for") VAR_1.add_template_global(FUNC_7, "url_for_source") VAR_1.add_template_global(FUNC_8, "translations") @VAR_1.context_processor def FUNC_9() -> dict[str, FavaLedger]: return dict(VAR_5=g.ledger) @VAR_1.before_request def FUNC_10() -> None: if request.endpoint in ("json_api.get_changed", "json_api.get_errors"): return VAR_5 = getattr(g, "ledger", None) if VAR_5: if request.blueprint != "json_api": VAR_5.changed() g.filtered = VAR_5.get_filtered( FUNC_15=request.args.get("account"), filter=request.args.get("filter"), time=request.args.get("time"), ) @VAR_1.after_request def FUNC_11( VAR_13: werkzeug.wrappers.Response, ) -> werkzeug.wrappers.Response: if VAR_1.config.get("INCOGNITO") and VAR_13.content_type.startswith( "text/html" ): VAR_40 = ( request.endpoint == "report" and request.view_args is not None and request.view_args["report_name"] == "editor" ) if not VAR_40: VAR_44 = VAR_13.get_data(as_text=True) VAR_13.set_data(replace_numbers(VAR_44)) return VAR_13 @VAR_1.url_value_preprocessor def FUNC_12(VAR_14: str | None, VAR_9: dict[str, str] | None) -> None: g.beancount_file_slug = VAR_9.pop("bfile", None) if VAR_9 else None with VAR_4: if not VAR_1.config.get("LEDGERS"): FUNC_2() if g.beancount_file_slug: if g.beancount_file_slug not in VAR_1.config["LEDGERS"]: if not any( g.beancount_file_slug == FUNC_0(VAR_5) for VAR_5 in VAR_1.config["LEDGERS"].values() ): abort(404) FUNC_1(VAR_1.config["LEDGERS"].values()) g.ledger = VAR_1.config["LEDGERS"][g.beancount_file_slug] g.conversion = request.args.get("conversion", "at_cost") g.interval = Interval.get(request.args.get("interval", "month")) @VAR_1.errorhandler(FavaAPIException) def FUNC_13(VAR_15: FavaAPIException) -> str: return render_template( "_layout.html", page_title="Error", VAR_43=VAR_15.message ) @VAR_1.route("/") @VAR_1.route("/<bfile>/") def FUNC_14() -> werkzeug.wrappers.Response: if not g.beancount_file_slug: g.beancount_file_slug = next(iter(VAR_1.config["LEDGERS"])) VAR_25 = FUNC_6("index") VAR_26 = VAR_1.config["LEDGERS"][ g.beancount_file_slug ].fava_options.default_page return redirect(f"{VAR_25}{VAR_26}") @VAR_1.route("/<bfile>/FUNC_15/<VAR_16>/") @VAR_1.route("/<bfile>/FUNC_15/<VAR_16>/<VAR_17>/") def FUNC_15(VAR_16: str, VAR_17: str = "journal") -> str: if VAR_17 in ["journal", "balances", "changes"]: return render_template( "account.html", account_name=VAR_16, VAR_17=subreport ) return abort(404) @VAR_1.route("/<bfile>/FUNC_16/", methods=["GET"]) def FUNC_16() -> Response: VAR_10 = request.args.get("filename") if VAR_10 is None: return abort(404) if is_document_or_import_file(VAR_10, g.ledger): return send_file_inline(VAR_10) return abort(404) @VAR_1.route("/<bfile>/FUNC_17/", methods=["GET"]) def FUNC_17() -> Response: VAR_27 = request.args.get("entry_hash", "") VAR_28 = request.args.get("key", "") VAR_29 = g.ledger.statement_path(VAR_27, VAR_28) return send_file_inline(VAR_29) @VAR_1.route("/<bfile>/holdings/by_<VAR_18>/") def FUNC_18(VAR_18: str) -> str: if VAR_18 in ["account", "currency", "cost_currency"]: return render_template( "_layout.html", active_page="holdings", VAR_18=aggregation_key, ) return abort(404) @VAR_1.route("/<bfile>/<VAR_19>/") def FUNC_19(VAR_19: str) -> str: if VAR_19 in VAR_3: return render_template("_layout.html", active_page=VAR_19) return abort(404) @VAR_1.route("/<bfile>/VAR_42/<VAR_19>/") def FUNC_20(VAR_19: str) -> str: try: VAR_41, VAR_42 = g.ledger.extensions.template_and_extension( VAR_19 ) VAR_43 = render_template_string(VAR_41, VAR_42=extension) return render_template( "_layout.html", VAR_43=content, page_title=VAR_42.report_title ) except LookupError: return abort(404) @VAR_1.route("/<bfile>/download-query/query_result.<VAR_20>") def FUNC_21(VAR_20: str) -> Any: VAR_16, VAR_30 = g.ledger.query_shell.query_to_file( g.filtered.entries, request.args.get("query_string", ""), VAR_20 ) VAR_10 = f"{secure_filename(VAR_16.strip())}.{VAR_20}" return send_file(VAR_30, as_attachment=True, download_name=VAR_10) @VAR_1.route("/<bfile>/download-journal/") def FUNC_22() -> Any: VAR_31 = datetime.datetime.now().replace(microsecond=0) VAR_10 = f"journal_{VAR_31.isoformat()}.beancount" VAR_30 = BytesIO(bytes(render_template("beancount_file"), "utf8")) return send_file(VAR_30, as_attachment=True, download_name=VAR_10) @VAR_1.route("/<bfile>/help/", defaults={"page_slug": "_index"}) @VAR_1.route("/<bfile>/help/<string:VAR_21>") def FUNC_23(VAR_21: str) -> str: if VAR_21 not in HELP_PAGES: abort(404) VAR_32 = markdown2.markdown_path( (resource_path("help") / (VAR_21 + ".md")), extras=["fenced-code-blocks", "tables", "header-ids"], ) return render_template( "_layout.html", active_page="help", VAR_21=page_slug, help_html=Markup( render_template_string( VAR_32, beancount_version=beancount_version, fava_version=fava_version, ) ), HELP_PAGES=HELP_PAGES, ) @VAR_1.route("/jump") def FUNC_24() -> werkzeug.wrappers.Response: VAR_33 = werkzeug.urls.url_parse(request.referrer) VAR_34 = VAR_33.decode_query() for VAR_28, VAR_9 in request.args.lists(): if VAR_9 == [""]: try: del VAR_34[VAR_28] except KeyError: pass else: VAR_34.setlist(VAR_28, VAR_9) VAR_35 = VAR_33.replace( query=werkzeug.urls.url_encode(VAR_34, sort=True) ) return redirect(werkzeug.urls.url_unparse(VAR_35))
[ 2, 5, 9, 12, 15, 21, 39, 58, 59, 68, 75, 78, 95, 96, 98, 99, 104, 105, 114, 115, 118, 125, 126, 129, 138, 139, 142, 143, 147, 148, 160, 161, 170, 171, 173, 174, 179, 180, 189, 190, 193, 195, 196, 202, 203, 208, 209, 216, 219, 225, 226, 244, 245, 259, 264, 265, 272, 273, 285, 286, 296, 297, 307, 308, 316, 317, 328, 329, 336, 337, 351, 352, 359, 362, 363, 371, 372, 394, 395, 399, 402, 406, 418, 423, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 101, 107, 117, 118, 119, 120, 128, 129, 130, 131, 132, 133, 163, 176, 182, 192, 206, 231, 268, 277, 290, 300, 311, 320, 332, 340, 355, 366, 376, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407 ]
[ 2, 5, 9, 12, 15, 21, 40, 59, 60, 69, 76, 79, 96, 97, 99, 100, 105, 106, 115, 116, 119, 126, 127, 130, 139, 140, 143, 144, 148, 149, 161, 162, 171, 172, 174, 175, 180, 181, 190, 191, 194, 196, 197, 203, 204, 209, 210, 217, 220, 226, 227, 245, 246, 260, 265, 266, 273, 274, 286, 287, 297, 298, 308, 309, 317, 318, 329, 330, 337, 338, 352, 353, 360, 363, 364, 372, 373, 397, 398, 402, 405, 409, 421, 426, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 102, 108, 118, 119, 120, 121, 129, 130, 131, 132, 133, 134, 164, 177, 183, 193, 207, 232, 269, 278, 291, 301, 312, 321, 333, 341, 356, 367, 377, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410 ]
1CWE-79
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CherryMusic - a standalone music server # Copyright (c) 2012 - 2015 Tom Wallroth & Tilman Boerner # # Project page: # http://fomori.org/cherrymusic/ # Sources on github: # http://github.com/devsnd/cherrymusic/ # # CherryMusic is based on # jPlayer (GPL/MIT license) http://www.jplayer.org/ # CherryPy (BSD license) http://www.cherrypy.org/ # # licensed under GNU GPL version 3 (or later) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # """This class provides the api to talk to the client. It will then call the cherrymodel, to get the requested information""" import os # shouldn't have to list any folder in the future! import json import cherrypy import codecs import sys try: from urllib.parse import unquote except ImportError: from backport.urllib.parse import unquote try: from urllib import parse except ImportError: from backport.urllib import parse import audiotranscode from tinytag import TinyTag from cherrymusicserver import userdb from cherrymusicserver import log from cherrymusicserver import albumartfetcher from cherrymusicserver import service from cherrymusicserver.pathprovider import readRes from cherrymusicserver.pathprovider import albumArtFilePath import cherrymusicserver as cherry import cherrymusicserver.metainfo as metainfo from cherrymusicserver.util import Performance, MemoryZipFile from cherrymusicserver.ext import zipstream import time debug = True @service.user(model='cherrymodel', playlistdb='playlist', useroptions='useroptions', userdb='users') class HTTPHandler(object): def __init__(self, config): self.config = config template_main = 'res/dist/main.html' template_login = 'res/login.html' template_firstrun = 'res/firstrun.html' self.mainpage = readRes(template_main) self.loginpage = readRes(template_login) self.firstrunpage = readRes(template_firstrun) self.handlers = { 'search': self.api_search, 'rememberplaylist': self.api_rememberplaylist, 'saveplaylist': self.api_saveplaylist, 'loadplaylist': self.api_loadplaylist, 'generaterandomplaylist': self.api_generaterandomplaylist, 'deleteplaylist': self.api_deleteplaylist, 'getmotd': self.api_getmotd, 'restoreplaylist': self.api_restoreplaylist, 'getplayables': self.api_getplayables, 'getuserlist': self.api_getuserlist, 'adduser': self.api_adduser, 'userdelete': self.api_userdelete, 'userchangepassword': self.api_userchangepassword, 'showplaylists': self.api_showplaylists, 'logout': self.api_logout, 'downloadpls': self.api_downloadpls, 'downloadm3u': self.api_downloadm3u, 'getsonginfo': self.api_getsonginfo, 'getencoders': self.api_getencoders, 'getdecoders': self.api_getdecoders, 'transcodingenabled': self.api_transcodingenabled, 'updatedb': self.api_updatedb, 'getconfiguration': self.api_getconfiguration, 'compactlistdir': self.api_compactlistdir, 'listdir': self.api_listdir, 'fetchalbumart': self.api_fetchalbumart, 'fetchalbumarturls': self.api_fetchalbumarturls, 'albumart_set': self.api_albumart_set, 'heartbeat': self.api_heartbeat, 'getuseroptions': self.api_getuseroptions, 'setuseroption': self.api_setuseroption, 'changeplaylist': self.api_changeplaylist, 'downloadcheck': self.api_downloadcheck, 'setuseroptionfor': self.api_setuseroptionfor, } def issecure(self, url): return parse.urlparse(url).scheme == 'https' def getBaseUrl(self, redirect_unencrypted=False): ipAndPort = parse.urlparse(cherrypy.url()).netloc is_secure_connection = self.issecure(cherrypy.url()) ssl_enabled = cherry.config['server.ssl_enabled'] if ssl_enabled and not is_secure_connection: log.d(_('Not secure, redirecting...')) ip = ipAndPort[:ipAndPort.rindex(':')] url = 'https://' + ip + ':' + str(cherry.config['server.ssl_port']) if redirect_unencrypted: raise cherrypy.HTTPRedirect(url, 302) else: url = 'http://' + ipAndPort return url def index(self, *args, **kwargs): self.getBaseUrl(redirect_unencrypted=True) firstrun = 0 == self.userdb.getUserCount() show_page = self.mainpage #generated main.html from devel.html if 'devel' in kwargs: #reload pages everytime in devel mode show_page = readRes('res/devel.html') self.loginpage = readRes('res/login.html') self.firstrunpage = readRes('res/firstrun.html') if 'login' in kwargs: username = kwargs.get('username', '') password = kwargs.get('password', '') login_action = kwargs.get('login', '') if login_action == 'login': self.session_auth(username, password) if cherrypy.session['username']: username = cherrypy.session['username'] log.i(_('user {name} just logged in.').format(name=username)) elif login_action == 'create admin user': if firstrun: if username.strip() and password.strip(): self.userdb.addUser(username, password, True) self.session_auth(username, password) return show_page else: return "No, you can't." if firstrun: return self.firstrunpage else: if self.isAuthorized(): return show_page else: return self.loginpage index.exposed = True def isAuthorized(self): try: sessionUsername = cherrypy.session.get('username', None) sessionUserId = cherrypy.session.get('userid', -1) nameById = self.userdb.getNameById(sessionUserId) except (UnicodeDecodeError, ValueError) as e: # workaround for python2/python3 jump, filed bug in cherrypy # https://bitbucket.org/cherrypy/cherrypy/issue/1216/sessions-python2-3-compability-unsupported log.w(_(''' Dropping all sessions! Try not to change between python 2 and 3, everybody has to relogin now.''')) cherrypy.session.delete() sessionUsername = None if sessionUsername is None: if self.autoLoginActive(): cherrypy.session['username'] = self.userdb.getNameById(1) cherrypy.session['userid'] = 1 cherrypy.session['admin'] = True return True else: return False elif sessionUsername != nameById: self.api_logout(value=None) return False return True def autoLoginActive(self): is_loopback = cherrypy.request.remote.ip in ('127.0.0.1', '::1') if is_loopback and cherry.config['server.localhost_auto_login']: return True return False def session_auth(self, username, password): user = self.userdb.auth(username, password) allow_remote = cherry.config['server.permit_remote_admin_login'] is_loopback = cherrypy.request.remote.ip in ('127.0.0.1', '::1') if not is_loopback and user.isadmin and not allow_remote: log.i(_('Rejected remote admin login from user: {name}').format(name=user.name)) user = userdb.User.nobody() cherrypy.session['username'] = user.name cherrypy.session['userid'] = user.uid cherrypy.session['admin'] = user.isadmin def getUserId(self): try: return cherrypy.session['userid'] except KeyError: cherrypy.lib.sessions.expire() cherrypy.HTTPRedirect(cherrypy.url(), 302) return '' def trans(self, newformat, *path, **params): ''' Transcodes the track given as ``path`` into ``newformat``. Streams the response of the corresponding ``audiotranscode.AudioTranscode().transcodeStream()`` call. params: bitrate: int for kbps. None or < 1 for default ''' if not self.isAuthorized(): raise cherrypy.HTTPRedirect(self.getBaseUrl(), 302) cherrypy.session.release_lock() if cherry.config['media.transcode'] and path: # bitrate bitrate = params.pop('bitrate', None) or None # catch empty strings if bitrate: try: bitrate = max(0, int(bitrate)) or None # None if < 1 except (TypeError, ValueError): raise cherrypy.HTTPError(400, "Bad query: " "bitrate ({0!r}) must be an integer".format(str(bitrate))) # path path = os.path.sep.join(path) if sys.version_info < (3, 0): # workaround for #327 (cherrypy issue) path = path.decode('utf-8') # make it work with non-ascii else: path = codecs.decode(codecs.encode(path, 'latin1'), 'utf-8') fullpath = os.path.join(cherry.config['media.basedir'], path) starttime = int(params.pop('starttime', 0)) transcoder = audiotranscode.AudioTranscode() mimetype = audiotranscode.mime_type(newformat) cherrypy.response.headers["Content-Type"] = mimetype try: return transcoder.transcode_stream(fullpath, newformat, bitrate=bitrate, starttime=starttime) except (audiotranscode.TranscodeError, IOError) as e: raise cherrypy.HTTPError(404, e.value) trans.exposed = True trans._cp_config = {'response.stream': True} def api(self, *args, **kwargs): """calls the appropriate handler from the handlers dict, if available. handlers having noauth set to true do not need authentification to work. """ #check action action = args[0] if args else '' if not action in self.handlers: return "Error: no such action. '%s'" % action #authorize if not explicitly deactivated handler = self.handlers[action] needsAuth = not ('noauth' in dir(handler) and handler.noauth) if needsAuth and not self.isAuthorized(): raise cherrypy.HTTPError(401, 'Unauthorized') handler_args = {} if 'data' in kwargs: handler_args = json.loads(kwargs['data']) is_binary = ('binary' in dir(handler) and handler.binary) if is_binary: return handler(**handler_args) else: return json.dumps({'data': handler(**handler_args)}) api.exposed = True def download_check_files(self, filelist): # only admins and allowed users may download if not cherrypy.session['admin']: uo = self.useroptions.forUser(self.getUserId()) if not uo.getOptionValue('media.may_download'): return 'not_permitted' # make sure nobody tries to escape from basedir for f in filelist: if '/../' in f: return 'invalid_file' # make sure all files are smaller than maximum download size size_limit = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(filelist, size_limit): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e) def api_downloadcheck(self, filelist): status = self.download_check_files(filelist) if status == 'not_permitted': return """You are not allowed to download files.""" elif status == 'invalid_file': return "Error: invalid filename found in {list}".format(list=filelist) elif status == 'too_big': size_limit = cherry.config['media.maximum_download_size'] return """Can't download: Playlist is bigger than {maxsize} mB. The server administrator can change this configuration. """.format(maxsize=size_limit/1024/1024) elif status == 'ok': return status else: message = "Error status check for download: {status!r}".format(status=status) log.e(message) return message def download(self, value): if not self.isAuthorized(): raise cherrypy.HTTPError(401, 'Unauthorized') filelist = [filepath for filepath in json.loads(unquote(value))] dlstatus = self.download_check_files(filelist) if dlstatus == 'ok': _save_and_release_session() zipmime = 'application/x-zip-compressed' cherrypy.response.headers["Content-Type"] = zipmime zipname = 'attachment; filename="music.zip"' cherrypy.response.headers['Content-Disposition'] = zipname basedir = cherry.config['media.basedir'] fullpath_filelist = [os.path.join(basedir, f) for f in filelist] return zipstream.ZipStream(fullpath_filelist) else: return dlstatus download.exposed = True download._cp_config = {'response.stream': True} def api_getuseroptions(self): uo = self.useroptions.forUser(self.getUserId()) uco = uo.getChangableOptions() if cherrypy.session['admin']: uco['media'].update({'may_download': True}) else: uco['media'].update({'may_download': uo.getOptionValue('media.may_download')}) return uco def api_heartbeat(self): uo = self.useroptions.forUser(self.getUserId()) uo.setOption('last_time_online', int(time.time())) def api_setuseroption(self, optionkey, optionval): uo = self.useroptions.forUser(self.getUserId()) uo.setOption(optionkey, optionval) return "success" def api_setuseroptionfor(self, userid, optionkey, optionval): if cherrypy.session['admin']: uo = self.useroptions.forUser(userid) uo.setOption(optionkey, optionval) return "success" else: return "error: not permitted. Only admins can change other users options" def api_fetchalbumarturls(self, searchterm): if not cherrypy.session['admin']: raise cherrypy.HTTPError(401, 'Unauthorized') _save_and_release_session() fetcher = albumartfetcher.AlbumArtFetcher() imgurls = fetcher.fetchurls(searchterm) # show no more than 10 images return imgurls[:min(len(imgurls), 10)] def api_albumart_set(self, directory, imageurl): if not cherrypy.session['admin']: raise cherrypy.HTTPError(401, 'Unauthorized') b64imgpath = albumArtFilePath(directory) fetcher = albumartfetcher.AlbumArtFetcher() data, header = fetcher.retrieveData(imageurl) self.albumartcache_save(b64imgpath, data) def api_fetchalbumart(self, directory): _save_and_release_session() default_folder_image = "../res/img/folder.png" log.i('Fetching album art for: %s' % directory) filepath = os.path.join(cherry.config['media.basedir'], directory) if os.path.isfile(filepath): # if the given path is a file, try to get the image from ID3 tag = TinyTag.get(filepath, image=True) image_data = tag.get_image() if image_data: log.d('Image found in tag.') header = {'Content-Type': 'image/jpg', 'Content-Length': len(image_data)} cherrypy.response.headers.update(header) return image_data else: # if the file does not contain an image, display the image of the # parent directory directory = os.path.dirname(directory) #try getting a cached album art image b64imgpath = albumArtFilePath(directory) img_data = self.albumartcache_load(b64imgpath) if img_data: cherrypy.response.headers["Content-Length"] = len(img_data) return img_data #try getting album art inside local folder fetcher = albumartfetcher.AlbumArtFetcher() localpath = os.path.join(cherry.config['media.basedir'], directory) header, data, resized = fetcher.fetchLocal(localpath) if header: if resized: #cache resized image for next time self.albumartcache_save(b64imgpath, data) cherrypy.response.headers.update(header) return data elif cherry.config['media.fetch_album_art']: #fetch album art from online source try: foldername = os.path.basename(directory) keywords = foldername log.i(_("Fetching album art for keywords {keywords!r}").format(keywords=keywords)) header, data = fetcher.fetch(keywords) if header: cherrypy.response.headers.update(header) self.albumartcache_save(b64imgpath, data) return data else: # albumart fetcher failed, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) except: # albumart fetcher threw exception, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) else: # no local album art found, online fetching deactivated, show default raise cherrypy.HTTPRedirect(default_folder_image, 302) api_fetchalbumart.noauth = True api_fetchalbumart.binary = True def albumartcache_load(self, imgb64path): if os.path.exists(imgb64path): with open(imgb64path, 'rb') as f: return f.read() def albumartcache_save(self, path, data): with open(path, 'wb') as f: f.write(data) def api_compactlistdir(self, directory, filterstr=None): try: files_to_list = self.model.listdir(directory, filterstr) except ValueError: raise cherrypy.HTTPError(400, 'Bad Request') return [entry.to_dict() for entry in files_to_list] def api_listdir(self, directory): try: return [entry.to_dict() for entry in self.model.listdir(directory)] except ValueError: raise cherrypy.HTTPError(400, 'Bad Request') def api_search(self, searchstring): if not searchstring.strip(): jsonresults = '[]' else: with Performance(_('processing whole search request')): searchresults = self.model.search(searchstring.strip()) with Performance(_('rendering search results as json')): jsonresults = [entry.to_dict() for entry in searchresults] return jsonresults def api_rememberplaylist(self, playlist): cherrypy.session['playlist'] = playlist def api_saveplaylist(self, playlist, public, playlistname, overwrite=False): res = self.playlistdb.savePlaylist( userid=self.getUserId(), public=1 if public else 0, playlist=playlist, playlisttitle=playlistname, overwrite=overwrite) if res == "success": return res else: raise cherrypy.HTTPError(400, res) def api_deleteplaylist(self, playlistid): res = self.playlistdb.deletePlaylist(playlistid, self.getUserId(), override_owner=False) if res == "success": return res else: # not the ideal status code but we don't know the actual # cause without parsing res raise cherrypy.HTTPError(400, res) def api_loadplaylist(self, playlistid): return [entry.to_dict() for entry in self.playlistdb.loadPlaylist( playlistid=playlistid, userid=self.getUserId() )] def api_generaterandomplaylist(self): return [entry.to_dict() for entry in self.model.randomMusicEntries(50)] def api_changeplaylist(self, plid, attribute, value): if attribute == 'public': is_valid = type(value) == bool and type(plid) == int if is_valid: return self.playlistdb.setPublic(userid=self.getUserId(), plid=plid, public=value) def api_getmotd(self): if cherrypy.session['admin'] and cherry.config['general.update_notification']: _save_and_release_session() new_versions = self.model.check_for_updates() if new_versions: newest_version = new_versions[0]['version'] features = [] fixes = [] for version in new_versions: for update in version['features']: if update.startswith('FEATURE:'): features.append(update[len('FEATURE:'):]) elif update.startswith('FIX:'): fixes.append(update[len('FIX:'):]) elif update.startswith('FIXED:'): fixes.append(update[len('FIXED:'):]) retdata = {'type': 'update', 'data': {}} retdata['data']['version'] = newest_version retdata['data']['features'] = features retdata['data']['fixes'] = fixes return retdata return {'type': 'wisdom', 'data': self.model.motd()} def api_restoreplaylist(self): session_playlist = cherrypy.session.get('playlist', []) return session_playlist def api_getplayables(self): """DEPRECATED""" return json.dumps(cherry.config['media.playable']) def api_getuserlist(self): if cherrypy.session['admin']: userlist = self.userdb.getUserList() for user in userlist: if user['id'] == cherrypy.session['userid']: user['deletable'] = False user_options = self.useroptions.forUser(user['id']) t = user_options.getOptionValue('last_time_online') may_download = user_options.getOptionValue('media.may_download') user['last_time_online'] = t user['may_download'] = may_download sortfunc = lambda user: user['last_time_online'] userlist = sorted(userlist, key=sortfunc, reverse=True) return json.dumps({'time': int(time.time()), 'userlist': userlist}) else: return json.dumps({'time': 0, 'userlist': []}) def api_adduser(self, username, password, isadmin): if cherrypy.session['admin']: if self.userdb.addUser(username, password, isadmin): return 'added new user: %s' % username else: return 'error, cannot add new user!' % username else: return "You didn't think that would work, did you?" def api_userchangepassword(self, oldpassword, newpassword, username=''): isself = username == '' if isself: username = cherrypy.session['username'] authed_user = self.userdb.auth(username, oldpassword) is_authenticated = userdb.User.nobody() != authed_user if not is_authenticated: raise cherrypy.HTTPError(403, "Forbidden") if isself or cherrypy.session['admin']: return self.userdb.changePassword(username, newpassword) else: raise cherrypy.HTTPError(403, "Forbidden") def api_userdelete(self, userid): is_self = cherrypy.session['userid'] == userid if cherrypy.session['admin'] and not is_self: deleted = self.userdb.deleteUser(userid) return 'success' if deleted else 'failed' else: return "You didn't think that would work, did you?" def api_showplaylists(self, sortby="created", filterby=''): playlists = self.playlistdb.showPlaylists(self.getUserId(), filterby) curr_time = int(time.time()) is_reverse = False #translate userids to usernames: for pl in playlists: pl['username'] = self.userdb.getNameById(pl['userid']) pl['type'] = 'playlist' pl['age'] = curr_time - pl['created'] if sortby[0] == '-': is_reverse = True sortby = sortby[1:] if not sortby in ('username', 'age', 'title', 'default'): sortby = 'created' if sortby == 'default': sortby = 'age' is_reverse = False playlists = sorted(playlists, key=lambda x: x[sortby], reverse = is_reverse) return playlists def api_logout(self): cherrypy.lib.sessions.expire() api_logout.no_auth = True def api_downloadpls(self, plid, hostaddr): userid = self.getUserId() pls = self.playlistdb.createPLS(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) if pls and name: return self.serve_string_as_file(pls, name+'.pls') api_downloadpls.binary = True def api_downloadm3u(self, plid, hostaddr): userid = self.getUserId() pls = self.playlistdb.createM3U(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) if pls and name: return self.serve_string_as_file(pls, name+'.m3u') api_downloadm3u.binary = True def export_playlists(self, format, all=False, hostaddr=''): userid = self.getUserId() if not userid: raise cherrypy.HTTPError(401, _("Please log in")) hostaddr = (hostaddr.strip().rstrip('/') + cherry.config['server.rootpath']).rstrip('/') format = format.lower() if format == 'm3u': filemaker = self.playlistdb.createM3U elif format == 'pls': filemaker = self.playlistdb.createPLS else: raise cherrypy.HTTPError(400, _('Unknown playlist format: {format!r}').format(format=format)) playlists = self.playlistdb.showPlaylists(userid, include_public=all) if not playlists: raise cherrypy.HTTPError(404, _('No playlists found')) with MemoryZipFile() as zip: for pl in playlists: plid = pl['plid'] plstr = filemaker(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) + '.' + format if not pl['owner']: username = self.userdb.getNameById(pl['userid']) name = username + '/' + name zip.writestr(name, plstr) zipmime = 'application/x-zip-compressed' zipname = 'attachment; filename="playlists.zip"' cherrypy.response.headers["Content-Type"] = zipmime cherrypy.response.headers['Content-Disposition'] = zipname return zip.getbytes() export_playlists.exposed = True def api_getsonginfo(self, path): basedir = cherry.config['media.basedir'] abspath = os.path.join(basedir, path) return json.dumps(metainfo.getSongInfo(abspath).dict()) def api_getencoders(self): return json.dumps(audiotranscode.getEncoders()) def api_getdecoders(self): return json.dumps(audiotranscode.getDecoders()) def api_transcodingenabled(self): return json.dumps(cherry.config['media.transcode']) def api_updatedb(self): self.model.updateLibrary() return 'success' def api_getconfiguration(self): clientconfigkeys = { 'transcodingenabled': cherry.config['media.transcode'], 'fetchalbumart': cherry.config['media.fetch_album_art'], 'isadmin': cherrypy.session['admin'], 'username': cherrypy.session['username'], 'servepath': 'serve/', 'transcodepath': 'trans/', 'auto_login': self.autoLoginActive(), 'version': cherry.REPO_VERSION or cherry.VERSION, } if cherry.config['media.transcode']: decoders = list(self.model.transcoder.available_decoder_formats()) clientconfigkeys['getdecoders'] = decoders encoders = list(self.model.transcoder.available_encoder_formats()) clientconfigkeys['getencoders'] = encoders else: clientconfigkeys['getdecoders'] = [] clientconfigkeys['getencoders'] = [] return clientconfigkeys def serve_string_as_file(self, string, filename): content_disposition = 'attachment; filename="'+filename+'"' cherrypy.response.headers["Content-Type"] = "application/x-download" cherrypy.response.headers["Content-Disposition"] = content_disposition return codecs.encode(string, "UTF-8") def _save_and_release_session(): """ workaround to cleanly release FileSessions in Cherrypy >= 3.3 From https://github.com/devsnd/cherrymusic/issues/483: > CherryPy >=3.3.0 (up to current version, 3.6) makes it impossible to > explicitly release FileSession locks, because: > 1. FileSession.save() asserts that the session is locked; and > 2. _cptools.SessionTool always adds a hook to call sessions.save > before the response is finalized. > If we still want to release the session in a controller, I guess the > best way to work around this is to remove the hook before the > controller returns: """ cherrypy.session.save() hooks = cherrypy.serving.request.hooks['before_finalize'] forbidden = cherrypy.lib.sessions.save hooks[:] = [h for h in hooks if h.callback is not forbidden] # there's likely only one hook, since a 2nd call to save would always fail; # but let's be safe, and block all calls to save :)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CherryMusic - a standalone music server # Copyright (c) 2012 - 2015 Tom Wallroth & Tilman Boerner # # Project page: # http://fomori.org/cherrymusic/ # Sources on github: # http://github.com/devsnd/cherrymusic/ # # CherryMusic is based on # jPlayer (GPL/MIT license) http://www.jplayer.org/ # CherryPy (BSD license) http://www.cherrypy.org/ # # licensed under GNU GPL version 3 (or later) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # """This class provides the api to talk to the client. It will then call the cherrymodel, to get the requested information""" import os # shouldn't have to list any folder in the future! import json import cherrypy import codecs import sys try: from urllib.parse import unquote except ImportError: from backport.urllib.parse import unquote try: from urllib import parse except ImportError: from backport.urllib import parse import audiotranscode from tinytag import TinyTag from cherrymusicserver import userdb from cherrymusicserver import log from cherrymusicserver import albumartfetcher from cherrymusicserver import service from cherrymusicserver.pathprovider import readRes from cherrymusicserver.pathprovider import albumArtFilePath import cherrymusicserver as cherry import cherrymusicserver.metainfo as metainfo from cherrymusicserver.util import Performance, MemoryZipFile from cherrymusicserver.ext import zipstream import time debug = True @service.user(model='cherrymodel', playlistdb='playlist', useroptions='useroptions', userdb='users') class HTTPHandler(object): def __init__(self, config): self.config = config template_main = 'res/dist/main.html' template_login = 'res/login.html' template_firstrun = 'res/firstrun.html' self.mainpage = readRes(template_main) self.loginpage = readRes(template_login) self.firstrunpage = readRes(template_firstrun) self.handlers = { 'search': self.api_search, 'rememberplaylist': self.api_rememberplaylist, 'saveplaylist': self.api_saveplaylist, 'loadplaylist': self.api_loadplaylist, 'generaterandomplaylist': self.api_generaterandomplaylist, 'deleteplaylist': self.api_deleteplaylist, 'getmotd': self.api_getmotd, 'restoreplaylist': self.api_restoreplaylist, 'getplayables': self.api_getplayables, 'getuserlist': self.api_getuserlist, 'adduser': self.api_adduser, 'userdelete': self.api_userdelete, 'userchangepassword': self.api_userchangepassword, 'showplaylists': self.api_showplaylists, 'logout': self.api_logout, 'downloadpls': self.api_downloadpls, 'downloadm3u': self.api_downloadm3u, 'getsonginfo': self.api_getsonginfo, 'getencoders': self.api_getencoders, 'getdecoders': self.api_getdecoders, 'transcodingenabled': self.api_transcodingenabled, 'updatedb': self.api_updatedb, 'getconfiguration': self.api_getconfiguration, 'compactlistdir': self.api_compactlistdir, 'listdir': self.api_listdir, 'fetchalbumart': self.api_fetchalbumart, 'fetchalbumarturls': self.api_fetchalbumarturls, 'albumart_set': self.api_albumart_set, 'heartbeat': self.api_heartbeat, 'getuseroptions': self.api_getuseroptions, 'setuseroption': self.api_setuseroption, 'changeplaylist': self.api_changeplaylist, 'downloadcheck': self.api_downloadcheck, 'setuseroptionfor': self.api_setuseroptionfor, } def issecure(self, url): return parse.urlparse(url).scheme == 'https' def getBaseUrl(self, redirect_unencrypted=False): ipAndPort = parse.urlparse(cherrypy.url()).netloc is_secure_connection = self.issecure(cherrypy.url()) ssl_enabled = cherry.config['server.ssl_enabled'] if ssl_enabled and not is_secure_connection: log.d(_('Not secure, redirecting...')) ip = ipAndPort[:ipAndPort.rindex(':')] url = 'https://' + ip + ':' + str(cherry.config['server.ssl_port']) if redirect_unencrypted: raise cherrypy.HTTPRedirect(url, 302) else: url = 'http://' + ipAndPort return url def index(self, *args, **kwargs): self.getBaseUrl(redirect_unencrypted=True) firstrun = 0 == self.userdb.getUserCount() show_page = self.mainpage #generated main.html from devel.html if 'devel' in kwargs: #reload pages everytime in devel mode show_page = readRes('res/devel.html') self.loginpage = readRes('res/login.html') self.firstrunpage = readRes('res/firstrun.html') if 'login' in kwargs: username = kwargs.get('username', '') password = kwargs.get('password', '') login_action = kwargs.get('login', '') if login_action == 'login': self.session_auth(username, password) if cherrypy.session['username']: username = cherrypy.session['username'] log.i(_('user {name} just logged in.').format(name=username)) elif login_action == 'create admin user': if firstrun: if username.strip() and password.strip(): self.userdb.addUser(username, password, True) self.session_auth(username, password) return show_page else: return "No, you can't." if firstrun: return self.firstrunpage else: if self.isAuthorized(): return show_page else: return self.loginpage index.exposed = True def isAuthorized(self): try: sessionUsername = cherrypy.session.get('username', None) sessionUserId = cherrypy.session.get('userid', -1) nameById = self.userdb.getNameById(sessionUserId) except (UnicodeDecodeError, ValueError) as e: # workaround for python2/python3 jump, filed bug in cherrypy # https://bitbucket.org/cherrypy/cherrypy/issue/1216/sessions-python2-3-compability-unsupported log.w(_(''' Dropping all sessions! Try not to change between python 2 and 3, everybody has to relogin now.''')) cherrypy.session.delete() sessionUsername = None if sessionUsername is None: if self.autoLoginActive(): cherrypy.session['username'] = self.userdb.getNameById(1) cherrypy.session['userid'] = 1 cherrypy.session['admin'] = True return True else: return False elif sessionUsername != nameById: self.api_logout(value=None) return False return True def autoLoginActive(self): is_loopback = cherrypy.request.remote.ip in ('127.0.0.1', '::1') if is_loopback and cherry.config['server.localhost_auto_login']: return True return False def session_auth(self, username, password): user = self.userdb.auth(username, password) allow_remote = cherry.config['server.permit_remote_admin_login'] is_loopback = cherrypy.request.remote.ip in ('127.0.0.1', '::1') if not is_loopback and user.isadmin and not allow_remote: log.i(_('Rejected remote admin login from user: {name}').format(name=user.name)) user = userdb.User.nobody() cherrypy.session['username'] = user.name cherrypy.session['userid'] = user.uid cherrypy.session['admin'] = user.isadmin def getUserId(self): try: return cherrypy.session['userid'] except KeyError: cherrypy.lib.sessions.expire() cherrypy.HTTPRedirect(cherrypy.url(), 302) return '' def trans(self, newformat, *path, **params): ''' Transcodes the track given as ``path`` into ``newformat``. Streams the response of the corresponding ``audiotranscode.AudioTranscode().transcodeStream()`` call. params: bitrate: int for kbps. None or < 1 for default ''' if not self.isAuthorized(): raise cherrypy.HTTPRedirect(self.getBaseUrl(), 302) cherrypy.session.release_lock() if cherry.config['media.transcode'] and path: # bitrate bitrate = params.pop('bitrate', None) or None # catch empty strings if bitrate: try: bitrate = max(0, int(bitrate)) or None # None if < 1 except (TypeError, ValueError): raise cherrypy.HTTPError(400, "Bad query: " "bitrate ({0!r}) must be an integer".format(str(bitrate))) # path path = os.path.sep.join(path) if sys.version_info < (3, 0): # workaround for #327 (cherrypy issue) path = path.decode('utf-8') # make it work with non-ascii else: path = codecs.decode(codecs.encode(path, 'latin1'), 'utf-8') fullpath = os.path.join(cherry.config['media.basedir'], path) starttime = int(params.pop('starttime', 0)) transcoder = audiotranscode.AudioTranscode() mimetype = audiotranscode.mime_type(newformat) cherrypy.response.headers["Content-Type"] = mimetype try: return transcoder.transcode_stream(fullpath, newformat, bitrate=bitrate, starttime=starttime) except (audiotranscode.TranscodeError, IOError) as e: raise cherrypy.HTTPError(404, e.value) trans.exposed = True trans._cp_config = {'response.stream': True} def api(self, *args, **kwargs): """calls the appropriate handler from the handlers dict, if available. handlers having noauth set to true do not need authentification to work. """ #check action action = args[0] if args else '' if not action in self.handlers: return "Error: no such action. '%s'" % action #authorize if not explicitly deactivated handler = self.handlers[action] needsAuth = not ('noauth' in dir(handler) and handler.noauth) if needsAuth and not self.isAuthorized(): raise cherrypy.HTTPError(401, 'Unauthorized') handler_args = {} if 'data' in kwargs: handler_args = json.loads(kwargs['data']) is_binary = ('binary' in dir(handler) and handler.binary) if is_binary: return handler(**handler_args) else: return json.dumps({'data': handler(**handler_args)}) api.exposed = True def download_check_files(self, filelist): # only admins and allowed users may download if not cherrypy.session['admin']: uo = self.useroptions.forUser(self.getUserId()) if not uo.getOptionValue('media.may_download'): return 'not_permitted' # make sure nobody tries to escape from basedir for f in filelist: # don't allow to traverse up in the file system if '/../' in f or f.startswith('../'): return 'invalid_file' # CVE-2015-8309: do not allow absolute file paths if os.path.isabs(f): return 'invalid_file' # make sure all files are smaller than maximum download size size_limit = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(filelist, size_limit): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e) def api_downloadcheck(self, filelist): status = self.download_check_files(filelist) if status == 'not_permitted': return """You are not allowed to download files.""" elif status == 'invalid_file': return "Error: invalid filename found in {list}".format(list=filelist) elif status == 'too_big': size_limit = cherry.config['media.maximum_download_size'] return """Can't download: Playlist is bigger than {maxsize} mB. The server administrator can change this configuration. """.format(maxsize=size_limit/1024/1024) elif status == 'ok': return status else: message = "Error status check for download: {status!r}".format(status=status) log.e(message) return message def download(self, value): if not self.isAuthorized(): raise cherrypy.HTTPError(401, 'Unauthorized') filelist = [filepath for filepath in json.loads(unquote(value))] dlstatus = self.download_check_files(filelist) if dlstatus == 'ok': _save_and_release_session() zipmime = 'application/x-zip-compressed' cherrypy.response.headers["Content-Type"] = zipmime zipname = 'attachment; filename="music.zip"' cherrypy.response.headers['Content-Disposition'] = zipname basedir = cherry.config['media.basedir'] fullpath_filelist = [os.path.join(basedir, f) for f in filelist] return zipstream.ZipStream(fullpath_filelist) else: return dlstatus download.exposed = True download._cp_config = {'response.stream': True} def api_getuseroptions(self): uo = self.useroptions.forUser(self.getUserId()) uco = uo.getChangableOptions() if cherrypy.session['admin']: uco['media'].update({'may_download': True}) else: uco['media'].update({'may_download': uo.getOptionValue('media.may_download')}) return uco def api_heartbeat(self): uo = self.useroptions.forUser(self.getUserId()) uo.setOption('last_time_online', int(time.time())) def api_setuseroption(self, optionkey, optionval): uo = self.useroptions.forUser(self.getUserId()) uo.setOption(optionkey, optionval) return "success" def api_setuseroptionfor(self, userid, optionkey, optionval): if cherrypy.session['admin']: uo = self.useroptions.forUser(userid) uo.setOption(optionkey, optionval) return "success" else: return "error: not permitted. Only admins can change other users options" def api_fetchalbumarturls(self, searchterm): if not cherrypy.session['admin']: raise cherrypy.HTTPError(401, 'Unauthorized') _save_and_release_session() fetcher = albumartfetcher.AlbumArtFetcher() imgurls = fetcher.fetchurls(searchterm) # show no more than 10 images return imgurls[:min(len(imgurls), 10)] def api_albumart_set(self, directory, imageurl): if not cherrypy.session['admin']: raise cherrypy.HTTPError(401, 'Unauthorized') b64imgpath = albumArtFilePath(directory) fetcher = albumartfetcher.AlbumArtFetcher() data, header = fetcher.retrieveData(imageurl) self.albumartcache_save(b64imgpath, data) def api_fetchalbumart(self, directory): _save_and_release_session() default_folder_image = "../res/img/folder.png" log.i('Fetching album art for: %s' % directory) filepath = os.path.join(cherry.config['media.basedir'], directory) if os.path.isfile(filepath): # if the given path is a file, try to get the image from ID3 tag = TinyTag.get(filepath, image=True) image_data = tag.get_image() if image_data: log.d('Image found in tag.') header = {'Content-Type': 'image/jpg', 'Content-Length': len(image_data)} cherrypy.response.headers.update(header) return image_data else: # if the file does not contain an image, display the image of the # parent directory directory = os.path.dirname(directory) #try getting a cached album art image b64imgpath = albumArtFilePath(directory) img_data = self.albumartcache_load(b64imgpath) if img_data: cherrypy.response.headers["Content-Length"] = len(img_data) return img_data #try getting album art inside local folder fetcher = albumartfetcher.AlbumArtFetcher() localpath = os.path.join(cherry.config['media.basedir'], directory) header, data, resized = fetcher.fetchLocal(localpath) if header: if resized: #cache resized image for next time self.albumartcache_save(b64imgpath, data) cherrypy.response.headers.update(header) return data elif cherry.config['media.fetch_album_art']: #fetch album art from online source try: foldername = os.path.basename(directory) keywords = foldername log.i(_("Fetching album art for keywords {keywords!r}").format(keywords=keywords)) header, data = fetcher.fetch(keywords) if header: cherrypy.response.headers.update(header) self.albumartcache_save(b64imgpath, data) return data else: # albumart fetcher failed, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) except: # albumart fetcher threw exception, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) else: # no local album art found, online fetching deactivated, show default raise cherrypy.HTTPRedirect(default_folder_image, 302) api_fetchalbumart.noauth = True api_fetchalbumart.binary = True def albumartcache_load(self, imgb64path): if os.path.exists(imgb64path): with open(imgb64path, 'rb') as f: return f.read() def albumartcache_save(self, path, data): with open(path, 'wb') as f: f.write(data) def api_compactlistdir(self, directory, filterstr=None): try: files_to_list = self.model.listdir(directory, filterstr) except ValueError: raise cherrypy.HTTPError(400, 'Bad Request') return [entry.to_dict() for entry in files_to_list] def api_listdir(self, directory): try: return [entry.to_dict() for entry in self.model.listdir(directory)] except ValueError: raise cherrypy.HTTPError(400, 'Bad Request') def api_search(self, searchstring): if not searchstring.strip(): jsonresults = '[]' else: with Performance(_('processing whole search request')): searchresults = self.model.search(searchstring.strip()) with Performance(_('rendering search results as json')): jsonresults = [entry.to_dict() for entry in searchresults] return jsonresults def api_rememberplaylist(self, playlist): cherrypy.session['playlist'] = playlist def api_saveplaylist(self, playlist, public, playlistname, overwrite=False): res = self.playlistdb.savePlaylist( userid=self.getUserId(), public=1 if public else 0, playlist=playlist, playlisttitle=playlistname, overwrite=overwrite) if res == "success": return res else: raise cherrypy.HTTPError(400, res) def api_deleteplaylist(self, playlistid): res = self.playlistdb.deletePlaylist(playlistid, self.getUserId(), override_owner=False) if res == "success": return res else: # not the ideal status code but we don't know the actual # cause without parsing res raise cherrypy.HTTPError(400, res) def api_loadplaylist(self, playlistid): return [entry.to_dict() for entry in self.playlistdb.loadPlaylist( playlistid=playlistid, userid=self.getUserId() )] def api_generaterandomplaylist(self): return [entry.to_dict() for entry in self.model.randomMusicEntries(50)] def api_changeplaylist(self, plid, attribute, value): if attribute == 'public': is_valid = type(value) == bool and type(plid) == int if is_valid: return self.playlistdb.setPublic(userid=self.getUserId(), plid=plid, public=value) def api_getmotd(self): if cherrypy.session['admin'] and cherry.config['general.update_notification']: _save_and_release_session() new_versions = self.model.check_for_updates() if new_versions: newest_version = new_versions[0]['version'] features = [] fixes = [] for version in new_versions: for update in version['features']: if update.startswith('FEATURE:'): features.append(update[len('FEATURE:'):]) elif update.startswith('FIX:'): fixes.append(update[len('FIX:'):]) elif update.startswith('FIXED:'): fixes.append(update[len('FIXED:'):]) retdata = {'type': 'update', 'data': {}} retdata['data']['version'] = newest_version retdata['data']['features'] = features retdata['data']['fixes'] = fixes return retdata return {'type': 'wisdom', 'data': self.model.motd()} def api_restoreplaylist(self): session_playlist = cherrypy.session.get('playlist', []) return session_playlist def api_getplayables(self): """DEPRECATED""" return json.dumps(cherry.config['media.playable']) def api_getuserlist(self): if cherrypy.session['admin']: userlist = self.userdb.getUserList() for user in userlist: if user['id'] == cherrypy.session['userid']: user['deletable'] = False user_options = self.useroptions.forUser(user['id']) t = user_options.getOptionValue('last_time_online') may_download = user_options.getOptionValue('media.may_download') user['last_time_online'] = t user['may_download'] = may_download sortfunc = lambda user: user['last_time_online'] userlist = sorted(userlist, key=sortfunc, reverse=True) return json.dumps({'time': int(time.time()), 'userlist': userlist}) else: return json.dumps({'time': 0, 'userlist': []}) def api_adduser(self, username, password, isadmin): if cherrypy.session['admin']: if self.userdb.addUser(username, password, isadmin): return 'added new user: %s' % username else: return 'error, cannot add new user!' % username else: return "You didn't think that would work, did you?" def api_userchangepassword(self, oldpassword, newpassword, username=''): isself = username == '' if isself: username = cherrypy.session['username'] authed_user = self.userdb.auth(username, oldpassword) is_authenticated = userdb.User.nobody() != authed_user if not is_authenticated: raise cherrypy.HTTPError(403, "Forbidden") if isself or cherrypy.session['admin']: return self.userdb.changePassword(username, newpassword) else: raise cherrypy.HTTPError(403, "Forbidden") def api_userdelete(self, userid): is_self = cherrypy.session['userid'] == userid if cherrypy.session['admin'] and not is_self: deleted = self.userdb.deleteUser(userid) return 'success' if deleted else 'failed' else: return "You didn't think that would work, did you?" def api_showplaylists(self, sortby="created", filterby=''): playlists = self.playlistdb.showPlaylists(self.getUserId(), filterby) curr_time = int(time.time()) is_reverse = False #translate userids to usernames: for pl in playlists: pl['username'] = self.userdb.getNameById(pl['userid']) pl['type'] = 'playlist' pl['age'] = curr_time - pl['created'] if sortby[0] == '-': is_reverse = True sortby = sortby[1:] if not sortby in ('username', 'age', 'title', 'default'): sortby = 'created' if sortby == 'default': sortby = 'age' is_reverse = False playlists = sorted(playlists, key=lambda x: x[sortby], reverse = is_reverse) return playlists def api_logout(self): cherrypy.lib.sessions.expire() api_logout.no_auth = True def api_downloadpls(self, plid, hostaddr): userid = self.getUserId() pls = self.playlistdb.createPLS(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) if pls and name: return self.serve_string_as_file(pls, name+'.pls') api_downloadpls.binary = True def api_downloadm3u(self, plid, hostaddr): userid = self.getUserId() pls = self.playlistdb.createM3U(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) if pls and name: return self.serve_string_as_file(pls, name+'.m3u') api_downloadm3u.binary = True def export_playlists(self, format, all=False, hostaddr=''): userid = self.getUserId() if not userid: raise cherrypy.HTTPError(401, _("Please log in")) hostaddr = (hostaddr.strip().rstrip('/') + cherry.config['server.rootpath']).rstrip('/') format = format.lower() if format == 'm3u': filemaker = self.playlistdb.createM3U elif format == 'pls': filemaker = self.playlistdb.createPLS else: raise cherrypy.HTTPError(400, _('Unknown playlist format: {format!r}').format(format=format)) playlists = self.playlistdb.showPlaylists(userid, include_public=all) if not playlists: raise cherrypy.HTTPError(404, _('No playlists found')) with MemoryZipFile() as zip: for pl in playlists: plid = pl['plid'] plstr = filemaker(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) + '.' + format if not pl['owner']: username = self.userdb.getNameById(pl['userid']) name = username + '/' + name zip.writestr(name, plstr) zipmime = 'application/x-zip-compressed' zipname = 'attachment; filename="playlists.zip"' cherrypy.response.headers["Content-Type"] = zipmime cherrypy.response.headers['Content-Disposition'] = zipname return zip.getbytes() export_playlists.exposed = True def api_getsonginfo(self, path): basedir = cherry.config['media.basedir'] abspath = os.path.join(basedir, path) return json.dumps(metainfo.getSongInfo(abspath).dict()) def api_getencoders(self): return json.dumps(audiotranscode.getEncoders()) def api_getdecoders(self): return json.dumps(audiotranscode.getDecoders()) def api_transcodingenabled(self): return json.dumps(cherry.config['media.transcode']) def api_updatedb(self): self.model.updateLibrary() return 'success' def api_getconfiguration(self): clientconfigkeys = { 'transcodingenabled': cherry.config['media.transcode'], 'fetchalbumart': cherry.config['media.fetch_album_art'], 'isadmin': cherrypy.session['admin'], 'username': cherrypy.session['username'], 'servepath': 'serve/', 'transcodepath': 'trans/', 'auto_login': self.autoLoginActive(), 'version': cherry.REPO_VERSION or cherry.VERSION, } if cherry.config['media.transcode']: decoders = list(self.model.transcoder.available_decoder_formats()) clientconfigkeys['getdecoders'] = decoders encoders = list(self.model.transcoder.available_encoder_formats()) clientconfigkeys['getencoders'] = encoders else: clientconfigkeys['getdecoders'] = [] clientconfigkeys['getencoders'] = [] return clientconfigkeys def serve_string_as_file(self, string, filename): content_disposition = 'attachment; filename="'+filename+'"' cherrypy.response.headers["Content-Type"] = "application/x-download" cherrypy.response.headers["Content-Disposition"] = content_disposition return codecs.encode(string, "UTF-8") def _save_and_release_session(): """ workaround to cleanly release FileSessions in Cherrypy >= 3.3 From https://github.com/devsnd/cherrymusic/issues/483: > CherryPy >=3.3.0 (up to current version, 3.6) makes it impossible to > explicitly release FileSession locks, because: > 1. FileSession.save() asserts that the session is locked; and > 2. _cptools.SessionTool always adds a hook to call sessions.save > before the response is finalized. > If we still want to release the session in a controller, I guess the > best way to work around this is to remove the hook before the > controller returns: """ cherrypy.session.save() hooks = cherrypy.serving.request.hooks['before_finalize'] forbidden = cherrypy.lib.sessions.save hooks[:] = [h for h in hooks if h.callback is not forbidden] # there's likely only one hook, since a 2nd call to save would always fail; # but let's be safe, and block all calls to save :)
xss
{ "code": [ " if '/../' in f:" ], "line_no": [ 303 ] }
{ "code": [ " if '/../' in f or f.startswith('../'):", " if os.path.isabs(f):" ], "line_no": [ 304, 307 ] }
import os # shouldn't have to list any folder in the future! import json import .cherrypy import codecs import sys try: from urllib.parse import unquote except ImportError: from backport.urllib.parse import unquote try: from urllib import parse except ImportError: from backport.urllib import parse import audiotranscode from tinytag import TinyTag from cherrymusicserver import .userdb from cherrymusicserver import log from cherrymusicserver import albumartfetcher from cherrymusicserver import service from cherrymusicserver.pathprovider import readRes from cherrymusicserver.pathprovider import albumArtFilePath import cherrymusicserver as cherry import cherrymusicserver.metainfo as metainfo from cherrymusicserver.util import Performance, MemoryZipFile from cherrymusicserver.ext import zipstream import .time VAR_0 = True @service.user(model='cherrymodel', playlistdb='playlist', useroptions='useroptions', userdb='users') class CLASS_0(object): def __init__(self, VAR_1): self.config = VAR_1 VAR_42 = 'res/dist/main.html' VAR_43 = 'res/login.html' VAR_44 = 'res/VAR_48.html' self.mainpage = readRes(VAR_42) self.loginpage = readRes(VAR_43) self.firstrunpage = readRes(VAR_44) self.handlers = { 'search': self.api_search, 'rememberplaylist': self.api_rememberplaylist, 'saveplaylist': self.api_saveplaylist, 'loadplaylist': self.api_loadplaylist, 'generaterandomplaylist': self.api_generaterandomplaylist, 'deleteplaylist': self.api_deleteplaylist, 'getmotd': self.api_getmotd, 'restoreplaylist': self.api_restoreplaylist, 'getplayables': self.api_getplayables, 'getuserlist': self.api_getuserlist, 'adduser': self.api_adduser, 'userdelete': self.api_userdelete, 'userchangepassword': self.api_userchangepassword, 'showplaylists': self.api_showplaylists, 'logout': self.api_logout, 'downloadpls': self.api_downloadpls, 'downloadm3u': self.api_downloadm3u, 'getsonginfo': self.api_getsonginfo, 'getencoders': self.api_getencoders, 'getdecoders': self.api_getdecoders, 'transcodingenabled': self.api_transcodingenabled, 'updatedb': self.api_updatedb, 'getconfiguration': self.api_getconfiguration, 'compactlistdir': self.api_compactlistdir, 'listdir': self.api_listdir, 'fetchalbumart': self.api_fetchalbumart, 'fetchalbumarturls': self.api_fetchalbumarturls, 'albumart_set': self.api_albumart_set, 'heartbeat': self.api_heartbeat, 'getuseroptions': self.api_getuseroptions, 'setuseroption': self.api_setuseroption, 'changeplaylist': self.api_changeplaylist, 'downloadcheck': self.api_downloadcheck, 'setuseroptionfor': self.api_setuseroptionfor, } def FUNC_1(self, VAR_2): return parse.urlparse(VAR_2).scheme == 'https' def FUNC_2(self, VAR_3=False): VAR_45 = parse.urlparse(VAR_53.url()).netloc VAR_46 = self.issecure(VAR_53.url()) VAR_47 = cherry.config['server.ssl_enabled'] if VAR_47 and not VAR_46: log.d(_('Not secure, redirecting...')) VAR_88 = VAR_45[:ipAndPort.rindex(':')] VAR_2 = 'https://' + VAR_88 + ':' + str(cherry.config['server.ssl_port']) if VAR_3: raise VAR_53.HTTPRedirect(VAR_2, 302) else: VAR_2 = 'http://' + VAR_45 return VAR_2 def FUNC_3(self, *VAR_4, **VAR_5): self.getBaseUrl(VAR_3=True) VAR_48 = 0 == self.userdb.getUserCount() VAR_49 = self.mainpage #generated main.html from devel.html if 'devel' in VAR_5: VAR_49 = readRes('res/devel.html') self.loginpage = readRes('res/login.html') self.firstrunpage = readRes('res/VAR_48.html') if 'login' in VAR_5: VAR_6 = VAR_5.get('username', '') VAR_7 = VAR_5.get('password', '') VAR_89 = VAR_5.get('login', '') if VAR_89 == 'login': self.session_auth(VAR_6, VAR_7) if VAR_53.session['username']: VAR_6 = VAR_53.session['username'] log.i(_('user {VAR_81} just logged in.').format(VAR_81=VAR_6)) elif VAR_89 == 'create admin user': if VAR_48: if VAR_6.strip() and VAR_7.strip(): self.userdb.addUser(VAR_6, VAR_7, True) self.session_auth(VAR_6, VAR_7) return VAR_49 else: return "No, you can't." if VAR_48: return self.firstrunpage else: if self.isAuthorized(): return VAR_49 else: return self.loginpage FUNC_3.exposed = True def FUNC_4(self): try: VAR_90 = VAR_53.session.get('username', None) VAR_91 = VAR_53.session.get('userid', -1) VAR_92 = self.userdb.getNameById(VAR_91) except (UnicodeDecodeError, ValueError) as e: log.w(_(''' Dropping VAR_37 sessions! Try not to change between python 2 and 3, everybody has to relogin now.''')) VAR_53.session.delete() VAR_90 = None if VAR_90 is None: if self.autoLoginActive(): VAR_53.session['username'] = self.userdb.getNameById(1) VAR_53.session['userid'] = 1 VAR_53.session['admin'] = True return True else: return False elif VAR_90 != VAR_92: self.api_logout(VAR_12=None) return False return True def FUNC_5(self): VAR_50 = VAR_53.request.remote.ip in ('127.0.0.1', '::1') if VAR_50 and cherry.config['server.localhost_auto_login']: return True return False def FUNC_6(self, VAR_6, VAR_7): VAR_51 = self.userdb.auth(VAR_6, VAR_7) VAR_52 = cherry.config['server.permit_remote_admin_login'] VAR_50 = VAR_53.request.remote.ip in ('127.0.0.1', '::1') if not VAR_50 and VAR_51.isadmin and not VAR_52: log.i(_('Rejected remote admin login from VAR_51: {VAR_81}').format(VAR_81=VAR_51.name)) VAR_51 = userdb.User.nobody() VAR_53.session['username'] = VAR_51.name VAR_53.session['userid'] = VAR_51.uid VAR_53.session['admin'] = VAR_51.isadmin def FUNC_7(self): try: return VAR_53.session['userid'] except KeyError: VAR_53.lib.sessions.expire() VAR_53.HTTPRedirect(VAR_53.url(), 302) return '' def FUNC_8(self, VAR_8, *VAR_9, **VAR_10): if not self.isAuthorized(): raise VAR_53.HTTPRedirect(self.getBaseUrl(), 302) VAR_53.session.release_lock() if cherry.config['media.transcode'] and VAR_9: bitrate = VAR_10.pop('bitrate', None) or None # catch empty strings if VAR_93: try: VAR_93 = max(0, int(VAR_93)) or None # None if < 1 except (TypeError, ValueError): raise VAR_53.HTTPError(400, "Bad query: " "bitrate ({0!r}) must be an integer".format(str(VAR_93))) VAR_9 = os.path.sep.join(VAR_9) if sys.version_info < (3, 0): # workaround for #327 (VAR_53 issue) VAR_9 = path.decode('utf-8') # make it work with non-ascii else: VAR_9 = codecs.decode(codecs.encode(VAR_9, 'latin1'), 'utf-8') VAR_94 = os.path.join(cherry.config['media.basedir'], VAR_9) VAR_95 = int(VAR_10.pop('starttime', 0)) VAR_96 = audiotranscode.AudioTranscode() VAR_97 = audiotranscode.mime_type(VAR_8) VAR_53.response.headers["Content-Type"] = VAR_97 try: return VAR_96.transcode_stream(VAR_94, VAR_8, VAR_93=bitrate, VAR_95=starttime) except (audiotranscode.TranscodeError, IOError) as e: raise VAR_53.HTTPError(404, e.value) FUNC_8.exposed = True FUNC_8._cp_config = {'response.stream': True} def FUNC_9(self, *VAR_4, **VAR_5): VAR_54 = VAR_4[0] if VAR_4 else '' if not VAR_54 in self.handlers: return "Error: no such VAR_54. '%s'" % VAR_54 VAR_55 = self.handlers[VAR_54] VAR_56 = not ('noauth' in dir(VAR_55) and VAR_55.noauth) if VAR_56 and not self.isAuthorized(): raise VAR_53.HTTPError(401, 'Unauthorized') VAR_57 = {} if 'data' in VAR_5: VAR_57 = json.loads(VAR_5['data']) VAR_58 = ('binary' in dir(VAR_55) and VAR_55.binary) if VAR_58: return VAR_55(**VAR_57) else: return json.dumps({'data': VAR_55(**VAR_57)}) FUNC_9.exposed = True def FUNC_10(self, VAR_11): if not VAR_53.session['admin']: VAR_62 = self.useroptions.forUser(self.getUserId()) if not VAR_62.getOptionValue('media.may_download'): return 'not_permitted' for f in VAR_11: if '/../' in f: return 'invalid_file' VAR_59 = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(VAR_11, VAR_59): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e) def FUNC_11(self, VAR_11): VAR_60 = self.download_check_files(VAR_11) if VAR_60 == 'not_permitted': return """You are not allowed to FUNC_12 files.""" elif VAR_60 == 'invalid_file': return "Error: invalid VAR_39 found in {list}".format(list=VAR_11) elif VAR_60 == 'too_big': VAR_59 = cherry.config['media.maximum_download_size'] return """Can't FUNC_12: Playlist is bigger than {maxsize} mB. The server administrator can change this configuration. """.format(maxsize=VAR_59/1024/1024) elif VAR_60 == 'ok': return VAR_60 else: VAR_125 = "Error VAR_60 check for FUNC_12: {VAR_60!r}".format(VAR_60=status) log.e(VAR_125) return VAR_125 def FUNC_12(self, VAR_12): if not self.isAuthorized(): raise VAR_53.HTTPError(401, 'Unauthorized') VAR_11 = [VAR_69 for VAR_69 in json.loads(unquote(VAR_12))] VAR_61 = self.download_check_files(VAR_11) if VAR_61 == 'ok': FUNC_0() VAR_82 = 'application/x-zip-compressed' VAR_53.response.headers["Content-Type"] = VAR_82 VAR_83 = 'attachment; VAR_39="music.zip"' VAR_53.response.headers['Content-Disposition'] = VAR_83 VAR_84 = cherry.config['media.basedir'] VAR_98 = [os.path.join(VAR_84, f) for f in VAR_11] return zipstream.ZipStream(VAR_98) else: return VAR_61 FUNC_12.exposed = True FUNC_12._cp_config = {'response.stream': True} def FUNC_13(self): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_63 = VAR_62.getChangableOptions() if VAR_53.session['admin']: VAR_63['media'].update({'may_download': True}) else: VAR_63['media'].update({'may_download': VAR_62.getOptionValue('media.may_download')}) return VAR_63 def FUNC_14(self): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_62.setOption('last_time_online', int(time.time())) def FUNC_15(self, VAR_13, VAR_14): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_62.setOption(VAR_13, VAR_14) return "success" def FUNC_16(self, VAR_15, VAR_13, VAR_14): if VAR_53.session['admin']: VAR_62 = self.useroptions.forUser(VAR_15) VAR_62.setOption(VAR_13, VAR_14) return "success" else: return "error: not permitted. Only admins can change other users options" def FUNC_17(self, VAR_16): if not VAR_53.session['admin']: raise VAR_53.HTTPError(401, 'Unauthorized') FUNC_0() VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_65 = VAR_64.fetchurls(VAR_16) return VAR_65[:min(len(VAR_65), 10)] def FUNC_18(self, VAR_17, VAR_18): if not VAR_53.session['admin']: raise VAR_53.HTTPError(401, 'Unauthorized') VAR_66 = albumArtFilePath(VAR_17) VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_20, VAR_67 = VAR_64.retrieveData(VAR_18) self.albumartcache_save(VAR_66, VAR_20) def FUNC_19(self, VAR_17): FUNC_0() VAR_68 = "../VAR_73/img/folder.png" log.i('Fetching album art for: %s' % VAR_17) VAR_69 = os.path.join(cherry.config['media.basedir'], VAR_17) if os.path.isfile(VAR_69): VAR_99 = TinyTag.get(VAR_69, image=True) VAR_100 = VAR_99.get_image() if VAR_100: log.d('Image found in VAR_99.') VAR_67 = {'Content-Type': 'image/jpg', 'Content-Length': len(VAR_100)} VAR_53.response.headers.update(VAR_67) return VAR_100 else: directory = os.path.dirname(VAR_17) VAR_66 = albumArtFilePath(VAR_17) VAR_70 = self.albumartcache_load(VAR_66) if VAR_70: VAR_53.response.headers["Content-Length"] = len(VAR_70) return VAR_70 VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_71 = os.path.join(cherry.config['media.basedir'], VAR_17) VAR_67, VAR_20, VAR_72 = VAR_64.fetchLocal(VAR_71) if VAR_67: if VAR_72: self.albumartcache_save(VAR_66, VAR_20) VAR_53.response.headers.update(VAR_67) return VAR_20 elif cherry.config['media.fetch_album_art']: try: VAR_123 = os.path.basename(VAR_17) VAR_124 = VAR_123 log.i(_("Fetching album art for VAR_124 {keywords!r}").format(VAR_124=keywords)) VAR_67, VAR_20 = VAR_64.fetch(VAR_124) if VAR_67: VAR_53.response.headers.update(VAR_67) self.albumartcache_save(VAR_66, VAR_20) return VAR_20 else: raise VAR_53.HTTPRedirect(VAR_68, 302) except: raise VAR_53.HTTPRedirect(VAR_68, 302) else: raise VAR_53.HTTPRedirect(VAR_68, 302) FUNC_19.noauth = True FUNC_19.binary = True def FUNC_20(self, VAR_19): if os.path.exists(VAR_19): with open(VAR_19, 'rb') as f: return f.read() def FUNC_21(self, VAR_9, VAR_20): with open(VAR_9, 'wb') as f: f.write(VAR_20) def FUNC_22(self, VAR_17, VAR_21=None): try: VAR_101 = self.model.listdir(VAR_17, VAR_21) except ValueError: raise VAR_53.HTTPError(400, 'Bad Request') return [entry.to_dict() for entry in VAR_101] def FUNC_23(self, VAR_17): try: return [entry.to_dict() for entry in self.model.listdir(VAR_17)] except ValueError: raise VAR_53.HTTPError(400, 'Bad Request') def FUNC_24(self, VAR_22): if not VAR_22.strip(): VAR_102 = '[]' else: with Performance(_('processing whole search request')): VAR_114 = self.model.search(VAR_22.strip()) with Performance(_('rendering search results as json')): VAR_102 = [entry.to_dict() for entry in VAR_114] return VAR_102 def FUNC_25(self, VAR_23): VAR_53.session['playlist'] = VAR_23 def FUNC_26(self, VAR_23, VAR_24, VAR_25, VAR_26=False): VAR_73 = self.playlistdb.savePlaylist( VAR_15=self.getUserId(), VAR_24=1 if VAR_24 else 0, VAR_23=playlist, playlisttitle=VAR_25, VAR_26=overwrite) if VAR_73 == "success": return VAR_73 else: raise VAR_53.HTTPError(400, VAR_73) def FUNC_27(self, VAR_27): VAR_73 = self.playlistdb.deletePlaylist(VAR_27, self.getUserId(), override_owner=False) if VAR_73 == "success": return VAR_73 else: raise VAR_53.HTTPError(400, VAR_73) def FUNC_28(self, VAR_27): return [entry.to_dict() for entry in self.playlistdb.loadPlaylist( VAR_27=playlistid, VAR_15=self.getUserId() )] def FUNC_29(self): return [entry.to_dict() for entry in self.model.randomMusicEntries(50)] def FUNC_30(self, VAR_28, VAR_29, VAR_12): if VAR_29 == 'public': VAR_103 = type(VAR_12) == bool and type(VAR_28) == int if VAR_103: return self.playlistdb.setPublic(VAR_15=self.getUserId(), VAR_28=plid, VAR_24=VAR_12) def FUNC_31(self): if VAR_53.session['admin'] and cherry.config['general.update_notification']: FUNC_0() VAR_104 = self.model.check_for_updates() if VAR_104: VAR_115 = VAR_104[0]['version'] VAR_116 = [] VAR_117 = [] for version in VAR_104: for update in version['features']: if update.startswith('FEATURE:'): VAR_116.append(update[len('FEATURE:'):]) elif update.startswith('FIX:'): VAR_117.append(update[len('FIX:'):]) elif update.startswith('FIXED:'): VAR_117.append(update[len('FIXED:'):]) VAR_118 = {'type': 'update', 'data': {}} VAR_118['data']['version'] = VAR_115 VAR_118['data']['features'] = VAR_116 VAR_118['data']['fixes'] = VAR_117 return VAR_118 return {'type': 'wisdom', 'data': self.model.motd()} def FUNC_32(self): VAR_74 = VAR_53.session.get('playlist', []) return VAR_74 def FUNC_33(self): return json.dumps(cherry.config['media.playable']) def FUNC_34(self): if VAR_53.session['admin']: VAR_105 = self.userdb.getUserList() for VAR_51 in VAR_105: if VAR_51['id'] == VAR_53.session['userid']: VAR_51['deletable'] = False VAR_119 = self.useroptions.forUser(VAR_51['id']) VAR_120 = VAR_119.getOptionValue('last_time_online') VAR_121 = VAR_119.getOptionValue('media.may_download') VAR_51['last_time_online'] = VAR_120 VAR_51['may_download'] = VAR_121 VAR_106 = lambda VAR_51: VAR_51['last_time_online'] VAR_105 = sorted(VAR_105, key=VAR_106, reverse=True) return json.dumps({'time': int(time.time()), 'userlist': VAR_105}) else: return json.dumps({'time': 0, 'userlist': []}) def FUNC_35(self, VAR_6, VAR_7, VAR_30): if VAR_53.session['admin']: if self.userdb.addUser(VAR_6, VAR_7, VAR_30): return 'added new VAR_51: %s' % VAR_6 else: return 'error, cannot add new VAR_51!' % VAR_6 else: return "You didn't think that would work, did you?" def FUNC_36(self, VAR_31, VAR_32, VAR_6=''): VAR_75 = VAR_6 == '' if VAR_75: VAR_6 = VAR_53.session['username'] VAR_107 = self.userdb.auth(VAR_6, VAR_31) VAR_108 = userdb.User.nobody() != VAR_107 if not VAR_108: raise VAR_53.HTTPError(403, "Forbidden") if VAR_75 or VAR_53.session['admin']: return self.userdb.changePassword(VAR_6, VAR_32) else: raise VAR_53.HTTPError(403, "Forbidden") def FUNC_37(self, VAR_15): VAR_76 = VAR_53.session['userid'] == VAR_15 if VAR_53.session['admin'] and not VAR_76: VAR_109 = self.userdb.deleteUser(VAR_15) return 'success' if VAR_109 else 'failed' else: return "You didn't think that would work, did you?" def FUNC_38(self, VAR_33="created", VAR_34=''): VAR_77 = self.playlistdb.showPlaylists(self.getUserId(), VAR_34) VAR_78 = int(time.time()) VAR_79 = False for VAR_110 in VAR_77: VAR_110['username'] = self.userdb.getNameById(VAR_110['userid']) VAR_110['type'] = 'playlist' VAR_110['age'] = VAR_78 - VAR_110['created'] if VAR_33[0] == '-': VAR_79 = True VAR_33 = VAR_33[1:] if not VAR_33 in ('username', 'age', 'title', 'default'): VAR_33 = 'created' if VAR_33 == 'default': VAR_33 = 'age' VAR_79 = False VAR_77 = sorted(VAR_77, key=lambda x: x[VAR_33], reverse = VAR_79) return VAR_77 def FUNC_39(self): VAR_53.lib.sessions.expire() FUNC_39.no_auth = True def FUNC_40(self, VAR_28, VAR_35): VAR_15 = self.getUserId() VAR_80 = self.playlistdb.createPLS(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) if VAR_80 and VAR_81: return self.serve_string_as_file(VAR_80, VAR_81+'.pls') FUNC_40.binary = True def FUNC_41(self, VAR_28, VAR_35): VAR_15 = self.getUserId() VAR_80 = self.playlistdb.createM3U(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) if VAR_80 and VAR_81: return self.serve_string_as_file(VAR_80, VAR_81+'.m3u') FUNC_41.binary = True def FUNC_42(self, VAR_36, VAR_37=False, VAR_35=''): VAR_15 = self.getUserId() if not VAR_15: raise VAR_53.HTTPError(401, _("Please log in")) VAR_35 = (hostaddr.strip().rstrip('/') + cherry.config['server.rootpath']).rstrip('/') VAR_36 = format.lower() if VAR_36 == 'm3u': VAR_111 = self.playlistdb.createM3U elif VAR_36 == 'pls': VAR_111 = self.playlistdb.createPLS else: raise VAR_53.HTTPError(400, _('Unknown VAR_23 VAR_36: {format!r}').format(VAR_36=format)) VAR_77 = self.playlistdb.showPlaylists(VAR_15, include_public=VAR_37) if not VAR_77: raise VAR_53.HTTPError(404, _('No VAR_77 found')) with MemoryZipFile() as zip: for VAR_110 in VAR_77: VAR_28 = VAR_110['plid'] VAR_122 = VAR_111(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) + '.' + VAR_36 if not VAR_110['owner']: VAR_6 = self.userdb.getNameById(VAR_110['userid']) VAR_81 = VAR_6 + '/' + VAR_81 zip.writestr(VAR_81, VAR_122) VAR_82 = 'application/x-zip-compressed' VAR_83 = 'attachment; VAR_39="playlists.zip"' VAR_53.response.headers["Content-Type"] = VAR_82 VAR_53.response.headers['Content-Disposition'] = VAR_83 return zip.getbytes() FUNC_42.exposed = True def FUNC_43(self, VAR_9): VAR_84 = cherry.config['media.basedir'] VAR_85 = os.path.join(VAR_84, VAR_9) return json.dumps(metainfo.getSongInfo(VAR_85).dict()) def FUNC_44(self): return json.dumps(audiotranscode.getEncoders()) def FUNC_45(self): return json.dumps(audiotranscode.getDecoders()) def FUNC_46(self): return json.dumps(cherry.config['media.transcode']) def FUNC_47(self): self.model.updateLibrary() return 'success' def FUNC_48(self): VAR_86 = { 'transcodingenabled': cherry.config['media.transcode'], 'fetchalbumart': cherry.config['media.fetch_album_art'], 'isadmin': VAR_53.session['admin'], 'username': VAR_53.session['username'], 'servepath': 'serve/', 'transcodepath': 'trans/', 'auto_login': self.autoLoginActive(), 'version': cherry.REPO_VERSION or cherry.VERSION, } if cherry.config['media.transcode']: VAR_112 = list(self.model.transcoder.available_decoder_formats()) VAR_86['getdecoders'] = VAR_112 VAR_113 = list(self.model.transcoder.available_encoder_formats()) VAR_86['getencoders'] = VAR_113 else: VAR_86['getdecoders'] = [] VAR_86['getencoders'] = [] return VAR_86 def FUNC_49(self, VAR_38, VAR_39): VAR_87 = 'attachment; VAR_39="'+VAR_39+'"' VAR_53.response.headers["Content-Type"] = "application/x-download" VAR_53.response.headers["Content-Disposition"] = VAR_87 return codecs.encode(VAR_38, "UTF-8") def FUNC_0(): VAR_53.session.save() VAR_40 = VAR_53.serving.request.hooks['before_finalize'] VAR_41 = VAR_53.lib.sessions.save VAR_40[:] = [h for h in VAR_40 if h.callback is not VAR_41]
import os # shouldn't have to list any folder in the future! import json import .cherrypy import codecs import sys try: from urllib.parse import unquote except ImportError: from backport.urllib.parse import unquote try: from urllib import parse except ImportError: from backport.urllib import parse import audiotranscode from tinytag import TinyTag from cherrymusicserver import .userdb from cherrymusicserver import log from cherrymusicserver import albumartfetcher from cherrymusicserver import service from cherrymusicserver.pathprovider import readRes from cherrymusicserver.pathprovider import albumArtFilePath import cherrymusicserver as cherry import cherrymusicserver.metainfo as metainfo from cherrymusicserver.util import Performance, MemoryZipFile from cherrymusicserver.ext import zipstream import .time VAR_0 = True @service.user(model='cherrymodel', playlistdb='playlist', useroptions='useroptions', userdb='users') class CLASS_0(object): def __init__(self, VAR_1): self.config = VAR_1 VAR_42 = 'res/dist/main.html' VAR_43 = 'res/login.html' VAR_44 = 'res/VAR_48.html' self.mainpage = readRes(VAR_42) self.loginpage = readRes(VAR_43) self.firstrunpage = readRes(VAR_44) self.handlers = { 'search': self.api_search, 'rememberplaylist': self.api_rememberplaylist, 'saveplaylist': self.api_saveplaylist, 'loadplaylist': self.api_loadplaylist, 'generaterandomplaylist': self.api_generaterandomplaylist, 'deleteplaylist': self.api_deleteplaylist, 'getmotd': self.api_getmotd, 'restoreplaylist': self.api_restoreplaylist, 'getplayables': self.api_getplayables, 'getuserlist': self.api_getuserlist, 'adduser': self.api_adduser, 'userdelete': self.api_userdelete, 'userchangepassword': self.api_userchangepassword, 'showplaylists': self.api_showplaylists, 'logout': self.api_logout, 'downloadpls': self.api_downloadpls, 'downloadm3u': self.api_downloadm3u, 'getsonginfo': self.api_getsonginfo, 'getencoders': self.api_getencoders, 'getdecoders': self.api_getdecoders, 'transcodingenabled': self.api_transcodingenabled, 'updatedb': self.api_updatedb, 'getconfiguration': self.api_getconfiguration, 'compactlistdir': self.api_compactlistdir, 'listdir': self.api_listdir, 'fetchalbumart': self.api_fetchalbumart, 'fetchalbumarturls': self.api_fetchalbumarturls, 'albumart_set': self.api_albumart_set, 'heartbeat': self.api_heartbeat, 'getuseroptions': self.api_getuseroptions, 'setuseroption': self.api_setuseroption, 'changeplaylist': self.api_changeplaylist, 'downloadcheck': self.api_downloadcheck, 'setuseroptionfor': self.api_setuseroptionfor, } def FUNC_1(self, VAR_2): return parse.urlparse(VAR_2).scheme == 'https' def FUNC_2(self, VAR_3=False): VAR_45 = parse.urlparse(VAR_53.url()).netloc VAR_46 = self.issecure(VAR_53.url()) VAR_47 = cherry.config['server.ssl_enabled'] if VAR_47 and not VAR_46: log.d(_('Not secure, redirecting...')) VAR_88 = VAR_45[:ipAndPort.rindex(':')] VAR_2 = 'https://' + VAR_88 + ':' + str(cherry.config['server.ssl_port']) if VAR_3: raise VAR_53.HTTPRedirect(VAR_2, 302) else: VAR_2 = 'http://' + VAR_45 return VAR_2 def FUNC_3(self, *VAR_4, **VAR_5): self.getBaseUrl(VAR_3=True) VAR_48 = 0 == self.userdb.getUserCount() VAR_49 = self.mainpage #generated main.html from devel.html if 'devel' in VAR_5: VAR_49 = readRes('res/devel.html') self.loginpage = readRes('res/login.html') self.firstrunpage = readRes('res/VAR_48.html') if 'login' in VAR_5: VAR_6 = VAR_5.get('username', '') VAR_7 = VAR_5.get('password', '') VAR_89 = VAR_5.get('login', '') if VAR_89 == 'login': self.session_auth(VAR_6, VAR_7) if VAR_53.session['username']: VAR_6 = VAR_53.session['username'] log.i(_('user {VAR_81} just logged in.').format(VAR_81=VAR_6)) elif VAR_89 == 'create admin user': if VAR_48: if VAR_6.strip() and VAR_7.strip(): self.userdb.addUser(VAR_6, VAR_7, True) self.session_auth(VAR_6, VAR_7) return VAR_49 else: return "No, you can't." if VAR_48: return self.firstrunpage else: if self.isAuthorized(): return VAR_49 else: return self.loginpage FUNC_3.exposed = True def FUNC_4(self): try: VAR_90 = VAR_53.session.get('username', None) VAR_91 = VAR_53.session.get('userid', -1) VAR_92 = self.userdb.getNameById(VAR_91) except (UnicodeDecodeError, ValueError) as e: log.w(_(''' Dropping VAR_37 sessions! Try not to change between python 2 and 3, everybody has to relogin now.''')) VAR_53.session.delete() VAR_90 = None if VAR_90 is None: if self.autoLoginActive(): VAR_53.session['username'] = self.userdb.getNameById(1) VAR_53.session['userid'] = 1 VAR_53.session['admin'] = True return True else: return False elif VAR_90 != VAR_92: self.api_logout(VAR_12=None) return False return True def FUNC_5(self): VAR_50 = VAR_53.request.remote.ip in ('127.0.0.1', '::1') if VAR_50 and cherry.config['server.localhost_auto_login']: return True return False def FUNC_6(self, VAR_6, VAR_7): VAR_51 = self.userdb.auth(VAR_6, VAR_7) VAR_52 = cherry.config['server.permit_remote_admin_login'] VAR_50 = VAR_53.request.remote.ip in ('127.0.0.1', '::1') if not VAR_50 and VAR_51.isadmin and not VAR_52: log.i(_('Rejected remote admin login from VAR_51: {VAR_81}').format(VAR_81=VAR_51.name)) VAR_51 = userdb.User.nobody() VAR_53.session['username'] = VAR_51.name VAR_53.session['userid'] = VAR_51.uid VAR_53.session['admin'] = VAR_51.isadmin def FUNC_7(self): try: return VAR_53.session['userid'] except KeyError: VAR_53.lib.sessions.expire() VAR_53.HTTPRedirect(VAR_53.url(), 302) return '' def FUNC_8(self, VAR_8, *VAR_9, **VAR_10): if not self.isAuthorized(): raise VAR_53.HTTPRedirect(self.getBaseUrl(), 302) VAR_53.session.release_lock() if cherry.config['media.transcode'] and VAR_9: bitrate = VAR_10.pop('bitrate', None) or None # catch empty strings if VAR_93: try: VAR_93 = max(0, int(VAR_93)) or None # None if < 1 except (TypeError, ValueError): raise VAR_53.HTTPError(400, "Bad query: " "bitrate ({0!r}) must be an integer".format(str(VAR_93))) VAR_9 = os.path.sep.join(VAR_9) if sys.version_info < (3, 0): # workaround for #327 (VAR_53 issue) VAR_9 = path.decode('utf-8') # make it work with non-ascii else: VAR_9 = codecs.decode(codecs.encode(VAR_9, 'latin1'), 'utf-8') VAR_94 = os.path.join(cherry.config['media.basedir'], VAR_9) VAR_95 = int(VAR_10.pop('starttime', 0)) VAR_96 = audiotranscode.AudioTranscode() VAR_97 = audiotranscode.mime_type(VAR_8) VAR_53.response.headers["Content-Type"] = VAR_97 try: return VAR_96.transcode_stream(VAR_94, VAR_8, VAR_93=bitrate, VAR_95=starttime) except (audiotranscode.TranscodeError, IOError) as e: raise VAR_53.HTTPError(404, e.value) FUNC_8.exposed = True FUNC_8._cp_config = {'response.stream': True} def FUNC_9(self, *VAR_4, **VAR_5): VAR_54 = VAR_4[0] if VAR_4 else '' if not VAR_54 in self.handlers: return "Error: no such VAR_54. '%s'" % VAR_54 VAR_55 = self.handlers[VAR_54] VAR_56 = not ('noauth' in dir(VAR_55) and VAR_55.noauth) if VAR_56 and not self.isAuthorized(): raise VAR_53.HTTPError(401, 'Unauthorized') VAR_57 = {} if 'data' in VAR_5: VAR_57 = json.loads(VAR_5['data']) VAR_58 = ('binary' in dir(VAR_55) and VAR_55.binary) if VAR_58: return VAR_55(**VAR_57) else: return json.dumps({'data': VAR_55(**VAR_57)}) FUNC_9.exposed = True def FUNC_10(self, VAR_11): if not VAR_53.session['admin']: VAR_62 = self.useroptions.forUser(self.getUserId()) if not VAR_62.getOptionValue('media.may_download'): return 'not_permitted' for f in VAR_11: if '/../' in f or f.startswith('../'): return 'invalid_file' if os.path.isabs(f): return 'invalid_file' VAR_59 = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(VAR_11, VAR_59): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e) def FUNC_11(self, VAR_11): VAR_60 = self.download_check_files(VAR_11) if VAR_60 == 'not_permitted': return """You are not allowed to FUNC_12 files.""" elif VAR_60 == 'invalid_file': return "Error: invalid VAR_39 found in {list}".format(list=VAR_11) elif VAR_60 == 'too_big': VAR_59 = cherry.config['media.maximum_download_size'] return """Can't FUNC_12: Playlist is bigger than {maxsize} mB. The server administrator can change this configuration. """.format(maxsize=VAR_59/1024/1024) elif VAR_60 == 'ok': return VAR_60 else: VAR_125 = "Error VAR_60 check for FUNC_12: {VAR_60!r}".format(VAR_60=status) log.e(VAR_125) return VAR_125 def FUNC_12(self, VAR_12): if not self.isAuthorized(): raise VAR_53.HTTPError(401, 'Unauthorized') VAR_11 = [VAR_69 for VAR_69 in json.loads(unquote(VAR_12))] VAR_61 = self.download_check_files(VAR_11) if VAR_61 == 'ok': FUNC_0() VAR_82 = 'application/x-zip-compressed' VAR_53.response.headers["Content-Type"] = VAR_82 VAR_83 = 'attachment; VAR_39="music.zip"' VAR_53.response.headers['Content-Disposition'] = VAR_83 VAR_84 = cherry.config['media.basedir'] VAR_98 = [os.path.join(VAR_84, f) for f in VAR_11] return zipstream.ZipStream(VAR_98) else: return VAR_61 FUNC_12.exposed = True FUNC_12._cp_config = {'response.stream': True} def FUNC_13(self): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_63 = VAR_62.getChangableOptions() if VAR_53.session['admin']: VAR_63['media'].update({'may_download': True}) else: VAR_63['media'].update({'may_download': VAR_62.getOptionValue('media.may_download')}) return VAR_63 def FUNC_14(self): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_62.setOption('last_time_online', int(time.time())) def FUNC_15(self, VAR_13, VAR_14): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_62.setOption(VAR_13, VAR_14) return "success" def FUNC_16(self, VAR_15, VAR_13, VAR_14): if VAR_53.session['admin']: VAR_62 = self.useroptions.forUser(VAR_15) VAR_62.setOption(VAR_13, VAR_14) return "success" else: return "error: not permitted. Only admins can change other users options" def FUNC_17(self, VAR_16): if not VAR_53.session['admin']: raise VAR_53.HTTPError(401, 'Unauthorized') FUNC_0() VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_65 = VAR_64.fetchurls(VAR_16) return VAR_65[:min(len(VAR_65), 10)] def FUNC_18(self, VAR_17, VAR_18): if not VAR_53.session['admin']: raise VAR_53.HTTPError(401, 'Unauthorized') VAR_66 = albumArtFilePath(VAR_17) VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_20, VAR_67 = VAR_64.retrieveData(VAR_18) self.albumartcache_save(VAR_66, VAR_20) def FUNC_19(self, VAR_17): FUNC_0() VAR_68 = "../VAR_73/img/folder.png" log.i('Fetching album art for: %s' % VAR_17) VAR_69 = os.path.join(cherry.config['media.basedir'], VAR_17) if os.path.isfile(VAR_69): VAR_99 = TinyTag.get(VAR_69, image=True) VAR_100 = VAR_99.get_image() if VAR_100: log.d('Image found in VAR_99.') VAR_67 = {'Content-Type': 'image/jpg', 'Content-Length': len(VAR_100)} VAR_53.response.headers.update(VAR_67) return VAR_100 else: directory = os.path.dirname(VAR_17) VAR_66 = albumArtFilePath(VAR_17) VAR_70 = self.albumartcache_load(VAR_66) if VAR_70: VAR_53.response.headers["Content-Length"] = len(VAR_70) return VAR_70 VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_71 = os.path.join(cherry.config['media.basedir'], VAR_17) VAR_67, VAR_20, VAR_72 = VAR_64.fetchLocal(VAR_71) if VAR_67: if VAR_72: self.albumartcache_save(VAR_66, VAR_20) VAR_53.response.headers.update(VAR_67) return VAR_20 elif cherry.config['media.fetch_album_art']: try: VAR_123 = os.path.basename(VAR_17) VAR_124 = VAR_123 log.i(_("Fetching album art for VAR_124 {keywords!r}").format(VAR_124=keywords)) VAR_67, VAR_20 = VAR_64.fetch(VAR_124) if VAR_67: VAR_53.response.headers.update(VAR_67) self.albumartcache_save(VAR_66, VAR_20) return VAR_20 else: raise VAR_53.HTTPRedirect(VAR_68, 302) except: raise VAR_53.HTTPRedirect(VAR_68, 302) else: raise VAR_53.HTTPRedirect(VAR_68, 302) FUNC_19.noauth = True FUNC_19.binary = True def FUNC_20(self, VAR_19): if os.path.exists(VAR_19): with open(VAR_19, 'rb') as f: return f.read() def FUNC_21(self, VAR_9, VAR_20): with open(VAR_9, 'wb') as f: f.write(VAR_20) def FUNC_22(self, VAR_17, VAR_21=None): try: VAR_101 = self.model.listdir(VAR_17, VAR_21) except ValueError: raise VAR_53.HTTPError(400, 'Bad Request') return [entry.to_dict() for entry in VAR_101] def FUNC_23(self, VAR_17): try: return [entry.to_dict() for entry in self.model.listdir(VAR_17)] except ValueError: raise VAR_53.HTTPError(400, 'Bad Request') def FUNC_24(self, VAR_22): if not VAR_22.strip(): VAR_102 = '[]' else: with Performance(_('processing whole search request')): VAR_114 = self.model.search(VAR_22.strip()) with Performance(_('rendering search results as json')): VAR_102 = [entry.to_dict() for entry in VAR_114] return VAR_102 def FUNC_25(self, VAR_23): VAR_53.session['playlist'] = VAR_23 def FUNC_26(self, VAR_23, VAR_24, VAR_25, VAR_26=False): VAR_73 = self.playlistdb.savePlaylist( VAR_15=self.getUserId(), VAR_24=1 if VAR_24 else 0, VAR_23=playlist, playlisttitle=VAR_25, VAR_26=overwrite) if VAR_73 == "success": return VAR_73 else: raise VAR_53.HTTPError(400, VAR_73) def FUNC_27(self, VAR_27): VAR_73 = self.playlistdb.deletePlaylist(VAR_27, self.getUserId(), override_owner=False) if VAR_73 == "success": return VAR_73 else: raise VAR_53.HTTPError(400, VAR_73) def FUNC_28(self, VAR_27): return [entry.to_dict() for entry in self.playlistdb.loadPlaylist( VAR_27=playlistid, VAR_15=self.getUserId() )] def FUNC_29(self): return [entry.to_dict() for entry in self.model.randomMusicEntries(50)] def FUNC_30(self, VAR_28, VAR_29, VAR_12): if VAR_29 == 'public': VAR_103 = type(VAR_12) == bool and type(VAR_28) == int if VAR_103: return self.playlistdb.setPublic(VAR_15=self.getUserId(), VAR_28=plid, VAR_24=VAR_12) def FUNC_31(self): if VAR_53.session['admin'] and cherry.config['general.update_notification']: FUNC_0() VAR_104 = self.model.check_for_updates() if VAR_104: VAR_115 = VAR_104[0]['version'] VAR_116 = [] VAR_117 = [] for version in VAR_104: for update in version['features']: if update.startswith('FEATURE:'): VAR_116.append(update[len('FEATURE:'):]) elif update.startswith('FIX:'): VAR_117.append(update[len('FIX:'):]) elif update.startswith('FIXED:'): VAR_117.append(update[len('FIXED:'):]) VAR_118 = {'type': 'update', 'data': {}} VAR_118['data']['version'] = VAR_115 VAR_118['data']['features'] = VAR_116 VAR_118['data']['fixes'] = VAR_117 return VAR_118 return {'type': 'wisdom', 'data': self.model.motd()} def FUNC_32(self): VAR_74 = VAR_53.session.get('playlist', []) return VAR_74 def FUNC_33(self): return json.dumps(cherry.config['media.playable']) def FUNC_34(self): if VAR_53.session['admin']: VAR_105 = self.userdb.getUserList() for VAR_51 in VAR_105: if VAR_51['id'] == VAR_53.session['userid']: VAR_51['deletable'] = False VAR_119 = self.useroptions.forUser(VAR_51['id']) VAR_120 = VAR_119.getOptionValue('last_time_online') VAR_121 = VAR_119.getOptionValue('media.may_download') VAR_51['last_time_online'] = VAR_120 VAR_51['may_download'] = VAR_121 VAR_106 = lambda VAR_51: VAR_51['last_time_online'] VAR_105 = sorted(VAR_105, key=VAR_106, reverse=True) return json.dumps({'time': int(time.time()), 'userlist': VAR_105}) else: return json.dumps({'time': 0, 'userlist': []}) def FUNC_35(self, VAR_6, VAR_7, VAR_30): if VAR_53.session['admin']: if self.userdb.addUser(VAR_6, VAR_7, VAR_30): return 'added new VAR_51: %s' % VAR_6 else: return 'error, cannot add new VAR_51!' % VAR_6 else: return "You didn't think that would work, did you?" def FUNC_36(self, VAR_31, VAR_32, VAR_6=''): VAR_75 = VAR_6 == '' if VAR_75: VAR_6 = VAR_53.session['username'] VAR_107 = self.userdb.auth(VAR_6, VAR_31) VAR_108 = userdb.User.nobody() != VAR_107 if not VAR_108: raise VAR_53.HTTPError(403, "Forbidden") if VAR_75 or VAR_53.session['admin']: return self.userdb.changePassword(VAR_6, VAR_32) else: raise VAR_53.HTTPError(403, "Forbidden") def FUNC_37(self, VAR_15): VAR_76 = VAR_53.session['userid'] == VAR_15 if VAR_53.session['admin'] and not VAR_76: VAR_109 = self.userdb.deleteUser(VAR_15) return 'success' if VAR_109 else 'failed' else: return "You didn't think that would work, did you?" def FUNC_38(self, VAR_33="created", VAR_34=''): VAR_77 = self.playlistdb.showPlaylists(self.getUserId(), VAR_34) VAR_78 = int(time.time()) VAR_79 = False for VAR_110 in VAR_77: VAR_110['username'] = self.userdb.getNameById(VAR_110['userid']) VAR_110['type'] = 'playlist' VAR_110['age'] = VAR_78 - VAR_110['created'] if VAR_33[0] == '-': VAR_79 = True VAR_33 = VAR_33[1:] if not VAR_33 in ('username', 'age', 'title', 'default'): VAR_33 = 'created' if VAR_33 == 'default': VAR_33 = 'age' VAR_79 = False VAR_77 = sorted(VAR_77, key=lambda x: x[VAR_33], reverse = VAR_79) return VAR_77 def FUNC_39(self): VAR_53.lib.sessions.expire() FUNC_39.no_auth = True def FUNC_40(self, VAR_28, VAR_35): VAR_15 = self.getUserId() VAR_80 = self.playlistdb.createPLS(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) if VAR_80 and VAR_81: return self.serve_string_as_file(VAR_80, VAR_81+'.pls') FUNC_40.binary = True def FUNC_41(self, VAR_28, VAR_35): VAR_15 = self.getUserId() VAR_80 = self.playlistdb.createM3U(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) if VAR_80 and VAR_81: return self.serve_string_as_file(VAR_80, VAR_81+'.m3u') FUNC_41.binary = True def FUNC_42(self, VAR_36, VAR_37=False, VAR_35=''): VAR_15 = self.getUserId() if not VAR_15: raise VAR_53.HTTPError(401, _("Please log in")) VAR_35 = (hostaddr.strip().rstrip('/') + cherry.config['server.rootpath']).rstrip('/') VAR_36 = format.lower() if VAR_36 == 'm3u': VAR_111 = self.playlistdb.createM3U elif VAR_36 == 'pls': VAR_111 = self.playlistdb.createPLS else: raise VAR_53.HTTPError(400, _('Unknown VAR_23 VAR_36: {format!r}').format(VAR_36=format)) VAR_77 = self.playlistdb.showPlaylists(VAR_15, include_public=VAR_37) if not VAR_77: raise VAR_53.HTTPError(404, _('No VAR_77 found')) with MemoryZipFile() as zip: for VAR_110 in VAR_77: VAR_28 = VAR_110['plid'] VAR_122 = VAR_111(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) + '.' + VAR_36 if not VAR_110['owner']: VAR_6 = self.userdb.getNameById(VAR_110['userid']) VAR_81 = VAR_6 + '/' + VAR_81 zip.writestr(VAR_81, VAR_122) VAR_82 = 'application/x-zip-compressed' VAR_83 = 'attachment; VAR_39="playlists.zip"' VAR_53.response.headers["Content-Type"] = VAR_82 VAR_53.response.headers['Content-Disposition'] = VAR_83 return zip.getbytes() FUNC_42.exposed = True def FUNC_43(self, VAR_9): VAR_84 = cherry.config['media.basedir'] VAR_85 = os.path.join(VAR_84, VAR_9) return json.dumps(metainfo.getSongInfo(VAR_85).dict()) def FUNC_44(self): return json.dumps(audiotranscode.getEncoders()) def FUNC_45(self): return json.dumps(audiotranscode.getDecoders()) def FUNC_46(self): return json.dumps(cherry.config['media.transcode']) def FUNC_47(self): self.model.updateLibrary() return 'success' def FUNC_48(self): VAR_86 = { 'transcodingenabled': cherry.config['media.transcode'], 'fetchalbumart': cherry.config['media.fetch_album_art'], 'isadmin': VAR_53.session['admin'], 'username': VAR_53.session['username'], 'servepath': 'serve/', 'transcodepath': 'trans/', 'auto_login': self.autoLoginActive(), 'version': cherry.REPO_VERSION or cherry.VERSION, } if cherry.config['media.transcode']: VAR_112 = list(self.model.transcoder.available_decoder_formats()) VAR_86['getdecoders'] = VAR_112 VAR_113 = list(self.model.transcoder.available_encoder_formats()) VAR_86['getencoders'] = VAR_113 else: VAR_86['getdecoders'] = [] VAR_86['getencoders'] = [] return VAR_86 def FUNC_49(self, VAR_38, VAR_39): VAR_87 = 'attachment; VAR_39="'+VAR_39+'"' VAR_53.response.headers["Content-Type"] = "application/x-download" VAR_53.response.headers["Content-Disposition"] = VAR_87 return codecs.encode(VAR_38, "UTF-8") def FUNC_0(): VAR_53.session.save() VAR_40 = VAR_53.serving.request.hooks['before_finalize'] VAR_41 = VAR_53.lib.sessions.save VAR_40[:] = [h for h in VAR_40 if h.callback is not VAR_41]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 35, 41, 50, 51, 54, 64, 67, 69, 70, 76, 80, 84, 121, 124, 138, 144, 173, 180, 181, 199, 205, 216, 224, 227, 230, 238, 239, 247, 248, 255, 257, 268, 269, 275, 279, 292, 294, 296, 301, 305, 314, 332, 351, 360, 364, 369, 377, 384, 386, 394, 398, 401, 403, 412, 413, 415, 416, 422, 423, 427, 430, 435, 446, 449, 452, 456, 461, 465, 472, 478, 488, 491, 503, 511, 512, 514, 520, 523, 531, 554, 558, 562, 580, 589, 602, 610, 615, 630, 634, 642, 650, 656, 665, 669, 679, 686, 691, 694, 697, 700, 704, 725, 731, 732, 735, 737, 740, 742, 745, 754, 755, 756, 32, 33, 34, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 226, 227, 228, 229, 230, 231, 232, 233, 271, 272, 273, 274, 560 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 35, 41, 50, 51, 54, 64, 67, 69, 70, 76, 80, 84, 121, 124, 138, 144, 173, 180, 181, 199, 205, 216, 224, 227, 230, 238, 239, 247, 248, 255, 257, 268, 269, 275, 279, 292, 294, 296, 301, 303, 306, 309, 318, 336, 355, 364, 368, 373, 381, 388, 390, 398, 402, 405, 407, 416, 417, 419, 420, 426, 427, 431, 434, 439, 450, 453, 456, 460, 465, 469, 476, 482, 492, 495, 507, 515, 516, 518, 524, 527, 535, 558, 562, 566, 584, 593, 606, 614, 619, 634, 638, 646, 654, 660, 669, 673, 683, 690, 695, 698, 701, 704, 708, 729, 735, 736, 739, 741, 744, 746, 749, 758, 759, 760, 32, 33, 34, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 226, 227, 228, 229, 230, 231, 232, 233, 271, 272, 273, 274, 564 ]
4CWE-601
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from spirit.core.utils.views import is_post, post_data, is_ajax from spirit.core.utils import json_response from spirit.comment.models import Comment from .models import CommentLike from .forms import LikeForm @login_required def create(request, comment_id): comment = get_object_or_404( Comment.objects.exclude(user=request.user), pk=comment_id) form = LikeForm( user=request.user, comment=comment, data=post_data(request)) if is_post(request) and form.is_valid(): like = form.save() like.comment.increase_likes_count() if is_ajax(request): return json_response({'url_delete': like.get_delete_url()}) return redirect(request.POST.get('next', comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/like/create.html', context={ 'form': form, 'comment': comment}) @login_required def delete(request, pk): like = get_object_or_404(CommentLike, pk=pk, user=request.user) if is_post(request): like.delete() like.comment.decrease_likes_count() if is_ajax(request): url = reverse( 'spirit:comment:like:create', kwargs={'comment_id': like.comment.pk}) return json_response({'url_create': url, }) return redirect(request.POST.get('next', like.comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/like/delete.html', context={'like': like})
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from django.urls import reverse from spirit.core.utils.http import safe_redirect from spirit.core.utils.views import is_post, post_data, is_ajax from spirit.core.utils import json_response from spirit.comment.models import Comment from .models import CommentLike from .forms import LikeForm @login_required def create(request, comment_id): comment = get_object_or_404( Comment.objects.exclude(user=request.user), pk=comment_id) form = LikeForm( user=request.user, comment=comment, data=post_data(request)) if is_post(request) and form.is_valid(): like = form.save() like.comment.increase_likes_count() if is_ajax(request): return json_response({'url_delete': like.get_delete_url()}) return safe_redirect(request, 'next', comment.get_absolute_url(), method='POST') return render( request=request, template_name='spirit/comment/like/create.html', context={ 'form': form, 'comment': comment}) @login_required def delete(request, pk): like = get_object_or_404(CommentLike, pk=pk, user=request.user) if is_post(request): like.delete() like.comment.decrease_likes_count() if is_ajax(request): url = reverse( 'spirit:comment:like:create', kwargs={'comment_id': like.comment.pk}) return json_response({'url_create': url, }) return safe_redirect( request, 'next', like.comment.get_absolute_url(), method='POST') return render( request=request, template_name='spirit/comment/like/delete.html', context={'like': like})
open_redirect
{ "code": [ "from django.shortcuts import render, redirect, get_object_or_404", " return redirect(request.POST.get('next', comment.get_absolute_url()))", " return redirect(request.POST.get('next', like.comment.get_absolute_url()))" ], "line_no": [ 4, 31, 55 ] }
{ "code": [ "from django.shortcuts import render, get_object_or_404", "from spirit.core.utils.http import safe_redirect", " return safe_redirect(", " request, 'next', like.comment.get_absolute_url(), method='POST')" ], "line_no": [ 4, 7, 56, 57 ] }
from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from spirit.core.utils.views import is_post, post_data, is_ajax from spirit.core.utils import json_response from spirit.comment.models import Comment from .models import CommentLike from .forms import LikeForm @login_required def FUNC_0(VAR_0, VAR_1): VAR_3 = get_object_or_404( Comment.objects.exclude(user=VAR_0.user), VAR_2=VAR_1) VAR_4 = LikeForm( user=VAR_0.user, VAR_3=comment, data=post_data(VAR_0)) if is_post(VAR_0) and VAR_4.is_valid(): VAR_5 = VAR_4.save() VAR_5.comment.increase_likes_count() if is_ajax(VAR_0): return json_response({'url_delete': VAR_5.get_delete_url()}) return redirect(VAR_0.POST.get('next', VAR_3.get_absolute_url())) return render( VAR_0=request, template_name='spirit/VAR_3/VAR_5/FUNC_0.html', context={ 'form': VAR_4, 'comment': VAR_3}) @login_required def FUNC_1(VAR_0, VAR_2): VAR_5 = get_object_or_404(CommentLike, VAR_2=pk, user=VAR_0.user) if is_post(VAR_0): VAR_5.delete() VAR_5.comment.decrease_likes_count() if is_ajax(VAR_0): VAR_6 = reverse( 'spirit:VAR_3:VAR_5:create', kwargs={'comment_id': VAR_5.comment.pk}) return json_response({'url_create': VAR_6, }) return redirect(VAR_0.POST.get('next', VAR_5.comment.get_absolute_url())) return render( VAR_0=request, template_name='spirit/VAR_3/VAR_5/FUNC_1.html', context={'like': VAR_5})
from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from django.urls import reverse from spirit.core.utils.http import safe_redirect from spirit.core.utils.views import is_post, post_data, is_ajax from spirit.core.utils import json_response from spirit.comment.models import Comment from .models import CommentLike from .forms import LikeForm @login_required def FUNC_0(VAR_0, VAR_1): VAR_3 = get_object_or_404( Comment.objects.exclude(user=VAR_0.user), VAR_2=VAR_1) VAR_4 = LikeForm( user=VAR_0.user, VAR_3=comment, data=post_data(VAR_0)) if is_post(VAR_0) and VAR_4.is_valid(): VAR_5 = VAR_4.save() VAR_5.comment.increase_likes_count() if is_ajax(VAR_0): return json_response({'url_delete': VAR_5.get_delete_url()}) return safe_redirect(VAR_0, 'next', VAR_3.get_absolute_url(), method='POST') return render( VAR_0=request, template_name='spirit/VAR_3/VAR_5/FUNC_0.html', context={ 'form': VAR_4, 'comment': VAR_3}) @login_required def FUNC_1(VAR_0, VAR_2): VAR_5 = get_object_or_404(CommentLike, VAR_2=pk, user=VAR_0.user) if is_post(VAR_0): VAR_5.delete() VAR_5.comment.decrease_likes_count() if is_ajax(VAR_0): VAR_6 = reverse( 'spirit:VAR_3:VAR_5:create', kwargs={'comment_id': VAR_5.comment.pk}) return json_response({'url_create': VAR_6, }) return safe_redirect( VAR_0, 'next', VAR_5.comment.get_absolute_url(), method='POST') return render( VAR_0=request, template_name='spirit/VAR_3/VAR_5/FUNC_1.html', context={'like': VAR_5})
[ 1, 2, 6, 12, 13, 23, 27, 30, 32, 39, 40, 44, 48, 54, 56, 61 ]
[ 1, 2, 6, 13, 14, 24, 28, 31, 33, 40, 41, 45, 49, 55, 58, 63 ]
0CWE-22
from openapi_python_client import utils def test_snake_case_uppercase_str(): assert utils.snake_case("HTTP") == "http" assert utils.snake_case("HTTP RESPONSE") == "http_response" def test_snake_case_from_pascal_with_acronyms(): assert utils.snake_case("HTTPResponse") == "http_response" assert utils.snake_case("APIClientHTTPResponse") == "api_client_http_response" assert utils.snake_case("OAuthClientHTTPResponse") == "o_auth_client_http_response" def test_snake_case_from_pascal(): assert utils.snake_case("HttpResponsePascalCase") == "http_response_pascal_case" def test_snake_case_from_camel(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def test_spinal_case(): assert utils.spinal_case("keep_alive") == "keep-alive"
from openapi_python_client import utils def test_snake_case_uppercase_str(): assert utils.snake_case("HTTP") == "http" assert utils.snake_case("HTTP RESPONSE") == "http_response" def test_snake_case_from_pascal_with_acronyms(): assert utils.snake_case("HTTPResponse") == "http_response" assert utils.snake_case("APIClientHTTPResponse") == "api_client_http_response" assert utils.snake_case("OAuthClientHTTPResponse") == "o_auth_client_http_response" def test_snake_case_from_pascal(): assert utils.snake_case("HttpResponsePascalCase") == "http_response_pascal_case" def test_snake_case_from_camel(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def test_kebab_case(): assert utils.kebab_case("keep_alive") == "keep-alive"
path_disclosure
{ "code": [ "def test_spinal_case():", " assert utils.spinal_case(\"keep_alive\") == \"keep-alive\"" ], "line_no": [ 23, 24 ] }
{ "code": [ "def test_kebab_case():", " assert utils.kebab_case(\"keep_alive\") == \"keep-alive\"" ], "line_no": [ 23, 24 ] }
from openapi_python_client import utils def FUNC_0(): assert utils.snake_case("HTTP") == "http" assert utils.snake_case("HTTP RESPONSE") == "http_response" def FUNC_1(): assert utils.snake_case("HTTPResponse") == "http_response" assert utils.snake_case("APIClientHTTPResponse") == "api_client_http_response" assert utils.snake_case("OAuthClientHTTPResponse") == "o_auth_client_http_response" def FUNC_2(): assert utils.snake_case("HttpResponsePascalCase") == "http_response_pascal_case" def FUNC_3(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def FUNC_4(): assert utils.spinal_case("keep_alive") == "keep-alive"
from openapi_python_client import utils def FUNC_0(): assert utils.snake_case("HTTP") == "http" assert utils.snake_case("HTTP RESPONSE") == "http_response" def FUNC_1(): assert utils.snake_case("HTTPResponse") == "http_response" assert utils.snake_case("APIClientHTTPResponse") == "api_client_http_response" assert utils.snake_case("OAuthClientHTTPResponse") == "o_auth_client_http_response" def FUNC_2(): assert utils.snake_case("HttpResponsePascalCase") == "http_response_pascal_case" def FUNC_3(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def FUNC_4(): assert utils.kebab_case("keep_alive") == "keep-alive"
[ 2, 3, 7, 8, 13, 14, 17, 18, 21, 22, 25 ]
[ 2, 3, 7, 8, 13, 14, 17, 18, 21, 22, 25 ]
5CWE-94
# -*- coding: utf-8 -*- # # Copyright © 2014 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions # of the GNU General Public License v.2, or (at your option) any later # version. This program is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY expressed or implied, including the # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. You # should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # Any Red Hat trademarks that are incorporated in the source # code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission # of Red Hat, Inc. # ''' MirrorManager2 xmlrpc controller. ''' import base64 import pickle import bz2 import flask from flaskext.xmlrpc import XMLRPCHandler, Fault from mirrormanager2.app import APP, ADMIN, SESSION from mirrormanager2.lib import model from mirrormanager2.lib.hostconfig import read_host_config XMLRPC = XMLRPCHandler('xmlrpc') XMLRPC.connect(APP, '/xmlrpc') @XMLRPC.register def checkin(pickledata): config = pickle.loads(bz2.decompress(base64.urlsafe_b64decode(pickledata))) r, message = read_host_config(SESSION, config) if r is not None: return message + 'checked in successful' else: return message + 'error checking in'
# -*- coding: utf-8 -*- # # Copyright © 2014 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions # of the GNU General Public License v.2, or (at your option) any later # version. This program is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY expressed or implied, including the # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. You # should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # Any Red Hat trademarks that are incorporated in the source # code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission # of Red Hat, Inc. # ''' MirrorManager2 xmlrpc controller. ''' import base64 import pickle import json import bz2 import flask from flaskext.xmlrpc import XMLRPCHandler, Fault from mirrormanager2.app import APP, ADMIN, SESSION from mirrormanager2.lib import model from mirrormanager2.lib.hostconfig import read_host_config XMLRPC = XMLRPCHandler('xmlrpc') XMLRPC.connect(APP, '/xmlrpc') @XMLRPC.register def checkin(pickledata): uncompressed = bz2.decompress(base64.urlsafe_b64decode(pickledata)) try: config = json.loads(uncompressed) except ValueError: config = pickle.loads(uncompressed) r, message = read_host_config(SESSION, config) if r is not None: return message + 'checked in successful' else: return message + 'error checking in'
remote_code_execution
{ "code": [ " config = pickle.loads(bz2.decompress(base64.urlsafe_b64decode(pickledata)))" ], "line_no": [ 44 ] }
{ "code": [ "import json", " uncompressed = bz2.decompress(base64.urlsafe_b64decode(pickledata))", " try:", " config = json.loads(uncompressed)", " except ValueError:", " config = pickle.loads(uncompressed)" ], "line_no": [ 28, 45, 46, 47, 48, 49 ] }
import base64 import pickle import bz2 import flask from flaskext.xmlrpc import .XMLRPCHandler, Fault from mirrormanager2.app import APP, ADMIN, SESSION from mirrormanager2.lib import model from mirrormanager2.lib.hostconfig import .read_host_config VAR_0 = XMLRPCHandler('xmlrpc') VAR_0.connect(APP, '/xmlrpc') @VAR_0.register def FUNC_0(VAR_1): VAR_2 = pickle.loads(bz2.decompress(base64.urlsafe_b64decode(VAR_1))) VAR_3, VAR_4 = read_host_config(SESSION, VAR_2) if VAR_3 is not None: return VAR_4 + 'checked in successful' else: return VAR_4 + 'error checking in'
import base64 import pickle import json import bz2 import flask from flaskext.xmlrpc import .XMLRPCHandler, Fault from mirrormanager2.app import APP, ADMIN, SESSION from mirrormanager2.lib import model from mirrormanager2.lib.hostconfig import .read_host_config VAR_0 = XMLRPCHandler('xmlrpc') VAR_0.connect(APP, '/xmlrpc') @VAR_0.register def FUNC_0(VAR_1): VAR_2 = bz2.decompress(base64.urlsafe_b64decode(VAR_1)) try: VAR_5 = json.loads(VAR_2) except ValueError: VAR_5 = pickle.loads(VAR_2) VAR_3, VAR_4 = read_host_config(SESSION, VAR_5) if VAR_3 is not None: return VAR_4 + 'checked in successful' else: return VAR_4 + 'error checking in'
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 25, 29, 32, 36, 37, 40, 41, 50, 22, 23, 24 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 25, 30, 33, 37, 38, 41, 42, 55, 22, 23, 24 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil import tempfile from binascii import unhexlify from io import BytesIO from typing import Optional from urllib import parse from mock import Mock import attr from parameterized import parameterized_class from PIL import Image as Image from twisted.internet import defer from twisted.internet.defer import Deferred from synapse.logging.context import make_deferred_yieldable from synapse.rest.media.v1._base import FileInfo from synapse.rest.media.v1.filepath import MediaFilePaths from synapse.rest.media.v1.media_storage import MediaStorage from synapse.rest.media.v1.storage_provider import FileStorageProviderBackend from tests import unittest from tests.server import FakeSite, make_request class MediaStorageTests(unittest.HomeserverTestCase): needs_threadpool = True def prepare(self, reactor, clock, hs): self.test_dir = tempfile.mkdtemp(prefix="synapse-tests-") self.addCleanup(shutil.rmtree, self.test_dir) self.primary_base_path = os.path.join(self.test_dir, "primary") self.secondary_base_path = os.path.join(self.test_dir, "secondary") hs.config.media_store_path = self.primary_base_path storage_providers = [FileStorageProviderBackend(hs, self.secondary_base_path)] self.filepaths = MediaFilePaths(self.primary_base_path) self.media_storage = MediaStorage( hs, self.primary_base_path, self.filepaths, storage_providers ) def test_ensure_media_is_in_local_cache(self): media_id = "some_media_id" test_body = "Test\n" # First we create a file that is in a storage provider but not in the # local primary media store rel_path = self.filepaths.local_media_filepath_rel(media_id) secondary_path = os.path.join(self.secondary_base_path, rel_path) os.makedirs(os.path.dirname(secondary_path)) with open(secondary_path, "w") as f: f.write(test_body) # Now we run ensure_media_is_in_local_cache, which should copy the file # to the local cache. file_info = FileInfo(None, media_id) # This uses a real blocking threadpool so we have to wait for it to be # actually done :/ x = defer.ensureDeferred( self.media_storage.ensure_media_is_in_local_cache(file_info) ) # Hotloop until the threadpool does its job... self.wait_on_thread(x) local_path = self.get_success(x) self.assertTrue(os.path.exists(local_path)) # Asserts the file is under the expected local cache directory self.assertEquals( os.path.commonprefix([self.primary_base_path, local_path]), self.primary_base_path, ) with open(local_path) as f: body = f.read() self.assertEqual(test_body, body) @attr.s class _TestImage: """An image for testing thumbnailing with the expected results Attributes: data: The raw image to thumbnail content_type: The type of the image as a content type, e.g. "image/png" extension: The extension associated with the format, e.g. ".png" expected_cropped: The expected bytes from cropped thumbnailing, or None if test should just check for success. expected_scaled: The expected bytes from scaled thumbnailing, or None if test should just check for a valid image returned. """ data = attr.ib(type=bytes) content_type = attr.ib(type=bytes) extension = attr.ib(type=bytes) expected_cropped = attr.ib(type=Optional[bytes]) expected_scaled = attr.ib(type=Optional[bytes]) expected_found = attr.ib(default=True, type=bool) @parameterized_class( ("test_image",), [ # smoll png ( _TestImage( unhexlify( b"89504e470d0a1a0a0000000d4948445200000001000000010806" b"0000001f15c4890000000a49444154789c63000100000500010d" b"0a2db40000000049454e44ae426082" ), b"image/png", b".png", unhexlify( b"89504e470d0a1a0a0000000d4948445200000020000000200806" b"000000737a7af40000001a49444154789cedc101010000008220" b"ffaf6e484001000000ef0610200001194334ee0000000049454e" b"44ae426082" ), unhexlify( b"89504e470d0a1a0a0000000d4948445200000001000000010806" b"0000001f15c4890000000d49444154789c636060606000000005" b"0001a5f645400000000049454e44ae426082" ), ), ), # small lossless webp ( _TestImage( unhexlify( b"524946461a000000574542505650384c0d0000002f0000001007" b"1011118888fe0700" ), b"image/webp", b".webp", None, None, ), ), # an empty file (_TestImage(b"", b"image/gif", b".gif", None, None, False,),), ], ) class MediaRepoTests(unittest.HomeserverTestCase): hijack_auth = True user_id = "@test:user" def make_homeserver(self, reactor, clock): self.fetches = [] def get_file(destination, path, output_stream, args=None, max_size=None): """ Returns tuple[int,dict,str,int] of file length, response headers, absolute URI, and response code. """ def write_to(r): data, response = r output_stream.write(data) return response d = Deferred() d.addCallback(write_to) self.fetches.append((d, destination, path, args)) return make_deferred_yieldable(d) client = Mock() client.get_file = get_file self.storage_path = self.mktemp() self.media_store_path = self.mktemp() os.mkdir(self.storage_path) os.mkdir(self.media_store_path) config = self.default_config() config["media_store_path"] = self.media_store_path config["thumbnail_requirements"] = {} config["max_image_pixels"] = 2000000 provider_config = { "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend", "store_local": True, "store_synchronous": False, "store_remote": True, "config": {"directory": self.storage_path}, } config["media_storage_providers"] = [provider_config] hs = self.setup_test_homeserver(config=config, http_client=client) return hs def prepare(self, reactor, clock, hs): self.media_repo = hs.get_media_repository_resource() self.download_resource = self.media_repo.children[b"download"] self.thumbnail_resource = self.media_repo.children[b"thumbnail"] self.media_id = "example.com/12345" def _req(self, content_disposition): request, channel = make_request( self.reactor, FakeSite(self.download_resource), "GET", self.media_id, shorthand=False, await_result=False, ) self.pump() # We've made one fetch, to example.com, using the media URL, and asking # the other server not to do a remote fetch self.assertEqual(len(self.fetches), 1) self.assertEqual(self.fetches[0][1], "example.com") self.assertEqual( self.fetches[0][2], "/_matrix/media/r0/download/" + self.media_id ) self.assertEqual(self.fetches[0][3], {"allow_remote": "false"}) headers = { b"Content-Length": [b"%d" % (len(self.test_image.data))], b"Content-Type": [self.test_image.content_type], } if content_disposition: headers[b"Content-Disposition"] = [content_disposition] self.fetches[0][0].callback( (self.test_image.data, (len(self.test_image.data), headers)) ) self.pump() self.assertEqual(channel.code, 200) return channel def test_disposition_filename_ascii(self): """ If the filename is filename=<ascii> then Synapse will decode it as an ASCII string, and use filename= in the response. """ channel = self._req(b"inline; filename=out" + self.test_image.extension) headers = channel.headers self.assertEqual( headers.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual( headers.getRawHeaders(b"Content-Disposition"), [b"inline; filename=out" + self.test_image.extension], ) def test_disposition_filenamestar_utf8escaped(self): """ If the filename is filename=*utf8''<utf8 escaped> then Synapse will correctly decode it as the UTF-8 string, and use filename* in the response. """ filename = parse.quote("\u2603".encode("utf8")).encode("ascii") channel = self._req( b"inline; filename*=utf-8''" + filename + self.test_image.extension ) headers = channel.headers self.assertEqual( headers.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual( headers.getRawHeaders(b"Content-Disposition"), [b"inline; filename*=utf-8''" + filename + self.test_image.extension], ) def test_disposition_none(self): """ If there is no filename, one isn't passed on in the Content-Disposition of the request. """ channel = self._req(None) headers = channel.headers self.assertEqual( headers.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual(headers.getRawHeaders(b"Content-Disposition"), None) def test_thumbnail_crop(self): self._test_thumbnail( "crop", self.test_image.expected_cropped, self.test_image.expected_found ) def test_thumbnail_scale(self): self._test_thumbnail( "scale", self.test_image.expected_scaled, self.test_image.expected_found ) def _test_thumbnail(self, method, expected_body, expected_found): params = "?width=32&height=32&method=" + method request, channel = make_request( self.reactor, FakeSite(self.thumbnail_resource), "GET", self.media_id + params, shorthand=False, await_result=False, ) self.pump() headers = { b"Content-Length": [b"%d" % (len(self.test_image.data))], b"Content-Type": [self.test_image.content_type], } self.fetches[0][0].callback( (self.test_image.data, (len(self.test_image.data), headers)) ) self.pump() if expected_found: self.assertEqual(channel.code, 200) if expected_body is not None: self.assertEqual( channel.result["body"], expected_body, channel.result["body"] ) else: # ensure that the result is at least some valid image Image.open(BytesIO(channel.result["body"])) else: # A 404 with a JSON body. self.assertEqual(channel.code, 404) self.assertEqual( channel.json_body, { "errcode": "M_NOT_FOUND", "error": "Not found [b'example.com', b'12345']", }, )
# -*- coding: utf-8 -*- # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil import tempfile from binascii import unhexlify from io import BytesIO from typing import Optional from urllib import parse from mock import Mock import attr from parameterized import parameterized_class from PIL import Image as Image from twisted.internet import defer from twisted.internet.defer import Deferred from synapse.logging.context import make_deferred_yieldable from synapse.rest.media.v1._base import FileInfo from synapse.rest.media.v1.filepath import MediaFilePaths from synapse.rest.media.v1.media_storage import MediaStorage from synapse.rest.media.v1.storage_provider import FileStorageProviderBackend from tests import unittest from tests.server import FakeSite, make_request class MediaStorageTests(unittest.HomeserverTestCase): needs_threadpool = True def prepare(self, reactor, clock, hs): self.test_dir = tempfile.mkdtemp(prefix="synapse-tests-") self.addCleanup(shutil.rmtree, self.test_dir) self.primary_base_path = os.path.join(self.test_dir, "primary") self.secondary_base_path = os.path.join(self.test_dir, "secondary") hs.config.media_store_path = self.primary_base_path storage_providers = [FileStorageProviderBackend(hs, self.secondary_base_path)] self.filepaths = MediaFilePaths(self.primary_base_path) self.media_storage = MediaStorage( hs, self.primary_base_path, self.filepaths, storage_providers ) def test_ensure_media_is_in_local_cache(self): media_id = "some_media_id" test_body = "Test\n" # First we create a file that is in a storage provider but not in the # local primary media store rel_path = self.filepaths.local_media_filepath_rel(media_id) secondary_path = os.path.join(self.secondary_base_path, rel_path) os.makedirs(os.path.dirname(secondary_path)) with open(secondary_path, "w") as f: f.write(test_body) # Now we run ensure_media_is_in_local_cache, which should copy the file # to the local cache. file_info = FileInfo(None, media_id) # This uses a real blocking threadpool so we have to wait for it to be # actually done :/ x = defer.ensureDeferred( self.media_storage.ensure_media_is_in_local_cache(file_info) ) # Hotloop until the threadpool does its job... self.wait_on_thread(x) local_path = self.get_success(x) self.assertTrue(os.path.exists(local_path)) # Asserts the file is under the expected local cache directory self.assertEquals( os.path.commonprefix([self.primary_base_path, local_path]), self.primary_base_path, ) with open(local_path) as f: body = f.read() self.assertEqual(test_body, body) @attr.s class _TestImage: """An image for testing thumbnailing with the expected results Attributes: data: The raw image to thumbnail content_type: The type of the image as a content type, e.g. "image/png" extension: The extension associated with the format, e.g. ".png" expected_cropped: The expected bytes from cropped thumbnailing, or None if test should just check for success. expected_scaled: The expected bytes from scaled thumbnailing, or None if test should just check for a valid image returned. """ data = attr.ib(type=bytes) content_type = attr.ib(type=bytes) extension = attr.ib(type=bytes) expected_cropped = attr.ib(type=Optional[bytes]) expected_scaled = attr.ib(type=Optional[bytes]) expected_found = attr.ib(default=True, type=bool) @parameterized_class( ("test_image",), [ # smoll png ( _TestImage( unhexlify( b"89504e470d0a1a0a0000000d4948445200000001000000010806" b"0000001f15c4890000000a49444154789c63000100000500010d" b"0a2db40000000049454e44ae426082" ), b"image/png", b".png", unhexlify( b"89504e470d0a1a0a0000000d4948445200000020000000200806" b"000000737a7af40000001a49444154789cedc101010000008220" b"ffaf6e484001000000ef0610200001194334ee0000000049454e" b"44ae426082" ), unhexlify( b"89504e470d0a1a0a0000000d4948445200000001000000010806" b"0000001f15c4890000000d49444154789c636060606000000005" b"0001a5f645400000000049454e44ae426082" ), ), ), # small lossless webp ( _TestImage( unhexlify( b"524946461a000000574542505650384c0d0000002f0000001007" b"1011118888fe0700" ), b"image/webp", b".webp", None, None, ), ), # an empty file (_TestImage(b"", b"image/gif", b".gif", None, None, False,),), ], ) class MediaRepoTests(unittest.HomeserverTestCase): hijack_auth = True user_id = "@test:user" def make_homeserver(self, reactor, clock): self.fetches = [] def get_file(destination, path, output_stream, args=None, max_size=None): """ Returns tuple[int,dict,str,int] of file length, response headers, absolute URI, and response code. """ def write_to(r): data, response = r output_stream.write(data) return response d = Deferred() d.addCallback(write_to) self.fetches.append((d, destination, path, args)) return make_deferred_yieldable(d) client = Mock() client.get_file = get_file self.storage_path = self.mktemp() self.media_store_path = self.mktemp() os.mkdir(self.storage_path) os.mkdir(self.media_store_path) config = self.default_config() config["media_store_path"] = self.media_store_path config["thumbnail_requirements"] = {} config["max_image_pixels"] = 2000000 provider_config = { "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend", "store_local": True, "store_synchronous": False, "store_remote": True, "config": {"directory": self.storage_path}, } config["media_storage_providers"] = [provider_config] hs = self.setup_test_homeserver(config=config, federation_http_client=client) return hs def prepare(self, reactor, clock, hs): self.media_repo = hs.get_media_repository_resource() self.download_resource = self.media_repo.children[b"download"] self.thumbnail_resource = self.media_repo.children[b"thumbnail"] self.media_id = "example.com/12345" def _req(self, content_disposition): request, channel = make_request( self.reactor, FakeSite(self.download_resource), "GET", self.media_id, shorthand=False, await_result=False, ) self.pump() # We've made one fetch, to example.com, using the media URL, and asking # the other server not to do a remote fetch self.assertEqual(len(self.fetches), 1) self.assertEqual(self.fetches[0][1], "example.com") self.assertEqual( self.fetches[0][2], "/_matrix/media/r0/download/" + self.media_id ) self.assertEqual(self.fetches[0][3], {"allow_remote": "false"}) headers = { b"Content-Length": [b"%d" % (len(self.test_image.data))], b"Content-Type": [self.test_image.content_type], } if content_disposition: headers[b"Content-Disposition"] = [content_disposition] self.fetches[0][0].callback( (self.test_image.data, (len(self.test_image.data), headers)) ) self.pump() self.assertEqual(channel.code, 200) return channel def test_disposition_filename_ascii(self): """ If the filename is filename=<ascii> then Synapse will decode it as an ASCII string, and use filename= in the response. """ channel = self._req(b"inline; filename=out" + self.test_image.extension) headers = channel.headers self.assertEqual( headers.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual( headers.getRawHeaders(b"Content-Disposition"), [b"inline; filename=out" + self.test_image.extension], ) def test_disposition_filenamestar_utf8escaped(self): """ If the filename is filename=*utf8''<utf8 escaped> then Synapse will correctly decode it as the UTF-8 string, and use filename* in the response. """ filename = parse.quote("\u2603".encode("utf8")).encode("ascii") channel = self._req( b"inline; filename*=utf-8''" + filename + self.test_image.extension ) headers = channel.headers self.assertEqual( headers.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual( headers.getRawHeaders(b"Content-Disposition"), [b"inline; filename*=utf-8''" + filename + self.test_image.extension], ) def test_disposition_none(self): """ If there is no filename, one isn't passed on in the Content-Disposition of the request. """ channel = self._req(None) headers = channel.headers self.assertEqual( headers.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual(headers.getRawHeaders(b"Content-Disposition"), None) def test_thumbnail_crop(self): self._test_thumbnail( "crop", self.test_image.expected_cropped, self.test_image.expected_found ) def test_thumbnail_scale(self): self._test_thumbnail( "scale", self.test_image.expected_scaled, self.test_image.expected_found ) def _test_thumbnail(self, method, expected_body, expected_found): params = "?width=32&height=32&method=" + method request, channel = make_request( self.reactor, FakeSite(self.thumbnail_resource), "GET", self.media_id + params, shorthand=False, await_result=False, ) self.pump() headers = { b"Content-Length": [b"%d" % (len(self.test_image.data))], b"Content-Type": [self.test_image.content_type], } self.fetches[0][0].callback( (self.test_image.data, (len(self.test_image.data), headers)) ) self.pump() if expected_found: self.assertEqual(channel.code, 200) if expected_body is not None: self.assertEqual( channel.result["body"], expected_body, channel.result["body"] ) else: # ensure that the result is at least some valid image Image.open(BytesIO(channel.result["body"])) else: # A 404 with a JSON body. self.assertEqual(channel.code, 404) self.assertEqual( channel.json_body, { "errcode": "M_NOT_FOUND", "error": "Not found [b'example.com', b'12345']", }, )
open_redirect
{ "code": [ " hs = self.setup_test_homeserver(config=config, http_client=client)" ], "line_no": [ 217 ] }
{ "code": [ " hs = self.setup_test_homeserver(config=config, federation_http_client=client)" ], "line_no": [ 217 ] }
import os import shutil import tempfile from binascii import unhexlify from io import BytesIO from typing import Optional from urllib import parse from mock import Mock import attr from parameterized import parameterized_class from PIL import Image as Image from twisted.internet import .defer from twisted.internet.defer import Deferred from synapse.logging.context import make_deferred_yieldable from synapse.rest.media.v1._base import FileInfo from synapse.rest.media.v1.filepath import MediaFilePaths from synapse.rest.media.v1.media_storage import MediaStorage from synapse.rest.media.v1.storage_provider import FileStorageProviderBackend from tests import unittest from tests.server import FakeSite, make_request class CLASS_0(unittest.HomeserverTestCase): VAR_0 = True def FUNC_0(self, VAR_1, VAR_2, VAR_3): self.test_dir = tempfile.mkdtemp(prefix="synapse-tests-") self.addCleanup(shutil.rmtree, self.test_dir) self.primary_base_path = os.path.join(self.test_dir, "primary") self.secondary_base_path = os.path.join(self.test_dir, "secondary") VAR_3.config.media_store_path = self.primary_base_path VAR_15 = [FileStorageProviderBackend(VAR_3, self.secondary_base_path)] self.filepaths = MediaFilePaths(self.primary_base_path) self.media_storage = MediaStorage( VAR_3, self.primary_base_path, self.filepaths, VAR_15 ) def FUNC_1(self): VAR_16 = "some_media_id" VAR_17 = "Test\n" VAR_18 = self.filepaths.local_media_filepath_rel(VAR_16) VAR_19 = os.path.join(self.secondary_base_path, VAR_18) os.makedirs(os.path.dirname(VAR_19)) with open(VAR_19, "w") as f: f.write(VAR_17) VAR_20 = FileInfo(None, VAR_16) VAR_21 = defer.ensureDeferred( self.media_storage.ensure_media_is_in_local_cache(VAR_20) ) self.wait_on_thread(VAR_21) VAR_22 = self.get_success(VAR_21) self.assertTrue(os.path.exists(VAR_22)) self.assertEquals( os.path.commonprefix([self.primary_base_path, VAR_22]), self.primary_base_path, ) with open(VAR_22) as f: VAR_36 = f.read() self.assertEqual(VAR_17, VAR_36) @attr.s class CLASS_1: VAR_4 = attr.ib(type=bytes) VAR_5 = attr.ib(type=bytes) VAR_6 = attr.ib(type=bytes) VAR_7 = attr.ib(type=Optional[bytes]) VAR_8 = attr.ib(type=Optional[bytes]) VAR_9 = attr.ib(default=True, type=bool) @parameterized_class( ("test_image",), [ ( CLASS_1( unhexlify( b"89504e470d0a1a0a0000000d4948445200000001000000010806" b"0000001f15c4890000000a49444154789c63000100000500010d" b"0a2db40000000049454e44ae426082" ), b"image/png", b".png", unhexlify( b"89504e470d0a1a0a0000000d4948445200000020000000200806" b"000000737a7af40000001a49444154789cedc101010000008220" b"ffaf6e484001000000ef0610200001194334ee0000000049454e" b"44ae426082" ), unhexlify( b"89504e470d0a1a0a0000000d4948445200000001000000010806" b"0000001f15c4890000000d49444154789c636060606000000005" b"0001a5f645400000000049454e44ae426082" ), ), ), ( CLASS_1( unhexlify( b"524946461a000000574542505650384c0d0000002f0000001007" b"1011118888fe0700" ), b"image/webp", b".webp", None, None, ), ), (CLASS_1(b"", b"image/gif", b".gif", None, None, False,),), ], ) class CLASS_2(unittest.HomeserverTestCase): VAR_10 = True VAR_11 = "@test:user" def FUNC_2(self, VAR_1, VAR_2): self.fetches = [] def FUNC_10(VAR_23, VAR_24, VAR_25, VAR_26=None, VAR_27=None): def FUNC_11(VAR_37): VAR_4, VAR_39 = VAR_37 VAR_25.write(VAR_4) return VAR_39 VAR_38 = Deferred() VAR_38.addCallback(FUNC_11) self.fetches.append((VAR_38, VAR_23, VAR_24, VAR_26)) return make_deferred_yieldable(VAR_38) VAR_28 = Mock() VAR_28.get_file = FUNC_10 self.storage_path = self.mktemp() self.media_store_path = self.mktemp() os.mkdir(self.storage_path) os.mkdir(self.media_store_path) VAR_29 = self.default_config() VAR_29["media_store_path"] = self.media_store_path VAR_29["thumbnail_requirements"] = {} VAR_29["max_image_pixels"] = 2000000 VAR_30 = { "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend", "store_local": True, "store_synchronous": False, "store_remote": True, "config": {"directory": self.storage_path}, } VAR_29["media_storage_providers"] = [VAR_30] VAR_3 = self.setup_test_homeserver(VAR_29=config, http_client=VAR_28) return VAR_3 def FUNC_0(self, VAR_1, VAR_2, VAR_3): self.media_repo = VAR_3.get_media_repository_resource() self.download_resource = self.media_repo.children[b"download"] self.thumbnail_resource = self.media_repo.children[b"thumbnail"] self.media_id = "example.com/12345" def FUNC_3(self, VAR_12): VAR_31, VAR_32 = make_request( self.reactor, FakeSite(self.download_resource), "GET", self.media_id, shorthand=False, await_result=False, ) self.pump() self.assertEqual(len(self.fetches), 1) self.assertEqual(self.fetches[0][1], "example.com") self.assertEqual( self.fetches[0][2], "/_matrix/media/r0/download/" + self.media_id ) self.assertEqual(self.fetches[0][3], {"allow_remote": "false"}) VAR_33 = { b"Content-Length": [b"%d" % (len(self.test_image.data))], b"Content-Type": [self.test_image.content_type], } if VAR_12: VAR_33[b"Content-Disposition"] = [VAR_12] self.fetches[0][0].callback( (self.test_image.data, (len(self.test_image.data), VAR_33)) ) self.pump() self.assertEqual(VAR_32.code, 200) return VAR_32 def FUNC_4(self): VAR_32 = self._req(b"inline; VAR_34=out" + self.test_image.extension) VAR_33 = VAR_32.headers self.assertEqual( VAR_33.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual( VAR_33.getRawHeaders(b"Content-Disposition"), [b"inline; VAR_34=out" + self.test_image.extension], ) def FUNC_5(self): VAR_34 = parse.quote("\u2603".encode("utf8")).encode("ascii") VAR_32 = self._req( b"inline; VAR_34*=utf-8''" + VAR_34 + self.test_image.extension ) VAR_33 = VAR_32.headers self.assertEqual( VAR_33.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual( VAR_33.getRawHeaders(b"Content-Disposition"), [b"inline; VAR_34*=utf-8''" + VAR_34 + self.test_image.extension], ) def FUNC_6(self): VAR_32 = self._req(None) VAR_33 = VAR_32.headers self.assertEqual( VAR_33.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual(VAR_33.getRawHeaders(b"Content-Disposition"), None) def FUNC_7(self): self._test_thumbnail( "crop", self.test_image.expected_cropped, self.test_image.expected_found ) def FUNC_8(self): self._test_thumbnail( "scale", self.test_image.expected_scaled, self.test_image.expected_found ) def FUNC_9(self, VAR_13, VAR_14, VAR_9): VAR_35 = "?width=32&height=32&VAR_13=" + VAR_13 VAR_31, VAR_32 = make_request( self.reactor, FakeSite(self.thumbnail_resource), "GET", self.media_id + VAR_35, shorthand=False, await_result=False, ) self.pump() VAR_33 = { b"Content-Length": [b"%d" % (len(self.test_image.data))], b"Content-Type": [self.test_image.content_type], } self.fetches[0][0].callback( (self.test_image.data, (len(self.test_image.data), VAR_33)) ) self.pump() if VAR_9: self.assertEqual(VAR_32.code, 200) if VAR_14 is not None: self.assertEqual( VAR_32.result["body"], VAR_14, VAR_32.result["body"] ) else: Image.open(BytesIO(VAR_32.result["body"])) else: self.assertEqual(VAR_32.code, 404) self.assertEqual( VAR_32.json_body, { "errcode": "M_NOT_FOUND", "error": "Not found [b'example.com', b'12345']", }, )
import os import shutil import tempfile from binascii import unhexlify from io import BytesIO from typing import Optional from urllib import parse from mock import Mock import attr from parameterized import parameterized_class from PIL import Image as Image from twisted.internet import .defer from twisted.internet.defer import Deferred from synapse.logging.context import make_deferred_yieldable from synapse.rest.media.v1._base import FileInfo from synapse.rest.media.v1.filepath import MediaFilePaths from synapse.rest.media.v1.media_storage import MediaStorage from synapse.rest.media.v1.storage_provider import FileStorageProviderBackend from tests import unittest from tests.server import FakeSite, make_request class CLASS_0(unittest.HomeserverTestCase): VAR_0 = True def FUNC_0(self, VAR_1, VAR_2, VAR_3): self.test_dir = tempfile.mkdtemp(prefix="synapse-tests-") self.addCleanup(shutil.rmtree, self.test_dir) self.primary_base_path = os.path.join(self.test_dir, "primary") self.secondary_base_path = os.path.join(self.test_dir, "secondary") VAR_3.config.media_store_path = self.primary_base_path VAR_15 = [FileStorageProviderBackend(VAR_3, self.secondary_base_path)] self.filepaths = MediaFilePaths(self.primary_base_path) self.media_storage = MediaStorage( VAR_3, self.primary_base_path, self.filepaths, VAR_15 ) def FUNC_1(self): VAR_16 = "some_media_id" VAR_17 = "Test\n" VAR_18 = self.filepaths.local_media_filepath_rel(VAR_16) VAR_19 = os.path.join(self.secondary_base_path, VAR_18) os.makedirs(os.path.dirname(VAR_19)) with open(VAR_19, "w") as f: f.write(VAR_17) VAR_20 = FileInfo(None, VAR_16) VAR_21 = defer.ensureDeferred( self.media_storage.ensure_media_is_in_local_cache(VAR_20) ) self.wait_on_thread(VAR_21) VAR_22 = self.get_success(VAR_21) self.assertTrue(os.path.exists(VAR_22)) self.assertEquals( os.path.commonprefix([self.primary_base_path, VAR_22]), self.primary_base_path, ) with open(VAR_22) as f: VAR_36 = f.read() self.assertEqual(VAR_17, VAR_36) @attr.s class CLASS_1: VAR_4 = attr.ib(type=bytes) VAR_5 = attr.ib(type=bytes) VAR_6 = attr.ib(type=bytes) VAR_7 = attr.ib(type=Optional[bytes]) VAR_8 = attr.ib(type=Optional[bytes]) VAR_9 = attr.ib(default=True, type=bool) @parameterized_class( ("test_image",), [ ( CLASS_1( unhexlify( b"89504e470d0a1a0a0000000d4948445200000001000000010806" b"0000001f15c4890000000a49444154789c63000100000500010d" b"0a2db40000000049454e44ae426082" ), b"image/png", b".png", unhexlify( b"89504e470d0a1a0a0000000d4948445200000020000000200806" b"000000737a7af40000001a49444154789cedc101010000008220" b"ffaf6e484001000000ef0610200001194334ee0000000049454e" b"44ae426082" ), unhexlify( b"89504e470d0a1a0a0000000d4948445200000001000000010806" b"0000001f15c4890000000d49444154789c636060606000000005" b"0001a5f645400000000049454e44ae426082" ), ), ), ( CLASS_1( unhexlify( b"524946461a000000574542505650384c0d0000002f0000001007" b"1011118888fe0700" ), b"image/webp", b".webp", None, None, ), ), (CLASS_1(b"", b"image/gif", b".gif", None, None, False,),), ], ) class CLASS_2(unittest.HomeserverTestCase): VAR_10 = True VAR_11 = "@test:user" def FUNC_2(self, VAR_1, VAR_2): self.fetches = [] def FUNC_10(VAR_23, VAR_24, VAR_25, VAR_26=None, VAR_27=None): def FUNC_11(VAR_37): VAR_4, VAR_39 = VAR_37 VAR_25.write(VAR_4) return VAR_39 VAR_38 = Deferred() VAR_38.addCallback(FUNC_11) self.fetches.append((VAR_38, VAR_23, VAR_24, VAR_26)) return make_deferred_yieldable(VAR_38) VAR_28 = Mock() VAR_28.get_file = FUNC_10 self.storage_path = self.mktemp() self.media_store_path = self.mktemp() os.mkdir(self.storage_path) os.mkdir(self.media_store_path) VAR_29 = self.default_config() VAR_29["media_store_path"] = self.media_store_path VAR_29["thumbnail_requirements"] = {} VAR_29["max_image_pixels"] = 2000000 VAR_30 = { "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend", "store_local": True, "store_synchronous": False, "store_remote": True, "config": {"directory": self.storage_path}, } VAR_29["media_storage_providers"] = [VAR_30] VAR_3 = self.setup_test_homeserver(VAR_29=config, federation_http_client=VAR_28) return VAR_3 def FUNC_0(self, VAR_1, VAR_2, VAR_3): self.media_repo = VAR_3.get_media_repository_resource() self.download_resource = self.media_repo.children[b"download"] self.thumbnail_resource = self.media_repo.children[b"thumbnail"] self.media_id = "example.com/12345" def FUNC_3(self, VAR_12): VAR_31, VAR_32 = make_request( self.reactor, FakeSite(self.download_resource), "GET", self.media_id, shorthand=False, await_result=False, ) self.pump() self.assertEqual(len(self.fetches), 1) self.assertEqual(self.fetches[0][1], "example.com") self.assertEqual( self.fetches[0][2], "/_matrix/media/r0/download/" + self.media_id ) self.assertEqual(self.fetches[0][3], {"allow_remote": "false"}) VAR_33 = { b"Content-Length": [b"%d" % (len(self.test_image.data))], b"Content-Type": [self.test_image.content_type], } if VAR_12: VAR_33[b"Content-Disposition"] = [VAR_12] self.fetches[0][0].callback( (self.test_image.data, (len(self.test_image.data), VAR_33)) ) self.pump() self.assertEqual(VAR_32.code, 200) return VAR_32 def FUNC_4(self): VAR_32 = self._req(b"inline; VAR_34=out" + self.test_image.extension) VAR_33 = VAR_32.headers self.assertEqual( VAR_33.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual( VAR_33.getRawHeaders(b"Content-Disposition"), [b"inline; VAR_34=out" + self.test_image.extension], ) def FUNC_5(self): VAR_34 = parse.quote("\u2603".encode("utf8")).encode("ascii") VAR_32 = self._req( b"inline; VAR_34*=utf-8''" + VAR_34 + self.test_image.extension ) VAR_33 = VAR_32.headers self.assertEqual( VAR_33.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual( VAR_33.getRawHeaders(b"Content-Disposition"), [b"inline; VAR_34*=utf-8''" + VAR_34 + self.test_image.extension], ) def FUNC_6(self): VAR_32 = self._req(None) VAR_33 = VAR_32.headers self.assertEqual( VAR_33.getRawHeaders(b"Content-Type"), [self.test_image.content_type] ) self.assertEqual(VAR_33.getRawHeaders(b"Content-Disposition"), None) def FUNC_7(self): self._test_thumbnail( "crop", self.test_image.expected_cropped, self.test_image.expected_found ) def FUNC_8(self): self._test_thumbnail( "scale", self.test_image.expected_scaled, self.test_image.expected_found ) def FUNC_9(self, VAR_13, VAR_14, VAR_9): VAR_35 = "?width=32&height=32&VAR_13=" + VAR_13 VAR_31, VAR_32 = make_request( self.reactor, FakeSite(self.thumbnail_resource), "GET", self.media_id + VAR_35, shorthand=False, await_result=False, ) self.pump() VAR_33 = { b"Content-Length": [b"%d" % (len(self.test_image.data))], b"Content-Type": [self.test_image.content_type], } self.fetches[0][0].callback( (self.test_image.data, (len(self.test_image.data), VAR_33)) ) self.pump() if VAR_9: self.assertEqual(VAR_32.code, 200) if VAR_14 is not None: self.assertEqual( VAR_32.result["body"], VAR_14, VAR_32.result["body"] ) else: Image.open(BytesIO(VAR_32.result["body"])) else: self.assertEqual(VAR_32.code, 404) self.assertEqual( VAR_32.json_body, { "errcode": "M_NOT_FOUND", "error": "Not found [b'example.com', b'12345']", }, )
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 22, 24, 28, 31, 37, 40, 41, 43, 45, 49, 52, 54, 56, 61, 65, 66, 67, 70, 72, 75, 76, 77, 79, 80, 81, 85, 86, 88, 90, 92, 93, 98, 101, 103, 104, 108, 118, 125, 126, 130, 153, 166, 171, 174, 176, 178, 184, 189, 194, 197, 202, 207, 216, 218, 220, 222, 226, 228, 230, 240, 241, 242, 249, 256, 260, 263, 265, 272, 281, 292, 301, 308, 314, 319, 324, 336, 345, 353, 356, 365, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 267, 268, 269, 270, 283, 284, 285, 286, 287, 303, 304, 305, 306, 180, 181, 182, 183 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 22, 24, 28, 31, 37, 40, 41, 43, 45, 49, 52, 54, 56, 61, 65, 66, 67, 70, 72, 75, 76, 77, 79, 80, 81, 85, 86, 88, 90, 92, 93, 98, 101, 103, 104, 108, 118, 125, 126, 130, 153, 166, 171, 174, 176, 178, 184, 189, 194, 197, 202, 207, 216, 218, 220, 222, 226, 228, 230, 240, 241, 242, 249, 256, 260, 263, 265, 272, 281, 292, 301, 308, 314, 319, 324, 336, 345, 353, 356, 365, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 267, 268, 269, 270, 283, 284, 285, 286, 287, 303, 304, 305, 306, 180, 181, 182, 183 ]
4CWE-601
import itertools from flask import request, abort, _app_ctx_stack, redirect from flask_security.core import AnonymousUser from security_monkey.datastore import User try: from flask.ext.login import current_user except ImportError: current_user = None from .models import RBACRole, RBACUserMixin from . import anonymous from flask import Response import json class AccessControlList(object): """ This class record rules for access controling. """ def __init__(self): self._allowed = [] self._exempt = [] self.seted = False def allow(self, role, method, resource, with_children=True): """Add allowing rules. :param role: Role of this rule. :param method: Method to allow in rule, include GET, POST, PUT etc. :param resource: Resource also view function. :param with_children: Allow role's children in rule as well if with_children is `True` """ if with_children: for r in role.get_children(): permission = (r.name, method, resource) if permission not in self._allowed: self._allowed.append(permission) permission = (role.name, method, resource) if permission not in self._allowed: self._allowed.append(permission) def exempt(self, view_func): """Exempt a view function from being checked permission :param view_func: The view function exempt from checking. """ if not view_func in self._exempt: self._exempt.append(view_func) def is_allowed(self, role, method, resource): """Check whether role is allowed to access resource :param role: Role to be checked. :param method: Method to be checked. :param resource: View function to be checked. """ return (role, method, resource) in self._allowed def is_exempt(self, view_func): """Return whether view_func is exempted. :param view_func: View function to be checked. """ return view_func in self._exempt class _RBACState(object): """Records configuration for Flask-RBAC""" def __init__(self, rbac, app): self.rbac = rbac self.app = app class RBAC(object): """ This class implements role-based access control module in Flask. There are two way to initialize Flask-RBAC:: app = Flask(__name__) rbac = RBAC(app) :param app: the Flask object """ _role_model = RBACRole _user_model = RBACUserMixin def __init__(self, app): self.acl = AccessControlList() self.before_acl = [] self.app = app self.init_app(app) def init_app(self, app): # Add (RBAC, app) to flask extensions. # Add hook to authenticate permission before request. if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['rbac'] = _RBACState(self, app) self.acl.allow(anonymous, 'GET', app.view_functions['static'].__name__) app.before_first_request(self._setup_acl) app.before_request(self._authenticate) def has_permission(self, method, endpoint, user=None): """Return whether the current user can access the resource. Example:: @app.route('/some_url', methods=['GET', 'POST']) @rbac.allow(['anonymous'], ['GET']) def a_view_func(): return Response('Blah Blah...') If you are not logged. `rbac.has_permission('GET', 'a_view_func')` return True. `rbac.has_permission('POST', 'a_view_func')` return False. :param method: The method wait to check. :param endpoint: The application endpoint. :param user: user who you need to check. Current user by default. """ app = self.get_app() _user = user or current_user roles = _user.get_roles() view_func = app.view_functions[endpoint] return self._check_permission(roles, method, view_func) def check_perm(self, role, method, callback=None): def decorator(view_func): if not self._check_permission([role], method, view_func): if callable(callback): callback() else: self._deny_hook() return view_func return decorator def allow(self, roles, methods, with_children=True): """Decorator: allow roles to access the view func with it. :param roles: List, each name of roles. Please note that, `anonymous` is refered to anonymous. If you add `anonymous` to the rule, everyone can access the resource, unless you deny other roles. :param methods: List, each name of methods. methods is valid in ['GET', 'POST', 'PUT', 'DELETE'] :param with_children: Whether allow children of roles as well. True by default. """ def decorator(view_func): _methods = [m.upper() for m in methods] for r, m, v in itertools.product(roles, _methods, [view_func.__name__]): self.before_acl.append((r, m, v, with_children)) return view_func return decorator def exempt(self, view_func): """ Decorator function Exempt a view function from being checked permission. """ self.acl.exempt(view_func.__name__) return view_func def get_app(self, reference_app=None): """ Helper to look up an app. """ if reference_app is not None: return reference_app if self.app is not None: return self.app ctx = _app_ctx_stack.top if ctx is not None: return ctx.app raise RuntimeError('application not registered on rbac ' 'instance and no application bound ' 'to current context') def _authenticate(self): app = self.get_app() assert app, "Please initialize your application into Flask-RBAC." assert self._role_model, "Please set role model before authenticate." assert self._user_model, "Please set user model before authenticate." user = current_user if not isinstance(user._get_current_object(), self._user_model) and not isinstance(user._get_current_object(), AnonymousUser): raise TypeError( "%s is not an instance of %s" % (user, self._user_model.__class__)) endpoint = request.endpoint resource = app.view_functions.get(endpoint, None) if not resource: abort(404) method = request.method if not hasattr(user, 'get_roles'): roles = [anonymous] else: roles = user.get_roles() permit = self._check_permission(roles, method, resource) if not permit: return self._deny_hook(resource=resource) def _check_permission(self, roles, method, resource): resource = resource.__name__ if self.acl.is_exempt(resource): return True if not self.acl.seted: self._setup_acl() _roles = set() _methods = {'*', method} _resources = {None, resource} _roles.add(anonymous) _roles.update(roles) for r, m, res in itertools.product(_roles, _methods, _resources): if self.acl.is_allowed(r.name, m, res): return True return False def _deny_hook(self, resource=None): app = self.get_app() if current_user.is_authenticated(): status = 403 else: status = 401 #abort(status) if app.config.get('FRONTED_BY_NGINX'): url = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login') else: url = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login') if current_user.is_authenticated(): auth_dict = { "authenticated": True, "user": current_user.email, "roles": current_user.role, } else: auth_dict = { "authenticated": False, "user": None, "url": url } return Response(response=json.dumps({"auth": auth_dict}), status=status, mimetype="application/json") def _setup_acl(self): for rn, method, resource, with_children in self.before_acl: role = self._role_model.get_by_name(rn) self.acl.allow(role, method, resource, with_children) self.acl.seted = True
import itertools from flask import request, abort, _app_ctx_stack, redirect from flask_security.core import AnonymousUser from security_monkey.datastore import User try: from flask.ext.login import current_user except ImportError: current_user = None from .models import RBACRole, RBACUserMixin from . import anonymous from flask import Response import json class AccessControlList(object): """ This class record rules for access controling. """ def __init__(self): self._allowed = [] self._exempt = [] self.seted = False def allow(self, role, method, resource, with_children=True): """Add allowing rules. :param role: Role of this rule. :param method: Method to allow in rule, include GET, POST, PUT etc. :param resource: Resource also view function. :param with_children: Allow role's children in rule as well if with_children is `True` """ if with_children: for r in role.get_children(): permission = (r.name, method, resource) if permission not in self._allowed: self._allowed.append(permission) permission = (role.name, method, resource) if permission not in self._allowed: self._allowed.append(permission) def exempt(self, view_func): """Exempt a view function from being checked permission :param view_func: The view function exempt from checking. """ if not view_func in self._exempt: self._exempt.append(view_func) def is_allowed(self, role, method, resource): """Check whether role is allowed to access resource :param role: Role to be checked. :param method: Method to be checked. :param resource: View function to be checked. """ return (role, method, resource) in self._allowed def is_exempt(self, view_func): """Return whether view_func is exempted. :param view_func: View function to be checked. """ return view_func in self._exempt class _RBACState(object): """Records configuration for Flask-RBAC""" def __init__(self, rbac, app): self.rbac = rbac self.app = app class RBAC(object): """ This class implements role-based access control module in Flask. There are two way to initialize Flask-RBAC:: app = Flask(__name__) rbac = RBAC(app) :param app: the Flask object """ _role_model = RBACRole _user_model = RBACUserMixin def __init__(self, app): self.acl = AccessControlList() self.before_acl = [] self.app = app self.init_app(app) def init_app(self, app): # Add (RBAC, app) to flask extensions. # Add hook to authenticate permission before request. if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['rbac'] = _RBACState(self, app) self.acl.allow(anonymous, 'GET', app.view_functions['static'].__name__) app.before_first_request(self._setup_acl) app.before_request(self._authenticate) def has_permission(self, method, endpoint, user=None): """Return whether the current user can access the resource. Example:: @app.route('/some_url', methods=['GET', 'POST']) @rbac.allow(['anonymous'], ['GET']) def a_view_func(): return Response('Blah Blah...') If you are not logged. `rbac.has_permission('GET', 'a_view_func')` return True. `rbac.has_permission('POST', 'a_view_func')` return False. :param method: The method wait to check. :param endpoint: The application endpoint. :param user: user who you need to check. Current user by default. """ app = self.get_app() _user = user or current_user roles = _user.get_roles() view_func = app.view_functions[endpoint] return self._check_permission(roles, method, view_func) def check_perm(self, role, method, callback=None): def decorator(view_func): if not self._check_permission([role], method, view_func): if callable(callback): callback() else: self._deny_hook() return view_func return decorator def allow(self, roles, methods, with_children=True): """Decorator: allow roles to access the view func with it. :param roles: List, each name of roles. Please note that, `anonymous` is refered to anonymous. If you add `anonymous` to the rule, everyone can access the resource, unless you deny other roles. :param methods: List, each name of methods. methods is valid in ['GET', 'POST', 'PUT', 'DELETE'] :param with_children: Whether allow children of roles as well. True by default. """ def decorator(view_func): _methods = [m.upper() for m in methods] for r, m, v in itertools.product(roles, _methods, [view_func.__name__]): self.before_acl.append((r, m, v, with_children)) return view_func return decorator def exempt(self, view_func): """ Decorator function Exempt a view function from being checked permission. """ self.acl.exempt(view_func.__name__) return view_func def get_app(self, reference_app=None): """ Helper to look up an app. """ if reference_app is not None: return reference_app if self.app is not None: return self.app ctx = _app_ctx_stack.top if ctx is not None: return ctx.app raise RuntimeError('application not registered on rbac ' 'instance and no application bound ' 'to current context') def _authenticate(self): app = self.get_app() assert app, "Please initialize your application into Flask-RBAC." assert self._role_model, "Please set role model before authenticate." assert self._user_model, "Please set user model before authenticate." user = current_user if not isinstance(user._get_current_object(), self._user_model) and not isinstance(user._get_current_object(), AnonymousUser): raise TypeError( "%s is not an instance of %s" % (user, self._user_model.__class__)) endpoint = request.endpoint resource = app.view_functions.get(endpoint, None) if not resource: abort(404) method = request.method if not hasattr(user, 'get_roles'): roles = [anonymous] else: roles = user.get_roles() permit = self._check_permission(roles, method, resource) if not permit: return self._deny_hook(resource=resource) def _check_permission(self, roles, method, resource): resource = resource.__name__ if self.acl.is_exempt(resource): return True if not self.acl.seted: self._setup_acl() _roles = set() _methods = {'*', method} _resources = {None, resource} _roles.add(anonymous) _roles.update(roles) for r, m, res in itertools.product(_roles, _methods, _resources): if self.acl.is_allowed(r.name, m, res): return True return False def _deny_hook(self, resource=None): app = self.get_app() if current_user.is_authenticated: status = 403 else: status = 401 #abort(status) if app.config.get('FRONTED_BY_NGINX'): url = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login') else: url = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login') if current_user.is_authenticated: auth_dict = { "authenticated": True, "user": current_user.email, "roles": current_user.role, } else: auth_dict = { "authenticated": False, "user": None, "url": url } return Response(response=json.dumps({"auth": auth_dict}), status=status, mimetype="application/json") def _setup_acl(self): for rn, method, resource, with_children in self.before_acl: role = self._role_model.get_by_name(rn) self.acl.allow(role, method, resource, with_children) self.acl.seted = True
open_redirect
{ "code": [ " if current_user.is_authenticated():", " if current_user.is_authenticated():" ], "line_no": [ 243, 253 ] }
{ "code": [ " if current_user.is_authenticated:", " if current_user.is_authenticated:" ], "line_no": [ 243, 253 ] }
import itertools from flask import request, abort, _app_ctx_stack, redirect from flask_security.core import AnonymousUser from security_monkey.datastore import User try: from flask.ext.login import .current_user except ImportError: VAR_15 = None from .models import .RBACRole, RBACUserMixin from . import anonymous from flask import Response import json class CLASS_0(object): def __init__(self): self._allowed = [] self._exempt = [] self.seted = False def FUNC_0(self, VAR_0, VAR_1, VAR_2, VAR_3=True): if VAR_3: for r in VAR_0.get_children(): VAR_16 = (r.name, VAR_1, VAR_2) if VAR_16 not in self._allowed: self._allowed.append(VAR_16) VAR_16 = (VAR_0.name, VAR_1, VAR_2) if VAR_16 not in self._allowed: self._allowed.append(VAR_16) def FUNC_1(self, VAR_4): if not VAR_4 in self._exempt: self._exempt.append(VAR_4) def FUNC_2(self, VAR_0, VAR_1, VAR_2): return (VAR_0, VAR_1, VAR_2) in self._allowed def FUNC_3(self, VAR_4): return VAR_4 in self._exempt class CLASS_1(object): def __init__(self, VAR_5, VAR_6): self.rbac = VAR_5 self.app = VAR_6 class CLASS_2(object): VAR_7 = RBACRole VAR_8 = RBACUserMixin def __init__(self, VAR_6): self.acl = CLASS_0() self.before_acl = [] self.app = VAR_6 self.init_app(VAR_6) def FUNC_4(self, VAR_6): if not hasattr(VAR_6, 'extensions'): VAR_6.extensions = {} VAR_6.extensions['rbac'] = CLASS_1(self, VAR_6) self.acl.allow(anonymous, 'GET', VAR_6.view_functions['static'].__name__) VAR_6.before_first_request(self._setup_acl) VAR_6.before_request(self._authenticate) def FUNC_5(self, VAR_1, VAR_9, VAR_10=None): VAR_6 = self.get_app() VAR_17 = VAR_10 or VAR_15 VAR_12 = VAR_17.get_roles() VAR_4 = VAR_6.view_functions[VAR_9] return self._check_permission(VAR_12, VAR_1, VAR_4) def FUNC_6(self, VAR_0, VAR_1, VAR_11=None): def FUNC_12(VAR_4): if not self._check_permission([VAR_0], VAR_1, VAR_4): if callable(VAR_11): callback() else: self._deny_hook() return VAR_4 return FUNC_12 def FUNC_0(self, VAR_12, VAR_13, VAR_3=True): def FUNC_12(VAR_4): VAR_21 = [m.upper() for m in VAR_13] for r, m, v in itertools.product(VAR_12, VAR_21, [VAR_4.__name__]): self.before_acl.append((r, m, v, VAR_3)) return VAR_4 return FUNC_12 def FUNC_1(self, VAR_4): self.acl.exempt(VAR_4.__name__) return VAR_4 def FUNC_7(self, VAR_14=None): if VAR_14 is not None: return VAR_14 if self.app is not None: return self.app VAR_18 = _app_ctx_stack.top if VAR_18 is not None: return VAR_18.app raise RuntimeError('application not registered on VAR_5 ' 'instance and no application bound ' 'to current context') def FUNC_8(self): VAR_6 = self.get_app() assert VAR_6, "Please initialize your application into Flask-CLASS_2." assert self._role_model, "Please set VAR_0 model before authenticate." assert self._user_model, "Please set VAR_10 model before authenticate." VAR_10 = VAR_15 if not isinstance(VAR_10._get_current_object(), self._user_model) and not isinstance(VAR_10._get_current_object(), AnonymousUser): raise TypeError( "%s is not an instance of %s" % (VAR_10, self._user_model.__class__)) VAR_9 = request.endpoint VAR_2 = VAR_6.view_functions.get(VAR_9, None) if not VAR_2: abort(404) VAR_1 = request.method if not hasattr(VAR_10, 'get_roles'): VAR_12 = [anonymous] else: VAR_12 = VAR_10.get_roles() VAR_19 = self._check_permission(VAR_12, VAR_1, VAR_2) if not VAR_19: return self._deny_hook(VAR_2=resource) def FUNC_9(self, VAR_12, VAR_1, VAR_2): VAR_2 = VAR_2.__name__ if self.acl.is_exempt(VAR_2): return True if not self.acl.seted: self._setup_acl() VAR_20 = set() VAR_21 = {'*', VAR_1} VAR_22 = {None, VAR_2} VAR_20.add(anonymous) VAR_20.update(VAR_12) for r, m, res in itertools.product(VAR_20, VAR_21, VAR_22): if self.acl.is_allowed(r.name, m, res): return True return False def FUNC_10(self, VAR_2=None): VAR_6 = self.get_app() if VAR_15.is_authenticated(): VAR_23 = 403 else: VAR_23 = 401 if VAR_6.config.get('FRONTED_BY_NGINX'): VAR_24 = "https://{}:{}{}".format(VAR_6.config.get('FQDN'), VAR_6.config.get('NGINX_PORT'), '/login') else: VAR_24 = "http://{}:{}{}".format(VAR_6.config.get('FQDN'), VAR_6.config.get('API_PORT'), '/login') if VAR_15.is_authenticated(): VAR_25 = { "authenticated": True, "user": VAR_15.email, "roles": VAR_15.role, } else: VAR_25 = { "authenticated": False, "user": None, "url": VAR_24 } return Response(response=json.dumps({"auth": VAR_25}), VAR_23=status, mimetype="application/json") def FUNC_11(self): for rn, VAR_1, VAR_2, VAR_3 in self.before_acl: VAR_0 = self._role_model.get_by_name(rn) self.acl.allow(VAR_0, VAR_1, VAR_2, VAR_3) self.acl.seted = True
import itertools from flask import request, abort, _app_ctx_stack, redirect from flask_security.core import AnonymousUser from security_monkey.datastore import User try: from flask.ext.login import .current_user except ImportError: VAR_15 = None from .models import .RBACRole, RBACUserMixin from . import anonymous from flask import Response import json class CLASS_0(object): def __init__(self): self._allowed = [] self._exempt = [] self.seted = False def FUNC_0(self, VAR_0, VAR_1, VAR_2, VAR_3=True): if VAR_3: for r in VAR_0.get_children(): VAR_16 = (r.name, VAR_1, VAR_2) if VAR_16 not in self._allowed: self._allowed.append(VAR_16) VAR_16 = (VAR_0.name, VAR_1, VAR_2) if VAR_16 not in self._allowed: self._allowed.append(VAR_16) def FUNC_1(self, VAR_4): if not VAR_4 in self._exempt: self._exempt.append(VAR_4) def FUNC_2(self, VAR_0, VAR_1, VAR_2): return (VAR_0, VAR_1, VAR_2) in self._allowed def FUNC_3(self, VAR_4): return VAR_4 in self._exempt class CLASS_1(object): def __init__(self, VAR_5, VAR_6): self.rbac = VAR_5 self.app = VAR_6 class CLASS_2(object): VAR_7 = RBACRole VAR_8 = RBACUserMixin def __init__(self, VAR_6): self.acl = CLASS_0() self.before_acl = [] self.app = VAR_6 self.init_app(VAR_6) def FUNC_4(self, VAR_6): if not hasattr(VAR_6, 'extensions'): VAR_6.extensions = {} VAR_6.extensions['rbac'] = CLASS_1(self, VAR_6) self.acl.allow(anonymous, 'GET', VAR_6.view_functions['static'].__name__) VAR_6.before_first_request(self._setup_acl) VAR_6.before_request(self._authenticate) def FUNC_5(self, VAR_1, VAR_9, VAR_10=None): VAR_6 = self.get_app() VAR_17 = VAR_10 or VAR_15 VAR_12 = VAR_17.get_roles() VAR_4 = VAR_6.view_functions[VAR_9] return self._check_permission(VAR_12, VAR_1, VAR_4) def FUNC_6(self, VAR_0, VAR_1, VAR_11=None): def FUNC_12(VAR_4): if not self._check_permission([VAR_0], VAR_1, VAR_4): if callable(VAR_11): callback() else: self._deny_hook() return VAR_4 return FUNC_12 def FUNC_0(self, VAR_12, VAR_13, VAR_3=True): def FUNC_12(VAR_4): VAR_21 = [m.upper() for m in VAR_13] for r, m, v in itertools.product(VAR_12, VAR_21, [VAR_4.__name__]): self.before_acl.append((r, m, v, VAR_3)) return VAR_4 return FUNC_12 def FUNC_1(self, VAR_4): self.acl.exempt(VAR_4.__name__) return VAR_4 def FUNC_7(self, VAR_14=None): if VAR_14 is not None: return VAR_14 if self.app is not None: return self.app VAR_18 = _app_ctx_stack.top if VAR_18 is not None: return VAR_18.app raise RuntimeError('application not registered on VAR_5 ' 'instance and no application bound ' 'to current context') def FUNC_8(self): VAR_6 = self.get_app() assert VAR_6, "Please initialize your application into Flask-CLASS_2." assert self._role_model, "Please set VAR_0 model before authenticate." assert self._user_model, "Please set VAR_10 model before authenticate." VAR_10 = VAR_15 if not isinstance(VAR_10._get_current_object(), self._user_model) and not isinstance(VAR_10._get_current_object(), AnonymousUser): raise TypeError( "%s is not an instance of %s" % (VAR_10, self._user_model.__class__)) VAR_9 = request.endpoint VAR_2 = VAR_6.view_functions.get(VAR_9, None) if not VAR_2: abort(404) VAR_1 = request.method if not hasattr(VAR_10, 'get_roles'): VAR_12 = [anonymous] else: VAR_12 = VAR_10.get_roles() VAR_19 = self._check_permission(VAR_12, VAR_1, VAR_2) if not VAR_19: return self._deny_hook(VAR_2=resource) def FUNC_9(self, VAR_12, VAR_1, VAR_2): VAR_2 = VAR_2.__name__ if self.acl.is_exempt(VAR_2): return True if not self.acl.seted: self._setup_acl() VAR_20 = set() VAR_21 = {'*', VAR_1} VAR_22 = {None, VAR_2} VAR_20.add(anonymous) VAR_20.update(VAR_12) for r, m, res in itertools.product(VAR_20, VAR_21, VAR_22): if self.acl.is_allowed(r.name, m, res): return True return False def FUNC_10(self, VAR_2=None): VAR_6 = self.get_app() if VAR_15.is_authenticated: VAR_23 = 403 else: VAR_23 = 401 if VAR_6.config.get('FRONTED_BY_NGINX'): VAR_24 = "https://{}:{}{}".format(VAR_6.config.get('FQDN'), VAR_6.config.get('NGINX_PORT'), '/login') else: VAR_24 = "http://{}:{}{}".format(VAR_6.config.get('FQDN'), VAR_6.config.get('API_PORT'), '/login') if VAR_15.is_authenticated: VAR_25 = { "authenticated": True, "user": VAR_15.email, "roles": VAR_15.role, } else: VAR_25 = { "authenticated": False, "user": None, "url": VAR_24 } return Response(response=json.dumps({"auth": VAR_25}), VAR_23=status, mimetype="application/json") def FUNC_11(self): for rn, VAR_1, VAR_2, VAR_3 in self.before_acl: VAR_0 = self._role_model.get_by_name(rn) self.acl.allow(VAR_0, VAR_1, VAR_2, VAR_3) self.acl.seted = True
[ 2, 6, 11, 13, 15, 18, 19, 24, 29, 32, 39, 48, 51, 56, 59, 65, 68, 72, 73, 79, 80, 85, 88, 91, 94, 98, 101, 103, 104, 105, 109, 113, 117, 122, 124, 127, 137, 147, 150, 167, 175, 190, 201, 204, 207, 213, 217, 219, 223, 226, 230, 232, 234, 238, 240, 247, 248, 265, 267, 268, 274, 21, 22, 23, 75, 82, 83, 84, 85, 86, 87, 88, 89, 90, 31, 32, 33, 34, 35, 36, 37, 38, 50, 51, 52, 53, 58, 59, 60, 61, 62, 63, 67, 68, 69, 70, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 169, 170, 171, 172, 177, 178, 179 ]
[ 2, 6, 11, 13, 15, 18, 19, 24, 29, 32, 39, 48, 51, 56, 59, 65, 68, 72, 73, 79, 80, 85, 88, 91, 94, 98, 101, 103, 104, 105, 109, 113, 117, 122, 124, 127, 137, 147, 150, 167, 175, 190, 201, 204, 207, 213, 217, 219, 223, 226, 230, 232, 234, 238, 240, 247, 248, 265, 267, 268, 274, 21, 22, 23, 75, 82, 83, 84, 85, 86, 87, 88, 89, 90, 31, 32, 33, 34, 35, 36, 37, 38, 50, 51, 52, 53, 58, 59, 60, 61, 62, 63, 67, 68, 69, 70, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 169, 170, 171, 172, 177, 178, 179 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock, call from signedjson.key import generate_signing_key from synapse.api.constants import EventTypes, Membership, PresenceState from synapse.api.presence import UserPresenceState from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.events.builder import EventBuilder from synapse.handlers.presence import ( EXTERNAL_PROCESS_EXPIRY, FEDERATION_PING_INTERVAL, FEDERATION_TIMEOUT, IDLE_TIMER, LAST_ACTIVE_GRANULARITY, SYNC_ONLINE_TIMEOUT, handle_timeout, handle_update, ) from synapse.rest.client.v1 import room from synapse.types import UserID, get_domain_from_id from tests import unittest class PresenceUpdateTestCase(unittest.TestCase): def test_offline_to_online(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) new_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now ) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertTrue(persist_and_notify) self.assertTrue(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 3) wheel_timer.insert.assert_has_calls( [ call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER), call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( now=now, obj=user_id, then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def test_online_to_online(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, currently_active=True ) new_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now ) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertFalse(persist_and_notify) self.assertTrue(federation_ping) self.assertTrue(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 3) wheel_timer.insert.assert_has_calls( [ call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER), call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( now=now, obj=user_id, then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def test_online_to_online_last_active_noop(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - LAST_ACTIVE_GRANULARITY - 10, currently_active=True, ) new_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now ) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertFalse(persist_and_notify) self.assertTrue(federation_ping) self.assertTrue(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 3) wheel_timer.insert.assert_has_calls( [ call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER), call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( now=now, obj=user_id, then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def test_online_to_online_last_active(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - LAST_ACTIVE_GRANULARITY - 1, currently_active=True, ) new_state = prev_state.copy_and_replace(state=PresenceState.ONLINE) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertTrue(persist_and_notify) self.assertFalse(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 2) wheel_timer.insert.assert_has_calls( [ call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER), call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), ], any_order=True, ) def test_remote_ping_timer(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now ) new_state = prev_state.copy_and_replace(state=PresenceState.ONLINE) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=False, wheel_timer=wheel_timer, now=now ) self.assertFalse(persist_and_notify) self.assertFalse(federation_ping) self.assertFalse(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(wheel_timer.insert.call_count, 1) wheel_timer.insert.assert_has_calls( [ call( now=now, obj=user_id, then=new_state.last_federation_update_ts + FEDERATION_TIMEOUT, ) ], any_order=True, ) def test_online_to_offline(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, currently_active=True ) new_state = prev_state.copy_and_replace(state=PresenceState.OFFLINE) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertTrue(persist_and_notify) self.assertEquals(new_state.state, state.state) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 0) def test_online_to_idle(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, currently_active=True ) new_state = prev_state.copy_and_replace(state=PresenceState.UNAVAILABLE) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertTrue(persist_and_notify) self.assertEquals(new_state.state, state.state) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(wheel_timer.insert.call_count, 1) wheel_timer.insert.assert_has_calls( [ call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ) ], any_order=True, ) class PresenceTimeoutTestCase(unittest.TestCase): def test_idle_timer(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - IDLE_TIMER - 1, last_user_sync_ts=now, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNotNone(new_state) self.assertEquals(new_state.state, PresenceState.UNAVAILABLE) def test_sync_timeout(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=0, last_user_sync_ts=now - SYNC_ONLINE_TIMEOUT - 1, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNotNone(new_state) self.assertEquals(new_state.state, PresenceState.OFFLINE) def test_sync_online(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - SYNC_ONLINE_TIMEOUT - 1, last_user_sync_ts=now - SYNC_ONLINE_TIMEOUT - 1, ) new_state = handle_timeout( state, is_mine=True, syncing_user_ids={user_id}, now=now ) self.assertIsNotNone(new_state) self.assertEquals(new_state.state, PresenceState.ONLINE) def test_federation_ping(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, last_user_sync_ts=now, last_federation_update_ts=now - FEDERATION_PING_INTERVAL - 1, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNotNone(new_state) self.assertEquals(new_state, new_state) def test_no_timeout(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, last_user_sync_ts=now, last_federation_update_ts=now, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNone(new_state) def test_federation_timeout(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, last_user_sync_ts=now, last_federation_update_ts=now - FEDERATION_TIMEOUT - 1, ) new_state = handle_timeout( state, is_mine=False, syncing_user_ids=set(), now=now ) self.assertIsNotNone(new_state) self.assertEquals(new_state.state, PresenceState.OFFLINE) def test_last_active(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - LAST_ACTIVE_GRANULARITY - 1, last_user_sync_ts=now, last_federation_update_ts=now, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNotNone(new_state) self.assertEquals(state, new_state) class PresenceHandlerTestCase(unittest.HomeserverTestCase): def prepare(self, reactor, clock, hs): self.presence_handler = hs.get_presence_handler() self.clock = hs.get_clock() def test_external_process_timeout(self): """Test that if an external process doesn't update the records for a while we time out their syncing users presence. """ process_id = 1 user_id = "@test:server" # Notify handler that a user is now syncing. self.get_success( self.presence_handler.update_external_syncs_row( process_id, user_id, True, self.clock.time_msec() ) ) # Check that if we wait a while without telling the handler the user has # stopped syncing that their presence state doesn't get timed out. self.reactor.advance(EXTERNAL_PROCESS_EXPIRY / 2) state = self.get_success( self.presence_handler.get_state(UserID.from_string(user_id)) ) self.assertEqual(state.state, PresenceState.ONLINE) # Check that if the external process timeout fires, then the syncing # user gets timed out self.reactor.advance(EXTERNAL_PROCESS_EXPIRY) state = self.get_success( self.presence_handler.get_state(UserID.from_string(user_id)) ) self.assertEqual(state.state, PresenceState.OFFLINE) class PresenceJoinTestCase(unittest.HomeserverTestCase): """Tests remote servers get told about presence of users in the room when they join and when new local users join. """ user_id = "@test:server" servlets = [room.register_servlets] def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( "server", http_client=None, federation_sender=Mock() ) return hs def prepare(self, reactor, clock, hs): self.federation_sender = hs.get_federation_sender() self.event_builder_factory = hs.get_event_builder_factory() self.federation_handler = hs.get_federation_handler() self.presence_handler = hs.get_presence_handler() # self.event_builder_for_2 = EventBuilderFactory(hs) # self.event_builder_for_2.hostname = "test2" self.store = hs.get_datastore() self.state = hs.get_state_handler() self.auth = hs.get_auth() # We don't actually check signatures in tests, so lets just create a # random key to use. self.random_signing_key = generate_signing_key("ver") def test_remote_joins(self): # We advance time to something that isn't 0, as we use 0 as a special # value. self.reactor.advance(1000000000000) # Create a room with two local users room_id = self.helper.create_room_as(self.user_id) self.helper.join(room_id, "@test2:server") # Mark test2 as online, test will be offline with a last_active of 0 self.get_success( self.presence_handler.set_state( UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE} ) ) self.reactor.pump([0]) # Wait for presence updates to be handled # # Test that a new server gets told about existing presence # self.federation_sender.reset_mock() # Add a new remote server to the room self._add_new_user(room_id, "@alice:server2") # We shouldn't have sent out any local presence *updates* self.federation_sender.send_presence.assert_not_called() # When new server is joined we send it the local users presence states. # We expect to only see user @test2:server, as @test:server is offline # and has a zero last_active_ts expected_state = self.get_success( self.presence_handler.current_state_for_user("@test2:server") ) self.assertEqual(expected_state.state, PresenceState.ONLINE) self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations=["server2"], states=[expected_state] ) # # Test that only the new server gets sent presence and not existing servers # self.federation_sender.reset_mock() self._add_new_user(room_id, "@bob:server3") self.federation_sender.send_presence.assert_not_called() self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations=["server3"], states=[expected_state] ) def test_remote_gets_presence_when_local_user_joins(self): # We advance time to something that isn't 0, as we use 0 as a special # value. self.reactor.advance(1000000000000) # Create a room with one local users room_id = self.helper.create_room_as(self.user_id) # Mark test as online self.get_success( self.presence_handler.set_state( UserID.from_string("@test:server"), {"presence": PresenceState.ONLINE} ) ) # Mark test2 as online, test will be offline with a last_active of 0. # Note we don't join them to the room yet self.get_success( self.presence_handler.set_state( UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE} ) ) # Add servers to the room self._add_new_user(room_id, "@alice:server2") self._add_new_user(room_id, "@bob:server3") self.reactor.pump([0]) # Wait for presence updates to be handled # # Test that when a local join happens remote servers get told about it # self.federation_sender.reset_mock() # Join local user to room self.helper.join(room_id, "@test2:server") self.reactor.pump([0]) # Wait for presence updates to be handled # We shouldn't have sent out any local presence *updates* self.federation_sender.send_presence.assert_not_called() # We expect to only send test2 presence to server2 and server3 expected_state = self.get_success( self.presence_handler.current_state_for_user("@test2:server") ) self.assertEqual(expected_state.state, PresenceState.ONLINE) self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations={"server2", "server3"}, states=[expected_state] ) def _add_new_user(self, room_id, user_id): """Add new user to the room by creating an event and poking the federation API. """ hostname = get_domain_from_id(user_id) room_version = self.get_success(self.store.get_room_version_id(room_id)) builder = EventBuilder( state=self.state, auth=self.auth, store=self.store, clock=self.clock, hostname=hostname, signing_key=self.random_signing_key, room_version=KNOWN_ROOM_VERSIONS[room_version], room_id=room_id, type=EventTypes.Member, sender=user_id, state_key=user_id, content={"membership": Membership.JOIN}, ) prev_event_ids = self.get_success( self.store.get_latest_event_ids_in_room(room_id) ) event = self.get_success(builder.build(prev_event_ids, None)) self.get_success(self.federation_handler.on_receive_pdu(hostname, event)) # Check that it was successfully persisted. self.get_success(self.store.get_event(event.event_id)) self.get_success(self.store.get_event(event.event_id))
# -*- coding: utf-8 -*- # Copyright 2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock, call from signedjson.key import generate_signing_key from synapse.api.constants import EventTypes, Membership, PresenceState from synapse.api.presence import UserPresenceState from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.events.builder import EventBuilder from synapse.handlers.presence import ( EXTERNAL_PROCESS_EXPIRY, FEDERATION_PING_INTERVAL, FEDERATION_TIMEOUT, IDLE_TIMER, LAST_ACTIVE_GRANULARITY, SYNC_ONLINE_TIMEOUT, handle_timeout, handle_update, ) from synapse.rest.client.v1 import room from synapse.types import UserID, get_domain_from_id from tests import unittest class PresenceUpdateTestCase(unittest.TestCase): def test_offline_to_online(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) new_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now ) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertTrue(persist_and_notify) self.assertTrue(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 3) wheel_timer.insert.assert_has_calls( [ call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER), call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( now=now, obj=user_id, then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def test_online_to_online(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, currently_active=True ) new_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now ) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertFalse(persist_and_notify) self.assertTrue(federation_ping) self.assertTrue(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 3) wheel_timer.insert.assert_has_calls( [ call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER), call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( now=now, obj=user_id, then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def test_online_to_online_last_active_noop(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - LAST_ACTIVE_GRANULARITY - 10, currently_active=True, ) new_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now ) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertFalse(persist_and_notify) self.assertTrue(federation_ping) self.assertTrue(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 3) wheel_timer.insert.assert_has_calls( [ call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER), call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( now=now, obj=user_id, then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def test_online_to_online_last_active(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - LAST_ACTIVE_GRANULARITY - 1, currently_active=True, ) new_state = prev_state.copy_and_replace(state=PresenceState.ONLINE) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertTrue(persist_and_notify) self.assertFalse(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 2) wheel_timer.insert.assert_has_calls( [ call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER), call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), ], any_order=True, ) def test_remote_ping_timer(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now ) new_state = prev_state.copy_and_replace(state=PresenceState.ONLINE) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=False, wheel_timer=wheel_timer, now=now ) self.assertFalse(persist_and_notify) self.assertFalse(federation_ping) self.assertFalse(state.currently_active) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(wheel_timer.insert.call_count, 1) wheel_timer.insert.assert_has_calls( [ call( now=now, obj=user_id, then=new_state.last_federation_update_ts + FEDERATION_TIMEOUT, ) ], any_order=True, ) def test_online_to_offline(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, currently_active=True ) new_state = prev_state.copy_and_replace(state=PresenceState.OFFLINE) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertTrue(persist_and_notify) self.assertEquals(new_state.state, state.state) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(wheel_timer.insert.call_count, 0) def test_online_to_idle(self): wheel_timer = Mock() user_id = "@foo:bar" now = 5000000 prev_state = UserPresenceState.default(user_id) prev_state = prev_state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, currently_active=True ) new_state = prev_state.copy_and_replace(state=PresenceState.UNAVAILABLE) state, persist_and_notify, federation_ping = handle_update( prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now ) self.assertTrue(persist_and_notify) self.assertEquals(new_state.state, state.state) self.assertEquals(state.last_federation_update_ts, now) self.assertEquals(new_state.state, state.state) self.assertEquals(new_state.status_msg, state.status_msg) self.assertEquals(wheel_timer.insert.call_count, 1) wheel_timer.insert.assert_has_calls( [ call( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ) ], any_order=True, ) class PresenceTimeoutTestCase(unittest.TestCase): def test_idle_timer(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - IDLE_TIMER - 1, last_user_sync_ts=now, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNotNone(new_state) self.assertEquals(new_state.state, PresenceState.UNAVAILABLE) def test_sync_timeout(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=0, last_user_sync_ts=now - SYNC_ONLINE_TIMEOUT - 1, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNotNone(new_state) self.assertEquals(new_state.state, PresenceState.OFFLINE) def test_sync_online(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - SYNC_ONLINE_TIMEOUT - 1, last_user_sync_ts=now - SYNC_ONLINE_TIMEOUT - 1, ) new_state = handle_timeout( state, is_mine=True, syncing_user_ids={user_id}, now=now ) self.assertIsNotNone(new_state) self.assertEquals(new_state.state, PresenceState.ONLINE) def test_federation_ping(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, last_user_sync_ts=now, last_federation_update_ts=now - FEDERATION_PING_INTERVAL - 1, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNotNone(new_state) self.assertEquals(new_state, new_state) def test_no_timeout(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, last_user_sync_ts=now, last_federation_update_ts=now, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNone(new_state) def test_federation_timeout(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now, last_user_sync_ts=now, last_federation_update_ts=now - FEDERATION_TIMEOUT - 1, ) new_state = handle_timeout( state, is_mine=False, syncing_user_ids=set(), now=now ) self.assertIsNotNone(new_state) self.assertEquals(new_state.state, PresenceState.OFFLINE) def test_last_active(self): user_id = "@foo:bar" now = 5000000 state = UserPresenceState.default(user_id) state = state.copy_and_replace( state=PresenceState.ONLINE, last_active_ts=now - LAST_ACTIVE_GRANULARITY - 1, last_user_sync_ts=now, last_federation_update_ts=now, ) new_state = handle_timeout(state, is_mine=True, syncing_user_ids=set(), now=now) self.assertIsNotNone(new_state) self.assertEquals(state, new_state) class PresenceHandlerTestCase(unittest.HomeserverTestCase): def prepare(self, reactor, clock, hs): self.presence_handler = hs.get_presence_handler() self.clock = hs.get_clock() def test_external_process_timeout(self): """Test that if an external process doesn't update the records for a while we time out their syncing users presence. """ process_id = 1 user_id = "@test:server" # Notify handler that a user is now syncing. self.get_success( self.presence_handler.update_external_syncs_row( process_id, user_id, True, self.clock.time_msec() ) ) # Check that if we wait a while without telling the handler the user has # stopped syncing that their presence state doesn't get timed out. self.reactor.advance(EXTERNAL_PROCESS_EXPIRY / 2) state = self.get_success( self.presence_handler.get_state(UserID.from_string(user_id)) ) self.assertEqual(state.state, PresenceState.ONLINE) # Check that if the external process timeout fires, then the syncing # user gets timed out self.reactor.advance(EXTERNAL_PROCESS_EXPIRY) state = self.get_success( self.presence_handler.get_state(UserID.from_string(user_id)) ) self.assertEqual(state.state, PresenceState.OFFLINE) class PresenceJoinTestCase(unittest.HomeserverTestCase): """Tests remote servers get told about presence of users in the room when they join and when new local users join. """ user_id = "@test:server" servlets = [room.register_servlets] def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( "server", federation_http_client=None, federation_sender=Mock() ) return hs def prepare(self, reactor, clock, hs): self.federation_sender = hs.get_federation_sender() self.event_builder_factory = hs.get_event_builder_factory() self.federation_handler = hs.get_federation_handler() self.presence_handler = hs.get_presence_handler() # self.event_builder_for_2 = EventBuilderFactory(hs) # self.event_builder_for_2.hostname = "test2" self.store = hs.get_datastore() self.state = hs.get_state_handler() self.auth = hs.get_auth() # We don't actually check signatures in tests, so lets just create a # random key to use. self.random_signing_key = generate_signing_key("ver") def test_remote_joins(self): # We advance time to something that isn't 0, as we use 0 as a special # value. self.reactor.advance(1000000000000) # Create a room with two local users room_id = self.helper.create_room_as(self.user_id) self.helper.join(room_id, "@test2:server") # Mark test2 as online, test will be offline with a last_active of 0 self.get_success( self.presence_handler.set_state( UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE} ) ) self.reactor.pump([0]) # Wait for presence updates to be handled # # Test that a new server gets told about existing presence # self.federation_sender.reset_mock() # Add a new remote server to the room self._add_new_user(room_id, "@alice:server2") # We shouldn't have sent out any local presence *updates* self.federation_sender.send_presence.assert_not_called() # When new server is joined we send it the local users presence states. # We expect to only see user @test2:server, as @test:server is offline # and has a zero last_active_ts expected_state = self.get_success( self.presence_handler.current_state_for_user("@test2:server") ) self.assertEqual(expected_state.state, PresenceState.ONLINE) self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations=["server2"], states=[expected_state] ) # # Test that only the new server gets sent presence and not existing servers # self.federation_sender.reset_mock() self._add_new_user(room_id, "@bob:server3") self.federation_sender.send_presence.assert_not_called() self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations=["server3"], states=[expected_state] ) def test_remote_gets_presence_when_local_user_joins(self): # We advance time to something that isn't 0, as we use 0 as a special # value. self.reactor.advance(1000000000000) # Create a room with one local users room_id = self.helper.create_room_as(self.user_id) # Mark test as online self.get_success( self.presence_handler.set_state( UserID.from_string("@test:server"), {"presence": PresenceState.ONLINE} ) ) # Mark test2 as online, test will be offline with a last_active of 0. # Note we don't join them to the room yet self.get_success( self.presence_handler.set_state( UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE} ) ) # Add servers to the room self._add_new_user(room_id, "@alice:server2") self._add_new_user(room_id, "@bob:server3") self.reactor.pump([0]) # Wait for presence updates to be handled # # Test that when a local join happens remote servers get told about it # self.federation_sender.reset_mock() # Join local user to room self.helper.join(room_id, "@test2:server") self.reactor.pump([0]) # Wait for presence updates to be handled # We shouldn't have sent out any local presence *updates* self.federation_sender.send_presence.assert_not_called() # We expect to only send test2 presence to server2 and server3 expected_state = self.get_success( self.presence_handler.current_state_for_user("@test2:server") ) self.assertEqual(expected_state.state, PresenceState.ONLINE) self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations={"server2", "server3"}, states=[expected_state] ) def _add_new_user(self, room_id, user_id): """Add new user to the room by creating an event and poking the federation API. """ hostname = get_domain_from_id(user_id) room_version = self.get_success(self.store.get_room_version_id(room_id)) builder = EventBuilder( state=self.state, auth=self.auth, store=self.store, clock=self.clock, hostname=hostname, signing_key=self.random_signing_key, room_version=KNOWN_ROOM_VERSIONS[room_version], room_id=room_id, type=EventTypes.Member, sender=user_id, state_key=user_id, content={"membership": Membership.JOIN}, ) prev_event_ids = self.get_success( self.store.get_latest_event_ids_in_room(room_id) ) event = self.get_success(builder.build(prev_event_ids, None)) self.get_success(self.federation_handler.on_receive_pdu(hostname, event)) # Check that it was successfully persisted. self.get_success(self.store.get_event(event.event_id)) self.get_success(self.store.get_event(event.event_id))
open_redirect
{ "code": [ " \"server\", http_client=None, federation_sender=Mock()" ], "line_no": [ 466 ] }
{ "code": [ " \"server\", federation_http_client=None, federation_sender=Mock()" ], "line_no": [ 466 ] }
from mock import Mock, call from signedjson.key import generate_signing_key from synapse.api.constants import EventTypes, Membership, PresenceState from synapse.api.presence import UserPresenceState from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.events.builder import EventBuilder from synapse.handlers.presence import ( EXTERNAL_PROCESS_EXPIRY, FEDERATION_PING_INTERVAL, FEDERATION_TIMEOUT, IDLE_TIMER, LAST_ACTIVE_GRANULARITY, SYNC_ONLINE_TIMEOUT, handle_timeout, handle_update, ) from synapse.rest.client.v1 import room from synapse.types import UserID, get_domain_from_id from tests import unittest class CLASS_0(unittest.TestCase): def FUNC_0(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_9 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 ) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertTrue(VAR_11) self.assertTrue(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 3) VAR_6.insert.assert_has_calls( [ call(VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + IDLE_TIMER), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def FUNC_1(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, currently_active=True ) VAR_9 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 ) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertFalse(VAR_11) self.assertTrue(VAR_12) self.assertTrue(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 3) VAR_6.insert.assert_has_calls( [ call(VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + IDLE_TIMER), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def FUNC_2(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - LAST_ACTIVE_GRANULARITY - 10, currently_active=True, ) VAR_9 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 ) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertFalse(VAR_11) self.assertTrue(VAR_12) self.assertTrue(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 3) VAR_6.insert.assert_has_calls( [ call(VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + IDLE_TIMER), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def FUNC_3(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - LAST_ACTIVE_GRANULARITY - 1, currently_active=True, ) VAR_9 = VAR_8.copy_and_replace(VAR_10=PresenceState.ONLINE) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertTrue(VAR_11) self.assertFalse(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 2) VAR_6.insert.assert_has_calls( [ call(VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + IDLE_TIMER), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), ], any_order=True, ) def FUNC_4(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 ) VAR_9 = VAR_8.copy_and_replace(VAR_10=PresenceState.ONLINE) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=False, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertFalse(VAR_11) self.assertFalse(VAR_12) self.assertFalse(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_6.insert.call_count, 1) VAR_6.insert.assert_has_calls( [ call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_federation_update_ts + FEDERATION_TIMEOUT, ) ], any_order=True, ) def FUNC_5(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, currently_active=True ) VAR_9 = VAR_8.copy_and_replace(VAR_10=PresenceState.OFFLINE) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertTrue(VAR_11) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 0) def FUNC_6(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, currently_active=True ) VAR_9 = VAR_8.copy_and_replace(VAR_10=PresenceState.UNAVAILABLE) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertTrue(VAR_11) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_6.insert.call_count, 1) VAR_6.insert.assert_has_calls( [ call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ) ], any_order=True, ) class CLASS_1(unittest.TestCase): def FUNC_7(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - IDLE_TIMER - 1, last_user_sync_ts=VAR_7, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9.state, PresenceState.UNAVAILABLE) def FUNC_8(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=0, last_user_sync_ts=VAR_7 - SYNC_ONLINE_TIMEOUT - 1, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9.state, PresenceState.OFFLINE) def FUNC_9(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - SYNC_ONLINE_TIMEOUT - 1, last_user_sync_ts=VAR_7 - SYNC_ONLINE_TIMEOUT - 1, ) VAR_9 = handle_timeout( VAR_10, is_mine=True, syncing_user_ids={VAR_3}, VAR_7=VAR_7 ) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9.state, PresenceState.ONLINE) def FUNC_10(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, last_user_sync_ts=VAR_7, last_federation_update_ts=VAR_7 - FEDERATION_PING_INTERVAL - 1, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9, new_state) def FUNC_11(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, last_user_sync_ts=VAR_7, last_federation_update_ts=VAR_7, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNone(VAR_9) def FUNC_12(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, last_user_sync_ts=VAR_7, last_federation_update_ts=VAR_7 - FEDERATION_TIMEOUT - 1, ) VAR_9 = handle_timeout( VAR_10, is_mine=False, syncing_user_ids=set(), VAR_7=VAR_7 ) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9.state, PresenceState.OFFLINE) def FUNC_13(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - LAST_ACTIVE_GRANULARITY - 1, last_user_sync_ts=VAR_7, last_federation_update_ts=VAR_7, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_10, VAR_9) class CLASS_2(unittest.HomeserverTestCase): def FUNC_14(self, VAR_0, VAR_1, VAR_2): self.presence_handler = VAR_2.get_presence_handler() self.clock = VAR_2.get_clock() def FUNC_15(self): VAR_13 = 1 VAR_3 = "@test:server" self.get_success( self.presence_handler.update_external_syncs_row( VAR_13, VAR_3, True, self.clock.time_msec() ) ) self.reactor.advance(EXTERNAL_PROCESS_EXPIRY / 2) VAR_10 = self.get_success( self.presence_handler.get_state(UserID.from_string(VAR_3)) ) self.assertEqual(VAR_10.state, PresenceState.ONLINE) self.reactor.advance(EXTERNAL_PROCESS_EXPIRY) VAR_10 = self.get_success( self.presence_handler.get_state(UserID.from_string(VAR_3)) ) self.assertEqual(VAR_10.state, PresenceState.OFFLINE) class CLASS_3(unittest.HomeserverTestCase): VAR_3 = "@test:server" VAR_4 = [room.register_servlets] def FUNC_16(self, VAR_0, VAR_1): VAR_2 = self.setup_test_homeserver( "server", http_client=None, federation_sender=Mock() ) return VAR_2 def FUNC_14(self, VAR_0, VAR_1, VAR_2): self.federation_sender = VAR_2.get_federation_sender() self.event_builder_factory = VAR_2.get_event_builder_factory() self.federation_handler = VAR_2.get_federation_handler() self.presence_handler = VAR_2.get_presence_handler() self.store = VAR_2.get_datastore() self.state = VAR_2.get_state_handler() self.auth = VAR_2.get_auth() self.random_signing_key = generate_signing_key("ver") def FUNC_17(self): self.reactor.advance(1000000000000) VAR_5 = self.helper.create_room_as(self.user_id) self.helper.join(VAR_5, "@test2:server") self.get_success( self.presence_handler.set_state( UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE} ) ) self.reactor.pump([0]) # Wait for presence updates to be handled self.federation_sender.reset_mock() self._add_new_user(VAR_5, "@alice:server2") self.federation_sender.send_presence.assert_not_called() VAR_14 = self.get_success( self.presence_handler.current_state_for_user("@test2:server") ) self.assertEqual(VAR_14.state, PresenceState.ONLINE) self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations=["server2"], states=[VAR_14] ) self.federation_sender.reset_mock() self._add_new_user(VAR_5, "@bob:server3") self.federation_sender.send_presence.assert_not_called() self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations=["server3"], states=[VAR_14] ) def FUNC_18(self): self.reactor.advance(1000000000000) VAR_5 = self.helper.create_room_as(self.user_id) self.get_success( self.presence_handler.set_state( UserID.from_string("@test:server"), {"presence": PresenceState.ONLINE} ) ) self.get_success( self.presence_handler.set_state( UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE} ) ) self._add_new_user(VAR_5, "@alice:server2") self._add_new_user(VAR_5, "@bob:server3") self.reactor.pump([0]) # Wait for presence updates to be handled self.federation_sender.reset_mock() self.helper.join(VAR_5, "@test2:server") self.reactor.pump([0]) # Wait for presence updates to be handled self.federation_sender.send_presence.assert_not_called() VAR_14 = self.get_success( self.presence_handler.current_state_for_user("@test2:server") ) self.assertEqual(VAR_14.state, PresenceState.ONLINE) self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations={"server2", "server3"}, states=[VAR_14] ) def FUNC_19(self, VAR_5, VAR_3): VAR_15 = get_domain_from_id(VAR_3) VAR_16 = self.get_success(self.store.get_room_version_id(VAR_5)) VAR_17 = EventBuilder( VAR_10=self.state, auth=self.auth, store=self.store, VAR_1=self.clock, VAR_15=hostname, signing_key=self.random_signing_key, VAR_16=KNOWN_ROOM_VERSIONS[VAR_16], VAR_5=room_id, type=EventTypes.Member, sender=VAR_3, state_key=VAR_3, content={"membership": Membership.JOIN}, ) VAR_18 = self.get_success( self.store.get_latest_event_ids_in_room(VAR_5) ) VAR_19 = self.get_success(VAR_17.build(VAR_18, None)) self.get_success(self.federation_handler.on_receive_pdu(VAR_15, VAR_19)) self.get_success(self.store.get_event(VAR_19.event_id)) self.get_success(self.store.get_event(VAR_19.event_id))
from mock import Mock, call from signedjson.key import generate_signing_key from synapse.api.constants import EventTypes, Membership, PresenceState from synapse.api.presence import UserPresenceState from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.events.builder import EventBuilder from synapse.handlers.presence import ( EXTERNAL_PROCESS_EXPIRY, FEDERATION_PING_INTERVAL, FEDERATION_TIMEOUT, IDLE_TIMER, LAST_ACTIVE_GRANULARITY, SYNC_ONLINE_TIMEOUT, handle_timeout, handle_update, ) from synapse.rest.client.v1 import room from synapse.types import UserID, get_domain_from_id from tests import unittest class CLASS_0(unittest.TestCase): def FUNC_0(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_9 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 ) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertTrue(VAR_11) self.assertTrue(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 3) VAR_6.insert.assert_has_calls( [ call(VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + IDLE_TIMER), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def FUNC_1(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, currently_active=True ) VAR_9 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 ) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertFalse(VAR_11) self.assertTrue(VAR_12) self.assertTrue(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 3) VAR_6.insert.assert_has_calls( [ call(VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + IDLE_TIMER), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def FUNC_2(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - LAST_ACTIVE_GRANULARITY - 10, currently_active=True, ) VAR_9 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 ) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertFalse(VAR_11) self.assertTrue(VAR_12) self.assertTrue(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 3) VAR_6.insert.assert_has_calls( [ call(VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + IDLE_TIMER), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + LAST_ACTIVE_GRANULARITY, ), ], any_order=True, ) def FUNC_3(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - LAST_ACTIVE_GRANULARITY - 1, currently_active=True, ) VAR_9 = VAR_8.copy_and_replace(VAR_10=PresenceState.ONLINE) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertTrue(VAR_11) self.assertFalse(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 2) VAR_6.insert.assert_has_calls( [ call(VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_active_ts + IDLE_TIMER), call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ), ], any_order=True, ) def FUNC_4(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 ) VAR_9 = VAR_8.copy_and_replace(VAR_10=PresenceState.ONLINE) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=False, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertFalse(VAR_11) self.assertFalse(VAR_12) self.assertFalse(VAR_10.currently_active) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_6.insert.call_count, 1) VAR_6.insert.assert_has_calls( [ call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_federation_update_ts + FEDERATION_TIMEOUT, ) ], any_order=True, ) def FUNC_5(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, currently_active=True ) VAR_9 = VAR_8.copy_and_replace(VAR_10=PresenceState.OFFLINE) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertTrue(VAR_11) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_6.insert.call_count, 0) def FUNC_6(self): VAR_6 = Mock() VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_8 = UserPresenceState.default(VAR_3) VAR_8 = VAR_8.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, currently_active=True ) VAR_9 = VAR_8.copy_and_replace(VAR_10=PresenceState.UNAVAILABLE) VAR_10, VAR_11, VAR_12 = handle_update( VAR_8, VAR_9, is_mine=True, VAR_6=wheel_timer, VAR_7=VAR_7 ) self.assertTrue(VAR_11) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_10.last_federation_update_ts, VAR_7) self.assertEquals(VAR_9.state, VAR_10.state) self.assertEquals(VAR_9.status_msg, VAR_10.status_msg) self.assertEquals(VAR_6.insert.call_count, 1) VAR_6.insert.assert_has_calls( [ call( VAR_7=VAR_7, obj=VAR_3, then=VAR_9.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ) ], any_order=True, ) class CLASS_1(unittest.TestCase): def FUNC_7(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - IDLE_TIMER - 1, last_user_sync_ts=VAR_7, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9.state, PresenceState.UNAVAILABLE) def FUNC_8(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=0, last_user_sync_ts=VAR_7 - SYNC_ONLINE_TIMEOUT - 1, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9.state, PresenceState.OFFLINE) def FUNC_9(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - SYNC_ONLINE_TIMEOUT - 1, last_user_sync_ts=VAR_7 - SYNC_ONLINE_TIMEOUT - 1, ) VAR_9 = handle_timeout( VAR_10, is_mine=True, syncing_user_ids={VAR_3}, VAR_7=VAR_7 ) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9.state, PresenceState.ONLINE) def FUNC_10(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, last_user_sync_ts=VAR_7, last_federation_update_ts=VAR_7 - FEDERATION_PING_INTERVAL - 1, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9, new_state) def FUNC_11(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, last_user_sync_ts=VAR_7, last_federation_update_ts=VAR_7, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNone(VAR_9) def FUNC_12(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7, last_user_sync_ts=VAR_7, last_federation_update_ts=VAR_7 - FEDERATION_TIMEOUT - 1, ) VAR_9 = handle_timeout( VAR_10, is_mine=False, syncing_user_ids=set(), VAR_7=VAR_7 ) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_9.state, PresenceState.OFFLINE) def FUNC_13(self): VAR_3 = "@foo:bar" VAR_7 = 5000000 VAR_10 = UserPresenceState.default(VAR_3) VAR_10 = state.copy_and_replace( VAR_10=PresenceState.ONLINE, last_active_ts=VAR_7 - LAST_ACTIVE_GRANULARITY - 1, last_user_sync_ts=VAR_7, last_federation_update_ts=VAR_7, ) VAR_9 = handle_timeout(VAR_10, is_mine=True, syncing_user_ids=set(), VAR_7=now) self.assertIsNotNone(VAR_9) self.assertEquals(VAR_10, VAR_9) class CLASS_2(unittest.HomeserverTestCase): def FUNC_14(self, VAR_0, VAR_1, VAR_2): self.presence_handler = VAR_2.get_presence_handler() self.clock = VAR_2.get_clock() def FUNC_15(self): VAR_13 = 1 VAR_3 = "@test:server" self.get_success( self.presence_handler.update_external_syncs_row( VAR_13, VAR_3, True, self.clock.time_msec() ) ) self.reactor.advance(EXTERNAL_PROCESS_EXPIRY / 2) VAR_10 = self.get_success( self.presence_handler.get_state(UserID.from_string(VAR_3)) ) self.assertEqual(VAR_10.state, PresenceState.ONLINE) self.reactor.advance(EXTERNAL_PROCESS_EXPIRY) VAR_10 = self.get_success( self.presence_handler.get_state(UserID.from_string(VAR_3)) ) self.assertEqual(VAR_10.state, PresenceState.OFFLINE) class CLASS_3(unittest.HomeserverTestCase): VAR_3 = "@test:server" VAR_4 = [room.register_servlets] def FUNC_16(self, VAR_0, VAR_1): VAR_2 = self.setup_test_homeserver( "server", federation_http_client=None, federation_sender=Mock() ) return VAR_2 def FUNC_14(self, VAR_0, VAR_1, VAR_2): self.federation_sender = VAR_2.get_federation_sender() self.event_builder_factory = VAR_2.get_event_builder_factory() self.federation_handler = VAR_2.get_federation_handler() self.presence_handler = VAR_2.get_presence_handler() self.store = VAR_2.get_datastore() self.state = VAR_2.get_state_handler() self.auth = VAR_2.get_auth() self.random_signing_key = generate_signing_key("ver") def FUNC_17(self): self.reactor.advance(1000000000000) VAR_5 = self.helper.create_room_as(self.user_id) self.helper.join(VAR_5, "@test2:server") self.get_success( self.presence_handler.set_state( UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE} ) ) self.reactor.pump([0]) # Wait for presence updates to be handled self.federation_sender.reset_mock() self._add_new_user(VAR_5, "@alice:server2") self.federation_sender.send_presence.assert_not_called() VAR_14 = self.get_success( self.presence_handler.current_state_for_user("@test2:server") ) self.assertEqual(VAR_14.state, PresenceState.ONLINE) self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations=["server2"], states=[VAR_14] ) self.federation_sender.reset_mock() self._add_new_user(VAR_5, "@bob:server3") self.federation_sender.send_presence.assert_not_called() self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations=["server3"], states=[VAR_14] ) def FUNC_18(self): self.reactor.advance(1000000000000) VAR_5 = self.helper.create_room_as(self.user_id) self.get_success( self.presence_handler.set_state( UserID.from_string("@test:server"), {"presence": PresenceState.ONLINE} ) ) self.get_success( self.presence_handler.set_state( UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE} ) ) self._add_new_user(VAR_5, "@alice:server2") self._add_new_user(VAR_5, "@bob:server3") self.reactor.pump([0]) # Wait for presence updates to be handled self.federation_sender.reset_mock() self.helper.join(VAR_5, "@test2:server") self.reactor.pump([0]) # Wait for presence updates to be handled self.federation_sender.send_presence.assert_not_called() VAR_14 = self.get_success( self.presence_handler.current_state_for_user("@test2:server") ) self.assertEqual(VAR_14.state, PresenceState.ONLINE) self.federation_sender.send_presence_to_destinations.assert_called_once_with( destinations={"server2", "server3"}, states=[VAR_14] ) def FUNC_19(self, VAR_5, VAR_3): VAR_15 = get_domain_from_id(VAR_3) VAR_16 = self.get_success(self.store.get_room_version_id(VAR_5)) VAR_17 = EventBuilder( VAR_10=self.state, auth=self.auth, store=self.store, VAR_1=self.clock, VAR_15=hostname, signing_key=self.random_signing_key, VAR_16=KNOWN_ROOM_VERSIONS[VAR_16], VAR_5=room_id, type=EventTypes.Member, sender=VAR_3, state_key=VAR_3, content={"membership": Membership.JOIN}, ) VAR_18 = self.get_success( self.store.get_latest_event_ids_in_room(VAR_5) ) VAR_19 = self.get_success(VAR_17.build(VAR_18, None)) self.get_success(self.federation_handler.on_receive_pdu(VAR_15, VAR_19)) self.get_success(self.store.get_event(VAR_19.event_id)) self.get_success(self.store.get_event(VAR_19.event_id))
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 37, 39, 40, 46, 51, 55, 61, 79, 84, 89, 93, 97, 104, 122, 127, 134, 138, 142, 149, 167, 172, 179, 181, 185, 191, 204, 209, 214, 216, 220, 226, 238, 243, 248, 250, 254, 258, 260, 265, 270, 272, 276, 282, 294, 295, 300, 307, 309, 312, 316, 323, 325, 328, 332, 339, 343, 346, 350, 358, 360, 363, 367, 375, 377, 379, 383, 391, 395, 398, 402, 410, 412, 415, 416, 421, 428, 429, 435, 436, 437, 439, 444, 445, 446, 448, 453, 454, 459, 461, 463, 469, 475, 476, 477, 478, 482, 483, 484, 486, 488, 489, 491, 492, 495, 496, 503, 504, 505, 506, 507, 509, 510, 512, 513, 515, 516, 517, 518, 526, 527, 528, 529, 530, 533, 538, 540, 541, 543, 544, 546, 547, 553, 554, 555, 561, 562, 565, 567, 568, 569, 570, 571, 573, 574, 576, 578, 579, 581, 582, 590, 594, 596, 598, 613, 617, 619, 621, 622, 625, 456, 457, 458, 423, 424, 425, 592, 593 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 37, 39, 40, 46, 51, 55, 61, 79, 84, 89, 93, 97, 104, 122, 127, 134, 138, 142, 149, 167, 172, 179, 181, 185, 191, 204, 209, 214, 216, 220, 226, 238, 243, 248, 250, 254, 258, 260, 265, 270, 272, 276, 282, 294, 295, 300, 307, 309, 312, 316, 323, 325, 328, 332, 339, 343, 346, 350, 358, 360, 363, 367, 375, 377, 379, 383, 391, 395, 398, 402, 410, 412, 415, 416, 421, 428, 429, 435, 436, 437, 439, 444, 445, 446, 448, 453, 454, 459, 461, 463, 469, 475, 476, 477, 478, 482, 483, 484, 486, 488, 489, 491, 492, 495, 496, 503, 504, 505, 506, 507, 509, 510, 512, 513, 515, 516, 517, 518, 526, 527, 528, 529, 530, 533, 538, 540, 541, 543, 544, 546, 547, 553, 554, 555, 561, 562, 565, 567, 568, 569, 570, 571, 573, 574, 576, 578, 579, 581, 582, 590, 594, 596, 598, 613, 617, 619, 621, 622, 625, 456, 457, 458, 423, 424, 425, 592, 593 ]
4CWE-601
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2011-2020 University of Dundee & Open Microscopy Environment. # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Decorators for use with OMERO.web applications. """ import logging import traceback from django.http import Http404, HttpResponseRedirect, JsonResponse from django.http.response import HttpResponseBase from django.shortcuts import render from django.http import HttpResponseForbidden, StreamingHttpResponse from django.conf import settings from django.utils.http import urlencode from functools import update_wrapper from django.core.urlresolvers import reverse, resolve, NoReverseMatch from django.core.cache import cache from omeroweb.utils import reverse_with_params from omeroweb.connector import Connector from omero.gateway.utils import propertiesToDict from omero import ApiUsageException logger = logging.getLogger(__name__) def parse_url(lookup_view): if not lookup_view: raise ValueError("No lookup_view") url = None try: url = reverse_with_params( viewname=lookup_view["viewname"], args=lookup_view.get("args", []), query_string=lookup_view.get("query_string", None), ) except KeyError: # assume we've been passed a url try: resolve(lookup_view) url = lookup_view except Exception: pass if url is None: logger.error("Reverse for '%s' not found." % lookup_view) raise NoReverseMatch("Reverse for '%s' not found." % lookup_view) return url def get_client_ip(request): x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[-1].strip() else: ip = request.META.get("REMOTE_ADDR") return ip def is_public_user(request): """ Is the session connector created for public user? Returns None if no connector found """ connector = request.session.get("connector") if connector is not None: return connector.is_public class ConnCleaningHttpResponse(StreamingHttpResponse): """Extension of L{HttpResponse} which closes the OMERO connection.""" def close(self): super(ConnCleaningHttpResponse, self).close() try: logger.debug("Closing OMERO connection in %r" % self) if self.conn is not None and self.conn.c is not None: self.conn.close(hard=False) except Exception: logger.error("Failed to clean up connection.", exc_info=True) class TableClosingHttpResponse(ConnCleaningHttpResponse): """Extension of L{HttpResponse} which closes the OMERO connection.""" def close(self): try: if self.table is not None: self.table.close() except Exception: logger.error("Failed to close OMERO.table.", exc_info=True) # Now call super to close conn super(TableClosingHttpResponse, self).close() class login_required(object): """ OMERO.web specific extension of the Django login_required() decorator, https://docs.djangoproject.com/en/dev/topics/auth/, which is responsible for ensuring a valid L{omero.gateway.BlitzGateway} connection. Is configurable by various options. doConnectionCleanup: Used to indicate methods that may return ConnCleaningHttpResponse. If True (default), then returning a ConnCleaningHttpResponse will raise an Exception since cleanup is intended to be immediate; if False, connection cleanup will be skipped ONLY when a ConnCleaningHttpResponse is returned. """ def __init__( self, useragent="OMERO.web", isAdmin=False, isGroupOwner=False, doConnectionCleanup=True, omero_group="-1", allowPublic=None, ): """ Initialises the decorator. """ self.useragent = useragent self.isAdmin = isAdmin self.isGroupOwner = isGroupOwner self.doConnectionCleanup = doConnectionCleanup self.omero_group = omero_group self.allowPublic = allowPublic # To make django's method_decorator work, this is required until # python/django sort out how argumented decorator wrapping should work # https://github.com/openmicroscopy/openmicroscopy/pull/1820 def __getattr__(self, name): if name == "__name__": return self.__class__.__name__ else: return super(login_required, self).getattr(name) def get_login_url(self): """The URL that should be redirected to if not logged in.""" return reverse(settings.LOGIN_VIEW) login_url = property(get_login_url) def get_share_connection(self, request, conn, share_id): try: conn.SERVICE_OPTS.setOmeroShare(share_id) conn.getShare(share_id) return conn except Exception: logger.error("Error activating share.", exc_info=True) return None def prepare_share_connection(self, request, conn, share_id): """Prepares the share connection if we have a valid share ID.""" # we always need to clear any dirty 'omero.share' values from previous # calls conn.SERVICE_OPTS.setOmeroShare() if share_id is None: return None share = conn.getShare(share_id) try: if share.getOwner().id != conn.getUserId(): if share.active and not share.isExpired(): return self.get_share_connection(request, conn, share_id) logger.debug("Share is unavailable.") return None except Exception: logger.error("Error retrieving share connection.", exc_info=True) return None def on_not_logged_in(self, request, url, error=None): """Called whenever the user is not logged in.""" if request.is_ajax(): logger.debug("Request is Ajax, returning HTTP 403.") return HttpResponseForbidden() try: for lookup_view in settings.LOGIN_REDIRECT["redirect"]: try: if url == reverse(lookup_view): url = parse_url(settings.LOGIN_REDIRECT) except NoReverseMatch: try: resolve(lookup_view) if url == lookup_view: url = parse_url(settings.LOGIN_REDIRECT) except Http404: logger.error("Cannot resolve url %s" % lookup_view) except KeyError: pass except Exception: logger.error("Error while redirection on not logged in.", exc_info=True) args = {"url": url} logger.debug( "Request is not Ajax, redirecting to %s?%s" % (self.login_url, urlencode(args)) ) return HttpResponseRedirect("%s?%s" % (self.login_url, urlencode(args))) def on_logged_in(self, request, conn): """ Called whenever the users is successfully logged in. Sets the 'omero.group' option if specified in the constructor """ if self.omero_group is not None: conn.SERVICE_OPTS.setOmeroGroup(self.omero_group) def on_share_connection_prepared(self, request, conn_share): """Called whenever a share connection is successfully prepared.""" pass def verify_is_admin(self, conn): """ If we have been requested to by the isAdmin flag, verify the user is an admin and raise an exception if they are not. """ if self.isAdmin and not conn.isAdmin(): raise Http404 def verify_is_group_owner(self, conn, gid): """ If we have been requested to by the isGroupOwner flag, verify the user is the owner of the provided group. If no group is provided the user's active session group ownership will be verified. """ if not self.isGroupOwner: return if gid is not None: if not conn.isLeader(gid): raise Http404 else: if not conn.isLeader(): raise Http404 def is_valid_public_url(self, server_id, request): """ Verifies that the URL for the resource being requested falls within the scope of the OMERO.webpublic URL filter. """ if settings.PUBLIC_ENABLED: if not hasattr(settings, "PUBLIC_USER"): logger.warn( "OMERO.webpublic enabled but public user " "(omero.web.public.user) not set, disabling " "OMERO.webpublic." ) settings.PUBLIC_ENABLED = False return False if not hasattr(settings, "PUBLIC_PASSWORD"): logger.warn( "OMERO.webpublic enabled but public user " "password (omero.web.public.password) not set, " "disabling OMERO.webpublic." ) settings.PUBLIC_ENABLED = False return False if settings.PUBLIC_GET_ONLY and (request.method != "GET"): return False if self.allowPublic is None: return settings.PUBLIC_URL_FILTER.search(request.path) is not None return self.allowPublic return False def load_server_settings(self, conn, request): """Loads Client preferences and Read-Only status from the server.""" try: request.session["can_create"] except KeyError: request.session.modified = True request.session["can_create"] = conn.canCreate() try: request.session["server_settings"] except Exception: request.session.modified = True request.session["server_settings"] = {} try: request.session["server_settings"] = propertiesToDict( conn.getClientSettings(), prefix="omero.client." ) except Exception: logger.error(traceback.format_exc()) # make extra call for omero.mail, not a part of omero.client request.session["server_settings"]["email"] = conn.getEmailSettings() def get_public_user_connector(self): """ Returns the current cached OMERO.webpublic connector or None if nothing has been cached. """ if not settings.PUBLIC_CACHE_ENABLED: return return cache.get(settings.PUBLIC_CACHE_KEY) def set_public_user_connector(self, connector): """Sets the current cached OMERO.webpublic connector.""" if not settings.PUBLIC_CACHE_ENABLED or connector.omero_session_key is None: return logger.debug("Setting OMERO.webpublic connector: %r" % connector) cache.set(settings.PUBLIC_CACHE_KEY, connector, settings.PUBLIC_CACHE_TIMEOUT) def get_connection(self, server_id, request): """ Prepares a Blitz connection wrapper (from L{omero.gateway}) for use with a view function. """ connection = self.get_authenticated_connection(server_id, request) is_valid_public_url = self.is_valid_public_url(server_id, request) logger.debug("Is valid public URL? %s" % is_valid_public_url) if connection is None and is_valid_public_url: # If OMERO.webpublic is enabled, pick up a username and # password from configuration and use those credentials to # create a connection. logger.debug( "OMERO.webpublic enabled, attempting to login " "with configuration supplied credentials." ) if server_id is None: server_id = settings.PUBLIC_SERVER_ID username = settings.PUBLIC_USER password = settings.PUBLIC_PASSWORD is_secure = settings.SECURE logger.debug("Is SSL? %s" % is_secure) # Try and use a cached OMERO.webpublic user session key. public_user_connector = self.get_public_user_connector() if public_user_connector is not None: logger.debug( "Attempting to use cached OMERO.webpublic " "connector: %r" % public_user_connector ) connection = public_user_connector.join_connection(self.useragent) if connection is not None: request.session["connector"] = public_user_connector logger.debug( "Attempt to use cached OMERO.web public " "session key successful!" ) return connection logger.debug( "Attempt to use cached OMERO.web public " "session key failed." ) # We don't have a cached OMERO.webpublic user session key, # create a new connection based on the credentials we've been # given. connector = Connector(server_id, is_secure) connection = connector.create_connection( self.useragent, username, password, is_public=True, userip=get_client_ip(request), ) request.session["connector"] = connector # Clear any previous context so we don't try to access this # NB: we also do this in WebclientLoginView.handle_logged_in() if "active_group" in request.session: del request.session["active_group"] if "user_id" in request.session: del request.session["user_id"] request.session.modified = True self.set_public_user_connector(connector) elif connection is not None: is_anonymous = connection.isAnonymous() logger.debug("Is anonymous? %s" % is_anonymous) if is_anonymous and not is_valid_public_url: if connection.c is not None: logger.debug("Closing anonymous connection") connection.close(hard=False) return None return connection def get_authenticated_connection(self, server_id, request): """ Prepares an authenticated Blitz connection wrapper (from L{omero.gateway}) for use with a view function. """ # TODO: Handle previous try_super logic; is it still needed? userip = get_client_ip(request) session = request.session request = request.GET is_secure = settings.SECURE logger.debug("Is SSL? %s" % is_secure) connector = session.get("connector", None) logger.debug("Connector: %s" % connector) if server_id is None: # If no server id is passed, the db entry will not be used and # instead we'll depend on the request.session and request.GET # values if connector is not None: server_id = connector.server_id else: try: server_id = request["server"] except Exception: logger.debug("No Server ID available.") return None # If we have an OMERO session key in our request variables attempt # to make a connection based on those credentials. try: omero_session_key = request["bsession"] connector = Connector(server_id, is_secure) except KeyError: # We do not have an OMERO session key in the current request. pass else: # We have an OMERO session key in the current request use it # to try join an existing connection / OMERO session. logger.debug( "Have OMERO session key %s, attempting to join..." % omero_session_key ) connector.user_id = None connector.omero_session_key = omero_session_key connection = connector.join_connection(self.useragent, userip) session["connector"] = connector return connection # An OMERO session is not available, we're either trying to service # a request to a login page or an anonymous request. username = None password = None try: username = request["username"] password = request["password"] except KeyError: if connector is None: logger.debug("No username or password in request, exiting.") # We do not have an OMERO session or a username and password # in the current request and we do not have a valid connector. # Raise an error (return None). return None if username is not None and password is not None: # We have a username and password in the current request, or # OMERO.webpublic is enabled and has provided us with a username # and password via configureation. Use them to try and create a # new connection / OMERO session. logger.debug("Creating connection with username and password...") connector = Connector(server_id, is_secure) connection = connector.create_connection( self.useragent, username, password, userip=userip ) session["connector"] = connector return connection logger.debug("Django session connector: %r" % connector) if connector is not None: # We have a connector, attempt to use it to join an existing # connection / OMERO session. connection = connector.join_connection(self.useragent, userip) if connection is not None: logger.debug("Connector valid, session successfully joined.") return connection # Fall through, we the session we've been asked to join may # be invalid and we may have other credentials as request # variables. logger.debug("Connector is no longer valid, destroying...") del session["connector"] return None session["connector"] = connector return None def __call__(ctx, f): """ Tries to prepare a logged in connection, then calls function and returns the result. """ def wrapped(request, *args, **kwargs): url = request.GET.get("url") if url is None or len(url) == 0: url = request.get_full_path() doConnectionCleanup = False conn = kwargs.get("conn", None) error = None server_id = kwargs.get("server_id", None) # Short circuit connection retrieval when a connection was # provided to us via 'conn'. This is useful when in testing # mode or when stacking view functions/methods. if conn is None: doConnectionCleanup = ctx.doConnectionCleanup logger.debug("Connection not provided, attempting to get one.") try: conn = ctx.get_connection(server_id, request) except Exception as x: logger.error("Error retrieving connection.", exc_info=True) error = str(x) else: # various configuration & checks only performed on new # 'conn' if conn is None: return ctx.on_not_logged_in(request, url, error) else: ctx.on_logged_in(request, conn) ctx.verify_is_admin(conn) ctx.verify_is_group_owner(conn, kwargs.get("gid")) ctx.load_server_settings(conn, request) share_id = kwargs.get("share_id") conn_share = ctx.prepare_share_connection(request, conn, share_id) if conn_share is not None: ctx.on_share_connection_prepared(request, conn_share) kwargs["conn"] = conn_share else: kwargs["conn"] = conn # kwargs['error'] = request.GET.get('error') kwargs["url"] = url retval = None try: retval = f(request, *args, **kwargs) finally: # If f() raised Exception, e.g. Http404() we must still cleanup delayConnectionCleanup = isinstance(retval, ConnCleaningHttpResponse) if doConnectionCleanup and delayConnectionCleanup: raise ApiUsageException( "Methods that return a" " ConnCleaningHttpResponse must be marked with" " @login_required(doConnectionCleanup=False)" ) doConnectionCleanup = not delayConnectionCleanup logger.debug("Doing connection cleanup? %s" % doConnectionCleanup) try: if doConnectionCleanup: if conn is not None and conn.c is not None: conn.close(hard=False) except Exception: logger.warn("Failed to clean up connection", exc_info=True) return retval return update_wrapper(wrapped, f) class render_response(object): """ This decorator handles the rendering of view methods to HttpResponse. It expects that wrapped view methods return a dict. This allows: - The template to be specified in the method arguments OR within the view method itself - The dict to be returned as json if required - The request is passed to the template context, as required by some tags etc - A hook is provided for adding additional data to the context, from the L{omero.gateway.BlitzGateway} or from the request. """ # To make django's method_decorator work, this is required until # python/django sort out how argumented decorator wrapping should work # https://github.com/openmicroscopy/openmicroscopy/pull/1820 def __getattr__(self, name): if name == "__name__": return self.__class__.__name__ else: return super(render_response, self).getattr(name) def prepare_context(self, request, context, *args, **kwargs): """ Hook for adding additional data to the context dict """ pass def __call__(ctx, f): """ Here we wrap the view method f and return the wrapped method """ def wrapper(request, *args, **kwargs): """ Wrapper calls the view function, processes the result and returns HttpResponse""" # call the view function itself... context = f(request, *args, **kwargs) # if we happen to have a Response, return it if isinstance(context, HttpResponseBase): return context # get template from view dict. Can be overridden from the **kwargs template = "template" in context and context["template"] or None template = kwargs.get("template", template) logger.debug("Rendering template: %s" % template) # allows us to return the dict as json (NB: BlitzGateway objects # don't serialize) if template is None or template == "json": # We still need to support non-dict data: safe = type(context) is dict return JsonResponse(context, safe=safe) else: # allow additional processing of context dict ctx.prepare_context(request, context, *args, **kwargs) return render(request, template, context) return update_wrapper(wrapper, f)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2011-2020 University of Dundee & Open Microscopy Environment. # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Decorators for use with OMERO.web applications. """ import logging import traceback from django.http import Http404, HttpResponseRedirect, JsonResponse from django.http.response import HttpResponseBase from django.shortcuts import render from django.http import HttpResponseForbidden, StreamingHttpResponse from django.conf import settings from django.utils.http import urlencode from functools import update_wrapper from django.core.urlresolvers import reverse, resolve, NoReverseMatch from django.core.cache import cache from omeroweb.utils import reverse_with_params from omeroweb.connector import Connector from omero.gateway.utils import propertiesToDict from omero import ApiUsageException logger = logging.getLogger(__name__) def parse_url(lookup_view): if not lookup_view: raise ValueError("No lookup_view") url = None try: url = reverse_with_params( viewname=lookup_view["viewname"], args=lookup_view.get("args", []), query_string=lookup_view.get("query_string", None), ) except KeyError: # assume we've been passed a url try: resolve(lookup_view) url = lookup_view except Exception: pass if url is None: logger.error("Reverse for '%s' not found." % lookup_view) raise NoReverseMatch("Reverse for '%s' not found." % lookup_view) return url def get_client_ip(request): x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[-1].strip() else: ip = request.META.get("REMOTE_ADDR") return ip def is_public_user(request): """ Is the session connector created for public user? Returns None if no connector found """ connector = request.session.get("connector") if connector is not None: return connector.is_public class ConnCleaningHttpResponse(StreamingHttpResponse): """Extension of L{HttpResponse} which closes the OMERO connection.""" def close(self): super(ConnCleaningHttpResponse, self).close() try: logger.debug("Closing OMERO connection in %r" % self) if self.conn is not None and self.conn.c is not None: self.conn.close(hard=False) except Exception: logger.error("Failed to clean up connection.", exc_info=True) class TableClosingHttpResponse(ConnCleaningHttpResponse): """Extension of L{HttpResponse} which closes the OMERO connection.""" def close(self): try: if self.table is not None: self.table.close() except Exception: logger.error("Failed to close OMERO.table.", exc_info=True) # Now call super to close conn super(TableClosingHttpResponse, self).close() class login_required(object): """ OMERO.web specific extension of the Django login_required() decorator, https://docs.djangoproject.com/en/dev/topics/auth/, which is responsible for ensuring a valid L{omero.gateway.BlitzGateway} connection. Is configurable by various options. doConnectionCleanup: Used to indicate methods that may return ConnCleaningHttpResponse. If True (default), then returning a ConnCleaningHttpResponse will raise an Exception since cleanup is intended to be immediate; if False, connection cleanup will be skipped ONLY when a ConnCleaningHttpResponse is returned. """ def __init__( self, useragent="OMERO.web", isAdmin=False, isGroupOwner=False, doConnectionCleanup=True, omero_group="-1", allowPublic=None, ): """ Initialises the decorator. """ self.useragent = useragent self.isAdmin = isAdmin self.isGroupOwner = isGroupOwner self.doConnectionCleanup = doConnectionCleanup self.omero_group = omero_group self.allowPublic = allowPublic # To make django's method_decorator work, this is required until # python/django sort out how argumented decorator wrapping should work # https://github.com/openmicroscopy/openmicroscopy/pull/1820 def __getattr__(self, name): if name == "__name__": return self.__class__.__name__ else: return super(login_required, self).getattr(name) def get_login_url(self): """The URL that should be redirected to if not logged in.""" return reverse(settings.LOGIN_VIEW) login_url = property(get_login_url) def get_share_connection(self, request, conn, share_id): try: conn.SERVICE_OPTS.setOmeroShare(share_id) conn.getShare(share_id) return conn except Exception: logger.error("Error activating share.", exc_info=True) return None def prepare_share_connection(self, request, conn, share_id): """Prepares the share connection if we have a valid share ID.""" # we always need to clear any dirty 'omero.share' values from previous # calls conn.SERVICE_OPTS.setOmeroShare() if share_id is None: return None share = conn.getShare(share_id) try: if share.getOwner().id != conn.getUserId(): if share.active and not share.isExpired(): return self.get_share_connection(request, conn, share_id) logger.debug("Share is unavailable.") return None except Exception: logger.error("Error retrieving share connection.", exc_info=True) return None def on_not_logged_in(self, request, url, error=None): """Called whenever the user is not logged in.""" if request.is_ajax(): logger.debug("Request is Ajax, returning HTTP 403.") return HttpResponseForbidden() try: for lookup_view in settings.LOGIN_REDIRECT["redirect"]: try: if url == reverse(lookup_view): url = parse_url(settings.LOGIN_REDIRECT) except NoReverseMatch: try: resolve(lookup_view) if url == lookup_view: url = parse_url(settings.LOGIN_REDIRECT) except Http404: logger.error("Cannot resolve url %s" % lookup_view) except KeyError: pass except Exception: logger.error("Error while redirection on not logged in.", exc_info=True) args = {"url": url} logger.debug( "Request is not Ajax, redirecting to %s?%s" % (self.login_url, urlencode(args)) ) return HttpResponseRedirect("%s?%s" % (self.login_url, urlencode(args))) def on_logged_in(self, request, conn): """ Called whenever the users is successfully logged in. Sets the 'omero.group' option if specified in the constructor """ if self.omero_group is not None: conn.SERVICE_OPTS.setOmeroGroup(self.omero_group) def on_share_connection_prepared(self, request, conn_share): """Called whenever a share connection is successfully prepared.""" pass def verify_is_admin(self, conn): """ If we have been requested to by the isAdmin flag, verify the user is an admin and raise an exception if they are not. """ if self.isAdmin and not conn.isAdmin(): raise Http404 def verify_is_group_owner(self, conn, gid): """ If we have been requested to by the isGroupOwner flag, verify the user is the owner of the provided group. If no group is provided the user's active session group ownership will be verified. """ if not self.isGroupOwner: return if gid is not None: if not conn.isLeader(gid): raise Http404 else: if not conn.isLeader(): raise Http404 def is_valid_public_url(self, server_id, request): """ Verifies that the URL for the resource being requested falls within the scope of the OMERO.webpublic URL filter. """ if settings.PUBLIC_ENABLED: if not hasattr(settings, "PUBLIC_USER"): logger.warn( "OMERO.webpublic enabled but public user " "(omero.web.public.user) not set, disabling " "OMERO.webpublic." ) settings.PUBLIC_ENABLED = False return False if not hasattr(settings, "PUBLIC_PASSWORD"): logger.warn( "OMERO.webpublic enabled but public user " "password (omero.web.public.password) not set, " "disabling OMERO.webpublic." ) settings.PUBLIC_ENABLED = False return False if settings.PUBLIC_GET_ONLY and (request.method != "GET"): return False if self.allowPublic is None: return settings.PUBLIC_URL_FILTER.search(request.path) is not None return self.allowPublic return False def load_server_settings(self, conn, request): """Loads Client preferences and Read-Only status from the server.""" try: request.session["can_create"] except KeyError: request.session.modified = True request.session["can_create"] = conn.canCreate() try: request.session["server_settings"] except Exception: request.session.modified = True request.session["server_settings"] = {} try: request.session["server_settings"] = propertiesToDict( conn.getClientSettings(), prefix="omero.client." ) except Exception: logger.error(traceback.format_exc()) # make extra call for omero.mail, not a part of omero.client request.session["server_settings"]["email"] = conn.getEmailSettings() def get_public_user_connector(self): """ Returns the current cached OMERO.webpublic connector or None if nothing has been cached. """ if not settings.PUBLIC_CACHE_ENABLED: return return cache.get(settings.PUBLIC_CACHE_KEY) def set_public_user_connector(self, connector): """Sets the current cached OMERO.webpublic connector.""" if not settings.PUBLIC_CACHE_ENABLED or connector.omero_session_key is None: return logger.debug("Setting OMERO.webpublic connector: %r" % connector) cache.set(settings.PUBLIC_CACHE_KEY, connector, settings.PUBLIC_CACHE_TIMEOUT) def get_connection(self, server_id, request): """ Prepares a Blitz connection wrapper (from L{omero.gateway}) for use with a view function. """ connection = self.get_authenticated_connection(server_id, request) is_valid_public_url = self.is_valid_public_url(server_id, request) logger.debug("Is valid public URL? %s" % is_valid_public_url) if connection is None and is_valid_public_url: # If OMERO.webpublic is enabled, pick up a username and # password from configuration and use those credentials to # create a connection. logger.debug( "OMERO.webpublic enabled, attempting to login " "with configuration supplied credentials." ) if server_id is None: server_id = settings.PUBLIC_SERVER_ID username = settings.PUBLIC_USER password = settings.PUBLIC_PASSWORD is_secure = settings.SECURE logger.debug("Is SSL? %s" % is_secure) # Try and use a cached OMERO.webpublic user session key. public_user_connector = self.get_public_user_connector() if public_user_connector is not None: logger.debug( "Attempting to use cached OMERO.webpublic " "connector: %r" % public_user_connector ) connection = public_user_connector.join_connection(self.useragent) if connection is not None: request.session["connector"] = public_user_connector logger.debug( "Attempt to use cached OMERO.web public " "session key successful!" ) return connection logger.debug( "Attempt to use cached OMERO.web public " "session key failed." ) # We don't have a cached OMERO.webpublic user session key, # create a new connection based on the credentials we've been # given. connector = Connector(server_id, is_secure) connection = connector.create_connection( self.useragent, username, password, is_public=True, userip=get_client_ip(request), ) request.session["connector"] = connector # Clear any previous context so we don't try to access this # NB: we also do this in WebclientLoginView.handle_logged_in() if "active_group" in request.session: del request.session["active_group"] if "user_id" in request.session: del request.session["user_id"] request.session.modified = True self.set_public_user_connector(connector) elif connection is not None: is_anonymous = connection.isAnonymous() logger.debug("Is anonymous? %s" % is_anonymous) if is_anonymous and not is_valid_public_url: if connection.c is not None: logger.debug("Closing anonymous connection") connection.close(hard=False) return None return connection def get_authenticated_connection(self, server_id, request): """ Prepares an authenticated Blitz connection wrapper (from L{omero.gateway}) for use with a view function. """ # TODO: Handle previous try_super logic; is it still needed? userip = get_client_ip(request) session = request.session request = request.GET is_secure = settings.SECURE logger.debug("Is SSL? %s" % is_secure) connector = session.get("connector", None) logger.debug("Connector: %s" % connector) if server_id is None: # If no server id is passed, the db entry will not be used and # instead we'll depend on the request.session and request.GET # values if connector is not None: server_id = connector.server_id else: try: server_id = request["server"] except Exception: logger.debug("No Server ID available.") return None # If we have an OMERO session key in our request variables attempt # to make a connection based on those credentials. try: omero_session_key = request["bsession"] connector = Connector(server_id, is_secure) except KeyError: # We do not have an OMERO session key in the current request. pass else: # We have an OMERO session key in the current request use it # to try join an existing connection / OMERO session. logger.debug( "Have OMERO session key %s, attempting to join..." % omero_session_key ) connector.user_id = None connector.omero_session_key = omero_session_key connection = connector.join_connection(self.useragent, userip) session["connector"] = connector return connection # An OMERO session is not available, we're either trying to service # a request to a login page or an anonymous request. username = None password = None try: username = request["username"] password = request["password"] except KeyError: if connector is None: logger.debug("No username or password in request, exiting.") # We do not have an OMERO session or a username and password # in the current request and we do not have a valid connector. # Raise an error (return None). return None if username is not None and password is not None: # We have a username and password in the current request, or # OMERO.webpublic is enabled and has provided us with a username # and password via configureation. Use them to try and create a # new connection / OMERO session. logger.debug("Creating connection with username and password...") connector = Connector(server_id, is_secure) connection = connector.create_connection( self.useragent, username, password, userip=userip ) session["connector"] = connector return connection logger.debug("Django session connector: %r" % connector) if connector is not None: # We have a connector, attempt to use it to join an existing # connection / OMERO session. connection = connector.join_connection(self.useragent, userip) if connection is not None: logger.debug("Connector valid, session successfully joined.") return connection # Fall through, we the session we've been asked to join may # be invalid and we may have other credentials as request # variables. logger.debug("Connector is no longer valid, destroying...") del session["connector"] return None session["connector"] = connector return None def __call__(ctx, f): """ Tries to prepare a logged in connection, then calls function and returns the result. """ def wrapped(request, *args, **kwargs): url = request.GET.get("url") if url is None or len(url) == 0: url = request.get_full_path() doConnectionCleanup = False conn = kwargs.get("conn", None) error = None server_id = kwargs.get("server_id", None) # Short circuit connection retrieval when a connection was # provided to us via 'conn'. This is useful when in testing # mode or when stacking view functions/methods. if conn is None: doConnectionCleanup = ctx.doConnectionCleanup logger.debug("Connection not provided, attempting to get one.") try: conn = ctx.get_connection(server_id, request) except Exception as x: logger.error("Error retrieving connection.", exc_info=True) error = str(x) else: # various configuration & checks only performed on new # 'conn' if conn is None: return ctx.on_not_logged_in(request, url, error) else: ctx.on_logged_in(request, conn) ctx.verify_is_admin(conn) ctx.verify_is_group_owner(conn, kwargs.get("gid")) ctx.load_server_settings(conn, request) share_id = kwargs.get("share_id") conn_share = ctx.prepare_share_connection(request, conn, share_id) if conn_share is not None: ctx.on_share_connection_prepared(request, conn_share) kwargs["conn"] = conn_share else: kwargs["conn"] = conn # kwargs['error'] = request.GET.get('error') kwargs["url"] = url retval = None try: retval = f(request, *args, **kwargs) finally: # If f() raised Exception, e.g. Http404() we must still cleanup delayConnectionCleanup = isinstance(retval, ConnCleaningHttpResponse) if doConnectionCleanup and delayConnectionCleanup: raise ApiUsageException( "Methods that return a" " ConnCleaningHttpResponse must be marked with" " @login_required(doConnectionCleanup=False)" ) doConnectionCleanup = not delayConnectionCleanup logger.debug("Doing connection cleanup? %s" % doConnectionCleanup) try: if doConnectionCleanup: if conn is not None and conn.c is not None: conn.close(hard=False) except Exception: logger.warn("Failed to clean up connection", exc_info=True) return retval return update_wrapper(wrapped, f) class render_response(object): """ This decorator handles the rendering of view methods to HttpResponse. It expects that wrapped view methods return a dict. This allows: - The template to be specified in the method arguments OR within the view method itself - The dict to be returned as json if required - The request is passed to the template context, as required by some tags etc - A hook is provided for adding additional data to the context, from the L{omero.gateway.BlitzGateway} or from the request. """ # To make django's method_decorator work, this is required until # python/django sort out how argumented decorator wrapping should work # https://github.com/openmicroscopy/openmicroscopy/pull/1820 def __getattr__(self, name): if name == "__name__": return self.__class__.__name__ else: return super(render_response, self).getattr(name) def prepare_context(self, request, context, *args, **kwargs): """ Hook for adding additional data to the context dict """ context["html"] = context.get("html", {}) context["html"]["meta_referrer"] = settings.HTML_META_REFERRER def __call__(ctx, f): """ Here we wrap the view method f and return the wrapped method """ def wrapper(request, *args, **kwargs): """ Wrapper calls the view function, processes the result and returns HttpResponse""" # call the view function itself... context = f(request, *args, **kwargs) # if we happen to have a Response, return it if isinstance(context, HttpResponseBase): return context # get template from view dict. Can be overridden from the **kwargs template = "template" in context and context["template"] or None template = kwargs.get("template", template) logger.debug("Rendering template: %s" % template) # allows us to return the dict as json (NB: BlitzGateway objects # don't serialize) if template is None or template == "json": # We still need to support non-dict data: safe = type(context) is dict return JsonResponse(context, safe=safe) else: # allow additional processing of context dict ctx.prepare_context(request, context, *args, **kwargs) return render(request, template, context) return update_wrapper(wrapper, f)
open_redirect
{ "code": [ " pass" ], "line_no": [ 585 ] }
{ "code": [ " context[\"html\"] = context.get(\"html\", {})" ], "line_no": [ 585 ] }
import logging import traceback from django.http import Http404, HttpResponseRedirect, JsonResponse from django.http.response import HttpResponseBase from django.shortcuts import render from django.http import HttpResponseForbidden, StreamingHttpResponse from django.conf import settings from django.utils.http import .urlencode from functools import update_wrapper from django.core.urlresolvers import reverse, resolve, NoReverseMatch from django.core.cache import cache from omeroweb.utils import reverse_with_params from omeroweb.connector import Connector from omero.gateway.utils import propertiesToDict from omero import ApiUsageException VAR_0 = logging.getLogger(__name__) def FUNC_0(VAR_1): if not VAR_1: raise ValueError("No lookup_view") VAR_3 = None try: VAR_3 = reverse_with_params( viewname=VAR_1["viewname"], VAR_23=VAR_1.get("args", []), query_string=VAR_1.get("query_string", None), ) except KeyError: try: resolve(VAR_1) VAR_3 = VAR_1 except Exception: pass if VAR_3 is None: VAR_0.error("Reverse for '%s' not found." % VAR_1) raise NoReverseMatch("Reverse for '%s' not found." % VAR_1) return VAR_3 def FUNC_1(VAR_2): VAR_4 = VAR_2.META.get("HTTP_X_FORWARDED_FOR") if VAR_4: VAR_25 = VAR_4.split(",")[-1].strip() else: VAR_25 = VAR_2.META.get("REMOTE_ADDR") return VAR_25 def FUNC_2(VAR_2): VAR_5 = VAR_2.session.get("connector") if VAR_5 is not None: return VAR_5.is_public class CLASS_0(StreamingHttpResponse): def FUNC_3(self): super(CLASS_0, self).close() try: VAR_0.debug("Closing OMERO VAR_27 in %r" % self) if self.conn is not None and self.conn.c is not None: self.conn.close(hard=False) except Exception: VAR_0.error("Failed to clean up VAR_27.", exc_info=True) class CLASS_1(CLASS_0): def FUNC_3(self): try: if self.table is not None: self.table.close() except Exception: VAR_0.error("Failed to FUNC_3 OMERO.table.", exc_info=True) super(CLASS_1, self).close() class CLASS_2(object): def __init__( self, VAR_6="OMERO.web", VAR_7=False, VAR_8=False, VAR_9=True, VAR_10="-1", VAR_11=None, ): self.useragent = VAR_6 self.isAdmin = VAR_7 self.isGroupOwner = VAR_8 self.doConnectionCleanup = VAR_9 self.omero_group = VAR_10 self.allowPublic = VAR_11 def __getattr__(self, VAR_12): if VAR_12 == "__name__": return self.__class__.__name__ else: return super(CLASS_2, self).getattr(VAR_12) def FUNC_4(self): return reverse(settings.LOGIN_VIEW) VAR_13 = property(FUNC_4) def FUNC_5(self, VAR_2, VAR_14, VAR_15): try: VAR_14.SERVICE_OPTS.setOmeroShare(VAR_15) VAR_14.getShare(VAR_15) return VAR_14 except Exception: VAR_0.error("Error activating VAR_26.", exc_info=True) return None def FUNC_6(self, VAR_2, VAR_14, VAR_15): VAR_14.SERVICE_OPTS.setOmeroShare() if VAR_15 is None: return None VAR_26 = VAR_14.getShare(VAR_15) try: if VAR_26.getOwner().id != VAR_14.getUserId(): if VAR_26.active and not VAR_26.isExpired(): return self.get_share_connection(VAR_2, VAR_14, VAR_15) VAR_0.debug("Share is unavailable.") return None except Exception: VAR_0.error("Error retrieving VAR_26 VAR_27.", exc_info=True) return None def FUNC_7(self, VAR_2, VAR_3, VAR_16=None): if VAR_2.is_ajax(): VAR_0.debug("Request is Ajax, returning HTTP 403.") return HttpResponseForbidden() try: for VAR_1 in settings.LOGIN_REDIRECT["redirect"]: try: if VAR_3 == reverse(VAR_1): VAR_3 = FUNC_0(settings.LOGIN_REDIRECT) except NoReverseMatch: try: resolve(VAR_1) if VAR_3 == VAR_1: VAR_3 = FUNC_0(settings.LOGIN_REDIRECT) except Http404: VAR_0.error("Cannot resolve VAR_3 %s" % VAR_1) except KeyError: pass except Exception: VAR_0.error("Error while redirection on not logged in.", exc_info=True) VAR_23 = {"url": VAR_3} VAR_0.debug( "Request is not Ajax, redirecting to %s?%s" % (self.login_url, urlencode(VAR_23)) ) return HttpResponseRedirect("%s?%s" % (self.login_url, urlencode(VAR_23))) def FUNC_8(self, VAR_2, VAR_14): if self.omero_group is not None: VAR_14.SERVICE_OPTS.setOmeroGroup(self.omero_group) def FUNC_9(self, VAR_2, VAR_17): pass def FUNC_10(self, VAR_14): if self.isAdmin and not VAR_14.isAdmin(): raise Http404 def FUNC_11(self, VAR_14, VAR_18): if not self.isGroupOwner: return if VAR_18 is not None: if not VAR_14.isLeader(VAR_18): raise Http404 else: if not VAR_14.isLeader(): raise Http404 def VAR_28(self, VAR_19, VAR_2): if settings.PUBLIC_ENABLED: if not hasattr(settings, "PUBLIC_USER"): VAR_0.warn( "OMERO.webpublic enabled but public user " "(omero.web.public.user) not set, disabling " "OMERO.webpublic." ) settings.PUBLIC_ENABLED = False return False if not hasattr(settings, "PUBLIC_PASSWORD"): VAR_0.warn( "OMERO.webpublic enabled but public user " "password (omero.web.public.password) not set, " "disabling OMERO.webpublic." ) settings.PUBLIC_ENABLED = False return False if settings.PUBLIC_GET_ONLY and (VAR_2.method != "GET"): return False if self.allowPublic is None: return settings.PUBLIC_URL_FILTER.search(VAR_2.path) is not None return self.allowPublic return False def FUNC_13(self, VAR_14, VAR_2): try: VAR_2.session["can_create"] except KeyError: VAR_2.session.modified = True VAR_2.session["can_create"] = VAR_14.canCreate() try: VAR_2.session["server_settings"] except Exception: VAR_2.session.modified = True VAR_2.session["server_settings"] = {} try: VAR_2.session["server_settings"] = propertiesToDict( VAR_14.getClientSettings(), prefix="omero.client." ) except Exception: VAR_0.error(traceback.format_exc()) VAR_2.session["server_settings"]["email"] = VAR_14.getEmailSettings() def FUNC_14(self): if not settings.PUBLIC_CACHE_ENABLED: return return cache.get(settings.PUBLIC_CACHE_KEY) def FUNC_15(self, VAR_5): if not settings.PUBLIC_CACHE_ENABLED or VAR_5.omero_session_key is None: return VAR_0.debug("Setting OMERO.webpublic VAR_5: %r" % VAR_5) cache.set(settings.PUBLIC_CACHE_KEY, VAR_5, settings.PUBLIC_CACHE_TIMEOUT) def FUNC_16(self, VAR_19, VAR_2): VAR_27 = self.get_authenticated_connection(VAR_19, VAR_2) VAR_28 = self.is_valid_public_url(VAR_19, VAR_2) VAR_0.debug("Is valid public URL? %s" % VAR_28) if VAR_27 is None and VAR_28: VAR_0.debug( "OMERO.webpublic enabled, attempting to login " "with configuration supplied credentials." ) if VAR_19 is None: VAR_19 = settings.PUBLIC_SERVER_ID VAR_32 = settings.PUBLIC_USER VAR_33 = settings.PUBLIC_PASSWORD VAR_31 = settings.SECURE VAR_0.debug("Is SSL? %s" % VAR_31) VAR_34 = self.get_public_user_connector() if VAR_34 is not None: VAR_0.debug( "Attempting to use cached OMERO.webpublic " "connector: %r" % VAR_34 ) VAR_27 = VAR_34.join_connection(self.useragent) if VAR_27 is not None: VAR_2.session["connector"] = VAR_34 VAR_0.debug( "Attempt to use cached OMERO.web public " "session key successful!" ) return VAR_27 VAR_0.debug( "Attempt to use cached OMERO.web public " "session key failed." ) VAR_5 = Connector(VAR_19, VAR_31) VAR_27 = VAR_5.create_connection( self.useragent, VAR_32, VAR_33, is_public=True, VAR_29=FUNC_1(VAR_2), ) VAR_2.session["connector"] = VAR_5 if "active_group" in VAR_2.session: del VAR_2.session["active_group"] if "user_id" in VAR_2.session: del VAR_2.session["user_id"] VAR_2.session.modified = True self.set_public_user_connector(VAR_5) elif VAR_27 is not None: VAR_38 = VAR_27.isAnonymous() VAR_0.debug("Is anonymous? %s" % VAR_38) if VAR_38 and not VAR_28: if VAR_27.c is not None: VAR_0.debug("Closing anonymous connection") VAR_27.close(hard=False) return None return VAR_27 def FUNC_17(self, VAR_19, VAR_2): VAR_29 = FUNC_1(VAR_2) VAR_30 = VAR_2.session VAR_2 = VAR_2.GET VAR_31 = settings.SECURE VAR_0.debug("Is SSL? %s" % VAR_31) VAR_5 = VAR_30.get("connector", None) VAR_0.debug("Connector: %s" % VAR_5) if VAR_19 is None: if VAR_5 is not None: VAR_19 = VAR_5.server_id else: try: VAR_19 = VAR_2["server"] except Exception: VAR_0.debug("No Server ID available.") return None try: VAR_35 = VAR_2["bsession"] VAR_5 = Connector(VAR_19, VAR_31) except KeyError: pass else: VAR_0.debug( "Have OMERO VAR_30 key %s, attempting to join..." % VAR_35 ) VAR_5.user_id = None VAR_5.omero_session_key = VAR_35 VAR_27 = VAR_5.join_connection(self.useragent, VAR_29) VAR_30["connector"] = VAR_5 return VAR_27 VAR_32 = None VAR_33 = None try: VAR_32 = VAR_2["username"] VAR_33 = VAR_2["password"] except KeyError: if VAR_5 is None: VAR_0.debug("No VAR_32 or VAR_33 in VAR_2, exiting.") return None if VAR_32 is not None and VAR_33 is not None: VAR_0.debug("Creating VAR_27 with VAR_32 and VAR_33...") VAR_5 = Connector(VAR_19, VAR_31) VAR_27 = VAR_5.create_connection( self.useragent, VAR_32, VAR_33, VAR_29=userip ) VAR_30["connector"] = VAR_5 return VAR_27 VAR_0.debug("Django VAR_30 VAR_5: %r" % VAR_5) if VAR_5 is not None: VAR_27 = VAR_5.join_connection(self.useragent, VAR_29) if VAR_27 is not None: VAR_0.debug("Connector valid, VAR_30 successfully joined.") return VAR_27 VAR_0.debug("Connector is no longer valid, destroying...") del VAR_30["connector"] return None VAR_30["connector"] = VAR_5 return None def __call__(VAR_20, VAR_21): def FUNC_19(VAR_2, *VAR_23, **VAR_24): VAR_3 = VAR_2.GET.get("url") if VAR_3 is None or len(VAR_3) == 0: VAR_3 = VAR_2.get_full_path() VAR_9 = False VAR_14 = VAR_24.get("conn", None) VAR_16 = None VAR_19 = VAR_24.get("server_id", None) if VAR_14 is None: VAR_9 = VAR_20.doConnectionCleanup VAR_0.debug("Connection not provided, attempting to get one.") try: VAR_14 = VAR_20.get_connection(VAR_19, VAR_2) except Exception as x: VAR_0.error("Error retrieving VAR_27.", exc_info=True) VAR_16 = str(x) else: if VAR_14 is None: return VAR_20.on_not_logged_in(VAR_2, VAR_3, VAR_16) else: VAR_20.on_logged_in(VAR_2, VAR_14) VAR_20.verify_is_admin(VAR_14) VAR_20.verify_is_group_owner(VAR_14, VAR_24.get("gid")) VAR_20.load_server_settings(VAR_14, VAR_2) VAR_15 = VAR_24.get("share_id") VAR_17 = VAR_20.prepare_share_connection(VAR_2, VAR_14, VAR_15) if VAR_17 is not None: VAR_20.on_share_connection_prepared(VAR_2, VAR_17) VAR_24["conn"] = VAR_17 else: VAR_24["conn"] = VAR_14 VAR_24["url"] = VAR_3 VAR_36 = None try: VAR_36 = VAR_21(VAR_2, *VAR_23, **VAR_24) finally: VAR_39 = isinstance(VAR_36, CLASS_0) if VAR_9 and VAR_39: raise ApiUsageException( "Methods that return a" " CLASS_0 must be marked with" " @CLASS_2(VAR_9=False)" ) VAR_9 = not VAR_39 VAR_0.debug("Doing VAR_27 cleanup? %s" % VAR_9) try: if VAR_9: if VAR_14 is not None and VAR_14.c is not None: VAR_14.close(hard=False) except Exception: VAR_0.warn("Failed to clean up connection", exc_info=True) return VAR_36 return update_wrapper(FUNC_19, VAR_21) class CLASS_3(object): def __getattr__(self, VAR_12): if VAR_12 == "__name__": return self.__class__.__name__ else: return super(CLASS_3, self).getattr(VAR_12) def FUNC_18(self, VAR_2, VAR_22, *VAR_23, **VAR_24): pass def __call__(VAR_20, VAR_21): def FUNC_20(VAR_2, *VAR_23, **VAR_24): VAR_22 = VAR_21(VAR_2, *VAR_23, **VAR_24) if isinstance(VAR_22, HttpResponseBase): return VAR_22 VAR_37 = "template" in VAR_22 and VAR_22["template"] or None VAR_37 = VAR_24.get("template", VAR_37) VAR_0.debug("Rendering VAR_37: %s" % VAR_37) if VAR_37 is None or VAR_37 == "json": VAR_40 = type(VAR_22) is dict return JsonResponse(VAR_22, VAR_40=safe) else: VAR_20.prepare_context(VAR_2, VAR_22, *VAR_23, **VAR_24) return render(VAR_2, VAR_37, VAR_22) return update_wrapper(FUNC_20, VAR_21)
import logging import traceback from django.http import Http404, HttpResponseRedirect, JsonResponse from django.http.response import HttpResponseBase from django.shortcuts import render from django.http import HttpResponseForbidden, StreamingHttpResponse from django.conf import settings from django.utils.http import .urlencode from functools import update_wrapper from django.core.urlresolvers import reverse, resolve, NoReverseMatch from django.core.cache import cache from omeroweb.utils import reverse_with_params from omeroweb.connector import Connector from omero.gateway.utils import propertiesToDict from omero import ApiUsageException VAR_0 = logging.getLogger(__name__) def FUNC_0(VAR_1): if not VAR_1: raise ValueError("No lookup_view") VAR_3 = None try: VAR_3 = reverse_with_params( viewname=VAR_1["viewname"], VAR_23=VAR_1.get("args", []), query_string=VAR_1.get("query_string", None), ) except KeyError: try: resolve(VAR_1) VAR_3 = VAR_1 except Exception: pass if VAR_3 is None: VAR_0.error("Reverse for '%s' not found." % VAR_1) raise NoReverseMatch("Reverse for '%s' not found." % VAR_1) return VAR_3 def FUNC_1(VAR_2): VAR_4 = VAR_2.META.get("HTTP_X_FORWARDED_FOR") if VAR_4: VAR_25 = VAR_4.split(",")[-1].strip() else: VAR_25 = VAR_2.META.get("REMOTE_ADDR") return VAR_25 def FUNC_2(VAR_2): VAR_5 = VAR_2.session.get("connector") if VAR_5 is not None: return VAR_5.is_public class CLASS_0(StreamingHttpResponse): def FUNC_3(self): super(CLASS_0, self).close() try: VAR_0.debug("Closing OMERO VAR_27 in %r" % self) if self.conn is not None and self.conn.c is not None: self.conn.close(hard=False) except Exception: VAR_0.error("Failed to clean up VAR_27.", exc_info=True) class CLASS_1(CLASS_0): def FUNC_3(self): try: if self.table is not None: self.table.close() except Exception: VAR_0.error("Failed to FUNC_3 OMERO.table.", exc_info=True) super(CLASS_1, self).close() class CLASS_2(object): def __init__( self, VAR_6="OMERO.web", VAR_7=False, VAR_8=False, VAR_9=True, VAR_10="-1", VAR_11=None, ): self.useragent = VAR_6 self.isAdmin = VAR_7 self.isGroupOwner = VAR_8 self.doConnectionCleanup = VAR_9 self.omero_group = VAR_10 self.allowPublic = VAR_11 def __getattr__(self, VAR_12): if VAR_12 == "__name__": return self.__class__.__name__ else: return super(CLASS_2, self).getattr(VAR_12) def FUNC_4(self): return reverse(settings.LOGIN_VIEW) VAR_13 = property(FUNC_4) def FUNC_5(self, VAR_2, VAR_14, VAR_15): try: VAR_14.SERVICE_OPTS.setOmeroShare(VAR_15) VAR_14.getShare(VAR_15) return VAR_14 except Exception: VAR_0.error("Error activating VAR_26.", exc_info=True) return None def FUNC_6(self, VAR_2, VAR_14, VAR_15): VAR_14.SERVICE_OPTS.setOmeroShare() if VAR_15 is None: return None VAR_26 = VAR_14.getShare(VAR_15) try: if VAR_26.getOwner().id != VAR_14.getUserId(): if VAR_26.active and not VAR_26.isExpired(): return self.get_share_connection(VAR_2, VAR_14, VAR_15) VAR_0.debug("Share is unavailable.") return None except Exception: VAR_0.error("Error retrieving VAR_26 VAR_27.", exc_info=True) return None def FUNC_7(self, VAR_2, VAR_3, VAR_16=None): if VAR_2.is_ajax(): VAR_0.debug("Request is Ajax, returning HTTP 403.") return HttpResponseForbidden() try: for VAR_1 in settings.LOGIN_REDIRECT["redirect"]: try: if VAR_3 == reverse(VAR_1): VAR_3 = FUNC_0(settings.LOGIN_REDIRECT) except NoReverseMatch: try: resolve(VAR_1) if VAR_3 == VAR_1: VAR_3 = FUNC_0(settings.LOGIN_REDIRECT) except Http404: VAR_0.error("Cannot resolve VAR_3 %s" % VAR_1) except KeyError: pass except Exception: VAR_0.error("Error while redirection on not logged in.", exc_info=True) VAR_23 = {"url": VAR_3} VAR_0.debug( "Request is not Ajax, redirecting to %s?%s" % (self.login_url, urlencode(VAR_23)) ) return HttpResponseRedirect("%s?%s" % (self.login_url, urlencode(VAR_23))) def FUNC_8(self, VAR_2, VAR_14): if self.omero_group is not None: VAR_14.SERVICE_OPTS.setOmeroGroup(self.omero_group) def FUNC_9(self, VAR_2, VAR_17): pass def FUNC_10(self, VAR_14): if self.isAdmin and not VAR_14.isAdmin(): raise Http404 def FUNC_11(self, VAR_14, VAR_18): if not self.isGroupOwner: return if VAR_18 is not None: if not VAR_14.isLeader(VAR_18): raise Http404 else: if not VAR_14.isLeader(): raise Http404 def VAR_28(self, VAR_19, VAR_2): if settings.PUBLIC_ENABLED: if not hasattr(settings, "PUBLIC_USER"): VAR_0.warn( "OMERO.webpublic enabled but public user " "(omero.web.public.user) not set, disabling " "OMERO.webpublic." ) settings.PUBLIC_ENABLED = False return False if not hasattr(settings, "PUBLIC_PASSWORD"): VAR_0.warn( "OMERO.webpublic enabled but public user " "password (omero.web.public.password) not set, " "disabling OMERO.webpublic." ) settings.PUBLIC_ENABLED = False return False if settings.PUBLIC_GET_ONLY and (VAR_2.method != "GET"): return False if self.allowPublic is None: return settings.PUBLIC_URL_FILTER.search(VAR_2.path) is not None return self.allowPublic return False def FUNC_13(self, VAR_14, VAR_2): try: VAR_2.session["can_create"] except KeyError: VAR_2.session.modified = True VAR_2.session["can_create"] = VAR_14.canCreate() try: VAR_2.session["server_settings"] except Exception: VAR_2.session.modified = True VAR_2.session["server_settings"] = {} try: VAR_2.session["server_settings"] = propertiesToDict( VAR_14.getClientSettings(), prefix="omero.client." ) except Exception: VAR_0.error(traceback.format_exc()) VAR_2.session["server_settings"]["email"] = VAR_14.getEmailSettings() def FUNC_14(self): if not settings.PUBLIC_CACHE_ENABLED: return return cache.get(settings.PUBLIC_CACHE_KEY) def FUNC_15(self, VAR_5): if not settings.PUBLIC_CACHE_ENABLED or VAR_5.omero_session_key is None: return VAR_0.debug("Setting OMERO.webpublic VAR_5: %r" % VAR_5) cache.set(settings.PUBLIC_CACHE_KEY, VAR_5, settings.PUBLIC_CACHE_TIMEOUT) def FUNC_16(self, VAR_19, VAR_2): VAR_27 = self.get_authenticated_connection(VAR_19, VAR_2) VAR_28 = self.is_valid_public_url(VAR_19, VAR_2) VAR_0.debug("Is valid public URL? %s" % VAR_28) if VAR_27 is None and VAR_28: VAR_0.debug( "OMERO.webpublic enabled, attempting to login " "with configuration supplied credentials." ) if VAR_19 is None: VAR_19 = settings.PUBLIC_SERVER_ID VAR_32 = settings.PUBLIC_USER VAR_33 = settings.PUBLIC_PASSWORD VAR_31 = settings.SECURE VAR_0.debug("Is SSL? %s" % VAR_31) VAR_34 = self.get_public_user_connector() if VAR_34 is not None: VAR_0.debug( "Attempting to use cached OMERO.webpublic " "connector: %r" % VAR_34 ) VAR_27 = VAR_34.join_connection(self.useragent) if VAR_27 is not None: VAR_2.session["connector"] = VAR_34 VAR_0.debug( "Attempt to use cached OMERO.web public " "session key successful!" ) return VAR_27 VAR_0.debug( "Attempt to use cached OMERO.web public " "session key failed." ) VAR_5 = Connector(VAR_19, VAR_31) VAR_27 = VAR_5.create_connection( self.useragent, VAR_32, VAR_33, is_public=True, VAR_29=FUNC_1(VAR_2), ) VAR_2.session["connector"] = VAR_5 if "active_group" in VAR_2.session: del VAR_2.session["active_group"] if "user_id" in VAR_2.session: del VAR_2.session["user_id"] VAR_2.session.modified = True self.set_public_user_connector(VAR_5) elif VAR_27 is not None: VAR_38 = VAR_27.isAnonymous() VAR_0.debug("Is anonymous? %s" % VAR_38) if VAR_38 and not VAR_28: if VAR_27.c is not None: VAR_0.debug("Closing anonymous connection") VAR_27.close(hard=False) return None return VAR_27 def FUNC_17(self, VAR_19, VAR_2): VAR_29 = FUNC_1(VAR_2) VAR_30 = VAR_2.session VAR_2 = VAR_2.GET VAR_31 = settings.SECURE VAR_0.debug("Is SSL? %s" % VAR_31) VAR_5 = VAR_30.get("connector", None) VAR_0.debug("Connector: %s" % VAR_5) if VAR_19 is None: if VAR_5 is not None: VAR_19 = VAR_5.server_id else: try: VAR_19 = VAR_2["server"] except Exception: VAR_0.debug("No Server ID available.") return None try: VAR_35 = VAR_2["bsession"] VAR_5 = Connector(VAR_19, VAR_31) except KeyError: pass else: VAR_0.debug( "Have OMERO VAR_30 key %s, attempting to join..." % VAR_35 ) VAR_5.user_id = None VAR_5.omero_session_key = VAR_35 VAR_27 = VAR_5.join_connection(self.useragent, VAR_29) VAR_30["connector"] = VAR_5 return VAR_27 VAR_32 = None VAR_33 = None try: VAR_32 = VAR_2["username"] VAR_33 = VAR_2["password"] except KeyError: if VAR_5 is None: VAR_0.debug("No VAR_32 or VAR_33 in VAR_2, exiting.") return None if VAR_32 is not None and VAR_33 is not None: VAR_0.debug("Creating VAR_27 with VAR_32 and VAR_33...") VAR_5 = Connector(VAR_19, VAR_31) VAR_27 = VAR_5.create_connection( self.useragent, VAR_32, VAR_33, VAR_29=userip ) VAR_30["connector"] = VAR_5 return VAR_27 VAR_0.debug("Django VAR_30 VAR_5: %r" % VAR_5) if VAR_5 is not None: VAR_27 = VAR_5.join_connection(self.useragent, VAR_29) if VAR_27 is not None: VAR_0.debug("Connector valid, VAR_30 successfully joined.") return VAR_27 VAR_0.debug("Connector is no longer valid, destroying...") del VAR_30["connector"] return None VAR_30["connector"] = VAR_5 return None def __call__(VAR_20, VAR_21): def FUNC_19(VAR_2, *VAR_23, **VAR_24): VAR_3 = VAR_2.GET.get("url") if VAR_3 is None or len(VAR_3) == 0: VAR_3 = VAR_2.get_full_path() VAR_9 = False VAR_14 = VAR_24.get("conn", None) VAR_16 = None VAR_19 = VAR_24.get("server_id", None) if VAR_14 is None: VAR_9 = VAR_20.doConnectionCleanup VAR_0.debug("Connection not provided, attempting to get one.") try: VAR_14 = VAR_20.get_connection(VAR_19, VAR_2) except Exception as x: VAR_0.error("Error retrieving VAR_27.", exc_info=True) VAR_16 = str(x) else: if VAR_14 is None: return VAR_20.on_not_logged_in(VAR_2, VAR_3, VAR_16) else: VAR_20.on_logged_in(VAR_2, VAR_14) VAR_20.verify_is_admin(VAR_14) VAR_20.verify_is_group_owner(VAR_14, VAR_24.get("gid")) VAR_20.load_server_settings(VAR_14, VAR_2) VAR_15 = VAR_24.get("share_id") VAR_17 = VAR_20.prepare_share_connection(VAR_2, VAR_14, VAR_15) if VAR_17 is not None: VAR_20.on_share_connection_prepared(VAR_2, VAR_17) VAR_24["conn"] = VAR_17 else: VAR_24["conn"] = VAR_14 VAR_24["url"] = VAR_3 VAR_36 = None try: VAR_36 = VAR_21(VAR_2, *VAR_23, **VAR_24) finally: VAR_39 = isinstance(VAR_36, CLASS_0) if VAR_9 and VAR_39: raise ApiUsageException( "Methods that return a" " CLASS_0 must be marked with" " @CLASS_2(VAR_9=False)" ) VAR_9 = not VAR_39 VAR_0.debug("Doing VAR_27 cleanup? %s" % VAR_9) try: if VAR_9: if VAR_14 is not None and VAR_14.c is not None: VAR_14.close(hard=False) except Exception: VAR_0.warn("Failed to clean up connection", exc_info=True) return VAR_36 return update_wrapper(FUNC_19, VAR_21) class CLASS_3(object): def __getattr__(self, VAR_12): if VAR_12 == "__name__": return self.__class__.__name__ else: return super(CLASS_3, self).getattr(VAR_12) def FUNC_18(self, VAR_2, VAR_22, *VAR_23, **VAR_24): VAR_22["html"] = VAR_22.get("html", {}) VAR_22["html"]["meta_referrer"] = settings.HTML_META_REFERRER def __call__(VAR_20, VAR_21): def FUNC_20(VAR_2, *VAR_23, **VAR_24): VAR_22 = VAR_21(VAR_2, *VAR_23, **VAR_24) if isinstance(VAR_22, HttpResponseBase): return VAR_22 VAR_37 = "template" in VAR_22 and VAR_22["template"] or None VAR_37 = VAR_24.get("template", VAR_37) VAR_0.debug("Rendering VAR_37: %s" % VAR_37) if VAR_37 is None or VAR_37 == "json": VAR_40 = type(VAR_22) is dict return JsonResponse(VAR_22, VAR_40=safe) else: VAR_20.prepare_context(VAR_2, VAR_22, *VAR_23, **VAR_24) return render(VAR_2, VAR_37, VAR_22) return update_wrapper(FUNC_20, VAR_21)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 25, 32, 38, 43, 45, 46, 58, 68, 69, 77, 78, 82, 88, 89, 92, 101, 102, 105, 112, 114, 115, 122, 130, 149, 150, 151, 152, 158, 162, 164, 173, 176, 177, 191, 197, 214, 216, 222, 230, 234, 242, 257, 286, 305, 307, 316, 323, 333, 334, 335, 346, 364, 365, 366, 376, 377, 393, 399, 400, 408, 410, 411, 412, 421, 422, 423, 428, 431, 432, 441, 442, 443, 452, 453, 454, 456, 458, 459, 460, 461, 469, 472, 473, 478, 479, 480, 484, 487, 493, 498, 500, 504, 505, 506, 516, 517, 525, 533, 534, 540, 557, 559, 560, 573, 574, 575, 576, 582, 586, 589, 594, 595, 597, 598, 601, 602, 606, 607, 608, 610, 614, 617, 619, 22, 23, 24, 80, 81, 82, 83, 84, 91, 104, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 140, 141, 142, 160, 175, 193, 224, 225, 226, 227, 232, 236, 237, 238, 239, 244, 245, 246, 247, 248, 259, 260, 261, 262, 288, 309, 310, 311, 312, 318, 325, 326, 327, 328, 395, 396, 397, 398, 489, 490, 491, 492, 584, 588, 591, 592, 593 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 25, 32, 38, 43, 45, 46, 58, 68, 69, 77, 78, 82, 88, 89, 92, 101, 102, 105, 112, 114, 115, 122, 130, 149, 150, 151, 152, 158, 162, 164, 173, 176, 177, 191, 197, 214, 216, 222, 230, 234, 242, 257, 286, 305, 307, 316, 323, 333, 334, 335, 346, 364, 365, 366, 376, 377, 393, 399, 400, 408, 410, 411, 412, 421, 422, 423, 428, 431, 432, 441, 442, 443, 452, 453, 454, 456, 458, 459, 460, 461, 469, 472, 473, 478, 479, 480, 484, 487, 493, 498, 500, 504, 505, 506, 516, 517, 525, 533, 534, 540, 557, 559, 560, 573, 574, 575, 576, 582, 587, 590, 595, 596, 598, 599, 602, 603, 607, 608, 609, 611, 615, 618, 620, 22, 23, 24, 80, 81, 82, 83, 84, 91, 104, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 140, 141, 142, 160, 175, 193, 224, 225, 226, 227, 232, 236, 237, 238, 239, 244, 245, 246, 247, 248, 259, 260, 261, 262, 288, 309, 310, 311, 312, 318, 325, 326, 327, 328, 395, 396, 397, 398, 489, 490, 491, 492, 584, 589, 592, 593, 594 ]
4CWE-601
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import get_user_model from django.contrib import messages from django.utils.translation import gettext as _ from djconfig import config from ...core.utils.views import is_post, post_data from ...core.utils.paginator import yt_paginate from ...core.utils.decorators import administrator_required from .forms import UserForm, UserProfileForm User = get_user_model() @administrator_required def edit(request, user_id): user = get_object_or_404(User, pk=user_id) uform = UserForm(data=post_data(request), instance=user) form = UserProfileForm(data=post_data(request), instance=user.st) if is_post(request) and all([uform.is_valid(), form.is_valid()]): uform.save() form.save() messages.info(request, _("This profile has been updated!")) return redirect(request.GET.get("next", request.get_full_path())) return render( request=request, template_name='spirit/user/admin/edit.html', context={'form': form, 'uform': uform}) @administrator_required def _index(request, queryset, template): users = yt_paginate( queryset.order_by('-date_joined', '-pk'), per_page=config.topics_per_page, page_number=request.GET.get('page', 1) ) return render(request, template, context={'users': users}) def index(request): return _index( request, queryset=User.objects.all(), template='spirit/user/admin/index.html' ) def index_admins(request): return _index( request, queryset=User.objects.filter(st__is_administrator=True), template='spirit/user/admin/admins.html' ) def index_mods(request): return _index( request, queryset=User.objects.filter(st__is_moderator=True, st__is_administrator=False), template='spirit/user/admin/mods.html' ) def index_unactive(request): return _index( request, queryset=User.objects.filter(is_active=False), template='spirit/user/admin/unactive.html' )
# -*- coding: utf-8 -*- from django.shortcuts import render, get_object_or_404 from django.contrib.auth import get_user_model from django.contrib import messages from django.utils.translation import gettext as _ from djconfig import config from spirit.core.utils.http import safe_redirect from spirit.core.utils.views import is_post, post_data from spirit.core.utils.paginator import yt_paginate from spirit.core.utils.decorators import administrator_required from .forms import UserForm, UserProfileForm User = get_user_model() @administrator_required def edit(request, user_id): user = get_object_or_404(User, pk=user_id) uform = UserForm(data=post_data(request), instance=user) form = UserProfileForm(data=post_data(request), instance=user.st) if is_post(request) and all([uform.is_valid(), form.is_valid()]): uform.save() form.save() messages.info(request, _("This profile has been updated!")) return safe_redirect(request, "next", request.get_full_path()) return render( request=request, template_name='spirit/user/admin/edit.html', context={'form': form, 'uform': uform}) @administrator_required def _index(request, queryset, template): users = yt_paginate( queryset.order_by('-date_joined', '-pk'), per_page=config.topics_per_page, page_number=request.GET.get('page', 1) ) return render(request, template, context={'users': users}) def index(request): return _index( request, queryset=User.objects.all(), template='spirit/user/admin/index.html' ) def index_admins(request): return _index( request, queryset=User.objects.filter(st__is_administrator=True), template='spirit/user/admin/admins.html' ) def index_mods(request): return _index( request, queryset=User.objects.filter(st__is_moderator=True, st__is_administrator=False), template='spirit/user/admin/mods.html' ) def index_unactive(request): return _index( request, queryset=User.objects.filter(is_active=False), template='spirit/user/admin/unactive.html' )
open_redirect
{ "code": [ "from django.shortcuts import render, redirect, get_object_or_404", "from ...core.utils.views import is_post, post_data", "from ...core.utils.paginator import yt_paginate", "from ...core.utils.decorators import administrator_required", " return redirect(request.GET.get(\"next\", request.get_full_path()))" ], "line_no": [ 3, 10, 11, 12, 27 ] }
{ "code": [ "from django.shortcuts import render, get_object_or_404", "from spirit.core.utils.http import safe_redirect", "from spirit.core.utils.views import is_post, post_data", "from spirit.core.utils.paginator import yt_paginate", "from spirit.core.utils.decorators import administrator_required", " return safe_redirect(request, \"next\", request.get_full_path())" ], "line_no": [ 3, 10, 11, 12, 13, 28 ] }
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import get_user_model from django.contrib import messages from django.utils.translation import gettext as _ from djconfig import config from ...core.utils.views import is_post, post_data from ...core.utils.paginator import yt_paginate from ...core.utils.decorators import administrator_required from .forms import .UserForm, UserProfileForm VAR_0 = get_user_model() @administrator_required def FUNC_0(VAR_1, VAR_2): VAR_5 = get_object_or_404(VAR_0, pk=VAR_2) VAR_6 = UserForm(data=post_data(VAR_1), instance=VAR_5) VAR_7 = UserProfileForm(data=post_data(VAR_1), instance=VAR_5.st) if is_post(VAR_1) and all([VAR_6.is_valid(), VAR_7.is_valid()]): VAR_6.save() VAR_7.save() messages.info(VAR_1, _("This profile has been updated!")) return redirect(VAR_1.GET.get("next", VAR_1.get_full_path())) return render( VAR_1=request, template_name='spirit/VAR_5/admin/FUNC_0.html', context={'form': VAR_7, 'uform': VAR_6}) @administrator_required def FUNC_1(VAR_1, VAR_3, VAR_4): VAR_8 = yt_paginate( VAR_3.order_by('-date_joined', '-pk'), per_page=config.topics_per_page, page_number=VAR_1.GET.get('page', 1) ) return render(VAR_1, VAR_4, context={'users': VAR_8}) def FUNC_2(VAR_1): return FUNC_1( VAR_1, VAR_3=VAR_0.objects.all(), VAR_4='spirit/VAR_5/admin/FUNC_2.html' ) def FUNC_3(VAR_1): return FUNC_1( VAR_1, VAR_3=VAR_0.objects.filter(st__is_administrator=True), VAR_4='spirit/VAR_5/admin/admins.html' ) def FUNC_4(VAR_1): return FUNC_1( VAR_1, VAR_3=VAR_0.objects.filter(st__is_moderator=True, st__is_administrator=False), VAR_4='spirit/VAR_5/admin/mods.html' ) def FUNC_5(VAR_1): return FUNC_1( VAR_1, VAR_3=VAR_0.objects.filter(is_active=False), VAR_4='spirit/VAR_5/admin/unactive.html' )
from django.shortcuts import render, get_object_or_404 from django.contrib.auth import get_user_model from django.contrib import messages from django.utils.translation import gettext as _ from djconfig import config from spirit.core.utils.http import safe_redirect from spirit.core.utils.views import is_post, post_data from spirit.core.utils.paginator import yt_paginate from spirit.core.utils.decorators import administrator_required from .forms import .UserForm, UserProfileForm VAR_0 = get_user_model() @administrator_required def FUNC_0(VAR_1, VAR_2): VAR_5 = get_object_or_404(VAR_0, pk=VAR_2) VAR_6 = UserForm(data=post_data(VAR_1), instance=VAR_5) VAR_7 = UserProfileForm(data=post_data(VAR_1), instance=VAR_5.st) if is_post(VAR_1) and all([VAR_6.is_valid(), VAR_7.is_valid()]): VAR_6.save() VAR_7.save() messages.info(VAR_1, _("This profile has been updated!")) return safe_redirect(VAR_1, "next", VAR_1.get_full_path()) return render( VAR_1=request, template_name='spirit/VAR_5/admin/FUNC_0.html', context={'form': VAR_7, 'uform': VAR_6}) @administrator_required def FUNC_1(VAR_1, VAR_3, VAR_4): VAR_8 = yt_paginate( VAR_3.order_by('-date_joined', '-pk'), per_page=config.topics_per_page, page_number=VAR_1.GET.get('page', 1) ) return render(VAR_1, VAR_4, context={'users': VAR_8}) def FUNC_2(VAR_1): return FUNC_1( VAR_1, VAR_3=VAR_0.objects.all(), VAR_4='spirit/VAR_5/admin/FUNC_2.html' ) def FUNC_3(VAR_1): return FUNC_1( VAR_1, VAR_3=VAR_0.objects.filter(st__is_administrator=True), VAR_4='spirit/VAR_5/admin/admins.html' ) def FUNC_4(VAR_1): return FUNC_1( VAR_1, VAR_3=VAR_0.objects.filter(st__is_moderator=True, st__is_administrator=False), VAR_4='spirit/VAR_5/admin/mods.html' ) def FUNC_5(VAR_1): return FUNC_1( VAR_1, VAR_3=VAR_0.objects.filter(is_active=False), VAR_4='spirit/VAR_5/admin/unactive.html' )
[ 1, 2, 7, 9, 14, 16, 17, 32, 33, 42, 43, 50, 51, 58, 59, 66, 67, 74 ]
[ 1, 2, 7, 9, 15, 17, 18, 33, 34, 43, 44, 51, 52, 59, 60, 67, 68, 75 ]
5CWE-94
from dataclasses import asdict from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, cast import httpx from ..client import AuthenticatedClient, Client from ..errors import ApiResponseError from ..models.a_model import AModel from ..models.an_enum import AnEnum from ..models.body_upload_file_tests_upload_post import BodyUploadFileTestsUploadPost from ..models.http_validation_error import HTTPValidationError def get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime], ) -> Union[ List[AModel], HTTPValidationError, ]: """ Get a list of things """ url = "{}/tests/".format(client.base_url) headers: Dict[str, Any] = client.get_headers() json_an_enum_value = [] for an_enum_value_item_data in an_enum_value: an_enum_value_item = an_enum_value_item_data.value json_an_enum_value.append(an_enum_value_item) if isinstance(some_date, date): json_some_date = some_date.isoformat() else: json_some_date = some_date.isoformat() params: Dict[str, Any] = { "an_enum_value": json_an_enum_value, "some_date": json_some_date, } response = httpx.get(url=url, headers=headers, params=params,) if response.status_code == 200: return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], response.json())] if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) def upload_file_tests_upload_post( *, client: Client, multipart_data: BodyUploadFileTestsUploadPost, keep_alive: Optional[bool] = None, ) -> Union[ None, HTTPValidationError, ]: """ Upload a file """ url = "{}/tests/upload".format(client.base_url) headers: Dict[str, Any] = client.get_headers() if keep_alive is not None: headers["keep-alive"] = keep_alive response = httpx.post(url=url, headers=headers, files=multipart_data.to_dict(),) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) def json_body_tests_json_body_post( *, client: Client, json_body: AModel, ) -> Union[ None, HTTPValidationError, ]: """ Try sending a JSON body """ url = "{}/tests/json_body".format(client.base_url) headers: Dict[str, Any] = client.get_headers() json_json_body = json_body.to_dict() response = httpx.post(url=url, headers=headers, json=json_json_body,) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response)
import datetime from dataclasses import asdict, field from typing import Any, Dict, List, Optional, Union, cast import httpx from ..client import AuthenticatedClient, Client from ..errors import ApiResponseError from ..models.a_model import AModel from ..models.an_enum import AnEnum from ..models.body_upload_file_tests_upload_post import BodyUploadFileTestsUploadPost from ..models.http_validation_error import HTTPValidationError def get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[datetime.date, datetime.datetime], ) -> Union[ List[AModel], HTTPValidationError, ]: """ Get a list of things """ url = "{}/tests/".format(client.base_url) headers: Dict[str, Any] = client.get_headers() json_an_enum_value = [] for an_enum_value_item_data in an_enum_value: an_enum_value_item = an_enum_value_item_data.value json_an_enum_value.append(an_enum_value_item) if isinstance(some_date, datetime.date): json_some_date = some_date.isoformat() else: json_some_date = some_date.isoformat() params: Dict[str, Any] = { "an_enum_value": json_an_enum_value, "some_date": json_some_date, } response = httpx.get(url=url, headers=headers, params=params,) if response.status_code == 200: return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], response.json())] if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) def upload_file_tests_upload_post( *, client: Client, multipart_data: BodyUploadFileTestsUploadPost, keep_alive: Optional[bool] = None, ) -> Union[ None, HTTPValidationError, ]: """ Upload a file """ url = "{}/tests/upload".format(client.base_url) headers: Dict[str, Any] = client.get_headers() if keep_alive is not None: headers["keep-alive"] = keep_alive response = httpx.post(url=url, headers=headers, files=multipart_data.to_dict(),) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) def json_body_tests_json_body_post( *, client: Client, json_body: AModel, ) -> Union[ None, HTTPValidationError, ]: """ Try sending a JSON body """ url = "{}/tests/json_body".format(client.base_url) headers: Dict[str, Any] = client.get_headers() json_json_body = json_body.to_dict() response = httpx.post(url=url, headers=headers, json=json_json_body,) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) def test_defaults_tests_test_defaults_post( *, client: Client, json_body: Dict[Any, Any], string_prop: Optional[str] = "the default string", datetime_prop: Optional[datetime.datetime] = datetime.datetime(1010, 10, 10, 0, 0), date_prop: Optional[datetime.date] = datetime.date(1010, 10, 10), float_prop: Optional[float] = 3.14, int_prop: Optional[int] = 7, boolean_prop: Optional[bool] = False, list_prop: Optional[List[AnEnum]] = field( default_factory=lambda: cast(Optional[List[AnEnum]], [AnEnum.FIRST_VALUE, AnEnum.SECOND_VALUE]) ), union_prop: Optional[Union[Optional[float], Optional[str]]] = "not a float", enum_prop: Optional[AnEnum] = None, ) -> Union[ None, HTTPValidationError, ]: """ """ url = "{}/tests/test_defaults".format(client.base_url) headers: Dict[str, Any] = client.get_headers() json_datetime_prop = datetime_prop.isoformat() if datetime_prop else None json_date_prop = date_prop.isoformat() if date_prop else None if list_prop is None: json_list_prop = None else: json_list_prop = [] for list_prop_item_data in list_prop: list_prop_item = list_prop_item_data.value json_list_prop.append(list_prop_item) if union_prop is None: json_union_prop: Optional[Union[Optional[float], Optional[str]]] = None elif isinstance(union_prop, float): json_union_prop = union_prop else: json_union_prop = union_prop json_enum_prop = enum_prop.value if enum_prop else None params: Dict[str, Any] = {} if string_prop is not None: params["string_prop"] = string_prop if datetime_prop is not None: params["datetime_prop"] = json_datetime_prop if date_prop is not None: params["date_prop"] = json_date_prop if float_prop is not None: params["float_prop"] = float_prop if int_prop is not None: params["int_prop"] = int_prop if boolean_prop is not None: params["boolean_prop"] = boolean_prop if list_prop is not None: params["list_prop"] = json_list_prop if union_prop is not None: params["union_prop"] = json_union_prop if enum_prop is not None: params["enum_prop"] = json_enum_prop json_json_body = json_body response = httpx.post(url=url, headers=headers, json=json_json_body, params=params,) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response)
remote_code_execution
{ "code": [ "from dataclasses import asdict", "from datetime import date, datetime", " *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],", " if isinstance(some_date, date):" ], "line_no": [ 1, 2, 16, 32 ] }
{ "code": [ "import datetime", "from dataclasses import asdict, field", " *, client: Client, an_enum_value: List[AnEnum], some_date: Union[datetime.date, datetime.datetime],", " if isinstance(some_date, datetime.date):", "def test_defaults_tests_test_defaults_post(", " *,", " client: Client,", " json_body: Dict[Any, Any],", " string_prop: Optional[str] = \"the default string\",", " datetime_prop: Optional[datetime.datetime] = datetime.datetime(1010, 10, 10, 0, 0),", " date_prop: Optional[datetime.date] = datetime.date(1010, 10, 10),", " float_prop: Optional[float] = 3.14,", " int_prop: Optional[int] = 7,", " boolean_prop: Optional[bool] = False,", " list_prop: Optional[List[AnEnum]] = field(", " default_factory=lambda: cast(Optional[List[AnEnum]], [AnEnum.FIRST_VALUE, AnEnum.SECOND_VALUE])", " ),", " union_prop: Optional[Union[Optional[float], Optional[str]]] = \"not a float\",", " enum_prop: Optional[AnEnum] = None,", ") -> Union[", " None, HTTPValidationError,", "]:", " \"\"\" \"\"\"", " url = \"{}/tests/test_defaults\".format(client.base_url)", " headers: Dict[str, Any] = client.get_headers()", " json_datetime_prop = datetime_prop.isoformat() if datetime_prop else None", " json_date_prop = date_prop.isoformat() if date_prop else None", " if list_prop is None:", " json_list_prop = None", " else:", " json_list_prop = []", " for list_prop_item_data in list_prop:", " list_prop_item = list_prop_item_data.value", " json_list_prop.append(list_prop_item)", " if union_prop is None:", " json_union_prop: Optional[Union[Optional[float], Optional[str]]] = None", " elif isinstance(union_prop, float):", " json_union_prop = union_prop", " else:", " json_union_prop = union_prop", " json_enum_prop = enum_prop.value if enum_prop else None", " params: Dict[str, Any] = {}", " if string_prop is not None:", " params[\"string_prop\"] = string_prop", " if datetime_prop is not None:", " params[\"datetime_prop\"] = json_datetime_prop", " if date_prop is not None:", " params[\"date_prop\"] = json_date_prop", " if float_prop is not None:", " params[\"float_prop\"] = float_prop", " if int_prop is not None:", " params[\"int_prop\"] = int_prop", " if boolean_prop is not None:", " params[\"boolean_prop\"] = boolean_prop", " if list_prop is not None:", " params[\"list_prop\"] = json_list_prop", " if union_prop is not None:", " params[\"union_prop\"] = json_union_prop", " if enum_prop is not None:", " params[\"enum_prop\"] = json_enum_prop", " json_json_body = json_body", " response = httpx.post(url=url, headers=headers, json=json_json_body, params=params,)", " if response.status_code == 200:", " return None", " if response.status_code == 422:", " return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json()))", " else:", " raise ApiResponseError(response=response)" ], "line_no": [ 1, 2, 16, 32, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 118, 119, 121, 123, 125, 127, 128, 129, 130, 131, 132, 134, 136, 137, 138, 139, 140, 141, 143, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 165, 167, 169, 170, 171, 172, 173, 174 ] }
from dataclasses import asdict from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, cast import httpx from ..client import AuthenticatedClient, Client from ..errors import ApiResponseError from ..models.a_model import AModel from ..models.an_enum import AnEnum from ..models.body_upload_file_tests_upload_post import BodyUploadFileTestsUploadPost from ..models.http_validation_error import HTTPValidationError def FUNC_0( *, VAR_0: Client, VAR_1: List[AnEnum], VAR_2: Union[date, datetime], ) -> Union[ List[AModel], HTTPValidationError, ]: VAR_6 = "{}/tests/".format(VAR_0.base_url) VAR_12: Dict[str, Any] = VAR_0.get_headers() VAR_7 = [] for an_enum_value_item_data in VAR_1: VAR_10 = an_enum_value_item_data.value VAR_7.append(VAR_10) if isinstance(VAR_2, date): VAR_11 = VAR_2.isoformat() else: VAR_11 = VAR_2.isoformat() params: Dict[str, Any] = { "an_enum_value": VAR_7, "some_date": VAR_11, } VAR_8 = httpx.get(VAR_6=url, VAR_12=headers, params=params,) if VAR_8.status_code == 200: return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], VAR_8.json())] if VAR_8.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_8.json())) else: raise ApiResponseError(VAR_8=response) def FUNC_1( *, VAR_0: Client, VAR_3: BodyUploadFileTestsUploadPost, VAR_4: Optional[bool] = None, ) -> Union[ None, HTTPValidationError, ]: VAR_6 = "{}/tests/upload".format(VAR_0.base_url) VAR_12: Dict[str, Any] = VAR_0.get_headers() if VAR_4 is not None: VAR_12["keep-alive"] = VAR_4 VAR_8 = httpx.post(VAR_6=url, VAR_12=headers, files=VAR_3.to_dict(),) if VAR_8.status_code == 200: return None if VAR_8.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_8.json())) else: raise ApiResponseError(VAR_8=response) def FUNC_2( *, VAR_0: Client, VAR_5: AModel, ) -> Union[ None, HTTPValidationError, ]: VAR_6 = "{}/tests/json_body".format(VAR_0.base_url) VAR_12: Dict[str, Any] = VAR_0.get_headers() VAR_9 = VAR_5.to_dict() VAR_8 = httpx.post(VAR_6=url, VAR_12=headers, json=VAR_9,) if VAR_8.status_code == 200: return None if VAR_8.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_8.json())) else: raise ApiResponseError(VAR_8=response)
import datetime from dataclasses import asdict, field from typing import Any, Dict, List, Optional, Union, cast import httpx from ..client import AuthenticatedClient, Client from ..errors import ApiResponseError from ..models.a_model import AModel from ..models.an_enum import AnEnum from ..models.body_upload_file_tests_upload_post import BodyUploadFileTestsUploadPost from ..models.http_validation_error import HTTPValidationError def FUNC_0( *, VAR_0: Client, VAR_1: List[AnEnum], VAR_2: Union[datetime.date, datetime.datetime], ) -> Union[ List[AModel], HTTPValidationError, ]: VAR_15 = "{}/tests/".format(VAR_0.base_url) VAR_24: Dict[str, Any] = VAR_0.get_headers() VAR_16 = [] for an_enum_value_item_data in VAR_1: VAR_22 = an_enum_value_item_data.value VAR_16.append(VAR_22) if isinstance(VAR_2, datetime.date): VAR_23 = VAR_2.isoformat() else: VAR_23 = VAR_2.isoformat() VAR_26: Dict[str, Any] = { "an_enum_value": VAR_16, "some_date": VAR_23, } VAR_17 = httpx.get(VAR_15=url, VAR_24=headers, VAR_26=params,) if VAR_17.status_code == 200: return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], VAR_17.json())] if VAR_17.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_17.json())) else: raise ApiResponseError(VAR_17=response) def FUNC_1( *, VAR_0: Client, VAR_3: BodyUploadFileTestsUploadPost, VAR_4: Optional[bool] = None, ) -> Union[ None, HTTPValidationError, ]: VAR_15 = "{}/tests/upload".format(VAR_0.base_url) VAR_24: Dict[str, Any] = VAR_0.get_headers() if VAR_4 is not None: VAR_24["keep-alive"] = VAR_4 VAR_17 = httpx.post(VAR_15=url, VAR_24=headers, files=VAR_3.to_dict(),) if VAR_17.status_code == 200: return None if VAR_17.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_17.json())) else: raise ApiResponseError(VAR_17=response) def FUNC_2( *, VAR_0: Client, VAR_5: AModel, ) -> Union[ None, HTTPValidationError, ]: VAR_15 = "{}/tests/json_body".format(VAR_0.base_url) VAR_24: Dict[str, Any] = VAR_0.get_headers() VAR_18 = VAR_5.to_dict() VAR_17 = httpx.post(VAR_15=url, VAR_24=headers, json=VAR_18,) if VAR_17.status_code == 200: return None if VAR_17.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_17.json())) else: raise ApiResponseError(VAR_17=response) def FUNC_3( *, VAR_0: Client, VAR_5: Dict[Any, Any], VAR_6: Optional[str] = "the default string", VAR_7: Optional[datetime.datetime] = datetime.datetime(1010, 10, 10, 0, 0), VAR_8: Optional[datetime.date] = datetime.date(1010, 10, 10), VAR_9: Optional[float] = 3.14, VAR_10: Optional[int] = 7, VAR_11: Optional[bool] = False, VAR_12: Optional[List[AnEnum]] = field( default_factory=lambda: cast(Optional[List[AnEnum]], [AnEnum.FIRST_VALUE, AnEnum.SECOND_VALUE]) ), VAR_13: Optional[Union[Optional[float], Optional[str]]] = "not a float", VAR_14: Optional[AnEnum] = None, ) -> Union[ None, HTTPValidationError, ]: VAR_15 = "{}/tests/test_defaults".format(VAR_0.base_url) VAR_24: Dict[str, Any] = VAR_0.get_headers() VAR_19 = VAR_7.isoformat() if VAR_7 else None VAR_20 = VAR_8.isoformat() if VAR_8 else None if VAR_12 is None: VAR_25 = None else: VAR_25 = [] for list_prop_item_data in VAR_12: VAR_27 = list_prop_item_data.value VAR_25.append(VAR_27) if VAR_13 is None: VAR_28: Optional[Union[Optional[float], Optional[str]]] = None elif isinstance(VAR_13, float): VAR_28 = VAR_13 else: VAR_28 = VAR_13 VAR_21 = VAR_14.value if VAR_14 else None VAR_26: Dict[str, Any] = {} if VAR_6 is not None: VAR_26["string_prop"] = VAR_6 if VAR_7 is not None: VAR_26["datetime_prop"] = VAR_19 if VAR_8 is not None: VAR_26["date_prop"] = VAR_20 if VAR_9 is not None: VAR_26["float_prop"] = VAR_9 if VAR_10 is not None: VAR_26["int_prop"] = VAR_10 if VAR_11 is not None: VAR_26["boolean_prop"] = VAR_11 if VAR_12 is not None: VAR_26["list_prop"] = VAR_25 if VAR_13 is not None: VAR_26["union_prop"] = VAR_28 if VAR_14 is not None: VAR_26["enum_prop"] = VAR_21 VAR_18 = VAR_5 VAR_17 = httpx.post(VAR_15=url, VAR_24=headers, json=VAR_18, VAR_26=params,) if VAR_17.status_code == 200: return None if VAR_17.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_17.json())) else: raise ApiResponseError(VAR_17=response)
[ 4, 6, 13, 14, 20, 23, 25, 29, 31, 34, 37, 42, 44, 51, 52, 58, 61, 65, 67, 74, 75, 81, 84, 86, 88, 90, 97, 21, 59, 82 ]
[ 4, 6, 13, 14, 20, 23, 25, 29, 31, 34, 37, 42, 44, 51, 52, 58, 61, 65, 67, 74, 75, 81, 84, 86, 88, 90, 97, 98, 117, 120, 122, 124, 126, 133, 135, 142, 144, 164, 166, 168, 175, 21, 59, 82, 118 ]
1CWE-79
#!/usr/bin/env python # -*- coding: utf-8 -*- #** # ######### # trape # ######### # # trape depends of this file # For full copyright information this visit: https://github.com/boxug/trape # # Copyright 2017 by boxug / <hey@boxug.com> #** import urllib2 from flask import Flask, render_template, session, request, json from core.trape import Trape from core.db import Database # Main parts, to generate relationships among others trape = Trape() app = Flask(__name__, template_folder='../templates', static_folder='../static') # call database db = Database() # preview header tool in console trape.header() @app.route("/" + trape.stats_path) def index(): return render_template("/login.html") @app.route("/logout") def logout(): return render_template("/login.html") @app.route("/login", methods=["POST"]) def login(): id = request.form['id'] if id == trape.stats_key: return json.dumps({'status':'OK', 'path' : trape.home_path, 'victim_path' : trape.victim_path, 'url_to_clone' : trape.url_to_clone, 'app_port' : trape.app_port, 'date_start' : trape.date_start, 'user_ip' : '127.0.0.1'}); else: return json.dumps({'status':'NOPE', 'path' : '/'}); @app.route("/get_data", methods=["POST"]) def home_get_dat(): d = db.sentences_stats('get_data') n = db.sentences_stats('all_networks') ('clean_online') rows = db.sentences_stats('get_clicks') c = rows[0][0] rows = db.sentences_stats('get_sessions') s = rows[0][0] rows = db.sentences_stats('get_online') o = rows[0][0] return json.dumps({'status' : 'OK', 'd' : d, 'n' : n, 'c' : c, 's' : s, 'o' : o}); @app.route("/get_preview", methods=["POST"]) def home_get_preview(): vId = request.form['vId'] d = db.sentences_stats('get_preview', vId) n = db.sentences_stats('id_networks', vId) return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n}); @app.route("/get_title", methods=["POST"]) def home_get_title(): opener = urllib2.build_opener() html = opener.open(trape.url_to_clone).read() html = html[html.find('<title>') + 7 : html.find('</title>')] return json.dumps({'status' : 'OK', 'title' : html}); @app.route("/get_requests", methods=["POST"]) def home_get_requests(): d = db.sentences_stats('get_requests') return json.dumps({'status' : 'OK', 'd' : d});
#!/usr/bin/env python # -*- coding: utf-8 -*- #** # ######### # trape # ######### # # trape depends of this file # For full copyright information this visit: https://github.com/boxug/trape # # Copyright 2017 by boxug / <hey@boxug.com> #** import urllib2 from flask import Flask, render_template, session, request, json from core.trape import Trape from core.db import Database # Main parts, to generate relationships among others trape = Trape() app = Flask(__name__, template_folder='../templates', static_folder='../static') # call database db = Database() # preview header tool in console trape.header() @app.route("/" + trape.stats_path) def index(): return render_template("/login.html") @app.route("/logout") def logout(): return render_template("/login.html") @app.route("/login", methods=["POST"]) def login(): id = request.form['id'] if id == trape.stats_key: return json.dumps({'status':'OK', 'path' : trape.home_path, 'victim_path' : trape.victim_path, 'url_to_clone' : trape.url_to_clone, 'app_port' : trape.app_port, 'date_start' : trape.date_start, 'user_ip' : '127.0.0.1'}); else: return json.dumps({'status':'NOPE', 'path' : '/'}); @app.route("/get_data", methods=["POST"]) def home_get_dat(): d = db.sentences_stats('get_data') n = db.sentences_stats('all_networks') rows = db.sentences_stats('get_clicks') c = rows[0][0] rows = db.sentences_stats('get_sessions') s = rows[0][0] vId = ('online', ) rows = db.sentences_stats('get_online', vId) o = rows[0][0] return json.dumps({'status' : 'OK', 'd' : d, 'n' : n, 'c' : c, 's' : s, 'o' : o}); @app.route("/get_preview", methods=["POST"]) def home_get_preview(): vId = request.form['vId'] t = (vId,) d = db.sentences_stats('get_preview', t) n = db.sentences_stats('id_networks', t) return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n}); @app.route("/get_title", methods=["POST"]) def home_get_title(): opener = urllib2.build_opener() html = opener.open(trape.url_to_clone).read() html = html[html.find('<title>') + 7 : html.find('</title>')] return json.dumps({'status' : 'OK', 'title' : html}); @app.route("/get_requests", methods=["POST"]) def home_get_requests(): d = db.sentences_stats('get_requests') return json.dumps({'status' : 'OK', 'd' : d});
xss
{ "code": [ " ('clean_online')", " rows = db.sentences_stats('get_online')", " d = db.sentences_stats('get_preview', vId)", " n = db.sentences_stats('id_networks', vId)" ], "line_no": [ 50, 55, 63, 64 ] }
{ "code": [ " vId = ('online', )", " rows = db.sentences_stats('get_online', vId)", " t = (vId,)", " d = db.sentences_stats('get_preview', t)", " n = db.sentences_stats('id_networks', t)" ], "line_no": [ 54, 55, 63, 64, 65 ] }
import urllib2 from flask import Flask, render_template, session, request, json from core.trape import Trape from core.db import Database VAR_0 = Trape() VAR_1 = Flask(__name__, template_folder='../templates', static_folder='../static') VAR_2 = Database() VAR_0.header() @VAR_1.route("/" + VAR_0.stats_path) def FUNC_0(): return render_template("/FUNC_2.html") @VAR_1.route("/logout") def FUNC_1(): return render_template("/FUNC_2.html") @VAR_1.route("/login", methods=["POST"]) def FUNC_2(): VAR_3 = request.form['id'] if VAR_3 == VAR_0.stats_key: return json.dumps({'status':'OK', 'path' : VAR_0.home_path, 'victim_path' : VAR_0.victim_path, 'url_to_clone' : VAR_0.url_to_clone, 'app_port' : VAR_0.app_port, 'date_start' : VAR_0.date_start, 'user_ip' : '127.0.0.1'}); else: return json.dumps({'status':'NOPE', 'path' : '/'}); @VAR_1.route("/get_data", methods=["POST"]) def FUNC_3(): VAR_4 = VAR_2.sentences_stats('get_data') VAR_5 = VAR_2.sentences_stats('all_networks') ('clean_online') VAR_6 = VAR_2.sentences_stats('get_clicks') VAR_7 = VAR_6[0][0] VAR_6 = VAR_2.sentences_stats('get_sessions') VAR_8 = VAR_6[0][0] VAR_6 = VAR_2.sentences_stats('get_online') VAR_9 = VAR_6[0][0] return json.dumps({'status' : 'OK', 'd' : VAR_4, 'n' : VAR_5, 'c' : VAR_7, 's' : VAR_8, 'o' : VAR_9}); @VAR_1.route("/get_preview", methods=["POST"]) def FUNC_4(): VAR_10 = request.form['vId'] VAR_4 = VAR_2.sentences_stats('get_preview', VAR_10) VAR_5 = VAR_2.sentences_stats('id_networks', VAR_10) return json.dumps({'status' : 'OK', 'vId' : VAR_10, 'd' : VAR_4, 'n' : VAR_5}); @VAR_1.route("/get_title", methods=["POST"]) def FUNC_5(): VAR_11 = urllib2.build_opener() VAR_12 = VAR_11.open(VAR_0.url_to_clone).read() VAR_12 = html[VAR_12.find('<title>') + 7 : VAR_12.find('</title>')] return json.dumps({'status' : 'OK', 'title' : VAR_12}); @VAR_1.route("/get_requests", methods=["POST"]) def FUNC_6(): VAR_4 = VAR_2.sentences_stats('get_requests') return json.dumps({'status' : 'OK', 'd' : VAR_4});
import urllib2 from flask import Flask, render_template, session, request, json from core.trape import Trape from core.db import Database VAR_0 = Trape() VAR_1 = Flask(__name__, template_folder='../templates', static_folder='../static') VAR_2 = Database() VAR_0.header() @VAR_1.route("/" + VAR_0.stats_path) def FUNC_0(): return render_template("/FUNC_2.html") @VAR_1.route("/logout") def FUNC_1(): return render_template("/FUNC_2.html") @VAR_1.route("/login", methods=["POST"]) def FUNC_2(): VAR_3 = request.form['id'] if VAR_3 == VAR_0.stats_key: return json.dumps({'status':'OK', 'path' : VAR_0.home_path, 'victim_path' : VAR_0.victim_path, 'url_to_clone' : VAR_0.url_to_clone, 'app_port' : VAR_0.app_port, 'date_start' : VAR_0.date_start, 'user_ip' : '127.0.0.1'}); else: return json.dumps({'status':'NOPE', 'path' : '/'}); @VAR_1.route("/get_data", methods=["POST"]) def FUNC_3(): VAR_4 = VAR_2.sentences_stats('get_data') VAR_5 = VAR_2.sentences_stats('all_networks') VAR_6 = VAR_2.sentences_stats('get_clicks') VAR_7 = VAR_6[0][0] VAR_6 = VAR_2.sentences_stats('get_sessions') VAR_8 = VAR_6[0][0] VAR_9 = ('online', ) VAR_6 = VAR_2.sentences_stats('get_online', VAR_9) VAR_10 = VAR_6[0][0] return json.dumps({'status' : 'OK', 'd' : VAR_4, 'n' : VAR_5, 'c' : VAR_7, 's' : VAR_8, 'o' : VAR_10}); @VAR_1.route("/get_preview", methods=["POST"]) def FUNC_4(): VAR_9 = request.form['vId'] VAR_11 = (VAR_9,) VAR_4 = VAR_2.sentences_stats('get_preview', VAR_11) VAR_5 = VAR_2.sentences_stats('id_networks', VAR_11) return json.dumps({'status' : 'OK', 'vId' : VAR_9, 'd' : VAR_4, 'n' : VAR_5}); @VAR_1.route("/get_title", methods=["POST"]) def FUNC_5(): VAR_12 = urllib2.build_opener() VAR_13 = VAR_12.open(VAR_0.url_to_clone).read() VAR_13 = html[VAR_13.find('<title>') + 7 : VAR_13.find('</title>')] return json.dumps({'status' : 'OK', 'title' : VAR_13}); @VAR_1.route("/get_requests", methods=["POST"]) def FUNC_6(): VAR_4 = VAR_2.sentences_stats('get_requests') return json.dumps({'status' : 'OK', 'd' : VAR_4});
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 18, 19, 22, 23, 25, 26, 28, 32, 36, 44, 49, 57, 59, 66, 73, 77 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 18, 19, 22, 23, 25, 26, 28, 32, 36, 44, 49, 57, 59, 67, 74, 78 ]
4CWE-601
import datetime import logging import re from flask import abort, current_app, flash, g, redirect, request, session, url_for from flask_babel import lazy_gettext from flask_login import login_user, logout_user import jwt from werkzeug.security import generate_password_hash from wtforms import PasswordField, validators from wtforms.validators import EqualTo from .decorators import has_access from .forms import LoginForm_db, LoginForm_oid, ResetPasswordForm, UserInfoEdit from .._compat import as_unicode from ..actions import action from ..baseviews import BaseView from ..charts.views import DirectByChartView from ..fieldwidgets import BS3PasswordFieldWidget from ..utils.base import lazy_formatter_gettext from ..views import expose, ModelView, SimpleFormView from ..widgets import ListWidget, ShowWidget log = logging.getLogger(__name__) class PermissionModelView(ModelView): route_base = "/permissions" base_permissions = ["can_list"] list_title = lazy_gettext("List Base Permissions") show_title = lazy_gettext("Show Base Permission") add_title = lazy_gettext("Add Base Permission") edit_title = lazy_gettext("Edit Base Permission") label_columns = {"name": lazy_gettext("Name")} class ViewMenuModelView(ModelView): route_base = "/viewmenus" base_permissions = ["can_list"] list_title = lazy_gettext("List View Menus") show_title = lazy_gettext("Show View Menu") add_title = lazy_gettext("Add View Menu") edit_title = lazy_gettext("Edit View Menu") label_columns = {"name": lazy_gettext("Name")} class PermissionViewModelView(ModelView): route_base = "/permissionviews" base_permissions = ["can_list"] list_title = lazy_gettext("List Permissions on Views/Menus") show_title = lazy_gettext("Show Permission on Views/Menus") add_title = lazy_gettext("Add Permission on Views/Menus") edit_title = lazy_gettext("Edit Permission on Views/Menus") label_columns = { "permission": lazy_gettext("Permission"), "view_menu": lazy_gettext("View/Menu"), } list_columns = ["permission", "view_menu"] class ResetMyPasswordView(SimpleFormView): """ View for resetting own user password """ route_base = "/resetmypassword" form = ResetPasswordForm form_title = lazy_gettext("Reset Password Form") redirect_url = "/" message = lazy_gettext("Password Changed") def form_post(self, form): self.appbuilder.sm.reset_password(g.user.id, form.password.data) flash(as_unicode(self.message), "info") class ResetPasswordView(SimpleFormView): """ View for reseting all users password """ route_base = "/resetpassword" form = ResetPasswordForm form_title = lazy_gettext("Reset Password Form") redirect_url = "/" message = lazy_gettext("Password Changed") def form_post(self, form): pk = request.args.get("pk") self.appbuilder.sm.reset_password(pk, form.password.data) flash(as_unicode(self.message), "info") class UserInfoEditView(SimpleFormView): form = UserInfoEdit form_title = lazy_gettext("Edit User Information") redirect_url = "/" message = lazy_gettext("User information changed") def form_get(self, form): item = self.appbuilder.sm.get_user_by_id(g.user.id) # fills the form generic solution for key, value in form.data.items(): if key == "csrf_token": continue form_field = getattr(form, key) form_field.data = getattr(item, key) def form_post(self, form): form = self.form.refresh(request.form) item = self.appbuilder.sm.get_user_by_id(g.user.id) form.populate_obj(item) self.appbuilder.sm.update_user(item) flash(as_unicode(self.message), "info") def _roles_custom_formatter(string: str) -> str: if current_app.config.get("AUTH_ROLES_SYNC_AT_LOGIN", False): string += ( ". <div class='alert alert-warning' role='alert'>" "AUTH_ROLES_SYNC_AT_LOGIN is enabled, changes to this field will " "not persist between user logins." "</div>" ) return string class UserModelView(ModelView): route_base = "/users" list_title = lazy_gettext("List Users") show_title = lazy_gettext("Show User") add_title = lazy_gettext("Add User") edit_title = lazy_gettext("Edit User") label_columns = { "get_full_name": lazy_gettext("Full Name"), "first_name": lazy_gettext("First Name"), "last_name": lazy_gettext("Last Name"), "username": lazy_gettext("User Name"), "password": lazy_gettext("Password"), "active": lazy_gettext("Is Active?"), "email": lazy_gettext("Email"), "roles": lazy_gettext("Role"), "last_login": lazy_gettext("Last login"), "login_count": lazy_gettext("Login count"), "fail_login_count": lazy_gettext("Failed login count"), "created_on": lazy_gettext("Created on"), "created_by": lazy_gettext("Created by"), "changed_on": lazy_gettext("Changed on"), "changed_by": lazy_gettext("Changed by"), } description_columns = { "first_name": lazy_gettext("Write the user first name or names"), "last_name": lazy_gettext("Write the user last name"), "username": lazy_gettext( "Username valid for authentication on DB or LDAP, unused for OID auth" ), "password": lazy_gettext( "Please use a good password policy," " this application does not check this for you" ), "active": lazy_gettext( "It's not a good policy to remove a user, just make it inactive" ), "email": lazy_gettext("The user's email, this will also be used for OID auth"), "roles": lazy_formatter_gettext( "The user role on the application," " this will associate with a list of permissions", _roles_custom_formatter, ), "conf_password": lazy_gettext("Please rewrite the user's password to confirm"), } list_columns = ["first_name", "last_name", "username", "email", "active", "roles"] show_fieldsets = [ ( lazy_gettext("User info"), {"fields": ["username", "active", "roles", "login_count"]}, ), ( lazy_gettext("Personal Info"), {"fields": ["first_name", "last_name", "email"], "expanded": True}, ), ( lazy_gettext("Audit Info"), { "fields": [ "last_login", "fail_login_count", "created_on", "created_by", "changed_on", "changed_by", ], "expanded": False, }, ), ] user_show_fieldsets = [ ( lazy_gettext("User info"), {"fields": ["username", "active", "roles", "login_count"]}, ), ( lazy_gettext("Personal Info"), {"fields": ["first_name", "last_name", "email"], "expanded": True}, ), ] search_exclude_columns = ["password"] add_columns = ["first_name", "last_name", "username", "active", "email", "roles"] edit_columns = ["first_name", "last_name", "username", "active", "email", "roles"] user_info_title = lazy_gettext("Your user information") @expose("/userinfo/") @has_access def userinfo(self): item = self.datamodel.get(g.user.id, self._base_filters) widgets = self._get_show_widget( g.user.id, item, show_fieldsets=self.user_show_fieldsets ) self.update_redirect() return self.render_template( self.show_template, title=self.user_info_title, widgets=widgets, appbuilder=self.appbuilder, ) @action("userinfoedit", lazy_gettext("Edit User"), "", "fa-edit", multiple=False) def userinfoedit(self, item): return redirect( url_for(self.appbuilder.sm.userinfoeditview.__name__ + ".this_form_get") ) class UserOIDModelView(UserModelView): """ View that add OID specifics to User view. Override to implement your own custom view. Then override useroidmodelview property on SecurityManager """ pass class UserLDAPModelView(UserModelView): """ View that add LDAP specifics to User view. Override to implement your own custom view. Then override userldapmodelview property on SecurityManager """ pass class UserOAuthModelView(UserModelView): """ View that add OAUTH specifics to User view. Override to implement your own custom view. Then override userldapmodelview property on SecurityManager """ pass class UserRemoteUserModelView(UserModelView): """ View that add REMOTE_USER specifics to User view. Override to implement your own custom view. Then override userldapmodelview property on SecurityManager """ pass class UserDBModelView(UserModelView): """ View that add DB specifics to User view. Override to implement your own custom view. Then override userdbmodelview property on SecurityManager """ add_form_extra_fields = { "password": PasswordField( lazy_gettext("Password"), description=lazy_gettext( "Please use a good password policy," " this application does not check this for you" ), validators=[validators.DataRequired()], widget=BS3PasswordFieldWidget(), ), "conf_password": PasswordField( lazy_gettext("Confirm Password"), description=lazy_gettext("Please rewrite the user's password to confirm"), validators=[ EqualTo("password", message=lazy_gettext("Passwords must match")) ], widget=BS3PasswordFieldWidget(), ), } add_columns = [ "first_name", "last_name", "username", "active", "email", "roles", "password", "conf_password", ] @expose("/show/<pk>", methods=["GET"]) @has_access def show(self, pk): actions = dict() actions["resetpasswords"] = self.actions.get("resetpasswords") item = self.datamodel.get(pk, self._base_filters) if not item: abort(404) widgets = self._get_show_widget(pk, item, actions=actions) self.update_redirect() return self.render_template( self.show_template, pk=pk, title=self.show_title, widgets=widgets, appbuilder=self.appbuilder, related_views=self._related_views, ) @expose("/userinfo/") @has_access def userinfo(self): actions = dict() actions["resetmypassword"] = self.actions.get("resetmypassword") actions["userinfoedit"] = self.actions.get("userinfoedit") item = self.datamodel.get(g.user.id, self._base_filters) widgets = self._get_show_widget( g.user.id, item, actions=actions, show_fieldsets=self.user_show_fieldsets ) self.update_redirect() return self.render_template( self.show_template, title=self.user_info_title, widgets=widgets, appbuilder=self.appbuilder, ) @action( "resetmypassword", lazy_gettext("Reset my password"), "", "fa-lock", multiple=False, ) def resetmypassword(self, item): return redirect( url_for(self.appbuilder.sm.resetmypasswordview.__name__ + ".this_form_get") ) @action( "resetpasswords", lazy_gettext("Reset Password"), "", "fa-lock", multiple=False ) def resetpasswords(self, item): return redirect( url_for( self.appbuilder.sm.resetpasswordview.__name__ + ".this_form_get", pk=item.id, ) ) def pre_update(self, item): item.changed_on = datetime.datetime.now() item.changed_by_fk = g.user.id def pre_add(self, item): item.password = generate_password_hash(item.password) class UserStatsChartView(DirectByChartView): chart_title = lazy_gettext("User Statistics") label_columns = { "username": lazy_gettext("User Name"), "login_count": lazy_gettext("Login count"), "fail_login_count": lazy_gettext("Failed login count"), } search_columns = UserModelView.search_columns definitions = [ {"label": "Login Count", "group": "username", "series": ["login_count"]}, { "label": "Failed Login Count", "group": "username", "series": ["fail_login_count"], }, ] class RoleListWidget(ListWidget): template = "appbuilder/general/widgets/roles/list.html" def __init__(self, **kwargs): kwargs["appbuilder"] = current_app.appbuilder super().__init__(**kwargs) class RoleShowWidget(ShowWidget): template = "appbuilder/general/widgets/roles/show.html" def __init__(self, **kwargs): kwargs["appbuilder"] = current_app.appbuilder super().__init__(**kwargs) class RoleModelView(ModelView): route_base = "/roles" list_title = lazy_gettext("List Roles") show_title = lazy_gettext("Show Role") add_title = lazy_gettext("Add Role") edit_title = lazy_gettext("Edit Role") list_widget = RoleListWidget show_widget = RoleShowWidget label_columns = { "name": lazy_gettext("Name"), "permissions": lazy_gettext("Permissions"), } list_columns = ["name", "permissions"] show_columns = ["name", "permissions"] edit_columns = ["name", "permissions"] add_columns = edit_columns order_columns = ["name"] @action( "copyrole", lazy_gettext("Copy Role"), lazy_gettext("Copy the selected roles?"), icon="fa-copy", single=False, ) def copy_role(self, items): self.update_redirect() for item in items: new_role = item.__class__() new_role.name = item.name new_role.permissions = item.permissions new_role.name = new_role.name + " copy" self.datamodel.add(new_role) return redirect(self.get_redirect()) class RegisterUserModelView(ModelView): route_base = "/registeruser" base_permissions = ["can_list", "can_show", "can_delete"] list_title = lazy_gettext("List of Registration Requests") show_title = lazy_gettext("Show Registration") list_columns = ["username", "registration_date", "email"] show_exclude_columns = ["password"] search_exclude_columns = ["password"] class AuthView(BaseView): route_base = "" login_template = "" invalid_login_message = lazy_gettext("Invalid login. Please try again.") title = lazy_gettext("Sign In") @expose("/login/", methods=["GET", "POST"]) def login(self): pass @expose("/logout/") def logout(self): logout_user() return redirect(self.appbuilder.get_url_for_index) class AuthDBView(AuthView): login_template = "appbuilder/general/security/login_db.html" @expose("/login/", methods=["GET", "POST"]) def login(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) form = LoginForm_db() if form.validate_on_submit(): user = self.appbuilder.sm.auth_user_db( form.username.data, form.password.data ) if not user: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) login_user(user, remember=False) return redirect(self.appbuilder.get_url_for_index) return self.render_template( self.login_template, title=self.title, form=form, appbuilder=self.appbuilder ) class AuthLDAPView(AuthView): login_template = "appbuilder/general/security/login_ldap.html" @expose("/login/", methods=["GET", "POST"]) def login(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) form = LoginForm_db() if form.validate_on_submit(): user = self.appbuilder.sm.auth_user_ldap( form.username.data, form.password.data ) if not user: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) login_user(user, remember=False) return redirect(self.appbuilder.get_url_for_index) return self.render_template( self.login_template, title=self.title, form=form, appbuilder=self.appbuilder ) """ For Future Use, API Auth, must check howto keep REST stateless """ """ @expose_api(name='auth',url='/api/auth') def auth(self): if g.user is not None and g.user.is_authenticated: http_return_code = 401 response = make_response( jsonify( { 'message': 'Login Failed already authenticated', 'severity': 'critical' } ), http_return_code ) username = str(request.args.get('username')) password = str(request.args.get('password')) user = self.appbuilder.sm.auth_user_ldap(username, password) if not user: http_return_code = 401 response = make_response( jsonify( { 'message': 'Login Failed', 'severity': 'critical' } ), http_return_code ) else: login_user(user, remember=False) http_return_code = 201 response = make_response( jsonify( { 'message': 'Login Success', 'severity': 'info' } ), http_return_code ) return response """ class AuthOIDView(AuthView): login_template = "appbuilder/general/security/login_oid.html" oid_ask_for = ["email"] oid_ask_for_optional = [] def __init__(self): super(AuthOIDView, self).__init__() @expose("/login/", methods=["GET", "POST"]) def login(self, flag=True): @self.appbuilder.sm.oid.loginhandler def login_handler(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) form = LoginForm_oid() if form.validate_on_submit(): session["remember_me"] = form.remember_me.data return self.appbuilder.sm.oid.try_login( form.openid.data, ask_for=self.oid_ask_for, ask_for_optional=self.oid_ask_for_optional, ) return self.render_template( self.login_template, title=self.title, form=form, providers=self.appbuilder.sm.openid_providers, appbuilder=self.appbuilder, ) @self.appbuilder.sm.oid.after_login def after_login(resp): if resp.email is None or resp.email == "": flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) user = self.appbuilder.sm.auth_user_oid(resp.email) if user is None: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) remember_me = False if "remember_me" in session: remember_me = session["remember_me"] session.pop("remember_me", None) login_user(user, remember=remember_me) return redirect(self.appbuilder.get_url_for_index) return login_handler(self) class AuthOAuthView(AuthView): login_template = "appbuilder/general/security/login_oauth.html" @expose("/login/") @expose("/login/<provider>") @expose("/login/<provider>/<register>") def login(self, provider=None, register=None): log.debug("Provider: {0}".format(provider)) if g.user is not None and g.user.is_authenticated: log.debug("Already authenticated {0}".format(g.user)) return redirect(self.appbuilder.get_url_for_index) if provider is None: if len(self.appbuilder.sm.oauth_providers) > 1: return self.render_template( self.login_template, providers=self.appbuilder.sm.oauth_providers, title=self.title, appbuilder=self.appbuilder, ) else: provider = self.appbuilder.sm.oauth_providers[0]["name"] log.debug("Going to call authorize for: {0}".format(provider)) state = jwt.encode( request.args.to_dict(flat=False), self.appbuilder.app.config["SECRET_KEY"], algorithm="HS256", ) try: if register: log.debug("Login to Register") session["register"] = True if provider == "twitter": return self.appbuilder.sm.oauth_remotes[provider].authorize_redirect( redirect_uri=url_for( ".oauth_authorized", provider=provider, _external=True, state=state, ) ) else: return self.appbuilder.sm.oauth_remotes[provider].authorize_redirect( redirect_uri=url_for( ".oauth_authorized", provider=provider, _external=True ), state=state.decode("ascii") if isinstance(state, bytes) else state, ) except Exception as e: log.error("Error on OAuth authorize: {0}".format(e)) flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_index) @expose("/oauth-authorized/<provider>") def oauth_authorized(self, provider): log.debug("Authorized init") resp = self.appbuilder.sm.oauth_remotes[provider].authorize_access_token() if resp is None: flash(u"You denied the request to sign in.", "warning") return redirect(self.appbuilder.get_url_for_login) log.debug("OAUTH Authorized resp: {0}".format(resp)) # Retrieves specific user info from the provider try: self.appbuilder.sm.set_oauth_session(provider, resp) userinfo = self.appbuilder.sm.oauth_user_info(provider, resp) except Exception as e: log.error("Error returning OAuth user info: {0}".format(e)) user = None else: log.debug("User info retrieved from {0}: {1}".format(provider, userinfo)) # User email is not whitelisted if provider in self.appbuilder.sm.oauth_whitelists: whitelist = self.appbuilder.sm.oauth_whitelists[provider] allow = False for e in whitelist: if re.search(e, userinfo["email"]): allow = True break if not allow: flash(u"You are not authorized.", "warning") return redirect(self.appbuilder.get_url_for_login) else: log.debug("No whitelist for OAuth provider") user = self.appbuilder.sm.auth_user_oauth(userinfo) if user is None: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) else: login_user(user) try: state = jwt.decode( request.args["state"], self.appbuilder.app.config["SECRET_KEY"], algorithms=["HS256"], ) except jwt.InvalidTokenError: raise Exception("State signature is not valid!") try: next_url = state["next"][0] or self.appbuilder.get_url_for_index except (KeyError, IndexError): next_url = self.appbuilder.get_url_for_index return redirect(next_url) class AuthRemoteUserView(AuthView): login_template = "" @expose("/login/") def login(self): username = request.environ.get("REMOTE_USER") if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) if username: user = self.appbuilder.sm.auth_user_remote_user(username) if user is None: flash(as_unicode(self.invalid_login_message), "warning") else: login_user(user) else: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_index)
import datetime import logging import re from typing import Optional from urllib.parse import urlparse from flask import ( abort, current_app, flash, g, redirect, request, Response, session, url_for, ) from flask_babel import lazy_gettext from flask_login import login_user, logout_user import jwt from werkzeug.security import generate_password_hash from wtforms import PasswordField, validators from wtforms.validators import EqualTo from .decorators import has_access from .forms import LoginForm_db, LoginForm_oid, ResetPasswordForm, UserInfoEdit from .._compat import as_unicode from ..actions import action from ..baseviews import BaseView from ..charts.views import DirectByChartView from ..fieldwidgets import BS3PasswordFieldWidget from ..utils.base import lazy_formatter_gettext from ..views import expose, ModelView, SimpleFormView from ..widgets import ListWidget, ShowWidget log = logging.getLogger(__name__) class PermissionModelView(ModelView): route_base = "/permissions" base_permissions = ["can_list"] list_title = lazy_gettext("List Base Permissions") show_title = lazy_gettext("Show Base Permission") add_title = lazy_gettext("Add Base Permission") edit_title = lazy_gettext("Edit Base Permission") label_columns = {"name": lazy_gettext("Name")} class ViewMenuModelView(ModelView): route_base = "/viewmenus" base_permissions = ["can_list"] list_title = lazy_gettext("List View Menus") show_title = lazy_gettext("Show View Menu") add_title = lazy_gettext("Add View Menu") edit_title = lazy_gettext("Edit View Menu") label_columns = {"name": lazy_gettext("Name")} class PermissionViewModelView(ModelView): route_base = "/permissionviews" base_permissions = ["can_list"] list_title = lazy_gettext("List Permissions on Views/Menus") show_title = lazy_gettext("Show Permission on Views/Menus") add_title = lazy_gettext("Add Permission on Views/Menus") edit_title = lazy_gettext("Edit Permission on Views/Menus") label_columns = { "permission": lazy_gettext("Permission"), "view_menu": lazy_gettext("View/Menu"), } list_columns = ["permission", "view_menu"] class ResetMyPasswordView(SimpleFormView): """ View for resetting own user password """ route_base = "/resetmypassword" form = ResetPasswordForm form_title = lazy_gettext("Reset Password Form") redirect_url = "/" message = lazy_gettext("Password Changed") def form_post(self, form): self.appbuilder.sm.reset_password(g.user.id, form.password.data) flash(as_unicode(self.message), "info") class ResetPasswordView(SimpleFormView): """ View for reseting all users password """ route_base = "/resetpassword" form = ResetPasswordForm form_title = lazy_gettext("Reset Password Form") redirect_url = "/" message = lazy_gettext("Password Changed") def form_post(self, form): pk = request.args.get("pk") self.appbuilder.sm.reset_password(pk, form.password.data) flash(as_unicode(self.message), "info") class UserInfoEditView(SimpleFormView): form = UserInfoEdit form_title = lazy_gettext("Edit User Information") redirect_url = "/" message = lazy_gettext("User information changed") def form_get(self, form): item = self.appbuilder.sm.get_user_by_id(g.user.id) # fills the form generic solution for key, value in form.data.items(): if key == "csrf_token": continue form_field = getattr(form, key) form_field.data = getattr(item, key) def form_post(self, form): form = self.form.refresh(request.form) item = self.appbuilder.sm.get_user_by_id(g.user.id) form.populate_obj(item) self.appbuilder.sm.update_user(item) flash(as_unicode(self.message), "info") def _roles_custom_formatter(string: str) -> str: if current_app.config.get("AUTH_ROLES_SYNC_AT_LOGIN", False): string += ( ". <div class='alert alert-warning' role='alert'>" "AUTH_ROLES_SYNC_AT_LOGIN is enabled, changes to this field will " "not persist between user logins." "</div>" ) return string class UserModelView(ModelView): route_base = "/users" list_title = lazy_gettext("List Users") show_title = lazy_gettext("Show User") add_title = lazy_gettext("Add User") edit_title = lazy_gettext("Edit User") label_columns = { "get_full_name": lazy_gettext("Full Name"), "first_name": lazy_gettext("First Name"), "last_name": lazy_gettext("Last Name"), "username": lazy_gettext("User Name"), "password": lazy_gettext("Password"), "active": lazy_gettext("Is Active?"), "email": lazy_gettext("Email"), "roles": lazy_gettext("Role"), "last_login": lazy_gettext("Last login"), "login_count": lazy_gettext("Login count"), "fail_login_count": lazy_gettext("Failed login count"), "created_on": lazy_gettext("Created on"), "created_by": lazy_gettext("Created by"), "changed_on": lazy_gettext("Changed on"), "changed_by": lazy_gettext("Changed by"), } description_columns = { "first_name": lazy_gettext("Write the user first name or names"), "last_name": lazy_gettext("Write the user last name"), "username": lazy_gettext( "Username valid for authentication on DB or LDAP, unused for OID auth" ), "password": lazy_gettext( "Please use a good password policy," " this application does not check this for you" ), "active": lazy_gettext( "It's not a good policy to remove a user, just make it inactive" ), "email": lazy_gettext("The user's email, this will also be used for OID auth"), "roles": lazy_formatter_gettext( "The user role on the application," " this will associate with a list of permissions", _roles_custom_formatter, ), "conf_password": lazy_gettext("Please rewrite the user's password to confirm"), } list_columns = ["first_name", "last_name", "username", "email", "active", "roles"] show_fieldsets = [ ( lazy_gettext("User info"), {"fields": ["username", "active", "roles", "login_count"]}, ), ( lazy_gettext("Personal Info"), {"fields": ["first_name", "last_name", "email"], "expanded": True}, ), ( lazy_gettext("Audit Info"), { "fields": [ "last_login", "fail_login_count", "created_on", "created_by", "changed_on", "changed_by", ], "expanded": False, }, ), ] user_show_fieldsets = [ ( lazy_gettext("User info"), {"fields": ["username", "active", "roles", "login_count"]}, ), ( lazy_gettext("Personal Info"), {"fields": ["first_name", "last_name", "email"], "expanded": True}, ), ] search_exclude_columns = ["password"] add_columns = ["first_name", "last_name", "username", "active", "email", "roles"] edit_columns = ["first_name", "last_name", "username", "active", "email", "roles"] user_info_title = lazy_gettext("Your user information") @expose("/userinfo/") @has_access def userinfo(self): item = self.datamodel.get(g.user.id, self._base_filters) widgets = self._get_show_widget( g.user.id, item, show_fieldsets=self.user_show_fieldsets ) self.update_redirect() return self.render_template( self.show_template, title=self.user_info_title, widgets=widgets, appbuilder=self.appbuilder, ) @action("userinfoedit", lazy_gettext("Edit User"), "", "fa-edit", multiple=False) def userinfoedit(self, item): return redirect( url_for(self.appbuilder.sm.userinfoeditview.__name__ + ".this_form_get") ) class UserOIDModelView(UserModelView): """ View that add OID specifics to User view. Override to implement your own custom view. Then override useroidmodelview property on SecurityManager """ pass class UserLDAPModelView(UserModelView): """ View that add LDAP specifics to User view. Override to implement your own custom view. Then override userldapmodelview property on SecurityManager """ pass class UserOAuthModelView(UserModelView): """ View that add OAUTH specifics to User view. Override to implement your own custom view. Then override userldapmodelview property on SecurityManager """ pass class UserRemoteUserModelView(UserModelView): """ View that add REMOTE_USER specifics to User view. Override to implement your own custom view. Then override userldapmodelview property on SecurityManager """ pass class UserDBModelView(UserModelView): """ View that add DB specifics to User view. Override to implement your own custom view. Then override userdbmodelview property on SecurityManager """ add_form_extra_fields = { "password": PasswordField( lazy_gettext("Password"), description=lazy_gettext( "Please use a good password policy," " this application does not check this for you" ), validators=[validators.DataRequired()], widget=BS3PasswordFieldWidget(), ), "conf_password": PasswordField( lazy_gettext("Confirm Password"), description=lazy_gettext("Please rewrite the user's password to confirm"), validators=[ EqualTo("password", message=lazy_gettext("Passwords must match")) ], widget=BS3PasswordFieldWidget(), ), } add_columns = [ "first_name", "last_name", "username", "active", "email", "roles", "password", "conf_password", ] @expose("/show/<pk>", methods=["GET"]) @has_access def show(self, pk): actions = dict() actions["resetpasswords"] = self.actions.get("resetpasswords") item = self.datamodel.get(pk, self._base_filters) if not item: abort(404) widgets = self._get_show_widget(pk, item, actions=actions) self.update_redirect() return self.render_template( self.show_template, pk=pk, title=self.show_title, widgets=widgets, appbuilder=self.appbuilder, related_views=self._related_views, ) @expose("/userinfo/") @has_access def userinfo(self): actions = dict() actions["resetmypassword"] = self.actions.get("resetmypassword") actions["userinfoedit"] = self.actions.get("userinfoedit") item = self.datamodel.get(g.user.id, self._base_filters) widgets = self._get_show_widget( g.user.id, item, actions=actions, show_fieldsets=self.user_show_fieldsets ) self.update_redirect() return self.render_template( self.show_template, title=self.user_info_title, widgets=widgets, appbuilder=self.appbuilder, ) @action( "resetmypassword", lazy_gettext("Reset my password"), "", "fa-lock", multiple=False, ) def resetmypassword(self, item): return redirect( url_for(self.appbuilder.sm.resetmypasswordview.__name__ + ".this_form_get") ) @action( "resetpasswords", lazy_gettext("Reset Password"), "", "fa-lock", multiple=False ) def resetpasswords(self, item): return redirect( url_for( self.appbuilder.sm.resetpasswordview.__name__ + ".this_form_get", pk=item.id, ) ) def pre_update(self, item): item.changed_on = datetime.datetime.now() item.changed_by_fk = g.user.id def pre_add(self, item): item.password = generate_password_hash(item.password) class UserStatsChartView(DirectByChartView): chart_title = lazy_gettext("User Statistics") label_columns = { "username": lazy_gettext("User Name"), "login_count": lazy_gettext("Login count"), "fail_login_count": lazy_gettext("Failed login count"), } search_columns = UserModelView.search_columns definitions = [ {"label": "Login Count", "group": "username", "series": ["login_count"]}, { "label": "Failed Login Count", "group": "username", "series": ["fail_login_count"], }, ] class RoleListWidget(ListWidget): template = "appbuilder/general/widgets/roles/list.html" def __init__(self, **kwargs): kwargs["appbuilder"] = current_app.appbuilder super().__init__(**kwargs) class RoleShowWidget(ShowWidget): template = "appbuilder/general/widgets/roles/show.html" def __init__(self, **kwargs): kwargs["appbuilder"] = current_app.appbuilder super().__init__(**kwargs) class RoleModelView(ModelView): route_base = "/roles" list_title = lazy_gettext("List Roles") show_title = lazy_gettext("Show Role") add_title = lazy_gettext("Add Role") edit_title = lazy_gettext("Edit Role") list_widget = RoleListWidget show_widget = RoleShowWidget label_columns = { "name": lazy_gettext("Name"), "permissions": lazy_gettext("Permissions"), } list_columns = ["name", "permissions"] show_columns = ["name", "permissions"] edit_columns = ["name", "permissions"] add_columns = edit_columns order_columns = ["name"] @action( "copyrole", lazy_gettext("Copy Role"), lazy_gettext("Copy the selected roles?"), icon="fa-copy", single=False, ) def copy_role(self, items): self.update_redirect() for item in items: new_role = item.__class__() new_role.name = item.name new_role.permissions = item.permissions new_role.name = new_role.name + " copy" self.datamodel.add(new_role) return redirect(self.get_redirect()) class RegisterUserModelView(ModelView): route_base = "/registeruser" base_permissions = ["can_list", "can_show", "can_delete"] list_title = lazy_gettext("List of Registration Requests") show_title = lazy_gettext("Show Registration") list_columns = ["username", "registration_date", "email"] show_exclude_columns = ["password"] search_exclude_columns = ["password"] class AuthView(BaseView): route_base = "" login_template = "" invalid_login_message = lazy_gettext("Invalid login. Please try again.") title = lazy_gettext("Sign In") @expose("/login/", methods=["GET", "POST"]) def login(self): pass @expose("/logout/") def logout(self): logout_user() return redirect(self.appbuilder.get_url_for_index) class AuthDBView(AuthView): login_template = "appbuilder/general/security/login_db.html" @expose("/login/", methods=["GET", "POST"]) def login(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) form = LoginForm_db() if form.validate_on_submit(): user = self.appbuilder.sm.auth_user_db( form.username.data, form.password.data ) if not user: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) login_user(user, remember=False) return redirect(self.appbuilder.get_url_for_index) return self.render_template( self.login_template, title=self.title, form=form, appbuilder=self.appbuilder ) class AuthLDAPView(AuthView): login_template = "appbuilder/general/security/login_ldap.html" @expose("/login/", methods=["GET", "POST"]) def login(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) form = LoginForm_db() if form.validate_on_submit(): user = self.appbuilder.sm.auth_user_ldap( form.username.data, form.password.data ) if not user: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) login_user(user, remember=False) return redirect(self.appbuilder.get_url_for_index) return self.render_template( self.login_template, title=self.title, form=form, appbuilder=self.appbuilder ) class AuthOIDView(AuthView): login_template = "appbuilder/general/security/login_oid.html" oid_ask_for = ["email"] oid_ask_for_optional = [] def __init__(self): super(AuthOIDView, self).__init__() @expose("/login/", methods=["GET", "POST"]) def login(self, flag=True): @self.appbuilder.sm.oid.loginhandler def login_handler(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) form = LoginForm_oid() if form.validate_on_submit(): session["remember_me"] = form.remember_me.data return self.appbuilder.sm.oid.try_login( form.openid.data, ask_for=self.oid_ask_for, ask_for_optional=self.oid_ask_for_optional, ) return self.render_template( self.login_template, title=self.title, form=form, providers=self.appbuilder.sm.openid_providers, appbuilder=self.appbuilder, ) @self.appbuilder.sm.oid.after_login def after_login(resp): if resp.email is None or resp.email == "": flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) user = self.appbuilder.sm.auth_user_oid(resp.email) if user is None: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) remember_me = False if "remember_me" in session: remember_me = session["remember_me"] session.pop("remember_me", None) login_user(user, remember=remember_me) return redirect(self.appbuilder.get_url_for_index) return login_handler(self) class AuthOAuthView(AuthView): login_template = "appbuilder/general/security/login_oauth.html" @expose("/login/") @expose("/login/<provider>") @expose("/login/<provider>/<register>") def login( self, provider: Optional[str] = None, register: Optional[str] = None ) -> Response: log.debug("Provider: {0}".format(provider)) if g.user is not None and g.user.is_authenticated: log.debug("Already authenticated {0}".format(g.user)) return redirect(self.appbuilder.get_url_for_index) if provider is None: if len(self.appbuilder.sm.oauth_providers) > 1: return self.render_template( self.login_template, providers=self.appbuilder.sm.oauth_providers, title=self.title, appbuilder=self.appbuilder, ) else: provider = self.appbuilder.sm.oauth_providers[0]["name"] log.debug("Going to call authorize for: {0}".format(provider)) state = jwt.encode( request.args.to_dict(flat=False), self.appbuilder.app.config["SECRET_KEY"], algorithm="HS256", ) try: if register: log.debug("Login to Register") session["register"] = True if provider == "twitter": return self.appbuilder.sm.oauth_remotes[provider].authorize_redirect( redirect_uri=url_for( ".oauth_authorized", provider=provider, _external=True, state=state, ) ) else: return self.appbuilder.sm.oauth_remotes[provider].authorize_redirect( redirect_uri=url_for( ".oauth_authorized", provider=provider, _external=True ), state=state.decode("ascii") if isinstance(state, bytes) else state, ) except Exception as e: log.error("Error on OAuth authorize: {0}".format(e)) flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_index) @expose("/oauth-authorized/<provider>") def oauth_authorized(self, provider: str) -> Response: log.debug("Authorized init") if provider not in self.appbuilder.sm.oauth_remotes: flash(u"Provider not supported.", "warning") log.warning("OAuth authorized got an unknown provider %s", provider) return redirect(self.appbuilder.get_url_for_login) resp = self.appbuilder.sm.oauth_remotes[provider].authorize_access_token() if resp is None: flash(u"You denied the request to sign in.", "warning") return redirect(self.appbuilder.get_url_for_login) log.debug("OAUTH Authorized resp: {0}".format(resp)) # Retrieves specific user info from the provider try: self.appbuilder.sm.set_oauth_session(provider, resp) userinfo = self.appbuilder.sm.oauth_user_info(provider, resp) except Exception as e: log.error("Error returning OAuth user info: {0}".format(e)) user = None else: log.debug("User info retrieved from {0}: {1}".format(provider, userinfo)) # User email is not whitelisted if provider in self.appbuilder.sm.oauth_whitelists: whitelist = self.appbuilder.sm.oauth_whitelists[provider] allow = False for e in whitelist: if re.search(e, userinfo["email"]): allow = True break if not allow: flash(u"You are not authorized.", "warning") return redirect(self.appbuilder.get_url_for_login) else: log.debug("No whitelist for OAuth provider") user = self.appbuilder.sm.auth_user_oauth(userinfo) if user is None: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) else: login_user(user) try: state = jwt.decode( request.args["state"], self.appbuilder.app.config["SECRET_KEY"], algorithms=["HS256"], ) except jwt.InvalidTokenError: raise Exception("State signature is not valid!") next_url = self.appbuilder.get_url_for_index # Check if there is a next url on state if "next" in state and len(state["next"]) > 0: parsed_uri = urlparse(state["next"][0]) if parsed_uri.netloc != request.host: log.warning("Got an invalid next URL: %s", parsed_uri.netloc) else: next_url = state["next"][0] return redirect(next_url) class AuthRemoteUserView(AuthView): login_template = "" @expose("/login/") def login(self): username = request.environ.get("REMOTE_USER") if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) if username: user = self.appbuilder.sm.auth_user_remote_user(username) if user is None: flash(as_unicode(self.invalid_login_message), "warning") else: login_user(user) else: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_index)
open_redirect
{ "code": [ "from flask import abort, current_app, flash, g, redirect, request, session, url_for", " \"\"\"", " For Future Use, API Auth, must check howto keep REST stateless", " \"\"\"", " \"\"\"", " @expose_api(name='auth',url='/api/auth')", " def auth(self):", " if g.user is not None and g.user.is_authenticated:", " http_return_code = 401", " response = make_response(", " jsonify(", " {", " 'message': 'Login Failed already authenticated',", " 'severity': 'critical'", " }", " ),", " http_return_code", " )", " username = str(request.args.get('username'))", " password = str(request.args.get('password'))", " user = self.appbuilder.sm.auth_user_ldap(username, password)", " if not user:", " http_return_code = 401", " response = make_response(", " jsonify(", " {", " 'message': 'Login Failed',", " 'severity': 'critical'", " }", " ),", " http_return_code", " )", " else:", " login_user(user, remember=False)", " http_return_code = 201", " response = make_response(", " jsonify(", " {", " 'message': 'Login Success',", " 'severity': 'info'", " }", " ),", " http_return_code", " )", " return response", " \"\"\"", " def login(self, provider=None, register=None):", " def oauth_authorized(self, provider):", " try:", " next_url = state[\"next\"][0] or self.appbuilder.get_url_for_index", " except (KeyError, IndexError):", " next_url = self.appbuilder.get_url_for_index" ], "line_no": [ 5, 540, 541, 542, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 644, 693, 738, 739, 740, 741 ] }
{ "code": [ "from urllib.parse import urlparse", "from flask import (", " abort,", " current_app,", " flash,", " g,", " request,", " Response,", " session,", " url_for,", ")", " def login(", " self, provider: Optional[str] = None, register: Optional[str] = None", " ) -> Response:", " if provider not in self.appbuilder.sm.oauth_remotes:", " flash(u\"Provider not supported.\", \"warning\")", " log.warning(\"OAuth authorized got an unknown provider %s\", provider)", " return redirect(self.appbuilder.get_url_for_login)", " if \"next\" in state and len(state[\"next\"]) > 0:", " parsed_uri = urlparse(state[\"next\"][0])", " if parsed_uri.netloc != request.host:", " log.warning(\"Got an invalid next URL: %s\", parsed_uri.netloc)", " else:", " next_url = state[\"next\"][0]" ], "line_no": [ 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 609, 610, 611, 662, 663, 664, 665, 711, 712, 713, 714, 715, 716 ] }
import datetime import .logging import re from flask import abort, current_app, flash, g, redirect, request, VAR_53, url_for from flask_babel import lazy_gettext from flask_login import .login_user, logout_user import jwt from werkzeug.security import generate_password_hash from wtforms import PasswordField, validators from wtforms.validators import EqualTo from .decorators import has_access from .forms import LoginForm_db, LoginForm_oid, ResetPasswordForm, UserInfoEdit from .._compat import as_unicode from ..actions import action from ..baseviews import BaseView from ..charts.views import DirectByChartView from ..fieldwidgets import BS3PasswordFieldWidget from ..utils.base import lazy_formatter_gettext from ..views import expose, ModelView, SimpleFormView from ..widgets import ListWidget, ShowWidget VAR_0 = logging.getLogger(__name__) class CLASS_0(ModelView): VAR_2 = "/permissions" VAR_3 = ["can_list"] VAR_4 = lazy_gettext("List Base Permissions") VAR_5 = lazy_gettext("Show Base Permission") VAR_6 = lazy_gettext("Add Base Permission") VAR_7 = lazy_gettext("Edit Base Permission") VAR_8 = {"name": lazy_gettext("Name")} class CLASS_1(ModelView): VAR_2 = "/viewmenus" VAR_3 = ["can_list"] VAR_4 = lazy_gettext("List View Menus") VAR_5 = lazy_gettext("Show View Menu") VAR_6 = lazy_gettext("Add View Menu") VAR_7 = lazy_gettext("Edit View Menu") VAR_8 = {"name": lazy_gettext("Name")} class CLASS_2(ModelView): VAR_2 = "/permissionviews" VAR_3 = ["can_list"] VAR_4 = lazy_gettext("List Permissions on Views/Menus") VAR_5 = lazy_gettext("Show Permission on Views/Menus") VAR_6 = lazy_gettext("Add Permission on Views/Menus") VAR_7 = lazy_gettext("Edit Permission on Views/Menus") VAR_8 = { "permission": lazy_gettext("Permission"), "view_menu": lazy_gettext("View/Menu"), } VAR_9 = ["permission", "view_menu"] class CLASS_3(SimpleFormView): VAR_2 = "/resetmypassword" VAR_10 = ResetPasswordForm VAR_11 = lazy_gettext("Reset Password Form") VAR_12 = "/" VAR_13 = lazy_gettext("Password Changed") def FUNC_1(self, VAR_10): self.appbuilder.sm.reset_password(g.user.id, VAR_10.password.data) flash(as_unicode(self.message), "info") class CLASS_4(SimpleFormView): VAR_2 = "/resetpassword" VAR_10 = ResetPasswordForm VAR_11 = lazy_gettext("Reset Password Form") VAR_12 = "/" VAR_13 = lazy_gettext("Password Changed") def FUNC_1(self, VAR_10): VAR_23 = request.args.get("pk") self.appbuilder.sm.reset_password(VAR_23, VAR_10.password.data) flash(as_unicode(self.message), "info") class CLASS_5(SimpleFormView): VAR_10 = UserInfoEdit VAR_11 = lazy_gettext("Edit User Information") VAR_12 = "/" VAR_13 = lazy_gettext("User information changed") def FUNC_2(self, VAR_10): VAR_21 = self.appbuilder.sm.get_user_by_id(g.user.id) for key, value in VAR_10.data.items(): if key == "csrf_token": continue VAR_48 = getattr(VAR_10, key) VAR_48.data = getattr(VAR_21, key) def FUNC_1(self, VAR_10): VAR_10 = self.form.refresh(request.form) VAR_21 = self.appbuilder.sm.get_user_by_id(g.user.id) VAR_10.populate_obj(VAR_21) self.appbuilder.sm.update_user(VAR_21) flash(as_unicode(self.message), "info") def FUNC_0(VAR_1: str) -> str: if current_app.config.get("AUTH_ROLES_SYNC_AT_LOGIN", False): VAR_1 += ( ". <div class='alert alert-warning' role='alert'>" "AUTH_ROLES_SYNC_AT_LOGIN is enabled, changes to this field will " "not persist between VAR_50 logins." "</div>" ) return VAR_1 class CLASS_6(ModelView): VAR_2 = "/users" VAR_4 = lazy_gettext("List Users") VAR_5 = lazy_gettext("Show User") VAR_6 = lazy_gettext("Add User") VAR_7 = lazy_gettext("Edit User") VAR_8 = { "get_full_name": lazy_gettext("Full Name"), "first_name": lazy_gettext("First Name"), "last_name": lazy_gettext("Last Name"), "username": lazy_gettext("User Name"), "password": lazy_gettext("Password"), "active": lazy_gettext("Is Active?"), "email": lazy_gettext("Email"), "roles": lazy_gettext("Role"), "last_login": lazy_gettext("Last login"), "login_count": lazy_gettext("Login count"), "fail_login_count": lazy_gettext("Failed FUNC_11 count"), "created_on": lazy_gettext("Created on"), "created_by": lazy_gettext("Created by"), "changed_on": lazy_gettext("Changed on"), "changed_by": lazy_gettext("Changed by"), } VAR_14 = { "first_name": lazy_gettext("Write the VAR_50 first name or names"), "last_name": lazy_gettext("Write the VAR_50 last name"), "username": lazy_gettext( "Username valid for authentication on DB or LDAP, unused for OID auth" ), "password": lazy_gettext( "Please use a good password policy," " this application does not check this for you" ), "active": lazy_gettext( "It's not a good policy to remove a VAR_50, just make it inactive" ), "email": lazy_gettext("The user's email, this will also be used for OID auth"), "roles": lazy_formatter_gettext( "The VAR_50 role on the application," " this will associate with a list of permissions", FUNC_0, ), "conf_password": lazy_gettext("Please rewrite the user's password to confirm"), } VAR_9 = ["first_name", "last_name", "username", "email", "active", "roles"] VAR_15 = [ ( lazy_gettext("User info"), {"fields": ["username", "active", "roles", "login_count"]}, ), ( lazy_gettext("Personal Info"), {"fields": ["first_name", "last_name", "email"], "expanded": True}, ), ( lazy_gettext("Audit Info"), { "fields": [ "last_login", "fail_login_count", "created_on", "created_by", "changed_on", "changed_by", ], "expanded": False, }, ), ] VAR_16 = [ ( lazy_gettext("User info"), {"fields": ["username", "active", "roles", "login_count"]}, ), ( lazy_gettext("Personal Info"), {"fields": ["first_name", "last_name", "email"], "expanded": True}, ), ] VAR_17 = ["password"] VAR_18 = ["first_name", "last_name", "username", "active", "email", "roles"] VAR_19 = ["first_name", "last_name", "username", "active", "email", "roles"] VAR_20 = lazy_gettext("Your VAR_50 information") @expose("/VAR_52/") @has_access def VAR_52(self): VAR_21 = self.datamodel.get(g.user.id, self._base_filters) VAR_43 = self._get_show_widget( g.user.id, VAR_21, VAR_15=self.user_show_fieldsets ) self.update_redirect() return self.render_template( self.show_template, VAR_37=self.user_info_title, VAR_43=widgets, appbuilder=self.appbuilder, ) @action("userinfoedit", lazy_gettext("Edit User"), "", "fa-edit", multiple=False) def FUNC_4(self, VAR_21): return redirect( url_for(self.appbuilder.sm.userinfoeditview.__name__ + ".this_form_get") ) class CLASS_7(CLASS_6): pass class CLASS_8(CLASS_6): pass class CLASS_9(CLASS_6): pass class CLASS_10(CLASS_6): pass class CLASS_11(CLASS_6): VAR_22 = { "password": PasswordField( lazy_gettext("Password"), description=lazy_gettext( "Please use a good password policy," " this application does not check this for you" ), validators=[validators.DataRequired()], widget=BS3PasswordFieldWidget(), ), "conf_password": PasswordField( lazy_gettext("Confirm Password"), description=lazy_gettext("Please rewrite the user's password to confirm"), validators=[ EqualTo("password", VAR_13=lazy_gettext("Passwords must match")) ], widget=BS3PasswordFieldWidget(), ), } VAR_18 = [ "first_name", "last_name", "username", "active", "email", "roles", "password", "conf_password", ] @expose("/FUNC_5/<VAR_23>", methods=["GET"]) @has_access def FUNC_5(self, VAR_23): VAR_44 = dict() VAR_44["resetpasswords"] = self.actions.get("resetpasswords") VAR_21 = self.datamodel.get(VAR_23, self._base_filters) if not VAR_21: abort(404) VAR_43 = self._get_show_widget(VAR_23, VAR_21, VAR_44=actions) self.update_redirect() return self.render_template( self.show_template, VAR_23=pk, VAR_37=self.show_title, VAR_43=widgets, appbuilder=self.appbuilder, related_views=self._related_views, ) @expose("/VAR_52/") @has_access def VAR_52(self): VAR_44 = dict() VAR_44["resetmypassword"] = self.actions.get("resetmypassword") VAR_44["userinfoedit"] = self.actions.get("userinfoedit") VAR_21 = self.datamodel.get(g.user.id, self._base_filters) VAR_43 = self._get_show_widget( g.user.id, VAR_21, VAR_44=actions, VAR_15=self.user_show_fieldsets ) self.update_redirect() return self.render_template( self.show_template, VAR_37=self.user_info_title, VAR_43=widgets, appbuilder=self.appbuilder, ) @action( "resetmypassword", lazy_gettext("Reset my password"), "", "fa-lock", multiple=False, ) def FUNC_6(self, VAR_21): return redirect( url_for(self.appbuilder.sm.resetmypasswordview.__name__ + ".this_form_get") ) @action( "resetpasswords", lazy_gettext("Reset Password"), "", "fa-lock", multiple=False ) def FUNC_7(self, VAR_21): return redirect( url_for( self.appbuilder.sm.resetpasswordview.__name__ + ".this_form_get", VAR_23=VAR_21.id, ) ) def FUNC_8(self, VAR_21): item.changed_on = datetime.datetime.now() VAR_21.changed_by_fk = g.user.id def FUNC_9(self, VAR_21): item.password = generate_password_hash(VAR_21.password) class CLASS_12(DirectByChartView): VAR_24 = lazy_gettext("User Statistics") VAR_8 = { "username": lazy_gettext("User Name"), "login_count": lazy_gettext("Login count"), "fail_login_count": lazy_gettext("Failed FUNC_11 count"), } VAR_25 = CLASS_6.search_columns VAR_26 = [ {"label": "Login Count", "group": "username", "series": ["login_count"]}, { "label": "Failed Login Count", "group": "username", "series": ["fail_login_count"], }, ] class CLASS_13(ListWidget): VAR_27 = "appbuilder/general/VAR_43/roles/list.html" def __init__(self, **VAR_28): kwargs["appbuilder"] = current_app.appbuilder super().__init__(**VAR_28) class CLASS_14(ShowWidget): VAR_27 = "appbuilder/general/VAR_43/roles/FUNC_5.html" def __init__(self, **VAR_28): kwargs["appbuilder"] = current_app.appbuilder super().__init__(**VAR_28) class CLASS_15(ModelView): VAR_2 = "/roles" VAR_4 = lazy_gettext("List Roles") VAR_5 = lazy_gettext("Show Role") VAR_6 = lazy_gettext("Add Role") VAR_7 = lazy_gettext("Edit Role") VAR_29 = CLASS_13 VAR_30 = CLASS_14 VAR_8 = { "name": lazy_gettext("Name"), "permissions": lazy_gettext("Permissions"), } VAR_9 = ["name", "permissions"] VAR_31 = ["name", "permissions"] VAR_19 = ["name", "permissions"] VAR_18 = VAR_19 VAR_32 = ["name"] @action( "copyrole", lazy_gettext("Copy Role"), lazy_gettext("Copy the selected roles?"), icon="fa-copy", single=False, ) def FUNC_10(self, VAR_33): self.update_redirect() for VAR_21 in VAR_33: VAR_49 = VAR_21.__class__() VAR_49.name = VAR_21.name VAR_49.permissions = VAR_21.permissions VAR_49.name = VAR_49.name + " copy" self.datamodel.add(VAR_49) return redirect(self.get_redirect()) class CLASS_16(ModelView): VAR_2 = "/registeruser" VAR_3 = ["can_list", "can_show", "can_delete"] VAR_4 = lazy_gettext("List of Registration Requests") VAR_5 = lazy_gettext("Show Registration") VAR_9 = ["username", "registration_date", "email"] VAR_34 = ["password"] VAR_17 = ["password"] class CLASS_17(BaseView): VAR_2 = "" VAR_35 = "" VAR_36 = lazy_gettext("Invalid FUNC_11. Please try again.") VAR_37 = lazy_gettext("Sign In") @expose("/FUNC_11/", methods=["GET", "POST"]) def FUNC_11(self): pass @expose("/FUNC_12/") def FUNC_12(self): logout_user() return redirect(self.appbuilder.get_url_for_index) class CLASS_18(CLASS_17): VAR_35 = "appbuilder/general/security/login_db.html" @expose("/FUNC_11/", methods=["GET", "POST"]) def FUNC_11(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) VAR_10 = LoginForm_db() if VAR_10.validate_on_submit(): VAR_50 = self.appbuilder.sm.auth_user_db( VAR_10.username.data, VAR_10.password.data ) if not VAR_50: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) login_user(VAR_50, remember=False) return redirect(self.appbuilder.get_url_for_index) return self.render_template( self.login_template, VAR_37=self.title, VAR_10=form, appbuilder=self.appbuilder ) class CLASS_19(CLASS_17): VAR_35 = "appbuilder/general/security/login_ldap.html" @expose("/FUNC_11/", methods=["GET", "POST"]) def FUNC_11(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) VAR_10 = LoginForm_db() if VAR_10.validate_on_submit(): VAR_50 = self.appbuilder.sm.auth_user_ldap( VAR_10.username.data, VAR_10.password.data ) if not VAR_50: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) login_user(VAR_50, remember=False) return redirect(self.appbuilder.get_url_for_index) return self.render_template( self.login_template, VAR_37=self.title, VAR_10=form, appbuilder=self.appbuilder ) """ For Future Use, API Auth, must check howto keep REST stateless """ """ @expose_api(name='auth',url='/api/auth') def auth(self): if g.user is not None and g.user.is_authenticated: http_return_code = 401 response = make_response( jsonify( { 'message': 'Login Failed already authenticated', 'severity': 'critical' } ), http_return_code ) VAR_47 = str(request.args.get('username')) password = str(request.args.get('password')) VAR_50 = self.appbuilder.sm.auth_user_ldap(VAR_47, password) if not VAR_50: http_return_code = 401 response = make_response( jsonify( { 'message': 'Login Failed', 'severity': 'critical' } ), http_return_code ) else: login_user(VAR_50, remember=False) http_return_code = 201 response = make_response( jsonify( { 'message': 'Login Success', 'severity': 'info' } ), http_return_code ) return response """ class CLASS_20(CLASS_17): VAR_35 = "appbuilder/general/security/login_oid.html" VAR_38 = ["email"] VAR_39 = [] def __init__(self): super(CLASS_20, self).__init__() @expose("/FUNC_11/", methods=["GET", "POST"]) def FUNC_11(self, VAR_40=True): @self.appbuilder.sm.oid.loginhandler def FUNC_14(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) VAR_10 = LoginForm_oid() if VAR_10.validate_on_submit(): VAR_53["remember_me"] = VAR_10.remember_me.data return self.appbuilder.sm.oid.try_login( VAR_10.openid.data, ask_for=self.oid_ask_for, ask_for_optional=self.oid_ask_for_optional, ) return self.render_template( self.login_template, VAR_37=self.title, VAR_10=form, providers=self.appbuilder.sm.openid_providers, appbuilder=self.appbuilder, ) @self.appbuilder.sm.oid.after_login def FUNC_15(VAR_45): if VAR_45.email is None or VAR_45.email == "": flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) VAR_50 = self.appbuilder.sm.auth_user_oid(VAR_45.email) if VAR_50 is None: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) VAR_51 = False if "remember_me" in VAR_53: VAR_51 = VAR_53["remember_me"] VAR_53.pop("remember_me", None) login_user(VAR_50, remember=VAR_51) return redirect(self.appbuilder.get_url_for_index) return FUNC_14(self) class CLASS_21(CLASS_17): VAR_35 = "appbuilder/general/security/login_oauth.html" @expose("/FUNC_11/") @expose("/FUNC_11/<VAR_41>") @expose("/FUNC_11/<VAR_41>/<VAR_42>") def FUNC_11(self, VAR_41=None, VAR_42=None): VAR_0.debug("Provider: {0}".format(VAR_41)) if g.user is not None and g.user.is_authenticated: VAR_0.debug("Already authenticated {0}".format(g.user)) return redirect(self.appbuilder.get_url_for_index) if VAR_41 is None: if len(self.appbuilder.sm.oauth_providers) > 1: return self.render_template( self.login_template, providers=self.appbuilder.sm.oauth_providers, VAR_37=self.title, appbuilder=self.appbuilder, ) else: VAR_41 = self.appbuilder.sm.oauth_providers[0]["name"] VAR_0.debug("Going to call authorize for: {0}".format(VAR_41)) VAR_46 = jwt.encode( request.args.to_dict(flat=False), self.appbuilder.app.config["SECRET_KEY"], algorithm="HS256", ) try: if VAR_42: VAR_0.debug("Login to Register") VAR_53["register"] = True if VAR_41 == "twitter": return self.appbuilder.sm.oauth_remotes[VAR_41].authorize_redirect( redirect_uri=url_for( ".oauth_authorized", VAR_41=provider, _external=True, VAR_46=state, ) ) else: return self.appbuilder.sm.oauth_remotes[VAR_41].authorize_redirect( redirect_uri=url_for( ".oauth_authorized", VAR_41=provider, _external=True ), VAR_46=state.decode("ascii") if isinstance(VAR_46, bytes) else VAR_46, ) except Exception as e: VAR_0.error("Error on OAuth authorize: {0}".format(e)) flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_index) @expose("/oauth-authorized/<VAR_41>") def FUNC_13(self, VAR_41): VAR_0.debug("Authorized init") VAR_45 = self.appbuilder.sm.oauth_remotes[VAR_41].authorize_access_token() if VAR_45 is None: flash(u"You denied the request to sign in.", "warning") return redirect(self.appbuilder.get_url_for_login) VAR_0.debug("OAUTH Authorized VAR_45: {0}".format(VAR_45)) try: self.appbuilder.sm.set_oauth_session(VAR_41, VAR_45) VAR_52 = self.appbuilder.sm.oauth_user_info(VAR_41, VAR_45) except Exception as e: VAR_0.error("Error returning OAuth VAR_50 info: {0}".format(e)) VAR_50 = None else: VAR_0.debug("User info retrieved from {0}: {1}".format(VAR_41, VAR_52)) if VAR_41 in self.appbuilder.sm.oauth_whitelists: VAR_54 = self.appbuilder.sm.oauth_whitelists[VAR_41] VAR_55 = False for e in VAR_54: if re.search(e, VAR_52["email"]): VAR_55 = True break if not VAR_55: flash(u"You are not authorized.", "warning") return redirect(self.appbuilder.get_url_for_login) else: VAR_0.debug("No VAR_54 for OAuth provider") VAR_50 = self.appbuilder.sm.auth_user_oauth(VAR_52) if VAR_50 is None: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) else: login_user(VAR_50) try: VAR_46 = jwt.decode( request.args["state"], self.appbuilder.app.config["SECRET_KEY"], algorithms=["HS256"], ) except jwt.InvalidTokenError: raise Exception("State signature is not valid!") try: VAR_56 = VAR_46["next"][0] or self.appbuilder.get_url_for_index except (KeyError, IndexError): VAR_56 = self.appbuilder.get_url_for_index return redirect(VAR_56) class CLASS_22(CLASS_17): VAR_35 = "" @expose("/FUNC_11/") def FUNC_11(self): VAR_47 = request.environ.get("REMOTE_USER") if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) if VAR_47: VAR_50 = self.appbuilder.sm.auth_user_remote_user(VAR_47) if VAR_50 is None: flash(as_unicode(self.invalid_login_message), "warning") else: login_user(VAR_50) else: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_index)
import datetime import .logging import re from typing import Optional from urllib.parse import urlparse from flask import ( abort, current_app, flash, g, redirect, request, Response, VAR_54, url_for, ) from flask_babel import lazy_gettext from flask_login import .login_user, logout_user import jwt from werkzeug.security import generate_password_hash from wtforms import PasswordField, validators from wtforms.validators import EqualTo from .decorators import has_access from .forms import LoginForm_db, LoginForm_oid, ResetPasswordForm, UserInfoEdit from .._compat import as_unicode from ..actions import action from ..baseviews import BaseView from ..charts.views import DirectByChartView from ..fieldwidgets import BS3PasswordFieldWidget from ..utils.base import lazy_formatter_gettext from ..views import expose, ModelView, SimpleFormView from ..widgets import ListWidget, ShowWidget VAR_0 = logging.getLogger(__name__) class CLASS_0(ModelView): VAR_2 = "/permissions" VAR_3 = ["can_list"] VAR_4 = lazy_gettext("List Base Permissions") VAR_5 = lazy_gettext("Show Base Permission") VAR_6 = lazy_gettext("Add Base Permission") VAR_7 = lazy_gettext("Edit Base Permission") VAR_8 = {"name": lazy_gettext("Name")} class CLASS_1(ModelView): VAR_2 = "/viewmenus" VAR_3 = ["can_list"] VAR_4 = lazy_gettext("List View Menus") VAR_5 = lazy_gettext("Show View Menu") VAR_6 = lazy_gettext("Add View Menu") VAR_7 = lazy_gettext("Edit View Menu") VAR_8 = {"name": lazy_gettext("Name")} class CLASS_2(ModelView): VAR_2 = "/permissionviews" VAR_3 = ["can_list"] VAR_4 = lazy_gettext("List Permissions on Views/Menus") VAR_5 = lazy_gettext("Show Permission on Views/Menus") VAR_6 = lazy_gettext("Add Permission on Views/Menus") VAR_7 = lazy_gettext("Edit Permission on Views/Menus") VAR_8 = { "permission": lazy_gettext("Permission"), "view_menu": lazy_gettext("View/Menu"), } VAR_9 = ["permission", "view_menu"] class CLASS_3(SimpleFormView): VAR_2 = "/resetmypassword" VAR_10 = ResetPasswordForm VAR_11 = lazy_gettext("Reset Password Form") VAR_12 = "/" VAR_13 = lazy_gettext("Password Changed") def FUNC_1(self, VAR_10): self.appbuilder.sm.reset_password(g.user.id, VAR_10.password.data) flash(as_unicode(self.message), "info") class CLASS_4(SimpleFormView): VAR_2 = "/resetpassword" VAR_10 = ResetPasswordForm VAR_11 = lazy_gettext("Reset Password Form") VAR_12 = "/" VAR_13 = lazy_gettext("Password Changed") def FUNC_1(self, VAR_10): VAR_23 = request.args.get("pk") self.appbuilder.sm.reset_password(VAR_23, VAR_10.password.data) flash(as_unicode(self.message), "info") class CLASS_5(SimpleFormView): VAR_10 = UserInfoEdit VAR_11 = lazy_gettext("Edit User Information") VAR_12 = "/" VAR_13 = lazy_gettext("User information changed") def FUNC_2(self, VAR_10): VAR_21 = self.appbuilder.sm.get_user_by_id(g.user.id) for key, value in VAR_10.data.items(): if key == "csrf_token": continue VAR_48 = getattr(VAR_10, key) VAR_48.data = getattr(VAR_21, key) def FUNC_1(self, VAR_10): VAR_10 = self.form.refresh(request.form) VAR_21 = self.appbuilder.sm.get_user_by_id(g.user.id) VAR_10.populate_obj(VAR_21) self.appbuilder.sm.update_user(VAR_21) flash(as_unicode(self.message), "info") def FUNC_0(VAR_1: str) -> str: if current_app.config.get("AUTH_ROLES_SYNC_AT_LOGIN", False): VAR_1 += ( ". <div class='alert alert-warning' role='alert'>" "AUTH_ROLES_SYNC_AT_LOGIN is enabled, changes to this field will " "not persist between VAR_50 logins." "</div>" ) return VAR_1 class CLASS_6(ModelView): VAR_2 = "/users" VAR_4 = lazy_gettext("List Users") VAR_5 = lazy_gettext("Show User") VAR_6 = lazy_gettext("Add User") VAR_7 = lazy_gettext("Edit User") VAR_8 = { "get_full_name": lazy_gettext("Full Name"), "first_name": lazy_gettext("First Name"), "last_name": lazy_gettext("Last Name"), "username": lazy_gettext("User Name"), "password": lazy_gettext("Password"), "active": lazy_gettext("Is Active?"), "email": lazy_gettext("Email"), "roles": lazy_gettext("Role"), "last_login": lazy_gettext("Last login"), "login_count": lazy_gettext("Login count"), "fail_login_count": lazy_gettext("Failed FUNC_11 count"), "created_on": lazy_gettext("Created on"), "created_by": lazy_gettext("Created by"), "changed_on": lazy_gettext("Changed on"), "changed_by": lazy_gettext("Changed by"), } VAR_14 = { "first_name": lazy_gettext("Write the VAR_50 first name or names"), "last_name": lazy_gettext("Write the VAR_50 last name"), "username": lazy_gettext( "Username valid for authentication on DB or LDAP, unused for OID auth" ), "password": lazy_gettext( "Please use a good password policy," " this application does not check this for you" ), "active": lazy_gettext( "It's not a good policy to remove a VAR_50, just make it inactive" ), "email": lazy_gettext("The user's email, this will also be used for OID auth"), "roles": lazy_formatter_gettext( "The VAR_50 role on the application," " this will associate with a list of permissions", FUNC_0, ), "conf_password": lazy_gettext("Please rewrite the user's password to confirm"), } VAR_9 = ["first_name", "last_name", "username", "email", "active", "roles"] VAR_15 = [ ( lazy_gettext("User info"), {"fields": ["username", "active", "roles", "login_count"]}, ), ( lazy_gettext("Personal Info"), {"fields": ["first_name", "last_name", "email"], "expanded": True}, ), ( lazy_gettext("Audit Info"), { "fields": [ "last_login", "fail_login_count", "created_on", "created_by", "changed_on", "changed_by", ], "expanded": False, }, ), ] VAR_16 = [ ( lazy_gettext("User info"), {"fields": ["username", "active", "roles", "login_count"]}, ), ( lazy_gettext("Personal Info"), {"fields": ["first_name", "last_name", "email"], "expanded": True}, ), ] VAR_17 = ["password"] VAR_18 = ["first_name", "last_name", "username", "active", "email", "roles"] VAR_19 = ["first_name", "last_name", "username", "active", "email", "roles"] VAR_20 = lazy_gettext("Your VAR_50 information") @expose("/VAR_52/") @has_access def VAR_52(self): VAR_21 = self.datamodel.get(g.user.id, self._base_filters) VAR_43 = self._get_show_widget( g.user.id, VAR_21, VAR_15=self.user_show_fieldsets ) self.update_redirect() return self.render_template( self.show_template, VAR_37=self.user_info_title, VAR_43=widgets, appbuilder=self.appbuilder, ) @action("userinfoedit", lazy_gettext("Edit User"), "", "fa-edit", multiple=False) def FUNC_4(self, VAR_21): return redirect( url_for(self.appbuilder.sm.userinfoeditview.__name__ + ".this_form_get") ) class CLASS_7(CLASS_6): pass class CLASS_8(CLASS_6): pass class CLASS_9(CLASS_6): pass class CLASS_10(CLASS_6): pass class CLASS_11(CLASS_6): VAR_22 = { "password": PasswordField( lazy_gettext("Password"), description=lazy_gettext( "Please use a good password policy," " this application does not check this for you" ), validators=[validators.DataRequired()], widget=BS3PasswordFieldWidget(), ), "conf_password": PasswordField( lazy_gettext("Confirm Password"), description=lazy_gettext("Please rewrite the user's password to confirm"), validators=[ EqualTo("password", VAR_13=lazy_gettext("Passwords must match")) ], widget=BS3PasswordFieldWidget(), ), } VAR_18 = [ "first_name", "last_name", "username", "active", "email", "roles", "password", "conf_password", ] @expose("/FUNC_5/<VAR_23>", methods=["GET"]) @has_access def FUNC_5(self, VAR_23): VAR_44 = dict() VAR_44["resetpasswords"] = self.actions.get("resetpasswords") VAR_21 = self.datamodel.get(VAR_23, self._base_filters) if not VAR_21: abort(404) VAR_43 = self._get_show_widget(VAR_23, VAR_21, VAR_44=actions) self.update_redirect() return self.render_template( self.show_template, VAR_23=pk, VAR_37=self.show_title, VAR_43=widgets, appbuilder=self.appbuilder, related_views=self._related_views, ) @expose("/VAR_52/") @has_access def VAR_52(self): VAR_44 = dict() VAR_44["resetmypassword"] = self.actions.get("resetmypassword") VAR_44["userinfoedit"] = self.actions.get("userinfoedit") VAR_21 = self.datamodel.get(g.user.id, self._base_filters) VAR_43 = self._get_show_widget( g.user.id, VAR_21, VAR_44=actions, VAR_15=self.user_show_fieldsets ) self.update_redirect() return self.render_template( self.show_template, VAR_37=self.user_info_title, VAR_43=widgets, appbuilder=self.appbuilder, ) @action( "resetmypassword", lazy_gettext("Reset my password"), "", "fa-lock", multiple=False, ) def FUNC_6(self, VAR_21): return redirect( url_for(self.appbuilder.sm.resetmypasswordview.__name__ + ".this_form_get") ) @action( "resetpasswords", lazy_gettext("Reset Password"), "", "fa-lock", multiple=False ) def FUNC_7(self, VAR_21): return redirect( url_for( self.appbuilder.sm.resetpasswordview.__name__ + ".this_form_get", VAR_23=VAR_21.id, ) ) def FUNC_8(self, VAR_21): item.changed_on = datetime.datetime.now() VAR_21.changed_by_fk = g.user.id def FUNC_9(self, VAR_21): item.password = generate_password_hash(VAR_21.password) class CLASS_12(DirectByChartView): VAR_24 = lazy_gettext("User Statistics") VAR_8 = { "username": lazy_gettext("User Name"), "login_count": lazy_gettext("Login count"), "fail_login_count": lazy_gettext("Failed FUNC_11 count"), } VAR_25 = CLASS_6.search_columns VAR_26 = [ {"label": "Login Count", "group": "username", "series": ["login_count"]}, { "label": "Failed Login Count", "group": "username", "series": ["fail_login_count"], }, ] class CLASS_13(ListWidget): VAR_27 = "appbuilder/general/VAR_43/roles/list.html" def __init__(self, **VAR_28): kwargs["appbuilder"] = current_app.appbuilder super().__init__(**VAR_28) class CLASS_14(ShowWidget): VAR_27 = "appbuilder/general/VAR_43/roles/FUNC_5.html" def __init__(self, **VAR_28): kwargs["appbuilder"] = current_app.appbuilder super().__init__(**VAR_28) class CLASS_15(ModelView): VAR_2 = "/roles" VAR_4 = lazy_gettext("List Roles") VAR_5 = lazy_gettext("Show Role") VAR_6 = lazy_gettext("Add Role") VAR_7 = lazy_gettext("Edit Role") VAR_29 = CLASS_13 VAR_30 = CLASS_14 VAR_8 = { "name": lazy_gettext("Name"), "permissions": lazy_gettext("Permissions"), } VAR_9 = ["name", "permissions"] VAR_31 = ["name", "permissions"] VAR_19 = ["name", "permissions"] VAR_18 = VAR_19 VAR_32 = ["name"] @action( "copyrole", lazy_gettext("Copy Role"), lazy_gettext("Copy the selected roles?"), icon="fa-copy", single=False, ) def FUNC_10(self, VAR_33): self.update_redirect() for VAR_21 in VAR_33: VAR_49 = VAR_21.__class__() VAR_49.name = VAR_21.name VAR_49.permissions = VAR_21.permissions VAR_49.name = VAR_49.name + " copy" self.datamodel.add(VAR_49) return redirect(self.get_redirect()) class CLASS_16(ModelView): VAR_2 = "/registeruser" VAR_3 = ["can_list", "can_show", "can_delete"] VAR_4 = lazy_gettext("List of Registration Requests") VAR_5 = lazy_gettext("Show Registration") VAR_9 = ["username", "registration_date", "email"] VAR_34 = ["password"] VAR_17 = ["password"] class CLASS_17(BaseView): VAR_2 = "" VAR_35 = "" VAR_36 = lazy_gettext("Invalid FUNC_11. Please try again.") VAR_37 = lazy_gettext("Sign In") @expose("/FUNC_11/", methods=["GET", "POST"]) def FUNC_11(self): pass @expose("/FUNC_12/") def FUNC_12(self): logout_user() return redirect(self.appbuilder.get_url_for_index) class CLASS_18(CLASS_17): VAR_35 = "appbuilder/general/security/login_db.html" @expose("/FUNC_11/", methods=["GET", "POST"]) def FUNC_11(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) VAR_10 = LoginForm_db() if VAR_10.validate_on_submit(): VAR_50 = self.appbuilder.sm.auth_user_db( VAR_10.username.data, VAR_10.password.data ) if not VAR_50: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) login_user(VAR_50, remember=False) return redirect(self.appbuilder.get_url_for_index) return self.render_template( self.login_template, VAR_37=self.title, VAR_10=form, appbuilder=self.appbuilder ) class CLASS_19(CLASS_17): VAR_35 = "appbuilder/general/security/login_ldap.html" @expose("/FUNC_11/", methods=["GET", "POST"]) def FUNC_11(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) VAR_10 = LoginForm_db() if VAR_10.validate_on_submit(): VAR_50 = self.appbuilder.sm.auth_user_ldap( VAR_10.username.data, VAR_10.password.data ) if not VAR_50: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) login_user(VAR_50, remember=False) return redirect(self.appbuilder.get_url_for_index) return self.render_template( self.login_template, VAR_37=self.title, VAR_10=form, appbuilder=self.appbuilder ) class CLASS_20(CLASS_17): VAR_35 = "appbuilder/general/security/login_oid.html" VAR_38 = ["email"] VAR_39 = [] def __init__(self): super(CLASS_20, self).__init__() @expose("/FUNC_11/", methods=["GET", "POST"]) def FUNC_11(self, VAR_40=True): @self.appbuilder.sm.oid.loginhandler def FUNC_14(self): if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) VAR_10 = LoginForm_oid() if VAR_10.validate_on_submit(): VAR_54["remember_me"] = VAR_10.remember_me.data return self.appbuilder.sm.oid.try_login( VAR_10.openid.data, ask_for=self.oid_ask_for, ask_for_optional=self.oid_ask_for_optional, ) return self.render_template( self.login_template, VAR_37=self.title, VAR_10=form, providers=self.appbuilder.sm.openid_providers, appbuilder=self.appbuilder, ) @self.appbuilder.sm.oid.after_login def FUNC_15(VAR_45): if VAR_45.email is None or VAR_45.email == "": flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) VAR_50 = self.appbuilder.sm.auth_user_oid(VAR_45.email) if VAR_50 is None: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) VAR_51 = False if "remember_me" in VAR_54: VAR_51 = VAR_54["remember_me"] VAR_54.pop("remember_me", None) login_user(VAR_50, remember=VAR_51) return redirect(self.appbuilder.get_url_for_index) return FUNC_14(self) class CLASS_21(CLASS_17): VAR_35 = "appbuilder/general/security/login_oauth.html" @expose("/FUNC_11/") @expose("/FUNC_11/<VAR_41>") @expose("/FUNC_11/<VAR_41>/<VAR_42>") def FUNC_11( self, VAR_41: Optional[str] = None, VAR_42: Optional[str] = None ) -> Response: VAR_0.debug("Provider: {0}".format(VAR_41)) if g.user is not None and g.user.is_authenticated: VAR_0.debug("Already authenticated {0}".format(g.user)) return redirect(self.appbuilder.get_url_for_index) if VAR_41 is None: if len(self.appbuilder.sm.oauth_providers) > 1: return self.render_template( self.login_template, providers=self.appbuilder.sm.oauth_providers, VAR_37=self.title, appbuilder=self.appbuilder, ) else: VAR_41 = self.appbuilder.sm.oauth_providers[0]["name"] VAR_0.debug("Going to call authorize for: {0}".format(VAR_41)) VAR_46 = jwt.encode( request.args.to_dict(flat=False), self.appbuilder.app.config["SECRET_KEY"], algorithm="HS256", ) try: if VAR_42: VAR_0.debug("Login to Register") VAR_54["register"] = True if VAR_41 == "twitter": return self.appbuilder.sm.oauth_remotes[VAR_41].authorize_redirect( redirect_uri=url_for( ".oauth_authorized", VAR_41=provider, _external=True, VAR_46=state, ) ) else: return self.appbuilder.sm.oauth_remotes[VAR_41].authorize_redirect( redirect_uri=url_for( ".oauth_authorized", VAR_41=provider, _external=True ), VAR_46=state.decode("ascii") if isinstance(VAR_46, bytes) else VAR_46, ) except Exception as e: VAR_0.error("Error on OAuth authorize: {0}".format(e)) flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_index) @expose("/oauth-authorized/<VAR_41>") def FUNC_13(self, VAR_41: str) -> Response: VAR_0.debug("Authorized init") if VAR_41 not in self.appbuilder.sm.oauth_remotes: flash(u"Provider not supported.", "warning") VAR_0.warning("OAuth authorized got an unknown VAR_41 %s", VAR_41) return redirect(self.appbuilder.get_url_for_login) VAR_45 = self.appbuilder.sm.oauth_remotes[VAR_41].authorize_access_token() if VAR_45 is None: flash(u"You denied the request to sign in.", "warning") return redirect(self.appbuilder.get_url_for_login) VAR_0.debug("OAUTH Authorized VAR_45: {0}".format(VAR_45)) try: self.appbuilder.sm.set_oauth_session(VAR_41, VAR_45) VAR_52 = self.appbuilder.sm.oauth_user_info(VAR_41, VAR_45) except Exception as e: VAR_0.error("Error returning OAuth VAR_50 info: {0}".format(e)) VAR_50 = None else: VAR_0.debug("User info retrieved from {0}: {1}".format(VAR_41, VAR_52)) if VAR_41 in self.appbuilder.sm.oauth_whitelists: VAR_55 = self.appbuilder.sm.oauth_whitelists[VAR_41] VAR_56 = False for e in VAR_55: if re.search(e, VAR_52["email"]): VAR_56 = True break if not VAR_56: flash(u"You are not authorized.", "warning") return redirect(self.appbuilder.get_url_for_login) else: VAR_0.debug("No VAR_55 for OAuth provider") VAR_50 = self.appbuilder.sm.auth_user_oauth(VAR_52) if VAR_50 is None: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_login) else: login_user(VAR_50) try: VAR_46 = jwt.decode( request.args["state"], self.appbuilder.app.config["SECRET_KEY"], algorithms=["HS256"], ) except jwt.InvalidTokenError: raise Exception("State signature is not valid!") VAR_53 = self.appbuilder.get_url_for_index if "next" in VAR_46 and len(VAR_46["next"]) > 0: VAR_57 = urlparse(VAR_46["next"][0]) if VAR_57.netloc != request.host: VAR_0.warning("Got an invalid next URL: %s", VAR_57.netloc) else: VAR_53 = VAR_46["next"][0] return redirect(VAR_53) class CLASS_22(CLASS_17): VAR_35 = "" @expose("/FUNC_11/") def FUNC_11(self): VAR_47 = request.environ.get("REMOTE_USER") if g.user is not None and g.user.is_authenticated: return redirect(self.appbuilder.get_url_for_index) if VAR_47: VAR_50 = self.appbuilder.sm.auth_user_remote_user(VAR_47) if VAR_50 is None: flash(as_unicode(self.invalid_login_message), "warning") else: login_user(VAR_50) else: flash(as_unicode(self.invalid_login_message), "warning") return redirect(self.appbuilder.get_url_for_index)
[ 4, 12, 23, 24, 26, 27, 31, 36, 38, 39, 43, 48, 50, 51, 55, 60, 66, 67, 72, 78, 82, 83, 88, 94, 99, 100, 106, 109, 115, 122, 123, 133, 134, 137, 142, 160, 182, 184, 209, 220, 222, 226, 241, 247, 248, 255, 257, 258, 265, 267, 268, 275, 277, 278, 285, 287, 288, 295, 315, 326, 345, 352, 364, 376, 387, 391, 394, 395, 403, 405, 414, 415, 418, 422, 423, 426, 430, 431, 434, 439, 442, 452, 469, 470, 479, 480, 486, 490, 495, 496, 499, 517, 518, 521, 539, 543, 586, 587, 592, 595, 617, 631, 634, 636, 637, 640, 649, 660, 691, 700, 709, 723, 737, 742, 744, 745, 748, 763, 69, 70, 71, 85, 86, 87, 250, 251, 252, 253, 254, 260, 261, 262, 263, 264, 270, 271, 272, 273, 274, 280, 281, 282, 283, 284, 290, 291, 292, 293, 294 ]
[ 6, 24, 35, 36, 38, 39, 43, 48, 50, 51, 55, 60, 62, 63, 67, 72, 78, 79, 84, 90, 94, 95, 100, 106, 111, 112, 118, 121, 127, 134, 135, 145, 146, 149, 154, 172, 194, 196, 221, 232, 234, 238, 253, 259, 260, 267, 269, 270, 277, 279, 280, 287, 289, 290, 297, 299, 300, 307, 327, 338, 357, 364, 376, 388, 399, 403, 406, 407, 415, 417, 426, 427, 430, 434, 435, 438, 442, 443, 446, 451, 454, 464, 481, 482, 491, 492, 498, 502, 507, 508, 511, 529, 530, 533, 551, 552, 557, 560, 582, 596, 599, 601, 602, 605, 616, 627, 658, 671, 680, 694, 708, 710, 718, 719, 722, 737, 81, 82, 83, 97, 98, 99, 262, 263, 264, 265, 266, 272, 273, 274, 275, 276, 282, 283, 284, 285, 286, 292, 293, 294, 295, 296, 302, 303, 304, 305, 306 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock from twisted.internet import defer from synapse.rest.client.v1 import presence from synapse.types import UserID from tests import unittest class PresenceTestCase(unittest.HomeserverTestCase): """ Tests presence REST API. """ user_id = "@sid:red" user = UserID.from_string(user_id) servlets = [presence.register_servlets] def make_homeserver(self, reactor, clock): presence_handler = Mock() presence_handler.set_state.return_value = defer.succeed(None) hs = self.setup_test_homeserver( "red", http_client=None, federation_client=Mock(), presence_handler=presence_handler, ) return hs def test_put_presence(self): """ PUT to the status endpoint with use_presence enabled will call set_state on the presence handler. """ self.hs.config.use_presence = True body = {"presence": "here", "status_msg": "beep boop"} request, channel = self.make_request( "PUT", "/presence/%s/status" % (self.user_id,), body ) self.assertEqual(channel.code, 200) self.assertEqual(self.hs.get_presence_handler().set_state.call_count, 1) def test_put_presence_disabled(self): """ PUT to the status endpoint with use_presence disabled will NOT call set_state on the presence handler. """ self.hs.config.use_presence = False body = {"presence": "here", "status_msg": "beep boop"} request, channel = self.make_request( "PUT", "/presence/%s/status" % (self.user_id,), body ) self.assertEqual(channel.code, 200) self.assertEqual(self.hs.get_presence_handler().set_state.call_count, 0)
# -*- coding: utf-8 -*- # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock from twisted.internet import defer from synapse.rest.client.v1 import presence from synapse.types import UserID from tests import unittest class PresenceTestCase(unittest.HomeserverTestCase): """ Tests presence REST API. """ user_id = "@sid:red" user = UserID.from_string(user_id) servlets = [presence.register_servlets] def make_homeserver(self, reactor, clock): presence_handler = Mock() presence_handler.set_state.return_value = defer.succeed(None) hs = self.setup_test_homeserver( "red", federation_http_client=None, federation_client=Mock(), presence_handler=presence_handler, ) return hs def test_put_presence(self): """ PUT to the status endpoint with use_presence enabled will call set_state on the presence handler. """ self.hs.config.use_presence = True body = {"presence": "here", "status_msg": "beep boop"} request, channel = self.make_request( "PUT", "/presence/%s/status" % (self.user_id,), body ) self.assertEqual(channel.code, 200) self.assertEqual(self.hs.get_presence_handler().set_state.call_count, 1) def test_put_presence_disabled(self): """ PUT to the status endpoint with use_presence disabled will NOT call set_state on the presence handler. """ self.hs.config.use_presence = False body = {"presence": "here", "status_msg": "beep boop"} request, channel = self.make_request( "PUT", "/presence/%s/status" % (self.user_id,), body ) self.assertEqual(channel.code, 200) self.assertEqual(self.hs.get_presence_handler().set_state.call_count, 0)
open_redirect
{ "code": [ " http_client=None," ], "line_no": [ 41 ] }
{ "code": [ " federation_http_client=None," ], "line_no": [ 41 ] }
from mock import Mock from twisted.internet import defer from synapse.rest.client.v1 import presence from synapse.types import UserID from tests import unittest class CLASS_0(unittest.HomeserverTestCase): VAR_0 = "@sid:red" VAR_1 = UserID.from_string(VAR_0) VAR_2 = [presence.register_servlets] def FUNC_0(self, VAR_3, VAR_4): VAR_5 = Mock() VAR_5.set_state.return_value = defer.succeed(None) VAR_6 = self.setup_test_homeserver( "red", http_client=None, federation_client=Mock(), VAR_5=presence_handler, ) return VAR_6 def FUNC_1(self): self.hs.config.use_presence = True VAR_7 = {"presence": "here", "status_msg": "beep boop"} VAR_8, VAR_9 = self.make_request( "PUT", "/presence/%s/status" % (self.user_id,), VAR_7 ) self.assertEqual(VAR_9.code, 200) self.assertEqual(self.hs.get_presence_handler().set_state.call_count, 1) def FUNC_2(self): self.hs.config.use_presence = False VAR_7 = {"presence": "here", "status_msg": "beep boop"} VAR_8, VAR_9 = self.make_request( "PUT", "/presence/%s/status" % (self.user_id,), VAR_7 ) self.assertEqual(VAR_9.code, 200) self.assertEqual(self.hs.get_presence_handler().set_state.call_count, 0)
from mock import Mock from twisted.internet import defer from synapse.rest.client.v1 import presence from synapse.types import UserID from tests import unittest class CLASS_0(unittest.HomeserverTestCase): VAR_0 = "@sid:red" VAR_1 = UserID.from_string(VAR_0) VAR_2 = [presence.register_servlets] def FUNC_0(self, VAR_3, VAR_4): VAR_5 = Mock() VAR_5.set_state.return_value = defer.succeed(None) VAR_6 = self.setup_test_homeserver( "red", federation_http_client=None, federation_client=Mock(), VAR_5=presence_handler, ) return VAR_6 def FUNC_1(self): self.hs.config.use_presence = True VAR_7 = {"presence": "here", "status_msg": "beep boop"} VAR_8, VAR_9 = self.make_request( "PUT", "/presence/%s/status" % (self.user_id,), VAR_7 ) self.assertEqual(VAR_9.code, 200) self.assertEqual(self.hs.get_presence_handler().set_state.call_count, 1) def FUNC_2(self): self.hs.config.use_presence = False VAR_7 = {"presence": "here", "status_msg": "beep boop"} VAR_8, VAR_9 = self.make_request( "PUT", "/presence/%s/status" % (self.user_id,), VAR_7 ) self.assertEqual(VAR_9.code, 200) self.assertEqual(self.hs.get_presence_handler().set_state.call_count, 0)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 19, 22, 24, 25, 28, 30, 33, 35, 38, 45, 47, 54, 59, 62, 69, 74, 77, 27, 49, 50, 51, 52, 64, 65, 66, 67 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 19, 22, 24, 25, 28, 30, 33, 35, 38, 45, 47, 54, 59, 62, 69, 74, 77, 27, 49, 50, 51, 52, 64, 65, 66, 67 ]
0CWE-22
import pytest from jinja2 import Environment, PackageLoader @pytest.fixture(scope="session") def env() -> Environment: from openapi_python_client import utils TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "spinalcase": utils.spinal_case} env = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) env.filters.update(TEMPLATE_FILTERS) return env
import pytest from jinja2 import Environment, PackageLoader @pytest.fixture(scope="session") def env() -> Environment: from openapi_python_client import utils TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} env = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) env.filters.update(TEMPLATE_FILTERS) return env
path_disclosure
{ "code": [ " TEMPLATE_FILTERS = {\"snakecase\": utils.snake_case, \"spinalcase\": utils.spinal_case}" ], "line_no": [ 9 ] }
{ "code": [ " TEMPLATE_FILTERS = {\"snakecase\": utils.snake_case, \"kebabcase\": utils.kebab_case}" ], "line_no": [ 9 ] }
import pytest from jinja2 import Environment, PackageLoader @pytest.fixture(scope="session") def VAR_1() -> Environment: from openapi_python_client import utils VAR_0 = {"snakecase": utils.snake_case, "spinalcase": utils.spinal_case} VAR_1 = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) VAR_1.filters.update(VAR_0) return VAR_1
import pytest from jinja2 import Environment, PackageLoader @pytest.fixture(scope="session") def VAR_1() -> Environment: from openapi_python_client import utils VAR_0 = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} VAR_1 = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) VAR_1.filters.update(VAR_0) return VAR_1
[ 3, 4, 8, 13 ]
[ 3, 4, 8, 13 ]
3CWE-352
import os import re from flask.testing import FlaskClient from flask import request from flask_login import current_user from responses import RequestsMock, GET from werkzeug.security import generate_password_hash from archivy.helpers import get_max_id, get_db from archivy.data import get_dirs, create_dir, get_items, get_item def test_get_index(test_app, client: FlaskClient): response = client.get("/") assert response.status_code == 200 def test_get_custom_css(test_app, client: FlaskClient): test_app.config["THEME_CONF"]["use_custom_css"] = True css_file = "custom.css" css_contents = """ body { color: red } """ os.mkdir(f"{test_app.config['USER_DIR']}/css/") with open(f"{test_app.config['USER_DIR']}/css/{css_file}", "w") as f: f.write(css_contents) test_app.config["THEME_CONF"]["custom_css_file"] = css_file resp = client.get("/static/custom.css") assert css_contents.encode("utf-8") in resp.data test_app.config["THEME_CONF"]["use_custom_css"] = False def test_get_new_bookmark(test_app, client: FlaskClient): response = client.get("/bookmarks/new") assert response.status_code == 200 def test_post_new_bookmark_missing_fields(test_app, client: FlaskClient): response = client.post("/bookmarks/new", data={"submit": True}) assert response.status_code == 200 assert b"This field is required" in response.data def test_get_new_note(test_app, client: FlaskClient): response = client.get("/notes/new") assert response.status_code == 200 def test_get_dataobj_not_found(test_app, client: FlaskClient): response = client.get("/dataobj/1") assert response.status_code == 302 def test_get_dataobj(test_app, client: FlaskClient, note_fixture): response = client.get("/dataobj/1") assert response.status_code == 200 def test_get_delete_dataobj_not_found(test_app, client: FlaskClient): response = client.get("/dataobj/delete/1") assert response.status_code == 302 def test_get_delete_dataobj(test_app, client: FlaskClient, note_fixture): response = client.get("/dataobj/delete/1") assert response.status_code == 302 def test_create_new_bookmark( test_app, client: FlaskClient, mocked_responses: RequestsMock ): mocked_responses.add( GET, "https://example.com/", body="""<html> <head><title>Random</title></head><body><p> Lorem ipsum dolor sit amet, consectetur adipiscing elit </p></body></html> """, ) bookmark_data = { "url": "https://example.com", "tags": "testing,bookmark", "path": "", "submit": "true", } resp = client.post("/bookmarks/new", data=bookmark_data) assert resp.status_code == 302 assert not b"invalid" in resp.data resp = client.post("/bookmarks/new", data=bookmark_data, follow_redirects=True) assert resp.status_code == 200 assert b'<span class="post-tag">bookmark</span>' in resp.data assert b'<span class="post-tag">testing</span>' in resp.data assert b"https://example.com" in resp.data assert b"Random" in resp.data def test_creating_bookmark_without_passing_path_saves_to_default_dir( test_app, client, mocked_responses ): mocked_responses.add(GET, "http://example.org", body="Example\n") bookmarks_dir = "bookmarks" test_app.config["DEFAULT_BOOKMARKS_DIR"] = bookmarks_dir create_dir(bookmarks_dir) resp = client.post( "/bookmarks/new", data={ "url": "http://example.org", "submit": "true", }, ) bookmark = get_items(structured=False)[0] assert ( "bookmarks" in bookmark["path"] ) # verify it was saved to default bookmark dir def test_create_note(test_app, client: FlaskClient): note_data = { "title": "Testing the create route", "tags": "testing,note", "path": "", "submit": "true", } resp = client.post("/notes/new", data=note_data) assert resp.status_code == 302 assert not b"invalid" in resp.data resp = client.post("/notes/new", data=note_data, follow_redirects=True) assert resp.status_code == 200 assert b'<span class="post-tag">note</span>' in resp.data assert b'<span class="post-tag">testing</span>' in resp.data assert b"Testing the create route" in resp.data def test_logging_in(test_app, client: FlaskClient): resp = client.post( "/login", data={"username": "halcyon", "password": "password"}, follow_redirects=True, ) assert resp.status_code == 200 assert request.path == "/" assert current_user def test_logging_in_with_invalid_creds(test_app, client: FlaskClient): resp = client.post( "/login", data={"username": "invalid", "password": "dasdasd"}, follow_redirects=True, ) assert resp.status_code == 200 assert request.path == "/login" assert b"Invalid credentials" in resp.data def test_edit_user(test_app, client: FlaskClient): """Tests editing a user's info, logging out and then logging in with new info.""" new_user = "new_halcyon" new_pass = "password2" resp = client.post( "/user/edit", data={"username": new_user, "password": new_pass}, follow_redirects=True, ) assert request.path == "/" client.delete("/logout") resp = client.post( "/login", data={"username": new_user, "password": new_pass}, follow_redirects=True, ) assert resp.status_code == 200 assert request.path == "/" # check information has updated. def test_logging_out(test_app, client: FlaskClient): """Tests logging out and then accessing restricted views""" client.delete("/logout") resp = client.get("/", follow_redirects=True) assert request.path == "/login" def test_create_dir(test_app, client: FlaskClient): """Tests /folders/create endpoint""" resp = client.post( "/folders/create", data={"parent_dir": "", "new_dir": "testing"}, follow_redirects=True, ) assert resp.status_code == 200 assert request.args.get("path") == "testing" assert "testing" in get_dirs() assert b"Folder successfully created" in resp.data def test_creating_without_dirname_fails(test_app, client: FlaskClient): resp = client.post( "/folders/create", data={"parent_dir": ""}, follow_redirects=True ) assert resp.status_code == 200 assert request.path == "/" assert b"Could not create folder." in resp.data def test_visiting_nonexistent_dir_fails(test_app, client: FlaskClient): resp = client.get("/?path=nonexistent_dir", follow_redirects=True) assert b"Directory does not exist." in resp.data def test_deleting_dir(test_app, client: FlaskClient): create_dir("testing") assert "testing" in get_dirs() resp = client.post( "/folders/delete", data={"dir_name": "testing"}, follow_redirects=True ) assert not "testing" in get_dirs() assert b"Folder successfully deleted." in resp.data def test_deleting_nonexisting_folder_fails(test_app, client: FlaskClient): resp = client.post("/folders/delete", data={"dir_name": "testing"}) assert resp.status_code == 404 def test_bookmarklet(test_app, client: FlaskClient): resp = client.get("/bookmarklet") assert resp.status_code == 200 def test_backlinks_are_saved( test_app, client: FlaskClient, note_fixture, bookmark_fixture ): test_app.config["SEARCH_CONF"]["enabled"] = 1 test_app.config["SEARCH_CONF"]["engine"] = "ripgrep" resp = client.put( f"/api/dataobjs/{note_fixture.id}", json={"content": f"[[{bookmark_fixture.title}|{bookmark_fixture.id}]]"}, ) assert resp.status_code == 200 resp = client.get(f"/dataobj/{bookmark_fixture.id}") assert b"Backlinks" in resp.data # backlink was detected test_app.config["SEARCH_CONF"]["enabled"] = 0 def test_bookmark_with_long_title_gets_truncated(test_app, client, mocked_responses): long_title = "a" * 300 # check that our mock title is indeed longer than the limit # and would cause an error, without our truncating assert os.pathconf("/", "PC_NAME_MAX") < len(long_title) mocked_responses.add(GET, "https://example.com", f"<title>{long_title}</title>") bookmark_data = { "url": "https://example.com", "submit": "true", } resp = client.post("/bookmarks/new", data=bookmark_data) assert resp.status_code == 200 def test_move_data(test_app, note_fixture, client): create_dir("random") resp = client.post( "/dataobj/move/1", data={"path": "random", "submit": "true"}, follow_redirects=True, ) assert resp.status_code == 200 assert b"Data successfully moved to random." in resp.data assert get_item(1)["dir"] == "random" def test_invalid_inputs_fail_move_data(test_app, note_fixture, client): resp = client.post("/dataobj/move/1", follow_redirects=True) assert b"No path specified." in resp.data resp = client.post( "/dataobj/move/2", data={"path": "aaa", "submit": "true"}, follow_redirects=True ) assert b"Data not found" in resp.data resp = client.post( "/dataobj/move/1", data={"path": "", "submit": "true"}, follow_redirects=True ) assert b"Data already in target directory" in resp.data faulty_paths = ["../adarnad", "~/adasd", "ssss"] for p in faulty_paths: resp = client.post( "/dataobj/move/1", data={"path": p, "submit": "true"}, follow_redirects=True ) assert b"Data could not be moved to " + bytes(p, "utf-8") in resp.data def test_rename_dir(test_app, client): create_dir("random") resp = client.post( "/folders/rename", data={"current_path": "random", "new_name": "renamed_random"}, follow_redirects=True, ) assert resp.status_code == 200 assert b"Renamed successfully" in resp.data def test_invalid_inputs_fail_renaming(test_app, client): create_dir("random") create_dir("random2") resp = client.post( "/folders/rename", data={"current_path": "inexisting", "new_name": "random3"}, follow_redirects=True, ) assert b"Directory not found" in resp.data resp = client.post( "/folders/rename", data={"current_path": "random", "new_name": "random2"}, follow_redirects=True, ) assert b"Target directory exists." in resp.data faulty_paths = ["../adarnad", "~/adasd", "/illegal_dir", "."] for p in faulty_paths: print(p) resp = client.post( "/folders/rename", data={"current_path": "random", "new_name": p}, follow_redirects=True, ) assert b"Invalid input" in resp.data def test_get_config_page(test_app, client): resp = client.get("/config") assert resp.status_code == 200 assert b"Edit Config" in resp.data def test_post_updated_config(test_app, client): # use dark theme as random conf value to change dark_theme = test_app.config["THEME_CONF"]["use_theme_dark"] resp = client.post( "/config", data={"submit": True, "THEME_CONF-use_theme_dark": not dark_theme} ) assert test_app.config["THEME_CONF"]["use_theme_dark"] == (not dark_theme) def test_getting_all_tags(test_app, client, bookmark_fixture): # bookmark fixture has embedded tags resp = client.get("/tags") bookmark_tags = ["embedded-tag", "tag2"] assert resp.status_code == 200 for tag in bookmark_tags: assert f"#{tag}" in str(resp.data) def test_getting_matches_for_specific_tag(test_app, client, bookmark_fixture): resp = client.get("/tags/tag2") assert resp.status_code == 200 assert bookmark_fixture.title in str(resp.data) assert str(bookmark_fixture.id) in str(resp.data)
import os import re from flask.testing import FlaskClient from flask import request from flask_login import current_user from responses import RequestsMock, GET from werkzeug.security import generate_password_hash from archivy.helpers import get_max_id, get_db from archivy.data import get_dirs, create_dir, get_items, get_item def test_get_index(test_app, client: FlaskClient): response = client.get("/") assert response.status_code == 200 def test_get_custom_css(test_app, client: FlaskClient): test_app.config["THEME_CONF"]["use_custom_css"] = True css_file = "custom.css" css_contents = """ body { color: red } """ os.mkdir(f"{test_app.config['USER_DIR']}/css/") with open(f"{test_app.config['USER_DIR']}/css/{css_file}", "w") as f: f.write(css_contents) test_app.config["THEME_CONF"]["custom_css_file"] = css_file resp = client.get("/static/custom.css") assert css_contents.encode("utf-8") in resp.data test_app.config["THEME_CONF"]["use_custom_css"] = False def test_get_new_bookmark(test_app, client: FlaskClient): response = client.get("/bookmarks/new") assert response.status_code == 200 def test_post_new_bookmark_missing_fields(test_app, client: FlaskClient): response = client.post("/bookmarks/new", data={"submit": True}) assert response.status_code == 200 assert b"This field is required" in response.data def test_get_new_note(test_app, client: FlaskClient): response = client.get("/notes/new") assert response.status_code == 200 def test_get_dataobj_not_found(test_app, client: FlaskClient): response = client.get("/dataobj/1") assert response.status_code == 302 def test_get_dataobj(test_app, client: FlaskClient, note_fixture): response = client.get("/dataobj/1") assert response.status_code == 200 def test_get_delete_dataobj_not_found(test_app, client: FlaskClient): response = client.post("/dataobj/delete/1") assert response.status_code == 302 def test_get_delete_dataobj(test_app, client: FlaskClient, note_fixture): response = client.post("/dataobj/delete/1") assert response.status_code == 302 def test_create_new_bookmark( test_app, client: FlaskClient, mocked_responses: RequestsMock ): mocked_responses.add( GET, "https://example.com/", body="""<html> <head><title>Random</title></head><body><p> Lorem ipsum dolor sit amet, consectetur adipiscing elit </p></body></html> """, ) bookmark_data = { "url": "https://example.com", "tags": "testing,bookmark", "path": "", "submit": "true", } resp = client.post("/bookmarks/new", data=bookmark_data) assert resp.status_code == 302 assert not b"invalid" in resp.data resp = client.post("/bookmarks/new", data=bookmark_data, follow_redirects=True) assert resp.status_code == 200 assert b'<span class="post-tag">bookmark</span>' in resp.data assert b'<span class="post-tag">testing</span>' in resp.data assert b"https://example.com" in resp.data assert b"Random" in resp.data def test_creating_bookmark_without_passing_path_saves_to_default_dir( test_app, client, mocked_responses ): mocked_responses.add(GET, "http://example.org", body="Example\n") bookmarks_dir = "bookmarks" test_app.config["DEFAULT_BOOKMARKS_DIR"] = bookmarks_dir create_dir(bookmarks_dir) resp = client.post( "/bookmarks/new", data={ "url": "http://example.org", "submit": "true", }, ) bookmark = get_items(structured=False)[0] assert ( "bookmarks" in bookmark["path"] ) # verify it was saved to default bookmark dir def test_create_note(test_app, client: FlaskClient): note_data = { "title": "Testing the create route", "tags": "testing,note", "path": "", "submit": "true", } resp = client.post("/notes/new", data=note_data) assert resp.status_code == 302 assert not b"invalid" in resp.data resp = client.post("/notes/new", data=note_data, follow_redirects=True) assert resp.status_code == 200 assert b'<span class="post-tag">note</span>' in resp.data assert b'<span class="post-tag">testing</span>' in resp.data assert b"Testing the create route" in resp.data def test_logging_in(test_app, client: FlaskClient): resp = client.post( "/login", data={"username": "halcyon", "password": "password"}, follow_redirects=True, ) assert resp.status_code == 200 assert request.path == "/" assert current_user def test_logging_in_with_invalid_creds(test_app, client: FlaskClient): resp = client.post( "/login", data={"username": "invalid", "password": "dasdasd"}, follow_redirects=True, ) assert resp.status_code == 200 assert request.path == "/login" assert b"Invalid credentials" in resp.data def test_edit_user(test_app, client: FlaskClient): """Tests editing a user's info, logging out and then logging in with new info.""" new_user = "new_halcyon" new_pass = "password2" resp = client.post( "/user/edit", data={"username": new_user, "password": new_pass}, follow_redirects=True, ) assert request.path == "/" client.delete("/logout") resp = client.post( "/login", data={"username": new_user, "password": new_pass}, follow_redirects=True, ) assert resp.status_code == 200 assert request.path == "/" # check information has updated. def test_logging_out(test_app, client: FlaskClient): """Tests logging out and then accessing restricted views""" client.delete("/logout") resp = client.get("/", follow_redirects=True) assert request.path == "/login" def test_create_dir(test_app, client: FlaskClient): """Tests /folders/create endpoint""" resp = client.post( "/folders/create", data={"parent_dir": "", "new_dir": "testing"}, follow_redirects=True, ) assert resp.status_code == 200 assert request.args.get("path") == "testing" assert "testing" in get_dirs() assert b"Folder successfully created" in resp.data def test_creating_without_dirname_fails(test_app, client: FlaskClient): resp = client.post( "/folders/create", data={"parent_dir": ""}, follow_redirects=True ) assert resp.status_code == 200 assert request.path == "/" assert b"Could not create folder." in resp.data def test_visiting_nonexistent_dir_fails(test_app, client: FlaskClient): resp = client.get("/?path=nonexistent_dir", follow_redirects=True) assert b"Directory does not exist." in resp.data def test_deleting_dir(test_app, client: FlaskClient): create_dir("testing") assert "testing" in get_dirs() resp = client.post( "/folders/delete", data={"dir_name": "testing"}, follow_redirects=True ) assert not "testing" in get_dirs() assert b"Folder successfully deleted." in resp.data def test_deleting_nonexisting_folder_fails(test_app, client: FlaskClient): resp = client.post("/folders/delete", data={"dir_name": "testing"}) assert resp.status_code == 404 def test_bookmarklet(test_app, client: FlaskClient): resp = client.get("/bookmarklet") assert resp.status_code == 200 def test_backlinks_are_saved( test_app, client: FlaskClient, note_fixture, bookmark_fixture ): test_app.config["SEARCH_CONF"]["enabled"] = 1 test_app.config["SEARCH_CONF"]["engine"] = "ripgrep" resp = client.put( f"/api/dataobjs/{note_fixture.id}", json={"content": f"[[{bookmark_fixture.title}|{bookmark_fixture.id}]]"}, ) assert resp.status_code == 200 resp = client.get(f"/dataobj/{bookmark_fixture.id}") assert b"Backlinks" in resp.data # backlink was detected test_app.config["SEARCH_CONF"]["enabled"] = 0 def test_bookmark_with_long_title_gets_truncated(test_app, client, mocked_responses): long_title = "a" * 300 # check that our mock title is indeed longer than the limit # and would cause an error, without our truncating assert os.pathconf("/", "PC_NAME_MAX") < len(long_title) mocked_responses.add(GET, "https://example.com", f"<title>{long_title}</title>") bookmark_data = { "url": "https://example.com", "submit": "true", } resp = client.post("/bookmarks/new", data=bookmark_data) assert resp.status_code == 200 def test_move_data(test_app, note_fixture, client): create_dir("random") resp = client.post( "/dataobj/move/1", data={"path": "random", "submit": "true"}, follow_redirects=True, ) assert resp.status_code == 200 assert b"Data successfully moved to random." in resp.data assert get_item(1)["dir"] == "random" def test_invalid_inputs_fail_move_data(test_app, note_fixture, client): resp = client.post("/dataobj/move/1", follow_redirects=True) assert b"No path specified." in resp.data resp = client.post( "/dataobj/move/2", data={"path": "aaa", "submit": "true"}, follow_redirects=True ) assert b"Data not found" in resp.data resp = client.post( "/dataobj/move/1", data={"path": "", "submit": "true"}, follow_redirects=True ) assert b"Data already in target directory" in resp.data faulty_paths = ["../adarnad", "~/adasd", "ssss"] for p in faulty_paths: resp = client.post( "/dataobj/move/1", data={"path": p, "submit": "true"}, follow_redirects=True ) assert b"Data could not be moved to " + bytes(p, "utf-8") in resp.data def test_rename_dir(test_app, client): create_dir("random") resp = client.post( "/folders/rename", data={"current_path": "random", "new_name": "renamed_random"}, follow_redirects=True, ) assert resp.status_code == 200 assert b"Renamed successfully" in resp.data def test_invalid_inputs_fail_renaming(test_app, client): create_dir("random") create_dir("random2") resp = client.post( "/folders/rename", data={"current_path": "inexisting", "new_name": "random3"}, follow_redirects=True, ) assert b"Directory not found" in resp.data resp = client.post( "/folders/rename", data={"current_path": "random", "new_name": "random2"}, follow_redirects=True, ) assert b"Target directory exists." in resp.data faulty_paths = ["../adarnad", "~/adasd", "/illegal_dir", "."] for p in faulty_paths: print(p) resp = client.post( "/folders/rename", data={"current_path": "random", "new_name": p}, follow_redirects=True, ) assert b"Invalid input" in resp.data def test_get_config_page(test_app, client): resp = client.get("/config") assert resp.status_code == 200 assert b"Edit Config" in resp.data def test_post_updated_config(test_app, client): # use dark theme as random conf value to change dark_theme = test_app.config["THEME_CONF"]["use_theme_dark"] resp = client.post( "/config", data={"submit": True, "THEME_CONF-use_theme_dark": not dark_theme} ) assert test_app.config["THEME_CONF"]["use_theme_dark"] == (not dark_theme) def test_getting_all_tags(test_app, client, bookmark_fixture): # bookmark fixture has embedded tags resp = client.get("/tags") bookmark_tags = ["embedded-tag", "tag2"] assert resp.status_code == 200 for tag in bookmark_tags: assert f"#{tag}" in str(resp.data) def test_getting_matches_for_specific_tag(test_app, client, bookmark_fixture): resp = client.get("/tags/tag2") assert resp.status_code == 200 assert bookmark_fixture.title in str(resp.data) assert str(bookmark_fixture.id) in str(resp.data)
xsrf
{ "code": [ " response = client.get(\"/dataobj/delete/1\")", " response = client.get(\"/dataobj/delete/1\")" ], "line_no": [ 64, 69 ] }
{ "code": [ " response = client.post(\"/dataobj/delete/1\")", " response = client.post(\"/dataobj/delete/1\")" ], "line_no": [ 64, 69 ] }
import os import re from flask.testing import FlaskClient from flask import request from flask_login import current_user from responses import RequestsMock, GET from werkzeug.security import generate_password_hash from archivy.helpers import get_max_id, get_db from archivy.data import get_dirs, create_dir, get_items, get_item def FUNC_0(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.get("/") assert VAR_5.status_code == 200 def FUNC_1(VAR_0, VAR_1: FlaskClient): VAR_0.config["THEME_CONF"]["use_custom_css"] = True VAR_6 = "custom.css" VAR_7 = """ body { color: red } """ os.mkdir(f"{VAR_0.config['USER_DIR']}/css/") with open(f"{VAR_0.config['USER_DIR']}/css/{VAR_6}", "w") as f: f.write(VAR_7) VAR_0.config["THEME_CONF"]["custom_css_file"] = VAR_6 VAR_8 = VAR_1.get("/static/custom.css") assert VAR_7.encode("utf-8") in VAR_8.data VAR_0.config["THEME_CONF"]["use_custom_css"] = False def FUNC_2(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.get("/bookmarks/new") assert VAR_5.status_code == 200 def FUNC_3(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.post("/bookmarks/new", data={"submit": True}) assert VAR_5.status_code == 200 assert b"This field is required" in VAR_5.data def FUNC_4(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.get("/notes/new") assert VAR_5.status_code == 200 def FUNC_5(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.get("/dataobj/1") assert VAR_5.status_code == 302 def FUNC_6(VAR_0, VAR_1: FlaskClient, VAR_2): VAR_5 = VAR_1.get("/dataobj/1") assert VAR_5.status_code == 200 def FUNC_7(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.get("/dataobj/delete/1") assert VAR_5.status_code == 302 def FUNC_8(VAR_0, VAR_1: FlaskClient, VAR_2): VAR_5 = VAR_1.get("/dataobj/delete/1") assert VAR_5.status_code == 302 def FUNC_9( VAR_0, VAR_1: FlaskClient, VAR_3: RequestsMock ): VAR_3.add( GET, "https://example.com/", body="""<html> <head><title>Random</title></head><body><p> Lorem ipsum dolor sit amet, consectetur adipiscing elit </p></body></html> """, ) VAR_9 = { "url": "https://example.com", "tags": "testing,bookmark", "path": "", "submit": "true", } VAR_8 = VAR_1.post("/bookmarks/new", data=VAR_9) assert VAR_8.status_code == 302 assert not b"invalid" in VAR_8.data VAR_8 = VAR_1.post("/bookmarks/new", data=VAR_9, follow_redirects=True) assert VAR_8.status_code == 200 assert b'<span class="post-tag">VAR_11</span>' in VAR_8.data assert b'<span class="post-tag">testing</span>' in VAR_8.data assert b"https://example.com" in VAR_8.data assert b"Random" in VAR_8.data def FUNC_10( VAR_0, VAR_1, VAR_3 ): VAR_3.add(GET, "http://example.org", body="Example\n") VAR_10 = "bookmarks" VAR_0.config["DEFAULT_BOOKMARKS_DIR"] = VAR_10 create_dir(VAR_10) VAR_8 = VAR_1.post( "/bookmarks/new", data={ "url": "http://example.org", "submit": "true", }, ) VAR_11 = get_items(structured=False)[0] assert ( "bookmarks" in VAR_11["path"] ) # verify it was saved to default VAR_11 dir def FUNC_11(VAR_0, VAR_1: FlaskClient): VAR_12 = { "title": "Testing the create route", "tags": "testing,note", "path": "", "submit": "true", } VAR_8 = VAR_1.post("/notes/new", data=VAR_12) assert VAR_8.status_code == 302 assert not b"invalid" in VAR_8.data VAR_8 = VAR_1.post("/notes/new", data=VAR_12, follow_redirects=True) assert VAR_8.status_code == 200 assert b'<span class="post-tag">note</span>' in VAR_8.data assert b'<span class="post-tag">testing</span>' in VAR_8.data assert b"Testing the create route" in VAR_8.data def FUNC_12(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post( "/login", data={"username": "halcyon", "password": "password"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert request.path == "/" assert current_user def FUNC_13(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post( "/login", data={"username": "invalid", "password": "dasdasd"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert request.path == "/login" assert b"Invalid credentials" in VAR_8.data def FUNC_14(VAR_0, VAR_1: FlaskClient): VAR_13 = "new_halcyon" VAR_14 = "password2" VAR_8 = VAR_1.post( "/user/edit", data={"username": VAR_13, "password": VAR_14}, follow_redirects=True, ) assert request.path == "/" VAR_1.delete("/logout") VAR_8 = VAR_1.post( "/login", data={"username": VAR_13, "password": VAR_14}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert request.path == "/" def FUNC_15(VAR_0, VAR_1: FlaskClient): VAR_1.delete("/logout") VAR_8 = VAR_1.get("/", follow_redirects=True) assert request.path == "/login" def FUNC_16(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post( "/folders/create", data={"parent_dir": "", "new_dir": "testing"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert request.args.get("path") == "testing" assert "testing" in get_dirs() assert b"Folder successfully created" in VAR_8.data def FUNC_17(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post( "/folders/create", data={"parent_dir": ""}, follow_redirects=True ) assert VAR_8.status_code == 200 assert request.path == "/" assert b"Could not create folder." in VAR_8.data def FUNC_18(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.get("/?path=nonexistent_dir", follow_redirects=True) assert b"Directory does not exist." in VAR_8.data def FUNC_19(VAR_0, VAR_1: FlaskClient): create_dir("testing") assert "testing" in get_dirs() VAR_8 = VAR_1.post( "/folders/delete", data={"dir_name": "testing"}, follow_redirects=True ) assert not "testing" in get_dirs() assert b"Folder successfully deleted." in VAR_8.data def FUNC_20(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post("/folders/delete", data={"dir_name": "testing"}) assert VAR_8.status_code == 404 def FUNC_21(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.get("/bookmarklet") assert VAR_8.status_code == 200 def FUNC_22( VAR_0, VAR_1: FlaskClient, VAR_2, VAR_4 ): VAR_0.config["SEARCH_CONF"]["enabled"] = 1 VAR_0.config["SEARCH_CONF"]["engine"] = "ripgrep" VAR_8 = VAR_1.put( f"/api/dataobjs/{VAR_2.id}", json={"content": f"[[{VAR_4.title}|{VAR_4.id}]]"}, ) assert VAR_8.status_code == 200 VAR_8 = VAR_1.get(f"/dataobj/{VAR_4.id}") assert b"Backlinks" in VAR_8.data # backlink was detected VAR_0.config["SEARCH_CONF"]["enabled"] = 0 def FUNC_23(VAR_0, VAR_1, VAR_3): VAR_15 = "a" * 300 assert os.pathconf("/", "PC_NAME_MAX") < len(VAR_15) VAR_3.add(GET, "https://example.com", f"<title>{VAR_15}</title>") VAR_9 = { "url": "https://example.com", "submit": "true", } VAR_8 = VAR_1.post("/bookmarks/new", data=VAR_9) assert VAR_8.status_code == 200 def FUNC_24(VAR_0, VAR_2, VAR_1): create_dir("random") VAR_8 = VAR_1.post( "/dataobj/move/1", data={"path": "random", "submit": "true"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert b"Data successfully moved to random." in VAR_8.data assert get_item(1)["dir"] == "random" def FUNC_25(VAR_0, VAR_2, VAR_1): VAR_8 = VAR_1.post("/dataobj/move/1", follow_redirects=True) assert b"No path specified." in VAR_8.data VAR_8 = VAR_1.post( "/dataobj/move/2", data={"path": "aaa", "submit": "true"}, follow_redirects=True ) assert b"Data not found" in VAR_8.data VAR_8 = VAR_1.post( "/dataobj/move/1", data={"path": "", "submit": "true"}, follow_redirects=True ) assert b"Data already in target directory" in VAR_8.data VAR_16 = ["../adarnad", "~/adasd", "ssss"] for p in VAR_16: VAR_8 = VAR_1.post( "/dataobj/move/1", data={"path": p, "submit": "true"}, follow_redirects=True ) assert b"Data could not be moved to " + bytes(p, "utf-8") in VAR_8.data def FUNC_26(VAR_0, VAR_1): create_dir("random") VAR_8 = VAR_1.post( "/folders/rename", data={"current_path": "random", "new_name": "renamed_random"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert b"Renamed successfully" in VAR_8.data def FUNC_27(VAR_0, VAR_1): create_dir("random") create_dir("random2") VAR_8 = VAR_1.post( "/folders/rename", data={"current_path": "inexisting", "new_name": "random3"}, follow_redirects=True, ) assert b"Directory not found" in VAR_8.data VAR_8 = VAR_1.post( "/folders/rename", data={"current_path": "random", "new_name": "random2"}, follow_redirects=True, ) assert b"Target directory exists." in VAR_8.data VAR_16 = ["../adarnad", "~/adasd", "/illegal_dir", "."] for p in VAR_16: print(p) VAR_8 = VAR_1.post( "/folders/rename", data={"current_path": "random", "new_name": p}, follow_redirects=True, ) assert b"Invalid input" in VAR_8.data def FUNC_28(VAR_0, VAR_1): VAR_8 = VAR_1.get("/config") assert VAR_8.status_code == 200 assert b"Edit Config" in VAR_8.data def FUNC_29(VAR_0, VAR_1): VAR_17 = VAR_0.config["THEME_CONF"]["use_theme_dark"] VAR_8 = VAR_1.post( "/config", data={"submit": True, "THEME_CONF-use_theme_dark": not VAR_17} ) assert VAR_0.config["THEME_CONF"]["use_theme_dark"] == (not VAR_17) def FUNC_30(VAR_0, VAR_1, VAR_4): VAR_8 = VAR_1.get("/tags") VAR_18 = ["embedded-tag", "tag2"] assert VAR_8.status_code == 200 for tag in VAR_18: assert f"#{tag}" in str(VAR_8.data) def FUNC_31(VAR_0, VAR_1, VAR_4): VAR_8 = VAR_1.get("/tags/tag2") assert VAR_8.status_code == 200 assert VAR_4.title in str(VAR_8.data) assert str(VAR_4.id) in str(VAR_8.data)
import os import re from flask.testing import FlaskClient from flask import request from flask_login import current_user from responses import RequestsMock, GET from werkzeug.security import generate_password_hash from archivy.helpers import get_max_id, get_db from archivy.data import get_dirs, create_dir, get_items, get_item def FUNC_0(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.get("/") assert VAR_5.status_code == 200 def FUNC_1(VAR_0, VAR_1: FlaskClient): VAR_0.config["THEME_CONF"]["use_custom_css"] = True VAR_6 = "custom.css" VAR_7 = """ body { color: red } """ os.mkdir(f"{VAR_0.config['USER_DIR']}/css/") with open(f"{VAR_0.config['USER_DIR']}/css/{VAR_6}", "w") as f: f.write(VAR_7) VAR_0.config["THEME_CONF"]["custom_css_file"] = VAR_6 VAR_8 = VAR_1.get("/static/custom.css") assert VAR_7.encode("utf-8") in VAR_8.data VAR_0.config["THEME_CONF"]["use_custom_css"] = False def FUNC_2(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.get("/bookmarks/new") assert VAR_5.status_code == 200 def FUNC_3(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.post("/bookmarks/new", data={"submit": True}) assert VAR_5.status_code == 200 assert b"This field is required" in VAR_5.data def FUNC_4(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.get("/notes/new") assert VAR_5.status_code == 200 def FUNC_5(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.get("/dataobj/1") assert VAR_5.status_code == 302 def FUNC_6(VAR_0, VAR_1: FlaskClient, VAR_2): VAR_5 = VAR_1.get("/dataobj/1") assert VAR_5.status_code == 200 def FUNC_7(VAR_0, VAR_1: FlaskClient): VAR_5 = VAR_1.post("/dataobj/delete/1") assert VAR_5.status_code == 302 def FUNC_8(VAR_0, VAR_1: FlaskClient, VAR_2): VAR_5 = VAR_1.post("/dataobj/delete/1") assert VAR_5.status_code == 302 def FUNC_9( VAR_0, VAR_1: FlaskClient, VAR_3: RequestsMock ): VAR_3.add( GET, "https://example.com/", body="""<html> <head><title>Random</title></head><body><p> Lorem ipsum dolor sit amet, consectetur adipiscing elit </p></body></html> """, ) VAR_9 = { "url": "https://example.com", "tags": "testing,bookmark", "path": "", "submit": "true", } VAR_8 = VAR_1.post("/bookmarks/new", data=VAR_9) assert VAR_8.status_code == 302 assert not b"invalid" in VAR_8.data VAR_8 = VAR_1.post("/bookmarks/new", data=VAR_9, follow_redirects=True) assert VAR_8.status_code == 200 assert b'<span class="post-tag">VAR_11</span>' in VAR_8.data assert b'<span class="post-tag">testing</span>' in VAR_8.data assert b"https://example.com" in VAR_8.data assert b"Random" in VAR_8.data def FUNC_10( VAR_0, VAR_1, VAR_3 ): VAR_3.add(GET, "http://example.org", body="Example\n") VAR_10 = "bookmarks" VAR_0.config["DEFAULT_BOOKMARKS_DIR"] = VAR_10 create_dir(VAR_10) VAR_8 = VAR_1.post( "/bookmarks/new", data={ "url": "http://example.org", "submit": "true", }, ) VAR_11 = get_items(structured=False)[0] assert ( "bookmarks" in VAR_11["path"] ) # verify it was saved to default VAR_11 dir def FUNC_11(VAR_0, VAR_1: FlaskClient): VAR_12 = { "title": "Testing the create route", "tags": "testing,note", "path": "", "submit": "true", } VAR_8 = VAR_1.post("/notes/new", data=VAR_12) assert VAR_8.status_code == 302 assert not b"invalid" in VAR_8.data VAR_8 = VAR_1.post("/notes/new", data=VAR_12, follow_redirects=True) assert VAR_8.status_code == 200 assert b'<span class="post-tag">note</span>' in VAR_8.data assert b'<span class="post-tag">testing</span>' in VAR_8.data assert b"Testing the create route" in VAR_8.data def FUNC_12(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post( "/login", data={"username": "halcyon", "password": "password"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert request.path == "/" assert current_user def FUNC_13(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post( "/login", data={"username": "invalid", "password": "dasdasd"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert request.path == "/login" assert b"Invalid credentials" in VAR_8.data def FUNC_14(VAR_0, VAR_1: FlaskClient): VAR_13 = "new_halcyon" VAR_14 = "password2" VAR_8 = VAR_1.post( "/user/edit", data={"username": VAR_13, "password": VAR_14}, follow_redirects=True, ) assert request.path == "/" VAR_1.delete("/logout") VAR_8 = VAR_1.post( "/login", data={"username": VAR_13, "password": VAR_14}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert request.path == "/" def FUNC_15(VAR_0, VAR_1: FlaskClient): VAR_1.delete("/logout") VAR_8 = VAR_1.get("/", follow_redirects=True) assert request.path == "/login" def FUNC_16(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post( "/folders/create", data={"parent_dir": "", "new_dir": "testing"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert request.args.get("path") == "testing" assert "testing" in get_dirs() assert b"Folder successfully created" in VAR_8.data def FUNC_17(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post( "/folders/create", data={"parent_dir": ""}, follow_redirects=True ) assert VAR_8.status_code == 200 assert request.path == "/" assert b"Could not create folder." in VAR_8.data def FUNC_18(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.get("/?path=nonexistent_dir", follow_redirects=True) assert b"Directory does not exist." in VAR_8.data def FUNC_19(VAR_0, VAR_1: FlaskClient): create_dir("testing") assert "testing" in get_dirs() VAR_8 = VAR_1.post( "/folders/delete", data={"dir_name": "testing"}, follow_redirects=True ) assert not "testing" in get_dirs() assert b"Folder successfully deleted." in VAR_8.data def FUNC_20(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.post("/folders/delete", data={"dir_name": "testing"}) assert VAR_8.status_code == 404 def FUNC_21(VAR_0, VAR_1: FlaskClient): VAR_8 = VAR_1.get("/bookmarklet") assert VAR_8.status_code == 200 def FUNC_22( VAR_0, VAR_1: FlaskClient, VAR_2, VAR_4 ): VAR_0.config["SEARCH_CONF"]["enabled"] = 1 VAR_0.config["SEARCH_CONF"]["engine"] = "ripgrep" VAR_8 = VAR_1.put( f"/api/dataobjs/{VAR_2.id}", json={"content": f"[[{VAR_4.title}|{VAR_4.id}]]"}, ) assert VAR_8.status_code == 200 VAR_8 = VAR_1.get(f"/dataobj/{VAR_4.id}") assert b"Backlinks" in VAR_8.data # backlink was detected VAR_0.config["SEARCH_CONF"]["enabled"] = 0 def FUNC_23(VAR_0, VAR_1, VAR_3): VAR_15 = "a" * 300 assert os.pathconf("/", "PC_NAME_MAX") < len(VAR_15) VAR_3.add(GET, "https://example.com", f"<title>{VAR_15}</title>") VAR_9 = { "url": "https://example.com", "submit": "true", } VAR_8 = VAR_1.post("/bookmarks/new", data=VAR_9) assert VAR_8.status_code == 200 def FUNC_24(VAR_0, VAR_2, VAR_1): create_dir("random") VAR_8 = VAR_1.post( "/dataobj/move/1", data={"path": "random", "submit": "true"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert b"Data successfully moved to random." in VAR_8.data assert get_item(1)["dir"] == "random" def FUNC_25(VAR_0, VAR_2, VAR_1): VAR_8 = VAR_1.post("/dataobj/move/1", follow_redirects=True) assert b"No path specified." in VAR_8.data VAR_8 = VAR_1.post( "/dataobj/move/2", data={"path": "aaa", "submit": "true"}, follow_redirects=True ) assert b"Data not found" in VAR_8.data VAR_8 = VAR_1.post( "/dataobj/move/1", data={"path": "", "submit": "true"}, follow_redirects=True ) assert b"Data already in target directory" in VAR_8.data VAR_16 = ["../adarnad", "~/adasd", "ssss"] for p in VAR_16: VAR_8 = VAR_1.post( "/dataobj/move/1", data={"path": p, "submit": "true"}, follow_redirects=True ) assert b"Data could not be moved to " + bytes(p, "utf-8") in VAR_8.data def FUNC_26(VAR_0, VAR_1): create_dir("random") VAR_8 = VAR_1.post( "/folders/rename", data={"current_path": "random", "new_name": "renamed_random"}, follow_redirects=True, ) assert VAR_8.status_code == 200 assert b"Renamed successfully" in VAR_8.data def FUNC_27(VAR_0, VAR_1): create_dir("random") create_dir("random2") VAR_8 = VAR_1.post( "/folders/rename", data={"current_path": "inexisting", "new_name": "random3"}, follow_redirects=True, ) assert b"Directory not found" in VAR_8.data VAR_8 = VAR_1.post( "/folders/rename", data={"current_path": "random", "new_name": "random2"}, follow_redirects=True, ) assert b"Target directory exists." in VAR_8.data VAR_16 = ["../adarnad", "~/adasd", "/illegal_dir", "."] for p in VAR_16: print(p) VAR_8 = VAR_1.post( "/folders/rename", data={"current_path": "random", "new_name": p}, follow_redirects=True, ) assert b"Invalid input" in VAR_8.data def FUNC_28(VAR_0, VAR_1): VAR_8 = VAR_1.get("/config") assert VAR_8.status_code == 200 assert b"Edit Config" in VAR_8.data def FUNC_29(VAR_0, VAR_1): VAR_17 = VAR_0.config["THEME_CONF"]["use_theme_dark"] VAR_8 = VAR_1.post( "/config", data={"submit": True, "THEME_CONF-use_theme_dark": not VAR_17} ) assert VAR_0.config["THEME_CONF"]["use_theme_dark"] == (not VAR_17) def FUNC_30(VAR_0, VAR_1, VAR_4): VAR_8 = VAR_1.get("/tags") VAR_18 = ["embedded-tag", "tag2"] assert VAR_8.status_code == 200 for tag in VAR_18: assert f"#{tag}" in str(VAR_8.data) def FUNC_31(VAR_0, VAR_1, VAR_4): VAR_8 = VAR_1.get("/tags/tag2") assert VAR_8.status_code == 200 assert VAR_4.title in str(VAR_8.data) assert str(VAR_4.id) in str(VAR_8.data)
[ 3, 9, 12, 13, 17, 18, 27, 35, 36, 40, 41, 46, 47, 51, 52, 56, 57, 61, 62, 66, 67, 71, 72, 85, 92, 96, 103, 104, 123, 124, 126, 133, 137, 143, 144, 154, 155, 165, 166, 169, 177, 179, 181, 189, 190, 191, 194, 196, 199, 200, 203, 209, 214, 215, 220, 224, 225, 229, 230, 239, 240, 244, 245, 249, 250, 256, 262, 266, 267, 269, 271, 272, 279, 282, 283, 286, 294, 296, 297, 299, 302, 307, 312, 319, 320, 323, 331, 332, 342, 349, 359, 360, 365, 366, 368, 370, 375, 376, 378, 384, 385, 391, 168, 193, 202 ]
[ 3, 9, 12, 13, 17, 18, 27, 35, 36, 40, 41, 46, 47, 51, 52, 56, 57, 61, 62, 66, 67, 71, 72, 85, 92, 96, 103, 104, 123, 124, 126, 133, 137, 143, 144, 154, 155, 165, 166, 169, 177, 179, 181, 189, 190, 191, 194, 196, 199, 200, 203, 209, 214, 215, 220, 224, 225, 229, 230, 239, 240, 244, 245, 249, 250, 256, 262, 266, 267, 269, 271, 272, 279, 282, 283, 286, 294, 296, 297, 299, 302, 307, 312, 319, 320, 323, 331, 332, 342, 349, 359, 360, 365, 366, 368, 370, 375, 376, 378, 384, 385, 391, 168, 193, 202 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2016 OpenMarket Ltd # Copyright 2018 New Vector Ltd # Copyright 2020 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import synapse.api.errors import synapse.handlers.device import synapse.storage from tests import unittest user1 = "@boris:aaa" user2 = "@theresa:bbb" class DeviceTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver("server", http_client=None) self.handler = hs.get_device_handler() self.store = hs.get_datastore() return hs def prepare(self, reactor, clock, hs): # These tests assume that it starts 1000 seconds in. self.reactor.advance(1000) def test_device_is_created_with_invalid_name(self): self.get_failure( self.handler.check_device_registered( user_id="@boris:foo", device_id="foo", initial_device_display_name="a" * (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1), ), synapse.api.errors.SynapseError, ) def test_device_is_created_if_doesnt_exist(self): res = self.get_success( self.handler.check_device_registered( user_id="@boris:foo", device_id="fco", initial_device_display_name="display name", ) ) self.assertEqual(res, "fco") dev = self.get_success(self.handler.store.get_device("@boris:foo", "fco")) self.assertEqual(dev["display_name"], "display name") def test_device_is_preserved_if_exists(self): res1 = self.get_success( self.handler.check_device_registered( user_id="@boris:foo", device_id="fco", initial_device_display_name="display name", ) ) self.assertEqual(res1, "fco") res2 = self.get_success( self.handler.check_device_registered( user_id="@boris:foo", device_id="fco", initial_device_display_name="new display name", ) ) self.assertEqual(res2, "fco") dev = self.get_success(self.handler.store.get_device("@boris:foo", "fco")) self.assertEqual(dev["display_name"], "display name") def test_device_id_is_made_up_if_unspecified(self): device_id = self.get_success( self.handler.check_device_registered( user_id="@theresa:foo", device_id=None, initial_device_display_name="display", ) ) dev = self.get_success(self.handler.store.get_device("@theresa:foo", device_id)) self.assertEqual(dev["display_name"], "display") def test_get_devices_by_user(self): self._record_users() res = self.get_success(self.handler.get_devices_by_user(user1)) self.assertEqual(3, len(res)) device_map = {d["device_id"]: d for d in res} self.assertDictContainsSubset( { "user_id": user1, "device_id": "xyz", "display_name": "display 0", "last_seen_ip": None, "last_seen_ts": None, }, device_map["xyz"], ) self.assertDictContainsSubset( { "user_id": user1, "device_id": "fco", "display_name": "display 1", "last_seen_ip": "ip1", "last_seen_ts": 1000000, }, device_map["fco"], ) self.assertDictContainsSubset( { "user_id": user1, "device_id": "abc", "display_name": "display 2", "last_seen_ip": "ip3", "last_seen_ts": 3000000, }, device_map["abc"], ) def test_get_device(self): self._record_users() res = self.get_success(self.handler.get_device(user1, "abc")) self.assertDictContainsSubset( { "user_id": user1, "device_id": "abc", "display_name": "display 2", "last_seen_ip": "ip3", "last_seen_ts": 3000000, }, res, ) def test_delete_device(self): self._record_users() # delete the device self.get_success(self.handler.delete_device(user1, "abc")) # check the device was deleted self.get_failure( self.handler.get_device(user1, "abc"), synapse.api.errors.NotFoundError ) # we'd like to check the access token was invalidated, but that's a # bit of a PITA. def test_update_device(self): self._record_users() update = {"display_name": "new display"} self.get_success(self.handler.update_device(user1, "abc", update)) res = self.get_success(self.handler.get_device(user1, "abc")) self.assertEqual(res["display_name"], "new display") def test_update_device_too_long_display_name(self): """Update a device with a display name that is invalid (too long).""" self._record_users() # Request to update a device display name with a new value that is longer than allowed. update = { "display_name": "a" * (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1) } self.get_failure( self.handler.update_device(user1, "abc", update), synapse.api.errors.SynapseError, ) # Ensure the display name was not updated. res = self.get_success(self.handler.get_device(user1, "abc")) self.assertEqual(res["display_name"], "display 2") def test_update_unknown_device(self): update = {"display_name": "new_display"} self.get_failure( self.handler.update_device("user_id", "unknown_device_id", update), synapse.api.errors.NotFoundError, ) def _record_users(self): # check this works for both devices which have a recorded client_ip, # and those which don't. self._record_user(user1, "xyz", "display 0") self._record_user(user1, "fco", "display 1", "token1", "ip1") self._record_user(user1, "abc", "display 2", "token2", "ip2") self._record_user(user1, "abc", "display 2", "token3", "ip3") self._record_user(user2, "def", "dispkay", "token4", "ip4") self.reactor.advance(10000) def _record_user( self, user_id, device_id, display_name, access_token=None, ip=None ): device_id = self.get_success( self.handler.check_device_registered( user_id=user_id, device_id=device_id, initial_device_display_name=display_name, ) ) if ip is not None: self.get_success( self.store.insert_client_ip( user_id, access_token, ip, "user_agent", device_id ) ) self.reactor.advance(1000) class DehydrationTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver("server", http_client=None) self.handler = hs.get_device_handler() self.registration = hs.get_registration_handler() self.auth = hs.get_auth() self.store = hs.get_datastore() return hs def test_dehydrate_and_rehydrate_device(self): user_id = "@boris:dehydration" self.get_success(self.store.register_user(user_id, "foobar")) # First check if we can store and fetch a dehydrated device stored_dehydrated_device_id = self.get_success( self.handler.store_dehydrated_device( user_id=user_id, device_data={"device_data": {"foo": "bar"}}, initial_device_display_name="dehydrated device", ) ) retrieved_device_id, device_data = self.get_success( self.handler.get_dehydrated_device(user_id=user_id) ) self.assertEqual(retrieved_device_id, stored_dehydrated_device_id) self.assertEqual(device_data, {"device_data": {"foo": "bar"}}) # Create a new login for the user and dehydrated the device device_id, access_token = self.get_success( self.registration.register_device( user_id=user_id, device_id=None, initial_display_name="new device", ) ) # Trying to claim a nonexistent device should throw an error self.get_failure( self.handler.rehydrate_device( user_id=user_id, access_token=access_token, device_id="not the right device ID", ), synapse.api.errors.NotFoundError, ) # dehydrating the right devices should succeed and change our device ID # to the dehydrated device's ID res = self.get_success( self.handler.rehydrate_device( user_id=user_id, access_token=access_token, device_id=retrieved_device_id, ) ) self.assertEqual(res, {"success": True}) # make sure that our device ID has changed user_info = self.get_success(self.auth.get_user_by_access_token(access_token)) self.assertEqual(user_info.device_id, retrieved_device_id) # make sure the device has the display name that was set from the login res = self.get_success(self.handler.get_device(user_id, retrieved_device_id)) self.assertEqual(res["display_name"], "new device") # make sure that the device ID that we were initially assigned no longer exists self.get_failure( self.handler.get_device(user_id, device_id), synapse.api.errors.NotFoundError, ) # make sure that there's no device available for dehydrating now ret = self.get_success(self.handler.get_dehydrated_device(user_id=user_id)) self.assertIsNone(ret)
# -*- coding: utf-8 -*- # Copyright 2016 OpenMarket Ltd # Copyright 2018 New Vector Ltd # Copyright 2020 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import synapse.api.errors import synapse.handlers.device import synapse.storage from tests import unittest user1 = "@boris:aaa" user2 = "@theresa:bbb" class DeviceTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver("server", federation_http_client=None) self.handler = hs.get_device_handler() self.store = hs.get_datastore() return hs def prepare(self, reactor, clock, hs): # These tests assume that it starts 1000 seconds in. self.reactor.advance(1000) def test_device_is_created_with_invalid_name(self): self.get_failure( self.handler.check_device_registered( user_id="@boris:foo", device_id="foo", initial_device_display_name="a" * (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1), ), synapse.api.errors.SynapseError, ) def test_device_is_created_if_doesnt_exist(self): res = self.get_success( self.handler.check_device_registered( user_id="@boris:foo", device_id="fco", initial_device_display_name="display name", ) ) self.assertEqual(res, "fco") dev = self.get_success(self.handler.store.get_device("@boris:foo", "fco")) self.assertEqual(dev["display_name"], "display name") def test_device_is_preserved_if_exists(self): res1 = self.get_success( self.handler.check_device_registered( user_id="@boris:foo", device_id="fco", initial_device_display_name="display name", ) ) self.assertEqual(res1, "fco") res2 = self.get_success( self.handler.check_device_registered( user_id="@boris:foo", device_id="fco", initial_device_display_name="new display name", ) ) self.assertEqual(res2, "fco") dev = self.get_success(self.handler.store.get_device("@boris:foo", "fco")) self.assertEqual(dev["display_name"], "display name") def test_device_id_is_made_up_if_unspecified(self): device_id = self.get_success( self.handler.check_device_registered( user_id="@theresa:foo", device_id=None, initial_device_display_name="display", ) ) dev = self.get_success(self.handler.store.get_device("@theresa:foo", device_id)) self.assertEqual(dev["display_name"], "display") def test_get_devices_by_user(self): self._record_users() res = self.get_success(self.handler.get_devices_by_user(user1)) self.assertEqual(3, len(res)) device_map = {d["device_id"]: d for d in res} self.assertDictContainsSubset( { "user_id": user1, "device_id": "xyz", "display_name": "display 0", "last_seen_ip": None, "last_seen_ts": None, }, device_map["xyz"], ) self.assertDictContainsSubset( { "user_id": user1, "device_id": "fco", "display_name": "display 1", "last_seen_ip": "ip1", "last_seen_ts": 1000000, }, device_map["fco"], ) self.assertDictContainsSubset( { "user_id": user1, "device_id": "abc", "display_name": "display 2", "last_seen_ip": "ip3", "last_seen_ts": 3000000, }, device_map["abc"], ) def test_get_device(self): self._record_users() res = self.get_success(self.handler.get_device(user1, "abc")) self.assertDictContainsSubset( { "user_id": user1, "device_id": "abc", "display_name": "display 2", "last_seen_ip": "ip3", "last_seen_ts": 3000000, }, res, ) def test_delete_device(self): self._record_users() # delete the device self.get_success(self.handler.delete_device(user1, "abc")) # check the device was deleted self.get_failure( self.handler.get_device(user1, "abc"), synapse.api.errors.NotFoundError ) # we'd like to check the access token was invalidated, but that's a # bit of a PITA. def test_update_device(self): self._record_users() update = {"display_name": "new display"} self.get_success(self.handler.update_device(user1, "abc", update)) res = self.get_success(self.handler.get_device(user1, "abc")) self.assertEqual(res["display_name"], "new display") def test_update_device_too_long_display_name(self): """Update a device with a display name that is invalid (too long).""" self._record_users() # Request to update a device display name with a new value that is longer than allowed. update = { "display_name": "a" * (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1) } self.get_failure( self.handler.update_device(user1, "abc", update), synapse.api.errors.SynapseError, ) # Ensure the display name was not updated. res = self.get_success(self.handler.get_device(user1, "abc")) self.assertEqual(res["display_name"], "display 2") def test_update_unknown_device(self): update = {"display_name": "new_display"} self.get_failure( self.handler.update_device("user_id", "unknown_device_id", update), synapse.api.errors.NotFoundError, ) def _record_users(self): # check this works for both devices which have a recorded client_ip, # and those which don't. self._record_user(user1, "xyz", "display 0") self._record_user(user1, "fco", "display 1", "token1", "ip1") self._record_user(user1, "abc", "display 2", "token2", "ip2") self._record_user(user1, "abc", "display 2", "token3", "ip3") self._record_user(user2, "def", "dispkay", "token4", "ip4") self.reactor.advance(10000) def _record_user( self, user_id, device_id, display_name, access_token=None, ip=None ): device_id = self.get_success( self.handler.check_device_registered( user_id=user_id, device_id=device_id, initial_device_display_name=display_name, ) ) if ip is not None: self.get_success( self.store.insert_client_ip( user_id, access_token, ip, "user_agent", device_id ) ) self.reactor.advance(1000) class DehydrationTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver("server", federation_http_client=None) self.handler = hs.get_device_handler() self.registration = hs.get_registration_handler() self.auth = hs.get_auth() self.store = hs.get_datastore() return hs def test_dehydrate_and_rehydrate_device(self): user_id = "@boris:dehydration" self.get_success(self.store.register_user(user_id, "foobar")) # First check if we can store and fetch a dehydrated device stored_dehydrated_device_id = self.get_success( self.handler.store_dehydrated_device( user_id=user_id, device_data={"device_data": {"foo": "bar"}}, initial_device_display_name="dehydrated device", ) ) retrieved_device_id, device_data = self.get_success( self.handler.get_dehydrated_device(user_id=user_id) ) self.assertEqual(retrieved_device_id, stored_dehydrated_device_id) self.assertEqual(device_data, {"device_data": {"foo": "bar"}}) # Create a new login for the user and dehydrated the device device_id, access_token = self.get_success( self.registration.register_device( user_id=user_id, device_id=None, initial_display_name="new device", ) ) # Trying to claim a nonexistent device should throw an error self.get_failure( self.handler.rehydrate_device( user_id=user_id, access_token=access_token, device_id="not the right device ID", ), synapse.api.errors.NotFoundError, ) # dehydrating the right devices should succeed and change our device ID # to the dehydrated device's ID res = self.get_success( self.handler.rehydrate_device( user_id=user_id, access_token=access_token, device_id=retrieved_device_id, ) ) self.assertEqual(res, {"success": True}) # make sure that our device ID has changed user_info = self.get_success(self.auth.get_user_by_access_token(access_token)) self.assertEqual(user_info.device_id, retrieved_device_id) # make sure the device has the display name that was set from the login res = self.get_success(self.handler.get_device(user_id, retrieved_device_id)) self.assertEqual(res["display_name"], "new device") # make sure that the device ID that we were initially assigned no longer exists self.get_failure( self.handler.get_device(user_id, device_id), synapse.api.errors.NotFoundError, ) # make sure that there's no device available for dehydrating now ret = self.get_success(self.handler.get_dehydrated_device(user_id=user_id)) self.assertIsNone(ret)
open_redirect
{ "code": [ " hs = self.setup_test_homeserver(\"server\", http_client=None)", " hs = self.setup_test_homeserver(\"server\", http_client=None)" ], "line_no": [ 30, 232 ] }
{ "code": [ " hs = self.setup_test_homeserver(\"server\", federation_http_client=None)", " hs = self.setup_test_homeserver(\"server\", federation_http_client=None)" ], "line_no": [ 30, 232 ] }
import synapse.api.errors import synapse.handlers.device import synapse.storage from tests import unittest VAR_0 = "@boris:aaa" VAR_1 = "@theresa:bbb" class CLASS_0(unittest.HomeserverTestCase): def FUNC_0(self, VAR_2, VAR_3): VAR_4 = self.setup_test_homeserver("server", http_client=None) self.handler = VAR_4.get_device_handler() self.store = VAR_4.get_datastore() return VAR_4 def FUNC_1(self, VAR_2, VAR_3, VAR_4): self.reactor.advance(1000) def FUNC_2(self): self.get_failure( self.handler.check_device_registered( VAR_5="@boris:foo", VAR_6="foo", initial_device_display_name="a" * (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1), ), synapse.api.errors.SynapseError, ) def FUNC_3(self): VAR_10 = self.get_success( self.handler.check_device_registered( VAR_5="@boris:foo", VAR_6="fco", initial_device_display_name="display name", ) ) self.assertEqual(VAR_10, "fco") VAR_11 = self.get_success(self.handler.store.get_device("@boris:foo", "fco")) self.assertEqual(VAR_11["display_name"], "display name") def FUNC_4(self): VAR_12 = self.get_success( self.handler.check_device_registered( VAR_5="@boris:foo", VAR_6="fco", initial_device_display_name="display name", ) ) self.assertEqual(VAR_12, "fco") VAR_13 = self.get_success( self.handler.check_device_registered( VAR_5="@boris:foo", VAR_6="fco", initial_device_display_name="new display name", ) ) self.assertEqual(VAR_13, "fco") VAR_11 = self.get_success(self.handler.store.get_device("@boris:foo", "fco")) self.assertEqual(VAR_11["display_name"], "display name") def FUNC_5(self): VAR_6 = self.get_success( self.handler.check_device_registered( VAR_5="@theresa:foo", VAR_6=None, initial_device_display_name="display", ) ) VAR_11 = self.get_success(self.handler.store.get_device("@theresa:foo", VAR_6)) self.assertEqual(VAR_11["display_name"], "display") def FUNC_6(self): self._record_users() VAR_10 = self.get_success(self.handler.get_devices_by_user(VAR_0)) self.assertEqual(3, len(VAR_10)) VAR_14 = {d["device_id"]: d for d in VAR_10} self.assertDictContainsSubset( { "user_id": VAR_0, "device_id": "xyz", "display_name": "display 0", "last_seen_ip": None, "last_seen_ts": None, }, VAR_14["xyz"], ) self.assertDictContainsSubset( { "user_id": VAR_0, "device_id": "fco", "display_name": "display 1", "last_seen_ip": "ip1", "last_seen_ts": 1000000, }, VAR_14["fco"], ) self.assertDictContainsSubset( { "user_id": VAR_0, "device_id": "abc", "display_name": "display 2", "last_seen_ip": "ip3", "last_seen_ts": 3000000, }, VAR_14["abc"], ) def FUNC_7(self): self._record_users() VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc")) self.assertDictContainsSubset( { "user_id": VAR_0, "device_id": "abc", "display_name": "display 2", "last_seen_ip": "ip3", "last_seen_ts": 3000000, }, VAR_10, ) def FUNC_8(self): self._record_users() self.get_success(self.handler.delete_device(VAR_0, "abc")) self.get_failure( self.handler.get_device(VAR_0, "abc"), synapse.api.errors.NotFoundError ) def FUNC_9(self): self._record_users() VAR_15 = {"display_name": "new display"} self.get_success(self.handler.update_device(VAR_0, "abc", VAR_15)) VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc")) self.assertEqual(VAR_10["display_name"], "new display") def FUNC_10(self): self._record_users() VAR_15 = { "display_name": "a" * (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1) } self.get_failure( self.handler.update_device(VAR_0, "abc", VAR_15), synapse.api.errors.SynapseError, ) VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc")) self.assertEqual(VAR_10["display_name"], "display 2") def FUNC_11(self): VAR_15 = {"display_name": "new_display"} self.get_failure( self.handler.update_device("user_id", "unknown_device_id", VAR_15), synapse.api.errors.NotFoundError, ) def FUNC_12(self): self._record_user(VAR_0, "xyz", "display 0") self._record_user(VAR_0, "fco", "display 1", "token1", "ip1") self._record_user(VAR_0, "abc", "display 2", "token2", "ip2") self._record_user(VAR_0, "abc", "display 2", "token3", "ip3") self._record_user(VAR_1, "def", "dispkay", "token4", "ip4") self.reactor.advance(10000) def FUNC_13( self, VAR_5, VAR_6, VAR_7, VAR_8=None, VAR_9=None ): VAR_6 = self.get_success( self.handler.check_device_registered( VAR_5=user_id, VAR_6=device_id, initial_device_display_name=VAR_7, ) ) if VAR_9 is not None: self.get_success( self.store.insert_client_ip( VAR_5, VAR_8, VAR_9, "user_agent", VAR_6 ) ) self.reactor.advance(1000) class CLASS_1(unittest.HomeserverTestCase): def FUNC_0(self, VAR_2, VAR_3): VAR_4 = self.setup_test_homeserver("server", http_client=None) self.handler = VAR_4.get_device_handler() self.registration = VAR_4.get_registration_handler() self.auth = VAR_4.get_auth() self.store = VAR_4.get_datastore() return VAR_4 def FUNC_14(self): VAR_5 = "@boris:dehydration" self.get_success(self.store.register_user(VAR_5, "foobar")) VAR_16 = self.get_success( self.handler.store_dehydrated_device( VAR_5=user_id, VAR_18={"device_data": {"foo": "bar"}}, initial_device_display_name="dehydrated device", ) ) VAR_17, VAR_18 = self.get_success( self.handler.get_dehydrated_device(VAR_5=user_id) ) self.assertEqual(VAR_17, VAR_16) self.assertEqual(VAR_18, {"device_data": {"foo": "bar"}}) VAR_6, VAR_8 = self.get_success( self.registration.register_device( VAR_5=user_id, VAR_6=None, initial_display_name="new device", ) ) self.get_failure( self.handler.rehydrate_device( VAR_5=user_id, VAR_8=access_token, VAR_6="not the right device ID", ), synapse.api.errors.NotFoundError, ) VAR_10 = self.get_success( self.handler.rehydrate_device( VAR_5=user_id, VAR_8=access_token, VAR_6=VAR_17, ) ) self.assertEqual(VAR_10, {"success": True}) VAR_19 = self.get_success(self.auth.get_user_by_access_token(VAR_8)) self.assertEqual(VAR_19.device_id, VAR_17) VAR_10 = self.get_success(self.handler.get_device(VAR_5, VAR_17)) self.assertEqual(VAR_10["display_name"], "new device") self.get_failure( self.handler.get_device(VAR_5, VAR_6), synapse.api.errors.NotFoundError, ) VAR_20 = self.get_success(self.handler.get_dehydrated_device(VAR_5=user_id)) self.assertIsNone(VAR_20)
import synapse.api.errors import synapse.handlers.device import synapse.storage from tests import unittest VAR_0 = "@boris:aaa" VAR_1 = "@theresa:bbb" class CLASS_0(unittest.HomeserverTestCase): def FUNC_0(self, VAR_2, VAR_3): VAR_4 = self.setup_test_homeserver("server", federation_http_client=None) self.handler = VAR_4.get_device_handler() self.store = VAR_4.get_datastore() return VAR_4 def FUNC_1(self, VAR_2, VAR_3, VAR_4): self.reactor.advance(1000) def FUNC_2(self): self.get_failure( self.handler.check_device_registered( VAR_5="@boris:foo", VAR_6="foo", initial_device_display_name="a" * (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1), ), synapse.api.errors.SynapseError, ) def FUNC_3(self): VAR_10 = self.get_success( self.handler.check_device_registered( VAR_5="@boris:foo", VAR_6="fco", initial_device_display_name="display name", ) ) self.assertEqual(VAR_10, "fco") VAR_11 = self.get_success(self.handler.store.get_device("@boris:foo", "fco")) self.assertEqual(VAR_11["display_name"], "display name") def FUNC_4(self): VAR_12 = self.get_success( self.handler.check_device_registered( VAR_5="@boris:foo", VAR_6="fco", initial_device_display_name="display name", ) ) self.assertEqual(VAR_12, "fco") VAR_13 = self.get_success( self.handler.check_device_registered( VAR_5="@boris:foo", VAR_6="fco", initial_device_display_name="new display name", ) ) self.assertEqual(VAR_13, "fco") VAR_11 = self.get_success(self.handler.store.get_device("@boris:foo", "fco")) self.assertEqual(VAR_11["display_name"], "display name") def FUNC_5(self): VAR_6 = self.get_success( self.handler.check_device_registered( VAR_5="@theresa:foo", VAR_6=None, initial_device_display_name="display", ) ) VAR_11 = self.get_success(self.handler.store.get_device("@theresa:foo", VAR_6)) self.assertEqual(VAR_11["display_name"], "display") def FUNC_6(self): self._record_users() VAR_10 = self.get_success(self.handler.get_devices_by_user(VAR_0)) self.assertEqual(3, len(VAR_10)) VAR_14 = {d["device_id"]: d for d in VAR_10} self.assertDictContainsSubset( { "user_id": VAR_0, "device_id": "xyz", "display_name": "display 0", "last_seen_ip": None, "last_seen_ts": None, }, VAR_14["xyz"], ) self.assertDictContainsSubset( { "user_id": VAR_0, "device_id": "fco", "display_name": "display 1", "last_seen_ip": "ip1", "last_seen_ts": 1000000, }, VAR_14["fco"], ) self.assertDictContainsSubset( { "user_id": VAR_0, "device_id": "abc", "display_name": "display 2", "last_seen_ip": "ip3", "last_seen_ts": 3000000, }, VAR_14["abc"], ) def FUNC_7(self): self._record_users() VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc")) self.assertDictContainsSubset( { "user_id": VAR_0, "device_id": "abc", "display_name": "display 2", "last_seen_ip": "ip3", "last_seen_ts": 3000000, }, VAR_10, ) def FUNC_8(self): self._record_users() self.get_success(self.handler.delete_device(VAR_0, "abc")) self.get_failure( self.handler.get_device(VAR_0, "abc"), synapse.api.errors.NotFoundError ) def FUNC_9(self): self._record_users() VAR_15 = {"display_name": "new display"} self.get_success(self.handler.update_device(VAR_0, "abc", VAR_15)) VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc")) self.assertEqual(VAR_10["display_name"], "new display") def FUNC_10(self): self._record_users() VAR_15 = { "display_name": "a" * (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1) } self.get_failure( self.handler.update_device(VAR_0, "abc", VAR_15), synapse.api.errors.SynapseError, ) VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc")) self.assertEqual(VAR_10["display_name"], "display 2") def FUNC_11(self): VAR_15 = {"display_name": "new_display"} self.get_failure( self.handler.update_device("user_id", "unknown_device_id", VAR_15), synapse.api.errors.NotFoundError, ) def FUNC_12(self): self._record_user(VAR_0, "xyz", "display 0") self._record_user(VAR_0, "fco", "display 1", "token1", "ip1") self._record_user(VAR_0, "abc", "display 2", "token2", "ip2") self._record_user(VAR_0, "abc", "display 2", "token3", "ip3") self._record_user(VAR_1, "def", "dispkay", "token4", "ip4") self.reactor.advance(10000) def FUNC_13( self, VAR_5, VAR_6, VAR_7, VAR_8=None, VAR_9=None ): VAR_6 = self.get_success( self.handler.check_device_registered( VAR_5=user_id, VAR_6=device_id, initial_device_display_name=VAR_7, ) ) if VAR_9 is not None: self.get_success( self.store.insert_client_ip( VAR_5, VAR_8, VAR_9, "user_agent", VAR_6 ) ) self.reactor.advance(1000) class CLASS_1(unittest.HomeserverTestCase): def FUNC_0(self, VAR_2, VAR_3): VAR_4 = self.setup_test_homeserver("server", federation_http_client=None) self.handler = VAR_4.get_device_handler() self.registration = VAR_4.get_registration_handler() self.auth = VAR_4.get_auth() self.store = VAR_4.get_datastore() return VAR_4 def FUNC_14(self): VAR_5 = "@boris:dehydration" self.get_success(self.store.register_user(VAR_5, "foobar")) VAR_16 = self.get_success( self.handler.store_dehydrated_device( VAR_5=user_id, VAR_18={"device_data": {"foo": "bar"}}, initial_device_display_name="dehydrated device", ) ) VAR_17, VAR_18 = self.get_success( self.handler.get_dehydrated_device(VAR_5=user_id) ) self.assertEqual(VAR_17, VAR_16) self.assertEqual(VAR_18, {"device_data": {"foo": "bar"}}) VAR_6, VAR_8 = self.get_success( self.registration.register_device( VAR_5=user_id, VAR_6=None, initial_display_name="new device", ) ) self.get_failure( self.handler.rehydrate_device( VAR_5=user_id, VAR_8=access_token, VAR_6="not the right device ID", ), synapse.api.errors.NotFoundError, ) VAR_10 = self.get_success( self.handler.rehydrate_device( VAR_5=user_id, VAR_8=access_token, VAR_6=VAR_17, ) ) self.assertEqual(VAR_10, {"success": True}) VAR_19 = self.get_success(self.auth.get_user_by_access_token(VAR_8)) self.assertEqual(VAR_19.device_id, VAR_17) VAR_10 = self.get_success(self.handler.get_device(VAR_5, VAR_17)) self.assertEqual(VAR_10["display_name"], "new device") self.get_failure( self.handler.get_device(VAR_5, VAR_6), synapse.api.errors.NotFoundError, ) VAR_20 = self.get_success(self.handler.get_dehydrated_device(VAR_5=user_id)) self.assertIsNone(VAR_20)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 21, 23, 26, 27, 34, 36, 38, 49, 59, 62, 72, 81, 84, 93, 96, 99, 101, 134, 137, 149, 152, 153, 155, 156, 160, 161, 162, 163, 166, 169, 172, 176, 177, 186, 187, 190, 197, 199, 200, 205, 207, 209, 220, 228, 229, 238, 241, 243, 244, 252, 256, 259, 260, 266, 267, 276, 277, 278, 286, 288, 289, 291, 293, 294, 296, 298, 299, 304, 305, 307, 309, 174 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 21, 23, 26, 27, 34, 36, 38, 49, 59, 62, 72, 81, 84, 93, 96, 99, 101, 134, 137, 149, 152, 153, 155, 156, 160, 161, 162, 163, 166, 169, 172, 176, 177, 186, 187, 190, 197, 199, 200, 205, 207, 209, 220, 228, 229, 238, 241, 243, 244, 252, 256, 259, 260, 266, 267, 276, 277, 278, 286, 288, 289, 291, 293, 294, 296, 298, 299, 304, 305, 307, 309, 174 ]
5CWE-94
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for SavedModelCLI tool.""" import contextlib import os import pickle import platform import shutil import sys from absl.testing import parameterized import numpy as np from six import StringIO from tensorflow.core.example import example_pb2 from tensorflow.core.framework import types_pb2 from tensorflow.core.protobuf import meta_graph_pb2 from tensorflow.python.debug.wrappers import local_cli_wrapper from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.lib.io import file_io from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import save from tensorflow.python.tools import saved_model_cli from tensorflow.python.training.tracking import tracking SAVED_MODEL_PATH = ('cc/saved_model/testdata/half_plus_two/00000123') @contextlib.contextmanager def captured_output(): new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err class SavedModelCLITestCase(test.TestCase, parameterized.TestCase): def setUp(self): super(SavedModelCLITestCase, self).setUp() if platform.system() == 'Windows': self.skipTest('Skipping failing tests on Windows.') def testShowCommandAll(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args(['show', '--dir', base_path, '--all']) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() # pylint: disable=line-too-long exp_out = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['classify_x2_to_y3']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: x2:0 The given SavedModel SignatureDef contains the following output(s): outputs['scores'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y3:0 Method name is: tensorflow/serving/classify signature_def['classify_x_to_y']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following output(s): outputs['scores'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y:0 Method name is: tensorflow/serving/classify signature_def['regress_x2_to_y3']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: x2:0 The given SavedModel SignatureDef contains the following output(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y3:0 Method name is: tensorflow/serving/regress signature_def['regress_x_to_y']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following output(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y:0 Method name is: tensorflow/serving/regress signature_def['regress_x_to_y2']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following output(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y2:0 Method name is: tensorflow/serving/regress signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['x'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: x:0 The given SavedModel SignatureDef contains the following output(s): outputs['y'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y:0 Method name is: tensorflow/serving/predict""" # pylint: enable=line-too-long self.maxDiff = None # Produce a useful error msg if the comparison fails self.assertMultiLineEqual(output, exp_out) self.assertEqual(err.getvalue().strip(), '') def testShowAllWithFunctions(self): class DummyModel(tracking.AutoTrackable): """Model with callable polymorphic functions specified.""" @def_function.function def func1(self, a, b, c): if c: return a + b else: return a * b @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2, 2), dtype=dtypes.float32) ]) def func2(self, x): return x + 2 @def_function.function def __call__(self, y, c=7): return y + 2 * c saved_model_dir = os.path.join(test.get_temp_dir(), 'dummy_model') dummy_model = DummyModel() # Call with specific values to create new polymorphic function traces. dummy_model.func1(constant_op.constant(5), constant_op.constant(9), True) dummy_model(constant_op.constant(5)) save.save(dummy_model, saved_model_dir) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args(['show', '--dir', saved_model_dir, '--all']) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() exp_out = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['__saved_model_init_op']: The given SavedModel SignatureDef contains the following input(s): The given SavedModel SignatureDef contains the following output(s): outputs['__saved_model_init_op'] tensor_info: dtype: DT_INVALID shape: unknown_rank name: NoOp Method name is: signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['x'] tensor_info: dtype: DT_FLOAT shape: (2, 2) name: serving_default_x:0 The given SavedModel SignatureDef contains the following output(s): outputs['output_0'] tensor_info: dtype: DT_FLOAT shape: (2, 2) name: PartitionedCall:0 Method name is: tensorflow/serving/predict Concrete Functions: Function Name: '__call__' Option #1 Callable with: Argument #1 y: TensorSpec(shape=(), dtype=tf.int32, name='y') Argument #2 DType: int Value: 7 Function Name: 'func1' Option #1 Callable with: Argument #1 a: TensorSpec(shape=(), dtype=tf.int32, name='a') Argument #2 b: TensorSpec(shape=(), dtype=tf.int32, name='b') Argument #3 DType: bool Value: True Function Name: 'func2' Option #1 Callable with: Argument #1 x: TensorSpec(shape=(2, 2), dtype=tf.float32, name='x') """.strip() # pylint: enable=line-too-long self.maxDiff = None # Produce a useful error msg if the comparison fails self.assertMultiLineEqual(output, exp_out) self.assertEqual(err.getvalue().strip(), '') def testShowAllWithPureConcreteFunction(self): class DummyModel(tracking.AutoTrackable): """Model with a callable concrete function.""" def __init__(self): function = def_function.function( self.multiply, input_signature=[ tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32) ]) self.pure_concrete_function = function.get_concrete_function() super(DummyModel, self).__init__() def multiply(self, a, b): return a * b saved_model_dir = os.path.join(test.get_temp_dir(), 'dummy_model') dummy_model = DummyModel() save.save(dummy_model, saved_model_dir) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args(['show', '--dir', saved_model_dir, '--all']) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() exp_out = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['__saved_model_init_op']: The given SavedModel SignatureDef contains the following input(s): The given SavedModel SignatureDef contains the following output(s): outputs['__saved_model_init_op'] tensor_info: dtype: DT_INVALID shape: unknown_rank name: NoOp Method name is: signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['a'] tensor_info: dtype: DT_FLOAT shape: () name: serving_default_a:0 inputs['b'] tensor_info: dtype: DT_FLOAT shape: () name: serving_default_b:0 The given SavedModel SignatureDef contains the following output(s): outputs['output_0'] tensor_info: dtype: DT_FLOAT shape: () name: PartitionedCall:0 Method name is: tensorflow/serving/predict Concrete Functions: Function Name: 'pure_concrete_function' Option #1 Callable with: Argument #1 a: TensorSpec(shape=(), dtype=tf.float32, name='a') Argument #2 b: TensorSpec(shape=(), dtype=tf.float32, name='b') """.strip() # pylint: enable=line-too-long self.maxDiff = None # Produce a useful error msg if the comparison fails self.assertMultiLineEqual(output, exp_out) self.assertEqual(err.getvalue().strip(), '') def testShowCommandTags(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args(['show', '--dir', base_path]) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() exp_out = 'The given SavedModel contains the following tag-sets:\n\'serve\'' self.assertMultiLineEqual(output, exp_out) self.assertEqual(err.getvalue().strip(), '') def testShowCommandSignature(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args( ['show', '--dir', base_path, '--tag_set', 'serve']) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() exp_header = ('The given SavedModel MetaGraphDef contains SignatureDefs ' 'with the following keys:') exp_start = 'SignatureDef key: ' exp_keys = [ '"classify_x2_to_y3"', '"classify_x_to_y"', '"regress_x2_to_y3"', '"regress_x_to_y"', '"regress_x_to_y2"', '"serving_default"' ] # Order of signatures does not matter self.assertMultiLineEqual( output, '\n'.join([exp_header] + [exp_start + exp_key for exp_key in exp_keys])) self.assertEqual(err.getvalue().strip(), '') def testShowCommandErrorNoTagSet(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args( ['show', '--dir', base_path, '--tag_set', 'badtagset']) with self.assertRaises(RuntimeError): saved_model_cli.show(args) def testShowCommandInputsOutputs(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args([ 'show', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default' ]) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() expected_output = ( 'The given SavedModel SignatureDef contains the following input(s):\n' ' inputs[\'x\'] tensor_info:\n' ' dtype: DT_FLOAT\n shape: (-1, 1)\n name: x:0\n' 'The given SavedModel SignatureDef contains the following output(s):\n' ' outputs[\'y\'] tensor_info:\n' ' dtype: DT_FLOAT\n shape: (-1, 1)\n name: y:0\n' 'Method name is: tensorflow/serving/predict') self.assertEqual(output, expected_output) self.assertEqual(err.getvalue().strip(), '') def testPrintREFTypeTensor(self): ref_tensor_info = meta_graph_pb2.TensorInfo() ref_tensor_info.dtype = types_pb2.DT_FLOAT_REF with captured_output() as (out, err): saved_model_cli._print_tensor_info(ref_tensor_info) self.assertTrue('DT_FLOAT_REF' in out.getvalue().strip()) self.assertEqual(err.getvalue().strip(), '') def testInputPreProcessFormats(self): input_str = 'input1=/path/file.txt[ab3];input2=file2' input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]' input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str) input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string( input_expr_str, safe=False) self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3')) self.assertTrue(input_dict['input2'] == ('file2', None)) print(input_expr_dict['input3']) self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2])) self.assertAllClose(input_expr_dict['input4'], [4, 5]) self.assertTrue(len(input_dict) == 2) self.assertTrue(len(input_expr_dict) == 2) def testInputPreProcessExamplesWithStrAndBytes(self): input_examples_str = 'inputs=[{"text":["foo"], "bytes":[b"bar"]}]' input_dict = saved_model_cli.preprocess_input_examples_arg_string( input_examples_str) feature = example_pb2.Example.FromString(input_dict['inputs'][0]) self.assertProtoEquals( """ features { feature { key: "bytes" value { bytes_list { value: "bar" } } } feature { key: "text" value { bytes_list { value: "foo" } } } } """, feature) def testInputPreprocessExampleWithCodeInjection(self): input_examples_str = 'inputs=os.system("echo hacked")' with self.assertRaisesRegex(RuntimeError, 'not a valid python literal.'): saved_model_cli.preprocess_input_examples_arg_string(input_examples_str) def testInputPreProcessFileNames(self): input_str = (r'inputx=C:\Program Files\data.npz[v:0];' r'input:0=c:\PROGRA~1\data.npy') input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str) self.assertTrue(input_dict['inputx'] == (r'C:\Program Files\data.npz', 'v:0')) self.assertTrue(input_dict['input:0'] == (r'c:\PROGRA~1\data.npy', None)) def testInputPreProcessErrorBadFormat(self): input_str = 'inputx=file[[v1]v2' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(input_str) input_str = 'inputx:file' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(input_str) input_str = 'inputx:np.zeros((5))' with self.assertRaisesRegex(RuntimeError, 'format is incorrect'): saved_model_cli.preprocess_input_exprs_arg_string(input_str, safe=False) def testInputParserNPY(self): x0 = np.array([[1], [2]]) x1 = np.array(range(6)).reshape(2, 3) input0_path = os.path.join(test.get_temp_dir(), 'input0.npy') input1_path = os.path.join(test.get_temp_dir(), 'input1.npy') np.save(input0_path, x0) np.save(input1_path, x1) input_str = 'x0=' + input0_path + '[x0];x1=' + input1_path feed_dict = saved_model_cli.load_inputs_from_input_arg_string( input_str, '', '') self.assertTrue(np.all(feed_dict['x0'] == x0)) self.assertTrue(np.all(feed_dict['x1'] == x1)) def testInputParserNPZ(self): x0 = np.array([[1], [2]]) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0) input_str = 'x=' + input_path + '[a];y=' + input_path feed_dict = saved_model_cli.load_inputs_from_input_arg_string( input_str, '', '') self.assertTrue(np.all(feed_dict['x'] == x0)) self.assertTrue(np.all(feed_dict['y'] == x0)) def testInputParserPickle(self): pkl0 = {'a': 5, 'b': np.array(range(4))} pkl1 = np.array([1]) pkl2 = np.array([[1], [3]]) input_path0 = os.path.join(test.get_temp_dir(), 'pickle0.pkl') input_path1 = os.path.join(test.get_temp_dir(), 'pickle1.pkl') input_path2 = os.path.join(test.get_temp_dir(), 'pickle2.pkl') with open(input_path0, 'wb') as f: pickle.dump(pkl0, f) with open(input_path1, 'wb') as f: pickle.dump(pkl1, f) with open(input_path2, 'wb') as f: pickle.dump(pkl2, f) input_str = 'x=' + input_path0 + '[b];y=' + input_path1 + '[c];' input_str += 'z=' + input_path2 feed_dict = saved_model_cli.load_inputs_from_input_arg_string( input_str, '', '') self.assertTrue(np.all(feed_dict['x'] == pkl0['b'])) self.assertTrue(np.all(feed_dict['y'] == pkl1)) self.assertTrue(np.all(feed_dict['z'] == pkl2)) def testInputParserPythonExpression(self): x1 = np.ones([2, 10]) x2 = np.array([[1], [2], [3]]) x3 = np.mgrid[0:5, 0:5] x4 = [[3], [4]] input_expr_str = ('x1=np.ones([2,10]);x2=np.array([[1],[2],[3]]);' 'x3=np.mgrid[0:5,0:5];x4=[[3],[4]]') feed_dict = saved_model_cli.load_inputs_from_input_arg_string( '', input_expr_str, '') self.assertTrue(np.all(feed_dict['x1'] == x1)) self.assertTrue(np.all(feed_dict['x2'] == x2)) self.assertTrue(np.all(feed_dict['x3'] == x3)) self.assertTrue(np.all(feed_dict['x4'] == x4)) def testInputParserBoth(self): x0 = np.array([[1], [2]]) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0) x1 = np.ones([2, 10]) input_str = 'x0=' + input_path + '[a]' input_expr_str = 'x1=np.ones([2,10])' feed_dict = saved_model_cli.load_inputs_from_input_arg_string( input_str, input_expr_str, '') self.assertTrue(np.all(feed_dict['x0'] == x0)) self.assertTrue(np.all(feed_dict['x1'] == x1)) def testInputParserBothDuplicate(self): x0 = np.array([[1], [2]]) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0) x1 = np.ones([2, 10]) input_str = 'x0=' + input_path + '[a]' input_expr_str = 'x0=np.ones([2,10])' feed_dict = saved_model_cli.load_inputs_from_input_arg_string( input_str, input_expr_str, '') self.assertTrue(np.all(feed_dict['x0'] == x1)) def testInputParserErrorNoName(self): x0 = np.array([[1], [2]]) x1 = np.array(range(5)) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0, b=x1) input_str = 'x=' + input_path with self.assertRaises(RuntimeError): saved_model_cli.load_inputs_from_input_arg_string(input_str, '', '') def testInputParserErrorWrongName(self): x0 = np.array([[1], [2]]) x1 = np.array(range(5)) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0, b=x1) input_str = 'x=' + input_path + '[c]' with self.assertRaises(RuntimeError): saved_model_cli.load_inputs_from_input_arg_string(input_str, '', '') @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputExamples(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'new_dir' + ('tfrt' if use_tfrt else '')) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":[8.0],"x2":[5.0]}, {"x":[4.0],"x2":[3.0]}]', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) saved_model_cli.run(args) y_actual = np.load(os.path.join(output_dir, 'outputs.npy')) y_expected = np.array([[6.0], [4.0]]) self.assertAllEqual(y_expected, y_actual) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandExistingOutdir(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommand_inputs.npz') np.savez(input_path, x0=x, x1=x_notused) output_file = os.path.join(test.get_temp_dir(), 'outputs.npy') if os.path.exists(output_file): os.remove(output_file) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x2_to_y3', '--inputs', 'inputs=' + input_path + '[x0]', '--outdir', test.get_temp_dir() ] + (['--use_tfrt'] if use_tfrt else [])) saved_model_cli.run(args) y_actual = np.load(output_file) y_expected = np.array([[3.5], [4.0]]) self.assertAllClose(y_expected, y_actual) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandNewOutdir(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommandNewOutdir_inputs.npz') output_dir = os.path.join(test.get_temp_dir(), 'new_dir') if os.path.isdir(output_dir): shutil.rmtree(output_dir) np.savez(input_path, x0=x, x1=x_notused) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + input_path + '[x0]', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) saved_model_cli.run(args) y_actual = np.load(os.path.join(output_dir, 'y.npy')) y_expected = np.array([[2.5], [3.0]]) self.assertAllClose(y_expected, y_actual) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandOutOverwrite(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommandOutOverwrite_inputs.npz') np.savez(input_path, x0=x, x1=x_notused) output_file = os.path.join(test.get_temp_dir(), 'y.npy') open(output_file, 'a').close() args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + input_path + '[x0]', '--outdir', test.get_temp_dir(), '--overwrite' ] + (['--use_tfrt'] if use_tfrt else [])) saved_model_cli.run(args) y_actual = np.load(output_file) y_expected = np.array([[2.5], [3.0]]) self.assertAllClose(y_expected, y_actual) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInvalidInputKeyError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x2_to_y3', '--input_exprs', 'x2=np.ones((3,1))' ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaises(ValueError): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInvalidSignature(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'INVALID_SIGNATURE', '--input_exprs', 'x2=np.ones((3,1))' ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaisesRegex(ValueError, 'Could not find signature "INVALID_SIGNATURE"'): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputExamplesNotListError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'new_dir') args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs={"x":8.0,"x2":5.0}', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaisesRegex(ValueError, 'must be a list'): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputExamplesFeatureValueNotListError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'new_dir') args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":8.0,"x2":5.0}]', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaisesRegex(ValueError, 'feature value must be a list'): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputExamplesFeatureBadType(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'new_dir') args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":[[1],[2]]}]', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaisesRegex(ValueError, 'is not supported'): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandOutputFileExistError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommandOutOverwrite_inputs.npz') np.savez(input_path, x0=x, x1=x_notused) output_file = os.path.join(test.get_temp_dir(), 'y.npy') open(output_file, 'a').close() args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + input_path + '[x0]', '--outdir', test.get_temp_dir() ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaises(RuntimeError): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputNotGivenError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default' ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaises(AttributeError): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandWithDebuggerEnabled(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommandNewOutdir_inputs.npz') output_dir = os.path.join(test.get_temp_dir(), 'new_dir') if os.path.isdir(output_dir): shutil.rmtree(output_dir) np.savez(input_path, x0=x, x1=x_notused) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + input_path + '[x0]', '--outdir', output_dir, '--tf_debug' ] + (['--use_tfrt'] if use_tfrt else [])) def fake_wrapper_session(sess): return sess with test.mock.patch.object( local_cli_wrapper, 'LocalCLIDebugWrapperSession', side_effect=fake_wrapper_session, autospec=True) as fake: saved_model_cli.run(args) fake.assert_called_with(test.mock.ANY) y_actual = np.load(os.path.join(output_dir, 'y.npy')) y_expected = np.array([[2.5], [3.0]]) self.assertAllClose(y_expected, y_actual) def testScanCommand(self): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args(['scan', '--dir', base_path]) with captured_output() as (out, _): saved_model_cli.scan(args) output = out.getvalue().strip() self.assertTrue('does not contain denylisted ops' in output) def testScanCommandFoundDenylistedOp(self): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args( ['scan', '--dir', base_path, '--tag_set', 'serve']) op_denylist = saved_model_cli._OP_DENYLIST saved_model_cli._OP_DENYLIST = set(['VariableV2']) with captured_output() as (out, _): saved_model_cli.scan(args) saved_model_cli._OP_DENYLIST = op_denylist output = out.getvalue().strip() self.assertTrue('\'VariableV2\'' in output) def testAOTCompileCPUWrongSignatureDefKey(self): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir') args = self.parser.parse_args([ 'aot_compile_cpu', '--dir', base_path, '--tag_set', 'serve', '--output_prefix', output_dir, '--cpp_class', 'Compiled', '--signature_def_key', 'MISSING' ]) with self.assertRaisesRegex(ValueError, 'Unable to find signature_def'): saved_model_cli.aot_compile_cpu(args) class AOTCompileDummyModel(tracking.AutoTrackable): """Model compatible with XLA compilation.""" def __init__(self): self.var = variables.Variable(1.0, name='my_var') self.write_var = variables.Variable(1.0, name='write_var') @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2, 2), dtype=dtypes.float32), # Test unused inputs. tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def func2(self, x, y): del y return {'res': x + self.var} @def_function.function(input_signature=[ # Test large inputs. tensor_spec.TensorSpec(shape=(2048, 16), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def func3(self, x, y): del y return {'res': x + self.var} @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def func_write(self, x, y): del y self.write_var.assign(x + self.var) return {'res': self.write_var} @parameterized.named_parameters( ('VariablesToFeedNone', '', 'func2', None), ('VariablesToFeedNoneTargetAarch64Linux', '', 'func2', 'aarch64-none-linux-gnu'), ('VariablesToFeedNoneTargetAarch64Android', '', 'func2', 'aarch64-none-android'), ('VariablesToFeedAll', 'all', 'func2', None), ('VariablesToFeedMyVar', 'my_var', 'func2', None), ('VariablesToFeedNoneLargeConstant', '', 'func3', None), ('WriteToWriteVar', 'all', 'func_write', None), ) def testAOTCompileCPUFreezesAndCompiles(self, variables_to_feed, func, target_triple): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') saved_model_dir = os.path.join(test.get_temp_dir(), 'dummy_model') dummy_model = self.AOTCompileDummyModel() func = getattr(dummy_model, func) with self.cached_session(): self.evaluate(dummy_model.var.initializer) self.evaluate(dummy_model.write_var.initializer) save.save(dummy_model, saved_model_dir, signatures={'func': func}) self.parser = saved_model_cli.create_parser() output_prefix = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir/out') args = [ # Use the default seving signature_key. 'aot_compile_cpu', '--dir', saved_model_dir, '--tag_set', 'serve', '--signature_def_key', 'func', '--output_prefix', output_prefix, '--variables_to_feed', variables_to_feed, '--cpp_class', 'Generated' ] if target_triple: args.extend(['--target_triple', target_triple]) args = self.parser.parse_args(args) with test.mock.patch.object(logging, 'warn') as captured_warn: saved_model_cli.aot_compile_cpu(args) self.assertRegex( str(captured_warn.call_args), 'Signature input key \'y\'.*has been pruned while freezing the graph.') self.assertTrue(file_io.file_exists('{}.o'.format(output_prefix))) self.assertTrue(file_io.file_exists('{}.h'.format(output_prefix))) self.assertTrue(file_io.file_exists('{}_metadata.o'.format(output_prefix))) self.assertTrue( file_io.file_exists('{}_makefile.inc'.format(output_prefix))) header_contents = file_io.read_file_to_string('{}.h'.format(output_prefix)) self.assertIn('class Generated', header_contents) self.assertIn('arg_feed_x_data', header_contents) self.assertIn('result_fetch_res_data', header_contents) # arg_y got filtered out as it's not used by the output. self.assertNotIn('arg_feed_y_data', header_contents) if variables_to_feed: # Read-only-variables' setters preserve constness. self.assertIn('set_var_param_my_var_data(const float', header_contents) self.assertNotIn('set_var_param_my_var_data(float', header_contents) if func == dummy_model.func_write: # Writeable variables setters do not preserve constness. self.assertIn('set_var_param_write_var_data(float', header_contents) self.assertNotIn('set_var_param_write_var_data(const float', header_contents) makefile_contents = file_io.read_file_to_string( '{}_makefile.inc'.format(output_prefix)) self.assertIn('-D_GLIBCXX_USE_CXX11_ABI=', makefile_contents) def testFreezeModel(self): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') variables_to_feed = 'all' func = 'func2' saved_model_dir = os.path.join(test.get_temp_dir(), 'dummy_model') dummy_model = self.AOTCompileDummyModel() func = getattr(dummy_model, func) with self.cached_session(): self.evaluate(dummy_model.var.initializer) self.evaluate(dummy_model.write_var.initializer) save.save(dummy_model, saved_model_dir, signatures={'func': func}) self.parser = saved_model_cli.create_parser() output_prefix = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir/out') args = [ # Use the default seving signature_key. 'freeze_model', '--dir', saved_model_dir, '--tag_set', 'serve', '--signature_def_key', 'func', '--output_prefix', output_prefix, '--variables_to_feed', variables_to_feed ] args = self.parser.parse_args(args) with test.mock.patch.object(logging, 'warn'): saved_model_cli.freeze_model(args) self.assertTrue( file_io.file_exists(os.path.join(output_prefix, 'frozen_graph.pb'))) self.assertTrue( file_io.file_exists(os.path.join(output_prefix, 'config.pbtxt'))) if __name__ == '__main__': test.main()
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for SavedModelCLI tool.""" import contextlib import os import pickle import platform import shutil import sys from absl.testing import parameterized import numpy as np from six import StringIO from tensorflow.core.example import example_pb2 from tensorflow.core.framework import types_pb2 from tensorflow.core.protobuf import meta_graph_pb2 from tensorflow.python.debug.wrappers import local_cli_wrapper from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.lib.io import file_io from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import save from tensorflow.python.tools import saved_model_cli from tensorflow.python.training.tracking import tracking SAVED_MODEL_PATH = ('cc/saved_model/testdata/half_plus_two/00000123') @contextlib.contextmanager def captured_output(): new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err class SavedModelCLITestCase(test.TestCase, parameterized.TestCase): def setUp(self): super(SavedModelCLITestCase, self).setUp() if platform.system() == 'Windows': self.skipTest('Skipping failing tests on Windows.') def testShowCommandAll(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args(['show', '--dir', base_path, '--all']) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() # pylint: disable=line-too-long exp_out = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['classify_x2_to_y3']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: x2:0 The given SavedModel SignatureDef contains the following output(s): outputs['scores'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y3:0 Method name is: tensorflow/serving/classify signature_def['classify_x_to_y']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following output(s): outputs['scores'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y:0 Method name is: tensorflow/serving/classify signature_def['regress_x2_to_y3']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: x2:0 The given SavedModel SignatureDef contains the following output(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y3:0 Method name is: tensorflow/serving/regress signature_def['regress_x_to_y']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following output(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y:0 Method name is: tensorflow/serving/regress signature_def['regress_x_to_y2']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following output(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y2:0 Method name is: tensorflow/serving/regress signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['x'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: x:0 The given SavedModel SignatureDef contains the following output(s): outputs['y'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y:0 Method name is: tensorflow/serving/predict""" # pylint: enable=line-too-long self.maxDiff = None # Produce a useful error msg if the comparison fails self.assertMultiLineEqual(output, exp_out) self.assertEqual(err.getvalue().strip(), '') def testShowAllWithFunctions(self): class DummyModel(tracking.AutoTrackable): """Model with callable polymorphic functions specified.""" @def_function.function def func1(self, a, b, c): if c: return a + b else: return a * b @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2, 2), dtype=dtypes.float32) ]) def func2(self, x): return x + 2 @def_function.function def __call__(self, y, c=7): return y + 2 * c saved_model_dir = os.path.join(test.get_temp_dir(), 'dummy_model') dummy_model = DummyModel() # Call with specific values to create new polymorphic function traces. dummy_model.func1(constant_op.constant(5), constant_op.constant(9), True) dummy_model(constant_op.constant(5)) save.save(dummy_model, saved_model_dir) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args(['show', '--dir', saved_model_dir, '--all']) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() exp_out = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['__saved_model_init_op']: The given SavedModel SignatureDef contains the following input(s): The given SavedModel SignatureDef contains the following output(s): outputs['__saved_model_init_op'] tensor_info: dtype: DT_INVALID shape: unknown_rank name: NoOp Method name is: signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['x'] tensor_info: dtype: DT_FLOAT shape: (2, 2) name: serving_default_x:0 The given SavedModel SignatureDef contains the following output(s): outputs['output_0'] tensor_info: dtype: DT_FLOAT shape: (2, 2) name: PartitionedCall:0 Method name is: tensorflow/serving/predict Concrete Functions: Function Name: '__call__' Option #1 Callable with: Argument #1 y: TensorSpec(shape=(), dtype=tf.int32, name='y') Argument #2 DType: int Value: 7 Function Name: 'func1' Option #1 Callable with: Argument #1 a: TensorSpec(shape=(), dtype=tf.int32, name='a') Argument #2 b: TensorSpec(shape=(), dtype=tf.int32, name='b') Argument #3 DType: bool Value: True Function Name: 'func2' Option #1 Callable with: Argument #1 x: TensorSpec(shape=(2, 2), dtype=tf.float32, name='x') """.strip() # pylint: enable=line-too-long self.maxDiff = None # Produce a useful error msg if the comparison fails self.assertMultiLineEqual(output, exp_out) self.assertEqual(err.getvalue().strip(), '') def testShowAllWithPureConcreteFunction(self): class DummyModel(tracking.AutoTrackable): """Model with a callable concrete function.""" def __init__(self): function = def_function.function( self.multiply, input_signature=[ tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32) ]) self.pure_concrete_function = function.get_concrete_function() super(DummyModel, self).__init__() def multiply(self, a, b): return a * b saved_model_dir = os.path.join(test.get_temp_dir(), 'dummy_model') dummy_model = DummyModel() save.save(dummy_model, saved_model_dir) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args(['show', '--dir', saved_model_dir, '--all']) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() exp_out = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['__saved_model_init_op']: The given SavedModel SignatureDef contains the following input(s): The given SavedModel SignatureDef contains the following output(s): outputs['__saved_model_init_op'] tensor_info: dtype: DT_INVALID shape: unknown_rank name: NoOp Method name is: signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['a'] tensor_info: dtype: DT_FLOAT shape: () name: serving_default_a:0 inputs['b'] tensor_info: dtype: DT_FLOAT shape: () name: serving_default_b:0 The given SavedModel SignatureDef contains the following output(s): outputs['output_0'] tensor_info: dtype: DT_FLOAT shape: () name: PartitionedCall:0 Method name is: tensorflow/serving/predict Concrete Functions: Function Name: 'pure_concrete_function' Option #1 Callable with: Argument #1 a: TensorSpec(shape=(), dtype=tf.float32, name='a') Argument #2 b: TensorSpec(shape=(), dtype=tf.float32, name='b') """.strip() # pylint: enable=line-too-long self.maxDiff = None # Produce a useful error msg if the comparison fails self.assertMultiLineEqual(output, exp_out) self.assertEqual(err.getvalue().strip(), '') def testShowCommandTags(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args(['show', '--dir', base_path]) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() exp_out = 'The given SavedModel contains the following tag-sets:\n\'serve\'' self.assertMultiLineEqual(output, exp_out) self.assertEqual(err.getvalue().strip(), '') def testShowCommandSignature(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args( ['show', '--dir', base_path, '--tag_set', 'serve']) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() exp_header = ('The given SavedModel MetaGraphDef contains SignatureDefs ' 'with the following keys:') exp_start = 'SignatureDef key: ' exp_keys = [ '"classify_x2_to_y3"', '"classify_x_to_y"', '"regress_x2_to_y3"', '"regress_x_to_y"', '"regress_x_to_y2"', '"serving_default"' ] # Order of signatures does not matter self.assertMultiLineEqual( output, '\n'.join([exp_header] + [exp_start + exp_key for exp_key in exp_keys])) self.assertEqual(err.getvalue().strip(), '') def testShowCommandErrorNoTagSet(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args( ['show', '--dir', base_path, '--tag_set', 'badtagset']) with self.assertRaises(RuntimeError): saved_model_cli.show(args) def testShowCommandInputsOutputs(self): base_path = test.test_src_dir_path(SAVED_MODEL_PATH) self.parser = saved_model_cli.create_parser() args = self.parser.parse_args([ 'show', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default' ]) with captured_output() as (out, err): saved_model_cli.show(args) output = out.getvalue().strip() expected_output = ( 'The given SavedModel SignatureDef contains the following input(s):\n' ' inputs[\'x\'] tensor_info:\n' ' dtype: DT_FLOAT\n shape: (-1, 1)\n name: x:0\n' 'The given SavedModel SignatureDef contains the following output(s):\n' ' outputs[\'y\'] tensor_info:\n' ' dtype: DT_FLOAT\n shape: (-1, 1)\n name: y:0\n' 'Method name is: tensorflow/serving/predict') self.assertEqual(output, expected_output) self.assertEqual(err.getvalue().strip(), '') def testPrintREFTypeTensor(self): ref_tensor_info = meta_graph_pb2.TensorInfo() ref_tensor_info.dtype = types_pb2.DT_FLOAT_REF with captured_output() as (out, err): saved_model_cli._print_tensor_info(ref_tensor_info) self.assertTrue('DT_FLOAT_REF' in out.getvalue().strip()) self.assertEqual(err.getvalue().strip(), '') def testInputPreProcessFormats(self): input_str = 'input1=/path/file.txt[ab3];input2=file2' input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]' input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str) input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string( input_expr_str, safe=False) self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3')) self.assertTrue(input_dict['input2'] == ('file2', None)) print(input_expr_dict['input3']) self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2])) self.assertAllClose(input_expr_dict['input4'], [4, 5]) self.assertTrue(len(input_dict) == 2) self.assertTrue(len(input_expr_dict) == 2) def testInputPreProcessExamplesWithStrAndBytes(self): input_examples_str = 'inputs=[{"text":["foo"], "bytes":[b"bar"]}]' input_dict = saved_model_cli.preprocess_input_examples_arg_string( input_examples_str) feature = example_pb2.Example.FromString(input_dict['inputs'][0]) self.assertProtoEquals( """ features { feature { key: "bytes" value { bytes_list { value: "bar" } } } feature { key: "text" value { bytes_list { value: "foo" } } } } """, feature) def testInputPreprocessExampleWithCodeInjection(self): input_examples_str = 'inputs=os.system("echo hacked")' with self.assertRaisesRegex(RuntimeError, 'not a valid python literal.'): saved_model_cli.preprocess_input_examples_arg_string(input_examples_str) def testInputPreProcessFileNames(self): input_str = (r'inputx=C:\Program Files\data.npz[v:0];' r'input:0=c:\PROGRA~1\data.npy') input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str) self.assertTrue(input_dict['inputx'] == (r'C:\Program Files\data.npz', 'v:0')) self.assertTrue(input_dict['input:0'] == (r'c:\PROGRA~1\data.npy', None)) def testInputPreProcessErrorBadFormat(self): input_str = 'inputx=file[[v1]v2' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(input_str) input_str = 'inputx:file' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(input_str) input_str = 'inputx:np.zeros((5))' with self.assertRaisesRegex(RuntimeError, 'format is incorrect'): saved_model_cli.preprocess_input_exprs_arg_string(input_str, safe=False) def testInputParserNPY(self): x0 = np.array([[1], [2]]) x1 = np.array(range(6)).reshape(2, 3) input0_path = os.path.join(test.get_temp_dir(), 'input0.npy') input1_path = os.path.join(test.get_temp_dir(), 'input1.npy') np.save(input0_path, x0) np.save(input1_path, x1) input_str = 'x0=' + input0_path + '[x0];x1=' + input1_path feed_dict = saved_model_cli.load_inputs_from_input_arg_string( input_str, '', '') self.assertTrue(np.all(feed_dict['x0'] == x0)) self.assertTrue(np.all(feed_dict['x1'] == x1)) def testInputParserNPZ(self): x0 = np.array([[1], [2]]) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0) input_str = 'x=' + input_path + '[a];y=' + input_path feed_dict = saved_model_cli.load_inputs_from_input_arg_string( input_str, '', '') self.assertTrue(np.all(feed_dict['x'] == x0)) self.assertTrue(np.all(feed_dict['y'] == x0)) def testInputParserPickle(self): pkl0 = {'a': 5, 'b': np.array(range(4))} pkl1 = np.array([1]) pkl2 = np.array([[1], [3]]) input_path0 = os.path.join(test.get_temp_dir(), 'pickle0.pkl') input_path1 = os.path.join(test.get_temp_dir(), 'pickle1.pkl') input_path2 = os.path.join(test.get_temp_dir(), 'pickle2.pkl') with open(input_path0, 'wb') as f: pickle.dump(pkl0, f) with open(input_path1, 'wb') as f: pickle.dump(pkl1, f) with open(input_path2, 'wb') as f: pickle.dump(pkl2, f) input_str = 'x=' + input_path0 + '[b];y=' + input_path1 + '[c];' input_str += 'z=' + input_path2 feed_dict = saved_model_cli.load_inputs_from_input_arg_string( input_str, '', '') self.assertTrue(np.all(feed_dict['x'] == pkl0['b'])) self.assertTrue(np.all(feed_dict['y'] == pkl1)) self.assertTrue(np.all(feed_dict['z'] == pkl2)) def testInputParserErrorNoName(self): x0 = np.array([[1], [2]]) x1 = np.array(range(5)) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0, b=x1) input_str = 'x=' + input_path with self.assertRaises(RuntimeError): saved_model_cli.load_inputs_from_input_arg_string(input_str, '', '') def testInputParserErrorWrongName(self): x0 = np.array([[1], [2]]) x1 = np.array(range(5)) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0, b=x1) input_str = 'x=' + input_path + '[c]' with self.assertRaises(RuntimeError): saved_model_cli.load_inputs_from_input_arg_string(input_str, '', '') @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputExamples(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'new_dir' + ('tfrt' if use_tfrt else '')) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":[8.0],"x2":[5.0]}, {"x":[4.0],"x2":[3.0]}]', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) saved_model_cli.run(args) y_actual = np.load(os.path.join(output_dir, 'outputs.npy')) y_expected = np.array([[6.0], [4.0]]) self.assertAllEqual(y_expected, y_actual) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandExistingOutdir(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommand_inputs.npz') np.savez(input_path, x0=x, x1=x_notused) output_file = os.path.join(test.get_temp_dir(), 'outputs.npy') if os.path.exists(output_file): os.remove(output_file) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x2_to_y3', '--inputs', 'inputs=' + input_path + '[x0]', '--outdir', test.get_temp_dir() ] + (['--use_tfrt'] if use_tfrt else [])) saved_model_cli.run(args) y_actual = np.load(output_file) y_expected = np.array([[3.5], [4.0]]) self.assertAllClose(y_expected, y_actual) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandNewOutdir(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommandNewOutdir_inputs.npz') output_dir = os.path.join(test.get_temp_dir(), 'new_dir') if os.path.isdir(output_dir): shutil.rmtree(output_dir) np.savez(input_path, x0=x, x1=x_notused) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + input_path + '[x0]', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) saved_model_cli.run(args) y_actual = np.load(os.path.join(output_dir, 'y.npy')) y_expected = np.array([[2.5], [3.0]]) self.assertAllClose(y_expected, y_actual) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandOutOverwrite(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommandOutOverwrite_inputs.npz') np.savez(input_path, x0=x, x1=x_notused) output_file = os.path.join(test.get_temp_dir(), 'y.npy') open(output_file, 'a').close() args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + input_path + '[x0]', '--outdir', test.get_temp_dir(), '--overwrite' ] + (['--use_tfrt'] if use_tfrt else [])) saved_model_cli.run(args) y_actual = np.load(output_file) y_expected = np.array([[2.5], [3.0]]) self.assertAllClose(y_expected, y_actual) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInvalidInputKeyError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x2_to_y3', '--input_exprs', 'x2=[1,2,3]' ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaises(ValueError): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInvalidSignature(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'INVALID_SIGNATURE', '--input_exprs', 'x2=[1,2,3]' ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaisesRegex(ValueError, 'Could not find signature "INVALID_SIGNATURE"'): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputExamplesNotListError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'new_dir') args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs={"x":8.0,"x2":5.0}', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaisesRegex(ValueError, 'must be a list'): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputExamplesFeatureValueNotListError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'new_dir') args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":8.0,"x2":5.0}]', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaisesRegex(ValueError, 'feature value must be a list'): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputExamplesFeatureBadType(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'new_dir') args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":[[1],[2]]}]', '--outdir', output_dir ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaisesRegex(ValueError, 'is not supported'): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandOutputFileExistError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommandOutOverwrite_inputs.npz') np.savez(input_path, x0=x, x1=x_notused) output_file = os.path.join(test.get_temp_dir(), 'y.npy') open(output_file, 'a').close() args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + input_path + '[x0]', '--outdir', test.get_temp_dir() ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaises(RuntimeError): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandInputNotGivenError(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default' ] + (['--use_tfrt'] if use_tfrt else [])) with self.assertRaises(AttributeError): saved_model_cli.run(args) @parameterized.named_parameters(('non_tfrt', False)) def testRunCommandWithDebuggerEnabled(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) x = np.array([[1], [2]]) x_notused = np.zeros((6, 3)) input_path = os.path.join(test.get_temp_dir(), 'testRunCommandNewOutdir_inputs.npz') output_dir = os.path.join(test.get_temp_dir(), 'new_dir') if os.path.isdir(output_dir): shutil.rmtree(output_dir) np.savez(input_path, x0=x, x1=x_notused) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + input_path + '[x0]', '--outdir', output_dir, '--tf_debug' ] + (['--use_tfrt'] if use_tfrt else [])) def fake_wrapper_session(sess): return sess with test.mock.patch.object( local_cli_wrapper, 'LocalCLIDebugWrapperSession', side_effect=fake_wrapper_session, autospec=True) as fake: saved_model_cli.run(args) fake.assert_called_with(test.mock.ANY) y_actual = np.load(os.path.join(output_dir, 'y.npy')) y_expected = np.array([[2.5], [3.0]]) self.assertAllClose(y_expected, y_actual) def testScanCommand(self): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args(['scan', '--dir', base_path]) with captured_output() as (out, _): saved_model_cli.scan(args) output = out.getvalue().strip() self.assertTrue('does not contain denylisted ops' in output) def testScanCommandFoundDenylistedOp(self): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args( ['scan', '--dir', base_path, '--tag_set', 'serve']) op_denylist = saved_model_cli._OP_DENYLIST saved_model_cli._OP_DENYLIST = set(['VariableV2']) with captured_output() as (out, _): saved_model_cli.scan(args) saved_model_cli._OP_DENYLIST = op_denylist output = out.getvalue().strip() self.assertTrue('\'VariableV2\'' in output) def testAOTCompileCPUWrongSignatureDefKey(self): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) output_dir = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir') args = self.parser.parse_args([ 'aot_compile_cpu', '--dir', base_path, '--tag_set', 'serve', '--output_prefix', output_dir, '--cpp_class', 'Compiled', '--signature_def_key', 'MISSING' ]) with self.assertRaisesRegex(ValueError, 'Unable to find signature_def'): saved_model_cli.aot_compile_cpu(args) class AOTCompileDummyModel(tracking.AutoTrackable): """Model compatible with XLA compilation.""" def __init__(self): self.var = variables.Variable(1.0, name='my_var') self.write_var = variables.Variable(1.0, name='write_var') @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2, 2), dtype=dtypes.float32), # Test unused inputs. tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def func2(self, x, y): del y return {'res': x + self.var} @def_function.function(input_signature=[ # Test large inputs. tensor_spec.TensorSpec(shape=(2048, 16), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def func3(self, x, y): del y return {'res': x + self.var} @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def func_write(self, x, y): del y self.write_var.assign(x + self.var) return {'res': self.write_var} @parameterized.named_parameters( ('VariablesToFeedNone', '', 'func2', None), ('VariablesToFeedNoneTargetAarch64Linux', '', 'func2', 'aarch64-none-linux-gnu'), ('VariablesToFeedNoneTargetAarch64Android', '', 'func2', 'aarch64-none-android'), ('VariablesToFeedAll', 'all', 'func2', None), ('VariablesToFeedMyVar', 'my_var', 'func2', None), ('VariablesToFeedNoneLargeConstant', '', 'func3', None), ('WriteToWriteVar', 'all', 'func_write', None), ) def testAOTCompileCPUFreezesAndCompiles(self, variables_to_feed, func, target_triple): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') saved_model_dir = os.path.join(test.get_temp_dir(), 'dummy_model') dummy_model = self.AOTCompileDummyModel() func = getattr(dummy_model, func) with self.cached_session(): self.evaluate(dummy_model.var.initializer) self.evaluate(dummy_model.write_var.initializer) save.save(dummy_model, saved_model_dir, signatures={'func': func}) self.parser = saved_model_cli.create_parser() output_prefix = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir/out') args = [ # Use the default seving signature_key. 'aot_compile_cpu', '--dir', saved_model_dir, '--tag_set', 'serve', '--signature_def_key', 'func', '--output_prefix', output_prefix, '--variables_to_feed', variables_to_feed, '--cpp_class', 'Generated' ] if target_triple: args.extend(['--target_triple', target_triple]) args = self.parser.parse_args(args) with test.mock.patch.object(logging, 'warn') as captured_warn: saved_model_cli.aot_compile_cpu(args) self.assertRegex( str(captured_warn.call_args), 'Signature input key \'y\'.*has been pruned while freezing the graph.') self.assertTrue(file_io.file_exists('{}.o'.format(output_prefix))) self.assertTrue(file_io.file_exists('{}.h'.format(output_prefix))) self.assertTrue(file_io.file_exists('{}_metadata.o'.format(output_prefix))) self.assertTrue( file_io.file_exists('{}_makefile.inc'.format(output_prefix))) header_contents = file_io.read_file_to_string('{}.h'.format(output_prefix)) self.assertIn('class Generated', header_contents) self.assertIn('arg_feed_x_data', header_contents) self.assertIn('result_fetch_res_data', header_contents) # arg_y got filtered out as it's not used by the output. self.assertNotIn('arg_feed_y_data', header_contents) if variables_to_feed: # Read-only-variables' setters preserve constness. self.assertIn('set_var_param_my_var_data(const float', header_contents) self.assertNotIn('set_var_param_my_var_data(float', header_contents) if func == dummy_model.func_write: # Writeable variables setters do not preserve constness. self.assertIn('set_var_param_write_var_data(float', header_contents) self.assertNotIn('set_var_param_write_var_data(const float', header_contents) makefile_contents = file_io.read_file_to_string( '{}_makefile.inc'.format(output_prefix)) self.assertIn('-D_GLIBCXX_USE_CXX11_ABI=', makefile_contents) def testFreezeModel(self): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') variables_to_feed = 'all' func = 'func2' saved_model_dir = os.path.join(test.get_temp_dir(), 'dummy_model') dummy_model = self.AOTCompileDummyModel() func = getattr(dummy_model, func) with self.cached_session(): self.evaluate(dummy_model.var.initializer) self.evaluate(dummy_model.write_var.initializer) save.save(dummy_model, saved_model_dir, signatures={'func': func}) self.parser = saved_model_cli.create_parser() output_prefix = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir/out') args = [ # Use the default seving signature_key. 'freeze_model', '--dir', saved_model_dir, '--tag_set', 'serve', '--signature_def_key', 'func', '--output_prefix', output_prefix, '--variables_to_feed', variables_to_feed ] args = self.parser.parse_args(args) with test.mock.patch.object(logging, 'warn'): saved_model_cli.freeze_model(args) self.assertTrue( file_io.file_exists(os.path.join(output_prefix, 'frozen_graph.pb'))) self.assertTrue( file_io.file_exists(os.path.join(output_prefix, 'config.pbtxt'))) if __name__ == '__main__': test.main()
remote_code_execution
{ "code": [ " def testInputParserPythonExpression(self):", " x1 = np.ones([2, 10])", " x2 = np.array([[1], [2], [3]])", " x3 = np.mgrid[0:5, 0:5]", " x4 = [[3], [4]]", " input_expr_str = ('x1=np.ones([2,10]);x2=np.array([[1],[2],[3]]);'", " 'x3=np.mgrid[0:5,0:5];x4=[[3],[4]]')", " feed_dict = saved_model_cli.load_inputs_from_input_arg_string(", " '', input_expr_str, '')", " self.assertTrue(np.all(feed_dict['x1'] == x1))", " self.assertTrue(np.all(feed_dict['x2'] == x2))", " self.assertTrue(np.all(feed_dict['x3'] == x3))", " self.assertTrue(np.all(feed_dict['x4'] == x4))", " def testInputParserBoth(self):", " x0 = np.array([[1], [2]])", " input_path = os.path.join(test.get_temp_dir(), 'input.npz')", " np.savez(input_path, a=x0)", " x1 = np.ones([2, 10])", " input_str = 'x0=' + input_path + '[a]'", " input_expr_str = 'x1=np.ones([2,10])'", " feed_dict = saved_model_cli.load_inputs_from_input_arg_string(", " input_str, input_expr_str, '')", " self.assertTrue(np.all(feed_dict['x0'] == x0))", " self.assertTrue(np.all(feed_dict['x1'] == x1))", " def testInputParserBothDuplicate(self):", " x0 = np.array([[1], [2]])", " input_path = os.path.join(test.get_temp_dir(), 'input.npz')", " np.savez(input_path, a=x0)", " x1 = np.ones([2, 10])", " input_str = 'x0=' + input_path + '[a]'", " input_expr_str = 'x0=np.ones([2,10])'", " feed_dict = saved_model_cli.load_inputs_from_input_arg_string(", " input_str, input_expr_str, '')", " self.assertTrue(np.all(feed_dict['x0'] == x1))", " 'regress_x2_to_y3', '--input_exprs', 'x2=np.ones((3,1))'", " 'INVALID_SIGNATURE', '--input_exprs', 'x2=np.ones((3,1))'" ], "line_no": [ 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 632, 643 ] }
{ "code": [ " 'regress_x2_to_y3', '--input_exprs', 'x2=[1,2,3]'", " 'INVALID_SIGNATURE', '--input_exprs', 'x2=[1,2,3]'" ], "line_no": [ 595, 606 ] }
import .contextlib import os import pickle import platform import shutil import .sys from absl.testing import parameterized import numpy as np from six import StringIO from tensorflow.core.example import example_pb2 from tensorflow.core.framework import types_pb2 from tensorflow.core.protobuf import meta_graph_pb2 from tensorflow.python.debug.wrappers import local_cli_wrapper from tensorflow.python.eager import def_function from tensorflow.python.framework import .constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.lib.io import file_io from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import save from tensorflow.python.tools import saved_model_cli from tensorflow.python.training.tracking import tracking VAR_0 = ('cc/saved_model/testdata/half_plus_two/00000123') @contextlib.contextmanager def FUNC_0(): VAR_1, VAR_2 = StringIO(), StringIO() VAR_3, VAR_4 = VAR_9.stdout, VAR_9.stderr try: VAR_9.stdout, VAR_9.stderr = VAR_1, VAR_2 yield VAR_9.stdout, VAR_9.stderr finally: VAR_9.stdout, VAR_9.stderr = VAR_3, VAR_4 class CLASS_0(test.TestCase, parameterized.TestCase): def FUNC_1(self): super(CLASS_0, self).setUp() if platform.system() == 'Windows': self.skipTest('Skipping failing tests on Windows.') def FUNC_2(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args(['show', '--dir', VAR_10, '--all']) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_13 = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['classify_x2_to_y3']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_39:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['scores'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y3:0 Method name is: tensorflow/serving/classify signature_def['classify_x_to_y']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['scores'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_50:0 Method name is: tensorflow/serving/classify signature_def['regress_x2_to_y3']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_39:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y3:0 Method name is: tensorflow/serving/regress signature_def['regress_x_to_y']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_50:0 Method name is: tensorflow/serving/regress signature_def['regress_x_to_y2']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y2:0 Method name is: tensorflow/serving/regress signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['x'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_45:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['y'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_50:0 Method name is: tensorflow/serving/predict""" self.maxDiff = None # Produce VAR_54 useful error msg if the comparison fails self.assertMultiLineEqual(VAR_12, VAR_13) self.assertEqual(err.getvalue().strip(), '') def FUNC_3(self): class CLASS_2(tracking.AutoTrackable): @def_function.function def FUNC_44(self, VAR_54, VAR_55, VAR_56): if VAR_56: return VAR_54 + VAR_55 else: return VAR_54 * VAR_55 @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2, 2), dtype=dtypes.float32) ]) def FUNC_41(self, VAR_45): return VAR_45 + 2 @def_function.function def __call__(self, VAR_50, VAR_56=7): return VAR_50 + 2 * VAR_56 VAR_14 = os.path.join(test.get_temp_dir(), 'dummy_model') VAR_15 = CLASS_2() VAR_15.func1(constant_op.constant(5), constant_op.constant(9), True) VAR_15(constant_op.constant(5)) save.save(VAR_15, VAR_14) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args(['show', '--dir', VAR_14, '--all']) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_13 = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['__saved_model_init_op']: The given SavedModel SignatureDef contains the following input(s): The given SavedModel SignatureDef contains the following VAR_12(s): outputs['__saved_model_init_op'] tensor_info: dtype: DT_INVALID shape: unknown_rank name: NoOp Method name is: signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['x'] tensor_info: dtype: DT_FLOAT shape: (2, 2) name: serving_default_x:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['output_0'] tensor_info: dtype: DT_FLOAT shape: (2, 2) name: PartitionedCall:0 Method name is: tensorflow/serving/predict Concrete Functions: Function Name: '__call__' Option #1 Callable with: Argument #1 VAR_50: TensorSpec(shape=(), dtype=tf.int32, name='y') Argument #2 DType: int Value: 7 Function Name: 'func1' Option #1 Callable with: Argument #1 VAR_54: TensorSpec(shape=(), dtype=tf.int32, name='a') Argument #2 VAR_55: TensorSpec(shape=(), dtype=tf.int32, name='b') Argument #3 DType: bool Value: True Function Name: 'func2' Option #1 Callable with: Argument #1 VAR_45: TensorSpec(shape=(2, 2), dtype=tf.float32, name='x') """.strip() # pylint: enable=line-too-long self.maxDiff = None # Produce VAR_54 useful error msg if the comparison fails self.assertMultiLineEqual(VAR_12, VAR_13) self.assertEqual(err.getvalue().strip(), '') def FUNC_4(self): class CLASS_2(tracking.AutoTrackable): def __init__(self): VAR_57 = def_function.function( self.multiply, input_signature=[ tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32) ]) self.pure_concrete_function = VAR_57.get_concrete_function() super(CLASS_2, self).__init__() def FUNC_45(self, VAR_54, VAR_55): return VAR_54 * VAR_55 VAR_14 = os.path.join(test.get_temp_dir(), 'dummy_model') VAR_15 = CLASS_2() save.save(VAR_15, VAR_14) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args(['show', '--dir', VAR_14, '--all']) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_13 = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['__saved_model_init_op']: The given SavedModel SignatureDef contains the following input(s): The given SavedModel SignatureDef contains the following VAR_12(s): outputs['__saved_model_init_op'] tensor_info: dtype: DT_INVALID shape: unknown_rank name: NoOp Method name is: signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['a'] tensor_info: dtype: DT_FLOAT shape: () name: serving_default_a:0 inputs['b'] tensor_info: dtype: DT_FLOAT shape: () name: serving_default_b:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['output_0'] tensor_info: dtype: DT_FLOAT shape: () name: PartitionedCall:0 Method name is: tensorflow/serving/predict Concrete Functions: Function Name: 'pure_concrete_function' Option #1 Callable with: Argument #1 VAR_54: TensorSpec(shape=(), dtype=tf.float32, name='a') Argument #2 VAR_55: TensorSpec(shape=(), dtype=tf.float32, name='b') """.strip() # pylint: enable=line-too-long self.maxDiff = None # Produce VAR_54 useful error msg if the comparison fails self.assertMultiLineEqual(VAR_12, VAR_13) self.assertEqual(err.getvalue().strip(), '') def FUNC_5(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args(['show', '--dir', VAR_10]) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_13 = 'The given SavedModel contains the following tag-sets:\n\'serve\'' self.assertMultiLineEqual(VAR_12, VAR_13) self.assertEqual(err.getvalue().strip(), '') def FUNC_6(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args( ['show', '--dir', VAR_10, '--tag_set', 'serve']) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_16 = ('The given SavedModel MetaGraphDef contains SignatureDefs ' 'with the following keys:') VAR_17 = 'SignatureDef key: ' VAR_18 = [ '"classify_x2_to_y3"', '"classify_x_to_y"', '"regress_x2_to_y3"', '"regress_x_to_y"', '"regress_x_to_y2"', '"serving_default"' ] self.assertMultiLineEqual( VAR_12, '\n'.join([VAR_16] + [VAR_17 + exp_key for exp_key in VAR_18])) self.assertEqual(err.getvalue().strip(), '') def FUNC_7(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args( ['show', '--dir', VAR_10, '--tag_set', 'badtagset']) with self.assertRaises(RuntimeError): saved_model_cli.show(VAR_11) def FUNC_8(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args([ 'show', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default' ]) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_19 = ( 'The given SavedModel SignatureDef contains the following input(s):\n' ' inputs[\'x\'] tensor_info:\n' ' dtype: DT_FLOAT\n shape: (-1, 1)\n name: VAR_45:0\n' 'The given SavedModel SignatureDef contains the following VAR_12(s):\n' ' outputs[\'y\'] tensor_info:\n' ' dtype: DT_FLOAT\n shape: (-1, 1)\n name: VAR_50:0\n' 'Method name is: tensorflow/serving/predict') self.assertEqual(VAR_12, VAR_19) self.assertEqual(err.getvalue().strip(), '') def FUNC_9(self): VAR_20 = meta_graph_pb2.TensorInfo() VAR_20.dtype = types_pb2.DT_FLOAT_REF with FUNC_0() as (out, err): saved_model_cli._print_tensor_info(VAR_20) self.assertTrue('DT_FLOAT_REF' in out.getvalue().strip()) self.assertEqual(err.getvalue().strip(), '') def FUNC_10(self): VAR_21 = 'input1=/path/file.txt[ab3];input2=file2' VAR_22 = 'input3=np.zeros([2,2]);input4=[4,5]' VAR_23 = saved_model_cli.preprocess_inputs_arg_string(VAR_21) VAR_24 = saved_model_cli.preprocess_input_exprs_arg_string( VAR_22, safe=False) self.assertTrue(VAR_23['input1'] == ('/path/file.txt', 'ab3')) self.assertTrue(VAR_23['input2'] == ('file2', None)) print(VAR_24['input3']) self.assertAllClose(VAR_24['input3'], np.zeros([2, 2])) self.assertAllClose(VAR_24['input4'], [4, 5]) self.assertTrue(len(VAR_23) == 2) self.assertTrue(len(VAR_24) == 2) def FUNC_11(self): VAR_25 = 'inputs=[{"text":["foo"], "bytes":[b"bar"]}]' VAR_23 = saved_model_cli.preprocess_input_examples_arg_string( VAR_25) VAR_26 = example_pb2.Example.FromString(VAR_23['inputs'][0]) self.assertProtoEquals( """ features { VAR_26 { key: "bytes" value { bytes_list { value: "bar" } } } VAR_26 { key: "text" value { bytes_list { value: "foo" } } } } """, VAR_26) def FUNC_12(self): VAR_25 = 'inputs=os.system("echo hacked")' with self.assertRaisesRegex(RuntimeError, 'not VAR_54 valid python literal.'): saved_model_cli.preprocess_input_examples_arg_string(VAR_25) def FUNC_13(self): VAR_21 = (r'inputx=C:\Program Files\data.npz[v:0];' r'input:0=VAR_56:\PROGRA~1\data.npy') VAR_23 = saved_model_cli.preprocess_inputs_arg_string(VAR_21) self.assertTrue(VAR_23['inputx'] == (r'C:\Program Files\data.npz', 'v:0')) self.assertTrue(VAR_23['input:0'] == (r'c:\PROGRA~1\data.npy', None)) def FUNC_14(self): VAR_21 = 'inputx=file[[v1]v2' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(VAR_21) VAR_21 = 'inputx:file' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(VAR_21) VAR_21 = 'inputx:np.zeros((5))' with self.assertRaisesRegex(RuntimeError, 'format is incorrect'): saved_model_cli.preprocess_input_exprs_arg_string(VAR_21, safe=False) def FUNC_15(self): VAR_27 = np.array([[1], [2]]) VAR_28 = np.array(range(6)).reshape(2, 3) VAR_29 = os.path.join(test.get_temp_dir(), 'input0.npy') VAR_30 = os.path.join(test.get_temp_dir(), 'input1.npy') np.save(VAR_29, VAR_27) np.save(VAR_30, VAR_28) VAR_21 = 'x0=' + VAR_29 + '[VAR_27];VAR_28=' + VAR_30 VAR_31 = saved_model_cli.load_inputs_from_input_arg_string( VAR_21, '', '') self.assertTrue(np.all(VAR_31['x0'] == VAR_27)) self.assertTrue(np.all(VAR_31['x1'] == VAR_28)) def FUNC_16(self): VAR_27 = np.array([[1], [2]]) VAR_32 = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(VAR_32, VAR_54=VAR_27) VAR_21 = 'x=' + VAR_32 + '[VAR_54];VAR_50=' + VAR_32 VAR_31 = saved_model_cli.load_inputs_from_input_arg_string( VAR_21, '', '') self.assertTrue(np.all(VAR_31['x'] == VAR_27)) self.assertTrue(np.all(VAR_31['y'] == VAR_27)) def FUNC_17(self): VAR_33 = {'a': 5, 'b': np.array(range(4))} VAR_34 = np.array([1]) VAR_35 = np.array([[1], [3]]) VAR_36 = os.path.join(test.get_temp_dir(), 'pickle0.pkl') VAR_37 = os.path.join(test.get_temp_dir(), 'pickle1.pkl') VAR_38 = os.path.join(test.get_temp_dir(), 'pickle2.pkl') with open(VAR_36, 'wb') as f: pickle.dump(VAR_33, f) with open(VAR_37, 'wb') as f: pickle.dump(VAR_34, f) with open(VAR_38, 'wb') as f: pickle.dump(VAR_35, f) VAR_21 = 'x=' + VAR_36 + '[VAR_55];VAR_50=' + VAR_37 + '[VAR_56];' VAR_21 += 'z=' + VAR_38 VAR_31 = saved_model_cli.load_inputs_from_input_arg_string( VAR_21, '', '') self.assertTrue(np.all(VAR_31['x'] == VAR_33['b'])) self.assertTrue(np.all(VAR_31['y'] == VAR_34)) self.assertTrue(np.all(VAR_31['z'] == VAR_35)) def FUNC_18(self): VAR_28 = np.ones([2, 10]) VAR_39 = np.array([[1], [2], [3]]) VAR_40 = np.mgrid[0:5, 0:5] VAR_41 = [[3], [4]] VAR_22 = ('x1=np.ones([2,10]);VAR_39=np.array([[1],[2],[3]]);' 'x3=np.mgrid[0:5,0:5];VAR_41=[[3],[4]]') VAR_31 = saved_model_cli.load_inputs_from_input_arg_string( '', VAR_22, '') self.assertTrue(np.all(VAR_31['x1'] == VAR_28)) self.assertTrue(np.all(VAR_31['x2'] == VAR_39)) self.assertTrue(np.all(VAR_31['x3'] == VAR_40)) self.assertTrue(np.all(VAR_31['x4'] == VAR_41)) def FUNC_19(self): VAR_27 = np.array([[1], [2]]) VAR_32 = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(VAR_32, VAR_54=VAR_27) VAR_28 = np.ones([2, 10]) VAR_21 = 'x0=' + VAR_32 + '[VAR_54]' VAR_22 = 'x1=np.ones([2,10])' VAR_31 = saved_model_cli.load_inputs_from_input_arg_string( VAR_21, VAR_22, '') self.assertTrue(np.all(VAR_31['x0'] == VAR_27)) self.assertTrue(np.all(VAR_31['x1'] == VAR_28)) def FUNC_20(self): VAR_27 = np.array([[1], [2]]) VAR_32 = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(VAR_32, VAR_54=VAR_27) VAR_28 = np.ones([2, 10]) VAR_21 = 'x0=' + VAR_32 + '[VAR_54]' VAR_22 = 'x0=np.ones([2,10])' VAR_31 = saved_model_cli.load_inputs_from_input_arg_string( VAR_21, VAR_22, '') self.assertTrue(np.all(VAR_31['x0'] == VAR_28)) def FUNC_21(self): VAR_27 = np.array([[1], [2]]) VAR_28 = np.array(range(5)) VAR_32 = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(VAR_32, VAR_54=VAR_27, VAR_55=VAR_28) VAR_21 = 'x=' + VAR_32 with self.assertRaises(RuntimeError): saved_model_cli.load_inputs_from_input_arg_string(VAR_21, '', '') def FUNC_22(self): VAR_27 = np.array([[1], [2]]) VAR_28 = np.array(range(5)) VAR_32 = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(VAR_32, VAR_54=VAR_27, VAR_55=VAR_28) VAR_21 = 'x=' + VAR_32 + '[VAR_56]' with self.assertRaises(RuntimeError): saved_model_cli.load_inputs_from_input_arg_string(VAR_21, '', '') @parameterized.named_parameters(('non_tfrt', False)) def FUNC_23(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = os.path.join(test.get_temp_dir(), 'new_dir' + ('tfrt' if VAR_5 else '')) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":[8.0],"x2":[5.0]}, {"x":[4.0],"x2":[3.0]}]', '--outdir', VAR_42 ] + (['--use_tfrt'] if VAR_5 else [])) saved_model_cli.run(VAR_11) VAR_43 = np.load(os.path.join(VAR_42, 'outputs.npy')) VAR_44 = np.array([[6.0], [4.0]]) self.assertAllEqual(VAR_44, VAR_43) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_24(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_45 = np.array([[1], [2]]) VAR_46 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommand_inputs.npz') np.savez(VAR_32, VAR_27=VAR_45, VAR_28=VAR_46) VAR_47 = os.path.join(test.get_temp_dir(), 'outputs.npy') if os.path.exists(VAR_47): os.remove(VAR_47) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x2_to_y3', '--inputs', 'inputs=' + VAR_32 + '[VAR_27]', '--outdir', test.get_temp_dir() ] + (['--use_tfrt'] if VAR_5 else [])) saved_model_cli.run(VAR_11) VAR_43 = np.load(VAR_47) VAR_44 = np.array([[3.5], [4.0]]) self.assertAllClose(VAR_44, VAR_43) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_25(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_45 = np.array([[1], [2]]) VAR_46 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommandNewOutdir_inputs.npz') VAR_42 = os.path.join(test.get_temp_dir(), 'new_dir') if os.path.isdir(VAR_42): shutil.rmtree(VAR_42) np.savez(VAR_32, VAR_27=VAR_45, VAR_28=VAR_46) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + VAR_32 + '[VAR_27]', '--outdir', VAR_42 ] + (['--use_tfrt'] if VAR_5 else [])) saved_model_cli.run(VAR_11) VAR_43 = np.load(os.path.join(VAR_42, 'y.npy')) VAR_44 = np.array([[2.5], [3.0]]) self.assertAllClose(VAR_44, VAR_43) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_26(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_45 = np.array([[1], [2]]) VAR_46 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommandOutOverwrite_inputs.npz') np.savez(VAR_32, VAR_27=VAR_45, VAR_28=VAR_46) VAR_47 = os.path.join(test.get_temp_dir(), 'y.npy') open(VAR_47, 'a').close() VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + VAR_32 + '[VAR_27]', '--outdir', test.get_temp_dir(), '--overwrite' ] + (['--use_tfrt'] if VAR_5 else [])) saved_model_cli.run(VAR_11) VAR_43 = np.load(VAR_47) VAR_44 = np.array([[2.5], [3.0]]) self.assertAllClose(VAR_44, VAR_43) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_27(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x2_to_y3', '--input_exprs', 'x2=np.ones((3,1))' ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaises(ValueError): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_28(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'INVALID_SIGNATURE', '--input_exprs', 'x2=np.ones((3,1))' ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaisesRegex(ValueError, 'Could not find signature "INVALID_SIGNATURE"'): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_29(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = os.path.join(test.get_temp_dir(), 'new_dir') VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs={"x":8.0,"x2":5.0}', '--outdir', VAR_42 ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaisesRegex(ValueError, 'must be VAR_54 list'): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_30(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = os.path.join(test.get_temp_dir(), 'new_dir') VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":8.0,"x2":5.0}]', '--outdir', VAR_42 ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaisesRegex(ValueError, 'feature value must be VAR_54 list'): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_31(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = os.path.join(test.get_temp_dir(), 'new_dir') VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":[[1],[2]]}]', '--outdir', VAR_42 ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaisesRegex(ValueError, 'is not supported'): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_32(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_45 = np.array([[1], [2]]) VAR_46 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommandOutOverwrite_inputs.npz') np.savez(VAR_32, VAR_27=VAR_45, VAR_28=VAR_46) VAR_47 = os.path.join(test.get_temp_dir(), 'y.npy') open(VAR_47, 'a').close() VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + VAR_32 + '[VAR_27]', '--outdir', test.get_temp_dir() ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaises(RuntimeError): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_33(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default' ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaises(AttributeError): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_34(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_45 = np.array([[1], [2]]) VAR_46 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommandNewOutdir_inputs.npz') VAR_42 = os.path.join(test.get_temp_dir(), 'new_dir') if os.path.isdir(VAR_42): shutil.rmtree(VAR_42) np.savez(VAR_32, VAR_27=VAR_45, VAR_28=VAR_46) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + VAR_32 + '[VAR_27]', '--outdir', VAR_42, '--tf_debug' ] + (['--use_tfrt'] if VAR_5 else [])) def FUNC_40(VAR_48): return VAR_48 with test.mock.patch.object( local_cli_wrapper, 'LocalCLIDebugWrapperSession', side_effect=FUNC_40, autospec=True) as fake: saved_model_cli.run(VAR_11) fake.assert_called_with(test.mock.ANY) VAR_43 = np.load(os.path.join(VAR_42, 'y.npy')) VAR_44 = np.array([[2.5], [3.0]]) self.assertAllClose(VAR_44, VAR_43) def FUNC_35(self): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args(['scan', '--dir', VAR_10]) with FUNC_0() as (out, _): saved_model_cli.scan(VAR_11) VAR_12 = out.getvalue().strip() self.assertTrue('does not contain denylisted ops' in VAR_12) def FUNC_36(self): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args( ['scan', '--dir', VAR_10, '--tag_set', 'serve']) VAR_49 = saved_model_cli._OP_DENYLIST saved_model_cli._OP_DENYLIST = set(['VariableV2']) with FUNC_0() as (out, _): saved_model_cli.scan(VAR_11) saved_model_cli._OP_DENYLIST = VAR_49 VAR_12 = out.getvalue().strip() self.assertTrue('\'VariableV2\'' in VAR_12) def FUNC_37(self): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir') VAR_11 = self.parser.parse_args([ 'aot_compile_cpu', '--dir', VAR_10, '--tag_set', 'serve', '--output_prefix', VAR_42, '--cpp_class', 'Compiled', '--signature_def_key', 'MISSING' ]) with self.assertRaisesRegex(ValueError, 'Unable to find signature_def'): saved_model_cli.aot_compile_cpu(VAR_11) class CLASS_1(tracking.AutoTrackable): def __init__(self): self.var = variables.Variable(1.0, name='my_var') self.write_var = variables.Variable(1.0, name='write_var') @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2, 2), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def FUNC_41(self, VAR_45, VAR_50): del VAR_50 return {'res': VAR_45 + self.var} @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2048, 16), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def FUNC_42(self, VAR_45, VAR_50): del VAR_50 return {'res': VAR_45 + self.var} @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def FUNC_43(self, VAR_45, VAR_50): del VAR_50 self.write_var.assign(VAR_45 + self.var) return {'res': self.write_var} @parameterized.named_parameters( ('VariablesToFeedNone', '', 'func2', None), ('VariablesToFeedNoneTargetAarch64Linux', '', 'func2', 'aarch64-none-linux-gnu'), ('VariablesToFeedNoneTargetAarch64Android', '', 'func2', 'aarch64-none-android'), ('VariablesToFeedAll', 'all', 'func2', None), ('VariablesToFeedMyVar', 'my_var', 'func2', None), ('VariablesToFeedNoneLargeConstant', '', 'func3', None), ('WriteToWriteVar', 'all', 'func_write', None), ) def FUNC_38(self, VAR_6, VAR_7, VAR_8): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') VAR_14 = os.path.join(test.get_temp_dir(), 'dummy_model') VAR_15 = self.AOTCompileDummyModel() VAR_7 = getattr(VAR_15, VAR_7) with self.cached_session(): self.evaluate(VAR_15.var.initializer) self.evaluate(VAR_15.write_var.initializer) save.save(VAR_15, VAR_14, signatures={'func': VAR_7}) self.parser = saved_model_cli.create_parser() VAR_51 = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir/out') VAR_11 = [ # Use the default seving signature_key. 'aot_compile_cpu', '--dir', VAR_14, '--tag_set', 'serve', '--signature_def_key', 'func', '--output_prefix', VAR_51, '--variables_to_feed', VAR_6, '--cpp_class', 'Generated' ] if VAR_8: VAR_11.extend(['--target_triple', VAR_8]) VAR_11 = self.parser.parse_args(VAR_11) with test.mock.patch.object(logging, 'warn') as captured_warn: saved_model_cli.aot_compile_cpu(VAR_11) self.assertRegex( str(captured_warn.call_args), 'Signature input key \'y\'.*has been pruned while freezing the graph.') self.assertTrue(file_io.file_exists('{}.o'.format(VAR_51))) self.assertTrue(file_io.file_exists('{}.h'.format(VAR_51))) self.assertTrue(file_io.file_exists('{}_metadata.o'.format(VAR_51))) self.assertTrue( file_io.file_exists('{}_makefile.inc'.format(VAR_51))) VAR_52 = file_io.read_file_to_string('{}.h'.format(VAR_51)) self.assertIn('class Generated', VAR_52) self.assertIn('arg_feed_x_data', VAR_52) self.assertIn('result_fetch_res_data', VAR_52) self.assertNotIn('arg_feed_y_data', VAR_52) if VAR_6: self.assertIn('set_var_param_my_var_data(const float', VAR_52) self.assertNotIn('set_var_param_my_var_data(float', VAR_52) if VAR_7 == VAR_15.func_write: self.assertIn('set_var_param_write_var_data(float', VAR_52) self.assertNotIn('set_var_param_write_var_data(const float', VAR_52) VAR_53 = file_io.read_file_to_string( '{}_makefile.inc'.format(VAR_51)) self.assertIn('-D_GLIBCXX_USE_CXX11_ABI=', VAR_53) def FUNC_39(self): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') VAR_6 = 'all' VAR_7 = 'func2' VAR_14 = os.path.join(test.get_temp_dir(), 'dummy_model') VAR_15 = self.AOTCompileDummyModel() VAR_7 = getattr(VAR_15, VAR_7) with self.cached_session(): self.evaluate(VAR_15.var.initializer) self.evaluate(VAR_15.write_var.initializer) save.save(VAR_15, VAR_14, signatures={'func': VAR_7}) self.parser = saved_model_cli.create_parser() VAR_51 = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir/out') VAR_11 = [ # Use the default seving signature_key. 'freeze_model', '--dir', VAR_14, '--tag_set', 'serve', '--signature_def_key', 'func', '--output_prefix', VAR_51, '--variables_to_feed', VAR_6 ] VAR_11 = self.parser.parse_args(VAR_11) with test.mock.patch.object(logging, 'warn'): saved_model_cli.freeze_model(VAR_11) self.assertTrue( file_io.file_exists(os.path.join(VAR_51, 'frozen_graph.pb'))) self.assertTrue( file_io.file_exists(os.path.join(VAR_51, 'config.pbtxt'))) if __name__ == '__main__': test.main()
import .contextlib import os import pickle import platform import shutil import .sys from absl.testing import parameterized import numpy as np from six import StringIO from tensorflow.core.example import example_pb2 from tensorflow.core.framework import types_pb2 from tensorflow.core.protobuf import meta_graph_pb2 from tensorflow.python.debug.wrappers import local_cli_wrapper from tensorflow.python.eager import def_function from tensorflow.python.framework import .constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.lib.io import file_io from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import save from tensorflow.python.tools import saved_model_cli from tensorflow.python.training.tracking import tracking VAR_0 = ('cc/saved_model/testdata/half_plus_two/00000123') @contextlib.contextmanager def FUNC_0(): VAR_1, VAR_2 = StringIO(), StringIO() VAR_3, VAR_4 = VAR_9.stdout, VAR_9.stderr try: VAR_9.stdout, VAR_9.stderr = VAR_1, VAR_2 yield VAR_9.stdout, VAR_9.stderr finally: VAR_9.stdout, VAR_9.stderr = VAR_3, VAR_4 class CLASS_0(test.TestCase, parameterized.TestCase): def FUNC_1(self): super(CLASS_0, self).setUp() if platform.system() == 'Windows': self.skipTest('Skipping failing tests on Windows.') def FUNC_2(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args(['show', '--dir', VAR_10, '--all']) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_13 = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['classify_x2_to_y3']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: x2:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['scores'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y3:0 Method name is: tensorflow/serving/classify signature_def['classify_x_to_y']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['scores'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_47:0 Method name is: tensorflow/serving/classify signature_def['regress_x2_to_y3']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: x2:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y3:0 Method name is: tensorflow/serving/regress signature_def['regress_x_to_y']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_47:0 Method name is: tensorflow/serving/regress signature_def['regress_x_to_y2']: The given SavedModel SignatureDef contains the following input(s): inputs['inputs'] tensor_info: dtype: DT_STRING shape: unknown_rank name: tf_example:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['outputs'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: y2:0 Method name is: tensorflow/serving/regress signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['x'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_42:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['y'] tensor_info: dtype: DT_FLOAT shape: (-1, 1) name: VAR_47:0 Method name is: tensorflow/serving/predict""" self.maxDiff = None # Produce VAR_51 useful error msg if the comparison fails self.assertMultiLineEqual(VAR_12, VAR_13) self.assertEqual(err.getvalue().strip(), '') def FUNC_3(self): class CLASS_2(tracking.AutoTrackable): @def_function.function def FUNC_41(self, VAR_51, VAR_52, VAR_53): if VAR_53: return VAR_51 + VAR_52 else: return VAR_51 * VAR_52 @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2, 2), dtype=dtypes.float32) ]) def FUNC_38(self, VAR_42): return VAR_42 + 2 @def_function.function def __call__(self, VAR_47, VAR_53=7): return VAR_47 + 2 * VAR_53 VAR_14 = os.path.join(test.get_temp_dir(), 'dummy_model') VAR_15 = CLASS_2() VAR_15.func1(constant_op.constant(5), constant_op.constant(9), True) VAR_15(constant_op.constant(5)) save.save(VAR_15, VAR_14) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args(['show', '--dir', VAR_14, '--all']) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_13 = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['__saved_model_init_op']: The given SavedModel SignatureDef contains the following input(s): The given SavedModel SignatureDef contains the following VAR_12(s): outputs['__saved_model_init_op'] tensor_info: dtype: DT_INVALID shape: unknown_rank name: NoOp Method name is: signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['x'] tensor_info: dtype: DT_FLOAT shape: (2, 2) name: serving_default_x:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['output_0'] tensor_info: dtype: DT_FLOAT shape: (2, 2) name: PartitionedCall:0 Method name is: tensorflow/serving/predict Concrete Functions: Function Name: '__call__' Option #1 Callable with: Argument #1 VAR_47: TensorSpec(shape=(), dtype=tf.int32, name='y') Argument #2 DType: int Value: 7 Function Name: 'func1' Option #1 Callable with: Argument #1 VAR_51: TensorSpec(shape=(), dtype=tf.int32, name='a') Argument #2 VAR_52: TensorSpec(shape=(), dtype=tf.int32, name='b') Argument #3 DType: bool Value: True Function Name: 'func2' Option #1 Callable with: Argument #1 VAR_42: TensorSpec(shape=(2, 2), dtype=tf.float32, name='x') """.strip() # pylint: enable=line-too-long self.maxDiff = None # Produce VAR_51 useful error msg if the comparison fails self.assertMultiLineEqual(VAR_12, VAR_13) self.assertEqual(err.getvalue().strip(), '') def FUNC_4(self): class CLASS_2(tracking.AutoTrackable): def __init__(self): VAR_54 = def_function.function( self.multiply, input_signature=[ tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32) ]) self.pure_concrete_function = VAR_54.get_concrete_function() super(CLASS_2, self).__init__() def FUNC_42(self, VAR_51, VAR_52): return VAR_51 * VAR_52 VAR_14 = os.path.join(test.get_temp_dir(), 'dummy_model') VAR_15 = CLASS_2() save.save(VAR_15, VAR_14) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args(['show', '--dir', VAR_14, '--all']) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_13 = """MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['__saved_model_init_op']: The given SavedModel SignatureDef contains the following input(s): The given SavedModel SignatureDef contains the following VAR_12(s): outputs['__saved_model_init_op'] tensor_info: dtype: DT_INVALID shape: unknown_rank name: NoOp Method name is: signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['a'] tensor_info: dtype: DT_FLOAT shape: () name: serving_default_a:0 inputs['b'] tensor_info: dtype: DT_FLOAT shape: () name: serving_default_b:0 The given SavedModel SignatureDef contains the following VAR_12(s): outputs['output_0'] tensor_info: dtype: DT_FLOAT shape: () name: PartitionedCall:0 Method name is: tensorflow/serving/predict Concrete Functions: Function Name: 'pure_concrete_function' Option #1 Callable with: Argument #1 VAR_51: TensorSpec(shape=(), dtype=tf.float32, name='a') Argument #2 VAR_52: TensorSpec(shape=(), dtype=tf.float32, name='b') """.strip() # pylint: enable=line-too-long self.maxDiff = None # Produce VAR_51 useful error msg if the comparison fails self.assertMultiLineEqual(VAR_12, VAR_13) self.assertEqual(err.getvalue().strip(), '') def FUNC_5(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args(['show', '--dir', VAR_10]) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_13 = 'The given SavedModel contains the following tag-sets:\n\'serve\'' self.assertMultiLineEqual(VAR_12, VAR_13) self.assertEqual(err.getvalue().strip(), '') def FUNC_6(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args( ['show', '--dir', VAR_10, '--tag_set', 'serve']) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_16 = ('The given SavedModel MetaGraphDef contains SignatureDefs ' 'with the following keys:') VAR_17 = 'SignatureDef key: ' VAR_18 = [ '"classify_x2_to_y3"', '"classify_x_to_y"', '"regress_x2_to_y3"', '"regress_x_to_y"', '"regress_x_to_y2"', '"serving_default"' ] self.assertMultiLineEqual( VAR_12, '\n'.join([VAR_16] + [VAR_17 + exp_key for exp_key in VAR_18])) self.assertEqual(err.getvalue().strip(), '') def FUNC_7(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args( ['show', '--dir', VAR_10, '--tag_set', 'badtagset']) with self.assertRaises(RuntimeError): saved_model_cli.show(VAR_11) def FUNC_8(self): VAR_10 = test.test_src_dir_path(VAR_0) self.parser = saved_model_cli.create_parser() VAR_11 = self.parser.parse_args([ 'show', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default' ]) with FUNC_0() as (out, err): saved_model_cli.show(VAR_11) VAR_12 = out.getvalue().strip() VAR_19 = ( 'The given SavedModel SignatureDef contains the following input(s):\n' ' inputs[\'x\'] tensor_info:\n' ' dtype: DT_FLOAT\n shape: (-1, 1)\n name: VAR_42:0\n' 'The given SavedModel SignatureDef contains the following VAR_12(s):\n' ' outputs[\'y\'] tensor_info:\n' ' dtype: DT_FLOAT\n shape: (-1, 1)\n name: VAR_47:0\n' 'Method name is: tensorflow/serving/predict') self.assertEqual(VAR_12, VAR_19) self.assertEqual(err.getvalue().strip(), '') def FUNC_9(self): VAR_20 = meta_graph_pb2.TensorInfo() VAR_20.dtype = types_pb2.DT_FLOAT_REF with FUNC_0() as (out, err): saved_model_cli._print_tensor_info(VAR_20) self.assertTrue('DT_FLOAT_REF' in out.getvalue().strip()) self.assertEqual(err.getvalue().strip(), '') def FUNC_10(self): VAR_21 = 'input1=/path/file.txt[ab3];input2=file2' VAR_22 = 'input3=np.zeros([2,2]);input4=[4,5]' VAR_23 = saved_model_cli.preprocess_inputs_arg_string(VAR_21) VAR_24 = saved_model_cli.preprocess_input_exprs_arg_string( VAR_22, safe=False) self.assertTrue(VAR_23['input1'] == ('/path/file.txt', 'ab3')) self.assertTrue(VAR_23['input2'] == ('file2', None)) print(VAR_24['input3']) self.assertAllClose(VAR_24['input3'], np.zeros([2, 2])) self.assertAllClose(VAR_24['input4'], [4, 5]) self.assertTrue(len(VAR_23) == 2) self.assertTrue(len(VAR_24) == 2) def FUNC_11(self): VAR_25 = 'inputs=[{"text":["foo"], "bytes":[b"bar"]}]' VAR_23 = saved_model_cli.preprocess_input_examples_arg_string( VAR_25) VAR_26 = example_pb2.Example.FromString(VAR_23['inputs'][0]) self.assertProtoEquals( """ features { VAR_26 { key: "bytes" value { bytes_list { value: "bar" } } } VAR_26 { key: "text" value { bytes_list { value: "foo" } } } } """, VAR_26) def FUNC_12(self): VAR_25 = 'inputs=os.system("echo hacked")' with self.assertRaisesRegex(RuntimeError, 'not VAR_51 valid python literal.'): saved_model_cli.preprocess_input_examples_arg_string(VAR_25) def FUNC_13(self): VAR_21 = (r'inputx=C:\Program Files\data.npz[v:0];' r'input:0=VAR_53:\PROGRA~1\data.npy') VAR_23 = saved_model_cli.preprocess_inputs_arg_string(VAR_21) self.assertTrue(VAR_23['inputx'] == (r'C:\Program Files\data.npz', 'v:0')) self.assertTrue(VAR_23['input:0'] == (r'c:\PROGRA~1\data.npy', None)) def FUNC_14(self): VAR_21 = 'inputx=file[[v1]v2' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(VAR_21) VAR_21 = 'inputx:file' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(VAR_21) VAR_21 = 'inputx:np.zeros((5))' with self.assertRaisesRegex(RuntimeError, 'format is incorrect'): saved_model_cli.preprocess_input_exprs_arg_string(VAR_21, safe=False) def FUNC_15(self): VAR_27 = np.array([[1], [2]]) VAR_28 = np.array(range(6)).reshape(2, 3) VAR_29 = os.path.join(test.get_temp_dir(), 'input0.npy') VAR_30 = os.path.join(test.get_temp_dir(), 'input1.npy') np.save(VAR_29, VAR_27) np.save(VAR_30, VAR_28) VAR_21 = 'x0=' + VAR_29 + '[VAR_27];VAR_28=' + VAR_30 VAR_31 = saved_model_cli.load_inputs_from_input_arg_string( VAR_21, '', '') self.assertTrue(np.all(VAR_31['x0'] == VAR_27)) self.assertTrue(np.all(VAR_31['x1'] == VAR_28)) def FUNC_16(self): VAR_27 = np.array([[1], [2]]) VAR_32 = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(VAR_32, VAR_51=VAR_27) VAR_21 = 'x=' + VAR_32 + '[VAR_51];VAR_47=' + VAR_32 VAR_31 = saved_model_cli.load_inputs_from_input_arg_string( VAR_21, '', '') self.assertTrue(np.all(VAR_31['x'] == VAR_27)) self.assertTrue(np.all(VAR_31['y'] == VAR_27)) def FUNC_17(self): VAR_33 = {'a': 5, 'b': np.array(range(4))} VAR_34 = np.array([1]) VAR_35 = np.array([[1], [3]]) VAR_36 = os.path.join(test.get_temp_dir(), 'pickle0.pkl') VAR_37 = os.path.join(test.get_temp_dir(), 'pickle1.pkl') VAR_38 = os.path.join(test.get_temp_dir(), 'pickle2.pkl') with open(VAR_36, 'wb') as f: pickle.dump(VAR_33, f) with open(VAR_37, 'wb') as f: pickle.dump(VAR_34, f) with open(VAR_38, 'wb') as f: pickle.dump(VAR_35, f) VAR_21 = 'x=' + VAR_36 + '[VAR_52];VAR_47=' + VAR_37 + '[VAR_53];' VAR_21 += 'z=' + VAR_38 VAR_31 = saved_model_cli.load_inputs_from_input_arg_string( VAR_21, '', '') self.assertTrue(np.all(VAR_31['x'] == VAR_33['b'])) self.assertTrue(np.all(VAR_31['y'] == VAR_34)) self.assertTrue(np.all(VAR_31['z'] == VAR_35)) def FUNC_18(self): VAR_27 = np.array([[1], [2]]) VAR_28 = np.array(range(5)) VAR_32 = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(VAR_32, VAR_51=VAR_27, VAR_52=VAR_28) VAR_21 = 'x=' + VAR_32 with self.assertRaises(RuntimeError): saved_model_cli.load_inputs_from_input_arg_string(VAR_21, '', '') def FUNC_19(self): VAR_27 = np.array([[1], [2]]) VAR_28 = np.array(range(5)) VAR_32 = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(VAR_32, VAR_51=VAR_27, VAR_52=VAR_28) VAR_21 = 'x=' + VAR_32 + '[VAR_53]' with self.assertRaises(RuntimeError): saved_model_cli.load_inputs_from_input_arg_string(VAR_21, '', '') @parameterized.named_parameters(('non_tfrt', False)) def FUNC_20(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_39 = os.path.join(test.get_temp_dir(), 'new_dir' + ('tfrt' if VAR_5 else '')) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":[8.0],"x2":[5.0]}, {"x":[4.0],"x2":[3.0]}]', '--outdir', VAR_39 ] + (['--use_tfrt'] if VAR_5 else [])) saved_model_cli.run(VAR_11) VAR_40 = np.load(os.path.join(VAR_39, 'outputs.npy')) VAR_41 = np.array([[6.0], [4.0]]) self.assertAllEqual(VAR_41, VAR_40) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_21(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = np.array([[1], [2]]) VAR_43 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommand_inputs.npz') np.savez(VAR_32, VAR_27=VAR_42, VAR_28=VAR_43) VAR_44 = os.path.join(test.get_temp_dir(), 'outputs.npy') if os.path.exists(VAR_44): os.remove(VAR_44) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x2_to_y3', '--inputs', 'inputs=' + VAR_32 + '[VAR_27]', '--outdir', test.get_temp_dir() ] + (['--use_tfrt'] if VAR_5 else [])) saved_model_cli.run(VAR_11) VAR_40 = np.load(VAR_44) VAR_41 = np.array([[3.5], [4.0]]) self.assertAllClose(VAR_41, VAR_40) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_22(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = np.array([[1], [2]]) VAR_43 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommandNewOutdir_inputs.npz') VAR_39 = os.path.join(test.get_temp_dir(), 'new_dir') if os.path.isdir(VAR_39): shutil.rmtree(VAR_39) np.savez(VAR_32, VAR_27=VAR_42, VAR_28=VAR_43) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + VAR_32 + '[VAR_27]', '--outdir', VAR_39 ] + (['--use_tfrt'] if VAR_5 else [])) saved_model_cli.run(VAR_11) VAR_40 = np.load(os.path.join(VAR_39, 'y.npy')) VAR_41 = np.array([[2.5], [3.0]]) self.assertAllClose(VAR_41, VAR_40) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_23(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = np.array([[1], [2]]) VAR_43 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommandOutOverwrite_inputs.npz') np.savez(VAR_32, VAR_27=VAR_42, VAR_28=VAR_43) VAR_44 = os.path.join(test.get_temp_dir(), 'y.npy') open(VAR_44, 'a').close() VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + VAR_32 + '[VAR_27]', '--outdir', test.get_temp_dir(), '--overwrite' ] + (['--use_tfrt'] if VAR_5 else [])) saved_model_cli.run(VAR_11) VAR_40 = np.load(VAR_44) VAR_41 = np.array([[2.5], [3.0]]) self.assertAllClose(VAR_41, VAR_40) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_24(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x2_to_y3', '--input_exprs', 'x2=[1,2,3]' ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaises(ValueError): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_25(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'INVALID_SIGNATURE', '--input_exprs', 'x2=[1,2,3]' ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaisesRegex(ValueError, 'Could not find signature "INVALID_SIGNATURE"'): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_26(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_39 = os.path.join(test.get_temp_dir(), 'new_dir') VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs={"x":8.0,"x2":5.0}', '--outdir', VAR_39 ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaisesRegex(ValueError, 'must be VAR_51 list'): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_27(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_39 = os.path.join(test.get_temp_dir(), 'new_dir') VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":8.0,"x2":5.0}]', '--outdir', VAR_39 ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaisesRegex(ValueError, 'feature value must be VAR_51 list'): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_28(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_39 = os.path.join(test.get_temp_dir(), 'new_dir') VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'regress_x_to_y', '--input_examples', 'inputs=[{"x":[[1],[2]]}]', '--outdir', VAR_39 ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaisesRegex(ValueError, 'is not supported'): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_29(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = np.array([[1], [2]]) VAR_43 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommandOutOverwrite_inputs.npz') np.savez(VAR_32, VAR_27=VAR_42, VAR_28=VAR_43) VAR_44 = os.path.join(test.get_temp_dir(), 'y.npy') open(VAR_44, 'a').close() VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + VAR_32 + '[VAR_27]', '--outdir', test.get_temp_dir() ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaises(RuntimeError): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_30(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default' ] + (['--use_tfrt'] if VAR_5 else [])) with self.assertRaises(AttributeError): saved_model_cli.run(VAR_11) @parameterized.named_parameters(('non_tfrt', False)) def FUNC_31(self, VAR_5): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_42 = np.array([[1], [2]]) VAR_43 = np.zeros((6, 3)) VAR_32 = os.path.join(test.get_temp_dir(), 'testRunCommandNewOutdir_inputs.npz') VAR_39 = os.path.join(test.get_temp_dir(), 'new_dir') if os.path.isdir(VAR_39): shutil.rmtree(VAR_39) np.savez(VAR_32, VAR_27=VAR_42, VAR_28=VAR_43) VAR_11 = self.parser.parse_args([ 'run', '--dir', VAR_10, '--tag_set', 'serve', '--signature_def', 'serving_default', '--inputs', 'x=' + VAR_32 + '[VAR_27]', '--outdir', VAR_39, '--tf_debug' ] + (['--use_tfrt'] if VAR_5 else [])) def FUNC_37(VAR_45): return VAR_45 with test.mock.patch.object( local_cli_wrapper, 'LocalCLIDebugWrapperSession', side_effect=FUNC_37, autospec=True) as fake: saved_model_cli.run(VAR_11) fake.assert_called_with(test.mock.ANY) VAR_40 = np.load(os.path.join(VAR_39, 'y.npy')) VAR_41 = np.array([[2.5], [3.0]]) self.assertAllClose(VAR_41, VAR_40) def FUNC_32(self): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args(['scan', '--dir', VAR_10]) with FUNC_0() as (out, _): saved_model_cli.scan(VAR_11) VAR_12 = out.getvalue().strip() self.assertTrue('does not contain denylisted ops' in VAR_12) def FUNC_33(self): self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_11 = self.parser.parse_args( ['scan', '--dir', VAR_10, '--tag_set', 'serve']) VAR_46 = saved_model_cli._OP_DENYLIST saved_model_cli._OP_DENYLIST = set(['VariableV2']) with FUNC_0() as (out, _): saved_model_cli.scan(VAR_11) saved_model_cli._OP_DENYLIST = VAR_46 VAR_12 = out.getvalue().strip() self.assertTrue('\'VariableV2\'' in VAR_12) def FUNC_34(self): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') self.parser = saved_model_cli.create_parser() VAR_10 = test.test_src_dir_path(VAR_0) VAR_39 = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir') VAR_11 = self.parser.parse_args([ 'aot_compile_cpu', '--dir', VAR_10, '--tag_set', 'serve', '--output_prefix', VAR_39, '--cpp_class', 'Compiled', '--signature_def_key', 'MISSING' ]) with self.assertRaisesRegex(ValueError, 'Unable to find signature_def'): saved_model_cli.aot_compile_cpu(VAR_11) class CLASS_1(tracking.AutoTrackable): def __init__(self): self.var = variables.Variable(1.0, name='my_var') self.write_var = variables.Variable(1.0, name='write_var') @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2, 2), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def FUNC_38(self, VAR_42, VAR_47): del VAR_47 return {'res': VAR_42 + self.var} @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(2048, 16), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def FUNC_39(self, VAR_42, VAR_47): del VAR_47 return {'res': VAR_42 + self.var} @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), tensor_spec.TensorSpec(shape=(), dtype=dtypes.float32), ]) def FUNC_40(self, VAR_42, VAR_47): del VAR_47 self.write_var.assign(VAR_42 + self.var) return {'res': self.write_var} @parameterized.named_parameters( ('VariablesToFeedNone', '', 'func2', None), ('VariablesToFeedNoneTargetAarch64Linux', '', 'func2', 'aarch64-none-linux-gnu'), ('VariablesToFeedNoneTargetAarch64Android', '', 'func2', 'aarch64-none-android'), ('VariablesToFeedAll', 'all', 'func2', None), ('VariablesToFeedMyVar', 'my_var', 'func2', None), ('VariablesToFeedNoneLargeConstant', '', 'func3', None), ('WriteToWriteVar', 'all', 'func_write', None), ) def FUNC_35(self, VAR_6, VAR_7, VAR_8): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') VAR_14 = os.path.join(test.get_temp_dir(), 'dummy_model') VAR_15 = self.AOTCompileDummyModel() VAR_7 = getattr(VAR_15, VAR_7) with self.cached_session(): self.evaluate(VAR_15.var.initializer) self.evaluate(VAR_15.write_var.initializer) save.save(VAR_15, VAR_14, signatures={'func': VAR_7}) self.parser = saved_model_cli.create_parser() VAR_48 = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir/out') VAR_11 = [ # Use the default seving signature_key. 'aot_compile_cpu', '--dir', VAR_14, '--tag_set', 'serve', '--signature_def_key', 'func', '--output_prefix', VAR_48, '--variables_to_feed', VAR_6, '--cpp_class', 'Generated' ] if VAR_8: VAR_11.extend(['--target_triple', VAR_8]) VAR_11 = self.parser.parse_args(VAR_11) with test.mock.patch.object(logging, 'warn') as captured_warn: saved_model_cli.aot_compile_cpu(VAR_11) self.assertRegex( str(captured_warn.call_args), 'Signature input key \'y\'.*has been pruned while freezing the graph.') self.assertTrue(file_io.file_exists('{}.o'.format(VAR_48))) self.assertTrue(file_io.file_exists('{}.h'.format(VAR_48))) self.assertTrue(file_io.file_exists('{}_metadata.o'.format(VAR_48))) self.assertTrue( file_io.file_exists('{}_makefile.inc'.format(VAR_48))) VAR_49 = file_io.read_file_to_string('{}.h'.format(VAR_48)) self.assertIn('class Generated', VAR_49) self.assertIn('arg_feed_x_data', VAR_49) self.assertIn('result_fetch_res_data', VAR_49) self.assertNotIn('arg_feed_y_data', VAR_49) if VAR_6: self.assertIn('set_var_param_my_var_data(const float', VAR_49) self.assertNotIn('set_var_param_my_var_data(float', VAR_49) if VAR_7 == VAR_15.func_write: self.assertIn('set_var_param_write_var_data(float', VAR_49) self.assertNotIn('set_var_param_write_var_data(const float', VAR_49) VAR_50 = file_io.read_file_to_string( '{}_makefile.inc'.format(VAR_48)) self.assertIn('-D_GLIBCXX_USE_CXX11_ABI=', VAR_50) def FUNC_36(self): if not test.is_built_with_xla(): self.skipTest('Skipping test because XLA is not compiled in.') VAR_6 = 'all' VAR_7 = 'func2' VAR_14 = os.path.join(test.get_temp_dir(), 'dummy_model') VAR_15 = self.AOTCompileDummyModel() VAR_7 = getattr(VAR_15, VAR_7) with self.cached_session(): self.evaluate(VAR_15.var.initializer) self.evaluate(VAR_15.write_var.initializer) save.save(VAR_15, VAR_14, signatures={'func': VAR_7}) self.parser = saved_model_cli.create_parser() VAR_48 = os.path.join(test.get_temp_dir(), 'aot_compile_cpu_dir/out') VAR_11 = [ # Use the default seving signature_key. 'freeze_model', '--dir', VAR_14, '--tag_set', 'serve', '--signature_def_key', 'func', '--output_prefix', VAR_48, '--variables_to_feed', VAR_6 ] VAR_11 = self.parser.parse_args(VAR_11) with test.mock.patch.object(logging, 'warn'): saved_model_cli.freeze_model(VAR_11) self.assertTrue( file_io.file_exists(os.path.join(VAR_48, 'frozen_graph.pb'))) self.assertTrue( file_io.file_exists(os.path.join(VAR_48, 'config.pbtxt'))) if __name__ == '__main__': test.main()
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 22, 26, 42, 44, 45, 55, 56, 58, 63, 71, 73, 86, 99, 112, 125, 138, 151, 155, 157, 160, 167, 173, 177, 180, 190, 199, 212, 222, 233, 243, 245, 248, 258, 261, 271, 280, 297, 310, 321, 337, 342, 350, 371, 379, 393, 420, 425, 433, 444, 457, 467, 488, 502, 514, 525, 534, 543, 560, 582, 604, 625, 636, 648, 661, 674, 687, 706, 717, 735, 738, 746, 750, 759, 772, 776, 787, 790, 794, 797, 803, 805, 812, 821, 837, 845, 870, 873, 877, 881, 885, 889, 899, 914, 915, 918, 15, 789, 159, 247 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 22, 26, 42, 44, 45, 55, 56, 58, 63, 71, 73, 86, 99, 112, 125, 138, 151, 155, 157, 160, 167, 173, 177, 180, 190, 199, 212, 222, 233, 243, 245, 248, 258, 261, 271, 280, 297, 310, 321, 337, 342, 350, 371, 379, 393, 420, 425, 433, 444, 457, 467, 488, 497, 506, 523, 545, 567, 588, 599, 611, 624, 637, 650, 669, 680, 698, 701, 709, 713, 722, 735, 739, 750, 753, 757, 760, 766, 768, 775, 784, 800, 808, 833, 836, 840, 844, 848, 852, 862, 877, 878, 881, 15, 752, 159, 247 ]
4CWE-601
import logging import requests from flask import redirect, url_for, Blueprint, flash, request, session from flask_oauthlib.client import OAuth from redash import models, settings from redash.authentication import ( create_and_login_user, logout_and_redirect_to_index, get_next_path, ) from redash.authentication.org_resolving import current_org logger = logging.getLogger("google_oauth") oauth = OAuth() blueprint = Blueprint("google_oauth", __name__) def google_remote_app(): if "google" not in oauth.remote_apps: oauth.remote_app( "google", base_url="https://www.google.com/accounts/", authorize_url="https://accounts.google.com/o/oauth2/auth?prompt=select_account+consent", request_token_url=None, request_token_params={ "scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile" }, access_token_url="https://accounts.google.com/o/oauth2/token", access_token_method="POST", consumer_key=settings.GOOGLE_CLIENT_ID, consumer_secret=settings.GOOGLE_CLIENT_SECRET, ) return oauth.google def get_user_profile(access_token): headers = {"Authorization": "OAuth {}".format(access_token)} response = requests.get( "https://www.googleapis.com/oauth2/v1/userinfo", headers=headers ) if response.status_code == 401: logger.warning("Failed getting user profile (response code 401).") return None return response.json() def verify_profile(org, profile): if org.is_public: return True email = profile["email"] domain = email.split("@")[-1] if domain in org.google_apps_domains: return True if org.has_user(email) == 1: return True return False @blueprint.route("/<org_slug>/oauth/google", endpoint="authorize_org") def org_login(org_slug): session["org_slug"] = current_org.slug return redirect(url_for(".authorize", next=request.args.get("next", None))) @blueprint.route("/oauth/google", endpoint="authorize") def login(): callback = url_for(".callback", _external=True) next_path = request.args.get( "next", url_for("redash.index", org_slug=session.get("org_slug")) ) logger.debug("Callback url: %s", callback) logger.debug("Next is: %s", next_path) return google_remote_app().authorize(callback=callback, state=next_path) @blueprint.route("/oauth/google_callback", endpoint="callback") def authorized(): resp = google_remote_app().authorized_response() access_token = resp["access_token"] if access_token is None: logger.warning("Access token missing in call back request.") flash("Validation error. Please retry.") return redirect(url_for("redash.login")) profile = get_user_profile(access_token) if profile is None: flash("Validation error. Please retry.") return redirect(url_for("redash.login")) if "org_slug" in session: org = models.Organization.get_by_slug(session.pop("org_slug")) else: org = current_org if not verify_profile(org, profile): logger.warning( "User tried to login with unauthorized domain name: %s (org: %s)", profile["email"], org, ) flash("Your Google Apps account ({}) isn't allowed.".format(profile["email"])) return redirect(url_for("redash.login", org_slug=org.slug)) picture_url = "%s?sz=40" % profile["picture"] user = create_and_login_user(org, profile["name"], profile["email"], picture_url) if user is None: return logout_and_redirect_to_index() unsafe_next_path = request.args.get("state") or url_for( "redash.index", org_slug=org.slug ) next_path = get_next_path(unsafe_next_path) return redirect(next_path)
import logging import requests from flask import redirect, url_for, Blueprint, flash, request, session from redash import models, settings from redash.authentication import ( create_and_login_user, logout_and_redirect_to_index, get_next_path, ) from redash.authentication.org_resolving import current_org from authlib.integrations.flask_client import OAuth def verify_profile(org, profile): if org.is_public: return True email = profile["email"] domain = email.split("@")[-1] if domain in org.google_apps_domains: return True if org.has_user(email) == 1: return True return False def create_google_oauth_blueprint(app): oauth = OAuth(app) logger = logging.getLogger("google_oauth") blueprint = Blueprint("google_oauth", __name__) CONF_URL = "https://accounts.google.com/.well-known/openid-configuration" oauth = OAuth(app) oauth.register( name="google", server_metadata_url=CONF_URL, client_kwargs={"scope": "openid email profile"}, ) def get_user_profile(access_token): headers = {"Authorization": "OAuth {}".format(access_token)} response = requests.get( "https://www.googleapis.com/oauth2/v1/userinfo", headers=headers ) if response.status_code == 401: logger.warning("Failed getting user profile (response code 401).") return None return response.json() @blueprint.route("/<org_slug>/oauth/google", endpoint="authorize_org") def org_login(org_slug): session["org_slug"] = current_org.slug return redirect(url_for(".authorize", next=request.args.get("next", None))) @blueprint.route("/oauth/google", endpoint="authorize") def login(): redirect_uri = url_for(".callback", _external=True) next_path = request.args.get( "next", url_for("redash.index", org_slug=session.get("org_slug")) ) logger.debug("Callback url: %s", redirect_uri) logger.debug("Next is: %s", next_path) session["next_url"] = next_path return oauth.google.authorize_redirect(redirect_uri) @blueprint.route("/oauth/google_callback", endpoint="callback") def authorized(): logger.debug("Authorized user inbound") resp = oauth.google.authorize_access_token() user = resp.get("userinfo") if user: session["user"] = user access_token = resp["access_token"] if access_token is None: logger.warning("Access token missing in call back request.") flash("Validation error. Please retry.") return redirect(url_for("redash.login")) profile = get_user_profile(access_token) if profile is None: flash("Validation error. Please retry.") return redirect(url_for("redash.login")) if "org_slug" in session: org = models.Organization.get_by_slug(session.pop("org_slug")) else: org = current_org if not verify_profile(org, profile): logger.warning( "User tried to login with unauthorized domain name: %s (org: %s)", profile["email"], org, ) flash( "Your Google Apps account ({}) isn't allowed.".format(profile["email"]) ) return redirect(url_for("redash.login", org_slug=org.slug)) picture_url = "%s?sz=40" % profile["picture"] user = create_and_login_user( org, profile["name"], profile["email"], picture_url ) if user is None: return logout_and_redirect_to_index() unsafe_next_path = session.get("next_url") or url_for( "redash.index", org_slug=org.slug ) next_path = get_next_path(unsafe_next_path) return redirect(next_path) return blueprint
open_redirect
{ "code": [ "from flask_oauthlib.client import OAuth", "logger = logging.getLogger(\"google_oauth\")", "oauth = OAuth()", "blueprint = Blueprint(\"google_oauth\", __name__)", "def google_remote_app():", " if \"google\" not in oauth.remote_apps:", " oauth.remote_app(", " \"google\",", " base_url=\"https://www.google.com/accounts/\",", " authorize_url=\"https://accounts.google.com/o/oauth2/auth?prompt=select_account+consent\",", " request_token_url=None,", " request_token_params={", " \"scope\": \"https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile\"", " },", " access_token_url=\"https://accounts.google.com/o/oauth2/token\",", " access_token_method=\"POST\",", " consumer_key=settings.GOOGLE_CLIENT_ID,", " consumer_secret=settings.GOOGLE_CLIENT_SECRET,", " )", " return oauth.google", "def get_user_profile(access_token):", " headers = {\"Authorization\": \"OAuth {}\".format(access_token)}", " response = requests.get(", " \"https://www.googleapis.com/oauth2/v1/userinfo\", headers=headers", " )", " if response.status_code == 401:", " logger.warning(\"Failed getting user profile (response code 401).\")", " return None", " return response.json()", "@blueprint.route(\"/<org_slug>/oauth/google\", endpoint=\"authorize_org\")", "def org_login(org_slug):", " session[\"org_slug\"] = current_org.slug", " return redirect(url_for(\".authorize\", next=request.args.get(\"next\", None)))", "@blueprint.route(\"/oauth/google\", endpoint=\"authorize\")", "def login():", " callback = url_for(\".callback\", _external=True)", " next_path = request.args.get(", " \"next\", url_for(\"redash.index\", org_slug=session.get(\"org_slug\"))", " logger.debug(\"Callback url: %s\", callback)", " logger.debug(\"Next is: %s\", next_path)", " return google_remote_app().authorize(callback=callback, state=next_path)", "@blueprint.route(\"/oauth/google_callback\", endpoint=\"callback\")", "def authorized():", " resp = google_remote_app().authorized_response()", " access_token = resp[\"access_token\"]", " if access_token is None:", " logger.warning(\"Access token missing in call back request.\")", " flash(\"Validation error. Please retry.\")", " return redirect(url_for(\"redash.login\"))", " profile = get_user_profile(access_token)", " if profile is None:", " flash(\"Validation error. Please retry.\")", " return redirect(url_for(\"redash.login\"))", " if \"org_slug\" in session:", " org = models.Organization.get_by_slug(session.pop(\"org_slug\"))", " else:", " org = current_org", " if not verify_profile(org, profile):", " logger.warning(", " \"User tried to login with unauthorized domain name: %s (org: %s)\",", " profile[\"email\"],", " org,", " flash(\"Your Google Apps account ({}) isn't allowed.\".format(profile[\"email\"]))", " return redirect(url_for(\"redash.login\", org_slug=org.slug))", " picture_url = \"%s?sz=40\" % profile[\"picture\"]", " user = create_and_login_user(org, profile[\"name\"], profile[\"email\"], picture_url)", " if user is None:", " return logout_and_redirect_to_index()", " unsafe_next_path = request.args.get(\"state\") or url_for(", " \"redash.index\", org_slug=org.slug", " )", " next_path = get_next_path(unsafe_next_path)", " return redirect(next_path)" ], "line_no": [ 4, 14, 16, 17, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 39, 40, 41, 42, 43, 45, 46, 47, 49, 68, 69, 70, 71, 74, 75, 76, 77, 78, 80, 81, 82, 85, 86, 87, 88, 90, 91, 92, 93, 95, 96, 97, 98, 100, 101, 102, 103, 105, 106, 107, 108, 109, 111, 112, 114, 115, 116, 117, 119, 120, 121, 122, 124 ] }
{ "code": [ "from authlib.integrations.flask_client import OAuth", "def create_google_oauth_blueprint(app):", " oauth = OAuth(app)", " logger = logging.getLogger(\"google_oauth\")", " CONF_URL = \"https://accounts.google.com/.well-known/openid-configuration\"", " oauth = OAuth(app)", " oauth.register(", " name=\"google\",", " server_metadata_url=CONF_URL,", " def get_user_profile(access_token):", " response = requests.get(", " if response.status_code == 401:", " logger.warning(\"Failed getting user profile (response code 401).\")", " return response.json()", " @blueprint.route(\"/<org_slug>/oauth/google\", endpoint=\"authorize_org\")", " def org_login(org_slug):", " return redirect(url_for(\".authorize\", next=request.args.get(\"next\", None)))", " def login():", " next_path = request.args.get(", " \"next\", url_for(\"redash.index\", org_slug=session.get(\"org_slug\"))", " )", " logger.debug(\"Next is: %s\", next_path)", " session[\"next_url\"] = next_path", " return oauth.google.authorize_redirect(redirect_uri)", " @blueprint.route(\"/oauth/google_callback\", endpoint=\"callback\")", " def authorized():", " logger.debug(\"Authorized user inbound\")", " user = resp.get(\"userinfo\")", " if user:", " session[\"user\"] = user", " if access_token is None:", " logger.warning(\"Access token missing in call back request.\")", " flash(\"Validation error. Please retry.\")", " profile = get_user_profile(access_token)", " if profile is None:", " flash(\"Validation error. Please retry.\")", " if \"org_slug\" in session:", " org = models.Organization.get_by_slug(session.pop(\"org_slug\"))", " else:", " if not verify_profile(org, profile):", " logger.warning(", " \"User tried to login with unauthorized domain name: %s (org: %s)\",", " profile[\"email\"],", " org,", " )", " flash(", " )", " return redirect(url_for(\"redash.login\", org_slug=org.slug))", " picture_url = \"%s?sz=40\" % profile[\"picture\"]", " org, profile[\"name\"], profile[\"email\"], picture_url", " )", " if user is None:", " return logout_and_redirect_to_index()", " unsafe_next_path = session.get(\"next_url\") or url_for(", " )", " next_path = get_next_path(unsafe_next_path)", " return redirect(next_path)", " return blueprint" ], "line_no": [ 14, 33, 34, 36, 39, 40, 41, 42, 43, 47, 49, 53, 54, 57, 59, 60, 62, 65, 69, 70, 71, 73, 75, 77, 79, 80, 82, 85, 86, 87, 91, 92, 93, 96, 97, 98, 101, 102, 103, 106, 107, 108, 109, 110, 111, 112, 114, 115, 117, 119, 120, 121, 122, 124, 126, 127, 129, 131 ] }
import logging import requests from flask import redirect, url_for, Blueprint, flash, request, VAR_11 from flask_oauthlib.client import OAuth from redash import models, settings from redash.authentication import ( create_and_login_user, logout_and_redirect_to_index, get_next_path, ) from redash.authentication.org_resolving import current_org VAR_0 = logging.getLogger("google_oauth") VAR_1 = OAuth() VAR_2 = Blueprint("google_oauth", __name__) def FUNC_0(): if "google" not in VAR_1.remote_apps: VAR_1.remote_app( "google", base_url="https://www.google.com/accounts/", authorize_url="https://accounts.google.com/o/oauth2/auth?prompt=select_account+consent", request_token_url=None, request_token_params={ "scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile" }, access_token_url="https://accounts.google.com/o/oauth2/token", access_token_method="POST", consumer_key=settings.GOOGLE_CLIENT_ID, consumer_secret=settings.GOOGLE_CLIENT_SECRET, ) return VAR_1.google def FUNC_1(VAR_3): VAR_7 = {"Authorization": "OAuth {}".format(VAR_3)} VAR_8 = requests.get( "https://www.googleapis.com/oauth2/v1/userinfo", VAR_7=headers ) if VAR_8.status_code == 401: VAR_0.warning("Failed getting VAR_16 VAR_5 (VAR_8 code 401).") return None return VAR_8.json() def FUNC_2(VAR_4, VAR_5): if VAR_4.is_public: return True VAR_9 = VAR_5["email"] VAR_10 = VAR_9.split("@")[-1] if VAR_10 in VAR_4.google_apps_domains: return True if VAR_4.has_user(VAR_9) == 1: return True return False @VAR_2.route("/<VAR_6>/VAR_1/google", endpoint="authorize_org") def FUNC_3(VAR_6): VAR_11["org_slug"] = current_org.slug return redirect(url_for(".authorize", next=request.args.get("next", None))) @VAR_2.route("/VAR_1/google", endpoint="authorize") def FUNC_4(): VAR_12 = url_for(".callback", _external=True) VAR_13 = request.args.get( "next", url_for("redash.index", VAR_6=VAR_11.get("org_slug")) ) VAR_0.debug("Callback url: %s", VAR_12) VAR_0.debug("Next is: %s", VAR_13) return FUNC_0().authorize(VAR_12=callback, state=VAR_13) @VAR_2.route("/VAR_1/google_callback", endpoint="callback") def FUNC_5(): VAR_14 = FUNC_0().authorized_response() VAR_3 = VAR_14["access_token"] if VAR_3 is None: VAR_0.warning("Access token missing in call back request.") flash("Validation error. Please retry.") return redirect(url_for("redash.login")) VAR_5 = FUNC_1(VAR_3) if VAR_5 is None: flash("Validation error. Please retry.") return redirect(url_for("redash.login")) if "org_slug" in VAR_11: VAR_4 = models.Organization.get_by_slug(VAR_11.pop("org_slug")) else: VAR_4 = current_org if not FUNC_2(VAR_4, VAR_5): VAR_0.warning( "User tried to FUNC_4 with unauthorized VAR_10 name: %s (VAR_4: %s)", VAR_5["email"], VAR_4, ) flash("Your Google Apps account ({}) isn't allowed.".format(VAR_5["email"])) return redirect(url_for("redash.login", VAR_6=VAR_4.slug)) VAR_15 = "%s?sz=40" % VAR_5["picture"] VAR_16 = create_and_login_user(VAR_4, VAR_5["name"], VAR_5["email"], VAR_15) if VAR_16 is None: return logout_and_redirect_to_index() VAR_17 = request.args.get("state") or url_for( "redash.index", VAR_6=VAR_4.slug ) VAR_13 = get_next_path(VAR_17) return redirect(VAR_13)
import logging import requests from flask import redirect, url_for, Blueprint, flash, request, VAR_13 from redash import models, settings from redash.authentication import ( create_and_login_user, logout_and_redirect_to_index, get_next_path, ) from redash.authentication.org_resolving import current_org from authlib.integrations.flask_client import OAuth def FUNC_0(VAR_0, VAR_1): if VAR_0.is_public: return True VAR_3 = VAR_1["email"] VAR_4 = VAR_3.split("@")[-1] if VAR_4 in VAR_0.google_apps_domains: return True if VAR_0.has_user(VAR_3) == 1: return True return False def FUNC_1(VAR_2): VAR_5 = OAuth(VAR_2) VAR_6 = logging.getLogger("google_oauth") VAR_7 = Blueprint("google_oauth", __name__) VAR_8 = "https://accounts.google.com/.well-known/openid-configuration" VAR_5 = OAuth(VAR_2) VAR_5.register( name="google", server_metadata_url=VAR_8, client_kwargs={"scope": "openid VAR_3 profile"}, ) def FUNC_2(VAR_9): VAR_11 = {"Authorization": "OAuth {}".format(VAR_9)} VAR_12 = requests.get( "https://www.googleapis.com/oauth2/v1/userinfo", VAR_11=headers ) if VAR_12.status_code == 401: VAR_6.warning("Failed getting VAR_17 VAR_1 (VAR_12 code 401).") return None return VAR_12.json() @VAR_7.route("/<VAR_10>/VAR_5/google", endpoint="authorize_org") def FUNC_3(VAR_10): VAR_13["org_slug"] = current_org.slug return redirect(url_for(".authorize", next=request.args.get("next", None))) @VAR_7.route("/VAR_5/google", endpoint="authorize") def FUNC_4(): VAR_14 = url_for(".callback", _external=True) VAR_15 = request.args.get( "next", url_for("redash.index", VAR_10=VAR_13.get("org_slug")) ) VAR_6.debug("Callback url: %s", VAR_14) VAR_6.debug("Next is: %s", VAR_15) VAR_13["next_url"] = VAR_15 return VAR_5.google.authorize_redirect(VAR_14) @VAR_7.route("/VAR_5/google_callback", endpoint="callback") def FUNC_5(): VAR_6.debug("Authorized VAR_17 inbound") VAR_16 = VAR_5.google.authorize_access_token() VAR_17 = VAR_16.get("userinfo") if VAR_17: VAR_13["user"] = VAR_17 VAR_9 = VAR_16["access_token"] if VAR_9 is None: VAR_6.warning("Access token missing in call back request.") flash("Validation error. Please retry.") return redirect(url_for("redash.login")) VAR_1 = FUNC_2(VAR_9) if VAR_1 is None: flash("Validation error. Please retry.") return redirect(url_for("redash.login")) if "org_slug" in VAR_13: VAR_0 = models.Organization.get_by_slug(VAR_13.pop("org_slug")) else: VAR_0 = current_org if not FUNC_0(VAR_0, VAR_1): VAR_6.warning( "User tried to FUNC_4 with unauthorized VAR_4 name: %s (VAR_0: %s)", VAR_1["email"], VAR_0, ) flash( "Your Google Apps account ({}) isn't allowed.".format(VAR_1["email"]) ) return redirect(url_for("redash.login", VAR_10=VAR_0.slug)) VAR_18 = "%s?sz=40" % VAR_1["picture"] VAR_17 = create_and_login_user( VAR_0, VAR_1["name"], VAR_1["email"], VAR_18 ) if VAR_17 is None: return logout_and_redirect_to_index() VAR_19 = VAR_13.get("next_url") or url_for( "redash.index", VAR_10=VAR_0.slug ) VAR_15 = get_next_path(VAR_19) return redirect(VAR_15) return VAR_7
[ 5, 13, 15, 18, 19, 35, 37, 38, 44, 48, 50, 51, 55, 58, 61, 64, 66, 67, 72, 73, 83, 84, 89, 94, 99, 104, 113, 118, 123, 125 ]
[ 4, 5, 13, 15, 16, 20, 23, 26, 29, 31, 32, 35, 38, 46, 52, 56, 58, 63, 66, 68, 74, 76, 78, 81, 83, 88, 90, 95, 100, 105, 116, 123, 128, 130, 132 ]
1CWE-79
# coding: utf-8 """A tornado based Jupyter notebook server.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import absolute_import, print_function import base64 import datetime import errno import importlib import io import json import logging import os import random import re import select import signal import socket import ssl import sys import threading import webbrowser from jinja2 import Environment, FileSystemLoader # Install the pyzmq ioloop. This has to be done before anything else from # tornado is imported. from zmq.eventloop import ioloop ioloop.install() # check for tornado 3.1.0 msg = "The Jupyter Notebook requires tornado >= 4.0" try: import tornado except ImportError: raise ImportError(msg) try: version_info = tornado.version_info except AttributeError: raise ImportError(msg + ", but you have < 1.1.0") if version_info < (4,0): raise ImportError(msg + ", but you have %s" % tornado.version) from tornado import httpserver from tornado import web from tornado.log import LogFormatter, app_log, access_log, gen_log from notebook import ( DEFAULT_STATIC_FILES_PATH, DEFAULT_TEMPLATE_PATH_LIST, __version__, ) from .base.handlers import Template404 from .log import log_request from .services.kernels.kernelmanager import MappingKernelManager from .services.config import ConfigManager from .services.contents.manager import ContentsManager from .services.contents.filemanager import FileContentsManager from .services.sessions.sessionmanager import SessionManager from .auth.login import LoginHandler from .auth.logout import LogoutHandler from .base.handlers import FileFindHandler, IPythonHandler from traitlets.config import Config from traitlets.config.application import catch_config_error, boolean_flag from jupyter_core.application import ( JupyterApp, base_flags, base_aliases, ) from jupyter_client import KernelManager from jupyter_client.kernelspec import KernelSpecManager, NoSuchKernel, NATIVE_KERNEL_NAME from jupyter_client.session import Session from nbformat.sign import NotebookNotary from traitlets import ( Dict, Unicode, Integer, List, Bool, Bytes, Instance, TraitError, Type, ) from ipython_genutils import py3compat from IPython.paths import get_ipython_dir from jupyter_core.paths import jupyter_runtime_dir, jupyter_path from notebook._sysinfo import get_sys_info from .utils import url_path_join, check_pid #----------------------------------------------------------------------------- # Module globals #----------------------------------------------------------------------------- _examples = """ jupyter notebook # start the notebook jupyter notebook --certfile=mycert.pem # use SSL/TLS certificate """ #----------------------------------------------------------------------------- # Helper functions #----------------------------------------------------------------------------- def random_ports(port, n): """Generate a list of n random ports near the given port. The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n]. """ for i in range(min(5, n)): yield port + i for i in range(n-5): yield max(1, port + random.randint(-2*n, 2*n)) def load_handlers(name): """Load the (URL pattern, handler) tuples for each component.""" name = 'notebook.' + name mod = __import__(name, fromlist=['default_handlers']) return mod.default_handlers class DeprecationHandler(IPythonHandler): def get(self, url_path): self.set_header("Content-Type", 'text/javascript') self.finish(""" console.warn('`/static/widgets/js` is deprecated. Use `/nbextensions/widgets/widgets/js` instead.'); define(['%s'], function(x) { return x; }); """ % url_path_join('nbextensions', 'widgets', 'widgets', url_path.rstrip('.js'))) self.log.warn('Deprecated widget Javascript path /static/widgets/js/*.js was used') #----------------------------------------------------------------------------- # The Tornado web application #----------------------------------------------------------------------------- class NotebookWebApplication(web.Application): def __init__(self, ipython_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, log, base_url, default_url, settings_overrides, jinja_env_options): settings = self.init_settings( ipython_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, log, base_url, default_url, settings_overrides, jinja_env_options) handlers = self.init_handlers(settings) super(NotebookWebApplication, self).__init__(handlers, **settings) def init_settings(self, ipython_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, log, base_url, default_url, settings_overrides, jinja_env_options=None): _template_path = settings_overrides.get( "template_path", ipython_app.template_file_path, ) if isinstance(_template_path, py3compat.string_types): _template_path = (_template_path,) template_path = [os.path.expanduser(path) for path in _template_path] jenv_opt = jinja_env_options if jinja_env_options else {} env = Environment(loader=FileSystemLoader(template_path), **jenv_opt) sys_info = get_sys_info() if sys_info['commit_source'] == 'repository': # don't cache (rely on 304) when working from master version_hash = '' else: # reset the cache on server restart version_hash = datetime.datetime.now().strftime("%Y%m%d%H%M%S") settings = dict( # basics log_function=log_request, base_url=base_url, default_url=default_url, template_path=template_path, static_path=ipython_app.static_file_path, static_custom_path=ipython_app.static_custom_path, static_handler_class = FileFindHandler, static_url_prefix = url_path_join(base_url,'/static/'), static_handler_args = { # don't cache custom.js 'no_cache_paths': [url_path_join(base_url, 'static', 'custom')], }, version_hash=version_hash, ignore_minified_js=ipython_app.ignore_minified_js, # authentication cookie_secret=ipython_app.cookie_secret, login_url=url_path_join(base_url,'/login'), login_handler_class=ipython_app.login_handler_class, logout_handler_class=ipython_app.logout_handler_class, password=ipython_app.password, # managers kernel_manager=kernel_manager, contents_manager=contents_manager, session_manager=session_manager, kernel_spec_manager=kernel_spec_manager, config_manager=config_manager, # IPython stuff jinja_template_vars=ipython_app.jinja_template_vars, nbextensions_path=ipython_app.nbextensions_path, websocket_url=ipython_app.websocket_url, mathjax_url=ipython_app.mathjax_url, config=ipython_app.config, config_dir=ipython_app.config_dir, jinja2_env=env, terminals_available=False, # Set later if terminals are available ) # allow custom overrides for the tornado web app. settings.update(settings_overrides) return settings def init_handlers(self, settings): """Load the (URL pattern, handler) tuples for each component.""" # Order matters. The first handler to match the URL will handle the request. handlers = [] handlers.append((r'/deprecatedwidgets/(.*)', DeprecationHandler)) handlers.extend(load_handlers('tree.handlers')) handlers.extend([(r"/login", settings['login_handler_class'])]) handlers.extend([(r"/logout", settings['logout_handler_class'])]) handlers.extend(load_handlers('files.handlers')) handlers.extend(load_handlers('notebook.handlers')) handlers.extend(load_handlers('nbconvert.handlers')) handlers.extend(load_handlers('kernelspecs.handlers')) handlers.extend(load_handlers('edit.handlers')) handlers.extend(load_handlers('services.api.handlers')) handlers.extend(load_handlers('services.config.handlers')) handlers.extend(load_handlers('services.kernels.handlers')) handlers.extend(load_handlers('services.contents.handlers')) handlers.extend(load_handlers('services.sessions.handlers')) handlers.extend(load_handlers('services.nbconvert.handlers')) handlers.extend(load_handlers('services.kernelspecs.handlers')) handlers.extend(load_handlers('services.security.handlers')) # BEGIN HARDCODED WIDGETS HACK try: import ipywidgets handlers.append( (r"/nbextensions/widgets/(.*)", FileFindHandler, { 'path': ipywidgets.find_static_assets(), 'no_cache_paths': ['/'], # don't cache anything in nbextensions }), ) except: app_log.warn('ipywidgets package not installed. Widgets are unavailable.') # END HARDCODED WIDGETS HACK handlers.append( (r"/nbextensions/(.*)", FileFindHandler, { 'path': settings['nbextensions_path'], 'no_cache_paths': ['/'], # don't cache anything in nbextensions }), ) handlers.append( (r"/custom/(.*)", FileFindHandler, { 'path': settings['static_custom_path'], 'no_cache_paths': ['/'], # don't cache anything in custom }) ) # register base handlers last handlers.extend(load_handlers('base.handlers')) # set the URL that will be redirected from `/` handlers.append( (r'/?', web.RedirectHandler, { 'url' : settings['default_url'], 'permanent': False, # want 302, not 301 }) ) # prepend base_url onto the patterns that we match new_handlers = [] for handler in handlers: pattern = url_path_join(settings['base_url'], handler[0]) new_handler = tuple([pattern] + list(handler[1:])) new_handlers.append(new_handler) # add 404 on the end, which will catch everything that falls through new_handlers.append((r'(.*)', Template404)) return new_handlers class NbserverListApp(JupyterApp): version = __version__ description="List currently running notebook servers in this profile." flags = dict( json=({'NbserverListApp': {'json': True}}, "Produce machine-readable JSON output."), ) json = Bool(False, config=True, help="If True, each line of output will be a JSON object with the " "details from the server info file.") def start(self): if not self.json: print("Currently running servers:") for serverinfo in list_running_servers(self.runtime_dir): if self.json: print(json.dumps(serverinfo)) else: print(serverinfo['url'], "::", serverinfo['notebook_dir']) #----------------------------------------------------------------------------- # Aliases and Flags #----------------------------------------------------------------------------- flags = dict(base_flags) flags['no-browser']=( {'NotebookApp' : {'open_browser' : False}}, "Don't open the notebook in a browser after startup." ) flags['pylab']=( {'NotebookApp' : {'pylab' : 'warn'}}, "DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib." ) flags['no-mathjax']=( {'NotebookApp' : {'enable_mathjax' : False}}, """Disable MathJax MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) # Add notebook manager flags flags.update(boolean_flag('script', 'FileContentsManager.save_script', 'DEPRECATED, IGNORED', 'DEPRECATED, IGNORED')) aliases = dict(base_aliases) aliases.update({ 'ip': 'NotebookApp.ip', 'port': 'NotebookApp.port', 'port-retries': 'NotebookApp.port_retries', 'transport': 'KernelManager.transport', 'keyfile': 'NotebookApp.keyfile', 'certfile': 'NotebookApp.certfile', 'notebook-dir': 'NotebookApp.notebook_dir', 'browser': 'NotebookApp.browser', 'pylab': 'NotebookApp.pylab', }) #----------------------------------------------------------------------------- # NotebookApp #----------------------------------------------------------------------------- class NotebookApp(JupyterApp): name = 'jupyter-notebook' version = __version__ description = """ The Jupyter HTML Notebook. This launches a Tornado based HTML Notebook Server that serves up an HTML5/Javascript Notebook client. """ examples = _examples aliases = aliases flags = flags classes = [ KernelManager, Session, MappingKernelManager, ContentsManager, FileContentsManager, NotebookNotary, KernelSpecManager, ] flags = Dict(flags) aliases = Dict(aliases) subcommands = dict( list=(NbserverListApp, NbserverListApp.description.splitlines()[0]), ) _log_formatter_cls = LogFormatter def _log_level_default(self): return logging.INFO def _log_datefmt_default(self): """Exclude date from default date format""" return "%H:%M:%S" def _log_format_default(self): """override default log format to include time""" return u"%(color)s[%(levelname)1.1s %(asctime)s.%(msecs).03d %(name)s]%(end_color)s %(message)s" # create requested profiles by default, if they don't exist: auto_create = Bool(True) ignore_minified_js = Bool(False, config=True, help='Use minified JS file or not, mainly use during dev to avoid JS recompilation', ) # file to be opened in the notebook server file_to_run = Unicode('', config=True) # Network related information allow_origin = Unicode('', config=True, help="""Set the Access-Control-Allow-Origin header Use '*' to allow any origin to access your server. Takes precedence over allow_origin_pat. """ ) allow_origin_pat = Unicode('', config=True, help="""Use a regular expression for the Access-Control-Allow-Origin header Requests from an origin matching the expression will get replies with: Access-Control-Allow-Origin: origin where `origin` is the origin of the request. Ignored if allow_origin is set. """ ) allow_credentials = Bool(False, config=True, help="Set the Access-Control-Allow-Credentials: true header" ) default_url = Unicode('/tree', config=True, help="The default URL to redirect to from `/`" ) ip = Unicode('localhost', config=True, help="The IP address the notebook server will listen on." ) def _ip_default(self): """Return localhost if available, 127.0.0.1 otherwise. On some (horribly broken) systems, localhost cannot be bound. """ s = socket.socket() try: s.bind(('localhost', 0)) except socket.error as e: self.log.warn("Cannot bind to localhost, using 127.0.0.1 as default ip\n%s", e) return '127.0.0.1' else: s.close() return 'localhost' def _ip_changed(self, name, old, new): if new == u'*': self.ip = u'' port = Integer(8888, config=True, help="The port the notebook server will listen on." ) port_retries = Integer(50, config=True, help="The number of additional ports to try if the specified port is not available." ) certfile = Unicode(u'', config=True, help="""The full path to an SSL/TLS certificate file.""" ) keyfile = Unicode(u'', config=True, help="""The full path to a private key file for usage with SSL/TLS.""" ) cookie_secret_file = Unicode(config=True, help="""The file where the cookie secret is stored.""" ) def _cookie_secret_file_default(self): return os.path.join(self.runtime_dir, 'notebook_cookie_secret') cookie_secret = Bytes(b'', config=True, help="""The random bytes used to secure cookies. By default this is a new random number every time you start the Notebook. Set it to a value in a config file to enable logins to persist across server sessions. Note: Cookie secrets should be kept private, do not share config files with cookie_secret stored in plaintext (you can read the value from a file). """ ) def _cookie_secret_default(self): if os.path.exists(self.cookie_secret_file): with io.open(self.cookie_secret_file, 'rb') as f: return f.read() else: secret = base64.encodestring(os.urandom(1024)) self._write_cookie_secret_file(secret) return secret def _write_cookie_secret_file(self, secret): """write my secret to my secret_file""" self.log.info("Writing notebook server cookie secret to %s", self.cookie_secret_file) with io.open(self.cookie_secret_file, 'wb') as f: f.write(secret) try: os.chmod(self.cookie_secret_file, 0o600) except OSError: self.log.warn( "Could not set permissions on %s", self.cookie_secret_file ) password = Unicode(u'', config=True, help="""Hashed password to use for web authentication. To generate, type in a python/IPython shell: from notebook.auth import passwd; passwd() The string should be of the form type:salt:hashed-password. """ ) open_browser = Bool(True, config=True, help="""Whether to open in a browser after starting. The specific browser used is platform dependent and determined by the python standard library `webbrowser` module, unless it is overridden using the --browser (NotebookApp.browser) configuration option. """) browser = Unicode(u'', config=True, help="""Specify what command to use to invoke a web browser when opening the notebook. If not specified, the default browser will be determined by the `webbrowser` standard library module, which allows setting of the BROWSER environment variable to override it. """) webapp_settings = Dict(config=True, help="DEPRECATED, use tornado_settings" ) def _webapp_settings_changed(self, name, old, new): self.log.warn("\n webapp_settings is deprecated, use tornado_settings.\n") self.tornado_settings = new tornado_settings = Dict(config=True, help="Supply overrides for the tornado.web.Application that the " "Jupyter notebook uses.") ssl_options = Dict(config=True, help="""Supply SSL options for the tornado HTTPServer. See the tornado docs for details.""") jinja_environment_options = Dict(config=True, help="Supply extra arguments that will be passed to Jinja environment.") jinja_template_vars = Dict( config=True, help="Extra variables to supply to jinja templates when rendering.", ) enable_mathjax = Bool(True, config=True, help="""Whether to enable MathJax for typesetting math/TeX MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) def _enable_mathjax_changed(self, name, old, new): """set mathjax url to empty if mathjax is disabled""" if not new: self.mathjax_url = u'' base_url = Unicode('/', config=True, help='''The base URL for the notebook server. Leading and trailing slashes can be omitted, and will automatically be added. ''') def _base_url_changed(self, name, old, new): if not new.startswith('/'): self.base_url = '/'+new elif not new.endswith('/'): self.base_url = new+'/' base_project_url = Unicode('/', config=True, help="""DEPRECATED use base_url""") def _base_project_url_changed(self, name, old, new): self.log.warn("base_project_url is deprecated, use base_url") self.base_url = new extra_static_paths = List(Unicode(), config=True, help="""Extra paths to search for serving static files. This allows adding javascript/css to be available from the notebook server machine, or overriding individual files in the IPython""" ) @property def static_file_path(self): """return extra paths + the default location""" return self.extra_static_paths + [DEFAULT_STATIC_FILES_PATH] static_custom_path = List(Unicode(), help="""Path to search for custom.js, css""" ) def _static_custom_path_default(self): return [ os.path.join(d, 'custom') for d in ( self.config_dir, # FIXME: serve IPython profile while we don't have `jupyter migrate` os.path.join(get_ipython_dir(), 'profile_default', 'static'), DEFAULT_STATIC_FILES_PATH) ] extra_template_paths = List(Unicode(), config=True, help="""Extra paths to search for serving jinja templates. Can be used to override templates from notebook.templates.""" ) @property def template_file_path(self): """return extra paths + the default locations""" return self.extra_template_paths + DEFAULT_TEMPLATE_PATH_LIST extra_nbextensions_path = List(Unicode(), config=True, help="""extra paths to look for Javascript notebook extensions""" ) @property def nbextensions_path(self): """The path to look for Javascript notebook extensions""" path = self.extra_nbextensions_path + jupyter_path('nbextensions') # FIXME: remove IPython nbextensions path once migration is setup path.append(os.path.join(get_ipython_dir(), 'nbextensions')) return path websocket_url = Unicode("", config=True, help="""The base URL for websockets, if it differs from the HTTP server (hint: it almost certainly doesn't). Should be in the form of an HTTP origin: ws[s]://hostname[:port] """ ) mathjax_url = Unicode("", config=True, help="""The url for MathJax.js.""" ) def _mathjax_url_default(self): if not self.enable_mathjax: return u'' static_url_prefix = self.tornado_settings.get("static_url_prefix", url_path_join(self.base_url, "static") ) return url_path_join(static_url_prefix, 'components', 'MathJax', 'MathJax.js') def _mathjax_url_changed(self, name, old, new): if new and not self.enable_mathjax: # enable_mathjax=False overrides mathjax_url self.mathjax_url = u'' else: self.log.info("Using MathJax: %s", new) contents_manager_class = Type( default_value=FileContentsManager, klass=ContentsManager, config=True, help='The notebook manager class to use.' ) kernel_manager_class = Type( default_value=MappingKernelManager, config=True, help='The kernel manager class to use.' ) session_manager_class = Type( default_value=SessionManager, config=True, help='The session manager class to use.' ) config_manager_class = Type( default_value=ConfigManager, config = True, help='The config manager class to use' ) kernel_spec_manager = Instance(KernelSpecManager, allow_none=True) kernel_spec_manager_class = Type( default_value=KernelSpecManager, config=True, help=""" The kernel spec manager class to use. Should be a subclass of `jupyter_client.kernelspec.KernelSpecManager`. The Api of KernelSpecManager is provisional and might change without warning between this version of Jupyter and the next stable one. """ ) login_handler_class = Type( default_value=LoginHandler, klass=web.RequestHandler, config=True, help='The login handler class to use.', ) logout_handler_class = Type( default_value=LogoutHandler, klass=web.RequestHandler, config=True, help='The logout handler class to use.', ) trust_xheaders = Bool(False, config=True, help=("Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-For headers" "sent by the upstream reverse proxy. Necessary if the proxy handles SSL") ) info_file = Unicode() def _info_file_default(self): info_file = "nbserver-%s.json" % os.getpid() return os.path.join(self.runtime_dir, info_file) pylab = Unicode('disabled', config=True, help=""" DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib. """ ) def _pylab_changed(self, name, old, new): """when --pylab is specified, display a warning and exit""" if new != 'warn': backend = ' %s' % new else: backend = '' self.log.error("Support for specifying --pylab on the command line has been removed.") self.log.error( "Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.".format(backend) ) self.exit(1) notebook_dir = Unicode(config=True, help="The directory to use for notebooks and kernels." ) def _notebook_dir_default(self): if self.file_to_run: return os.path.dirname(os.path.abspath(self.file_to_run)) else: return py3compat.getcwd() def _notebook_dir_changed(self, name, old, new): """Do a bit of validation of the notebook dir.""" if not os.path.isabs(new): # If we receive a non-absolute path, make it absolute. self.notebook_dir = os.path.abspath(new) return if not os.path.isdir(new): raise TraitError("No such notebook dir: %r" % new) # setting App.notebook_dir implies setting notebook and kernel dirs as well self.config.FileContentsManager.root_dir = new self.config.MappingKernelManager.root_dir = new server_extensions = List(Unicode(), config=True, help=("Python modules to load as notebook server extensions. " "This is an experimental API, and may change in future releases.") ) reraise_server_extension_failures = Bool( False, config=True, help="Reraise exceptions encountered loading server extensions?", ) def parse_command_line(self, argv=None): super(NotebookApp, self).parse_command_line(argv) if self.extra_args: arg0 = self.extra_args[0] f = os.path.abspath(arg0) self.argv.remove(arg0) if not os.path.exists(f): self.log.critical("No such file or directory: %s", f) self.exit(1) # Use config here, to ensure that it takes higher priority than # anything that comes from the profile. c = Config() if os.path.isdir(f): c.NotebookApp.notebook_dir = f elif os.path.isfile(f): c.NotebookApp.file_to_run = f self.update_config(c) def init_configurables(self): self.kernel_spec_manager = self.kernel_spec_manager_class( parent=self, ) self.kernel_manager = self.kernel_manager_class( parent=self, log=self.log, connection_dir=self.runtime_dir, kernel_spec_manager=self.kernel_spec_manager, ) self.contents_manager = self.contents_manager_class( parent=self, log=self.log, ) self.session_manager = self.session_manager_class( parent=self, log=self.log, kernel_manager=self.kernel_manager, contents_manager=self.contents_manager, ) self.config_manager = self.config_manager_class( parent=self, log=self.log, config_dir=os.path.join(self.config_dir, 'nbconfig'), ) def init_logging(self): # This prevents double log messages because tornado use a root logger that # self.log is a child of. The logging module dipatches log messages to a log # and all of its ancenstors until propagate is set to False. self.log.propagate = False for log in app_log, access_log, gen_log: # consistent log output name (NotebookApp instead of tornado.access, etc.) log.name = self.log.name # hook up tornado 3's loggers to our app handlers logger = logging.getLogger('tornado') logger.propagate = True logger.parent = self.log logger.setLevel(self.log.level) def init_webapp(self): """initialize tornado webapp and httpserver""" self.tornado_settings['allow_origin'] = self.allow_origin if self.allow_origin_pat: self.tornado_settings['allow_origin_pat'] = re.compile(self.allow_origin_pat) self.tornado_settings['allow_credentials'] = self.allow_credentials # ensure default_url starts with base_url if not self.default_url.startswith(self.base_url): self.default_url = url_path_join(self.base_url, self.default_url) self.web_app = NotebookWebApplication( self, self.kernel_manager, self.contents_manager, self.session_manager, self.kernel_spec_manager, self.config_manager, self.log, self.base_url, self.default_url, self.tornado_settings, self.jinja_environment_options ) ssl_options = self.ssl_options if self.certfile: ssl_options['certfile'] = self.certfile if self.keyfile: ssl_options['keyfile'] = self.keyfile if not ssl_options: # None indicates no SSL config ssl_options = None else: # Disable SSLv3, since its use is discouraged. ssl_options['ssl_version']=ssl.PROTOCOL_TLSv1 self.login_handler_class.validate_security(self, ssl_options=ssl_options) self.http_server = httpserver.HTTPServer(self.web_app, ssl_options=ssl_options, xheaders=self.trust_xheaders) success = None for port in random_ports(self.port, self.port_retries+1): try: self.http_server.listen(port, self.ip) except socket.error as e: if e.errno == errno.EADDRINUSE: self.log.info('The port %i is already in use, trying another random port.' % port) continue elif e.errno in (errno.EACCES, getattr(errno, 'WSAEACCES', errno.EACCES)): self.log.warn("Permission to listen on port %i denied" % port) continue else: raise else: self.port = port success = True break if not success: self.log.critical('ERROR: the notebook server could not be started because ' 'no available port could be found.') self.exit(1) @property def display_url(self): ip = self.ip if self.ip else '[all ip addresses on your system]' return self._url(ip) @property def connection_url(self): ip = self.ip if self.ip else 'localhost' return self._url(ip) def _url(self, ip): proto = 'https' if self.certfile else 'http' return "%s://%s:%i%s" % (proto, ip, self.port, self.base_url) def init_terminals(self): try: from .terminal import initialize initialize(self.web_app, self.notebook_dir, self.connection_url) self.web_app.settings['terminals_available'] = True except ImportError as e: log = self.log.debug if sys.platform == 'win32' else self.log.warn log("Terminals not available (error was %s)", e) def init_signal(self): if not sys.platform.startswith('win') and sys.stdin.isatty(): signal.signal(signal.SIGINT, self._handle_sigint) signal.signal(signal.SIGTERM, self._signal_stop) if hasattr(signal, 'SIGUSR1'): # Windows doesn't support SIGUSR1 signal.signal(signal.SIGUSR1, self._signal_info) if hasattr(signal, 'SIGINFO'): # only on BSD-based systems signal.signal(signal.SIGINFO, self._signal_info) def _handle_sigint(self, sig, frame): """SIGINT handler spawns confirmation dialog""" # register more forceful signal handler for ^C^C case signal.signal(signal.SIGINT, self._signal_stop) # request confirmation dialog in bg thread, to avoid # blocking the App thread = threading.Thread(target=self._confirm_exit) thread.daemon = True thread.start() def _restore_sigint_handler(self): """callback for restoring original SIGINT handler""" signal.signal(signal.SIGINT, self._handle_sigint) def _confirm_exit(self): """confirm shutdown on ^C A second ^C, or answering 'y' within 5s will cause shutdown, otherwise original SIGINT handler will be restored. This doesn't work on Windows. """ info = self.log.info info('interrupted') print(self.notebook_info()) sys.stdout.write("Shutdown this notebook server (y/[n])? ") sys.stdout.flush() r,w,x = select.select([sys.stdin], [], [], 5) if r: line = sys.stdin.readline() if line.lower().startswith('y') and 'n' not in line.lower(): self.log.critical("Shutdown confirmed") ioloop.IOLoop.current().stop() return else: print("No answer for 5s:", end=' ') print("resuming operation...") # no answer, or answer is no: # set it back to original SIGINT handler # use IOLoop.add_callback because signal.signal must be called # from main thread ioloop.IOLoop.current().add_callback(self._restore_sigint_handler) def _signal_stop(self, sig, frame): self.log.critical("received signal %s, stopping", sig) ioloop.IOLoop.current().stop() def _signal_info(self, sig, frame): print(self.notebook_info()) def init_components(self): """Check the components submodule, and warn if it's unclean""" # TODO: this should still check, but now we use bower, not git submodule pass def init_server_extensions(self): """Load any extensions specified by config. Import the module, then call the load_jupyter_server_extension function, if one exists. The extension API is experimental, and may change in future releases. """ for modulename in self.server_extensions: try: mod = importlib.import_module(modulename) func = getattr(mod, 'load_jupyter_server_extension', None) if func is not None: func(self) except Exception: if self.reraise_server_extension_failures: raise self.log.warn("Error loading server extension %s", modulename, exc_info=True) @catch_config_error def initialize(self, argv=None): super(NotebookApp, self).initialize(argv) self.init_logging() if self._dispatching: return self.init_configurables() self.init_components() self.init_webapp() self.init_terminals() self.init_signal() self.init_server_extensions() def cleanup_kernels(self): """Shutdown all kernels. The kernels will shutdown themselves when this process no longer exists, but explicit shutdown allows the KernelManagers to cleanup the connection files. """ self.log.info('Shutting down kernels') self.kernel_manager.shutdown_all() def notebook_info(self): "Return the current working directory and the server url information" info = self.contents_manager.info_string() + "\n" info += "%d active kernels \n" % len(self.kernel_manager._kernels) return info + "The Jupyter Notebook is running at: %s" % self.display_url def server_info(self): """Return a JSONable dict of information about this server.""" return {'url': self.connection_url, 'hostname': self.ip if self.ip else 'localhost', 'port': self.port, 'secure': bool(self.certfile), 'base_url': self.base_url, 'notebook_dir': os.path.abspath(self.notebook_dir), 'pid': os.getpid() } def write_server_info_file(self): """Write the result of server_info() to the JSON file info_file.""" with open(self.info_file, 'w') as f: json.dump(self.server_info(), f, indent=2) def remove_server_info_file(self): """Remove the nbserver-<pid>.json file created for this server. Ignores the error raised when the file has already been removed. """ try: os.unlink(self.info_file) except OSError as e: if e.errno != errno.ENOENT: raise def start(self): """ Start the Notebook server app, after initialization This method takes no arguments so all configuration and initialization must be done prior to calling this method.""" super(NotebookApp, self).start() info = self.log.info for line in self.notebook_info().split("\n"): info(line) info("Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).") self.write_server_info_file() if self.open_browser or self.file_to_run: try: browser = webbrowser.get(self.browser or None) except webbrowser.Error as e: self.log.warn('No web browser found: %s.' % e) browser = None if self.file_to_run: if not os.path.exists(self.file_to_run): self.log.critical("%s does not exist" % self.file_to_run) self.exit(1) relpath = os.path.relpath(self.file_to_run, self.notebook_dir) uri = url_path_join('notebooks', *relpath.split(os.sep)) else: uri = 'tree' if browser: b = lambda : browser.open(url_path_join(self.connection_url, uri), new=2) threading.Thread(target=b).start() self.io_loop = ioloop.IOLoop.current() if sys.platform.startswith('win'): # add no-op to wake every 5s # to handle signals that may be ignored by the inner loop pc = ioloop.PeriodicCallback(lambda : None, 5000) pc.start() try: self.io_loop.start() except KeyboardInterrupt: info("Interrupted...") finally: self.cleanup_kernels() self.remove_server_info_file() def stop(self): def _stop(): self.http_server.stop() self.io_loop.stop() self.io_loop.add_callback(_stop) def list_running_servers(runtime_dir=None): """Iterate over the server info files of running notebook servers. Given a profile name, find nbserver-* files in the security directory of that profile, and yield dicts of their information, each one pertaining to a currently running notebook server instance. """ if runtime_dir is None: runtime_dir = jupyter_runtime_dir() # The runtime dir might not exist if not os.path.isdir(runtime_dir): return for file in os.listdir(runtime_dir): if file.startswith('nbserver-'): with io.open(os.path.join(runtime_dir, file), encoding='utf-8') as f: info = json.load(f) # Simple check whether that process is really still running # Also remove leftover files from IPython 2.x without a pid field if ('pid' in info) and check_pid(info['pid']): yield info else: # If the process has died, try to delete its info file try: os.unlink(file) except OSError: pass # TODO: This should warn or log or something #----------------------------------------------------------------------------- # Main entry point #----------------------------------------------------------------------------- main = launch_new_instance = NotebookApp.launch_instance
# coding: utf-8 """A tornado based Jupyter notebook server.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import absolute_import, print_function import base64 import datetime import errno import importlib import io import json import logging import os import random import re import select import signal import socket import ssl import sys import threading import webbrowser from jinja2 import Environment, FileSystemLoader # Install the pyzmq ioloop. This has to be done before anything else from # tornado is imported. from zmq.eventloop import ioloop ioloop.install() # check for tornado 3.1.0 msg = "The Jupyter Notebook requires tornado >= 4.0" try: import tornado except ImportError: raise ImportError(msg) try: version_info = tornado.version_info except AttributeError: raise ImportError(msg + ", but you have < 1.1.0") if version_info < (4,0): raise ImportError(msg + ", but you have %s" % tornado.version) from tornado import httpserver from tornado import web from tornado.log import LogFormatter, app_log, access_log, gen_log from notebook import ( DEFAULT_STATIC_FILES_PATH, DEFAULT_TEMPLATE_PATH_LIST, __version__, ) from .base.handlers import Template404 from .log import log_request from .services.kernels.kernelmanager import MappingKernelManager from .services.config import ConfigManager from .services.contents.manager import ContentsManager from .services.contents.filemanager import FileContentsManager from .services.sessions.sessionmanager import SessionManager from .auth.login import LoginHandler from .auth.logout import LogoutHandler from .base.handlers import FileFindHandler, IPythonHandler from traitlets.config import Config from traitlets.config.application import catch_config_error, boolean_flag from jupyter_core.application import ( JupyterApp, base_flags, base_aliases, ) from jupyter_client import KernelManager from jupyter_client.kernelspec import KernelSpecManager, NoSuchKernel, NATIVE_KERNEL_NAME from jupyter_client.session import Session from nbformat.sign import NotebookNotary from traitlets import ( Dict, Unicode, Integer, List, Bool, Bytes, Instance, TraitError, Type, ) from ipython_genutils import py3compat from IPython.paths import get_ipython_dir from jupyter_core.paths import jupyter_runtime_dir, jupyter_path from notebook._sysinfo import get_sys_info from .utils import url_path_join, check_pid #----------------------------------------------------------------------------- # Module globals #----------------------------------------------------------------------------- _examples = """ jupyter notebook # start the notebook jupyter notebook --certfile=mycert.pem # use SSL/TLS certificate """ #----------------------------------------------------------------------------- # Helper functions #----------------------------------------------------------------------------- def random_ports(port, n): """Generate a list of n random ports near the given port. The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n]. """ for i in range(min(5, n)): yield port + i for i in range(n-5): yield max(1, port + random.randint(-2*n, 2*n)) def load_handlers(name): """Load the (URL pattern, handler) tuples for each component.""" name = 'notebook.' + name mod = __import__(name, fromlist=['default_handlers']) return mod.default_handlers class DeprecationHandler(IPythonHandler): def get(self, url_path): self.set_header("Content-Type", 'text/javascript') self.finish(""" console.warn('`/static/widgets/js` is deprecated. Use `/nbextensions/widgets/widgets/js` instead.'); define(['%s'], function(x) { return x; }); """ % url_path_join('nbextensions', 'widgets', 'widgets', url_path.rstrip('.js'))) self.log.warn('Deprecated widget Javascript path /static/widgets/js/*.js was used') #----------------------------------------------------------------------------- # The Tornado web application #----------------------------------------------------------------------------- class NotebookWebApplication(web.Application): def __init__(self, ipython_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, log, base_url, default_url, settings_overrides, jinja_env_options): settings = self.init_settings( ipython_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, log, base_url, default_url, settings_overrides, jinja_env_options) handlers = self.init_handlers(settings) super(NotebookWebApplication, self).__init__(handlers, **settings) def init_settings(self, ipython_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, log, base_url, default_url, settings_overrides, jinja_env_options=None): _template_path = settings_overrides.get( "template_path", ipython_app.template_file_path, ) if isinstance(_template_path, py3compat.string_types): _template_path = (_template_path,) template_path = [os.path.expanduser(path) for path in _template_path] jenv_opt = {"autoescape": True} jenv_opt.update(jinja_env_options if jinja_env_options else {}) env = Environment(loader=FileSystemLoader(template_path), **jenv_opt) sys_info = get_sys_info() if sys_info['commit_source'] == 'repository': # don't cache (rely on 304) when working from master version_hash = '' else: # reset the cache on server restart version_hash = datetime.datetime.now().strftime("%Y%m%d%H%M%S") settings = dict( # basics log_function=log_request, base_url=base_url, default_url=default_url, template_path=template_path, static_path=ipython_app.static_file_path, static_custom_path=ipython_app.static_custom_path, static_handler_class = FileFindHandler, static_url_prefix = url_path_join(base_url,'/static/'), static_handler_args = { # don't cache custom.js 'no_cache_paths': [url_path_join(base_url, 'static', 'custom')], }, version_hash=version_hash, ignore_minified_js=ipython_app.ignore_minified_js, # authentication cookie_secret=ipython_app.cookie_secret, login_url=url_path_join(base_url,'/login'), login_handler_class=ipython_app.login_handler_class, logout_handler_class=ipython_app.logout_handler_class, password=ipython_app.password, # managers kernel_manager=kernel_manager, contents_manager=contents_manager, session_manager=session_manager, kernel_spec_manager=kernel_spec_manager, config_manager=config_manager, # IPython stuff jinja_template_vars=ipython_app.jinja_template_vars, nbextensions_path=ipython_app.nbextensions_path, websocket_url=ipython_app.websocket_url, mathjax_url=ipython_app.mathjax_url, config=ipython_app.config, config_dir=ipython_app.config_dir, jinja2_env=env, terminals_available=False, # Set later if terminals are available ) # allow custom overrides for the tornado web app. settings.update(settings_overrides) return settings def init_handlers(self, settings): """Load the (URL pattern, handler) tuples for each component.""" # Order matters. The first handler to match the URL will handle the request. handlers = [] handlers.append((r'/deprecatedwidgets/(.*)', DeprecationHandler)) handlers.extend(load_handlers('tree.handlers')) handlers.extend([(r"/login", settings['login_handler_class'])]) handlers.extend([(r"/logout", settings['logout_handler_class'])]) handlers.extend(load_handlers('files.handlers')) handlers.extend(load_handlers('notebook.handlers')) handlers.extend(load_handlers('nbconvert.handlers')) handlers.extend(load_handlers('kernelspecs.handlers')) handlers.extend(load_handlers('edit.handlers')) handlers.extend(load_handlers('services.api.handlers')) handlers.extend(load_handlers('services.config.handlers')) handlers.extend(load_handlers('services.kernels.handlers')) handlers.extend(load_handlers('services.contents.handlers')) handlers.extend(load_handlers('services.sessions.handlers')) handlers.extend(load_handlers('services.nbconvert.handlers')) handlers.extend(load_handlers('services.kernelspecs.handlers')) handlers.extend(load_handlers('services.security.handlers')) # BEGIN HARDCODED WIDGETS HACK try: import ipywidgets handlers.append( (r"/nbextensions/widgets/(.*)", FileFindHandler, { 'path': ipywidgets.find_static_assets(), 'no_cache_paths': ['/'], # don't cache anything in nbextensions }), ) except: app_log.warn('ipywidgets package not installed. Widgets are unavailable.') # END HARDCODED WIDGETS HACK handlers.append( (r"/nbextensions/(.*)", FileFindHandler, { 'path': settings['nbextensions_path'], 'no_cache_paths': ['/'], # don't cache anything in nbextensions }), ) handlers.append( (r"/custom/(.*)", FileFindHandler, { 'path': settings['static_custom_path'], 'no_cache_paths': ['/'], # don't cache anything in custom }) ) # register base handlers last handlers.extend(load_handlers('base.handlers')) # set the URL that will be redirected from `/` handlers.append( (r'/?', web.RedirectHandler, { 'url' : settings['default_url'], 'permanent': False, # want 302, not 301 }) ) # prepend base_url onto the patterns that we match new_handlers = [] for handler in handlers: pattern = url_path_join(settings['base_url'], handler[0]) new_handler = tuple([pattern] + list(handler[1:])) new_handlers.append(new_handler) # add 404 on the end, which will catch everything that falls through new_handlers.append((r'(.*)', Template404)) return new_handlers class NbserverListApp(JupyterApp): version = __version__ description="List currently running notebook servers in this profile." flags = dict( json=({'NbserverListApp': {'json': True}}, "Produce machine-readable JSON output."), ) json = Bool(False, config=True, help="If True, each line of output will be a JSON object with the " "details from the server info file.") def start(self): if not self.json: print("Currently running servers:") for serverinfo in list_running_servers(self.runtime_dir): if self.json: print(json.dumps(serverinfo)) else: print(serverinfo['url'], "::", serverinfo['notebook_dir']) #----------------------------------------------------------------------------- # Aliases and Flags #----------------------------------------------------------------------------- flags = dict(base_flags) flags['no-browser']=( {'NotebookApp' : {'open_browser' : False}}, "Don't open the notebook in a browser after startup." ) flags['pylab']=( {'NotebookApp' : {'pylab' : 'warn'}}, "DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib." ) flags['no-mathjax']=( {'NotebookApp' : {'enable_mathjax' : False}}, """Disable MathJax MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) # Add notebook manager flags flags.update(boolean_flag('script', 'FileContentsManager.save_script', 'DEPRECATED, IGNORED', 'DEPRECATED, IGNORED')) aliases = dict(base_aliases) aliases.update({ 'ip': 'NotebookApp.ip', 'port': 'NotebookApp.port', 'port-retries': 'NotebookApp.port_retries', 'transport': 'KernelManager.transport', 'keyfile': 'NotebookApp.keyfile', 'certfile': 'NotebookApp.certfile', 'notebook-dir': 'NotebookApp.notebook_dir', 'browser': 'NotebookApp.browser', 'pylab': 'NotebookApp.pylab', }) #----------------------------------------------------------------------------- # NotebookApp #----------------------------------------------------------------------------- class NotebookApp(JupyterApp): name = 'jupyter-notebook' version = __version__ description = """ The Jupyter HTML Notebook. This launches a Tornado based HTML Notebook Server that serves up an HTML5/Javascript Notebook client. """ examples = _examples aliases = aliases flags = flags classes = [ KernelManager, Session, MappingKernelManager, ContentsManager, FileContentsManager, NotebookNotary, KernelSpecManager, ] flags = Dict(flags) aliases = Dict(aliases) subcommands = dict( list=(NbserverListApp, NbserverListApp.description.splitlines()[0]), ) _log_formatter_cls = LogFormatter def _log_level_default(self): return logging.INFO def _log_datefmt_default(self): """Exclude date from default date format""" return "%H:%M:%S" def _log_format_default(self): """override default log format to include time""" return u"%(color)s[%(levelname)1.1s %(asctime)s.%(msecs).03d %(name)s]%(end_color)s %(message)s" # create requested profiles by default, if they don't exist: auto_create = Bool(True) ignore_minified_js = Bool(False, config=True, help='Use minified JS file or not, mainly use during dev to avoid JS recompilation', ) # file to be opened in the notebook server file_to_run = Unicode('', config=True) # Network related information allow_origin = Unicode('', config=True, help="""Set the Access-Control-Allow-Origin header Use '*' to allow any origin to access your server. Takes precedence over allow_origin_pat. """ ) allow_origin_pat = Unicode('', config=True, help="""Use a regular expression for the Access-Control-Allow-Origin header Requests from an origin matching the expression will get replies with: Access-Control-Allow-Origin: origin where `origin` is the origin of the request. Ignored if allow_origin is set. """ ) allow_credentials = Bool(False, config=True, help="Set the Access-Control-Allow-Credentials: true header" ) default_url = Unicode('/tree', config=True, help="The default URL to redirect to from `/`" ) ip = Unicode('localhost', config=True, help="The IP address the notebook server will listen on." ) def _ip_default(self): """Return localhost if available, 127.0.0.1 otherwise. On some (horribly broken) systems, localhost cannot be bound. """ s = socket.socket() try: s.bind(('localhost', 0)) except socket.error as e: self.log.warn("Cannot bind to localhost, using 127.0.0.1 as default ip\n%s", e) return '127.0.0.1' else: s.close() return 'localhost' def _ip_changed(self, name, old, new): if new == u'*': self.ip = u'' port = Integer(8888, config=True, help="The port the notebook server will listen on." ) port_retries = Integer(50, config=True, help="The number of additional ports to try if the specified port is not available." ) certfile = Unicode(u'', config=True, help="""The full path to an SSL/TLS certificate file.""" ) keyfile = Unicode(u'', config=True, help="""The full path to a private key file for usage with SSL/TLS.""" ) cookie_secret_file = Unicode(config=True, help="""The file where the cookie secret is stored.""" ) def _cookie_secret_file_default(self): return os.path.join(self.runtime_dir, 'notebook_cookie_secret') cookie_secret = Bytes(b'', config=True, help="""The random bytes used to secure cookies. By default this is a new random number every time you start the Notebook. Set it to a value in a config file to enable logins to persist across server sessions. Note: Cookie secrets should be kept private, do not share config files with cookie_secret stored in plaintext (you can read the value from a file). """ ) def _cookie_secret_default(self): if os.path.exists(self.cookie_secret_file): with io.open(self.cookie_secret_file, 'rb') as f: return f.read() else: secret = base64.encodestring(os.urandom(1024)) self._write_cookie_secret_file(secret) return secret def _write_cookie_secret_file(self, secret): """write my secret to my secret_file""" self.log.info("Writing notebook server cookie secret to %s", self.cookie_secret_file) with io.open(self.cookie_secret_file, 'wb') as f: f.write(secret) try: os.chmod(self.cookie_secret_file, 0o600) except OSError: self.log.warn( "Could not set permissions on %s", self.cookie_secret_file ) password = Unicode(u'', config=True, help="""Hashed password to use for web authentication. To generate, type in a python/IPython shell: from notebook.auth import passwd; passwd() The string should be of the form type:salt:hashed-password. """ ) open_browser = Bool(True, config=True, help="""Whether to open in a browser after starting. The specific browser used is platform dependent and determined by the python standard library `webbrowser` module, unless it is overridden using the --browser (NotebookApp.browser) configuration option. """) browser = Unicode(u'', config=True, help="""Specify what command to use to invoke a web browser when opening the notebook. If not specified, the default browser will be determined by the `webbrowser` standard library module, which allows setting of the BROWSER environment variable to override it. """) webapp_settings = Dict(config=True, help="DEPRECATED, use tornado_settings" ) def _webapp_settings_changed(self, name, old, new): self.log.warn("\n webapp_settings is deprecated, use tornado_settings.\n") self.tornado_settings = new tornado_settings = Dict(config=True, help="Supply overrides for the tornado.web.Application that the " "Jupyter notebook uses.") ssl_options = Dict(config=True, help="""Supply SSL options for the tornado HTTPServer. See the tornado docs for details.""") jinja_environment_options = Dict(config=True, help="Supply extra arguments that will be passed to Jinja environment.") jinja_template_vars = Dict( config=True, help="Extra variables to supply to jinja templates when rendering.", ) enable_mathjax = Bool(True, config=True, help="""Whether to enable MathJax for typesetting math/TeX MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) def _enable_mathjax_changed(self, name, old, new): """set mathjax url to empty if mathjax is disabled""" if not new: self.mathjax_url = u'' base_url = Unicode('/', config=True, help='''The base URL for the notebook server. Leading and trailing slashes can be omitted, and will automatically be added. ''') def _base_url_changed(self, name, old, new): if not new.startswith('/'): self.base_url = '/'+new elif not new.endswith('/'): self.base_url = new+'/' base_project_url = Unicode('/', config=True, help="""DEPRECATED use base_url""") def _base_project_url_changed(self, name, old, new): self.log.warn("base_project_url is deprecated, use base_url") self.base_url = new extra_static_paths = List(Unicode(), config=True, help="""Extra paths to search for serving static files. This allows adding javascript/css to be available from the notebook server machine, or overriding individual files in the IPython""" ) @property def static_file_path(self): """return extra paths + the default location""" return self.extra_static_paths + [DEFAULT_STATIC_FILES_PATH] static_custom_path = List(Unicode(), help="""Path to search for custom.js, css""" ) def _static_custom_path_default(self): return [ os.path.join(d, 'custom') for d in ( self.config_dir, # FIXME: serve IPython profile while we don't have `jupyter migrate` os.path.join(get_ipython_dir(), 'profile_default', 'static'), DEFAULT_STATIC_FILES_PATH) ] extra_template_paths = List(Unicode(), config=True, help="""Extra paths to search for serving jinja templates. Can be used to override templates from notebook.templates.""" ) @property def template_file_path(self): """return extra paths + the default locations""" return self.extra_template_paths + DEFAULT_TEMPLATE_PATH_LIST extra_nbextensions_path = List(Unicode(), config=True, help="""extra paths to look for Javascript notebook extensions""" ) @property def nbextensions_path(self): """The path to look for Javascript notebook extensions""" path = self.extra_nbextensions_path + jupyter_path('nbextensions') # FIXME: remove IPython nbextensions path once migration is setup path.append(os.path.join(get_ipython_dir(), 'nbextensions')) return path websocket_url = Unicode("", config=True, help="""The base URL for websockets, if it differs from the HTTP server (hint: it almost certainly doesn't). Should be in the form of an HTTP origin: ws[s]://hostname[:port] """ ) mathjax_url = Unicode("", config=True, help="""The url for MathJax.js.""" ) def _mathjax_url_default(self): if not self.enable_mathjax: return u'' static_url_prefix = self.tornado_settings.get("static_url_prefix", url_path_join(self.base_url, "static") ) return url_path_join(static_url_prefix, 'components', 'MathJax', 'MathJax.js') def _mathjax_url_changed(self, name, old, new): if new and not self.enable_mathjax: # enable_mathjax=False overrides mathjax_url self.mathjax_url = u'' else: self.log.info("Using MathJax: %s", new) contents_manager_class = Type( default_value=FileContentsManager, klass=ContentsManager, config=True, help='The notebook manager class to use.' ) kernel_manager_class = Type( default_value=MappingKernelManager, config=True, help='The kernel manager class to use.' ) session_manager_class = Type( default_value=SessionManager, config=True, help='The session manager class to use.' ) config_manager_class = Type( default_value=ConfigManager, config = True, help='The config manager class to use' ) kernel_spec_manager = Instance(KernelSpecManager, allow_none=True) kernel_spec_manager_class = Type( default_value=KernelSpecManager, config=True, help=""" The kernel spec manager class to use. Should be a subclass of `jupyter_client.kernelspec.KernelSpecManager`. The Api of KernelSpecManager is provisional and might change without warning between this version of Jupyter and the next stable one. """ ) login_handler_class = Type( default_value=LoginHandler, klass=web.RequestHandler, config=True, help='The login handler class to use.', ) logout_handler_class = Type( default_value=LogoutHandler, klass=web.RequestHandler, config=True, help='The logout handler class to use.', ) trust_xheaders = Bool(False, config=True, help=("Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-For headers" "sent by the upstream reverse proxy. Necessary if the proxy handles SSL") ) info_file = Unicode() def _info_file_default(self): info_file = "nbserver-%s.json" % os.getpid() return os.path.join(self.runtime_dir, info_file) pylab = Unicode('disabled', config=True, help=""" DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib. """ ) def _pylab_changed(self, name, old, new): """when --pylab is specified, display a warning and exit""" if new != 'warn': backend = ' %s' % new else: backend = '' self.log.error("Support for specifying --pylab on the command line has been removed.") self.log.error( "Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.".format(backend) ) self.exit(1) notebook_dir = Unicode(config=True, help="The directory to use for notebooks and kernels." ) def _notebook_dir_default(self): if self.file_to_run: return os.path.dirname(os.path.abspath(self.file_to_run)) else: return py3compat.getcwd() def _notebook_dir_changed(self, name, old, new): """Do a bit of validation of the notebook dir.""" if not os.path.isabs(new): # If we receive a non-absolute path, make it absolute. self.notebook_dir = os.path.abspath(new) return if not os.path.isdir(new): raise TraitError("No such notebook dir: %r" % new) # setting App.notebook_dir implies setting notebook and kernel dirs as well self.config.FileContentsManager.root_dir = new self.config.MappingKernelManager.root_dir = new server_extensions = List(Unicode(), config=True, help=("Python modules to load as notebook server extensions. " "This is an experimental API, and may change in future releases.") ) reraise_server_extension_failures = Bool( False, config=True, help="Reraise exceptions encountered loading server extensions?", ) def parse_command_line(self, argv=None): super(NotebookApp, self).parse_command_line(argv) if self.extra_args: arg0 = self.extra_args[0] f = os.path.abspath(arg0) self.argv.remove(arg0) if not os.path.exists(f): self.log.critical("No such file or directory: %s", f) self.exit(1) # Use config here, to ensure that it takes higher priority than # anything that comes from the profile. c = Config() if os.path.isdir(f): c.NotebookApp.notebook_dir = f elif os.path.isfile(f): c.NotebookApp.file_to_run = f self.update_config(c) def init_configurables(self): self.kernel_spec_manager = self.kernel_spec_manager_class( parent=self, ) self.kernel_manager = self.kernel_manager_class( parent=self, log=self.log, connection_dir=self.runtime_dir, kernel_spec_manager=self.kernel_spec_manager, ) self.contents_manager = self.contents_manager_class( parent=self, log=self.log, ) self.session_manager = self.session_manager_class( parent=self, log=self.log, kernel_manager=self.kernel_manager, contents_manager=self.contents_manager, ) self.config_manager = self.config_manager_class( parent=self, log=self.log, config_dir=os.path.join(self.config_dir, 'nbconfig'), ) def init_logging(self): # This prevents double log messages because tornado use a root logger that # self.log is a child of. The logging module dipatches log messages to a log # and all of its ancenstors until propagate is set to False. self.log.propagate = False for log in app_log, access_log, gen_log: # consistent log output name (NotebookApp instead of tornado.access, etc.) log.name = self.log.name # hook up tornado 3's loggers to our app handlers logger = logging.getLogger('tornado') logger.propagate = True logger.parent = self.log logger.setLevel(self.log.level) def init_webapp(self): """initialize tornado webapp and httpserver""" self.tornado_settings['allow_origin'] = self.allow_origin if self.allow_origin_pat: self.tornado_settings['allow_origin_pat'] = re.compile(self.allow_origin_pat) self.tornado_settings['allow_credentials'] = self.allow_credentials # ensure default_url starts with base_url if not self.default_url.startswith(self.base_url): self.default_url = url_path_join(self.base_url, self.default_url) self.web_app = NotebookWebApplication( self, self.kernel_manager, self.contents_manager, self.session_manager, self.kernel_spec_manager, self.config_manager, self.log, self.base_url, self.default_url, self.tornado_settings, self.jinja_environment_options ) ssl_options = self.ssl_options if self.certfile: ssl_options['certfile'] = self.certfile if self.keyfile: ssl_options['keyfile'] = self.keyfile if not ssl_options: # None indicates no SSL config ssl_options = None else: # Disable SSLv3, since its use is discouraged. ssl_options['ssl_version']=ssl.PROTOCOL_TLSv1 self.login_handler_class.validate_security(self, ssl_options=ssl_options) self.http_server = httpserver.HTTPServer(self.web_app, ssl_options=ssl_options, xheaders=self.trust_xheaders) success = None for port in random_ports(self.port, self.port_retries+1): try: self.http_server.listen(port, self.ip) except socket.error as e: if e.errno == errno.EADDRINUSE: self.log.info('The port %i is already in use, trying another random port.' % port) continue elif e.errno in (errno.EACCES, getattr(errno, 'WSAEACCES', errno.EACCES)): self.log.warn("Permission to listen on port %i denied" % port) continue else: raise else: self.port = port success = True break if not success: self.log.critical('ERROR: the notebook server could not be started because ' 'no available port could be found.') self.exit(1) @property def display_url(self): ip = self.ip if self.ip else '[all ip addresses on your system]' return self._url(ip) @property def connection_url(self): ip = self.ip if self.ip else 'localhost' return self._url(ip) def _url(self, ip): proto = 'https' if self.certfile else 'http' return "%s://%s:%i%s" % (proto, ip, self.port, self.base_url) def init_terminals(self): try: from .terminal import initialize initialize(self.web_app, self.notebook_dir, self.connection_url) self.web_app.settings['terminals_available'] = True except ImportError as e: log = self.log.debug if sys.platform == 'win32' else self.log.warn log("Terminals not available (error was %s)", e) def init_signal(self): if not sys.platform.startswith('win') and sys.stdin.isatty(): signal.signal(signal.SIGINT, self._handle_sigint) signal.signal(signal.SIGTERM, self._signal_stop) if hasattr(signal, 'SIGUSR1'): # Windows doesn't support SIGUSR1 signal.signal(signal.SIGUSR1, self._signal_info) if hasattr(signal, 'SIGINFO'): # only on BSD-based systems signal.signal(signal.SIGINFO, self._signal_info) def _handle_sigint(self, sig, frame): """SIGINT handler spawns confirmation dialog""" # register more forceful signal handler for ^C^C case signal.signal(signal.SIGINT, self._signal_stop) # request confirmation dialog in bg thread, to avoid # blocking the App thread = threading.Thread(target=self._confirm_exit) thread.daemon = True thread.start() def _restore_sigint_handler(self): """callback for restoring original SIGINT handler""" signal.signal(signal.SIGINT, self._handle_sigint) def _confirm_exit(self): """confirm shutdown on ^C A second ^C, or answering 'y' within 5s will cause shutdown, otherwise original SIGINT handler will be restored. This doesn't work on Windows. """ info = self.log.info info('interrupted') print(self.notebook_info()) sys.stdout.write("Shutdown this notebook server (y/[n])? ") sys.stdout.flush() r,w,x = select.select([sys.stdin], [], [], 5) if r: line = sys.stdin.readline() if line.lower().startswith('y') and 'n' not in line.lower(): self.log.critical("Shutdown confirmed") ioloop.IOLoop.current().stop() return else: print("No answer for 5s:", end=' ') print("resuming operation...") # no answer, or answer is no: # set it back to original SIGINT handler # use IOLoop.add_callback because signal.signal must be called # from main thread ioloop.IOLoop.current().add_callback(self._restore_sigint_handler) def _signal_stop(self, sig, frame): self.log.critical("received signal %s, stopping", sig) ioloop.IOLoop.current().stop() def _signal_info(self, sig, frame): print(self.notebook_info()) def init_components(self): """Check the components submodule, and warn if it's unclean""" # TODO: this should still check, but now we use bower, not git submodule pass def init_server_extensions(self): """Load any extensions specified by config. Import the module, then call the load_jupyter_server_extension function, if one exists. The extension API is experimental, and may change in future releases. """ for modulename in self.server_extensions: try: mod = importlib.import_module(modulename) func = getattr(mod, 'load_jupyter_server_extension', None) if func is not None: func(self) except Exception: if self.reraise_server_extension_failures: raise self.log.warn("Error loading server extension %s", modulename, exc_info=True) @catch_config_error def initialize(self, argv=None): super(NotebookApp, self).initialize(argv) self.init_logging() if self._dispatching: return self.init_configurables() self.init_components() self.init_webapp() self.init_terminals() self.init_signal() self.init_server_extensions() def cleanup_kernels(self): """Shutdown all kernels. The kernels will shutdown themselves when this process no longer exists, but explicit shutdown allows the KernelManagers to cleanup the connection files. """ self.log.info('Shutting down kernels') self.kernel_manager.shutdown_all() def notebook_info(self): "Return the current working directory and the server url information" info = self.contents_manager.info_string() + "\n" info += "%d active kernels \n" % len(self.kernel_manager._kernels) return info + "The Jupyter Notebook is running at: %s" % self.display_url def server_info(self): """Return a JSONable dict of information about this server.""" return {'url': self.connection_url, 'hostname': self.ip if self.ip else 'localhost', 'port': self.port, 'secure': bool(self.certfile), 'base_url': self.base_url, 'notebook_dir': os.path.abspath(self.notebook_dir), 'pid': os.getpid() } def write_server_info_file(self): """Write the result of server_info() to the JSON file info_file.""" with open(self.info_file, 'w') as f: json.dump(self.server_info(), f, indent=2) def remove_server_info_file(self): """Remove the nbserver-<pid>.json file created for this server. Ignores the error raised when the file has already been removed. """ try: os.unlink(self.info_file) except OSError as e: if e.errno != errno.ENOENT: raise def start(self): """ Start the Notebook server app, after initialization This method takes no arguments so all configuration and initialization must be done prior to calling this method.""" super(NotebookApp, self).start() info = self.log.info for line in self.notebook_info().split("\n"): info(line) info("Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).") self.write_server_info_file() if self.open_browser or self.file_to_run: try: browser = webbrowser.get(self.browser or None) except webbrowser.Error as e: self.log.warn('No web browser found: %s.' % e) browser = None if self.file_to_run: if not os.path.exists(self.file_to_run): self.log.critical("%s does not exist" % self.file_to_run) self.exit(1) relpath = os.path.relpath(self.file_to_run, self.notebook_dir) uri = url_path_join('notebooks', *relpath.split(os.sep)) else: uri = 'tree' if browser: b = lambda : browser.open(url_path_join(self.connection_url, uri), new=2) threading.Thread(target=b).start() self.io_loop = ioloop.IOLoop.current() if sys.platform.startswith('win'): # add no-op to wake every 5s # to handle signals that may be ignored by the inner loop pc = ioloop.PeriodicCallback(lambda : None, 5000) pc.start() try: self.io_loop.start() except KeyboardInterrupt: info("Interrupted...") finally: self.cleanup_kernels() self.remove_server_info_file() def stop(self): def _stop(): self.http_server.stop() self.io_loop.stop() self.io_loop.add_callback(_stop) def list_running_servers(runtime_dir=None): """Iterate over the server info files of running notebook servers. Given a profile name, find nbserver-* files in the security directory of that profile, and yield dicts of their information, each one pertaining to a currently running notebook server instance. """ if runtime_dir is None: runtime_dir = jupyter_runtime_dir() # The runtime dir might not exist if not os.path.isdir(runtime_dir): return for file in os.listdir(runtime_dir): if file.startswith('nbserver-'): with io.open(os.path.join(runtime_dir, file), encoding='utf-8') as f: info = json.load(f) # Simple check whether that process is really still running # Also remove leftover files from IPython 2.x without a pid field if ('pid' in info) and check_pid(info['pid']): yield info else: # If the process has died, try to delete its info file try: os.unlink(file) except OSError: pass # TODO: This should warn or log or something #----------------------------------------------------------------------------- # Main entry point #----------------------------------------------------------------------------- main = launch_new_instance = NotebookApp.launch_instance
xss
{ "code": [ " jenv_opt = jinja_env_options if jinja_env_options else {}" ], "line_no": [ 162 ] }
{ "code": [ " jenv_opt = {\"autoescape\": True}", " jenv_opt.update(jinja_env_options if jinja_env_options else {})" ], "line_no": [ 162, 163 ] }
from __future__ import absolute_import, print_function import .base64 import datetime import errno import importlib import io import .json import .logging import os import .random import .re import .select import .signal import .socket import .ssl import .sys import .threading import .webbrowser from jinja2 import Environment, FileSystemLoader from zmq.eventloop import ioloop ioloop.install() VAR_0 = "The Jupyter Notebook requires tornado >= 4.0" try: import tornado except ImportError: raise ImportError(VAR_0) try: VAR_10 = tornado.version_info except AttributeError: raise ImportError(VAR_0 + ", but you have < 1.1.0") if VAR_10 < (4,0): raise ImportError(VAR_0 + ", but you have %s" % tornado.version) from tornado import httpserver from tornado import .web from tornado.log import LogFormatter, app_log, access_log, gen_log from notebook import ( DEFAULT_STATIC_FILES_PATH, DEFAULT_TEMPLATE_PATH_LIST, __version__, ) from .base.handlers import Template404 from .log import .log_request from .services.kernels.kernelmanager import MappingKernelManager from .services.config import ConfigManager from .services.contents.manager import ContentsManager from .services.contents.filemanager import FileContentsManager from .services.sessions.sessionmanager import SessionManager from .auth.login import LoginHandler from .auth.logout import LogoutHandler from .base.handlers import FileFindHandler, IPythonHandler from traitlets.config import Config from traitlets.config.application import .catch_config_error, boolean_flag from jupyter_core.application import ( JupyterApp, base_flags, base_aliases, ) from jupyter_client import KernelManager from jupyter_client.kernelspec import KernelSpecManager, NoSuchKernel, NATIVE_KERNEL_NAME from jupyter_client.session import Session from nbformat.sign import NotebookNotary from traitlets import ( Dict, Unicode, Integer, List, Bool, Bytes, Instance, TraitError, Type, ) from ipython_genutils import py3compat from IPython.paths import .get_ipython_dir from jupyter_core.paths import jupyter_runtime_dir, jupyter_path from notebook._sysinfo import .get_sys_info from .utils import .url_path_join, check_pid VAR_1 = """ jupyter notebook # FUNC_6 the notebook jupyter notebook --VAR_42=mycert.pem # use SSL/TLS certificate """ def FUNC_0(VAR_2, VAR_3): for i in range(min(5, VAR_3)): yield VAR_2 + i for i in range(VAR_3-5): yield max(1, VAR_2 + random.randint(-2*VAR_3, 2*VAR_3)) def FUNC_1(VAR_4): VAR_4 = 'notebook.' + VAR_4 VAR_11 = __import__(VAR_4, fromlist=['default_handlers']) return VAR_11.default_handlers class CLASS_0(IPythonHandler): def FUNC_3(self, VAR_12): self.set_header("Content-Type", 'text/javascript') self.finish(""" console.warn('`/static/widgets/js` is deprecated. Use `/nbextensions/widgets/widgets/js` instead.'); define(['%s'], function(VAR_96) { return VAR_96; }); """ % url_path_join('nbextensions', 'widgets', 'widgets', VAR_12.rstrip('.js'))) self.log.warn('Deprecated widget Javascript VAR_87 /static/widgets/js/*.js was used') class CLASS_1(web.Application): def __init__(self, VAR_13, VAR_14, VAR_15, VAR_16, VAR_17, VAR_18, VAR_19, VAR_20, VAR_21, VAR_22, VAR_23): VAR_24 = self.init_settings( VAR_13, VAR_14, VAR_15, VAR_16, VAR_17, VAR_18, VAR_19, VAR_20, VAR_21, VAR_22, VAR_23) VAR_79 = self.init_handlers(VAR_24) super(CLASS_1, self).__init__(VAR_79, **VAR_24) def FUNC_4(self, VAR_13, VAR_14, VAR_15, VAR_16, VAR_17, VAR_18, VAR_19, VAR_20, VAR_21, VAR_22, VAR_23=None): VAR_80 = VAR_22.get( "template_path", VAR_13.template_file_path, ) if isinstance(VAR_80, py3compat.string_types): VAR_80 = (_template_path,) VAR_81 = [os.path.expanduser(VAR_87) for VAR_87 in VAR_80] VAR_82 = VAR_23 if VAR_23 else {} VAR_83 = Environment(loader=FileSystemLoader(VAR_81), **VAR_82) VAR_84 = get_sys_info() if VAR_84['commit_source'] == 'repository': VAR_97 = '' else: VAR_97 = datetime.datetime.now().strftime("%Y%m%d%H%M%S") VAR_24 = dict( log_function=log_request, VAR_20=base_url, VAR_21=default_url, VAR_81=template_path, static_path=VAR_13.static_file_path, VAR_58=VAR_13.static_custom_path, static_handler_class = FileFindHandler, VAR_88 = url_path_join(VAR_20,'/static/'), static_handler_args = { 'no_cache_paths': [url_path_join(VAR_20, 'static', 'custom')], }, VAR_97=version_hash, VAR_33=VAR_13.ignore_minified_js, VAR_45=VAR_13.cookie_secret, login_url=url_path_join(VAR_20,'/login'), VAR_68=VAR_13.login_handler_class, VAR_69=VAR_13.logout_handler_class, VAR_47=VAR_13.password, VAR_14=kernel_manager, VAR_15=contents_manager, VAR_16=session_manager, VAR_17=kernel_spec_manager, VAR_18=config_manager, VAR_54=VAR_13.jinja_template_vars, FUNC_22=VAR_13.nbextensions_path, VAR_61=VAR_13.websocket_url, VAR_62=VAR_13.mathjax_url, config=VAR_13.config, config_dir=VAR_13.config_dir, jinja2_env=VAR_83, terminals_available=False, # Set later if terminals are available ) VAR_24.update(VAR_22) return VAR_24 def FUNC_5(self, VAR_24): VAR_79 = [] VAR_79.append((r'/deprecatedwidgets/(.*)', CLASS_0)) VAR_79.extend(FUNC_1('tree.handlers')) VAR_79.extend([(r"/login", VAR_24['login_handler_class'])]) VAR_79.extend([(r"/logout", VAR_24['logout_handler_class'])]) VAR_79.extend(FUNC_1('files.handlers')) VAR_79.extend(FUNC_1('notebook.handlers')) VAR_79.extend(FUNC_1('nbconvert.handlers')) VAR_79.extend(FUNC_1('kernelspecs.handlers')) VAR_79.extend(FUNC_1('edit.handlers')) VAR_79.extend(FUNC_1('services.api.handlers')) VAR_79.extend(FUNC_1('services.config.handlers')) VAR_79.extend(FUNC_1('services.kernels.handlers')) VAR_79.extend(FUNC_1('services.contents.handlers')) VAR_79.extend(FUNC_1('services.sessions.handlers')) VAR_79.extend(FUNC_1('services.nbconvert.handlers')) VAR_79.extend(FUNC_1('services.kernelspecs.handlers')) VAR_79.extend(FUNC_1('services.security.handlers')) try: import .ipywidgets VAR_79.append( (r"/nbextensions/widgets/(.*)", FileFindHandler, { 'path': ipywidgets.find_static_assets(), 'no_cache_paths': ['/'], # don't cache anything in nbextensions }), ) except: app_log.warn('ipywidgets package not installed. Widgets are unavailable.') VAR_79.append( (r"/nbextensions/(.*)", FileFindHandler, { 'path': VAR_24['nbextensions_path'], 'no_cache_paths': ['/'], # don't cache anything in nbextensions }), ) VAR_79.append( (r"/custom/(.*)", FileFindHandler, { 'path': VAR_24['static_custom_path'], 'no_cache_paths': ['/'], # don't cache anything in custom }) ) VAR_79.extend(FUNC_1('base.handlers')) VAR_79.append( (r'/?', web.RedirectHandler, { 'url' : VAR_24['default_url'], 'permanent': False, # want 302, not 301 }) ) VAR_85 = [] for handler in VAR_79: VAR_98 = url_path_join(VAR_24['base_url'], handler[0]) VAR_99 = tuple([VAR_98] + list(handler[1:])) VAR_85.append(VAR_99) VAR_85.append((r'(.*)', Template404)) return VAR_85 class CLASS_2(JupyterApp): VAR_25 = __version__ VAR_26="List currently running notebook servers in this profile." VAR_5 = dict( VAR_27=({'NbserverListApp': {'json': True}}, "Produce machine-readable JSON output."), ) VAR_27 = Bool(False, config=True, help="If True, each VAR_104 of output will be a JSON object with the " "details from the server VAR_93 file.") def FUNC_6(self): if not self.json: print("Currently running servers:") for serverinfo in FUNC_2(self.runtime_dir): if self.json: print(VAR_27.dumps(serverinfo)) else: print(serverinfo['url'], "::", serverinfo['notebook_dir']) VAR_5 = dict(base_flags) VAR_5['no-browser']=( {'NotebookApp' : {'open_browser' : False}}, "Don't open the notebook in a VAR_49 after startup." ) VAR_5['pylab']=( {'NotebookApp' : {'pylab' : 'warn'}}, "DISABLED: use %VAR_72 or %matplotlib in the notebook to enable matplotlib." ) VAR_5['no-mathjax']=( {'NotebookApp' : {'enable_mathjax' : False}}, """Disable MathJax MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) flags.update(boolean_flag('script', 'FileContentsManager.save_script', 'DEPRECATED, IGNORED', 'DEPRECATED, IGNORED')) VAR_6 = dict(base_aliases) VAR_6.update({ 'ip': 'NotebookApp.ip', 'port': 'NotebookApp.port', 'port-retries': 'NotebookApp.port_retries', 'transport': 'KernelManager.transport', 'keyfile': 'NotebookApp.keyfile', 'certfile': 'NotebookApp.certfile', 'notebook-dir': 'NotebookApp.notebook_dir', 'browser': 'NotebookApp.browser', 'pylab': 'NotebookApp.pylab', }) class CLASS_3(JupyterApp): VAR_4 = 'jupyter-notebook' VAR_25 = __version__ VAR_26 = """ The Jupyter HTML Notebook. This launches a Tornado based HTML Notebook Server that serves up an HTML5/Javascript Notebook client. """ VAR_28 = VAR_1 VAR_6 = aliases VAR_5 = VAR_5 VAR_29 = [ KernelManager, Session, MappingKernelManager, ContentsManager, FileContentsManager, NotebookNotary, KernelSpecManager, ] VAR_5 = Dict(VAR_5) VAR_6 = Dict(VAR_6) VAR_30 = dict( list=(CLASS_2, NbserverListApp.description.splitlines()[0]), ) VAR_31 = LogFormatter def FUNC_7(self): return logging.INFO def FUNC_8(self): return "%H:%M:%S" def FUNC_9(self): return u"%(color)VAR_86[%(levelname)1.1s %(asctime)VAR_86.%(msecs).03d %(VAR_4)VAR_86]%(end_color)VAR_86 %(message)s" VAR_32 = Bool(True) VAR_33 = Bool(False, config=True, help='Use minified JS file or not, mainly use during dev to avoid JS recompilation', ) VAR_34 = Unicode('', config=True) VAR_35 = Unicode('', config=True, help="""Set the Access-Control-Allow-Origin header Use '*' to allow any origin to access your server. Takes precedence over VAR_36. """ ) VAR_36 = Unicode('', config=True, help="""Use a regular expression for the Access-Control-Allow-Origin header Requests from an origin matching the expression will FUNC_3 replies with: Access-Control-Allow-Origin: origin where `origin` is the origin of the request. Ignored if VAR_35 is set. """ ) VAR_37 = Bool(False, config=True, help="Set the Access-Control-Allow-Credentials: true header" ) VAR_21 = Unicode('/tree', config=True, help="The default URL to redirect to from `/`" ) VAR_38 = Unicode('localhost', config=True, help="The IP address the notebook server will listen on." ) def FUNC_10(self): VAR_86 = socket.socket() try: VAR_86.bind(('localhost', 0)) except socket.error as e: self.log.warn("Cannot bind to localhost, using 127.0.0.1 as default VAR_38\VAR_3%s", e) return '127.0.0.1' else: VAR_86.close() return 'localhost' def FUNC_11(self, VAR_4, VAR_39, VAR_40): if VAR_40 == u'*': self.ip = u'' VAR_2 = Integer(8888, config=True, help="The VAR_2 the notebook server will listen on." ) VAR_41 = Integer(50, config=True, help="The number of additional ports to try if the specified VAR_2 is not available." ) VAR_42 = Unicode(u'', config=True, help="""The full VAR_87 to an SSL/TLS certificate file.""" ) VAR_43 = Unicode(u'', config=True, help="""The full VAR_87 to a private key file for usage with SSL/TLS.""" ) VAR_44 = Unicode(config=True, help="""The file where the cookie VAR_46 is stored.""" ) def FUNC_12(self): return os.path.join(self.runtime_dir, 'notebook_cookie_secret') VAR_45 = Bytes(b'', config=True, help="""The random bytes used to secure cookies. By default this is a VAR_40 random number every time you FUNC_6 the Notebook. Set it to a value in a config file to enable logins to persist across server sessions. Note: Cookie secrets should be kept private, do not share config files with VAR_45 stored in plaintext (you can read the value from a file). """ ) def FUNC_13(self): if os.path.exists(self.cookie_secret_file): with io.open(self.cookie_secret_file, 'rb') as VAR_102: return VAR_102.read() else: VAR_46 = base64.encodestring(os.urandom(1024)) self._write_cookie_secret_file(VAR_46) return VAR_46 def FUNC_14(self, VAR_46): self.log.info("Writing notebook server cookie VAR_46 to %s", self.cookie_secret_file) with io.open(self.cookie_secret_file, 'wb') as VAR_102: VAR_102.write(VAR_46) try: os.chmod(self.cookie_secret_file, 0o600) except OSError: self.log.warn( "Could not set permissions on %s", self.cookie_secret_file ) VAR_47 = Unicode(u'', config=True, help="""Hashed VAR_47 to use for web authentication. To generate, type in a python/IPython shell: from notebook.auth import passwd; passwd() The string should be of the form type:salt:hashed-VAR_47. """ ) VAR_48 = Bool(True, config=True, help="""Whether to open in a VAR_49 after starting. The specific VAR_49 used is platform dependent and determined by the python standard library `webbrowser` module, unless it is overridden using the --VAR_49 (CLASS_3.browser) configuration option. """) VAR_49 = Unicode(u'', config=True, help="""Specify what command to use to invoke a web VAR_49 when opening the notebook. If not specified, the default VAR_49 will be determined by the `webbrowser` standard library module, which allows setting of the BROWSER environment variable to override it. """) VAR_50 = Dict(config=True, help="DEPRECATED, use tornado_settings" ) def FUNC_15(self, VAR_4, VAR_39, VAR_40): self.log.warn("\VAR_3 VAR_50 is deprecated, use VAR_51.\n") self.tornado_settings = VAR_40 VAR_51 = Dict(config=True, help="Supply overrides for the tornado.web.Application that the " "Jupyter notebook uses.") VAR_52 = Dict(config=True, help="""Supply SSL options for the tornado HTTPServer. See the tornado docs for details.""") VAR_53 = Dict(config=True, help="Supply extra arguments that will be passed to Jinja environment.") VAR_54 = Dict( config=True, help="Extra variables to supply to jinja templates when rendering.", ) VAR_55 = Bool(True, config=True, help="""Whether to enable MathJax for typesetting math/TeX MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) def FUNC_16(self, VAR_4, VAR_39, VAR_40): if not VAR_40: self.mathjax_url = u'' VAR_20 = Unicode('/', config=True, help='''The base URL for the notebook server. Leading and trailing slashes can be omitted, and will automatically be added. ''') def FUNC_17(self, VAR_4, VAR_39, VAR_40): if not VAR_40.startswith('/'): self.base_url = '/'+VAR_40 elif not VAR_40.endswith('/'): self.base_url = VAR_40+'/' VAR_56 = Unicode('/', config=True, help="""DEPRECATED use base_url""") def FUNC_18(self, VAR_4, VAR_39, VAR_40): self.log.warn("base_project_url is deprecated, use base_url") self.base_url = VAR_40 VAR_57 = List(Unicode(), config=True, help="""Extra paths to search for serving static files. This allows adding javascript/css to be available from the notebook server machine, or overriding individual files in the IPython""" ) @property def FUNC_19(self): return self.extra_static_paths + [DEFAULT_STATIC_FILES_PATH] VAR_58 = List(Unicode(), help="""Path to search for custom.js, css""" ) def FUNC_20(self): return [ os.path.join(d, 'custom') for d in ( self.config_dir, os.path.join(get_ipython_dir(), 'profile_default', 'static'), DEFAULT_STATIC_FILES_PATH) ] VAR_59 = List(Unicode(), config=True, help="""Extra paths to search for serving jinja templates. Can be used to override templates from notebook.templates.""" ) @property def FUNC_21(self): return self.extra_template_paths + DEFAULT_TEMPLATE_PATH_LIST VAR_60 = List(Unicode(), config=True, help="""extra paths to look for Javascript notebook extensions""" ) @property def FUNC_22(self): VAR_87 = self.extra_nbextensions_path + jupyter_path('nbextensions') VAR_87.append(os.path.join(get_ipython_dir(), 'nbextensions')) return VAR_87 VAR_61 = Unicode("", config=True, help="""The base URL for websockets, if it differs from the HTTP server (hint: it almost certainly doesn't). Should be in the form of an HTTP origin: ws[VAR_86]://hostname[:VAR_2] """ ) VAR_62 = Unicode("", config=True, help="""The url for MathJax.js.""" ) def FUNC_23(self): if not self.enable_mathjax: return u'' VAR_88 = self.tornado_settings.get("static_url_prefix", url_path_join(self.base_url, "static") ) return url_path_join(VAR_88, 'components', 'MathJax', 'MathJax.js') def FUNC_24(self, VAR_4, VAR_39, VAR_40): if VAR_40 and not self.enable_mathjax: self.mathjax_url = u'' else: self.log.info("Using MathJax: %s", VAR_40) VAR_63 = Type( default_value=FileContentsManager, klass=ContentsManager, config=True, help='The notebook manager class to use.' ) VAR_64 = Type( default_value=MappingKernelManager, config=True, help='The kernel manager class to use.' ) VAR_65 = Type( default_value=SessionManager, config=True, help='The session manager class to use.' ) VAR_66 = Type( default_value=ConfigManager, config = True, help='The config manager class to use' ) VAR_17 = Instance(KernelSpecManager, allow_none=True) VAR_67 = Type( default_value=KernelSpecManager, config=True, help=""" The kernel spec manager class to use. Should be a subclass of `jupyter_client.kernelspec.KernelSpecManager`. The Api of KernelSpecManager is provisional and might change without warning between this VAR_25 of Jupyter and the next stable one. """ ) VAR_68 = Type( default_value=LoginHandler, klass=web.RequestHandler, config=True, help='The login handler class to use.', ) VAR_69 = Type( default_value=LogoutHandler, klass=web.RequestHandler, config=True, help='The logout handler class to use.', ) VAR_70 = Bool(False, config=True, help=("Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-For headers" "sent by the upstream reverse proxy. Necessary if the proxy handles SSL") ) VAR_71 = Unicode() def FUNC_25(self): VAR_71 = "nbserver-%VAR_86.json" % os.getpid() return os.path.join(self.runtime_dir, VAR_71) VAR_72 = Unicode('disabled', config=True, help=""" DISABLED: use %VAR_72 or %matplotlib in the notebook to enable matplotlib. """ ) def FUNC_26(self, VAR_4, VAR_39, VAR_40): if VAR_40 != 'warn': VAR_100 = ' %s' % VAR_40 else: VAR_100 = '' self.log.error("Support for specifying --VAR_72 on the command VAR_104 has been removed.") self.log.error( "Please use `%VAR_72{0}` or `%matplotlib{0}` in the notebook itself.".format(VAR_100) ) self.exit(1) VAR_73 = Unicode(config=True, help="The directory to use for notebooks and kernels." ) def FUNC_27(self): if self.file_to_run: return os.path.dirname(os.path.abspath(self.file_to_run)) else: return py3compat.getcwd() def FUNC_28(self, VAR_4, VAR_39, VAR_40): if not os.path.isabs(VAR_40): self.notebook_dir = os.path.abspath(VAR_40) return if not os.path.isdir(VAR_40): raise TraitError("No such notebook dir: %r" % VAR_40) self.config.FileContentsManager.root_dir = VAR_40 self.config.MappingKernelManager.root_dir = VAR_40 VAR_74 = List(Unicode(), config=True, help=("Python modules to load as notebook server extensions. " "This is an experimental API, and may change in future releases.") ) VAR_75 = Bool( False, config=True, help="Reraise exceptions encountered loading server extensions?", ) def FUNC_29(self, VAR_76=None): super(CLASS_3, self).parse_command_line(VAR_76) if self.extra_args: VAR_101 = self.extra_args[0] VAR_102 = os.path.abspath(VAR_101) self.argv.remove(VAR_101) if not os.path.exists(VAR_102): self.log.critical("No such file or directory: %s", VAR_102) self.exit(1) VAR_103 = Config() if os.path.isdir(VAR_102): VAR_103.NotebookApp.notebook_dir = VAR_102 elif os.path.isfile(VAR_102): VAR_103.NotebookApp.file_to_run = VAR_102 self.update_config(VAR_103) def FUNC_30(self): self.kernel_spec_manager = self.kernel_spec_manager_class( parent=self, ) self.kernel_manager = self.kernel_manager_class( parent=self, VAR_19=self.log, connection_dir=self.runtime_dir, VAR_17=self.kernel_spec_manager, ) self.contents_manager = self.contents_manager_class( parent=self, VAR_19=self.log, ) self.session_manager = self.session_manager_class( parent=self, VAR_19=self.log, VAR_14=self.kernel_manager, VAR_15=self.contents_manager, ) self.config_manager = self.config_manager_class( parent=self, VAR_19=self.log, config_dir=os.path.join(self.config_dir, 'nbconfig'), ) def FUNC_31(self): self.log.propagate = False for VAR_19 in app_log, access_log, gen_log: VAR_19.name = self.log.name VAR_89 = logging.getLogger('tornado') VAR_89.propagate = True VAR_89.parent = self.log VAR_89.setLevel(self.log.level) def FUNC_32(self): self.tornado_settings['allow_origin'] = self.allow_origin if self.allow_origin_pat: self.tornado_settings['allow_origin_pat'] = re.compile(self.allow_origin_pat) self.tornado_settings['allow_credentials'] = self.allow_credentials if not self.default_url.startswith(self.base_url): self.default_url = url_path_join(self.base_url, self.default_url) self.web_app = CLASS_1( self, self.kernel_manager, self.contents_manager, self.session_manager, self.kernel_spec_manager, self.config_manager, self.log, self.base_url, self.default_url, self.tornado_settings, self.jinja_environment_options ) VAR_52 = self.ssl_options if self.certfile: VAR_52['certfile'] = self.certfile if self.keyfile: VAR_52['keyfile'] = self.keyfile if not VAR_52: VAR_52 = None else: VAR_52['ssl_version']=ssl.PROTOCOL_TLSv1 self.login_handler_class.validate_security(self, VAR_52=ssl_options) self.http_server = httpserver.HTTPServer(self.web_app, VAR_52=ssl_options, xheaders=self.trust_xheaders) VAR_90 = None for VAR_2 in FUNC_0(self.port, self.port_retries+1): try: self.http_server.listen(VAR_2, self.ip) except socket.error as e: if e.errno == errno.EADDRINUSE: self.log.info('The VAR_2 %i is already in use, trying another random VAR_2.' % VAR_2) continue elif e.errno in (errno.EACCES, getattr(errno, 'WSAEACCES', errno.EACCES)): self.log.warn("Permission to listen on VAR_2 %i denied" % VAR_2) continue else: raise else: self.port = VAR_2 VAR_90 = True break if not VAR_90: self.log.critical('ERROR: the notebook server could not be started because ' 'no available VAR_2 could be found.') self.exit(1) @property def FUNC_33(self): VAR_38 = self.ip if self.ip else '[all VAR_38 addresses on your system]' return self._url(VAR_38) @property def FUNC_34(self): VAR_38 = self.ip if self.ip else 'localhost' return self._url(VAR_38) def FUNC_35(self, VAR_38): VAR_91 = 'https' if self.certfile else 'http' return "%VAR_86://%s:%i%s" % (VAR_91, VAR_38, self.port, self.base_url) def FUNC_36(self): try: from .terminal import .initialize FUNC_45(self.web_app, self.notebook_dir, self.connection_url) self.web_app.settings['terminals_available'] = True except ImportError as e: VAR_19 = self.log.debug if sys.platform == 'win32' else self.log.warn VAR_19("Terminals not available (error was %VAR_86)", e) def FUNC_37(self): if not sys.platform.startswith('win') and sys.stdin.isatty(): signal.signal(signal.SIGINT, self._handle_sigint) signal.signal(signal.SIGTERM, self._signal_stop) if hasattr(signal, 'SIGUSR1'): signal.signal(signal.SIGUSR1, self._signal_info) if hasattr(signal, 'SIGINFO'): signal.signal(signal.SIGINFO, self._signal_info) def FUNC_38(self, VAR_77, VAR_78): signal.signal(signal.SIGINT, self._signal_stop) VAR_92 = threading.Thread(target=self._confirm_exit) VAR_92.daemon = True VAR_92.start() def FUNC_39(self): signal.signal(signal.SIGINT, self._handle_sigint) def FUNC_40(self): VAR_93 = self.log.info VAR_93('interrupted') print(self.notebook_info()) sys.stdout.write("Shutdown this notebook server (y/[VAR_3])? ") sys.stdout.flush() VAR_94,VAR_95,VAR_96 = select.select([sys.stdin], [], [], 5) if VAR_94: VAR_104 = sys.stdin.readline() if VAR_104.lower().startswith('y') and 'n' not in VAR_104.lower(): self.log.critical("Shutdown confirmed") ioloop.IOLoop.current().stop() return else: print("No answer for 5s:", end=' ') print("resuming operation...") ioloop.IOLoop.current().add_callback(self._restore_sigint_handler) def FUNC_41(self, VAR_77, VAR_78): self.log.critical("received signal %VAR_86, stopping", VAR_77) ioloop.IOLoop.current().stop() def FUNC_42(self, VAR_77, VAR_78): print(self.notebook_info()) def FUNC_43(self): pass def FUNC_44(self): for modulename in self.server_extensions: try: VAR_11 = importlib.import_module(modulename) VAR_106 = getattr(VAR_11, 'load_jupyter_server_extension', None) if VAR_106 is not None: VAR_106(self) except Exception: if self.reraise_server_extension_failures: raise self.log.warn("Error loading server extension %s", modulename, exc_info=True) @catch_config_error def FUNC_45(self, VAR_76=None): super(CLASS_3, self).initialize(VAR_76) self.init_logging() if self._dispatching: return self.init_configurables() self.init_components() self.init_webapp() self.init_terminals() self.init_signal() self.init_server_extensions() def FUNC_46(self): self.log.info('Shutting down kernels') self.kernel_manager.shutdown_all() VAR_93 = self.contents_manager.info_string() + "\n" VAR_93 += "%d active kernels \n" % len(self.kernel_manager._kernels) return VAR_93 + "The Jupyter Notebook is running at: %s" % self.display_url def FUNC_48(self): return {'url': self.connection_url, 'hostname': self.ip if self.ip else 'localhost', 'port': self.port, 'secure': bool(self.certfile), 'base_url': self.base_url, 'notebook_dir': os.path.abspath(self.notebook_dir), 'pid': os.getpid() } def FUNC_49(self): with open(self.info_file, 'w') as VAR_102: VAR_27.dump(self.server_info(), VAR_102, indent=2) def FUNC_50(self): try: os.unlink(self.info_file) except OSError as e: if e.errno != errno.ENOENT: raise def FUNC_6(self): super(CLASS_3, self).start() VAR_93 = self.log.info for VAR_104 in self.notebook_info().split("\n"): VAR_93(VAR_104) VAR_93("Use Control-C to FUNC_51 this server and shut down all kernels (twice to skip confirmation).") self.write_server_info_file() if self.open_browser or self.file_to_run: try: VAR_49 = webbrowser.get(self.browser or None) except webbrowser.Error as e: self.log.warn('No web VAR_49 found: %VAR_86.' % e) VAR_49 = None if self.file_to_run: if not os.path.exists(self.file_to_run): self.log.critical("%VAR_86 does not exist" % self.file_to_run) self.exit(1) VAR_107 = os.path.relpath(self.file_to_run, self.notebook_dir) VAR_108 = url_path_join('notebooks', *VAR_107.split(os.sep)) else: VAR_108 = 'tree' if VAR_49: VAR_109 = lambda : VAR_49.open(url_path_join(self.connection_url, VAR_108), VAR_40=2) threading.Thread(target=VAR_109).start() self.io_loop = ioloop.IOLoop.current() if sys.platform.startswith('win'): VAR_105 = ioloop.PeriodicCallback(lambda : None, 5000) VAR_105.start() try: self.io_loop.start() except KeyboardInterrupt: VAR_93("Interrupted...") finally: self.cleanup_kernels() self.remove_server_info_file() def FUNC_51(self): def FUNC_52(): self.http_server.stop() self.io_loop.stop() self.io_loop.add_callback(FUNC_52) def FUNC_2(VAR_7=None): if VAR_7 is None: VAR_7 = jupyter_runtime_dir() if not os.path.isdir(VAR_7): return for file in os.listdir(VAR_7): if file.startswith('nbserver-'): with io.open(os.path.join(VAR_7, file), encoding='utf-8') as VAR_102: VAR_93 = VAR_27.load(VAR_102) if ('pid' in VAR_93) and check_pid(VAR_93['pid']): yield VAR_93 else: try: os.unlink(file) except OSError: pass # TODO: This should warn or VAR_19 or something VAR_8 = VAR_9 = CLASS_3.launch_instance
from __future__ import absolute_import, print_function import .base64 import datetime import errno import importlib import io import .json import .logging import os import .random import .re import .select import .signal import .socket import .ssl import .sys import .threading import .webbrowser from jinja2 import Environment, FileSystemLoader from zmq.eventloop import ioloop ioloop.install() VAR_0 = "The Jupyter Notebook requires tornado >= 4.0" try: import tornado except ImportError: raise ImportError(VAR_0) try: VAR_10 = tornado.version_info except AttributeError: raise ImportError(VAR_0 + ", but you have < 1.1.0") if VAR_10 < (4,0): raise ImportError(VAR_0 + ", but you have %s" % tornado.version) from tornado import httpserver from tornado import .web from tornado.log import LogFormatter, app_log, access_log, gen_log from notebook import ( DEFAULT_STATIC_FILES_PATH, DEFAULT_TEMPLATE_PATH_LIST, __version__, ) from .base.handlers import Template404 from .log import .log_request from .services.kernels.kernelmanager import MappingKernelManager from .services.config import ConfigManager from .services.contents.manager import ContentsManager from .services.contents.filemanager import FileContentsManager from .services.sessions.sessionmanager import SessionManager from .auth.login import LoginHandler from .auth.logout import LogoutHandler from .base.handlers import FileFindHandler, IPythonHandler from traitlets.config import Config from traitlets.config.application import .catch_config_error, boolean_flag from jupyter_core.application import ( JupyterApp, base_flags, base_aliases, ) from jupyter_client import KernelManager from jupyter_client.kernelspec import KernelSpecManager, NoSuchKernel, NATIVE_KERNEL_NAME from jupyter_client.session import Session from nbformat.sign import NotebookNotary from traitlets import ( Dict, Unicode, Integer, List, Bool, Bytes, Instance, TraitError, Type, ) from ipython_genutils import py3compat from IPython.paths import .get_ipython_dir from jupyter_core.paths import jupyter_runtime_dir, jupyter_path from notebook._sysinfo import .get_sys_info from .utils import .url_path_join, check_pid VAR_1 = """ jupyter notebook # FUNC_6 the notebook jupyter notebook --VAR_42=mycert.pem # use SSL/TLS certificate """ def FUNC_0(VAR_2, VAR_3): for i in range(min(5, VAR_3)): yield VAR_2 + i for i in range(VAR_3-5): yield max(1, VAR_2 + random.randint(-2*VAR_3, 2*VAR_3)) def FUNC_1(VAR_4): VAR_4 = 'notebook.' + VAR_4 VAR_11 = __import__(VAR_4, fromlist=['default_handlers']) return VAR_11.default_handlers class CLASS_0(IPythonHandler): def FUNC_3(self, VAR_12): self.set_header("Content-Type", 'text/javascript') self.finish(""" console.warn('`/static/widgets/js` is deprecated. Use `/nbextensions/widgets/widgets/js` instead.'); define(['%s'], function(VAR_96) { return VAR_96; }); """ % url_path_join('nbextensions', 'widgets', 'widgets', VAR_12.rstrip('.js'))) self.log.warn('Deprecated widget Javascript VAR_87 /static/widgets/js/*.js was used') class CLASS_1(web.Application): def __init__(self, VAR_13, VAR_14, VAR_15, VAR_16, VAR_17, VAR_18, VAR_19, VAR_20, VAR_21, VAR_22, VAR_23): VAR_24 = self.init_settings( VAR_13, VAR_14, VAR_15, VAR_16, VAR_17, VAR_18, VAR_19, VAR_20, VAR_21, VAR_22, VAR_23) VAR_79 = self.init_handlers(VAR_24) super(CLASS_1, self).__init__(VAR_79, **VAR_24) def FUNC_4(self, VAR_13, VAR_14, VAR_15, VAR_16, VAR_17, VAR_18, VAR_19, VAR_20, VAR_21, VAR_22, VAR_23=None): VAR_80 = VAR_22.get( "template_path", VAR_13.template_file_path, ) if isinstance(VAR_80, py3compat.string_types): VAR_80 = (_template_path,) VAR_81 = [os.path.expanduser(VAR_87) for VAR_87 in VAR_80] VAR_82 = {"autoescape": True} VAR_82.update(VAR_23 if VAR_23 else {}) VAR_83 = Environment(loader=FileSystemLoader(VAR_81), **VAR_82) VAR_84 = get_sys_info() if VAR_84['commit_source'] == 'repository': VAR_97 = '' else: VAR_97 = datetime.datetime.now().strftime("%Y%m%d%H%M%S") VAR_24 = dict( log_function=log_request, VAR_20=base_url, VAR_21=default_url, VAR_81=template_path, static_path=VAR_13.static_file_path, VAR_58=VAR_13.static_custom_path, static_handler_class = FileFindHandler, VAR_88 = url_path_join(VAR_20,'/static/'), static_handler_args = { 'no_cache_paths': [url_path_join(VAR_20, 'static', 'custom')], }, VAR_97=version_hash, VAR_33=VAR_13.ignore_minified_js, VAR_45=VAR_13.cookie_secret, login_url=url_path_join(VAR_20,'/login'), VAR_68=VAR_13.login_handler_class, VAR_69=VAR_13.logout_handler_class, VAR_47=VAR_13.password, VAR_14=kernel_manager, VAR_15=contents_manager, VAR_16=session_manager, VAR_17=kernel_spec_manager, VAR_18=config_manager, VAR_54=VAR_13.jinja_template_vars, FUNC_22=VAR_13.nbextensions_path, VAR_61=VAR_13.websocket_url, VAR_62=VAR_13.mathjax_url, config=VAR_13.config, config_dir=VAR_13.config_dir, jinja2_env=VAR_83, terminals_available=False, # Set later if terminals are available ) VAR_24.update(VAR_22) return VAR_24 def FUNC_5(self, VAR_24): VAR_79 = [] VAR_79.append((r'/deprecatedwidgets/(.*)', CLASS_0)) VAR_79.extend(FUNC_1('tree.handlers')) VAR_79.extend([(r"/login", VAR_24['login_handler_class'])]) VAR_79.extend([(r"/logout", VAR_24['logout_handler_class'])]) VAR_79.extend(FUNC_1('files.handlers')) VAR_79.extend(FUNC_1('notebook.handlers')) VAR_79.extend(FUNC_1('nbconvert.handlers')) VAR_79.extend(FUNC_1('kernelspecs.handlers')) VAR_79.extend(FUNC_1('edit.handlers')) VAR_79.extend(FUNC_1('services.api.handlers')) VAR_79.extend(FUNC_1('services.config.handlers')) VAR_79.extend(FUNC_1('services.kernels.handlers')) VAR_79.extend(FUNC_1('services.contents.handlers')) VAR_79.extend(FUNC_1('services.sessions.handlers')) VAR_79.extend(FUNC_1('services.nbconvert.handlers')) VAR_79.extend(FUNC_1('services.kernelspecs.handlers')) VAR_79.extend(FUNC_1('services.security.handlers')) try: import .ipywidgets VAR_79.append( (r"/nbextensions/widgets/(.*)", FileFindHandler, { 'path': ipywidgets.find_static_assets(), 'no_cache_paths': ['/'], # don't cache anything in nbextensions }), ) except: app_log.warn('ipywidgets package not installed. Widgets are unavailable.') VAR_79.append( (r"/nbextensions/(.*)", FileFindHandler, { 'path': VAR_24['nbextensions_path'], 'no_cache_paths': ['/'], # don't cache anything in nbextensions }), ) VAR_79.append( (r"/custom/(.*)", FileFindHandler, { 'path': VAR_24['static_custom_path'], 'no_cache_paths': ['/'], # don't cache anything in custom }) ) VAR_79.extend(FUNC_1('base.handlers')) VAR_79.append( (r'/?', web.RedirectHandler, { 'url' : VAR_24['default_url'], 'permanent': False, # want 302, not 301 }) ) VAR_85 = [] for handler in VAR_79: VAR_98 = url_path_join(VAR_24['base_url'], handler[0]) VAR_99 = tuple([VAR_98] + list(handler[1:])) VAR_85.append(VAR_99) VAR_85.append((r'(.*)', Template404)) return VAR_85 class CLASS_2(JupyterApp): VAR_25 = __version__ VAR_26="List currently running notebook servers in this profile." VAR_5 = dict( VAR_27=({'NbserverListApp': {'json': True}}, "Produce machine-readable JSON output."), ) VAR_27 = Bool(False, config=True, help="If True, each VAR_104 of output will be a JSON object with the " "details from the server VAR_93 file.") def FUNC_6(self): if not self.json: print("Currently running servers:") for serverinfo in FUNC_2(self.runtime_dir): if self.json: print(VAR_27.dumps(serverinfo)) else: print(serverinfo['url'], "::", serverinfo['notebook_dir']) VAR_5 = dict(base_flags) VAR_5['no-browser']=( {'NotebookApp' : {'open_browser' : False}}, "Don't open the notebook in a VAR_49 after startup." ) VAR_5['pylab']=( {'NotebookApp' : {'pylab' : 'warn'}}, "DISABLED: use %VAR_72 or %matplotlib in the notebook to enable matplotlib." ) VAR_5['no-mathjax']=( {'NotebookApp' : {'enable_mathjax' : False}}, """Disable MathJax MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) flags.update(boolean_flag('script', 'FileContentsManager.save_script', 'DEPRECATED, IGNORED', 'DEPRECATED, IGNORED')) VAR_6 = dict(base_aliases) VAR_6.update({ 'ip': 'NotebookApp.ip', 'port': 'NotebookApp.port', 'port-retries': 'NotebookApp.port_retries', 'transport': 'KernelManager.transport', 'keyfile': 'NotebookApp.keyfile', 'certfile': 'NotebookApp.certfile', 'notebook-dir': 'NotebookApp.notebook_dir', 'browser': 'NotebookApp.browser', 'pylab': 'NotebookApp.pylab', }) class CLASS_3(JupyterApp): VAR_4 = 'jupyter-notebook' VAR_25 = __version__ VAR_26 = """ The Jupyter HTML Notebook. This launches a Tornado based HTML Notebook Server that serves up an HTML5/Javascript Notebook client. """ VAR_28 = VAR_1 VAR_6 = aliases VAR_5 = VAR_5 VAR_29 = [ KernelManager, Session, MappingKernelManager, ContentsManager, FileContentsManager, NotebookNotary, KernelSpecManager, ] VAR_5 = Dict(VAR_5) VAR_6 = Dict(VAR_6) VAR_30 = dict( list=(CLASS_2, NbserverListApp.description.splitlines()[0]), ) VAR_31 = LogFormatter def FUNC_7(self): return logging.INFO def FUNC_8(self): return "%H:%M:%S" def FUNC_9(self): return u"%(color)VAR_86[%(levelname)1.1s %(asctime)VAR_86.%(msecs).03d %(VAR_4)VAR_86]%(end_color)VAR_86 %(message)s" VAR_32 = Bool(True) VAR_33 = Bool(False, config=True, help='Use minified JS file or not, mainly use during dev to avoid JS recompilation', ) VAR_34 = Unicode('', config=True) VAR_35 = Unicode('', config=True, help="""Set the Access-Control-Allow-Origin header Use '*' to allow any origin to access your server. Takes precedence over VAR_36. """ ) VAR_36 = Unicode('', config=True, help="""Use a regular expression for the Access-Control-Allow-Origin header Requests from an origin matching the expression will FUNC_3 replies with: Access-Control-Allow-Origin: origin where `origin` is the origin of the request. Ignored if VAR_35 is set. """ ) VAR_37 = Bool(False, config=True, help="Set the Access-Control-Allow-Credentials: true header" ) VAR_21 = Unicode('/tree', config=True, help="The default URL to redirect to from `/`" ) VAR_38 = Unicode('localhost', config=True, help="The IP address the notebook server will listen on." ) def FUNC_10(self): VAR_86 = socket.socket() try: VAR_86.bind(('localhost', 0)) except socket.error as e: self.log.warn("Cannot bind to localhost, using 127.0.0.1 as default VAR_38\VAR_3%s", e) return '127.0.0.1' else: VAR_86.close() return 'localhost' def FUNC_11(self, VAR_4, VAR_39, VAR_40): if VAR_40 == u'*': self.ip = u'' VAR_2 = Integer(8888, config=True, help="The VAR_2 the notebook server will listen on." ) VAR_41 = Integer(50, config=True, help="The number of additional ports to try if the specified VAR_2 is not available." ) VAR_42 = Unicode(u'', config=True, help="""The full VAR_87 to an SSL/TLS certificate file.""" ) VAR_43 = Unicode(u'', config=True, help="""The full VAR_87 to a private key file for usage with SSL/TLS.""" ) VAR_44 = Unicode(config=True, help="""The file where the cookie VAR_46 is stored.""" ) def FUNC_12(self): return os.path.join(self.runtime_dir, 'notebook_cookie_secret') VAR_45 = Bytes(b'', config=True, help="""The random bytes used to secure cookies. By default this is a VAR_40 random number every time you FUNC_6 the Notebook. Set it to a value in a config file to enable logins to persist across server sessions. Note: Cookie secrets should be kept private, do not share config files with VAR_45 stored in plaintext (you can read the value from a file). """ ) def FUNC_13(self): if os.path.exists(self.cookie_secret_file): with io.open(self.cookie_secret_file, 'rb') as VAR_102: return VAR_102.read() else: VAR_46 = base64.encodestring(os.urandom(1024)) self._write_cookie_secret_file(VAR_46) return VAR_46 def FUNC_14(self, VAR_46): self.log.info("Writing notebook server cookie VAR_46 to %s", self.cookie_secret_file) with io.open(self.cookie_secret_file, 'wb') as VAR_102: VAR_102.write(VAR_46) try: os.chmod(self.cookie_secret_file, 0o600) except OSError: self.log.warn( "Could not set permissions on %s", self.cookie_secret_file ) VAR_47 = Unicode(u'', config=True, help="""Hashed VAR_47 to use for web authentication. To generate, type in a python/IPython shell: from notebook.auth import passwd; passwd() The string should be of the form type:salt:hashed-VAR_47. """ ) VAR_48 = Bool(True, config=True, help="""Whether to open in a VAR_49 after starting. The specific VAR_49 used is platform dependent and determined by the python standard library `webbrowser` module, unless it is overridden using the --VAR_49 (CLASS_3.browser) configuration option. """) VAR_49 = Unicode(u'', config=True, help="""Specify what command to use to invoke a web VAR_49 when opening the notebook. If not specified, the default VAR_49 will be determined by the `webbrowser` standard library module, which allows setting of the BROWSER environment variable to override it. """) VAR_50 = Dict(config=True, help="DEPRECATED, use tornado_settings" ) def FUNC_15(self, VAR_4, VAR_39, VAR_40): self.log.warn("\VAR_3 VAR_50 is deprecated, use VAR_51.\n") self.tornado_settings = VAR_40 VAR_51 = Dict(config=True, help="Supply overrides for the tornado.web.Application that the " "Jupyter notebook uses.") VAR_52 = Dict(config=True, help="""Supply SSL options for the tornado HTTPServer. See the tornado docs for details.""") VAR_53 = Dict(config=True, help="Supply extra arguments that will be passed to Jinja environment.") VAR_54 = Dict( config=True, help="Extra variables to supply to jinja templates when rendering.", ) VAR_55 = Bool(True, config=True, help="""Whether to enable MathJax for typesetting math/TeX MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) def FUNC_16(self, VAR_4, VAR_39, VAR_40): if not VAR_40: self.mathjax_url = u'' VAR_20 = Unicode('/', config=True, help='''The base URL for the notebook server. Leading and trailing slashes can be omitted, and will automatically be added. ''') def FUNC_17(self, VAR_4, VAR_39, VAR_40): if not VAR_40.startswith('/'): self.base_url = '/'+VAR_40 elif not VAR_40.endswith('/'): self.base_url = VAR_40+'/' VAR_56 = Unicode('/', config=True, help="""DEPRECATED use base_url""") def FUNC_18(self, VAR_4, VAR_39, VAR_40): self.log.warn("base_project_url is deprecated, use base_url") self.base_url = VAR_40 VAR_57 = List(Unicode(), config=True, help="""Extra paths to search for serving static files. This allows adding javascript/css to be available from the notebook server machine, or overriding individual files in the IPython""" ) @property def FUNC_19(self): return self.extra_static_paths + [DEFAULT_STATIC_FILES_PATH] VAR_58 = List(Unicode(), help="""Path to search for custom.js, css""" ) def FUNC_20(self): return [ os.path.join(d, 'custom') for d in ( self.config_dir, os.path.join(get_ipython_dir(), 'profile_default', 'static'), DEFAULT_STATIC_FILES_PATH) ] VAR_59 = List(Unicode(), config=True, help="""Extra paths to search for serving jinja templates. Can be used to override templates from notebook.templates.""" ) @property def FUNC_21(self): return self.extra_template_paths + DEFAULT_TEMPLATE_PATH_LIST VAR_60 = List(Unicode(), config=True, help="""extra paths to look for Javascript notebook extensions""" ) @property def FUNC_22(self): VAR_87 = self.extra_nbextensions_path + jupyter_path('nbextensions') VAR_87.append(os.path.join(get_ipython_dir(), 'nbextensions')) return VAR_87 VAR_61 = Unicode("", config=True, help="""The base URL for websockets, if it differs from the HTTP server (hint: it almost certainly doesn't). Should be in the form of an HTTP origin: ws[VAR_86]://hostname[:VAR_2] """ ) VAR_62 = Unicode("", config=True, help="""The url for MathJax.js.""" ) def FUNC_23(self): if not self.enable_mathjax: return u'' VAR_88 = self.tornado_settings.get("static_url_prefix", url_path_join(self.base_url, "static") ) return url_path_join(VAR_88, 'components', 'MathJax', 'MathJax.js') def FUNC_24(self, VAR_4, VAR_39, VAR_40): if VAR_40 and not self.enable_mathjax: self.mathjax_url = u'' else: self.log.info("Using MathJax: %s", VAR_40) VAR_63 = Type( default_value=FileContentsManager, klass=ContentsManager, config=True, help='The notebook manager class to use.' ) VAR_64 = Type( default_value=MappingKernelManager, config=True, help='The kernel manager class to use.' ) VAR_65 = Type( default_value=SessionManager, config=True, help='The session manager class to use.' ) VAR_66 = Type( default_value=ConfigManager, config = True, help='The config manager class to use' ) VAR_17 = Instance(KernelSpecManager, allow_none=True) VAR_67 = Type( default_value=KernelSpecManager, config=True, help=""" The kernel spec manager class to use. Should be a subclass of `jupyter_client.kernelspec.KernelSpecManager`. The Api of KernelSpecManager is provisional and might change without warning between this VAR_25 of Jupyter and the next stable one. """ ) VAR_68 = Type( default_value=LoginHandler, klass=web.RequestHandler, config=True, help='The login handler class to use.', ) VAR_69 = Type( default_value=LogoutHandler, klass=web.RequestHandler, config=True, help='The logout handler class to use.', ) VAR_70 = Bool(False, config=True, help=("Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-For headers" "sent by the upstream reverse proxy. Necessary if the proxy handles SSL") ) VAR_71 = Unicode() def FUNC_25(self): VAR_71 = "nbserver-%VAR_86.json" % os.getpid() return os.path.join(self.runtime_dir, VAR_71) VAR_72 = Unicode('disabled', config=True, help=""" DISABLED: use %VAR_72 or %matplotlib in the notebook to enable matplotlib. """ ) def FUNC_26(self, VAR_4, VAR_39, VAR_40): if VAR_40 != 'warn': VAR_100 = ' %s' % VAR_40 else: VAR_100 = '' self.log.error("Support for specifying --VAR_72 on the command VAR_104 has been removed.") self.log.error( "Please use `%VAR_72{0}` or `%matplotlib{0}` in the notebook itself.".format(VAR_100) ) self.exit(1) VAR_73 = Unicode(config=True, help="The directory to use for notebooks and kernels." ) def FUNC_27(self): if self.file_to_run: return os.path.dirname(os.path.abspath(self.file_to_run)) else: return py3compat.getcwd() def FUNC_28(self, VAR_4, VAR_39, VAR_40): if not os.path.isabs(VAR_40): self.notebook_dir = os.path.abspath(VAR_40) return if not os.path.isdir(VAR_40): raise TraitError("No such notebook dir: %r" % VAR_40) self.config.FileContentsManager.root_dir = VAR_40 self.config.MappingKernelManager.root_dir = VAR_40 VAR_74 = List(Unicode(), config=True, help=("Python modules to load as notebook server extensions. " "This is an experimental API, and may change in future releases.") ) VAR_75 = Bool( False, config=True, help="Reraise exceptions encountered loading server extensions?", ) def FUNC_29(self, VAR_76=None): super(CLASS_3, self).parse_command_line(VAR_76) if self.extra_args: VAR_101 = self.extra_args[0] VAR_102 = os.path.abspath(VAR_101) self.argv.remove(VAR_101) if not os.path.exists(VAR_102): self.log.critical("No such file or directory: %s", VAR_102) self.exit(1) VAR_103 = Config() if os.path.isdir(VAR_102): VAR_103.NotebookApp.notebook_dir = VAR_102 elif os.path.isfile(VAR_102): VAR_103.NotebookApp.file_to_run = VAR_102 self.update_config(VAR_103) def FUNC_30(self): self.kernel_spec_manager = self.kernel_spec_manager_class( parent=self, ) self.kernel_manager = self.kernel_manager_class( parent=self, VAR_19=self.log, connection_dir=self.runtime_dir, VAR_17=self.kernel_spec_manager, ) self.contents_manager = self.contents_manager_class( parent=self, VAR_19=self.log, ) self.session_manager = self.session_manager_class( parent=self, VAR_19=self.log, VAR_14=self.kernel_manager, VAR_15=self.contents_manager, ) self.config_manager = self.config_manager_class( parent=self, VAR_19=self.log, config_dir=os.path.join(self.config_dir, 'nbconfig'), ) def FUNC_31(self): self.log.propagate = False for VAR_19 in app_log, access_log, gen_log: VAR_19.name = self.log.name VAR_89 = logging.getLogger('tornado') VAR_89.propagate = True VAR_89.parent = self.log VAR_89.setLevel(self.log.level) def FUNC_32(self): self.tornado_settings['allow_origin'] = self.allow_origin if self.allow_origin_pat: self.tornado_settings['allow_origin_pat'] = re.compile(self.allow_origin_pat) self.tornado_settings['allow_credentials'] = self.allow_credentials if not self.default_url.startswith(self.base_url): self.default_url = url_path_join(self.base_url, self.default_url) self.web_app = CLASS_1( self, self.kernel_manager, self.contents_manager, self.session_manager, self.kernel_spec_manager, self.config_manager, self.log, self.base_url, self.default_url, self.tornado_settings, self.jinja_environment_options ) VAR_52 = self.ssl_options if self.certfile: VAR_52['certfile'] = self.certfile if self.keyfile: VAR_52['keyfile'] = self.keyfile if not VAR_52: VAR_52 = None else: VAR_52['ssl_version']=ssl.PROTOCOL_TLSv1 self.login_handler_class.validate_security(self, VAR_52=ssl_options) self.http_server = httpserver.HTTPServer(self.web_app, VAR_52=ssl_options, xheaders=self.trust_xheaders) VAR_90 = None for VAR_2 in FUNC_0(self.port, self.port_retries+1): try: self.http_server.listen(VAR_2, self.ip) except socket.error as e: if e.errno == errno.EADDRINUSE: self.log.info('The VAR_2 %i is already in use, trying another random VAR_2.' % VAR_2) continue elif e.errno in (errno.EACCES, getattr(errno, 'WSAEACCES', errno.EACCES)): self.log.warn("Permission to listen on VAR_2 %i denied" % VAR_2) continue else: raise else: self.port = VAR_2 VAR_90 = True break if not VAR_90: self.log.critical('ERROR: the notebook server could not be started because ' 'no available VAR_2 could be found.') self.exit(1) @property def FUNC_33(self): VAR_38 = self.ip if self.ip else '[all VAR_38 addresses on your system]' return self._url(VAR_38) @property def FUNC_34(self): VAR_38 = self.ip if self.ip else 'localhost' return self._url(VAR_38) def FUNC_35(self, VAR_38): VAR_91 = 'https' if self.certfile else 'http' return "%VAR_86://%s:%i%s" % (VAR_91, VAR_38, self.port, self.base_url) def FUNC_36(self): try: from .terminal import .initialize FUNC_45(self.web_app, self.notebook_dir, self.connection_url) self.web_app.settings['terminals_available'] = True except ImportError as e: VAR_19 = self.log.debug if sys.platform == 'win32' else self.log.warn VAR_19("Terminals not available (error was %VAR_86)", e) def FUNC_37(self): if not sys.platform.startswith('win') and sys.stdin.isatty(): signal.signal(signal.SIGINT, self._handle_sigint) signal.signal(signal.SIGTERM, self._signal_stop) if hasattr(signal, 'SIGUSR1'): signal.signal(signal.SIGUSR1, self._signal_info) if hasattr(signal, 'SIGINFO'): signal.signal(signal.SIGINFO, self._signal_info) def FUNC_38(self, VAR_77, VAR_78): signal.signal(signal.SIGINT, self._signal_stop) VAR_92 = threading.Thread(target=self._confirm_exit) VAR_92.daemon = True VAR_92.start() def FUNC_39(self): signal.signal(signal.SIGINT, self._handle_sigint) def FUNC_40(self): VAR_93 = self.log.info VAR_93('interrupted') print(self.notebook_info()) sys.stdout.write("Shutdown this notebook server (y/[VAR_3])? ") sys.stdout.flush() VAR_94,VAR_95,VAR_96 = select.select([sys.stdin], [], [], 5) if VAR_94: VAR_104 = sys.stdin.readline() if VAR_104.lower().startswith('y') and 'n' not in VAR_104.lower(): self.log.critical("Shutdown confirmed") ioloop.IOLoop.current().stop() return else: print("No answer for 5s:", end=' ') print("resuming operation...") ioloop.IOLoop.current().add_callback(self._restore_sigint_handler) def FUNC_41(self, VAR_77, VAR_78): self.log.critical("received signal %VAR_86, stopping", VAR_77) ioloop.IOLoop.current().stop() def FUNC_42(self, VAR_77, VAR_78): print(self.notebook_info()) def FUNC_43(self): pass def FUNC_44(self): for modulename in self.server_extensions: try: VAR_11 = importlib.import_module(modulename) VAR_106 = getattr(VAR_11, 'load_jupyter_server_extension', None) if VAR_106 is not None: VAR_106(self) except Exception: if self.reraise_server_extension_failures: raise self.log.warn("Error loading server extension %s", modulename, exc_info=True) @catch_config_error def FUNC_45(self, VAR_76=None): super(CLASS_3, self).initialize(VAR_76) self.init_logging() if self._dispatching: return self.init_configurables() self.init_components() self.init_webapp() self.init_terminals() self.init_signal() self.init_server_extensions() def FUNC_46(self): self.log.info('Shutting down kernels') self.kernel_manager.shutdown_all() VAR_93 = self.contents_manager.info_string() + "\n" VAR_93 += "%d active kernels \n" % len(self.kernel_manager._kernels) return VAR_93 + "The Jupyter Notebook is running at: %s" % self.display_url def FUNC_48(self): return {'url': self.connection_url, 'hostname': self.ip if self.ip else 'localhost', 'port': self.port, 'secure': bool(self.certfile), 'base_url': self.base_url, 'notebook_dir': os.path.abspath(self.notebook_dir), 'pid': os.getpid() } def FUNC_49(self): with open(self.info_file, 'w') as VAR_102: VAR_27.dump(self.server_info(), VAR_102, indent=2) def FUNC_50(self): try: os.unlink(self.info_file) except OSError as e: if e.errno != errno.ENOENT: raise def FUNC_6(self): super(CLASS_3, self).start() VAR_93 = self.log.info for VAR_104 in self.notebook_info().split("\n"): VAR_93(VAR_104) VAR_93("Use Control-C to FUNC_51 this server and shut down all kernels (twice to skip confirmation).") self.write_server_info_file() if self.open_browser or self.file_to_run: try: VAR_49 = webbrowser.get(self.browser or None) except webbrowser.Error as e: self.log.warn('No web VAR_49 found: %VAR_86.' % e) VAR_49 = None if self.file_to_run: if not os.path.exists(self.file_to_run): self.log.critical("%VAR_86 does not exist" % self.file_to_run) self.exit(1) VAR_107 = os.path.relpath(self.file_to_run, self.notebook_dir) VAR_108 = url_path_join('notebooks', *VAR_107.split(os.sep)) else: VAR_108 = 'tree' if VAR_49: VAR_109 = lambda : VAR_49.open(url_path_join(self.connection_url, VAR_108), VAR_40=2) threading.Thread(target=VAR_109).start() self.io_loop = ioloop.IOLoop.current() if sys.platform.startswith('win'): VAR_105 = ioloop.PeriodicCallback(lambda : None, 5000) VAR_105.start() try: self.io_loop.start() except KeyboardInterrupt: VAR_93("Interrupted...") finally: self.cleanup_kernels() self.remove_server_info_file() def FUNC_51(self): def FUNC_52(): self.http_server.stop() self.io_loop.stop() self.io_loop.add_callback(FUNC_52) def FUNC_2(VAR_7=None): if VAR_7 is None: VAR_7 = jupyter_runtime_dir() if not os.path.isdir(VAR_7): return for file in os.listdir(VAR_7): if file.startswith('nbserver-'): with io.open(os.path.join(VAR_7, file), encoding='utf-8') as VAR_102: VAR_93 = VAR_27.load(VAR_102) if ('pid' in VAR_93) and check_pid(VAR_93['pid']): yield VAR_93 else: try: os.unlink(file) except OSError: pass # TODO: This should warn or VAR_19 or something VAR_8 = VAR_9 = CLASS_3.launch_instance
[ 1, 3, 4, 5, 6, 8, 26, 27, 29, 30, 31, 34, 35, 47, 51, 64, 68, 86, 88, 89, 90, 91, 92, 97, 98, 99, 100, 101, 104, 112, 118, 119, 128, 129, 130, 131, 132, 134, 139, 145, 147, 153, 161, 164, 167, 170, 172, 174, 184, 189, 190, 196, 197, 203, 204, 214, 215, 218, 221, 222, 241, 242, 253, 254, 267, 269, 276, 277, 283, 286, 287, 291, 296, 300, 309, 310, 311, 312, 313, 326, 330, 334, 335, 339, 341, 353, 354, 355, 356, 357, 359, 364, 371, 379, 383, 385, 388, 392, 396, 397, 399, 404, 405, 407, 408, 409, 412, 414, 418, 421, 423, 425, 427, 431, 435, 439, 445, 457, 460, 467, 471, 475, 481, 486, 499, 512, 515, 517, 519, 523, 531, 539, 546, 550, 554, 557, 562, 565, 569, 577, 580, 589, 594, 597, 601, 606, 614, 618, 621, 624, 629, 633, 638, 641, 645, 659, 662, 666, 683, 689, 691, 698, 703, 710, 717, 722, 724, 728, 745, 749, 755, 759, 764, 765, 768, 773, 779, 782, 790, 791, 792, 799, 825, 827, 828, 829, 831, 833, 835, 840, 847, 850, 864, 867, 872, 894, 899, 904, 908, 917, 923, 926, 928, 931, 933, 934, 938, 942, 945, 948, 966, 967, 968, 969, 971, 975, 978, 981, 983, 986, 989, 1003, 1016, 1019, 1025, 1031, 1042, 1047, 1050, 1058, 1061, 1065, 1070, 1072, 1079, 1084, 1093, 1096, 1097, 1107, 1113, 1114, 1117, 1124, 1125, 1128, 1133, 1134, 1135, 1139, 1144, 1145, 1146, 1147, 1149, 1150, 2, 103, 104, 105, 106, 107, 114, 1116, 1117, 1118, 1119, 1120, 1121, 220, 390, 394, 444, 445, 446, 447, 501, 574, 604, 627, 636, 735, 757, 842, 930, 940, 944, 945, 946, 947, 948, 949, 950, 980, 985, 986, 987, 988, 989, 990, 991, 1018, 1019, 1020, 1021, 1022, 1026, 1027, 1033, 1044, 1049, 1050, 1051, 1052, 1060, 1061, 1062, 1063 ]
[ 1, 3, 4, 5, 6, 8, 26, 27, 29, 30, 31, 34, 35, 47, 51, 64, 68, 86, 88, 89, 90, 91, 92, 97, 98, 99, 100, 101, 104, 112, 118, 119, 128, 129, 130, 131, 132, 134, 139, 145, 147, 153, 161, 164, 166, 169, 172, 174, 176, 186, 191, 192, 198, 199, 205, 206, 216, 217, 220, 223, 224, 243, 244, 255, 256, 269, 271, 278, 279, 285, 288, 289, 293, 298, 302, 311, 312, 313, 314, 315, 328, 332, 336, 337, 341, 343, 355, 356, 357, 358, 359, 361, 366, 373, 381, 385, 387, 390, 394, 398, 399, 401, 406, 407, 409, 410, 411, 414, 416, 420, 423, 425, 427, 429, 433, 437, 441, 447, 459, 462, 469, 473, 477, 483, 488, 501, 514, 517, 519, 521, 525, 533, 541, 548, 552, 556, 559, 564, 567, 571, 579, 582, 591, 596, 599, 603, 608, 616, 620, 623, 626, 631, 635, 640, 643, 647, 661, 664, 668, 685, 691, 693, 700, 705, 712, 719, 724, 726, 730, 747, 751, 757, 761, 766, 767, 770, 775, 781, 784, 792, 793, 794, 801, 827, 829, 830, 831, 833, 835, 837, 842, 849, 852, 866, 869, 874, 896, 901, 906, 910, 919, 925, 928, 930, 933, 935, 936, 940, 944, 947, 950, 968, 969, 970, 971, 973, 977, 980, 983, 985, 988, 991, 1005, 1018, 1021, 1027, 1033, 1044, 1049, 1052, 1060, 1063, 1067, 1072, 1074, 1081, 1086, 1095, 1098, 1099, 1109, 1115, 1116, 1119, 1126, 1127, 1130, 1135, 1136, 1137, 1141, 1146, 1147, 1148, 1149, 1151, 1152, 2, 103, 104, 105, 106, 107, 114, 1118, 1119, 1120, 1121, 1122, 1123, 222, 392, 396, 446, 447, 448, 449, 503, 576, 606, 629, 638, 737, 759, 844, 932, 942, 946, 947, 948, 949, 950, 951, 952, 982, 987, 988, 989, 990, 991, 992, 993, 1020, 1021, 1022, 1023, 1024, 1028, 1029, 1035, 1046, 1051, 1052, 1053, 1054, 1062, 1063, 1064, 1065 ]
0CWE-22
""" Regenerate golden-master """ import shutil from pathlib import Path from typer.testing import CliRunner from openapi_python_client.cli import app if __name__ == "__main__": from .fastapi_app import generate_openapi_json generate_openapi_json() runner = CliRunner() openapi_path = Path(__file__).parent / "fastapi_app" / "openapi.json" gm_path = Path(__file__).parent / "golden-master" shutil.rmtree(gm_path, ignore_errors=True) output_path = Path.cwd() / "my-test-api-client" shutil.rmtree(output_path, ignore_errors=True) config_path = Path(__file__).parent / "config.yml" result = runner.invoke(app, [f"--config={config_path}", "generate", f"--path={openapi_path}"]) if result.stdout: print(result.stdout) if result.exception: raise result.exception output_path.rename(gm_path)
""" Regenerate golden-master """ import shutil from pathlib import Path from typer.testing import CliRunner from openapi_python_client.cli import app if __name__ == "__main__": runner = CliRunner() openapi_path = Path(__file__).parent / "fastapi_app" / "openapi.json" gm_path = Path(__file__).parent / "golden-master" shutil.rmtree(gm_path, ignore_errors=True) output_path = Path.cwd() / "my-test-api-client" shutil.rmtree(output_path, ignore_errors=True) config_path = Path(__file__).parent / "config.yml" result = runner.invoke(app, [f"--config={config_path}", "generate", f"--path={openapi_path}"]) if result.stdout: print(result.stdout) if result.exception: raise result.exception output_path.rename(gm_path)
path_disclosure
{ "code": [ " from .fastapi_app import generate_openapi_json", " generate_openapi_json()" ], "line_no": [ 10, 12 ] }
{ "code": [], "line_no": [] }
import shutil from pathlib import Path from typer.testing import CliRunner from openapi_python_client.cli import app if __name__ == "__main__": from .fastapi_app import generate_openapi_json generate_openapi_json() VAR_0 = CliRunner() VAR_1 = Path(__file__).parent / "fastapi_app" / "openapi.json" VAR_2 = Path(__file__).parent / "golden-master" shutil.rmtree(VAR_2, ignore_errors=True) VAR_3 = Path.cwd() / "my-test-api-client" shutil.rmtree(VAR_3, ignore_errors=True) VAR_4 = Path(__file__).parent / "config.yml" VAR_5 = VAR_0.invoke(app, [f"--config={VAR_4}", "generate", f"--path={VAR_1}"]) if VAR_5.stdout: print(VAR_5.stdout) if VAR_5.exception: raise VAR_5.exception VAR_3.rename(VAR_2)
import shutil from pathlib import Path from typer.testing import CliRunner from openapi_python_client.cli import app if __name__ == "__main__": VAR_0 = CliRunner() VAR_1 = Path(__file__).parent / "fastapi_app" / "openapi.json" VAR_2 = Path(__file__).parent / "golden-master" shutil.rmtree(VAR_2, ignore_errors=True) VAR_3 = Path.cwd() / "my-test-api-client" shutil.rmtree(VAR_3, ignore_errors=True) VAR_4 = Path(__file__).parent / "config.yml" VAR_5 = VAR_0.invoke(app, [f"--config={VAR_4}", "generate", f"--path={VAR_1}"]) if VAR_5.stdout: print(VAR_5.stdout) if VAR_5.exception: raise VAR_5.exception VAR_3.rename(VAR_2)
[ 4, 6, 8, 11, 20, 27, 1 ]
[ 4, 6, 8, 17, 24, 1 ]
1CWE-79
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse from django.views.decorators.http import require_POST from weblate.lang.models import Language from weblate.trans.forms import ReportsForm from weblate.trans.models.change import Change from weblate.trans.util import redirect_param from weblate.utils.views import get_component, get_project, show_form_errors # Header, two longer fields for name and email, shorter fields for numbers RST_HEADING = " ".join(["=" * 40] * 2 + ["=" * 24] * 20) HTML_HEADING = "<table>\n<tr>{0}</tr>" def generate_credits(user, start_date, end_date, **kwargs): """Generate credits data for given component.""" result = [] base = Change.objects.content() if user: base = base.filter(author=user) for language in Language.objects.filter(**kwargs).distinct().iterator(): authors = base.filter(language=language, **kwargs).authors_list( (start_date, end_date) ) if not authors: continue result.append({language.name: sorted(authors, key=lambda item: item[2])}) return result @login_required @require_POST def get_credits(request, project=None, component=None): """View for credits.""" if project is None: obj = None kwargs = {"translation__isnull": False} elif component is None: obj = get_project(request, project) kwargs = {"translation__component__project": obj} else: obj = get_component(request, project, component) kwargs = {"translation__component": obj} form = ReportsForm(request.POST) if not form.is_valid(): show_form_errors(request, form) return redirect_param(obj or "home", "#reports") data = generate_credits( None if request.user.has_perm("reports.view", obj) else request.user, form.cleaned_data["start_date"], form.cleaned_data["end_date"], **kwargs, ) if form.cleaned_data["style"] == "json": return JsonResponse(data=data, safe=False) if form.cleaned_data["style"] == "html": start = "<table>" row_start = "<tr>" language_format = "<th>{0}</th>" translator_start = "<td><ul>" translator_format = '<li><a href="mailto:{0}">{1}</a> ({2})</li>' translator_end = "</ul></td>" row_end = "</tr>" mime = "text/html" end = "</table>" else: start = "" row_start = "" language_format = "* {0}\n" translator_start = "" translator_format = " * {1} <{0}> ({2})" translator_end = "" row_end = "" mime = "text/plain" end = "" result = [start] for language in data: name, translators = language.popitem() result.append(row_start) result.append(language_format.format(name)) result.append( translator_start + "\n".join(translator_format.format(*t) for t in translators) + translator_end ) result.append(row_end) result.append(end) return HttpResponse("\n".join(result), content_type=f"{mime}; charset=utf-8") COUNT_DEFAULTS = { field: 0 for field in ( "t_chars", "t_words", "chars", "words", "edits", "count", "t_chars_new", "t_words_new", "chars_new", "words_new", "edits_new", "count_new", "t_chars_approve", "t_words_approve", "chars_approve", "words_approve", "edits_approve", "count_approve", "t_chars_edit", "t_words_edit", "chars_edit", "words_edit", "edits_edit", "count_edit", ) } def generate_counts(user, start_date, end_date, **kwargs): """Generate credits data for given component.""" result = {} action_map = {Change.ACTION_NEW: "new", Change.ACTION_APPROVE: "approve"} base = Change.objects.content().filter(unit__isnull=False) if user: base = base.filter(author=user) else: base = base.filter(author__isnull=False) changes = base.filter( timestamp__range=(start_date, end_date), **kwargs ).prefetch_related("author", "unit") for change in changes: email = change.author.email if email not in result: result[email] = current = {"name": change.author.full_name, "email": email} current.update(COUNT_DEFAULTS) else: current = result[email] src_chars = len(change.unit.source) src_words = change.unit.num_words tgt_chars = len(change.target) tgt_words = len(change.target.split()) edits = change.get_distance() current["chars"] += src_chars current["words"] += src_words current["t_chars"] += tgt_chars current["t_words"] += tgt_words current["edits"] += edits current["count"] += 1 suffix = action_map.get(change.action, "edit") current["t_chars_" + suffix] += tgt_chars current["t_words_" + suffix] += tgt_words current["chars_" + suffix] += src_chars current["words_" + suffix] += src_words current["edits_" + suffix] += edits current["count_" + suffix] += 1 return list(result.values()) @login_required @require_POST def get_counts(request, project=None, component=None): """View for work counts.""" if project is None: obj = None kwargs = {} elif component is None: obj = get_project(request, project) kwargs = {"project": obj} else: obj = get_component(request, project, component) kwargs = {"component": obj} form = ReportsForm(request.POST) if not form.is_valid(): show_form_errors(request, form) return redirect_param(obj or "home", "#reports") data = generate_counts( None if request.user.has_perm("reports.view", obj) else request.user, form.cleaned_data["start_date"], form.cleaned_data["end_date"], **kwargs, ) if form.cleaned_data["style"] == "json": return JsonResponse(data=data, safe=False) headers = ( "Name", "Email", "Count total", "Edits total", "Source words total", "Source chars total", "Target words total", "Target chars total", "Count new", "Edits new", "Source words new", "Source chars new", "Target words new", "Target chars new", "Count approved", "Edits approved", "Source words approved", "Source chars approved", "Target words approved", "Target chars approved", "Count edited", "Edits edited", "Source words edited", "Source chars edited", "Target words edited", "Target chars edited", ) if form.cleaned_data["style"] == "html": start = HTML_HEADING.format("".join(f"<th>{h}</th>" for h in headers)) row_start = "<tr>" cell_name = cell_count = "<td>{0}</td>\n" row_end = "</tr>" mime = "text/html" end = "</table>" else: start = "{0}\n{1} {2}\n{0}".format( RST_HEADING, " ".join(f"{h:40}" for h in headers[:2]), " ".join(f"{h:24}" for h in headers[2:]), ) row_start = "" cell_name = "{0:40} " cell_count = "{0:24} " row_end = "" mime = "text/plain" end = RST_HEADING result = [start] for item in data: if row_start: result.append(row_start) result.append( "".join( ( cell_name.format(item["name"] or "Anonymous"), cell_name.format(item["email"] or ""), cell_count.format(item["count"]), cell_count.format(item["edits"]), cell_count.format(item["words"]), cell_count.format(item["chars"]), cell_count.format(item["t_words"]), cell_count.format(item["t_chars"]), cell_count.format(item["count_new"]), cell_count.format(item["edits_new"]), cell_count.format(item["words_new"]), cell_count.format(item["chars_new"]), cell_count.format(item["t_words_new"]), cell_count.format(item["t_chars_new"]), cell_count.format(item["count_approve"]), cell_count.format(item["edits_approve"]), cell_count.format(item["words_approve"]), cell_count.format(item["chars_approve"]), cell_count.format(item["t_words_approve"]), cell_count.format(item["t_chars_approve"]), cell_count.format(item["count_edit"]), cell_count.format(item["edits_edit"]), cell_count.format(item["words_edit"]), cell_count.format(item["chars_edit"]), cell_count.format(item["t_words_edit"]), cell_count.format(item["t_chars_edit"]), ) ) ) if row_end: result.append(row_end) result.append(end) return HttpResponse("\n".join(result), content_type=f"{mime}; charset=utf-8")
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse from django.utils.html import escape from django.views.decorators.http import require_POST from weblate.lang.models import Language from weblate.trans.forms import ReportsForm from weblate.trans.models.change import Change from weblate.trans.util import redirect_param from weblate.utils.views import get_component, get_project, show_form_errors # Header, two longer fields for name and email, shorter fields for numbers RST_HEADING = " ".join(["=" * 40] * 2 + ["=" * 24] * 20) HTML_HEADING = "<table>\n<tr>{0}</tr>" def generate_credits(user, start_date, end_date, **kwargs): """Generate credits data for given component.""" result = [] base = Change.objects.content() if user: base = base.filter(author=user) for language in Language.objects.filter(**kwargs).distinct().iterator(): authors = base.filter(language=language, **kwargs).authors_list( (start_date, end_date) ) if not authors: continue result.append({language.name: sorted(authors, key=lambda item: item[2])}) return result @login_required @require_POST def get_credits(request, project=None, component=None): """View for credits.""" if project is None: obj = None kwargs = {"translation__isnull": False} elif component is None: obj = get_project(request, project) kwargs = {"translation__component__project": obj} else: obj = get_component(request, project, component) kwargs = {"translation__component": obj} form = ReportsForm(request.POST) if not form.is_valid(): show_form_errors(request, form) return redirect_param(obj or "home", "#reports") data = generate_credits( None if request.user.has_perm("reports.view", obj) else request.user, form.cleaned_data["start_date"], form.cleaned_data["end_date"], **kwargs, ) if form.cleaned_data["style"] == "json": return JsonResponse(data=data, safe=False) if form.cleaned_data["style"] == "html": start = "<table>" row_start = "<tr>" language_format = "<th>{0}</th>" translator_start = "<td><ul>" translator_format = '<li><a href="mailto:{0}">{1}</a> ({2})</li>' translator_end = "</ul></td>" row_end = "</tr>" mime = "text/html" end = "</table>" else: start = "" row_start = "" language_format = "* {0}\n" translator_start = "" translator_format = " * {1} <{0}> ({2})" translator_end = "" row_end = "" mime = "text/plain" end = "" result = [start] for language in data: name, translators = language.popitem() result.append(row_start) result.append(language_format.format(escape(name))) result.append( translator_start + "\n".join( translator_format.format(escape(t[0]), escape(t[1]), t[2]) for t in translators ) + translator_end ) result.append(row_end) result.append(end) return HttpResponse("\n".join(result), content_type=f"{mime}; charset=utf-8") COUNT_DEFAULTS = { field: 0 for field in ( "t_chars", "t_words", "chars", "words", "edits", "count", "t_chars_new", "t_words_new", "chars_new", "words_new", "edits_new", "count_new", "t_chars_approve", "t_words_approve", "chars_approve", "words_approve", "edits_approve", "count_approve", "t_chars_edit", "t_words_edit", "chars_edit", "words_edit", "edits_edit", "count_edit", ) } def generate_counts(user, start_date, end_date, **kwargs): """Generate credits data for given component.""" result = {} action_map = {Change.ACTION_NEW: "new", Change.ACTION_APPROVE: "approve"} base = Change.objects.content().filter(unit__isnull=False) if user: base = base.filter(author=user) else: base = base.filter(author__isnull=False) changes = base.filter( timestamp__range=(start_date, end_date), **kwargs ).prefetch_related("author", "unit") for change in changes: email = change.author.email if email not in result: result[email] = current = {"name": change.author.full_name, "email": email} current.update(COUNT_DEFAULTS) else: current = result[email] src_chars = len(change.unit.source) src_words = change.unit.num_words tgt_chars = len(change.target) tgt_words = len(change.target.split()) edits = change.get_distance() current["chars"] += src_chars current["words"] += src_words current["t_chars"] += tgt_chars current["t_words"] += tgt_words current["edits"] += edits current["count"] += 1 suffix = action_map.get(change.action, "edit") current["t_chars_" + suffix] += tgt_chars current["t_words_" + suffix] += tgt_words current["chars_" + suffix] += src_chars current["words_" + suffix] += src_words current["edits_" + suffix] += edits current["count_" + suffix] += 1 return list(result.values()) @login_required @require_POST def get_counts(request, project=None, component=None): """View for work counts.""" if project is None: obj = None kwargs = {} elif component is None: obj = get_project(request, project) kwargs = {"project": obj} else: obj = get_component(request, project, component) kwargs = {"component": obj} form = ReportsForm(request.POST) if not form.is_valid(): show_form_errors(request, form) return redirect_param(obj or "home", "#reports") data = generate_counts( None if request.user.has_perm("reports.view", obj) else request.user, form.cleaned_data["start_date"], form.cleaned_data["end_date"], **kwargs, ) if form.cleaned_data["style"] == "json": return JsonResponse(data=data, safe=False) headers = ( "Name", "Email", "Count total", "Edits total", "Source words total", "Source chars total", "Target words total", "Target chars total", "Count new", "Edits new", "Source words new", "Source chars new", "Target words new", "Target chars new", "Count approved", "Edits approved", "Source words approved", "Source chars approved", "Target words approved", "Target chars approved", "Count edited", "Edits edited", "Source words edited", "Source chars edited", "Target words edited", "Target chars edited", ) if form.cleaned_data["style"] == "html": start = HTML_HEADING.format("".join(f"<th>{h}</th>" for h in headers)) row_start = "<tr>" cell_name = cell_count = "<td>{0}</td>\n" row_end = "</tr>" mime = "text/html" end = "</table>" else: start = "{0}\n{1} {2}\n{0}".format( RST_HEADING, " ".join(f"{h:40}" for h in headers[:2]), " ".join(f"{h:24}" for h in headers[2:]), ) row_start = "" cell_name = "{0:40} " cell_count = "{0:24} " row_end = "" mime = "text/plain" end = RST_HEADING result = [start] for item in data: if row_start: result.append(row_start) result.append( "".join( ( cell_name.format(escape(item["name"]) or "Anonymous"), cell_name.format(escape(item["email"]) or ""), cell_count.format(item["count"]), cell_count.format(item["edits"]), cell_count.format(item["words"]), cell_count.format(item["chars"]), cell_count.format(item["t_words"]), cell_count.format(item["t_chars"]), cell_count.format(item["count_new"]), cell_count.format(item["edits_new"]), cell_count.format(item["words_new"]), cell_count.format(item["chars_new"]), cell_count.format(item["t_words_new"]), cell_count.format(item["t_chars_new"]), cell_count.format(item["count_approve"]), cell_count.format(item["edits_approve"]), cell_count.format(item["words_approve"]), cell_count.format(item["chars_approve"]), cell_count.format(item["t_words_approve"]), cell_count.format(item["t_chars_approve"]), cell_count.format(item["count_edit"]), cell_count.format(item["edits_edit"]), cell_count.format(item["words_edit"]), cell_count.format(item["chars_edit"]), cell_count.format(item["t_words_edit"]), cell_count.format(item["t_chars_edit"]), ) ) ) if row_end: result.append(row_end) result.append(end) return HttpResponse("\n".join(result), content_type=f"{mime}; charset=utf-8")
xss
{ "code": [ " result.append(language_format.format(name))", " + \"\\n\".join(translator_format.format(*t) for t in translators)", " cell_name.format(item[\"name\"] or \"Anonymous\"),", " cell_name.format(item[\"email\"] or \"\")," ], "line_no": [ 112, 115, 291, 292 ] }
{ "code": [ "from django.utils.html import escape", " result.append(language_format.format(escape(name)))", " + \"\\n\".join(", " translator_format.format(escape(t[0]), escape(t[1]), t[2])", " for t in translators", " )", " cell_name.format(escape(item[\"name\"]) or \"Anonymous\"),", " cell_name.format(escape(item[\"email\"]) or \"\")," ], "line_no": [ 22, 112, 115, 116, 117, 118, 294, 295 ] }
from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse from django.views.decorators.http import require_POST from weblate.lang.models import Language from weblate.trans.forms import ReportsForm from weblate.trans.models.change import Change from weblate.trans.util import redirect_param from weblate.utils.views import get_component, get_project, show_form_errors VAR_0 = " ".join(["=" * 40] * 2 + ["=" * 24] * 20) VAR_1 = "<table>\n<tr>{0}</tr>" def FUNC_0(VAR_2, VAR_3, VAR_4, **VAR_5): VAR_10 = [] VAR_11 = Change.objects.content() if VAR_2: VAR_11 = VAR_11.filter(author=VAR_2) for language in Language.objects.filter(**VAR_5).distinct().iterator(): VAR_17 = VAR_11.filter(language=language, **VAR_5).authors_list( (VAR_3, VAR_4) ) if not VAR_17: continue VAR_10.append({language.name: sorted(VAR_17, key=lambda item: item[2])}) return VAR_10 @login_required @require_POST def FUNC_1(VAR_6, VAR_7=None, VAR_8=None): if VAR_7 is None: VAR_18 = None VAR_5 = {"translation__isnull": False} elif VAR_8 is None: VAR_18 = get_project(VAR_6, VAR_7) VAR_5 = {"translation__component__project": VAR_18} else: VAR_18 = get_component(VAR_6, VAR_7, VAR_8) VAR_5 = {"translation__component": VAR_18} VAR_12 = ReportsForm(VAR_6.POST) if not VAR_12.is_valid(): show_form_errors(VAR_6, VAR_12) return redirect_param(VAR_18 or "home", "#reports") VAR_13 = FUNC_0( None if VAR_6.user.has_perm("reports.view", VAR_18) else VAR_6.user, VAR_12.cleaned_data["start_date"], VAR_12.cleaned_data["end_date"], **VAR_5, ) if VAR_12.cleaned_data["style"] == "json": return JsonResponse(VAR_13=data, safe=False) if VAR_12.cleaned_data["style"] == "html": VAR_19 = "<table>" VAR_20 = "<tr>" VAR_21 = "<th>{0}</th>" VAR_22 = "<td><ul>" VAR_23 = '<li><a href="mailto:{0}">{1}</a> ({2})</li>' VAR_24 = "</ul></td>" VAR_25 = "</tr>" VAR_26 = "text/html" VAR_27 = "</table>" else: VAR_19 = "" VAR_20 = "" VAR_21 = "* {0}\n" VAR_22 = "" VAR_23 = " * {1} <{0}> ({2})" VAR_24 = "" VAR_25 = "" VAR_26 = "text/plain" VAR_27 = "" VAR_10 = [VAR_19] for language in VAR_13: VAR_28, VAR_29 = language.popitem() VAR_10.append(VAR_20) VAR_10.append(VAR_21.format(VAR_28)) VAR_10.append( VAR_22 + "\n".join(VAR_23.format(*t) for t in VAR_29) + VAR_24 ) VAR_10.append(VAR_25) VAR_10.append(VAR_27) return HttpResponse("\n".join(VAR_10), content_type=f"{VAR_26}; charset=utf-8") VAR_9 = { field: 0 for field in ( "t_chars", "t_words", "chars", "words", "edits", "count", "t_chars_new", "t_words_new", "chars_new", "words_new", "edits_new", "count_new", "t_chars_approve", "t_words_approve", "chars_approve", "words_approve", "edits_approve", "count_approve", "t_chars_edit", "t_words_edit", "chars_edit", "words_edit", "edits_edit", "count_edit", ) } def FUNC_2(VAR_2, VAR_3, VAR_4, **VAR_5): VAR_10 = {} VAR_14 = {Change.ACTION_NEW: "new", Change.ACTION_APPROVE: "approve"} VAR_11 = Change.objects.content().filter(unit__isnull=False) if VAR_2: VAR_11 = VAR_11.filter(author=VAR_2) else: VAR_11 = VAR_11.filter(author__isnull=False) VAR_15 = VAR_11.filter( timestamp__range=(VAR_3, VAR_4), **VAR_5 ).prefetch_related("author", "unit") for change in VAR_15: VAR_30 = change.author.email if VAR_30 not in VAR_10: result[VAR_30] = VAR_39 = {"name": change.author.full_name, "email": VAR_30} VAR_39.update(VAR_9) else: VAR_39 = VAR_10[VAR_30] VAR_31 = len(change.unit.source) VAR_32 = change.unit.num_words VAR_33 = len(change.target) VAR_34 = len(change.target.split()) VAR_35 = change.get_distance() VAR_39["chars"] += VAR_31 VAR_39["words"] += VAR_32 VAR_39["t_chars"] += VAR_33 VAR_39["t_words"] += VAR_34 VAR_39["edits"] += VAR_35 VAR_39["count"] += 1 VAR_36 = VAR_14.get(change.action, "edit") VAR_39["t_chars_" + VAR_36] += VAR_33 VAR_39["t_words_" + VAR_36] += VAR_34 VAR_39["chars_" + VAR_36] += VAR_31 VAR_39["words_" + VAR_36] += VAR_32 VAR_39["edits_" + VAR_36] += VAR_35 VAR_39["count_" + VAR_36] += 1 return list(VAR_10.values()) @login_required @require_POST def FUNC_3(VAR_6, VAR_7=None, VAR_8=None): if VAR_7 is None: VAR_18 = None VAR_5 = {} elif VAR_8 is None: VAR_18 = get_project(VAR_6, VAR_7) VAR_5 = {"project": VAR_18} else: VAR_18 = get_component(VAR_6, VAR_7, VAR_8) VAR_5 = {"component": VAR_18} VAR_12 = ReportsForm(VAR_6.POST) if not VAR_12.is_valid(): show_form_errors(VAR_6, VAR_12) return redirect_param(VAR_18 or "home", "#reports") VAR_13 = FUNC_2( None if VAR_6.user.has_perm("reports.view", VAR_18) else VAR_6.user, VAR_12.cleaned_data["start_date"], VAR_12.cleaned_data["end_date"], **VAR_5, ) if VAR_12.cleaned_data["style"] == "json": return JsonResponse(VAR_13=data, safe=False) VAR_16 = ( "Name", "Email", "Count total", "Edits total", "Source words total", "Source chars total", "Target words total", "Target chars total", "Count new", "Edits new", "Source words new", "Source chars new", "Target words new", "Target chars new", "Count approved", "Edits approved", "Source words approved", "Source chars approved", "Target words approved", "Target chars approved", "Count edited", "Edits edited", "Source words edited", "Source chars edited", "Target words edited", "Target chars edited", ) if VAR_12.cleaned_data["style"] == "html": VAR_19 = VAR_1.format("".join(f"<th>{h}</th>" for h in VAR_16)) VAR_20 = "<tr>" VAR_37 = VAR_38 = "<td>{0}</td>\n" VAR_25 = "</tr>" VAR_26 = "text/html" VAR_27 = "</table>" else: VAR_19 = "{0}\n{1} {2}\n{0}".format( VAR_0, " ".join(f"{h:40}" for h in VAR_16[:2]), " ".join(f"{h:24}" for h in VAR_16[2:]), ) VAR_20 = "" VAR_37 = "{0:40} " VAR_38 = "{0:24} " VAR_25 = "" VAR_26 = "text/plain" VAR_27 = VAR_0 VAR_10 = [VAR_19] for item in VAR_13: if VAR_20: VAR_10.append(VAR_20) VAR_10.append( "".join( ( VAR_37.format(item["name"] or "Anonymous"), VAR_37.format(item["email"] or ""), VAR_38.format(item["count"]), VAR_38.format(item["edits"]), VAR_38.format(item["words"]), VAR_38.format(item["chars"]), VAR_38.format(item["t_words"]), VAR_38.format(item["t_chars"]), VAR_38.format(item["count_new"]), VAR_38.format(item["edits_new"]), VAR_38.format(item["words_new"]), VAR_38.format(item["chars_new"]), VAR_38.format(item["t_words_new"]), VAR_38.format(item["t_chars_new"]), VAR_38.format(item["count_approve"]), VAR_38.format(item["edits_approve"]), VAR_38.format(item["words_approve"]), VAR_38.format(item["chars_approve"]), VAR_38.format(item["t_words_approve"]), VAR_38.format(item["t_chars_approve"]), VAR_38.format(item["count_edit"]), VAR_38.format(item["edits_edit"]), VAR_38.format(item["words_edit"]), VAR_38.format(item["chars_edit"]), VAR_38.format(item["t_words_edit"]), VAR_38.format(item["t_chars_edit"]), ) ) ) if VAR_25: VAR_10.append(VAR_25) VAR_10.append(VAR_27) return HttpResponse("\n".join(VAR_10), content_type=f"{VAR_26}; charset=utf-8")
from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse from django.utils.html import escape from django.views.decorators.http import require_POST from weblate.lang.models import Language from weblate.trans.forms import ReportsForm from weblate.trans.models.change import Change from weblate.trans.util import redirect_param from weblate.utils.views import get_component, get_project, show_form_errors VAR_0 = " ".join(["=" * 40] * 2 + ["=" * 24] * 20) VAR_1 = "<table>\n<tr>{0}</tr>" def FUNC_0(VAR_2, VAR_3, VAR_4, **VAR_5): VAR_10 = [] VAR_11 = Change.objects.content() if VAR_2: VAR_11 = VAR_11.filter(author=VAR_2) for language in Language.objects.filter(**VAR_5).distinct().iterator(): VAR_17 = VAR_11.filter(language=language, **VAR_5).authors_list( (VAR_3, VAR_4) ) if not VAR_17: continue VAR_10.append({language.name: sorted(VAR_17, key=lambda item: item[2])}) return VAR_10 @login_required @require_POST def FUNC_1(VAR_6, VAR_7=None, VAR_8=None): if VAR_7 is None: VAR_18 = None VAR_5 = {"translation__isnull": False} elif VAR_8 is None: VAR_18 = get_project(VAR_6, VAR_7) VAR_5 = {"translation__component__project": VAR_18} else: VAR_18 = get_component(VAR_6, VAR_7, VAR_8) VAR_5 = {"translation__component": VAR_18} VAR_12 = ReportsForm(VAR_6.POST) if not VAR_12.is_valid(): show_form_errors(VAR_6, VAR_12) return redirect_param(VAR_18 or "home", "#reports") VAR_13 = FUNC_0( None if VAR_6.user.has_perm("reports.view", VAR_18) else VAR_6.user, VAR_12.cleaned_data["start_date"], VAR_12.cleaned_data["end_date"], **VAR_5, ) if VAR_12.cleaned_data["style"] == "json": return JsonResponse(VAR_13=data, safe=False) if VAR_12.cleaned_data["style"] == "html": VAR_19 = "<table>" VAR_20 = "<tr>" VAR_21 = "<th>{0}</th>" VAR_22 = "<td><ul>" VAR_23 = '<li><a href="mailto:{0}">{1}</a> ({2})</li>' VAR_24 = "</ul></td>" VAR_25 = "</tr>" VAR_26 = "text/html" VAR_27 = "</table>" else: VAR_19 = "" VAR_20 = "" VAR_21 = "* {0}\n" VAR_22 = "" VAR_23 = " * {1} <{0}> ({2})" VAR_24 = "" VAR_25 = "" VAR_26 = "text/plain" VAR_27 = "" VAR_10 = [VAR_19] for language in VAR_13: VAR_28, VAR_29 = language.popitem() VAR_10.append(VAR_20) VAR_10.append(VAR_21.format(escape(VAR_28))) VAR_10.append( VAR_22 + "\n".join( VAR_23.format(escape(t[0]), escape(t[1]), t[2]) for t in VAR_29 ) + VAR_24 ) VAR_10.append(VAR_25) VAR_10.append(VAR_27) return HttpResponse("\n".join(VAR_10), content_type=f"{VAR_26}; charset=utf-8") VAR_9 = { field: 0 for field in ( "t_chars", "t_words", "chars", "words", "edits", "count", "t_chars_new", "t_words_new", "chars_new", "words_new", "edits_new", "count_new", "t_chars_approve", "t_words_approve", "chars_approve", "words_approve", "edits_approve", "count_approve", "t_chars_edit", "t_words_edit", "chars_edit", "words_edit", "edits_edit", "count_edit", ) } def FUNC_2(VAR_2, VAR_3, VAR_4, **VAR_5): VAR_10 = {} VAR_14 = {Change.ACTION_NEW: "new", Change.ACTION_APPROVE: "approve"} VAR_11 = Change.objects.content().filter(unit__isnull=False) if VAR_2: VAR_11 = VAR_11.filter(author=VAR_2) else: VAR_11 = VAR_11.filter(author__isnull=False) VAR_15 = VAR_11.filter( timestamp__range=(VAR_3, VAR_4), **VAR_5 ).prefetch_related("author", "unit") for change in VAR_15: VAR_30 = change.author.email if VAR_30 not in VAR_10: result[VAR_30] = VAR_39 = {"name": change.author.full_name, "email": VAR_30} VAR_39.update(VAR_9) else: VAR_39 = VAR_10[VAR_30] VAR_31 = len(change.unit.source) VAR_32 = change.unit.num_words VAR_33 = len(change.target) VAR_34 = len(change.target.split()) VAR_35 = change.get_distance() VAR_39["chars"] += VAR_31 VAR_39["words"] += VAR_32 VAR_39["t_chars"] += VAR_33 VAR_39["t_words"] += VAR_34 VAR_39["edits"] += VAR_35 VAR_39["count"] += 1 VAR_36 = VAR_14.get(change.action, "edit") VAR_39["t_chars_" + VAR_36] += VAR_33 VAR_39["t_words_" + VAR_36] += VAR_34 VAR_39["chars_" + VAR_36] += VAR_31 VAR_39["words_" + VAR_36] += VAR_32 VAR_39["edits_" + VAR_36] += VAR_35 VAR_39["count_" + VAR_36] += 1 return list(VAR_10.values()) @login_required @require_POST def FUNC_3(VAR_6, VAR_7=None, VAR_8=None): if VAR_7 is None: VAR_18 = None VAR_5 = {} elif VAR_8 is None: VAR_18 = get_project(VAR_6, VAR_7) VAR_5 = {"project": VAR_18} else: VAR_18 = get_component(VAR_6, VAR_7, VAR_8) VAR_5 = {"component": VAR_18} VAR_12 = ReportsForm(VAR_6.POST) if not VAR_12.is_valid(): show_form_errors(VAR_6, VAR_12) return redirect_param(VAR_18 or "home", "#reports") VAR_13 = FUNC_2( None if VAR_6.user.has_perm("reports.view", VAR_18) else VAR_6.user, VAR_12.cleaned_data["start_date"], VAR_12.cleaned_data["end_date"], **VAR_5, ) if VAR_12.cleaned_data["style"] == "json": return JsonResponse(VAR_13=data, safe=False) VAR_16 = ( "Name", "Email", "Count total", "Edits total", "Source words total", "Source chars total", "Target words total", "Target chars total", "Count new", "Edits new", "Source words new", "Source chars new", "Target words new", "Target chars new", "Count approved", "Edits approved", "Source words approved", "Source chars approved", "Target words approved", "Target chars approved", "Count edited", "Edits edited", "Source words edited", "Source chars edited", "Target words edited", "Target chars edited", ) if VAR_12.cleaned_data["style"] == "html": VAR_19 = VAR_1.format("".join(f"<th>{h}</th>" for h in VAR_16)) VAR_20 = "<tr>" VAR_37 = VAR_38 = "<td>{0}</td>\n" VAR_25 = "</tr>" VAR_26 = "text/html" VAR_27 = "</table>" else: VAR_19 = "{0}\n{1} {2}\n{0}".format( VAR_0, " ".join(f"{h:40}" for h in VAR_16[:2]), " ".join(f"{h:24}" for h in VAR_16[2:]), ) VAR_20 = "" VAR_37 = "{0:40} " VAR_38 = "{0:24} " VAR_25 = "" VAR_26 = "text/plain" VAR_27 = VAR_0 VAR_10 = [VAR_19] for item in VAR_13: if VAR_20: VAR_10.append(VAR_20) VAR_10.append( "".join( ( VAR_37.format(escape(item["name"]) or "Anonymous"), VAR_37.format(escape(item["email"]) or ""), VAR_38.format(item["count"]), VAR_38.format(item["edits"]), VAR_38.format(item["words"]), VAR_38.format(item["chars"]), VAR_38.format(item["t_words"]), VAR_38.format(item["t_chars"]), VAR_38.format(item["count_new"]), VAR_38.format(item["edits_new"]), VAR_38.format(item["words_new"]), VAR_38.format(item["chars_new"]), VAR_38.format(item["t_words_new"]), VAR_38.format(item["t_chars_new"]), VAR_38.format(item["count_approve"]), VAR_38.format(item["edits_approve"]), VAR_38.format(item["words_approve"]), VAR_38.format(item["chars_approve"]), VAR_38.format(item["t_words_approve"]), VAR_38.format(item["t_chars_approve"]), VAR_38.format(item["count_edit"]), VAR_38.format(item["edits_edit"]), VAR_38.format(item["words_edit"]), VAR_38.format(item["chars_edit"]), VAR_38.format(item["t_words_edit"]), VAR_38.format(item["t_chars_edit"]), ) ) ) if VAR_25: VAR_10.append(VAR_25) VAR_10.append(VAR_27) return HttpResponse("\n".join(VAR_10), content_type=f"{VAR_26}; charset=utf-8")
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 24, 30, 31, 33, 35, 36, 40, 44, 52, 54, 55, 69, 71, 75, 82, 85, 106, 108, 119, 121, 123, 124, 154, 155, 160, 166, 172, 178, 184, 191, 193, 200, 202, 203, 217, 219, 223, 230, 233, 262, 282, 284, 322, 324, 326, 38, 59, 157, 207 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 24, 30, 31, 33, 35, 36, 40, 44, 52, 54, 55, 69, 71, 75, 82, 85, 106, 108, 122, 124, 126, 127, 157, 158, 163, 169, 175, 181, 187, 194, 196, 203, 205, 206, 220, 222, 226, 233, 236, 265, 285, 287, 325, 327, 329, 38, 59, 160, 210 ]
5CWE-94
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Command-line interface to inspect and execute a graph in a SavedModel. For detailed usages and examples, please refer to: https://www.tensorflow.org/guide/saved_model#cli_to_inspect_and_execute_savedmodel """ import argparse import ast import os import re import sys from absl import app # pylint: disable=unused-import import numpy as np import six from tensorflow.core.example import example_pb2 from tensorflow.core.framework import types_pb2 from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.debug.wrappers import local_cli_wrapper from tensorflow.python.eager import def_function from tensorflow.python.eager import function as defun from tensorflow.python.framework import meta_graph as meta_graph_lib from tensorflow.python.framework import ops as ops_lib from tensorflow.python.framework import tensor_spec from tensorflow.python.lib.io import file_io from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import load from tensorflow.python.saved_model import loader from tensorflow.python.saved_model import save from tensorflow.python.saved_model import signature_constants from tensorflow.python.tools import saved_model_aot_compile from tensorflow.python.tools import saved_model_utils from tensorflow.python.tpu import tpu from tensorflow.python.util.compat import collections_abc _XLA_DEBUG_OPTIONS_URL = ( 'https://github.com/tensorflow/tensorflow/blob/master/' 'tensorflow/compiler/xla/debug_options_flags.cc') # Set of ops to denylist. _OP_DENYLIST = set(['WriteFile', 'ReadFile', 'PrintV2']) def _show_tag_sets(saved_model_dir): """Prints the tag-sets stored in SavedModel directory. Prints all the tag-sets for MetaGraphs stored in SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect. """ tag_sets = saved_model_utils.get_saved_model_tag_sets(saved_model_dir) print('The given SavedModel contains the following tag-sets:') for tag_set in sorted(tag_sets): print('%r' % ', '.join(sorted(tag_set))) def _show_signature_def_map_keys(saved_model_dir, tag_set): """Prints the keys for each SignatureDef in the SignatureDef map. Prints the list of SignatureDef keys from the SignatureDef map specified by the given tag-set and SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect. tag_set: Group of tag(s) of the MetaGraphDef to get SignatureDef map from, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. """ signature_def_map = get_signature_def_map(saved_model_dir, tag_set) print('The given SavedModel MetaGraphDef contains SignatureDefs with the ' 'following keys:') for signature_def_key in sorted(signature_def_map.keys()): print('SignatureDef key: \"%s\"' % signature_def_key) def _get_inputs_tensor_info_from_meta_graph_def(meta_graph_def, signature_def_key): """Gets TensorInfo for all inputs of the SignatureDef. Returns a dictionary that maps each input key to its TensorInfo for the given signature_def_key in the meta_graph_def Args: meta_graph_def: MetaGraphDef protocol buffer with the SignatureDef map to look up SignatureDef key. signature_def_key: A SignatureDef key string. Returns: A dictionary that maps input tensor keys to TensorInfos. Raises: ValueError if `signature_def_key` is not found in the MetaGraphDef. """ if signature_def_key not in meta_graph_def.signature_def: raise ValueError( f'Could not find signature "{signature_def_key}". Please choose from: ' f'{", ".join(meta_graph_def.signature_def.keys())}') return meta_graph_def.signature_def[signature_def_key].inputs def _get_outputs_tensor_info_from_meta_graph_def(meta_graph_def, signature_def_key): """Gets TensorInfos for all outputs of the SignatureDef. Returns a dictionary that maps each output key to its TensorInfo for the given signature_def_key in the meta_graph_def. Args: meta_graph_def: MetaGraphDef protocol buffer with the SignatureDefmap to look up signature_def_key. signature_def_key: A SignatureDef key string. Returns: A dictionary that maps output tensor keys to TensorInfos. """ return meta_graph_def.signature_def[signature_def_key].outputs def _show_inputs_outputs(saved_model_dir, tag_set, signature_def_key, indent=0): """Prints input and output TensorInfos. Prints the details of input and output TensorInfos for the SignatureDef mapped by the given signature_def_key. Args: saved_model_dir: Directory containing the SavedModel to inspect. tag_set: Group of tag(s) of the MetaGraphDef, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. signature_def_key: A SignatureDef key string. indent: How far (in increments of 2 spaces) to indent each line of output. """ meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) inputs_tensor_info = _get_inputs_tensor_info_from_meta_graph_def( meta_graph_def, signature_def_key) outputs_tensor_info = _get_outputs_tensor_info_from_meta_graph_def( meta_graph_def, signature_def_key) indent_str = ' ' * indent def in_print(s): print(indent_str + s) in_print('The given SavedModel SignatureDef contains the following input(s):') for input_key, input_tensor in sorted(inputs_tensor_info.items()): in_print(' inputs[\'%s\'] tensor_info:' % input_key) _print_tensor_info(input_tensor, indent+1) in_print('The given SavedModel SignatureDef contains the following ' 'output(s):') for output_key, output_tensor in sorted(outputs_tensor_info.items()): in_print(' outputs[\'%s\'] tensor_info:' % output_key) _print_tensor_info(output_tensor, indent+1) in_print('Method name is: %s' % meta_graph_def.signature_def[signature_def_key].method_name) def _show_defined_functions(saved_model_dir): """Prints the callable concrete and polymorphic functions of the Saved Model. Args: saved_model_dir: Directory containing the SavedModel to inspect. """ meta_graphs = saved_model_utils.read_saved_model(saved_model_dir).meta_graphs has_object_graph_def = False for meta_graph_def in meta_graphs: has_object_graph_def |= meta_graph_def.HasField('object_graph_def') if not has_object_graph_def: return with ops_lib.Graph().as_default(): trackable_object = load.load(saved_model_dir) print('\nConcrete Functions:', end='') children = list( save._AugmentedGraphView(trackable_object) # pylint: disable=protected-access .list_children(trackable_object)) children = sorted(children, key=lambda x: x.name) for name, child in children: concrete_functions = [] if isinstance(child, defun.ConcreteFunction): concrete_functions.append(child) elif isinstance(child, def_function.Function): concrete_functions.extend( child._list_all_concrete_functions_for_serialization()) # pylint: disable=protected-access else: continue print('\n Function Name: \'%s\'' % name) concrete_functions = sorted(concrete_functions, key=lambda x: x.name) for index, concrete_function in enumerate(concrete_functions, 1): args, kwargs = None, None if concrete_function.structured_input_signature: args, kwargs = concrete_function.structured_input_signature elif concrete_function._arg_keywords: # pylint: disable=protected-access # For pure ConcreteFunctions we might have nothing better than # _arg_keywords. args = concrete_function._arg_keywords # pylint: disable=protected-access if args: print(' Option #%d' % index) print(' Callable with:') _print_args(args, indent=4) if kwargs: _print_args(kwargs, 'Named Argument', indent=4) def _print_args(arguments, argument_type='Argument', indent=0): """Formats and prints the argument of the concrete functions defined in the model. Args: arguments: Arguments to format print. argument_type: Type of arguments. indent: How far (in increments of 2 spaces) to indent each line of output. """ indent_str = ' ' * indent def _maybe_add_quotes(value): is_quotes = '\'' * isinstance(value, str) return is_quotes + str(value) + is_quotes def in_print(s, end='\n'): print(indent_str + s, end=end) for index, element in enumerate(arguments, 1): if indent == 4: in_print('%s #%d' % (argument_type, index)) if isinstance(element, six.string_types): in_print(' %s' % element) elif isinstance(element, tensor_spec.TensorSpec): print((indent + 1) * ' ' + '%s: %s' % (element.name, repr(element))) elif (isinstance(element, collections_abc.Iterable) and not isinstance(element, dict)): in_print(' DType: %s' % type(element).__name__) in_print(' Value: [', end='') for value in element: print('%s' % _maybe_add_quotes(value), end=', ') print('\b\b]') elif isinstance(element, dict): in_print(' DType: %s' % type(element).__name__) in_print(' Value: {', end='') for (key, value) in element.items(): print('\'%s\': %s' % (str(key), _maybe_add_quotes(value)), end=', ') print('\b\b}') else: in_print(' DType: %s' % type(element).__name__) in_print(' Value: %s' % str(element)) def _print_tensor_info(tensor_info, indent=0): """Prints details of the given tensor_info. Args: tensor_info: TensorInfo object to be printed. indent: How far (in increments of 2 spaces) to indent each line output """ indent_str = ' ' * indent def in_print(s): print(indent_str + s) in_print(' dtype: ' + {value: key for (key, value) in types_pb2.DataType.items()}[tensor_info.dtype]) # Display shape as tuple. if tensor_info.tensor_shape.unknown_rank: shape = 'unknown_rank' else: dims = [str(dim.size) for dim in tensor_info.tensor_shape.dim] shape = ', '.join(dims) shape = '(' + shape + ')' in_print(' shape: ' + shape) in_print(' name: ' + tensor_info.name) def _show_all(saved_model_dir): """Prints tag-set, SignatureDef and Inputs/Outputs information in SavedModel. Prints all tag-set, SignatureDef and Inputs/Outputs information stored in SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect. """ tag_sets = saved_model_utils.get_saved_model_tag_sets(saved_model_dir) for tag_set in sorted(tag_sets): print("\nMetaGraphDef with tag-set: '%s' " "contains the following SignatureDefs:" % ', '.join(tag_set)) tag_set = ','.join(tag_set) signature_def_map = get_signature_def_map(saved_model_dir, tag_set) for signature_def_key in sorted(signature_def_map.keys()): print('\nsignature_def[\'' + signature_def_key + '\']:') _show_inputs_outputs(saved_model_dir, tag_set, signature_def_key, indent=1) _show_defined_functions(saved_model_dir) def get_meta_graph_def(saved_model_dir, tag_set): """DEPRECATED: Use saved_model_utils.get_meta_graph_def instead. Gets MetaGraphDef from SavedModel. Returns the MetaGraphDef for the given tag-set and SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect or execute. tag_set: Group of tag(s) of the MetaGraphDef to load, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. Raises: RuntimeError: An error when the given tag-set does not exist in the SavedModel. Returns: A MetaGraphDef corresponding to the tag-set. """ return saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) def get_signature_def_map(saved_model_dir, tag_set): """Gets SignatureDef map from a MetaGraphDef in a SavedModel. Returns the SignatureDef map for the given tag-set in the SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect or execute. tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. Returns: A SignatureDef map that maps from string keys to SignatureDefs. """ meta_graph = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) return meta_graph.signature_def def scan_meta_graph_def(meta_graph_def): """Scans meta_graph_def and reports if there are ops on denylist. Print ops if they are on black list, or print success if no denylisted ops found. Args: meta_graph_def: MetaGraphDef protocol buffer. """ all_ops_set = set( meta_graph_lib.ops_used_by_graph_def(meta_graph_def.graph_def)) denylisted_ops = _OP_DENYLIST & all_ops_set if denylisted_ops: # TODO(yifeif): print more warnings print( 'MetaGraph with tag set %s contains the following denylisted ops:' % meta_graph_def.meta_info_def.tags, denylisted_ops) else: print('MetaGraph with tag set %s does not contain denylisted ops.' % meta_graph_def.meta_info_def.tags) def run_saved_model_with_feed_dict(saved_model_dir, tag_set, signature_def_key, input_tensor_key_feed_dict, outdir, overwrite_flag, worker=None, init_tpu=False, use_tfrt=False, tf_debug=False): """Runs SavedModel and fetch all outputs. Runs the input dictionary through the MetaGraphDef within a SavedModel specified by the given tag_set and SignatureDef. Also save the outputs to file if outdir is not None. Args: saved_model_dir: Directory containing the SavedModel to execute. tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. signature_def_key: A SignatureDef key string. input_tensor_key_feed_dict: A dictionary maps input keys to numpy ndarrays. outdir: A directory to save the outputs to. If the directory doesn't exist, it will be created. overwrite_flag: A boolean flag to allow overwrite output file if file with the same name exists. worker: If provided, the session will be run on the worker. Valid worker specification is a bns or gRPC path. init_tpu: If true, the TPU system will be initialized after the session is created. use_tfrt: If true, TFRT session will be used. tf_debug: A boolean flag to use TensorFlow Debugger (TFDBG) to observe the intermediate Tensor values and runtime GraphDefs while running the SavedModel. Raises: ValueError: When any of the input tensor keys is not valid. RuntimeError: An error when output file already exists and overwrite is not enabled. """ # Get a list of output tensor names. meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) # Re-create feed_dict based on input tensor name instead of key as session.run # uses tensor name. inputs_tensor_info = _get_inputs_tensor_info_from_meta_graph_def( meta_graph_def, signature_def_key) # Check if input tensor keys are valid. for input_key_name in input_tensor_key_feed_dict.keys(): if input_key_name not in inputs_tensor_info: raise ValueError( '"%s" is not a valid input key. Please choose from %s, or use ' '--show option.' % (input_key_name, '"' + '", "'.join(inputs_tensor_info.keys()) + '"')) inputs_feed_dict = { inputs_tensor_info[key].name: tensor for key, tensor in input_tensor_key_feed_dict.items() } # Get outputs outputs_tensor_info = _get_outputs_tensor_info_from_meta_graph_def( meta_graph_def, signature_def_key) # Sort to preserve order because we need to go from value to key later. output_tensor_keys_sorted = sorted(outputs_tensor_info.keys()) output_tensor_names_sorted = [ outputs_tensor_info[tensor_key].name for tensor_key in output_tensor_keys_sorted ] config = None if use_tfrt: logging.info('Using TFRT session.') config = config_pb2.ConfigProto( experimental=config_pb2.ConfigProto.Experimental(use_tfrt=True)) with session.Session(worker, graph=ops_lib.Graph(), config=config) as sess: if init_tpu: print('Initializing TPU System ...') # This is needed for freshly started worker, or if the job # restarts after a preemption. sess.run(tpu.initialize_system()) loader.load(sess, tag_set.split(','), saved_model_dir) if tf_debug: sess = local_cli_wrapper.LocalCLIDebugWrapperSession(sess) outputs = sess.run(output_tensor_names_sorted, feed_dict=inputs_feed_dict) for i, output in enumerate(outputs): output_tensor_key = output_tensor_keys_sorted[i] print('Result for output key %s:\n%s' % (output_tensor_key, output)) # Only save if outdir is specified. if outdir: # Create directory if outdir does not exist if not os.path.isdir(outdir): os.makedirs(outdir) output_full_path = os.path.join(outdir, output_tensor_key + '.npy') # If overwrite not enabled and file already exist, error out if not overwrite_flag and os.path.exists(output_full_path): raise RuntimeError( 'Output file %s already exists. Add \"--overwrite\" to overwrite' ' the existing output files.' % output_full_path) np.save(output_full_path, output) print('Output %s is saved to %s' % (output_tensor_key, output_full_path)) def preprocess_inputs_arg_string(inputs_str): """Parses input arg into dictionary that maps input to file/variable tuple. Parses input string in the format of, for example, "input1=filename1[variable_name1],input2=filename2" into a dictionary looks like {'input_key1': (filename1, variable_name1), 'input_key2': (file2, None)} , which maps input keys to a tuple of file name and variable name(None if empty). Args: inputs_str: A string that specified where to load inputs. Inputs are separated by semicolons. * For each input key: '<input_key>=<filename>' or '<input_key>=<filename>[<variable_name>]' * The optional 'variable_name' key will be set to None if not specified. Returns: A dictionary that maps input keys to a tuple of file name and variable name. Raises: RuntimeError: An error when the given input string is in a bad format. """ input_dict = {} inputs_raw = inputs_str.split(';') for input_raw in filter(bool, inputs_raw): # skip empty strings # Format of input=filename[variable_name]' match = re.match(r'([^=]+)=([^\[\]]+)\[([^\[\]]+)\]$', input_raw) if match: input_dict[match.group(1)] = match.group(2), match.group(3) else: # Format of input=filename' match = re.match(r'([^=]+)=([^\[\]]+)$', input_raw) if match: input_dict[match.group(1)] = match.group(2), None else: raise RuntimeError( '--inputs "%s" format is incorrect. Please follow' '"<input_key>=<filename>", or' '"<input_key>=<filename>[<variable_name>]"' % input_raw) return input_dict def preprocess_input_exprs_arg_string(input_exprs_str, safe=True): """Parses input arg into dictionary that maps input key to python expression. Parses input string in the format of 'input_key=<python expression>' into a dictionary that maps each input_key to its python expression. Args: input_exprs_str: A string that specifies python expression for input keys. Each input is separated by semicolon. For each input key: 'input_key=<python expression>' safe: Whether to evaluate the python expression as literals or allow arbitrary calls (e.g. numpy usage). Returns: A dictionary that maps input keys to their values. Raises: RuntimeError: An error when the given input string is in a bad format. """ input_dict = {} for input_raw in filter(bool, input_exprs_str.split(';')): if '=' not in input_exprs_str: raise RuntimeError('--input_exprs "%s" format is incorrect. Please follow' '"<input_key>=<python expression>"' % input_exprs_str) input_key, expr = input_raw.split('=', 1) if safe: try: input_dict[input_key] = ast.literal_eval(expr) except: raise RuntimeError( f'Expression "{expr}" is not a valid python literal.') else: # ast.literal_eval does not work with numpy expressions input_dict[input_key] = eval(expr) # pylint: disable=eval-used return input_dict def preprocess_input_examples_arg_string(input_examples_str): """Parses input into dict that maps input keys to lists of tf.Example. Parses input string in the format of 'input_key1=[{feature_name: feature_list}];input_key2=[{feature_name:feature_list}];' into a dictionary that maps each input_key to its list of serialized tf.Example. Args: input_examples_str: A string that specifies a list of dictionaries of feature_names and their feature_lists for each input. Each input is separated by semicolon. For each input key: 'input=[{feature_name1: feature_list1, feature_name2:feature_list2}]' items in feature_list can be the type of float, int, long or str. Returns: A dictionary that maps input keys to lists of serialized tf.Example. Raises: ValueError: An error when the given tf.Example is not a list. """ input_dict = preprocess_input_exprs_arg_string(input_examples_str) for input_key, example_list in input_dict.items(): if not isinstance(example_list, list): raise ValueError( 'tf.Example input must be a list of dictionaries, but "%s" is %s' % (example_list, type(example_list))) input_dict[input_key] = [ _create_example_string(example) for example in example_list ] return input_dict def _create_example_string(example_dict): """Create a serialized tf.example from feature dictionary.""" example = example_pb2.Example() for feature_name, feature_list in example_dict.items(): if not isinstance(feature_list, list): raise ValueError('feature value must be a list, but %s: "%s" is %s' % (feature_name, feature_list, type(feature_list))) if isinstance(feature_list[0], float): example.features.feature[feature_name].float_list.value.extend( feature_list) elif isinstance(feature_list[0], str): example.features.feature[feature_name].bytes_list.value.extend( [f.encode('utf8') for f in feature_list]) elif isinstance(feature_list[0], bytes): example.features.feature[feature_name].bytes_list.value.extend( feature_list) elif isinstance(feature_list[0], six.integer_types): example.features.feature[feature_name].int64_list.value.extend( feature_list) else: raise ValueError( 'Type %s for value %s is not supported for tf.train.Feature.' % (type(feature_list[0]), feature_list[0])) return example.SerializeToString() def load_inputs_from_input_arg_string(inputs_str, input_exprs_str, input_examples_str): """Parses input arg strings and create inputs feed_dict. Parses '--inputs' string for inputs to be loaded from file, and parses '--input_exprs' string for inputs to be evaluated from python expression. '--input_examples' string for inputs to be created from tf.example feature dictionary list. Args: inputs_str: A string that specified where to load inputs. Each input is separated by semicolon. * For each input key: '<input_key>=<filename>' or '<input_key>=<filename>[<variable_name>]' * The optional 'variable_name' key will be set to None if not specified. * File specified by 'filename' will be loaded using numpy.load. Inputs can be loaded from only .npy, .npz or pickle files. * The "[variable_name]" key is optional depending on the input file type as descripted in more details below. When loading from a npy file, which always contains a numpy ndarray, the content will be directly assigned to the specified input tensor. If a variable_name is specified, it will be ignored and a warning will be issued. When loading from a npz zip file, user can specify which variable within the zip file to load for the input tensor inside the square brackets. If nothing is specified, this function will check that only one file is included in the zip and load it for the specified input tensor. When loading from a pickle file, if no variable_name is specified in the square brackets, whatever that is inside the pickle file will be passed to the specified input tensor, else SavedModel CLI will assume a dictionary is stored in the pickle file and the value corresponding to the variable_name will be used. input_exprs_str: A string that specifies python expressions for inputs. * In the format of: '<input_key>=<python expression>'. * numpy module is available as np. input_examples_str: A string that specifies tf.Example with dictionary. * In the format of: '<input_key>=<[{feature:value list}]>' Returns: A dictionary that maps input tensor keys to numpy ndarrays. Raises: RuntimeError: An error when a key is specified, but the input file contains multiple numpy ndarrays, none of which matches the given key. RuntimeError: An error when no key is specified, but the input file contains more than one numpy ndarrays. """ tensor_key_feed_dict = {} inputs = preprocess_inputs_arg_string(inputs_str) input_exprs = preprocess_input_exprs_arg_string(input_exprs_str, safe=False) input_examples = preprocess_input_examples_arg_string(input_examples_str) for input_tensor_key, (filename, variable_name) in inputs.items(): data = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # pylint: disable=unexpected-keyword-arg # When a variable_name key is specified for the input file if variable_name: # if file contains a single ndarray, ignore the input name if isinstance(data, np.ndarray): logging.warn( 'Input file %s contains a single ndarray. Name key \"%s\" ignored.' % (filename, variable_name)) tensor_key_feed_dict[input_tensor_key] = data else: if variable_name in data: tensor_key_feed_dict[input_tensor_key] = data[variable_name] else: raise RuntimeError( 'Input file %s does not contain variable with name \"%s\".' % (filename, variable_name)) # When no key is specified for the input file. else: # Check if npz file only contains a single numpy ndarray. if isinstance(data, np.lib.npyio.NpzFile): variable_name_list = data.files if len(variable_name_list) != 1: raise RuntimeError( 'Input file %s contains more than one ndarrays. Please specify ' 'the name of ndarray to use.' % filename) tensor_key_feed_dict[input_tensor_key] = data[variable_name_list[0]] else: tensor_key_feed_dict[input_tensor_key] = data # When input is a python expression: for input_tensor_key, py_expr_evaluated in input_exprs.items(): if input_tensor_key in tensor_key_feed_dict: logging.warn( 'input_key %s has been specified with both --inputs and --input_exprs' ' options. Value in --input_exprs will be used.' % input_tensor_key) tensor_key_feed_dict[input_tensor_key] = py_expr_evaluated # When input is a tf.Example: for input_tensor_key, example in input_examples.items(): if input_tensor_key in tensor_key_feed_dict: logging.warn( 'input_key %s has been specified in multiple options. Value in ' '--input_examples will be used.' % input_tensor_key) tensor_key_feed_dict[input_tensor_key] = example return tensor_key_feed_dict def show(args): """Function triggered by show command. Args: args: A namespace parsed from command line. """ # If all tag is specified, display all information. if args.all: _show_all(args.dir) else: # If no tag is specified, display all tag_set, if no signature_def key is # specified, display all SignatureDef keys, else show input output tensor # information corresponding to the given SignatureDef key if args.tag_set is None: _show_tag_sets(args.dir) else: if args.signature_def is None: _show_signature_def_map_keys(args.dir, args.tag_set) else: _show_inputs_outputs(args.dir, args.tag_set, args.signature_def) def run(args): """Function triggered by run command. Args: args: A namespace parsed from command line. Raises: AttributeError: An error when neither --inputs nor --input_exprs is passed to run command. """ if not args.inputs and not args.input_exprs and not args.input_examples: raise AttributeError( 'At least one of --inputs, --input_exprs or --input_examples must be ' 'required') tensor_key_feed_dict = load_inputs_from_input_arg_string( args.inputs, args.input_exprs, args.input_examples) run_saved_model_with_feed_dict( args.dir, args.tag_set, args.signature_def, tensor_key_feed_dict, args.outdir, args.overwrite, worker=args.worker, init_tpu=args.init_tpu, use_tfrt=args.use_tfrt, tf_debug=args.tf_debug) def scan(args): """Function triggered by scan command. Args: args: A namespace parsed from command line. """ if args.tag_set: scan_meta_graph_def( saved_model_utils.get_meta_graph_def(args.dir, args.tag_set)) else: saved_model = saved_model_utils.read_saved_model(args.dir) for meta_graph_def in saved_model.meta_graphs: scan_meta_graph_def(meta_graph_def) def convert_with_tensorrt(args): """Function triggered by 'convert tensorrt' command. Args: args: A namespace parsed from command line. """ # Import here instead of at top, because this will crash if TensorRT is # not installed from tensorflow.python.compiler.tensorrt import trt_convert as trt # pylint: disable=g-import-not-at-top if not args.convert_tf1_model: params = trt.DEFAULT_TRT_CONVERSION_PARAMS._replace( max_workspace_size_bytes=args.max_workspace_size_bytes, precision_mode=args.precision_mode, minimum_segment_size=args.minimum_segment_size) converter = trt.TrtGraphConverterV2( input_saved_model_dir=args.dir, input_saved_model_tags=args.tag_set.split(','), **params._asdict()) try: converter.convert() except Exception as e: raise RuntimeError( '{}. Try passing "--convert_tf1_model=True".'.format(e)) converter.save(output_saved_model_dir=args.output_dir) else: trt.create_inference_graph( None, None, max_batch_size=1, max_workspace_size_bytes=args.max_workspace_size_bytes, precision_mode=args.precision_mode, minimum_segment_size=args.minimum_segment_size, is_dynamic_op=True, input_saved_model_dir=args.dir, input_saved_model_tags=args.tag_set.split(','), output_saved_model_dir=args.output_dir) def freeze_model(args): """Function triggered by freeze_model command. Args: args: A namespace parsed from command line. """ checkpoint_path = ( args.checkpoint_path or os.path.join(args.dir, 'variables/variables')) if not args.variables_to_feed: variables_to_feed = [] elif args.variables_to_feed.lower() == 'all': variables_to_feed = None # We will identify them after. else: variables_to_feed = args.variables_to_feed.split(',') saved_model_aot_compile.freeze_model( checkpoint_path=checkpoint_path, meta_graph_def=saved_model_utils.get_meta_graph_def( args.dir, args.tag_set), signature_def_key=args.signature_def_key, variables_to_feed=variables_to_feed, output_prefix=args.output_prefix) def aot_compile_cpu(args): """Function triggered by aot_compile_cpu command. Args: args: A namespace parsed from command line. """ checkpoint_path = ( args.checkpoint_path or os.path.join(args.dir, 'variables/variables')) if not args.variables_to_feed: variables_to_feed = [] elif args.variables_to_feed.lower() == 'all': variables_to_feed = None # We will identify them after. else: variables_to_feed = args.variables_to_feed.split(',') saved_model_aot_compile.aot_compile_cpu_meta_graph_def( checkpoint_path=checkpoint_path, meta_graph_def=saved_model_utils.get_meta_graph_def( args.dir, args.tag_set), signature_def_key=args.signature_def_key, variables_to_feed=variables_to_feed, output_prefix=args.output_prefix, target_triple=args.target_triple, target_cpu=args.target_cpu, cpp_class=args.cpp_class, multithreading=args.multithreading.lower() not in ('f', 'false', '0')) def add_show_subparser(subparsers): """Add parser for `show`.""" show_msg = ( 'Usage examples:\n' 'To show all tag-sets in a SavedModel:\n' '$saved_model_cli show --dir /tmp/saved_model\n\n' 'To show all available SignatureDef keys in a ' 'MetaGraphDef specified by its tag-set:\n' '$saved_model_cli show --dir /tmp/saved_model --tag_set serve\n\n' 'For a MetaGraphDef with multiple tags in the tag-set, all tags must be ' 'passed in, separated by \';\':\n' '$saved_model_cli show --dir /tmp/saved_model --tag_set serve,gpu\n\n' 'To show all inputs and outputs TensorInfo for a specific' ' SignatureDef specified by the SignatureDef key in a' ' MetaGraph.\n' '$saved_model_cli show --dir /tmp/saved_model --tag_set serve' ' --signature_def serving_default\n\n' 'To show all available information in the SavedModel:\n' '$saved_model_cli show --dir /tmp/saved_model --all') parser_show = subparsers.add_parser( 'show', description=show_msg, formatter_class=argparse.RawTextHelpFormatter) parser_show.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to inspect') parser_show.add_argument( '--all', action='store_true', help='if set, will output all information in given SavedModel') parser_show.add_argument( '--tag_set', type=str, default=None, help='tag-set of graph in SavedModel to show, separated by \',\'') parser_show.add_argument( '--signature_def', type=str, default=None, metavar='SIGNATURE_DEF_KEY', help='key of SignatureDef to display input(s) and output(s) for') parser_show.set_defaults(func=show) def add_run_subparser(subparsers): """Add parser for `run`.""" run_msg = ('Usage example:\n' 'To run input tensors from files through a MetaGraphDef and save' ' the output tensors to files:\n' '$saved_model_cli show --dir /tmp/saved_model --tag_set serve \\\n' ' --signature_def serving_default \\\n' ' --inputs input1_key=/tmp/124.npz[x],input2_key=/tmp/123.npy ' '\\\n' ' --input_exprs \'input3_key=np.ones(2)\' \\\n' ' --input_examples ' '\'input4_key=[{"id":[26],"weights":[0.5, 0.5]}]\' \\\n' ' --outdir=/out\n\n' 'For more information about input file format, please see:\n' 'https://www.tensorflow.org/guide/saved_model_cli\n') parser_run = subparsers.add_parser( 'run', description=run_msg, formatter_class=argparse.RawTextHelpFormatter) parser_run.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to execute') parser_run.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to load, separated by \',\'') parser_run.add_argument( '--signature_def', type=str, required=True, metavar='SIGNATURE_DEF_KEY', help='key of SignatureDef to run') msg = ('Loading inputs from files, in the format of \'<input_key>=<filename>,' ' or \'<input_key>=<filename>[<variable_name>]\', separated by \';\'.' ' The file format can only be from .npy, .npz or pickle.') parser_run.add_argument('--inputs', type=str, default='', help=msg) msg = ('Specifying inputs by python expressions, in the format of' ' "<input_key>=\'<python expression>\'", separated by \';\'. ' 'numpy module is available as \'np\'. Please note that the expression ' 'will be evaluated as-is, and is susceptible to code injection. ' 'When this is set, the value will override duplicate input keys from ' '--inputs option.') parser_run.add_argument('--input_exprs', type=str, default='', help=msg) msg = ( 'Specifying tf.Example inputs as list of dictionaries. For example: ' '<input_key>=[{feature0:value_list,feature1:value_list}]. Use ";" to ' 'separate input keys. Will override duplicate input keys from --inputs ' 'and --input_exprs option.') parser_run.add_argument('--input_examples', type=str, default='', help=msg) parser_run.add_argument( '--outdir', type=str, default=None, help='if specified, output tensor(s) will be saved to given directory') parser_run.add_argument( '--overwrite', action='store_true', help='if set, output file will be overwritten if it already exists.') parser_run.add_argument( '--tf_debug', action='store_true', help='if set, will use TensorFlow Debugger (tfdbg) to watch the ' 'intermediate Tensors and runtime GraphDefs while running the ' 'SavedModel.') parser_run.add_argument( '--worker', type=str, default=None, help='if specified, a Session will be run on the worker. ' 'Valid worker specification is a bns or gRPC path.') parser_run.add_argument( '--init_tpu', action='store_true', default=None, help='if specified, tpu.initialize_system will be called on the Session. ' 'This option should be only used if the worker is a TPU job.') parser_run.add_argument( '--use_tfrt', action='store_true', default=None, help='if specified, TFRT session will be used, instead of TF1 session.') parser_run.set_defaults(func=run) def add_scan_subparser(subparsers): """Add parser for `scan`.""" scan_msg = ('Usage example:\n' 'To scan for denylisted ops in SavedModel:\n' '$saved_model_cli scan --dir /tmp/saved_model\n' 'To scan a specific MetaGraph, pass in --tag_set\n') parser_scan = subparsers.add_parser( 'scan', description=scan_msg, formatter_class=argparse.RawTextHelpFormatter) parser_scan.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to execute') parser_scan.add_argument( '--tag_set', type=str, help='tag-set of graph in SavedModel to scan, separated by \',\'') parser_scan.set_defaults(func=scan) def add_convert_subparser(subparsers): """Add parser for `convert`.""" convert_msg = ('Usage example:\n' 'To convert the SavedModel to one that have TensorRT ops:\n' '$saved_model_cli convert \\\n' ' --dir /tmp/saved_model \\\n' ' --tag_set serve \\\n' ' --output_dir /tmp/saved_model_trt \\\n' ' tensorrt \n') parser_convert = subparsers.add_parser( 'convert', description=convert_msg, formatter_class=argparse.RawTextHelpFormatter) parser_convert.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to convert') parser_convert.add_argument( '--output_dir', type=str, required=True, help='output directory for the converted SavedModel') parser_convert.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to convert, separated by \',\'') convert_subparsers = parser_convert.add_subparsers( title='conversion methods', description='valid conversion methods', help='the conversion to run with the SavedModel') parser_convert_with_tensorrt = convert_subparsers.add_parser( 'tensorrt', description='Convert the SavedModel with Tensorflow-TensorRT integration', formatter_class=argparse.RawTextHelpFormatter) parser_convert_with_tensorrt.add_argument( '--max_workspace_size_bytes', type=int, default=2 << 20, help=('the maximum GPU temporary memory which the TRT engine can use at ' 'execution time')) parser_convert_with_tensorrt.add_argument( '--precision_mode', type=str, default='FP32', help='one of FP32, FP16 and INT8') parser_convert_with_tensorrt.add_argument( '--minimum_segment_size', type=int, default=3, help=('the minimum number of nodes required for a subgraph to be replaced' 'in a TensorRT node')) parser_convert_with_tensorrt.add_argument( '--convert_tf1_model', type=bool, default=False, help='support TRT conversion for TF1 models') parser_convert_with_tensorrt.set_defaults(func=convert_with_tensorrt) def _parse_common_freeze_and_aot(parser_compile): """Parse arguments shared by freeze model and aot_compile.""" parser_compile.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to convert') parser_compile.add_argument( '--output_prefix', type=str, required=True, help=('output directory + filename prefix for the resulting header(s) ' 'and object file(s)')) parser_compile.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to convert, separated by \',\'') parser_compile.add_argument( '--signature_def_key', type=str, default=signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, help=('signature_def key to use. ' 'default: DEFAULT_SERVING_SIGNATURE_DEF_KEY')) parser_compile.add_argument( '--checkpoint_path', type=str, default=None, help='Custom checkpoint to use (default: use the SavedModel variables)') parser_compile.add_argument( '--variables_to_feed', type=str, default='', help=('The names of variables that will be fed into the network. ' 'Options are: empty (default; all variables are frozen, none may ' 'be fed), \'all\' (all variables may be fed), or a ' 'comma-delimited list of names of variables that may be fed. In ' 'the last case, the non-fed variables will be frozen in the graph.' '**NOTE** Any variables passed to `variables_to_feed` *must be set ' 'by the user*. These variables will NOT be frozen and their ' 'values will be uninitialized in the compiled object ' '(this applies to all input arguments from the signature as ' 'well).')) def add_freeze_model_subparser(subparsers): """Add parser for `freeze_model`.""" compile_msg = '\n'.join( ['Usage example:', 'To freeze a SavedModel in preparation for tfcompile:', '$saved_model_cli freeze_model \\', ' --dir /tmp/saved_model \\', ' --tag_set serve \\', ' --output_prefix /tmp/saved_model_xla_aot', ]) parser_compile = subparsers.add_parser( 'freeze_model', description=compile_msg, formatter_class=argparse.RawTextHelpFormatter) _parse_common_freeze_and_aot(parser_compile) parser_compile.set_defaults(func=freeze_model) def add_aot_compile_cpu_subparser(subparsers): """Add parser for `aot_compile_cpu`.""" compile_msg = '\n'.join( ['Usage example:', 'To compile a SavedModel signature via (CPU) XLA AOT:', '$saved_model_cli aot_compile_cpu \\', ' --dir /tmp/saved_model \\', ' --tag_set serve \\', ' --output_dir /tmp/saved_model_xla_aot', '', '', 'Note: Additional XLA compilation options are available by setting the ', 'XLA_FLAGS environment variable. See the XLA debug options flags for ', 'all the options: ', ' {}'.format(_XLA_DEBUG_OPTIONS_URL), '', 'For example, to disable XLA fast math when compiling:', '', 'XLA_FLAGS="--xla_cpu_enable_fast_math=false" $saved_model_cli ' 'aot_compile_cpu ...', '', 'Some possibly useful flags:', ' --xla_cpu_enable_fast_math=false', ' --xla_force_host_platform_device_count=<num threads>', ' (useful in conjunction with disabling multi threading)' ]) parser_compile = subparsers.add_parser( 'aot_compile_cpu', description=compile_msg, formatter_class=argparse.RawTextHelpFormatter) _parse_common_freeze_and_aot(parser_compile) parser_compile.add_argument( '--target_triple', type=str, default='x86_64-pc-linux', help=('Target triple for LLVM during AOT compilation. Examples: ' 'x86_64-none-darwin, x86_64-apple-ios, arm64-none-ios, ' 'armv7-none-android. More examples are available in tfcompile.bzl ' 'in the tensorflow codebase.')) parser_compile.add_argument( '--target_cpu', type=str, default='', help=('Target cpu name for LLVM during AOT compilation. Examples: ' 'x86_64, skylake, haswell, westmere, <empty> (unknown). For ' 'a complete list of options, run (for x86 targets): ' '`llc -march=x86 -mcpu=help`')) parser_compile.add_argument( '--cpp_class', type=str, required=True, help=('The name of the generated C++ class, wrapping the generated ' 'function. The syntax of this flag is ' '[[<optional_namespace>::],...]<class_name>. This mirrors the ' 'C++ syntax for referring to a class, where multiple namespaces ' 'may precede the class name, separated by double-colons. ' 'The class will be generated in the given namespace(s), or if no ' 'namespaces are given, within the global namespace.')) parser_compile.add_argument( '--multithreading', type=str, default='False', help=('Enable multithreading in the compiled computation. ' 'Note that if using this option, the resulting object files ' 'may have external dependencies on multithreading libraries ' 'like nsync.')) parser_compile.set_defaults(func=aot_compile_cpu) def create_parser(): """Creates a parser that parse the command line arguments. Returns: A namespace parsed from command line arguments. """ parser = argparse.ArgumentParser( description='saved_model_cli: Command-line interface for SavedModel') parser.add_argument('-v', '--version', action='version', version='0.1.0') subparsers = parser.add_subparsers( title='commands', description='valid commands', help='additional help') # show command add_show_subparser(subparsers) # run command add_run_subparser(subparsers) # scan command add_scan_subparser(subparsers) # tensorrt convert command add_convert_subparser(subparsers) # aot_compile_cpu command add_aot_compile_cpu_subparser(subparsers) # freeze_model command add_freeze_model_subparser(subparsers) return parser def main(): logging.set_verbosity(logging.INFO) parser = create_parser() args = parser.parse_args() if not hasattr(args, 'func'): parser.error('too few arguments') args.func(args) if __name__ == '__main__': sys.exit(main())
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Command-line interface to inspect and execute a graph in a SavedModel. For detailed usages and examples, please refer to: https://www.tensorflow.org/guide/saved_model#cli_to_inspect_and_execute_savedmodel """ import argparse import ast import os import re import sys from absl import app # pylint: disable=unused-import import numpy as np import six from tensorflow.core.example import example_pb2 from tensorflow.core.framework import types_pb2 from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.debug.wrappers import local_cli_wrapper from tensorflow.python.eager import def_function from tensorflow.python.eager import function as defun from tensorflow.python.framework import meta_graph as meta_graph_lib from tensorflow.python.framework import ops as ops_lib from tensorflow.python.framework import tensor_spec from tensorflow.python.lib.io import file_io from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import load from tensorflow.python.saved_model import loader from tensorflow.python.saved_model import save from tensorflow.python.saved_model import signature_constants from tensorflow.python.tools import saved_model_aot_compile from tensorflow.python.tools import saved_model_utils from tensorflow.python.tpu import tpu from tensorflow.python.util.compat import collections_abc _XLA_DEBUG_OPTIONS_URL = ( 'https://github.com/tensorflow/tensorflow/blob/master/' 'tensorflow/compiler/xla/debug_options_flags.cc') # Set of ops to denylist. _OP_DENYLIST = set(['WriteFile', 'ReadFile', 'PrintV2']) def _show_tag_sets(saved_model_dir): """Prints the tag-sets stored in SavedModel directory. Prints all the tag-sets for MetaGraphs stored in SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect. """ tag_sets = saved_model_utils.get_saved_model_tag_sets(saved_model_dir) print('The given SavedModel contains the following tag-sets:') for tag_set in sorted(tag_sets): print('%r' % ', '.join(sorted(tag_set))) def _show_signature_def_map_keys(saved_model_dir, tag_set): """Prints the keys for each SignatureDef in the SignatureDef map. Prints the list of SignatureDef keys from the SignatureDef map specified by the given tag-set and SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect. tag_set: Group of tag(s) of the MetaGraphDef to get SignatureDef map from, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. """ signature_def_map = get_signature_def_map(saved_model_dir, tag_set) print('The given SavedModel MetaGraphDef contains SignatureDefs with the ' 'following keys:') for signature_def_key in sorted(signature_def_map.keys()): print('SignatureDef key: \"%s\"' % signature_def_key) def _get_inputs_tensor_info_from_meta_graph_def(meta_graph_def, signature_def_key): """Gets TensorInfo for all inputs of the SignatureDef. Returns a dictionary that maps each input key to its TensorInfo for the given signature_def_key in the meta_graph_def Args: meta_graph_def: MetaGraphDef protocol buffer with the SignatureDef map to look up SignatureDef key. signature_def_key: A SignatureDef key string. Returns: A dictionary that maps input tensor keys to TensorInfos. Raises: ValueError if `signature_def_key` is not found in the MetaGraphDef. """ if signature_def_key not in meta_graph_def.signature_def: raise ValueError( f'Could not find signature "{signature_def_key}". Please choose from: ' f'{", ".join(meta_graph_def.signature_def.keys())}') return meta_graph_def.signature_def[signature_def_key].inputs def _get_outputs_tensor_info_from_meta_graph_def(meta_graph_def, signature_def_key): """Gets TensorInfos for all outputs of the SignatureDef. Returns a dictionary that maps each output key to its TensorInfo for the given signature_def_key in the meta_graph_def. Args: meta_graph_def: MetaGraphDef protocol buffer with the SignatureDefmap to look up signature_def_key. signature_def_key: A SignatureDef key string. Returns: A dictionary that maps output tensor keys to TensorInfos. """ return meta_graph_def.signature_def[signature_def_key].outputs def _show_inputs_outputs(saved_model_dir, tag_set, signature_def_key, indent=0): """Prints input and output TensorInfos. Prints the details of input and output TensorInfos for the SignatureDef mapped by the given signature_def_key. Args: saved_model_dir: Directory containing the SavedModel to inspect. tag_set: Group of tag(s) of the MetaGraphDef, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. signature_def_key: A SignatureDef key string. indent: How far (in increments of 2 spaces) to indent each line of output. """ meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) inputs_tensor_info = _get_inputs_tensor_info_from_meta_graph_def( meta_graph_def, signature_def_key) outputs_tensor_info = _get_outputs_tensor_info_from_meta_graph_def( meta_graph_def, signature_def_key) indent_str = ' ' * indent def in_print(s): print(indent_str + s) in_print('The given SavedModel SignatureDef contains the following input(s):') for input_key, input_tensor in sorted(inputs_tensor_info.items()): in_print(' inputs[\'%s\'] tensor_info:' % input_key) _print_tensor_info(input_tensor, indent+1) in_print('The given SavedModel SignatureDef contains the following ' 'output(s):') for output_key, output_tensor in sorted(outputs_tensor_info.items()): in_print(' outputs[\'%s\'] tensor_info:' % output_key) _print_tensor_info(output_tensor, indent+1) in_print('Method name is: %s' % meta_graph_def.signature_def[signature_def_key].method_name) def _show_defined_functions(saved_model_dir): """Prints the callable concrete and polymorphic functions of the Saved Model. Args: saved_model_dir: Directory containing the SavedModel to inspect. """ meta_graphs = saved_model_utils.read_saved_model(saved_model_dir).meta_graphs has_object_graph_def = False for meta_graph_def in meta_graphs: has_object_graph_def |= meta_graph_def.HasField('object_graph_def') if not has_object_graph_def: return with ops_lib.Graph().as_default(): trackable_object = load.load(saved_model_dir) print('\nConcrete Functions:', end='') children = list( save._AugmentedGraphView(trackable_object) # pylint: disable=protected-access .list_children(trackable_object)) children = sorted(children, key=lambda x: x.name) for name, child in children: concrete_functions = [] if isinstance(child, defun.ConcreteFunction): concrete_functions.append(child) elif isinstance(child, def_function.Function): concrete_functions.extend( child._list_all_concrete_functions_for_serialization()) # pylint: disable=protected-access else: continue print('\n Function Name: \'%s\'' % name) concrete_functions = sorted(concrete_functions, key=lambda x: x.name) for index, concrete_function in enumerate(concrete_functions, 1): args, kwargs = None, None if concrete_function.structured_input_signature: args, kwargs = concrete_function.structured_input_signature elif concrete_function._arg_keywords: # pylint: disable=protected-access # For pure ConcreteFunctions we might have nothing better than # _arg_keywords. args = concrete_function._arg_keywords # pylint: disable=protected-access if args: print(' Option #%d' % index) print(' Callable with:') _print_args(args, indent=4) if kwargs: _print_args(kwargs, 'Named Argument', indent=4) def _print_args(arguments, argument_type='Argument', indent=0): """Formats and prints the argument of the concrete functions defined in the model. Args: arguments: Arguments to format print. argument_type: Type of arguments. indent: How far (in increments of 2 spaces) to indent each line of output. """ indent_str = ' ' * indent def _maybe_add_quotes(value): is_quotes = '\'' * isinstance(value, str) return is_quotes + str(value) + is_quotes def in_print(s, end='\n'): print(indent_str + s, end=end) for index, element in enumerate(arguments, 1): if indent == 4: in_print('%s #%d' % (argument_type, index)) if isinstance(element, six.string_types): in_print(' %s' % element) elif isinstance(element, tensor_spec.TensorSpec): print((indent + 1) * ' ' + '%s: %s' % (element.name, repr(element))) elif (isinstance(element, collections_abc.Iterable) and not isinstance(element, dict)): in_print(' DType: %s' % type(element).__name__) in_print(' Value: [', end='') for value in element: print('%s' % _maybe_add_quotes(value), end=', ') print('\b\b]') elif isinstance(element, dict): in_print(' DType: %s' % type(element).__name__) in_print(' Value: {', end='') for (key, value) in element.items(): print('\'%s\': %s' % (str(key), _maybe_add_quotes(value)), end=', ') print('\b\b}') else: in_print(' DType: %s' % type(element).__name__) in_print(' Value: %s' % str(element)) def _print_tensor_info(tensor_info, indent=0): """Prints details of the given tensor_info. Args: tensor_info: TensorInfo object to be printed. indent: How far (in increments of 2 spaces) to indent each line output """ indent_str = ' ' * indent def in_print(s): print(indent_str + s) in_print(' dtype: ' + {value: key for (key, value) in types_pb2.DataType.items()}[tensor_info.dtype]) # Display shape as tuple. if tensor_info.tensor_shape.unknown_rank: shape = 'unknown_rank' else: dims = [str(dim.size) for dim in tensor_info.tensor_shape.dim] shape = ', '.join(dims) shape = '(' + shape + ')' in_print(' shape: ' + shape) in_print(' name: ' + tensor_info.name) def _show_all(saved_model_dir): """Prints tag-set, SignatureDef and Inputs/Outputs information in SavedModel. Prints all tag-set, SignatureDef and Inputs/Outputs information stored in SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect. """ tag_sets = saved_model_utils.get_saved_model_tag_sets(saved_model_dir) for tag_set in sorted(tag_sets): print("\nMetaGraphDef with tag-set: '%s' " "contains the following SignatureDefs:" % ', '.join(tag_set)) tag_set = ','.join(tag_set) signature_def_map = get_signature_def_map(saved_model_dir, tag_set) for signature_def_key in sorted(signature_def_map.keys()): print('\nsignature_def[\'' + signature_def_key + '\']:') _show_inputs_outputs(saved_model_dir, tag_set, signature_def_key, indent=1) _show_defined_functions(saved_model_dir) def get_meta_graph_def(saved_model_dir, tag_set): """DEPRECATED: Use saved_model_utils.get_meta_graph_def instead. Gets MetaGraphDef from SavedModel. Returns the MetaGraphDef for the given tag-set and SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect or execute. tag_set: Group of tag(s) of the MetaGraphDef to load, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. Raises: RuntimeError: An error when the given tag-set does not exist in the SavedModel. Returns: A MetaGraphDef corresponding to the tag-set. """ return saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) def get_signature_def_map(saved_model_dir, tag_set): """Gets SignatureDef map from a MetaGraphDef in a SavedModel. Returns the SignatureDef map for the given tag-set in the SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect or execute. tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. Returns: A SignatureDef map that maps from string keys to SignatureDefs. """ meta_graph = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) return meta_graph.signature_def def scan_meta_graph_def(meta_graph_def): """Scans meta_graph_def and reports if there are ops on denylist. Print ops if they are on black list, or print success if no denylisted ops found. Args: meta_graph_def: MetaGraphDef protocol buffer. """ all_ops_set = set( meta_graph_lib.ops_used_by_graph_def(meta_graph_def.graph_def)) denylisted_ops = _OP_DENYLIST & all_ops_set if denylisted_ops: # TODO(yifeif): print more warnings print( 'MetaGraph with tag set %s contains the following denylisted ops:' % meta_graph_def.meta_info_def.tags, denylisted_ops) else: print('MetaGraph with tag set %s does not contain denylisted ops.' % meta_graph_def.meta_info_def.tags) def run_saved_model_with_feed_dict(saved_model_dir, tag_set, signature_def_key, input_tensor_key_feed_dict, outdir, overwrite_flag, worker=None, init_tpu=False, use_tfrt=False, tf_debug=False): """Runs SavedModel and fetch all outputs. Runs the input dictionary through the MetaGraphDef within a SavedModel specified by the given tag_set and SignatureDef. Also save the outputs to file if outdir is not None. Args: saved_model_dir: Directory containing the SavedModel to execute. tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. signature_def_key: A SignatureDef key string. input_tensor_key_feed_dict: A dictionary maps input keys to numpy ndarrays. outdir: A directory to save the outputs to. If the directory doesn't exist, it will be created. overwrite_flag: A boolean flag to allow overwrite output file if file with the same name exists. worker: If provided, the session will be run on the worker. Valid worker specification is a bns or gRPC path. init_tpu: If true, the TPU system will be initialized after the session is created. use_tfrt: If true, TFRT session will be used. tf_debug: A boolean flag to use TensorFlow Debugger (TFDBG) to observe the intermediate Tensor values and runtime GraphDefs while running the SavedModel. Raises: ValueError: When any of the input tensor keys is not valid. RuntimeError: An error when output file already exists and overwrite is not enabled. """ # Get a list of output tensor names. meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) # Re-create feed_dict based on input tensor name instead of key as session.run # uses tensor name. inputs_tensor_info = _get_inputs_tensor_info_from_meta_graph_def( meta_graph_def, signature_def_key) # Check if input tensor keys are valid. for input_key_name in input_tensor_key_feed_dict.keys(): if input_key_name not in inputs_tensor_info: raise ValueError( '"%s" is not a valid input key. Please choose from %s, or use ' '--show option.' % (input_key_name, '"' + '", "'.join(inputs_tensor_info.keys()) + '"')) inputs_feed_dict = { inputs_tensor_info[key].name: tensor for key, tensor in input_tensor_key_feed_dict.items() } # Get outputs outputs_tensor_info = _get_outputs_tensor_info_from_meta_graph_def( meta_graph_def, signature_def_key) # Sort to preserve order because we need to go from value to key later. output_tensor_keys_sorted = sorted(outputs_tensor_info.keys()) output_tensor_names_sorted = [ outputs_tensor_info[tensor_key].name for tensor_key in output_tensor_keys_sorted ] config = None if use_tfrt: logging.info('Using TFRT session.') config = config_pb2.ConfigProto( experimental=config_pb2.ConfigProto.Experimental(use_tfrt=True)) with session.Session(worker, graph=ops_lib.Graph(), config=config) as sess: if init_tpu: print('Initializing TPU System ...') # This is needed for freshly started worker, or if the job # restarts after a preemption. sess.run(tpu.initialize_system()) loader.load(sess, tag_set.split(','), saved_model_dir) if tf_debug: sess = local_cli_wrapper.LocalCLIDebugWrapperSession(sess) outputs = sess.run(output_tensor_names_sorted, feed_dict=inputs_feed_dict) for i, output in enumerate(outputs): output_tensor_key = output_tensor_keys_sorted[i] print('Result for output key %s:\n%s' % (output_tensor_key, output)) # Only save if outdir is specified. if outdir: # Create directory if outdir does not exist if not os.path.isdir(outdir): os.makedirs(outdir) output_full_path = os.path.join(outdir, output_tensor_key + '.npy') # If overwrite not enabled and file already exist, error out if not overwrite_flag and os.path.exists(output_full_path): raise RuntimeError( 'Output file %s already exists. Add \"--overwrite\" to overwrite' ' the existing output files.' % output_full_path) np.save(output_full_path, output) print('Output %s is saved to %s' % (output_tensor_key, output_full_path)) def preprocess_inputs_arg_string(inputs_str): """Parses input arg into dictionary that maps input to file/variable tuple. Parses input string in the format of, for example, "input1=filename1[variable_name1],input2=filename2" into a dictionary looks like {'input_key1': (filename1, variable_name1), 'input_key2': (file2, None)} , which maps input keys to a tuple of file name and variable name(None if empty). Args: inputs_str: A string that specified where to load inputs. Inputs are separated by semicolons. * For each input key: '<input_key>=<filename>' or '<input_key>=<filename>[<variable_name>]' * The optional 'variable_name' key will be set to None if not specified. Returns: A dictionary that maps input keys to a tuple of file name and variable name. Raises: RuntimeError: An error when the given input string is in a bad format. """ input_dict = {} inputs_raw = inputs_str.split(';') for input_raw in filter(bool, inputs_raw): # skip empty strings # Format of input=filename[variable_name]' match = re.match(r'([^=]+)=([^\[\]]+)\[([^\[\]]+)\]$', input_raw) if match: input_dict[match.group(1)] = match.group(2), match.group(3) else: # Format of input=filename' match = re.match(r'([^=]+)=([^\[\]]+)$', input_raw) if match: input_dict[match.group(1)] = match.group(2), None else: raise RuntimeError( '--inputs "%s" format is incorrect. Please follow' '"<input_key>=<filename>", or' '"<input_key>=<filename>[<variable_name>]"' % input_raw) return input_dict def preprocess_input_exprs_arg_string(input_exprs_str, safe=True): """Parses input arg into dictionary that maps input key to python expression. Parses input string in the format of 'input_key=<python expression>' into a dictionary that maps each input_key to its python expression. Args: input_exprs_str: A string that specifies python expression for input keys. Each input is separated by semicolon. For each input key: 'input_key=<python expression>' safe: Whether to evaluate the python expression as literals or allow arbitrary calls (e.g. numpy usage). Returns: A dictionary that maps input keys to their values. Raises: RuntimeError: An error when the given input string is in a bad format. """ input_dict = {} for input_raw in filter(bool, input_exprs_str.split(';')): if '=' not in input_exprs_str: raise RuntimeError('--input_exprs "%s" format is incorrect. Please follow' '"<input_key>=<python expression>"' % input_exprs_str) input_key, expr = input_raw.split('=', 1) if safe: try: input_dict[input_key] = ast.literal_eval(expr) except: raise RuntimeError( f'Expression "{expr}" is not a valid python literal.') else: # ast.literal_eval does not work with numpy expressions input_dict[input_key] = eval(expr) # pylint: disable=eval-used return input_dict def preprocess_input_examples_arg_string(input_examples_str): """Parses input into dict that maps input keys to lists of tf.Example. Parses input string in the format of 'input_key1=[{feature_name: feature_list}];input_key2=[{feature_name:feature_list}];' into a dictionary that maps each input_key to its list of serialized tf.Example. Args: input_examples_str: A string that specifies a list of dictionaries of feature_names and their feature_lists for each input. Each input is separated by semicolon. For each input key: 'input=[{feature_name1: feature_list1, feature_name2:feature_list2}]' items in feature_list can be the type of float, int, long or str. Returns: A dictionary that maps input keys to lists of serialized tf.Example. Raises: ValueError: An error when the given tf.Example is not a list. """ input_dict = preprocess_input_exprs_arg_string(input_examples_str) for input_key, example_list in input_dict.items(): if not isinstance(example_list, list): raise ValueError( 'tf.Example input must be a list of dictionaries, but "%s" is %s' % (example_list, type(example_list))) input_dict[input_key] = [ _create_example_string(example) for example in example_list ] return input_dict def _create_example_string(example_dict): """Create a serialized tf.example from feature dictionary.""" example = example_pb2.Example() for feature_name, feature_list in example_dict.items(): if not isinstance(feature_list, list): raise ValueError('feature value must be a list, but %s: "%s" is %s' % (feature_name, feature_list, type(feature_list))) if isinstance(feature_list[0], float): example.features.feature[feature_name].float_list.value.extend( feature_list) elif isinstance(feature_list[0], str): example.features.feature[feature_name].bytes_list.value.extend( [f.encode('utf8') for f in feature_list]) elif isinstance(feature_list[0], bytes): example.features.feature[feature_name].bytes_list.value.extend( feature_list) elif isinstance(feature_list[0], six.integer_types): example.features.feature[feature_name].int64_list.value.extend( feature_list) else: raise ValueError( 'Type %s for value %s is not supported for tf.train.Feature.' % (type(feature_list[0]), feature_list[0])) return example.SerializeToString() def load_inputs_from_input_arg_string(inputs_str, input_exprs_str, input_examples_str): """Parses input arg strings and create inputs feed_dict. Parses '--inputs' string for inputs to be loaded from file, and parses '--input_exprs' string for inputs to be evaluated from python expression. '--input_examples' string for inputs to be created from tf.example feature dictionary list. Args: inputs_str: A string that specified where to load inputs. Each input is separated by semicolon. * For each input key: '<input_key>=<filename>' or '<input_key>=<filename>[<variable_name>]' * The optional 'variable_name' key will be set to None if not specified. * File specified by 'filename' will be loaded using numpy.load. Inputs can be loaded from only .npy, .npz or pickle files. * The "[variable_name]" key is optional depending on the input file type as descripted in more details below. When loading from a npy file, which always contains a numpy ndarray, the content will be directly assigned to the specified input tensor. If a variable_name is specified, it will be ignored and a warning will be issued. When loading from a npz zip file, user can specify which variable within the zip file to load for the input tensor inside the square brackets. If nothing is specified, this function will check that only one file is included in the zip and load it for the specified input tensor. When loading from a pickle file, if no variable_name is specified in the square brackets, whatever that is inside the pickle file will be passed to the specified input tensor, else SavedModel CLI will assume a dictionary is stored in the pickle file and the value corresponding to the variable_name will be used. input_exprs_str: A string that specifies python expressions for inputs. * In the format of: '<input_key>=<python expression>'. * numpy module is available as np. input_examples_str: A string that specifies tf.Example with dictionary. * In the format of: '<input_key>=<[{feature:value list}]>' Returns: A dictionary that maps input tensor keys to numpy ndarrays. Raises: RuntimeError: An error when a key is specified, but the input file contains multiple numpy ndarrays, none of which matches the given key. RuntimeError: An error when no key is specified, but the input file contains more than one numpy ndarrays. """ tensor_key_feed_dict = {} inputs = preprocess_inputs_arg_string(inputs_str) input_exprs = preprocess_input_exprs_arg_string(input_exprs_str) input_examples = preprocess_input_examples_arg_string(input_examples_str) for input_tensor_key, (filename, variable_name) in inputs.items(): data = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # pylint: disable=unexpected-keyword-arg # When a variable_name key is specified for the input file if variable_name: # if file contains a single ndarray, ignore the input name if isinstance(data, np.ndarray): logging.warn( 'Input file %s contains a single ndarray. Name key \"%s\" ignored.' % (filename, variable_name)) tensor_key_feed_dict[input_tensor_key] = data else: if variable_name in data: tensor_key_feed_dict[input_tensor_key] = data[variable_name] else: raise RuntimeError( 'Input file %s does not contain variable with name \"%s\".' % (filename, variable_name)) # When no key is specified for the input file. else: # Check if npz file only contains a single numpy ndarray. if isinstance(data, np.lib.npyio.NpzFile): variable_name_list = data.files if len(variable_name_list) != 1: raise RuntimeError( 'Input file %s contains more than one ndarrays. Please specify ' 'the name of ndarray to use.' % filename) tensor_key_feed_dict[input_tensor_key] = data[variable_name_list[0]] else: tensor_key_feed_dict[input_tensor_key] = data # When input is a python expression: for input_tensor_key, py_expr_evaluated in input_exprs.items(): if input_tensor_key in tensor_key_feed_dict: logging.warn( 'input_key %s has been specified with both --inputs and --input_exprs' ' options. Value in --input_exprs will be used.' % input_tensor_key) tensor_key_feed_dict[input_tensor_key] = py_expr_evaluated # When input is a tf.Example: for input_tensor_key, example in input_examples.items(): if input_tensor_key in tensor_key_feed_dict: logging.warn( 'input_key %s has been specified in multiple options. Value in ' '--input_examples will be used.' % input_tensor_key) tensor_key_feed_dict[input_tensor_key] = example return tensor_key_feed_dict def show(args): """Function triggered by show command. Args: args: A namespace parsed from command line. """ # If all tag is specified, display all information. if args.all: _show_all(args.dir) else: # If no tag is specified, display all tag_set, if no signature_def key is # specified, display all SignatureDef keys, else show input output tensor # information corresponding to the given SignatureDef key if args.tag_set is None: _show_tag_sets(args.dir) else: if args.signature_def is None: _show_signature_def_map_keys(args.dir, args.tag_set) else: _show_inputs_outputs(args.dir, args.tag_set, args.signature_def) def run(args): """Function triggered by run command. Args: args: A namespace parsed from command line. Raises: AttributeError: An error when neither --inputs nor --input_exprs is passed to run command. """ if not args.inputs and not args.input_exprs and not args.input_examples: raise AttributeError( 'At least one of --inputs, --input_exprs or --input_examples must be ' 'required') tensor_key_feed_dict = load_inputs_from_input_arg_string( args.inputs, args.input_exprs, args.input_examples) run_saved_model_with_feed_dict( args.dir, args.tag_set, args.signature_def, tensor_key_feed_dict, args.outdir, args.overwrite, worker=args.worker, init_tpu=args.init_tpu, use_tfrt=args.use_tfrt, tf_debug=args.tf_debug) def scan(args): """Function triggered by scan command. Args: args: A namespace parsed from command line. """ if args.tag_set: scan_meta_graph_def( saved_model_utils.get_meta_graph_def(args.dir, args.tag_set)) else: saved_model = saved_model_utils.read_saved_model(args.dir) for meta_graph_def in saved_model.meta_graphs: scan_meta_graph_def(meta_graph_def) def convert_with_tensorrt(args): """Function triggered by 'convert tensorrt' command. Args: args: A namespace parsed from command line. """ # Import here instead of at top, because this will crash if TensorRT is # not installed from tensorflow.python.compiler.tensorrt import trt_convert as trt # pylint: disable=g-import-not-at-top if not args.convert_tf1_model: params = trt.DEFAULT_TRT_CONVERSION_PARAMS._replace( max_workspace_size_bytes=args.max_workspace_size_bytes, precision_mode=args.precision_mode, minimum_segment_size=args.minimum_segment_size) converter = trt.TrtGraphConverterV2( input_saved_model_dir=args.dir, input_saved_model_tags=args.tag_set.split(','), **params._asdict()) try: converter.convert() except Exception as e: raise RuntimeError( '{}. Try passing "--convert_tf1_model=True".'.format(e)) converter.save(output_saved_model_dir=args.output_dir) else: trt.create_inference_graph( None, None, max_batch_size=1, max_workspace_size_bytes=args.max_workspace_size_bytes, precision_mode=args.precision_mode, minimum_segment_size=args.minimum_segment_size, is_dynamic_op=True, input_saved_model_dir=args.dir, input_saved_model_tags=args.tag_set.split(','), output_saved_model_dir=args.output_dir) def freeze_model(args): """Function triggered by freeze_model command. Args: args: A namespace parsed from command line. """ checkpoint_path = ( args.checkpoint_path or os.path.join(args.dir, 'variables/variables')) if not args.variables_to_feed: variables_to_feed = [] elif args.variables_to_feed.lower() == 'all': variables_to_feed = None # We will identify them after. else: variables_to_feed = args.variables_to_feed.split(',') saved_model_aot_compile.freeze_model( checkpoint_path=checkpoint_path, meta_graph_def=saved_model_utils.get_meta_graph_def( args.dir, args.tag_set), signature_def_key=args.signature_def_key, variables_to_feed=variables_to_feed, output_prefix=args.output_prefix) def aot_compile_cpu(args): """Function triggered by aot_compile_cpu command. Args: args: A namespace parsed from command line. """ checkpoint_path = ( args.checkpoint_path or os.path.join(args.dir, 'variables/variables')) if not args.variables_to_feed: variables_to_feed = [] elif args.variables_to_feed.lower() == 'all': variables_to_feed = None # We will identify them after. else: variables_to_feed = args.variables_to_feed.split(',') saved_model_aot_compile.aot_compile_cpu_meta_graph_def( checkpoint_path=checkpoint_path, meta_graph_def=saved_model_utils.get_meta_graph_def( args.dir, args.tag_set), signature_def_key=args.signature_def_key, variables_to_feed=variables_to_feed, output_prefix=args.output_prefix, target_triple=args.target_triple, target_cpu=args.target_cpu, cpp_class=args.cpp_class, multithreading=args.multithreading.lower() not in ('f', 'false', '0')) def add_show_subparser(subparsers): """Add parser for `show`.""" show_msg = ( 'Usage examples:\n' 'To show all tag-sets in a SavedModel:\n' '$saved_model_cli show --dir /tmp/saved_model\n\n' 'To show all available SignatureDef keys in a ' 'MetaGraphDef specified by its tag-set:\n' '$saved_model_cli show --dir /tmp/saved_model --tag_set serve\n\n' 'For a MetaGraphDef with multiple tags in the tag-set, all tags must be ' 'passed in, separated by \';\':\n' '$saved_model_cli show --dir /tmp/saved_model --tag_set serve,gpu\n\n' 'To show all inputs and outputs TensorInfo for a specific' ' SignatureDef specified by the SignatureDef key in a' ' MetaGraph.\n' '$saved_model_cli show --dir /tmp/saved_model --tag_set serve' ' --signature_def serving_default\n\n' 'To show all available information in the SavedModel:\n' '$saved_model_cli show --dir /tmp/saved_model --all') parser_show = subparsers.add_parser( 'show', description=show_msg, formatter_class=argparse.RawTextHelpFormatter) parser_show.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to inspect') parser_show.add_argument( '--all', action='store_true', help='if set, will output all information in given SavedModel') parser_show.add_argument( '--tag_set', type=str, default=None, help='tag-set of graph in SavedModel to show, separated by \',\'') parser_show.add_argument( '--signature_def', type=str, default=None, metavar='SIGNATURE_DEF_KEY', help='key of SignatureDef to display input(s) and output(s) for') parser_show.set_defaults(func=show) def add_run_subparser(subparsers): """Add parser for `run`.""" run_msg = ('Usage example:\n' 'To run input tensors from files through a MetaGraphDef and save' ' the output tensors to files:\n' '$saved_model_cli show --dir /tmp/saved_model --tag_set serve \\\n' ' --signature_def serving_default \\\n' ' --inputs input1_key=/tmp/124.npz[x],input2_key=/tmp/123.npy ' '\\\n' ' --input_exprs \'input3_key=np.ones(2)\' \\\n' ' --input_examples ' '\'input4_key=[{"id":[26],"weights":[0.5, 0.5]}]\' \\\n' ' --outdir=/out\n\n' 'For more information about input file format, please see:\n' 'https://www.tensorflow.org/guide/saved_model_cli\n') parser_run = subparsers.add_parser( 'run', description=run_msg, formatter_class=argparse.RawTextHelpFormatter) parser_run.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to execute') parser_run.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to load, separated by \',\'') parser_run.add_argument( '--signature_def', type=str, required=True, metavar='SIGNATURE_DEF_KEY', help='key of SignatureDef to run') msg = ('Loading inputs from files, in the format of \'<input_key>=<filename>,' ' or \'<input_key>=<filename>[<variable_name>]\', separated by \';\'.' ' The file format can only be from .npy, .npz or pickle.') parser_run.add_argument('--inputs', type=str, default='', help=msg) msg = ('Specifying inputs by python expressions, in the format of' ' "<input_key>=\'<python expression>\'", separated by \';\'. ' 'numpy module is available as \'np\'. Please note that the expression ' 'will be evaluated as-is, and is susceptible to code injection. ' 'When this is set, the value will override duplicate input keys from ' '--inputs option.') parser_run.add_argument('--input_exprs', type=str, default='', help=msg) msg = ( 'Specifying tf.Example inputs as list of dictionaries. For example: ' '<input_key>=[{feature0:value_list,feature1:value_list}]. Use ";" to ' 'separate input keys. Will override duplicate input keys from --inputs ' 'and --input_exprs option.') parser_run.add_argument('--input_examples', type=str, default='', help=msg) parser_run.add_argument( '--outdir', type=str, default=None, help='if specified, output tensor(s) will be saved to given directory') parser_run.add_argument( '--overwrite', action='store_true', help='if set, output file will be overwritten if it already exists.') parser_run.add_argument( '--tf_debug', action='store_true', help='if set, will use TensorFlow Debugger (tfdbg) to watch the ' 'intermediate Tensors and runtime GraphDefs while running the ' 'SavedModel.') parser_run.add_argument( '--worker', type=str, default=None, help='if specified, a Session will be run on the worker. ' 'Valid worker specification is a bns or gRPC path.') parser_run.add_argument( '--init_tpu', action='store_true', default=None, help='if specified, tpu.initialize_system will be called on the Session. ' 'This option should be only used if the worker is a TPU job.') parser_run.add_argument( '--use_tfrt', action='store_true', default=None, help='if specified, TFRT session will be used, instead of TF1 session.') parser_run.set_defaults(func=run) def add_scan_subparser(subparsers): """Add parser for `scan`.""" scan_msg = ('Usage example:\n' 'To scan for denylisted ops in SavedModel:\n' '$saved_model_cli scan --dir /tmp/saved_model\n' 'To scan a specific MetaGraph, pass in --tag_set\n') parser_scan = subparsers.add_parser( 'scan', description=scan_msg, formatter_class=argparse.RawTextHelpFormatter) parser_scan.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to execute') parser_scan.add_argument( '--tag_set', type=str, help='tag-set of graph in SavedModel to scan, separated by \',\'') parser_scan.set_defaults(func=scan) def add_convert_subparser(subparsers): """Add parser for `convert`.""" convert_msg = ('Usage example:\n' 'To convert the SavedModel to one that have TensorRT ops:\n' '$saved_model_cli convert \\\n' ' --dir /tmp/saved_model \\\n' ' --tag_set serve \\\n' ' --output_dir /tmp/saved_model_trt \\\n' ' tensorrt \n') parser_convert = subparsers.add_parser( 'convert', description=convert_msg, formatter_class=argparse.RawTextHelpFormatter) parser_convert.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to convert') parser_convert.add_argument( '--output_dir', type=str, required=True, help='output directory for the converted SavedModel') parser_convert.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to convert, separated by \',\'') convert_subparsers = parser_convert.add_subparsers( title='conversion methods', description='valid conversion methods', help='the conversion to run with the SavedModel') parser_convert_with_tensorrt = convert_subparsers.add_parser( 'tensorrt', description='Convert the SavedModel with Tensorflow-TensorRT integration', formatter_class=argparse.RawTextHelpFormatter) parser_convert_with_tensorrt.add_argument( '--max_workspace_size_bytes', type=int, default=2 << 20, help=('the maximum GPU temporary memory which the TRT engine can use at ' 'execution time')) parser_convert_with_tensorrt.add_argument( '--precision_mode', type=str, default='FP32', help='one of FP32, FP16 and INT8') parser_convert_with_tensorrt.add_argument( '--minimum_segment_size', type=int, default=3, help=('the minimum number of nodes required for a subgraph to be replaced' 'in a TensorRT node')) parser_convert_with_tensorrt.add_argument( '--convert_tf1_model', type=bool, default=False, help='support TRT conversion for TF1 models') parser_convert_with_tensorrt.set_defaults(func=convert_with_tensorrt) def _parse_common_freeze_and_aot(parser_compile): """Parse arguments shared by freeze model and aot_compile.""" parser_compile.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to convert') parser_compile.add_argument( '--output_prefix', type=str, required=True, help=('output directory + filename prefix for the resulting header(s) ' 'and object file(s)')) parser_compile.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to convert, separated by \',\'') parser_compile.add_argument( '--signature_def_key', type=str, default=signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, help=('signature_def key to use. ' 'default: DEFAULT_SERVING_SIGNATURE_DEF_KEY')) parser_compile.add_argument( '--checkpoint_path', type=str, default=None, help='Custom checkpoint to use (default: use the SavedModel variables)') parser_compile.add_argument( '--variables_to_feed', type=str, default='', help=('The names of variables that will be fed into the network. ' 'Options are: empty (default; all variables are frozen, none may ' 'be fed), \'all\' (all variables may be fed), or a ' 'comma-delimited list of names of variables that may be fed. In ' 'the last case, the non-fed variables will be frozen in the graph.' '**NOTE** Any variables passed to `variables_to_feed` *must be set ' 'by the user*. These variables will NOT be frozen and their ' 'values will be uninitialized in the compiled object ' '(this applies to all input arguments from the signature as ' 'well).')) def add_freeze_model_subparser(subparsers): """Add parser for `freeze_model`.""" compile_msg = '\n'.join( ['Usage example:', 'To freeze a SavedModel in preparation for tfcompile:', '$saved_model_cli freeze_model \\', ' --dir /tmp/saved_model \\', ' --tag_set serve \\', ' --output_prefix /tmp/saved_model_xla_aot', ]) parser_compile = subparsers.add_parser( 'freeze_model', description=compile_msg, formatter_class=argparse.RawTextHelpFormatter) _parse_common_freeze_and_aot(parser_compile) parser_compile.set_defaults(func=freeze_model) def add_aot_compile_cpu_subparser(subparsers): """Add parser for `aot_compile_cpu`.""" compile_msg = '\n'.join( ['Usage example:', 'To compile a SavedModel signature via (CPU) XLA AOT:', '$saved_model_cli aot_compile_cpu \\', ' --dir /tmp/saved_model \\', ' --tag_set serve \\', ' --output_dir /tmp/saved_model_xla_aot', '', '', 'Note: Additional XLA compilation options are available by setting the ', 'XLA_FLAGS environment variable. See the XLA debug options flags for ', 'all the options: ', ' {}'.format(_XLA_DEBUG_OPTIONS_URL), '', 'For example, to disable XLA fast math when compiling:', '', 'XLA_FLAGS="--xla_cpu_enable_fast_math=false" $saved_model_cli ' 'aot_compile_cpu ...', '', 'Some possibly useful flags:', ' --xla_cpu_enable_fast_math=false', ' --xla_force_host_platform_device_count=<num threads>', ' (useful in conjunction with disabling multi threading)' ]) parser_compile = subparsers.add_parser( 'aot_compile_cpu', description=compile_msg, formatter_class=argparse.RawTextHelpFormatter) _parse_common_freeze_and_aot(parser_compile) parser_compile.add_argument( '--target_triple', type=str, default='x86_64-pc-linux', help=('Target triple for LLVM during AOT compilation. Examples: ' 'x86_64-none-darwin, x86_64-apple-ios, arm64-none-ios, ' 'armv7-none-android. More examples are available in tfcompile.bzl ' 'in the tensorflow codebase.')) parser_compile.add_argument( '--target_cpu', type=str, default='', help=('Target cpu name for LLVM during AOT compilation. Examples: ' 'x86_64, skylake, haswell, westmere, <empty> (unknown). For ' 'a complete list of options, run (for x86 targets): ' '`llc -march=x86 -mcpu=help`')) parser_compile.add_argument( '--cpp_class', type=str, required=True, help=('The name of the generated C++ class, wrapping the generated ' 'function. The syntax of this flag is ' '[[<optional_namespace>::],...]<class_name>. This mirrors the ' 'C++ syntax for referring to a class, where multiple namespaces ' 'may precede the class name, separated by double-colons. ' 'The class will be generated in the given namespace(s), or if no ' 'namespaces are given, within the global namespace.')) parser_compile.add_argument( '--multithreading', type=str, default='False', help=('Enable multithreading in the compiled computation. ' 'Note that if using this option, the resulting object files ' 'may have external dependencies on multithreading libraries ' 'like nsync.')) parser_compile.set_defaults(func=aot_compile_cpu) def create_parser(): """Creates a parser that parse the command line arguments. Returns: A namespace parsed from command line arguments. """ parser = argparse.ArgumentParser( description='saved_model_cli: Command-line interface for SavedModel') parser.add_argument('-v', '--version', action='version', version='0.1.0') subparsers = parser.add_subparsers( title='commands', description='valid commands', help='additional help') # show command add_show_subparser(subparsers) # run command add_run_subparser(subparsers) # scan command add_scan_subparser(subparsers) # tensorrt convert command add_convert_subparser(subparsers) # aot_compile_cpu command add_aot_compile_cpu_subparser(subparsers) # freeze_model command add_freeze_model_subparser(subparsers) return parser def main(): logging.set_verbosity(logging.INFO) parser = create_parser() args = parser.parse_args() if not hasattr(args, 'func'): parser.error('too few arguments') args.func(args) if __name__ == '__main__': sys.exit(main())
remote_code_execution
{ "code": [ " input_exprs = preprocess_input_exprs_arg_string(input_exprs_str, safe=False)" ], "line_no": [ 687 ] }
{ "code": [ " input_exprs = preprocess_input_exprs_arg_string(input_exprs_str)" ], "line_no": [ 687 ] }
import argparse import ast import os import re import .sys from absl import app # pylint: disable=unused-import import numpy as np import .six from tensorflow.core.example import .example_pb2 from tensorflow.core.framework import types_pb2 from tensorflow.core.protobuf import .config_pb2 from tensorflow.python.client import .session from tensorflow.python.debug.wrappers import local_cli_wrapper from tensorflow.python.eager import def_function from tensorflow.python.eager import function as defun from tensorflow.python.framework import .meta_graph as meta_graph_lib from tensorflow.python.framework import ops as ops_lib from tensorflow.python.framework import tensor_spec from tensorflow.python.lib.io import file_io from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import load from tensorflow.python.saved_model import loader from tensorflow.python.saved_model import .save from tensorflow.python.saved_model import .signature_constants from tensorflow.python.tools import .saved_model_aot_compile from tensorflow.python.tools import .saved_model_utils from tensorflow.python.tpu import tpu from tensorflow.python.util.compat import collections_abc VAR_0 = ( 'https://github.com/tensorflow/tensorflow/blob/master/' 'tensorflow/compiler/xla/debug_options_flags.cc') VAR_1 = set(['WriteFile', 'ReadFile', 'PrintV2']) def FUNC_0(VAR_2): VAR_25 = saved_model_utils.get_saved_model_tag_sets(VAR_2) print('The given SavedModel contains the following tag-sets:') for VAR_3 in sorted(VAR_25): print('%r' % ', '.join(sorted(VAR_3))) def FUNC_1(VAR_2, VAR_3): VAR_26 = FUNC_10(VAR_2, VAR_3) print('The given SavedModel MetaGraphDef contains SignatureDefs with the ' 'following keys:') for VAR_5 in sorted(VAR_26.keys()): print('SignatureDef key: \"%VAR_30\"' % VAR_5) def FUNC_2(VAR_4, VAR_5): if VAR_5 not in VAR_4.signature_def: raise ValueError( f'Could not find signature "{VAR_5}". Please choose from: ' f'{", ".join(VAR_4.signature_def.keys())}') return VAR_4.signature_def[VAR_5].inputs def FUNC_3(VAR_4, VAR_5): return VAR_4.signature_def[VAR_5].outputs def FUNC_4(VAR_2, VAR_3, VAR_5, VAR_6=0): VAR_4 = saved_model_utils.get_meta_graph_def(VAR_2, VAR_3) VAR_27 = FUNC_2( VAR_4, VAR_5) VAR_28 = FUNC_3( VAR_4, VAR_5) VAR_29 = ' ' * VAR_6 def FUNC_33(VAR_30): print(VAR_29 + VAR_30) FUNC_33('The given SavedModel SignatureDef contains the following input(VAR_30):') for VAR_71, input_tensor in sorted(VAR_27.items()): FUNC_33(' VAR_47[\'%VAR_30\'] VAR_9:' % VAR_71) FUNC_7(input_tensor, VAR_6+1) FUNC_33('The given SavedModel SignatureDef contains the following ' 'output(VAR_30):') for output_key, output_tensor in sorted(VAR_28.items()): FUNC_33(' VAR_69[\'%VAR_30\'] VAR_9:' % output_key) FUNC_7(output_tensor, VAR_6+1) FUNC_33('Method name is: %s' % VAR_4.signature_def[VAR_5].method_name) def FUNC_5(VAR_2): VAR_31 = saved_model_utils.read_saved_model(VAR_2).meta_graphs VAR_32 = False for VAR_4 in VAR_31: VAR_32 |= VAR_4.HasField('object_graph_def') if not VAR_32: return with ops_lib.Graph().as_default(): VAR_64 = load.load(VAR_2) print('\nConcrete Functions:', VAR_35='') VAR_33 = list( save._AugmentedGraphView(VAR_64) # pylint: disable=protected-access .list_children(VAR_64)) VAR_33 = sorted(VAR_33, key=lambda x: x.name) for name, child in VAR_33: VAR_65 = [] if isinstance(child, defun.ConcreteFunction): VAR_65.append(child) elif isinstance(child, def_function.Function): VAR_65.extend( child._list_all_concrete_functions_for_serialization()) # pylint: disable=protected-access else: continue print('\n Function Name: \'%VAR_30\'' % name) VAR_65 = sorted(VAR_65, key=lambda x: x.name) for index, concrete_function in enumerate(VAR_65, 1): VAR_22, VAR_79 = None, None if concrete_function.structured_input_signature: VAR_22, VAR_79 = concrete_function.structured_input_signature elif concrete_function._arg_keywords: # pylint: disable=protected-access VAR_22 = concrete_function._arg_keywords # pylint: disable=protected-access if VAR_22: print(' Option #%d' % index) print(' Callable with:') FUNC_6(VAR_22, VAR_6=4) if VAR_79: FUNC_6(VAR_79, 'Named Argument', VAR_6=4) def FUNC_6(VAR_7, VAR_8='Argument', VAR_6=0): VAR_29 = ' ' * VAR_6 def FUNC_34(VAR_34): VAR_66 = '\'' * isinstance(VAR_34, str) return VAR_66 + str(VAR_34) + VAR_66 def FUNC_33(VAR_30, VAR_35='\n'): print(VAR_29 + VAR_30, VAR_35=end) for index, element in enumerate(VAR_7, 1): if VAR_6 == 4: FUNC_33('%VAR_30 #%d' % (VAR_8, index)) if isinstance(element, six.string_types): FUNC_33(' %s' % element) elif isinstance(element, tensor_spec.TensorSpec): print((VAR_6 + 1) * ' ' + '%VAR_30: %s' % (element.name, repr(element))) elif (isinstance(element, collections_abc.Iterable) and not isinstance(element, dict)): FUNC_33(' DType: %s' % type(element).__name__) FUNC_33(' Value: [', VAR_35='') for VAR_34 in element: print('%s' % FUNC_34(VAR_34), VAR_35=', ') print('\b\b]') elif isinstance(element, dict): FUNC_33(' DType: %s' % type(element).__name__) FUNC_33(' Value: {', VAR_35='') for (key, VAR_34) in element.items(): print('\'%VAR_30\': %s' % (str(key), FUNC_34(VAR_34)), VAR_35=', ') print('\b\b}') else: FUNC_33(' DType: %s' % type(element).__name__) FUNC_33(' Value: %s' % str(element)) def FUNC_7(VAR_9, VAR_6=0): VAR_29 = ' ' * VAR_6 def FUNC_33(VAR_30): print(VAR_29 + VAR_30) FUNC_33(' dtype: ' + {VAR_34: key for (key, VAR_34) in types_pb2.DataType.items()}[VAR_9.dtype]) if VAR_9.tensor_shape.unknown_rank: VAR_67 = 'unknown_rank' else: VAR_68 = [str(dim.size) for dim in VAR_9.tensor_shape.dim] VAR_67 = ', '.join(VAR_68) VAR_67 = '(' + VAR_67 + ')' FUNC_33(' VAR_67: ' + VAR_67) FUNC_33(' name: ' + VAR_9.name) def FUNC_8(VAR_2): VAR_25 = saved_model_utils.get_saved_model_tag_sets(VAR_2) for VAR_3 in sorted(VAR_25): print("\nMetaGraphDef with tag-set: '%s' " "contains the following SignatureDefs:" % ', '.join(VAR_3)) VAR_3 = ','.join(VAR_3) VAR_26 = FUNC_10(VAR_2, VAR_3) for VAR_5 in sorted(VAR_26.keys()): print('\nsignature_def[\'' + VAR_5 + '\']:') FUNC_4(VAR_2, VAR_3, VAR_5, VAR_6=1) FUNC_5(VAR_2) def FUNC_9(VAR_2, VAR_3): return saved_model_utils.get_meta_graph_def(VAR_2, VAR_3) def FUNC_10(VAR_2, VAR_3): VAR_36 = saved_model_utils.get_meta_graph_def(VAR_2, VAR_3) return VAR_36.signature_def def FUNC_11(VAR_4): VAR_37 = set( meta_graph_lib.ops_used_by_graph_def(VAR_4.graph_def)) VAR_38 = VAR_1 & VAR_37 if VAR_38: print( 'MetaGraph with tag set %VAR_30 contains the following denylisted ops:' % VAR_4.meta_info_def.tags, VAR_38) else: print('MetaGraph with tag set %VAR_30 does not contain denylisted ops.' % VAR_4.meta_info_def.tags) def FUNC_12(VAR_2, VAR_3, VAR_5, VAR_10, VAR_11, VAR_12, VAR_13=None, VAR_14=False, VAR_15=False, VAR_16=False): VAR_4 = saved_model_utils.get_meta_graph_def(VAR_2, VAR_3) VAR_27 = FUNC_2( VAR_4, VAR_5) for input_key_name in VAR_10.keys(): if input_key_name not in VAR_27: raise ValueError( '"%s" is not a valid input key. Please choose from %VAR_30, or use ' '--FUNC_18 option.' % (input_key_name, '"' + '", "'.join(VAR_27.keys()) + '"')) VAR_39 = { VAR_27[key].name: tensor for key, tensor in VAR_10.items() } VAR_28 = FUNC_3( VAR_4, VAR_5) VAR_40 = sorted(VAR_28.keys()) VAR_41 = [ VAR_28[tensor_key].name for tensor_key in VAR_40 ] VAR_42 = None if VAR_15: logging.info('Using TFRT session.') VAR_42 = config_pb2.ConfigProto( experimental=config_pb2.ConfigProto.Experimental(VAR_15=True)) with session.Session(VAR_13, graph=ops_lib.Graph(), VAR_42=config) as VAR_80: if VAR_14: print('Initializing TPU System ...') VAR_80.run(tpu.initialize_system()) loader.load(VAR_80, VAR_3.split(','), VAR_2) if VAR_16: VAR_80 = local_cli_wrapper.LocalCLIDebugWrapperSession(VAR_80) VAR_69 = VAR_80.run(VAR_41, feed_dict=VAR_39) for i, output in enumerate(VAR_69): VAR_81 = VAR_40[i] print('Result for output key %VAR_30:\n%s' % (VAR_81, output)) if VAR_11: if not os.path.isdir(VAR_11): os.makedirs(VAR_11) VAR_82 = os.path.join(VAR_11, VAR_81 + '.npy') if not VAR_12 and os.path.exists(VAR_82): raise RuntimeError( 'Output file %VAR_30 already exists. Add \"--overwrite\" to overwrite' ' the existing output files.' % VAR_82) np.save(VAR_82, output) print('Output %VAR_30 is saved to %s' % (VAR_81, VAR_82)) def FUNC_13(VAR_17): VAR_43 = {} VAR_44 = VAR_17.split(';') for input_raw in filter(bool, VAR_44): # skip empty strings VAR_70 = re.match(r'([^=]+)=([^\[\]]+)\[([^\[\]]+)\]$', input_raw) if VAR_70: VAR_43[VAR_70.group(1)] = VAR_70.group(2), VAR_70.group(3) else: VAR_70 = re.match(r'([^=]+)=([^\[\]]+)$', input_raw) if VAR_70: VAR_43[VAR_70.group(1)] = VAR_70.group(2), None else: raise RuntimeError( '--VAR_47 "%s" format is incorrect. Please follow' '"<VAR_71>=<filename>", or' '"<VAR_71>=<filename>[<variable_name>]"' % input_raw) return VAR_43 def FUNC_14(VAR_18, VAR_19=True): VAR_43 = {} for input_raw in filter(bool, VAR_18.split(';')): if '=' not in VAR_18: raise RuntimeError('--VAR_48 "%s" format is incorrect. Please follow' '"<VAR_71>=<python expression>"' % VAR_18) VAR_71, VAR_72 = input_raw.split('=', 1) if VAR_19: try: VAR_43[VAR_71] = ast.literal_eval(VAR_72) except: raise RuntimeError( f'Expression "{VAR_72}" is not a valid python literal.') else: VAR_43[VAR_71] = eval(VAR_72) # pylint: disable=eval-used return VAR_43 def FUNC_15(VAR_20): VAR_43 = FUNC_14(VAR_20) for VAR_71, example_list in VAR_43.items(): if not isinstance(example_list, list): raise ValueError( 'tf.Example input must be a list of dictionaries, but "%s" is %s' % (example_list, type(example_list))) VAR_43[VAR_71] = [ FUNC_16(VAR_45) for VAR_45 in example_list ] return VAR_43 def FUNC_16(VAR_21): VAR_45 = example_pb2.Example() for feature_name, feature_list in VAR_21.items(): if not isinstance(feature_list, list): raise ValueError('feature VAR_34 must be a list, but %VAR_30: "%s" is %s' % (feature_name, feature_list, type(feature_list))) if isinstance(feature_list[0], float): VAR_45.features.feature[feature_name].float_list.value.extend( feature_list) elif isinstance(feature_list[0], str): VAR_45.features.feature[feature_name].bytes_list.value.extend( [f.encode('utf8') for f in feature_list]) elif isinstance(feature_list[0], bytes): VAR_45.features.feature[feature_name].bytes_list.value.extend( feature_list) elif isinstance(feature_list[0], six.integer_types): VAR_45.features.feature[feature_name].int64_list.value.extend( feature_list) else: raise ValueError( 'Type %VAR_30 for VAR_34 %VAR_30 is not supported for tf.train.Feature.' % (type(feature_list[0]), feature_list[0])) return VAR_45.SerializeToString() def FUNC_17(VAR_17, VAR_18, VAR_20): VAR_46 = {} VAR_47 = FUNC_13(VAR_17) VAR_48 = FUNC_14(VAR_18, VAR_19=False) VAR_49 = FUNC_15(VAR_20) for VAR_74, (filename, variable_name) in VAR_47.items(): VAR_73 = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # pylint: disable=unexpected-keyword-arg if variable_name: if isinstance(VAR_73, np.ndarray): logging.warn( 'Input file %VAR_30 contains a single ndarray. Name key \"%VAR_30\" ignored.' % (filename, variable_name)) VAR_46[VAR_74] = VAR_73 else: if variable_name in VAR_73: VAR_46[VAR_74] = VAR_73[variable_name] else: raise RuntimeError( 'Input file %VAR_30 does not contain variable with name \"%VAR_30\".' % (filename, variable_name)) else: if isinstance(VAR_73, np.lib.npyio.NpzFile): VAR_83 = VAR_73.files if len(VAR_83) != 1: raise RuntimeError( 'Input file %VAR_30 contains more than one ndarrays. Please specify ' 'the name of ndarray to use.' % filename) VAR_46[VAR_74] = VAR_73[VAR_83[0]] else: VAR_46[VAR_74] = VAR_73 for VAR_74, py_expr_evaluated in VAR_48.items(): if VAR_74 in VAR_46: logging.warn( 'input_key %VAR_30 has been specified with both --VAR_47 and --input_exprs' ' options. Value in --VAR_48 will be used.' % VAR_74) VAR_46[VAR_74] = py_expr_evaluated for VAR_74, VAR_45 in VAR_49.items(): if VAR_74 in VAR_46: logging.warn( 'input_key %VAR_30 has been specified in multiple options. Value in ' '--VAR_49 will be used.' % VAR_74) VAR_46[VAR_74] = VAR_45 return VAR_46 def FUNC_18(VAR_22): if VAR_22.all: FUNC_8(VAR_22.dir) else: if VAR_22.tag_set is None: FUNC_0(VAR_22.dir) else: if VAR_22.signature_def is None: FUNC_1(VAR_22.dir, VAR_22.tag_set) else: FUNC_4(VAR_22.dir, VAR_22.tag_set, VAR_22.signature_def) def FUNC_19(VAR_22): if not VAR_22.inputs and not VAR_22.input_exprs and not VAR_22.input_examples: raise AttributeError( 'At least one of --VAR_47, --VAR_48 or --VAR_49 must be ' 'required') VAR_46 = FUNC_17( VAR_22.inputs, VAR_22.input_exprs, VAR_22.input_examples) FUNC_12( VAR_22.dir, VAR_22.tag_set, VAR_22.signature_def, VAR_46, VAR_22.outdir, VAR_22.overwrite, VAR_13=VAR_22.worker, VAR_14=VAR_22.init_tpu, VAR_15=VAR_22.use_tfrt, VAR_16=VAR_22.tf_debug) def FUNC_20(VAR_22): if VAR_22.tag_set: FUNC_11( saved_model_utils.get_meta_graph_def(VAR_22.dir, VAR_22.tag_set)) else: VAR_75 = saved_model_utils.read_saved_model(VAR_22.dir) for VAR_4 in VAR_75.meta_graphs: FUNC_11(VAR_4) def FUNC_21(VAR_22): from tensorflow.python.compiler.tensorrt import trt_convert as trt # pylint: disable=g-import-not-at-top if not VAR_22.convert_tf1_model: VAR_76 = trt.DEFAULT_TRT_CONVERSION_PARAMS._replace( max_workspace_size_bytes=VAR_22.max_workspace_size_bytes, precision_mode=VAR_22.precision_mode, minimum_segment_size=VAR_22.minimum_segment_size) VAR_77 = trt.TrtGraphConverterV2( input_saved_model_dir=VAR_22.dir, input_saved_model_tags=VAR_22.tag_set.split(','), **VAR_76._asdict()) try: VAR_77.convert() except Exception as e: raise RuntimeError( '{}. Try passing "--convert_tf1_model=True".'.format(e)) VAR_77.save(output_saved_model_dir=VAR_22.output_dir) else: trt.create_inference_graph( None, None, max_batch_size=1, max_workspace_size_bytes=VAR_22.max_workspace_size_bytes, precision_mode=VAR_22.precision_mode, minimum_segment_size=VAR_22.minimum_segment_size, is_dynamic_op=True, input_saved_model_dir=VAR_22.dir, input_saved_model_tags=VAR_22.tag_set.split(','), output_saved_model_dir=VAR_22.output_dir) def FUNC_22(VAR_22): VAR_50 = ( VAR_22.checkpoint_path or os.path.join(VAR_22.dir, 'variables/variables')) if not VAR_22.variables_to_feed: VAR_78 = [] elif VAR_22.variables_to_feed.lower() == 'all': VAR_78 = None # We will identify them after. else: VAR_78 = VAR_22.variables_to_feed.split(',') saved_model_aot_compile.freeze_model( VAR_50=checkpoint_path, VAR_4=saved_model_utils.get_meta_graph_def( VAR_22.dir, VAR_22.tag_set), VAR_5=VAR_22.signature_def_key, VAR_78=variables_to_feed, output_prefix=VAR_22.output_prefix) def FUNC_23(VAR_22): VAR_50 = ( VAR_22.checkpoint_path or os.path.join(VAR_22.dir, 'variables/variables')) if not VAR_22.variables_to_feed: VAR_78 = [] elif VAR_22.variables_to_feed.lower() == 'all': VAR_78 = None # We will identify them after. else: VAR_78 = VAR_22.variables_to_feed.split(',') saved_model_aot_compile.aot_compile_cpu_meta_graph_def( VAR_50=checkpoint_path, VAR_4=saved_model_utils.get_meta_graph_def( VAR_22.dir, VAR_22.tag_set), VAR_5=VAR_22.signature_def_key, VAR_78=variables_to_feed, output_prefix=VAR_22.output_prefix, target_triple=VAR_22.target_triple, target_cpu=VAR_22.target_cpu, cpp_class=VAR_22.cpp_class, multithreading=VAR_22.multithreading.lower() not in ('f', 'false', '0')) def FUNC_24(VAR_23): VAR_51 = ( 'Usage examples:\n' 'To FUNC_18 all tag-sets in a SavedModel:\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75\n\n' 'To FUNC_18 all available SignatureDef keys in a ' 'MetaGraphDef specified by its tag-set:\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --VAR_3 serve\n\n' 'For a MetaGraphDef with multiple tags in the tag-set, all tags must be ' 'passed in, separated by \';\':\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --VAR_3 serve,gpu\n\n' 'To FUNC_18 all VAR_47 and VAR_69 TensorInfo for a specific' ' SignatureDef specified by the SignatureDef key in a' ' MetaGraph.\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --VAR_3 serve' ' --signature_def serving_default\n\n' 'To FUNC_18 all available information in the SavedModel:\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --all') VAR_52 = VAR_23.add_parser( 'show', description=VAR_51, formatter_class=argparse.RawTextHelpFormatter) VAR_52.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to inspect') VAR_52.add_argument( '--all', action='store_true', help='if set, will output all information in given SavedModel') VAR_52.add_argument( '--tag_set', type=str, default=None, help='tag-set of graph in SavedModel to FUNC_18, separated by \',\'') VAR_52.add_argument( '--signature_def', type=str, default=None, metavar='SIGNATURE_DEF_KEY', help='key of SignatureDef to display input(VAR_30) and output(VAR_30) for') VAR_52.set_defaults(func=FUNC_18) def FUNC_25(VAR_23): VAR_53 = ('Usage VAR_45:\n' 'To FUNC_19 input tensors from files through a MetaGraphDef and save' ' the output tensors to files:\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --VAR_3 serve \\\n' ' --signature_def serving_default \\\n' ' --VAR_47 input1_key=/tmp/124.npz[x],input2_key=/tmp/123.npy ' '\\\n' ' --VAR_48 \'input3_key=np.ones(2)\' \\\n' ' --VAR_49 ' '\'input4_key=[{"id":[26],"weights":[0.5, 0.5]}]\' \\\n' ' --VAR_11=/out\n\n' 'For more information about input file format, please see:\n' 'https://www.tensorflow.org/guide/saved_model_cli\n') VAR_54 = VAR_23.add_parser( 'run', description=VAR_53, formatter_class=argparse.RawTextHelpFormatter) VAR_54.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to execute') VAR_54.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to load, separated by \',\'') VAR_54.add_argument( '--signature_def', type=str, required=True, metavar='SIGNATURE_DEF_KEY', help='key of SignatureDef to run') VAR_55 = ('Loading VAR_47 from files, in the format of \'<VAR_71>=<filename>,' ' or \'<VAR_71>=<filename>[<variable_name>]\', separated by \';\'.' ' The file format can only be from .npy, .npz or pickle.') VAR_54.add_argument('--inputs', type=str, default='', help=VAR_55) VAR_55 = ('Specifying VAR_47 by python expressions, in the format of' ' "<VAR_71>=\'<python expression>\'", separated by \';\'. ' 'numpy module is available as \'np\'. Please note that the expression ' 'will be evaluated as-is, and is susceptible to code injection. ' 'When this is set, the VAR_34 will override duplicate input keys from ' '--VAR_47 option.') VAR_54.add_argument('--input_exprs', type=str, default='', help=VAR_55) VAR_55 = ( 'Specifying tf.Example VAR_47 as list of dictionaries. For VAR_45: ' '<VAR_71>=[{feature0:value_list,feature1:value_list}]. Use ";" to ' 'separate input keys. Will override duplicate input keys from --VAR_47 ' 'and --VAR_48 option.') VAR_54.add_argument('--input_examples', type=str, default='', help=VAR_55) VAR_54.add_argument( '--outdir', type=str, default=None, help='if specified, output tensor(VAR_30) will be saved to given directory') VAR_54.add_argument( '--overwrite', action='store_true', help='if set, output file will be overwritten if it already exists.') VAR_54.add_argument( '--tf_debug', action='store_true', help='if set, will use TensorFlow Debugger (tfdbg) to watch the ' 'intermediate Tensors and runtime GraphDefs while running the ' 'SavedModel.') VAR_54.add_argument( '--worker', type=str, default=None, help='if specified, a Session will be FUNC_19 on the VAR_13. ' 'Valid VAR_13 specification is a bns or gRPC path.') VAR_54.add_argument( '--init_tpu', action='store_true', default=None, help='if specified, tpu.initialize_system will be called on the Session. ' 'This option should be only used if the VAR_13 is a TPU job.') VAR_54.add_argument( '--use_tfrt', action='store_true', default=None, help='if specified, TFRT session will be used, instead of TF1 session.') VAR_54.set_defaults(func=FUNC_19) def FUNC_26(VAR_23): VAR_56 = ('Usage VAR_45:\n' 'To FUNC_20 for denylisted ops in SavedModel:\n' '$saved_model_cli FUNC_20 --dir /tmp/VAR_75\n' 'To FUNC_20 a specific MetaGraph, pass in --VAR_3\n') VAR_57 = VAR_23.add_parser( 'scan', description=VAR_56, formatter_class=argparse.RawTextHelpFormatter) VAR_57.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to execute') VAR_57.add_argument( '--tag_set', type=str, help='tag-set of graph in SavedModel to FUNC_20, separated by \',\'') VAR_57.set_defaults(func=FUNC_20) def FUNC_27(VAR_23): VAR_58 = ('Usage VAR_45:\n' 'To convert the SavedModel to one that have TensorRT ops:\n' '$saved_model_cli convert \\\n' ' --dir /tmp/VAR_75 \\\n' ' --VAR_3 serve \\\n' ' --output_dir /tmp/saved_model_trt \\\n' ' tensorrt \n') VAR_59 = VAR_23.add_parser( 'convert', description=VAR_58, formatter_class=argparse.RawTextHelpFormatter) VAR_59.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to convert') VAR_59.add_argument( '--output_dir', type=str, required=True, help='output directory for the converted SavedModel') VAR_59.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to convert, separated by \',\'') VAR_60 = VAR_59.add_subparsers( title='conversion methods', description='valid conversion methods', help='the conversion to FUNC_19 with the SavedModel') VAR_61 = VAR_60.add_parser( 'tensorrt', description='Convert the SavedModel with Tensorflow-TensorRT integration', formatter_class=argparse.RawTextHelpFormatter) VAR_61.add_argument( '--max_workspace_size_bytes', type=int, default=2 << 20, help=('the maximum GPU temporary memory which the TRT engine can use at ' 'execution time')) VAR_61.add_argument( '--precision_mode', type=str, default='FP32', help='one of FP32, FP16 and INT8') VAR_61.add_argument( '--minimum_segment_size', type=int, default=3, help=('the minimum number of nodes required for a subgraph to be replaced' 'in a TensorRT node')) VAR_61.add_argument( '--convert_tf1_model', type=bool, default=False, help='support TRT conversion for TF1 models') VAR_61.set_defaults(func=FUNC_21) def FUNC_28(VAR_24): VAR_24.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to convert') VAR_24.add_argument( '--output_prefix', type=str, required=True, help=('output directory + filename prefix for the resulting header(VAR_30) ' 'and object file(VAR_30)')) VAR_24.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to convert, separated by \',\'') VAR_24.add_argument( '--signature_def_key', type=str, default=signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, help=('signature_def key to use. ' 'default: DEFAULT_SERVING_SIGNATURE_DEF_KEY')) VAR_24.add_argument( '--checkpoint_path', type=str, default=None, help='Custom checkpoint to use (default: use the SavedModel variables)') VAR_24.add_argument( '--variables_to_feed', type=str, default='', help=('The names of variables that will be fed into the network. ' 'Options are: empty (default; all variables are frozen, none may ' 'be fed), \'all\' (all variables may be fed), or a ' 'comma-delimited list of names of variables that may be fed. In ' 'the last case, the non-fed variables will be frozen in the graph.' '**NOTE** Any variables passed to `VAR_78` *must be set ' 'by the user*. These variables will NOT be frozen and their ' 'values will be uninitialized in the compiled object ' '(this applies to all input VAR_7 from the signature as ' 'well).')) def FUNC_29(VAR_23): VAR_62 = '\n'.join( ['Usage VAR_45:', 'To freeze a SavedModel in preparation for tfcompile:', '$saved_model_cli FUNC_22 \\', ' --dir /tmp/VAR_75 \\', ' --VAR_3 serve \\', ' --output_prefix /tmp/saved_model_xla_aot', ]) VAR_24 = VAR_23.add_parser( 'freeze_model', description=VAR_62, formatter_class=argparse.RawTextHelpFormatter) FUNC_28(VAR_24) VAR_24.set_defaults(func=FUNC_22) def FUNC_30(VAR_23): VAR_62 = '\n'.join( ['Usage VAR_45:', 'To compile a SavedModel signature via (CPU) XLA AOT:', '$saved_model_cli FUNC_23 \\', ' --dir /tmp/VAR_75 \\', ' --VAR_3 serve \\', ' --output_dir /tmp/saved_model_xla_aot', '', '', 'Note: Additional XLA compilation options are available by setting the ', 'XLA_FLAGS environment variable. See the XLA debug options flags for ', 'all the options: ', ' {}'.format(VAR_0), '', 'For VAR_45, to disable XLA fast math when compiling:', '', 'XLA_FLAGS="--xla_cpu_enable_fast_math=false" $saved_model_cli ' 'aot_compile_cpu ...', '', 'Some possibly useful flags:', ' --xla_cpu_enable_fast_math=false', ' --xla_force_host_platform_device_count=<num threads>', ' (useful in conjunction with disabling multi threading)' ]) VAR_24 = VAR_23.add_parser( 'aot_compile_cpu', description=VAR_62, formatter_class=argparse.RawTextHelpFormatter) FUNC_28(VAR_24) VAR_24.add_argument( '--target_triple', type=str, default='x86_64-pc-linux', help=('Target triple for LLVM during AOT compilation. Examples: ' 'x86_64-none-darwin, x86_64-apple-ios, arm64-none-ios, ' 'armv7-none-android. More examples are available in tfcompile.bzl ' 'in the tensorflow codebase.')) VAR_24.add_argument( '--target_cpu', type=str, default='', help=('Target cpu name for LLVM during AOT compilation. Examples: ' 'x86_64, skylake, haswell, westmere, <empty> (unknown). For ' 'a complete list of options, FUNC_19 (for x86 targets): ' '`llc -march=x86 -mcpu=help`')) VAR_24.add_argument( '--cpp_class', type=str, required=True, help=('The name of the generated C++ class, wrapping the generated ' 'function. The syntax of this flag is ' '[[<optional_namespace>::],...]<class_name>. This mirrors the ' 'C++ syntax for referring to a class, where multiple namespaces ' 'may precede the class name, separated by double-colons. ' 'The class will be generated in the given namespace(VAR_30), or if no ' 'namespaces are given, within the global namespace.')) VAR_24.add_argument( '--multithreading', type=str, default='False', help=('Enable multithreading in the compiled computation. ' 'Note that if using this option, the resulting object files ' 'may have external dependencies on multithreading libraries ' 'like nsync.')) VAR_24.set_defaults(func=FUNC_23) def FUNC_31(): VAR_63 = argparse.ArgumentParser( description='saved_model_cli: Command-line interface for SavedModel') VAR_63.add_argument('-v', '--version', action='version', version='0.1.0') VAR_23 = VAR_63.add_subparsers( title='commands', description='valid commands', help='additional help') FUNC_24(VAR_23) FUNC_25(VAR_23) FUNC_26(VAR_23) FUNC_27(VAR_23) FUNC_30(VAR_23) FUNC_29(VAR_23) return VAR_63 def FUNC_32(): logging.set_verbosity(logging.INFO) VAR_63 = FUNC_31() VAR_22 = VAR_63.parse_args() if not hasattr(VAR_22, 'func'): VAR_63.error('too few arguments') VAR_22.func(VAR_22) if __name__ == '__main__': sys.exit(FUNC_32())
import argparse import ast import os import re import .sys from absl import app # pylint: disable=unused-import import numpy as np import .six from tensorflow.core.example import .example_pb2 from tensorflow.core.framework import types_pb2 from tensorflow.core.protobuf import .config_pb2 from tensorflow.python.client import .session from tensorflow.python.debug.wrappers import local_cli_wrapper from tensorflow.python.eager import def_function from tensorflow.python.eager import function as defun from tensorflow.python.framework import .meta_graph as meta_graph_lib from tensorflow.python.framework import ops as ops_lib from tensorflow.python.framework import tensor_spec from tensorflow.python.lib.io import file_io from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import load from tensorflow.python.saved_model import loader from tensorflow.python.saved_model import .save from tensorflow.python.saved_model import .signature_constants from tensorflow.python.tools import .saved_model_aot_compile from tensorflow.python.tools import .saved_model_utils from tensorflow.python.tpu import tpu from tensorflow.python.util.compat import collections_abc VAR_0 = ( 'https://github.com/tensorflow/tensorflow/blob/master/' 'tensorflow/compiler/xla/debug_options_flags.cc') VAR_1 = set(['WriteFile', 'ReadFile', 'PrintV2']) def FUNC_0(VAR_2): VAR_25 = saved_model_utils.get_saved_model_tag_sets(VAR_2) print('The given SavedModel contains the following tag-sets:') for VAR_3 in sorted(VAR_25): print('%r' % ', '.join(sorted(VAR_3))) def FUNC_1(VAR_2, VAR_3): VAR_26 = FUNC_10(VAR_2, VAR_3) print('The given SavedModel MetaGraphDef contains SignatureDefs with the ' 'following keys:') for VAR_5 in sorted(VAR_26.keys()): print('SignatureDef key: \"%VAR_30\"' % VAR_5) def FUNC_2(VAR_4, VAR_5): if VAR_5 not in VAR_4.signature_def: raise ValueError( f'Could not find signature "{VAR_5}". Please choose from: ' f'{", ".join(VAR_4.signature_def.keys())}') return VAR_4.signature_def[VAR_5].inputs def FUNC_3(VAR_4, VAR_5): return VAR_4.signature_def[VAR_5].outputs def FUNC_4(VAR_2, VAR_3, VAR_5, VAR_6=0): VAR_4 = saved_model_utils.get_meta_graph_def(VAR_2, VAR_3) VAR_27 = FUNC_2( VAR_4, VAR_5) VAR_28 = FUNC_3( VAR_4, VAR_5) VAR_29 = ' ' * VAR_6 def FUNC_33(VAR_30): print(VAR_29 + VAR_30) FUNC_33('The given SavedModel SignatureDef contains the following input(VAR_30):') for VAR_71, input_tensor in sorted(VAR_27.items()): FUNC_33(' VAR_47[\'%VAR_30\'] VAR_9:' % VAR_71) FUNC_7(input_tensor, VAR_6+1) FUNC_33('The given SavedModel SignatureDef contains the following ' 'output(VAR_30):') for output_key, output_tensor in sorted(VAR_28.items()): FUNC_33(' VAR_69[\'%VAR_30\'] VAR_9:' % output_key) FUNC_7(output_tensor, VAR_6+1) FUNC_33('Method name is: %s' % VAR_4.signature_def[VAR_5].method_name) def FUNC_5(VAR_2): VAR_31 = saved_model_utils.read_saved_model(VAR_2).meta_graphs VAR_32 = False for VAR_4 in VAR_31: VAR_32 |= VAR_4.HasField('object_graph_def') if not VAR_32: return with ops_lib.Graph().as_default(): VAR_64 = load.load(VAR_2) print('\nConcrete Functions:', VAR_35='') VAR_33 = list( save._AugmentedGraphView(VAR_64) # pylint: disable=protected-access .list_children(VAR_64)) VAR_33 = sorted(VAR_33, key=lambda x: x.name) for name, child in VAR_33: VAR_65 = [] if isinstance(child, defun.ConcreteFunction): VAR_65.append(child) elif isinstance(child, def_function.Function): VAR_65.extend( child._list_all_concrete_functions_for_serialization()) # pylint: disable=protected-access else: continue print('\n Function Name: \'%VAR_30\'' % name) VAR_65 = sorted(VAR_65, key=lambda x: x.name) for index, concrete_function in enumerate(VAR_65, 1): VAR_22, VAR_79 = None, None if concrete_function.structured_input_signature: VAR_22, VAR_79 = concrete_function.structured_input_signature elif concrete_function._arg_keywords: # pylint: disable=protected-access VAR_22 = concrete_function._arg_keywords # pylint: disable=protected-access if VAR_22: print(' Option #%d' % index) print(' Callable with:') FUNC_6(VAR_22, VAR_6=4) if VAR_79: FUNC_6(VAR_79, 'Named Argument', VAR_6=4) def FUNC_6(VAR_7, VAR_8='Argument', VAR_6=0): VAR_29 = ' ' * VAR_6 def FUNC_34(VAR_34): VAR_66 = '\'' * isinstance(VAR_34, str) return VAR_66 + str(VAR_34) + VAR_66 def FUNC_33(VAR_30, VAR_35='\n'): print(VAR_29 + VAR_30, VAR_35=end) for index, element in enumerate(VAR_7, 1): if VAR_6 == 4: FUNC_33('%VAR_30 #%d' % (VAR_8, index)) if isinstance(element, six.string_types): FUNC_33(' %s' % element) elif isinstance(element, tensor_spec.TensorSpec): print((VAR_6 + 1) * ' ' + '%VAR_30: %s' % (element.name, repr(element))) elif (isinstance(element, collections_abc.Iterable) and not isinstance(element, dict)): FUNC_33(' DType: %s' % type(element).__name__) FUNC_33(' Value: [', VAR_35='') for VAR_34 in element: print('%s' % FUNC_34(VAR_34), VAR_35=', ') print('\b\b]') elif isinstance(element, dict): FUNC_33(' DType: %s' % type(element).__name__) FUNC_33(' Value: {', VAR_35='') for (key, VAR_34) in element.items(): print('\'%VAR_30\': %s' % (str(key), FUNC_34(VAR_34)), VAR_35=', ') print('\b\b}') else: FUNC_33(' DType: %s' % type(element).__name__) FUNC_33(' Value: %s' % str(element)) def FUNC_7(VAR_9, VAR_6=0): VAR_29 = ' ' * VAR_6 def FUNC_33(VAR_30): print(VAR_29 + VAR_30) FUNC_33(' dtype: ' + {VAR_34: key for (key, VAR_34) in types_pb2.DataType.items()}[VAR_9.dtype]) if VAR_9.tensor_shape.unknown_rank: VAR_67 = 'unknown_rank' else: VAR_68 = [str(dim.size) for dim in VAR_9.tensor_shape.dim] VAR_67 = ', '.join(VAR_68) VAR_67 = '(' + VAR_67 + ')' FUNC_33(' VAR_67: ' + VAR_67) FUNC_33(' name: ' + VAR_9.name) def FUNC_8(VAR_2): VAR_25 = saved_model_utils.get_saved_model_tag_sets(VAR_2) for VAR_3 in sorted(VAR_25): print("\nMetaGraphDef with tag-set: '%s' " "contains the following SignatureDefs:" % ', '.join(VAR_3)) VAR_3 = ','.join(VAR_3) VAR_26 = FUNC_10(VAR_2, VAR_3) for VAR_5 in sorted(VAR_26.keys()): print('\nsignature_def[\'' + VAR_5 + '\']:') FUNC_4(VAR_2, VAR_3, VAR_5, VAR_6=1) FUNC_5(VAR_2) def FUNC_9(VAR_2, VAR_3): return saved_model_utils.get_meta_graph_def(VAR_2, VAR_3) def FUNC_10(VAR_2, VAR_3): VAR_36 = saved_model_utils.get_meta_graph_def(VAR_2, VAR_3) return VAR_36.signature_def def FUNC_11(VAR_4): VAR_37 = set( meta_graph_lib.ops_used_by_graph_def(VAR_4.graph_def)) VAR_38 = VAR_1 & VAR_37 if VAR_38: print( 'MetaGraph with tag set %VAR_30 contains the following denylisted ops:' % VAR_4.meta_info_def.tags, VAR_38) else: print('MetaGraph with tag set %VAR_30 does not contain denylisted ops.' % VAR_4.meta_info_def.tags) def FUNC_12(VAR_2, VAR_3, VAR_5, VAR_10, VAR_11, VAR_12, VAR_13=None, VAR_14=False, VAR_15=False, VAR_16=False): VAR_4 = saved_model_utils.get_meta_graph_def(VAR_2, VAR_3) VAR_27 = FUNC_2( VAR_4, VAR_5) for input_key_name in VAR_10.keys(): if input_key_name not in VAR_27: raise ValueError( '"%s" is not a valid input key. Please choose from %VAR_30, or use ' '--FUNC_18 option.' % (input_key_name, '"' + '", "'.join(VAR_27.keys()) + '"')) VAR_39 = { VAR_27[key].name: tensor for key, tensor in VAR_10.items() } VAR_28 = FUNC_3( VAR_4, VAR_5) VAR_40 = sorted(VAR_28.keys()) VAR_41 = [ VAR_28[tensor_key].name for tensor_key in VAR_40 ] VAR_42 = None if VAR_15: logging.info('Using TFRT session.') VAR_42 = config_pb2.ConfigProto( experimental=config_pb2.ConfigProto.Experimental(VAR_15=True)) with session.Session(VAR_13, graph=ops_lib.Graph(), VAR_42=config) as VAR_80: if VAR_14: print('Initializing TPU System ...') VAR_80.run(tpu.initialize_system()) loader.load(VAR_80, VAR_3.split(','), VAR_2) if VAR_16: VAR_80 = local_cli_wrapper.LocalCLIDebugWrapperSession(VAR_80) VAR_69 = VAR_80.run(VAR_41, feed_dict=VAR_39) for i, output in enumerate(VAR_69): VAR_81 = VAR_40[i] print('Result for output key %VAR_30:\n%s' % (VAR_81, output)) if VAR_11: if not os.path.isdir(VAR_11): os.makedirs(VAR_11) VAR_82 = os.path.join(VAR_11, VAR_81 + '.npy') if not VAR_12 and os.path.exists(VAR_82): raise RuntimeError( 'Output file %VAR_30 already exists. Add \"--overwrite\" to overwrite' ' the existing output files.' % VAR_82) np.save(VAR_82, output) print('Output %VAR_30 is saved to %s' % (VAR_81, VAR_82)) def FUNC_13(VAR_17): VAR_43 = {} VAR_44 = VAR_17.split(';') for input_raw in filter(bool, VAR_44): # skip empty strings VAR_70 = re.match(r'([^=]+)=([^\[\]]+)\[([^\[\]]+)\]$', input_raw) if VAR_70: VAR_43[VAR_70.group(1)] = VAR_70.group(2), VAR_70.group(3) else: VAR_70 = re.match(r'([^=]+)=([^\[\]]+)$', input_raw) if VAR_70: VAR_43[VAR_70.group(1)] = VAR_70.group(2), None else: raise RuntimeError( '--VAR_47 "%s" format is incorrect. Please follow' '"<VAR_71>=<filename>", or' '"<VAR_71>=<filename>[<variable_name>]"' % input_raw) return VAR_43 def FUNC_14(VAR_18, VAR_19=True): VAR_43 = {} for input_raw in filter(bool, VAR_18.split(';')): if '=' not in VAR_18: raise RuntimeError('--VAR_48 "%s" format is incorrect. Please follow' '"<VAR_71>=<python expression>"' % VAR_18) VAR_71, VAR_72 = input_raw.split('=', 1) if VAR_19: try: VAR_43[VAR_71] = ast.literal_eval(VAR_72) except: raise RuntimeError( f'Expression "{VAR_72}" is not a valid python literal.') else: VAR_43[VAR_71] = eval(VAR_72) # pylint: disable=eval-used return VAR_43 def FUNC_15(VAR_20): VAR_43 = FUNC_14(VAR_20) for VAR_71, example_list in VAR_43.items(): if not isinstance(example_list, list): raise ValueError( 'tf.Example input must be a list of dictionaries, but "%s" is %s' % (example_list, type(example_list))) VAR_43[VAR_71] = [ FUNC_16(VAR_45) for VAR_45 in example_list ] return VAR_43 def FUNC_16(VAR_21): VAR_45 = example_pb2.Example() for feature_name, feature_list in VAR_21.items(): if not isinstance(feature_list, list): raise ValueError('feature VAR_34 must be a list, but %VAR_30: "%s" is %s' % (feature_name, feature_list, type(feature_list))) if isinstance(feature_list[0], float): VAR_45.features.feature[feature_name].float_list.value.extend( feature_list) elif isinstance(feature_list[0], str): VAR_45.features.feature[feature_name].bytes_list.value.extend( [f.encode('utf8') for f in feature_list]) elif isinstance(feature_list[0], bytes): VAR_45.features.feature[feature_name].bytes_list.value.extend( feature_list) elif isinstance(feature_list[0], six.integer_types): VAR_45.features.feature[feature_name].int64_list.value.extend( feature_list) else: raise ValueError( 'Type %VAR_30 for VAR_34 %VAR_30 is not supported for tf.train.Feature.' % (type(feature_list[0]), feature_list[0])) return VAR_45.SerializeToString() def FUNC_17(VAR_17, VAR_18, VAR_20): VAR_46 = {} VAR_47 = FUNC_13(VAR_17) VAR_48 = FUNC_14(VAR_18) VAR_49 = FUNC_15(VAR_20) for VAR_74, (filename, variable_name) in VAR_47.items(): VAR_73 = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # pylint: disable=unexpected-keyword-arg if variable_name: if isinstance(VAR_73, np.ndarray): logging.warn( 'Input file %VAR_30 contains a single ndarray. Name key \"%VAR_30\" ignored.' % (filename, variable_name)) VAR_46[VAR_74] = VAR_73 else: if variable_name in VAR_73: VAR_46[VAR_74] = VAR_73[variable_name] else: raise RuntimeError( 'Input file %VAR_30 does not contain variable with name \"%VAR_30\".' % (filename, variable_name)) else: if isinstance(VAR_73, np.lib.npyio.NpzFile): VAR_83 = VAR_73.files if len(VAR_83) != 1: raise RuntimeError( 'Input file %VAR_30 contains more than one ndarrays. Please specify ' 'the name of ndarray to use.' % filename) VAR_46[VAR_74] = VAR_73[VAR_83[0]] else: VAR_46[VAR_74] = VAR_73 for VAR_74, py_expr_evaluated in VAR_48.items(): if VAR_74 in VAR_46: logging.warn( 'input_key %VAR_30 has been specified with both --VAR_47 and --input_exprs' ' options. Value in --VAR_48 will be used.' % VAR_74) VAR_46[VAR_74] = py_expr_evaluated for VAR_74, VAR_45 in VAR_49.items(): if VAR_74 in VAR_46: logging.warn( 'input_key %VAR_30 has been specified in multiple options. Value in ' '--VAR_49 will be used.' % VAR_74) VAR_46[VAR_74] = VAR_45 return VAR_46 def FUNC_18(VAR_22): if VAR_22.all: FUNC_8(VAR_22.dir) else: if VAR_22.tag_set is None: FUNC_0(VAR_22.dir) else: if VAR_22.signature_def is None: FUNC_1(VAR_22.dir, VAR_22.tag_set) else: FUNC_4(VAR_22.dir, VAR_22.tag_set, VAR_22.signature_def) def FUNC_19(VAR_22): if not VAR_22.inputs and not VAR_22.input_exprs and not VAR_22.input_examples: raise AttributeError( 'At least one of --VAR_47, --VAR_48 or --VAR_49 must be ' 'required') VAR_46 = FUNC_17( VAR_22.inputs, VAR_22.input_exprs, VAR_22.input_examples) FUNC_12( VAR_22.dir, VAR_22.tag_set, VAR_22.signature_def, VAR_46, VAR_22.outdir, VAR_22.overwrite, VAR_13=VAR_22.worker, VAR_14=VAR_22.init_tpu, VAR_15=VAR_22.use_tfrt, VAR_16=VAR_22.tf_debug) def FUNC_20(VAR_22): if VAR_22.tag_set: FUNC_11( saved_model_utils.get_meta_graph_def(VAR_22.dir, VAR_22.tag_set)) else: VAR_75 = saved_model_utils.read_saved_model(VAR_22.dir) for VAR_4 in VAR_75.meta_graphs: FUNC_11(VAR_4) def FUNC_21(VAR_22): from tensorflow.python.compiler.tensorrt import trt_convert as trt # pylint: disable=g-import-not-at-top if not VAR_22.convert_tf1_model: VAR_76 = trt.DEFAULT_TRT_CONVERSION_PARAMS._replace( max_workspace_size_bytes=VAR_22.max_workspace_size_bytes, precision_mode=VAR_22.precision_mode, minimum_segment_size=VAR_22.minimum_segment_size) VAR_77 = trt.TrtGraphConverterV2( input_saved_model_dir=VAR_22.dir, input_saved_model_tags=VAR_22.tag_set.split(','), **VAR_76._asdict()) try: VAR_77.convert() except Exception as e: raise RuntimeError( '{}. Try passing "--convert_tf1_model=True".'.format(e)) VAR_77.save(output_saved_model_dir=VAR_22.output_dir) else: trt.create_inference_graph( None, None, max_batch_size=1, max_workspace_size_bytes=VAR_22.max_workspace_size_bytes, precision_mode=VAR_22.precision_mode, minimum_segment_size=VAR_22.minimum_segment_size, is_dynamic_op=True, input_saved_model_dir=VAR_22.dir, input_saved_model_tags=VAR_22.tag_set.split(','), output_saved_model_dir=VAR_22.output_dir) def FUNC_22(VAR_22): VAR_50 = ( VAR_22.checkpoint_path or os.path.join(VAR_22.dir, 'variables/variables')) if not VAR_22.variables_to_feed: VAR_78 = [] elif VAR_22.variables_to_feed.lower() == 'all': VAR_78 = None # We will identify them after. else: VAR_78 = VAR_22.variables_to_feed.split(',') saved_model_aot_compile.freeze_model( VAR_50=checkpoint_path, VAR_4=saved_model_utils.get_meta_graph_def( VAR_22.dir, VAR_22.tag_set), VAR_5=VAR_22.signature_def_key, VAR_78=variables_to_feed, output_prefix=VAR_22.output_prefix) def FUNC_23(VAR_22): VAR_50 = ( VAR_22.checkpoint_path or os.path.join(VAR_22.dir, 'variables/variables')) if not VAR_22.variables_to_feed: VAR_78 = [] elif VAR_22.variables_to_feed.lower() == 'all': VAR_78 = None # We will identify them after. else: VAR_78 = VAR_22.variables_to_feed.split(',') saved_model_aot_compile.aot_compile_cpu_meta_graph_def( VAR_50=checkpoint_path, VAR_4=saved_model_utils.get_meta_graph_def( VAR_22.dir, VAR_22.tag_set), VAR_5=VAR_22.signature_def_key, VAR_78=variables_to_feed, output_prefix=VAR_22.output_prefix, target_triple=VAR_22.target_triple, target_cpu=VAR_22.target_cpu, cpp_class=VAR_22.cpp_class, multithreading=VAR_22.multithreading.lower() not in ('f', 'false', '0')) def FUNC_24(VAR_23): VAR_51 = ( 'Usage examples:\n' 'To FUNC_18 all tag-sets in a SavedModel:\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75\n\n' 'To FUNC_18 all available SignatureDef keys in a ' 'MetaGraphDef specified by its tag-set:\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --VAR_3 serve\n\n' 'For a MetaGraphDef with multiple tags in the tag-set, all tags must be ' 'passed in, separated by \';\':\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --VAR_3 serve,gpu\n\n' 'To FUNC_18 all VAR_47 and VAR_69 TensorInfo for a specific' ' SignatureDef specified by the SignatureDef key in a' ' MetaGraph.\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --VAR_3 serve' ' --signature_def serving_default\n\n' 'To FUNC_18 all available information in the SavedModel:\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --all') VAR_52 = VAR_23.add_parser( 'show', description=VAR_51, formatter_class=argparse.RawTextHelpFormatter) VAR_52.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to inspect') VAR_52.add_argument( '--all', action='store_true', help='if set, will output all information in given SavedModel') VAR_52.add_argument( '--tag_set', type=str, default=None, help='tag-set of graph in SavedModel to FUNC_18, separated by \',\'') VAR_52.add_argument( '--signature_def', type=str, default=None, metavar='SIGNATURE_DEF_KEY', help='key of SignatureDef to display input(VAR_30) and output(VAR_30) for') VAR_52.set_defaults(func=FUNC_18) def FUNC_25(VAR_23): VAR_53 = ('Usage VAR_45:\n' 'To FUNC_19 input tensors from files through a MetaGraphDef and save' ' the output tensors to files:\n' '$saved_model_cli FUNC_18 --dir /tmp/VAR_75 --VAR_3 serve \\\n' ' --signature_def serving_default \\\n' ' --VAR_47 input1_key=/tmp/124.npz[x],input2_key=/tmp/123.npy ' '\\\n' ' --VAR_48 \'input3_key=np.ones(2)\' \\\n' ' --VAR_49 ' '\'input4_key=[{"id":[26],"weights":[0.5, 0.5]}]\' \\\n' ' --VAR_11=/out\n\n' 'For more information about input file format, please see:\n' 'https://www.tensorflow.org/guide/saved_model_cli\n') VAR_54 = VAR_23.add_parser( 'run', description=VAR_53, formatter_class=argparse.RawTextHelpFormatter) VAR_54.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to execute') VAR_54.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to load, separated by \',\'') VAR_54.add_argument( '--signature_def', type=str, required=True, metavar='SIGNATURE_DEF_KEY', help='key of SignatureDef to run') VAR_55 = ('Loading VAR_47 from files, in the format of \'<VAR_71>=<filename>,' ' or \'<VAR_71>=<filename>[<variable_name>]\', separated by \';\'.' ' The file format can only be from .npy, .npz or pickle.') VAR_54.add_argument('--inputs', type=str, default='', help=VAR_55) VAR_55 = ('Specifying VAR_47 by python expressions, in the format of' ' "<VAR_71>=\'<python expression>\'", separated by \';\'. ' 'numpy module is available as \'np\'. Please note that the expression ' 'will be evaluated as-is, and is susceptible to code injection. ' 'When this is set, the VAR_34 will override duplicate input keys from ' '--VAR_47 option.') VAR_54.add_argument('--input_exprs', type=str, default='', help=VAR_55) VAR_55 = ( 'Specifying tf.Example VAR_47 as list of dictionaries. For VAR_45: ' '<VAR_71>=[{feature0:value_list,feature1:value_list}]. Use ";" to ' 'separate input keys. Will override duplicate input keys from --VAR_47 ' 'and --VAR_48 option.') VAR_54.add_argument('--input_examples', type=str, default='', help=VAR_55) VAR_54.add_argument( '--outdir', type=str, default=None, help='if specified, output tensor(VAR_30) will be saved to given directory') VAR_54.add_argument( '--overwrite', action='store_true', help='if set, output file will be overwritten if it already exists.') VAR_54.add_argument( '--tf_debug', action='store_true', help='if set, will use TensorFlow Debugger (tfdbg) to watch the ' 'intermediate Tensors and runtime GraphDefs while running the ' 'SavedModel.') VAR_54.add_argument( '--worker', type=str, default=None, help='if specified, a Session will be FUNC_19 on the VAR_13. ' 'Valid VAR_13 specification is a bns or gRPC path.') VAR_54.add_argument( '--init_tpu', action='store_true', default=None, help='if specified, tpu.initialize_system will be called on the Session. ' 'This option should be only used if the VAR_13 is a TPU job.') VAR_54.add_argument( '--use_tfrt', action='store_true', default=None, help='if specified, TFRT session will be used, instead of TF1 session.') VAR_54.set_defaults(func=FUNC_19) def FUNC_26(VAR_23): VAR_56 = ('Usage VAR_45:\n' 'To FUNC_20 for denylisted ops in SavedModel:\n' '$saved_model_cli FUNC_20 --dir /tmp/VAR_75\n' 'To FUNC_20 a specific MetaGraph, pass in --VAR_3\n') VAR_57 = VAR_23.add_parser( 'scan', description=VAR_56, formatter_class=argparse.RawTextHelpFormatter) VAR_57.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to execute') VAR_57.add_argument( '--tag_set', type=str, help='tag-set of graph in SavedModel to FUNC_20, separated by \',\'') VAR_57.set_defaults(func=FUNC_20) def FUNC_27(VAR_23): VAR_58 = ('Usage VAR_45:\n' 'To convert the SavedModel to one that have TensorRT ops:\n' '$saved_model_cli convert \\\n' ' --dir /tmp/VAR_75 \\\n' ' --VAR_3 serve \\\n' ' --output_dir /tmp/saved_model_trt \\\n' ' tensorrt \n') VAR_59 = VAR_23.add_parser( 'convert', description=VAR_58, formatter_class=argparse.RawTextHelpFormatter) VAR_59.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to convert') VAR_59.add_argument( '--output_dir', type=str, required=True, help='output directory for the converted SavedModel') VAR_59.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to convert, separated by \',\'') VAR_60 = VAR_59.add_subparsers( title='conversion methods', description='valid conversion methods', help='the conversion to FUNC_19 with the SavedModel') VAR_61 = VAR_60.add_parser( 'tensorrt', description='Convert the SavedModel with Tensorflow-TensorRT integration', formatter_class=argparse.RawTextHelpFormatter) VAR_61.add_argument( '--max_workspace_size_bytes', type=int, default=2 << 20, help=('the maximum GPU temporary memory which the TRT engine can use at ' 'execution time')) VAR_61.add_argument( '--precision_mode', type=str, default='FP32', help='one of FP32, FP16 and INT8') VAR_61.add_argument( '--minimum_segment_size', type=int, default=3, help=('the minimum number of nodes required for a subgraph to be replaced' 'in a TensorRT node')) VAR_61.add_argument( '--convert_tf1_model', type=bool, default=False, help='support TRT conversion for TF1 models') VAR_61.set_defaults(func=FUNC_21) def FUNC_28(VAR_24): VAR_24.add_argument( '--dir', type=str, required=True, help='directory containing the SavedModel to convert') VAR_24.add_argument( '--output_prefix', type=str, required=True, help=('output directory + filename prefix for the resulting header(VAR_30) ' 'and object file(VAR_30)')) VAR_24.add_argument( '--tag_set', type=str, required=True, help='tag-set of graph in SavedModel to convert, separated by \',\'') VAR_24.add_argument( '--signature_def_key', type=str, default=signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, help=('signature_def key to use. ' 'default: DEFAULT_SERVING_SIGNATURE_DEF_KEY')) VAR_24.add_argument( '--checkpoint_path', type=str, default=None, help='Custom checkpoint to use (default: use the SavedModel variables)') VAR_24.add_argument( '--variables_to_feed', type=str, default='', help=('The names of variables that will be fed into the network. ' 'Options are: empty (default; all variables are frozen, none may ' 'be fed), \'all\' (all variables may be fed), or a ' 'comma-delimited list of names of variables that may be fed. In ' 'the last case, the non-fed variables will be frozen in the graph.' '**NOTE** Any variables passed to `VAR_78` *must be set ' 'by the user*. These variables will NOT be frozen and their ' 'values will be uninitialized in the compiled object ' '(this applies to all input VAR_7 from the signature as ' 'well).')) def FUNC_29(VAR_23): VAR_62 = '\n'.join( ['Usage VAR_45:', 'To freeze a SavedModel in preparation for tfcompile:', '$saved_model_cli FUNC_22 \\', ' --dir /tmp/VAR_75 \\', ' --VAR_3 serve \\', ' --output_prefix /tmp/saved_model_xla_aot', ]) VAR_24 = VAR_23.add_parser( 'freeze_model', description=VAR_62, formatter_class=argparse.RawTextHelpFormatter) FUNC_28(VAR_24) VAR_24.set_defaults(func=FUNC_22) def FUNC_30(VAR_23): VAR_62 = '\n'.join( ['Usage VAR_45:', 'To compile a SavedModel signature via (CPU) XLA AOT:', '$saved_model_cli FUNC_23 \\', ' --dir /tmp/VAR_75 \\', ' --VAR_3 serve \\', ' --output_dir /tmp/saved_model_xla_aot', '', '', 'Note: Additional XLA compilation options are available by setting the ', 'XLA_FLAGS environment variable. See the XLA debug options flags for ', 'all the options: ', ' {}'.format(VAR_0), '', 'For VAR_45, to disable XLA fast math when compiling:', '', 'XLA_FLAGS="--xla_cpu_enable_fast_math=false" $saved_model_cli ' 'aot_compile_cpu ...', '', 'Some possibly useful flags:', ' --xla_cpu_enable_fast_math=false', ' --xla_force_host_platform_device_count=<num threads>', ' (useful in conjunction with disabling multi threading)' ]) VAR_24 = VAR_23.add_parser( 'aot_compile_cpu', description=VAR_62, formatter_class=argparse.RawTextHelpFormatter) FUNC_28(VAR_24) VAR_24.add_argument( '--target_triple', type=str, default='x86_64-pc-linux', help=('Target triple for LLVM during AOT compilation. Examples: ' 'x86_64-none-darwin, x86_64-apple-ios, arm64-none-ios, ' 'armv7-none-android. More examples are available in tfcompile.bzl ' 'in the tensorflow codebase.')) VAR_24.add_argument( '--target_cpu', type=str, default='', help=('Target cpu name for LLVM during AOT compilation. Examples: ' 'x86_64, skylake, haswell, westmere, <empty> (unknown). For ' 'a complete list of options, FUNC_19 (for x86 targets): ' '`llc -march=x86 -mcpu=help`')) VAR_24.add_argument( '--cpp_class', type=str, required=True, help=('The name of the generated C++ class, wrapping the generated ' 'function. The syntax of this flag is ' '[[<optional_namespace>::],...]<class_name>. This mirrors the ' 'C++ syntax for referring to a class, where multiple namespaces ' 'may precede the class name, separated by double-colons. ' 'The class will be generated in the given namespace(VAR_30), or if no ' 'namespaces are given, within the global namespace.')) VAR_24.add_argument( '--multithreading', type=str, default='False', help=('Enable multithreading in the compiled computation. ' 'Note that if using this option, the resulting object files ' 'may have external dependencies on multithreading libraries ' 'like nsync.')) VAR_24.set_defaults(func=FUNC_23) def FUNC_31(): VAR_63 = argparse.ArgumentParser( description='saved_model_cli: Command-line interface for SavedModel') VAR_63.add_argument('-v', '--version', action='version', version='0.1.0') VAR_23 = VAR_63.add_subparsers( title='commands', description='valid commands', help='additional help') FUNC_24(VAR_23) FUNC_25(VAR_23) FUNC_26(VAR_23) FUNC_27(VAR_23) FUNC_30(VAR_23) FUNC_29(VAR_23) return VAR_63 def FUNC_32(): logging.set_verbosity(logging.INFO) VAR_63 = FUNC_31() VAR_22 = VAR_63.parse_args() if not hasattr(VAR_22, 'func'): VAR_63.error('too few arguments') VAR_22.func(VAR_22) if __name__ == '__main__': sys.exit(FUNC_32())
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 19, 21, 27, 31, 52, 53, 57, 58, 59, 61, 62, 65, 67, 75, 76, 79, 82, 94, 95, 99, 102, 107, 110, 119, 120, 124, 127, 132, 137, 138, 141, 144, 158, 162, 167, 173, 176, 177, 180, 186, 193, 215, 216, 224, 225, 228, 236, 240, 243, 267, 268, 271, 279, 283, 292, 293, 296, 299, 307, 315, 316, 319, 322, 328, 332, 337, 338, 341, 344, 350, 356, 357, 360, 363, 371, 378, 379, 391, 395, 415, 421, 424, 425, 426, 429, 430, 437, 442, 445, 451, 460, 461, 463, 465, 468, 470, 474, 475, 477, 481, 482, 487, 491, 492, 495, 503, 511, 514, 521, 523, 527, 536, 538, 539, 542, 545, 552, 555, 560, 573, 576, 577, 580, 584, 591, 594, 608, 609, 634, 635, 639, 644, 674, 677, 685, 689, 692, 693, 695, 708, 710, 720, 721, 728, 729, 737, 738, 741, 745, 749, 750, 751, 759, 760, 763, 766, 788, 789, 792, 803, 804, 807, 811, 812, 814, 842, 843, 846, 859, 867, 868, 871, 884, 896, 897, 942, 943, 1027, 1028, 1049, 1050, 1110, 1111, 1155, 1156, 1167, 1174, 1175, 1201, 1242, 1244, 1245, 1248, 1255, 1258, 1259, 1261, 1262, 1264, 1265, 1267, 1268, 1270, 1271, 1273, 1274, 1277, 1278, 1286, 1287, 1290, 15, 16, 17, 18, 19, 20, 64, 65, 66, 67, 68, 69, 70, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 179, 180, 181, 182, 183, 227, 228, 229, 230, 231, 232, 233, 234, 270, 271, 272, 273, 274, 275, 295, 296, 297, 298, 299, 300, 301, 302, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 359, 360, 361, 362, 363, 364, 365, 366, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 611, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 740, 741, 742, 743, 744, 762, 763, 764, 765, 766, 767, 768, 769, 770, 791, 792, 793, 794, 795, 806, 807, 808, 809, 810, 845, 846, 847, 848, 849, 870, 871, 872, 873, 874, 899, 945, 1030, 1052, 1113, 1158, 1177, 1247, 1248, 1249, 1250, 1251 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 19, 21, 27, 31, 52, 53, 57, 58, 59, 61, 62, 65, 67, 75, 76, 79, 82, 94, 95, 99, 102, 107, 110, 119, 120, 124, 127, 132, 137, 138, 141, 144, 158, 162, 167, 173, 176, 177, 180, 186, 193, 215, 216, 224, 225, 228, 236, 240, 243, 267, 268, 271, 279, 283, 292, 293, 296, 299, 307, 315, 316, 319, 322, 328, 332, 337, 338, 341, 344, 350, 356, 357, 360, 363, 371, 378, 379, 391, 395, 415, 421, 424, 425, 426, 429, 430, 437, 442, 445, 451, 460, 461, 463, 465, 468, 470, 474, 475, 477, 481, 482, 487, 491, 492, 495, 503, 511, 514, 521, 523, 527, 536, 538, 539, 542, 545, 552, 555, 560, 573, 576, 577, 580, 584, 591, 594, 608, 609, 634, 635, 639, 644, 674, 677, 685, 689, 692, 693, 695, 708, 710, 720, 721, 728, 729, 737, 738, 741, 745, 749, 750, 751, 759, 760, 763, 766, 788, 789, 792, 803, 804, 807, 811, 812, 814, 842, 843, 846, 859, 867, 868, 871, 884, 896, 897, 942, 943, 1027, 1028, 1049, 1050, 1110, 1111, 1155, 1156, 1167, 1174, 1175, 1201, 1242, 1244, 1245, 1248, 1255, 1258, 1259, 1261, 1262, 1264, 1265, 1267, 1268, 1270, 1271, 1273, 1274, 1277, 1278, 1286, 1287, 1290, 15, 16, 17, 18, 19, 20, 64, 65, 66, 67, 68, 69, 70, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 179, 180, 181, 182, 183, 227, 228, 229, 230, 231, 232, 233, 234, 270, 271, 272, 273, 274, 275, 295, 296, 297, 298, 299, 300, 301, 302, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 359, 360, 361, 362, 363, 364, 365, 366, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 611, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 740, 741, 742, 743, 744, 762, 763, 764, 765, 766, 767, 768, 769, 770, 791, 792, 793, 794, 795, 806, 807, 808, 809, 810, 845, 846, 847, 848, 849, 870, 871, 872, 873, 874, 899, 945, 1030, 1052, 1113, 1158, 1177, 1247, 1248, 1249, 1250, 1251 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # Copyright 2018 New Vector Ltd # Copyright 2019 Matrix.org Federation C.I.C # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union, ) from prometheus_client import Counter, Gauge, Histogram from twisted.internet import defer from twisted.internet.abstract import isIPAddress from twisted.python import failure from synapse.api.constants import EventTypes, Membership from synapse.api.errors import ( AuthError, Codes, FederationError, IncompatibleRoomVersionError, NotFoundError, SynapseError, UnsupportedRoomVersionError, ) from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.events import EventBase from synapse.federation.federation_base import FederationBase, event_from_pdu_json from synapse.federation.persistence import TransactionActions from synapse.federation.units import Edu, Transaction from synapse.http.endpoint import parse_server_name from synapse.http.servlet import assert_params_in_dict from synapse.logging.context import ( make_deferred_yieldable, nested_logging_context, run_in_background, ) from synapse.logging.opentracing import log_kv, start_active_span_from_edu, trace from synapse.logging.utils import log_function from synapse.replication.http.federation import ( ReplicationFederationSendEduRestServlet, ReplicationGetQueryRestServlet, ) from synapse.types import JsonDict, get_domain_from_id from synapse.util import glob_to_regex, json_decoder, unwrapFirstError from synapse.util.async_helpers import Linearizer, concurrently_execute from synapse.util.caches.response_cache import ResponseCache if TYPE_CHECKING: from synapse.server import HomeServer # when processing incoming transactions, we try to handle multiple rooms in # parallel, up to this limit. TRANSACTION_CONCURRENCY_LIMIT = 10 logger = logging.getLogger(__name__) received_pdus_counter = Counter("synapse_federation_server_received_pdus", "") received_edus_counter = Counter("synapse_federation_server_received_edus", "") received_queries_counter = Counter( "synapse_federation_server_received_queries", "", ["type"] ) pdu_process_time = Histogram( "synapse_federation_server_pdu_process_time", "Time taken to process an event", ) last_pdu_age_metric = Gauge( "synapse_federation_last_received_pdu_age", "The age (in seconds) of the last PDU successfully received from the given domain", labelnames=("server_name",), ) class FederationServer(FederationBase): def __init__(self, hs): super().__init__(hs) self.auth = hs.get_auth() self.handler = hs.get_federation_handler() self.state = hs.get_state_handler() self.device_handler = hs.get_device_handler() # Ensure the following handlers are loaded since they register callbacks # with FederationHandlerRegistry. hs.get_directory_handler() self._federation_ratelimiter = hs.get_federation_ratelimiter() self._server_linearizer = Linearizer("fed_server") self._transaction_linearizer = Linearizer("fed_txn_handler") # We cache results for transaction with the same ID self._transaction_resp_cache = ResponseCache( hs, "fed_txn_handler", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self.transaction_actions = TransactionActions(self.store) self.registry = hs.get_federation_registry() # We cache responses to state queries, as they take a while and often # come in waves. self._state_resp_cache = ResponseCache( hs, "state_resp", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self._state_ids_resp_cache = ResponseCache( hs, "state_ids_resp", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self._federation_metrics_domains = ( hs.get_config().federation.federation_metrics_domains ) async def on_backfill_request( self, origin: str, room_id: str, versions: List[str], limit: int ) -> Tuple[int, Dict[str, Any]]: with (await self._server_linearizer.queue((origin, room_id))): origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) pdus = await self.handler.on_backfill_request( origin, room_id, versions, limit ) res = self._transaction_from_pdus(pdus).get_dict() return 200, res async def on_incoming_transaction( self, origin: str, transaction_data: JsonDict ) -> Tuple[int, Dict[str, Any]]: # keep this as early as possible to make the calculated origin ts as # accurate as possible. request_time = self._clock.time_msec() transaction = Transaction(**transaction_data) transaction_id = transaction.transaction_id # type: ignore if not transaction_id: raise Exception("Transaction missing transaction_id") logger.debug("[%s] Got transaction", transaction_id) # We wrap in a ResponseCache so that we de-duplicate retried # transactions. return await self._transaction_resp_cache.wrap( (origin, transaction_id), self._on_incoming_transaction_inner, origin, transaction, request_time, ) async def _on_incoming_transaction_inner( self, origin: str, transaction: Transaction, request_time: int ) -> Tuple[int, Dict[str, Any]]: # Use a linearizer to ensure that transactions from a remote are # processed in order. with await self._transaction_linearizer.queue(origin): # We rate limit here *after* we've queued up the incoming requests, # so that we don't fill up the ratelimiter with blocked requests. # # This is important as the ratelimiter allows N concurrent requests # at a time, and only starts ratelimiting if there are more requests # than that being processed at a time. If we queued up requests in # the linearizer/response cache *after* the ratelimiting then those # queued up requests would count as part of the allowed limit of N # concurrent requests. with self._federation_ratelimiter.ratelimit(origin) as d: await d result = await self._handle_incoming_transaction( origin, transaction, request_time ) return result async def _handle_incoming_transaction( self, origin: str, transaction: Transaction, request_time: int ) -> Tuple[int, Dict[str, Any]]: """ Process an incoming transaction and return the HTTP response Args: origin: the server making the request transaction: incoming transaction request_time: timestamp that the HTTP request arrived at Returns: HTTP response code and body """ response = await self.transaction_actions.have_responded(origin, transaction) if response: logger.debug( "[%s] We've already responded to this request", transaction.transaction_id, # type: ignore ) return response logger.debug("[%s] Transaction is new", transaction.transaction_id) # type: ignore # Reject if PDU count > 50 or EDU count > 100 if len(transaction.pdus) > 50 or ( # type: ignore hasattr(transaction, "edus") and len(transaction.edus) > 100 # type: ignore ): logger.info("Transaction PDU or EDU count too large. Returning 400") response = {} await self.transaction_actions.set_response( origin, transaction, 400, response ) return 400, response # We process PDUs and EDUs in parallel. This is important as we don't # want to block things like to device messages from reaching clients # behind the potentially expensive handling of PDUs. pdu_results, _ = await make_deferred_yieldable( defer.gatherResults( [ run_in_background( self._handle_pdus_in_txn, origin, transaction, request_time ), run_in_background(self._handle_edus_in_txn, origin, transaction), ], consumeErrors=True, ).addErrback(unwrapFirstError) ) response = {"pdus": pdu_results} logger.debug("Returning: %s", str(response)) await self.transaction_actions.set_response(origin, transaction, 200, response) return 200, response async def _handle_pdus_in_txn( self, origin: str, transaction: Transaction, request_time: int ) -> Dict[str, dict]: """Process the PDUs in a received transaction. Args: origin: the server making the request transaction: incoming transaction request_time: timestamp that the HTTP request arrived at Returns: A map from event ID of a processed PDU to any errors we should report back to the sending server. """ received_pdus_counter.inc(len(transaction.pdus)) # type: ignore origin_host, _ = parse_server_name(origin) pdus_by_room = {} # type: Dict[str, List[EventBase]] newest_pdu_ts = 0 for p in transaction.pdus: # type: ignore # FIXME (richardv): I don't think this works: # https://github.com/matrix-org/synapse/issues/8429 if "unsigned" in p: unsigned = p["unsigned"] if "age" in unsigned: p["age"] = unsigned["age"] if "age" in p: p["age_ts"] = request_time - int(p["age"]) del p["age"] # We try and pull out an event ID so that if later checks fail we # can log something sensible. We don't mandate an event ID here in # case future event formats get rid of the key. possible_event_id = p.get("event_id", "<Unknown>") # Now we get the room ID so that we can check that we know the # version of the room. room_id = p.get("room_id") if not room_id: logger.info( "Ignoring PDU as does not have a room_id. Event ID: %s", possible_event_id, ) continue try: room_version = await self.store.get_room_version(room_id) except NotFoundError: logger.info("Ignoring PDU for unknown room_id: %s", room_id) continue except UnsupportedRoomVersionError as e: # this can happen if support for a given room version is withdrawn, # so that we still get events for said room. logger.info("Ignoring PDU: %s", e) continue event = event_from_pdu_json(p, room_version) pdus_by_room.setdefault(room_id, []).append(event) if event.origin_server_ts > newest_pdu_ts: newest_pdu_ts = event.origin_server_ts pdu_results = {} # we can process different rooms in parallel (which is useful if they # require callouts to other servers to fetch missing events), but # impose a limit to avoid going too crazy with ram/cpu. async def process_pdus_for_room(room_id: str): logger.debug("Processing PDUs for %s", room_id) try: await self.check_server_matches_acl(origin_host, room_id) except AuthError as e: logger.warning("Ignoring PDUs for room %s from banned server", room_id) for pdu in pdus_by_room[room_id]: event_id = pdu.event_id pdu_results[event_id] = e.error_dict() return for pdu in pdus_by_room[room_id]: event_id = pdu.event_id with pdu_process_time.time(): with nested_logging_context(event_id): try: await self._handle_received_pdu(origin, pdu) pdu_results[event_id] = {} except FederationError as e: logger.warning("Error handling PDU %s: %s", event_id, e) pdu_results[event_id] = {"error": str(e)} except Exception as e: f = failure.Failure() pdu_results[event_id] = {"error": str(e)} logger.error( "Failed to handle PDU %s", event_id, exc_info=(f.type, f.value, f.getTracebackObject()), ) await concurrently_execute( process_pdus_for_room, pdus_by_room.keys(), TRANSACTION_CONCURRENCY_LIMIT ) if newest_pdu_ts and origin in self._federation_metrics_domains: newest_pdu_age = self._clock.time_msec() - newest_pdu_ts last_pdu_age_metric.labels(server_name=origin).set(newest_pdu_age / 1000) return pdu_results async def _handle_edus_in_txn(self, origin: str, transaction: Transaction): """Process the EDUs in a received transaction. """ async def _process_edu(edu_dict): received_edus_counter.inc() edu = Edu( origin=origin, destination=self.server_name, edu_type=edu_dict["edu_type"], content=edu_dict["content"], ) await self.registry.on_edu(edu.edu_type, origin, edu.content) await concurrently_execute( _process_edu, getattr(transaction, "edus", []), TRANSACTION_CONCURRENCY_LIMIT, ) async def on_room_state_request( self, origin: str, room_id: str, event_id: str ) -> Tuple[int, Dict[str, Any]]: origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) in_room = await self.auth.check_host_in_room(room_id, origin) if not in_room: raise AuthError(403, "Host not in room.") # we grab the linearizer to protect ourselves from servers which hammer # us. In theory we might already have the response to this query # in the cache so we could return it without waiting for the linearizer # - but that's non-trivial to get right, and anyway somewhat defeats # the point of the linearizer. with (await self._server_linearizer.queue((origin, room_id))): resp = dict( await self._state_resp_cache.wrap( (room_id, event_id), self._on_context_state_request_compute, room_id, event_id, ) ) room_version = await self.store.get_room_version_id(room_id) resp["room_version"] = room_version return 200, resp async def on_state_ids_request( self, origin: str, room_id: str, event_id: str ) -> Tuple[int, Dict[str, Any]]: if not event_id: raise NotImplementedError("Specify an event") origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) in_room = await self.auth.check_host_in_room(room_id, origin) if not in_room: raise AuthError(403, "Host not in room.") resp = await self._state_ids_resp_cache.wrap( (room_id, event_id), self._on_state_ids_request_compute, room_id, event_id, ) return 200, resp async def _on_state_ids_request_compute(self, room_id, event_id): state_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id) auth_chain_ids = await self.store.get_auth_chain_ids(state_ids) return {"pdu_ids": state_ids, "auth_chain_ids": auth_chain_ids} async def _on_context_state_request_compute( self, room_id: str, event_id: str ) -> Dict[str, list]: if event_id: pdus = await self.handler.get_state_for_pdu(room_id, event_id) else: pdus = (await self.state.get_current_state(room_id)).values() auth_chain = await self.store.get_auth_chain([pdu.event_id for pdu in pdus]) return { "pdus": [pdu.get_pdu_json() for pdu in pdus], "auth_chain": [pdu.get_pdu_json() for pdu in auth_chain], } async def on_pdu_request( self, origin: str, event_id: str ) -> Tuple[int, Union[JsonDict, str]]: pdu = await self.handler.get_persisted_pdu(origin, event_id) if pdu: return 200, self._transaction_from_pdus([pdu]).get_dict() else: return 404, "" async def on_query_request( self, query_type: str, args: Dict[str, str] ) -> Tuple[int, Dict[str, Any]]: received_queries_counter.labels(query_type).inc() resp = await self.registry.on_query(query_type, args) return 200, resp async def on_make_join_request( self, origin: str, room_id: str, user_id: str, supported_versions: List[str] ) -> Dict[str, Any]: origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) room_version = await self.store.get_room_version_id(room_id) if room_version not in supported_versions: logger.warning( "Room version %s not in %s", room_version, supported_versions ) raise IncompatibleRoomVersionError(room_version=room_version) pdu = await self.handler.on_make_join_request(origin, room_id, user_id) time_now = self._clock.time_msec() return {"event": pdu.get_pdu_json(time_now), "room_version": room_version} async def on_invite_request( self, origin: str, content: JsonDict, room_version_id: str ) -> Dict[str, Any]: room_version = KNOWN_ROOM_VERSIONS.get(room_version_id) if not room_version: raise SynapseError( 400, "Homeserver does not support this room version", Codes.UNSUPPORTED_ROOM_VERSION, ) pdu = event_from_pdu_json(content, room_version) origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, pdu.room_id) pdu = await self._check_sigs_and_hash(room_version, pdu) ret_pdu = await self.handler.on_invite_request(origin, pdu, room_version) time_now = self._clock.time_msec() return {"event": ret_pdu.get_pdu_json(time_now)} async def on_send_join_request( self, origin: str, content: JsonDict ) -> Dict[str, Any]: logger.debug("on_send_join_request: content: %s", content) assert_params_in_dict(content, ["room_id"]) room_version = await self.store.get_room_version(content["room_id"]) pdu = event_from_pdu_json(content, room_version) origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, pdu.room_id) logger.debug("on_send_join_request: pdu sigs: %s", pdu.signatures) pdu = await self._check_sigs_and_hash(room_version, pdu) res_pdus = await self.handler.on_send_join_request(origin, pdu) time_now = self._clock.time_msec() return { "state": [p.get_pdu_json(time_now) for p in res_pdus["state"]], "auth_chain": [p.get_pdu_json(time_now) for p in res_pdus["auth_chain"]], } async def on_make_leave_request( self, origin: str, room_id: str, user_id: str ) -> Dict[str, Any]: origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) pdu = await self.handler.on_make_leave_request(origin, room_id, user_id) room_version = await self.store.get_room_version_id(room_id) time_now = self._clock.time_msec() return {"event": pdu.get_pdu_json(time_now), "room_version": room_version} async def on_send_leave_request(self, origin: str, content: JsonDict) -> dict: logger.debug("on_send_leave_request: content: %s", content) assert_params_in_dict(content, ["room_id"]) room_version = await self.store.get_room_version(content["room_id"]) pdu = event_from_pdu_json(content, room_version) origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, pdu.room_id) logger.debug("on_send_leave_request: pdu sigs: %s", pdu.signatures) pdu = await self._check_sigs_and_hash(room_version, pdu) await self.handler.on_send_leave_request(origin, pdu) return {} async def on_event_auth( self, origin: str, room_id: str, event_id: str ) -> Tuple[int, Dict[str, Any]]: with (await self._server_linearizer.queue((origin, room_id))): origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) time_now = self._clock.time_msec() auth_pdus = await self.handler.on_event_auth(event_id) res = {"auth_chain": [a.get_pdu_json(time_now) for a in auth_pdus]} return 200, res @log_function async def on_query_client_keys( self, origin: str, content: Dict[str, str] ) -> Tuple[int, Dict[str, Any]]: return await self.on_query_request("client_keys", content) async def on_query_user_devices( self, origin: str, user_id: str ) -> Tuple[int, Dict[str, Any]]: keys = await self.device_handler.on_federation_query_user_devices(user_id) return 200, keys @trace async def on_claim_client_keys( self, origin: str, content: JsonDict ) -> Dict[str, Any]: query = [] for user_id, device_keys in content.get("one_time_keys", {}).items(): for device_id, algorithm in device_keys.items(): query.append((user_id, device_id, algorithm)) log_kv({"message": "Claiming one time keys.", "user, device pairs": query}) results = await self.store.claim_e2e_one_time_keys(query) json_result = {} # type: Dict[str, Dict[str, dict]] for user_id, device_keys in results.items(): for device_id, keys in device_keys.items(): for key_id, json_str in keys.items(): json_result.setdefault(user_id, {})[device_id] = { key_id: json_decoder.decode(json_str) } logger.info( "Claimed one-time-keys: %s", ",".join( ( "%s for %s:%s" % (key_id, user_id, device_id) for user_id, user_keys in json_result.items() for device_id, device_keys in user_keys.items() for key_id, _ in device_keys.items() ) ), ) return {"one_time_keys": json_result} async def on_get_missing_events( self, origin: str, room_id: str, earliest_events: List[str], latest_events: List[str], limit: int, ) -> Dict[str, list]: with (await self._server_linearizer.queue((origin, room_id))): origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) logger.debug( "on_get_missing_events: earliest_events: %r, latest_events: %r," " limit: %d", earliest_events, latest_events, limit, ) missing_events = await self.handler.on_get_missing_events( origin, room_id, earliest_events, latest_events, limit ) if len(missing_events) < 5: logger.debug( "Returning %d events: %r", len(missing_events), missing_events ) else: logger.debug("Returning %d events", len(missing_events)) time_now = self._clock.time_msec() return {"events": [ev.get_pdu_json(time_now) for ev in missing_events]} @log_function async def on_openid_userinfo(self, token: str) -> Optional[str]: ts_now_ms = self._clock.time_msec() return await self.store.get_user_id_for_open_id_token(token, ts_now_ms) def _transaction_from_pdus(self, pdu_list: List[EventBase]) -> Transaction: """Returns a new Transaction containing the given PDUs suitable for transmission. """ time_now = self._clock.time_msec() pdus = [p.get_pdu_json(time_now) for p in pdu_list] return Transaction( origin=self.server_name, pdus=pdus, origin_server_ts=int(time_now), destination=None, ) async def _handle_received_pdu(self, origin: str, pdu: EventBase) -> None: """ Process a PDU received in a federation /send/ transaction. If the event is invalid, then this method throws a FederationError. (The error will then be logged and sent back to the sender (which probably won't do anything with it), and other events in the transaction will be processed as normal). It is likely that we'll then receive other events which refer to this rejected_event in their prev_events, etc. When that happens, we'll attempt to fetch the rejected event again, which will presumably fail, so those second-generation events will also get rejected. Eventually, we get to the point where there are more than 10 events between any new events and the original rejected event. Since we only try to backfill 10 events deep on received pdu, we then accept the new event, possibly introducing a discontinuity in the DAG, with new forward extremities, so normal service is approximately returned, until we try to backfill across the discontinuity. Args: origin: server which sent the pdu pdu: received pdu Raises: FederationError if the signatures / hash do not match, or if the event was unacceptable for any other reason (eg, too large, too many prev_events, couldn't find the prev_events) """ # check that it's actually being sent from a valid destination to # workaround bug #1753 in 0.18.5 and 0.18.6 if origin != get_domain_from_id(pdu.sender): # We continue to accept join events from any server; this is # necessary for the federation join dance to work correctly. # (When we join over federation, the "helper" server is # responsible for sending out the join event, rather than the # origin. See bug #1893. This is also true for some third party # invites). if not ( pdu.type == "m.room.member" and pdu.content and pdu.content.get("membership", None) in (Membership.JOIN, Membership.INVITE) ): logger.info( "Discarding PDU %s from invalid origin %s", pdu.event_id, origin ) return else: logger.info("Accepting join PDU %s from %s", pdu.event_id, origin) # We've already checked that we know the room version by this point room_version = await self.store.get_room_version(pdu.room_id) # Check signature. try: pdu = await self._check_sigs_and_hash(room_version, pdu) except SynapseError as e: raise FederationError("ERROR", e.code, e.msg, affected=pdu.event_id) await self.handler.on_receive_pdu(origin, pdu, sent_to_us_directly=True) def __str__(self): return "<ReplicationLayer(%s)>" % self.server_name async def exchange_third_party_invite( self, sender_user_id: str, target_user_id: str, room_id: str, signed: Dict ): ret = await self.handler.exchange_third_party_invite( sender_user_id, target_user_id, room_id, signed ) return ret async def on_exchange_third_party_invite_request(self, event_dict: Dict): ret = await self.handler.on_exchange_third_party_invite_request(event_dict) return ret async def check_server_matches_acl(self, server_name: str, room_id: str): """Check if the given server is allowed by the server ACLs in the room Args: server_name: name of server, *without any port part* room_id: ID of the room to check Raises: AuthError if the server does not match the ACL """ state_ids = await self.store.get_current_state_ids(room_id) acl_event_id = state_ids.get((EventTypes.ServerACL, "")) if not acl_event_id: return acl_event = await self.store.get_event(acl_event_id) if server_matches_acl_event(server_name, acl_event): return raise AuthError(code=403, msg="Server is banned from room") def server_matches_acl_event(server_name: str, acl_event: EventBase) -> bool: """Check if the given server is allowed by the ACL event Args: server_name: name of server, without any port part acl_event: m.room.server_acl event Returns: True if this server is allowed by the ACLs """ logger.debug("Checking %s against acl %s", server_name, acl_event.content) # first of all, check if literal IPs are blocked, and if so, whether the # server name is a literal IP allow_ip_literals = acl_event.content.get("allow_ip_literals", True) if not isinstance(allow_ip_literals, bool): logger.warning("Ignoring non-bool allow_ip_literals flag") allow_ip_literals = True if not allow_ip_literals: # check for ipv6 literals. These start with '['. if server_name[0] == "[": return False # check for ipv4 literals. We can just lift the routine from twisted. if isIPAddress(server_name): return False # next, check the deny list deny = acl_event.content.get("deny", []) if not isinstance(deny, (list, tuple)): logger.warning("Ignoring non-list deny ACL %s", deny) deny = [] for e in deny: if _acl_entry_matches(server_name, e): # logger.info("%s matched deny rule %s", server_name, e) return False # then the allow list. allow = acl_event.content.get("allow", []) if not isinstance(allow, (list, tuple)): logger.warning("Ignoring non-list allow ACL %s", allow) allow = [] for e in allow: if _acl_entry_matches(server_name, e): # logger.info("%s matched allow rule %s", server_name, e) return True # everything else should be rejected. # logger.info("%s fell through", server_name) return False def _acl_entry_matches(server_name: str, acl_entry: Any) -> bool: if not isinstance(acl_entry, str): logger.warning( "Ignoring non-str ACL entry '%s' (is %s)", acl_entry, type(acl_entry) ) return False regex = glob_to_regex(acl_entry) return bool(regex.match(server_name)) class FederationHandlerRegistry: """Allows classes to register themselves as handlers for a given EDU or query type for incoming federation traffic. """ def __init__(self, hs: "HomeServer"): self.config = hs.config self.http_client = hs.get_simple_http_client() self.clock = hs.get_clock() self._instance_name = hs.get_instance_name() # These are safe to load in monolith mode, but will explode if we try # and use them. However we have guards before we use them to ensure that # we don't route to ourselves, and in monolith mode that will always be # the case. self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs) self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs) self.edu_handlers = ( {} ) # type: Dict[str, Callable[[str, dict], Awaitable[None]]] self.query_handlers = {} # type: Dict[str, Callable[[dict], Awaitable[None]]] # Map from type to instance name that we should route EDU handling to. self._edu_type_to_instance = {} # type: Dict[str, str] def register_edu_handler( self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]] ): """Sets the handler callable that will be used to handle an incoming federation EDU of the given type. Args: edu_type: The type of the incoming EDU to register handler for handler: A callable invoked on incoming EDU of the given type. The arguments are the origin server name and the EDU contents. """ if edu_type in self.edu_handlers: raise KeyError("Already have an EDU handler for %s" % (edu_type,)) logger.info("Registering federation EDU handler for %r", edu_type) self.edu_handlers[edu_type] = handler def register_query_handler( self, query_type: str, handler: Callable[[dict], defer.Deferred] ): """Sets the handler callable that will be used to handle an incoming federation query of the given type. Args: query_type: Category name of the query, which should match the string used by make_query. handler: Invoked to handle incoming queries of this type. The return will be yielded on and the result used as the response to the query request. """ if query_type in self.query_handlers: raise KeyError("Already have a Query handler for %s" % (query_type,)) logger.info("Registering federation query handler for %r", query_type) self.query_handlers[query_type] = handler def register_instance_for_edu(self, edu_type: str, instance_name: str): """Register that the EDU handler is on a different instance than master. """ self._edu_type_to_instance[edu_type] = instance_name async def on_edu(self, edu_type: str, origin: str, content: dict): if not self.config.use_presence and edu_type == "m.presence": return # Check if we have a handler on this instance handler = self.edu_handlers.get(edu_type) if handler: with start_active_span_from_edu(content, "handle_edu"): try: await handler(origin, content) except SynapseError as e: logger.info("Failed to handle edu %r: %r", edu_type, e) except Exception: logger.exception("Failed to handle edu %r", edu_type) return # Check if we can route it somewhere else that isn't us route_to = self._edu_type_to_instance.get(edu_type, "master") if route_to != self._instance_name: try: await self._send_edu( instance_name=route_to, edu_type=edu_type, origin=origin, content=content, ) except SynapseError as e: logger.info("Failed to handle edu %r: %r", edu_type, e) except Exception: logger.exception("Failed to handle edu %r", edu_type) return # Oh well, let's just log and move on. logger.warning("No handler registered for EDU type %s", edu_type) async def on_query(self, query_type: str, args: dict): handler = self.query_handlers.get(query_type) if handler: return await handler(args) # Check if we can route it somewhere else that isn't us if self._instance_name == "master": return await self._get_query_client(query_type=query_type, args=args) # Uh oh, no handler! Let's raise an exception so the request returns an # error. logger.warning("No handler registered for query type %s", query_type) raise NotFoundError("No handler for Query type '%s'" % (query_type,))
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # Copyright 2018 New Vector Ltd # Copyright 2019 Matrix.org Federation C.I.C # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union, ) from prometheus_client import Counter, Gauge, Histogram from twisted.internet import defer from twisted.internet.abstract import isIPAddress from twisted.python import failure from synapse.api.constants import EventTypes, Membership from synapse.api.errors import ( AuthError, Codes, FederationError, IncompatibleRoomVersionError, NotFoundError, SynapseError, UnsupportedRoomVersionError, ) from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.events import EventBase from synapse.federation.federation_base import FederationBase, event_from_pdu_json from synapse.federation.persistence import TransactionActions from synapse.federation.units import Edu, Transaction from synapse.http.endpoint import parse_server_name from synapse.http.servlet import assert_params_in_dict from synapse.logging.context import ( make_deferred_yieldable, nested_logging_context, run_in_background, ) from synapse.logging.opentracing import log_kv, start_active_span_from_edu, trace from synapse.logging.utils import log_function from synapse.replication.http.federation import ( ReplicationFederationSendEduRestServlet, ReplicationGetQueryRestServlet, ) from synapse.types import JsonDict, get_domain_from_id from synapse.util import glob_to_regex, json_decoder, unwrapFirstError from synapse.util.async_helpers import Linearizer, concurrently_execute from synapse.util.caches.response_cache import ResponseCache if TYPE_CHECKING: from synapse.server import HomeServer # when processing incoming transactions, we try to handle multiple rooms in # parallel, up to this limit. TRANSACTION_CONCURRENCY_LIMIT = 10 logger = logging.getLogger(__name__) received_pdus_counter = Counter("synapse_federation_server_received_pdus", "") received_edus_counter = Counter("synapse_federation_server_received_edus", "") received_queries_counter = Counter( "synapse_federation_server_received_queries", "", ["type"] ) pdu_process_time = Histogram( "synapse_federation_server_pdu_process_time", "Time taken to process an event", ) last_pdu_age_metric = Gauge( "synapse_federation_last_received_pdu_age", "The age (in seconds) of the last PDU successfully received from the given domain", labelnames=("server_name",), ) class FederationServer(FederationBase): def __init__(self, hs): super().__init__(hs) self.auth = hs.get_auth() self.handler = hs.get_federation_handler() self.state = hs.get_state_handler() self.device_handler = hs.get_device_handler() # Ensure the following handlers are loaded since they register callbacks # with FederationHandlerRegistry. hs.get_directory_handler() self._federation_ratelimiter = hs.get_federation_ratelimiter() self._server_linearizer = Linearizer("fed_server") self._transaction_linearizer = Linearizer("fed_txn_handler") # We cache results for transaction with the same ID self._transaction_resp_cache = ResponseCache( hs, "fed_txn_handler", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self.transaction_actions = TransactionActions(self.store) self.registry = hs.get_federation_registry() # We cache responses to state queries, as they take a while and often # come in waves. self._state_resp_cache = ResponseCache( hs, "state_resp", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self._state_ids_resp_cache = ResponseCache( hs, "state_ids_resp", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self._federation_metrics_domains = ( hs.get_config().federation.federation_metrics_domains ) async def on_backfill_request( self, origin: str, room_id: str, versions: List[str], limit: int ) -> Tuple[int, Dict[str, Any]]: with (await self._server_linearizer.queue((origin, room_id))): origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) pdus = await self.handler.on_backfill_request( origin, room_id, versions, limit ) res = self._transaction_from_pdus(pdus).get_dict() return 200, res async def on_incoming_transaction( self, origin: str, transaction_data: JsonDict ) -> Tuple[int, Dict[str, Any]]: # keep this as early as possible to make the calculated origin ts as # accurate as possible. request_time = self._clock.time_msec() transaction = Transaction(**transaction_data) transaction_id = transaction.transaction_id # type: ignore if not transaction_id: raise Exception("Transaction missing transaction_id") logger.debug("[%s] Got transaction", transaction_id) # We wrap in a ResponseCache so that we de-duplicate retried # transactions. return await self._transaction_resp_cache.wrap( (origin, transaction_id), self._on_incoming_transaction_inner, origin, transaction, request_time, ) async def _on_incoming_transaction_inner( self, origin: str, transaction: Transaction, request_time: int ) -> Tuple[int, Dict[str, Any]]: # Use a linearizer to ensure that transactions from a remote are # processed in order. with await self._transaction_linearizer.queue(origin): # We rate limit here *after* we've queued up the incoming requests, # so that we don't fill up the ratelimiter with blocked requests. # # This is important as the ratelimiter allows N concurrent requests # at a time, and only starts ratelimiting if there are more requests # than that being processed at a time. If we queued up requests in # the linearizer/response cache *after* the ratelimiting then those # queued up requests would count as part of the allowed limit of N # concurrent requests. with self._federation_ratelimiter.ratelimit(origin) as d: await d result = await self._handle_incoming_transaction( origin, transaction, request_time ) return result async def _handle_incoming_transaction( self, origin: str, transaction: Transaction, request_time: int ) -> Tuple[int, Dict[str, Any]]: """ Process an incoming transaction and return the HTTP response Args: origin: the server making the request transaction: incoming transaction request_time: timestamp that the HTTP request arrived at Returns: HTTP response code and body """ response = await self.transaction_actions.have_responded(origin, transaction) if response: logger.debug( "[%s] We've already responded to this request", transaction.transaction_id, # type: ignore ) return response logger.debug("[%s] Transaction is new", transaction.transaction_id) # type: ignore # Reject if PDU count > 50 or EDU count > 100 if len(transaction.pdus) > 50 or ( # type: ignore hasattr(transaction, "edus") and len(transaction.edus) > 100 # type: ignore ): logger.info("Transaction PDU or EDU count too large. Returning 400") response = {} await self.transaction_actions.set_response( origin, transaction, 400, response ) return 400, response # We process PDUs and EDUs in parallel. This is important as we don't # want to block things like to device messages from reaching clients # behind the potentially expensive handling of PDUs. pdu_results, _ = await make_deferred_yieldable( defer.gatherResults( [ run_in_background( self._handle_pdus_in_txn, origin, transaction, request_time ), run_in_background(self._handle_edus_in_txn, origin, transaction), ], consumeErrors=True, ).addErrback(unwrapFirstError) ) response = {"pdus": pdu_results} logger.debug("Returning: %s", str(response)) await self.transaction_actions.set_response(origin, transaction, 200, response) return 200, response async def _handle_pdus_in_txn( self, origin: str, transaction: Transaction, request_time: int ) -> Dict[str, dict]: """Process the PDUs in a received transaction. Args: origin: the server making the request transaction: incoming transaction request_time: timestamp that the HTTP request arrived at Returns: A map from event ID of a processed PDU to any errors we should report back to the sending server. """ received_pdus_counter.inc(len(transaction.pdus)) # type: ignore origin_host, _ = parse_server_name(origin) pdus_by_room = {} # type: Dict[str, List[EventBase]] newest_pdu_ts = 0 for p in transaction.pdus: # type: ignore # FIXME (richardv): I don't think this works: # https://github.com/matrix-org/synapse/issues/8429 if "unsigned" in p: unsigned = p["unsigned"] if "age" in unsigned: p["age"] = unsigned["age"] if "age" in p: p["age_ts"] = request_time - int(p["age"]) del p["age"] # We try and pull out an event ID so that if later checks fail we # can log something sensible. We don't mandate an event ID here in # case future event formats get rid of the key. possible_event_id = p.get("event_id", "<Unknown>") # Now we get the room ID so that we can check that we know the # version of the room. room_id = p.get("room_id") if not room_id: logger.info( "Ignoring PDU as does not have a room_id. Event ID: %s", possible_event_id, ) continue try: room_version = await self.store.get_room_version(room_id) except NotFoundError: logger.info("Ignoring PDU for unknown room_id: %s", room_id) continue except UnsupportedRoomVersionError as e: # this can happen if support for a given room version is withdrawn, # so that we still get events for said room. logger.info("Ignoring PDU: %s", e) continue event = event_from_pdu_json(p, room_version) pdus_by_room.setdefault(room_id, []).append(event) if event.origin_server_ts > newest_pdu_ts: newest_pdu_ts = event.origin_server_ts pdu_results = {} # we can process different rooms in parallel (which is useful if they # require callouts to other servers to fetch missing events), but # impose a limit to avoid going too crazy with ram/cpu. async def process_pdus_for_room(room_id: str): logger.debug("Processing PDUs for %s", room_id) try: await self.check_server_matches_acl(origin_host, room_id) except AuthError as e: logger.warning("Ignoring PDUs for room %s from banned server", room_id) for pdu in pdus_by_room[room_id]: event_id = pdu.event_id pdu_results[event_id] = e.error_dict() return for pdu in pdus_by_room[room_id]: event_id = pdu.event_id with pdu_process_time.time(): with nested_logging_context(event_id): try: await self._handle_received_pdu(origin, pdu) pdu_results[event_id] = {} except FederationError as e: logger.warning("Error handling PDU %s: %s", event_id, e) pdu_results[event_id] = {"error": str(e)} except Exception as e: f = failure.Failure() pdu_results[event_id] = {"error": str(e)} logger.error( "Failed to handle PDU %s", event_id, exc_info=(f.type, f.value, f.getTracebackObject()), ) await concurrently_execute( process_pdus_for_room, pdus_by_room.keys(), TRANSACTION_CONCURRENCY_LIMIT ) if newest_pdu_ts and origin in self._federation_metrics_domains: newest_pdu_age = self._clock.time_msec() - newest_pdu_ts last_pdu_age_metric.labels(server_name=origin).set(newest_pdu_age / 1000) return pdu_results async def _handle_edus_in_txn(self, origin: str, transaction: Transaction): """Process the EDUs in a received transaction. """ async def _process_edu(edu_dict): received_edus_counter.inc() edu = Edu( origin=origin, destination=self.server_name, edu_type=edu_dict["edu_type"], content=edu_dict["content"], ) await self.registry.on_edu(edu.edu_type, origin, edu.content) await concurrently_execute( _process_edu, getattr(transaction, "edus", []), TRANSACTION_CONCURRENCY_LIMIT, ) async def on_room_state_request( self, origin: str, room_id: str, event_id: str ) -> Tuple[int, Dict[str, Any]]: origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) in_room = await self.auth.check_host_in_room(room_id, origin) if not in_room: raise AuthError(403, "Host not in room.") # we grab the linearizer to protect ourselves from servers which hammer # us. In theory we might already have the response to this query # in the cache so we could return it without waiting for the linearizer # - but that's non-trivial to get right, and anyway somewhat defeats # the point of the linearizer. with (await self._server_linearizer.queue((origin, room_id))): resp = dict( await self._state_resp_cache.wrap( (room_id, event_id), self._on_context_state_request_compute, room_id, event_id, ) ) room_version = await self.store.get_room_version_id(room_id) resp["room_version"] = room_version return 200, resp async def on_state_ids_request( self, origin: str, room_id: str, event_id: str ) -> Tuple[int, Dict[str, Any]]: if not event_id: raise NotImplementedError("Specify an event") origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) in_room = await self.auth.check_host_in_room(room_id, origin) if not in_room: raise AuthError(403, "Host not in room.") resp = await self._state_ids_resp_cache.wrap( (room_id, event_id), self._on_state_ids_request_compute, room_id, event_id, ) return 200, resp async def _on_state_ids_request_compute(self, room_id, event_id): state_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id) auth_chain_ids = await self.store.get_auth_chain_ids(state_ids) return {"pdu_ids": state_ids, "auth_chain_ids": auth_chain_ids} async def _on_context_state_request_compute( self, room_id: str, event_id: str ) -> Dict[str, list]: if event_id: pdus = await self.handler.get_state_for_pdu(room_id, event_id) else: pdus = (await self.state.get_current_state(room_id)).values() auth_chain = await self.store.get_auth_chain([pdu.event_id for pdu in pdus]) return { "pdus": [pdu.get_pdu_json() for pdu in pdus], "auth_chain": [pdu.get_pdu_json() for pdu in auth_chain], } async def on_pdu_request( self, origin: str, event_id: str ) -> Tuple[int, Union[JsonDict, str]]: pdu = await self.handler.get_persisted_pdu(origin, event_id) if pdu: return 200, self._transaction_from_pdus([pdu]).get_dict() else: return 404, "" async def on_query_request( self, query_type: str, args: Dict[str, str] ) -> Tuple[int, Dict[str, Any]]: received_queries_counter.labels(query_type).inc() resp = await self.registry.on_query(query_type, args) return 200, resp async def on_make_join_request( self, origin: str, room_id: str, user_id: str, supported_versions: List[str] ) -> Dict[str, Any]: origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) room_version = await self.store.get_room_version_id(room_id) if room_version not in supported_versions: logger.warning( "Room version %s not in %s", room_version, supported_versions ) raise IncompatibleRoomVersionError(room_version=room_version) pdu = await self.handler.on_make_join_request(origin, room_id, user_id) time_now = self._clock.time_msec() return {"event": pdu.get_pdu_json(time_now), "room_version": room_version} async def on_invite_request( self, origin: str, content: JsonDict, room_version_id: str ) -> Dict[str, Any]: room_version = KNOWN_ROOM_VERSIONS.get(room_version_id) if not room_version: raise SynapseError( 400, "Homeserver does not support this room version", Codes.UNSUPPORTED_ROOM_VERSION, ) pdu = event_from_pdu_json(content, room_version) origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, pdu.room_id) pdu = await self._check_sigs_and_hash(room_version, pdu) ret_pdu = await self.handler.on_invite_request(origin, pdu, room_version) time_now = self._clock.time_msec() return {"event": ret_pdu.get_pdu_json(time_now)} async def on_send_join_request( self, origin: str, content: JsonDict ) -> Dict[str, Any]: logger.debug("on_send_join_request: content: %s", content) assert_params_in_dict(content, ["room_id"]) room_version = await self.store.get_room_version(content["room_id"]) pdu = event_from_pdu_json(content, room_version) origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, pdu.room_id) logger.debug("on_send_join_request: pdu sigs: %s", pdu.signatures) pdu = await self._check_sigs_and_hash(room_version, pdu) res_pdus = await self.handler.on_send_join_request(origin, pdu) time_now = self._clock.time_msec() return { "state": [p.get_pdu_json(time_now) for p in res_pdus["state"]], "auth_chain": [p.get_pdu_json(time_now) for p in res_pdus["auth_chain"]], } async def on_make_leave_request( self, origin: str, room_id: str, user_id: str ) -> Dict[str, Any]: origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) pdu = await self.handler.on_make_leave_request(origin, room_id, user_id) room_version = await self.store.get_room_version_id(room_id) time_now = self._clock.time_msec() return {"event": pdu.get_pdu_json(time_now), "room_version": room_version} async def on_send_leave_request(self, origin: str, content: JsonDict) -> dict: logger.debug("on_send_leave_request: content: %s", content) assert_params_in_dict(content, ["room_id"]) room_version = await self.store.get_room_version(content["room_id"]) pdu = event_from_pdu_json(content, room_version) origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, pdu.room_id) logger.debug("on_send_leave_request: pdu sigs: %s", pdu.signatures) pdu = await self._check_sigs_and_hash(room_version, pdu) await self.handler.on_send_leave_request(origin, pdu) return {} async def on_event_auth( self, origin: str, room_id: str, event_id: str ) -> Tuple[int, Dict[str, Any]]: with (await self._server_linearizer.queue((origin, room_id))): origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) time_now = self._clock.time_msec() auth_pdus = await self.handler.on_event_auth(event_id) res = {"auth_chain": [a.get_pdu_json(time_now) for a in auth_pdus]} return 200, res @log_function async def on_query_client_keys( self, origin: str, content: Dict[str, str] ) -> Tuple[int, Dict[str, Any]]: return await self.on_query_request("client_keys", content) async def on_query_user_devices( self, origin: str, user_id: str ) -> Tuple[int, Dict[str, Any]]: keys = await self.device_handler.on_federation_query_user_devices(user_id) return 200, keys @trace async def on_claim_client_keys( self, origin: str, content: JsonDict ) -> Dict[str, Any]: query = [] for user_id, device_keys in content.get("one_time_keys", {}).items(): for device_id, algorithm in device_keys.items(): query.append((user_id, device_id, algorithm)) log_kv({"message": "Claiming one time keys.", "user, device pairs": query}) results = await self.store.claim_e2e_one_time_keys(query) json_result = {} # type: Dict[str, Dict[str, dict]] for user_id, device_keys in results.items(): for device_id, keys in device_keys.items(): for key_id, json_str in keys.items(): json_result.setdefault(user_id, {})[device_id] = { key_id: json_decoder.decode(json_str) } logger.info( "Claimed one-time-keys: %s", ",".join( ( "%s for %s:%s" % (key_id, user_id, device_id) for user_id, user_keys in json_result.items() for device_id, device_keys in user_keys.items() for key_id, _ in device_keys.items() ) ), ) return {"one_time_keys": json_result} async def on_get_missing_events( self, origin: str, room_id: str, earliest_events: List[str], latest_events: List[str], limit: int, ) -> Dict[str, list]: with (await self._server_linearizer.queue((origin, room_id))): origin_host, _ = parse_server_name(origin) await self.check_server_matches_acl(origin_host, room_id) logger.debug( "on_get_missing_events: earliest_events: %r, latest_events: %r," " limit: %d", earliest_events, latest_events, limit, ) missing_events = await self.handler.on_get_missing_events( origin, room_id, earliest_events, latest_events, limit ) if len(missing_events) < 5: logger.debug( "Returning %d events: %r", len(missing_events), missing_events ) else: logger.debug("Returning %d events", len(missing_events)) time_now = self._clock.time_msec() return {"events": [ev.get_pdu_json(time_now) for ev in missing_events]} @log_function async def on_openid_userinfo(self, token: str) -> Optional[str]: ts_now_ms = self._clock.time_msec() return await self.store.get_user_id_for_open_id_token(token, ts_now_ms) def _transaction_from_pdus(self, pdu_list: List[EventBase]) -> Transaction: """Returns a new Transaction containing the given PDUs suitable for transmission. """ time_now = self._clock.time_msec() pdus = [p.get_pdu_json(time_now) for p in pdu_list] return Transaction( origin=self.server_name, pdus=pdus, origin_server_ts=int(time_now), destination=None, ) async def _handle_received_pdu(self, origin: str, pdu: EventBase) -> None: """ Process a PDU received in a federation /send/ transaction. If the event is invalid, then this method throws a FederationError. (The error will then be logged and sent back to the sender (which probably won't do anything with it), and other events in the transaction will be processed as normal). It is likely that we'll then receive other events which refer to this rejected_event in their prev_events, etc. When that happens, we'll attempt to fetch the rejected event again, which will presumably fail, so those second-generation events will also get rejected. Eventually, we get to the point where there are more than 10 events between any new events and the original rejected event. Since we only try to backfill 10 events deep on received pdu, we then accept the new event, possibly introducing a discontinuity in the DAG, with new forward extremities, so normal service is approximately returned, until we try to backfill across the discontinuity. Args: origin: server which sent the pdu pdu: received pdu Raises: FederationError if the signatures / hash do not match, or if the event was unacceptable for any other reason (eg, too large, too many prev_events, couldn't find the prev_events) """ # check that it's actually being sent from a valid destination to # workaround bug #1753 in 0.18.5 and 0.18.6 if origin != get_domain_from_id(pdu.sender): # We continue to accept join events from any server; this is # necessary for the federation join dance to work correctly. # (When we join over federation, the "helper" server is # responsible for sending out the join event, rather than the # origin. See bug #1893. This is also true for some third party # invites). if not ( pdu.type == "m.room.member" and pdu.content and pdu.content.get("membership", None) in (Membership.JOIN, Membership.INVITE) ): logger.info( "Discarding PDU %s from invalid origin %s", pdu.event_id, origin ) return else: logger.info("Accepting join PDU %s from %s", pdu.event_id, origin) # We've already checked that we know the room version by this point room_version = await self.store.get_room_version(pdu.room_id) # Check signature. try: pdu = await self._check_sigs_and_hash(room_version, pdu) except SynapseError as e: raise FederationError("ERROR", e.code, e.msg, affected=pdu.event_id) await self.handler.on_receive_pdu(origin, pdu, sent_to_us_directly=True) def __str__(self): return "<ReplicationLayer(%s)>" % self.server_name async def exchange_third_party_invite( self, sender_user_id: str, target_user_id: str, room_id: str, signed: Dict ): ret = await self.handler.exchange_third_party_invite( sender_user_id, target_user_id, room_id, signed ) return ret async def on_exchange_third_party_invite_request(self, event_dict: Dict): ret = await self.handler.on_exchange_third_party_invite_request(event_dict) return ret async def check_server_matches_acl(self, server_name: str, room_id: str): """Check if the given server is allowed by the server ACLs in the room Args: server_name: name of server, *without any port part* room_id: ID of the room to check Raises: AuthError if the server does not match the ACL """ state_ids = await self.store.get_current_state_ids(room_id) acl_event_id = state_ids.get((EventTypes.ServerACL, "")) if not acl_event_id: return acl_event = await self.store.get_event(acl_event_id) if server_matches_acl_event(server_name, acl_event): return raise AuthError(code=403, msg="Server is banned from room") def server_matches_acl_event(server_name: str, acl_event: EventBase) -> bool: """Check if the given server is allowed by the ACL event Args: server_name: name of server, without any port part acl_event: m.room.server_acl event Returns: True if this server is allowed by the ACLs """ logger.debug("Checking %s against acl %s", server_name, acl_event.content) # first of all, check if literal IPs are blocked, and if so, whether the # server name is a literal IP allow_ip_literals = acl_event.content.get("allow_ip_literals", True) if not isinstance(allow_ip_literals, bool): logger.warning("Ignoring non-bool allow_ip_literals flag") allow_ip_literals = True if not allow_ip_literals: # check for ipv6 literals. These start with '['. if server_name[0] == "[": return False # check for ipv4 literals. We can just lift the routine from twisted. if isIPAddress(server_name): return False # next, check the deny list deny = acl_event.content.get("deny", []) if not isinstance(deny, (list, tuple)): logger.warning("Ignoring non-list deny ACL %s", deny) deny = [] for e in deny: if _acl_entry_matches(server_name, e): # logger.info("%s matched deny rule %s", server_name, e) return False # then the allow list. allow = acl_event.content.get("allow", []) if not isinstance(allow, (list, tuple)): logger.warning("Ignoring non-list allow ACL %s", allow) allow = [] for e in allow: if _acl_entry_matches(server_name, e): # logger.info("%s matched allow rule %s", server_name, e) return True # everything else should be rejected. # logger.info("%s fell through", server_name) return False def _acl_entry_matches(server_name: str, acl_entry: Any) -> bool: if not isinstance(acl_entry, str): logger.warning( "Ignoring non-str ACL entry '%s' (is %s)", acl_entry, type(acl_entry) ) return False regex = glob_to_regex(acl_entry) return bool(regex.match(server_name)) class FederationHandlerRegistry: """Allows classes to register themselves as handlers for a given EDU or query type for incoming federation traffic. """ def __init__(self, hs: "HomeServer"): self.config = hs.config self.clock = hs.get_clock() self._instance_name = hs.get_instance_name() # These are safe to load in monolith mode, but will explode if we try # and use them. However we have guards before we use them to ensure that # we don't route to ourselves, and in monolith mode that will always be # the case. self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs) self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs) self.edu_handlers = ( {} ) # type: Dict[str, Callable[[str, dict], Awaitable[None]]] self.query_handlers = {} # type: Dict[str, Callable[[dict], Awaitable[None]]] # Map from type to instance name that we should route EDU handling to. self._edu_type_to_instance = {} # type: Dict[str, str] def register_edu_handler( self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]] ): """Sets the handler callable that will be used to handle an incoming federation EDU of the given type. Args: edu_type: The type of the incoming EDU to register handler for handler: A callable invoked on incoming EDU of the given type. The arguments are the origin server name and the EDU contents. """ if edu_type in self.edu_handlers: raise KeyError("Already have an EDU handler for %s" % (edu_type,)) logger.info("Registering federation EDU handler for %r", edu_type) self.edu_handlers[edu_type] = handler def register_query_handler( self, query_type: str, handler: Callable[[dict], defer.Deferred] ): """Sets the handler callable that will be used to handle an incoming federation query of the given type. Args: query_type: Category name of the query, which should match the string used by make_query. handler: Invoked to handle incoming queries of this type. The return will be yielded on and the result used as the response to the query request. """ if query_type in self.query_handlers: raise KeyError("Already have a Query handler for %s" % (query_type,)) logger.info("Registering federation query handler for %r", query_type) self.query_handlers[query_type] = handler def register_instance_for_edu(self, edu_type: str, instance_name: str): """Register that the EDU handler is on a different instance than master. """ self._edu_type_to_instance[edu_type] = instance_name async def on_edu(self, edu_type: str, origin: str, content: dict): if not self.config.use_presence and edu_type == "m.presence": return # Check if we have a handler on this instance handler = self.edu_handlers.get(edu_type) if handler: with start_active_span_from_edu(content, "handle_edu"): try: await handler(origin, content) except SynapseError as e: logger.info("Failed to handle edu %r: %r", edu_type, e) except Exception: logger.exception("Failed to handle edu %r", edu_type) return # Check if we can route it somewhere else that isn't us route_to = self._edu_type_to_instance.get(edu_type, "master") if route_to != self._instance_name: try: await self._send_edu( instance_name=route_to, edu_type=edu_type, origin=origin, content=content, ) except SynapseError as e: logger.info("Failed to handle edu %r: %r", edu_type, e) except Exception: logger.exception("Failed to handle edu %r", edu_type) return # Oh well, let's just log and move on. logger.warning("No handler registered for EDU type %s", edu_type) async def on_query(self, query_type: str, args: dict): handler = self.query_handlers.get(query_type) if handler: return await handler(args) # Check if we can route it somewhere else that isn't us if self._instance_name == "master": return await self._get_query_client(query_type=query_type, args=args) # Uh oh, no handler! Let's raise an exception so the request returns an # error. logger.warning("No handler registered for query type %s", query_type) raise NotFoundError("No handler for Query type '%s'" % (query_type,))
open_redirect
{ "code": [ " self.http_client = hs.get_simple_http_client()" ], "line_no": [ 848 ] }
{ "code": [], "line_no": [] }
import logging from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union, ) from prometheus_client import Counter, Gauge, Histogram from twisted.internet import defer from twisted.internet.abstract import isIPAddress from twisted.python import .failure from synapse.api.constants import EventTypes, Membership from synapse.api.errors import ( AuthError, Codes, FederationError, IncompatibleRoomVersionError, NotFoundError, SynapseError, UnsupportedRoomVersionError, ) from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.events import EventBase from synapse.federation.federation_base import FederationBase, event_from_pdu_json from synapse.federation.persistence import TransactionActions from synapse.federation.units import Edu, Transaction from synapse.http.endpoint import .parse_server_name from synapse.http.servlet import assert_params_in_dict from synapse.logging.context import ( make_deferred_yieldable, nested_logging_context, run_in_background, ) from synapse.logging.opentracing import log_kv, start_active_span_from_edu, trace from synapse.logging.utils import log_function from synapse.replication.http.federation import ( ReplicationFederationSendEduRestServlet, ReplicationGetQueryRestServlet, ) from synapse.types import JsonDict, get_domain_from_id from synapse.util import glob_to_regex, json_decoder, unwrapFirstError from synapse.util.async_helpers import Linearizer, concurrently_execute from synapse.util.caches.response_cache import ResponseCache if TYPE_CHECKING: from synapse.server import HomeServer VAR_0 = 10 VAR_1 = logging.getLogger(__name__) VAR_2 = Counter("synapse_federation_server_received_pdus", "") VAR_3 = Counter("synapse_federation_server_received_edus", "") VAR_4 = Counter( "synapse_federation_server_received_queries", "", ["type"] ) VAR_5 = Histogram( "synapse_federation_server_pdu_process_time", "Time taken to process an event", ) VAR_6 = Gauge( "synapse_federation_last_received_pdu_age", "The age (in seconds) of the last PDU successfully received from the given domain", labelnames=("server_name",), ) class CLASS_0(FederationBase): def __init__(self, VAR_10): super().__init__(VAR_10) self.auth = VAR_10.get_auth() self.handler = VAR_10.get_federation_handler() self.state = VAR_10.get_state_handler() self.device_handler = VAR_10.get_device_handler() VAR_10.get_directory_handler() self._federation_ratelimiter = VAR_10.get_federation_ratelimiter() self._server_linearizer = Linearizer("fed_server") self._transaction_linearizer = Linearizer("fed_txn_handler") self._transaction_resp_cache = ResponseCache( VAR_10, "fed_txn_handler", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self.transaction_actions = TransactionActions(self.store) self.registry = VAR_10.get_federation_registry() self._state_resp_cache = ResponseCache( VAR_10, "state_resp", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self._state_ids_resp_cache = ResponseCache( VAR_10, "state_ids_resp", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self._federation_metrics_domains = ( VAR_10.get_config().federation.federation_metrics_domains ) async def FUNC_2( self, VAR_11: str, VAR_12: str, VAR_13: List[str], VAR_14: int ) -> Tuple[int, Dict[str, Any]]: with (await self._server_linearizer.queue((VAR_11, VAR_12))): VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_63 = await self.handler.on_backfill_request( VAR_11, VAR_12, VAR_13, VAR_14 ) VAR_67 = self._transaction_from_pdus(VAR_63).get_dict() return 200, VAR_67 async def FUNC_3( self, VAR_11: str, VAR_15: JsonDict ) -> Tuple[int, Dict[str, Any]]: VAR_17 = self._clock.time_msec() VAR_16 = Transaction(**VAR_15) VAR_41 = VAR_16.transaction_id # type: ignore if not VAR_41: raise Exception("Transaction missing transaction_id") VAR_1.debug("[%s] Got transaction", VAR_41) return await self._transaction_resp_cache.wrap( (VAR_11, VAR_41), self._on_incoming_transaction_inner, VAR_11, VAR_16, VAR_17, ) async def FUNC_4( self, VAR_11: str, VAR_16: Transaction, VAR_17: int ) -> Tuple[int, Dict[str, Any]]: with await self._transaction_linearizer.queue(VAR_11): with self._federation_ratelimiter.ratelimit(VAR_11) as d: await d VAR_74 = await self._handle_incoming_transaction( VAR_11, VAR_16, VAR_17 ) return VAR_74 async def FUNC_5( self, VAR_11: str, VAR_16: Transaction, VAR_17: int ) -> Tuple[int, Dict[str, Any]]: VAR_42 = await self.transaction_actions.have_responded(VAR_11, VAR_16) if VAR_42: VAR_1.debug( "[%s] We've already responded to this request", VAR_16.transaction_id, # type: ignore ) return VAR_42 VAR_1.debug("[%s] Transaction is new", VAR_16.transaction_id) # type: ignore if len(VAR_16.pdus) > 50 or ( # type: ignore hasattr(VAR_16, "edus") and len(VAR_16.edus) > 100 # type: ignore ): VAR_1.info("Transaction PDU or EDU count too large. Returning 400") VAR_42 = {} await self.transaction_actions.set_response( VAR_11, VAR_16, 400, VAR_42 ) return 400, VAR_42 VAR_43, VAR_44 = await make_deferred_yieldable( defer.gatherResults( [ run_in_background( self._handle_pdus_in_txn, VAR_11, VAR_16, VAR_17 ), run_in_background(self._handle_edus_in_txn, VAR_11, VAR_16), ], consumeErrors=True, ).addErrback(unwrapFirstError) ) VAR_42 = {"pdus": VAR_43} VAR_1.debug("Returning: %s", str(VAR_42)) await self.transaction_actions.set_response(VAR_11, VAR_16, 200, VAR_42) return 200, VAR_42 async def FUNC_6( self, VAR_11: str, VAR_16: Transaction, VAR_17: int ) -> Dict[str, dict]: VAR_2.inc(len(VAR_16.pdus)) # type: ignore VAR_45, VAR_44 = parse_server_name(VAR_11) VAR_46 = {} # type: Dict[str, List[EventBase]] VAR_47 = 0 for VAR_76 in VAR_16.pdus: # type: ignore if "unsigned" in VAR_76: VAR_75 = VAR_76["unsigned"] if "age" in VAR_75: VAR_76["age"] = VAR_75["age"] if "age" in VAR_76: VAR_76["age_ts"] = VAR_17 - int(VAR_76["age"]) del VAR_76["age"] VAR_68 = VAR_76.get("event_id", "<Unknown>") VAR_12 = VAR_76.get("room_id") if not VAR_12: VAR_1.info( "Ignoring PDU as does not have a VAR_12. Event ID: %s", VAR_68, ) continue try: VAR_50 = await self.store.get_room_version(VAR_12) except NotFoundError: VAR_1.info("Ignoring PDU for unknown VAR_12: %s", VAR_12) continue except UnsupportedRoomVersionError as e: VAR_1.info("Ignoring PDU: %s", e) continue VAR_69 = event_from_pdu_json(VAR_76, VAR_50) VAR_46.setdefault(VAR_12, []).append(VAR_69) if VAR_69.origin_server_ts > VAR_47: VAR_47 = VAR_69.origin_server_ts VAR_43 = {} async def FUNC_35(VAR_12: str): VAR_1.debug("Processing PDUs for %s", VAR_12) try: await self.check_server_matches_acl(VAR_45, VAR_12) except AuthError as e: VAR_1.warning("Ignoring PDUs for room %s from banned server", VAR_12) for VAR_29 in VAR_46[VAR_12]: VAR_18 = VAR_29.event_id VAR_43[VAR_18] = e.error_dict() return for VAR_29 in VAR_46[VAR_12]: VAR_18 = VAR_29.event_id with VAR_5.time(): with nested_logging_context(VAR_18): try: await self._handle_received_pdu(VAR_11, VAR_29) VAR_43[VAR_18] = {} except FederationError as e: VAR_1.warning("Error handling PDU %s: %s", VAR_18, e) VAR_43[VAR_18] = {"error": str(e)} except Exception as e: VAR_78 = failure.Failure() VAR_43[VAR_18] = {"error": str(e)} VAR_1.error( "Failed to handle PDU %s", VAR_18, exc_info=(VAR_78.type, VAR_78.value, VAR_78.getTracebackObject()), ) await concurrently_execute( FUNC_35, VAR_46.keys(), VAR_0 ) if VAR_47 and VAR_11 in self._federation_metrics_domains: VAR_70 = self._clock.time_msec() - VAR_47 VAR_6.labels(VAR_7=VAR_11).set(VAR_70 / 1000) return VAR_43 async def FUNC_7(self, VAR_11: str, VAR_16: Transaction): async def FUNC_36(VAR_48): VAR_3.inc() VAR_71 = Edu( VAR_11=origin, destination=self.server_name, VAR_38=VAR_48["edu_type"], VAR_23=VAR_48["content"], ) await self.registry.on_edu(VAR_71.edu_type, VAR_11, VAR_71.content) await concurrently_execute( FUNC_36, getattr(VAR_16, "edus", []), VAR_0, ) async def FUNC_8( self, VAR_11: str, VAR_12: str, VAR_18: str ) -> Tuple[int, Dict[str, Any]]: VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_49 = await self.auth.check_host_in_room(VAR_12, VAR_11) if not VAR_49: raise AuthError(403, "Host not in room.") with (await self._server_linearizer.queue((VAR_11, VAR_12))): VAR_51 = dict( await self._state_resp_cache.wrap( (VAR_12, VAR_18), self._on_context_state_request_compute, VAR_12, VAR_18, ) ) VAR_50 = await self.store.get_room_version_id(VAR_12) VAR_51["room_version"] = VAR_50 return 200, VAR_51 async def FUNC_9( self, VAR_11: str, VAR_12: str, VAR_18: str ) -> Tuple[int, Dict[str, Any]]: if not VAR_18: raise NotImplementedError("Specify an event") VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_49 = await self.auth.check_host_in_room(VAR_12, VAR_11) if not VAR_49: raise AuthError(403, "Host not in room.") VAR_51 = await self._state_ids_resp_cache.wrap( (VAR_12, VAR_18), self._on_state_ids_request_compute, VAR_12, VAR_18, ) return 200, VAR_51 async def FUNC_10(self, VAR_12, VAR_18): VAR_52 = await self.handler.get_state_ids_for_pdu(VAR_12, VAR_18) VAR_53 = await self.store.get_auth_chain_ids(VAR_52) return {"pdu_ids": VAR_52, "auth_chain_ids": VAR_53} async def FUNC_11( self, VAR_12: str, VAR_18: str ) -> Dict[str, list]: if VAR_18: VAR_63 = await self.handler.get_state_for_pdu(VAR_12, VAR_18) else: VAR_63 = (await self.state.get_current_state(VAR_12)).values() VAR_54 = await self.store.get_auth_chain([VAR_29.event_id for VAR_29 in VAR_63]) return { "pdus": [VAR_29.get_pdu_json() for VAR_29 in VAR_63], "auth_chain": [VAR_29.get_pdu_json() for VAR_29 in VAR_54], } async def FUNC_12( self, VAR_11: str, VAR_18: str ) -> Tuple[int, Union[JsonDict, str]]: VAR_29 = await self.handler.get_persisted_pdu(VAR_11, VAR_18) if VAR_29: return 200, self._transaction_from_pdus([VAR_29]).get_dict() else: return 404, "" async def FUNC_13( self, VAR_19: str, VAR_20: Dict[str, str] ) -> Tuple[int, Dict[str, Any]]: VAR_4.labels(VAR_19).inc() VAR_51 = await self.registry.on_query(VAR_19, VAR_20) return 200, VAR_51 async def FUNC_14( self, VAR_11: str, VAR_12: str, VAR_21: str, VAR_22: List[str] ) -> Dict[str, Any]: VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_50 = await self.store.get_room_version_id(VAR_12) if VAR_50 not in VAR_22: VAR_1.warning( "Room version %s not in %s", VAR_50, VAR_22 ) raise IncompatibleRoomVersionError(VAR_50=room_version) VAR_29 = await self.handler.on_make_join_request(VAR_11, VAR_12, VAR_21) VAR_55 = self._clock.time_msec() return {"event": VAR_29.get_pdu_json(VAR_55), "room_version": VAR_50} async def FUNC_15( self, VAR_11: str, VAR_23: JsonDict, VAR_24: str ) -> Dict[str, Any]: VAR_50 = KNOWN_ROOM_VERSIONS.get(VAR_24) if not VAR_50: raise SynapseError( 400, "Homeserver does not support this room version", Codes.UNSUPPORTED_ROOM_VERSION, ) VAR_29 = event_from_pdu_json(VAR_23, VAR_50) VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_29.room_id) VAR_29 = await self._check_sigs_and_hash(VAR_50, VAR_29) VAR_56 = await self.handler.on_invite_request(VAR_11, VAR_29, VAR_50) VAR_55 = self._clock.time_msec() return {"event": VAR_56.get_pdu_json(VAR_55)} async def FUNC_16( self, VAR_11: str, VAR_23: JsonDict ) -> Dict[str, Any]: VAR_1.debug("on_send_join_request: VAR_23: %s", VAR_23) assert_params_in_dict(VAR_23, ["room_id"]) VAR_50 = await self.store.get_room_version(VAR_23["room_id"]) VAR_29 = event_from_pdu_json(VAR_23, VAR_50) VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_29.room_id) VAR_1.debug("on_send_join_request: VAR_29 sigs: %s", VAR_29.signatures) VAR_29 = await self._check_sigs_and_hash(VAR_50, VAR_29) VAR_57 = await self.handler.on_send_join_request(VAR_11, VAR_29) VAR_55 = self._clock.time_msec() return { "state": [VAR_76.get_pdu_json(VAR_55) for VAR_76 in VAR_57["state"]], "auth_chain": [VAR_76.get_pdu_json(VAR_55) for VAR_76 in VAR_57["auth_chain"]], } async def FUNC_17( self, VAR_11: str, VAR_12: str, VAR_21: str ) -> Dict[str, Any]: VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_29 = await self.handler.on_make_leave_request(VAR_11, VAR_12, VAR_21) VAR_50 = await self.store.get_room_version_id(VAR_12) VAR_55 = self._clock.time_msec() return {"event": VAR_29.get_pdu_json(VAR_55), "room_version": VAR_50} async def FUNC_18(self, VAR_11: str, VAR_23: JsonDict) -> dict: VAR_1.debug("on_send_leave_request: VAR_23: %s", VAR_23) assert_params_in_dict(VAR_23, ["room_id"]) VAR_50 = await self.store.get_room_version(VAR_23["room_id"]) VAR_29 = event_from_pdu_json(VAR_23, VAR_50) VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_29.room_id) VAR_1.debug("on_send_leave_request: VAR_29 sigs: %s", VAR_29.signatures) VAR_29 = await self._check_sigs_and_hash(VAR_50, VAR_29) await self.handler.on_send_leave_request(VAR_11, VAR_29) return {} async def FUNC_19( self, VAR_11: str, VAR_12: str, VAR_18: str ) -> Tuple[int, Dict[str, Any]]: with (await self._server_linearizer.queue((VAR_11, VAR_12))): VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_55 = self._clock.time_msec() VAR_72 = await self.handler.on_event_auth(VAR_18) VAR_67 = {"auth_chain": [a.get_pdu_json(VAR_55) for a in VAR_72]} return 200, VAR_67 @log_function async def FUNC_20( self, VAR_11: str, VAR_23: Dict[str, str] ) -> Tuple[int, Dict[str, Any]]: return await self.on_query_request("client_keys", VAR_23) async def FUNC_21( self, VAR_11: str, VAR_21: str ) -> Tuple[int, Dict[str, Any]]: VAR_58 = await self.device_handler.on_federation_query_user_devices(VAR_21) return 200, VAR_58 @trace async def FUNC_22( self, VAR_11: str, VAR_23: JsonDict ) -> Dict[str, Any]: VAR_59 = [] for VAR_21, device_keys in VAR_23.get("one_time_keys", {}).items(): for VAR_77, algorithm in device_keys.items(): VAR_59.append((VAR_21, VAR_77, algorithm)) log_kv({"message": "Claiming one time VAR_58.", "user, device pairs": VAR_59}) VAR_60 = await self.store.claim_e2e_one_time_keys(VAR_59) VAR_61 = {} # type: Dict[str, Dict[str, dict]] for VAR_21, device_keys in VAR_60.items(): for VAR_77, VAR_58 in device_keys.items(): for key_id, json_str in VAR_58.items(): VAR_61.setdefault(VAR_21, {})[VAR_77] = { key_id: json_decoder.decode(json_str) } VAR_1.info( "Claimed one-time-VAR_58: %s", ",".join( ( "%s for %s:%s" % (key_id, VAR_21, VAR_77) for VAR_21, user_keys in VAR_61.items() for VAR_77, device_keys in user_keys.items() for key_id, VAR_44 in device_keys.items() ) ), ) return {"one_time_keys": VAR_61} async def FUNC_23( self, VAR_11: str, VAR_12: str, VAR_25: List[str], VAR_26: List[str], VAR_14: int, ) -> Dict[str, list]: with (await self._server_linearizer.queue((VAR_11, VAR_12))): VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_1.debug( "on_get_missing_events: VAR_25: %r, VAR_26: %r," " VAR_14: %d", VAR_25, VAR_26, VAR_14, ) VAR_73 = await self.handler.on_get_missing_events( VAR_11, VAR_12, VAR_25, VAR_26, VAR_14 ) if len(VAR_73) < 5: VAR_1.debug( "Returning %d events: %r", len(VAR_73), missing_events ) else: VAR_1.debug("Returning %d events", len(VAR_73)) VAR_55 = self._clock.time_msec() return {"events": [ev.get_pdu_json(VAR_55) for ev in VAR_73]} @log_function async def FUNC_24(self, VAR_27: str) -> Optional[str]: VAR_62 = self._clock.time_msec() return await self.store.get_user_id_for_open_id_token(VAR_27, VAR_62) def FUNC_25(self, VAR_28: List[EventBase]) -> Transaction: VAR_55 = self._clock.time_msec() VAR_63 = [VAR_76.get_pdu_json(VAR_55) for VAR_76 in VAR_28] return Transaction( VAR_11=self.server_name, VAR_63=pdus, origin_server_ts=int(VAR_55), destination=None, ) async def FUNC_26(self, VAR_11: str, VAR_29: EventBase) -> None: if VAR_11 != get_domain_from_id(VAR_29.sender): if not ( VAR_29.type == "m.room.member" and VAR_29.content and VAR_29.content.get("membership", None) in (Membership.JOIN, Membership.INVITE) ): VAR_1.info( "Discarding PDU %s from invalid VAR_11 %s", VAR_29.event_id, VAR_11 ) return else: VAR_1.info("Accepting join PDU %s from %s", VAR_29.event_id, VAR_11) VAR_50 = await self.store.get_room_version(VAR_29.room_id) try: VAR_29 = await self._check_sigs_and_hash(VAR_50, VAR_29) except SynapseError as e: raise FederationError("ERROR", e.code, e.msg, affected=VAR_29.event_id) await self.handler.on_receive_pdu(VAR_11, VAR_29, sent_to_us_directly=True) def __str__(self): return "<ReplicationLayer(%s)>" % self.server_name async def FUNC_27( self, VAR_30: str, VAR_31: str, VAR_12: str, VAR_32: Dict ): VAR_64 = await self.handler.exchange_third_party_invite( VAR_30, VAR_31, VAR_12, VAR_32 ) return VAR_64 async def FUNC_28(self, VAR_33: Dict): VAR_64 = await self.handler.on_exchange_third_party_invite_request(VAR_33) return VAR_64 async def FUNC_29(self, VAR_7: str, VAR_12: str): VAR_52 = await self.store.get_current_state_ids(VAR_12) VAR_65 = VAR_52.get((EventTypes.ServerACL, "")) if not VAR_65: return VAR_8 = await self.store.get_event(VAR_65) if FUNC_0(VAR_7, VAR_8): return raise AuthError(code=403, msg="Server is banned from room") def FUNC_0(VAR_7: str, VAR_8: EventBase) -> bool: VAR_1.debug("Checking %s against acl %s", VAR_7, VAR_8.content) VAR_34 = VAR_8.content.get("allow_ip_literals", True) if not isinstance(VAR_34, bool): VAR_1.warning("Ignoring non-bool VAR_34 flag") VAR_34 = True if not VAR_34: if VAR_7[0] == "[": return False if isIPAddress(VAR_7): return False VAR_35 = VAR_8.content.get("deny", []) if not isinstance(VAR_35, (list, tuple)): VAR_1.warning("Ignoring non-list VAR_35 ACL %s", VAR_35) VAR_35 = [] for e in VAR_35: if FUNC_1(VAR_7, e): return False VAR_36 = VAR_8.content.get("allow", []) if not isinstance(VAR_36, (list, tuple)): VAR_1.warning("Ignoring non-list VAR_36 ACL %s", VAR_36) VAR_36 = [] for e in VAR_36: if FUNC_1(VAR_7, e): return True return False def FUNC_1(VAR_7: str, VAR_9: Any) -> bool: if not isinstance(VAR_9, str): VAR_1.warning( "Ignoring non-str ACL entry '%s' (is %s)", VAR_9, type(VAR_9) ) return False VAR_37 = glob_to_regex(VAR_9) return bool(VAR_37.match(VAR_7)) class CLASS_1: def __init__(self, VAR_10: "HomeServer"): self.config = VAR_10.config self.http_client = VAR_10.get_simple_http_client() self.clock = VAR_10.get_clock() self._instance_name = VAR_10.get_instance_name() self._get_query_client = ReplicationGetQueryRestServlet.make_client(VAR_10) self._send_edu = ReplicationFederationSendEduRestServlet.make_client(VAR_10) self.edu_handlers = ( {} ) # type: Dict[str, Callable[[str, dict], Awaitable[None]]] self.query_handlers = {} # type: Dict[str, Callable[[dict], Awaitable[None]]] self._edu_type_to_instance = {} # type: Dict[str, str] def FUNC_30( self, VAR_38: str, VAR_39: Callable[[str, JsonDict], Awaitable[None]] ): if VAR_38 in self.edu_handlers: raise KeyError("Already have an EDU VAR_39 for %s" % (VAR_38,)) VAR_1.info("Registering federation EDU VAR_39 for %r", VAR_38) self.edu_handlers[VAR_38] = VAR_39 def FUNC_31( self, VAR_19: str, VAR_39: Callable[[dict], defer.Deferred] ): if VAR_19 in self.query_handlers: raise KeyError("Already have a Query VAR_39 for %s" % (VAR_19,)) VAR_1.info("Registering federation VAR_59 VAR_39 for %r", VAR_19) self.query_handlers[VAR_19] = VAR_39 def FUNC_32(self, VAR_38: str, VAR_40: str): self._edu_type_to_instance[VAR_38] = VAR_40 async def FUNC_33(self, VAR_38: str, VAR_11: str, VAR_23: dict): if not self.config.use_presence and VAR_38 == "m.presence": return VAR_39 = self.edu_handlers.get(VAR_38) if VAR_39: with start_active_span_from_edu(VAR_23, "handle_edu"): try: await VAR_39(VAR_11, VAR_23) except SynapseError as e: VAR_1.info("Failed to handle VAR_71 %r: %r", VAR_38, e) except Exception: VAR_1.exception("Failed to handle VAR_71 %r", VAR_38) return VAR_66 = self._edu_type_to_instance.get(VAR_38, "master") if VAR_66 != self._instance_name: try: await self._send_edu( VAR_40=VAR_66, VAR_38=edu_type, VAR_11=origin, VAR_23=content, ) except SynapseError as e: VAR_1.info("Failed to handle VAR_71 %r: %r", VAR_38, e) except Exception: VAR_1.exception("Failed to handle VAR_71 %r", VAR_38) return VAR_1.warning("No VAR_39 registered for EDU type %s", VAR_38) async def FUNC_34(self, VAR_19: str, VAR_20: dict): VAR_39 = self.query_handlers.get(VAR_19) if VAR_39: return await VAR_39(VAR_20) if self._instance_name == "master": return await self._get_query_client(VAR_19=query_type, VAR_20=args) VAR_1.warning("No VAR_39 registered for VAR_59 type %s", VAR_19) raise NotFoundError("No VAR_39 for Query type '%s'" % (VAR_19,))
import logging from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union, ) from prometheus_client import Counter, Gauge, Histogram from twisted.internet import defer from twisted.internet.abstract import isIPAddress from twisted.python import .failure from synapse.api.constants import EventTypes, Membership from synapse.api.errors import ( AuthError, Codes, FederationError, IncompatibleRoomVersionError, NotFoundError, SynapseError, UnsupportedRoomVersionError, ) from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.events import EventBase from synapse.federation.federation_base import FederationBase, event_from_pdu_json from synapse.federation.persistence import TransactionActions from synapse.federation.units import Edu, Transaction from synapse.http.endpoint import .parse_server_name from synapse.http.servlet import assert_params_in_dict from synapse.logging.context import ( make_deferred_yieldable, nested_logging_context, run_in_background, ) from synapse.logging.opentracing import log_kv, start_active_span_from_edu, trace from synapse.logging.utils import log_function from synapse.replication.http.federation import ( ReplicationFederationSendEduRestServlet, ReplicationGetQueryRestServlet, ) from synapse.types import JsonDict, get_domain_from_id from synapse.util import glob_to_regex, json_decoder, unwrapFirstError from synapse.util.async_helpers import Linearizer, concurrently_execute from synapse.util.caches.response_cache import ResponseCache if TYPE_CHECKING: from synapse.server import HomeServer VAR_0 = 10 VAR_1 = logging.getLogger(__name__) VAR_2 = Counter("synapse_federation_server_received_pdus", "") VAR_3 = Counter("synapse_federation_server_received_edus", "") VAR_4 = Counter( "synapse_federation_server_received_queries", "", ["type"] ) VAR_5 = Histogram( "synapse_federation_server_pdu_process_time", "Time taken to process an event", ) VAR_6 = Gauge( "synapse_federation_last_received_pdu_age", "The age (in seconds) of the last PDU successfully received from the given domain", labelnames=("server_name",), ) class CLASS_0(FederationBase): def __init__(self, VAR_10): super().__init__(VAR_10) self.auth = VAR_10.get_auth() self.handler = VAR_10.get_federation_handler() self.state = VAR_10.get_state_handler() self.device_handler = VAR_10.get_device_handler() VAR_10.get_directory_handler() self._federation_ratelimiter = VAR_10.get_federation_ratelimiter() self._server_linearizer = Linearizer("fed_server") self._transaction_linearizer = Linearizer("fed_txn_handler") self._transaction_resp_cache = ResponseCache( VAR_10, "fed_txn_handler", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self.transaction_actions = TransactionActions(self.store) self.registry = VAR_10.get_federation_registry() self._state_resp_cache = ResponseCache( VAR_10, "state_resp", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self._state_ids_resp_cache = ResponseCache( VAR_10, "state_ids_resp", timeout_ms=30000 ) # type: ResponseCache[Tuple[str, str]] self._federation_metrics_domains = ( VAR_10.get_config().federation.federation_metrics_domains ) async def FUNC_2( self, VAR_11: str, VAR_12: str, VAR_13: List[str], VAR_14: int ) -> Tuple[int, Dict[str, Any]]: with (await self._server_linearizer.queue((VAR_11, VAR_12))): VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_63 = await self.handler.on_backfill_request( VAR_11, VAR_12, VAR_13, VAR_14 ) VAR_67 = self._transaction_from_pdus(VAR_63).get_dict() return 200, VAR_67 async def FUNC_3( self, VAR_11: str, VAR_15: JsonDict ) -> Tuple[int, Dict[str, Any]]: VAR_17 = self._clock.time_msec() VAR_16 = Transaction(**VAR_15) VAR_41 = VAR_16.transaction_id # type: ignore if not VAR_41: raise Exception("Transaction missing transaction_id") VAR_1.debug("[%s] Got transaction", VAR_41) return await self._transaction_resp_cache.wrap( (VAR_11, VAR_41), self._on_incoming_transaction_inner, VAR_11, VAR_16, VAR_17, ) async def FUNC_4( self, VAR_11: str, VAR_16: Transaction, VAR_17: int ) -> Tuple[int, Dict[str, Any]]: with await self._transaction_linearizer.queue(VAR_11): with self._federation_ratelimiter.ratelimit(VAR_11) as d: await d VAR_74 = await self._handle_incoming_transaction( VAR_11, VAR_16, VAR_17 ) return VAR_74 async def FUNC_5( self, VAR_11: str, VAR_16: Transaction, VAR_17: int ) -> Tuple[int, Dict[str, Any]]: VAR_42 = await self.transaction_actions.have_responded(VAR_11, VAR_16) if VAR_42: VAR_1.debug( "[%s] We've already responded to this request", VAR_16.transaction_id, # type: ignore ) return VAR_42 VAR_1.debug("[%s] Transaction is new", VAR_16.transaction_id) # type: ignore if len(VAR_16.pdus) > 50 or ( # type: ignore hasattr(VAR_16, "edus") and len(VAR_16.edus) > 100 # type: ignore ): VAR_1.info("Transaction PDU or EDU count too large. Returning 400") VAR_42 = {} await self.transaction_actions.set_response( VAR_11, VAR_16, 400, VAR_42 ) return 400, VAR_42 VAR_43, VAR_44 = await make_deferred_yieldable( defer.gatherResults( [ run_in_background( self._handle_pdus_in_txn, VAR_11, VAR_16, VAR_17 ), run_in_background(self._handle_edus_in_txn, VAR_11, VAR_16), ], consumeErrors=True, ).addErrback(unwrapFirstError) ) VAR_42 = {"pdus": VAR_43} VAR_1.debug("Returning: %s", str(VAR_42)) await self.transaction_actions.set_response(VAR_11, VAR_16, 200, VAR_42) return 200, VAR_42 async def FUNC_6( self, VAR_11: str, VAR_16: Transaction, VAR_17: int ) -> Dict[str, dict]: VAR_2.inc(len(VAR_16.pdus)) # type: ignore VAR_45, VAR_44 = parse_server_name(VAR_11) VAR_46 = {} # type: Dict[str, List[EventBase]] VAR_47 = 0 for VAR_76 in VAR_16.pdus: # type: ignore if "unsigned" in VAR_76: VAR_75 = VAR_76["unsigned"] if "age" in VAR_75: VAR_76["age"] = VAR_75["age"] if "age" in VAR_76: VAR_76["age_ts"] = VAR_17 - int(VAR_76["age"]) del VAR_76["age"] VAR_68 = VAR_76.get("event_id", "<Unknown>") VAR_12 = VAR_76.get("room_id") if not VAR_12: VAR_1.info( "Ignoring PDU as does not have a VAR_12. Event ID: %s", VAR_68, ) continue try: VAR_50 = await self.store.get_room_version(VAR_12) except NotFoundError: VAR_1.info("Ignoring PDU for unknown VAR_12: %s", VAR_12) continue except UnsupportedRoomVersionError as e: VAR_1.info("Ignoring PDU: %s", e) continue VAR_69 = event_from_pdu_json(VAR_76, VAR_50) VAR_46.setdefault(VAR_12, []).append(VAR_69) if VAR_69.origin_server_ts > VAR_47: VAR_47 = VAR_69.origin_server_ts VAR_43 = {} async def FUNC_35(VAR_12: str): VAR_1.debug("Processing PDUs for %s", VAR_12) try: await self.check_server_matches_acl(VAR_45, VAR_12) except AuthError as e: VAR_1.warning("Ignoring PDUs for room %s from banned server", VAR_12) for VAR_29 in VAR_46[VAR_12]: VAR_18 = VAR_29.event_id VAR_43[VAR_18] = e.error_dict() return for VAR_29 in VAR_46[VAR_12]: VAR_18 = VAR_29.event_id with VAR_5.time(): with nested_logging_context(VAR_18): try: await self._handle_received_pdu(VAR_11, VAR_29) VAR_43[VAR_18] = {} except FederationError as e: VAR_1.warning("Error handling PDU %s: %s", VAR_18, e) VAR_43[VAR_18] = {"error": str(e)} except Exception as e: VAR_78 = failure.Failure() VAR_43[VAR_18] = {"error": str(e)} VAR_1.error( "Failed to handle PDU %s", VAR_18, exc_info=(VAR_78.type, VAR_78.value, VAR_78.getTracebackObject()), ) await concurrently_execute( FUNC_35, VAR_46.keys(), VAR_0 ) if VAR_47 and VAR_11 in self._federation_metrics_domains: VAR_70 = self._clock.time_msec() - VAR_47 VAR_6.labels(VAR_7=VAR_11).set(VAR_70 / 1000) return VAR_43 async def FUNC_7(self, VAR_11: str, VAR_16: Transaction): async def FUNC_36(VAR_48): VAR_3.inc() VAR_71 = Edu( VAR_11=origin, destination=self.server_name, VAR_38=VAR_48["edu_type"], VAR_23=VAR_48["content"], ) await self.registry.on_edu(VAR_71.edu_type, VAR_11, VAR_71.content) await concurrently_execute( FUNC_36, getattr(VAR_16, "edus", []), VAR_0, ) async def FUNC_8( self, VAR_11: str, VAR_12: str, VAR_18: str ) -> Tuple[int, Dict[str, Any]]: VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_49 = await self.auth.check_host_in_room(VAR_12, VAR_11) if not VAR_49: raise AuthError(403, "Host not in room.") with (await self._server_linearizer.queue((VAR_11, VAR_12))): VAR_51 = dict( await self._state_resp_cache.wrap( (VAR_12, VAR_18), self._on_context_state_request_compute, VAR_12, VAR_18, ) ) VAR_50 = await self.store.get_room_version_id(VAR_12) VAR_51["room_version"] = VAR_50 return 200, VAR_51 async def FUNC_9( self, VAR_11: str, VAR_12: str, VAR_18: str ) -> Tuple[int, Dict[str, Any]]: if not VAR_18: raise NotImplementedError("Specify an event") VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_49 = await self.auth.check_host_in_room(VAR_12, VAR_11) if not VAR_49: raise AuthError(403, "Host not in room.") VAR_51 = await self._state_ids_resp_cache.wrap( (VAR_12, VAR_18), self._on_state_ids_request_compute, VAR_12, VAR_18, ) return 200, VAR_51 async def FUNC_10(self, VAR_12, VAR_18): VAR_52 = await self.handler.get_state_ids_for_pdu(VAR_12, VAR_18) VAR_53 = await self.store.get_auth_chain_ids(VAR_52) return {"pdu_ids": VAR_52, "auth_chain_ids": VAR_53} async def FUNC_11( self, VAR_12: str, VAR_18: str ) -> Dict[str, list]: if VAR_18: VAR_63 = await self.handler.get_state_for_pdu(VAR_12, VAR_18) else: VAR_63 = (await self.state.get_current_state(VAR_12)).values() VAR_54 = await self.store.get_auth_chain([VAR_29.event_id for VAR_29 in VAR_63]) return { "pdus": [VAR_29.get_pdu_json() for VAR_29 in VAR_63], "auth_chain": [VAR_29.get_pdu_json() for VAR_29 in VAR_54], } async def FUNC_12( self, VAR_11: str, VAR_18: str ) -> Tuple[int, Union[JsonDict, str]]: VAR_29 = await self.handler.get_persisted_pdu(VAR_11, VAR_18) if VAR_29: return 200, self._transaction_from_pdus([VAR_29]).get_dict() else: return 404, "" async def FUNC_13( self, VAR_19: str, VAR_20: Dict[str, str] ) -> Tuple[int, Dict[str, Any]]: VAR_4.labels(VAR_19).inc() VAR_51 = await self.registry.on_query(VAR_19, VAR_20) return 200, VAR_51 async def FUNC_14( self, VAR_11: str, VAR_12: str, VAR_21: str, VAR_22: List[str] ) -> Dict[str, Any]: VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_50 = await self.store.get_room_version_id(VAR_12) if VAR_50 not in VAR_22: VAR_1.warning( "Room version %s not in %s", VAR_50, VAR_22 ) raise IncompatibleRoomVersionError(VAR_50=room_version) VAR_29 = await self.handler.on_make_join_request(VAR_11, VAR_12, VAR_21) VAR_55 = self._clock.time_msec() return {"event": VAR_29.get_pdu_json(VAR_55), "room_version": VAR_50} async def FUNC_15( self, VAR_11: str, VAR_23: JsonDict, VAR_24: str ) -> Dict[str, Any]: VAR_50 = KNOWN_ROOM_VERSIONS.get(VAR_24) if not VAR_50: raise SynapseError( 400, "Homeserver does not support this room version", Codes.UNSUPPORTED_ROOM_VERSION, ) VAR_29 = event_from_pdu_json(VAR_23, VAR_50) VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_29.room_id) VAR_29 = await self._check_sigs_and_hash(VAR_50, VAR_29) VAR_56 = await self.handler.on_invite_request(VAR_11, VAR_29, VAR_50) VAR_55 = self._clock.time_msec() return {"event": VAR_56.get_pdu_json(VAR_55)} async def FUNC_16( self, VAR_11: str, VAR_23: JsonDict ) -> Dict[str, Any]: VAR_1.debug("on_send_join_request: VAR_23: %s", VAR_23) assert_params_in_dict(VAR_23, ["room_id"]) VAR_50 = await self.store.get_room_version(VAR_23["room_id"]) VAR_29 = event_from_pdu_json(VAR_23, VAR_50) VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_29.room_id) VAR_1.debug("on_send_join_request: VAR_29 sigs: %s", VAR_29.signatures) VAR_29 = await self._check_sigs_and_hash(VAR_50, VAR_29) VAR_57 = await self.handler.on_send_join_request(VAR_11, VAR_29) VAR_55 = self._clock.time_msec() return { "state": [VAR_76.get_pdu_json(VAR_55) for VAR_76 in VAR_57["state"]], "auth_chain": [VAR_76.get_pdu_json(VAR_55) for VAR_76 in VAR_57["auth_chain"]], } async def FUNC_17( self, VAR_11: str, VAR_12: str, VAR_21: str ) -> Dict[str, Any]: VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_29 = await self.handler.on_make_leave_request(VAR_11, VAR_12, VAR_21) VAR_50 = await self.store.get_room_version_id(VAR_12) VAR_55 = self._clock.time_msec() return {"event": VAR_29.get_pdu_json(VAR_55), "room_version": VAR_50} async def FUNC_18(self, VAR_11: str, VAR_23: JsonDict) -> dict: VAR_1.debug("on_send_leave_request: VAR_23: %s", VAR_23) assert_params_in_dict(VAR_23, ["room_id"]) VAR_50 = await self.store.get_room_version(VAR_23["room_id"]) VAR_29 = event_from_pdu_json(VAR_23, VAR_50) VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_29.room_id) VAR_1.debug("on_send_leave_request: VAR_29 sigs: %s", VAR_29.signatures) VAR_29 = await self._check_sigs_and_hash(VAR_50, VAR_29) await self.handler.on_send_leave_request(VAR_11, VAR_29) return {} async def FUNC_19( self, VAR_11: str, VAR_12: str, VAR_18: str ) -> Tuple[int, Dict[str, Any]]: with (await self._server_linearizer.queue((VAR_11, VAR_12))): VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_55 = self._clock.time_msec() VAR_72 = await self.handler.on_event_auth(VAR_18) VAR_67 = {"auth_chain": [a.get_pdu_json(VAR_55) for a in VAR_72]} return 200, VAR_67 @log_function async def FUNC_20( self, VAR_11: str, VAR_23: Dict[str, str] ) -> Tuple[int, Dict[str, Any]]: return await self.on_query_request("client_keys", VAR_23) async def FUNC_21( self, VAR_11: str, VAR_21: str ) -> Tuple[int, Dict[str, Any]]: VAR_58 = await self.device_handler.on_federation_query_user_devices(VAR_21) return 200, VAR_58 @trace async def FUNC_22( self, VAR_11: str, VAR_23: JsonDict ) -> Dict[str, Any]: VAR_59 = [] for VAR_21, device_keys in VAR_23.get("one_time_keys", {}).items(): for VAR_77, algorithm in device_keys.items(): VAR_59.append((VAR_21, VAR_77, algorithm)) log_kv({"message": "Claiming one time VAR_58.", "user, device pairs": VAR_59}) VAR_60 = await self.store.claim_e2e_one_time_keys(VAR_59) VAR_61 = {} # type: Dict[str, Dict[str, dict]] for VAR_21, device_keys in VAR_60.items(): for VAR_77, VAR_58 in device_keys.items(): for key_id, json_str in VAR_58.items(): VAR_61.setdefault(VAR_21, {})[VAR_77] = { key_id: json_decoder.decode(json_str) } VAR_1.info( "Claimed one-time-VAR_58: %s", ",".join( ( "%s for %s:%s" % (key_id, VAR_21, VAR_77) for VAR_21, user_keys in VAR_61.items() for VAR_77, device_keys in user_keys.items() for key_id, VAR_44 in device_keys.items() ) ), ) return {"one_time_keys": VAR_61} async def FUNC_23( self, VAR_11: str, VAR_12: str, VAR_25: List[str], VAR_26: List[str], VAR_14: int, ) -> Dict[str, list]: with (await self._server_linearizer.queue((VAR_11, VAR_12))): VAR_45, VAR_44 = parse_server_name(VAR_11) await self.check_server_matches_acl(VAR_45, VAR_12) VAR_1.debug( "on_get_missing_events: VAR_25: %r, VAR_26: %r," " VAR_14: %d", VAR_25, VAR_26, VAR_14, ) VAR_73 = await self.handler.on_get_missing_events( VAR_11, VAR_12, VAR_25, VAR_26, VAR_14 ) if len(VAR_73) < 5: VAR_1.debug( "Returning %d events: %r", len(VAR_73), missing_events ) else: VAR_1.debug("Returning %d events", len(VAR_73)) VAR_55 = self._clock.time_msec() return {"events": [ev.get_pdu_json(VAR_55) for ev in VAR_73]} @log_function async def FUNC_24(self, VAR_27: str) -> Optional[str]: VAR_62 = self._clock.time_msec() return await self.store.get_user_id_for_open_id_token(VAR_27, VAR_62) def FUNC_25(self, VAR_28: List[EventBase]) -> Transaction: VAR_55 = self._clock.time_msec() VAR_63 = [VAR_76.get_pdu_json(VAR_55) for VAR_76 in VAR_28] return Transaction( VAR_11=self.server_name, VAR_63=pdus, origin_server_ts=int(VAR_55), destination=None, ) async def FUNC_26(self, VAR_11: str, VAR_29: EventBase) -> None: if VAR_11 != get_domain_from_id(VAR_29.sender): if not ( VAR_29.type == "m.room.member" and VAR_29.content and VAR_29.content.get("membership", None) in (Membership.JOIN, Membership.INVITE) ): VAR_1.info( "Discarding PDU %s from invalid VAR_11 %s", VAR_29.event_id, VAR_11 ) return else: VAR_1.info("Accepting join PDU %s from %s", VAR_29.event_id, VAR_11) VAR_50 = await self.store.get_room_version(VAR_29.room_id) try: VAR_29 = await self._check_sigs_and_hash(VAR_50, VAR_29) except SynapseError as e: raise FederationError("ERROR", e.code, e.msg, affected=VAR_29.event_id) await self.handler.on_receive_pdu(VAR_11, VAR_29, sent_to_us_directly=True) def __str__(self): return "<ReplicationLayer(%s)>" % self.server_name async def FUNC_27( self, VAR_30: str, VAR_31: str, VAR_12: str, VAR_32: Dict ): VAR_64 = await self.handler.exchange_third_party_invite( VAR_30, VAR_31, VAR_12, VAR_32 ) return VAR_64 async def FUNC_28(self, VAR_33: Dict): VAR_64 = await self.handler.on_exchange_third_party_invite_request(VAR_33) return VAR_64 async def FUNC_29(self, VAR_7: str, VAR_12: str): VAR_52 = await self.store.get_current_state_ids(VAR_12) VAR_65 = VAR_52.get((EventTypes.ServerACL, "")) if not VAR_65: return VAR_8 = await self.store.get_event(VAR_65) if FUNC_0(VAR_7, VAR_8): return raise AuthError(code=403, msg="Server is banned from room") def FUNC_0(VAR_7: str, VAR_8: EventBase) -> bool: VAR_1.debug("Checking %s against acl %s", VAR_7, VAR_8.content) VAR_34 = VAR_8.content.get("allow_ip_literals", True) if not isinstance(VAR_34, bool): VAR_1.warning("Ignoring non-bool VAR_34 flag") VAR_34 = True if not VAR_34: if VAR_7[0] == "[": return False if isIPAddress(VAR_7): return False VAR_35 = VAR_8.content.get("deny", []) if not isinstance(VAR_35, (list, tuple)): VAR_1.warning("Ignoring non-list VAR_35 ACL %s", VAR_35) VAR_35 = [] for e in VAR_35: if FUNC_1(VAR_7, e): return False VAR_36 = VAR_8.content.get("allow", []) if not isinstance(VAR_36, (list, tuple)): VAR_1.warning("Ignoring non-list VAR_36 ACL %s", VAR_36) VAR_36 = [] for e in VAR_36: if FUNC_1(VAR_7, e): return True return False def FUNC_1(VAR_7: str, VAR_9: Any) -> bool: if not isinstance(VAR_9, str): VAR_1.warning( "Ignoring non-str ACL entry '%s' (is %s)", VAR_9, type(VAR_9) ) return False VAR_37 = glob_to_regex(VAR_9) return bool(VAR_37.match(VAR_7)) class CLASS_1: def __init__(self, VAR_10: "HomeServer"): self.config = VAR_10.config self.clock = VAR_10.get_clock() self._instance_name = VAR_10.get_instance_name() self._get_query_client = ReplicationGetQueryRestServlet.make_client(VAR_10) self._send_edu = ReplicationFederationSendEduRestServlet.make_client(VAR_10) self.edu_handlers = ( {} ) # type: Dict[str, Callable[[str, dict], Awaitable[None]]] self.query_handlers = {} # type: Dict[str, Callable[[dict], Awaitable[None]]] self._edu_type_to_instance = {} # type: Dict[str, str] def FUNC_30( self, VAR_38: str, VAR_39: Callable[[str, JsonDict], Awaitable[None]] ): if VAR_38 in self.edu_handlers: raise KeyError("Already have an EDU VAR_39 for %s" % (VAR_38,)) VAR_1.info("Registering federation EDU VAR_39 for %r", VAR_38) self.edu_handlers[VAR_38] = VAR_39 def FUNC_31( self, VAR_19: str, VAR_39: Callable[[dict], defer.Deferred] ): if VAR_19 in self.query_handlers: raise KeyError("Already have a Query VAR_39 for %s" % (VAR_19,)) VAR_1.info("Registering federation VAR_59 VAR_39 for %r", VAR_19) self.query_handlers[VAR_19] = VAR_39 def FUNC_32(self, VAR_38: str, VAR_40: str): self._edu_type_to_instance[VAR_38] = VAR_40 async def FUNC_33(self, VAR_38: str, VAR_11: str, VAR_23: dict): if not self.config.use_presence and VAR_38 == "m.presence": return VAR_39 = self.edu_handlers.get(VAR_38) if VAR_39: with start_active_span_from_edu(VAR_23, "handle_edu"): try: await VAR_39(VAR_11, VAR_23) except SynapseError as e: VAR_1.info("Failed to handle VAR_71 %r: %r", VAR_38, e) except Exception: VAR_1.exception("Failed to handle VAR_71 %r", VAR_38) return VAR_66 = self._edu_type_to_instance.get(VAR_38, "master") if VAR_66 != self._instance_name: try: await self._send_edu( VAR_40=VAR_66, VAR_38=edu_type, VAR_11=origin, VAR_23=content, ) except SynapseError as e: VAR_1.info("Failed to handle VAR_71 %r: %r", VAR_38, e) except Exception: VAR_1.exception("Failed to handle VAR_71 %r", VAR_38) return VAR_1.warning("No VAR_39 registered for EDU type %s", VAR_38) async def FUNC_34(self, VAR_19: str, VAR_20: dict): VAR_39 = self.query_handlers.get(VAR_19) if VAR_39: return await VAR_39(VAR_20) if self._instance_name == "master": return await self._get_query_client(VAR_19=query_type, VAR_20=args) VAR_1.warning("No VAR_39 registered for VAR_59 type %s", VAR_19) raise NotFoundError("No VAR_39 for Query type '%s'" % (VAR_19,))
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 29, 31, 35, 68, 71, 72, 73, 75, 77, 79, 81, 85, 89, 90, 96, 97, 101, 105, 107, 108, 109, 111, 113, 116, 117, 121, 123, 125, 126, 127, 134, 138, 145, 149, 151, 153, 157, 158, 160, 163, 166, 168, 169, 170, 178, 182, 183, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 200, 202, 207, 212, 217, 224, 226, 227, 231, 233, 239, 240, 241, 242, 254, 256, 258, 261, 266, 271, 276, 278, 280, 282, 284, 286, 287, 295, 296, 297, 298, 300, 301, 302, 310, 317, 318, 321, 324, 327, 329, 330, 331, 332, 333, 344, 363, 367, 371, 373, 377, 380, 388, 394, 400, 404, 405, 406, 407, 408, 409, 419, 422, 424, 430, 433, 437, 441, 443, 448, 456, 458, 463, 468, 473, 480, 486, 493, 497, 508, 516, 521, 525, 528, 530, 532, 539, 546, 548, 551, 554, 558, 561, 563, 565, 568, 575, 580, 586, 592, 601, 604, 612, 624, 626, 638, 646, 650, 657, 659, 661, 666, 679, 682, 687, 692, 699, 703, 708, 709, 711, 712, 713, 714, 715, 716, 729, 730, 732, 733, 738, 740, 743, 751, 755, 758, 762, 768, 771, 775, 777, 778, 781, 785, 790, 791, 792, 798, 801, 802, 805, 806, 813, 815, 816, 823, 825, 826, 827, 829, 830, 839, 840, 845, 851, 852, 853, 854, 855, 858, 863, 864, 866, 872, 881, 883, 885, 891, 901, 903, 905, 910, 914, 915, 926, 927, 942, 943, 945, 950, 951, 954, 955, 956, 959, 780, 781, 782, 783, 784, 785, 786, 787, 788, 842, 843, 844, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 375, 376, 668, 669, 670, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 757, 758, 759, 760, 761, 762, 763, 764, 765, 870, 871, 872, 873, 874, 875, 876, 877, 878, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 907, 908 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 29, 31, 35, 68, 71, 72, 73, 75, 77, 79, 81, 85, 89, 90, 96, 97, 101, 105, 107, 108, 109, 111, 113, 116, 117, 121, 123, 125, 126, 127, 134, 138, 145, 149, 151, 153, 157, 158, 160, 163, 166, 168, 169, 170, 178, 182, 183, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 200, 202, 207, 212, 217, 224, 226, 227, 231, 233, 239, 240, 241, 242, 254, 256, 258, 261, 266, 271, 276, 278, 280, 282, 284, 286, 287, 295, 296, 297, 298, 300, 301, 302, 310, 317, 318, 321, 324, 327, 329, 330, 331, 332, 333, 344, 363, 367, 371, 373, 377, 380, 388, 394, 400, 404, 405, 406, 407, 408, 409, 419, 422, 424, 430, 433, 437, 441, 443, 448, 456, 458, 463, 468, 473, 480, 486, 493, 497, 508, 516, 521, 525, 528, 530, 532, 539, 546, 548, 551, 554, 558, 561, 563, 565, 568, 575, 580, 586, 592, 601, 604, 612, 624, 626, 638, 646, 650, 657, 659, 661, 666, 679, 682, 687, 692, 699, 703, 708, 709, 711, 712, 713, 714, 715, 716, 729, 730, 732, 733, 738, 740, 743, 751, 755, 758, 762, 768, 771, 775, 777, 778, 781, 785, 790, 791, 792, 798, 801, 802, 805, 806, 813, 815, 816, 823, 825, 826, 827, 829, 830, 839, 840, 845, 850, 851, 852, 853, 854, 857, 862, 863, 865, 871, 880, 882, 884, 890, 900, 902, 904, 909, 913, 914, 925, 926, 941, 942, 944, 949, 950, 953, 954, 955, 958, 780, 781, 782, 783, 784, 785, 786, 787, 788, 842, 843, 844, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 375, 376, 668, 669, 670, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 757, 758, 759, 760, 761, 762, 763, 764, 765, 869, 870, 871, 872, 873, 874, 875, 876, 877, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 906, 907 ]
1CWE-79
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import inspect import json import six import warnings from django.conf import settings from django.contrib.auth.views import redirect_to_login from django.core.exceptions import ImproperlyConfigured from django.http.response import HttpResponseForbidden from django.utils.encoding import force_str, force_text from django.utils.http import urlencode from django.utils.translation import ugettext_lazy as _ from shuup.admin.module_registry import get_modules from shuup.admin.shop_provider import get_shop from shuup.admin.utils.permissions import get_missing_permissions from shuup.utils import importing from shuup.utils.django_compat import NoReverseMatch, URLPattern, get_callable, is_authenticated, reverse from shuup.utils.excs import Problem try: from urllib.parse import parse_qsl except ImportError: # pragma: no cover from urlparse import parse_qsl # Python 2.7 class AdminRegexURLPattern(URLPattern): def __init__(self, regex, callback, default_args=None, name=None, require_authentication=True, permissions=()): self.permissions = tuple(permissions) self.require_authentication = require_authentication if callable(callback): callback = self.wrap_with_permissions(callback) from django.urls import re_path repath = re_path(regex, callback, default_args, name) pattern = repath.pattern super(AdminRegexURLPattern, self).__init__(pattern, callback, default_args, name) def _get_unauth_response(self, request, reason): """ Get an error response (or raise a Problem) for a given request and reason message. :type request: Request. :param request: HttpRequest :type reason: Reason string. :param reason: str """ if request.is_ajax(): return HttpResponseForbidden(json.dumps({"error": force_text(reason)})) error_params = urlencode({"error": force_text(reason)}) login_url = force_str(reverse("shuup_admin:login") + "?" + error_params) resp = redirect_to_login(next=request.path, login_url=login_url) if is_authenticated(request.user): # Instead of redirecting to the login page, let the user know what's wrong with # a helpful link. raise ( Problem(_("Can't view this page. %(reason)s") % {"reason": reason}).with_link( url=resp.url, title=_("Log in with different credentials...") ) ) return resp def _get_unauth_reason(self, request): """ Figure out if there's any reason not to allow the user access to this view via the given request. :type request: Request. :param request: HttpRequest :rtype: str|None """ if self.require_authentication: if not is_authenticated(request.user): return _("Sign in to continue.") elif not getattr(request.user, "is_staff", False): return _("Your account must have `Access to Admin Panel` permissions to access this page.") elif not get_shop(request): return _("There is no active shop available. Contact support for more details.") missing_permissions = get_missing_permissions(request.user, self.permissions) if missing_permissions: return _("You do not have the required permissions: %s") % ", ".join(missing_permissions) def wrap_with_permissions(self, view_func): if callable(getattr(view_func, "as_view", None)): view_func = view_func.as_view() @six.wraps(view_func) def _wrapped_view(request, *args, **kwargs): unauth_reason = self._get_unauth_reason(request) if unauth_reason: return self._get_unauth_response(request, unauth_reason) return view_func(request, *args, **kwargs) return _wrapped_view @property def callback(self): if self._callback is not None: return self._callback callback = get_callable(self._callback_str) self._callback = self.wrap_with_permissions(callback) return self._callback @callback.setter def callback(self, value): self._callback = value def admin_url(regex, view, kwargs=None, name=None, prefix="", require_authentication=True, permissions=None): if permissions is None: permissions = (name,) if name else () if isinstance(view, six.string_types): if not view: raise ImproperlyConfigured("Error! Empty URL pattern view name not permitted (for pattern `%r`)." % regex) if prefix: view = prefix + "." + view view = importing.load(view) return AdminRegexURLPattern( regex, view, kwargs, name, require_authentication=require_authentication, permissions=permissions ) def get_edit_and_list_urls(url_prefix, view_template, name_template, permissions=()): """ Get a list of edit/new/list URLs for (presumably) an object type with standardized URLs and names. :param url_prefix: What to prefix the generated URLs with. E.g. `"^taxes/tax"`. :type url_prefix: str :param view_template: A template string for the dotted name of the view class. E.g. "shuup.admin.modules.taxes.views.Tax%sView". :type view_template: str :param name_template: A template string for the URLnames. E.g. "tax.%s". :type name_template: str :return: List of URLs. :rtype: list[AdminRegexURLPattern] """ if permissions: warnings.warn( "Warning! `get_edit_and_list_urls` permissions attribute will be " "deprecated in Shuup 2.0 as unused for this util.", DeprecationWarning, ) return [ admin_url( r"%s/(?P<pk>\d+)/$" % url_prefix, view_template % "Edit", name=name_template % "edit", permissions=(name_template % "edit",), ), admin_url( "%s/new/$" % url_prefix, view_template % "Edit", name=name_template % "new", kwargs={"pk": None}, permissions=(name_template % "new",), ), admin_url( "%s/$" % url_prefix, view_template % "List", name=name_template % "list", permissions=(name_template % "list",), ), admin_url( "%s/list-settings/" % url_prefix, "shuup.admin.modules.settings.views.ListSettingsView", name=name_template % "list_settings", permissions=(name_template % "list_settings",), ), ] class NoModelUrl(ValueError): pass def get_model_url( object, kind="detail", user=None, required_permissions=None, shop=None, raise_permission_denied=False, **kwargs ): """ Get a an admin object URL for the given object or object class by interrogating each admin module. If a user is provided, checks whether user has correct permissions before returning URL. Raises `NoModelUrl` if lookup fails :param object: Model or object class. :type object: class :param kind: URL kind. Currently "new", "list", "edit", "detail". :type kind: str :param user: Optional instance to check for permissions. :type user: django.contrib.auth.models.User|None :param required_permissions: Optional iterable of permission strings. :type required_permissions: Iterable[str]|None :param shop: The shop that owns the resource. :type request: shuup.core.models.Shop|None :param raise_permission_denied: raise PermissionDenied exception if the url is found but user has not permission. If false, None will be returned instead. Default is False. :type raise_permission_denied: bool :return: Resolved URL. :rtype: str """ for module in get_modules(): url = module.get_model_url(object, kind, shop) if not url: continue if user is None: return url from shuup.utils.django_compat import Resolver404, resolve try: if required_permissions is not None: warnings.warn( "Warning! `required_permissions` parameter will be deprecated " "in Shuup 2.0 as unused for this util.", DeprecationWarning, ) permissions = required_permissions else: resolved = resolve(url) from shuup.admin.utils.permissions import get_permissions_for_module_url permissions = get_permissions_for_module_url(module, resolved.url_name) missing_permissions = get_missing_permissions(user, permissions) if not missing_permissions: return url if raise_permission_denied: from django.core.exceptions import PermissionDenied reason = _("Can't view this page. You do not have the required permission(s): `{permissions}`.").format( permissions=", ".join(missing_permissions) ) raise PermissionDenied(reason) except Resolver404: # what are you doing developer? return url raise NoModelUrl("Error! Can't get object URL of kind %s: %r." % (kind, force_text(object))) def derive_model_url(model_class, urlname_prefix, object, kind): """ Try to guess a model URL for the given `object` and `kind`. An utility for people implementing `get_model_url`. :param model_class: The model class the object must be an instance or subclass of. :type model_class: class :param urlname_prefix: URLname prefix. For instance, `shuup_admin:shop_product.` :type urlname_prefix: str :param object: The model or model class as passed to `get_model_url`. :type object: django.db.models.Model|class :param kind: URL kind as passed to `get_model_url`. :type kind: str :return: Resolved URL or None. :rtype: str|None """ if not (isinstance(object, model_class) or (inspect.isclass(object) and issubclass(object, model_class))): return kind_to_urlnames = { "detail": ("%s.detail" % urlname_prefix, "%s.edit" % urlname_prefix), } kwarg_sets = [{}] if getattr(object, "pk", None): kwarg_sets.append({"pk": object.pk}) for urlname in kind_to_urlnames.get(kind, ["%s.%s" % (urlname_prefix, kind)]): for kwargs in kwarg_sets: try: return reverse(urlname, kwargs=kwargs) except NoReverseMatch: pass # No match whatsoever. return None def manipulate_query_string(url, **qs): if "?" in url: url, current_qs = url.split("?", 1) qs = dict(parse_qsl(current_qs), **qs) qs = [(key, value) for (key, value) in qs.items() if value is not None] if qs: return "%s?%s" % (url, urlencode(qs)) else: return url def get_model_front_url(request, object): """ Get a frontend URL for an object. :param request: Request. :type request: HttpRequest :param object: A model instance. :type object: django.db.models.Model :return: URL or None. :rtype: str|None """ # TODO: This method could use an extension point for alternative frontends. if not object.pk: return None if "shuup.front" in settings.INSTALLED_APPS: # Best effort to use the default frontend for front URLs. try: from shuup.front.template_helpers.urls import model_url return model_url({"request": request}, object) except (ValueError, NoReverseMatch): pass return None def get_front_url(context): """ Get front URL for admin navigation. 1. Use front URL from view context if passed. 2. Fallback to index. """ front_url = context.get("front_url") if not front_url: try: front_url = reverse("shuup:index") except NoReverseMatch: front_url = None return front_url
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import inspect import json import six import warnings from django.conf import settings from django.contrib.auth.views import redirect_to_login from django.core.exceptions import ImproperlyConfigured from django.http.response import HttpResponseForbidden from django.utils.encoding import force_str, force_text from django.utils.html import escape from django.utils.http import urlencode from django.utils.translation import ugettext_lazy as _ from shuup.admin.module_registry import get_modules from shuup.admin.shop_provider import get_shop from shuup.admin.utils.permissions import get_missing_permissions from shuup.utils import importing from shuup.utils.django_compat import NoReverseMatch, URLPattern, get_callable, is_authenticated, reverse from shuup.utils.excs import Problem try: from urllib.parse import parse_qsl except ImportError: # pragma: no cover from urlparse import parse_qsl # Python 2.7 class AdminRegexURLPattern(URLPattern): def __init__(self, regex, callback, default_args=None, name=None, require_authentication=True, permissions=()): self.permissions = tuple(permissions) self.require_authentication = require_authentication if callable(callback): callback = self.wrap_with_permissions(callback) from django.urls import re_path repath = re_path(regex, callback, default_args, name) pattern = repath.pattern super(AdminRegexURLPattern, self).__init__(pattern, callback, default_args, name) def _get_unauth_response(self, request, reason): """ Get an error response (or raise a Problem) for a given request and reason message. :type request: Request. :param request: HttpRequest :type reason: Reason string. :param reason: str """ if request.is_ajax(): return HttpResponseForbidden(json.dumps({"error": force_text(reason)})) error_params = urlencode({"error": force_text(reason)}) login_url = force_str(reverse("shuup_admin:login") + "?" + error_params) resp = redirect_to_login(next=request.path, login_url=login_url) if is_authenticated(request.user): # Instead of redirecting to the login page, let the user know what's wrong with # a helpful link. raise ( Problem(_("Can't view this page. %(reason)s") % {"reason": escape(reason)}).with_link( url=resp.url, title=_("Log in with different credentials...") ) ) return resp def _get_unauth_reason(self, request): """ Figure out if there's any reason not to allow the user access to this view via the given request. :type request: Request. :param request: HttpRequest :rtype: str|None """ if self.require_authentication: if not is_authenticated(request.user): return _("Sign in to continue.") elif not getattr(request.user, "is_staff", False): return _("Your account must have `Access to Admin Panel` permissions to access this page.") elif not get_shop(request): return _("There is no active shop available. Contact support for more details.") missing_permissions = get_missing_permissions(request.user, self.permissions) if missing_permissions: return _("You do not have the required permissions: %s") % ", ".join(missing_permissions) def wrap_with_permissions(self, view_func): if callable(getattr(view_func, "as_view", None)): view_func = view_func.as_view() @six.wraps(view_func) def _wrapped_view(request, *args, **kwargs): unauth_reason = self._get_unauth_reason(request) if unauth_reason: return self._get_unauth_response(request, unauth_reason) return view_func(request, *args, **kwargs) return _wrapped_view @property def callback(self): if self._callback is not None: return self._callback callback = get_callable(self._callback_str) self._callback = self.wrap_with_permissions(callback) return self._callback @callback.setter def callback(self, value): self._callback = value def admin_url(regex, view, kwargs=None, name=None, prefix="", require_authentication=True, permissions=None): if permissions is None: permissions = (name,) if name else () if isinstance(view, six.string_types): if not view: raise ImproperlyConfigured("Error! Empty URL pattern view name not permitted (for pattern `%r`)." % regex) if prefix: view = prefix + "." + view view = importing.load(view) return AdminRegexURLPattern( regex, view, kwargs, name, require_authentication=require_authentication, permissions=permissions ) def get_edit_and_list_urls(url_prefix, view_template, name_template, permissions=()): """ Get a list of edit/new/list URLs for (presumably) an object type with standardized URLs and names. :param url_prefix: What to prefix the generated URLs with. E.g. `"^taxes/tax"`. :type url_prefix: str :param view_template: A template string for the dotted name of the view class. E.g. "shuup.admin.modules.taxes.views.Tax%sView". :type view_template: str :param name_template: A template string for the URLnames. E.g. "tax.%s". :type name_template: str :return: List of URLs. :rtype: list[AdminRegexURLPattern] """ if permissions: warnings.warn( "Warning! `get_edit_and_list_urls` permissions attribute will be " "deprecated in Shuup 2.0 as unused for this util.", DeprecationWarning, ) return [ admin_url( r"%s/(?P<pk>\d+)/$" % url_prefix, view_template % "Edit", name=name_template % "edit", permissions=(name_template % "edit",), ), admin_url( "%s/new/$" % url_prefix, view_template % "Edit", name=name_template % "new", kwargs={"pk": None}, permissions=(name_template % "new",), ), admin_url( "%s/$" % url_prefix, view_template % "List", name=name_template % "list", permissions=(name_template % "list",), ), admin_url( "%s/list-settings/" % url_prefix, "shuup.admin.modules.settings.views.ListSettingsView", name=name_template % "list_settings", permissions=(name_template % "list_settings",), ), ] class NoModelUrl(ValueError): pass def get_model_url( object, kind="detail", user=None, required_permissions=None, shop=None, raise_permission_denied=False, **kwargs ): """ Get a an admin object URL for the given object or object class by interrogating each admin module. If a user is provided, checks whether user has correct permissions before returning URL. Raises `NoModelUrl` if lookup fails :param object: Model or object class. :type object: class :param kind: URL kind. Currently "new", "list", "edit", "detail". :type kind: str :param user: Optional instance to check for permissions. :type user: django.contrib.auth.models.User|None :param required_permissions: Optional iterable of permission strings. :type required_permissions: Iterable[str]|None :param shop: The shop that owns the resource. :type request: shuup.core.models.Shop|None :param raise_permission_denied: raise PermissionDenied exception if the url is found but user has not permission. If false, None will be returned instead. Default is False. :type raise_permission_denied: bool :return: Resolved URL. :rtype: str """ for module in get_modules(): url = module.get_model_url(object, kind, shop) if not url: continue if user is None: return url from shuup.utils.django_compat import Resolver404, resolve try: if required_permissions is not None: warnings.warn( "Warning! `required_permissions` parameter will be deprecated " "in Shuup 2.0 as unused for this util.", DeprecationWarning, ) permissions = required_permissions else: resolved = resolve(url) from shuup.admin.utils.permissions import get_permissions_for_module_url permissions = get_permissions_for_module_url(module, resolved.url_name) missing_permissions = get_missing_permissions(user, permissions) if not missing_permissions: return url if raise_permission_denied: from django.core.exceptions import PermissionDenied reason = _("Can't view this page. You do not have the required permission(s): `{permissions}`.").format( permissions=", ".join(missing_permissions) ) raise PermissionDenied(reason) except Resolver404: # what are you doing developer? return url raise NoModelUrl("Error! Can't get object URL of kind %s: %r." % (kind, force_text(object))) def derive_model_url(model_class, urlname_prefix, object, kind): """ Try to guess a model URL for the given `object` and `kind`. An utility for people implementing `get_model_url`. :param model_class: The model class the object must be an instance or subclass of. :type model_class: class :param urlname_prefix: URLname prefix. For instance, `shuup_admin:shop_product.` :type urlname_prefix: str :param object: The model or model class as passed to `get_model_url`. :type object: django.db.models.Model|class :param kind: URL kind as passed to `get_model_url`. :type kind: str :return: Resolved URL or None. :rtype: str|None """ if not (isinstance(object, model_class) or (inspect.isclass(object) and issubclass(object, model_class))): return kind_to_urlnames = { "detail": ("%s.detail" % urlname_prefix, "%s.edit" % urlname_prefix), } kwarg_sets = [{}] if getattr(object, "pk", None): kwarg_sets.append({"pk": object.pk}) for urlname in kind_to_urlnames.get(kind, ["%s.%s" % (urlname_prefix, kind)]): for kwargs in kwarg_sets: try: return reverse(urlname, kwargs=kwargs) except NoReverseMatch: pass # No match whatsoever. return None def manipulate_query_string(url, **qs): if "?" in url: url, current_qs = url.split("?", 1) qs = dict(parse_qsl(current_qs), **qs) qs = [(key, value) for (key, value) in qs.items() if value is not None] if qs: return "%s?%s" % (url, urlencode(qs)) else: return url def get_model_front_url(request, object): """ Get a frontend URL for an object. :param request: Request. :type request: HttpRequest :param object: A model instance. :type object: django.db.models.Model :return: URL or None. :rtype: str|None """ # TODO: This method could use an extension point for alternative frontends. if not object.pk: return None if "shuup.front" in settings.INSTALLED_APPS: # Best effort to use the default frontend for front URLs. try: from shuup.front.template_helpers.urls import model_url return model_url({"request": request}, object) except (ValueError, NoReverseMatch): pass return None def get_front_url(context): """ Get front URL for admin navigation. 1. Use front URL from view context if passed. 2. Fallback to index. """ front_url = context.get("front_url") if not front_url: try: front_url = reverse("shuup:index") except NoReverseMatch: front_url = None return front_url
xss
{ "code": [ " Problem(_(\"Can't view this page. %(reason)s\") % {\"reason\": reason}).with_link(" ], "line_no": [ 67 ] }
{ "code": [ "from django.utils.html import escape", " Problem(_(\"Can't view this page. %(reason)s\") % {\"reason\": escape(reason)}).with_link(" ], "line_no": [ 19, 68 ] }
from __future__ import unicode_literals import inspect import json import six import warnings from django.conf import settings from django.contrib.auth.views import redirect_to_login from django.core.exceptions import ImproperlyConfigured from django.http.response import HttpResponseForbidden from django.utils.encoding import force_str, force_text from django.utils.http import .urlencode from django.utils.translation import ugettext_lazy as _ from shuup.admin.module_registry import get_modules from shuup.admin.shop_provider import get_shop from shuup.admin.utils.permissions import get_missing_permissions from shuup.utils import importing from shuup.utils.django_compat import NoReverseMatch, URLPattern, get_callable, is_authenticated, reverse from shuup.utils.excs import Problem try: from urllib.parse import parse_qsl except ImportError: # pragma: no cover from urlparse import parse_qsl # Python 2.7 class CLASS_0(URLPattern): def __init__(self, VAR_0, VAR_22, VAR_23=None, VAR_3=None, VAR_5=True, VAR_6=()): self.permissions = tuple(VAR_6) self.require_authentication = VAR_5 if callable(VAR_22): FUNC_10 = self.wrap_with_permissions(VAR_22) from django.urls import re_path VAR_30 = re_path(VAR_0, VAR_22, VAR_23, VAR_3) VAR_31 = VAR_30.pattern super(CLASS_0, self).__init__(VAR_31, VAR_22, VAR_23, VAR_3) def FUNC_7(self, VAR_20, VAR_24): if VAR_20.is_ajax(): return HttpResponseForbidden(json.dumps({"error": force_text(VAR_24)})) VAR_32 = urlencode({"error": force_text(VAR_24)}) VAR_33 = force_str(reverse("shuup_admin:login") + "?" + VAR_32) VAR_34 = redirect_to_login(next=VAR_20.path, VAR_33=login_url) if is_authenticated(VAR_20.user): raise ( Problem(_("Can't VAR_1 this page. %(VAR_24)s") % {"reason": VAR_24}).with_link( VAR_18=VAR_34.url, title=_("Log in with different credentials...") ) ) return VAR_34 def FUNC_8(self, VAR_20): if self.require_authentication: if not is_authenticated(VAR_20.user): return _("Sign in to continue.") elif not getattr(VAR_20.user, "is_staff", False): return _("Your account must have `Access to Admin Panel` VAR_6 to access this page.") elif not get_shop(VAR_20): return _("There is no active VAR_14 available. Contact support for more details.") VAR_35 = get_missing_permissions(VAR_20.user, self.permissions) if VAR_35: return _("You do not have the required VAR_6: %s") % ", ".join(VAR_35) def FUNC_9(self, VAR_25): if callable(getattr(VAR_25, "as_view", None)): VAR_25 = view_func.as_view() @six.wraps(VAR_25) def FUNC_11(VAR_20, *VAR_36, **VAR_2): VAR_38 = self._get_unauth_reason(VAR_20) if VAR_38: return self._get_unauth_response(VAR_20, VAR_38) return VAR_25(VAR_20, *VAR_36, **VAR_2) return FUNC_11 @property def VAR_22(self): if self._callback is not None: return self._callback VAR_22 = get_callable(self._callback_str) self._callback = self.wrap_with_permissions(VAR_22) return self._callback @VAR_22.setter def VAR_22(self, VAR_26): self._callback = VAR_26 def FUNC_0(VAR_0, VAR_1, VAR_2=None, VAR_3=None, VAR_4="", VAR_5=True, VAR_6=None): if VAR_6 is None: VAR_6 = (VAR_3,) if VAR_3 else () if isinstance(VAR_1, six.string_types): if not VAR_1: raise ImproperlyConfigured("Error! Empty URL VAR_31 VAR_1 VAR_3 not permitted (for VAR_31 `%r`)." % VAR_0) if VAR_4: VAR_1 = VAR_4 + "." + VAR_1 VAR_1 = importing.load(VAR_1) return CLASS_0( VAR_0, VAR_1, VAR_2, VAR_3, VAR_5=require_authentication, VAR_6=permissions ) def FUNC_1(VAR_7, VAR_8, VAR_9, VAR_6=()): if VAR_6: warnings.warn( "Warning! `FUNC_1` VAR_6 attribute will be " "deprecated in Shuup 2.0 as unused for this util.", DeprecationWarning, ) return [ FUNC_0( r"%s/(?P<pk>\d+)/$" % VAR_7, VAR_8 % "Edit", VAR_3=VAR_9 % "edit", VAR_6=(VAR_9 % "edit",), ), FUNC_0( "%s/new/$" % VAR_7, VAR_8 % "Edit", VAR_3=VAR_9 % "new", VAR_2={"pk": None}, VAR_6=(VAR_9 % "new",), ), FUNC_0( "%s/$" % VAR_7, VAR_8 % "List", VAR_3=VAR_9 % "list", VAR_6=(VAR_9 % "list",), ), FUNC_0( "%s/list-settings/" % VAR_7, "shuup.admin.modules.settings.views.ListSettingsView", VAR_3=VAR_9 % "list_settings", VAR_6=(VAR_9 % "list_settings",), ), ] class CLASS_1(ValueError): pass def FUNC_2( VAR_10, VAR_11="detail", VAR_12=None, VAR_13=None, VAR_14=None, VAR_15=False, **VAR_2 ): for module in get_modules(): VAR_18 = module.get_model_url(VAR_10, VAR_11, VAR_14) if not VAR_18: continue if VAR_12 is None: return VAR_18 from shuup.utils.django_compat import Resolver404, resolve try: if VAR_13 is not None: warnings.warn( "Warning! `VAR_13` parameter will be deprecated " "in Shuup 2.0 as unused for this util.", DeprecationWarning, ) VAR_6 = VAR_13 else: VAR_39 = resolve(VAR_18) from shuup.admin.utils.permissions import get_permissions_for_module_url VAR_6 = get_permissions_for_module_url(module, VAR_39.url_name) VAR_35 = get_missing_permissions(VAR_12, VAR_6) if not VAR_35: return VAR_18 if VAR_15: from django.core.exceptions import PermissionDenied VAR_24 = _("Can't VAR_1 this page. You do not have the required permission(s): `{VAR_6}`.").format( VAR_6=", ".join(VAR_35) ) raise PermissionDenied(VAR_24) except Resolver404: return VAR_18 raise CLASS_1("Error! Can't get VAR_10 URL of VAR_11 %s: %r." % (VAR_11, force_text(VAR_10))) def FUNC_3(VAR_16, VAR_17, VAR_10, VAR_11): if not (isinstance(VAR_10, VAR_16) or (inspect.isclass(VAR_10) and issubclass(VAR_10, VAR_16))): return VAR_27 = { "detail": ("%s.detail" % VAR_17, "%s.edit" % VAR_17), } VAR_28 = [{}] if getattr(VAR_10, "pk", None): VAR_28.append({"pk": VAR_10.pk}) for urlname in VAR_27.get(VAR_11, ["%s.%s" % (VAR_17, VAR_11)]): for VAR_2 in VAR_28: try: return reverse(urlname, VAR_2=kwargs) except NoReverseMatch: pass return None def FUNC_4(VAR_18, **VAR_19): if "?" in VAR_18: url, VAR_37 = VAR_18.split("?", 1) VAR_19 = dict(parse_qsl(VAR_37), **VAR_19) qs = [(key, VAR_26) for (key, VAR_26) in VAR_19.items() if VAR_26 is not None] if VAR_19: return "%s?%s" % (VAR_18, urlencode(VAR_19)) else: return VAR_18 def FUNC_5(VAR_20, VAR_10): if not VAR_10.pk: return None if "shuup.front" in settings.INSTALLED_APPS: try: from shuup.front.template_helpers.urls import model_url return model_url({"request": VAR_20}, VAR_10) except (ValueError, NoReverseMatch): pass return None def FUNC_6(VAR_21): VAR_29 = VAR_21.get("front_url") if not VAR_29: try: VAR_29 = reverse("shuup:index") except NoReverseMatch: VAR_29 = None return VAR_29
from __future__ import unicode_literals import inspect import json import six import warnings from django.conf import settings from django.contrib.auth.views import redirect_to_login from django.core.exceptions import ImproperlyConfigured from django.http.response import HttpResponseForbidden from django.utils.encoding import force_str, force_text from django.utils.html import escape from django.utils.http import .urlencode from django.utils.translation import ugettext_lazy as _ from shuup.admin.module_registry import get_modules from shuup.admin.shop_provider import get_shop from shuup.admin.utils.permissions import get_missing_permissions from shuup.utils import importing from shuup.utils.django_compat import NoReverseMatch, URLPattern, get_callable, is_authenticated, reverse from shuup.utils.excs import Problem try: from urllib.parse import parse_qsl except ImportError: # pragma: no cover from urlparse import parse_qsl # Python 2.7 class CLASS_0(URLPattern): def __init__(self, VAR_0, VAR_22, VAR_23=None, VAR_3=None, VAR_5=True, VAR_6=()): self.permissions = tuple(VAR_6) self.require_authentication = VAR_5 if callable(VAR_22): FUNC_10 = self.wrap_with_permissions(VAR_22) from django.urls import re_path VAR_30 = re_path(VAR_0, VAR_22, VAR_23, VAR_3) VAR_31 = VAR_30.pattern super(CLASS_0, self).__init__(VAR_31, VAR_22, VAR_23, VAR_3) def FUNC_7(self, VAR_20, VAR_24): if VAR_20.is_ajax(): return HttpResponseForbidden(json.dumps({"error": force_text(VAR_24)})) VAR_32 = urlencode({"error": force_text(VAR_24)}) VAR_33 = force_str(reverse("shuup_admin:login") + "?" + VAR_32) VAR_34 = redirect_to_login(next=VAR_20.path, VAR_33=login_url) if is_authenticated(VAR_20.user): raise ( Problem(_("Can't VAR_1 this page. %(VAR_24)s") % {"reason": escape(VAR_24)}).with_link( VAR_18=VAR_34.url, title=_("Log in with different credentials...") ) ) return VAR_34 def FUNC_8(self, VAR_20): if self.require_authentication: if not is_authenticated(VAR_20.user): return _("Sign in to continue.") elif not getattr(VAR_20.user, "is_staff", False): return _("Your account must have `Access to Admin Panel` VAR_6 to access this page.") elif not get_shop(VAR_20): return _("There is no active VAR_14 available. Contact support for more details.") VAR_35 = get_missing_permissions(VAR_20.user, self.permissions) if VAR_35: return _("You do not have the required VAR_6: %s") % ", ".join(VAR_35) def FUNC_9(self, VAR_25): if callable(getattr(VAR_25, "as_view", None)): VAR_25 = view_func.as_view() @six.wraps(VAR_25) def FUNC_11(VAR_20, *VAR_36, **VAR_2): VAR_38 = self._get_unauth_reason(VAR_20) if VAR_38: return self._get_unauth_response(VAR_20, VAR_38) return VAR_25(VAR_20, *VAR_36, **VAR_2) return FUNC_11 @property def VAR_22(self): if self._callback is not None: return self._callback VAR_22 = get_callable(self._callback_str) self._callback = self.wrap_with_permissions(VAR_22) return self._callback @VAR_22.setter def VAR_22(self, VAR_26): self._callback = VAR_26 def FUNC_0(VAR_0, VAR_1, VAR_2=None, VAR_3=None, VAR_4="", VAR_5=True, VAR_6=None): if VAR_6 is None: VAR_6 = (VAR_3,) if VAR_3 else () if isinstance(VAR_1, six.string_types): if not VAR_1: raise ImproperlyConfigured("Error! Empty URL VAR_31 VAR_1 VAR_3 not permitted (for VAR_31 `%r`)." % VAR_0) if VAR_4: VAR_1 = VAR_4 + "." + VAR_1 VAR_1 = importing.load(VAR_1) return CLASS_0( VAR_0, VAR_1, VAR_2, VAR_3, VAR_5=require_authentication, VAR_6=permissions ) def FUNC_1(VAR_7, VAR_8, VAR_9, VAR_6=()): if VAR_6: warnings.warn( "Warning! `FUNC_1` VAR_6 attribute will be " "deprecated in Shuup 2.0 as unused for this util.", DeprecationWarning, ) return [ FUNC_0( r"%s/(?P<pk>\d+)/$" % VAR_7, VAR_8 % "Edit", VAR_3=VAR_9 % "edit", VAR_6=(VAR_9 % "edit",), ), FUNC_0( "%s/new/$" % VAR_7, VAR_8 % "Edit", VAR_3=VAR_9 % "new", VAR_2={"pk": None}, VAR_6=(VAR_9 % "new",), ), FUNC_0( "%s/$" % VAR_7, VAR_8 % "List", VAR_3=VAR_9 % "list", VAR_6=(VAR_9 % "list",), ), FUNC_0( "%s/list-settings/" % VAR_7, "shuup.admin.modules.settings.views.ListSettingsView", VAR_3=VAR_9 % "list_settings", VAR_6=(VAR_9 % "list_settings",), ), ] class CLASS_1(ValueError): pass def FUNC_2( VAR_10, VAR_11="detail", VAR_12=None, VAR_13=None, VAR_14=None, VAR_15=False, **VAR_2 ): for module in get_modules(): VAR_18 = module.get_model_url(VAR_10, VAR_11, VAR_14) if not VAR_18: continue if VAR_12 is None: return VAR_18 from shuup.utils.django_compat import Resolver404, resolve try: if VAR_13 is not None: warnings.warn( "Warning! `VAR_13` parameter will be deprecated " "in Shuup 2.0 as unused for this util.", DeprecationWarning, ) VAR_6 = VAR_13 else: VAR_39 = resolve(VAR_18) from shuup.admin.utils.permissions import get_permissions_for_module_url VAR_6 = get_permissions_for_module_url(module, VAR_39.url_name) VAR_35 = get_missing_permissions(VAR_12, VAR_6) if not VAR_35: return VAR_18 if VAR_15: from django.core.exceptions import PermissionDenied VAR_24 = _("Can't VAR_1 this page. You do not have the required permission(s): `{VAR_6}`.").format( VAR_6=", ".join(VAR_35) ) raise PermissionDenied(VAR_24) except Resolver404: return VAR_18 raise CLASS_1("Error! Can't get VAR_10 URL of VAR_11 %s: %r." % (VAR_11, force_text(VAR_10))) def FUNC_3(VAR_16, VAR_17, VAR_10, VAR_11): if not (isinstance(VAR_10, VAR_16) or (inspect.isclass(VAR_10) and issubclass(VAR_10, VAR_16))): return VAR_27 = { "detail": ("%s.detail" % VAR_17, "%s.edit" % VAR_17), } VAR_28 = [{}] if getattr(VAR_10, "pk", None): VAR_28.append({"pk": VAR_10.pk}) for urlname in VAR_27.get(VAR_11, ["%s.%s" % (VAR_17, VAR_11)]): for VAR_2 in VAR_28: try: return reverse(urlname, VAR_2=kwargs) except NoReverseMatch: pass return None def FUNC_4(VAR_18, **VAR_19): if "?" in VAR_18: url, VAR_37 = VAR_18.split("?", 1) VAR_19 = dict(parse_qsl(VAR_37), **VAR_19) qs = [(key, VAR_26) for (key, VAR_26) in VAR_19.items() if VAR_26 is not None] if VAR_19: return "%s?%s" % (VAR_18, urlencode(VAR_19)) else: return VAR_18 def FUNC_5(VAR_20, VAR_10): if not VAR_10.pk: return None if "shuup.front" in settings.INSTALLED_APPS: try: from shuup.front.template_helpers.urls import model_url return model_url({"request": VAR_20}, VAR_10) except (ValueError, NoReverseMatch): pass return None def FUNC_6(VAR_21): VAR_29 = VAR_21.get("front_url") if not VAR_29: try: VAR_29 = reverse("shuup:index") except NoReverseMatch: VAR_29 = None return VAR_29
[ 1, 2, 3, 4, 5, 6, 7, 9, 21, 28, 33, 34, 39, 42, 44, 48, 52, 64, 65, 72, 76, 88, 92, 96, 103, 105, 110, 114, 118, 119, 123, 129, 131, 135, 136, 140, 157, 185, 186, 189, 190, 197, 200, 202, 222, 225, 228, 230, 242, 244, 246, 249, 252, 257, 259, 261, 263, 264, 268, 270, 284, 288, 292, 299, 301, 302, 312, 313, 317, 325, 329, 332, 337, 338, 342, 353, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 340, 341, 342, 343, 344, 345, 50, 51, 52, 53, 54, 55, 56, 57, 74, 75, 76, 77, 78, 79, 80 ]
[ 1, 2, 3, 4, 5, 6, 7, 9, 22, 29, 34, 35, 40, 43, 45, 49, 53, 65, 66, 73, 77, 89, 93, 97, 104, 106, 111, 115, 119, 120, 124, 130, 132, 136, 137, 141, 158, 186, 187, 190, 191, 198, 201, 203, 223, 226, 229, 231, 243, 245, 247, 250, 253, 258, 260, 262, 264, 265, 269, 271, 285, 289, 293, 300, 302, 303, 313, 314, 318, 326, 330, 333, 338, 339, 343, 354, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 341, 342, 343, 344, 345, 346, 51, 52, 53, 54, 55, 56, 57, 58, 75, 76, 77, 78, 79, 80, 81 ]
1CWE-79
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe from frappe import _ import frappe.utils import frappe.sessions import frappe.desk.form.run_method from frappe.utils.response import build_response from frappe.api import validate_auth from frappe.utils import cint from frappe.core.doctype.server_script.server_script_utils import run_server_script_api from werkzeug.wrappers import Response from six import string_types ALLOWED_MIMETYPES = ('image/png', 'image/jpeg', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.spreadsheet') def handle(): """handle request""" validate_auth() cmd = frappe.local.form_dict.cmd data = None if cmd!='login': data = execute_cmd(cmd) # data can be an empty string or list which are valid responses if data is not None: if isinstance(data, Response): # method returns a response object, pass it on return data # add the response to `message` label frappe.response['message'] = data return build_response("json") def execute_cmd(cmd, from_async=False): """execute a request as python module""" for hook in frappe.get_hooks("override_whitelisted_methods", {}).get(cmd, []): # override using the first hook cmd = hook break # via server script if run_server_script_api(cmd): return None try: method = get_attr(cmd) except Exception as e: if frappe.local.conf.developer_mode: raise e else: frappe.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return if from_async: method = method.queue is_whitelisted(method) is_valid_http_method(method) return frappe.call(method, **frappe.form_dict) def is_valid_http_method(method): http_method = frappe.local.request.method if http_method not in frappe.allowed_http_methods_for_whitelisted_func[method]: frappe.throw(_("Not permitted"), frappe.PermissionError) def is_whitelisted(method): # check if whitelisted if frappe.session['user'] == 'Guest': if (method not in frappe.guest_methods): frappe.throw(_("Not permitted"), frappe.PermissionError) if method not in frappe.xss_safe_methods: # strictly sanitize form_dict # escapes html characters like <> except for predefined tags like a, b, ul etc. for key, value in frappe.form_dict.items(): if isinstance(value, string_types): frappe.form_dict[key] = frappe.utils.sanitize_html(value) else: if not method in frappe.whitelisted: frappe.throw(_("Not permitted"), frappe.PermissionError) @frappe.whitelist(allow_guest=True) def version(): return frappe.__version__ @frappe.whitelist() def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None): frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args) @frappe.whitelist(allow_guest=True) def logout(): frappe.local.login_manager.logout() frappe.db.commit() @frappe.whitelist(allow_guest=True) def web_logout(): frappe.local.login_manager.logout() frappe.db.commit() frappe.respond_as_web_page(_("Logged Out"), _("You have been successfully logged out"), indicator_color='green') @frappe.whitelist(allow_guest=True) def run_custom_method(doctype, name, custom_method): """cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}""" doc = frappe.get_doc(doctype, name) if getattr(doc, custom_method, frappe._dict()).is_whitelisted: frappe.call(getattr(doc, custom_method), **frappe.local.form_dict) else: frappe.throw(_("Not permitted"), frappe.PermissionError) @frappe.whitelist() def uploadfile(): ret = None try: if frappe.form_dict.get('from_form'): try: ret = frappe.get_doc({ "doctype": "File", "attached_to_name": frappe.form_dict.docname, "attached_to_doctype": frappe.form_dict.doctype, "attached_to_field": frappe.form_dict.docfield, "file_url": frappe.form_dict.file_url, "file_name": frappe.form_dict.filename, "is_private": frappe.utils.cint(frappe.form_dict.is_private), "content": frappe.form_dict.filedata, "decode": True }) ret.save() except frappe.DuplicateEntryError: # ignore pass ret = None frappe.db.rollback() else: if frappe.form_dict.get('method'): method = frappe.get_attr(frappe.form_dict.method) is_whitelisted(method) ret = method() except Exception: frappe.errprint(frappe.utils.get_traceback()) frappe.response['http_status_code'] = 500 ret = None return ret @frappe.whitelist(allow_guest=True) def upload_file(): user = None if frappe.session.user == 'Guest': if frappe.get_system_settings('allow_guests_to_upload_files'): ignore_permissions = True else: return else: user = frappe.get_doc("User", frappe.session.user) ignore_permissions = False files = frappe.request.files is_private = frappe.form_dict.is_private doctype = frappe.form_dict.doctype docname = frappe.form_dict.docname fieldname = frappe.form_dict.fieldname file_url = frappe.form_dict.file_url folder = frappe.form_dict.folder or 'Home' method = frappe.form_dict.method content = None filename = None if 'file' in files: file = files['file'] content = file.stream.read() filename = file.filename frappe.local.uploaded_file = content frappe.local.uploaded_filename = filename if frappe.session.user == 'Guest' or (user and not user.has_desk_access()): import mimetypes filetype = mimetypes.guess_type(filename)[0] if filetype not in ALLOWED_MIMETYPES: frappe.throw(_("You can only upload JPG, PNG, PDF, or Microsoft documents.")) if method: method = frappe.get_attr(method) is_whitelisted(method) return method() else: ret = frappe.get_doc({ "doctype": "File", "attached_to_doctype": doctype, "attached_to_name": docname, "attached_to_field": fieldname, "folder": folder, "file_name": filename, "file_url": file_url, "is_private": cint(is_private), "content": content }) ret.save(ignore_permissions=ignore_permissions) return ret def get_attr(cmd): """get method object from cmd""" if '.' in cmd: method = frappe.get_attr(cmd) else: method = globals()[cmd] frappe.log("method:" + cmd) return method @frappe.whitelist(allow_guest = True) def ping(): return "pong"
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals from werkzeug.wrappers import Response from six import text_type, string_types, StringIO import frappe import frappe.utils import frappe.sessions import frappe.desk.form.run_method from frappe.utils import cint from frappe.api import validate_auth from frappe import _, is_whitelisted from frappe.utils.response import build_response from frappe.utils.csvutils import build_csv_response from frappe.core.doctype.server_script.server_script_utils import run_server_script_api ALLOWED_MIMETYPES = ('image/png', 'image/jpeg', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.spreadsheet') def handle(): """handle request""" validate_auth() cmd = frappe.local.form_dict.cmd data = None if cmd!='login': data = execute_cmd(cmd) # data can be an empty string or list which are valid responses if data is not None: if isinstance(data, Response): # method returns a response object, pass it on return data # add the response to `message` label frappe.response['message'] = data return build_response("json") def execute_cmd(cmd, from_async=False): """execute a request as python module""" for hook in frappe.get_hooks("override_whitelisted_methods", {}).get(cmd, []): # override using the first hook cmd = hook break # via server script if run_server_script_api(cmd): return None try: method = get_attr(cmd) except Exception as e: if frappe.local.conf.developer_mode: raise e else: frappe.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return if from_async: method = method.queue if method != run_doc_method: is_whitelisted(method) is_valid_http_method(method) return frappe.call(method, **frappe.form_dict) def is_valid_http_method(method): http_method = frappe.local.request.method if http_method not in frappe.allowed_http_methods_for_whitelisted_func[method]: frappe.throw(_("Not permitted"), frappe.PermissionError) @frappe.whitelist(allow_guest=True) def version(): return frappe.__version__ @frappe.whitelist(allow_guest=True) def logout(): frappe.local.login_manager.logout() frappe.db.commit() @frappe.whitelist(allow_guest=True) def web_logout(): frappe.local.login_manager.logout() frappe.db.commit() frappe.respond_as_web_page(_("Logged Out"), _("You have been successfully logged out"), indicator_color='green') @frappe.whitelist() def uploadfile(): ret = None try: if frappe.form_dict.get('from_form'): try: ret = frappe.get_doc({ "doctype": "File", "attached_to_name": frappe.form_dict.docname, "attached_to_doctype": frappe.form_dict.doctype, "attached_to_field": frappe.form_dict.docfield, "file_url": frappe.form_dict.file_url, "file_name": frappe.form_dict.filename, "is_private": frappe.utils.cint(frappe.form_dict.is_private), "content": frappe.form_dict.filedata, "decode": True }) ret.save() except frappe.DuplicateEntryError: # ignore pass ret = None frappe.db.rollback() else: if frappe.form_dict.get('method'): method = frappe.get_attr(frappe.form_dict.method) is_whitelisted(method) ret = method() except Exception: frappe.errprint(frappe.utils.get_traceback()) frappe.response['http_status_code'] = 500 ret = None return ret @frappe.whitelist(allow_guest=True) def upload_file(): user = None if frappe.session.user == 'Guest': if frappe.get_system_settings('allow_guests_to_upload_files'): ignore_permissions = True else: return else: user = frappe.get_doc("User", frappe.session.user) ignore_permissions = False files = frappe.request.files is_private = frappe.form_dict.is_private doctype = frappe.form_dict.doctype docname = frappe.form_dict.docname fieldname = frappe.form_dict.fieldname file_url = frappe.form_dict.file_url folder = frappe.form_dict.folder or 'Home' method = frappe.form_dict.method content = None filename = None if 'file' in files: file = files['file'] content = file.stream.read() filename = file.filename frappe.local.uploaded_file = content frappe.local.uploaded_filename = filename if frappe.session.user == 'Guest' or (user and not user.has_desk_access()): import mimetypes filetype = mimetypes.guess_type(filename)[0] if filetype not in ALLOWED_MIMETYPES: frappe.throw(_("You can only upload JPG, PNG, PDF, or Microsoft documents.")) if method: method = frappe.get_attr(method) is_whitelisted(method) return method() else: ret = frappe.get_doc({ "doctype": "File", "attached_to_doctype": doctype, "attached_to_name": docname, "attached_to_field": fieldname, "folder": folder, "file_name": filename, "file_url": file_url, "is_private": cint(is_private), "content": content }) ret.save(ignore_permissions=ignore_permissions) return ret def get_attr(cmd): """get method object from cmd""" if '.' in cmd: method = frappe.get_attr(cmd) else: method = globals()[cmd] frappe.log("method:" + cmd) return method @frappe.whitelist(allow_guest=True) def ping(): return "pong" @frappe.whitelist() def run_doc_method(method, docs=None, dt=None, dn=None, arg=None, args=None): """run controller method - old style""" import json, inspect if not args: args = arg or "" if dt: # not called from a doctype (from a page) if not dn: dn = dt # single doc = frappe.get_doc(dt, dn) else: doc = frappe.get_doc(json.loads(docs)) doc._original_modified = doc.modified doc.check_if_latest() if not doc.has_permission("read"): frappe.msgprint(_("Not permitted"), raise_exception = True) if not doc: return try: args = json.loads(args) except ValueError: args = args method_obj = getattr(doc, method) is_whitelisted(getattr(method_obj, '__func__', method_obj)) try: fnargs = inspect.getargspec(method_obj)[0] except ValueError: fnargs = inspect.getfullargspec(method_obj).args if not fnargs or (len(fnargs)==1 and fnargs[0]=="self"): r = doc.run_method(method) elif "args" in fnargs or not isinstance(args, dict): r = doc.run_method(method, args) else: r = doc.run_method(method, **args) frappe.response.docs.append(doc) if not r: return # build output as csv if cint(frappe.form_dict.get('as_csv')): build_csv_response(r, doc.doctype.replace(' ', '')) return frappe.response['message'] = r # for backwards compatibility runserverobj = run_doc_method
xss
{ "code": [ "from frappe import _", "from frappe.utils.response import build_response", "from frappe.api import validate_auth", "from werkzeug.wrappers import Response", "from six import string_types", "\tis_whitelisted(method)", "\tis_valid_http_method(method)", "def is_whitelisted(method):", "\tif frappe.session['user'] == 'Guest':", "\t\tif (method not in frappe.guest_methods):", "\t\t\tfrappe.throw(_(\"Not permitted\"), frappe.PermissionError)", "\t\tif method not in frappe.xss_safe_methods:", "\t\t\tfor key, value in frappe.form_dict.items():", "\t\t\t\tif isinstance(value, string_types):", "\t\t\t\t\tfrappe.form_dict[key] = frappe.utils.sanitize_html(value)", "\telse:", "\t\tif not method in frappe.whitelisted:", "\t\t\tfrappe.throw(_(\"Not permitted\"), frappe.PermissionError)", "@frappe.whitelist()", "def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None):", "\tfrappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)", "@frappe.whitelist(allow_guest=True)", "def run_custom_method(doctype, name, custom_method):", "\tdoc = frappe.get_doc(doctype, name)", "\tif getattr(doc, custom_method, frappe._dict()).is_whitelisted:", "\t\tfrappe.call(getattr(doc, custom_method), **frappe.local.form_dict)", "\telse:", "\t\tfrappe.throw(_(\"Not permitted\"), frappe.PermissionError)", "@frappe.whitelist(allow_guest = True)" ], "line_no": [ 6, 10, 11, 14, 15, 67, 68, 78, 80, 81, 82, 84, 87, 88, 89, 91, 92, 93, 99, 100, 101, 115, 116, 118, 119, 120, 121, 122, 225 ] }
{ "code": [ "from werkzeug.wrappers import Response", "from six import text_type, string_types, StringIO", "from frappe.api import validate_auth", "from frappe.utils.response import build_response", "from frappe.utils.csvutils import build_csv_response", "\tif method != run_doc_method:", "\t\tis_whitelisted(method)", "@frappe.whitelist(allow_guest=True)", "@frappe.whitelist()", "def run_doc_method(method, docs=None, dt=None, dn=None, arg=None, args=None):", "\t\"\"\"run controller method - old style\"\"\"", "\timport json, inspect", "\tif not args: args = arg or \"\"", "\telse:", "\t\tdoc._original_modified = doc.modified", "\t\tdoc.check_if_latest()", "\tif not doc.has_permission(\"read\"):", "\t\tfrappe.msgprint(_(\"Not permitted\"), raise_exception = True)", "\t\treturn", "\ttry:", "\texcept ValueError:", "\t\targs = args", "\tmethod_obj = getattr(doc, method)", "\tis_whitelisted(getattr(method_obj, '__func__', method_obj))", "\ttry:", "\t\tfnargs = inspect.getargspec(method_obj)[0]", "\texcept ValueError:", "\t\tfnargs = inspect.getfullargspec(method_obj).args", "\tif not fnargs or (len(fnargs)==1 and fnargs[0]==\"self\"):", "\t\tr = doc.run_method(method)", "\telif \"args\" in fnargs or not isinstance(args, dict):", "\t\tr = doc.run_method(method, args)", "\telse:", "\t\tr = doc.run_method(method, **args)", "\tfrappe.response.docs.append(doc)", "\tif not r:", "\t\treturn", "\tif cint(frappe.form_dict.get('as_csv')):", "\t\tbuild_csv_response(r, doc.doctype.replace(' ', ''))", "\t\treturn", "\tfrappe.response['message'] = r", "runserverobj = run_doc_method" ], "line_no": [ 6, 7, 15, 17, 18, 72, 73, 201, 205, 206, 207, 208, 210, 216, 218, 219, 221, 222, 225, 227, 229, 230, 232, 233, 235, 236, 237, 238, 240, 241, 243, 244, 246, 247, 249, 251, 252, 255, 256, 257, 259, 262 ] }
from __future__ import unicode_literals import .frappe from VAR_25 import _ import .frappe.utils import .frappe.sessions import .frappe.desk.form.run_method from VAR_25.utils.response import build_response from VAR_25.api import validate_auth from VAR_25.utils import cint from VAR_25.core.doctype.server_script.server_script_utils import run_server_script_api from werkzeug.wrappers import Response from six import string_types VAR_0 = ('image/png', 'image/jpeg', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.spreadsheet') def FUNC_0(): validate_auth() VAR_1 = VAR_25.local.form_dict.cmd VAR_12 = None if VAR_1!='login': VAR_12 = FUNC_1(VAR_1) if VAR_12 is not None: if isinstance(VAR_12, Response): return VAR_12 VAR_25.response['message'] = VAR_12 return build_response("json") def FUNC_1(VAR_1, VAR_2=False): for hook in VAR_25.get_hooks("override_whitelisted_methods", {}).get(VAR_1, []): VAR_1 = hook break if run_server_script_api(VAR_1): return None try: VAR_3 = FUNC_11(VAR_1) except Exception as e: if VAR_25.local.conf.developer_mode: raise e else: VAR_25.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return if VAR_2: VAR_3 = method.queue FUNC_3(VAR_3) FUNC_2(VAR_3) return VAR_25.call(VAR_3, **VAR_25.form_dict) def FUNC_2(VAR_3): VAR_13 = VAR_25.local.request.method if VAR_13 not in VAR_25.allowed_http_methods_for_whitelisted_func[VAR_3]: VAR_25.throw(_("Not permitted"), VAR_25.PermissionError) def FUNC_3(VAR_3): if VAR_25.session['user'] == 'Guest': if (VAR_3 not in VAR_25.guest_methods): VAR_25.throw(_("Not permitted"), VAR_25.PermissionError) if VAR_3 not in VAR_25.xss_safe_methods: for VAR_29, value in VAR_25.form_dict.items(): if isinstance(value, string_types): VAR_25.form_dict[VAR_29] = VAR_25.utils.sanitize_html(value) else: if not VAR_3 in VAR_25.whitelisted: VAR_25.throw(_("Not permitted"), VAR_25.PermissionError) @VAR_25.whitelist(allow_guest=True) def FUNC_4(): return VAR_25.__version__ @VAR_25.whitelist() def FUNC_5(VAR_3, VAR_4=None, VAR_5=None, VAR_6=None, VAR_7=None, VAR_8=None): VAR_25.desk.form.run_method.runserverobj(VAR_3, VAR_4=docs, VAR_5=dt, VAR_6=dn, VAR_7=arg, VAR_8=args) @VAR_25.whitelist(allow_guest=True) def FUNC_6(): VAR_25.local.login_manager.logout() VAR_25.db.commit() @VAR_25.whitelist(allow_guest=True) def FUNC_7(): VAR_25.local.login_manager.logout() VAR_25.db.commit() VAR_25.respond_as_web_page(_("Logged Out"), _("You have been successfully logged out"), indicator_color='green') @VAR_25.whitelist(allow_guest=True) def FUNC_8(VAR_9, VAR_10, VAR_11): VAR_14 = VAR_25.get_doc(VAR_9, VAR_10) if getattr(VAR_14, VAR_11, VAR_25._dict()).is_whitelisted: VAR_25.call(getattr(VAR_14, VAR_11), **VAR_25.local.form_dict) else: VAR_25.throw(_("Not permitted"), VAR_25.PermissionError) @VAR_25.whitelist() def FUNC_9(): VAR_15 = None try: if VAR_25.form_dict.get('from_form'): try: VAR_15 = VAR_25.get_doc({ "doctype": "File", "attached_to_name": VAR_25.form_dict.docname, "attached_to_doctype": VAR_25.form_dict.doctype, "attached_to_field": VAR_25.form_dict.docfield, "file_url": VAR_25.form_dict.file_url, "file_name": VAR_25.form_dict.filename, "is_private": VAR_25.utils.cint(VAR_25.form_dict.is_private), "content": VAR_25.form_dict.filedata, "decode": True }) VAR_15.save() except VAR_25.DuplicateEntryError: VAR_15 = None VAR_25.db.rollback() else: if VAR_25.form_dict.get('method'): VAR_3 = VAR_25.get_attr(VAR_25.form_dict.method) FUNC_3(VAR_3) VAR_15 = VAR_3() except Exception: VAR_25.errprint(VAR_25.utils.get_traceback()) VAR_25.response['http_status_code'] = 500 VAR_15 = None return VAR_15 @VAR_25.whitelist(allow_guest=True) def FUNC_10(): VAR_16 = None if VAR_25.session.user == 'Guest': if VAR_25.get_system_settings('allow_guests_to_upload_files'): VAR_26 = True else: return else: VAR_16 = VAR_25.get_doc("User", VAR_25.session.user) VAR_26 = False VAR_17 = VAR_25.request.files VAR_18 = VAR_25.form_dict.is_private VAR_9 = VAR_25.form_dict.doctype VAR_19 = VAR_25.form_dict.docname VAR_20 = VAR_25.form_dict.fieldname VAR_21 = VAR_25.form_dict.file_url VAR_22 = VAR_25.form_dict.folder or 'Home' VAR_3 = VAR_25.form_dict.method VAR_23 = None VAR_24 = None if 'file' in VAR_17: VAR_27 = VAR_17['file'] VAR_23 = VAR_27.stream.read() VAR_24 = VAR_27.filename VAR_25.local.uploaded_file = VAR_23 VAR_25.local.uploaded_filename = VAR_24 if VAR_25.session.user == 'Guest' or (VAR_16 and not VAR_16.has_desk_access()): import mimetypes VAR_28 = mimetypes.guess_type(VAR_24)[0] if VAR_28 not in VAR_0: VAR_25.throw(_("You can only upload JPG, PNG, PDF, or Microsoft documents.")) if VAR_3: VAR_3 = VAR_25.get_attr(VAR_3) FUNC_3(VAR_3) return VAR_3() else: VAR_15 = VAR_25.get_doc({ "doctype": "File", "attached_to_doctype": VAR_9, "attached_to_name": VAR_19, "attached_to_field": VAR_20, "folder": VAR_22, "file_name": VAR_24, "file_url": VAR_21, "is_private": cint(VAR_18), "content": VAR_23 }) VAR_15.save(VAR_26=ignore_permissions) return VAR_15 def FUNC_11(VAR_1): if '.' in VAR_1: VAR_3 = VAR_25.get_attr(VAR_1) else: VAR_3 = globals()[VAR_1] VAR_25.log("method:" + VAR_1) return VAR_3 @VAR_25.whitelist(allow_guest = True) def FUNC_12(): return "pong"
from __future__ import unicode_literals from werkzeug.wrappers import Response from six import text_type, string_types, StringIO import .frappe import .frappe.utils import .frappe.sessions import .frappe.desk.form.run_method from VAR_24.utils import cint from VAR_24.api import validate_auth from VAR_24 import _, is_whitelisted from VAR_24.utils.response import build_response from VAR_24.utils.csvutils import build_csv_response from VAR_24.core.doctype.server_script.server_script_utils import .run_server_script_api VAR_0 = ('image/png', 'image/jpeg', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.spreadsheet') def FUNC_0(): validate_auth() VAR_1 = VAR_24.local.form_dict.cmd VAR_10 = None if VAR_1!='login': VAR_10 = FUNC_1(VAR_1) if VAR_10 is not None: if isinstance(VAR_10, Response): return VAR_10 VAR_24.response['message'] = VAR_10 return build_response("json") def FUNC_1(VAR_1, VAR_2=False): for hook in VAR_24.get_hooks("override_whitelisted_methods", {}).get(VAR_1, []): VAR_1 = hook break if run_server_script_api(VAR_1): return None try: VAR_3 = FUNC_8(VAR_1) except Exception as e: if VAR_24.local.conf.developer_mode: raise e else: VAR_24.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return if VAR_2: VAR_3 = method.queue if VAR_3 != FUNC_10: is_whitelisted(VAR_3) FUNC_2(VAR_3) return VAR_24.call(VAR_3, **VAR_24.form_dict) def FUNC_2(VAR_3): VAR_11 = VAR_24.local.request.method if VAR_11 not in VAR_24.allowed_http_methods_for_whitelisted_func[VAR_3]: VAR_24.throw(_("Not permitted"), VAR_24.PermissionError) @VAR_24.whitelist(allow_guest=True) def FUNC_3(): return VAR_24.__version__ @VAR_24.whitelist(allow_guest=True) def FUNC_4(): VAR_24.local.login_manager.logout() VAR_24.db.commit() @VAR_24.whitelist(allow_guest=True) def FUNC_5(): VAR_24.local.login_manager.logout() VAR_24.db.commit() VAR_24.respond_as_web_page(_("Logged Out"), _("You have been successfully logged out"), indicator_color='green') @VAR_24.whitelist() def FUNC_6(): VAR_12 = None try: if VAR_24.form_dict.get('from_form'): try: VAR_12 = VAR_24.get_doc({ "doctype": "File", "attached_to_name": VAR_24.form_dict.docname, "attached_to_doctype": VAR_24.form_dict.doctype, "attached_to_field": VAR_24.form_dict.docfield, "file_url": VAR_24.form_dict.file_url, "file_name": VAR_24.form_dict.filename, "is_private": VAR_24.utils.cint(VAR_24.form_dict.is_private), "content": VAR_24.form_dict.filedata, "decode": True }) VAR_12.save() except VAR_24.DuplicateEntryError: VAR_12 = None VAR_24.db.rollback() else: if VAR_24.form_dict.get('method'): VAR_3 = VAR_24.get_attr(VAR_24.form_dict.method) is_whitelisted(VAR_3) VAR_12 = VAR_3() except Exception: VAR_24.errprint(VAR_24.utils.get_traceback()) VAR_24.response['http_status_code'] = 500 VAR_12 = None return VAR_12 @VAR_24.whitelist(allow_guest=True) def FUNC_7(): VAR_13 = None if VAR_24.session.user == 'Guest': if VAR_24.get_system_settings('allow_guests_to_upload_files'): VAR_25 = True else: return else: VAR_13 = VAR_24.get_doc("User", VAR_24.session.user) VAR_25 = False VAR_14 = VAR_24.request.files VAR_15 = VAR_24.form_dict.is_private VAR_16 = VAR_24.form_dict.doctype VAR_17 = VAR_24.form_dict.docname VAR_18 = VAR_24.form_dict.fieldname VAR_19 = VAR_24.form_dict.file_url VAR_20 = VAR_24.form_dict.folder or 'Home' VAR_3 = VAR_24.form_dict.method VAR_21 = None VAR_22 = None if 'file' in VAR_14: VAR_26 = VAR_14['file'] VAR_21 = VAR_26.stream.read() VAR_22 = VAR_26.filename VAR_24.local.uploaded_file = VAR_21 VAR_24.local.uploaded_filename = VAR_22 if VAR_24.session.user == 'Guest' or (VAR_13 and not VAR_13.has_desk_access()): import mimetypes VAR_27 = mimetypes.guess_type(VAR_22)[0] if VAR_27 not in VAR_0: VAR_24.throw(_("You can only upload JPG, PNG, PDF, or Microsoft documents.")) if VAR_3: VAR_3 = VAR_24.get_attr(VAR_3) is_whitelisted(VAR_3) return VAR_3() else: VAR_12 = VAR_24.get_doc({ "doctype": "File", "attached_to_doctype": VAR_16, "attached_to_name": VAR_17, "attached_to_field": VAR_18, "folder": VAR_20, "file_name": VAR_22, "file_url": VAR_19, "is_private": cint(VAR_15), "content": VAR_21 }) VAR_12.save(VAR_25=ignore_permissions) return VAR_12 def FUNC_8(VAR_1): if '.' in VAR_1: VAR_3 = VAR_24.get_attr(VAR_1) else: VAR_3 = globals()[VAR_1] VAR_24.log("method:" + VAR_1) return VAR_3 @VAR_24.whitelist(allow_guest=True) def FUNC_9(): return "pong" @VAR_24.whitelist() def FUNC_10(VAR_3, VAR_4=None, VAR_5=None, VAR_6=None, VAR_7=None, VAR_8=None): import json, inspect if not VAR_8: args = VAR_7 or "" if VAR_5: # not called from a VAR_16 (from a page) if not VAR_6: dn = VAR_5 # single VAR_28 = VAR_24.get_doc(VAR_5, VAR_6) else: VAR_28 = VAR_24.get_doc(json.loads(VAR_4)) VAR_28._original_modified = VAR_28.modified VAR_28.check_if_latest() if not VAR_28.has_permission("read"): VAR_24.msgprint(_("Not permitted"), raise_exception = True) if not VAR_28: return try: VAR_8 = json.loads(VAR_8) except ValueError: VAR_8 = args VAR_23 = getattr(VAR_28, VAR_3) is_whitelisted(getattr(VAR_23, '__func__', VAR_23)) try: VAR_29 = inspect.getargspec(VAR_23)[0] except ValueError: VAR_29 = inspect.getfullargspec(VAR_23).args if not VAR_29 or (len(VAR_29)==1 and VAR_29[0]=="self"): VAR_30 = VAR_28.run_method(VAR_3) elif "args" in VAR_29 or not isinstance(VAR_8, dict): VAR_30 = VAR_28.run_method(VAR_3, VAR_8) else: VAR_30 = VAR_28.run_method(VAR_3, **VAR_8) VAR_24.response.docs.append(VAR_28) if not VAR_30: return if cint(VAR_24.form_dict.get('as_csv')): build_csv_response(VAR_30, VAR_28.doctype.replace(' ', '')) return VAR_24.response['message'] = VAR_30 VAR_9 = FUNC_10
[ 1, 2, 3, 16, 21, 22, 28, 31, 32, 35, 37, 38, 40, 42, 46, 49, 50, 53, 63, 66, 69, 71, 74, 77, 79, 83, 85, 86, 90, 94, 98, 102, 107, 114, 123, 127, 144, 156, 158, 170, 181, 186, 189, 195, 214, 215, 224, 228, 24, 44, 117, 217 ]
[ 1, 2, 3, 5, 8, 13, 20, 21, 26, 27, 33, 36, 37, 40, 42, 43, 45, 47, 51, 54, 55, 58, 68, 71, 75, 77, 80, 83, 87, 92, 99, 103, 120, 132, 134, 146, 157, 162, 165, 171, 190, 191, 200, 204, 209, 211, 215, 220, 223, 226, 231, 234, 239, 242, 245, 248, 250, 253, 254, 258, 260, 261, 263, 29, 49, 193, 207 ]
1CWE-79
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from ..constants import voidElements, booleanAttributes, spaceCharacters from ..constants import rcdataElements, entities, xmlEntities from .. import utils from xml.sax.saxutils import escape spaceCharacters = "".join(spaceCharacters) quoteAttributeSpec = re.compile("[" + spaceCharacters + "\"'=<>`]") try: from codecs import register_error, xmlcharrefreplace_errors except ImportError: unicode_encode_errors = "strict" else: unicode_encode_errors = "htmlentityreplace" encode_entity_map = {} is_ucs4 = len("\U0010FFFF") == 1 for k, v in list(entities.items()): # skip multi-character entities if ((is_ucs4 and len(v) > 1) or (not is_ucs4 and len(v) > 2)): continue if v != "&": if len(v) == 2: v = utils.surrogatePairToCodepoint(v) else: v = ord(v) if v not in encode_entity_map or k.islower(): # prefer &lt; over &LT; and similarly for &amp;, &gt;, etc. encode_entity_map[v] = k def htmlentityreplace_errors(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): res = [] codepoints = [] skip = False for i, c in enumerate(exc.object[exc.start:exc.end]): if skip: skip = False continue index = i + exc.start if utils.isSurrogatePair(exc.object[index:min([exc.end, index + 2])]): codepoint = utils.surrogatePairToCodepoint(exc.object[index:index + 2]) skip = True else: codepoint = ord(c) codepoints.append(codepoint) for cp in codepoints: e = encode_entity_map.get(cp) if e: res.append("&") res.append(e) if not e.endswith(";"): res.append(";") else: res.append("&#x%s;" % (hex(cp)[2:])) return ("".join(res), exc.end) else: return xmlcharrefreplace_errors(exc) register_error(unicode_encode_errors, htmlentityreplace_errors) del register_error class HTMLSerializer(object): # attribute quoting options quote_attr_values = False quote_char = '"' use_best_quote_char = True # tag syntax options omit_optional_tags = True minimize_boolean_attributes = True use_trailing_solidus = False space_before_trailing_solidus = True # escaping options escape_lt_in_attrs = False escape_rcdata = False resolve_entities = True # miscellaneous options alphabetical_attributes = False inject_meta_charset = True strip_whitespace = False sanitize = False options = ("quote_attr_values", "quote_char", "use_best_quote_char", "omit_optional_tags", "minimize_boolean_attributes", "use_trailing_solidus", "space_before_trailing_solidus", "escape_lt_in_attrs", "escape_rcdata", "resolve_entities", "alphabetical_attributes", "inject_meta_charset", "strip_whitespace", "sanitize") def __init__(self, **kwargs): """Initialize HTMLSerializer. Keyword options (default given first unless specified) include: inject_meta_charset=True|False Whether it insert a meta element to define the character set of the document. quote_attr_values=True|False Whether to quote attribute values that don't require quoting per HTML5 parsing rules. quote_char=u'"'|u"'" Use given quote character for attribute quoting. Default is to use double quote unless attribute value contains a double quote, in which case single quotes are used instead. escape_lt_in_attrs=False|True Whether to escape < in attribute values. escape_rcdata=False|True Whether to escape characters that need to be escaped within normal elements within rcdata elements such as style. resolve_entities=True|False Whether to resolve named character entities that appear in the source tree. The XML predefined entities &lt; &gt; &amp; &quot; &apos; are unaffected by this setting. strip_whitespace=False|True Whether to remove semantically meaningless whitespace. (This compresses all whitespace to a single space except within pre.) minimize_boolean_attributes=True|False Shortens boolean attributes to give just the attribute value, for example <input disabled="disabled"> becomes <input disabled>. use_trailing_solidus=False|True Includes a close-tag slash at the end of the start tag of void elements (empty elements whose end tag is forbidden). E.g. <hr/>. space_before_trailing_solidus=True|False Places a space immediately before the closing slash in a tag using a trailing solidus. E.g. <hr />. Requires use_trailing_solidus. sanitize=False|True Strip all unsafe or unknown constructs from output. See `html5lib user documentation`_ omit_optional_tags=True|False Omit start/end tags that are optional. alphabetical_attributes=False|True Reorder attributes to be in alphabetical order. .. _html5lib user documentation: http://code.google.com/p/html5lib/wiki/UserDocumentation """ if 'quote_char' in kwargs: self.use_best_quote_char = False for attr in self.options: setattr(self, attr, kwargs.get(attr, getattr(self, attr))) self.errors = [] self.strict = False def encode(self, string): assert(isinstance(string, text_type)) if self.encoding: return string.encode(self.encoding, unicode_encode_errors) else: return string def encodeStrict(self, string): assert(isinstance(string, text_type)) if self.encoding: return string.encode(self.encoding, "strict") else: return string def serialize(self, treewalker, encoding=None): self.encoding = encoding in_cdata = False self.errors = [] if encoding and self.inject_meta_charset: from ..filters.inject_meta_charset import Filter treewalker = Filter(treewalker, encoding) # WhitespaceFilter should be used before OptionalTagFilter # for maximum efficiently of this latter filter if self.strip_whitespace: from ..filters.whitespace import Filter treewalker = Filter(treewalker) if self.sanitize: from ..filters.sanitizer import Filter treewalker = Filter(treewalker) if self.omit_optional_tags: from ..filters.optionaltags import Filter treewalker = Filter(treewalker) # Alphabetical attributes must be last, as other filters # could add attributes and alter the order if self.alphabetical_attributes: from ..filters.alphabeticalattributes import Filter treewalker = Filter(treewalker) for token in treewalker: type = token["type"] if type == "Doctype": doctype = "<!DOCTYPE %s" % token["name"] if token["publicId"]: doctype += ' PUBLIC "%s"' % token["publicId"] elif token["systemId"]: doctype += " SYSTEM" if token["systemId"]: if token["systemId"].find('"') >= 0: if token["systemId"].find("'") >= 0: self.serializeError("System identifer contains both single and double quote characters") quote_char = "'" else: quote_char = '"' doctype += " %s%s%s" % (quote_char, token["systemId"], quote_char) doctype += ">" yield self.encodeStrict(doctype) elif type in ("Characters", "SpaceCharacters"): if type == "SpaceCharacters" or in_cdata: if in_cdata and token["data"].find("</") >= 0: self.serializeError("Unexpected </ in CDATA") yield self.encode(token["data"]) else: yield self.encode(escape(token["data"])) elif type in ("StartTag", "EmptyTag"): name = token["name"] yield self.encodeStrict("<%s" % name) if name in rcdataElements and not self.escape_rcdata: in_cdata = True elif in_cdata: self.serializeError("Unexpected child element of a CDATA element") for (attr_namespace, attr_name), attr_value in token["data"].items(): # TODO: Add namespace support here k = attr_name v = attr_value yield self.encodeStrict(' ') yield self.encodeStrict(k) if not self.minimize_boolean_attributes or \ (k not in booleanAttributes.get(name, tuple()) and k not in booleanAttributes.get("", tuple())): yield self.encodeStrict("=") if self.quote_attr_values: quote_attr = True else: quote_attr = len(v) == 0 or quoteAttributeSpec.search(v) v = v.replace("&", "&amp;") if self.escape_lt_in_attrs: v = v.replace("<", "&lt;") if quote_attr: quote_char = self.quote_char if self.use_best_quote_char: if "'" in v and '"' not in v: quote_char = '"' elif '"' in v and "'" not in v: quote_char = "'" if quote_char == "'": v = v.replace("'", "&#39;") else: v = v.replace('"', "&quot;") yield self.encodeStrict(quote_char) yield self.encode(v) yield self.encodeStrict(quote_char) else: yield self.encode(v) if name in voidElements and self.use_trailing_solidus: if self.space_before_trailing_solidus: yield self.encodeStrict(" /") else: yield self.encodeStrict("/") yield self.encode(">") elif type == "EndTag": name = token["name"] if name in rcdataElements: in_cdata = False elif in_cdata: self.serializeError("Unexpected child element of a CDATA element") yield self.encodeStrict("</%s>" % name) elif type == "Comment": data = token["data"] if data.find("--") >= 0: self.serializeError("Comment contains --") yield self.encodeStrict("<!--%s-->" % token["data"]) elif type == "Entity": name = token["name"] key = name + ";" if key not in entities: self.serializeError("Entity %s not recognized" % name) if self.resolve_entities and key not in xmlEntities: data = entities[key] else: data = "&%s;" % name yield self.encodeStrict(data) else: self.serializeError(token["data"]) def render(self, treewalker, encoding=None): if encoding: return b"".join(list(self.serialize(treewalker, encoding))) else: return "".join(list(self.serialize(treewalker))) def serializeError(self, data="XXX ERROR MESSAGE NEEDED"): # XXX The idea is to make data mandatory. self.errors.append(data) if self.strict: raise SerializeError def SerializeError(Exception): """Error in serialized tree""" pass
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from ..constants import voidElements, booleanAttributes, spaceCharacters from ..constants import rcdataElements, entities, xmlEntities from .. import utils from xml.sax.saxutils import escape spaceCharacters = "".join(spaceCharacters) quoteAttributeSpecChars = spaceCharacters + "\"'=<>`" quoteAttributeSpec = re.compile("[" + quoteAttributeSpecChars + "]") quoteAttributeLegacy = re.compile("[" + quoteAttributeSpecChars + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n" "\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15" "\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" "\x20\x2f\x60\xa0\u1680\u180e\u180f\u2000" "\u2001\u2002\u2003\u2004\u2005\u2006\u2007" "\u2008\u2009\u200a\u2028\u2029\u202f\u205f" "\u3000]") try: from codecs import register_error, xmlcharrefreplace_errors except ImportError: unicode_encode_errors = "strict" else: unicode_encode_errors = "htmlentityreplace" encode_entity_map = {} is_ucs4 = len("\U0010FFFF") == 1 for k, v in list(entities.items()): # skip multi-character entities if ((is_ucs4 and len(v) > 1) or (not is_ucs4 and len(v) > 2)): continue if v != "&": if len(v) == 2: v = utils.surrogatePairToCodepoint(v) else: v = ord(v) if v not in encode_entity_map or k.islower(): # prefer &lt; over &LT; and similarly for &amp;, &gt;, etc. encode_entity_map[v] = k def htmlentityreplace_errors(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): res = [] codepoints = [] skip = False for i, c in enumerate(exc.object[exc.start:exc.end]): if skip: skip = False continue index = i + exc.start if utils.isSurrogatePair(exc.object[index:min([exc.end, index + 2])]): codepoint = utils.surrogatePairToCodepoint(exc.object[index:index + 2]) skip = True else: codepoint = ord(c) codepoints.append(codepoint) for cp in codepoints: e = encode_entity_map.get(cp) if e: res.append("&") res.append(e) if not e.endswith(";"): res.append(";") else: res.append("&#x%s;" % (hex(cp)[2:])) return ("".join(res), exc.end) else: return xmlcharrefreplace_errors(exc) register_error(unicode_encode_errors, htmlentityreplace_errors) del register_error class HTMLSerializer(object): # attribute quoting options quote_attr_values = "legacy" # be secure by default quote_char = '"' use_best_quote_char = True # tag syntax options omit_optional_tags = True minimize_boolean_attributes = True use_trailing_solidus = False space_before_trailing_solidus = True # escaping options escape_lt_in_attrs = False escape_rcdata = False resolve_entities = True # miscellaneous options alphabetical_attributes = False inject_meta_charset = True strip_whitespace = False sanitize = False options = ("quote_attr_values", "quote_char", "use_best_quote_char", "omit_optional_tags", "minimize_boolean_attributes", "use_trailing_solidus", "space_before_trailing_solidus", "escape_lt_in_attrs", "escape_rcdata", "resolve_entities", "alphabetical_attributes", "inject_meta_charset", "strip_whitespace", "sanitize") def __init__(self, **kwargs): """Initialize HTMLSerializer. Keyword options (default given first unless specified) include: inject_meta_charset=True|False Whether it insert a meta element to define the character set of the document. quote_attr_values="legacy"|"spec"|"always" Whether to quote attribute values that don't require quoting per legacy browser behaviour, when required by the standard, or always. quote_char=u'"'|u"'" Use given quote character for attribute quoting. Default is to use double quote unless attribute value contains a double quote, in which case single quotes are used instead. escape_lt_in_attrs=False|True Whether to escape < in attribute values. escape_rcdata=False|True Whether to escape characters that need to be escaped within normal elements within rcdata elements such as style. resolve_entities=True|False Whether to resolve named character entities that appear in the source tree. The XML predefined entities &lt; &gt; &amp; &quot; &apos; are unaffected by this setting. strip_whitespace=False|True Whether to remove semantically meaningless whitespace. (This compresses all whitespace to a single space except within pre.) minimize_boolean_attributes=True|False Shortens boolean attributes to give just the attribute value, for example <input disabled="disabled"> becomes <input disabled>. use_trailing_solidus=False|True Includes a close-tag slash at the end of the start tag of void elements (empty elements whose end tag is forbidden). E.g. <hr/>. space_before_trailing_solidus=True|False Places a space immediately before the closing slash in a tag using a trailing solidus. E.g. <hr />. Requires use_trailing_solidus. sanitize=False|True Strip all unsafe or unknown constructs from output. See `html5lib user documentation`_ omit_optional_tags=True|False Omit start/end tags that are optional. alphabetical_attributes=False|True Reorder attributes to be in alphabetical order. .. _html5lib user documentation: http://code.google.com/p/html5lib/wiki/UserDocumentation """ if 'quote_char' in kwargs: self.use_best_quote_char = False for attr in self.options: setattr(self, attr, kwargs.get(attr, getattr(self, attr))) self.errors = [] self.strict = False def encode(self, string): assert(isinstance(string, text_type)) if self.encoding: return string.encode(self.encoding, unicode_encode_errors) else: return string def encodeStrict(self, string): assert(isinstance(string, text_type)) if self.encoding: return string.encode(self.encoding, "strict") else: return string def serialize(self, treewalker, encoding=None): self.encoding = encoding in_cdata = False self.errors = [] if encoding and self.inject_meta_charset: from ..filters.inject_meta_charset import Filter treewalker = Filter(treewalker, encoding) # WhitespaceFilter should be used before OptionalTagFilter # for maximum efficiently of this latter filter if self.strip_whitespace: from ..filters.whitespace import Filter treewalker = Filter(treewalker) if self.sanitize: from ..filters.sanitizer import Filter treewalker = Filter(treewalker) if self.omit_optional_tags: from ..filters.optionaltags import Filter treewalker = Filter(treewalker) # Alphabetical attributes must be last, as other filters # could add attributes and alter the order if self.alphabetical_attributes: from ..filters.alphabeticalattributes import Filter treewalker = Filter(treewalker) for token in treewalker: type = token["type"] if type == "Doctype": doctype = "<!DOCTYPE %s" % token["name"] if token["publicId"]: doctype += ' PUBLIC "%s"' % token["publicId"] elif token["systemId"]: doctype += " SYSTEM" if token["systemId"]: if token["systemId"].find('"') >= 0: if token["systemId"].find("'") >= 0: self.serializeError("System identifer contains both single and double quote characters") quote_char = "'" else: quote_char = '"' doctype += " %s%s%s" % (quote_char, token["systemId"], quote_char) doctype += ">" yield self.encodeStrict(doctype) elif type in ("Characters", "SpaceCharacters"): if type == "SpaceCharacters" or in_cdata: if in_cdata and token["data"].find("</") >= 0: self.serializeError("Unexpected </ in CDATA") yield self.encode(token["data"]) else: yield self.encode(escape(token["data"])) elif type in ("StartTag", "EmptyTag"): name = token["name"] yield self.encodeStrict("<%s" % name) if name in rcdataElements and not self.escape_rcdata: in_cdata = True elif in_cdata: self.serializeError("Unexpected child element of a CDATA element") for (attr_namespace, attr_name), attr_value in token["data"].items(): # TODO: Add namespace support here k = attr_name v = attr_value yield self.encodeStrict(' ') yield self.encodeStrict(k) if not self.minimize_boolean_attributes or \ (k not in booleanAttributes.get(name, tuple()) and k not in booleanAttributes.get("", tuple())): yield self.encodeStrict("=") if self.quote_attr_values == "always" or len(v) == 0: quote_attr = True elif self.quote_attr_values == "spec": quote_attr = quoteAttributeSpec.search(v) is not None elif self.quote_attr_values == "legacy": quote_attr = quoteAttributeLegacy.search(v) is not None else: raise ValueError("quote_attr_values must be one of: " "'always', 'spec', or 'legacy'") v = v.replace("&", "&amp;") if self.escape_lt_in_attrs: v = v.replace("<", "&lt;") if quote_attr: quote_char = self.quote_char if self.use_best_quote_char: if "'" in v and '"' not in v: quote_char = '"' elif '"' in v and "'" not in v: quote_char = "'" if quote_char == "'": v = v.replace("'", "&#39;") else: v = v.replace('"', "&quot;") yield self.encodeStrict(quote_char) yield self.encode(v) yield self.encodeStrict(quote_char) else: yield self.encode(v) if name in voidElements and self.use_trailing_solidus: if self.space_before_trailing_solidus: yield self.encodeStrict(" /") else: yield self.encodeStrict("/") yield self.encode(">") elif type == "EndTag": name = token["name"] if name in rcdataElements: in_cdata = False elif in_cdata: self.serializeError("Unexpected child element of a CDATA element") yield self.encodeStrict("</%s>" % name) elif type == "Comment": data = token["data"] if data.find("--") >= 0: self.serializeError("Comment contains --") yield self.encodeStrict("<!--%s-->" % token["data"]) elif type == "Entity": name = token["name"] key = name + ";" if key not in entities: self.serializeError("Entity %s not recognized" % name) if self.resolve_entities and key not in xmlEntities: data = entities[key] else: data = "&%s;" % name yield self.encodeStrict(data) else: self.serializeError(token["data"]) def render(self, treewalker, encoding=None): if encoding: return b"".join(list(self.serialize(treewalker, encoding))) else: return "".join(list(self.serialize(treewalker))) def serializeError(self, data="XXX ERROR MESSAGE NEEDED"): # XXX The idea is to make data mandatory. self.errors.append(data) if self.strict: raise SerializeError def SerializeError(Exception): """Error in serialized tree""" pass
xss
{ "code": [ "quoteAttributeSpec = re.compile(\"[\" + spaceCharacters + \"\\\"'=<>`]\")", " quote_attr_values = False", " per HTML5 parsing rules.", " if self.quote_attr_values:", " quote_attr = len(v) == 0 or quoteAttributeSpec.search(v)" ], "line_no": [ 13, 75, 113, 242, 245 ] }
{ "code": [ "quoteAttributeSpecChars = spaceCharacters + \"\\\"'=<>`\"", "quoteAttributeLegacy = re.compile(\"[\" + quoteAttributeSpecChars +", " \"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\"", " \"\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\"", " \"\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\"", " \"\\x20\\x2f\\x60\\xa0\\u1680\\u180e\\u180f\\u2000\"", " \"\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\"", " \"\\u3000]\")", " per legacy browser behaviour, when required by the standard, or always.", " if self.quote_attr_values == \"always\" or len(v) == 0:", " elif self.quote_attr_values == \"spec\":", " quote_attr = quoteAttributeSpec.search(v) is not None", " elif self.quote_attr_values == \"legacy\":", " quote_attr = quoteAttributeLegacy.search(v) is not None", " raise ValueError(\"quote_attr_values must be one of: \"", " \"'always', 'spec', or 'legacy'\")" ], "line_no": [ 13, 15, 16, 17, 18, 19, 20, 22, 122, 251, 253, 254, 255, 256, 258, 259 ] }
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from ..constants import .voidElements, booleanAttributes, VAR_0 from ..constants import rcdataElements, entities, xmlEntities from .. import utils from xml.sax.saxutils import .escape VAR_0 = "".join(VAR_0) VAR_1 = re.compile("[" + VAR_0 + "\"'=<>`]") try: from codecs import register_error, xmlcharrefreplace_errors except ImportError: VAR_3 = "strict" else: VAR_3 = "htmlentityreplace" VAR_4 = {} VAR_5 = len("\U0010FFFF") == 1 for VAR_38, VAR_32 in list(entities.items()): if ((VAR_5 and len(VAR_32) > 1) or (not VAR_5 and len(VAR_32) > 2)): continue if VAR_32 != "&": if len(VAR_32) == 2: VAR_32 = utils.surrogatePairToCodepoint(VAR_32) else: VAR_32 = ord(VAR_32) if VAR_32 not in VAR_4 or VAR_38.islower(): VAR_4[VAR_32] = VAR_38 def FUNC_1(VAR_6): if isinstance(VAR_6, (UnicodeEncodeError, UnicodeTranslateError)): VAR_28 = [] VAR_29 = [] VAR_30 = False for i, c in enumerate(VAR_6.object[VAR_6.start:VAR_6.end]): if VAR_30: skip = False continue VAR_33 = i + VAR_6.start if utils.isSurrogatePair(VAR_6.object[VAR_33:min([VAR_6.end, VAR_33 + 2])]): VAR_36 = utils.surrogatePairToCodepoint(VAR_6.object[VAR_33:index + 2]) VAR_30 = True else: VAR_36 = ord(c) VAR_29.append(VAR_36) for cp in VAR_29: VAR_34 = VAR_4.get(cp) if VAR_34: VAR_28.append("&") VAR_28.append(VAR_34) if not VAR_34.endswith(";"): VAR_28.append(";") else: VAR_28.append("&#x%s;" % (hex(cp)[2:])) return ("".join(VAR_28), VAR_6.end) else: return xmlcharrefreplace_errors(VAR_6) register_error(VAR_3, FUNC_1) del register_error class CLASS_0(object): VAR_7 = False VAR_8 = '"' VAR_9 = True VAR_10 = True VAR_11 = True VAR_12 = False VAR_13 = True VAR_14 = False VAR_15 = False VAR_16 = True VAR_17 = False VAR_18 = True VAR_19 = False VAR_20 = False VAR_21 = ("quote_attr_values", "quote_char", "use_best_quote_char", "omit_optional_tags", "minimize_boolean_attributes", "use_trailing_solidus", "space_before_trailing_solidus", "escape_lt_in_attrs", "escape_rcdata", "resolve_entities", "alphabetical_attributes", "inject_meta_charset", "strip_whitespace", "sanitize") def __init__(self, **VAR_22): if 'quote_char' in VAR_22: self.use_best_quote_char = False for attr in self.options: setattr(self, attr, VAR_22.get(attr, getattr(self, attr))) self.errors = [] self.strict = False def FUNC_2(self, VAR_23): assert(isinstance(VAR_23, text_type)) if self.encoding: return VAR_23.encode(self.encoding, VAR_3) else: return VAR_23 def FUNC_3(self, VAR_23): assert(isinstance(VAR_23, text_type)) if self.encoding: return VAR_23.encode(self.encoding, "strict") else: return VAR_23 def FUNC_4(self, VAR_24, VAR_25=None): self.encoding = VAR_25 VAR_27 = False self.errors = [] if VAR_25 and self.inject_meta_charset: from ..filters.inject_meta_charset import Filter VAR_24 = Filter(VAR_24, VAR_25) if self.strip_whitespace: from ..filters.whitespace import Filter VAR_24 = Filter(VAR_24) if self.sanitize: from ..filters.sanitizer import Filter VAR_24 = Filter(VAR_24) if self.omit_optional_tags: from ..filters.optionaltags import Filter VAR_24 = Filter(VAR_24) if self.alphabetical_attributes: from ..filters.alphabeticalattributes import Filter VAR_24 = Filter(VAR_24) for token in VAR_24: VAR_31 = token["type"] if VAR_31 == "Doctype": VAR_35 = "<!DOCTYPE %s" % token["name"] if token["publicId"]: VAR_35 += ' PUBLIC "%s"' % token["publicId"] elif token["systemId"]: VAR_35 += " SYSTEM" if token["systemId"]: if token["systemId"].find('"') >= 0: if token["systemId"].find("'") >= 0: self.serializeError("System identifer contains both single and double quote characters") VAR_8 = "'" else: VAR_8 = '"' VAR_35 += " %s%s%s" % (VAR_8, token["systemId"], VAR_8) VAR_35 += ">" yield self.encodeStrict(VAR_35) elif VAR_31 in ("Characters", "SpaceCharacters"): if VAR_31 == "SpaceCharacters" or VAR_27: if VAR_27 and token["data"].find("</") >= 0: self.serializeError("Unexpected </ in CDATA") yield self.encode(token["data"]) else: yield self.encode(escape(token["data"])) elif VAR_31 in ("StartTag", "EmptyTag"): VAR_37 = token["name"] yield self.encodeStrict("<%s" % VAR_37) if VAR_37 in rcdataElements and not self.escape_rcdata: VAR_27 = True elif VAR_27: self.serializeError("Unexpected child element of a CDATA element") for (attr_namespace, attr_name), attr_value in token["data"].items(): VAR_38 = attr_name VAR_32 = attr_value yield self.encodeStrict(' ') yield self.encodeStrict(VAR_38) if not self.minimize_boolean_attributes or \ (VAR_38 not in booleanAttributes.get(VAR_37, tuple()) and VAR_38 not in booleanAttributes.get("", tuple())): yield self.encodeStrict("=") if self.quote_attr_values: VAR_39 = True else: VAR_39 = len(VAR_32) == 0 or VAR_1.search(VAR_32) VAR_32 = VAR_32.replace("&", "&amp;") if self.escape_lt_in_attrs: VAR_32 = VAR_32.replace("<", "&lt;") if VAR_39: VAR_8 = self.quote_char if self.use_best_quote_char: if "'" in VAR_32 and '"' not in VAR_32: VAR_8 = '"' elif '"' in VAR_32 and "'" not in VAR_32: VAR_8 = "'" if VAR_8 == "'": VAR_32 = VAR_32.replace("'", "&#39;") else: VAR_32 = VAR_32.replace('"', "&quot;") yield self.encodeStrict(VAR_8) yield self.encode(VAR_32) yield self.encodeStrict(VAR_8) else: yield self.encode(VAR_32) if VAR_37 in voidElements and self.use_trailing_solidus: if self.space_before_trailing_solidus: yield self.encodeStrict(" /") else: yield self.encodeStrict("/") yield self.encode(">") elif VAR_31 == "EndTag": VAR_37 = token["name"] if VAR_37 in rcdataElements: VAR_27 = False elif VAR_27: self.serializeError("Unexpected child element of a CDATA element") yield self.encodeStrict("</%s>" % VAR_37) elif VAR_31 == "Comment": VAR_26 = token["data"] if VAR_26.find("--") >= 0: self.serializeError("Comment contains --") yield self.encodeStrict("<!--%s-->" % token["data"]) elif VAR_31 == "Entity": VAR_37 = token["name"] VAR_40 = VAR_37 + ";" if VAR_40 not in entities: self.serializeError("Entity %s not recognized" % VAR_37) if self.resolve_entities and VAR_40 not in xmlEntities: VAR_26 = entities[VAR_40] else: VAR_26 = "&%s;" % VAR_37 yield self.encodeStrict(VAR_26) else: self.serializeError(token["data"]) def FUNC_5(self, VAR_24, VAR_25=None): if VAR_25: return b"".join(list(self.serialize(VAR_24, VAR_25))) else: return "".join(list(self.serialize(VAR_24))) def FUNC_6(self, VAR_26="XXX ERROR MESSAGE NEEDED"): self.errors.append(VAR_26) if self.strict: raise FUNC_0 def FUNC_0(VAR_2): pass
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from ..constants import .voidElements, booleanAttributes, VAR_0 from ..constants import rcdataElements, entities, xmlEntities from .. import utils from xml.sax.saxutils import .escape VAR_0 = "".join(VAR_0) VAR_1 = VAR_0 + "\"'=<>`" VAR_2 = re.compile("[" + VAR_1 + "]") VAR_3 = re.compile("[" + VAR_1 + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n" "\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15" "\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" "\x20\x2f\x60\xa0\u1680\u180e\u180f\u2000" "\u2001\u2002\u2003\u2004\u2005\u2006\u2007" "\u2008\u2009\u200a\u2028\u2029\u202f\u205f" "\u3000]") try: from codecs import register_error, xmlcharrefreplace_errors except ImportError: VAR_5 = "strict" else: VAR_5 = "htmlentityreplace" VAR_6 = {} VAR_7 = len("\U0010FFFF") == 1 for VAR_40, VAR_34 in list(entities.items()): if ((VAR_7 and len(VAR_34) > 1) or (not VAR_7 and len(VAR_34) > 2)): continue if VAR_34 != "&": if len(VAR_34) == 2: VAR_34 = utils.surrogatePairToCodepoint(VAR_34) else: VAR_34 = ord(VAR_34) if VAR_34 not in VAR_6 or VAR_40.islower(): VAR_6[VAR_34] = VAR_40 def FUNC_1(VAR_8): if isinstance(VAR_8, (UnicodeEncodeError, UnicodeTranslateError)): VAR_30 = [] VAR_31 = [] VAR_32 = False for i, c in enumerate(VAR_8.object[VAR_8.start:VAR_8.end]): if VAR_32: skip = False continue VAR_35 = i + VAR_8.start if utils.isSurrogatePair(VAR_8.object[VAR_35:min([VAR_8.end, VAR_35 + 2])]): VAR_38 = utils.surrogatePairToCodepoint(VAR_8.object[VAR_35:index + 2]) VAR_32 = True else: VAR_38 = ord(c) VAR_31.append(VAR_38) for cp in VAR_31: VAR_36 = VAR_6.get(cp) if VAR_36: VAR_30.append("&") VAR_30.append(VAR_36) if not VAR_36.endswith(";"): VAR_30.append(";") else: VAR_30.append("&#x%s;" % (hex(cp)[2:])) return ("".join(VAR_30), VAR_8.end) else: return xmlcharrefreplace_errors(VAR_8) register_error(VAR_5, FUNC_1) del register_error class CLASS_0(object): VAR_9 = "legacy" # be secure by default VAR_10 = '"' VAR_11 = True VAR_12 = True VAR_13 = True VAR_14 = False VAR_15 = True VAR_16 = False VAR_17 = False VAR_18 = True VAR_19 = False VAR_20 = True VAR_21 = False VAR_22 = False VAR_23 = ("quote_attr_values", "quote_char", "use_best_quote_char", "omit_optional_tags", "minimize_boolean_attributes", "use_trailing_solidus", "space_before_trailing_solidus", "escape_lt_in_attrs", "escape_rcdata", "resolve_entities", "alphabetical_attributes", "inject_meta_charset", "strip_whitespace", "sanitize") def __init__(self, **VAR_24): if 'quote_char' in VAR_24: self.use_best_quote_char = False for attr in self.options: setattr(self, attr, VAR_24.get(attr, getattr(self, attr))) self.errors = [] self.strict = False def FUNC_2(self, VAR_25): assert(isinstance(VAR_25, text_type)) if self.encoding: return VAR_25.encode(self.encoding, VAR_5) else: return VAR_25 def FUNC_3(self, VAR_25): assert(isinstance(VAR_25, text_type)) if self.encoding: return VAR_25.encode(self.encoding, "strict") else: return VAR_25 def FUNC_4(self, VAR_26, VAR_27=None): self.encoding = VAR_27 VAR_29 = False self.errors = [] if VAR_27 and self.inject_meta_charset: from ..filters.inject_meta_charset import Filter VAR_26 = Filter(VAR_26, VAR_27) if self.strip_whitespace: from ..filters.whitespace import Filter VAR_26 = Filter(VAR_26) if self.sanitize: from ..filters.sanitizer import Filter VAR_26 = Filter(VAR_26) if self.omit_optional_tags: from ..filters.optionaltags import Filter VAR_26 = Filter(VAR_26) if self.alphabetical_attributes: from ..filters.alphabeticalattributes import Filter VAR_26 = Filter(VAR_26) for token in VAR_26: VAR_33 = token["type"] if VAR_33 == "Doctype": VAR_37 = "<!DOCTYPE %s" % token["name"] if token["publicId"]: VAR_37 += ' PUBLIC "%s"' % token["publicId"] elif token["systemId"]: VAR_37 += " SYSTEM" if token["systemId"]: if token["systemId"].find('"') >= 0: if token["systemId"].find("'") >= 0: self.serializeError("System identifer contains both single and double quote characters") VAR_10 = "'" else: VAR_10 = '"' VAR_37 += " %s%s%s" % (VAR_10, token["systemId"], VAR_10) VAR_37 += ">" yield self.encodeStrict(VAR_37) elif VAR_33 in ("Characters", "SpaceCharacters"): if VAR_33 == "SpaceCharacters" or VAR_29: if VAR_29 and token["data"].find("</") >= 0: self.serializeError("Unexpected </ in CDATA") yield self.encode(token["data"]) else: yield self.encode(escape(token["data"])) elif VAR_33 in ("StartTag", "EmptyTag"): VAR_39 = token["name"] yield self.encodeStrict("<%s" % VAR_39) if VAR_39 in rcdataElements and not self.escape_rcdata: VAR_29 = True elif VAR_29: self.serializeError("Unexpected child element of a CDATA element") for (attr_namespace, attr_name), attr_value in token["data"].items(): VAR_40 = attr_name VAR_34 = attr_value yield self.encodeStrict(' ') yield self.encodeStrict(VAR_40) if not self.minimize_boolean_attributes or \ (VAR_40 not in booleanAttributes.get(VAR_39, tuple()) and VAR_40 not in booleanAttributes.get("", tuple())): yield self.encodeStrict("=") if self.quote_attr_values == "always" or len(VAR_34) == 0: VAR_41 = True elif self.quote_attr_values == "spec": VAR_41 = VAR_2.search(VAR_34) is not None elif self.quote_attr_values == "legacy": VAR_41 = VAR_3.search(VAR_34) is not None else: raise ValueError("quote_attr_values must be one of: " "'always', 'spec', or 'legacy'") VAR_34 = v.replace("&", "&amp;") if self.escape_lt_in_attrs: VAR_34 = v.replace("<", "&lt;") if VAR_41: VAR_10 = self.quote_char if self.use_best_quote_char: if "'" in VAR_34 and '"' not in VAR_34: VAR_10 = '"' elif '"' in VAR_34 and "'" not in VAR_34: VAR_10 = "'" if VAR_10 == "'": VAR_34 = v.replace("'", "&#39;") else: VAR_34 = v.replace('"', "&quot;") yield self.encodeStrict(VAR_10) yield self.encode(VAR_34) yield self.encodeStrict(VAR_10) else: yield self.encode(VAR_34) if VAR_39 in voidElements and self.use_trailing_solidus: if self.space_before_trailing_solidus: yield self.encodeStrict(" /") else: yield self.encodeStrict("/") yield self.encode(">") elif VAR_33 == "EndTag": VAR_39 = token["name"] if VAR_39 in rcdataElements: VAR_29 = False elif VAR_29: self.serializeError("Unexpected child element of a CDATA element") yield self.encodeStrict("</%s>" % VAR_39) elif VAR_33 == "Comment": VAR_28 = token["data"] if VAR_28.find("--") >= 0: self.serializeError("Comment contains --") yield self.encodeStrict("<!--%s-->" % token["data"]) elif VAR_33 == "Entity": VAR_39 = token["name"] VAR_42 = VAR_39 + ";" if VAR_42 not in entities: self.serializeError("Entity %s not recognized" % VAR_39) if self.resolve_entities and VAR_42 not in xmlEntities: VAR_28 = entities[VAR_42] else: VAR_28 = "&%s;" % VAR_39 yield self.encodeStrict(VAR_28) else: self.serializeError(token["data"]) def FUNC_5(self, VAR_26, VAR_27=None): if VAR_27: return b"".join(list(self.serialize(VAR_26, VAR_27))) else: return "".join(list(self.serialize(VAR_26))) def FUNC_6(self, VAR_28="XXX ERROR MESSAGE NEEDED"): self.errors.append(VAR_28) if self.strict: raise FUNC_0 def FUNC_0(VAR_4): pass
[ 3, 5, 10, 12, 14, 21, 25, 35, 37, 66, 68, 70, 71, 73, 74, 78, 79, 84, 85, 89, 90, 95, 102, 105, 107, 146, 155, 162, 169, 174, 178, 179, 189, 190, 194, 199, 212, 215, 223, 232, 236, 271, 279, 285, 296, 299, 305, 307, 311, 312, 316, 314, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148 ]
[ 3, 5, 10, 12, 23, 30, 34, 44, 46, 75, 77, 79, 80, 82, 83, 87, 88, 93, 94, 98, 99, 104, 111, 114, 116, 155, 164, 171, 178, 183, 187, 188, 198, 199, 203, 208, 221, 224, 232, 241, 245, 285, 293, 299, 310, 313, 319, 321, 325, 326, 330, 328, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157 ]
0CWE-22
import copy import glob import hashlib import logging import os import shutil from subprocess import CalledProcessError, DEVNULL, check_output # skipcq:BAN-B404 import tempfile import typing from pathlib import Path from typing import Any, Text, Tuple, Union, Optional, List, Dict, NamedTuple from packaging import version from rasa.constants import MINIMUM_COMPATIBLE_VERSION import rasa.shared.utils.io import rasa.utils.io from rasa.cli.utils import create_output_path from rasa.shared.utils.cli import print_success from rasa.shared.constants import ( CONFIG_KEYS_CORE, CONFIG_KEYS_NLU, CONFIG_KEYS, DEFAULT_DOMAIN_PATH, DEFAULT_MODELS_PATH, DEFAULT_CORE_SUBDIRECTORY_NAME, DEFAULT_NLU_SUBDIRECTORY_NAME, ) from rasa.exceptions import ModelNotFound from rasa.utils.common import TempDirectoryPath if typing.TYPE_CHECKING: from rasa.shared.importers.importer import TrainingDataImporter logger = logging.getLogger(__name__) # Type alias for the fingerprint Fingerprint = Dict[Text, Union[Optional[Text], List[Text], int, float]] FINGERPRINT_FILE_PATH = "fingerprint.json" FINGERPRINT_CONFIG_KEY = "config" FINGERPRINT_CONFIG_CORE_KEY = "core-config" FINGERPRINT_CONFIG_NLU_KEY = "nlu-config" FINGERPRINT_CONFIG_WITHOUT_EPOCHS_KEY = "config-without-epochs" FINGERPRINT_DOMAIN_WITHOUT_NLG_KEY = "domain" FINGERPRINT_NLG_KEY = "nlg" FINGERPRINT_RASA_VERSION_KEY = "version" FINGERPRINT_STORIES_KEY = "stories" FINGERPRINT_NLU_DATA_KEY = "messages" FINGERPRINT_NLU_LABELS_KEY = "nlu_labels" FINGERPRINT_PROJECT = "project" FINGERPRINT_TRAINED_AT_KEY = "trained_at" class Section(NamedTuple): """Specifies which fingerprint keys decide whether this sub-model is retrained.""" name: Text relevant_keys: List[Text] SECTION_CORE = Section( name="Core model", relevant_keys=[ FINGERPRINT_CONFIG_KEY, FINGERPRINT_CONFIG_CORE_KEY, FINGERPRINT_DOMAIN_WITHOUT_NLG_KEY, FINGERPRINT_STORIES_KEY, FINGERPRINT_RASA_VERSION_KEY, ], ) SECTION_NLU = Section( name="NLU model", relevant_keys=[ FINGERPRINT_CONFIG_KEY, FINGERPRINT_CONFIG_NLU_KEY, FINGERPRINT_NLU_DATA_KEY, FINGERPRINT_RASA_VERSION_KEY, ], ) SECTION_NLG = Section(name="NLG responses", relevant_keys=[FINGERPRINT_NLG_KEY]) class FingerprintComparisonResult: """Container for the results of a fingerprint comparison.""" def __init__( self, nlu: bool = True, core: bool = True, nlg: bool = True, force_training: bool = False, ): """Creates a `FingerprintComparisonResult` instance. Args: nlu: `True` if the NLU model should be retrained. core: `True` if the Core model should be retrained. nlg: `True` if the responses in the domain should be updated. force_training: `True` if a training of all parts is forced. """ self.nlu = nlu self.core = core self.nlg = nlg self.force_training = force_training def is_training_required(self) -> bool: """Check if anything has to be retrained.""" return any([self.nlg, self.nlu, self.core, self.force_training]) def should_retrain_core(self) -> bool: """Check if the Core model has to be updated.""" return self.force_training or self.core def should_retrain_nlg(self) -> bool: """Check if the responses have to be updated.""" return self.should_retrain_core() or self.nlg def should_retrain_nlu(self) -> bool: """Check if the NLU model has to be updated.""" return self.force_training or self.nlu def get_local_model(model_path: Text = DEFAULT_MODELS_PATH) -> Text: """Returns verified path to local model archive. Args: model_path: Path to the zipped model. If it's a directory, the latest trained model is returned. Returns: Path to the zipped model. If it's a directory, the latest trained model is returned. Raises: ModelNotFound Exception: When no model could be found at the provided path. """ if not model_path: raise ModelNotFound("No path specified.") elif not os.path.exists(model_path): raise ModelNotFound(f"No file or directory at '{model_path}'.") if os.path.isdir(model_path): model_path = get_latest_model(model_path) if not model_path: raise ModelNotFound( f"Could not find any Rasa model files in '{model_path}'." ) elif not model_path.endswith(".tar.gz"): raise ModelNotFound(f"Path '{model_path}' does not point to a Rasa model file.") return model_path def get_model(model_path: Text = DEFAULT_MODELS_PATH) -> TempDirectoryPath: """Gets a model and unpacks it. Args: model_path: Path to the zipped model. If it's a directory, the latest trained model is returned. Returns: Path to the unpacked model. Raises: ModelNotFound Exception: When no model could be found at the provided path. """ model_path = get_local_model(model_path) try: model_relative_path = os.path.relpath(model_path) except ValueError: model_relative_path = model_path logger.info(f"Loading model {model_relative_path}...") return unpack_model(model_path) def get_latest_model(model_path: Text = DEFAULT_MODELS_PATH) -> Optional[Text]: """Get the latest model from a path. Args: model_path: Path to a directory containing zipped models. Returns: Path to latest model in the given directory. """ if not os.path.exists(model_path) or os.path.isfile(model_path): model_path = os.path.dirname(model_path) list_of_files = glob.glob(os.path.join(model_path, "*.tar.gz")) if len(list_of_files) == 0: return None return max(list_of_files, key=os.path.getctime) def unpack_model( model_file: Text, working_directory: Optional[Union[Path, Text]] = None ) -> TempDirectoryPath: """Unpack a zipped Rasa model. Args: model_file: Path to zipped model. working_directory: Location where the model should be unpacked to. If `None` a temporary directory will be created. Returns: Path to unpacked Rasa model. """ import tarfile if working_directory is None: working_directory = tempfile.mkdtemp() # All files are in a subdirectory. try: with tarfile.open(model_file, mode="r:gz") as tar: tar.extractall(working_directory) logger.debug(f"Extracted model to '{working_directory}'.") except (tarfile.TarError, ValueError) as e: logger.error(f"Failed to extract model at {model_file}. Error: {e}") raise return TempDirectoryPath(working_directory) def get_model_subdirectories( unpacked_model_path: Text, ) -> Tuple[Optional[Text], Optional[Text]]: """Return paths for Core and NLU model directories, if they exist. If neither directories exist, a `ModelNotFound` exception is raised. Args: unpacked_model_path: Path to unpacked Rasa model. Returns: Tuple (path to Core subdirectory if it exists or `None` otherwise, path to NLU subdirectory if it exists or `None` otherwise). """ core_path = os.path.join(unpacked_model_path, DEFAULT_CORE_SUBDIRECTORY_NAME) nlu_path = os.path.join(unpacked_model_path, DEFAULT_NLU_SUBDIRECTORY_NAME) if not os.path.isdir(core_path): core_path = None if not os.path.isdir(nlu_path): nlu_path = None if not core_path and not nlu_path: raise ModelNotFound( "No NLU or Core data for unpacked model at: '{}'.".format( unpacked_model_path ) ) return core_path, nlu_path def create_package_rasa( training_directory: Text, output_filename: Text, fingerprint: Optional[Fingerprint] = None, ) -> Text: """Create a zipped Rasa model from trained model files. Args: training_directory: Path to the directory which contains the trained model files. output_filename: Name of the zipped model file to be created. fingerprint: A unique fingerprint to identify the model version. Returns: Path to zipped model. """ import tarfile if fingerprint: persist_fingerprint(training_directory, fingerprint) output_directory = os.path.dirname(output_filename) if not os.path.exists(output_directory): os.makedirs(output_directory) with tarfile.open(output_filename, "w:gz") as tar: for elem in os.scandir(training_directory): tar.add(elem.path, arcname=elem.name) shutil.rmtree(training_directory) return output_filename def project_fingerprint() -> Optional[Text]: """Create a hash for the project in the current working directory. Returns: project hash """ try: remote = check_output( # skipcq:BAN-B607,BAN-B603 ["git", "remote", "get-url", "origin"], stderr=DEVNULL ) return hashlib.sha256(remote).hexdigest() except (CalledProcessError, OSError): return None async def model_fingerprint(file_importer: "TrainingDataImporter") -> Fingerprint: """Create a model fingerprint from its used configuration and training data. Args: file_importer: File importer which provides the training data and model config. Returns: The fingerprint. """ import time config = await file_importer.get_config() domain = await file_importer.get_domain() stories = await file_importer.get_stories() nlu_data = await file_importer.get_nlu_data() responses = domain.responses # Do a copy of the domain to not change the actual domain (shallow is enough) domain = copy.copy(domain) # don't include the response texts in the fingerprint. # Their fingerprint is separate. domain.responses = {} return { FINGERPRINT_CONFIG_KEY: _get_fingerprint_of_config( config, exclude_keys=CONFIG_KEYS ), FINGERPRINT_CONFIG_CORE_KEY: _get_fingerprint_of_config( config, include_keys=CONFIG_KEYS_CORE ), FINGERPRINT_CONFIG_NLU_KEY: _get_fingerprint_of_config( config, include_keys=CONFIG_KEYS_NLU ), FINGERPRINT_CONFIG_WITHOUT_EPOCHS_KEY: ( _get_fingerprint_of_config_without_epochs(config) ), FINGERPRINT_DOMAIN_WITHOUT_NLG_KEY: domain.fingerprint(), FINGERPRINT_NLG_KEY: rasa.shared.utils.io.deep_container_fingerprint(responses), FINGERPRINT_PROJECT: project_fingerprint(), FINGERPRINT_NLU_DATA_KEY: nlu_data.fingerprint(), FINGERPRINT_NLU_LABELS_KEY: nlu_data.label_fingerprint(), FINGERPRINT_STORIES_KEY: stories.fingerprint(), FINGERPRINT_TRAINED_AT_KEY: time.time(), FINGERPRINT_RASA_VERSION_KEY: rasa.__version__, } def _get_fingerprint_of_config( config: Optional[Dict[Text, Any]], include_keys: Optional[List[Text]] = None, exclude_keys: Optional[List[Text]] = None, ) -> Text: if not config: return "" keys = include_keys or list(filter(lambda k: k not in exclude_keys, config.keys())) sub_config = {k: config[k] for k in keys if k in config} return rasa.shared.utils.io.deep_container_fingerprint(sub_config) def _get_fingerprint_of_config_without_epochs( config: Optional[Dict[Text, Any]], ) -> Text: if not config: return "" copied_config = copy.deepcopy(config) for key in ["pipeline", "policies"]: if copied_config.get(key): for p in copied_config[key]: if "epochs" in p: del p["epochs"] return rasa.shared.utils.io.deep_container_fingerprint(copied_config) def fingerprint_from_path(model_path: Text) -> Fingerprint: """Load a persisted fingerprint. Args: model_path: Path to directory containing the fingerprint. Returns: The fingerprint or an empty dict if no fingerprint was found. """ if not model_path or not os.path.exists(model_path): return {} fingerprint_path = os.path.join(model_path, FINGERPRINT_FILE_PATH) if os.path.isfile(fingerprint_path): return rasa.shared.utils.io.read_json_file(fingerprint_path) else: return {} def persist_fingerprint(output_path: Text, fingerprint: Fingerprint) -> None: """Persist a model fingerprint. Args: output_path: Directory in which the fingerprint should be saved. fingerprint: The fingerprint to be persisted. """ path = os.path.join(output_path, FINGERPRINT_FILE_PATH) rasa.shared.utils.io.dump_obj_as_json_to_file(path, fingerprint) def did_section_fingerprint_change( fingerprint1: Fingerprint, fingerprint2: Fingerprint, section: Section ) -> bool: """Check whether the fingerprint of a section has changed.""" for k in section.relevant_keys: if fingerprint1.get(k) != fingerprint2.get(k): logger.info(f"Data ({k}) for {section.name} section changed.") return True return False def move_model(source: Text, target: Text) -> bool: """Move two model directories. Args: source: The original folder which should be merged in another. target: The destination folder where it should be moved to. Returns: `True` if the merge was successful, else `False`. """ try: shutil.move(source, target) return True except Exception as e: logging.debug(f"Could not merge model: {e}") return False def should_retrain( new_fingerprint: Fingerprint, old_model: Optional[Text], train_path: Text, has_e2e_examples: bool = False, force_training: bool = False, ) -> FingerprintComparisonResult: """Check which components of a model should be retrained. Args: new_fingerprint: The fingerprint of the new model to be trained. old_model: Path to the old zipped model file. train_path: Path to the directory in which the new model will be trained. has_e2e_examples: Whether the new training data contains e2e examples. force_training: Indicates if the model needs to be retrained even if the data has not changed. Returns: A FingerprintComparisonResult object indicating whether Rasa Core and/or Rasa NLU needs to be retrained or not. """ fingerprint_comparison = FingerprintComparisonResult() if old_model is None or not os.path.exists(old_model): return fingerprint_comparison try: with unpack_model(old_model) as unpacked: last_fingerprint = fingerprint_from_path(unpacked) old_core, old_nlu = get_model_subdirectories(unpacked) fingerprint_comparison = FingerprintComparisonResult( core=did_section_fingerprint_change( last_fingerprint, new_fingerprint, SECTION_CORE ), nlu=did_section_fingerprint_change( last_fingerprint, new_fingerprint, SECTION_NLU ), nlg=did_section_fingerprint_change( last_fingerprint, new_fingerprint, SECTION_NLG ), force_training=force_training, ) # We should retrain core if nlu data changes and there are e2e stories. if has_e2e_examples and fingerprint_comparison.should_retrain_nlu(): fingerprint_comparison.core = True core_merge_failed = False if not fingerprint_comparison.should_retrain_core(): target_path = os.path.join(train_path, DEFAULT_CORE_SUBDIRECTORY_NAME) core_merge_failed = not move_model(old_core, target_path) fingerprint_comparison.core = core_merge_failed if not fingerprint_comparison.should_retrain_nlg() and core_merge_failed: # If moving the Core model failed, we should also retrain NLG fingerprint_comparison.nlg = True if not fingerprint_comparison.should_retrain_nlu(): target_path = os.path.join(train_path, "nlu") fingerprint_comparison.nlu = not move_model(old_nlu, target_path) return fingerprint_comparison except Exception as e: logger.error( f"Failed to get the fingerprint. Error: {e}.\n" f"Proceeding with running default retrain..." ) return fingerprint_comparison def can_finetune( last_fingerprint: Fingerprint, new_fingerprint: Fingerprint, core: bool = False, nlu: bool = False, ) -> bool: """Checks if components of a model can be finetuned with incremental training. Args: last_fingerprint: The fingerprint of the old model to potentially be fine-tuned. new_fingerprint: The fingerprint of the new model. core: Check sections for finetuning a core model. nlu: Check sections for finetuning an nlu model. Returns: `True` if the old model can be finetuned, `False` otherwise. """ section_keys = [ FINGERPRINT_CONFIG_WITHOUT_EPOCHS_KEY, ] if core: section_keys.append(FINGERPRINT_DOMAIN_WITHOUT_NLG_KEY) if nlu: section_keys.append(FINGERPRINT_NLU_LABELS_KEY) fingerprint_changed = did_section_fingerprint_change( last_fingerprint, new_fingerprint, Section(name="finetune", relevant_keys=section_keys), ) old_model_above_min_version = version.parse( last_fingerprint.get(FINGERPRINT_RASA_VERSION_KEY) ) >= version.parse(MINIMUM_COMPATIBLE_VERSION) return old_model_above_min_version and not fingerprint_changed def package_model( fingerprint: Fingerprint, output_directory: Text, train_path: Text, fixed_model_name: Optional[Text] = None, model_prefix: Text = "", ) -> Text: """ Compress a trained model. Args: fingerprint: fingerprint of the model output_directory: path to the directory in which the model should be stored train_path: path to uncompressed model fixed_model_name: name of the compressed model file model_prefix: prefix of the compressed model file Returns: path to 'tar.gz' model file """ output_directory = create_output_path( output_directory, prefix=model_prefix, fixed_name=fixed_model_name ) create_package_rasa(train_path, output_directory, fingerprint) print_success( "Your Rasa model is trained and saved at '{}'.".format( os.path.abspath(output_directory) ) ) return output_directory async def update_model_with_new_domain( importer: "TrainingDataImporter", unpacked_model_path: Union[Path, Text] ) -> None: """Overwrites the domain of an unpacked model with a new domain. Args: importer: Importer which provides the new domain. unpacked_model_path: Path to the unpacked model. """ model_path = Path(unpacked_model_path) / DEFAULT_CORE_SUBDIRECTORY_NAME domain = await importer.get_domain() domain.persist(model_path / DEFAULT_DOMAIN_PATH) def get_model_for_finetuning( previous_model_file: Optional[Union[Path, Text]] ) -> Optional[Text]: """Gets validated path for model to finetune. Args: previous_model_file: Path to model file which should be used for finetuning or a directory in case the latest trained model should be used. Returns: Path to model archive. `None` if there is no model. """ if Path(previous_model_file).is_dir(): logger.debug( f"Trying to load latest model from '{previous_model_file}' for " f"finetuning." ) return get_latest_model(previous_model_file) if Path(previous_model_file).is_file(): return previous_model_file logger.debug( "No valid model for finetuning found as directory either " "contains no model or model file cannot be found." ) return None
import copy import glob import hashlib import logging import os import shutil from subprocess import CalledProcessError, DEVNULL, check_output # skipcq:BAN-B404 import tempfile import typing from pathlib import Path from typing import Any, Text, Tuple, Union, Optional, List, Dict, NamedTuple from packaging import version from rasa.constants import MINIMUM_COMPATIBLE_VERSION import rasa.shared.utils.io import rasa.utils.io from rasa.cli.utils import create_output_path from rasa.shared.utils.cli import print_success from rasa.shared.constants import ( CONFIG_KEYS_CORE, CONFIG_KEYS_NLU, CONFIG_KEYS, DEFAULT_DOMAIN_PATH, DEFAULT_MODELS_PATH, DEFAULT_CORE_SUBDIRECTORY_NAME, DEFAULT_NLU_SUBDIRECTORY_NAME, ) from rasa.exceptions import ModelNotFound from rasa.utils.common import TempDirectoryPath if typing.TYPE_CHECKING: from rasa.shared.importers.importer import TrainingDataImporter logger = logging.getLogger(__name__) # Type alias for the fingerprint Fingerprint = Dict[Text, Union[Optional[Text], List[Text], int, float]] FINGERPRINT_FILE_PATH = "fingerprint.json" FINGERPRINT_CONFIG_KEY = "config" FINGERPRINT_CONFIG_CORE_KEY = "core-config" FINGERPRINT_CONFIG_NLU_KEY = "nlu-config" FINGERPRINT_CONFIG_WITHOUT_EPOCHS_KEY = "config-without-epochs" FINGERPRINT_DOMAIN_WITHOUT_NLG_KEY = "domain" FINGERPRINT_NLG_KEY = "nlg" FINGERPRINT_RASA_VERSION_KEY = "version" FINGERPRINT_STORIES_KEY = "stories" FINGERPRINT_NLU_DATA_KEY = "messages" FINGERPRINT_NLU_LABELS_KEY = "nlu_labels" FINGERPRINT_PROJECT = "project" FINGERPRINT_TRAINED_AT_KEY = "trained_at" class Section(NamedTuple): """Specifies which fingerprint keys decide whether this sub-model is retrained.""" name: Text relevant_keys: List[Text] SECTION_CORE = Section( name="Core model", relevant_keys=[ FINGERPRINT_CONFIG_KEY, FINGERPRINT_CONFIG_CORE_KEY, FINGERPRINT_DOMAIN_WITHOUT_NLG_KEY, FINGERPRINT_STORIES_KEY, FINGERPRINT_RASA_VERSION_KEY, ], ) SECTION_NLU = Section( name="NLU model", relevant_keys=[ FINGERPRINT_CONFIG_KEY, FINGERPRINT_CONFIG_NLU_KEY, FINGERPRINT_NLU_DATA_KEY, FINGERPRINT_RASA_VERSION_KEY, ], ) SECTION_NLG = Section(name="NLG responses", relevant_keys=[FINGERPRINT_NLG_KEY]) class FingerprintComparisonResult: """Container for the results of a fingerprint comparison.""" def __init__( self, nlu: bool = True, core: bool = True, nlg: bool = True, force_training: bool = False, ): """Creates a `FingerprintComparisonResult` instance. Args: nlu: `True` if the NLU model should be retrained. core: `True` if the Core model should be retrained. nlg: `True` if the responses in the domain should be updated. force_training: `True` if a training of all parts is forced. """ self.nlu = nlu self.core = core self.nlg = nlg self.force_training = force_training def is_training_required(self) -> bool: """Check if anything has to be retrained.""" return any([self.nlg, self.nlu, self.core, self.force_training]) def should_retrain_core(self) -> bool: """Check if the Core model has to be updated.""" return self.force_training or self.core def should_retrain_nlg(self) -> bool: """Check if the responses have to be updated.""" return self.should_retrain_core() or self.nlg def should_retrain_nlu(self) -> bool: """Check if the NLU model has to be updated.""" return self.force_training or self.nlu def get_local_model(model_path: Text = DEFAULT_MODELS_PATH) -> Text: """Returns verified path to local model archive. Args: model_path: Path to the zipped model. If it's a directory, the latest trained model is returned. Returns: Path to the zipped model. If it's a directory, the latest trained model is returned. Raises: ModelNotFound Exception: When no model could be found at the provided path. """ if not model_path: raise ModelNotFound("No path specified.") elif not os.path.exists(model_path): raise ModelNotFound(f"No file or directory at '{model_path}'.") if os.path.isdir(model_path): model_path = get_latest_model(model_path) if not model_path: raise ModelNotFound( f"Could not find any Rasa model files in '{model_path}'." ) elif not model_path.endswith(".tar.gz"): raise ModelNotFound(f"Path '{model_path}' does not point to a Rasa model file.") return model_path def get_model(model_path: Text = DEFAULT_MODELS_PATH) -> TempDirectoryPath: """Gets a model and unpacks it. Args: model_path: Path to the zipped model. If it's a directory, the latest trained model is returned. Returns: Path to the unpacked model. Raises: ModelNotFound Exception: When no model could be found at the provided path. """ model_path = get_local_model(model_path) try: model_relative_path = os.path.relpath(model_path) except ValueError: model_relative_path = model_path logger.info(f"Loading model {model_relative_path}...") return unpack_model(model_path) def get_latest_model(model_path: Text = DEFAULT_MODELS_PATH) -> Optional[Text]: """Get the latest model from a path. Args: model_path: Path to a directory containing zipped models. Returns: Path to latest model in the given directory. """ if not os.path.exists(model_path) or os.path.isfile(model_path): model_path = os.path.dirname(model_path) list_of_files = glob.glob(os.path.join(model_path, "*.tar.gz")) if len(list_of_files) == 0: return None return max(list_of_files, key=os.path.getctime) def unpack_model( model_file: Text, working_directory: Optional[Union[Path, Text]] = None ) -> TempDirectoryPath: """Unpack a zipped Rasa model. Args: model_file: Path to zipped model. working_directory: Location where the model should be unpacked to. If `None` a temporary directory will be created. Returns: Path to unpacked Rasa model. """ import tarfile from tarsafe import TarSafe if working_directory is None: working_directory = tempfile.mkdtemp() # All files are in a subdirectory. try: with TarSafe.open(model_file, mode="r:gz") as tar: tar.extractall(working_directory) logger.debug(f"Extracted model to '{working_directory}'.") except (tarfile.TarError, ValueError) as e: logger.error(f"Failed to extract model at {model_file}. Error: {e}") raise return TempDirectoryPath(working_directory) def get_model_subdirectories( unpacked_model_path: Text, ) -> Tuple[Optional[Text], Optional[Text]]: """Return paths for Core and NLU model directories, if they exist. If neither directories exist, a `ModelNotFound` exception is raised. Args: unpacked_model_path: Path to unpacked Rasa model. Returns: Tuple (path to Core subdirectory if it exists or `None` otherwise, path to NLU subdirectory if it exists or `None` otherwise). """ core_path = os.path.join(unpacked_model_path, DEFAULT_CORE_SUBDIRECTORY_NAME) nlu_path = os.path.join(unpacked_model_path, DEFAULT_NLU_SUBDIRECTORY_NAME) if not os.path.isdir(core_path): core_path = None if not os.path.isdir(nlu_path): nlu_path = None if not core_path and not nlu_path: raise ModelNotFound( "No NLU or Core data for unpacked model at: '{}'.".format( unpacked_model_path ) ) return core_path, nlu_path def create_package_rasa( training_directory: Text, output_filename: Text, fingerprint: Optional[Fingerprint] = None, ) -> Text: """Create a zipped Rasa model from trained model files. Args: training_directory: Path to the directory which contains the trained model files. output_filename: Name of the zipped model file to be created. fingerprint: A unique fingerprint to identify the model version. Returns: Path to zipped model. """ import tarfile if fingerprint: persist_fingerprint(training_directory, fingerprint) output_directory = os.path.dirname(output_filename) if not os.path.exists(output_directory): os.makedirs(output_directory) with tarfile.open(output_filename, "w:gz") as tar: for elem in os.scandir(training_directory): tar.add(elem.path, arcname=elem.name) shutil.rmtree(training_directory) return output_filename def project_fingerprint() -> Optional[Text]: """Create a hash for the project in the current working directory. Returns: project hash """ try: remote = check_output( # skipcq:BAN-B607,BAN-B603 ["git", "remote", "get-url", "origin"], stderr=DEVNULL ) return hashlib.sha256(remote).hexdigest() except (CalledProcessError, OSError): return None async def model_fingerprint(file_importer: "TrainingDataImporter") -> Fingerprint: """Create a model fingerprint from its used configuration and training data. Args: file_importer: File importer which provides the training data and model config. Returns: The fingerprint. """ import time config = await file_importer.get_config() domain = await file_importer.get_domain() stories = await file_importer.get_stories() nlu_data = await file_importer.get_nlu_data() responses = domain.responses # Do a copy of the domain to not change the actual domain (shallow is enough) domain = copy.copy(domain) # don't include the response texts in the fingerprint. # Their fingerprint is separate. domain.responses = {} return { FINGERPRINT_CONFIG_KEY: _get_fingerprint_of_config( config, exclude_keys=CONFIG_KEYS ), FINGERPRINT_CONFIG_CORE_KEY: _get_fingerprint_of_config( config, include_keys=CONFIG_KEYS_CORE ), FINGERPRINT_CONFIG_NLU_KEY: _get_fingerprint_of_config( config, include_keys=CONFIG_KEYS_NLU ), FINGERPRINT_CONFIG_WITHOUT_EPOCHS_KEY: ( _get_fingerprint_of_config_without_epochs(config) ), FINGERPRINT_DOMAIN_WITHOUT_NLG_KEY: domain.fingerprint(), FINGERPRINT_NLG_KEY: rasa.shared.utils.io.deep_container_fingerprint(responses), FINGERPRINT_PROJECT: project_fingerprint(), FINGERPRINT_NLU_DATA_KEY: nlu_data.fingerprint(), FINGERPRINT_NLU_LABELS_KEY: nlu_data.label_fingerprint(), FINGERPRINT_STORIES_KEY: stories.fingerprint(), FINGERPRINT_TRAINED_AT_KEY: time.time(), FINGERPRINT_RASA_VERSION_KEY: rasa.__version__, } def _get_fingerprint_of_config( config: Optional[Dict[Text, Any]], include_keys: Optional[List[Text]] = None, exclude_keys: Optional[List[Text]] = None, ) -> Text: if not config: return "" keys = include_keys or list(filter(lambda k: k not in exclude_keys, config.keys())) sub_config = {k: config[k] for k in keys if k in config} return rasa.shared.utils.io.deep_container_fingerprint(sub_config) def _get_fingerprint_of_config_without_epochs( config: Optional[Dict[Text, Any]], ) -> Text: if not config: return "" copied_config = copy.deepcopy(config) for key in ["pipeline", "policies"]: if copied_config.get(key): for p in copied_config[key]: if "epochs" in p: del p["epochs"] return rasa.shared.utils.io.deep_container_fingerprint(copied_config) def fingerprint_from_path(model_path: Text) -> Fingerprint: """Load a persisted fingerprint. Args: model_path: Path to directory containing the fingerprint. Returns: The fingerprint or an empty dict if no fingerprint was found. """ if not model_path or not os.path.exists(model_path): return {} fingerprint_path = os.path.join(model_path, FINGERPRINT_FILE_PATH) if os.path.isfile(fingerprint_path): return rasa.shared.utils.io.read_json_file(fingerprint_path) else: return {} def persist_fingerprint(output_path: Text, fingerprint: Fingerprint) -> None: """Persist a model fingerprint. Args: output_path: Directory in which the fingerprint should be saved. fingerprint: The fingerprint to be persisted. """ path = os.path.join(output_path, FINGERPRINT_FILE_PATH) rasa.shared.utils.io.dump_obj_as_json_to_file(path, fingerprint) def did_section_fingerprint_change( fingerprint1: Fingerprint, fingerprint2: Fingerprint, section: Section ) -> bool: """Check whether the fingerprint of a section has changed.""" for k in section.relevant_keys: if fingerprint1.get(k) != fingerprint2.get(k): logger.info(f"Data ({k}) for {section.name} section changed.") return True return False def move_model(source: Text, target: Text) -> bool: """Move two model directories. Args: source: The original folder which should be merged in another. target: The destination folder where it should be moved to. Returns: `True` if the merge was successful, else `False`. """ try: shutil.move(source, target) return True except Exception as e: logging.debug(f"Could not merge model: {e}") return False def should_retrain( new_fingerprint: Fingerprint, old_model: Optional[Text], train_path: Text, has_e2e_examples: bool = False, force_training: bool = False, ) -> FingerprintComparisonResult: """Check which components of a model should be retrained. Args: new_fingerprint: The fingerprint of the new model to be trained. old_model: Path to the old zipped model file. train_path: Path to the directory in which the new model will be trained. has_e2e_examples: Whether the new training data contains e2e examples. force_training: Indicates if the model needs to be retrained even if the data has not changed. Returns: A FingerprintComparisonResult object indicating whether Rasa Core and/or Rasa NLU needs to be retrained or not. """ fingerprint_comparison = FingerprintComparisonResult() if old_model is None or not os.path.exists(old_model): return fingerprint_comparison try: with unpack_model(old_model) as unpacked: last_fingerprint = fingerprint_from_path(unpacked) old_core, old_nlu = get_model_subdirectories(unpacked) fingerprint_comparison = FingerprintComparisonResult( core=did_section_fingerprint_change( last_fingerprint, new_fingerprint, SECTION_CORE ), nlu=did_section_fingerprint_change( last_fingerprint, new_fingerprint, SECTION_NLU ), nlg=did_section_fingerprint_change( last_fingerprint, new_fingerprint, SECTION_NLG ), force_training=force_training, ) # We should retrain core if nlu data changes and there are e2e stories. if has_e2e_examples and fingerprint_comparison.should_retrain_nlu(): fingerprint_comparison.core = True core_merge_failed = False if not fingerprint_comparison.should_retrain_core(): target_path = os.path.join(train_path, DEFAULT_CORE_SUBDIRECTORY_NAME) core_merge_failed = not move_model(old_core, target_path) fingerprint_comparison.core = core_merge_failed if not fingerprint_comparison.should_retrain_nlg() and core_merge_failed: # If moving the Core model failed, we should also retrain NLG fingerprint_comparison.nlg = True if not fingerprint_comparison.should_retrain_nlu(): target_path = os.path.join(train_path, "nlu") fingerprint_comparison.nlu = not move_model(old_nlu, target_path) return fingerprint_comparison except Exception as e: logger.error( f"Failed to get the fingerprint. Error: {e}.\n" f"Proceeding with running default retrain..." ) return fingerprint_comparison def can_finetune( last_fingerprint: Fingerprint, new_fingerprint: Fingerprint, core: bool = False, nlu: bool = False, ) -> bool: """Checks if components of a model can be finetuned with incremental training. Args: last_fingerprint: The fingerprint of the old model to potentially be fine-tuned. new_fingerprint: The fingerprint of the new model. core: Check sections for finetuning a core model. nlu: Check sections for finetuning an nlu model. Returns: `True` if the old model can be finetuned, `False` otherwise. """ section_keys = [ FINGERPRINT_CONFIG_WITHOUT_EPOCHS_KEY, ] if core: section_keys.append(FINGERPRINT_DOMAIN_WITHOUT_NLG_KEY) if nlu: section_keys.append(FINGERPRINT_NLU_LABELS_KEY) fingerprint_changed = did_section_fingerprint_change( last_fingerprint, new_fingerprint, Section(name="finetune", relevant_keys=section_keys), ) old_model_above_min_version = version.parse( last_fingerprint.get(FINGERPRINT_RASA_VERSION_KEY) ) >= version.parse(MINIMUM_COMPATIBLE_VERSION) return old_model_above_min_version and not fingerprint_changed def package_model( fingerprint: Fingerprint, output_directory: Text, train_path: Text, fixed_model_name: Optional[Text] = None, model_prefix: Text = "", ) -> Text: """ Compress a trained model. Args: fingerprint: fingerprint of the model output_directory: path to the directory in which the model should be stored train_path: path to uncompressed model fixed_model_name: name of the compressed model file model_prefix: prefix of the compressed model file Returns: path to 'tar.gz' model file """ output_directory = create_output_path( output_directory, prefix=model_prefix, fixed_name=fixed_model_name ) create_package_rasa(train_path, output_directory, fingerprint) print_success( "Your Rasa model is trained and saved at '{}'.".format( os.path.abspath(output_directory) ) ) return output_directory async def update_model_with_new_domain( importer: "TrainingDataImporter", unpacked_model_path: Union[Path, Text] ) -> None: """Overwrites the domain of an unpacked model with a new domain. Args: importer: Importer which provides the new domain. unpacked_model_path: Path to the unpacked model. """ model_path = Path(unpacked_model_path) / DEFAULT_CORE_SUBDIRECTORY_NAME domain = await importer.get_domain() domain.persist(model_path / DEFAULT_DOMAIN_PATH) def get_model_for_finetuning( previous_model_file: Optional[Union[Path, Text]] ) -> Optional[Text]: """Gets validated path for model to finetune. Args: previous_model_file: Path to model file which should be used for finetuning or a directory in case the latest trained model should be used. Returns: Path to model archive. `None` if there is no model. """ if Path(previous_model_file).is_dir(): logger.debug( f"Trying to load latest model from '{previous_model_file}' for " f"finetuning." ) return get_latest_model(previous_model_file) if Path(previous_model_file).is_file(): return previous_model_file logger.debug( "No valid model for finetuning found as directory either " "contains no model or model file cannot be found." ) return None
path_disclosure
{ "code": [ " with tarfile.open(model_file, mode=\"r:gz\") as tar:" ], "line_no": [ 231 ] }
{ "code": [ " with TarSafe.open(model_file, mode=\"r:gz\") as tar:" ], "line_no": [ 232 ] }
import copy import glob import hashlib import logging import os import shutil from subprocess import CalledProcessError, DEVNULL, check_output # skipcq:BAN-B404 import tempfile import typing from pathlib import Path from typing import Any, Text, Tuple, Union, Optional, List, Dict, NamedTuple from packaging import version from rasa.constants import MINIMUM_COMPATIBLE_VERSION import rasa.shared.utils.io import rasa.utils.io from rasa.cli.utils import create_output_path from rasa.shared.utils.cli import print_success from rasa.shared.constants import ( CONFIG_KEYS_CORE, CONFIG_KEYS_NLU, CONFIG_KEYS, DEFAULT_DOMAIN_PATH, DEFAULT_MODELS_PATH, DEFAULT_CORE_SUBDIRECTORY_NAME, DEFAULT_NLU_SUBDIRECTORY_NAME, ) from rasa.exceptions import ModelNotFound from rasa.utils.common import TempDirectoryPath if typing.TYPE_CHECKING: from rasa.shared.importers.importer import TrainingDataImporter VAR_0 = logging.getLogger(__name__) VAR_1 = Dict[Text, Union[Optional[Text], List[Text], int, float]] VAR_2 = "fingerprint.json" VAR_3 = "config" VAR_4 = "core-config" VAR_5 = "nlu-config" VAR_6 = "config-without-epochs" VAR_7 = "domain" VAR_8 = "nlg" VAR_9 = "version" VAR_10 = "stories" VAR_11 = "messages" VAR_12 = "nlu_labels" VAR_13 = "project" VAR_14 = "trained_at" class CLASS_0(NamedTuple): name: Text relevant_keys: List[Text] VAR_15 = CLASS_0( name="Core model", relevant_keys=[ VAR_3, VAR_4, VAR_7, VAR_10, VAR_9, ], ) VAR_16 = CLASS_0( name="NLU model", relevant_keys=[ VAR_3, VAR_5, VAR_11, VAR_9, ], ) VAR_17 = CLASS_0(name="NLG responses", relevant_keys=[VAR_8]) class CLASS_1: def __init__( self, VAR_42: bool = True, VAR_41: bool = True, VAR_48: bool = True, VAR_39: bool = False, ): self.nlu = VAR_42 self.core = VAR_41 self.nlg = VAR_48 self.force_training = VAR_39 def FUNC_19(self) -> bool: return any([self.nlg, self.nlu, self.core, self.force_training]) def FUNC_20(self) -> bool: return self.force_training or self.core def FUNC_21(self) -> bool: return self.should_retrain_core() or self.nlg def FUNC_22(self) -> bool: return self.force_training or self.nlu def FUNC_0(VAR_18: Text = DEFAULT_MODELS_PATH) -> Text: if not VAR_18: raise ModelNotFound("No VAR_60 specified.") elif not os.path.exists(VAR_18): raise ModelNotFound(f"No file or directory at '{VAR_18}'.") if os.path.isdir(VAR_18): VAR_18 = FUNC_2(VAR_18) if not VAR_18: raise ModelNotFound( f"Could not find any Rasa model files in '{VAR_18}'." ) elif not VAR_18.endswith(".tar.gz"): raise ModelNotFound(f"Path '{VAR_18}' does not point to a Rasa model file.") return VAR_18 def FUNC_1(VAR_18: Text = DEFAULT_MODELS_PATH) -> TempDirectoryPath: VAR_18 = FUNC_0(VAR_18) try: VAR_65 = os.path.relpath(VAR_18) except ValueError: VAR_65 = VAR_18 VAR_0.info(f"Loading model {VAR_65}...") return FUNC_3(VAR_18) def FUNC_2(VAR_18: Text = DEFAULT_MODELS_PATH) -> Optional[Text]: if not os.path.exists(VAR_18) or os.path.isfile(VAR_18): VAR_18 = os.path.dirname(VAR_18) VAR_49 = glob.glob(os.path.join(VAR_18, "*.tar.gz")) if len(VAR_49) == 0: return None return max(VAR_49, key=os.path.getctime) def FUNC_3( VAR_19: Text, VAR_20: Optional[Union[Path, Text]] = None ) -> TempDirectoryPath: import tarfile if VAR_20 is None: VAR_20 = tempfile.mkdtemp() try: with tarfile.open(VAR_19, mode="r:gz") as tar: tar.extractall(VAR_20) VAR_0.debug(f"Extracted model to '{VAR_20}'.") except (tarfile.TarError, ValueError) as e: VAR_0.error(f"Failed to extract model at {VAR_19}. Error: {e}") raise return TempDirectoryPath(VAR_20) def FUNC_4( VAR_21: Text, ) -> Tuple[Optional[Text], Optional[Text]]: VAR_50 = os.path.join(VAR_21, DEFAULT_CORE_SUBDIRECTORY_NAME) VAR_51 = os.path.join(VAR_21, DEFAULT_NLU_SUBDIRECTORY_NAME) if not os.path.isdir(VAR_50): VAR_50 = None if not os.path.isdir(VAR_51): nlu_path = None if not VAR_50 and not VAR_51: raise ModelNotFound( "No NLU or Core data for unpacked model at: '{}'.".format( VAR_21 ) ) return VAR_50, VAR_51 def FUNC_5( VAR_22: Text, VAR_23: Text, VAR_24: Optional[VAR_1] = None, ) -> Text: import tarfile if VAR_24: FUNC_11(VAR_22, VAR_24) VAR_43 = os.path.dirname(VAR_23) if not os.path.exists(VAR_43): os.makedirs(VAR_43) with tarfile.open(VAR_23, "w:gz") as tar: for elem in os.scandir(VAR_22): tar.add(elem.path, arcname=elem.name) shutil.rmtree(VAR_22) return VAR_23 def FUNC_6() -> Optional[Text]: try: VAR_66 = check_output( # skipcq:BAN-B607,BAN-B603 ["git", "remote", "get-url", "origin"], stderr=DEVNULL ) return hashlib.sha256(VAR_66).hexdigest() except (CalledProcessError, OSError): return None async def FUNC_7(VAR_25: "TrainingDataImporter") -> VAR_1: import time VAR_26 = await VAR_25.get_config() VAR_52 = await VAR_25.get_domain() VAR_53 = await VAR_25.get_stories() VAR_54 = await VAR_25.get_nlu_data() VAR_55 = VAR_52.responses VAR_52 = copy.copy(VAR_52) VAR_52.responses = {} return { VAR_3: FUNC_8( VAR_26, VAR_28=CONFIG_KEYS ), VAR_4: FUNC_8( VAR_26, VAR_27=CONFIG_KEYS_CORE ), VAR_5: FUNC_8( VAR_26, VAR_27=CONFIG_KEYS_NLU ), VAR_6: ( FUNC_9(VAR_26) ), VAR_7: VAR_52.fingerprint(), VAR_8: rasa.shared.utils.io.deep_container_fingerprint(VAR_55), VAR_13: FUNC_6(), VAR_11: VAR_54.fingerprint(), VAR_12: VAR_54.label_fingerprint(), VAR_10: VAR_53.fingerprint(), VAR_14: time.time(), VAR_9: rasa.__version__, } def FUNC_8( VAR_26: Optional[Dict[Text, Any]], VAR_27: Optional[List[Text]] = None, VAR_28: Optional[List[Text]] = None, ) -> Text: if not VAR_26: return "" VAR_56 = VAR_27 or list(filter(lambda k: k not in VAR_28, VAR_26.keys())) VAR_57 = {k: VAR_26[k] for k in VAR_56 if k in VAR_26} return rasa.shared.utils.io.deep_container_fingerprint(VAR_57) def FUNC_9( VAR_26: Optional[Dict[Text, Any]], ) -> Text: if not VAR_26: return "" VAR_58 = copy.deepcopy(VAR_26) for key in ["pipeline", "policies"]: if VAR_58.get(key): for p in VAR_58[key]: if "epochs" in p: del p["epochs"] return rasa.shared.utils.io.deep_container_fingerprint(VAR_58) def FUNC_10(VAR_18: Text) -> VAR_1: if not VAR_18 or not os.path.exists(VAR_18): return {} VAR_59 = os.path.join(VAR_18, VAR_2) if os.path.isfile(VAR_59): return rasa.shared.utils.io.read_json_file(VAR_59) else: return {} def FUNC_11(VAR_29: Text, VAR_24: VAR_1) -> None: VAR_60 = os.path.join(VAR_29, VAR_2) rasa.shared.utils.io.dump_obj_as_json_to_file(VAR_60, VAR_24) def FUNC_12( VAR_30: VAR_1, VAR_31: VAR_1, VAR_32: CLASS_0 ) -> bool: for k in VAR_32.relevant_keys: if VAR_30.get(k) != VAR_31.get(k): VAR_0.info(f"Data ({k}) for {VAR_32.name} VAR_32 changed.") return True return False def FUNC_13(VAR_33: Text, VAR_34: Text) -> bool: try: shutil.move(VAR_33, VAR_34) return True except Exception as e: logging.debug(f"Could not merge model: {e}") return False def FUNC_14( VAR_35: VAR_1, VAR_36: Optional[Text], VAR_37: Text, VAR_38: bool = False, VAR_39: bool = False, ) -> CLASS_1: VAR_61 = CLASS_1() if VAR_36 is None or not os.path.exists(VAR_36): return VAR_61 try: with FUNC_3(VAR_36) as unpacked: VAR_40 = FUNC_10(unpacked) VAR_67, VAR_68 = FUNC_4(unpacked) VAR_61 = CLASS_1( VAR_41=FUNC_12( VAR_40, VAR_35, VAR_15 ), VAR_42=FUNC_12( VAR_40, VAR_35, VAR_16 ), VAR_48=FUNC_12( VAR_40, VAR_35, VAR_17 ), VAR_39=force_training, ) if VAR_38 and VAR_61.should_retrain_nlu(): VAR_61.core = True VAR_69 = False if not VAR_61.should_retrain_core(): VAR_70 = os.path.join(VAR_37, DEFAULT_CORE_SUBDIRECTORY_NAME) VAR_69 = not FUNC_13(VAR_67, VAR_70) VAR_61.core = VAR_69 if not VAR_61.should_retrain_nlg() and VAR_69: VAR_61.nlg = True if not VAR_61.should_retrain_nlu(): VAR_70 = os.path.join(VAR_37, "nlu") VAR_61.nlu = not FUNC_13(VAR_68, VAR_70) return VAR_61 except Exception as e: VAR_0.error( f"Failed to get the VAR_24. Error: {e}.\n" f"Proceeding with running default retrain..." ) return VAR_61 def FUNC_15( VAR_40: VAR_1, VAR_35: VAR_1, VAR_41: bool = False, VAR_42: bool = False, ) -> bool: VAR_62 = [ VAR_6, ] if VAR_41: VAR_62.append(VAR_7) if VAR_42: VAR_62.append(VAR_12) VAR_63 = FUNC_12( VAR_40, VAR_35, CLASS_0(name="finetune", relevant_keys=VAR_62), ) VAR_64 = version.parse( VAR_40.get(VAR_9) ) >= version.parse(MINIMUM_COMPATIBLE_VERSION) return VAR_64 and not VAR_63 def FUNC_16( VAR_24: VAR_1, VAR_43: Text, VAR_37: Text, VAR_44: Optional[Text] = None, VAR_45: Text = "", ) -> Text: VAR_43 = create_output_path( VAR_43, prefix=VAR_45, fixed_name=VAR_44 ) FUNC_5(VAR_37, VAR_43, VAR_24) print_success( "Your Rasa model is trained and saved at '{}'.".format( os.path.abspath(VAR_43) ) ) return VAR_43 async def FUNC_17( VAR_46: "TrainingDataImporter", VAR_21: Union[Path, Text] ) -> None: VAR_18 = Path(VAR_21) / DEFAULT_CORE_SUBDIRECTORY_NAME VAR_52 = await VAR_46.get_domain() VAR_52.persist(VAR_18 / DEFAULT_DOMAIN_PATH) def FUNC_18( VAR_47: Optional[Union[Path, Text]] ) -> Optional[Text]: if Path(VAR_47).is_dir(): VAR_0.debug( f"Trying to load latest model from '{VAR_47}' for " f"finetuning." ) return FUNC_2(VAR_47) if Path(VAR_47).is_file(): return VAR_47 VAR_0.debug( "No valid model for finetuning found as directory either " "contains no model or model file cannot be found." ) return None
import copy import glob import hashlib import logging import os import shutil from subprocess import CalledProcessError, DEVNULL, check_output # skipcq:BAN-B404 import tempfile import typing from pathlib import Path from typing import Any, Text, Tuple, Union, Optional, List, Dict, NamedTuple from packaging import version from rasa.constants import MINIMUM_COMPATIBLE_VERSION import rasa.shared.utils.io import rasa.utils.io from rasa.cli.utils import create_output_path from rasa.shared.utils.cli import print_success from rasa.shared.constants import ( CONFIG_KEYS_CORE, CONFIG_KEYS_NLU, CONFIG_KEYS, DEFAULT_DOMAIN_PATH, DEFAULT_MODELS_PATH, DEFAULT_CORE_SUBDIRECTORY_NAME, DEFAULT_NLU_SUBDIRECTORY_NAME, ) from rasa.exceptions import ModelNotFound from rasa.utils.common import TempDirectoryPath if typing.TYPE_CHECKING: from rasa.shared.importers.importer import TrainingDataImporter VAR_0 = logging.getLogger(__name__) VAR_1 = Dict[Text, Union[Optional[Text], List[Text], int, float]] VAR_2 = "fingerprint.json" VAR_3 = "config" VAR_4 = "core-config" VAR_5 = "nlu-config" VAR_6 = "config-without-epochs" VAR_7 = "domain" VAR_8 = "nlg" VAR_9 = "version" VAR_10 = "stories" VAR_11 = "messages" VAR_12 = "nlu_labels" VAR_13 = "project" VAR_14 = "trained_at" class CLASS_0(NamedTuple): name: Text relevant_keys: List[Text] VAR_15 = CLASS_0( name="Core model", relevant_keys=[ VAR_3, VAR_4, VAR_7, VAR_10, VAR_9, ], ) VAR_16 = CLASS_0( name="NLU model", relevant_keys=[ VAR_3, VAR_5, VAR_11, VAR_9, ], ) VAR_17 = CLASS_0(name="NLG responses", relevant_keys=[VAR_8]) class CLASS_1: def __init__( self, VAR_42: bool = True, VAR_41: bool = True, VAR_48: bool = True, VAR_39: bool = False, ): self.nlu = VAR_42 self.core = VAR_41 self.nlg = VAR_48 self.force_training = VAR_39 def FUNC_19(self) -> bool: return any([self.nlg, self.nlu, self.core, self.force_training]) def FUNC_20(self) -> bool: return self.force_training or self.core def FUNC_21(self) -> bool: return self.should_retrain_core() or self.nlg def FUNC_22(self) -> bool: return self.force_training or self.nlu def FUNC_0(VAR_18: Text = DEFAULT_MODELS_PATH) -> Text: if not VAR_18: raise ModelNotFound("No VAR_60 specified.") elif not os.path.exists(VAR_18): raise ModelNotFound(f"No file or directory at '{VAR_18}'.") if os.path.isdir(VAR_18): VAR_18 = FUNC_2(VAR_18) if not VAR_18: raise ModelNotFound( f"Could not find any Rasa model files in '{VAR_18}'." ) elif not VAR_18.endswith(".tar.gz"): raise ModelNotFound(f"Path '{VAR_18}' does not point to a Rasa model file.") return VAR_18 def FUNC_1(VAR_18: Text = DEFAULT_MODELS_PATH) -> TempDirectoryPath: VAR_18 = FUNC_0(VAR_18) try: VAR_65 = os.path.relpath(VAR_18) except ValueError: VAR_65 = VAR_18 VAR_0.info(f"Loading model {VAR_65}...") return FUNC_3(VAR_18) def FUNC_2(VAR_18: Text = DEFAULT_MODELS_PATH) -> Optional[Text]: if not os.path.exists(VAR_18) or os.path.isfile(VAR_18): VAR_18 = os.path.dirname(VAR_18) VAR_49 = glob.glob(os.path.join(VAR_18, "*.tar.gz")) if len(VAR_49) == 0: return None return max(VAR_49, key=os.path.getctime) def FUNC_3( VAR_19: Text, VAR_20: Optional[Union[Path, Text]] = None ) -> TempDirectoryPath: import tarfile from tarsafe import TarSafe if VAR_20 is None: VAR_20 = tempfile.mkdtemp() try: with TarSafe.open(VAR_19, mode="r:gz") as tar: tar.extractall(VAR_20) VAR_0.debug(f"Extracted model to '{VAR_20}'.") except (tarfile.TarError, ValueError) as e: VAR_0.error(f"Failed to extract model at {VAR_19}. Error: {e}") raise return TempDirectoryPath(VAR_20) def FUNC_4( VAR_21: Text, ) -> Tuple[Optional[Text], Optional[Text]]: VAR_50 = os.path.join(VAR_21, DEFAULT_CORE_SUBDIRECTORY_NAME) VAR_51 = os.path.join(VAR_21, DEFAULT_NLU_SUBDIRECTORY_NAME) if not os.path.isdir(VAR_50): VAR_50 = None if not os.path.isdir(VAR_51): nlu_path = None if not VAR_50 and not VAR_51: raise ModelNotFound( "No NLU or Core data for unpacked model at: '{}'.".format( VAR_21 ) ) return VAR_50, VAR_51 def FUNC_5( VAR_22: Text, VAR_23: Text, VAR_24: Optional[VAR_1] = None, ) -> Text: import tarfile if VAR_24: FUNC_11(VAR_22, VAR_24) VAR_43 = os.path.dirname(VAR_23) if not os.path.exists(VAR_43): os.makedirs(VAR_43) with tarfile.open(VAR_23, "w:gz") as tar: for elem in os.scandir(VAR_22): tar.add(elem.path, arcname=elem.name) shutil.rmtree(VAR_22) return VAR_23 def FUNC_6() -> Optional[Text]: try: VAR_66 = check_output( # skipcq:BAN-B607,BAN-B603 ["git", "remote", "get-url", "origin"], stderr=DEVNULL ) return hashlib.sha256(VAR_66).hexdigest() except (CalledProcessError, OSError): return None async def FUNC_7(VAR_25: "TrainingDataImporter") -> VAR_1: import time VAR_26 = await VAR_25.get_config() VAR_52 = await VAR_25.get_domain() VAR_53 = await VAR_25.get_stories() VAR_54 = await VAR_25.get_nlu_data() VAR_55 = VAR_52.responses VAR_52 = copy.copy(VAR_52) VAR_52.responses = {} return { VAR_3: FUNC_8( VAR_26, VAR_28=CONFIG_KEYS ), VAR_4: FUNC_8( VAR_26, VAR_27=CONFIG_KEYS_CORE ), VAR_5: FUNC_8( VAR_26, VAR_27=CONFIG_KEYS_NLU ), VAR_6: ( FUNC_9(VAR_26) ), VAR_7: VAR_52.fingerprint(), VAR_8: rasa.shared.utils.io.deep_container_fingerprint(VAR_55), VAR_13: FUNC_6(), VAR_11: VAR_54.fingerprint(), VAR_12: VAR_54.label_fingerprint(), VAR_10: VAR_53.fingerprint(), VAR_14: time.time(), VAR_9: rasa.__version__, } def FUNC_8( VAR_26: Optional[Dict[Text, Any]], VAR_27: Optional[List[Text]] = None, VAR_28: Optional[List[Text]] = None, ) -> Text: if not VAR_26: return "" VAR_56 = VAR_27 or list(filter(lambda k: k not in VAR_28, VAR_26.keys())) VAR_57 = {k: VAR_26[k] for k in VAR_56 if k in VAR_26} return rasa.shared.utils.io.deep_container_fingerprint(VAR_57) def FUNC_9( VAR_26: Optional[Dict[Text, Any]], ) -> Text: if not VAR_26: return "" VAR_58 = copy.deepcopy(VAR_26) for key in ["pipeline", "policies"]: if VAR_58.get(key): for p in VAR_58[key]: if "epochs" in p: del p["epochs"] return rasa.shared.utils.io.deep_container_fingerprint(VAR_58) def FUNC_10(VAR_18: Text) -> VAR_1: if not VAR_18 or not os.path.exists(VAR_18): return {} VAR_59 = os.path.join(VAR_18, VAR_2) if os.path.isfile(VAR_59): return rasa.shared.utils.io.read_json_file(VAR_59) else: return {} def FUNC_11(VAR_29: Text, VAR_24: VAR_1) -> None: VAR_60 = os.path.join(VAR_29, VAR_2) rasa.shared.utils.io.dump_obj_as_json_to_file(VAR_60, VAR_24) def FUNC_12( VAR_30: VAR_1, VAR_31: VAR_1, VAR_32: CLASS_0 ) -> bool: for k in VAR_32.relevant_keys: if VAR_30.get(k) != VAR_31.get(k): VAR_0.info(f"Data ({k}) for {VAR_32.name} VAR_32 changed.") return True return False def FUNC_13(VAR_33: Text, VAR_34: Text) -> bool: try: shutil.move(VAR_33, VAR_34) return True except Exception as e: logging.debug(f"Could not merge model: {e}") return False def FUNC_14( VAR_35: VAR_1, VAR_36: Optional[Text], VAR_37: Text, VAR_38: bool = False, VAR_39: bool = False, ) -> CLASS_1: VAR_61 = CLASS_1() if VAR_36 is None or not os.path.exists(VAR_36): return VAR_61 try: with FUNC_3(VAR_36) as unpacked: VAR_40 = FUNC_10(unpacked) VAR_67, VAR_68 = FUNC_4(unpacked) VAR_61 = CLASS_1( VAR_41=FUNC_12( VAR_40, VAR_35, VAR_15 ), VAR_42=FUNC_12( VAR_40, VAR_35, VAR_16 ), VAR_48=FUNC_12( VAR_40, VAR_35, VAR_17 ), VAR_39=force_training, ) if VAR_38 and VAR_61.should_retrain_nlu(): VAR_61.core = True VAR_69 = False if not VAR_61.should_retrain_core(): VAR_70 = os.path.join(VAR_37, DEFAULT_CORE_SUBDIRECTORY_NAME) VAR_69 = not FUNC_13(VAR_67, VAR_70) VAR_61.core = VAR_69 if not VAR_61.should_retrain_nlg() and VAR_69: VAR_61.nlg = True if not VAR_61.should_retrain_nlu(): VAR_70 = os.path.join(VAR_37, "nlu") VAR_61.nlu = not FUNC_13(VAR_68, VAR_70) return VAR_61 except Exception as e: VAR_0.error( f"Failed to get the VAR_24. Error: {e}.\n" f"Proceeding with running default retrain..." ) return VAR_61 def FUNC_15( VAR_40: VAR_1, VAR_35: VAR_1, VAR_41: bool = False, VAR_42: bool = False, ) -> bool: VAR_62 = [ VAR_6, ] if VAR_41: VAR_62.append(VAR_7) if VAR_42: VAR_62.append(VAR_12) VAR_63 = FUNC_12( VAR_40, VAR_35, CLASS_0(name="finetune", relevant_keys=VAR_62), ) VAR_64 = version.parse( VAR_40.get(VAR_9) ) >= version.parse(MINIMUM_COMPATIBLE_VERSION) return VAR_64 and not VAR_63 def FUNC_16( VAR_24: VAR_1, VAR_43: Text, VAR_37: Text, VAR_44: Optional[Text] = None, VAR_45: Text = "", ) -> Text: VAR_43 = create_output_path( VAR_43, prefix=VAR_45, fixed_name=VAR_44 ) FUNC_5(VAR_37, VAR_43, VAR_24) print_success( "Your Rasa model is trained and saved at '{}'.".format( os.path.abspath(VAR_43) ) ) return VAR_43 async def FUNC_17( VAR_46: "TrainingDataImporter", VAR_21: Union[Path, Text] ) -> None: VAR_18 = Path(VAR_21) / DEFAULT_CORE_SUBDIRECTORY_NAME VAR_52 = await VAR_46.get_domain() VAR_52.persist(VAR_18 / DEFAULT_DOMAIN_PATH) def FUNC_18( VAR_47: Optional[Union[Path, Text]] ) -> Optional[Text]: if Path(VAR_47).is_dir(): VAR_0.debug( f"Trying to load latest model from '{VAR_47}' for " f"finetuning." ) return FUNC_2(VAR_47) if Path(VAR_47).is_file(): return VAR_47 VAR_0.debug( "No valid model for finetuning found as directory either " "contains no model or model file cannot be found." ) return None
[ 12, 14, 29, 32, 35, 37, 38, 39, 41, 43, 56, 57, 60, 63, 64, 85, 86, 89, 98, 109, 112, 114, 117, 119, 122, 124, 127, 129, 130, 133, 137, 141, 144, 150, 159, 161, 162, 165, 169, 172, 175, 178, 183, 185, 187, 188, 191, 194, 197, 201, 203, 206, 208, 209, 214, 219, 222, 225, 228, 229, 237, 239, 240, 246, 249, 253, 257, 260, 263, 270, 272, 273, 280, 286, 289, 292, 295, 299, 303, 306, 307, 310, 321, 322, 325, 328, 331, 334, 339, 341, 342, 344, 345, 347, 370, 371, 379, 381, 383, 385, 386, 392, 394, 400, 402, 403, 406, 409, 415, 417, 422, 423, 426, 430, 432, 435, 436, 446, 447, 450, 454, 457, 465, 466, 475, 483, 489, 492, 497, 510, 511, 514, 520, 522, 524, 528, 536, 537, 545, 551, 562, 568, 573, 574, 584, 591, 598, 604, 606, 607, 612, 620, 621, 626, 630, 640, 643, 649, 59, 88, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 190, 191, 192, 193, 194, 195, 196, 197, 198, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 309, 310, 311, 312, 313, 324, 325, 326, 327, 328, 329, 330, 331, 332, 405, 406, 407, 408, 409, 410, 411, 412, 425, 426, 427, 428, 429, 430, 431, 440, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 611, 612, 613, 614, 615, 616, 625, 626, 627, 628, 629, 630, 631, 632, 633, 97, 98, 99, 100, 101, 102, 103, 104, 111, 116, 121, 126 ]
[ 12, 14, 29, 32, 35, 37, 38, 39, 41, 43, 56, 57, 60, 63, 64, 85, 86, 89, 98, 109, 112, 114, 117, 119, 122, 124, 127, 129, 130, 133, 137, 141, 144, 150, 159, 161, 162, 165, 169, 172, 175, 178, 183, 185, 187, 188, 191, 194, 197, 201, 203, 206, 208, 209, 214, 219, 222, 226, 229, 230, 238, 240, 241, 247, 250, 254, 258, 261, 264, 271, 273, 274, 281, 287, 290, 293, 296, 300, 304, 307, 308, 311, 322, 323, 326, 329, 332, 335, 340, 342, 343, 345, 346, 348, 371, 372, 380, 382, 384, 386, 387, 393, 395, 401, 403, 404, 407, 410, 416, 418, 423, 424, 427, 431, 433, 436, 437, 447, 448, 451, 455, 458, 466, 467, 476, 484, 490, 493, 498, 511, 512, 515, 521, 523, 525, 529, 537, 538, 546, 552, 563, 569, 574, 575, 585, 592, 599, 605, 607, 608, 613, 621, 622, 627, 631, 641, 644, 650, 59, 88, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 190, 191, 192, 193, 194, 195, 196, 197, 198, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 310, 311, 312, 313, 314, 325, 326, 327, 328, 329, 330, 331, 332, 333, 406, 407, 408, 409, 410, 411, 412, 413, 426, 427, 428, 429, 430, 431, 432, 441, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 612, 613, 614, 615, 616, 617, 626, 627, 628, 629, 630, 631, 632, 633, 634, 97, 98, 99, 100, 101, 102, 103, 104, 111, 116, 121, 126 ]
1CWE-79
"""Reading/writing Beancount files.""" from __future__ import annotations import datetime import re import threading from codecs import decode from codecs import encode from hashlib import sha256 from operator import attrgetter from typing import Generator from typing import TYPE_CHECKING from beancount.core.data import Balance from beancount.core.data import Directive from beancount.core.data import Entries from beancount.core.data import SORT_ORDER from beancount.core.data import Transaction from beancount.core.flags import FLAG_CONVERSIONS from beancount.core.flags import FLAG_MERGING from beancount.core.flags import FLAG_PADDING from beancount.core.flags import FLAG_SUMMARIZE from beancount.core.flags import FLAG_TRANSFER from beancount.parser.printer import format_entry # type: ignore from fava.core._compat import FLAG_RETURNS from fava.core._compat import FLAG_UNREALIZED from fava.core.accounts import get_entry_accounts from fava.core.fava_options import InsertEntryOption from fava.core.misc import align from fava.core.module_base import FavaModule from fava.helpers import FavaAPIException from fava.util import next_key if TYPE_CHECKING: # pragma: no cover from fava.core import FavaLedger #: The flags to exclude when rendering entries. EXCL_FLAGS = { FLAG_PADDING, # P FLAG_SUMMARIZE, # S FLAG_TRANSFER, # T FLAG_CONVERSIONS, # C FLAG_UNREALIZED, # U FLAG_RETURNS, # R FLAG_MERGING, # M } def sha256_str(val: str) -> str: """Hash a string.""" return sha256(encode(val, encoding="utf-8")).hexdigest() class FileModule(FavaModule): """Functions related to reading/writing to Beancount files.""" def __init__(self, ledger: FavaLedger) -> None: super().__init__(ledger) self.lock = threading.Lock() def get_source(self, path: str) -> tuple[str, str]: """Get source files. Args: path: The path of the file. Returns: A string with the file contents and the `sha256sum` of the file. Raises: FavaAPIException: If the file at `path` is not one of the source files. """ if path not in self.ledger.options["include"]: raise FavaAPIException("Trying to read a non-source file") with open(path, mode="rb") as file: contents = file.read() sha256sum = sha256(contents).hexdigest() source = decode(contents) return source, sha256sum def set_source(self, path: str, source: str, sha256sum: str) -> str: """Write to source file. Args: path: The path of the file. source: A string with the file contents. sha256sum: Hash of the file. Returns: The `sha256sum` of the updated file. Raises: FavaAPIException: If the file at `path` is not one of the source files or if the file was changed externally. """ with self.lock: _, original_sha256sum = self.get_source(path) if original_sha256sum != sha256sum: raise FavaAPIException("The file changed externally.") contents = encode(source, encoding="utf-8") with open(path, "w+b") as file: file.write(contents) self.ledger.extensions.after_write_source(path, source) self.ledger.load_file() return sha256(contents).hexdigest() def insert_metadata( self, entry_hash: str, basekey: str, value: str ) -> None: """Insert metadata into a file at lineno. Also, prevent duplicate keys. """ with self.lock: self.ledger.changed() entry: Directive = self.ledger.get_entry(entry_hash) key = next_key(basekey, entry.meta) indent = self.ledger.fava_options.indent insert_metadata_in_file( entry.meta["filename"], entry.meta["lineno"], indent, key, value, ) self.ledger.extensions.after_insert_metadata(entry, key, value) def save_entry_slice( self, entry_hash: str, source_slice: str, sha256sum: str ) -> str: """Save slice of the source file for an entry. Args: entry_hash: An entry. source_slice: The lines that the entry should be replaced with. sha256sum: The sha256sum of the current lines of the entry. Returns: The `sha256sum` of the new lines of the entry. Raises: FavaAPIException: If the entry is not found or the file changed. """ with self.lock: entry = self.ledger.get_entry(entry_hash) ret = save_entry_slice(entry, source_slice, sha256sum) self.ledger.extensions.after_entry_modified(entry, source_slice) return ret def insert_entries(self, entries: Entries) -> None: """Insert entries. Args: entries: A list of entries. """ with self.lock: self.ledger.changed() fava_options = self.ledger.fava_options for entry in sorted(entries, key=incomplete_sortkey): insert_options = fava_options.insert_entry currency_column = fava_options.currency_column indent = fava_options.indent fava_options.insert_entry = insert_entry( entry, self.ledger.beancount_file_path, insert_options, currency_column, indent, ) self.ledger.extensions.after_insert_entry(entry) def render_entries(self, entries: Entries) -> Generator[str, None, None]: """Return entries in Beancount format. Only renders :class:`.Balance` and :class:`.Transaction`. Args: entries: A list of entries. Yields: The entries rendered in Beancount format. """ indent = self.ledger.fava_options.indent for entry in entries: if isinstance(entry, (Balance, Transaction)): if isinstance(entry, Transaction) and entry.flag in EXCL_FLAGS: continue try: yield get_entry_slice(entry)[0] + "\n" except (KeyError, FileNotFoundError): yield _format_entry( entry, self.ledger.fava_options.currency_column, indent, ) def incomplete_sortkey(entry: Directive) -> tuple[datetime.date, int]: """Sortkey for entries that might have incomplete metadata.""" return (entry.date, SORT_ORDER.get(type(entry), 0)) def insert_metadata_in_file( filename: str, lineno: int, indent: int, key: str, value: str ) -> None: """Inserts the specified metadata in the file below lineno, taking into account the whitespace in front of the line that lineno.""" with open(filename, encoding="utf-8") as file: contents = file.readlines() contents.insert(lineno, f'{" " * indent}{key}: "{value}"\n') with open(filename, "w", encoding="utf-8") as file: file.write("".join(contents)) def find_entry_lines(lines: list[str], lineno: int) -> list[str]: """Lines of entry starting at lineno. Args: lines: A list of lines. lineno: The 0-based line-index to start at. """ entry_lines = [lines[lineno]] while True: lineno += 1 try: line = lines[lineno] except IndexError: return entry_lines if not line.strip() or re.match(r"\S", line[0]): return entry_lines entry_lines.append(line) def get_entry_slice(entry: Directive) -> tuple[str, str]: """Get slice of the source file for an entry. Args: entry: An entry. Returns: A string containing the lines of the entry and the `sha256sum` of these lines. """ with open(entry.meta["filename"], encoding="utf-8") as file: lines = file.readlines() entry_lines = find_entry_lines(lines, entry.meta["lineno"] - 1) entry_source = "".join(entry_lines).rstrip("\n") return entry_source, sha256_str(entry_source) def save_entry_slice( entry: Directive, source_slice: str, sha256sum: str ) -> str: """Save slice of the source file for an entry. Args: entry: An entry. source_slice: The lines that the entry should be replaced with. sha256sum: The sha256sum of the current lines of the entry. Returns: The `sha256sum` of the new lines of the entry. Raises: FavaAPIException: If the file at `path` is not one of the source files. """ with open(entry.meta["filename"], encoding="utf-8") as file: lines = file.readlines() first_entry_line = entry.meta["lineno"] - 1 entry_lines = find_entry_lines(lines, first_entry_line) entry_source = "".join(entry_lines).rstrip("\n") if sha256_str(entry_source) != sha256sum: raise FavaAPIException("The file changed externally.") lines = ( lines[:first_entry_line] + [source_slice + "\n"] + lines[first_entry_line + len(entry_lines) :] ) with open(entry.meta["filename"], "w", encoding="utf-8") as file: file.writelines(lines) return sha256_str(source_slice) def insert_entry( entry: Directive, default_filename: str, insert_options: list[InsertEntryOption], currency_column: int, indent: int, ) -> list[InsertEntryOption]: """Insert an entry. Args: entry: An entry. default_filename: The default file to insert into if no option matches. insert_options: Insert options. currency_column: The column to align currencies at. indent: Number of indent spaces. Returns: A list of updated insert options. """ filename, lineno = find_insert_position( entry, insert_options, default_filename ) content = _format_entry(entry, currency_column, indent) with open(filename, encoding="utf-8") as file: contents = file.readlines() if lineno is None: # Appending contents += "\n" + content else: contents.insert(lineno, content + "\n") with open(filename, "w", encoding="utf-8") as file: file.writelines(contents) if lineno is None: return insert_options added_lines = content.count("\n") + 1 return [ option._replace(lineno=option.lineno + added_lines) if option.filename == filename and option.lineno > lineno else option for option in insert_options ] def _format_entry(entry: Directive, currency_column: int, indent: int) -> str: """Wrapper that strips unnecessary whitespace from format_entry.""" meta = { key: entry.meta[key] for key in entry.meta if not key.startswith("_") } entry = entry._replace(meta=meta) string = align(format_entry(entry, prefix=" " * indent), currency_column) string = string.replace("<class 'beancount.core.number.MISSING'>", "") return "\n".join(line.rstrip() for line in string.split("\n")) def find_insert_position( entry: Directive, insert_options: list[InsertEntryOption], default_filename: str, ) -> tuple[str, int | None]: """Find insert position for an entry. Args: entry: An entry. insert_options: A list of InsertOption. default_filename: The default file to insert into if no option matches. Returns: A tuple of the filename and the line number. """ # Get the list of accounts that should be considered for the entry. # For transactions, we want the reversed list of posting accounts. accounts = get_entry_accounts(entry) # Make no assumptions about the order of insert_options entries and instead # sort them ourselves (by descending dates) insert_options = sorted( insert_options, key=attrgetter("date"), reverse=True ) for account in accounts: for insert_option in insert_options: # Only consider InsertOptions before the entry date. if insert_option.date >= entry.date: continue if insert_option.re.match(account): return (insert_option.filename, insert_option.lineno - 1) return (default_filename, None)
"""Reading/writing Beancount files.""" from __future__ import annotations import datetime import re import threading from codecs import decode from codecs import encode from hashlib import sha256 from operator import attrgetter from typing import Generator from typing import TYPE_CHECKING from beancount.core.data import Balance from beancount.core.data import Directive from beancount.core.data import Entries from beancount.core.data import SORT_ORDER from beancount.core.data import Transaction from beancount.core.flags import FLAG_CONVERSIONS from beancount.core.flags import FLAG_MERGING from beancount.core.flags import FLAG_PADDING from beancount.core.flags import FLAG_SUMMARIZE from beancount.core.flags import FLAG_TRANSFER from beancount.parser.printer import format_entry # type: ignore from markupsafe import Markup from fava.core._compat import FLAG_RETURNS from fava.core._compat import FLAG_UNREALIZED from fava.core.accounts import get_entry_accounts from fava.core.fava_options import InsertEntryOption from fava.core.misc import align from fava.core.module_base import FavaModule from fava.helpers import FavaAPIException from fava.util import next_key if TYPE_CHECKING: # pragma: no cover from fava.core import FavaLedger #: The flags to exclude when rendering entries. EXCL_FLAGS = { FLAG_PADDING, # P FLAG_SUMMARIZE, # S FLAG_TRANSFER, # T FLAG_CONVERSIONS, # C FLAG_UNREALIZED, # U FLAG_RETURNS, # R FLAG_MERGING, # M } def sha256_str(val: str) -> str: """Hash a string.""" return sha256(encode(val, encoding="utf-8")).hexdigest() class FileModule(FavaModule): """Functions related to reading/writing to Beancount files.""" def __init__(self, ledger: FavaLedger) -> None: super().__init__(ledger) self.lock = threading.Lock() def get_source(self, path: str) -> tuple[str, str]: """Get source files. Args: path: The path of the file. Returns: A string with the file contents and the `sha256sum` of the file. Raises: FavaAPIException: If the file at `path` is not one of the source files. """ if path not in self.ledger.options["include"]: raise FavaAPIException("Trying to read a non-source file") with open(path, mode="rb") as file: contents = file.read() sha256sum = sha256(contents).hexdigest() source = decode(contents) return source, sha256sum def set_source(self, path: str, source: str, sha256sum: str) -> str: """Write to source file. Args: path: The path of the file. source: A string with the file contents. sha256sum: Hash of the file. Returns: The `sha256sum` of the updated file. Raises: FavaAPIException: If the file at `path` is not one of the source files or if the file was changed externally. """ with self.lock: _, original_sha256sum = self.get_source(path) if original_sha256sum != sha256sum: raise FavaAPIException("The file changed externally.") contents = encode(source, encoding="utf-8") with open(path, "w+b") as file: file.write(contents) self.ledger.extensions.after_write_source(path, source) self.ledger.load_file() return sha256(contents).hexdigest() def insert_metadata( self, entry_hash: str, basekey: str, value: str ) -> None: """Insert metadata into a file at lineno. Also, prevent duplicate keys. """ with self.lock: self.ledger.changed() entry: Directive = self.ledger.get_entry(entry_hash) key = next_key(basekey, entry.meta) indent = self.ledger.fava_options.indent insert_metadata_in_file( entry.meta["filename"], entry.meta["lineno"], indent, key, value, ) self.ledger.extensions.after_insert_metadata(entry, key, value) def save_entry_slice( self, entry_hash: str, source_slice: str, sha256sum: str ) -> str: """Save slice of the source file for an entry. Args: entry_hash: An entry. source_slice: The lines that the entry should be replaced with. sha256sum: The sha256sum of the current lines of the entry. Returns: The `sha256sum` of the new lines of the entry. Raises: FavaAPIException: If the entry is not found or the file changed. """ with self.lock: entry = self.ledger.get_entry(entry_hash) ret = save_entry_slice(entry, source_slice, sha256sum) self.ledger.extensions.after_entry_modified(entry, source_slice) return ret def insert_entries(self, entries: Entries) -> None: """Insert entries. Args: entries: A list of entries. """ with self.lock: self.ledger.changed() fava_options = self.ledger.fava_options for entry in sorted(entries, key=incomplete_sortkey): insert_options = fava_options.insert_entry currency_column = fava_options.currency_column indent = fava_options.indent fava_options.insert_entry = insert_entry( entry, self.ledger.beancount_file_path, insert_options, currency_column, indent, ) self.ledger.extensions.after_insert_entry(entry) def render_entries( self, entries: Entries ) -> Generator[Markup, None, None]: """Return entries in Beancount format. Only renders :class:`.Balance` and :class:`.Transaction`. Args: entries: A list of entries. Yields: The entries rendered in Beancount format. """ indent = self.ledger.fava_options.indent for entry in entries: if isinstance(entry, (Balance, Transaction)): if isinstance(entry, Transaction) and entry.flag in EXCL_FLAGS: continue try: yield Markup(get_entry_slice(entry)[0] + "\n") except (KeyError, FileNotFoundError): yield Markup( _format_entry( entry, self.ledger.fava_options.currency_column, indent, ) ) def incomplete_sortkey(entry: Directive) -> tuple[datetime.date, int]: """Sortkey for entries that might have incomplete metadata.""" return (entry.date, SORT_ORDER.get(type(entry), 0)) def insert_metadata_in_file( filename: str, lineno: int, indent: int, key: str, value: str ) -> None: """Inserts the specified metadata in the file below lineno, taking into account the whitespace in front of the line that lineno.""" with open(filename, encoding="utf-8") as file: contents = file.readlines() contents.insert(lineno, f'{" " * indent}{key}: "{value}"\n') with open(filename, "w", encoding="utf-8") as file: file.write("".join(contents)) def find_entry_lines(lines: list[str], lineno: int) -> list[str]: """Lines of entry starting at lineno. Args: lines: A list of lines. lineno: The 0-based line-index to start at. """ entry_lines = [lines[lineno]] while True: lineno += 1 try: line = lines[lineno] except IndexError: return entry_lines if not line.strip() or re.match(r"\S", line[0]): return entry_lines entry_lines.append(line) def get_entry_slice(entry: Directive) -> tuple[str, str]: """Get slice of the source file for an entry. Args: entry: An entry. Returns: A string containing the lines of the entry and the `sha256sum` of these lines. """ with open(entry.meta["filename"], encoding="utf-8") as file: lines = file.readlines() entry_lines = find_entry_lines(lines, entry.meta["lineno"] - 1) entry_source = "".join(entry_lines).rstrip("\n") return entry_source, sha256_str(entry_source) def save_entry_slice( entry: Directive, source_slice: str, sha256sum: str ) -> str: """Save slice of the source file for an entry. Args: entry: An entry. source_slice: The lines that the entry should be replaced with. sha256sum: The sha256sum of the current lines of the entry. Returns: The `sha256sum` of the new lines of the entry. Raises: FavaAPIException: If the file at `path` is not one of the source files. """ with open(entry.meta["filename"], encoding="utf-8") as file: lines = file.readlines() first_entry_line = entry.meta["lineno"] - 1 entry_lines = find_entry_lines(lines, first_entry_line) entry_source = "".join(entry_lines).rstrip("\n") if sha256_str(entry_source) != sha256sum: raise FavaAPIException("The file changed externally.") lines = ( lines[:first_entry_line] + [source_slice + "\n"] + lines[first_entry_line + len(entry_lines) :] ) with open(entry.meta["filename"], "w", encoding="utf-8") as file: file.writelines(lines) return sha256_str(source_slice) def insert_entry( entry: Directive, default_filename: str, insert_options: list[InsertEntryOption], currency_column: int, indent: int, ) -> list[InsertEntryOption]: """Insert an entry. Args: entry: An entry. default_filename: The default file to insert into if no option matches. insert_options: Insert options. currency_column: The column to align currencies at. indent: Number of indent spaces. Returns: A list of updated insert options. """ filename, lineno = find_insert_position( entry, insert_options, default_filename ) content = _format_entry(entry, currency_column, indent) with open(filename, encoding="utf-8") as file: contents = file.readlines() if lineno is None: # Appending contents += "\n" + content else: contents.insert(lineno, content + "\n") with open(filename, "w", encoding="utf-8") as file: file.writelines(contents) if lineno is None: return insert_options added_lines = content.count("\n") + 1 return [ option._replace(lineno=option.lineno + added_lines) if option.filename == filename and option.lineno > lineno else option for option in insert_options ] def _format_entry(entry: Directive, currency_column: int, indent: int) -> str: """Wrapper that strips unnecessary whitespace from format_entry.""" meta = { key: entry.meta[key] for key in entry.meta if not key.startswith("_") } entry = entry._replace(meta=meta) string = align(format_entry(entry, prefix=" " * indent), currency_column) string = string.replace("<class 'beancount.core.number.MISSING'>", "") return "\n".join(line.rstrip() for line in string.split("\n")) def find_insert_position( entry: Directive, insert_options: list[InsertEntryOption], default_filename: str, ) -> tuple[str, int | None]: """Find insert position for an entry. Args: entry: An entry. insert_options: A list of InsertOption. default_filename: The default file to insert into if no option matches. Returns: A tuple of the filename and the line number. """ # Get the list of accounts that should be considered for the entry. # For transactions, we want the reversed list of posting accounts. accounts = get_entry_accounts(entry) # Make no assumptions about the order of insert_options entries and instead # sort them ourselves (by descending dates) insert_options = sorted( insert_options, key=attrgetter("date"), reverse=True ) for account in accounts: for insert_option in insert_options: # Only consider InsertOptions before the entry date. if insert_option.date >= entry.date: continue if insert_option.re.match(account): return (insert_option.filename, insert_option.lineno - 1) return (default_filename, None)
xss
{ "code": [ " def render_entries(self, entries: Entries) -> Generator[str, None, None]:", " yield get_entry_slice(entry)[0] + \"\\n\"", " yield _format_entry(", " entry,", " self.ledger.fava_options.currency_column,", " indent," ], "line_no": [ 179, 196, 198, 199, 200, 201 ] }
{ "code": [ " def render_entries(", " ) -> Generator[Markup, None, None]:", " yield Markup(get_entry_slice(entry)[0] + \"\\n\")", " yield Markup(", " _format_entry(", " self.ledger.fava_options.currency_column,", " indent," ], "line_no": [ 180, 182, 199, 201, 202, 204, 205 ] }
from __future__ import annotations import datetime import re import threading from codecs import decode from codecs import encode from hashlib import sha256 from operator import attrgetter from typing import Generator from typing import TYPE_CHECKING from beancount.core.data import Balance from beancount.core.data import Directive from beancount.core.data import Entries from beancount.core.data import SORT_ORDER from beancount.core.data import Transaction from beancount.core.flags import FLAG_CONVERSIONS from beancount.core.flags import FLAG_MERGING from beancount.core.flags import FLAG_PADDING from beancount.core.flags import FLAG_SUMMARIZE from beancount.core.flags import FLAG_TRANSFER from beancount.parser.printer import format_entry # type: ignore from fava.core._compat import FLAG_RETURNS from fava.core._compat import FLAG_UNREALIZED from fava.core.accounts import get_entry_accounts from fava.core.fava_options import InsertEntryOption from fava.core.misc import align from fava.core.module_base import FavaModule from fava.helpers import FavaAPIException from fava.util import next_key if TYPE_CHECKING: # pragma: no cover from fava.core import FavaLedger VAR_0 = { FLAG_PADDING, # P FLAG_SUMMARIZE, # S FLAG_TRANSFER, # T FLAG_CONVERSIONS, # C FLAG_UNREALIZED, # U FLAG_RETURNS, # R FLAG_MERGING, # M } def FUNC_0(VAR_1: str) -> str: return sha256(encode(VAR_1, encoding="utf-8")).hexdigest() class CLASS_0(FavaModule): def __init__(self, VAR_14: FavaLedger) -> None: super().__init__(VAR_14) self.lock = threading.Lock() def FUNC_9(self, VAR_15: str) -> tuple[str, str]: if VAR_15 not in self.ledger.options["include"]: raise FavaAPIException("Trying to read a non-VAR_16 file") with open(VAR_15, mode="rb") as file: VAR_28 = file.read() VAR_10 = sha256(VAR_28).hexdigest() VAR_16 = decode(VAR_28) return VAR_16, VAR_10 def FUNC_10(self, VAR_15: str, VAR_16: str, VAR_10: str) -> str: with self.lock: VAR_29, VAR_30 = self.get_source(VAR_15) if VAR_30 != VAR_10: raise FavaAPIException("The file changed externally.") VAR_28 = encode(VAR_16, encoding="utf-8") with open(VAR_15, "w+b") as file: file.write(VAR_28) self.ledger.extensions.after_write_source(VAR_15, VAR_16) self.ledger.load_file() return sha256(VAR_28).hexdigest() def FUNC_11( self, VAR_17: str, VAR_18: str, VAR_7: str ) -> None: with self.lock: self.ledger.changed() VAR_2: Directive = self.ledger.get_entry(VAR_17) VAR_6 = next_key(VAR_18, VAR_2.meta) VAR_5 = self.ledger.fava_options.indent FUNC_2( VAR_2.meta["filename"], VAR_2.meta["lineno"], VAR_5, VAR_6, VAR_7, ) self.ledger.extensions.after_insert_metadata(VAR_2, VAR_6, VAR_7) def FUNC_5( self, VAR_17: str, VAR_9: str, VAR_10: str ) -> str: with self.lock: VAR_2 = self.ledger.get_entry(VAR_17) VAR_31 = FUNC_5(VAR_2, VAR_9, VAR_10) self.ledger.extensions.after_entry_modified(VAR_2, VAR_9) return VAR_31 def FUNC_12(self, VAR_19: Entries) -> None: with self.lock: self.ledger.changed() VAR_32 = self.ledger.fava_options for VAR_2 in sorted(VAR_19, VAR_6=FUNC_1): VAR_12 = VAR_32.insert_entry VAR_13 = VAR_32.currency_column VAR_5 = VAR_32.indent VAR_32.insert_entry = FUNC_6( VAR_2, self.ledger.beancount_file_path, VAR_12, VAR_13, VAR_5, ) self.ledger.extensions.after_insert_entry(VAR_2) def FUNC_13(self, VAR_19: Entries) -> Generator[str, None, None]: VAR_5 = self.ledger.fava_options.indent for VAR_2 in VAR_19: if isinstance(VAR_2, (Balance, Transaction)): if isinstance(VAR_2, Transaction) and VAR_2.flag in VAR_0: continue try: yield FUNC_4(VAR_2)[0] + "\n" except (KeyError, FileNotFoundError): yield FUNC_7( VAR_2, self.ledger.fava_options.currency_column, VAR_5, ) def FUNC_1(VAR_2: Directive) -> tuple[datetime.date, int]: return (VAR_2.date, SORT_ORDER.get(type(VAR_2), 0)) def FUNC_2( VAR_3: str, VAR_4: int, VAR_5: int, VAR_6: str, VAR_7: str ) -> None: with open(VAR_3, encoding="utf-8") as file: VAR_28 = file.readlines() VAR_28.insert(VAR_4, f'{" " * VAR_5}{VAR_6}: "{VAR_7}"\n') with open(VAR_3, "w", encoding="utf-8") as file: file.write("".join(VAR_28)) def FUNC_3(VAR_8: list[str], VAR_4: int) -> list[str]: VAR_20 = [VAR_8[VAR_4]] while True: VAR_4 += 1 try: VAR_33 = VAR_8[VAR_4] except IndexError: return VAR_20 if not VAR_33.strip() or re.match(r"\S", VAR_33[0]): return VAR_20 entry_lines.append(VAR_33) def FUNC_4(VAR_2: Directive) -> tuple[str, str]: with open(VAR_2.meta["filename"], encoding="utf-8") as file: VAR_8 = file.readlines() VAR_20 = FUNC_3(VAR_8, VAR_2.meta["lineno"] - 1) VAR_21 = "".join(VAR_20).rstrip("\n") return VAR_21, FUNC_0(VAR_21) def FUNC_5( VAR_2: Directive, VAR_9: str, VAR_10: str ) -> str: with open(VAR_2.meta["filename"], encoding="utf-8") as file: VAR_8 = file.readlines() VAR_22 = VAR_2.meta["lineno"] - 1 VAR_20 = FUNC_3(VAR_8, VAR_22) VAR_21 = "".join(VAR_20).rstrip("\n") if FUNC_0(VAR_21) != VAR_10: raise FavaAPIException("The file changed externally.") VAR_8 = ( lines[:VAR_22] + [VAR_9 + "\n"] + VAR_8[VAR_22 + len(VAR_20) :] ) with open(VAR_2.meta["filename"], "w", encoding="utf-8") as file: file.writelines(VAR_8) return FUNC_0(VAR_9) def FUNC_6( VAR_2: Directive, VAR_11: str, VAR_12: list[InsertEntryOption], VAR_13: int, VAR_5: int, ) -> list[InsertEntryOption]: VAR_3, VAR_4 = FUNC_8( VAR_2, VAR_12, VAR_11 ) VAR_23 = FUNC_7(VAR_2, VAR_13, VAR_5) with open(VAR_3, encoding="utf-8") as file: VAR_28 = file.readlines() if VAR_4 is None: VAR_28 += "\n" + VAR_23 else: VAR_28.insert(VAR_4, VAR_23 + "\n") with open(VAR_3, "w", encoding="utf-8") as file: file.writelines(VAR_28) if VAR_4 is None: return VAR_12 VAR_24 = VAR_23.count("\n") + 1 return [ option._replace(VAR_4=option.lineno + VAR_24) if option.filename == VAR_3 and option.lineno > VAR_4 else option for option in VAR_12 ] def FUNC_7(VAR_2: Directive, VAR_13: int, VAR_5: int) -> str: VAR_25 = { VAR_6: VAR_2.meta[VAR_6] for VAR_6 in VAR_2.meta if not VAR_6.startswith("_") } VAR_2 = VAR_2._replace(VAR_25=meta) VAR_26 = align(format_entry(VAR_2, prefix=" " * VAR_5), VAR_13) VAR_26 = VAR_26.replace("<class 'beancount.core.number.MISSING'>", "") return "\n".join(VAR_33.rstrip() for VAR_33 in VAR_26.split("\n")) def FUNC_8( VAR_2: Directive, VAR_12: list[InsertEntryOption], VAR_11: str, ) -> tuple[str, int | None]: VAR_27 = get_entry_accounts(VAR_2) VAR_12 = sorted( VAR_12, VAR_6=attrgetter("date"), reverse=True ) for account in VAR_27: for insert_option in VAR_12: if insert_option.date >= VAR_2.date: continue if insert_option.re.match(account): return (insert_option.filename, insert_option.lineno - 1) return (VAR_11, None)
from __future__ import annotations import datetime import re import threading from codecs import decode from codecs import encode from hashlib import sha256 from operator import attrgetter from typing import Generator from typing import TYPE_CHECKING from beancount.core.data import Balance from beancount.core.data import Directive from beancount.core.data import Entries from beancount.core.data import SORT_ORDER from beancount.core.data import Transaction from beancount.core.flags import FLAG_CONVERSIONS from beancount.core.flags import FLAG_MERGING from beancount.core.flags import FLAG_PADDING from beancount.core.flags import FLAG_SUMMARIZE from beancount.core.flags import FLAG_TRANSFER from beancount.parser.printer import format_entry # type: ignore from markupsafe import Markup from fava.core._compat import FLAG_RETURNS from fava.core._compat import FLAG_UNREALIZED from fava.core.accounts import get_entry_accounts from fava.core.fava_options import InsertEntryOption from fava.core.misc import align from fava.core.module_base import FavaModule from fava.helpers import FavaAPIException from fava.util import next_key if TYPE_CHECKING: # pragma: no cover from fava.core import FavaLedger VAR_0 = { FLAG_PADDING, # P FLAG_SUMMARIZE, # S FLAG_TRANSFER, # T FLAG_CONVERSIONS, # C FLAG_UNREALIZED, # U FLAG_RETURNS, # R FLAG_MERGING, # M } def FUNC_0(VAR_1: str) -> str: return sha256(encode(VAR_1, encoding="utf-8")).hexdigest() class CLASS_0(FavaModule): def __init__(self, VAR_14: FavaLedger) -> None: super().__init__(VAR_14) self.lock = threading.Lock() def FUNC_9(self, VAR_15: str) -> tuple[str, str]: if VAR_15 not in self.ledger.options["include"]: raise FavaAPIException("Trying to read a non-VAR_16 file") with open(VAR_15, mode="rb") as file: VAR_28 = file.read() VAR_10 = sha256(VAR_28).hexdigest() VAR_16 = decode(VAR_28) return VAR_16, VAR_10 def FUNC_10(self, VAR_15: str, VAR_16: str, VAR_10: str) -> str: with self.lock: VAR_29, VAR_30 = self.get_source(VAR_15) if VAR_30 != VAR_10: raise FavaAPIException("The file changed externally.") VAR_28 = encode(VAR_16, encoding="utf-8") with open(VAR_15, "w+b") as file: file.write(VAR_28) self.ledger.extensions.after_write_source(VAR_15, VAR_16) self.ledger.load_file() return sha256(VAR_28).hexdigest() def FUNC_11( self, VAR_17: str, VAR_18: str, VAR_7: str ) -> None: with self.lock: self.ledger.changed() VAR_2: Directive = self.ledger.get_entry(VAR_17) VAR_6 = next_key(VAR_18, VAR_2.meta) VAR_5 = self.ledger.fava_options.indent FUNC_2( VAR_2.meta["filename"], VAR_2.meta["lineno"], VAR_5, VAR_6, VAR_7, ) self.ledger.extensions.after_insert_metadata(VAR_2, VAR_6, VAR_7) def FUNC_5( self, VAR_17: str, VAR_9: str, VAR_10: str ) -> str: with self.lock: VAR_2 = self.ledger.get_entry(VAR_17) VAR_31 = FUNC_5(VAR_2, VAR_9, VAR_10) self.ledger.extensions.after_entry_modified(VAR_2, VAR_9) return VAR_31 def FUNC_12(self, VAR_19: Entries) -> None: with self.lock: self.ledger.changed() VAR_32 = self.ledger.fava_options for VAR_2 in sorted(VAR_19, VAR_6=FUNC_1): VAR_12 = VAR_32.insert_entry VAR_13 = VAR_32.currency_column VAR_5 = VAR_32.indent VAR_32.insert_entry = FUNC_6( VAR_2, self.ledger.beancount_file_path, VAR_12, VAR_13, VAR_5, ) self.ledger.extensions.after_insert_entry(VAR_2) def FUNC_13( self, VAR_19: Entries ) -> Generator[Markup, None, None]: VAR_5 = self.ledger.fava_options.indent for VAR_2 in VAR_19: if isinstance(VAR_2, (Balance, Transaction)): if isinstance(VAR_2, Transaction) and VAR_2.flag in VAR_0: continue try: yield Markup(FUNC_4(VAR_2)[0] + "\n") except (KeyError, FileNotFoundError): yield Markup( FUNC_7( VAR_2, self.ledger.fava_options.currency_column, VAR_5, ) ) def FUNC_1(VAR_2: Directive) -> tuple[datetime.date, int]: return (VAR_2.date, SORT_ORDER.get(type(VAR_2), 0)) def FUNC_2( VAR_3: str, VAR_4: int, VAR_5: int, VAR_6: str, VAR_7: str ) -> None: with open(VAR_3, encoding="utf-8") as file: VAR_28 = file.readlines() VAR_28.insert(VAR_4, f'{" " * VAR_5}{VAR_6}: "{VAR_7}"\n') with open(VAR_3, "w", encoding="utf-8") as file: file.write("".join(VAR_28)) def FUNC_3(VAR_8: list[str], VAR_4: int) -> list[str]: VAR_20 = [VAR_8[VAR_4]] while True: VAR_4 += 1 try: VAR_33 = VAR_8[VAR_4] except IndexError: return VAR_20 if not VAR_33.strip() or re.match(r"\S", VAR_33[0]): return VAR_20 entry_lines.append(VAR_33) def FUNC_4(VAR_2: Directive) -> tuple[str, str]: with open(VAR_2.meta["filename"], encoding="utf-8") as file: VAR_8 = file.readlines() VAR_20 = FUNC_3(VAR_8, VAR_2.meta["lineno"] - 1) VAR_21 = "".join(VAR_20).rstrip("\n") return VAR_21, FUNC_0(VAR_21) def FUNC_5( VAR_2: Directive, VAR_9: str, VAR_10: str ) -> str: with open(VAR_2.meta["filename"], encoding="utf-8") as file: VAR_8 = file.readlines() VAR_22 = VAR_2.meta["lineno"] - 1 VAR_20 = FUNC_3(VAR_8, VAR_22) VAR_21 = "".join(VAR_20).rstrip("\n") if FUNC_0(VAR_21) != VAR_10: raise FavaAPIException("The file changed externally.") VAR_8 = ( lines[:VAR_22] + [VAR_9 + "\n"] + VAR_8[VAR_22 + len(VAR_20) :] ) with open(VAR_2.meta["filename"], "w", encoding="utf-8") as file: file.writelines(VAR_8) return FUNC_0(VAR_9) def FUNC_6( VAR_2: Directive, VAR_11: str, VAR_12: list[InsertEntryOption], VAR_13: int, VAR_5: int, ) -> list[InsertEntryOption]: VAR_3, VAR_4 = FUNC_8( VAR_2, VAR_12, VAR_11 ) VAR_23 = FUNC_7(VAR_2, VAR_13, VAR_5) with open(VAR_3, encoding="utf-8") as file: VAR_28 = file.readlines() if VAR_4 is None: VAR_28 += "\n" + VAR_23 else: VAR_28.insert(VAR_4, VAR_23 + "\n") with open(VAR_3, "w", encoding="utf-8") as file: file.writelines(VAR_28) if VAR_4 is None: return VAR_12 VAR_24 = VAR_23.count("\n") + 1 return [ option._replace(VAR_4=option.lineno + VAR_24) if option.filename == VAR_3 and option.lineno > VAR_4 else option for option in VAR_12 ] def FUNC_7(VAR_2: Directive, VAR_13: int, VAR_5: int) -> str: VAR_25 = { VAR_6: VAR_2.meta[VAR_6] for VAR_6 in VAR_2.meta if not VAR_6.startswith("_") } VAR_2 = VAR_2._replace(VAR_25=meta) VAR_26 = align(format_entry(VAR_2, prefix=" " * VAR_5), VAR_13) VAR_26 = VAR_26.replace("<class 'beancount.core.number.MISSING'>", "") return "\n".join(VAR_33.rstrip() for VAR_33 in VAR_26.split("\n")) def FUNC_8( VAR_2: Directive, VAR_12: list[InsertEntryOption], VAR_11: str, ) -> tuple[str, int | None]: VAR_27 = get_entry_accounts(VAR_2) VAR_12 = sorted( VAR_12, VAR_6=attrgetter("date"), reverse=True ) for account in VAR_27: for insert_option in VAR_12: if insert_option.date >= VAR_2.date: continue if insert_option.re.match(account): return (insert_option.filename, insert_option.lineno - 1) return (VAR_11, None)
[ 3, 13, 25, 34, 37, 38, 48, 49, 53, 54, 57, 61, 64, 67, 70, 77, 80, 83, 85, 88, 93, 96, 105, 109, 112, 114, 119, 135, 140, 145, 156, 159, 178, 181, 183, 186, 203, 204, 208, 209, 217, 219, 222, 223, 226, 241, 242, 245, 248, 255, 258, 260, 261, 266, 271, 274, 279, 282, 288, 296, 298, 299, 308, 315, 323, 326, 328, 332, 335, 338, 346, 347, 357, 358, 365, 370, 374, 375, 376, 378, 379, 380, 384, 387, 392, 394, 1, 51, 56, 206, 213, 214, 225, 226, 227, 228, 229, 230, 244, 245, 246, 247, 248, 249, 250, 251, 252, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 349, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 118, 119, 120, 121, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 158, 159, 160, 161, 162, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189 ]
[ 3, 13, 26, 35, 38, 39, 49, 50, 54, 55, 58, 62, 65, 68, 71, 78, 81, 84, 86, 89, 94, 97, 106, 110, 113, 115, 120, 136, 141, 146, 157, 160, 179, 184, 186, 189, 208, 209, 213, 214, 222, 224, 227, 228, 231, 246, 247, 250, 253, 260, 263, 265, 266, 271, 276, 279, 284, 287, 293, 301, 303, 304, 313, 320, 328, 331, 333, 337, 340, 343, 351, 352, 362, 363, 370, 375, 379, 380, 381, 383, 384, 385, 389, 392, 397, 399, 1, 52, 57, 211, 218, 219, 230, 231, 232, 233, 234, 235, 249, 250, 251, 252, 253, 254, 255, 256, 257, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 354, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 119, 120, 121, 122, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 159, 160, 161, 162, 163, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192 ]
2CWE-89
from django.db.models.expressions import F, OrderBy class OrderableAggMixin: def __init__(self, expression, ordering=(), **extra): if not isinstance(ordering, (list, tuple)): ordering = [ordering] ordering = ordering or [] # Transform minus sign prefixed strings into an OrderBy() expression. ordering = ( (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in ordering ) super().__init__(expression, **extra) self.ordering = self._parse_expressions(*ordering) def resolve_expression(self, *args, **kwargs): self.ordering = [expr.resolve_expression(*args, **kwargs) for expr in self.ordering] return super().resolve_expression(*args, **kwargs) def as_sql(self, compiler, connection): if self.ordering: ordering_params = [] ordering_expr_sql = [] for expr in self.ordering: expr_sql, expr_params = expr.as_sql(compiler, connection) ordering_expr_sql.append(expr_sql) ordering_params.extend(expr_params) sql, sql_params = super().as_sql(compiler, connection, ordering=( 'ORDER BY ' + ', '.join(ordering_expr_sql) )) return sql, sql_params + ordering_params return super().as_sql(compiler, connection, ordering='') def set_source_expressions(self, exprs): # Extract the ordering expressions because ORDER BY clause is handled # in a custom way. self.ordering = exprs[self._get_ordering_expressions_index():] return super().set_source_expressions(exprs[:self._get_ordering_expressions_index()]) def get_source_expressions(self): return super().get_source_expressions() + self.ordering def _get_ordering_expressions_index(self): """Return the index at which the ordering expressions start.""" source_expressions = self.get_source_expressions() return len(source_expressions) - len(self.ordering)
from django.db.models.expressions import F, OrderBy class OrderableAggMixin: def __init__(self, *expressions, ordering=(), **extra): if not isinstance(ordering, (list, tuple)): ordering = [ordering] ordering = ordering or [] # Transform minus sign prefixed strings into an OrderBy() expression. ordering = ( (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in ordering ) super().__init__(*expressions, **extra) self.ordering = self._parse_expressions(*ordering) def resolve_expression(self, *args, **kwargs): self.ordering = [expr.resolve_expression(*args, **kwargs) for expr in self.ordering] return super().resolve_expression(*args, **kwargs) def as_sql(self, compiler, connection): if self.ordering: ordering_params = [] ordering_expr_sql = [] for expr in self.ordering: expr_sql, expr_params = expr.as_sql(compiler, connection) ordering_expr_sql.append(expr_sql) ordering_params.extend(expr_params) sql, sql_params = super().as_sql(compiler, connection, ordering=( 'ORDER BY ' + ', '.join(ordering_expr_sql) )) return sql, sql_params + ordering_params return super().as_sql(compiler, connection, ordering='') def set_source_expressions(self, exprs): # Extract the ordering expressions because ORDER BY clause is handled # in a custom way. self.ordering = exprs[self._get_ordering_expressions_index():] return super().set_source_expressions(exprs[:self._get_ordering_expressions_index()]) def get_source_expressions(self): return super().get_source_expressions() + self.ordering def _get_ordering_expressions_index(self): """Return the index at which the ordering expressions start.""" source_expressions = self.get_source_expressions() return len(source_expressions) - len(self.ordering)
sql
{ "code": [ " def __init__(self, expression, ordering=(), **extra):", " super().__init__(expression, **extra)" ], "line_no": [ 6, 15 ] }
{ "code": [ " def __init__(self, *expressions, ordering=(), **extra):", " super().__init__(*expressions, **extra)" ], "line_no": [ 6, 15 ] }
from django.db.models.expressions import F, OrderBy class CLASS_0: def __init__(self, VAR_0, VAR_1=(), **VAR_2): if not isinstance(VAR_1, (list, tuple)): VAR_1 = [ordering] VAR_1 = VAR_1 or [] VAR_1 = ( (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in VAR_1 ) super().__init__(VAR_0, **VAR_2) self.ordering = self._parse_expressions(*VAR_1) def FUNC_0(self, *VAR_3, **VAR_4): self.ordering = [expr.resolve_expression(*VAR_3, **VAR_4) for expr in self.ordering] return super().resolve_expression(*VAR_3, **VAR_4) def FUNC_1(self, VAR_5, VAR_6): if self.ordering: VAR_9 = [] VAR_10 = [] for expr in self.ordering: VAR_13, VAR_14 = expr.as_sql(VAR_5, VAR_6) VAR_10.append(VAR_13) VAR_9.extend(VAR_14) VAR_11, VAR_12 = super().as_sql(VAR_5, VAR_6, VAR_1=( 'ORDER BY ' + ', '.join(VAR_10) )) return VAR_11, VAR_12 + VAR_9 return super().as_sql(VAR_5, VAR_6, VAR_1='') def FUNC_2(self, VAR_7): self.ordering = VAR_7[self._get_ordering_expressions_index():] return super().set_source_expressions(VAR_7[:self._get_ordering_expressions_index()]) def FUNC_3(self): return super().get_source_expressions() + self.ordering def FUNC_4(self): VAR_8 = self.get_source_expressions() return len(VAR_8) - len(self.ordering)
from django.db.models.expressions import F, OrderBy class CLASS_0: def __init__(self, *VAR_0, VAR_1=(), **VAR_2): if not isinstance(VAR_1, (list, tuple)): VAR_1 = [ordering] VAR_1 = VAR_1 or [] VAR_1 = ( (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in VAR_1 ) super().__init__(*VAR_0, **VAR_2) self.ordering = self._parse_expressions(*VAR_1) def FUNC_0(self, *VAR_3, **VAR_4): self.ordering = [expr.resolve_expression(*VAR_3, **VAR_4) for expr in self.ordering] return super().resolve_expression(*VAR_3, **VAR_4) def FUNC_1(self, VAR_5, VAR_6): if self.ordering: VAR_9 = [] VAR_10 = [] for expr in self.ordering: VAR_13, VAR_14 = expr.as_sql(VAR_5, VAR_6) VAR_10.append(VAR_13) VAR_9.extend(VAR_14) VAR_11, VAR_12 = super().as_sql(VAR_5, VAR_6, VAR_1=( 'ORDER BY ' + ', '.join(VAR_10) )) return VAR_11, VAR_12 + VAR_9 return super().as_sql(VAR_5, VAR_6, VAR_1='') def FUNC_2(self, VAR_7): self.ordering = VAR_7[self._get_ordering_expressions_index():] return super().set_source_expressions(VAR_7[:self._get_ordering_expressions_index()]) def FUNC_3(self): return super().get_source_expressions() + self.ordering def FUNC_4(self): VAR_8 = self.get_source_expressions() return len(VAR_8) - len(self.ordering)
[ 2, 3, 5, 10, 17, 21, 35, 37, 38, 41, 44, 49, 46 ]
[ 2, 3, 5, 10, 17, 21, 35, 37, 38, 41, 44, 49, 46 ]
3CWE-352
# -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, # andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, # falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, # ruben-herold, marblepebble, JackED42, SiphonSquirrel, # apetresc, nanu-c, mutschler # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os from datetime import datetime import json from shutil import copyfile from uuid import uuid4 from markupsafe import escape try: from lxml.html.clean import clean_html except ImportError: pass # Improve this to check if scholarly is available in a global way, like other pythonic libraries try: from scholarly import scholarly have_scholar = True except ImportError: have_scholar = False from flask import Blueprint, request, flash, redirect, url_for, abort, Markup, Response from flask_babel import gettext as _ from flask_login import current_user, login_required from sqlalchemy.exc import OperationalError, IntegrityError from sqlite3 import OperationalError as sqliteOperationalError from . import constants, logger, isoLanguages, gdriveutils, uploader, helper, kobo_sync_status from . import config, get_locale, ub, db from . import calibre_db from .services.worker import WorkerThread from .tasks.upload import TaskUpload from .render_template import render_title_template from .usermanagement import login_required_if_no_ano try: from functools import wraps except ImportError: pass # We're not using Python 3 editbook = Blueprint('editbook', __name__) log = logger.create() def upload_required(f): @wraps(f) def inner(*args, **kwargs): if current_user.role_upload(): return f(*args, **kwargs) abort(403) return inner def edit_required(f): @wraps(f) def inner(*args, **kwargs): if current_user.role_edit() or current_user.role_admin(): return f(*args, **kwargs) abort(403) return inner def search_objects_remove(db_book_object, db_type, input_elements): del_elements = [] for c_elements in db_book_object: found = False if db_type == 'languages': type_elements = c_elements.lang_code elif db_type == 'custom': type_elements = c_elements.value else: type_elements = c_elements.name for inp_element in input_elements: if inp_element.lower() == type_elements.lower(): # if inp_element == type_elements: found = True break # if the element was not found in the new list, add it to remove list if not found: del_elements.append(c_elements) return del_elements def search_objects_add(db_book_object, db_type, input_elements): add_elements = [] for inp_element in input_elements: found = False for c_elements in db_book_object: if db_type == 'languages': type_elements = c_elements.lang_code elif db_type == 'custom': type_elements = c_elements.value else: type_elements = c_elements.name if inp_element == type_elements: found = True break if not found: add_elements.append(inp_element) return add_elements def remove_objects(db_book_object, db_session, del_elements): changed = False if len(del_elements) > 0: for del_element in del_elements: db_book_object.remove(del_element) changed = True if len(del_element.books) == 0: db_session.delete(del_element) return changed def add_objects(db_book_object, db_object, db_session, db_type, add_elements): changed = False if db_type == 'languages': db_filter = db_object.lang_code elif db_type == 'custom': db_filter = db_object.value else: db_filter = db_object.name for add_element in add_elements: # check if a element with that name exists db_element = db_session.query(db_object).filter(db_filter == add_element).first() # if no element is found add it # if new_element is None: if db_type == 'author': new_element = db_object(add_element, helper.get_sorted_author(add_element.replace('|', ',')), "") elif db_type == 'series': new_element = db_object(add_element, add_element) elif db_type == 'custom': new_element = db_object(value=add_element) elif db_type == 'publisher': new_element = db_object(add_element, None) else: # db_type should be tag or language new_element = db_object(add_element) if db_element is None: changed = True db_session.add(new_element) db_book_object.append(new_element) else: db_element = create_objects_for_addition(db_element, add_element, db_type) changed = True # add element to book changed = True db_book_object.append(db_element) return changed def create_objects_for_addition(db_element, add_element, db_type): if db_type == 'custom': if db_element.value != add_element: db_element.value = add_element # ToDo: Before new_element, but this is not plausible elif db_type == 'languages': if db_element.lang_code != add_element: db_element.lang_code = add_element elif db_type == 'series': if db_element.name != add_element: db_element.name = add_element db_element.sort = add_element elif db_type == 'author': if db_element.name != add_element: db_element.name = add_element db_element.sort = add_element.replace('|', ',') elif db_type == 'publisher': if db_element.name != add_element: db_element.name = add_element db_element.sort = None elif db_element.name != add_element: db_element.name = add_element return db_element # Modifies different Database objects, first check if elements if elements have to be deleted, # because they are no longer used, than check if elements have to be added to database def modify_database_object(input_elements, db_book_object, db_object, db_session, db_type): # passing input_elements not as a list may lead to undesired results if not isinstance(input_elements, list): raise TypeError(str(input_elements) + " should be passed as a list") input_elements = [x for x in input_elements if x != ''] # we have all input element (authors, series, tags) names now # 1. search for elements to remove del_elements = search_objects_remove(db_book_object, db_type, input_elements) # 2. search for elements that need to be added add_elements = search_objects_add(db_book_object, db_type, input_elements) # if there are elements to remove, we remove them now changed = remove_objects(db_book_object, db_session, del_elements) # if there are elements to add, we add them now! if len(add_elements) > 0: changed |= add_objects(db_book_object, db_object, db_session, db_type, add_elements) return changed def modify_identifiers(input_identifiers, db_identifiers, db_session): """Modify Identifiers to match input information. input_identifiers is a list of read-to-persist Identifiers objects. db_identifiers is a list of already persisted list of Identifiers objects.""" changed = False error = False input_dict = dict([(identifier.type.lower(), identifier) for identifier in input_identifiers]) if len(input_identifiers) != len(input_dict): error = True db_dict = dict([(identifier.type.lower(), identifier) for identifier in db_identifiers ]) # delete db identifiers not present in input or modify them with input val for identifier_type, identifier in db_dict.items(): if identifier_type not in input_dict.keys(): db_session.delete(identifier) changed = True else: input_identifier = input_dict[identifier_type] identifier.type = input_identifier.type identifier.val = input_identifier.val # add input identifiers not present in db for identifier_type, identifier in input_dict.items(): if identifier_type not in db_dict.keys(): db_session.add(identifier) changed = True return changed, error @editbook.route("/ajax/delete/<int:book_id>") @login_required def delete_book_from_details(book_id): return Response(delete_book_from_table(book_id, "", True), mimetype='application/json') @editbook.route("/delete/<int:book_id>", defaults={'book_format': ""}) @editbook.route("/delete/<int:book_id>/<string:book_format>") @login_required def delete_book_ajax(book_id, book_format): return delete_book_from_table(book_id, book_format, False) def delete_whole_book(book_id, book): # delete book from Shelfs, Downloads, Read list ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).delete() ub.session.query(ub.ReadBook).filter(ub.ReadBook.book_id == book_id).delete() ub.delete_download(book_id) ub.session_commit() # check if only this book links to: # author, language, series, tags, custom columns modify_database_object([u''], book.authors, db.Authors, calibre_db.session, 'author') modify_database_object([u''], book.tags, db.Tags, calibre_db.session, 'tags') modify_database_object([u''], book.series, db.Series, calibre_db.session, 'series') modify_database_object([u''], book.languages, db.Languages, calibre_db.session, 'languages') modify_database_object([u''], book.publishers, db.Publishers, calibre_db.session, 'publishers') cc = calibre_db.session.query(db.Custom_Columns). \ filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() for c in cc: cc_string = "custom_column_" + str(c.id) if not c.is_multiple: if len(getattr(book, cc_string)) > 0: if c.datatype == 'bool' or c.datatype == 'integer' or c.datatype == 'float': del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) log.debug('remove ' + str(c.id)) calibre_db.session.delete(del_cc) calibre_db.session.commit() elif c.datatype == 'rating': del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) if len(del_cc.books) == 0: log.debug('remove ' + str(c.id)) calibre_db.session.delete(del_cc) calibre_db.session.commit() else: del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) log.debug('remove ' + str(c.id)) calibre_db.session.delete(del_cc) calibre_db.session.commit() else: modify_database_object([u''], getattr(book, cc_string), db.cc_classes[c.id], calibre_db.session, 'custom') calibre_db.session.query(db.Books).filter(db.Books.id == book_id).delete() def render_delete_book_result(book_format, jsonResponse, warning, book_id): if book_format: if jsonResponse: return json.dumps([warning, {"location": url_for("editbook.edit_book", book_id=book_id), "type": "success", "format": book_format, "message": _('Book Format Successfully Deleted')}]) else: flash(_('Book Format Successfully Deleted'), category="success") return redirect(url_for('editbook.edit_book', book_id=book_id)) else: if jsonResponse: return json.dumps([warning, {"location": url_for('web.index'), "type": "success", "format": book_format, "message": _('Book Successfully Deleted')}]) else: flash(_('Book Successfully Deleted'), category="success") return redirect(url_for('web.index')) def delete_book_from_table(book_id, book_format, jsonResponse): warning = {} if current_user.role_delete_books(): book = calibre_db.get_book(book_id) if book: try: result, error = helper.delete_book(book, config.config_calibre_dir, book_format=book_format.upper()) if not result: if jsonResponse: return json.dumps([{"location": url_for("editbook.edit_book", book_id=book_id), "type": "danger", "format": "", "message": error}]) else: flash(error, category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) if error: if jsonResponse: warning = {"location": url_for("editbook.edit_book", book_id=book_id), "type": "warning", "format": "", "message": error} else: flash(error, category="warning") if not book_format: delete_whole_book(book_id, book) else: calibre_db.session.query(db.Data).filter(db.Data.book == book.id).\ filter(db.Data.format == book_format).delete() calibre_db.session.commit() except Exception as ex: log.debug_or_exception(ex) calibre_db.session.rollback() if jsonResponse: return json.dumps([{"location": url_for("editbook.edit_book", book_id=book_id), "type": "danger", "format": "", "message": ex}]) else: flash(str(ex), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) else: # book not found log.error('Book with id "%s" could not be deleted: not found', book_id) return render_delete_book_result(book_format, jsonResponse, warning, book_id) def render_edit_book(book_id): cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() book = calibre_db.get_filtered_book(book_id, allow_show_archived=True) if not book: flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) for lang in book.languages: lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code) book = calibre_db.order_authors(book) author_names = [] for authr in book.authors: author_names.append(authr.name.replace('|', ',')) # Option for showing convertbook button valid_source_formats=list() allowed_conversion_formats = list() kepub_possible=None if config.config_converterpath: for file in book.data: if file.format.lower() in constants.EXTENSIONS_CONVERT_FROM: valid_source_formats.append(file.format.lower()) if config.config_kepubifypath and 'epub' in [file.format.lower() for file in book.data]: kepub_possible = True if not config.config_converterpath: valid_source_formats.append('epub') # Determine what formats don't already exist if config.config_converterpath: allowed_conversion_formats = constants.EXTENSIONS_CONVERT_TO[:] for file in book.data: if file.format.lower() in allowed_conversion_formats: allowed_conversion_formats.remove(file.format.lower()) if kepub_possible: allowed_conversion_formats.append('kepub') return render_title_template('book_edit.html', book=book, authors=author_names, cc=cc, title=_(u"edit metadata"), page="editbook", conversion_formats=allowed_conversion_formats, config=config, source_formats=valid_source_formats) def edit_book_ratings(to_save, book): changed = False if to_save["rating"].strip(): old_rating = False if len(book.ratings) > 0: old_rating = book.ratings[0].rating ratingx2 = int(float(to_save["rating"]) * 2) if ratingx2 != old_rating: changed = True is_rating = calibre_db.session.query(db.Ratings).filter(db.Ratings.rating == ratingx2).first() if is_rating: book.ratings.append(is_rating) else: new_rating = db.Ratings(rating=ratingx2) book.ratings.append(new_rating) if old_rating: book.ratings.remove(book.ratings[0]) else: if len(book.ratings) > 0: book.ratings.remove(book.ratings[0]) changed = True return changed def edit_book_tags(tags, book): input_tags = tags.split(',') input_tags = list(map(lambda it: it.strip(), input_tags)) # Remove duplicates input_tags = helper.uniq(input_tags) return modify_database_object(input_tags, book.tags, db.Tags, calibre_db.session, 'tags') def edit_book_series(series, book): input_series = [series.strip()] input_series = [x for x in input_series if x != ''] return modify_database_object(input_series, book.series, db.Series, calibre_db.session, 'series') def edit_book_series_index(series_index, book): # Add default series_index to book modif_date = False series_index = series_index or '1' if not series_index.replace('.', '', 1).isdigit(): flash(_("%(seriesindex)s is not a valid number, skipping", seriesindex=series_index), category="warning") return False if str(book.series_index) != series_index: book.series_index = series_index modif_date = True return modif_date # Handle book comments/description def edit_book_comments(comments, book): modif_date = False if comments: comments = clean_html(comments) if len(book.comments): if book.comments[0].text != comments: book.comments[0].text = comments modif_date = True else: if comments: book.comments.append(db.Comments(text=comments, book=book.id)) modif_date = True return modif_date def edit_book_languages(languages, book, upload=False, invalid=None): input_languages = languages.split(',') unknown_languages = [] if not upload: input_l = isoLanguages.get_language_codes(get_locale(), input_languages, unknown_languages) else: input_l = isoLanguages.get_valid_language_codes(get_locale(), input_languages, unknown_languages) for l in unknown_languages: log.error("'%s' is not a valid language", l) if isinstance(invalid, list): invalid.append(l) else: raise ValueError(_(u"'%(langname)s' is not a valid language", langname=l)) # ToDo: Not working correct if upload and len(input_l) == 1: # If the language of the file is excluded from the users view, it's not imported, to allow the user to view # the book it's language is set to the filter language if input_l[0] != current_user.filter_language() and current_user.filter_language() != "all": input_l[0] = calibre_db.session.query(db.Languages). \ filter(db.Languages.lang_code == current_user.filter_language()).first().lang_code # Remove duplicates input_l = helper.uniq(input_l) return modify_database_object(input_l, book.languages, db.Languages, calibre_db.session, 'languages') def edit_book_publisher(publishers, book): changed = False if publishers: publisher = publishers.rstrip().strip() if len(book.publishers) == 0 or (len(book.publishers) > 0 and publisher != book.publishers[0].name): changed |= modify_database_object([publisher], book.publishers, db.Publishers, calibre_db.session, 'publisher') elif len(book.publishers): changed |= modify_database_object([], book.publishers, db.Publishers, calibre_db.session, 'publisher') return changed def edit_cc_data_value(book_id, book, c, to_save, cc_db_value, cc_string): changed = False if to_save[cc_string] == 'None': to_save[cc_string] = None elif c.datatype == 'bool': to_save[cc_string] = 1 if to_save[cc_string] == 'True' else 0 elif c.datatype == 'comments': to_save[cc_string] = Markup(to_save[cc_string]).unescape() if to_save[cc_string]: to_save[cc_string] = clean_html(to_save[cc_string]) elif c.datatype == 'datetime': try: to_save[cc_string] = datetime.strptime(to_save[cc_string], "%Y-%m-%d") except ValueError: to_save[cc_string] = db.Books.DEFAULT_PUBDATE if to_save[cc_string] != cc_db_value: if cc_db_value is not None: if to_save[cc_string] is not None: setattr(getattr(book, cc_string)[0], 'value', to_save[cc_string]) changed = True else: del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) calibre_db.session.delete(del_cc) changed = True else: cc_class = db.cc_classes[c.id] new_cc = cc_class(value=to_save[cc_string], book=book_id) calibre_db.session.add(new_cc) changed = True return changed, to_save def edit_cc_data_string(book, c, to_save, cc_db_value, cc_string): changed = False if c.datatype == 'rating': to_save[cc_string] = str(int(float(to_save[cc_string]) * 2)) if to_save[cc_string].strip() != cc_db_value: if cc_db_value is not None: # remove old cc_val del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) if len(del_cc.books) == 0: calibre_db.session.delete(del_cc) changed = True cc_class = db.cc_classes[c.id] new_cc = calibre_db.session.query(cc_class).filter( cc_class.value == to_save[cc_string].strip()).first() # if no cc val is found add it if new_cc is None: new_cc = cc_class(value=to_save[cc_string].strip()) calibre_db.session.add(new_cc) changed = True calibre_db.session.flush() new_cc = calibre_db.session.query(cc_class).filter( cc_class.value == to_save[cc_string].strip()).first() # add cc value to book getattr(book, cc_string).append(new_cc) return changed, to_save def edit_single_cc_data(book_id, book, column_id, to_save): cc = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)) .filter(db.Custom_Columns.id == column_id) .all()) return edit_cc_data(book_id, book, to_save, cc) def edit_all_cc_data(book_id, book, to_save): cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() return edit_cc_data(book_id, book, to_save, cc) def edit_cc_data(book_id, book, to_save, cc): changed = False for c in cc: cc_string = "custom_column_" + str(c.id) if not c.is_multiple: if len(getattr(book, cc_string)) > 0: cc_db_value = getattr(book, cc_string)[0].value else: cc_db_value = None if to_save[cc_string].strip(): if c.datatype in ['int', 'bool', 'float', "datetime", "comments"]: changed, to_save = edit_cc_data_value(book_id, book, c, to_save, cc_db_value, cc_string) else: changed, to_save = edit_cc_data_string(book, c, to_save, cc_db_value, cc_string) else: if cc_db_value is not None: # remove old cc_val del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) if not del_cc.books or len(del_cc.books) == 0: calibre_db.session.delete(del_cc) changed = True else: input_tags = to_save[cc_string].split(',') input_tags = list(map(lambda it: it.strip(), input_tags)) changed |= modify_database_object(input_tags, getattr(book, cc_string), db.cc_classes[c.id], calibre_db.session, 'custom') return changed def upload_single_file(request, book, book_id): # Check and handle Uploaded file if 'btn-upload-format' in request.files: requested_file = request.files['btn-upload-format'] # check for empty request if requested_file.filename != '': if not current_user.role_upload(): abort(403) if '.' in requested_file.filename: file_ext = requested_file.filename.rsplit('.', 1)[-1].lower() if file_ext not in constants.EXTENSIONS_UPLOAD and '' not in constants.EXTENSIONS_UPLOAD: flash(_("File extension '%(ext)s' is not allowed to be uploaded to this server", ext=file_ext), category="error") return redirect(url_for('web.show_book', book_id=book.id)) else: flash(_('File to be uploaded must have an extension'), category="error") return redirect(url_for('web.show_book', book_id=book.id)) file_name = book.path.rsplit('/', 1)[-1] filepath = os.path.normpath(os.path.join(config.config_calibre_dir, book.path)) saved_filename = os.path.join(filepath, file_name + '.' + file_ext) # check if file path exists, otherwise create it, copy file to calibre path and delete temp file if not os.path.exists(filepath): try: os.makedirs(filepath) except OSError: flash(_(u"Failed to create path %(path)s (Permission denied).", path=filepath), category="error") return redirect(url_for('web.show_book', book_id=book.id)) try: requested_file.save(saved_filename) except OSError: flash(_(u"Failed to store file %(file)s.", file=saved_filename), category="error") return redirect(url_for('web.show_book', book_id=book.id)) file_size = os.path.getsize(saved_filename) is_format = calibre_db.get_book_format(book_id, file_ext.upper()) # Format entry already exists, no need to update the database if is_format: log.warning('Book format %s already existing', file_ext.upper()) else: try: db_format = db.Data(book_id, file_ext.upper(), file_size, file_name) calibre_db.session.add(db_format) calibre_db.session.commit() calibre_db.update_title_sort(config) except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() log.error('Database error: %s', e) flash(_(u"Database error: %(error)s.", error=e), category="error") return redirect(url_for('web.show_book', book_id=book.id)) # Queue uploader info link = '<a href="{}">{}</a>'.format(url_for('web.show_book', book_id=book.id), escape(book.title)) uploadText=_(u"File format %(ext)s added to %(book)s", ext=file_ext.upper(), book=link) WorkerThread.add(current_user.name, TaskUpload(uploadText)) return uploader.process( saved_filename, *os.path.splitext(requested_file.filename), rarExecutable=config.config_rarfile_location) def upload_cover(request, book): if 'btn-upload-cover' in request.files: requested_file = request.files['btn-upload-cover'] # check for empty request if requested_file.filename != '': if not current_user.role_upload(): abort(403) ret, message = helper.save_cover(requested_file, book.path) if ret is True: return True else: flash(message, category="error") return False return None def handle_title_on_edit(book, book_title): # handle book title book_title = book_title.rstrip().strip() if book.title != book_title: if book_title == '': book_title = _(u'Unknown') book.title = book_title return True return False def handle_author_on_edit(book, author_name, update_stored=True): # handle author(s) input_authors = author_name.split('&') input_authors = list(map(lambda it: it.strip().replace(',', '|'), input_authors)) # Remove duplicates in authors list input_authors = helper.uniq(input_authors) # we have all author names now if input_authors == ['']: input_authors = [_(u'Unknown')] # prevent empty Author change = modify_database_object(input_authors, book.authors, db.Authors, calibre_db.session, 'author') # Search for each author if author is in database, if not, author name and sorted author name is generated new # everything then is assembled for sorted author field in database sort_authors_list = list() for inp in input_authors: stored_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == inp).first() if not stored_author: stored_author = helper.get_sorted_author(inp) else: stored_author = stored_author.sort sort_authors_list.append(helper.get_sorted_author(stored_author)) sort_authors = ' & '.join(sort_authors_list) if book.author_sort != sort_authors and update_stored: book.author_sort = sort_authors change = True return input_authors, change @editbook.route("/admin/book/<int:book_id>", methods=['GET', 'POST']) @login_required_if_no_ano @edit_required def edit_book(book_id): modif_date = False # create the function for sorting... try: calibre_db.update_title_sort(config) except sqliteOperationalError as e: log.debug_or_exception(e) calibre_db.session.rollback() # Show form if request.method != 'POST': return render_edit_book(book_id) book = calibre_db.get_filtered_book(book_id, allow_show_archived=True) # Book not found if not book: flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) meta = upload_single_file(request, book, book_id) if upload_cover(request, book) is True: book.has_cover = 1 modif_date = True try: to_save = request.form.to_dict() merge_metadata(to_save, meta) # Update book edited_books_id = None # handle book title title_change = handle_title_on_edit(book, to_save["book_title"]) input_authors, authorchange = handle_author_on_edit(book, to_save["author_name"]) if authorchange or title_change: edited_books_id = book.id modif_date = True if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() error = False if edited_books_id: error = helper.update_dir_stucture(edited_books_id, config.config_calibre_dir, input_authors[0]) if not error: if "cover_url" in to_save: if to_save["cover_url"]: if not current_user.role_upload(): return "", (403) if to_save["cover_url"].endswith('/static/generic_cover.jpg'): book.has_cover = 0 else: result, error = helper.save_cover_from_url(to_save["cover_url"], book.path) if result is True: book.has_cover = 1 modif_date = True else: flash(error, category="error") # Add default series_index to book modif_date |= edit_book_series_index(to_save["series_index"], book) # Handle book comments/description modif_date |= edit_book_comments(Markup(to_save['description']).unescape(), book) # Handle identifiers input_identifiers = identifier_list(to_save, book) modification, warning = modify_identifiers(input_identifiers, book.identifiers, calibre_db.session) if warning: flash(_("Identifiers are not Case Sensitive, Overwriting Old Identifier"), category="warning") modif_date |= modification # Handle book tags modif_date |= edit_book_tags(to_save['tags'], book) # Handle book series modif_date |= edit_book_series(to_save["series"], book) # handle book publisher modif_date |= edit_book_publisher(to_save['publisher'], book) # handle book languages modif_date |= edit_book_languages(to_save['languages'], book) # handle book ratings modif_date |= edit_book_ratings(to_save, book) # handle cc data modif_date |= edit_all_cc_data(book_id, book, to_save) if to_save["pubdate"]: try: book.pubdate = datetime.strptime(to_save["pubdate"], "%Y-%m-%d") except ValueError: book.pubdate = db.Books.DEFAULT_PUBDATE else: book.pubdate = db.Books.DEFAULT_PUBDATE if modif_date: book.last_modified = datetime.utcnow() kobo_sync_status.remove_synced_book(edited_books_id) calibre_db.session.merge(book) calibre_db.session.commit() if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if "detail_view" in to_save: return redirect(url_for('web.show_book', book_id=book.id)) else: flash(_("Metadata successfully updated"), category="success") return render_edit_book(book_id) else: calibre_db.session.rollback() flash(error, category="error") return render_edit_book(book_id) except ValueError as e: calibre_db.session.rollback() flash(str(e), category="error") return redirect(url_for('web.show_book', book_id=book.id)) except Exception as ex: log.debug_or_exception(ex) calibre_db.session.rollback() flash(_("Error editing book, please check logfile for details"), category="error") return redirect(url_for('web.show_book', book_id=book.id)) def merge_metadata(to_save, meta): if to_save['author_name'] == _(u'Unknown'): to_save['author_name'] = '' if to_save['book_title'] == _(u'Unknown'): to_save['book_title'] = '' for s_field, m_field in [ ('tags', 'tags'), ('author_name', 'author'), ('series', 'series'), ('series_index', 'series_id'), ('languages', 'languages'), ('book_title', 'title')]: to_save[s_field] = to_save[s_field] or getattr(meta, m_field, '') to_save["description"] = to_save["description"] or Markup( getattr(meta, 'description', '')).unescape() def identifier_list(to_save, book): """Generate a list of Identifiers from form information""" id_type_prefix = 'identifier-type-' id_val_prefix = 'identifier-val-' result = [] for type_key, type_value in to_save.items(): if not type_key.startswith(id_type_prefix): continue val_key = id_val_prefix + type_key[len(id_type_prefix):] if val_key not in to_save.keys(): continue result.append(db.Identifiers(to_save[val_key], type_value, book.id)) return result def prepare_authors_on_upload(title, authr): if title != _(u'Unknown') and authr != _(u'Unknown'): entry = calibre_db.check_exists_book(authr, title) if entry: log.info("Uploaded book probably exists in library") flash(_(u"Uploaded book probably exists in the library, consider to change before upload new: ") + Markup(render_title_template('book_exists_flash.html', entry=entry)), category="warning") # handle authors input_authors = authr.split('&') # handle_authors(input_authors) input_authors = list(map(lambda it: it.strip().replace(',', '|'), input_authors)) # Remove duplicates in authors list input_authors = helper.uniq(input_authors) # we have all author names now if input_authors == ['']: input_authors = [_(u'Unknown')] # prevent empty Author sort_authors_list = list() db_author = None for inp in input_authors: stored_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == inp).first() if not stored_author: if not db_author: db_author = db.Authors(inp, helper.get_sorted_author(inp), "") calibre_db.session.add(db_author) calibre_db.session.commit() sort_author = helper.get_sorted_author(inp) else: if not db_author: db_author = stored_author sort_author = stored_author.sort sort_authors_list.append(sort_author) sort_authors = ' & '.join(sort_authors_list) return sort_authors, input_authors, db_author def create_book_on_upload(modif_date, meta): title = meta.title authr = meta.author sort_authors, input_authors, db_author = prepare_authors_on_upload(title, authr) title_dir = helper.get_valid_filename(title) author_dir = helper.get_valid_filename(db_author.name) # combine path and normalize path from windows systems path = os.path.join(author_dir, title_dir).replace('\\', '/') # Calibre adds books with utc as timezone db_book = db.Books(title, "", sort_authors, datetime.utcnow(), datetime(101, 1, 1), '1', datetime.utcnow(), path, meta.cover, db_author, [], "") modif_date |= modify_database_object(input_authors, db_book.authors, db.Authors, calibre_db.session, 'author') # Add series_index to book modif_date |= edit_book_series_index(meta.series_id, db_book) # add languages invalid=[] modif_date |= edit_book_languages(meta.languages, db_book, upload=True, invalid=invalid) if invalid: for l in invalid: flash(_(u"'%(langname)s' is not a valid language", langname=l), category="warning") # handle tags modif_date |= edit_book_tags(meta.tags, db_book) # handle publisher modif_date |= edit_book_publisher(meta.publisher, db_book) # handle series modif_date |= edit_book_series(meta.series, db_book) # Add file to book file_size = os.path.getsize(meta.file_path) db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir) db_book.data.append(db_data) calibre_db.session.add(db_book) # flush content, get db_book.id available calibre_db.session.flush() return db_book, input_authors, title_dir def file_handling_on_upload(requested_file): # check if file extension is correct if '.' in requested_file.filename: file_ext = requested_file.filename.rsplit('.', 1)[-1].lower() if file_ext not in constants.EXTENSIONS_UPLOAD and '' not in constants.EXTENSIONS_UPLOAD: flash( _("File extension '%(ext)s' is not allowed to be uploaded to this server", ext=file_ext), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') else: flash(_('File to be uploaded must have an extension'), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') # extract metadata from file try: meta = uploader.upload(requested_file, config.config_rarfile_location) except (IOError, OSError): log.error("File %s could not saved to temp dir", requested_file.filename) flash(_(u"File %(filename)s could not saved to temp dir", filename=requested_file.filename), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') return meta, None def move_coverfile(meta, db_book): # move cover to final directory, including book id if meta.cover: coverfile = meta.cover else: coverfile = os.path.join(constants.STATIC_DIR, 'generic_cover.jpg') new_coverpath = os.path.join(config.config_calibre_dir, db_book.path, "cover.jpg") try: copyfile(coverfile, new_coverpath) if meta.cover: os.unlink(meta.cover) except OSError as e: log.error("Failed to move cover file %s: %s", new_coverpath, e) flash(_(u"Failed to Move Cover File %(file)s: %(error)s", file=new_coverpath, error=e), category="error") @editbook.route("/upload", methods=["GET", "POST"]) @login_required_if_no_ano @upload_required def upload(): if not config.config_uploading: abort(404) if request.method == 'POST' and 'btn-upload' in request.files: for requested_file in request.files.getlist("btn-upload"): try: modif_date = False # create the function for sorting... calibre_db.update_title_sort(config) calibre_db.session.connection().connection.connection.create_function('uuid4', 0, lambda: str(uuid4())) meta, error = file_handling_on_upload(requested_file) if error: return error db_book, input_authors, title_dir = create_book_on_upload(modif_date, meta) # Comments needs book id therefore only possible after flush modif_date |= edit_book_comments(Markup(meta.description).unescape(), db_book) book_id = db_book.id title = db_book.title error = helper.update_dir_structure_file(book_id, config.config_calibre_dir, input_authors[0], meta.file_path, title_dir + meta.extension.lower()) move_coverfile(meta, db_book) # save data to database, reread data calibre_db.session.commit() if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if error: flash(error, category="error") link = '<a href="{}">{}</a>'.format(url_for('web.show_book', book_id=book_id), escape(title)) uploadText = _(u"File %(file)s uploaded", file=link) WorkerThread.add(current_user.name, TaskUpload(uploadText)) if len(request.files.getlist("btn-upload")) < 2: if current_user.role_edit() or current_user.role_admin(): resp = {"location": url_for('editbook.edit_book', book_id=book_id)} return Response(json.dumps(resp), mimetype='application/json') else: resp = {"location": url_for('web.show_book', book_id=book_id)} return Response(json.dumps(resp), mimetype='application/json') except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() log.error("Database error: %s", e) flash(_(u"Database error: %(error)s.", error=e), category="error") return Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') @editbook.route("/admin/book/convert/<int:book_id>", methods=['POST']) @login_required_if_no_ano @edit_required def convert_bookformat(book_id): # check to see if we have form fields to work with - if not send user back book_format_from = request.form.get('book_format_from', None) book_format_to = request.form.get('book_format_to', None) if (book_format_from is None) or (book_format_to is None): flash(_(u"Source or destination format for conversion missing"), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to) rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(), book_format_to.upper(), current_user.name) if rtn is None: flash(_(u"Book successfully queued for converting to %(book_format)s", book_format=book_format_to), category="success") else: flash(_(u"There was an error converting this book: %(res)s", res=rtn), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) @editbook.route("/ajax/getcustomenum/<int:c_id>") @login_required def table_get_custom_enum(c_id): ret = list() cc = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.id == c_id) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none()) ret.append({'value': "", 'text': ""}) for idx, en in enumerate(cc.get_display_dict()['enum_values']): ret.append({'value': en, 'text': en}) return json.dumps(ret) @editbook.route("/ajax/editbooks/<param>", methods=['POST']) @login_required_if_no_ano @edit_required def edit_list_book(param): vals = request.form.to_dict() book = calibre_db.get_book(vals['pk']) ret = "" if param =='series_index': edit_book_series_index(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': book.series_index}), mimetype='application/json') elif param =='tags': edit_book_tags(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': ', '.join([tag.name for tag in book.tags])}), mimetype='application/json') elif param =='series': edit_book_series(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': ', '.join([serie.name for serie in book.series])}), mimetype='application/json') elif param =='publishers': edit_book_publisher(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': ', '.join([publisher.name for publisher in book.publishers])}), mimetype='application/json') elif param =='languages': invalid = list() edit_book_languages(vals['value'], book, invalid=invalid) if invalid: ret = Response(json.dumps({'success': False, 'msg': 'Invalid languages in request: {}'.format(','.join(invalid))}), mimetype='application/json') else: lang_names = list() for lang in book.languages: lang_names.append(isoLanguages.get_language_name(get_locale(), lang.lang_code)) ret = Response(json.dumps({'success': True, 'newValue': ', '.join(lang_names)}), mimetype='application/json') elif param =='author_sort': book.author_sort = vals['value'] ret = Response(json.dumps({'success': True, 'newValue': book.author_sort}), mimetype='application/json') elif param == 'title': sort = book.sort handle_title_on_edit(book, vals.get('value', "")) helper.update_dir_stucture(book.id, config.config_calibre_dir) ret = Response(json.dumps({'success': True, 'newValue': book.title}), mimetype='application/json') elif param =='sort': book.sort = vals['value'] ret = Response(json.dumps({'success': True, 'newValue': book.sort}), mimetype='application/json') elif param =='comments': edit_book_comments(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': book.comments[0].text}), mimetype='application/json') elif param =='authors': input_authors, __ = handle_author_on_edit(book, vals['value'], vals.get('checkA', None) == "true") helper.update_dir_stucture(book.id, config.config_calibre_dir, input_authors[0]) ret = Response(json.dumps({'success': True, 'newValue': ' & '.join([author.replace('|',',') for author in input_authors])}), mimetype='application/json') elif param.startswith("custom_column_"): new_val = dict() new_val[param] = vals['value'] edit_single_cc_data(book.id, book, param[14:], new_val) ret = Response(json.dumps({'success': True, 'newValue': vals['value']}), mimetype='application/json') book.last_modified = datetime.utcnow() try: calibre_db.session.commit() # revert change for sort if automatic fields link is deactivated if param == 'title' and vals.get('checkT') == "false": book.sort = sort calibre_db.session.commit() except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() log.error("Database error: %s", e) return ret @editbook.route("/ajax/sort_value/<field>/<int:bookid>") @login_required def get_sorted_entry(field, bookid): if field in ['title', 'authors', 'sort', 'author_sort']: book = calibre_db.get_filtered_book(bookid) if book: if field == 'title': return json.dumps({'sort': book.sort}) elif field == 'authors': return json.dumps({'author_sort': book.author_sort}) if field == 'sort': return json.dumps({'sort': book.title}) if field == 'author_sort': return json.dumps({'author_sort': book.author}) return "" @editbook.route("/ajax/simulatemerge", methods=['POST']) @login_required @edit_required def simulate_merge_list_book(): vals = request.get_json().get('Merge_books') if vals: to_book = calibre_db.get_book(vals[0]).title vals.pop(0) if to_book: for book_id in vals: from_book = [] from_book.append(calibre_db.get_book(book_id).title) return json.dumps({'to': to_book, 'from': from_book}) return "" @editbook.route("/ajax/mergebooks", methods=['POST']) @login_required @edit_required def merge_list_book(): vals = request.get_json().get('Merge_books') to_file = list() if vals: # load all formats from target book to_book = calibre_db.get_book(vals[0]) vals.pop(0) if to_book: for file in to_book.data: to_file.append(file.format) to_name = helper.get_valid_filename(to_book.title) + ' - ' + \ helper.get_valid_filename(to_book.authors[0].name) for book_id in vals: from_book = calibre_db.get_book(book_id) if from_book: for element in from_book.data: if element.format not in to_file: # create new data entry with: book_id, book_format, uncompressed_size, name filepath_new = os.path.normpath(os.path.join(config.config_calibre_dir, to_book.path, to_name + "." + element.format.lower())) filepath_old = os.path.normpath(os.path.join(config.config_calibre_dir, from_book.path, element.name + "." + element.format.lower())) copyfile(filepath_old, filepath_new) to_book.data.append(db.Data(to_book.id, element.format, element.uncompressed_size, to_name)) delete_book_from_table(from_book.id,"", True) return json.dumps({'success': True}) return "" @editbook.route("/ajax/xchange", methods=['POST']) @login_required @edit_required def table_xchange_author_title(): vals = request.get_json().get('xchange') if vals: for val in vals: modif_date = False book = calibre_db.get_book(val) authors = book.title entries = calibre_db.order_authors(book) author_names = [] for authr in entries.authors: author_names.append(authr.name.replace('|', ',')) title_change = handle_title_on_edit(book, " ".join(author_names)) input_authors, authorchange = handle_author_on_edit(book, authors) if authorchange or title_change: edited_books_id = book.id modif_date = True if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if edited_books_id: helper.update_dir_stucture(edited_books_id, config.config_calibre_dir, input_authors[0]) if modif_date: book.last_modified = datetime.utcnow() try: calibre_db.session.commit() except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() log.error("Database error: %s", e) return json.dumps({'success': False}) if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() return json.dumps({'success': True}) return ""
# -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, # andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, # falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, # ruben-herold, marblepebble, JackED42, SiphonSquirrel, # apetresc, nanu-c, mutschler # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os from datetime import datetime import json from shutil import copyfile from uuid import uuid4 from markupsafe import escape from functools import wraps try: from lxml.html.clean import clean_html except ImportError: pass # Improve this to check if scholarly is available in a global way, like other pythonic libraries try: from scholarly import scholarly have_scholar = True except ImportError: have_scholar = False from flask import Blueprint, request, flash, redirect, url_for, abort, Markup, Response from flask_babel import gettext as _ from flask_login import current_user, login_required from sqlalchemy.exc import OperationalError, IntegrityError from sqlite3 import OperationalError as sqliteOperationalError from . import constants, logger, isoLanguages, gdriveutils, uploader, helper, kobo_sync_status from . import config, get_locale, ub, db from . import calibre_db from .services.worker import WorkerThread from .tasks.upload import TaskUpload from .render_template import render_title_template from .usermanagement import login_required_if_no_ano editbook = Blueprint('editbook', __name__) log = logger.create() def upload_required(f): @wraps(f) def inner(*args, **kwargs): if current_user.role_upload(): return f(*args, **kwargs) abort(403) return inner def edit_required(f): @wraps(f) def inner(*args, **kwargs): if current_user.role_edit() or current_user.role_admin(): return f(*args, **kwargs) abort(403) return inner def search_objects_remove(db_book_object, db_type, input_elements): del_elements = [] for c_elements in db_book_object: found = False if db_type == 'languages': type_elements = c_elements.lang_code elif db_type == 'custom': type_elements = c_elements.value else: type_elements = c_elements.name for inp_element in input_elements: if inp_element.lower() == type_elements.lower(): # if inp_element == type_elements: found = True break # if the element was not found in the new list, add it to remove list if not found: del_elements.append(c_elements) return del_elements def search_objects_add(db_book_object, db_type, input_elements): add_elements = [] for inp_element in input_elements: found = False for c_elements in db_book_object: if db_type == 'languages': type_elements = c_elements.lang_code elif db_type == 'custom': type_elements = c_elements.value else: type_elements = c_elements.name if inp_element == type_elements: found = True break if not found: add_elements.append(inp_element) return add_elements def remove_objects(db_book_object, db_session, del_elements): changed = False if len(del_elements) > 0: for del_element in del_elements: db_book_object.remove(del_element) changed = True if len(del_element.books) == 0: db_session.delete(del_element) return changed def add_objects(db_book_object, db_object, db_session, db_type, add_elements): changed = False if db_type == 'languages': db_filter = db_object.lang_code elif db_type == 'custom': db_filter = db_object.value else: db_filter = db_object.name for add_element in add_elements: # check if a element with that name exists db_element = db_session.query(db_object).filter(db_filter == add_element).first() # if no element is found add it # if new_element is None: if db_type == 'author': new_element = db_object(add_element, helper.get_sorted_author(add_element.replace('|', ',')), "") elif db_type == 'series': new_element = db_object(add_element, add_element) elif db_type == 'custom': new_element = db_object(value=add_element) elif db_type == 'publisher': new_element = db_object(add_element, None) else: # db_type should be tag or language new_element = db_object(add_element) if db_element is None: changed = True db_session.add(new_element) db_book_object.append(new_element) else: db_element = create_objects_for_addition(db_element, add_element, db_type) changed = True # add element to book changed = True db_book_object.append(db_element) return changed def create_objects_for_addition(db_element, add_element, db_type): if db_type == 'custom': if db_element.value != add_element: db_element.value = add_element # ToDo: Before new_element, but this is not plausible elif db_type == 'languages': if db_element.lang_code != add_element: db_element.lang_code = add_element elif db_type == 'series': if db_element.name != add_element: db_element.name = add_element db_element.sort = add_element elif db_type == 'author': if db_element.name != add_element: db_element.name = add_element db_element.sort = add_element.replace('|', ',') elif db_type == 'publisher': if db_element.name != add_element: db_element.name = add_element db_element.sort = None elif db_element.name != add_element: db_element.name = add_element return db_element # Modifies different Database objects, first check if elements if elements have to be deleted, # because they are no longer used, than check if elements have to be added to database def modify_database_object(input_elements, db_book_object, db_object, db_session, db_type): # passing input_elements not as a list may lead to undesired results if not isinstance(input_elements, list): raise TypeError(str(input_elements) + " should be passed as a list") input_elements = [x for x in input_elements if x != ''] # we have all input element (authors, series, tags) names now # 1. search for elements to remove del_elements = search_objects_remove(db_book_object, db_type, input_elements) # 2. search for elements that need to be added add_elements = search_objects_add(db_book_object, db_type, input_elements) # if there are elements to remove, we remove them now changed = remove_objects(db_book_object, db_session, del_elements) # if there are elements to add, we add them now! if len(add_elements) > 0: changed |= add_objects(db_book_object, db_object, db_session, db_type, add_elements) return changed def modify_identifiers(input_identifiers, db_identifiers, db_session): """Modify Identifiers to match input information. input_identifiers is a list of read-to-persist Identifiers objects. db_identifiers is a list of already persisted list of Identifiers objects.""" changed = False error = False input_dict = dict([(identifier.type.lower(), identifier) for identifier in input_identifiers]) if len(input_identifiers) != len(input_dict): error = True db_dict = dict([(identifier.type.lower(), identifier) for identifier in db_identifiers ]) # delete db identifiers not present in input or modify them with input val for identifier_type, identifier in db_dict.items(): if identifier_type not in input_dict.keys(): db_session.delete(identifier) changed = True else: input_identifier = input_dict[identifier_type] identifier.type = input_identifier.type identifier.val = input_identifier.val # add input identifiers not present in db for identifier_type, identifier in input_dict.items(): if identifier_type not in db_dict.keys(): db_session.add(identifier) changed = True return changed, error @editbook.route("/ajax/delete/<int:book_id>", methods=["POST"]) @login_required def delete_book_from_details(book_id): return Response(delete_book_from_table(book_id, "", True), mimetype='application/json') @editbook.route("/delete/<int:book_id>", defaults={'book_format': ""}, methods=["POST"]) @editbook.route("/delete/<int:book_id>/<string:book_format>", methods=["POST"]) @login_required def delete_book_ajax(book_id, book_format): return delete_book_from_table(book_id, book_format, False) def delete_whole_book(book_id, book): # delete book from Shelfs, Downloads, Read list ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).delete() ub.session.query(ub.ReadBook).filter(ub.ReadBook.book_id == book_id).delete() ub.delete_download(book_id) ub.session_commit() # check if only this book links to: # author, language, series, tags, custom columns modify_database_object([u''], book.authors, db.Authors, calibre_db.session, 'author') modify_database_object([u''], book.tags, db.Tags, calibre_db.session, 'tags') modify_database_object([u''], book.series, db.Series, calibre_db.session, 'series') modify_database_object([u''], book.languages, db.Languages, calibre_db.session, 'languages') modify_database_object([u''], book.publishers, db.Publishers, calibre_db.session, 'publishers') cc = calibre_db.session.query(db.Custom_Columns). \ filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() for c in cc: cc_string = "custom_column_" + str(c.id) if not c.is_multiple: if len(getattr(book, cc_string)) > 0: if c.datatype == 'bool' or c.datatype == 'integer' or c.datatype == 'float': del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) log.debug('remove ' + str(c.id)) calibre_db.session.delete(del_cc) calibre_db.session.commit() elif c.datatype == 'rating': del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) if len(del_cc.books) == 0: log.debug('remove ' + str(c.id)) calibre_db.session.delete(del_cc) calibre_db.session.commit() else: del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) log.debug('remove ' + str(c.id)) calibre_db.session.delete(del_cc) calibre_db.session.commit() else: modify_database_object([u''], getattr(book, cc_string), db.cc_classes[c.id], calibre_db.session, 'custom') calibre_db.session.query(db.Books).filter(db.Books.id == book_id).delete() def render_delete_book_result(book_format, jsonResponse, warning, book_id): if book_format: if jsonResponse: return json.dumps([warning, {"location": url_for("editbook.edit_book", book_id=book_id), "type": "success", "format": book_format, "message": _('Book Format Successfully Deleted')}]) else: flash(_('Book Format Successfully Deleted'), category="success") return redirect(url_for('editbook.edit_book', book_id=book_id)) else: if jsonResponse: return json.dumps([warning, {"location": url_for('web.index'), "type": "success", "format": book_format, "message": _('Book Successfully Deleted')}]) else: flash(_('Book Successfully Deleted'), category="success") return redirect(url_for('web.index')) def delete_book_from_table(book_id, book_format, jsonResponse): warning = {} if current_user.role_delete_books(): book = calibre_db.get_book(book_id) if book: try: result, error = helper.delete_book(book, config.config_calibre_dir, book_format=book_format.upper()) if not result: if jsonResponse: return json.dumps([{"location": url_for("editbook.edit_book", book_id=book_id), "type": "danger", "format": "", "message": error}]) else: flash(error, category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) if error: if jsonResponse: warning = {"location": url_for("editbook.edit_book", book_id=book_id), "type": "warning", "format": "", "message": error} else: flash(error, category="warning") if not book_format: delete_whole_book(book_id, book) else: calibre_db.session.query(db.Data).filter(db.Data.book == book.id).\ filter(db.Data.format == book_format).delete() calibre_db.session.commit() except Exception as ex: log.debug_or_exception(ex) calibre_db.session.rollback() if jsonResponse: return json.dumps([{"location": url_for("editbook.edit_book", book_id=book_id), "type": "danger", "format": "", "message": ex}]) else: flash(str(ex), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) else: # book not found log.error('Book with id "%s" could not be deleted: not found', book_id) return render_delete_book_result(book_format, jsonResponse, warning, book_id) def render_edit_book(book_id): cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() book = calibre_db.get_filtered_book(book_id, allow_show_archived=True) if not book: flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) for lang in book.languages: lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code) book = calibre_db.order_authors(book) author_names = [] for authr in book.authors: author_names.append(authr.name.replace('|', ',')) # Option for showing convertbook button valid_source_formats=list() allowed_conversion_formats = list() kepub_possible=None if config.config_converterpath: for file in book.data: if file.format.lower() in constants.EXTENSIONS_CONVERT_FROM: valid_source_formats.append(file.format.lower()) if config.config_kepubifypath and 'epub' in [file.format.lower() for file in book.data]: kepub_possible = True if not config.config_converterpath: valid_source_formats.append('epub') # Determine what formats don't already exist if config.config_converterpath: allowed_conversion_formats = constants.EXTENSIONS_CONVERT_TO[:] for file in book.data: if file.format.lower() in allowed_conversion_formats: allowed_conversion_formats.remove(file.format.lower()) if kepub_possible: allowed_conversion_formats.append('kepub') return render_title_template('book_edit.html', book=book, authors=author_names, cc=cc, title=_(u"edit metadata"), page="editbook", conversion_formats=allowed_conversion_formats, config=config, source_formats=valid_source_formats) def edit_book_ratings(to_save, book): changed = False if to_save["rating"].strip(): old_rating = False if len(book.ratings) > 0: old_rating = book.ratings[0].rating ratingx2 = int(float(to_save["rating"]) * 2) if ratingx2 != old_rating: changed = True is_rating = calibre_db.session.query(db.Ratings).filter(db.Ratings.rating == ratingx2).first() if is_rating: book.ratings.append(is_rating) else: new_rating = db.Ratings(rating=ratingx2) book.ratings.append(new_rating) if old_rating: book.ratings.remove(book.ratings[0]) else: if len(book.ratings) > 0: book.ratings.remove(book.ratings[0]) changed = True return changed def edit_book_tags(tags, book): input_tags = tags.split(',') input_tags = list(map(lambda it: it.strip(), input_tags)) # Remove duplicates input_tags = helper.uniq(input_tags) return modify_database_object(input_tags, book.tags, db.Tags, calibre_db.session, 'tags') def edit_book_series(series, book): input_series = [series.strip()] input_series = [x for x in input_series if x != ''] return modify_database_object(input_series, book.series, db.Series, calibre_db.session, 'series') def edit_book_series_index(series_index, book): # Add default series_index to book modif_date = False series_index = series_index or '1' if not series_index.replace('.', '', 1).isdigit(): flash(_("%(seriesindex)s is not a valid number, skipping", seriesindex=series_index), category="warning") return False if str(book.series_index) != series_index: book.series_index = series_index modif_date = True return modif_date # Handle book comments/description def edit_book_comments(comments, book): modif_date = False if comments: comments = clean_html(comments) if len(book.comments): if book.comments[0].text != comments: book.comments[0].text = comments modif_date = True else: if comments: book.comments.append(db.Comments(text=comments, book=book.id)) modif_date = True return modif_date def edit_book_languages(languages, book, upload=False, invalid=None): input_languages = languages.split(',') unknown_languages = [] if not upload: input_l = isoLanguages.get_language_codes(get_locale(), input_languages, unknown_languages) else: input_l = isoLanguages.get_valid_language_codes(get_locale(), input_languages, unknown_languages) for l in unknown_languages: log.error("'%s' is not a valid language", l) if isinstance(invalid, list): invalid.append(l) else: raise ValueError(_(u"'%(langname)s' is not a valid language", langname=l)) # ToDo: Not working correct if upload and len(input_l) == 1: # If the language of the file is excluded from the users view, it's not imported, to allow the user to view # the book it's language is set to the filter language if input_l[0] != current_user.filter_language() and current_user.filter_language() != "all": input_l[0] = calibre_db.session.query(db.Languages). \ filter(db.Languages.lang_code == current_user.filter_language()).first().lang_code # Remove duplicates input_l = helper.uniq(input_l) return modify_database_object(input_l, book.languages, db.Languages, calibre_db.session, 'languages') def edit_book_publisher(publishers, book): changed = False if publishers: publisher = publishers.rstrip().strip() if len(book.publishers) == 0 or (len(book.publishers) > 0 and publisher != book.publishers[0].name): changed |= modify_database_object([publisher], book.publishers, db.Publishers, calibre_db.session, 'publisher') elif len(book.publishers): changed |= modify_database_object([], book.publishers, db.Publishers, calibre_db.session, 'publisher') return changed def edit_cc_data_value(book_id, book, c, to_save, cc_db_value, cc_string): changed = False if to_save[cc_string] == 'None': to_save[cc_string] = None elif c.datatype == 'bool': to_save[cc_string] = 1 if to_save[cc_string] == 'True' else 0 elif c.datatype == 'comments': to_save[cc_string] = Markup(to_save[cc_string]).unescape() if to_save[cc_string]: to_save[cc_string] = clean_html(to_save[cc_string]) elif c.datatype == 'datetime': try: to_save[cc_string] = datetime.strptime(to_save[cc_string], "%Y-%m-%d") except ValueError: to_save[cc_string] = db.Books.DEFAULT_PUBDATE if to_save[cc_string] != cc_db_value: if cc_db_value is not None: if to_save[cc_string] is not None: setattr(getattr(book, cc_string)[0], 'value', to_save[cc_string]) changed = True else: del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) calibre_db.session.delete(del_cc) changed = True else: cc_class = db.cc_classes[c.id] new_cc = cc_class(value=to_save[cc_string], book=book_id) calibre_db.session.add(new_cc) changed = True return changed, to_save def edit_cc_data_string(book, c, to_save, cc_db_value, cc_string): changed = False if c.datatype == 'rating': to_save[cc_string] = str(int(float(to_save[cc_string]) * 2)) if to_save[cc_string].strip() != cc_db_value: if cc_db_value is not None: # remove old cc_val del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) if len(del_cc.books) == 0: calibre_db.session.delete(del_cc) changed = True cc_class = db.cc_classes[c.id] new_cc = calibre_db.session.query(cc_class).filter( cc_class.value == to_save[cc_string].strip()).first() # if no cc val is found add it if new_cc is None: new_cc = cc_class(value=to_save[cc_string].strip()) calibre_db.session.add(new_cc) changed = True calibre_db.session.flush() new_cc = calibre_db.session.query(cc_class).filter( cc_class.value == to_save[cc_string].strip()).first() # add cc value to book getattr(book, cc_string).append(new_cc) return changed, to_save def edit_single_cc_data(book_id, book, column_id, to_save): cc = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)) .filter(db.Custom_Columns.id == column_id) .all()) return edit_cc_data(book_id, book, to_save, cc) def edit_all_cc_data(book_id, book, to_save): cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() return edit_cc_data(book_id, book, to_save, cc) def edit_cc_data(book_id, book, to_save, cc): changed = False for c in cc: cc_string = "custom_column_" + str(c.id) if not c.is_multiple: if len(getattr(book, cc_string)) > 0: cc_db_value = getattr(book, cc_string)[0].value else: cc_db_value = None if to_save[cc_string].strip(): if c.datatype in ['int', 'bool', 'float', "datetime", "comments"]: changed, to_save = edit_cc_data_value(book_id, book, c, to_save, cc_db_value, cc_string) else: changed, to_save = edit_cc_data_string(book, c, to_save, cc_db_value, cc_string) else: if cc_db_value is not None: # remove old cc_val del_cc = getattr(book, cc_string)[0] getattr(book, cc_string).remove(del_cc) if not del_cc.books or len(del_cc.books) == 0: calibre_db.session.delete(del_cc) changed = True else: input_tags = to_save[cc_string].split(',') input_tags = list(map(lambda it: it.strip(), input_tags)) changed |= modify_database_object(input_tags, getattr(book, cc_string), db.cc_classes[c.id], calibre_db.session, 'custom') return changed def upload_single_file(request, book, book_id): # Check and handle Uploaded file if 'btn-upload-format' in request.files: requested_file = request.files['btn-upload-format'] # check for empty request if requested_file.filename != '': if not current_user.role_upload(): abort(403) if '.' in requested_file.filename: file_ext = requested_file.filename.rsplit('.', 1)[-1].lower() if file_ext not in constants.EXTENSIONS_UPLOAD and '' not in constants.EXTENSIONS_UPLOAD: flash(_("File extension '%(ext)s' is not allowed to be uploaded to this server", ext=file_ext), category="error") return redirect(url_for('web.show_book', book_id=book.id)) else: flash(_('File to be uploaded must have an extension'), category="error") return redirect(url_for('web.show_book', book_id=book.id)) file_name = book.path.rsplit('/', 1)[-1] filepath = os.path.normpath(os.path.join(config.config_calibre_dir, book.path)) saved_filename = os.path.join(filepath, file_name + '.' + file_ext) # check if file path exists, otherwise create it, copy file to calibre path and delete temp file if not os.path.exists(filepath): try: os.makedirs(filepath) except OSError: flash(_(u"Failed to create path %(path)s (Permission denied).", path=filepath), category="error") return redirect(url_for('web.show_book', book_id=book.id)) try: requested_file.save(saved_filename) except OSError: flash(_(u"Failed to store file %(file)s.", file=saved_filename), category="error") return redirect(url_for('web.show_book', book_id=book.id)) file_size = os.path.getsize(saved_filename) is_format = calibre_db.get_book_format(book_id, file_ext.upper()) # Format entry already exists, no need to update the database if is_format: log.warning('Book format %s already existing', file_ext.upper()) else: try: db_format = db.Data(book_id, file_ext.upper(), file_size, file_name) calibre_db.session.add(db_format) calibre_db.session.commit() calibre_db.update_title_sort(config) except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() log.error('Database error: %s', e) flash(_(u"Database error: %(error)s.", error=e), category="error") return redirect(url_for('web.show_book', book_id=book.id)) # Queue uploader info link = '<a href="{}">{}</a>'.format(url_for('web.show_book', book_id=book.id), escape(book.title)) uploadText=_(u"File format %(ext)s added to %(book)s", ext=file_ext.upper(), book=link) WorkerThread.add(current_user.name, TaskUpload(uploadText)) return uploader.process( saved_filename, *os.path.splitext(requested_file.filename), rarExecutable=config.config_rarfile_location) def upload_cover(request, book): if 'btn-upload-cover' in request.files: requested_file = request.files['btn-upload-cover'] # check for empty request if requested_file.filename != '': if not current_user.role_upload(): abort(403) ret, message = helper.save_cover(requested_file, book.path) if ret is True: return True else: flash(message, category="error") return False return None def handle_title_on_edit(book, book_title): # handle book title book_title = book_title.rstrip().strip() if book.title != book_title: if book_title == '': book_title = _(u'Unknown') book.title = book_title return True return False def handle_author_on_edit(book, author_name, update_stored=True): # handle author(s) input_authors = author_name.split('&') input_authors = list(map(lambda it: it.strip().replace(',', '|'), input_authors)) # Remove duplicates in authors list input_authors = helper.uniq(input_authors) # we have all author names now if input_authors == ['']: input_authors = [_(u'Unknown')] # prevent empty Author change = modify_database_object(input_authors, book.authors, db.Authors, calibre_db.session, 'author') # Search for each author if author is in database, if not, author name and sorted author name is generated new # everything then is assembled for sorted author field in database sort_authors_list = list() for inp in input_authors: stored_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == inp).first() if not stored_author: stored_author = helper.get_sorted_author(inp) else: stored_author = stored_author.sort sort_authors_list.append(helper.get_sorted_author(stored_author)) sort_authors = ' & '.join(sort_authors_list) if book.author_sort != sort_authors and update_stored: book.author_sort = sort_authors change = True return input_authors, change @editbook.route("/admin/book/<int:book_id>", methods=['GET', 'POST']) @login_required_if_no_ano @edit_required def edit_book(book_id): modif_date = False # create the function for sorting... try: calibre_db.update_title_sort(config) except sqliteOperationalError as e: log.debug_or_exception(e) calibre_db.session.rollback() # Show form if request.method != 'POST': return render_edit_book(book_id) book = calibre_db.get_filtered_book(book_id, allow_show_archived=True) # Book not found if not book: flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) meta = upload_single_file(request, book, book_id) if upload_cover(request, book) is True: book.has_cover = 1 modif_date = True try: to_save = request.form.to_dict() merge_metadata(to_save, meta) # Update book edited_books_id = None # handle book title title_change = handle_title_on_edit(book, to_save["book_title"]) input_authors, authorchange = handle_author_on_edit(book, to_save["author_name"]) if authorchange or title_change: edited_books_id = book.id modif_date = True if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() error = False if edited_books_id: error = helper.update_dir_stucture(edited_books_id, config.config_calibre_dir, input_authors[0]) if not error: if "cover_url" in to_save: if to_save["cover_url"]: if not current_user.role_upload(): return "", (403) if to_save["cover_url"].endswith('/static/generic_cover.jpg'): book.has_cover = 0 else: result, error = helper.save_cover_from_url(to_save["cover_url"], book.path) if result is True: book.has_cover = 1 modif_date = True else: flash(error, category="error") # Add default series_index to book modif_date |= edit_book_series_index(to_save["series_index"], book) # Handle book comments/description modif_date |= edit_book_comments(Markup(to_save['description']).unescape(), book) # Handle identifiers input_identifiers = identifier_list(to_save, book) modification, warning = modify_identifiers(input_identifiers, book.identifiers, calibre_db.session) if warning: flash(_("Identifiers are not Case Sensitive, Overwriting Old Identifier"), category="warning") modif_date |= modification # Handle book tags modif_date |= edit_book_tags(to_save['tags'], book) # Handle book series modif_date |= edit_book_series(to_save["series"], book) # handle book publisher modif_date |= edit_book_publisher(to_save['publisher'], book) # handle book languages modif_date |= edit_book_languages(to_save['languages'], book) # handle book ratings modif_date |= edit_book_ratings(to_save, book) # handle cc data modif_date |= edit_all_cc_data(book_id, book, to_save) if to_save["pubdate"]: try: book.pubdate = datetime.strptime(to_save["pubdate"], "%Y-%m-%d") except ValueError: book.pubdate = db.Books.DEFAULT_PUBDATE else: book.pubdate = db.Books.DEFAULT_PUBDATE if modif_date: book.last_modified = datetime.utcnow() kobo_sync_status.remove_synced_book(edited_books_id) calibre_db.session.merge(book) calibre_db.session.commit() if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if "detail_view" in to_save: return redirect(url_for('web.show_book', book_id=book.id)) else: flash(_("Metadata successfully updated"), category="success") return render_edit_book(book_id) else: calibre_db.session.rollback() flash(error, category="error") return render_edit_book(book_id) except ValueError as e: calibre_db.session.rollback() flash(str(e), category="error") return redirect(url_for('web.show_book', book_id=book.id)) except Exception as ex: log.debug_or_exception(ex) calibre_db.session.rollback() flash(_("Error editing book, please check logfile for details"), category="error") return redirect(url_for('web.show_book', book_id=book.id)) def merge_metadata(to_save, meta): if to_save['author_name'] == _(u'Unknown'): to_save['author_name'] = '' if to_save['book_title'] == _(u'Unknown'): to_save['book_title'] = '' for s_field, m_field in [ ('tags', 'tags'), ('author_name', 'author'), ('series', 'series'), ('series_index', 'series_id'), ('languages', 'languages'), ('book_title', 'title')]: to_save[s_field] = to_save[s_field] or getattr(meta, m_field, '') to_save["description"] = to_save["description"] or Markup( getattr(meta, 'description', '')).unescape() def identifier_list(to_save, book): """Generate a list of Identifiers from form information""" id_type_prefix = 'identifier-type-' id_val_prefix = 'identifier-val-' result = [] for type_key, type_value in to_save.items(): if not type_key.startswith(id_type_prefix): continue val_key = id_val_prefix + type_key[len(id_type_prefix):] if val_key not in to_save.keys(): continue result.append(db.Identifiers(to_save[val_key], type_value, book.id)) return result def prepare_authors_on_upload(title, authr): if title != _(u'Unknown') and authr != _(u'Unknown'): entry = calibre_db.check_exists_book(authr, title) if entry: log.info("Uploaded book probably exists in library") flash(_(u"Uploaded book probably exists in the library, consider to change before upload new: ") + Markup(render_title_template('book_exists_flash.html', entry=entry)), category="warning") # handle authors input_authors = authr.split('&') # handle_authors(input_authors) input_authors = list(map(lambda it: it.strip().replace(',', '|'), input_authors)) # Remove duplicates in authors list input_authors = helper.uniq(input_authors) # we have all author names now if input_authors == ['']: input_authors = [_(u'Unknown')] # prevent empty Author sort_authors_list = list() db_author = None for inp in input_authors: stored_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == inp).first() if not stored_author: if not db_author: db_author = db.Authors(inp, helper.get_sorted_author(inp), "") calibre_db.session.add(db_author) calibre_db.session.commit() sort_author = helper.get_sorted_author(inp) else: if not db_author: db_author = stored_author sort_author = stored_author.sort sort_authors_list.append(sort_author) sort_authors = ' & '.join(sort_authors_list) return sort_authors, input_authors, db_author def create_book_on_upload(modif_date, meta): title = meta.title authr = meta.author sort_authors, input_authors, db_author = prepare_authors_on_upload(title, authr) title_dir = helper.get_valid_filename(title) author_dir = helper.get_valid_filename(db_author.name) # combine path and normalize path from windows systems path = os.path.join(author_dir, title_dir).replace('\\', '/') # Calibre adds books with utc as timezone db_book = db.Books(title, "", sort_authors, datetime.utcnow(), datetime(101, 1, 1), '1', datetime.utcnow(), path, meta.cover, db_author, [], "") modif_date |= modify_database_object(input_authors, db_book.authors, db.Authors, calibre_db.session, 'author') # Add series_index to book modif_date |= edit_book_series_index(meta.series_id, db_book) # add languages invalid=[] modif_date |= edit_book_languages(meta.languages, db_book, upload=True, invalid=invalid) if invalid: for l in invalid: flash(_(u"'%(langname)s' is not a valid language", langname=l), category="warning") # handle tags modif_date |= edit_book_tags(meta.tags, db_book) # handle publisher modif_date |= edit_book_publisher(meta.publisher, db_book) # handle series modif_date |= edit_book_series(meta.series, db_book) # Add file to book file_size = os.path.getsize(meta.file_path) db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir) db_book.data.append(db_data) calibre_db.session.add(db_book) # flush content, get db_book.id available calibre_db.session.flush() return db_book, input_authors, title_dir def file_handling_on_upload(requested_file): # check if file extension is correct if '.' in requested_file.filename: file_ext = requested_file.filename.rsplit('.', 1)[-1].lower() if file_ext not in constants.EXTENSIONS_UPLOAD and '' not in constants.EXTENSIONS_UPLOAD: flash( _("File extension '%(ext)s' is not allowed to be uploaded to this server", ext=file_ext), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') else: flash(_('File to be uploaded must have an extension'), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') # extract metadata from file try: meta = uploader.upload(requested_file, config.config_rarfile_location) except (IOError, OSError): log.error("File %s could not saved to temp dir", requested_file.filename) flash(_(u"File %(filename)s could not saved to temp dir", filename=requested_file.filename), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') return meta, None def move_coverfile(meta, db_book): # move cover to final directory, including book id if meta.cover: coverfile = meta.cover else: coverfile = os.path.join(constants.STATIC_DIR, 'generic_cover.jpg') new_coverpath = os.path.join(config.config_calibre_dir, db_book.path, "cover.jpg") try: copyfile(coverfile, new_coverpath) if meta.cover: os.unlink(meta.cover) except OSError as e: log.error("Failed to move cover file %s: %s", new_coverpath, e) flash(_(u"Failed to Move Cover File %(file)s: %(error)s", file=new_coverpath, error=e), category="error") @editbook.route("/upload", methods=["POST"]) @login_required_if_no_ano @upload_required def upload(): if not config.config_uploading: abort(404) if request.method == 'POST' and 'btn-upload' in request.files: for requested_file in request.files.getlist("btn-upload"): try: modif_date = False # create the function for sorting... calibre_db.update_title_sort(config) calibre_db.session.connection().connection.connection.create_function('uuid4', 0, lambda: str(uuid4())) meta, error = file_handling_on_upload(requested_file) if error: return error db_book, input_authors, title_dir = create_book_on_upload(modif_date, meta) # Comments needs book id therefore only possible after flush modif_date |= edit_book_comments(Markup(meta.description).unescape(), db_book) book_id = db_book.id title = db_book.title error = helper.update_dir_structure_file(book_id, config.config_calibre_dir, input_authors[0], meta.file_path, title_dir + meta.extension.lower()) move_coverfile(meta, db_book) # save data to database, reread data calibre_db.session.commit() if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if error: flash(error, category="error") link = '<a href="{}">{}</a>'.format(url_for('web.show_book', book_id=book_id), escape(title)) uploadText = _(u"File %(file)s uploaded", file=link) WorkerThread.add(current_user.name, TaskUpload(uploadText)) if len(request.files.getlist("btn-upload")) < 2: if current_user.role_edit() or current_user.role_admin(): resp = {"location": url_for('editbook.edit_book', book_id=book_id)} return Response(json.dumps(resp), mimetype='application/json') else: resp = {"location": url_for('web.show_book', book_id=book_id)} return Response(json.dumps(resp), mimetype='application/json') except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() log.error("Database error: %s", e) flash(_(u"Database error: %(error)s.", error=e), category="error") return Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') @editbook.route("/admin/book/convert/<int:book_id>", methods=['POST']) @login_required_if_no_ano @edit_required def convert_bookformat(book_id): # check to see if we have form fields to work with - if not send user back book_format_from = request.form.get('book_format_from', None) book_format_to = request.form.get('book_format_to', None) if (book_format_from is None) or (book_format_to is None): flash(_(u"Source or destination format for conversion missing"), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to) rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(), book_format_to.upper(), current_user.name) if rtn is None: flash(_(u"Book successfully queued for converting to %(book_format)s", book_format=book_format_to), category="success") else: flash(_(u"There was an error converting this book: %(res)s", res=rtn), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) @editbook.route("/ajax/getcustomenum/<int:c_id>") @login_required def table_get_custom_enum(c_id): ret = list() cc = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.id == c_id) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none()) ret.append({'value': "", 'text': ""}) for idx, en in enumerate(cc.get_display_dict()['enum_values']): ret.append({'value': en, 'text': en}) return json.dumps(ret) @editbook.route("/ajax/editbooks/<param>", methods=['POST']) @login_required_if_no_ano @edit_required def edit_list_book(param): vals = request.form.to_dict() book = calibre_db.get_book(vals['pk']) ret = "" if param =='series_index': edit_book_series_index(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': book.series_index}), mimetype='application/json') elif param =='tags': edit_book_tags(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': ', '.join([tag.name for tag in book.tags])}), mimetype='application/json') elif param =='series': edit_book_series(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': ', '.join([serie.name for serie in book.series])}), mimetype='application/json') elif param =='publishers': edit_book_publisher(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': ', '.join([publisher.name for publisher in book.publishers])}), mimetype='application/json') elif param =='languages': invalid = list() edit_book_languages(vals['value'], book, invalid=invalid) if invalid: ret = Response(json.dumps({'success': False, 'msg': 'Invalid languages in request: {}'.format(','.join(invalid))}), mimetype='application/json') else: lang_names = list() for lang in book.languages: lang_names.append(isoLanguages.get_language_name(get_locale(), lang.lang_code)) ret = Response(json.dumps({'success': True, 'newValue': ', '.join(lang_names)}), mimetype='application/json') elif param =='author_sort': book.author_sort = vals['value'] ret = Response(json.dumps({'success': True, 'newValue': book.author_sort}), mimetype='application/json') elif param == 'title': sort = book.sort handle_title_on_edit(book, vals.get('value', "")) helper.update_dir_stucture(book.id, config.config_calibre_dir) ret = Response(json.dumps({'success': True, 'newValue': book.title}), mimetype='application/json') elif param =='sort': book.sort = vals['value'] ret = Response(json.dumps({'success': True, 'newValue': book.sort}), mimetype='application/json') elif param =='comments': edit_book_comments(vals['value'], book) ret = Response(json.dumps({'success': True, 'newValue': book.comments[0].text}), mimetype='application/json') elif param =='authors': input_authors, __ = handle_author_on_edit(book, vals['value'], vals.get('checkA', None) == "true") helper.update_dir_stucture(book.id, config.config_calibre_dir, input_authors[0]) ret = Response(json.dumps({'success': True, 'newValue': ' & '.join([author.replace('|',',') for author in input_authors])}), mimetype='application/json') elif param.startswith("custom_column_"): new_val = dict() new_val[param] = vals['value'] edit_single_cc_data(book.id, book, param[14:], new_val) ret = Response(json.dumps({'success': True, 'newValue': vals['value']}), mimetype='application/json') book.last_modified = datetime.utcnow() try: calibre_db.session.commit() # revert change for sort if automatic fields link is deactivated if param == 'title' and vals.get('checkT') == "false": book.sort = sort calibre_db.session.commit() except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() log.error("Database error: %s", e) return ret @editbook.route("/ajax/sort_value/<field>/<int:bookid>") @login_required def get_sorted_entry(field, bookid): if field in ['title', 'authors', 'sort', 'author_sort']: book = calibre_db.get_filtered_book(bookid) if book: if field == 'title': return json.dumps({'sort': book.sort}) elif field == 'authors': return json.dumps({'author_sort': book.author_sort}) if field == 'sort': return json.dumps({'sort': book.title}) if field == 'author_sort': return json.dumps({'author_sort': book.author}) return "" @editbook.route("/ajax/simulatemerge", methods=['POST']) @login_required @edit_required def simulate_merge_list_book(): vals = request.get_json().get('Merge_books') if vals: to_book = calibre_db.get_book(vals[0]).title vals.pop(0) if to_book: for book_id in vals: from_book = [] from_book.append(calibre_db.get_book(book_id).title) return json.dumps({'to': to_book, 'from': from_book}) return "" @editbook.route("/ajax/mergebooks", methods=['POST']) @login_required @edit_required def merge_list_book(): vals = request.get_json().get('Merge_books') to_file = list() if vals: # load all formats from target book to_book = calibre_db.get_book(vals[0]) vals.pop(0) if to_book: for file in to_book.data: to_file.append(file.format) to_name = helper.get_valid_filename(to_book.title) + ' - ' + \ helper.get_valid_filename(to_book.authors[0].name) for book_id in vals: from_book = calibre_db.get_book(book_id) if from_book: for element in from_book.data: if element.format not in to_file: # create new data entry with: book_id, book_format, uncompressed_size, name filepath_new = os.path.normpath(os.path.join(config.config_calibre_dir, to_book.path, to_name + "." + element.format.lower())) filepath_old = os.path.normpath(os.path.join(config.config_calibre_dir, from_book.path, element.name + "." + element.format.lower())) copyfile(filepath_old, filepath_new) to_book.data.append(db.Data(to_book.id, element.format, element.uncompressed_size, to_name)) delete_book_from_table(from_book.id,"", True) return json.dumps({'success': True}) return "" @editbook.route("/ajax/xchange", methods=['POST']) @login_required @edit_required def table_xchange_author_title(): vals = request.get_json().get('xchange') if vals: for val in vals: modif_date = False book = calibre_db.get_book(val) authors = book.title entries = calibre_db.order_authors(book) author_names = [] for authr in entries.authors: author_names.append(authr.name.replace('|', ',')) title_change = handle_title_on_edit(book, " ".join(author_names)) input_authors, authorchange = handle_author_on_edit(book, authors) if authorchange or title_change: edited_books_id = book.id modif_date = True if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if edited_books_id: helper.update_dir_stucture(edited_books_id, config.config_calibre_dir, input_authors[0]) if modif_date: book.last_modified = datetime.utcnow() try: calibre_db.session.commit() except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() log.error("Database error: %s", e) return json.dumps({'success': False}) if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() return json.dumps({'success': True}) return ""
xsrf
{ "code": [ "try:", " from functools import wraps", "except ImportError:", "@editbook.route(\"/ajax/delete/<int:book_id>\")", "@editbook.route(\"/delete/<int:book_id>\", defaults={'book_format': \"\"})", "@editbook.route(\"/delete/<int:book_id>/<string:book_format>\")", "@editbook.route(\"/upload\", methods=[\"GET\", \"POST\"])" ], "line_no": [ 54, 55, 56, 240, 246, 247, 1017 ] }
{ "code": [ "from functools import wraps", "@editbook.route(\"/ajax/delete/<int:book_id>\", methods=[\"POST\"])", "@editbook.route(\"/delete/<int:book_id>\", defaults={'book_format': \"\"}, methods=[\"POST\"])", "@editbook.route(\"/delete/<int:book_id>/<string:book_format>\", methods=[\"POST\"])", "@editbook.route(\"/upload\", methods=[\"POST\"])" ], "line_no": [ 29, 235, 241, 242, 1012 ] }
import os from datetime import datetime import json from shutil import .copyfile from uuid import uuid4 from markupsafe import escape try: from lxml.html.clean import .clean_html except ImportError: pass try: from scholarly import scholarly VAR_47 = True except ImportError: VAR_47 = False from flask import Blueprint, VAR_33, flash, redirect, url_for, abort, Markup, Response from flask_babel import gettext as _ from flask_login import .current_user, login_required from sqlalchemy.exc import OperationalError, IntegrityError from sqlite3 import OperationalError as sqliteOperationalError from . import .constants, logger, isoLanguages, gdriveutils, uploader, helper, kobo_sync_status from . import .config, get_locale, ub, db from . import .calibre_db from .services.worker import WorkerThread from .tasks.upload import TaskUpload from .render_template import render_title_template from .usermanagement import .login_required_if_no_ano try: from functools import wraps except ImportError: pass # We're not using Python 3 VAR_0 = Blueprint('editbook', __name__) VAR_1 = logger.create() def FUNC_0(VAR_2): @wraps(VAR_2) def FUNC_46(*VAR_48, **VAR_49): if current_user.role_upload(): return VAR_2(*VAR_48, **VAR_49) abort(403) return FUNC_46 def FUNC_1(VAR_2): @wraps(VAR_2) def FUNC_46(*VAR_48, **VAR_49): if current_user.role_edit() or current_user.role_admin(): return VAR_2(*VAR_48, **VAR_49) abort(403) return FUNC_46 def FUNC_2(VAR_3, VAR_4, VAR_5): VAR_7 = [] for c_elements in VAR_3: VAR_83 = False if VAR_4 == 'languages': VAR_100 = c_elements.lang_code elif VAR_4 == 'custom': VAR_100 = c_elements.value else: VAR_100 = c_elements.name for inp_element in VAR_5: if inp_element.lower() == VAR_100.lower(): VAR_83 = True break if not VAR_83: VAR_7.append(c_elements) return VAR_7 def FUNC_3(VAR_3, VAR_4, VAR_5): VAR_9 = [] for inp_element in VAR_5: VAR_83 = False for c_elements in VAR_3: if VAR_4 == 'languages': VAR_100 = c_elements.lang_code elif VAR_4 == 'custom': VAR_100 = c_elements.value else: VAR_100 = c_elements.name if inp_element == VAR_100: VAR_83 = True break if not VAR_83: VAR_9.append(inp_element) return VAR_9 def FUNC_4(VAR_3, VAR_6, VAR_7): VAR_50 = False if len(VAR_7) > 0: for del_element in VAR_7: VAR_3.remove(del_element) VAR_50 = True if len(del_element.books) == 0: VAR_6.delete(del_element) return VAR_50 def FUNC_5(VAR_3, VAR_8, VAR_6, VAR_4, VAR_9): VAR_50 = False if VAR_4 == 'languages': VAR_84 = VAR_8.lang_code elif VAR_4 == 'custom': VAR_84 = VAR_8.value else: VAR_84 = VAR_8.name for VAR_11 in VAR_9: VAR_10 = VAR_6.query(VAR_8).filter(VAR_84 == VAR_11).first() if VAR_4 == 'author': VAR_101 = VAR_8(VAR_11, helper.get_sorted_author(VAR_11.replace('|', ',')), "") elif VAR_4 == 'series': VAR_101 = VAR_8(VAR_11, add_element) elif VAR_4 == 'custom': VAR_101 = VAR_8(value=VAR_11) elif VAR_4 == 'publisher': VAR_101 = VAR_8(VAR_11, None) else: # VAR_4 should be tag or language VAR_101 = VAR_8(VAR_11) if VAR_10 is None: VAR_50 = True VAR_6.add(VAR_101) VAR_3.append(VAR_101) else: VAR_10 = FUNC_6(VAR_10, VAR_11, VAR_4) VAR_50 = True VAR_50 = True VAR_3.append(VAR_10) return VAR_50 def FUNC_6(VAR_10, VAR_11, VAR_4): if VAR_4 == 'custom': if VAR_10.value != VAR_11: VAR_10.value = VAR_11 # ToDo: Before VAR_101, but this is not plausible elif VAR_4 == 'languages': if VAR_10.lang_code != VAR_11: VAR_10.lang_code = VAR_11 elif VAR_4 == 'series': if VAR_10.name != VAR_11: VAR_10.name = VAR_11 VAR_10.sort = VAR_11 elif VAR_4 == 'author': if VAR_10.name != VAR_11: VAR_10.name = VAR_11 VAR_10.sort = VAR_11.replace('|', ',') elif VAR_4 == 'publisher': if VAR_10.name != VAR_11: VAR_10.name = VAR_11 VAR_10.sort = None elif VAR_10.name != VAR_11: VAR_10.name = VAR_11 return VAR_10 def FUNC_7(VAR_5, VAR_3, VAR_8, VAR_6, VAR_4): if not isinstance(VAR_5, list): raise TypeError(str(VAR_5) + " should be passed as a list") VAR_5 = [x for x in VAR_5 if x != ''] VAR_7 = FUNC_2(VAR_3, VAR_4, VAR_5) VAR_9 = FUNC_3(VAR_3, VAR_4, VAR_5) VAR_50 = FUNC_4(VAR_3, VAR_6, VAR_7) if len(VAR_9) > 0: VAR_50 |= FUNC_5(VAR_3, VAR_8, VAR_6, VAR_4, VAR_9) return VAR_50 def FUNC_8(VAR_12, VAR_13, VAR_6): VAR_50 = False VAR_51 = False VAR_52 = dict([(identifier.type.lower(), identifier) for identifier in VAR_12]) if len(VAR_12) != len(VAR_52): VAR_51 = True VAR_53 = dict([(identifier.type.lower(), identifier) for identifier in VAR_13 ]) for identifier_type, identifier in VAR_53.items(): if identifier_type not in VAR_52.keys(): VAR_6.delete(identifier) VAR_50 = True else: VAR_102 = VAR_52[identifier_type] identifier.type = VAR_102.type identifier.val = VAR_102.val for identifier_type, identifier in VAR_52.items(): if identifier_type not in VAR_53.keys(): VAR_6.add(identifier) VAR_50 = True return VAR_50, VAR_51 @VAR_0.route("/ajax/delete/<int:VAR_14>") @login_required def FUNC_9(VAR_14): return Response(FUNC_13(VAR_14, "", True), mimetype='application/json') @VAR_0.route("/delete/<int:VAR_14>", defaults={'book_format': ""}) @VAR_0.route("/delete/<int:VAR_14>/<string:VAR_15>") @login_required def FUNC_10(VAR_14, VAR_15): return FUNC_13(VAR_14, VAR_15, False) def FUNC_11(VAR_14, VAR_16): ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == VAR_14).delete() ub.session.query(ub.ReadBook).filter(ub.ReadBook.book_id == VAR_14).delete() ub.delete_download(VAR_14) ub.session_commit() FUNC_7([u''], VAR_16.authors, db.Authors, calibre_db.session, 'author') FUNC_7([u''], VAR_16.tags, db.Tags, calibre_db.session, 'tags') FUNC_7([u''], VAR_16.series, db.Series, calibre_db.session, 'series') FUNC_7([u''], VAR_16.languages, db.Languages, calibre_db.session, 'languages') FUNC_7([u''], VAR_16.publishers, db.Publishers, calibre_db.session, 'publishers') VAR_32 = calibre_db.session.query(db.Custom_Columns). \ filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() for VAR_28 in VAR_32: VAR_30 = "custom_column_" + str(VAR_28.id) if not VAR_28.is_multiple: if len(getattr(VAR_16, VAR_30)) > 0: if VAR_28.datatype == 'bool' or VAR_28.datatype == 'integer' or VAR_28.datatype == 'float': VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) VAR_1.debug('remove ' + str(VAR_28.id)) calibre_db.session.delete(VAR_104) calibre_db.session.commit() elif VAR_28.datatype == 'rating': VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) if len(VAR_104.books) == 0: VAR_1.debug('remove ' + str(VAR_28.id)) calibre_db.session.delete(VAR_104) calibre_db.session.commit() else: VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) VAR_1.debug('remove ' + str(VAR_28.id)) calibre_db.session.delete(VAR_104) calibre_db.session.commit() else: FUNC_7([u''], getattr(VAR_16, VAR_30), db.cc_classes[VAR_28.id], calibre_db.session, 'custom') calibre_db.session.query(db.Books).filter(db.Books.id == VAR_14).delete() def FUNC_12(VAR_15, VAR_17, VAR_18, VAR_14): if VAR_15: if VAR_17: return json.dumps([VAR_18, {"location": url_for("editbook.edit_book", VAR_14=book_id), "type": "success", "format": VAR_15, "message": _('Book Format Successfully Deleted')}]) else: flash(_('Book Format Successfully Deleted'), category="success") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) else: if VAR_17: return json.dumps([VAR_18, {"location": url_for('web.index'), "type": "success", "format": VAR_15, "message": _('Book Successfully Deleted')}]) else: flash(_('Book Successfully Deleted'), category="success") return redirect(url_for('web.index')) def FUNC_13(VAR_14, VAR_15, VAR_17): VAR_18 = {} if current_user.role_delete_books(): VAR_16 = calibre_db.get_book(VAR_14) if VAR_16: try: VAR_69, VAR_51 = helper.delete_book(VAR_16, config.config_calibre_dir, VAR_15=book_format.upper()) if not VAR_69: if VAR_17: return json.dumps([{"location": url_for("editbook.edit_book", VAR_14=book_id), "type": "danger", "format": "", "message": VAR_51}]) else: flash(VAR_51, category="error") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) if VAR_51: if VAR_17: VAR_18 = {"location": url_for("editbook.edit_book", VAR_14=book_id), "type": "warning", "format": "", "message": VAR_51} else: flash(VAR_51, category="warning") if not VAR_15: FUNC_11(VAR_14, VAR_16) else: calibre_db.session.query(db.Data).filter(db.Data.book == VAR_16.id).\ filter(db.Data.format == VAR_15).delete() calibre_db.session.commit() except Exception as ex: VAR_1.debug_or_exception(ex) calibre_db.session.rollback() if VAR_17: return json.dumps([{"location": url_for("editbook.edit_book", VAR_14=book_id), "type": "danger", "format": "", "message": ex}]) else: flash(str(ex), category="error") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) else: VAR_1.error('Book with id "%s" could not be deleted: not found', VAR_14) return FUNC_12(VAR_15, VAR_17, VAR_18, VAR_14) def FUNC_14(VAR_14): VAR_32 = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() VAR_16 = calibre_db.get_filtered_book(VAR_14, allow_show_archived=True) if not VAR_16: flash(_(u"Oops! Selected VAR_16 VAR_38 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) for lang in VAR_16.languages: lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code) VAR_16 = calibre_db.order_authors(VAR_16) VAR_54 = [] for VAR_39 in VAR_16.authors: VAR_54.append(VAR_39.name.replace('|', ',')) VAR_55=list() VAR_56 = list() VAR_57=None if config.config_converterpath: for file in VAR_16.data: if file.format.lower() in constants.EXTENSIONS_CONVERT_FROM: VAR_55.append(file.format.lower()) if config.config_kepubifypath and 'epub' in [file.format.lower() for file in VAR_16.data]: VAR_57 = True if not config.config_converterpath: VAR_55.append('epub') if config.config_converterpath: VAR_56 = constants.EXTENSIONS_CONVERT_TO[:] for file in VAR_16.data: if file.format.lower() in VAR_56: allowed_conversion_formats.remove(file.format.lower()) if VAR_57: VAR_56.append('kepub') return render_title_template('book_edit.html', VAR_16=book, VAR_115=VAR_54, VAR_32=cc, VAR_38=_(u"edit metadata"), page="editbook", conversion_formats=VAR_56, config=config, source_formats=VAR_55) def FUNC_15(VAR_19, VAR_16): VAR_50 = False if VAR_19["rating"].strip(): VAR_85 = False if len(VAR_16.ratings) > 0: VAR_85 = VAR_16.ratings[0].rating VAR_86 = int(float(VAR_19["rating"]) * 2) if VAR_86 != VAR_85: VAR_50 = True VAR_103 = calibre_db.session.query(db.Ratings).filter(db.Ratings.rating == VAR_86).first() if VAR_103: VAR_16.ratings.append(VAR_103) else: VAR_117 = db.Ratings(rating=VAR_86) VAR_16.ratings.append(VAR_117) if VAR_85: VAR_16.ratings.remove(VAR_16.ratings[0]) else: if len(VAR_16.ratings) > 0: VAR_16.ratings.remove(VAR_16.ratings[0]) VAR_50 = True return VAR_50 def FUNC_16(VAR_20, VAR_16): VAR_58 = VAR_20.split(',') VAR_58 = list(map(lambda it: it.strip(), VAR_58)) VAR_58 = helper.uniq(VAR_58) return FUNC_7(VAR_58, VAR_16.tags, db.Tags, calibre_db.session, 'tags') def FUNC_17(VAR_21, VAR_16): VAR_59 = [VAR_21.strip()] VAR_59 = [x for x in VAR_59 if x != ''] return FUNC_7(VAR_59, VAR_16.series, db.Series, calibre_db.session, 'series') def FUNC_18(VAR_22, VAR_16): VAR_40 = False VAR_22 = VAR_22 or '1' if not VAR_22.replace('.', '', 1).isdigit(): flash(_("%(seriesindex)s is not a valid number, skipping", seriesindex=VAR_22), category="warning") return False if str(VAR_16.series_index) != VAR_22: VAR_16.series_index = VAR_22 VAR_40 = True return VAR_40 def FUNC_19(VAR_23, VAR_16): VAR_40 = False if VAR_23: comments = clean_html(VAR_23) if len(VAR_16.comments): if VAR_16.comments[0].text != VAR_23: VAR_16.comments[0].text = VAR_23 VAR_40 = True else: if VAR_23: VAR_16.comments.append(db.Comments(text=VAR_23, VAR_16=VAR_16.id)) VAR_40 = True return VAR_40 def FUNC_20(VAR_24, VAR_16, VAR_25=False, VAR_26=None): VAR_60 = VAR_24.split(',') VAR_61 = [] if not VAR_25: VAR_62 = isoLanguages.get_language_codes(get_locale(), VAR_60, VAR_61) else: VAR_62 = isoLanguages.get_valid_language_codes(get_locale(), VAR_60, VAR_61) for l in VAR_61: VAR_1.error("'%s' is not a valid language", l) if isinstance(VAR_26, list): VAR_26.append(l) else: raise ValueError(_(u"'%(langname)s' is not a valid language", langname=l)) if VAR_25 and len(VAR_62) == 1: if VAR_62[0] != current_user.filter_language() and current_user.filter_language() != "all": VAR_62[0] = calibre_db.session.query(db.Languages). \ filter(db.Languages.lang_code == current_user.filter_language()).first().lang_code VAR_62 = helper.uniq(VAR_62) return FUNC_7(VAR_62, VAR_16.languages, db.Languages, calibre_db.session, 'languages') def FUNC_21(VAR_27, VAR_16): VAR_50 = False if VAR_27: VAR_87 = VAR_27.rstrip().strip() if len(VAR_16.publishers) == 0 or (len(VAR_16.publishers) > 0 and VAR_87 != VAR_16.publishers[0].name): VAR_50 |= FUNC_7([VAR_87], VAR_16.publishers, db.Publishers, calibre_db.session, 'publisher') elif len(VAR_16.publishers): VAR_50 |= FUNC_7([], VAR_16.publishers, db.Publishers, calibre_db.session, 'publisher') return VAR_50 def FUNC_22(VAR_14, VAR_16, VAR_28, VAR_19, VAR_29, VAR_30): VAR_50 = False if VAR_19[VAR_30] == 'None': VAR_19[VAR_30] = None elif VAR_28.datatype == 'bool': VAR_19[VAR_30] = 1 if VAR_19[VAR_30] == 'True' else 0 elif VAR_28.datatype == 'comments': VAR_19[VAR_30] = Markup(VAR_19[VAR_30]).unescape() if VAR_19[VAR_30]: VAR_19[VAR_30] = clean_html(VAR_19[VAR_30]) elif VAR_28.datatype == 'datetime': try: VAR_19[VAR_30] = datetime.strptime(VAR_19[VAR_30], "%Y-%m-%d") except ValueError: VAR_19[VAR_30] = db.Books.DEFAULT_PUBDATE if VAR_19[VAR_30] != VAR_29: if VAR_29 is not None: if VAR_19[VAR_30] is not None: setattr(getattr(VAR_16, VAR_30)[0], 'value', VAR_19[VAR_30]) VAR_50 = True else: VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) calibre_db.session.delete(VAR_104) VAR_50 = True else: VAR_88 = db.cc_classes[VAR_28.id] VAR_89 = VAR_88(value=VAR_19[VAR_30], VAR_16=VAR_14) calibre_db.session.add(VAR_89) VAR_50 = True return VAR_50, VAR_19 def FUNC_23(VAR_16, VAR_28, VAR_19, VAR_29, VAR_30): VAR_50 = False if VAR_28.datatype == 'rating': VAR_19[VAR_30] = str(int(float(VAR_19[VAR_30]) * 2)) if VAR_19[VAR_30].strip() != VAR_29: if VAR_29 is not None: VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) if len(VAR_104.books) == 0: calibre_db.session.delete(VAR_104) VAR_50 = True VAR_88 = db.cc_classes[VAR_28.id] VAR_89 = calibre_db.session.query(VAR_88).filter( VAR_88.value == VAR_19[VAR_30].strip()).first() if VAR_89 is None: VAR_89 = VAR_88(value=VAR_19[VAR_30].strip()) calibre_db.session.add(VAR_89) VAR_50 = True calibre_db.session.flush() VAR_89 = calibre_db.session.query(VAR_88).filter( VAR_88.value == VAR_19[VAR_30].strip()).first() getattr(VAR_16, VAR_30).append(VAR_89) return VAR_50, VAR_19 def FUNC_24(VAR_14, VAR_16, VAR_31, VAR_19): VAR_32 = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)) .filter(db.Custom_Columns.id == VAR_31) .all()) return FUNC_26(VAR_14, VAR_16, VAR_19, VAR_32) def FUNC_25(VAR_14, VAR_16, VAR_19): VAR_32 = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() return FUNC_26(VAR_14, VAR_16, VAR_19, VAR_32) def FUNC_26(VAR_14, VAR_16, VAR_19, VAR_32): VAR_50 = False for VAR_28 in VAR_32: VAR_30 = "custom_column_" + str(VAR_28.id) if not VAR_28.is_multiple: if len(getattr(VAR_16, VAR_30)) > 0: VAR_29 = getattr(VAR_16, VAR_30)[0].value else: VAR_29 = None if VAR_19[VAR_30].strip(): if VAR_28.datatype in ['int', 'bool', 'float', "datetime", "comments"]: VAR_50, VAR_19 = FUNC_22(VAR_14, VAR_16, VAR_28, VAR_19, VAR_29, VAR_30) else: VAR_50, VAR_19 = FUNC_23(VAR_16, VAR_28, VAR_19, VAR_29, VAR_30) else: if VAR_29 is not None: VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) if not VAR_104.books or len(VAR_104.books) == 0: calibre_db.session.delete(VAR_104) VAR_50 = True else: VAR_58 = VAR_19[VAR_30].split(',') VAR_58 = list(map(lambda it: it.strip(), VAR_58)) VAR_50 |= FUNC_7(VAR_58, getattr(VAR_16, VAR_30), db.cc_classes[VAR_28.id], calibre_db.session, 'custom') return VAR_50 def FUNC_27(VAR_33, VAR_16, VAR_14): if 'btn-VAR_25-format' in VAR_33.files: VAR_41 = VAR_33.files['btn-VAR_25-format'] if VAR_41.filename != '': if not current_user.role_upload(): abort(403) if '.' in VAR_41.filename: VAR_97 = VAR_41.filename.rsplit('.', 1)[-1].lower() if VAR_97 not in constants.EXTENSIONS_UPLOAD and '' not in constants.EXTENSIONS_UPLOAD: flash(_("File extension '%(ext)s' is not allowed to be uploaded to this server", ext=VAR_97), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) else: flash(_('File to be uploaded must have an extension'), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) VAR_105 = VAR_16.path.rsplit('/', 1)[-1] VAR_106 = os.path.normpath(os.path.join(config.config_calibre_dir, VAR_16.path)) VAR_107 = os.path.join(VAR_106, VAR_105 + '.' + VAR_97) if not os.path.exists(VAR_106): try: os.makedirs(VAR_106) except OSError: flash(_(u"Failed to create VAR_73 %(path)s (Permission denied).", VAR_73=VAR_106), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) try: VAR_41.save(VAR_107) except OSError: flash(_(u"Failed to store file %(file)s.", file=VAR_107), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) VAR_74 = os.path.getsize(VAR_107) VAR_108 = calibre_db.get_book_format(VAR_14, VAR_97.upper()) if VAR_108: VAR_1.warning('Book format %s already existing', VAR_97.upper()) else: try: VAR_119 = db.Data(VAR_14, VAR_97.upper(), VAR_74, VAR_105) calibre_db.session.add(VAR_119) calibre_db.session.commit() calibre_db.update_title_sort(config) except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() VAR_1.error('Database VAR_51: %s', e) flash(_(u"Database VAR_51: %(VAR_51)s.", VAR_51=e), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) VAR_109 = '<a href="{}">{}</a>'.format(url_for('web.show_book', VAR_14=VAR_16.id), escape(VAR_16.title)) VAR_110=_(u"File format %(ext)s added to %(VAR_16)s", ext=VAR_97.upper(), VAR_16=VAR_109) WorkerThread.add(current_user.name, TaskUpload(VAR_110)) return uploader.process( VAR_107, *os.path.splitext(VAR_41.filename), rarExecutable=config.config_rarfile_location) def FUNC_28(VAR_33, VAR_16): if 'btn-VAR_25-cover' in VAR_33.files: VAR_41 = VAR_33.files['btn-VAR_25-cover'] if VAR_41.filename != '': if not current_user.role_upload(): abort(403) VAR_80, VAR_111 = helper.save_cover(VAR_41, VAR_16.path) if VAR_80 is True: return True else: flash(VAR_111, category="error") return False return None def FUNC_29(VAR_16, VAR_34): VAR_34 = book_title.rstrip().strip() if VAR_16.title != VAR_34: if VAR_34 == '': VAR_34 = _(u'Unknown') VAR_16.title = VAR_34 return True return False def FUNC_30(VAR_16, VAR_35, VAR_36=True): VAR_63 = VAR_35.split('&') VAR_63 = list(map(lambda it: it.strip().replace(',', '|'), VAR_63)) VAR_63 = helper.uniq(VAR_63) if VAR_63 == ['']: VAR_63 = [_(u'Unknown')] # prevent empty Author VAR_64 = FUNC_7(VAR_63, VAR_16.authors, db.Authors, calibre_db.session, 'author') VAR_65 = list() for inp in VAR_63: VAR_90 = calibre_db.session.query(db.Authors).filter(db.Authors.name == inp).first() if not VAR_90: VAR_90 = helper.get_sorted_author(inp) else: VAR_90 = VAR_90.sort VAR_65.append(helper.get_sorted_author(VAR_90)) VAR_66 = ' & '.join(VAR_65) if VAR_16.author_sort != VAR_66 and VAR_36: VAR_16.author_sort = VAR_66 VAR_64 = True return VAR_63, VAR_64 @VAR_0.route("/admin/VAR_16/<int:VAR_14>", methods=['GET', 'POST']) @login_required_if_no_ano @FUNC_1 def FUNC_31(VAR_14): VAR_40 = False try: calibre_db.update_title_sort(config) except sqliteOperationalError as e: VAR_1.debug_or_exception(e) calibre_db.session.rollback() if VAR_33.method != 'POST': return FUNC_14(VAR_14) VAR_16 = calibre_db.get_filtered_book(VAR_14, allow_show_archived=True) if not VAR_16: flash(_(u"Oops! Selected VAR_16 VAR_38 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) VAR_37 = FUNC_27(VAR_33, VAR_16, VAR_14) if FUNC_28(VAR_33, VAR_16) is True: VAR_16.has_cover = 1 VAR_40 = True try: VAR_19 = VAR_33.form.to_dict() FUNC_32(VAR_19, VAR_37) VAR_91 = None VAR_92 = FUNC_29(VAR_16, VAR_19["book_title"]) VAR_63, VAR_93 = FUNC_30(VAR_16, VAR_19["author_name"]) if VAR_93 or VAR_92: VAR_91 = VAR_16.id VAR_40 = True if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() VAR_51 = False if VAR_91: VAR_51 = helper.update_dir_stucture(VAR_91, config.config_calibre_dir, VAR_63[0]) if not VAR_51: if "cover_url" in VAR_19: if VAR_19["cover_url"]: if not current_user.role_upload(): return "", (403) if VAR_19["cover_url"].endswith('/static/generic_cover.jpg'): VAR_16.has_cover = 0 else: VAR_69, VAR_51 = helper.save_cover_from_url(VAR_19["cover_url"], VAR_16.path) if VAR_69 is True: VAR_16.has_cover = 1 VAR_40 = True else: flash(VAR_51, category="error") VAR_40 |= FUNC_18(VAR_19["series_index"], VAR_16) VAR_40 |= FUNC_19(Markup(VAR_19['description']).unescape(), VAR_16) VAR_12 = FUNC_33(VAR_19, VAR_16) VAR_112, VAR_18 = FUNC_8(VAR_12, VAR_16.identifiers, calibre_db.session) if VAR_18: flash(_("Identifiers are not Case Sensitive, Overwriting Old Identifier"), category="warning") VAR_40 |= VAR_112 VAR_40 |= FUNC_16(VAR_19['tags'], VAR_16) VAR_40 |= FUNC_17(VAR_19["series"], VAR_16) VAR_40 |= FUNC_21(VAR_19['publisher'], VAR_16) VAR_40 |= FUNC_20(VAR_19['languages'], VAR_16) VAR_40 |= FUNC_15(VAR_19, VAR_16) VAR_40 |= FUNC_25(VAR_14, VAR_16, VAR_19) if VAR_19["pubdate"]: try: VAR_16.pubdate = datetime.strptime(VAR_19["pubdate"], "%Y-%m-%d") except ValueError: VAR_16.pubdate = db.Books.DEFAULT_PUBDATE else: VAR_16.pubdate = db.Books.DEFAULT_PUBDATE if VAR_40: VAR_16.last_modified = datetime.utcnow() kobo_sync_status.remove_synced_book(VAR_91) calibre_db.session.merge(VAR_16) calibre_db.session.commit() if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if "detail_view" in VAR_19: return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) else: flash(_("Metadata successfully updated"), category="success") return FUNC_14(VAR_14) else: calibre_db.session.rollback() flash(VAR_51, category="error") return FUNC_14(VAR_14) except ValueError as e: calibre_db.session.rollback() flash(str(e), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) except Exception as ex: VAR_1.debug_or_exception(ex) calibre_db.session.rollback() flash(_("Error editing VAR_16, please check logfile for details"), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) def FUNC_32(VAR_19, VAR_37): if VAR_19['author_name'] == _(u'Unknown'): VAR_19['author_name'] = '' if VAR_19['book_title'] == _(u'Unknown'): VAR_19['book_title'] = '' for VAR_94, m_field in [ ('tags', 'tags'), ('author_name', 'author'), ('series', 'series'), ('series_index', 'series_id'), ('languages', 'languages'), ('book_title', 'title')]: VAR_19[VAR_94] = VAR_19[VAR_94] or getattr(VAR_37, m_field, '') VAR_19["description"] = VAR_19["description"] or Markup( getattr(VAR_37, 'description', '')).unescape() def FUNC_33(VAR_19, VAR_16): VAR_67 = 'identifier-type-' VAR_68 = 'identifier-val-' VAR_69 = [] for type_key, type_value in VAR_19.items(): if not type_key.startswith(VAR_67): continue VAR_95 = VAR_68 + type_key[len(VAR_67):] if VAR_95 not in VAR_19.keys(): continue VAR_69.append(db.Identifiers(VAR_19[VAR_95], type_value, VAR_16.id)) return VAR_69 def FUNC_34(VAR_38, VAR_39): if VAR_38 != _(u'Unknown') and VAR_39 != _(u'Unknown'): VAR_96 = calibre_db.check_exists_book(VAR_39, VAR_38) if VAR_96: VAR_1.info("Uploaded VAR_16 probably exists in library") flash(_(u"Uploaded VAR_16 probably exists in the library, consider to VAR_64 before VAR_25 new: ") + Markup(render_title_template('book_exists_flash.html', VAR_96=entry)), category="warning") VAR_63 = VAR_39.split('&') VAR_63 = list(map(lambda it: it.strip().replace(',', '|'), VAR_63)) VAR_63 = helper.uniq(VAR_63) if VAR_63 == ['']: VAR_63 = [_(u'Unknown')] # prevent empty Author VAR_65 = list() VAR_70 = None for inp in VAR_63: VAR_90 = calibre_db.session.query(db.Authors).filter(db.Authors.name == inp).first() if not VAR_90: if not VAR_70: db_author = db.Authors(inp, helper.get_sorted_author(inp), "") calibre_db.session.add(VAR_70) calibre_db.session.commit() VAR_113 = helper.get_sorted_author(inp) else: if not VAR_70: db_author = VAR_90 VAR_113 = VAR_90.sort VAR_65.append(VAR_113) VAR_66 = ' & '.join(VAR_65) return VAR_66, VAR_63, VAR_70 def FUNC_35(VAR_40, VAR_37): VAR_38 = VAR_37.title VAR_39 = VAR_37.author VAR_66, VAR_63, VAR_70 = FUNC_34(VAR_38, VAR_39) VAR_71 = helper.get_valid_filename(VAR_38) VAR_72 = helper.get_valid_filename(VAR_70.name) VAR_73 = os.path.join(VAR_72, VAR_71).replace('\\', '/') VAR_42 = db.Books(VAR_38, "", VAR_66, datetime.utcnow(), datetime(101, 1, 1), '1', datetime.utcnow(), VAR_73, VAR_37.cover, VAR_70, [], "") VAR_40 |= FUNC_7(VAR_63, VAR_42.authors, db.Authors, calibre_db.session, 'author') VAR_40 |= FUNC_18(VAR_37.series_id, VAR_42) VAR_26=[] VAR_40 |= FUNC_20(VAR_37.languages, VAR_42, VAR_25=True, VAR_26=invalid) if VAR_26: for l in VAR_26: flash(_(u"'%(langname)s' is not a valid language", langname=l), category="warning") VAR_40 |= FUNC_16(VAR_37.tags, VAR_42) VAR_40 |= FUNC_21(VAR_37.publisher, VAR_42) VAR_40 |= FUNC_17(VAR_37.series, VAR_42) VAR_74 = os.path.getsize(VAR_37.file_path) VAR_75 = db.Data(VAR_42, VAR_37.extension.upper()[1:], VAR_74, VAR_71) VAR_42.data.append(VAR_75) calibre_db.session.add(VAR_42) calibre_db.session.flush() return VAR_42, VAR_63, VAR_71 def FUNC_36(VAR_41): if '.' in VAR_41.filename: VAR_97 = VAR_41.filename.rsplit('.', 1)[-1].lower() if VAR_97 not in constants.EXTENSIONS_UPLOAD and '' not in constants.EXTENSIONS_UPLOAD: flash( _("File extension '%(ext)s' is not allowed to be uploaded to this server", ext=VAR_97), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') else: flash(_('File to be uploaded must have an extension'), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') try: VAR_37 = uploader.upload(VAR_41, config.config_rarfile_location) except (IOError, OSError): VAR_1.error("File %s could not saved to temp dir", VAR_41.filename) flash(_(u"File %(filename)s could not saved to temp dir", filename=VAR_41.filename), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') return VAR_37, None def FUNC_37(VAR_37, VAR_42): if VAR_37.cover: VAR_98 = VAR_37.cover else: VAR_98 = os.path.join(constants.STATIC_DIR, 'generic_cover.jpg') VAR_76 = os.path.join(config.config_calibre_dir, VAR_42.path, "cover.jpg") try: copyfile(VAR_98, VAR_76) if VAR_37.cover: os.unlink(VAR_37.cover) except OSError as e: VAR_1.error("Failed to move cover file %s: %s", VAR_76, e) flash(_(u"Failed to Move Cover File %(file)s: %(VAR_51)s", file=VAR_76, VAR_51=e), category="error") @VAR_0.route("/upload", methods=["GET", "POST"]) @login_required_if_no_ano @FUNC_0 def VAR_25(): if not config.config_uploading: abort(404) if VAR_33.method == 'POST' and 'btn-upload' in VAR_33.files: for VAR_41 in VAR_33.files.getlist("btn-upload"): try: VAR_40 = False calibre_db.update_title_sort(config) calibre_db.session.connection().connection.connection.create_function('uuid4', 0, lambda: str(uuid4())) VAR_37, VAR_51 = FUNC_36(VAR_41) if VAR_51: return VAR_51 VAR_42, VAR_63, VAR_71 = FUNC_35(VAR_40, VAR_37) VAR_40 |= FUNC_19(Markup(VAR_37.description).unescape(), VAR_42) VAR_14 = VAR_42.id VAR_38 = VAR_42.title VAR_51 = helper.update_dir_structure_file(VAR_14, config.config_calibre_dir, VAR_63[0], VAR_37.file_path, VAR_71 + VAR_37.extension.lower()) FUNC_37(VAR_37, VAR_42) calibre_db.session.commit() if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if VAR_51: flash(VAR_51, category="error") VAR_109 = '<a href="{}">{}</a>'.format(url_for('web.show_book', VAR_14=book_id), escape(VAR_38)) VAR_110 = _(u"File %(file)s uploaded", file=VAR_109) WorkerThread.add(current_user.name, TaskUpload(VAR_110)) if len(VAR_33.files.getlist("btn-upload")) < 2: if current_user.role_edit() or current_user.role_admin(): VAR_120 = {"location": url_for('editbook.edit_book', VAR_14=book_id)} return Response(json.dumps(VAR_120), mimetype='application/json') else: VAR_120 = {"location": url_for('web.show_book', VAR_14=book_id)} return Response(json.dumps(VAR_120), mimetype='application/json') except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() VAR_1.error("Database VAR_51: %s", e) flash(_(u"Database VAR_51: %(VAR_51)s.", VAR_51=e), category="error") return Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') @VAR_0.route("/admin/VAR_16/convert/<int:VAR_14>", methods=['POST']) @login_required_if_no_ano @FUNC_1 def FUNC_39(VAR_14): VAR_77 = VAR_33.form.get('book_format_from', None) VAR_78 = VAR_33.form.get('book_format_to', None) if (VAR_77 is None) or (VAR_78 is None): flash(_(u"Source or destination format for conversion missing"), category="error") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) VAR_1.info('converting: VAR_16 id: %s from: %s to: %s', VAR_14, VAR_77, VAR_78) VAR_79 = helper.convert_book_format(VAR_14, config.config_calibre_dir, VAR_77.upper(), VAR_78.upper(), current_user.name) if VAR_79 is None: flash(_(u"Book successfully queued for converting to %(VAR_15)s", VAR_15=VAR_78), category="success") else: flash(_(u"There was an VAR_51 converting this VAR_16: %(res)s", res=VAR_79), category="error") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) @VAR_0.route("/ajax/getcustomenum/<int:VAR_43>") @login_required def FUNC_40(VAR_43): VAR_80 = list() VAR_32 = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.id == VAR_43) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none()) VAR_80.append({'value': "", 'text': ""}) for idx, en in enumerate(VAR_32.get_display_dict()['enum_values']): VAR_80.append({'value': en, 'text': en}) return json.dumps(VAR_80) @VAR_0.route("/ajax/editbooks/<VAR_44>", methods=['POST']) @login_required_if_no_ano @FUNC_1 def FUNC_41(VAR_44): VAR_81 = VAR_33.form.to_dict() VAR_16 = calibre_db.get_book(VAR_81['pk']) VAR_80 = "" if VAR_44 =='series_index': FUNC_18(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.series_index}), mimetype='application/json') elif VAR_44 =='tags': FUNC_16(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': ', '.join([tag.name for tag in VAR_16.tags])}), mimetype='application/json') elif VAR_44 =='series': FUNC_17(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': ', '.join([serie.name for serie in VAR_16.series])}), mimetype='application/json') elif VAR_44 =='publishers': FUNC_21(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': ', '.join([VAR_87.name for VAR_87 in VAR_16.publishers])}), mimetype='application/json') elif VAR_44 =='languages': VAR_26 = list() FUNC_20(VAR_81['value'], VAR_16, VAR_26=invalid) if VAR_26: VAR_80 = Response(json.dumps({'success': False, 'msg': 'Invalid VAR_24 in VAR_33: {}'.format(','.join(VAR_26))}), mimetype='application/json') else: VAR_121 = list() for lang in VAR_16.languages: VAR_121.append(isoLanguages.get_language_name(get_locale(), lang.lang_code)) VAR_80 = Response(json.dumps({'success': True, 'newValue': ', '.join(VAR_121)}), mimetype='application/json') elif VAR_44 =='author_sort': VAR_16.author_sort = VAR_81['value'] VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.author_sort}), mimetype='application/json') elif VAR_44 == 'title': VAR_124 = VAR_16.sort FUNC_29(VAR_16, VAR_81.get('value', "")) helper.update_dir_stucture(VAR_16.id, config.config_calibre_dir) VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.title}), mimetype='application/json') elif VAR_44 =='sort': VAR_16.sort = VAR_81['value'] VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.sort}), mimetype='application/json') elif VAR_44 =='comments': FUNC_19(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.comments[0].text}), mimetype='application/json') elif VAR_44 =='authors': VAR_63, VAR_125 = FUNC_30(VAR_16, VAR_81['value'], VAR_81.get('checkA', None) == "true") helper.update_dir_stucture(VAR_16.id, config.config_calibre_dir, VAR_63[0]) VAR_80 = Response(json.dumps({'success': True, 'newValue': ' & '.join([author.replace('|',',') for author in VAR_63])}), mimetype='application/json') elif VAR_44.startswith("custom_column_"): VAR_126 = dict() VAR_126[VAR_44] = VAR_81['value'] FUNC_24(VAR_16.id, VAR_16, VAR_44[14:], VAR_126) VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_81['value']}), mimetype='application/json') VAR_16.last_modified = datetime.utcnow() try: calibre_db.session.commit() if VAR_44 == 'title' and VAR_81.get('checkT') == "false": VAR_16.sort = VAR_124 calibre_db.session.commit() except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() VAR_1.error("Database VAR_51: %s", e) return VAR_80 @VAR_0.route("/ajax/sort_value/<VAR_45>/<int:VAR_46>") @login_required def FUNC_42(VAR_45, VAR_46): if VAR_45 in ['title', 'authors', 'sort', 'author_sort']: VAR_16 = calibre_db.get_filtered_book(VAR_46) if VAR_16: if VAR_45 == 'title': return json.dumps({'sort': VAR_16.sort}) elif VAR_45 == 'authors': return json.dumps({'author_sort': VAR_16.author_sort}) if VAR_45 == 'sort': return json.dumps({'sort': VAR_16.title}) if VAR_45 == 'author_sort': return json.dumps({'author_sort': VAR_16.author}) return "" @VAR_0.route("/ajax/simulatemerge", methods=['POST']) @login_required @FUNC_1 def FUNC_43(): VAR_81 = VAR_33.get_json().get('Merge_books') if VAR_81: VAR_99 = calibre_db.get_book(VAR_81[0]).title VAR_81.pop(0) if VAR_99: for VAR_14 in VAR_81: VAR_118 = [] VAR_118.append(calibre_db.get_book(VAR_14).title) return json.dumps({'to': VAR_99, 'from': VAR_118}) return "" @VAR_0.route("/ajax/mergebooks", methods=['POST']) @login_required @FUNC_1 def FUNC_44(): VAR_81 = VAR_33.get_json().get('Merge_books') VAR_82 = list() if VAR_81: VAR_99 = calibre_db.get_book(VAR_81[0]) VAR_81.pop(0) if VAR_99: for file in VAR_99.data: VAR_82.append(file.format) VAR_114 = helper.get_valid_filename(VAR_99.title) + ' - ' + \ helper.get_valid_filename(VAR_99.authors[0].name) for VAR_14 in VAR_81: VAR_118 = calibre_db.get_book(VAR_14) if VAR_118: for element in VAR_118.data: if element.format not in VAR_82: VAR_122 = os.path.normpath(os.path.join(config.config_calibre_dir, VAR_99.path, VAR_114 + "." + element.format.lower())) VAR_123 = os.path.normpath(os.path.join(config.config_calibre_dir, VAR_118.path, element.name + "." + element.format.lower())) copyfile(VAR_123, VAR_122) VAR_99.data.append(db.Data(VAR_99.id, element.format, element.uncompressed_size, VAR_114)) FUNC_13(VAR_118.id,"", True) return json.dumps({'success': True}) return "" @VAR_0.route("/ajax/xchange", methods=['POST']) @login_required @FUNC_1 def FUNC_45(): VAR_81 = VAR_33.get_json().get('xchange') if VAR_81: for val in VAR_81: VAR_40 = False VAR_16 = calibre_db.get_book(val) VAR_115 = VAR_16.title VAR_116 = calibre_db.order_authors(VAR_16) VAR_54 = [] for VAR_39 in VAR_116.authors: VAR_54.append(VAR_39.name.replace('|', ',')) VAR_92 = FUNC_29(VAR_16, " ".join(VAR_54)) VAR_63, VAR_93 = FUNC_30(VAR_16, VAR_115) if VAR_93 or VAR_92: VAR_91 = VAR_16.id VAR_40 = True if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if VAR_91: helper.update_dir_stucture(VAR_91, config.config_calibre_dir, VAR_63[0]) if VAR_40: VAR_16.last_modified = datetime.utcnow() try: calibre_db.session.commit() except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() VAR_1.error("Database VAR_51: %s", e) return json.dumps({'success': False}) if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() return json.dumps({'success': True}) return ""
import os from datetime import datetime import json from shutil import .copyfile from uuid import uuid4 from markupsafe import escape from functools import wraps try: from lxml.html.clean import .clean_html except ImportError: pass try: from scholarly import scholarly VAR_47 = True except ImportError: VAR_47 = False from flask import Blueprint, VAR_33, flash, redirect, url_for, abort, Markup, Response from flask_babel import gettext as _ from flask_login import .current_user, login_required from sqlalchemy.exc import OperationalError, IntegrityError from sqlite3 import OperationalError as sqliteOperationalError from . import .constants, logger, isoLanguages, gdriveutils, uploader, helper, kobo_sync_status from . import .config, get_locale, ub, db from . import .calibre_db from .services.worker import WorkerThread from .tasks.upload import TaskUpload from .render_template import render_title_template from .usermanagement import .login_required_if_no_ano VAR_0 = Blueprint('editbook', __name__) VAR_1 = logger.create() def FUNC_0(VAR_2): @wraps(VAR_2) def FUNC_46(*VAR_48, **VAR_49): if current_user.role_upload(): return VAR_2(*VAR_48, **VAR_49) abort(403) return FUNC_46 def FUNC_1(VAR_2): @wraps(VAR_2) def FUNC_46(*VAR_48, **VAR_49): if current_user.role_edit() or current_user.role_admin(): return VAR_2(*VAR_48, **VAR_49) abort(403) return FUNC_46 def FUNC_2(VAR_3, VAR_4, VAR_5): VAR_7 = [] for c_elements in VAR_3: VAR_83 = False if VAR_4 == 'languages': VAR_100 = c_elements.lang_code elif VAR_4 == 'custom': VAR_100 = c_elements.value else: VAR_100 = c_elements.name for inp_element in VAR_5: if inp_element.lower() == VAR_100.lower(): VAR_83 = True break if not VAR_83: VAR_7.append(c_elements) return VAR_7 def FUNC_3(VAR_3, VAR_4, VAR_5): VAR_9 = [] for inp_element in VAR_5: VAR_83 = False for c_elements in VAR_3: if VAR_4 == 'languages': VAR_100 = c_elements.lang_code elif VAR_4 == 'custom': VAR_100 = c_elements.value else: VAR_100 = c_elements.name if inp_element == VAR_100: VAR_83 = True break if not VAR_83: VAR_9.append(inp_element) return VAR_9 def FUNC_4(VAR_3, VAR_6, VAR_7): VAR_50 = False if len(VAR_7) > 0: for del_element in VAR_7: VAR_3.remove(del_element) VAR_50 = True if len(del_element.books) == 0: VAR_6.delete(del_element) return VAR_50 def FUNC_5(VAR_3, VAR_8, VAR_6, VAR_4, VAR_9): VAR_50 = False if VAR_4 == 'languages': VAR_84 = VAR_8.lang_code elif VAR_4 == 'custom': VAR_84 = VAR_8.value else: VAR_84 = VAR_8.name for VAR_11 in VAR_9: VAR_10 = VAR_6.query(VAR_8).filter(VAR_84 == VAR_11).first() if VAR_4 == 'author': VAR_101 = VAR_8(VAR_11, helper.get_sorted_author(VAR_11.replace('|', ',')), "") elif VAR_4 == 'series': VAR_101 = VAR_8(VAR_11, add_element) elif VAR_4 == 'custom': VAR_101 = VAR_8(value=VAR_11) elif VAR_4 == 'publisher': VAR_101 = VAR_8(VAR_11, None) else: # VAR_4 should be tag or language VAR_101 = VAR_8(VAR_11) if VAR_10 is None: VAR_50 = True VAR_6.add(VAR_101) VAR_3.append(VAR_101) else: VAR_10 = FUNC_6(VAR_10, VAR_11, VAR_4) VAR_50 = True VAR_50 = True VAR_3.append(VAR_10) return VAR_50 def FUNC_6(VAR_10, VAR_11, VAR_4): if VAR_4 == 'custom': if VAR_10.value != VAR_11: VAR_10.value = VAR_11 # ToDo: Before VAR_101, but this is not plausible elif VAR_4 == 'languages': if VAR_10.lang_code != VAR_11: VAR_10.lang_code = VAR_11 elif VAR_4 == 'series': if VAR_10.name != VAR_11: VAR_10.name = VAR_11 VAR_10.sort = VAR_11 elif VAR_4 == 'author': if VAR_10.name != VAR_11: VAR_10.name = VAR_11 VAR_10.sort = VAR_11.replace('|', ',') elif VAR_4 == 'publisher': if VAR_10.name != VAR_11: VAR_10.name = VAR_11 VAR_10.sort = None elif VAR_10.name != VAR_11: VAR_10.name = VAR_11 return VAR_10 def FUNC_7(VAR_5, VAR_3, VAR_8, VAR_6, VAR_4): if not isinstance(VAR_5, list): raise TypeError(str(VAR_5) + " should be passed as a list") VAR_5 = [x for x in VAR_5 if x != ''] VAR_7 = FUNC_2(VAR_3, VAR_4, VAR_5) VAR_9 = FUNC_3(VAR_3, VAR_4, VAR_5) VAR_50 = FUNC_4(VAR_3, VAR_6, VAR_7) if len(VAR_9) > 0: VAR_50 |= FUNC_5(VAR_3, VAR_8, VAR_6, VAR_4, VAR_9) return VAR_50 def FUNC_8(VAR_12, VAR_13, VAR_6): VAR_50 = False VAR_51 = False VAR_52 = dict([(identifier.type.lower(), identifier) for identifier in VAR_12]) if len(VAR_12) != len(VAR_52): VAR_51 = True VAR_53 = dict([(identifier.type.lower(), identifier) for identifier in VAR_13 ]) for identifier_type, identifier in VAR_53.items(): if identifier_type not in VAR_52.keys(): VAR_6.delete(identifier) VAR_50 = True else: VAR_102 = VAR_52[identifier_type] identifier.type = VAR_102.type identifier.val = VAR_102.val for identifier_type, identifier in VAR_52.items(): if identifier_type not in VAR_53.keys(): VAR_6.add(identifier) VAR_50 = True return VAR_50, VAR_51 @VAR_0.route("/ajax/delete/<int:VAR_14>", methods=["POST"]) @login_required def FUNC_9(VAR_14): return Response(FUNC_13(VAR_14, "", True), mimetype='application/json') @VAR_0.route("/delete/<int:VAR_14>", defaults={'book_format': ""}, methods=["POST"]) @VAR_0.route("/delete/<int:VAR_14>/<string:VAR_15>", methods=["POST"]) @login_required def FUNC_10(VAR_14, VAR_15): return FUNC_13(VAR_14, VAR_15, False) def FUNC_11(VAR_14, VAR_16): ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == VAR_14).delete() ub.session.query(ub.ReadBook).filter(ub.ReadBook.book_id == VAR_14).delete() ub.delete_download(VAR_14) ub.session_commit() FUNC_7([u''], VAR_16.authors, db.Authors, calibre_db.session, 'author') FUNC_7([u''], VAR_16.tags, db.Tags, calibre_db.session, 'tags') FUNC_7([u''], VAR_16.series, db.Series, calibre_db.session, 'series') FUNC_7([u''], VAR_16.languages, db.Languages, calibre_db.session, 'languages') FUNC_7([u''], VAR_16.publishers, db.Publishers, calibre_db.session, 'publishers') VAR_32 = calibre_db.session.query(db.Custom_Columns). \ filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() for VAR_28 in VAR_32: VAR_30 = "custom_column_" + str(VAR_28.id) if not VAR_28.is_multiple: if len(getattr(VAR_16, VAR_30)) > 0: if VAR_28.datatype == 'bool' or VAR_28.datatype == 'integer' or VAR_28.datatype == 'float': VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) VAR_1.debug('remove ' + str(VAR_28.id)) calibre_db.session.delete(VAR_104) calibre_db.session.commit() elif VAR_28.datatype == 'rating': VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) if len(VAR_104.books) == 0: VAR_1.debug('remove ' + str(VAR_28.id)) calibre_db.session.delete(VAR_104) calibre_db.session.commit() else: VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) VAR_1.debug('remove ' + str(VAR_28.id)) calibre_db.session.delete(VAR_104) calibre_db.session.commit() else: FUNC_7([u''], getattr(VAR_16, VAR_30), db.cc_classes[VAR_28.id], calibre_db.session, 'custom') calibre_db.session.query(db.Books).filter(db.Books.id == VAR_14).delete() def FUNC_12(VAR_15, VAR_17, VAR_18, VAR_14): if VAR_15: if VAR_17: return json.dumps([VAR_18, {"location": url_for("editbook.edit_book", VAR_14=book_id), "type": "success", "format": VAR_15, "message": _('Book Format Successfully Deleted')}]) else: flash(_('Book Format Successfully Deleted'), category="success") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) else: if VAR_17: return json.dumps([VAR_18, {"location": url_for('web.index'), "type": "success", "format": VAR_15, "message": _('Book Successfully Deleted')}]) else: flash(_('Book Successfully Deleted'), category="success") return redirect(url_for('web.index')) def FUNC_13(VAR_14, VAR_15, VAR_17): VAR_18 = {} if current_user.role_delete_books(): VAR_16 = calibre_db.get_book(VAR_14) if VAR_16: try: VAR_69, VAR_51 = helper.delete_book(VAR_16, config.config_calibre_dir, VAR_15=book_format.upper()) if not VAR_69: if VAR_17: return json.dumps([{"location": url_for("editbook.edit_book", VAR_14=book_id), "type": "danger", "format": "", "message": VAR_51}]) else: flash(VAR_51, category="error") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) if VAR_51: if VAR_17: VAR_18 = {"location": url_for("editbook.edit_book", VAR_14=book_id), "type": "warning", "format": "", "message": VAR_51} else: flash(VAR_51, category="warning") if not VAR_15: FUNC_11(VAR_14, VAR_16) else: calibre_db.session.query(db.Data).filter(db.Data.book == VAR_16.id).\ filter(db.Data.format == VAR_15).delete() calibre_db.session.commit() except Exception as ex: VAR_1.debug_or_exception(ex) calibre_db.session.rollback() if VAR_17: return json.dumps([{"location": url_for("editbook.edit_book", VAR_14=book_id), "type": "danger", "format": "", "message": ex}]) else: flash(str(ex), category="error") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) else: VAR_1.error('Book with id "%s" could not be deleted: not found', VAR_14) return FUNC_12(VAR_15, VAR_17, VAR_18, VAR_14) def FUNC_14(VAR_14): VAR_32 = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() VAR_16 = calibre_db.get_filtered_book(VAR_14, allow_show_archived=True) if not VAR_16: flash(_(u"Oops! Selected VAR_16 VAR_38 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) for lang in VAR_16.languages: lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code) VAR_16 = calibre_db.order_authors(VAR_16) VAR_54 = [] for VAR_39 in VAR_16.authors: VAR_54.append(VAR_39.name.replace('|', ',')) VAR_55=list() VAR_56 = list() VAR_57=None if config.config_converterpath: for file in VAR_16.data: if file.format.lower() in constants.EXTENSIONS_CONVERT_FROM: VAR_55.append(file.format.lower()) if config.config_kepubifypath and 'epub' in [file.format.lower() for file in VAR_16.data]: VAR_57 = True if not config.config_converterpath: VAR_55.append('epub') if config.config_converterpath: VAR_56 = constants.EXTENSIONS_CONVERT_TO[:] for file in VAR_16.data: if file.format.lower() in VAR_56: allowed_conversion_formats.remove(file.format.lower()) if VAR_57: VAR_56.append('kepub') return render_title_template('book_edit.html', VAR_16=book, VAR_115=VAR_54, VAR_32=cc, VAR_38=_(u"edit metadata"), page="editbook", conversion_formats=VAR_56, config=config, source_formats=VAR_55) def FUNC_15(VAR_19, VAR_16): VAR_50 = False if VAR_19["rating"].strip(): VAR_85 = False if len(VAR_16.ratings) > 0: VAR_85 = VAR_16.ratings[0].rating VAR_86 = int(float(VAR_19["rating"]) * 2) if VAR_86 != VAR_85: VAR_50 = True VAR_103 = calibre_db.session.query(db.Ratings).filter(db.Ratings.rating == VAR_86).first() if VAR_103: VAR_16.ratings.append(VAR_103) else: VAR_117 = db.Ratings(rating=VAR_86) VAR_16.ratings.append(VAR_117) if VAR_85: VAR_16.ratings.remove(VAR_16.ratings[0]) else: if len(VAR_16.ratings) > 0: VAR_16.ratings.remove(VAR_16.ratings[0]) VAR_50 = True return VAR_50 def FUNC_16(VAR_20, VAR_16): VAR_58 = VAR_20.split(',') VAR_58 = list(map(lambda it: it.strip(), VAR_58)) VAR_58 = helper.uniq(VAR_58) return FUNC_7(VAR_58, VAR_16.tags, db.Tags, calibre_db.session, 'tags') def FUNC_17(VAR_21, VAR_16): VAR_59 = [VAR_21.strip()] VAR_59 = [x for x in VAR_59 if x != ''] return FUNC_7(VAR_59, VAR_16.series, db.Series, calibre_db.session, 'series') def FUNC_18(VAR_22, VAR_16): VAR_40 = False VAR_22 = VAR_22 or '1' if not VAR_22.replace('.', '', 1).isdigit(): flash(_("%(seriesindex)s is not a valid number, skipping", seriesindex=VAR_22), category="warning") return False if str(VAR_16.series_index) != VAR_22: VAR_16.series_index = VAR_22 VAR_40 = True return VAR_40 def FUNC_19(VAR_23, VAR_16): VAR_40 = False if VAR_23: comments = clean_html(VAR_23) if len(VAR_16.comments): if VAR_16.comments[0].text != VAR_23: VAR_16.comments[0].text = VAR_23 VAR_40 = True else: if VAR_23: VAR_16.comments.append(db.Comments(text=VAR_23, VAR_16=VAR_16.id)) VAR_40 = True return VAR_40 def FUNC_20(VAR_24, VAR_16, VAR_25=False, VAR_26=None): VAR_60 = VAR_24.split(',') VAR_61 = [] if not VAR_25: VAR_62 = isoLanguages.get_language_codes(get_locale(), VAR_60, VAR_61) else: VAR_62 = isoLanguages.get_valid_language_codes(get_locale(), VAR_60, VAR_61) for l in VAR_61: VAR_1.error("'%s' is not a valid language", l) if isinstance(VAR_26, list): VAR_26.append(l) else: raise ValueError(_(u"'%(langname)s' is not a valid language", langname=l)) if VAR_25 and len(VAR_62) == 1: if VAR_62[0] != current_user.filter_language() and current_user.filter_language() != "all": VAR_62[0] = calibre_db.session.query(db.Languages). \ filter(db.Languages.lang_code == current_user.filter_language()).first().lang_code VAR_62 = helper.uniq(VAR_62) return FUNC_7(VAR_62, VAR_16.languages, db.Languages, calibre_db.session, 'languages') def FUNC_21(VAR_27, VAR_16): VAR_50 = False if VAR_27: VAR_87 = VAR_27.rstrip().strip() if len(VAR_16.publishers) == 0 or (len(VAR_16.publishers) > 0 and VAR_87 != VAR_16.publishers[0].name): VAR_50 |= FUNC_7([VAR_87], VAR_16.publishers, db.Publishers, calibre_db.session, 'publisher') elif len(VAR_16.publishers): VAR_50 |= FUNC_7([], VAR_16.publishers, db.Publishers, calibre_db.session, 'publisher') return VAR_50 def FUNC_22(VAR_14, VAR_16, VAR_28, VAR_19, VAR_29, VAR_30): VAR_50 = False if VAR_19[VAR_30] == 'None': VAR_19[VAR_30] = None elif VAR_28.datatype == 'bool': VAR_19[VAR_30] = 1 if VAR_19[VAR_30] == 'True' else 0 elif VAR_28.datatype == 'comments': VAR_19[VAR_30] = Markup(VAR_19[VAR_30]).unescape() if VAR_19[VAR_30]: VAR_19[VAR_30] = clean_html(VAR_19[VAR_30]) elif VAR_28.datatype == 'datetime': try: VAR_19[VAR_30] = datetime.strptime(VAR_19[VAR_30], "%Y-%m-%d") except ValueError: VAR_19[VAR_30] = db.Books.DEFAULT_PUBDATE if VAR_19[VAR_30] != VAR_29: if VAR_29 is not None: if VAR_19[VAR_30] is not None: setattr(getattr(VAR_16, VAR_30)[0], 'value', VAR_19[VAR_30]) VAR_50 = True else: VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) calibre_db.session.delete(VAR_104) VAR_50 = True else: VAR_88 = db.cc_classes[VAR_28.id] VAR_89 = VAR_88(value=VAR_19[VAR_30], VAR_16=VAR_14) calibre_db.session.add(VAR_89) VAR_50 = True return VAR_50, VAR_19 def FUNC_23(VAR_16, VAR_28, VAR_19, VAR_29, VAR_30): VAR_50 = False if VAR_28.datatype == 'rating': VAR_19[VAR_30] = str(int(float(VAR_19[VAR_30]) * 2)) if VAR_19[VAR_30].strip() != VAR_29: if VAR_29 is not None: VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) if len(VAR_104.books) == 0: calibre_db.session.delete(VAR_104) VAR_50 = True VAR_88 = db.cc_classes[VAR_28.id] VAR_89 = calibre_db.session.query(VAR_88).filter( VAR_88.value == VAR_19[VAR_30].strip()).first() if VAR_89 is None: VAR_89 = VAR_88(value=VAR_19[VAR_30].strip()) calibre_db.session.add(VAR_89) VAR_50 = True calibre_db.session.flush() VAR_89 = calibre_db.session.query(VAR_88).filter( VAR_88.value == VAR_19[VAR_30].strip()).first() getattr(VAR_16, VAR_30).append(VAR_89) return VAR_50, VAR_19 def FUNC_24(VAR_14, VAR_16, VAR_31, VAR_19): VAR_32 = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)) .filter(db.Custom_Columns.id == VAR_31) .all()) return FUNC_26(VAR_14, VAR_16, VAR_19, VAR_32) def FUNC_25(VAR_14, VAR_16, VAR_19): VAR_32 = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() return FUNC_26(VAR_14, VAR_16, VAR_19, VAR_32) def FUNC_26(VAR_14, VAR_16, VAR_19, VAR_32): VAR_50 = False for VAR_28 in VAR_32: VAR_30 = "custom_column_" + str(VAR_28.id) if not VAR_28.is_multiple: if len(getattr(VAR_16, VAR_30)) > 0: VAR_29 = getattr(VAR_16, VAR_30)[0].value else: VAR_29 = None if VAR_19[VAR_30].strip(): if VAR_28.datatype in ['int', 'bool', 'float', "datetime", "comments"]: VAR_50, VAR_19 = FUNC_22(VAR_14, VAR_16, VAR_28, VAR_19, VAR_29, VAR_30) else: VAR_50, VAR_19 = FUNC_23(VAR_16, VAR_28, VAR_19, VAR_29, VAR_30) else: if VAR_29 is not None: VAR_104 = getattr(VAR_16, VAR_30)[0] getattr(VAR_16, VAR_30).remove(VAR_104) if not VAR_104.books or len(VAR_104.books) == 0: calibre_db.session.delete(VAR_104) VAR_50 = True else: VAR_58 = VAR_19[VAR_30].split(',') VAR_58 = list(map(lambda it: it.strip(), VAR_58)) VAR_50 |= FUNC_7(VAR_58, getattr(VAR_16, VAR_30), db.cc_classes[VAR_28.id], calibre_db.session, 'custom') return VAR_50 def FUNC_27(VAR_33, VAR_16, VAR_14): if 'btn-VAR_25-format' in VAR_33.files: VAR_41 = VAR_33.files['btn-VAR_25-format'] if VAR_41.filename != '': if not current_user.role_upload(): abort(403) if '.' in VAR_41.filename: VAR_97 = VAR_41.filename.rsplit('.', 1)[-1].lower() if VAR_97 not in constants.EXTENSIONS_UPLOAD and '' not in constants.EXTENSIONS_UPLOAD: flash(_("File extension '%(ext)s' is not allowed to be uploaded to this server", ext=VAR_97), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) else: flash(_('File to be uploaded must have an extension'), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) VAR_105 = VAR_16.path.rsplit('/', 1)[-1] VAR_106 = os.path.normpath(os.path.join(config.config_calibre_dir, VAR_16.path)) VAR_107 = os.path.join(VAR_106, VAR_105 + '.' + VAR_97) if not os.path.exists(VAR_106): try: os.makedirs(VAR_106) except OSError: flash(_(u"Failed to create VAR_73 %(path)s (Permission denied).", VAR_73=VAR_106), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) try: VAR_41.save(VAR_107) except OSError: flash(_(u"Failed to store file %(file)s.", file=VAR_107), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) VAR_74 = os.path.getsize(VAR_107) VAR_108 = calibre_db.get_book_format(VAR_14, VAR_97.upper()) if VAR_108: VAR_1.warning('Book format %s already existing', VAR_97.upper()) else: try: VAR_119 = db.Data(VAR_14, VAR_97.upper(), VAR_74, VAR_105) calibre_db.session.add(VAR_119) calibre_db.session.commit() calibre_db.update_title_sort(config) except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() VAR_1.error('Database VAR_51: %s', e) flash(_(u"Database VAR_51: %(VAR_51)s.", VAR_51=e), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) VAR_109 = '<a href="{}">{}</a>'.format(url_for('web.show_book', VAR_14=VAR_16.id), escape(VAR_16.title)) VAR_110=_(u"File format %(ext)s added to %(VAR_16)s", ext=VAR_97.upper(), VAR_16=VAR_109) WorkerThread.add(current_user.name, TaskUpload(VAR_110)) return uploader.process( VAR_107, *os.path.splitext(VAR_41.filename), rarExecutable=config.config_rarfile_location) def FUNC_28(VAR_33, VAR_16): if 'btn-VAR_25-cover' in VAR_33.files: VAR_41 = VAR_33.files['btn-VAR_25-cover'] if VAR_41.filename != '': if not current_user.role_upload(): abort(403) VAR_80, VAR_111 = helper.save_cover(VAR_41, VAR_16.path) if VAR_80 is True: return True else: flash(VAR_111, category="error") return False return None def FUNC_29(VAR_16, VAR_34): VAR_34 = book_title.rstrip().strip() if VAR_16.title != VAR_34: if VAR_34 == '': VAR_34 = _(u'Unknown') VAR_16.title = VAR_34 return True return False def FUNC_30(VAR_16, VAR_35, VAR_36=True): VAR_63 = VAR_35.split('&') VAR_63 = list(map(lambda it: it.strip().replace(',', '|'), VAR_63)) VAR_63 = helper.uniq(VAR_63) if VAR_63 == ['']: VAR_63 = [_(u'Unknown')] # prevent empty Author VAR_64 = FUNC_7(VAR_63, VAR_16.authors, db.Authors, calibre_db.session, 'author') VAR_65 = list() for inp in VAR_63: VAR_90 = calibre_db.session.query(db.Authors).filter(db.Authors.name == inp).first() if not VAR_90: VAR_90 = helper.get_sorted_author(inp) else: VAR_90 = VAR_90.sort VAR_65.append(helper.get_sorted_author(VAR_90)) VAR_66 = ' & '.join(VAR_65) if VAR_16.author_sort != VAR_66 and VAR_36: VAR_16.author_sort = VAR_66 VAR_64 = True return VAR_63, VAR_64 @VAR_0.route("/admin/VAR_16/<int:VAR_14>", methods=['GET', 'POST']) @login_required_if_no_ano @FUNC_1 def FUNC_31(VAR_14): VAR_40 = False try: calibre_db.update_title_sort(config) except sqliteOperationalError as e: VAR_1.debug_or_exception(e) calibre_db.session.rollback() if VAR_33.method != 'POST': return FUNC_14(VAR_14) VAR_16 = calibre_db.get_filtered_book(VAR_14, allow_show_archived=True) if not VAR_16: flash(_(u"Oops! Selected VAR_16 VAR_38 is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) VAR_37 = FUNC_27(VAR_33, VAR_16, VAR_14) if FUNC_28(VAR_33, VAR_16) is True: VAR_16.has_cover = 1 VAR_40 = True try: VAR_19 = VAR_33.form.to_dict() FUNC_32(VAR_19, VAR_37) VAR_91 = None VAR_92 = FUNC_29(VAR_16, VAR_19["book_title"]) VAR_63, VAR_93 = FUNC_30(VAR_16, VAR_19["author_name"]) if VAR_93 or VAR_92: VAR_91 = VAR_16.id VAR_40 = True if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() VAR_51 = False if VAR_91: VAR_51 = helper.update_dir_stucture(VAR_91, config.config_calibre_dir, VAR_63[0]) if not VAR_51: if "cover_url" in VAR_19: if VAR_19["cover_url"]: if not current_user.role_upload(): return "", (403) if VAR_19["cover_url"].endswith('/static/generic_cover.jpg'): VAR_16.has_cover = 0 else: VAR_69, VAR_51 = helper.save_cover_from_url(VAR_19["cover_url"], VAR_16.path) if VAR_69 is True: VAR_16.has_cover = 1 VAR_40 = True else: flash(VAR_51, category="error") VAR_40 |= FUNC_18(VAR_19["series_index"], VAR_16) VAR_40 |= FUNC_19(Markup(VAR_19['description']).unescape(), VAR_16) VAR_12 = FUNC_33(VAR_19, VAR_16) VAR_112, VAR_18 = FUNC_8(VAR_12, VAR_16.identifiers, calibre_db.session) if VAR_18: flash(_("Identifiers are not Case Sensitive, Overwriting Old Identifier"), category="warning") VAR_40 |= VAR_112 VAR_40 |= FUNC_16(VAR_19['tags'], VAR_16) VAR_40 |= FUNC_17(VAR_19["series"], VAR_16) VAR_40 |= FUNC_21(VAR_19['publisher'], VAR_16) VAR_40 |= FUNC_20(VAR_19['languages'], VAR_16) VAR_40 |= FUNC_15(VAR_19, VAR_16) VAR_40 |= FUNC_25(VAR_14, VAR_16, VAR_19) if VAR_19["pubdate"]: try: VAR_16.pubdate = datetime.strptime(VAR_19["pubdate"], "%Y-%m-%d") except ValueError: VAR_16.pubdate = db.Books.DEFAULT_PUBDATE else: VAR_16.pubdate = db.Books.DEFAULT_PUBDATE if VAR_40: VAR_16.last_modified = datetime.utcnow() kobo_sync_status.remove_synced_book(VAR_91) calibre_db.session.merge(VAR_16) calibre_db.session.commit() if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if "detail_view" in VAR_19: return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) else: flash(_("Metadata successfully updated"), category="success") return FUNC_14(VAR_14) else: calibre_db.session.rollback() flash(VAR_51, category="error") return FUNC_14(VAR_14) except ValueError as e: calibre_db.session.rollback() flash(str(e), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) except Exception as ex: VAR_1.debug_or_exception(ex) calibre_db.session.rollback() flash(_("Error editing VAR_16, please check logfile for details"), category="error") return redirect(url_for('web.show_book', VAR_14=VAR_16.id)) def FUNC_32(VAR_19, VAR_37): if VAR_19['author_name'] == _(u'Unknown'): VAR_19['author_name'] = '' if VAR_19['book_title'] == _(u'Unknown'): VAR_19['book_title'] = '' for VAR_94, m_field in [ ('tags', 'tags'), ('author_name', 'author'), ('series', 'series'), ('series_index', 'series_id'), ('languages', 'languages'), ('book_title', 'title')]: VAR_19[VAR_94] = VAR_19[VAR_94] or getattr(VAR_37, m_field, '') VAR_19["description"] = VAR_19["description"] or Markup( getattr(VAR_37, 'description', '')).unescape() def FUNC_33(VAR_19, VAR_16): VAR_67 = 'identifier-type-' VAR_68 = 'identifier-val-' VAR_69 = [] for type_key, type_value in VAR_19.items(): if not type_key.startswith(VAR_67): continue VAR_95 = VAR_68 + type_key[len(VAR_67):] if VAR_95 not in VAR_19.keys(): continue VAR_69.append(db.Identifiers(VAR_19[VAR_95], type_value, VAR_16.id)) return VAR_69 def FUNC_34(VAR_38, VAR_39): if VAR_38 != _(u'Unknown') and VAR_39 != _(u'Unknown'): VAR_96 = calibre_db.check_exists_book(VAR_39, VAR_38) if VAR_96: VAR_1.info("Uploaded VAR_16 probably exists in library") flash(_(u"Uploaded VAR_16 probably exists in the library, consider to VAR_64 before VAR_25 new: ") + Markup(render_title_template('book_exists_flash.html', VAR_96=entry)), category="warning") VAR_63 = VAR_39.split('&') VAR_63 = list(map(lambda it: it.strip().replace(',', '|'), VAR_63)) VAR_63 = helper.uniq(VAR_63) if VAR_63 == ['']: VAR_63 = [_(u'Unknown')] # prevent empty Author VAR_65 = list() VAR_70 = None for inp in VAR_63: VAR_90 = calibre_db.session.query(db.Authors).filter(db.Authors.name == inp).first() if not VAR_90: if not VAR_70: db_author = db.Authors(inp, helper.get_sorted_author(inp), "") calibre_db.session.add(VAR_70) calibre_db.session.commit() VAR_113 = helper.get_sorted_author(inp) else: if not VAR_70: db_author = VAR_90 VAR_113 = VAR_90.sort VAR_65.append(VAR_113) VAR_66 = ' & '.join(VAR_65) return VAR_66, VAR_63, VAR_70 def FUNC_35(VAR_40, VAR_37): VAR_38 = VAR_37.title VAR_39 = VAR_37.author VAR_66, VAR_63, VAR_70 = FUNC_34(VAR_38, VAR_39) VAR_71 = helper.get_valid_filename(VAR_38) VAR_72 = helper.get_valid_filename(VAR_70.name) VAR_73 = os.path.join(VAR_72, VAR_71).replace('\\', '/') VAR_42 = db.Books(VAR_38, "", VAR_66, datetime.utcnow(), datetime(101, 1, 1), '1', datetime.utcnow(), VAR_73, VAR_37.cover, VAR_70, [], "") VAR_40 |= FUNC_7(VAR_63, VAR_42.authors, db.Authors, calibre_db.session, 'author') VAR_40 |= FUNC_18(VAR_37.series_id, VAR_42) VAR_26=[] VAR_40 |= FUNC_20(VAR_37.languages, VAR_42, VAR_25=True, VAR_26=invalid) if VAR_26: for l in VAR_26: flash(_(u"'%(langname)s' is not a valid language", langname=l), category="warning") VAR_40 |= FUNC_16(VAR_37.tags, VAR_42) VAR_40 |= FUNC_21(VAR_37.publisher, VAR_42) VAR_40 |= FUNC_17(VAR_37.series, VAR_42) VAR_74 = os.path.getsize(VAR_37.file_path) VAR_75 = db.Data(VAR_42, VAR_37.extension.upper()[1:], VAR_74, VAR_71) VAR_42.data.append(VAR_75) calibre_db.session.add(VAR_42) calibre_db.session.flush() return VAR_42, VAR_63, VAR_71 def FUNC_36(VAR_41): if '.' in VAR_41.filename: VAR_97 = VAR_41.filename.rsplit('.', 1)[-1].lower() if VAR_97 not in constants.EXTENSIONS_UPLOAD and '' not in constants.EXTENSIONS_UPLOAD: flash( _("File extension '%(ext)s' is not allowed to be uploaded to this server", ext=VAR_97), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') else: flash(_('File to be uploaded must have an extension'), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') try: VAR_37 = uploader.upload(VAR_41, config.config_rarfile_location) except (IOError, OSError): VAR_1.error("File %s could not saved to temp dir", VAR_41.filename) flash(_(u"File %(filename)s could not saved to temp dir", filename=VAR_41.filename), category="error") return None, Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') return VAR_37, None def FUNC_37(VAR_37, VAR_42): if VAR_37.cover: VAR_98 = VAR_37.cover else: VAR_98 = os.path.join(constants.STATIC_DIR, 'generic_cover.jpg') VAR_76 = os.path.join(config.config_calibre_dir, VAR_42.path, "cover.jpg") try: copyfile(VAR_98, VAR_76) if VAR_37.cover: os.unlink(VAR_37.cover) except OSError as e: VAR_1.error("Failed to move cover file %s: %s", VAR_76, e) flash(_(u"Failed to Move Cover File %(file)s: %(VAR_51)s", file=VAR_76, VAR_51=e), category="error") @VAR_0.route("/upload", methods=["POST"]) @login_required_if_no_ano @FUNC_0 def VAR_25(): if not config.config_uploading: abort(404) if VAR_33.method == 'POST' and 'btn-upload' in VAR_33.files: for VAR_41 in VAR_33.files.getlist("btn-upload"): try: VAR_40 = False calibre_db.update_title_sort(config) calibre_db.session.connection().connection.connection.create_function('uuid4', 0, lambda: str(uuid4())) VAR_37, VAR_51 = FUNC_36(VAR_41) if VAR_51: return VAR_51 VAR_42, VAR_63, VAR_71 = FUNC_35(VAR_40, VAR_37) VAR_40 |= FUNC_19(Markup(VAR_37.description).unescape(), VAR_42) VAR_14 = VAR_42.id VAR_38 = VAR_42.title VAR_51 = helper.update_dir_structure_file(VAR_14, config.config_calibre_dir, VAR_63[0], VAR_37.file_path, VAR_71 + VAR_37.extension.lower()) FUNC_37(VAR_37, VAR_42) calibre_db.session.commit() if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if VAR_51: flash(VAR_51, category="error") VAR_109 = '<a href="{}">{}</a>'.format(url_for('web.show_book', VAR_14=book_id), escape(VAR_38)) VAR_110 = _(u"File %(file)s uploaded", file=VAR_109) WorkerThread.add(current_user.name, TaskUpload(VAR_110)) if len(VAR_33.files.getlist("btn-upload")) < 2: if current_user.role_edit() or current_user.role_admin(): VAR_120 = {"location": url_for('editbook.edit_book', VAR_14=book_id)} return Response(json.dumps(VAR_120), mimetype='application/json') else: VAR_120 = {"location": url_for('web.show_book', VAR_14=book_id)} return Response(json.dumps(VAR_120), mimetype='application/json') except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() VAR_1.error("Database VAR_51: %s", e) flash(_(u"Database VAR_51: %(VAR_51)s.", VAR_51=e), category="error") return Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') @VAR_0.route("/admin/VAR_16/convert/<int:VAR_14>", methods=['POST']) @login_required_if_no_ano @FUNC_1 def FUNC_39(VAR_14): VAR_77 = VAR_33.form.get('book_format_from', None) VAR_78 = VAR_33.form.get('book_format_to', None) if (VAR_77 is None) or (VAR_78 is None): flash(_(u"Source or destination format for conversion missing"), category="error") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) VAR_1.info('converting: VAR_16 id: %s from: %s to: %s', VAR_14, VAR_77, VAR_78) VAR_79 = helper.convert_book_format(VAR_14, config.config_calibre_dir, VAR_77.upper(), VAR_78.upper(), current_user.name) if VAR_79 is None: flash(_(u"Book successfully queued for converting to %(VAR_15)s", VAR_15=VAR_78), category="success") else: flash(_(u"There was an VAR_51 converting this VAR_16: %(res)s", res=VAR_79), category="error") return redirect(url_for('editbook.edit_book', VAR_14=book_id)) @VAR_0.route("/ajax/getcustomenum/<int:VAR_43>") @login_required def FUNC_40(VAR_43): VAR_80 = list() VAR_32 = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.id == VAR_43) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none()) VAR_80.append({'value': "", 'text': ""}) for idx, en in enumerate(VAR_32.get_display_dict()['enum_values']): VAR_80.append({'value': en, 'text': en}) return json.dumps(VAR_80) @VAR_0.route("/ajax/editbooks/<VAR_44>", methods=['POST']) @login_required_if_no_ano @FUNC_1 def FUNC_41(VAR_44): VAR_81 = VAR_33.form.to_dict() VAR_16 = calibre_db.get_book(VAR_81['pk']) VAR_80 = "" if VAR_44 =='series_index': FUNC_18(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.series_index}), mimetype='application/json') elif VAR_44 =='tags': FUNC_16(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': ', '.join([tag.name for tag in VAR_16.tags])}), mimetype='application/json') elif VAR_44 =='series': FUNC_17(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': ', '.join([serie.name for serie in VAR_16.series])}), mimetype='application/json') elif VAR_44 =='publishers': FUNC_21(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': ', '.join([VAR_87.name for VAR_87 in VAR_16.publishers])}), mimetype='application/json') elif VAR_44 =='languages': VAR_26 = list() FUNC_20(VAR_81['value'], VAR_16, VAR_26=invalid) if VAR_26: VAR_80 = Response(json.dumps({'success': False, 'msg': 'Invalid VAR_24 in VAR_33: {}'.format(','.join(VAR_26))}), mimetype='application/json') else: VAR_121 = list() for lang in VAR_16.languages: VAR_121.append(isoLanguages.get_language_name(get_locale(), lang.lang_code)) VAR_80 = Response(json.dumps({'success': True, 'newValue': ', '.join(VAR_121)}), mimetype='application/json') elif VAR_44 =='author_sort': VAR_16.author_sort = VAR_81['value'] VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.author_sort}), mimetype='application/json') elif VAR_44 == 'title': VAR_124 = VAR_16.sort FUNC_29(VAR_16, VAR_81.get('value', "")) helper.update_dir_stucture(VAR_16.id, config.config_calibre_dir) VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.title}), mimetype='application/json') elif VAR_44 =='sort': VAR_16.sort = VAR_81['value'] VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.sort}), mimetype='application/json') elif VAR_44 =='comments': FUNC_19(VAR_81['value'], VAR_16) VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_16.comments[0].text}), mimetype='application/json') elif VAR_44 =='authors': VAR_63, VAR_125 = FUNC_30(VAR_16, VAR_81['value'], VAR_81.get('checkA', None) == "true") helper.update_dir_stucture(VAR_16.id, config.config_calibre_dir, VAR_63[0]) VAR_80 = Response(json.dumps({'success': True, 'newValue': ' & '.join([author.replace('|',',') for author in VAR_63])}), mimetype='application/json') elif VAR_44.startswith("custom_column_"): VAR_126 = dict() VAR_126[VAR_44] = VAR_81['value'] FUNC_24(VAR_16.id, VAR_16, VAR_44[14:], VAR_126) VAR_80 = Response(json.dumps({'success': True, 'newValue': VAR_81['value']}), mimetype='application/json') VAR_16.last_modified = datetime.utcnow() try: calibre_db.session.commit() if VAR_44 == 'title' and VAR_81.get('checkT') == "false": VAR_16.sort = VAR_124 calibre_db.session.commit() except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() VAR_1.error("Database VAR_51: %s", e) return VAR_80 @VAR_0.route("/ajax/sort_value/<VAR_45>/<int:VAR_46>") @login_required def FUNC_42(VAR_45, VAR_46): if VAR_45 in ['title', 'authors', 'sort', 'author_sort']: VAR_16 = calibre_db.get_filtered_book(VAR_46) if VAR_16: if VAR_45 == 'title': return json.dumps({'sort': VAR_16.sort}) elif VAR_45 == 'authors': return json.dumps({'author_sort': VAR_16.author_sort}) if VAR_45 == 'sort': return json.dumps({'sort': VAR_16.title}) if VAR_45 == 'author_sort': return json.dumps({'author_sort': VAR_16.author}) return "" @VAR_0.route("/ajax/simulatemerge", methods=['POST']) @login_required @FUNC_1 def FUNC_43(): VAR_81 = VAR_33.get_json().get('Merge_books') if VAR_81: VAR_99 = calibre_db.get_book(VAR_81[0]).title VAR_81.pop(0) if VAR_99: for VAR_14 in VAR_81: VAR_118 = [] VAR_118.append(calibre_db.get_book(VAR_14).title) return json.dumps({'to': VAR_99, 'from': VAR_118}) return "" @VAR_0.route("/ajax/mergebooks", methods=['POST']) @login_required @FUNC_1 def FUNC_44(): VAR_81 = VAR_33.get_json().get('Merge_books') VAR_82 = list() if VAR_81: VAR_99 = calibre_db.get_book(VAR_81[0]) VAR_81.pop(0) if VAR_99: for file in VAR_99.data: VAR_82.append(file.format) VAR_114 = helper.get_valid_filename(VAR_99.title) + ' - ' + \ helper.get_valid_filename(VAR_99.authors[0].name) for VAR_14 in VAR_81: VAR_118 = calibre_db.get_book(VAR_14) if VAR_118: for element in VAR_118.data: if element.format not in VAR_82: VAR_122 = os.path.normpath(os.path.join(config.config_calibre_dir, VAR_99.path, VAR_114 + "." + element.format.lower())) VAR_123 = os.path.normpath(os.path.join(config.config_calibre_dir, VAR_118.path, element.name + "." + element.format.lower())) copyfile(VAR_123, VAR_122) VAR_99.data.append(db.Data(VAR_99.id, element.format, element.uncompressed_size, VAR_114)) FUNC_13(VAR_118.id,"", True) return json.dumps({'success': True}) return "" @VAR_0.route("/ajax/xchange", methods=['POST']) @login_required @FUNC_1 def FUNC_45(): VAR_81 = VAR_33.get_json().get('xchange') if VAR_81: for val in VAR_81: VAR_40 = False VAR_16 = calibre_db.get_book(val) VAR_115 = VAR_16.title VAR_116 = calibre_db.order_authors(VAR_16) VAR_54 = [] for VAR_39 in VAR_116.authors: VAR_54.append(VAR_39.name.replace('|', ',')) VAR_92 = FUNC_29(VAR_16, " ".join(VAR_54)) VAR_63, VAR_93 = FUNC_30(VAR_16, VAR_115) if VAR_93 or VAR_92: VAR_91 = VAR_16.id VAR_40 = True if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if VAR_91: helper.update_dir_stucture(VAR_91, config.config_calibre_dir, VAR_63[0]) if VAR_40: VAR_16.last_modified = datetime.utcnow() try: calibre_db.session.commit() except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() VAR_1.error("Database VAR_51: %s", e) return json.dumps({'success': False}) if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() return json.dumps({'success': True}) return ""
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 33, 34, 40, 53, 58, 59, 60, 61, 64, 65, 72, 74, 81, 83, 96, 99, 103, 104, 122, 123, 133, 143, 145, 146, 164, 168, 169, 192, 193, 194, 195, 197, 201, 202, 204, 206, 208, 212, 213, 224, 233, 239, 244, 245, 251, 252, 254, 259, 260, 261, 267, 297, 298, 318, 319, 361, 363, 366, 367, 374, 377, 379, 383, 384, 396, 397, 410, 411, 434, 438, 441, 442, 447, 448, 450, 460, 461, 462, 476, 477, 491, 493, 494, 498, 501, 502, 513, 514, 530, 547, 548, 555, 564, 572, 575, 582, 586, 603, 618, 620, 623, 636, 640, 641, 653, 656, 657, 671, 672, 676, 680, 681, 685, 696, 697, 699, 707, 708, 710, 713, 715, 718, 720, 721, 722, 736, 737, 743, 744, 750, 751, 754, 756, 757, 761, 769, 771, 772, 774, 779, 782, 786, 801, 802, 804, 806, 812, 814, 816, 818, 820, 822, 824, 832, 836, 859, 860, 873, 874, 888, 889, 897, 898, 900, 902, 904, 905, 908, 926, 927, 932, 935, 936, 938, 939, 942, 945, 946, 948, 949, 955, 956, 958, 959, 961, 962, 964, 965, 970, 971, 974, 976, 987, 988, 997, 998, 1000, 1015, 1016, 1027, 1030, 1034, 1036, 1037, 1039, 1042, 1048, 1050, 1051, 1053, 1061, 1074, 1079, 1082, 1086, 1090, 1098, 1110, 1111, 1178, 1182, 1190, 1191, 1207, 1208, 1223, 1224, 1232, 1245, 1260, 1275, 1281, 1284, 1295, 1300, 215, 216, 217, 876 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 30, 35, 36, 42, 55, 56, 59, 60, 67, 69, 76, 78, 91, 94, 98, 99, 117, 118, 128, 138, 140, 141, 159, 163, 164, 187, 188, 189, 190, 192, 196, 197, 199, 201, 203, 207, 208, 219, 228, 234, 239, 240, 246, 247, 249, 254, 255, 256, 262, 292, 293, 313, 314, 356, 358, 361, 362, 369, 372, 374, 378, 379, 391, 392, 405, 406, 429, 433, 436, 437, 442, 443, 445, 455, 456, 457, 471, 472, 486, 488, 489, 493, 496, 497, 508, 509, 525, 542, 543, 550, 559, 567, 570, 577, 581, 598, 613, 615, 618, 631, 635, 636, 648, 651, 652, 666, 667, 671, 675, 676, 680, 691, 692, 694, 702, 703, 705, 708, 710, 713, 715, 716, 717, 731, 732, 738, 739, 745, 746, 749, 751, 752, 756, 764, 766, 767, 769, 774, 777, 781, 796, 797, 799, 801, 807, 809, 811, 813, 815, 817, 819, 827, 831, 854, 855, 868, 869, 883, 884, 892, 893, 895, 897, 899, 900, 903, 921, 922, 927, 930, 931, 933, 934, 937, 940, 941, 943, 944, 950, 951, 953, 954, 956, 957, 959, 960, 965, 966, 969, 971, 982, 983, 992, 993, 995, 1010, 1011, 1022, 1025, 1029, 1031, 1032, 1034, 1037, 1043, 1045, 1046, 1048, 1056, 1069, 1074, 1077, 1081, 1085, 1093, 1105, 1106, 1173, 1177, 1185, 1186, 1202, 1203, 1218, 1219, 1227, 1240, 1255, 1270, 1276, 1279, 1290, 1295, 210, 211, 212, 871 ]
1CWE-79
""" django-helpdesk - A Django powered ticket tracker for small enterprise. (c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details. models.py - Model (and hence database) definitions. This is the core of the helpdesk structure. """ from django.contrib.auth.models import Permission from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db import models from django.conf import settings from django.utils import timezone from django.utils.translation import ugettext_lazy as _, ugettext from io import StringIO import re import os import mimetypes import datetime from django.utils.safestring import mark_safe from markdown import markdown from markdown.extensions import Extension import uuid from helpdesk import settings as helpdesk_settings from .validators import validate_file_extension from .templated_email import send_templated_mail def format_time_spent(time_spent): if time_spent: time_spent = "{0:02d}h:{1:02d}m".format( time_spent.seconds // 3600, time_spent.seconds % 3600 // 60 ) else: time_spent = "" return time_spent class EscapeHtml(Extension): def extendMarkdown(self, md, md_globals): del md.preprocessors['html_block'] del md.inlinePatterns['html'] def get_markdown(text): if not text: return "" pattern = fr'([\[\s\S\]]*?)\(([\s\S]*?):([\[\s\S\]]*?)\)' # Regex check if re.match(pattern, text): # get get value of group regex scheme = re.search(pattern, text, re.IGNORECASE).group(2) # scheme check if scheme in helpdesk_settings.ALLOWED_URL_SCHEMES: replacement = '\\1(\\2:\\3)' else: replacement = '\\1(\\3)' text = re.sub(pattern, replacement, text, flags=re.IGNORECASE) return mark_safe( markdown( text, extensions=[ EscapeHtml(), 'markdown.extensions.nl2br', 'markdown.extensions.fenced_code' ] ) ) class Queue(models.Model): """ A queue is a collection of tickets into what would generally be business areas or departments. For example, a company may have a queue for each Product they provide, or a queue for each of Accounts, Pre-Sales, and Support. """ title = models.CharField( _('Title'), max_length=100, ) slug = models.SlugField( _('Slug'), max_length=50, unique=True, help_text=_('This slug is used when building ticket ID\'s. Once set, ' 'try not to change it or e-mailing may get messy.'), ) email_address = models.EmailField( _('E-Mail Address'), blank=True, null=True, help_text=_('All outgoing e-mails for this queue will use this e-mail ' 'address. If you use IMAP or POP3, this should be the e-mail ' 'address for that mailbox.'), ) locale = models.CharField( _('Locale'), max_length=10, blank=True, null=True, help_text=_('Locale of this queue. All correspondence in this ' 'queue will be in this language.'), ) allow_public_submission = models.BooleanField( _('Allow Public Submission?'), blank=True, default=False, help_text=_('Should this queue be listed on the public submission form?'), ) allow_email_submission = models.BooleanField( _('Allow E-Mail Submission?'), blank=True, default=False, help_text=_('Do you want to poll the e-mail box below for new ' 'tickets?'), ) escalate_days = models.IntegerField( _('Escalation Days'), blank=True, null=True, help_text=_('For tickets which are not held, how often do you wish to ' 'increase their priority? Set to 0 for no escalation.'), ) new_ticket_cc = models.CharField( _('New Ticket CC Address'), blank=True, null=True, max_length=200, help_text=_('If an e-mail address is entered here, then it will ' 'receive notification of all new tickets created for this queue. ' 'Enter a comma between multiple e-mail addresses.'), ) updated_ticket_cc = models.CharField( _('Updated Ticket CC Address'), blank=True, null=True, max_length=200, help_text=_('If an e-mail address is entered here, then it will ' 'receive notification of all activity (new tickets, closed ' 'tickets, updates, reassignments, etc) for this queue. Separate ' 'multiple addresses with a comma.'), ) enable_notifications_on_email_events = models.BooleanField( _('Notify contacts when email updates arrive'), blank=True, default=False, help_text=_('When an email arrives to either create a ticket or to ' 'interact with an existing discussion. Should email notifications be sent ? ' 'Note: the new_ticket_cc and updated_ticket_cc work independently of this feature'), ) email_box_type = models.CharField( _('E-Mail Box Type'), max_length=5, choices=(('pop3', _('POP 3')), ('imap', _('IMAP')), ('local', _('Local Directory'))), blank=True, null=True, help_text=_('E-Mail server type for creating tickets automatically ' 'from a mailbox - both POP3 and IMAP are supported, as well as ' 'reading from a local directory.'), ) email_box_host = models.CharField( _('E-Mail Hostname'), max_length=200, blank=True, null=True, help_text=_('Your e-mail server address - either the domain name or ' 'IP address. May be "localhost".'), ) email_box_port = models.IntegerField( _('E-Mail Port'), blank=True, null=True, help_text=_('Port number to use for accessing e-mail. Default for ' 'POP3 is "110", and for IMAP is "143". This may differ on some ' 'servers. Leave it blank to use the defaults.'), ) email_box_ssl = models.BooleanField( _('Use SSL for E-Mail?'), blank=True, default=False, help_text=_('Whether to use SSL for IMAP or POP3 - the default ports ' 'when using SSL are 993 for IMAP and 995 for POP3.'), ) email_box_user = models.CharField( _('E-Mail Username'), max_length=200, blank=True, null=True, help_text=_('Username for accessing this mailbox.'), ) email_box_pass = models.CharField( _('E-Mail Password'), max_length=200, blank=True, null=True, help_text=_('Password for the above username'), ) email_box_imap_folder = models.CharField( _('IMAP Folder'), max_length=100, blank=True, null=True, help_text=_('If using IMAP, what folder do you wish to fetch messages ' 'from? This allows you to use one IMAP account for multiple ' 'queues, by filtering messages on your IMAP server into separate ' 'folders. Default: INBOX.'), ) email_box_local_dir = models.CharField( _('E-Mail Local Directory'), max_length=200, blank=True, null=True, help_text=_('If using a local directory, what directory path do you ' 'wish to poll for new email? ' 'Example: /var/lib/mail/helpdesk/'), ) permission_name = models.CharField( _('Django auth permission name'), max_length=72, # based on prepare_permission_name() pre-pending chars to slug blank=True, null=True, editable=False, help_text=_('Name used in the django.contrib.auth permission system'), ) email_box_interval = models.IntegerField( _('E-Mail Check Interval'), help_text=_('How often do you wish to check this mailbox? (in Minutes)'), blank=True, null=True, default='5', ) email_box_last_check = models.DateTimeField( blank=True, null=True, editable=False, # This is updated by management/commands/get_mail.py. ) socks_proxy_type = models.CharField( _('Socks Proxy Type'), max_length=8, choices=(('socks4', _('SOCKS4')), ('socks5', _('SOCKS5'))), blank=True, null=True, help_text=_('SOCKS4 or SOCKS5 allows you to proxy your connections through a SOCKS server.'), ) socks_proxy_host = models.GenericIPAddressField( _('Socks Proxy Host'), blank=True, null=True, help_text=_('Socks proxy IP address. Default: 127.0.0.1'), ) socks_proxy_port = models.IntegerField( _('Socks Proxy Port'), blank=True, null=True, help_text=_('Socks proxy port number. Default: 9150 (default TOR port)'), ) logging_type = models.CharField( _('Logging Type'), max_length=5, choices=( ('none', _('None')), ('debug', _('Debug')), ('info', _('Information')), ('warn', _('Warning')), ('error', _('Error')), ('crit', _('Critical')) ), blank=True, null=True, help_text=_('Set the default logging level. All messages at that ' 'level or above will be logged to the directory set ' 'below. If no level is set, logging will be disabled.'), ) logging_dir = models.CharField( _('Logging Directory'), max_length=200, blank=True, null=True, help_text=_('If logging is enabled, what directory should we use to ' 'store log files for this queue? ' 'The standard logging mechanims are used if no directory is set'), ) default_owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='default_owner', blank=True, null=True, verbose_name=_('Default owner'), ) dedicated_time = models.DurationField( help_text=_("Time to be spent on this Queue in total"), blank=True, null=True ) def __str__(self): return "%s" % self.title class Meta: ordering = ('title',) verbose_name = _('Queue') verbose_name_plural = _('Queues') def _from_address(self): """ Short property to provide a sender address in SMTP format, eg 'Name <email>'. We do this so we can put a simple error message in the sender name field, so hopefully the admin can see and fix it. """ if not self.email_address: # must check if given in format "Foo <foo@example.com>" default_email = re.match(".*<(?P<email>.*@*.)>", settings.DEFAULT_FROM_EMAIL) if default_email is not None: # already in the right format, so just include it here return u'NO QUEUE EMAIL ADDRESS DEFINED %s' % settings.DEFAULT_FROM_EMAIL else: return u'NO QUEUE EMAIL ADDRESS DEFINED <%s>' % settings.DEFAULT_FROM_EMAIL else: return u'%s <%s>' % (self.title, self.email_address) from_address = property(_from_address) @property def time_spent(self): """Return back total time spent on the ticket. This is calculated value based on total sum from all FollowUps """ total = datetime.timedelta(0) for val in self.ticket_set.all(): if val.time_spent: total = total + val.time_spent return total @property def time_spent_formated(self): return format_time_spent(self.time_spent) def prepare_permission_name(self): """Prepare internally the codename for the permission and store it in permission_name. :return: The codename that can be used to create a new Permission object. """ # Prepare the permission associated to this Queue basename = "queue_access_%s" % self.slug self.permission_name = "helpdesk.%s" % basename return basename def save(self, *args, **kwargs): if self.email_box_type == 'imap' and not self.email_box_imap_folder: self.email_box_imap_folder = 'INBOX' if self.socks_proxy_type: if not self.socks_proxy_host: self.socks_proxy_host = '127.0.0.1' if not self.socks_proxy_port: self.socks_proxy_port = 9150 else: self.socks_proxy_host = None self.socks_proxy_port = None if not self.email_box_port: if self.email_box_type == 'imap' and self.email_box_ssl: self.email_box_port = 993 elif self.email_box_type == 'imap' and not self.email_box_ssl: self.email_box_port = 143 elif self.email_box_type == 'pop3' and self.email_box_ssl: self.email_box_port = 995 elif self.email_box_type == 'pop3' and not self.email_box_ssl: self.email_box_port = 110 if not self.id: # Prepare the permission codename and the permission # (even if they are not needed with the current configuration) basename = self.prepare_permission_name() Permission.objects.create( name=_("Permission for queue: ") + self.title, content_type=ContentType.objects.get_for_model(self.__class__), codename=basename, ) super(Queue, self).save(*args, **kwargs) def delete(self, *args, **kwargs): permission_name = self.permission_name super(Queue, self).delete(*args, **kwargs) # once the Queue is safely deleted, remove the permission (if exists) if permission_name: try: p = Permission.objects.get(codename=permission_name[9:]) p.delete() except ObjectDoesNotExist: pass def mk_secret(): return str(uuid.uuid4()) class Ticket(models.Model): """ To allow a ticket to be entered as quickly as possible, only the bare minimum fields are required. These basically allow us to sort and manage the ticket. The user can always go back and enter more information later. A good example of this is when a customer is on the phone, and you want to give them a ticket ID as quickly as possible. You can enter some basic info, save the ticket, give the customer the ID and get off the phone, then add in further detail at a later time (once the customer is not on the line). Note that assigned_to is optional - unassigned tickets are displayed on the dashboard to prompt users to take ownership of them. """ OPEN_STATUS = 1 REOPENED_STATUS = 2 RESOLVED_STATUS = 3 CLOSED_STATUS = 4 DUPLICATE_STATUS = 5 STATUS_CHOICES = ( (OPEN_STATUS, _('Open')), (REOPENED_STATUS, _('Reopened')), (RESOLVED_STATUS, _('Resolved')), (CLOSED_STATUS, _('Closed')), (DUPLICATE_STATUS, _('Duplicate')), ) PRIORITY_CHOICES = ( (1, _('1. Critical')), (2, _('2. High')), (3, _('3. Normal')), (4, _('4. Low')), (5, _('5. Very Low')), ) title = models.CharField( _('Title'), max_length=200, ) queue = models.ForeignKey( Queue, on_delete=models.CASCADE, verbose_name=_('Queue'), ) created = models.DateTimeField( _('Created'), blank=True, help_text=_('Date this ticket was first created'), ) modified = models.DateTimeField( _('Modified'), blank=True, help_text=_('Date this ticket was most recently changed.'), ) submitter_email = models.EmailField( _('Submitter E-Mail'), blank=True, null=True, help_text=_('The submitter will receive an email for all public ' 'follow-ups left for this task.'), ) assigned_to = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='assigned_to', blank=True, null=True, verbose_name=_('Assigned to'), ) status = models.IntegerField( _('Status'), choices=STATUS_CHOICES, default=OPEN_STATUS, ) on_hold = models.BooleanField( _('On Hold'), blank=True, default=False, help_text=_('If a ticket is on hold, it will not automatically be escalated.'), ) description = models.TextField( _('Description'), blank=True, null=True, help_text=_('The content of the customers query.'), ) resolution = models.TextField( _('Resolution'), blank=True, null=True, help_text=_('The resolution provided to the customer by our staff.'), ) priority = models.IntegerField( _('Priority'), choices=PRIORITY_CHOICES, default=3, blank=3, help_text=_('1 = Highest Priority, 5 = Low Priority'), ) due_date = models.DateTimeField( _('Due on'), blank=True, null=True, ) last_escalation = models.DateTimeField( blank=True, null=True, editable=False, help_text=_('The date this ticket was last escalated - updated ' 'automatically by management/commands/escalate_tickets.py.'), ) secret_key = models.CharField( _("Secret key needed for viewing/editing ticket by non-logged in users"), max_length=36, default=mk_secret, ) kbitem = models.ForeignKey( "KBItem", blank=True, null=True, on_delete=models.CASCADE, verbose_name=_('Knowledge base item the user was viewing when they created this ticket.'), ) merged_to = models.ForeignKey( 'self', verbose_name=_('merged to'), related_name='merged_tickets', on_delete=models.CASCADE, null=True, blank=True ) @property def time_spent(self): """Return back total time spent on the ticket. This is calculated value based on total sum from all FollowUps """ total = datetime.timedelta(0) for val in self.followup_set.all(): if val.time_spent: total = total + val.time_spent return total @property def time_spent_formated(self): return format_time_spent(self.time_spent) def send(self, roles, dont_send_to=None, **kwargs): """ Send notifications to everyone interested in this ticket. The the roles argument is a dictionary mapping from roles to (template, context) pairs. If a role is not present in the dictionary, users of that type will not receive the notification. The following roles exist: - 'submitter' - 'new_ticket_cc' - 'ticket_cc' - 'assigned_to' Here is an example roles dictionary: { 'submitter': (template_name, context), 'assigned_to': (template_name2, context), } **kwargs are passed to send_templated_mail defined in templated_email.py returns the set of email addresses the notification was delivered to. """ recipients = set() if dont_send_to is not None: recipients.update(dont_send_to) recipients.add(self.queue.email_address) def should_receive(email): return email and email not in recipients def send(role, recipient): if recipient and recipient not in recipients and role in roles: template, context = roles[role] send_templated_mail(template, context, recipient, sender=self.queue.from_address, **kwargs) recipients.add(recipient) send('submitter', self.submitter_email) send('ticket_cc', self.queue.updated_ticket_cc) send('new_ticket_cc', self.queue.new_ticket_cc) if self.assigned_to: send('assigned_to', self.assigned_to.email) if self.queue.enable_notifications_on_email_events: for cc in self.ticketcc_set.all(): send('ticket_cc', cc.email_address) return recipients def _get_assigned_to(self): """ Custom property to allow us to easily print 'Unassigned' if a ticket has no owner, or the users name if it's assigned. If the user has a full name configured, we use that, otherwise their username. """ if not self.assigned_to: return _('Unassigned') else: if self.assigned_to.get_full_name(): return self.assigned_to.get_full_name() else: return self.assigned_to.get_username() get_assigned_to = property(_get_assigned_to) def _get_ticket(self): """ A user-friendly ticket ID, which is a combination of ticket ID and queue slug. This is generally used in e-mail subjects. """ return u"[%s]" % self.ticket_for_url ticket = property(_get_ticket) def _get_ticket_for_url(self): """ A URL-friendly ticket ID, used in links. """ return u"%s-%s" % (self.queue.slug, self.id) ticket_for_url = property(_get_ticket_for_url) def _get_priority_css_class(self): """ Return the boostrap class corresponding to the priority. """ if self.priority == 2: return "warning" elif self.priority == 1: return "danger" elif self.priority == 5: return "success" else: return "" get_priority_css_class = property(_get_priority_css_class) def _get_status(self): """ Displays the ticket status, with an "On Hold" message if needed. """ held_msg = '' if self.on_hold: held_msg = _(' - On Hold') dep_msg = '' if not self.can_be_resolved: dep_msg = _(' - Open dependencies') return u'%s%s%s' % (self.get_status_display(), held_msg, dep_msg) get_status = property(_get_status) def _get_ticket_url(self): """ Returns a publicly-viewable URL for this ticket, used when giving a URL to the submitter of a ticket. """ from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.urls import reverse try: site = Site.objects.get_current() except ImproperlyConfigured: site = Site(domain='configure-django-sites.com') if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK: protocol = 'https' else: protocol = 'http' return u"%s://%s%s?ticket=%s&email=%s&key=%s" % ( protocol, site.domain, reverse('helpdesk:public_view'), self.ticket_for_url, self.submitter_email, self.secret_key ) ticket_url = property(_get_ticket_url) def _get_staff_url(self): """ Returns a staff-only URL for this ticket, used when giving a URL to a staff member (in emails etc) """ from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.urls import reverse try: site = Site.objects.get_current() except ImproperlyConfigured: site = Site(domain='configure-django-sites.com') if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK: protocol = 'https' else: protocol = 'http' return u"%s://%s%s" % ( protocol, site.domain, reverse('helpdesk:view', args=[self.id]) ) staff_url = property(_get_staff_url) def _can_be_resolved(self): """ Returns a boolean. True = any dependencies are resolved False = There are non-resolved dependencies """ OPEN_STATUSES = (Ticket.OPEN_STATUS, Ticket.REOPENED_STATUS) return TicketDependency.objects.filter(ticket=self).filter( depends_on__status__in=OPEN_STATUSES).count() == 0 can_be_resolved = property(_can_be_resolved) def get_submitter_userprofile(self): User = get_user_model() try: return User.objects.get(email=self.submitter_email) except (User.DoesNotExist, User.MultipleObjectsReturned): return None class Meta: get_latest_by = "created" ordering = ('id',) verbose_name = _('Ticket') verbose_name_plural = _('Tickets') def __str__(self): return '%s %s' % (self.id, self.title) def get_absolute_url(self): from django.urls import reverse return reverse('helpdesk:view', args=(self.id,)) def save(self, *args, **kwargs): if not self.id: # This is a new ticket as no ID yet exists. self.created = timezone.now() if not self.priority: self.priority = 3 self.modified = timezone.now() if len(self.title) > 200: self.title = self.title[:197] + "..." super(Ticket, self).save(*args, **kwargs) @staticmethod def queue_and_id_from_query(query): # Apply the opposite logic here compared to self._get_ticket_for_url # Ensure that queues with '-' in them will work parts = query.split('-') queue = '-'.join(parts[0:-1]) return queue, parts[-1] def get_markdown(self): return get_markdown(self.description) @property def get_resolution_markdown(self): return get_markdown(self.resolution) def add_email_to_ticketcc_if_not_in(self, email=None, user=None, ticketcc=None): """ Check that given email/user_email/ticketcc_email is not already present on the ticket (submitter email, assigned to, or in ticket CCs) and add it to a new ticket CC, or move the given one :param str email: :param User user: :param TicketCC ticketcc: :rtype: TicketCC|None """ if ticketcc: email = ticketcc.display elif user: if user.email: email = user.email else: # Ignore if user has no email address return elif not email: raise ValueError('You must provide at least one parameter to get the email from') # Prepare all emails already into the ticket ticket_emails = [x.display for x in self.ticketcc_set.all()] if self.submitter_email: ticket_emails.append(self.submitter_email) if self.assigned_to and self.assigned_to.email: ticket_emails.append(self.assigned_to.email) # Check that email is not already part of the ticket if email not in ticket_emails: if ticketcc: ticketcc.ticket = self ticketcc.save(update_fields=['ticket']) elif user: ticketcc = self.ticketcc_set.create(user=user) else: ticketcc = self.ticketcc_set.create(email=email) return ticketcc class FollowUpManager(models.Manager): def private_followups(self): return self.filter(public=False) def public_followups(self): return self.filter(public=True) class FollowUp(models.Model): """ A FollowUp is a comment and/or change to a ticket. We keep a simple title, the comment entered by the user, and the new status of a ticket to enable easy flagging of details on the view-ticket page. The title is automatically generated at save-time, based on what action the user took. Tickets that aren't public are never shown to or e-mailed to the submitter, although all staff can see them. """ ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Ticket'), ) date = models.DateTimeField( _('Date'), default=timezone.now ) title = models.CharField( _('Title'), max_length=200, blank=True, null=True, ) comment = models.TextField( _('Comment'), blank=True, null=True, ) public = models.BooleanField( _('Public'), blank=True, default=False, help_text=_( 'Public tickets are viewable by the submitter and all ' 'staff, but non-public tickets can only be seen by staff.' ), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, verbose_name=_('User'), ) new_status = models.IntegerField( _('New Status'), choices=Ticket.STATUS_CHOICES, blank=True, null=True, help_text=_('If the status was changed, what was it changed to?'), ) message_id = models.CharField( _('E-Mail ID'), max_length=256, blank=True, null=True, help_text=_("The Message ID of the submitter's email."), editable=False, ) objects = FollowUpManager() time_spent = models.DurationField( help_text=_("Time spent on this follow up"), blank=True, null=True ) class Meta: ordering = ('date',) verbose_name = _('Follow-up') verbose_name_plural = _('Follow-ups') def __str__(self): return '%s' % self.title def get_absolute_url(self): return u"%s#followup%s" % (self.ticket.get_absolute_url(), self.id) def save(self, *args, **kwargs): t = self.ticket t.modified = timezone.now() t.save() super(FollowUp, self).save(*args, **kwargs) def get_markdown(self): return get_markdown(self.comment) @property def time_spent_formated(self): return format_time_spent(self.time_spent) class TicketChange(models.Model): """ For each FollowUp, any changes to the parent ticket (eg Title, Priority, etc) are tracked here for display purposes. """ followup = models.ForeignKey( FollowUp, on_delete=models.CASCADE, verbose_name=_('Follow-up'), ) field = models.CharField( _('Field'), max_length=100, ) old_value = models.TextField( _('Old Value'), blank=True, null=True, ) new_value = models.TextField( _('New Value'), blank=True, null=True, ) def __str__(self): out = '%s ' % self.field if not self.new_value: out += ugettext('removed') elif not self.old_value: out += ugettext('set to %s') % self.new_value else: out += ugettext('changed from "%(old_value)s" to "%(new_value)s"') % { 'old_value': self.old_value, 'new_value': self.new_value } return out class Meta: verbose_name = _('Ticket change') verbose_name_plural = _('Ticket changes') def attachment_path(instance, filename): """Just bridge""" return instance.attachment_path(filename) class Attachment(models.Model): """ Represents a file attached to a follow-up. This could come from an e-mail attachment, or it could be uploaded via the web interface. """ file = models.FileField( _('File'), upload_to=attachment_path, max_length=1000, validators=[validate_file_extension] ) filename = models.CharField( _('Filename'), blank=True, max_length=1000, ) mime_type = models.CharField( _('MIME Type'), blank=True, max_length=255, ) size = models.IntegerField( _('Size'), blank=True, help_text=_('Size of this file in bytes'), ) def __str__(self): return '%s' % self.filename def save(self, *args, **kwargs): if not self.size: self.size = self.get_size() if not self.filename: self.filename = self.get_filename() if not self.mime_type: self.mime_type = \ mimetypes.guess_type(self.filename, strict=False)[0] or \ 'application/octet-stream' return super(Attachment, self).save(*args, **kwargs) def get_filename(self): return str(self.file) def get_size(self): return self.file.file.size def attachment_path(self, filename): """Provide a file path that will help prevent files being overwritten, by putting attachments in a folder off attachments for ticket/followup_id/. """ assert NotImplementedError( "This method is to be implemented by Attachment classes" ) class Meta: ordering = ('filename',) verbose_name = _('Attachment') verbose_name_plural = _('Attachments') abstract = True class FollowUpAttachment(Attachment): followup = models.ForeignKey( FollowUp, on_delete=models.CASCADE, verbose_name=_('Follow-up'), ) def attachment_path(self, filename): os.umask(0) path = 'helpdesk/attachments/{ticket_for_url}-{secret_key}/{id_}'.format( ticket_for_url=self.followup.ticket.ticket_for_url, secret_key=self.followup.ticket.secret_key, id_=self.followup.id) att_path = os.path.join(settings.MEDIA_ROOT, path) if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage": if not os.path.exists(att_path): os.makedirs(att_path, 0o777) return os.path.join(path, filename) class KBIAttachment(Attachment): kbitem = models.ForeignKey( "KBItem", on_delete=models.CASCADE, verbose_name=_('Knowledge base item'), ) def attachment_path(self, filename): os.umask(0) path = 'helpdesk/attachments/kb/{category}/{kbi}'.format( category=self.kbitem.category, kbi=self.kbitem.id) att_path = os.path.join(settings.MEDIA_ROOT, path) if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage": if not os.path.exists(att_path): os.makedirs(att_path, 0o777) return os.path.join(path, filename) class PreSetReply(models.Model): """ We can allow the admin to define a number of pre-set replies, used to simplify the sending of updates and resolutions. These are basically Django templates with a limited context - however if you wanted to get crafy it would be easy to write a reply that displays ALL updates in hierarchical order etc with use of for loops over {{ ticket.followup_set.all }} and friends. When replying to a ticket, the user can select any reply set for the current queue, and the body text is fetched via AJAX. """ class Meta: ordering = ('name',) verbose_name = _('Pre-set reply') verbose_name_plural = _('Pre-set replies') queues = models.ManyToManyField( Queue, blank=True, help_text=_('Leave blank to allow this reply to be used for all ' 'queues, or select those queues you wish to limit this reply to.'), ) name = models.CharField( _('Name'), max_length=100, help_text=_('Only used to assist users with selecting a reply - not ' 'shown to the user.'), ) body = models.TextField( _('Body'), help_text=_('Context available: {{ ticket }} - ticket object (eg ' '{{ ticket.title }}); {{ queue }} - The queue; and {{ user }} ' '- the current user.'), ) def __str__(self): return '%s' % self.name class EscalationExclusion(models.Model): """ An 'EscalationExclusion' lets us define a date on which escalation should not happen, for example a weekend or public holiday. You may also have a queue that is only used on one day per week. To create these on a regular basis, check out the README file for an example cronjob that runs 'create_escalation_exclusions.py'. """ queues = models.ManyToManyField( Queue, blank=True, help_text=_('Leave blank for this exclusion to be applied to all queues, ' 'or select those queues you wish to exclude with this entry.'), ) name = models.CharField( _('Name'), max_length=100, ) date = models.DateField( _('Date'), help_text=_('Date on which escalation should not happen'), ) def __str__(self): return '%s' % self.name class Meta: verbose_name = _('Escalation exclusion') verbose_name_plural = _('Escalation exclusions') class EmailTemplate(models.Model): """ Since these are more likely to be changed than other templates, we store them in the database. This means that an admin can change email templates without having to have access to the filesystem. """ template_name = models.CharField( _('Template Name'), max_length=100, ) subject = models.CharField( _('Subject'), max_length=100, help_text=_('This will be prefixed with "[ticket.ticket] ticket.title"' '. We recommend something simple such as "(Updated") or "(Closed)"' ' - the same context is available as in plain_text, below.'), ) heading = models.CharField( _('Heading'), max_length=100, help_text=_('In HTML e-mails, this will be the heading at the top of ' 'the email - the same context is available as in plain_text, ' 'below.'), ) plain_text = models.TextField( _('Plain Text'), help_text=_('The context available to you includes {{ ticket }}, ' '{{ queue }}, and depending on the time of the call: ' '{{ resolution }} or {{ comment }}.'), ) html = models.TextField( _('HTML'), help_text=_('The same context is available here as in plain_text, above.'), ) locale = models.CharField( _('Locale'), max_length=10, blank=True, null=True, help_text=_('Locale of this template.'), ) def __str__(self): return '%s' % self.template_name class Meta: ordering = ('template_name', 'locale') verbose_name = _('e-mail template') verbose_name_plural = _('e-mail templates') class KBCategory(models.Model): """ Lets help users help themselves: the Knowledge Base is a categorised listing of questions & answers. """ name = models.CharField( _('Name of the category'), max_length=100, ) title = models.CharField( _('Title on knowledgebase page'), max_length=100, ) slug = models.SlugField( _('Slug'), ) description = models.TextField( _('Description'), ) queue = models.ForeignKey( Queue, blank=True, null=True, on_delete=models.CASCADE, verbose_name=_('Default queue when creating a ticket after viewing this category.'), ) public = models.BooleanField( default=True, verbose_name=_("Is KBCategory publicly visible?") ) def __str__(self): return '%s' % self.name class Meta: ordering = ('title',) verbose_name = _('Knowledge base category') verbose_name_plural = _('Knowledge base categories') def get_absolute_url(self): from django.urls import reverse return reverse('helpdesk:kb_category', kwargs={'slug': self.slug}) class KBItem(models.Model): """ An item within the knowledgebase. Very straightforward question/answer style system. """ voted_by = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='votes', ) downvoted_by = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='downvotes', ) category = models.ForeignKey( KBCategory, on_delete=models.CASCADE, verbose_name=_('Category'), ) title = models.CharField( _('Title'), max_length=100, ) question = models.TextField( _('Question'), ) answer = models.TextField( _('Answer'), ) votes = models.IntegerField( _('Votes'), help_text=_('Total number of votes cast for this item'), default=0, ) recommendations = models.IntegerField( _('Positive Votes'), help_text=_('Number of votes for this item which were POSITIVE.'), default=0, ) last_updated = models.DateTimeField( _('Last Updated'), help_text=_('The date on which this question was most recently changed.'), blank=True, ) team = models.ForeignKey( helpdesk_settings.HELPDESK_TEAMS_MODEL, on_delete=models.CASCADE, verbose_name=_('Team'), blank=True, null=True, ) order = models.PositiveIntegerField( _('Order'), blank=True, null=True, ) enabled = models.BooleanField( _('Enabled to display to users'), default=True, ) def save(self, *args, **kwargs): if not self.last_updated: self.last_updated = timezone.now() return super(KBItem, self).save(*args, **kwargs) def get_team(self): return helpdesk_settings.HELPDESK_KBITEM_TEAM_GETTER(self) def _score(self): """ Return a score out of 10 or Unrated if no votes """ if self.votes > 0: return (self.recommendations / self.votes) * 10 else: return _('Unrated') score = property(_score) def __str__(self): return '%s: %s' % (self.category.title, self.title) class Meta: ordering = ('order', 'title',) verbose_name = _('Knowledge base item') verbose_name_plural = _('Knowledge base items') def get_absolute_url(self): from django.urls import reverse return str(reverse('helpdesk:kb_category', args=(self.category.slug,))) + "?kbitem=" + str(self.pk) def query_url(self): from django.urls import reverse return str(reverse('helpdesk:list')) + "?kbitem=" + str(self.pk) def num_open_tickets(self): return Ticket.objects.filter(kbitem=self, status__in=(1, 2)).count() def unassigned_tickets(self): return Ticket.objects.filter(kbitem=self, status__in=(1, 2), assigned_to__isnull=True) def get_markdown(self): return get_markdown(self.answer) class SavedSearch(models.Model): """ Allow a user to save a ticket search, eg their filtering and sorting options, and optionally share it with other users. This lets people easily create a set of commonly-used filters, such as: * My tickets waiting on me * My tickets waiting on submitter * My tickets in 'Priority Support' queue with priority of 1 * All tickets containing the word 'billing'. etc... """ user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_('User'), ) title = models.CharField( _('Query Name'), max_length=100, help_text=_('User-provided name for this query'), ) shared = models.BooleanField( _('Shared With Other Users?'), blank=True, default=False, help_text=_('Should other users see this query?'), ) query = models.TextField( _('Search Query'), help_text=_('Pickled query object. Be wary changing this.'), ) def __str__(self): if self.shared: return '%s (*)' % self.title else: return '%s' % self.title class Meta: verbose_name = _('Saved search') verbose_name_plural = _('Saved searches') def get_default_setting(setting): from helpdesk.settings import DEFAULT_USER_SETTINGS return DEFAULT_USER_SETTINGS[setting] def login_view_ticketlist_default(): return get_default_setting('login_view_ticketlist') def email_on_ticket_change_default(): return get_default_setting('email_on_ticket_change') def email_on_ticket_assign_default(): return get_default_setting('email_on_ticket_assign') def tickets_per_page_default(): return get_default_setting('tickets_per_page') def use_email_as_submitter_default(): return get_default_setting('use_email_as_submitter') class UserSettings(models.Model): """ A bunch of user-specific settings that we want to be able to define, such as notification preferences and other things that should probably be configurable. """ PAGE_SIZES = ((10, '10'), (25, '25'), (50, '50'), (100, '100')) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="usersettings_helpdesk") settings_pickled = models.TextField( _('DEPRECATED! Settings Dictionary DEPRECATED!'), help_text=_('DEPRECATED! This is a base64-encoded representation of a pickled Python dictionary. ' 'Do not change this field via the admin.'), blank=True, null=True, ) login_view_ticketlist = models.BooleanField( verbose_name=_('Show Ticket List on Login?'), help_text=_('Display the ticket list upon login? Otherwise, the dashboard is shown.'), default=login_view_ticketlist_default, ) email_on_ticket_change = models.BooleanField( verbose_name=_('E-mail me on ticket change?'), help_text=_( 'If you\'re the ticket owner and the ticket is changed via the web by somebody else,' 'do you want to receive an e-mail?' ), default=email_on_ticket_change_default, ) email_on_ticket_assign = models.BooleanField( verbose_name=_('E-mail me when assigned a ticket?'), help_text=_('If you are assigned a ticket via the web, do you want to receive an e-mail?'), default=email_on_ticket_assign_default, ) tickets_per_page = models.IntegerField( verbose_name=_('Number of tickets to show per page'), help_text=_('How many tickets do you want to see on the Ticket List page?'), default=tickets_per_page_default, choices=PAGE_SIZES, ) use_email_as_submitter = models.BooleanField( verbose_name=_('Use my e-mail address when submitting tickets?'), help_text=_('When you submit a ticket, do you want to automatically ' 'use your e-mail address as the submitter address? You ' 'can type a different e-mail address when entering the ' 'ticket if needed, this option only changes the default.'), default=use_email_as_submitter_default, ) def __str__(self): return 'Preferences for %s' % self.user class Meta: verbose_name = _('User Setting') verbose_name_plural = _('User Settings') def create_usersettings(sender, instance, created, **kwargs): """ Helper function to create UserSettings instances as required, eg when we first create the UserSettings database table via 'syncdb' or when we save a new user. If we end up with users with no UserSettings, then we get horrible 'DoesNotExist: UserSettings matching query does not exist.' errors. """ if created: UserSettings.objects.create(user=instance) models.signals.post_save.connect(create_usersettings, sender=settings.AUTH_USER_MODEL) class IgnoreEmail(models.Model): """ This model lets us easily ignore e-mails from certain senders when processing IMAP and POP3 mailboxes, eg mails from postmaster or from known trouble-makers. """ class Meta: verbose_name = _('Ignored e-mail address') verbose_name_plural = _('Ignored e-mail addresses') queues = models.ManyToManyField( Queue, blank=True, help_text=_('Leave blank for this e-mail to be ignored on all queues, ' 'or select those queues you wish to ignore this e-mail for.'), ) name = models.CharField( _('Name'), max_length=100, ) date = models.DateField( _('Date'), help_text=_('Date on which this e-mail address was added'), blank=True, editable=False ) email_address = models.CharField( _('E-Mail Address'), max_length=150, help_text=_('Enter a full e-mail address, or portions with ' 'wildcards, eg *@domain.com or postmaster@*.'), ) keep_in_mailbox = models.BooleanField( _('Save Emails in Mailbox?'), blank=True, default=False, help_text=_('Do you want to save emails from this address in the mailbox? ' 'If this is unticked, emails from this address will be deleted.'), ) def __str__(self): return '%s' % self.name def save(self, *args, **kwargs): if not self.date: self.date = timezone.now() return super(IgnoreEmail, self).save(*args, **kwargs) def queue_list(self): """Return a list of the queues this IgnoreEmail applies to. If this IgnoreEmail applies to ALL queues, return '*'. """ queues = self.queues.all().order_by('title') if len(queues) == 0: return '*' else: return ', '.join([str(q) for q in queues]) def test(self, email): """ Possible situations: 1. Username & Domain both match 2. Username is wildcard, domain matches 3. Username matches, domain is wildcard 4. username & domain are both wildcards 5. Other (no match) 1-4 return True, 5 returns False. """ own_parts = self.email_address.split("@") email_parts = email.split("@") if self.email_address == email or \ own_parts[0] == "*" and own_parts[1] == email_parts[1] or \ own_parts[1] == "*" and own_parts[0] == email_parts[0] or \ own_parts[0] == "*" and own_parts[1] == "*": return True else: return False class TicketCC(models.Model): """ Often, there are people who wish to follow a ticket who aren't the person who originally submitted it. This model provides a way for those people to follow a ticket. In this circumstance, a 'person' could be either an e-mail address or an existing system user. """ ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Ticket'), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, help_text=_('User who wishes to receive updates for this ticket.'), verbose_name=_('User'), ) email = models.EmailField( _('E-Mail Address'), blank=True, null=True, help_text=_('For non-user followers, enter their e-mail address'), ) can_view = models.BooleanField( _('Can View Ticket?'), blank=True, default=False, help_text=_('Can this CC login to view the ticket details?'), ) can_update = models.BooleanField( _('Can Update Ticket?'), blank=True, default=False, help_text=_('Can this CC login and update the ticket?'), ) def _email_address(self): if self.user and self.user.email is not None: return self.user.email else: return self.email email_address = property(_email_address) def _display(self): if self.user: return self.user else: return self.email display = property(_display) def __str__(self): return '%s for %s' % (self.display, self.ticket.title) def clean(self): if self.user and not self.user.email: raise ValidationError('User has no email address') class CustomFieldManager(models.Manager): def get_queryset(self): return super(CustomFieldManager, self).get_queryset().order_by('ordering') class CustomField(models.Model): """ Definitions for custom fields that are glued onto each ticket. """ name = models.SlugField( _('Field Name'), help_text=_('As used in the database and behind the scenes. ' 'Must be unique and consist of only lowercase letters with no punctuation.'), unique=True, ) label = models.CharField( _('Label'), max_length=30, help_text=_('The display label for this field'), ) help_text = models.TextField( _('Help Text'), help_text=_('Shown to the user when editing the ticket'), blank=True, null=True ) DATA_TYPE_CHOICES = ( ('varchar', _('Character (single line)')), ('text', _('Text (multi-line)')), ('integer', _('Integer')), ('decimal', _('Decimal')), ('list', _('List')), ('boolean', _('Boolean (checkbox yes/no)')), ('date', _('Date')), ('time', _('Time')), ('datetime', _('Date & Time')), ('email', _('E-Mail Address')), ('url', _('URL')), ('ipaddress', _('IP Address')), ('slug', _('Slug')), ) data_type = models.CharField( _('Data Type'), max_length=100, help_text=_('Allows you to restrict the data entered into this field'), choices=DATA_TYPE_CHOICES, ) max_length = models.IntegerField( _('Maximum Length (characters)'), blank=True, null=True, ) decimal_places = models.IntegerField( _('Decimal Places'), help_text=_('Only used for decimal fields'), blank=True, null=True, ) empty_selection_list = models.BooleanField( _('Add empty first choice to List?'), default=False, help_text=_('Only for List: adds an empty first entry to the choices list, ' 'which enforces that the user makes an active choice.'), ) list_values = models.TextField( _('List Values'), help_text=_('For list fields only. Enter one option per line.'), blank=True, null=True, ) ordering = models.IntegerField( _('Ordering'), help_text=_('Lower numbers are displayed first; higher numbers are listed later'), blank=True, null=True, ) def _choices_as_array(self): valuebuffer = StringIO(self.list_values) choices = [[item.strip(), item.strip()] for item in valuebuffer.readlines()] valuebuffer.close() return choices choices_as_array = property(_choices_as_array) required = models.BooleanField( _('Required?'), help_text=_('Does the user have to enter a value for this field?'), default=False, ) staff_only = models.BooleanField( _('Staff Only?'), help_text=_('If this is ticked, then the public submission form ' 'will NOT show this field'), default=False, ) objects = CustomFieldManager() def __str__(self): return '%s' % self.name class Meta: verbose_name = _('Custom field') verbose_name_plural = _('Custom fields') class TicketCustomFieldValue(models.Model): ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Ticket'), ) field = models.ForeignKey( CustomField, on_delete=models.CASCADE, verbose_name=_('Field'), ) value = models.TextField(blank=True, null=True) def __str__(self): return '%s / %s' % (self.ticket, self.field) class Meta: unique_together = (('ticket', 'field'),) verbose_name = _('Ticket custom field value') verbose_name_plural = _('Ticket custom field values') class TicketDependency(models.Model): """ The ticket identified by `ticket` cannot be resolved until the ticket in `depends_on` has been resolved. To help enforce this, a helper function `can_be_resolved` on each Ticket instance checks that these have all been resolved. """ class Meta: unique_together = (('ticket', 'depends_on'),) verbose_name = _('Ticket dependency') verbose_name_plural = _('Ticket dependencies') ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Ticket'), related_name='ticketdependency', ) depends_on = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Depends On Ticket'), related_name='depends_on', ) def __str__(self): return '%s / %s' % (self.ticket, self.depends_on)
""" django-helpdesk - A Django powered ticket tracker for small enterprise. (c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details. models.py - Model (and hence database) definitions. This is the core of the helpdesk structure. """ from django.contrib.auth.models import Permission from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db import models from django.conf import settings from django.utils import timezone from django.utils.translation import ugettext_lazy as _, ugettext from io import StringIO import re import os import mimetypes import datetime from django.utils.safestring import mark_safe from markdown import markdown from markdown.extensions import Extension import uuid from helpdesk import settings as helpdesk_settings from .validators import validate_file_extension from .templated_email import send_templated_mail def format_time_spent(time_spent): if time_spent: time_spent = "{0:02d}h:{1:02d}m".format( time_spent.seconds // 3600, time_spent.seconds % 3600 // 60 ) else: time_spent = "" return time_spent class EscapeHtml(Extension): def extendMarkdown(self, md, md_globals): del md.preprocessors['html_block'] del md.inlinePatterns['html'] def get_markdown(text): if not text: return "" pattern = fr'([\[\s\S\]]*?)\(([\s\S]*?):([\s\S]*?)\)' # Regex check if re.match(pattern, text): # get get value of group regex scheme = re.search(pattern, text, re.IGNORECASE).group(2) # scheme check if scheme in helpdesk_settings.ALLOWED_URL_SCHEMES: replacement = '\\1(\\2:\\3)' else: replacement = '\\1(\\3)' text = re.sub(pattern, replacement, text, flags=re.IGNORECASE) return mark_safe( markdown( text, extensions=[ EscapeHtml(), 'markdown.extensions.nl2br', 'markdown.extensions.fenced_code' ] ) ) class Queue(models.Model): """ A queue is a collection of tickets into what would generally be business areas or departments. For example, a company may have a queue for each Product they provide, or a queue for each of Accounts, Pre-Sales, and Support. """ title = models.CharField( _('Title'), max_length=100, ) slug = models.SlugField( _('Slug'), max_length=50, unique=True, help_text=_('This slug is used when building ticket ID\'s. Once set, ' 'try not to change it or e-mailing may get messy.'), ) email_address = models.EmailField( _('E-Mail Address'), blank=True, null=True, help_text=_('All outgoing e-mails for this queue will use this e-mail ' 'address. If you use IMAP or POP3, this should be the e-mail ' 'address for that mailbox.'), ) locale = models.CharField( _('Locale'), max_length=10, blank=True, null=True, help_text=_('Locale of this queue. All correspondence in this ' 'queue will be in this language.'), ) allow_public_submission = models.BooleanField( _('Allow Public Submission?'), blank=True, default=False, help_text=_('Should this queue be listed on the public submission form?'), ) allow_email_submission = models.BooleanField( _('Allow E-Mail Submission?'), blank=True, default=False, help_text=_('Do you want to poll the e-mail box below for new ' 'tickets?'), ) escalate_days = models.IntegerField( _('Escalation Days'), blank=True, null=True, help_text=_('For tickets which are not held, how often do you wish to ' 'increase their priority? Set to 0 for no escalation.'), ) new_ticket_cc = models.CharField( _('New Ticket CC Address'), blank=True, null=True, max_length=200, help_text=_('If an e-mail address is entered here, then it will ' 'receive notification of all new tickets created for this queue. ' 'Enter a comma between multiple e-mail addresses.'), ) updated_ticket_cc = models.CharField( _('Updated Ticket CC Address'), blank=True, null=True, max_length=200, help_text=_('If an e-mail address is entered here, then it will ' 'receive notification of all activity (new tickets, closed ' 'tickets, updates, reassignments, etc) for this queue. Separate ' 'multiple addresses with a comma.'), ) enable_notifications_on_email_events = models.BooleanField( _('Notify contacts when email updates arrive'), blank=True, default=False, help_text=_('When an email arrives to either create a ticket or to ' 'interact with an existing discussion. Should email notifications be sent ? ' 'Note: the new_ticket_cc and updated_ticket_cc work independently of this feature'), ) email_box_type = models.CharField( _('E-Mail Box Type'), max_length=5, choices=(('pop3', _('POP 3')), ('imap', _('IMAP')), ('local', _('Local Directory'))), blank=True, null=True, help_text=_('E-Mail server type for creating tickets automatically ' 'from a mailbox - both POP3 and IMAP are supported, as well as ' 'reading from a local directory.'), ) email_box_host = models.CharField( _('E-Mail Hostname'), max_length=200, blank=True, null=True, help_text=_('Your e-mail server address - either the domain name or ' 'IP address. May be "localhost".'), ) email_box_port = models.IntegerField( _('E-Mail Port'), blank=True, null=True, help_text=_('Port number to use for accessing e-mail. Default for ' 'POP3 is "110", and for IMAP is "143". This may differ on some ' 'servers. Leave it blank to use the defaults.'), ) email_box_ssl = models.BooleanField( _('Use SSL for E-Mail?'), blank=True, default=False, help_text=_('Whether to use SSL for IMAP or POP3 - the default ports ' 'when using SSL are 993 for IMAP and 995 for POP3.'), ) email_box_user = models.CharField( _('E-Mail Username'), max_length=200, blank=True, null=True, help_text=_('Username for accessing this mailbox.'), ) email_box_pass = models.CharField( _('E-Mail Password'), max_length=200, blank=True, null=True, help_text=_('Password for the above username'), ) email_box_imap_folder = models.CharField( _('IMAP Folder'), max_length=100, blank=True, null=True, help_text=_('If using IMAP, what folder do you wish to fetch messages ' 'from? This allows you to use one IMAP account for multiple ' 'queues, by filtering messages on your IMAP server into separate ' 'folders. Default: INBOX.'), ) email_box_local_dir = models.CharField( _('E-Mail Local Directory'), max_length=200, blank=True, null=True, help_text=_('If using a local directory, what directory path do you ' 'wish to poll for new email? ' 'Example: /var/lib/mail/helpdesk/'), ) permission_name = models.CharField( _('Django auth permission name'), max_length=72, # based on prepare_permission_name() pre-pending chars to slug blank=True, null=True, editable=False, help_text=_('Name used in the django.contrib.auth permission system'), ) email_box_interval = models.IntegerField( _('E-Mail Check Interval'), help_text=_('How often do you wish to check this mailbox? (in Minutes)'), blank=True, null=True, default='5', ) email_box_last_check = models.DateTimeField( blank=True, null=True, editable=False, # This is updated by management/commands/get_mail.py. ) socks_proxy_type = models.CharField( _('Socks Proxy Type'), max_length=8, choices=(('socks4', _('SOCKS4')), ('socks5', _('SOCKS5'))), blank=True, null=True, help_text=_('SOCKS4 or SOCKS5 allows you to proxy your connections through a SOCKS server.'), ) socks_proxy_host = models.GenericIPAddressField( _('Socks Proxy Host'), blank=True, null=True, help_text=_('Socks proxy IP address. Default: 127.0.0.1'), ) socks_proxy_port = models.IntegerField( _('Socks Proxy Port'), blank=True, null=True, help_text=_('Socks proxy port number. Default: 9150 (default TOR port)'), ) logging_type = models.CharField( _('Logging Type'), max_length=5, choices=( ('none', _('None')), ('debug', _('Debug')), ('info', _('Information')), ('warn', _('Warning')), ('error', _('Error')), ('crit', _('Critical')) ), blank=True, null=True, help_text=_('Set the default logging level. All messages at that ' 'level or above will be logged to the directory set ' 'below. If no level is set, logging will be disabled.'), ) logging_dir = models.CharField( _('Logging Directory'), max_length=200, blank=True, null=True, help_text=_('If logging is enabled, what directory should we use to ' 'store log files for this queue? ' 'The standard logging mechanims are used if no directory is set'), ) default_owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='default_owner', blank=True, null=True, verbose_name=_('Default owner'), ) dedicated_time = models.DurationField( help_text=_("Time to be spent on this Queue in total"), blank=True, null=True ) def __str__(self): return "%s" % self.title class Meta: ordering = ('title',) verbose_name = _('Queue') verbose_name_plural = _('Queues') def _from_address(self): """ Short property to provide a sender address in SMTP format, eg 'Name <email>'. We do this so we can put a simple error message in the sender name field, so hopefully the admin can see and fix it. """ if not self.email_address: # must check if given in format "Foo <foo@example.com>" default_email = re.match(".*<(?P<email>.*@*.)>", settings.DEFAULT_FROM_EMAIL) if default_email is not None: # already in the right format, so just include it here return u'NO QUEUE EMAIL ADDRESS DEFINED %s' % settings.DEFAULT_FROM_EMAIL else: return u'NO QUEUE EMAIL ADDRESS DEFINED <%s>' % settings.DEFAULT_FROM_EMAIL else: return u'%s <%s>' % (self.title, self.email_address) from_address = property(_from_address) @property def time_spent(self): """Return back total time spent on the ticket. This is calculated value based on total sum from all FollowUps """ total = datetime.timedelta(0) for val in self.ticket_set.all(): if val.time_spent: total = total + val.time_spent return total @property def time_spent_formated(self): return format_time_spent(self.time_spent) def prepare_permission_name(self): """Prepare internally the codename for the permission and store it in permission_name. :return: The codename that can be used to create a new Permission object. """ # Prepare the permission associated to this Queue basename = "queue_access_%s" % self.slug self.permission_name = "helpdesk.%s" % basename return basename def save(self, *args, **kwargs): if self.email_box_type == 'imap' and not self.email_box_imap_folder: self.email_box_imap_folder = 'INBOX' if self.socks_proxy_type: if not self.socks_proxy_host: self.socks_proxy_host = '127.0.0.1' if not self.socks_proxy_port: self.socks_proxy_port = 9150 else: self.socks_proxy_host = None self.socks_proxy_port = None if not self.email_box_port: if self.email_box_type == 'imap' and self.email_box_ssl: self.email_box_port = 993 elif self.email_box_type == 'imap' and not self.email_box_ssl: self.email_box_port = 143 elif self.email_box_type == 'pop3' and self.email_box_ssl: self.email_box_port = 995 elif self.email_box_type == 'pop3' and not self.email_box_ssl: self.email_box_port = 110 if not self.id: # Prepare the permission codename and the permission # (even if they are not needed with the current configuration) basename = self.prepare_permission_name() Permission.objects.create( name=_("Permission for queue: ") + self.title, content_type=ContentType.objects.get_for_model(self.__class__), codename=basename, ) super(Queue, self).save(*args, **kwargs) def delete(self, *args, **kwargs): permission_name = self.permission_name super(Queue, self).delete(*args, **kwargs) # once the Queue is safely deleted, remove the permission (if exists) if permission_name: try: p = Permission.objects.get(codename=permission_name[9:]) p.delete() except ObjectDoesNotExist: pass def mk_secret(): return str(uuid.uuid4()) class Ticket(models.Model): """ To allow a ticket to be entered as quickly as possible, only the bare minimum fields are required. These basically allow us to sort and manage the ticket. The user can always go back and enter more information later. A good example of this is when a customer is on the phone, and you want to give them a ticket ID as quickly as possible. You can enter some basic info, save the ticket, give the customer the ID and get off the phone, then add in further detail at a later time (once the customer is not on the line). Note that assigned_to is optional - unassigned tickets are displayed on the dashboard to prompt users to take ownership of them. """ OPEN_STATUS = 1 REOPENED_STATUS = 2 RESOLVED_STATUS = 3 CLOSED_STATUS = 4 DUPLICATE_STATUS = 5 STATUS_CHOICES = ( (OPEN_STATUS, _('Open')), (REOPENED_STATUS, _('Reopened')), (RESOLVED_STATUS, _('Resolved')), (CLOSED_STATUS, _('Closed')), (DUPLICATE_STATUS, _('Duplicate')), ) PRIORITY_CHOICES = ( (1, _('1. Critical')), (2, _('2. High')), (3, _('3. Normal')), (4, _('4. Low')), (5, _('5. Very Low')), ) title = models.CharField( _('Title'), max_length=200, ) queue = models.ForeignKey( Queue, on_delete=models.CASCADE, verbose_name=_('Queue'), ) created = models.DateTimeField( _('Created'), blank=True, help_text=_('Date this ticket was first created'), ) modified = models.DateTimeField( _('Modified'), blank=True, help_text=_('Date this ticket was most recently changed.'), ) submitter_email = models.EmailField( _('Submitter E-Mail'), blank=True, null=True, help_text=_('The submitter will receive an email for all public ' 'follow-ups left for this task.'), ) assigned_to = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='assigned_to', blank=True, null=True, verbose_name=_('Assigned to'), ) status = models.IntegerField( _('Status'), choices=STATUS_CHOICES, default=OPEN_STATUS, ) on_hold = models.BooleanField( _('On Hold'), blank=True, default=False, help_text=_('If a ticket is on hold, it will not automatically be escalated.'), ) description = models.TextField( _('Description'), blank=True, null=True, help_text=_('The content of the customers query.'), ) resolution = models.TextField( _('Resolution'), blank=True, null=True, help_text=_('The resolution provided to the customer by our staff.'), ) priority = models.IntegerField( _('Priority'), choices=PRIORITY_CHOICES, default=3, blank=3, help_text=_('1 = Highest Priority, 5 = Low Priority'), ) due_date = models.DateTimeField( _('Due on'), blank=True, null=True, ) last_escalation = models.DateTimeField( blank=True, null=True, editable=False, help_text=_('The date this ticket was last escalated - updated ' 'automatically by management/commands/escalate_tickets.py.'), ) secret_key = models.CharField( _("Secret key needed for viewing/editing ticket by non-logged in users"), max_length=36, default=mk_secret, ) kbitem = models.ForeignKey( "KBItem", blank=True, null=True, on_delete=models.CASCADE, verbose_name=_('Knowledge base item the user was viewing when they created this ticket.'), ) merged_to = models.ForeignKey( 'self', verbose_name=_('merged to'), related_name='merged_tickets', on_delete=models.CASCADE, null=True, blank=True ) @property def time_spent(self): """Return back total time spent on the ticket. This is calculated value based on total sum from all FollowUps """ total = datetime.timedelta(0) for val in self.followup_set.all(): if val.time_spent: total = total + val.time_spent return total @property def time_spent_formated(self): return format_time_spent(self.time_spent) def send(self, roles, dont_send_to=None, **kwargs): """ Send notifications to everyone interested in this ticket. The the roles argument is a dictionary mapping from roles to (template, context) pairs. If a role is not present in the dictionary, users of that type will not receive the notification. The following roles exist: - 'submitter' - 'new_ticket_cc' - 'ticket_cc' - 'assigned_to' Here is an example roles dictionary: { 'submitter': (template_name, context), 'assigned_to': (template_name2, context), } **kwargs are passed to send_templated_mail defined in templated_email.py returns the set of email addresses the notification was delivered to. """ recipients = set() if dont_send_to is not None: recipients.update(dont_send_to) recipients.add(self.queue.email_address) def should_receive(email): return email and email not in recipients def send(role, recipient): if recipient and recipient not in recipients and role in roles: template, context = roles[role] send_templated_mail(template, context, recipient, sender=self.queue.from_address, **kwargs) recipients.add(recipient) send('submitter', self.submitter_email) send('ticket_cc', self.queue.updated_ticket_cc) send('new_ticket_cc', self.queue.new_ticket_cc) if self.assigned_to: send('assigned_to', self.assigned_to.email) if self.queue.enable_notifications_on_email_events: for cc in self.ticketcc_set.all(): send('ticket_cc', cc.email_address) return recipients def _get_assigned_to(self): """ Custom property to allow us to easily print 'Unassigned' if a ticket has no owner, or the users name if it's assigned. If the user has a full name configured, we use that, otherwise their username. """ if not self.assigned_to: return _('Unassigned') else: if self.assigned_to.get_full_name(): return self.assigned_to.get_full_name() else: return self.assigned_to.get_username() get_assigned_to = property(_get_assigned_to) def _get_ticket(self): """ A user-friendly ticket ID, which is a combination of ticket ID and queue slug. This is generally used in e-mail subjects. """ return u"[%s]" % self.ticket_for_url ticket = property(_get_ticket) def _get_ticket_for_url(self): """ A URL-friendly ticket ID, used in links. """ return u"%s-%s" % (self.queue.slug, self.id) ticket_for_url = property(_get_ticket_for_url) def _get_priority_css_class(self): """ Return the boostrap class corresponding to the priority. """ if self.priority == 2: return "warning" elif self.priority == 1: return "danger" elif self.priority == 5: return "success" else: return "" get_priority_css_class = property(_get_priority_css_class) def _get_status(self): """ Displays the ticket status, with an "On Hold" message if needed. """ held_msg = '' if self.on_hold: held_msg = _(' - On Hold') dep_msg = '' if not self.can_be_resolved: dep_msg = _(' - Open dependencies') return u'%s%s%s' % (self.get_status_display(), held_msg, dep_msg) get_status = property(_get_status) def _get_ticket_url(self): """ Returns a publicly-viewable URL for this ticket, used when giving a URL to the submitter of a ticket. """ from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.urls import reverse try: site = Site.objects.get_current() except ImproperlyConfigured: site = Site(domain='configure-django-sites.com') if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK: protocol = 'https' else: protocol = 'http' return u"%s://%s%s?ticket=%s&email=%s&key=%s" % ( protocol, site.domain, reverse('helpdesk:public_view'), self.ticket_for_url, self.submitter_email, self.secret_key ) ticket_url = property(_get_ticket_url) def _get_staff_url(self): """ Returns a staff-only URL for this ticket, used when giving a URL to a staff member (in emails etc) """ from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.urls import reverse try: site = Site.objects.get_current() except ImproperlyConfigured: site = Site(domain='configure-django-sites.com') if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK: protocol = 'https' else: protocol = 'http' return u"%s://%s%s" % ( protocol, site.domain, reverse('helpdesk:view', args=[self.id]) ) staff_url = property(_get_staff_url) def _can_be_resolved(self): """ Returns a boolean. True = any dependencies are resolved False = There are non-resolved dependencies """ OPEN_STATUSES = (Ticket.OPEN_STATUS, Ticket.REOPENED_STATUS) return TicketDependency.objects.filter(ticket=self).filter( depends_on__status__in=OPEN_STATUSES).count() == 0 can_be_resolved = property(_can_be_resolved) def get_submitter_userprofile(self): User = get_user_model() try: return User.objects.get(email=self.submitter_email) except (User.DoesNotExist, User.MultipleObjectsReturned): return None class Meta: get_latest_by = "created" ordering = ('id',) verbose_name = _('Ticket') verbose_name_plural = _('Tickets') def __str__(self): return '%s %s' % (self.id, self.title) def get_absolute_url(self): from django.urls import reverse return reverse('helpdesk:view', args=(self.id,)) def save(self, *args, **kwargs): if not self.id: # This is a new ticket as no ID yet exists. self.created = timezone.now() if not self.priority: self.priority = 3 self.modified = timezone.now() if len(self.title) > 200: self.title = self.title[:197] + "..." super(Ticket, self).save(*args, **kwargs) @staticmethod def queue_and_id_from_query(query): # Apply the opposite logic here compared to self._get_ticket_for_url # Ensure that queues with '-' in them will work parts = query.split('-') queue = '-'.join(parts[0:-1]) return queue, parts[-1] def get_markdown(self): return get_markdown(self.description) @property def get_resolution_markdown(self): return get_markdown(self.resolution) def add_email_to_ticketcc_if_not_in(self, email=None, user=None, ticketcc=None): """ Check that given email/user_email/ticketcc_email is not already present on the ticket (submitter email, assigned to, or in ticket CCs) and add it to a new ticket CC, or move the given one :param str email: :param User user: :param TicketCC ticketcc: :rtype: TicketCC|None """ if ticketcc: email = ticketcc.display elif user: if user.email: email = user.email else: # Ignore if user has no email address return elif not email: raise ValueError('You must provide at least one parameter to get the email from') # Prepare all emails already into the ticket ticket_emails = [x.display for x in self.ticketcc_set.all()] if self.submitter_email: ticket_emails.append(self.submitter_email) if self.assigned_to and self.assigned_to.email: ticket_emails.append(self.assigned_to.email) # Check that email is not already part of the ticket if email not in ticket_emails: if ticketcc: ticketcc.ticket = self ticketcc.save(update_fields=['ticket']) elif user: ticketcc = self.ticketcc_set.create(user=user) else: ticketcc = self.ticketcc_set.create(email=email) return ticketcc class FollowUpManager(models.Manager): def private_followups(self): return self.filter(public=False) def public_followups(self): return self.filter(public=True) class FollowUp(models.Model): """ A FollowUp is a comment and/or change to a ticket. We keep a simple title, the comment entered by the user, and the new status of a ticket to enable easy flagging of details on the view-ticket page. The title is automatically generated at save-time, based on what action the user took. Tickets that aren't public are never shown to or e-mailed to the submitter, although all staff can see them. """ ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Ticket'), ) date = models.DateTimeField( _('Date'), default=timezone.now ) title = models.CharField( _('Title'), max_length=200, blank=True, null=True, ) comment = models.TextField( _('Comment'), blank=True, null=True, ) public = models.BooleanField( _('Public'), blank=True, default=False, help_text=_( 'Public tickets are viewable by the submitter and all ' 'staff, but non-public tickets can only be seen by staff.' ), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, verbose_name=_('User'), ) new_status = models.IntegerField( _('New Status'), choices=Ticket.STATUS_CHOICES, blank=True, null=True, help_text=_('If the status was changed, what was it changed to?'), ) message_id = models.CharField( _('E-Mail ID'), max_length=256, blank=True, null=True, help_text=_("The Message ID of the submitter's email."), editable=False, ) objects = FollowUpManager() time_spent = models.DurationField( help_text=_("Time spent on this follow up"), blank=True, null=True ) class Meta: ordering = ('date',) verbose_name = _('Follow-up') verbose_name_plural = _('Follow-ups') def __str__(self): return '%s' % self.title def get_absolute_url(self): return u"%s#followup%s" % (self.ticket.get_absolute_url(), self.id) def save(self, *args, **kwargs): t = self.ticket t.modified = timezone.now() t.save() super(FollowUp, self).save(*args, **kwargs) def get_markdown(self): return get_markdown(self.comment) @property def time_spent_formated(self): return format_time_spent(self.time_spent) class TicketChange(models.Model): """ For each FollowUp, any changes to the parent ticket (eg Title, Priority, etc) are tracked here for display purposes. """ followup = models.ForeignKey( FollowUp, on_delete=models.CASCADE, verbose_name=_('Follow-up'), ) field = models.CharField( _('Field'), max_length=100, ) old_value = models.TextField( _('Old Value'), blank=True, null=True, ) new_value = models.TextField( _('New Value'), blank=True, null=True, ) def __str__(self): out = '%s ' % self.field if not self.new_value: out += ugettext('removed') elif not self.old_value: out += ugettext('set to %s') % self.new_value else: out += ugettext('changed from "%(old_value)s" to "%(new_value)s"') % { 'old_value': self.old_value, 'new_value': self.new_value } return out class Meta: verbose_name = _('Ticket change') verbose_name_plural = _('Ticket changes') def attachment_path(instance, filename): """Just bridge""" return instance.attachment_path(filename) class Attachment(models.Model): """ Represents a file attached to a follow-up. This could come from an e-mail attachment, or it could be uploaded via the web interface. """ file = models.FileField( _('File'), upload_to=attachment_path, max_length=1000, validators=[validate_file_extension] ) filename = models.CharField( _('Filename'), blank=True, max_length=1000, ) mime_type = models.CharField( _('MIME Type'), blank=True, max_length=255, ) size = models.IntegerField( _('Size'), blank=True, help_text=_('Size of this file in bytes'), ) def __str__(self): return '%s' % self.filename def save(self, *args, **kwargs): if not self.size: self.size = self.get_size() if not self.filename: self.filename = self.get_filename() if not self.mime_type: self.mime_type = \ mimetypes.guess_type(self.filename, strict=False)[0] or \ 'application/octet-stream' return super(Attachment, self).save(*args, **kwargs) def get_filename(self): return str(self.file) def get_size(self): return self.file.file.size def attachment_path(self, filename): """Provide a file path that will help prevent files being overwritten, by putting attachments in a folder off attachments for ticket/followup_id/. """ assert NotImplementedError( "This method is to be implemented by Attachment classes" ) class Meta: ordering = ('filename',) verbose_name = _('Attachment') verbose_name_plural = _('Attachments') abstract = True class FollowUpAttachment(Attachment): followup = models.ForeignKey( FollowUp, on_delete=models.CASCADE, verbose_name=_('Follow-up'), ) def attachment_path(self, filename): os.umask(0) path = 'helpdesk/attachments/{ticket_for_url}-{secret_key}/{id_}'.format( ticket_for_url=self.followup.ticket.ticket_for_url, secret_key=self.followup.ticket.secret_key, id_=self.followup.id) att_path = os.path.join(settings.MEDIA_ROOT, path) if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage": if not os.path.exists(att_path): os.makedirs(att_path, 0o777) return os.path.join(path, filename) class KBIAttachment(Attachment): kbitem = models.ForeignKey( "KBItem", on_delete=models.CASCADE, verbose_name=_('Knowledge base item'), ) def attachment_path(self, filename): os.umask(0) path = 'helpdesk/attachments/kb/{category}/{kbi}'.format( category=self.kbitem.category, kbi=self.kbitem.id) att_path = os.path.join(settings.MEDIA_ROOT, path) if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage": if not os.path.exists(att_path): os.makedirs(att_path, 0o777) return os.path.join(path, filename) class PreSetReply(models.Model): """ We can allow the admin to define a number of pre-set replies, used to simplify the sending of updates and resolutions. These are basically Django templates with a limited context - however if you wanted to get crafy it would be easy to write a reply that displays ALL updates in hierarchical order etc with use of for loops over {{ ticket.followup_set.all }} and friends. When replying to a ticket, the user can select any reply set for the current queue, and the body text is fetched via AJAX. """ class Meta: ordering = ('name',) verbose_name = _('Pre-set reply') verbose_name_plural = _('Pre-set replies') queues = models.ManyToManyField( Queue, blank=True, help_text=_('Leave blank to allow this reply to be used for all ' 'queues, or select those queues you wish to limit this reply to.'), ) name = models.CharField( _('Name'), max_length=100, help_text=_('Only used to assist users with selecting a reply - not ' 'shown to the user.'), ) body = models.TextField( _('Body'), help_text=_('Context available: {{ ticket }} - ticket object (eg ' '{{ ticket.title }}); {{ queue }} - The queue; and {{ user }} ' '- the current user.'), ) def __str__(self): return '%s' % self.name class EscalationExclusion(models.Model): """ An 'EscalationExclusion' lets us define a date on which escalation should not happen, for example a weekend or public holiday. You may also have a queue that is only used on one day per week. To create these on a regular basis, check out the README file for an example cronjob that runs 'create_escalation_exclusions.py'. """ queues = models.ManyToManyField( Queue, blank=True, help_text=_('Leave blank for this exclusion to be applied to all queues, ' 'or select those queues you wish to exclude with this entry.'), ) name = models.CharField( _('Name'), max_length=100, ) date = models.DateField( _('Date'), help_text=_('Date on which escalation should not happen'), ) def __str__(self): return '%s' % self.name class Meta: verbose_name = _('Escalation exclusion') verbose_name_plural = _('Escalation exclusions') class EmailTemplate(models.Model): """ Since these are more likely to be changed than other templates, we store them in the database. This means that an admin can change email templates without having to have access to the filesystem. """ template_name = models.CharField( _('Template Name'), max_length=100, ) subject = models.CharField( _('Subject'), max_length=100, help_text=_('This will be prefixed with "[ticket.ticket] ticket.title"' '. We recommend something simple such as "(Updated") or "(Closed)"' ' - the same context is available as in plain_text, below.'), ) heading = models.CharField( _('Heading'), max_length=100, help_text=_('In HTML e-mails, this will be the heading at the top of ' 'the email - the same context is available as in plain_text, ' 'below.'), ) plain_text = models.TextField( _('Plain Text'), help_text=_('The context available to you includes {{ ticket }}, ' '{{ queue }}, and depending on the time of the call: ' '{{ resolution }} or {{ comment }}.'), ) html = models.TextField( _('HTML'), help_text=_('The same context is available here as in plain_text, above.'), ) locale = models.CharField( _('Locale'), max_length=10, blank=True, null=True, help_text=_('Locale of this template.'), ) def __str__(self): return '%s' % self.template_name class Meta: ordering = ('template_name', 'locale') verbose_name = _('e-mail template') verbose_name_plural = _('e-mail templates') class KBCategory(models.Model): """ Lets help users help themselves: the Knowledge Base is a categorised listing of questions & answers. """ name = models.CharField( _('Name of the category'), max_length=100, ) title = models.CharField( _('Title on knowledgebase page'), max_length=100, ) slug = models.SlugField( _('Slug'), ) description = models.TextField( _('Description'), ) queue = models.ForeignKey( Queue, blank=True, null=True, on_delete=models.CASCADE, verbose_name=_('Default queue when creating a ticket after viewing this category.'), ) public = models.BooleanField( default=True, verbose_name=_("Is KBCategory publicly visible?") ) def __str__(self): return '%s' % self.name class Meta: ordering = ('title',) verbose_name = _('Knowledge base category') verbose_name_plural = _('Knowledge base categories') def get_absolute_url(self): from django.urls import reverse return reverse('helpdesk:kb_category', kwargs={'slug': self.slug}) class KBItem(models.Model): """ An item within the knowledgebase. Very straightforward question/answer style system. """ voted_by = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='votes', ) downvoted_by = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='downvotes', ) category = models.ForeignKey( KBCategory, on_delete=models.CASCADE, verbose_name=_('Category'), ) title = models.CharField( _('Title'), max_length=100, ) question = models.TextField( _('Question'), ) answer = models.TextField( _('Answer'), ) votes = models.IntegerField( _('Votes'), help_text=_('Total number of votes cast for this item'), default=0, ) recommendations = models.IntegerField( _('Positive Votes'), help_text=_('Number of votes for this item which were POSITIVE.'), default=0, ) last_updated = models.DateTimeField( _('Last Updated'), help_text=_('The date on which this question was most recently changed.'), blank=True, ) team = models.ForeignKey( helpdesk_settings.HELPDESK_TEAMS_MODEL, on_delete=models.CASCADE, verbose_name=_('Team'), blank=True, null=True, ) order = models.PositiveIntegerField( _('Order'), blank=True, null=True, ) enabled = models.BooleanField( _('Enabled to display to users'), default=True, ) def save(self, *args, **kwargs): if not self.last_updated: self.last_updated = timezone.now() return super(KBItem, self).save(*args, **kwargs) def get_team(self): return helpdesk_settings.HELPDESK_KBITEM_TEAM_GETTER(self) def _score(self): """ Return a score out of 10 or Unrated if no votes """ if self.votes > 0: return (self.recommendations / self.votes) * 10 else: return _('Unrated') score = property(_score) def __str__(self): return '%s: %s' % (self.category.title, self.title) class Meta: ordering = ('order', 'title',) verbose_name = _('Knowledge base item') verbose_name_plural = _('Knowledge base items') def get_absolute_url(self): from django.urls import reverse return str(reverse('helpdesk:kb_category', args=(self.category.slug,))) + "?kbitem=" + str(self.pk) def query_url(self): from django.urls import reverse return str(reverse('helpdesk:list')) + "?kbitem=" + str(self.pk) def num_open_tickets(self): return Ticket.objects.filter(kbitem=self, status__in=(1, 2)).count() def unassigned_tickets(self): return Ticket.objects.filter(kbitem=self, status__in=(1, 2), assigned_to__isnull=True) def get_markdown(self): return get_markdown(self.answer) class SavedSearch(models.Model): """ Allow a user to save a ticket search, eg their filtering and sorting options, and optionally share it with other users. This lets people easily create a set of commonly-used filters, such as: * My tickets waiting on me * My tickets waiting on submitter * My tickets in 'Priority Support' queue with priority of 1 * All tickets containing the word 'billing'. etc... """ user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_('User'), ) title = models.CharField( _('Query Name'), max_length=100, help_text=_('User-provided name for this query'), ) shared = models.BooleanField( _('Shared With Other Users?'), blank=True, default=False, help_text=_('Should other users see this query?'), ) query = models.TextField( _('Search Query'), help_text=_('Pickled query object. Be wary changing this.'), ) def __str__(self): if self.shared: return '%s (*)' % self.title else: return '%s' % self.title class Meta: verbose_name = _('Saved search') verbose_name_plural = _('Saved searches') def get_default_setting(setting): from helpdesk.settings import DEFAULT_USER_SETTINGS return DEFAULT_USER_SETTINGS[setting] def login_view_ticketlist_default(): return get_default_setting('login_view_ticketlist') def email_on_ticket_change_default(): return get_default_setting('email_on_ticket_change') def email_on_ticket_assign_default(): return get_default_setting('email_on_ticket_assign') def tickets_per_page_default(): return get_default_setting('tickets_per_page') def use_email_as_submitter_default(): return get_default_setting('use_email_as_submitter') class UserSettings(models.Model): """ A bunch of user-specific settings that we want to be able to define, such as notification preferences and other things that should probably be configurable. """ PAGE_SIZES = ((10, '10'), (25, '25'), (50, '50'), (100, '100')) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="usersettings_helpdesk") settings_pickled = models.TextField( _('DEPRECATED! Settings Dictionary DEPRECATED!'), help_text=_('DEPRECATED! This is a base64-encoded representation of a pickled Python dictionary. ' 'Do not change this field via the admin.'), blank=True, null=True, ) login_view_ticketlist = models.BooleanField( verbose_name=_('Show Ticket List on Login?'), help_text=_('Display the ticket list upon login? Otherwise, the dashboard is shown.'), default=login_view_ticketlist_default, ) email_on_ticket_change = models.BooleanField( verbose_name=_('E-mail me on ticket change?'), help_text=_( 'If you\'re the ticket owner and the ticket is changed via the web by somebody else,' 'do you want to receive an e-mail?' ), default=email_on_ticket_change_default, ) email_on_ticket_assign = models.BooleanField( verbose_name=_('E-mail me when assigned a ticket?'), help_text=_('If you are assigned a ticket via the web, do you want to receive an e-mail?'), default=email_on_ticket_assign_default, ) tickets_per_page = models.IntegerField( verbose_name=_('Number of tickets to show per page'), help_text=_('How many tickets do you want to see on the Ticket List page?'), default=tickets_per_page_default, choices=PAGE_SIZES, ) use_email_as_submitter = models.BooleanField( verbose_name=_('Use my e-mail address when submitting tickets?'), help_text=_('When you submit a ticket, do you want to automatically ' 'use your e-mail address as the submitter address? You ' 'can type a different e-mail address when entering the ' 'ticket if needed, this option only changes the default.'), default=use_email_as_submitter_default, ) def __str__(self): return 'Preferences for %s' % self.user class Meta: verbose_name = _('User Setting') verbose_name_plural = _('User Settings') def create_usersettings(sender, instance, created, **kwargs): """ Helper function to create UserSettings instances as required, eg when we first create the UserSettings database table via 'syncdb' or when we save a new user. If we end up with users with no UserSettings, then we get horrible 'DoesNotExist: UserSettings matching query does not exist.' errors. """ if created: UserSettings.objects.create(user=instance) models.signals.post_save.connect(create_usersettings, sender=settings.AUTH_USER_MODEL) class IgnoreEmail(models.Model): """ This model lets us easily ignore e-mails from certain senders when processing IMAP and POP3 mailboxes, eg mails from postmaster or from known trouble-makers. """ class Meta: verbose_name = _('Ignored e-mail address') verbose_name_plural = _('Ignored e-mail addresses') queues = models.ManyToManyField( Queue, blank=True, help_text=_('Leave blank for this e-mail to be ignored on all queues, ' 'or select those queues you wish to ignore this e-mail for.'), ) name = models.CharField( _('Name'), max_length=100, ) date = models.DateField( _('Date'), help_text=_('Date on which this e-mail address was added'), blank=True, editable=False ) email_address = models.CharField( _('E-Mail Address'), max_length=150, help_text=_('Enter a full e-mail address, or portions with ' 'wildcards, eg *@domain.com or postmaster@*.'), ) keep_in_mailbox = models.BooleanField( _('Save Emails in Mailbox?'), blank=True, default=False, help_text=_('Do you want to save emails from this address in the mailbox? ' 'If this is unticked, emails from this address will be deleted.'), ) def __str__(self): return '%s' % self.name def save(self, *args, **kwargs): if not self.date: self.date = timezone.now() return super(IgnoreEmail, self).save(*args, **kwargs) def queue_list(self): """Return a list of the queues this IgnoreEmail applies to. If this IgnoreEmail applies to ALL queues, return '*'. """ queues = self.queues.all().order_by('title') if len(queues) == 0: return '*' else: return ', '.join([str(q) for q in queues]) def test(self, email): """ Possible situations: 1. Username & Domain both match 2. Username is wildcard, domain matches 3. Username matches, domain is wildcard 4. username & domain are both wildcards 5. Other (no match) 1-4 return True, 5 returns False. """ own_parts = self.email_address.split("@") email_parts = email.split("@") if self.email_address == email or \ own_parts[0] == "*" and own_parts[1] == email_parts[1] or \ own_parts[1] == "*" and own_parts[0] == email_parts[0] or \ own_parts[0] == "*" and own_parts[1] == "*": return True else: return False class TicketCC(models.Model): """ Often, there are people who wish to follow a ticket who aren't the person who originally submitted it. This model provides a way for those people to follow a ticket. In this circumstance, a 'person' could be either an e-mail address or an existing system user. """ ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Ticket'), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, help_text=_('User who wishes to receive updates for this ticket.'), verbose_name=_('User'), ) email = models.EmailField( _('E-Mail Address'), blank=True, null=True, help_text=_('For non-user followers, enter their e-mail address'), ) can_view = models.BooleanField( _('Can View Ticket?'), blank=True, default=False, help_text=_('Can this CC login to view the ticket details?'), ) can_update = models.BooleanField( _('Can Update Ticket?'), blank=True, default=False, help_text=_('Can this CC login and update the ticket?'), ) def _email_address(self): if self.user and self.user.email is not None: return self.user.email else: return self.email email_address = property(_email_address) def _display(self): if self.user: return self.user else: return self.email display = property(_display) def __str__(self): return '%s for %s' % (self.display, self.ticket.title) def clean(self): if self.user and not self.user.email: raise ValidationError('User has no email address') class CustomFieldManager(models.Manager): def get_queryset(self): return super(CustomFieldManager, self).get_queryset().order_by('ordering') class CustomField(models.Model): """ Definitions for custom fields that are glued onto each ticket. """ name = models.SlugField( _('Field Name'), help_text=_('As used in the database and behind the scenes. ' 'Must be unique and consist of only lowercase letters with no punctuation.'), unique=True, ) label = models.CharField( _('Label'), max_length=30, help_text=_('The display label for this field'), ) help_text = models.TextField( _('Help Text'), help_text=_('Shown to the user when editing the ticket'), blank=True, null=True ) DATA_TYPE_CHOICES = ( ('varchar', _('Character (single line)')), ('text', _('Text (multi-line)')), ('integer', _('Integer')), ('decimal', _('Decimal')), ('list', _('List')), ('boolean', _('Boolean (checkbox yes/no)')), ('date', _('Date')), ('time', _('Time')), ('datetime', _('Date & Time')), ('email', _('E-Mail Address')), ('url', _('URL')), ('ipaddress', _('IP Address')), ('slug', _('Slug')), ) data_type = models.CharField( _('Data Type'), max_length=100, help_text=_('Allows you to restrict the data entered into this field'), choices=DATA_TYPE_CHOICES, ) max_length = models.IntegerField( _('Maximum Length (characters)'), blank=True, null=True, ) decimal_places = models.IntegerField( _('Decimal Places'), help_text=_('Only used for decimal fields'), blank=True, null=True, ) empty_selection_list = models.BooleanField( _('Add empty first choice to List?'), default=False, help_text=_('Only for List: adds an empty first entry to the choices list, ' 'which enforces that the user makes an active choice.'), ) list_values = models.TextField( _('List Values'), help_text=_('For list fields only. Enter one option per line.'), blank=True, null=True, ) ordering = models.IntegerField( _('Ordering'), help_text=_('Lower numbers are displayed first; higher numbers are listed later'), blank=True, null=True, ) def _choices_as_array(self): valuebuffer = StringIO(self.list_values) choices = [[item.strip(), item.strip()] for item in valuebuffer.readlines()] valuebuffer.close() return choices choices_as_array = property(_choices_as_array) required = models.BooleanField( _('Required?'), help_text=_('Does the user have to enter a value for this field?'), default=False, ) staff_only = models.BooleanField( _('Staff Only?'), help_text=_('If this is ticked, then the public submission form ' 'will NOT show this field'), default=False, ) objects = CustomFieldManager() def __str__(self): return '%s' % self.name class Meta: verbose_name = _('Custom field') verbose_name_plural = _('Custom fields') class TicketCustomFieldValue(models.Model): ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Ticket'), ) field = models.ForeignKey( CustomField, on_delete=models.CASCADE, verbose_name=_('Field'), ) value = models.TextField(blank=True, null=True) def __str__(self): return '%s / %s' % (self.ticket, self.field) class Meta: unique_together = (('ticket', 'field'),) verbose_name = _('Ticket custom field value') verbose_name_plural = _('Ticket custom field values') class TicketDependency(models.Model): """ The ticket identified by `ticket` cannot be resolved until the ticket in `depends_on` has been resolved. To help enforce this, a helper function `can_be_resolved` on each Ticket instance checks that these have all been resolved. """ class Meta: unique_together = (('ticket', 'depends_on'),) verbose_name = _('Ticket dependency') verbose_name_plural = _('Ticket dependencies') ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Ticket'), related_name='ticketdependency', ) depends_on = models.ForeignKey( Ticket, on_delete=models.CASCADE, verbose_name=_('Depends On Ticket'), related_name='depends_on', ) def __str__(self): return '%s / %s' % (self.ticket, self.depends_on)
xss
{ "code": [ " pattern = fr'([\\[\\s\\S\\]]*?)\\(([\\s\\S]*?):([\\[\\s\\S\\]]*?)\\)'" ], "line_no": [ 59 ] }
{ "code": [ " pattern = fr'([\\[\\s\\S\\]]*?)\\(([\\s\\S]*?):([\\s\\S]*?)\\)'" ], "line_no": [ 59 ] }
from django.contrib.auth.models import Permission from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db import models from django.conf import .settings from django.utils import .timezone from django.utils.translation import ugettext_lazy as _, ugettext from io import StringIO import re import os import mimetypes import .datetime from django.utils.safestring import mark_safe from markdown import markdown from markdown.extensions import Extension import uuid from helpdesk import .settings as helpdesk_settings from .validators import validate_file_extension from .templated_email import .send_templated_mail def FUNC_0(VAR_0): if VAR_0: VAR_0 = "{0:02d}h:{1:02d}m".format( VAR_0.seconds // 3600, VAR_0.seconds % 3600 // 60 ) else: VAR_0 = "" return VAR_0 class CLASS_0(Extension): def FUNC_11(self, VAR_8, VAR_9): del VAR_8.preprocessors['html_block'] del VAR_8.inlinePatterns['html'] def FUNC_1(VAR_1): if not VAR_1: return "" VAR_10 = fr'([\[\s\S\]]*?)\(([\s\S]*?):([\[\s\S\]]*?)\)' if re.match(VAR_10, VAR_1): VAR_135 = re.search(VAR_10, VAR_1, re.IGNORECASE).group(2) if VAR_135 in helpdesk_settings.ALLOWED_URL_SCHEMES: VAR_160 = '\\1(\\2:\\3)' else: VAR_160 = '\\1(\\3)' VAR_1 = re.sub(VAR_10, VAR_160, VAR_1, flags=re.IGNORECASE) return mark_safe( markdown( VAR_1, extensions=[ CLASS_0(), 'markdown.extensions.nl2br', 'markdown.extensions.fenced_code' ] ) ) class CLASS_1(models.Model): VAR_11 = models.CharField( _('Title'), VAR_125=100, ) VAR_12 = models.SlugField( _('Slug'), VAR_125=50, unique=True, VAR_122=_('This VAR_12 is used when building VAR_65 ID\'s. Once set, ' 'try not to change it or e-mailing may get messy.'), ) VAR_13 = models.EmailField( _('E-Mail Address'), blank=True, null=True, VAR_122=_('All outgoing e-mails for this VAR_48 will use this e-mail ' 'address. If you use IMAP or POP3, this should be the e-mail ' 'address for that mailbox.'), ) VAR_14 = models.CharField( _('Locale'), VAR_125=10, blank=True, null=True, VAR_122=_('Locale of this VAR_48. All correspondence in this ' 'queue will be in this language.'), ) VAR_15 = models.BooleanField( _('Allow Public Submission?'), blank=True, default=False, VAR_122=_('Should this VAR_48 be listed on the VAR_78 submission form?'), ) VAR_16 = models.BooleanField( _('Allow E-Mail Submission?'), blank=True, default=False, VAR_122=_('Do you want to poll the e-mail box below for new ' 'tickets?'), ) VAR_17 = models.IntegerField( _('Escalation Days'), blank=True, null=True, VAR_122=_('For tickets which are not held, how often do you wish to ' 'increase their VAR_56? Set to 0 for no escalation.'), ) VAR_18 = models.CharField( _('New CLASS_2 CC Address'), blank=True, null=True, VAR_125=200, VAR_122=_('If an e-mail address is entered here, then it will ' 'receive notification of all new tickets VAR_6 for this VAR_48. ' 'Enter a comma between multiple e-mail addresses.'), ) VAR_19 = models.CharField( _('Updated CLASS_2 CC Address'), blank=True, null=True, VAR_125=200, VAR_122=_('If an e-mail address is entered here, then it will ' 'receive notification of all activity (new tickets, closed ' 'tickets, updates, reassignments, etc) for this VAR_48. Separate ' 'multiple addresses with a comma.'), ) VAR_20 = models.BooleanField( _('Notify contacts when VAR_73 updates arrive'), blank=True, default=False, VAR_122=_('When an VAR_73 arrives to either create a VAR_65 or to ' 'interact with an existing discussion. Should VAR_73 notifications be sent ? ' 'Note: the VAR_18 and VAR_19 work independently of this feature'), ) VAR_21 = models.CharField( _('E-Mail Box Type'), VAR_125=5, VAR_158=(('pop3', _('POP 3')), ('imap', _('IMAP')), ('local', _('Local Directory'))), blank=True, null=True, VAR_122=_('E-Mail server type for creating tickets automatically ' 'from a mailbox - both POP3 and IMAP are supported, as well as ' 'reading from a local directory.'), ) VAR_22 = models.CharField( _('E-Mail Hostname'), VAR_125=200, blank=True, null=True, VAR_122=_('Your e-mail server address - either the domain VAR_90 or ' 'IP address. May be "localhost".'), ) VAR_23 = models.IntegerField( _('E-Mail Port'), blank=True, null=True, VAR_122=_('Port number to use for accessing e-mail. Default for ' 'POP3 is "110", and for IMAP is "143". This may differ on some ' 'servers. Leave it blank to use the defaults.'), ) VAR_24 = models.BooleanField( _('Use SSL for E-Mail?'), blank=True, default=False, VAR_122=_('Whether to use SSL for IMAP or POP3 - the default ports ' 'when using SSL are 993 for IMAP and 995 for POP3.'), ) VAR_25 = models.CharField( _('E-Mail Username'), VAR_125=200, blank=True, null=True, VAR_122=_('Username for accessing this mailbox.'), ) VAR_26 = models.CharField( _('E-Mail Password'), VAR_125=200, blank=True, null=True, VAR_122=_('Password for the above username'), ) VAR_27 = models.CharField( _('IMAP Folder'), VAR_125=100, blank=True, null=True, VAR_122=_('If using IMAP, what folder do you wish to fetch messages ' 'from? This allows you to use one IMAP account for multiple ' 'queues, by filtering messages on your IMAP server into separate ' 'folders. Default: INBOX.'), ) VAR_28 = models.CharField( _('E-Mail Local Directory'), VAR_125=200, blank=True, null=True, VAR_122=_('If using a local directory, what directory VAR_153 do you ' 'wish to poll for new VAR_73? ' 'Example: /var/lib/mail/helpdesk/'), ) VAR_29 = models.CharField( _('Django auth permission name'), VAR_125=72, # based on FUNC_15() pre-pending chars to VAR_12 blank=True, null=True, editable=False, VAR_122=_('Name used in the django.contrib.auth permission system'), ) VAR_30 = models.IntegerField( _('E-Mail Check Interval'), VAR_122=_('How often do you wish to check this mailbox? (in Minutes)'), blank=True, null=True, default='5', ) VAR_31 = models.DateTimeField( blank=True, null=True, editable=False, ) VAR_32 = models.CharField( _('Socks Proxy Type'), VAR_125=8, VAR_158=(('socks4', _('SOCKS4')), ('socks5', _('SOCKS5'))), blank=True, null=True, VAR_122=_('SOCKS4 or SOCKS5 allows you to proxy your connections through a SOCKS server.'), ) VAR_33 = models.GenericIPAddressField( _('Socks Proxy Host'), blank=True, null=True, VAR_122=_('Socks proxy IP address. Default: 127.0.0.1'), ) VAR_34 = models.IntegerField( _('Socks Proxy Port'), blank=True, null=True, VAR_122=_('Socks proxy port number. Default: 9150 (default TOR port)'), ) VAR_35 = models.CharField( _('Logging Type'), VAR_125=5, VAR_158=( ('none', _('None')), ('debug', _('Debug')), ('info', _('Information')), ('warn', _('Warning')), ('error', _('Error')), ('crit', _('Critical')) ), blank=True, null=True, VAR_122=_('Set the default logging level. All messages at that ' 'level or above will be logged to the directory set ' 'below. If no level is set, logging will be disabled.'), ) VAR_36 = models.CharField( _('Logging Directory'), VAR_125=200, blank=True, null=True, VAR_122=_('If logging is VAR_107, what directory should we use to ' 'store log files for this VAR_48? ' 'The standard logging mechanims are used if no directory is set'), ) VAR_37 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='default_owner', blank=True, null=True, VAR_136=_('Default owner'), ) VAR_38 = models.DurationField( VAR_122=_("Time to be spent on this CLASS_1 in total"), blank=True, null=True ) def __str__(self): return "%s" % self.title class CLASS_22: VAR_129 = ('title',) VAR_136 = _('Queue') VAR_137 = _('Queues') def FUNC_12(self): if not self.email_address: VAR_161 = re.match(".*<(?P<VAR_73>.*@*.)>", settings.DEFAULT_FROM_EMAIL) if VAR_161 is not None: return u'NO QUEUE EMAIL ADDRESS DEFINED %s' % settings.DEFAULT_FROM_EMAIL else: return u'NO QUEUE EMAIL ADDRESS DEFINED <%s>' % settings.DEFAULT_FROM_EMAIL else: return u'%s <%s>' % (self.title, self.email_address) VAR_39 = property(FUNC_12) @property def VAR_0(self): VAR_138 = datetime.timedelta(0) for val in self.ticket_set.all(): if val.time_spent: VAR_138 = VAR_138 + val.time_spent return VAR_138 @property def FUNC_14(self): return FUNC_0(self.time_spent) def FUNC_15(self): VAR_139 = "queue_access_%s" % self.slug self.permission_name = "helpdesk.%s" % VAR_139 return VAR_139 def FUNC_16(self, *VAR_40, **VAR_7): if self.email_box_type == 'imap' and not self.email_box_imap_folder: self.email_box_imap_folder = 'INBOX' if self.socks_proxy_type: if not self.socks_proxy_host: self.socks_proxy_host = '127.0.0.1' if not self.socks_proxy_port: self.socks_proxy_port = 9150 else: self.socks_proxy_host = None self.socks_proxy_port = None if not self.email_box_port: if self.email_box_type == 'imap' and self.email_box_ssl: self.email_box_port = 993 elif self.email_box_type == 'imap' and not self.email_box_ssl: self.email_box_port = 143 elif self.email_box_type == 'pop3' and self.email_box_ssl: self.email_box_port = 995 elif self.email_box_type == 'pop3' and not self.email_box_ssl: self.email_box_port = 110 if not self.id: VAR_139 = self.prepare_permission_name() Permission.objects.create( VAR_90=_("Permission for VAR_48: ") + self.title, content_type=ContentType.objects.get_for_model(self.__class__), codename=VAR_139, ) super(CLASS_1, self).save(*VAR_40, **VAR_7) def FUNC_17(self, *VAR_40, **VAR_7): VAR_29 = self.permission_name super(CLASS_1, self).delete(*VAR_40, **VAR_7) if VAR_29: try: VAR_164 = Permission.objects.get(codename=VAR_29[9:]) VAR_164.delete() except ObjectDoesNotExist: pass def FUNC_2(): return str(uuid.uuid4()) class CLASS_2(models.Model): VAR_41 = 1 VAR_42 = 2 VAR_43 = 3 VAR_44 = 4 VAR_45 = 5 VAR_46 = ( (VAR_41, _('Open')), (VAR_42, _('Reopened')), (VAR_43, _('Resolved')), (VAR_44, _('Closed')), (VAR_45, _('Duplicate')), ) VAR_47 = ( (1, _('1. Critical')), (2, _('2. High')), (3, _('3. Normal')), (4, _('4. Low')), (5, _('5. Very Low')), ) VAR_11 = models.CharField( _('Title'), VAR_125=200, ) VAR_48 = models.ForeignKey( CLASS_1, on_delete=models.CASCADE, VAR_136=_('Queue'), ) VAR_6 = models.DateTimeField( _('Created'), blank=True, VAR_122=_('Date this VAR_65 was first created'), ) VAR_49 = models.DateTimeField( _('Modified'), blank=True, VAR_122=_('Date this VAR_65 was most recently changed.'), ) VAR_50 = models.EmailField( _('Submitter E-Mail'), blank=True, null=True, VAR_122=_('The submitter will receive an VAR_73 for all VAR_78 ' 'follow-ups left for this task.'), ) VAR_51 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='assigned_to', blank=True, null=True, VAR_136=_('Assigned to'), ) VAR_52 = models.IntegerField( _('Status'), VAR_158=VAR_46, default=VAR_41, ) VAR_53 = models.BooleanField( _('On Hold'), blank=True, default=False, VAR_122=_('If a VAR_65 is on hold, it will not automatically be escalated.'), ) VAR_54 = models.TextField( _('Description'), blank=True, null=True, VAR_122=_('The content of the customers VAR_72.'), ) VAR_55 = models.TextField( _('Resolution'), blank=True, null=True, VAR_122=_('The VAR_55 provided to the customer by our staff.'), ) VAR_56 = models.IntegerField( _('Priority'), VAR_158=VAR_47, default=3, blank=3, VAR_122=_('1 = Highest Priority, 5 = Low Priority'), ) VAR_57 = models.DateTimeField( _('Due on'), blank=True, null=True, ) VAR_58 = models.DateTimeField( blank=True, null=True, editable=False, VAR_122=_('The VAR_76 this VAR_65 was last escalated - updated ' 'automatically by management/commands/escalate_tickets.py.'), ) VAR_59 = models.CharField( _("Secret key needed for viewing/editing VAR_65 by non-logged in users"), VAR_125=36, default=FUNC_2, ) VAR_60 = models.ForeignKey( "KBItem", blank=True, null=True, on_delete=models.CASCADE, VAR_136=_('Knowledge base item the VAR_74 was viewing when they VAR_6 this VAR_65.'), ) VAR_61 = models.ForeignKey( 'self', VAR_136=_('merged to'), related_name='merged_tickets', on_delete=models.CASCADE, null=True, blank=True ) @property def VAR_0(self): VAR_138 = datetime.timedelta(0) for val in self.followup_set.all(): if val.time_spent: VAR_138 = VAR_138 + val.time_spent return VAR_138 @property def FUNC_14(self): return FUNC_0(self.time_spent) def FUNC_18(self, VAR_62, VAR_63=None, **VAR_7): VAR_140 = set() if VAR_63 is not None: VAR_140.update(VAR_63) VAR_140.add(self.queue.email_address) def FUNC_48(VAR_73): return VAR_73 and VAR_73 not in VAR_140 def FUNC_18(VAR_141, VAR_142): if VAR_142 and VAR_142 not in VAR_140 and VAR_141 in VAR_62: VAR_165, VAR_166 = VAR_62[VAR_141] send_templated_mail(VAR_165, VAR_166, VAR_142, VAR_5=self.queue.from_address, **VAR_7) VAR_140.add(VAR_142) FUNC_18('submitter', self.submitter_email) FUNC_18('ticket_cc', self.queue.updated_ticket_cc) FUNC_18('new_ticket_cc', self.queue.new_ticket_cc) if self.assigned_to: FUNC_18('assigned_to', self.assigned_to.email) if self.queue.enable_notifications_on_email_events: for cc in self.ticketcc_set.all(): FUNC_18('ticket_cc', cc.email_address) return VAR_140 def FUNC_19(self): if not self.assigned_to: return _('Unassigned') else: if self.assigned_to.get_full_name(): return self.assigned_to.get_full_name() else: return self.assigned_to.get_username() VAR_64 = property(FUNC_19) def FUNC_20(self): return u"[%s]" % self.ticket_for_url VAR_65 = property(FUNC_20) def FUNC_21(self): return u"%s-%s" % (self.queue.slug, self.id) VAR_66 = property(FUNC_21) def FUNC_22(self): if self.priority == 2: return "warning" elif self.priority == 1: return "danger" elif self.priority == 5: return "success" else: return "" VAR_67 = property(FUNC_22) def FUNC_23(self): VAR_143 = '' if self.on_hold: VAR_143 = _(' - On Hold') VAR_144 = '' if not self.can_be_resolved: VAR_144 = _(' - Open dependencies') return u'%s%s%s' % (self.get_status_display(), VAR_143, VAR_144) VAR_68 = property(FUNC_23) def FUNC_24(self): from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.urls import reverse try: VAR_162 = Site.objects.get_current() except ImproperlyConfigured: VAR_162 = Site(domain='configure-django-sites.com') if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK: VAR_163 = 'https' else: VAR_163 = 'http' return u"%s://%s%s?VAR_65=%s&VAR_73=%s&key=%s" % ( VAR_163, VAR_162.domain, reverse('helpdesk:public_view'), self.ticket_for_url, self.submitter_email, self.secret_key ) VAR_69 = property(FUNC_24) def FUNC_25(self): from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.urls import reverse try: VAR_162 = Site.objects.get_current() except ImproperlyConfigured: VAR_162 = Site(domain='configure-django-sites.com') if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK: VAR_163 = 'https' else: VAR_163 = 'http' return u"%s://%s%s" % ( VAR_163, VAR_162.domain, reverse('helpdesk:view', VAR_40=[self.id]) ) VAR_70 = property(FUNC_25) def FUNC_26(self): VAR_145 = (CLASS_2.OPEN_STATUS, CLASS_2.REOPENED_STATUS) return CLASS_21.objects.filter(VAR_65=self).filter( depends_on__status__in=VAR_145).count() == 0 VAR_71 = property(FUNC_26) def FUNC_27(self): VAR_146 = get_user_model() try: return VAR_146.objects.get(VAR_73=self.submitter_email) except (VAR_146.DoesNotExist, VAR_146.MultipleObjectsReturned): return None class CLASS_22: VAR_147 = "created" VAR_129 = ('id',) VAR_136 = _('Ticket') VAR_137 = _('Tickets') def __str__(self): return '%s %s' % (self.id, self.title) def FUNC_28(self): from django.urls import reverse return reverse('helpdesk:view', VAR_40=(self.id,)) def FUNC_16(self, *VAR_40, **VAR_7): if not self.id: self.created = timezone.now() if not self.priority: self.priority = 3 self.modified = timezone.now() if len(self.title) > 200: self.title = self.title[:197] + "..." super(CLASS_2, self).save(*VAR_40, **VAR_7) @staticmethod def FUNC_29(VAR_72): VAR_148 = VAR_72.split('-') VAR_48 = '-'.join(VAR_148[0:-1]) return VAR_48, VAR_148[-1] def FUNC_1(self): return FUNC_1(self.description) @property def FUNC_30(self): return FUNC_1(self.resolution) def FUNC_31(self, VAR_73=None, VAR_74=None, VAR_75=None): if VAR_75: VAR_73 = VAR_75.display elif VAR_74: if VAR_74.email: VAR_73 = VAR_74.email else: return elif not VAR_73: raise ValueError('You must provide at least one parameter to get the VAR_73 from') VAR_149 = [x.display for x in self.ticketcc_set.all()] if self.submitter_email: VAR_149.append(self.submitter_email) if self.assigned_to and self.assigned_to.email: VAR_149.append(self.assigned_to.email) if VAR_73 not in VAR_149: if VAR_75: VAR_75.ticket = self VAR_75.save(update_fields=['ticket']) elif VAR_74: VAR_75 = self.ticketcc_set.create(VAR_74=user) else: VAR_75 = self.ticketcc_set.create(VAR_73=email) return VAR_75 class CLASS_3(models.Manager): def FUNC_32(self): return self.filter(VAR_78=False) def FUNC_33(self): return self.filter(VAR_78=True) class CLASS_4(models.Model): VAR_65 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Ticket'), ) VAR_76 = models.DateTimeField( _('Date'), default=timezone.now ) VAR_11 = models.CharField( _('Title'), VAR_125=200, blank=True, null=True, ) VAR_77 = models.TextField( _('Comment'), blank=True, null=True, ) VAR_78 = models.BooleanField( _('Public'), blank=True, default=False, VAR_122=_( 'Public tickets are viewable by the submitter and all ' 'staff, but non-VAR_78 tickets can only be seen by staff.' ), ) VAR_74 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, VAR_136=_('User'), ) VAR_79 = models.IntegerField( _('New Status'), VAR_158=CLASS_2.STATUS_CHOICES, blank=True, null=True, VAR_122=_('If the VAR_52 was changed, what was it changed to?'), ) VAR_80 = models.CharField( _('E-Mail ID'), VAR_125=256, blank=True, null=True, VAR_122=_("The Message ID of the submitter's VAR_73."), editable=False, ) VAR_81 = CLASS_3() VAR_0 = models.DurationField( VAR_122=_("Time spent on this follow up"), blank=True, null=True ) class CLASS_22: VAR_129 = ('date',) VAR_136 = _('Follow-up') VAR_137 = _('Follow-ups') def __str__(self): return '%s' % self.title def FUNC_28(self): return u"%s#VAR_82%s" % (self.ticket.get_absolute_url(), self.id) def FUNC_16(self, *VAR_40, **VAR_7): VAR_150 = self.ticket VAR_150.modified = timezone.now() VAR_150.save() super(CLASS_4, self).save(*VAR_40, **VAR_7) def FUNC_1(self): return FUNC_1(self.comment) @property def FUNC_14(self): return FUNC_0(self.time_spent) class CLASS_5(models.Model): VAR_82 = models.ForeignKey( CLASS_4, on_delete=models.CASCADE, VAR_136=_('Follow-up'), ) VAR_83 = models.CharField( _('Field'), VAR_125=100, ) VAR_84 = models.TextField( _('Old Value'), blank=True, null=True, ) VAR_85 = models.TextField( _('New Value'), blank=True, null=True, ) def __str__(self): VAR_151 = '%s ' % self.field if not self.new_value: VAR_151 += ugettext('removed') elif not self.old_value: VAR_151 += ugettext('set to %s') % self.new_value else: VAR_151 += ugettext('changed from "%(VAR_84)s" to "%(VAR_85)s"') % { 'old_value': self.old_value, 'new_value': self.new_value } return VAR_151 class CLASS_22: VAR_136 = _('Ticket change') VAR_137 = _('Ticket changes') def FUNC_3(VAR_2, VAR_3): return VAR_2.attachment_path(VAR_3) class CLASS_6(models.Model): VAR_86 = models.FileField( _('File'), upload_to=FUNC_3, VAR_125=1000, validators=[validate_file_extension] ) VAR_3 = models.CharField( _('Filename'), blank=True, VAR_125=1000, ) VAR_87 = models.CharField( _('MIME Type'), blank=True, VAR_125=255, ) VAR_88 = models.IntegerField( _('Size'), blank=True, VAR_122=_('Size of this VAR_86 in bytes'), ) def __str__(self): return '%s' % self.filename def FUNC_16(self, *VAR_40, **VAR_7): if not self.size: self.size = self.get_size() if not self.filename: self.filename = self.get_filename() if not self.mime_type: self.mime_type = \ mimetypes.guess_type(self.filename, strict=False)[0] or \ 'application/octet-stream' return super(CLASS_6, self).save(*VAR_40, **VAR_7) def FUNC_34(self): return str(self.file) def FUNC_35(self): return self.file.file.size def FUNC_3(self, VAR_3): assert NotImplementedError( "This method is to be implemented by CLASS_6 classes" ) class CLASS_22: VAR_129 = ('filename',) VAR_136 = _('Attachment') VAR_137 = _('Attachments') VAR_152 = True class CLASS_7(CLASS_6): VAR_82 = models.ForeignKey( CLASS_4, on_delete=models.CASCADE, VAR_136=_('Follow-up'), ) def FUNC_3(self, VAR_3): os.umask(0) VAR_153 = 'helpdesk/attachments/{VAR_66}-{VAR_59}/{id_}'.format( VAR_66=self.followup.ticket.ticket_for_url, VAR_59=self.followup.ticket.secret_key, id_=self.followup.id) VAR_154 = os.path.join(settings.MEDIA_ROOT, VAR_153) if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage": if not os.path.exists(VAR_154): os.makedirs(VAR_154, 0o777) return os.path.join(VAR_153, VAR_3) class CLASS_8(CLASS_6): VAR_60 = models.ForeignKey( "KBItem", on_delete=models.CASCADE, VAR_136=_('Knowledge base item'), ) def FUNC_3(self, VAR_3): os.umask(0) VAR_153 = 'helpdesk/attachments/kb/{VAR_99}/{kbi}'.format( VAR_99=self.kbitem.category, kbi=self.kbitem.id) VAR_154 = os.path.join(settings.MEDIA_ROOT, VAR_153) if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage": if not os.path.exists(VAR_154): os.makedirs(VAR_154, 0o777) return os.path.join(VAR_153, VAR_3) class CLASS_9(models.Model): class CLASS_22: VAR_129 = ('name',) VAR_136 = _('Pre-set reply') VAR_137 = _('Pre-set replies') VAR_89 = models.ManyToManyField( CLASS_1, blank=True, VAR_122=_('Leave blank to allow this reply to be used for all ' 'queues, or select those VAR_89 you wish to limit this reply to.'), ) VAR_90 = models.CharField( _('Name'), VAR_125=100, VAR_122=_('Only used to assist users with selecting a reply - not ' 'shown to the VAR_74.'), ) VAR_91 = models.TextField( _('Body'), VAR_122=_('Context available: {{ VAR_65 }} - VAR_65 object (eg ' '{{ VAR_65.title }}); {{ VAR_48 }} - The VAR_48; and {{ VAR_74 }} ' '- the current VAR_74.'), ) def __str__(self): return '%s' % self.name class CLASS_10(models.Model): VAR_89 = models.ManyToManyField( CLASS_1, blank=True, VAR_122=_('Leave blank for this exclusion to be applied to all VAR_89, ' 'or select those VAR_89 you wish to exclude with this entry.'), ) VAR_90 = models.CharField( _('Name'), VAR_125=100, ) VAR_76 = models.DateField( _('Date'), VAR_122=_('Date on which escalation should not happen'), ) def __str__(self): return '%s' % self.name class CLASS_22: VAR_136 = _('Escalation exclusion') VAR_137 = _('Escalation exclusions') class CLASS_11(models.Model): VAR_92 = models.CharField( _('Template Name'), VAR_125=100, ) VAR_93 = models.CharField( _('Subject'), VAR_125=100, VAR_122=_('This will be prefixed with "[VAR_65.ticket] VAR_65.title"' '. We recommend something simple such as "(Updated") or "(Closed)"' ' - the same VAR_166 is available as in VAR_95, below.'), ) VAR_94 = models.CharField( _('Heading'), VAR_125=100, VAR_122=_('In HTML e-mails, this will be the VAR_94 at the top of ' 'the VAR_73 - the same VAR_166 is available as in VAR_95, ' 'below.'), ) VAR_95 = models.TextField( _('Plain Text'), VAR_122=_('The VAR_166 available to you includes {{ VAR_65 }}, ' '{{ VAR_48 }}, and depending on the time of the call: ' '{{ VAR_55 }} or {{ VAR_77 }}.'), ) VAR_96 = models.TextField( _('HTML'), VAR_122=_('The same VAR_166 is available here as in VAR_95, above.'), ) VAR_14 = models.CharField( _('Locale'), VAR_125=10, blank=True, null=True, VAR_122=_('Locale of this VAR_165.'), ) def __str__(self): return '%s' % self.template_name class CLASS_22: VAR_129 = ('template_name', 'locale') VAR_136 = _('e-mail template') VAR_137 = _('e-mail templates') class CLASS_12(models.Model): VAR_90 = models.CharField( _('Name of the category'), VAR_125=100, ) VAR_11 = models.CharField( _('Title on knowledgebase page'), VAR_125=100, ) VAR_12 = models.SlugField( _('Slug'), ) VAR_54 = models.TextField( _('Description'), ) VAR_48 = models.ForeignKey( CLASS_1, blank=True, null=True, on_delete=models.CASCADE, VAR_136=_('Default VAR_48 when creating a VAR_65 after viewing this VAR_99.'), ) VAR_78 = models.BooleanField( default=True, VAR_136=_("Is CLASS_12 publicly visible?") ) def __str__(self): return '%s' % self.name class CLASS_22: VAR_129 = ('title',) VAR_136 = _('Knowledge base category') VAR_137 = _('Knowledge base categories') def FUNC_28(self): from django.urls import reverse return reverse('helpdesk:kb_category', VAR_7={'slug': self.slug}) class CLASS_13(models.Model): VAR_97 = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='votes', ) VAR_98 = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='downvotes', ) VAR_99 = models.ForeignKey( CLASS_12, on_delete=models.CASCADE, VAR_136=_('Category'), ) VAR_11 = models.CharField( _('Title'), VAR_125=100, ) VAR_100 = models.TextField( _('Question'), ) VAR_101 = models.TextField( _('Answer'), ) VAR_102 = models.IntegerField( _('Votes'), VAR_122=_('Total number of VAR_102 cast for this item'), default=0, ) VAR_103 = models.IntegerField( _('Positive Votes'), VAR_122=_('Number of VAR_102 for this item which were POSITIVE.'), default=0, ) VAR_104 = models.DateTimeField( _('Last Updated'), VAR_122=_('The VAR_76 on which this VAR_100 was most recently changed.'), blank=True, ) VAR_105 = models.ForeignKey( helpdesk_settings.HELPDESK_TEAMS_MODEL, on_delete=models.CASCADE, VAR_136=_('Team'), blank=True, null=True, ) VAR_106 = models.PositiveIntegerField( _('Order'), blank=True, null=True, ) VAR_107 = models.BooleanField( _('Enabled to VAR_120 to users'), default=True, ) def FUNC_16(self, *VAR_40, **VAR_7): if not self.last_updated: self.last_updated = timezone.now() return super(CLASS_13, self).save(*VAR_40, **VAR_7) def FUNC_36(self): return helpdesk_settings.HELPDESK_KBITEM_TEAM_GETTER(self) def FUNC_37(self): if self.votes > 0: return (self.recommendations / self.votes) * 10 else: return _('Unrated') VAR_108 = property(FUNC_37) def __str__(self): return '%s: %s' % (self.category.title, self.title) class CLASS_22: VAR_129 = ('order', 'title',) VAR_136 = _('Knowledge base item') VAR_137 = _('Knowledge base items') def FUNC_28(self): from django.urls import reverse return str(reverse('helpdesk:kb_category', VAR_40=(self.category.slug,))) + "?VAR_60=" + str(self.pk) def FUNC_38(self): from django.urls import reverse return str(reverse('helpdesk:list')) + "?VAR_60=" + str(self.pk) def FUNC_39(self): return CLASS_2.objects.filter(VAR_60=self, status__in=(1, 2)).count() def FUNC_40(self): return CLASS_2.objects.filter(VAR_60=self, status__in=(1, 2), assigned_to__isnull=True) def FUNC_1(self): return FUNC_1(self.answer) class CLASS_14(models.Model): VAR_74 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, VAR_136=_('User'), ) VAR_11 = models.CharField( _('Query Name'), VAR_125=100, VAR_122=_('User-provided VAR_90 for this query'), ) VAR_109 = models.BooleanField( _('Shared With Other Users?'), blank=True, default=False, VAR_122=_('Should other users see this VAR_72?'), ) VAR_72 = models.TextField( _('Search Query'), VAR_122=_('Pickled VAR_72 object. Be wary changing this.'), ) def __str__(self): if self.shared: return '%s (*)' % self.title else: return '%s' % self.title class CLASS_22: VAR_136 = _('Saved search') VAR_137 = _('Saved searches') def FUNC_4(VAR_4): from helpdesk.settings import DEFAULT_USER_SETTINGS return DEFAULT_USER_SETTINGS[VAR_4] def FUNC_5(): return FUNC_4('login_view_ticketlist') def FUNC_6(): return FUNC_4('email_on_ticket_change') def FUNC_7(): return FUNC_4('email_on_ticket_assign') def FUNC_8(): return FUNC_4('tickets_per_page') def FUNC_9(): return FUNC_4('use_email_as_submitter') class CLASS_15(models.Model): VAR_110 = ((10, '10'), (25, '25'), (50, '50'), (100, '100')) VAR_74 = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="usersettings_helpdesk") VAR_111 = models.TextField( _('DEPRECATED! Settings Dictionary DEPRECATED!'), VAR_122=_('DEPRECATED! This is a base64-encoded representation of a pickled Python dictionary. ' 'Do not change this VAR_83 via the admin.'), blank=True, null=True, ) VAR_112 = models.BooleanField( VAR_136=_('Show CLASS_2 List on Login?'), VAR_122=_('Display the VAR_65 list upon login? Otherwise, the dashboard is shown.'), default=FUNC_5, ) VAR_113 = models.BooleanField( VAR_136=_('E-mail me on VAR_65 change?'), VAR_122=_( 'If you\'re the VAR_65 owner and the VAR_65 is changed via the web by somebody else,' 'do you want to receive an e-mail?' ), default=FUNC_6, ) VAR_114 = models.BooleanField( VAR_136=_('E-mail me when assigned a VAR_65?'), VAR_122=_('If you are assigned a VAR_65 via the web, do you want to receive an e-mail?'), default=FUNC_7, ) VAR_115 = models.IntegerField( VAR_136=_('Number of tickets to show per page'), VAR_122=_('How many tickets do you want to see on the CLASS_2 List page?'), default=FUNC_8, VAR_158=VAR_110, ) VAR_116 = models.BooleanField( VAR_136=_('Use my e-mail address when submitting tickets?'), VAR_122=_('When you submit a VAR_65, do you want to automatically ' 'use your e-mail address as the submitter address? You ' 'can type a different e-mail address when entering the ' 'ticket if needed, this option only changes the default.'), default=FUNC_9, ) def __str__(self): return 'Preferences for %s' % self.user class CLASS_22: VAR_136 = _('User Setting') VAR_137 = _('User Settings') def FUNC_10(VAR_5, VAR_2, VAR_6, **VAR_7): if VAR_6: CLASS_15.objects.create(VAR_74=VAR_2) models.signals.post_save.connect(FUNC_10, VAR_5=settings.AUTH_USER_MODEL) class CLASS_16(models.Model): class CLASS_22: VAR_136 = _('Ignored e-mail address') VAR_137 = _('Ignored e-mail addresses') VAR_89 = models.ManyToManyField( CLASS_1, blank=True, VAR_122=_('Leave blank for this e-mail to be ignored on all VAR_89, ' 'or select those VAR_89 you wish to ignore this e-mail for.'), ) VAR_90 = models.CharField( _('Name'), VAR_125=100, ) VAR_76 = models.DateField( _('Date'), VAR_122=_('Date on which this e-mail address was added'), blank=True, editable=False ) VAR_13 = models.CharField( _('E-Mail Address'), VAR_125=150, VAR_122=_('Enter a full e-mail address, or portions with ' 'wildcards, eg *@domain.com or postmaster@*.'), ) VAR_117 = models.BooleanField( _('Save Emails in Mailbox?'), blank=True, default=False, VAR_122=_('Do you want to FUNC_16 emails from this address in the mailbox? ' 'If this is unticked, emails from this address will be deleted.'), ) def __str__(self): return '%s' % self.name def FUNC_16(self, *VAR_40, **VAR_7): if not self.date: self.date = timezone.now() return super(CLASS_16, self).save(*VAR_40, **VAR_7) def FUNC_41(self): VAR_89 = self.queues.all().order_by('title') if len(VAR_89) == 0: return '*' else: return ', '.join([str(q) for q in VAR_89]) def FUNC_42(self, VAR_73): VAR_155 = self.email_address.split("@") VAR_156 = VAR_73.split("@") if self.email_address == VAR_73 or \ VAR_155[0] == "*" and VAR_155[1] == VAR_156[1] or \ VAR_155[1] == "*" and VAR_155[0] == VAR_156[0] or \ VAR_155[0] == "*" and VAR_155[1] == "*": return True else: return False class CLASS_17(models.Model): VAR_65 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Ticket'), ) VAR_74 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, VAR_122=_('User who wishes to receive updates for this VAR_65.'), VAR_136=_('User'), ) VAR_73 = models.EmailField( _('E-Mail Address'), blank=True, null=True, VAR_122=_('For non-VAR_74 followers, enter their e-mail address'), ) VAR_118 = models.BooleanField( _('Can View CLASS_2?'), blank=True, default=False, VAR_122=_('Can this CC login to view the VAR_65 details?'), ) VAR_119 = models.BooleanField( _('Can Update CLASS_2?'), blank=True, default=False, VAR_122=_('Can this CC login and update the VAR_65?'), ) def FUNC_43(self): if self.user and self.user.email is not None: return self.user.email else: return self.email VAR_13 = property(FUNC_43) def FUNC_44(self): if self.user: return self.user else: return self.email VAR_120 = property(FUNC_44) def __str__(self): return '%s for %s' % (self.display, self.ticket.title) def FUNC_45(self): if self.user and not self.user.email: raise ValidationError('User has no VAR_73 address') class CLASS_18(models.Manager): def FUNC_46(self): return super(CLASS_18, self).get_queryset().order_by('ordering') class CLASS_19(models.Model): VAR_90 = models.SlugField( _('Field Name'), VAR_122=_('As used in the database and behind the scenes. ' 'Must be unique and consist of only lowercase letters with no punctuation.'), unique=True, ) VAR_121 = models.CharField( _('Label'), VAR_125=30, VAR_122=_('The VAR_120 VAR_121 for this field'), ) VAR_122 = models.TextField( _('Help Text'), VAR_122=_('Shown to the VAR_74 when editing the ticket'), blank=True, null=True ) VAR_123 = ( ('varchar', _('Character (single line)')), ('text', _('Text (multi-line)')), ('integer', _('Integer')), ('decimal', _('Decimal')), ('list', _('List')), ('boolean', _('Boolean (checkbox yes/no)')), ('date', _('Date')), ('time', _('Time')), ('datetime', _('Date & Time')), ('email', _('E-Mail Address')), ('url', _('URL')), ('ipaddress', _('IP Address')), ('slug', _('Slug')), ) VAR_124 = models.CharField( _('Data Type'), VAR_125=100, VAR_122=_('Allows you to restrict the data entered into this field'), VAR_158=VAR_123, ) VAR_125 = models.IntegerField( _('Maximum Length (characters)'), blank=True, null=True, ) VAR_126 = models.IntegerField( _('Decimal Places'), VAR_122=_('Only used for decimal fields'), blank=True, null=True, ) VAR_127 = models.BooleanField( _('Add empty first choice to List?'), default=False, VAR_122=_('Only for List: adds an empty first entry to the VAR_158 list, ' 'which enforces that the VAR_74 makes an active choice.'), ) VAR_128 = models.TextField( _('List Values'), VAR_122=_('For list fields only. Enter one option per line.'), blank=True, null=True, ) VAR_129 = models.IntegerField( _('Ordering'), VAR_122=_('Lower numbers are displayed first; higher numbers are listed later'), blank=True, null=True, ) def FUNC_47(self): VAR_157 = StringIO(self.list_values) VAR_158 = [[item.strip(), item.strip()] for item in VAR_157.readlines()] VAR_157.close() return VAR_158 VAR_130 = property(FUNC_47) VAR_131 = models.BooleanField( _('Required?'), VAR_122=_('Does the VAR_74 have to enter a VAR_133 for this VAR_83?'), default=False, ) VAR_132 = models.BooleanField( _('Staff Only?'), VAR_122=_('If this is ticked, then the VAR_78 submission form ' 'will NOT show this field'), default=False, ) VAR_81 = CLASS_18() def __str__(self): return '%s' % self.name class CLASS_22: VAR_136 = _('Custom field') VAR_137 = _('Custom fields') class CLASS_20(models.Model): VAR_65 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Ticket'), ) VAR_83 = models.ForeignKey( CLASS_19, on_delete=models.CASCADE, VAR_136=_('Field'), ) VAR_133 = models.TextField(blank=True, null=True) def __str__(self): return '%s / %s' % (self.ticket, self.field) class CLASS_22: VAR_159 = (('ticket', 'field'),) VAR_136 = _('Ticket custom VAR_83 value') VAR_137 = _('Ticket custom VAR_83 values') class CLASS_21(models.Model): class CLASS_22: VAR_159 = (('ticket', 'depends_on'),) VAR_136 = _('Ticket dependency') VAR_137 = _('Ticket dependencies') VAR_65 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Ticket'), related_name='ticketdependency', ) VAR_134 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Depends On Ticket'), related_name='depends_on', ) def __str__(self): return '%s / %s' % (self.ticket, self.depends_on)
from django.contrib.auth.models import Permission from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db import models from django.conf import .settings from django.utils import .timezone from django.utils.translation import ugettext_lazy as _, ugettext from io import StringIO import re import os import mimetypes import .datetime from django.utils.safestring import mark_safe from markdown import markdown from markdown.extensions import Extension import uuid from helpdesk import .settings as helpdesk_settings from .validators import validate_file_extension from .templated_email import .send_templated_mail def FUNC_0(VAR_0): if VAR_0: VAR_0 = "{0:02d}h:{1:02d}m".format( VAR_0.seconds // 3600, VAR_0.seconds % 3600 // 60 ) else: VAR_0 = "" return VAR_0 class CLASS_0(Extension): def FUNC_11(self, VAR_8, VAR_9): del VAR_8.preprocessors['html_block'] del VAR_8.inlinePatterns['html'] def FUNC_1(VAR_1): if not VAR_1: return "" VAR_10 = fr'([\[\s\S\]]*?)\(([\s\S]*?):([\s\S]*?)\)' if re.match(VAR_10, VAR_1): VAR_135 = re.search(VAR_10, VAR_1, re.IGNORECASE).group(2) if VAR_135 in helpdesk_settings.ALLOWED_URL_SCHEMES: VAR_160 = '\\1(\\2:\\3)' else: VAR_160 = '\\1(\\3)' VAR_1 = re.sub(VAR_10, VAR_160, VAR_1, flags=re.IGNORECASE) return mark_safe( markdown( VAR_1, extensions=[ CLASS_0(), 'markdown.extensions.nl2br', 'markdown.extensions.fenced_code' ] ) ) class CLASS_1(models.Model): VAR_11 = models.CharField( _('Title'), VAR_125=100, ) VAR_12 = models.SlugField( _('Slug'), VAR_125=50, unique=True, VAR_122=_('This VAR_12 is used when building VAR_65 ID\'s. Once set, ' 'try not to change it or e-mailing may get messy.'), ) VAR_13 = models.EmailField( _('E-Mail Address'), blank=True, null=True, VAR_122=_('All outgoing e-mails for this VAR_48 will use this e-mail ' 'address. If you use IMAP or POP3, this should be the e-mail ' 'address for that mailbox.'), ) VAR_14 = models.CharField( _('Locale'), VAR_125=10, blank=True, null=True, VAR_122=_('Locale of this VAR_48. All correspondence in this ' 'queue will be in this language.'), ) VAR_15 = models.BooleanField( _('Allow Public Submission?'), blank=True, default=False, VAR_122=_('Should this VAR_48 be listed on the VAR_78 submission form?'), ) VAR_16 = models.BooleanField( _('Allow E-Mail Submission?'), blank=True, default=False, VAR_122=_('Do you want to poll the e-mail box below for new ' 'tickets?'), ) VAR_17 = models.IntegerField( _('Escalation Days'), blank=True, null=True, VAR_122=_('For tickets which are not held, how often do you wish to ' 'increase their VAR_56? Set to 0 for no escalation.'), ) VAR_18 = models.CharField( _('New CLASS_2 CC Address'), blank=True, null=True, VAR_125=200, VAR_122=_('If an e-mail address is entered here, then it will ' 'receive notification of all new tickets VAR_6 for this VAR_48. ' 'Enter a comma between multiple e-mail addresses.'), ) VAR_19 = models.CharField( _('Updated CLASS_2 CC Address'), blank=True, null=True, VAR_125=200, VAR_122=_('If an e-mail address is entered here, then it will ' 'receive notification of all activity (new tickets, closed ' 'tickets, updates, reassignments, etc) for this VAR_48. Separate ' 'multiple addresses with a comma.'), ) VAR_20 = models.BooleanField( _('Notify contacts when VAR_73 updates arrive'), blank=True, default=False, VAR_122=_('When an VAR_73 arrives to either create a VAR_65 or to ' 'interact with an existing discussion. Should VAR_73 notifications be sent ? ' 'Note: the VAR_18 and VAR_19 work independently of this feature'), ) VAR_21 = models.CharField( _('E-Mail Box Type'), VAR_125=5, VAR_158=(('pop3', _('POP 3')), ('imap', _('IMAP')), ('local', _('Local Directory'))), blank=True, null=True, VAR_122=_('E-Mail server type for creating tickets automatically ' 'from a mailbox - both POP3 and IMAP are supported, as well as ' 'reading from a local directory.'), ) VAR_22 = models.CharField( _('E-Mail Hostname'), VAR_125=200, blank=True, null=True, VAR_122=_('Your e-mail server address - either the domain VAR_90 or ' 'IP address. May be "localhost".'), ) VAR_23 = models.IntegerField( _('E-Mail Port'), blank=True, null=True, VAR_122=_('Port number to use for accessing e-mail. Default for ' 'POP3 is "110", and for IMAP is "143". This may differ on some ' 'servers. Leave it blank to use the defaults.'), ) VAR_24 = models.BooleanField( _('Use SSL for E-Mail?'), blank=True, default=False, VAR_122=_('Whether to use SSL for IMAP or POP3 - the default ports ' 'when using SSL are 993 for IMAP and 995 for POP3.'), ) VAR_25 = models.CharField( _('E-Mail Username'), VAR_125=200, blank=True, null=True, VAR_122=_('Username for accessing this mailbox.'), ) VAR_26 = models.CharField( _('E-Mail Password'), VAR_125=200, blank=True, null=True, VAR_122=_('Password for the above username'), ) VAR_27 = models.CharField( _('IMAP Folder'), VAR_125=100, blank=True, null=True, VAR_122=_('If using IMAP, what folder do you wish to fetch messages ' 'from? This allows you to use one IMAP account for multiple ' 'queues, by filtering messages on your IMAP server into separate ' 'folders. Default: INBOX.'), ) VAR_28 = models.CharField( _('E-Mail Local Directory'), VAR_125=200, blank=True, null=True, VAR_122=_('If using a local directory, what directory VAR_153 do you ' 'wish to poll for new VAR_73? ' 'Example: /var/lib/mail/helpdesk/'), ) VAR_29 = models.CharField( _('Django auth permission name'), VAR_125=72, # based on FUNC_15() pre-pending chars to VAR_12 blank=True, null=True, editable=False, VAR_122=_('Name used in the django.contrib.auth permission system'), ) VAR_30 = models.IntegerField( _('E-Mail Check Interval'), VAR_122=_('How often do you wish to check this mailbox? (in Minutes)'), blank=True, null=True, default='5', ) VAR_31 = models.DateTimeField( blank=True, null=True, editable=False, ) VAR_32 = models.CharField( _('Socks Proxy Type'), VAR_125=8, VAR_158=(('socks4', _('SOCKS4')), ('socks5', _('SOCKS5'))), blank=True, null=True, VAR_122=_('SOCKS4 or SOCKS5 allows you to proxy your connections through a SOCKS server.'), ) VAR_33 = models.GenericIPAddressField( _('Socks Proxy Host'), blank=True, null=True, VAR_122=_('Socks proxy IP address. Default: 127.0.0.1'), ) VAR_34 = models.IntegerField( _('Socks Proxy Port'), blank=True, null=True, VAR_122=_('Socks proxy port number. Default: 9150 (default TOR port)'), ) VAR_35 = models.CharField( _('Logging Type'), VAR_125=5, VAR_158=( ('none', _('None')), ('debug', _('Debug')), ('info', _('Information')), ('warn', _('Warning')), ('error', _('Error')), ('crit', _('Critical')) ), blank=True, null=True, VAR_122=_('Set the default logging level. All messages at that ' 'level or above will be logged to the directory set ' 'below. If no level is set, logging will be disabled.'), ) VAR_36 = models.CharField( _('Logging Directory'), VAR_125=200, blank=True, null=True, VAR_122=_('If logging is VAR_107, what directory should we use to ' 'store log files for this VAR_48? ' 'The standard logging mechanims are used if no directory is set'), ) VAR_37 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='default_owner', blank=True, null=True, VAR_136=_('Default owner'), ) VAR_38 = models.DurationField( VAR_122=_("Time to be spent on this CLASS_1 in total"), blank=True, null=True ) def __str__(self): return "%s" % self.title class CLASS_22: VAR_129 = ('title',) VAR_136 = _('Queue') VAR_137 = _('Queues') def FUNC_12(self): if not self.email_address: VAR_161 = re.match(".*<(?P<VAR_73>.*@*.)>", settings.DEFAULT_FROM_EMAIL) if VAR_161 is not None: return u'NO QUEUE EMAIL ADDRESS DEFINED %s' % settings.DEFAULT_FROM_EMAIL else: return u'NO QUEUE EMAIL ADDRESS DEFINED <%s>' % settings.DEFAULT_FROM_EMAIL else: return u'%s <%s>' % (self.title, self.email_address) VAR_39 = property(FUNC_12) @property def VAR_0(self): VAR_138 = datetime.timedelta(0) for val in self.ticket_set.all(): if val.time_spent: VAR_138 = VAR_138 + val.time_spent return VAR_138 @property def FUNC_14(self): return FUNC_0(self.time_spent) def FUNC_15(self): VAR_139 = "queue_access_%s" % self.slug self.permission_name = "helpdesk.%s" % VAR_139 return VAR_139 def FUNC_16(self, *VAR_40, **VAR_7): if self.email_box_type == 'imap' and not self.email_box_imap_folder: self.email_box_imap_folder = 'INBOX' if self.socks_proxy_type: if not self.socks_proxy_host: self.socks_proxy_host = '127.0.0.1' if not self.socks_proxy_port: self.socks_proxy_port = 9150 else: self.socks_proxy_host = None self.socks_proxy_port = None if not self.email_box_port: if self.email_box_type == 'imap' and self.email_box_ssl: self.email_box_port = 993 elif self.email_box_type == 'imap' and not self.email_box_ssl: self.email_box_port = 143 elif self.email_box_type == 'pop3' and self.email_box_ssl: self.email_box_port = 995 elif self.email_box_type == 'pop3' and not self.email_box_ssl: self.email_box_port = 110 if not self.id: VAR_139 = self.prepare_permission_name() Permission.objects.create( VAR_90=_("Permission for VAR_48: ") + self.title, content_type=ContentType.objects.get_for_model(self.__class__), codename=VAR_139, ) super(CLASS_1, self).save(*VAR_40, **VAR_7) def FUNC_17(self, *VAR_40, **VAR_7): VAR_29 = self.permission_name super(CLASS_1, self).delete(*VAR_40, **VAR_7) if VAR_29: try: VAR_164 = Permission.objects.get(codename=VAR_29[9:]) VAR_164.delete() except ObjectDoesNotExist: pass def FUNC_2(): return str(uuid.uuid4()) class CLASS_2(models.Model): VAR_41 = 1 VAR_42 = 2 VAR_43 = 3 VAR_44 = 4 VAR_45 = 5 VAR_46 = ( (VAR_41, _('Open')), (VAR_42, _('Reopened')), (VAR_43, _('Resolved')), (VAR_44, _('Closed')), (VAR_45, _('Duplicate')), ) VAR_47 = ( (1, _('1. Critical')), (2, _('2. High')), (3, _('3. Normal')), (4, _('4. Low')), (5, _('5. Very Low')), ) VAR_11 = models.CharField( _('Title'), VAR_125=200, ) VAR_48 = models.ForeignKey( CLASS_1, on_delete=models.CASCADE, VAR_136=_('Queue'), ) VAR_6 = models.DateTimeField( _('Created'), blank=True, VAR_122=_('Date this VAR_65 was first created'), ) VAR_49 = models.DateTimeField( _('Modified'), blank=True, VAR_122=_('Date this VAR_65 was most recently changed.'), ) VAR_50 = models.EmailField( _('Submitter E-Mail'), blank=True, null=True, VAR_122=_('The submitter will receive an VAR_73 for all VAR_78 ' 'follow-ups left for this task.'), ) VAR_51 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='assigned_to', blank=True, null=True, VAR_136=_('Assigned to'), ) VAR_52 = models.IntegerField( _('Status'), VAR_158=VAR_46, default=VAR_41, ) VAR_53 = models.BooleanField( _('On Hold'), blank=True, default=False, VAR_122=_('If a VAR_65 is on hold, it will not automatically be escalated.'), ) VAR_54 = models.TextField( _('Description'), blank=True, null=True, VAR_122=_('The content of the customers VAR_72.'), ) VAR_55 = models.TextField( _('Resolution'), blank=True, null=True, VAR_122=_('The VAR_55 provided to the customer by our staff.'), ) VAR_56 = models.IntegerField( _('Priority'), VAR_158=VAR_47, default=3, blank=3, VAR_122=_('1 = Highest Priority, 5 = Low Priority'), ) VAR_57 = models.DateTimeField( _('Due on'), blank=True, null=True, ) VAR_58 = models.DateTimeField( blank=True, null=True, editable=False, VAR_122=_('The VAR_76 this VAR_65 was last escalated - updated ' 'automatically by management/commands/escalate_tickets.py.'), ) VAR_59 = models.CharField( _("Secret key needed for viewing/editing VAR_65 by non-logged in users"), VAR_125=36, default=FUNC_2, ) VAR_60 = models.ForeignKey( "KBItem", blank=True, null=True, on_delete=models.CASCADE, VAR_136=_('Knowledge base item the VAR_74 was viewing when they VAR_6 this VAR_65.'), ) VAR_61 = models.ForeignKey( 'self', VAR_136=_('merged to'), related_name='merged_tickets', on_delete=models.CASCADE, null=True, blank=True ) @property def VAR_0(self): VAR_138 = datetime.timedelta(0) for val in self.followup_set.all(): if val.time_spent: VAR_138 = VAR_138 + val.time_spent return VAR_138 @property def FUNC_14(self): return FUNC_0(self.time_spent) def FUNC_18(self, VAR_62, VAR_63=None, **VAR_7): VAR_140 = set() if VAR_63 is not None: VAR_140.update(VAR_63) VAR_140.add(self.queue.email_address) def FUNC_48(VAR_73): return VAR_73 and VAR_73 not in VAR_140 def FUNC_18(VAR_141, VAR_142): if VAR_142 and VAR_142 not in VAR_140 and VAR_141 in VAR_62: VAR_165, VAR_166 = VAR_62[VAR_141] send_templated_mail(VAR_165, VAR_166, VAR_142, VAR_5=self.queue.from_address, **VAR_7) VAR_140.add(VAR_142) FUNC_18('submitter', self.submitter_email) FUNC_18('ticket_cc', self.queue.updated_ticket_cc) FUNC_18('new_ticket_cc', self.queue.new_ticket_cc) if self.assigned_to: FUNC_18('assigned_to', self.assigned_to.email) if self.queue.enable_notifications_on_email_events: for cc in self.ticketcc_set.all(): FUNC_18('ticket_cc', cc.email_address) return VAR_140 def FUNC_19(self): if not self.assigned_to: return _('Unassigned') else: if self.assigned_to.get_full_name(): return self.assigned_to.get_full_name() else: return self.assigned_to.get_username() VAR_64 = property(FUNC_19) def FUNC_20(self): return u"[%s]" % self.ticket_for_url VAR_65 = property(FUNC_20) def FUNC_21(self): return u"%s-%s" % (self.queue.slug, self.id) VAR_66 = property(FUNC_21) def FUNC_22(self): if self.priority == 2: return "warning" elif self.priority == 1: return "danger" elif self.priority == 5: return "success" else: return "" VAR_67 = property(FUNC_22) def FUNC_23(self): VAR_143 = '' if self.on_hold: VAR_143 = _(' - On Hold') VAR_144 = '' if not self.can_be_resolved: VAR_144 = _(' - Open dependencies') return u'%s%s%s' % (self.get_status_display(), VAR_143, VAR_144) VAR_68 = property(FUNC_23) def FUNC_24(self): from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.urls import reverse try: VAR_162 = Site.objects.get_current() except ImproperlyConfigured: VAR_162 = Site(domain='configure-django-sites.com') if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK: VAR_163 = 'https' else: VAR_163 = 'http' return u"%s://%s%s?VAR_65=%s&VAR_73=%s&key=%s" % ( VAR_163, VAR_162.domain, reverse('helpdesk:public_view'), self.ticket_for_url, self.submitter_email, self.secret_key ) VAR_69 = property(FUNC_24) def FUNC_25(self): from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.urls import reverse try: VAR_162 = Site.objects.get_current() except ImproperlyConfigured: VAR_162 = Site(domain='configure-django-sites.com') if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK: VAR_163 = 'https' else: VAR_163 = 'http' return u"%s://%s%s" % ( VAR_163, VAR_162.domain, reverse('helpdesk:view', VAR_40=[self.id]) ) VAR_70 = property(FUNC_25) def FUNC_26(self): VAR_145 = (CLASS_2.OPEN_STATUS, CLASS_2.REOPENED_STATUS) return CLASS_21.objects.filter(VAR_65=self).filter( depends_on__status__in=VAR_145).count() == 0 VAR_71 = property(FUNC_26) def FUNC_27(self): VAR_146 = get_user_model() try: return VAR_146.objects.get(VAR_73=self.submitter_email) except (VAR_146.DoesNotExist, VAR_146.MultipleObjectsReturned): return None class CLASS_22: VAR_147 = "created" VAR_129 = ('id',) VAR_136 = _('Ticket') VAR_137 = _('Tickets') def __str__(self): return '%s %s' % (self.id, self.title) def FUNC_28(self): from django.urls import reverse return reverse('helpdesk:view', VAR_40=(self.id,)) def FUNC_16(self, *VAR_40, **VAR_7): if not self.id: self.created = timezone.now() if not self.priority: self.priority = 3 self.modified = timezone.now() if len(self.title) > 200: self.title = self.title[:197] + "..." super(CLASS_2, self).save(*VAR_40, **VAR_7) @staticmethod def FUNC_29(VAR_72): VAR_148 = VAR_72.split('-') VAR_48 = '-'.join(VAR_148[0:-1]) return VAR_48, VAR_148[-1] def FUNC_1(self): return FUNC_1(self.description) @property def FUNC_30(self): return FUNC_1(self.resolution) def FUNC_31(self, VAR_73=None, VAR_74=None, VAR_75=None): if VAR_75: VAR_73 = VAR_75.display elif VAR_74: if VAR_74.email: VAR_73 = VAR_74.email else: return elif not VAR_73: raise ValueError('You must provide at least one parameter to get the VAR_73 from') VAR_149 = [x.display for x in self.ticketcc_set.all()] if self.submitter_email: VAR_149.append(self.submitter_email) if self.assigned_to and self.assigned_to.email: VAR_149.append(self.assigned_to.email) if VAR_73 not in VAR_149: if VAR_75: VAR_75.ticket = self VAR_75.save(update_fields=['ticket']) elif VAR_74: VAR_75 = self.ticketcc_set.create(VAR_74=user) else: VAR_75 = self.ticketcc_set.create(VAR_73=email) return VAR_75 class CLASS_3(models.Manager): def FUNC_32(self): return self.filter(VAR_78=False) def FUNC_33(self): return self.filter(VAR_78=True) class CLASS_4(models.Model): VAR_65 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Ticket'), ) VAR_76 = models.DateTimeField( _('Date'), default=timezone.now ) VAR_11 = models.CharField( _('Title'), VAR_125=200, blank=True, null=True, ) VAR_77 = models.TextField( _('Comment'), blank=True, null=True, ) VAR_78 = models.BooleanField( _('Public'), blank=True, default=False, VAR_122=_( 'Public tickets are viewable by the submitter and all ' 'staff, but non-VAR_78 tickets can only be seen by staff.' ), ) VAR_74 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, VAR_136=_('User'), ) VAR_79 = models.IntegerField( _('New Status'), VAR_158=CLASS_2.STATUS_CHOICES, blank=True, null=True, VAR_122=_('If the VAR_52 was changed, what was it changed to?'), ) VAR_80 = models.CharField( _('E-Mail ID'), VAR_125=256, blank=True, null=True, VAR_122=_("The Message ID of the submitter's VAR_73."), editable=False, ) VAR_81 = CLASS_3() VAR_0 = models.DurationField( VAR_122=_("Time spent on this follow up"), blank=True, null=True ) class CLASS_22: VAR_129 = ('date',) VAR_136 = _('Follow-up') VAR_137 = _('Follow-ups') def __str__(self): return '%s' % self.title def FUNC_28(self): return u"%s#VAR_82%s" % (self.ticket.get_absolute_url(), self.id) def FUNC_16(self, *VAR_40, **VAR_7): VAR_150 = self.ticket VAR_150.modified = timezone.now() VAR_150.save() super(CLASS_4, self).save(*VAR_40, **VAR_7) def FUNC_1(self): return FUNC_1(self.comment) @property def FUNC_14(self): return FUNC_0(self.time_spent) class CLASS_5(models.Model): VAR_82 = models.ForeignKey( CLASS_4, on_delete=models.CASCADE, VAR_136=_('Follow-up'), ) VAR_83 = models.CharField( _('Field'), VAR_125=100, ) VAR_84 = models.TextField( _('Old Value'), blank=True, null=True, ) VAR_85 = models.TextField( _('New Value'), blank=True, null=True, ) def __str__(self): VAR_151 = '%s ' % self.field if not self.new_value: VAR_151 += ugettext('removed') elif not self.old_value: VAR_151 += ugettext('set to %s') % self.new_value else: VAR_151 += ugettext('changed from "%(VAR_84)s" to "%(VAR_85)s"') % { 'old_value': self.old_value, 'new_value': self.new_value } return VAR_151 class CLASS_22: VAR_136 = _('Ticket change') VAR_137 = _('Ticket changes') def FUNC_3(VAR_2, VAR_3): return VAR_2.attachment_path(VAR_3) class CLASS_6(models.Model): VAR_86 = models.FileField( _('File'), upload_to=FUNC_3, VAR_125=1000, validators=[validate_file_extension] ) VAR_3 = models.CharField( _('Filename'), blank=True, VAR_125=1000, ) VAR_87 = models.CharField( _('MIME Type'), blank=True, VAR_125=255, ) VAR_88 = models.IntegerField( _('Size'), blank=True, VAR_122=_('Size of this VAR_86 in bytes'), ) def __str__(self): return '%s' % self.filename def FUNC_16(self, *VAR_40, **VAR_7): if not self.size: self.size = self.get_size() if not self.filename: self.filename = self.get_filename() if not self.mime_type: self.mime_type = \ mimetypes.guess_type(self.filename, strict=False)[0] or \ 'application/octet-stream' return super(CLASS_6, self).save(*VAR_40, **VAR_7) def FUNC_34(self): return str(self.file) def FUNC_35(self): return self.file.file.size def FUNC_3(self, VAR_3): assert NotImplementedError( "This method is to be implemented by CLASS_6 classes" ) class CLASS_22: VAR_129 = ('filename',) VAR_136 = _('Attachment') VAR_137 = _('Attachments') VAR_152 = True class CLASS_7(CLASS_6): VAR_82 = models.ForeignKey( CLASS_4, on_delete=models.CASCADE, VAR_136=_('Follow-up'), ) def FUNC_3(self, VAR_3): os.umask(0) VAR_153 = 'helpdesk/attachments/{VAR_66}-{VAR_59}/{id_}'.format( VAR_66=self.followup.ticket.ticket_for_url, VAR_59=self.followup.ticket.secret_key, id_=self.followup.id) VAR_154 = os.path.join(settings.MEDIA_ROOT, VAR_153) if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage": if not os.path.exists(VAR_154): os.makedirs(VAR_154, 0o777) return os.path.join(VAR_153, VAR_3) class CLASS_8(CLASS_6): VAR_60 = models.ForeignKey( "KBItem", on_delete=models.CASCADE, VAR_136=_('Knowledge base item'), ) def FUNC_3(self, VAR_3): os.umask(0) VAR_153 = 'helpdesk/attachments/kb/{VAR_99}/{kbi}'.format( VAR_99=self.kbitem.category, kbi=self.kbitem.id) VAR_154 = os.path.join(settings.MEDIA_ROOT, VAR_153) if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage": if not os.path.exists(VAR_154): os.makedirs(VAR_154, 0o777) return os.path.join(VAR_153, VAR_3) class CLASS_9(models.Model): class CLASS_22: VAR_129 = ('name',) VAR_136 = _('Pre-set reply') VAR_137 = _('Pre-set replies') VAR_89 = models.ManyToManyField( CLASS_1, blank=True, VAR_122=_('Leave blank to allow this reply to be used for all ' 'queues, or select those VAR_89 you wish to limit this reply to.'), ) VAR_90 = models.CharField( _('Name'), VAR_125=100, VAR_122=_('Only used to assist users with selecting a reply - not ' 'shown to the VAR_74.'), ) VAR_91 = models.TextField( _('Body'), VAR_122=_('Context available: {{ VAR_65 }} - VAR_65 object (eg ' '{{ VAR_65.title }}); {{ VAR_48 }} - The VAR_48; and {{ VAR_74 }} ' '- the current VAR_74.'), ) def __str__(self): return '%s' % self.name class CLASS_10(models.Model): VAR_89 = models.ManyToManyField( CLASS_1, blank=True, VAR_122=_('Leave blank for this exclusion to be applied to all VAR_89, ' 'or select those VAR_89 you wish to exclude with this entry.'), ) VAR_90 = models.CharField( _('Name'), VAR_125=100, ) VAR_76 = models.DateField( _('Date'), VAR_122=_('Date on which escalation should not happen'), ) def __str__(self): return '%s' % self.name class CLASS_22: VAR_136 = _('Escalation exclusion') VAR_137 = _('Escalation exclusions') class CLASS_11(models.Model): VAR_92 = models.CharField( _('Template Name'), VAR_125=100, ) VAR_93 = models.CharField( _('Subject'), VAR_125=100, VAR_122=_('This will be prefixed with "[VAR_65.ticket] VAR_65.title"' '. We recommend something simple such as "(Updated") or "(Closed)"' ' - the same VAR_166 is available as in VAR_95, below.'), ) VAR_94 = models.CharField( _('Heading'), VAR_125=100, VAR_122=_('In HTML e-mails, this will be the VAR_94 at the top of ' 'the VAR_73 - the same VAR_166 is available as in VAR_95, ' 'below.'), ) VAR_95 = models.TextField( _('Plain Text'), VAR_122=_('The VAR_166 available to you includes {{ VAR_65 }}, ' '{{ VAR_48 }}, and depending on the time of the call: ' '{{ VAR_55 }} or {{ VAR_77 }}.'), ) VAR_96 = models.TextField( _('HTML'), VAR_122=_('The same VAR_166 is available here as in VAR_95, above.'), ) VAR_14 = models.CharField( _('Locale'), VAR_125=10, blank=True, null=True, VAR_122=_('Locale of this VAR_165.'), ) def __str__(self): return '%s' % self.template_name class CLASS_22: VAR_129 = ('template_name', 'locale') VAR_136 = _('e-mail template') VAR_137 = _('e-mail templates') class CLASS_12(models.Model): VAR_90 = models.CharField( _('Name of the category'), VAR_125=100, ) VAR_11 = models.CharField( _('Title on knowledgebase page'), VAR_125=100, ) VAR_12 = models.SlugField( _('Slug'), ) VAR_54 = models.TextField( _('Description'), ) VAR_48 = models.ForeignKey( CLASS_1, blank=True, null=True, on_delete=models.CASCADE, VAR_136=_('Default VAR_48 when creating a VAR_65 after viewing this VAR_99.'), ) VAR_78 = models.BooleanField( default=True, VAR_136=_("Is CLASS_12 publicly visible?") ) def __str__(self): return '%s' % self.name class CLASS_22: VAR_129 = ('title',) VAR_136 = _('Knowledge base category') VAR_137 = _('Knowledge base categories') def FUNC_28(self): from django.urls import reverse return reverse('helpdesk:kb_category', VAR_7={'slug': self.slug}) class CLASS_13(models.Model): VAR_97 = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='votes', ) VAR_98 = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='downvotes', ) VAR_99 = models.ForeignKey( CLASS_12, on_delete=models.CASCADE, VAR_136=_('Category'), ) VAR_11 = models.CharField( _('Title'), VAR_125=100, ) VAR_100 = models.TextField( _('Question'), ) VAR_101 = models.TextField( _('Answer'), ) VAR_102 = models.IntegerField( _('Votes'), VAR_122=_('Total number of VAR_102 cast for this item'), default=0, ) VAR_103 = models.IntegerField( _('Positive Votes'), VAR_122=_('Number of VAR_102 for this item which were POSITIVE.'), default=0, ) VAR_104 = models.DateTimeField( _('Last Updated'), VAR_122=_('The VAR_76 on which this VAR_100 was most recently changed.'), blank=True, ) VAR_105 = models.ForeignKey( helpdesk_settings.HELPDESK_TEAMS_MODEL, on_delete=models.CASCADE, VAR_136=_('Team'), blank=True, null=True, ) VAR_106 = models.PositiveIntegerField( _('Order'), blank=True, null=True, ) VAR_107 = models.BooleanField( _('Enabled to VAR_120 to users'), default=True, ) def FUNC_16(self, *VAR_40, **VAR_7): if not self.last_updated: self.last_updated = timezone.now() return super(CLASS_13, self).save(*VAR_40, **VAR_7) def FUNC_36(self): return helpdesk_settings.HELPDESK_KBITEM_TEAM_GETTER(self) def FUNC_37(self): if self.votes > 0: return (self.recommendations / self.votes) * 10 else: return _('Unrated') VAR_108 = property(FUNC_37) def __str__(self): return '%s: %s' % (self.category.title, self.title) class CLASS_22: VAR_129 = ('order', 'title',) VAR_136 = _('Knowledge base item') VAR_137 = _('Knowledge base items') def FUNC_28(self): from django.urls import reverse return str(reverse('helpdesk:kb_category', VAR_40=(self.category.slug,))) + "?VAR_60=" + str(self.pk) def FUNC_38(self): from django.urls import reverse return str(reverse('helpdesk:list')) + "?VAR_60=" + str(self.pk) def FUNC_39(self): return CLASS_2.objects.filter(VAR_60=self, status__in=(1, 2)).count() def FUNC_40(self): return CLASS_2.objects.filter(VAR_60=self, status__in=(1, 2), assigned_to__isnull=True) def FUNC_1(self): return FUNC_1(self.answer) class CLASS_14(models.Model): VAR_74 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, VAR_136=_('User'), ) VAR_11 = models.CharField( _('Query Name'), VAR_125=100, VAR_122=_('User-provided VAR_90 for this query'), ) VAR_109 = models.BooleanField( _('Shared With Other Users?'), blank=True, default=False, VAR_122=_('Should other users see this VAR_72?'), ) VAR_72 = models.TextField( _('Search Query'), VAR_122=_('Pickled VAR_72 object. Be wary changing this.'), ) def __str__(self): if self.shared: return '%s (*)' % self.title else: return '%s' % self.title class CLASS_22: VAR_136 = _('Saved search') VAR_137 = _('Saved searches') def FUNC_4(VAR_4): from helpdesk.settings import DEFAULT_USER_SETTINGS return DEFAULT_USER_SETTINGS[VAR_4] def FUNC_5(): return FUNC_4('login_view_ticketlist') def FUNC_6(): return FUNC_4('email_on_ticket_change') def FUNC_7(): return FUNC_4('email_on_ticket_assign') def FUNC_8(): return FUNC_4('tickets_per_page') def FUNC_9(): return FUNC_4('use_email_as_submitter') class CLASS_15(models.Model): VAR_110 = ((10, '10'), (25, '25'), (50, '50'), (100, '100')) VAR_74 = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="usersettings_helpdesk") VAR_111 = models.TextField( _('DEPRECATED! Settings Dictionary DEPRECATED!'), VAR_122=_('DEPRECATED! This is a base64-encoded representation of a pickled Python dictionary. ' 'Do not change this VAR_83 via the admin.'), blank=True, null=True, ) VAR_112 = models.BooleanField( VAR_136=_('Show CLASS_2 List on Login?'), VAR_122=_('Display the VAR_65 list upon login? Otherwise, the dashboard is shown.'), default=FUNC_5, ) VAR_113 = models.BooleanField( VAR_136=_('E-mail me on VAR_65 change?'), VAR_122=_( 'If you\'re the VAR_65 owner and the VAR_65 is changed via the web by somebody else,' 'do you want to receive an e-mail?' ), default=FUNC_6, ) VAR_114 = models.BooleanField( VAR_136=_('E-mail me when assigned a VAR_65?'), VAR_122=_('If you are assigned a VAR_65 via the web, do you want to receive an e-mail?'), default=FUNC_7, ) VAR_115 = models.IntegerField( VAR_136=_('Number of tickets to show per page'), VAR_122=_('How many tickets do you want to see on the CLASS_2 List page?'), default=FUNC_8, VAR_158=VAR_110, ) VAR_116 = models.BooleanField( VAR_136=_('Use my e-mail address when submitting tickets?'), VAR_122=_('When you submit a VAR_65, do you want to automatically ' 'use your e-mail address as the submitter address? You ' 'can type a different e-mail address when entering the ' 'ticket if needed, this option only changes the default.'), default=FUNC_9, ) def __str__(self): return 'Preferences for %s' % self.user class CLASS_22: VAR_136 = _('User Setting') VAR_137 = _('User Settings') def FUNC_10(VAR_5, VAR_2, VAR_6, **VAR_7): if VAR_6: CLASS_15.objects.create(VAR_74=VAR_2) models.signals.post_save.connect(FUNC_10, VAR_5=settings.AUTH_USER_MODEL) class CLASS_16(models.Model): class CLASS_22: VAR_136 = _('Ignored e-mail address') VAR_137 = _('Ignored e-mail addresses') VAR_89 = models.ManyToManyField( CLASS_1, blank=True, VAR_122=_('Leave blank for this e-mail to be ignored on all VAR_89, ' 'or select those VAR_89 you wish to ignore this e-mail for.'), ) VAR_90 = models.CharField( _('Name'), VAR_125=100, ) VAR_76 = models.DateField( _('Date'), VAR_122=_('Date on which this e-mail address was added'), blank=True, editable=False ) VAR_13 = models.CharField( _('E-Mail Address'), VAR_125=150, VAR_122=_('Enter a full e-mail address, or portions with ' 'wildcards, eg *@domain.com or postmaster@*.'), ) VAR_117 = models.BooleanField( _('Save Emails in Mailbox?'), blank=True, default=False, VAR_122=_('Do you want to FUNC_16 emails from this address in the mailbox? ' 'If this is unticked, emails from this address will be deleted.'), ) def __str__(self): return '%s' % self.name def FUNC_16(self, *VAR_40, **VAR_7): if not self.date: self.date = timezone.now() return super(CLASS_16, self).save(*VAR_40, **VAR_7) def FUNC_41(self): VAR_89 = self.queues.all().order_by('title') if len(VAR_89) == 0: return '*' else: return ', '.join([str(q) for q in VAR_89]) def FUNC_42(self, VAR_73): VAR_155 = self.email_address.split("@") VAR_156 = VAR_73.split("@") if self.email_address == VAR_73 or \ VAR_155[0] == "*" and VAR_155[1] == VAR_156[1] or \ VAR_155[1] == "*" and VAR_155[0] == VAR_156[0] or \ VAR_155[0] == "*" and VAR_155[1] == "*": return True else: return False class CLASS_17(models.Model): VAR_65 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Ticket'), ) VAR_74 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, VAR_122=_('User who wishes to receive updates for this VAR_65.'), VAR_136=_('User'), ) VAR_73 = models.EmailField( _('E-Mail Address'), blank=True, null=True, VAR_122=_('For non-VAR_74 followers, enter their e-mail address'), ) VAR_118 = models.BooleanField( _('Can View CLASS_2?'), blank=True, default=False, VAR_122=_('Can this CC login to view the VAR_65 details?'), ) VAR_119 = models.BooleanField( _('Can Update CLASS_2?'), blank=True, default=False, VAR_122=_('Can this CC login and update the VAR_65?'), ) def FUNC_43(self): if self.user and self.user.email is not None: return self.user.email else: return self.email VAR_13 = property(FUNC_43) def FUNC_44(self): if self.user: return self.user else: return self.email VAR_120 = property(FUNC_44) def __str__(self): return '%s for %s' % (self.display, self.ticket.title) def FUNC_45(self): if self.user and not self.user.email: raise ValidationError('User has no VAR_73 address') class CLASS_18(models.Manager): def FUNC_46(self): return super(CLASS_18, self).get_queryset().order_by('ordering') class CLASS_19(models.Model): VAR_90 = models.SlugField( _('Field Name'), VAR_122=_('As used in the database and behind the scenes. ' 'Must be unique and consist of only lowercase letters with no punctuation.'), unique=True, ) VAR_121 = models.CharField( _('Label'), VAR_125=30, VAR_122=_('The VAR_120 VAR_121 for this field'), ) VAR_122 = models.TextField( _('Help Text'), VAR_122=_('Shown to the VAR_74 when editing the ticket'), blank=True, null=True ) VAR_123 = ( ('varchar', _('Character (single line)')), ('text', _('Text (multi-line)')), ('integer', _('Integer')), ('decimal', _('Decimal')), ('list', _('List')), ('boolean', _('Boolean (checkbox yes/no)')), ('date', _('Date')), ('time', _('Time')), ('datetime', _('Date & Time')), ('email', _('E-Mail Address')), ('url', _('URL')), ('ipaddress', _('IP Address')), ('slug', _('Slug')), ) VAR_124 = models.CharField( _('Data Type'), VAR_125=100, VAR_122=_('Allows you to restrict the data entered into this field'), VAR_158=VAR_123, ) VAR_125 = models.IntegerField( _('Maximum Length (characters)'), blank=True, null=True, ) VAR_126 = models.IntegerField( _('Decimal Places'), VAR_122=_('Only used for decimal fields'), blank=True, null=True, ) VAR_127 = models.BooleanField( _('Add empty first choice to List?'), default=False, VAR_122=_('Only for List: adds an empty first entry to the VAR_158 list, ' 'which enforces that the VAR_74 makes an active choice.'), ) VAR_128 = models.TextField( _('List Values'), VAR_122=_('For list fields only. Enter one option per line.'), blank=True, null=True, ) VAR_129 = models.IntegerField( _('Ordering'), VAR_122=_('Lower numbers are displayed first; higher numbers are listed later'), blank=True, null=True, ) def FUNC_47(self): VAR_157 = StringIO(self.list_values) VAR_158 = [[item.strip(), item.strip()] for item in VAR_157.readlines()] VAR_157.close() return VAR_158 VAR_130 = property(FUNC_47) VAR_131 = models.BooleanField( _('Required?'), VAR_122=_('Does the VAR_74 have to enter a VAR_133 for this VAR_83?'), default=False, ) VAR_132 = models.BooleanField( _('Staff Only?'), VAR_122=_('If this is ticked, then the VAR_78 submission form ' 'will NOT show this field'), default=False, ) VAR_81 = CLASS_18() def __str__(self): return '%s' % self.name class CLASS_22: VAR_136 = _('Custom field') VAR_137 = _('Custom fields') class CLASS_20(models.Model): VAR_65 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Ticket'), ) VAR_83 = models.ForeignKey( CLASS_19, on_delete=models.CASCADE, VAR_136=_('Field'), ) VAR_133 = models.TextField(blank=True, null=True) def __str__(self): return '%s / %s' % (self.ticket, self.field) class CLASS_22: VAR_159 = (('ticket', 'field'),) VAR_136 = _('Ticket custom VAR_83 value') VAR_137 = _('Ticket custom VAR_83 values') class CLASS_21(models.Model): class CLASS_22: VAR_159 = (('ticket', 'depends_on'),) VAR_136 = _('Ticket dependency') VAR_137 = _('Ticket dependencies') VAR_65 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Ticket'), related_name='ticketdependency', ) VAR_134 = models.ForeignKey( CLASS_2, on_delete=models.CASCADE, VAR_136=_('Depends On Ticket'), related_name='depends_on', ) def __str__(self): return '%s / %s' % (self.ticket, self.depends_on)
[ 3, 5, 9, 23, 27, 28, 30, 32, 34, 36, 37, 47, 48, 53, 54, 58, 60, 62, 64, 69, 71, 81, 82, 87, 90, 92, 97, 105, 114, 123, 130, 138, 146, 156, 167, 176, 187, 196, 205, 213, 221, 229, 240, 250, 259, 267, 272, 274, 283, 290, 297, 315, 325, 334, 339, 342, 347, 355, 358, 365, 376, 380, 385, 389, 393, 402, 412, 414, 415, 417, 423, 425, 429, 430, 437, 438, 441, 442, 449, 455, 459, 465, 473, 481, 486, 492, 498, 504, 512, 521, 527, 534, 541, 548, 556, 562, 570, 576, 584, 593, 604, 608, 612, 615, 617, 622, 624, 629, 631, 633, 636, 639, 641, 644, 650, 660, 673, 677, 680, 685, 699, 712, 738, 762, 773, 780, 786, 789, 793, 796, 798, 801, 803, 806, 808, 811, 812, 816, 819, 823, 829, 841, 845, 846, 852, 853, 863, 864, 866, 869, 872, 873, 879, 882, 886, 892, 897, 904, 910, 920, 928, 936, 945, 947, 952, 957, 960, 963, 969, 972, 976, 977, 983, 989, 994, 1000, 1006, 1019, 1023, 1024, 1028, 1029, 1035, 1042, 1048, 1054, 1060, 1063, 1065, 1068, 1071, 1076, 1078, 1081, 1084, 1092, 1098, 1099, 1101, 1107, 1109, 1120, 1121, 1123, 1129, 1131, 1141, 1142, 1150, 1158, 1165, 1172, 1179, 1182, 1183, 1188, 1190, 1194, 1201, 1206, 1211, 1214, 1218, 1219, 1224, 1228, 1233, 1241, 1249, 1256, 1261, 1269, 1272, 1277, 1278, 1284, 1289, 1294, 1298, 1302, 1310, 1315, 1318, 1323, 1327, 1328, 1347, 1352, 1356, 1360, 1366, 1372, 1378, 1386, 1392, 1397, 1402, 1405, 1413, 1416, 1421, 1425, 1429, 1432, 1435, 1438, 1439, 1456, 1462, 1469, 1474, 1480, 1484, 1485, 1489, 1490, 1493, 1494, 1497, 1498, 1501, 1502, 1505, 1506, 1509, 1510, 1518, 1523, 1531, 1537, 1546, 1552, 1559, 1568, 1571, 1575, 1576, 1582, 1588, 1589, 1591, 1592, 1602, 1609, 1614, 1621, 1628, 1636, 1639, 1644, 1654, 1663, 1666, 1669, 1677, 1678, 1684, 1688, 1694, 1703, 1710, 1717, 1724, 1731, 1738, 1741, 1745, 1746, 1748, 1751, 1752, 1757, 1764, 1770, 1777, 1793, 1800, 1806, 1813, 1820, 1827, 1834, 1841, 1847, 1854, 1856, 1859, 1863, 1864, 1871, 1877, 1879, 1882, 1887, 1888, 1899, 1906, 1913, 1916, 1, 2, 3, 4, 5, 6, 7, 8, 84, 85, 86, 87, 88, 89, 90, 91, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 979, 980, 981, 982, 1026, 1031, 1032, 1033, 1034, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1221, 1222, 1223, 1224, 1225, 1226, 1227, 1280, 1281, 1282, 1283, 1330, 1331, 1332, 1333, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1512, 1513, 1514, 1515, 1516, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1594, 1595, 1596, 1597, 1598, 1680, 1681, 1682, 1683, 1684, 1685, 1686, 1687, 1754, 1755, 1756, 1890, 1891, 1892, 1893, 1894, 349, 350, 351, 352, 353, 368, 369, 370, 382, 383, 384, 596, 597, 598, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 662, 663, 664, 675, 676, 682, 687, 688, 689, 701, 702, 703, 714, 715, 716, 717, 740, 741, 742, 743, 764, 765, 766, 767, 768, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 1086, 1087, 1088, 1407, 1646, 1647, 1648, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 1664, 1665 ]
[ 3, 5, 9, 23, 27, 28, 30, 32, 34, 36, 37, 47, 48, 53, 54, 58, 60, 62, 64, 69, 71, 81, 82, 87, 90, 92, 97, 105, 114, 123, 130, 138, 146, 156, 167, 176, 187, 196, 205, 213, 221, 229, 240, 250, 259, 267, 272, 274, 283, 290, 297, 315, 325, 334, 339, 342, 347, 355, 358, 365, 376, 380, 385, 389, 393, 402, 412, 414, 415, 417, 423, 425, 429, 430, 437, 438, 441, 442, 449, 455, 459, 465, 473, 481, 486, 492, 498, 504, 512, 521, 527, 534, 541, 548, 556, 562, 570, 576, 584, 593, 604, 608, 612, 615, 617, 622, 624, 629, 631, 633, 636, 639, 641, 644, 650, 660, 673, 677, 680, 685, 699, 712, 738, 762, 773, 780, 786, 789, 793, 796, 798, 801, 803, 806, 808, 811, 812, 816, 819, 823, 829, 841, 845, 846, 852, 853, 863, 864, 866, 869, 872, 873, 879, 882, 886, 892, 897, 904, 910, 920, 928, 936, 945, 947, 952, 957, 960, 963, 969, 972, 976, 977, 983, 989, 994, 1000, 1006, 1019, 1023, 1024, 1028, 1029, 1035, 1042, 1048, 1054, 1060, 1063, 1065, 1068, 1071, 1076, 1078, 1081, 1084, 1092, 1098, 1099, 1101, 1107, 1109, 1120, 1121, 1123, 1129, 1131, 1141, 1142, 1150, 1158, 1165, 1172, 1179, 1182, 1183, 1188, 1190, 1194, 1201, 1206, 1211, 1214, 1218, 1219, 1224, 1228, 1233, 1241, 1249, 1256, 1261, 1269, 1272, 1277, 1278, 1284, 1289, 1294, 1298, 1302, 1310, 1315, 1318, 1323, 1327, 1328, 1347, 1352, 1356, 1360, 1366, 1372, 1378, 1386, 1392, 1397, 1402, 1405, 1413, 1416, 1421, 1425, 1429, 1432, 1435, 1438, 1439, 1456, 1462, 1469, 1474, 1480, 1484, 1485, 1489, 1490, 1493, 1494, 1497, 1498, 1501, 1502, 1505, 1506, 1509, 1510, 1518, 1523, 1531, 1537, 1546, 1552, 1559, 1568, 1571, 1575, 1576, 1582, 1588, 1589, 1591, 1592, 1602, 1609, 1614, 1621, 1628, 1636, 1639, 1644, 1654, 1663, 1666, 1669, 1677, 1678, 1684, 1688, 1694, 1703, 1710, 1717, 1724, 1731, 1738, 1741, 1745, 1746, 1748, 1751, 1752, 1757, 1764, 1770, 1777, 1793, 1800, 1806, 1813, 1820, 1827, 1834, 1841, 1847, 1854, 1856, 1859, 1863, 1864, 1871, 1877, 1879, 1882, 1887, 1888, 1899, 1906, 1913, 1916, 1, 2, 3, 4, 5, 6, 7, 8, 84, 85, 86, 87, 88, 89, 90, 91, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 979, 980, 981, 982, 1026, 1031, 1032, 1033, 1034, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1221, 1222, 1223, 1224, 1225, 1226, 1227, 1280, 1281, 1282, 1283, 1330, 1331, 1332, 1333, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1512, 1513, 1514, 1515, 1516, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1594, 1595, 1596, 1597, 1598, 1680, 1681, 1682, 1683, 1684, 1685, 1686, 1687, 1754, 1755, 1756, 1890, 1891, 1892, 1893, 1894, 349, 350, 351, 352, 353, 368, 369, 370, 382, 383, 384, 596, 597, 598, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 662, 663, 664, 675, 676, 682, 687, 688, 689, 701, 702, 703, 714, 715, 716, 717, 740, 741, 742, 743, 764, 765, 766, 767, 768, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 1086, 1087, 1088, 1407, 1646, 1647, 1648, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 1664, 1665 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2020 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import urllib.parse from io import BytesIO, StringIO from mock import Mock import signedjson.key from canonicaljson import encode_canonical_json from nacl.signing import SigningKey from signedjson.sign import sign_json from twisted.web.resource import NoResource from synapse.crypto.keyring import PerspectivesKeyFetcher from synapse.http.site import SynapseRequest from synapse.rest.key.v2 import KeyApiV2Resource from synapse.storage.keys import FetchKeyResult from synapse.util.httpresourcetree import create_resource_tree from synapse.util.stringutils import random_string from tests import unittest from tests.server import FakeChannel from tests.utils import default_config class BaseRemoteKeyResourceTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): self.http_client = Mock() return self.setup_test_homeserver(http_client=self.http_client) def create_test_resource(self): return create_resource_tree( {"/_matrix/key/v2": KeyApiV2Resource(self.hs)}, root_resource=NoResource() ) def expect_outgoing_key_request( self, server_name: str, signing_key: SigningKey ) -> None: """ Tell the mock http client to expect an outgoing GET request for the given key """ async def get_json(destination, path, ignore_backoff=False, **kwargs): self.assertTrue(ignore_backoff) self.assertEqual(destination, server_name) key_id = "%s:%s" % (signing_key.alg, signing_key.version) self.assertEqual( path, "/_matrix/key/v2/server/%s" % (urllib.parse.quote(key_id),) ) response = { "server_name": server_name, "old_verify_keys": {}, "valid_until_ts": 200 * 1000, "verify_keys": { key_id: { "key": signedjson.key.encode_verify_key_base64( signing_key.verify_key ) } }, } sign_json(response, server_name, signing_key) return response self.http_client.get_json.side_effect = get_json class RemoteKeyResourceTestCase(BaseRemoteKeyResourceTestCase): def make_notary_request(self, server_name: str, key_id: str) -> dict: """Send a GET request to the test server requesting the given key. Checks that the response is a 200 and returns the decoded json body. """ channel = FakeChannel(self.site, self.reactor) req = SynapseRequest(channel) req.content = BytesIO(b"") req.requestReceived( b"GET", b"/_matrix/key/v2/query/%s/%s" % (server_name.encode("utf-8"), key_id.encode("utf-8")), b"1.1", ) channel.await_result() self.assertEqual(channel.code, 200) resp = channel.json_body return resp def test_get_key(self): """Fetch a remote key""" SERVER_NAME = "remote.server" testkey = signedjson.key.generate_signing_key("ver1") self.expect_outgoing_key_request(SERVER_NAME, testkey) resp = self.make_notary_request(SERVER_NAME, "ed25519:ver1") keys = resp["server_keys"] self.assertEqual(len(keys), 1) self.assertIn("ed25519:ver1", keys[0]["verify_keys"]) self.assertEqual(len(keys[0]["verify_keys"]), 1) # it should be signed by both the origin server and the notary self.assertIn(SERVER_NAME, keys[0]["signatures"]) self.assertIn(self.hs.hostname, keys[0]["signatures"]) def test_get_own_key(self): """Fetch our own key""" testkey = signedjson.key.generate_signing_key("ver1") self.expect_outgoing_key_request(self.hs.hostname, testkey) resp = self.make_notary_request(self.hs.hostname, "ed25519:ver1") keys = resp["server_keys"] self.assertEqual(len(keys), 1) # it should be signed by both itself, and the notary signing key sigs = keys[0]["signatures"] self.assertEqual(len(sigs), 1) self.assertIn(self.hs.hostname, sigs) oursigs = sigs[self.hs.hostname] self.assertEqual(len(oursigs), 2) # the requested key should be present in the verify_keys section self.assertIn("ed25519:ver1", keys[0]["verify_keys"]) class EndToEndPerspectivesTests(BaseRemoteKeyResourceTestCase): """End-to-end tests of the perspectives fetch case The idea here is to actually wire up a PerspectivesKeyFetcher to the notary endpoint, to check that the two implementations are compatible. """ def default_config(self): config = super().default_config() # replace the signing key with our own self.hs_signing_key = signedjson.key.generate_signing_key("kssk") strm = StringIO() signedjson.key.write_signing_keys(strm, [self.hs_signing_key]) config["signing_key"] = strm.getvalue() return config def prepare(self, reactor, clock, homeserver): # make a second homeserver, configured to use the first one as a key notary self.http_client2 = Mock() config = default_config(name="keyclient") config["trusted_key_servers"] = [ { "server_name": self.hs.hostname, "verify_keys": { "ed25519:%s" % ( self.hs_signing_key.version, ): signedjson.key.encode_verify_key_base64( self.hs_signing_key.verify_key ) }, } ] self.hs2 = self.setup_test_homeserver( http_client=self.http_client2, config=config ) # wire up outbound POST /key/v2/query requests from hs2 so that they # will be forwarded to hs1 async def post_json(destination, path, data): self.assertEqual(destination, self.hs.hostname) self.assertEqual( path, "/_matrix/key/v2/query", ) channel = FakeChannel(self.site, self.reactor) req = SynapseRequest(channel) req.content = BytesIO(encode_canonical_json(data)) req.requestReceived( b"POST", path.encode("utf-8"), b"1.1", ) channel.await_result() self.assertEqual(channel.code, 200) resp = channel.json_body return resp self.http_client2.post_json.side_effect = post_json def test_get_key(self): """Fetch a key belonging to a random server""" # make up a key to be fetched. testkey = signedjson.key.generate_signing_key("abc") # we expect hs1 to make a regular key request to the target server self.expect_outgoing_key_request("targetserver", testkey) keyid = "ed25519:%s" % (testkey.version,) fetcher = PerspectivesKeyFetcher(self.hs2) d = fetcher.get_keys({"targetserver": {keyid: 1000}}) res = self.get_success(d) self.assertIn("targetserver", res) keyres = res["targetserver"][keyid] assert isinstance(keyres, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(keyres.verify_key), signedjson.key.encode_verify_key_base64(testkey.verify_key), ) def test_get_notary_key(self): """Fetch a key belonging to the notary server""" # make up a key to be fetched. We randomise the keyid to try to get it to # appear before the key server signing key sometimes (otherwise we bail out # before fetching its signature) testkey = signedjson.key.generate_signing_key(random_string(5)) # we expect hs1 to make a regular key request to itself self.expect_outgoing_key_request(self.hs.hostname, testkey) keyid = "ed25519:%s" % (testkey.version,) fetcher = PerspectivesKeyFetcher(self.hs2) d = fetcher.get_keys({self.hs.hostname: {keyid: 1000}}) res = self.get_success(d) self.assertIn(self.hs.hostname, res) keyres = res[self.hs.hostname][keyid] assert isinstance(keyres, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(keyres.verify_key), signedjson.key.encode_verify_key_base64(testkey.verify_key), ) def test_get_notary_keyserver_key(self): """Fetch the notary's keyserver key""" # we expect hs1 to make a regular key request to itself self.expect_outgoing_key_request(self.hs.hostname, self.hs_signing_key) keyid = "ed25519:%s" % (self.hs_signing_key.version,) fetcher = PerspectivesKeyFetcher(self.hs2) d = fetcher.get_keys({self.hs.hostname: {keyid: 1000}}) res = self.get_success(d) self.assertIn(self.hs.hostname, res) keyres = res[self.hs.hostname][keyid] assert isinstance(keyres, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(keyres.verify_key), signedjson.key.encode_verify_key_base64(self.hs_signing_key.verify_key), )
# -*- coding: utf-8 -*- # Copyright 2020 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import urllib.parse from io import BytesIO, StringIO from mock import Mock import signedjson.key from canonicaljson import encode_canonical_json from nacl.signing import SigningKey from signedjson.sign import sign_json from twisted.web.resource import NoResource from synapse.crypto.keyring import PerspectivesKeyFetcher from synapse.http.site import SynapseRequest from synapse.rest.key.v2 import KeyApiV2Resource from synapse.storage.keys import FetchKeyResult from synapse.util.httpresourcetree import create_resource_tree from synapse.util.stringutils import random_string from tests import unittest from tests.server import FakeChannel from tests.utils import default_config class BaseRemoteKeyResourceTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): self.http_client = Mock() return self.setup_test_homeserver(federation_http_client=self.http_client) def create_test_resource(self): return create_resource_tree( {"/_matrix/key/v2": KeyApiV2Resource(self.hs)}, root_resource=NoResource() ) def expect_outgoing_key_request( self, server_name: str, signing_key: SigningKey ) -> None: """ Tell the mock http client to expect an outgoing GET request for the given key """ async def get_json(destination, path, ignore_backoff=False, **kwargs): self.assertTrue(ignore_backoff) self.assertEqual(destination, server_name) key_id = "%s:%s" % (signing_key.alg, signing_key.version) self.assertEqual( path, "/_matrix/key/v2/server/%s" % (urllib.parse.quote(key_id),) ) response = { "server_name": server_name, "old_verify_keys": {}, "valid_until_ts": 200 * 1000, "verify_keys": { key_id: { "key": signedjson.key.encode_verify_key_base64( signing_key.verify_key ) } }, } sign_json(response, server_name, signing_key) return response self.http_client.get_json.side_effect = get_json class RemoteKeyResourceTestCase(BaseRemoteKeyResourceTestCase): def make_notary_request(self, server_name: str, key_id: str) -> dict: """Send a GET request to the test server requesting the given key. Checks that the response is a 200 and returns the decoded json body. """ channel = FakeChannel(self.site, self.reactor) req = SynapseRequest(channel) req.content = BytesIO(b"") req.requestReceived( b"GET", b"/_matrix/key/v2/query/%s/%s" % (server_name.encode("utf-8"), key_id.encode("utf-8")), b"1.1", ) channel.await_result() self.assertEqual(channel.code, 200) resp = channel.json_body return resp def test_get_key(self): """Fetch a remote key""" SERVER_NAME = "remote.server" testkey = signedjson.key.generate_signing_key("ver1") self.expect_outgoing_key_request(SERVER_NAME, testkey) resp = self.make_notary_request(SERVER_NAME, "ed25519:ver1") keys = resp["server_keys"] self.assertEqual(len(keys), 1) self.assertIn("ed25519:ver1", keys[0]["verify_keys"]) self.assertEqual(len(keys[0]["verify_keys"]), 1) # it should be signed by both the origin server and the notary self.assertIn(SERVER_NAME, keys[0]["signatures"]) self.assertIn(self.hs.hostname, keys[0]["signatures"]) def test_get_own_key(self): """Fetch our own key""" testkey = signedjson.key.generate_signing_key("ver1") self.expect_outgoing_key_request(self.hs.hostname, testkey) resp = self.make_notary_request(self.hs.hostname, "ed25519:ver1") keys = resp["server_keys"] self.assertEqual(len(keys), 1) # it should be signed by both itself, and the notary signing key sigs = keys[0]["signatures"] self.assertEqual(len(sigs), 1) self.assertIn(self.hs.hostname, sigs) oursigs = sigs[self.hs.hostname] self.assertEqual(len(oursigs), 2) # the requested key should be present in the verify_keys section self.assertIn("ed25519:ver1", keys[0]["verify_keys"]) class EndToEndPerspectivesTests(BaseRemoteKeyResourceTestCase): """End-to-end tests of the perspectives fetch case The idea here is to actually wire up a PerspectivesKeyFetcher to the notary endpoint, to check that the two implementations are compatible. """ def default_config(self): config = super().default_config() # replace the signing key with our own self.hs_signing_key = signedjson.key.generate_signing_key("kssk") strm = StringIO() signedjson.key.write_signing_keys(strm, [self.hs_signing_key]) config["signing_key"] = strm.getvalue() return config def prepare(self, reactor, clock, homeserver): # make a second homeserver, configured to use the first one as a key notary self.http_client2 = Mock() config = default_config(name="keyclient") config["trusted_key_servers"] = [ { "server_name": self.hs.hostname, "verify_keys": { "ed25519:%s" % ( self.hs_signing_key.version, ): signedjson.key.encode_verify_key_base64( self.hs_signing_key.verify_key ) }, } ] self.hs2 = self.setup_test_homeserver( federation_http_client=self.http_client2, config=config ) # wire up outbound POST /key/v2/query requests from hs2 so that they # will be forwarded to hs1 async def post_json(destination, path, data): self.assertEqual(destination, self.hs.hostname) self.assertEqual( path, "/_matrix/key/v2/query", ) channel = FakeChannel(self.site, self.reactor) req = SynapseRequest(channel) req.content = BytesIO(encode_canonical_json(data)) req.requestReceived( b"POST", path.encode("utf-8"), b"1.1", ) channel.await_result() self.assertEqual(channel.code, 200) resp = channel.json_body return resp self.http_client2.post_json.side_effect = post_json def test_get_key(self): """Fetch a key belonging to a random server""" # make up a key to be fetched. testkey = signedjson.key.generate_signing_key("abc") # we expect hs1 to make a regular key request to the target server self.expect_outgoing_key_request("targetserver", testkey) keyid = "ed25519:%s" % (testkey.version,) fetcher = PerspectivesKeyFetcher(self.hs2) d = fetcher.get_keys({"targetserver": {keyid: 1000}}) res = self.get_success(d) self.assertIn("targetserver", res) keyres = res["targetserver"][keyid] assert isinstance(keyres, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(keyres.verify_key), signedjson.key.encode_verify_key_base64(testkey.verify_key), ) def test_get_notary_key(self): """Fetch a key belonging to the notary server""" # make up a key to be fetched. We randomise the keyid to try to get it to # appear before the key server signing key sometimes (otherwise we bail out # before fetching its signature) testkey = signedjson.key.generate_signing_key(random_string(5)) # we expect hs1 to make a regular key request to itself self.expect_outgoing_key_request(self.hs.hostname, testkey) keyid = "ed25519:%s" % (testkey.version,) fetcher = PerspectivesKeyFetcher(self.hs2) d = fetcher.get_keys({self.hs.hostname: {keyid: 1000}}) res = self.get_success(d) self.assertIn(self.hs.hostname, res) keyres = res[self.hs.hostname][keyid] assert isinstance(keyres, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(keyres.verify_key), signedjson.key.encode_verify_key_base64(testkey.verify_key), ) def test_get_notary_keyserver_key(self): """Fetch the notary's keyserver key""" # we expect hs1 to make a regular key request to itself self.expect_outgoing_key_request(self.hs.hostname, self.hs_signing_key) keyid = "ed25519:%s" % (self.hs_signing_key.version,) fetcher = PerspectivesKeyFetcher(self.hs2) d = fetcher.get_keys({self.hs.hostname: {keyid: 1000}}) res = self.get_success(d) self.assertIn(self.hs.hostname, res) keyres = res[self.hs.hostname][keyid] assert isinstance(keyres, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(keyres.verify_key), signedjson.key.encode_verify_key_base64(self.hs_signing_key.verify_key), )
open_redirect
{ "code": [ " return self.setup_test_homeserver(http_client=self.http_client)", " http_client=self.http_client2, config=config" ], "line_no": [ 42, 175 ] }
{ "code": [ " return self.setup_test_homeserver(federation_http_client=self.http_client)", " federation_http_client=self.http_client2, config=config" ], "line_no": [ 42, 175 ] }
import urllib.parse from io import BytesIO, StringIO from mock import Mock import signedjson.key from canonicaljson import encode_canonical_json from nacl.signing import SigningKey from signedjson.sign import sign_json from twisted.web.resource import NoResource from synapse.crypto.keyring import PerspectivesKeyFetcher from synapse.http.site import SynapseRequest from synapse.rest.key.v2 import KeyApiV2Resource from synapse.storage.keys import FetchKeyResult from synapse.util.httpresourcetree import create_resource_tree from synapse.util.stringutils import random_string from tests import unittest from tests.server import FakeChannel from tests.utils import .default_config class CLASS_0(unittest.HomeserverTestCase): def FUNC_0(self, VAR_0, VAR_1): self.http_client = Mock() return self.setup_test_homeserver(http_client=self.http_client) def FUNC_1(self): return create_resource_tree( {"/_matrix/key/v2": KeyApiV2Resource(self.hs)}, root_resource=NoResource() ) def FUNC_2( self, VAR_2: str, VAR_3: SigningKey ) -> None: async def FUNC_10(VAR_6, VAR_7, VAR_8=False, **VAR_9): self.assertTrue(VAR_8) self.assertEqual(VAR_6, VAR_2) VAR_4 = "%s:%s" % (VAR_3.alg, VAR_3.version) self.assertEqual( VAR_7, "/_matrix/key/v2/server/%s" % (urllib.parse.quote(VAR_4),) ) VAR_26 = { "server_name": VAR_2, "old_verify_keys": {}, "valid_until_ts": 200 * 1000, "verify_keys": { VAR_4: { "key": signedjson.key.encode_verify_key_base64( VAR_3.verify_key ) } }, } sign_json(VAR_26, VAR_2, VAR_3) return VAR_26 self.http_client.get_json.side_effect = FUNC_10 class CLASS_1(CLASS_0): def FUNC_3(self, VAR_2: str, VAR_4: str) -> dict: VAR_10 = FakeChannel(self.site, self.reactor) VAR_11 = SynapseRequest(VAR_10) VAR_11.content = BytesIO(b"") VAR_11.requestReceived( b"GET", b"/_matrix/key/v2/query/%s/%s" % (VAR_2.encode("utf-8"), VAR_4.encode("utf-8")), b"1.1", ) VAR_10.await_result() self.assertEqual(VAR_10.code, 200) VAR_12 = VAR_10.json_body return VAR_12 def FUNC_4(self): VAR_13 = "remote.server" VAR_14 = signedjson.key.generate_signing_key("ver1") self.expect_outgoing_key_request(VAR_13, VAR_14) VAR_12 = self.make_notary_request(VAR_13, "ed25519:ver1") VAR_15 = VAR_12["server_keys"] self.assertEqual(len(VAR_15), 1) self.assertIn("ed25519:ver1", VAR_15[0]["verify_keys"]) self.assertEqual(len(VAR_15[0]["verify_keys"]), 1) self.assertIn(VAR_13, VAR_15[0]["signatures"]) self.assertIn(self.hs.hostname, VAR_15[0]["signatures"]) def FUNC_5(self): VAR_14 = signedjson.key.generate_signing_key("ver1") self.expect_outgoing_key_request(self.hs.hostname, VAR_14) VAR_12 = self.make_notary_request(self.hs.hostname, "ed25519:ver1") VAR_15 = VAR_12["server_keys"] self.assertEqual(len(VAR_15), 1) VAR_16 = VAR_15[0]["signatures"] self.assertEqual(len(VAR_16), 1) self.assertIn(self.hs.hostname, VAR_16) VAR_17 = VAR_16[self.hs.hostname] self.assertEqual(len(VAR_17), 2) self.assertIn("ed25519:ver1", VAR_15[0]["verify_keys"]) class CLASS_2(CLASS_0): def FUNC_6(self): VAR_18 = super().default_config() self.hs_signing_key = signedjson.key.generate_signing_key("kssk") VAR_19 = StringIO() signedjson.key.write_signing_keys(VAR_19, [self.hs_signing_key]) VAR_18["signing_key"] = VAR_19.getvalue() return VAR_18 def FUNC_7(self, VAR_0, VAR_1, VAR_5): self.http_client2 = Mock() VAR_18 = FUNC_6(name="keyclient") VAR_18["trusted_key_servers"] = [ { "server_name": self.hs.hostname, "verify_keys": { "ed25519:%s" % ( self.hs_signing_key.version, ): signedjson.key.encode_verify_key_base64( self.hs_signing_key.verify_key ) }, } ] self.hs2 = self.setup_test_homeserver( http_client=self.http_client2, VAR_18=config ) async def FUNC_11(VAR_6, VAR_7, VAR_20): self.assertEqual(VAR_6, self.hs.hostname) self.assertEqual( VAR_7, "/_matrix/key/v2/query", ) VAR_10 = FakeChannel(self.site, self.reactor) VAR_11 = SynapseRequest(VAR_10) VAR_11.content = BytesIO(encode_canonical_json(VAR_20)) VAR_11.requestReceived( b"POST", VAR_7.encode("utf-8"), b"1.1", ) VAR_10.await_result() self.assertEqual(VAR_10.code, 200) VAR_12 = VAR_10.json_body return VAR_12 self.http_client2.post_json.side_effect = FUNC_11 def FUNC_4(self): VAR_14 = signedjson.key.generate_signing_key("abc") self.expect_outgoing_key_request("targetserver", VAR_14) VAR_21 = "ed25519:%s" % (VAR_14.version,) VAR_22 = PerspectivesKeyFetcher(self.hs2) VAR_23 = VAR_22.get_keys({"targetserver": {VAR_21: 1000}}) VAR_24 = self.get_success(VAR_23) self.assertIn("targetserver", VAR_24) VAR_25 = VAR_24["targetserver"][VAR_21] assert isinstance(VAR_25, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(VAR_25.verify_key), signedjson.key.encode_verify_key_base64(VAR_14.verify_key), ) def FUNC_8(self): VAR_14 = signedjson.key.generate_signing_key(random_string(5)) self.expect_outgoing_key_request(self.hs.hostname, VAR_14) VAR_21 = "ed25519:%s" % (VAR_14.version,) VAR_22 = PerspectivesKeyFetcher(self.hs2) VAR_23 = VAR_22.get_keys({self.hs.hostname: {VAR_21: 1000}}) VAR_24 = self.get_success(VAR_23) self.assertIn(self.hs.hostname, VAR_24) VAR_25 = VAR_24[self.hs.hostname][VAR_21] assert isinstance(VAR_25, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(VAR_25.verify_key), signedjson.key.encode_verify_key_base64(VAR_14.verify_key), ) def FUNC_9(self): self.expect_outgoing_key_request(self.hs.hostname, self.hs_signing_key) VAR_21 = "ed25519:%s" % (self.hs_signing_key.version,) VAR_22 = PerspectivesKeyFetcher(self.hs2) VAR_23 = VAR_22.get_keys({self.hs.hostname: {VAR_21: 1000}}) VAR_24 = self.get_success(VAR_23) self.assertIn(self.hs.hostname, VAR_24) VAR_25 = VAR_24[self.hs.hostname][VAR_21] assert isinstance(VAR_25, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(VAR_25.verify_key), signedjson.key.encode_verify_key_base64(self.hs_signing_key.verify_key), )
import urllib.parse from io import BytesIO, StringIO from mock import Mock import signedjson.key from canonicaljson import encode_canonical_json from nacl.signing import SigningKey from signedjson.sign import sign_json from twisted.web.resource import NoResource from synapse.crypto.keyring import PerspectivesKeyFetcher from synapse.http.site import SynapseRequest from synapse.rest.key.v2 import KeyApiV2Resource from synapse.storage.keys import FetchKeyResult from synapse.util.httpresourcetree import create_resource_tree from synapse.util.stringutils import random_string from tests import unittest from tests.server import FakeChannel from tests.utils import .default_config class CLASS_0(unittest.HomeserverTestCase): def FUNC_0(self, VAR_0, VAR_1): self.http_client = Mock() return self.setup_test_homeserver(federation_http_client=self.http_client) def FUNC_1(self): return create_resource_tree( {"/_matrix/key/v2": KeyApiV2Resource(self.hs)}, root_resource=NoResource() ) def FUNC_2( self, VAR_2: str, VAR_3: SigningKey ) -> None: async def FUNC_10(VAR_6, VAR_7, VAR_8=False, **VAR_9): self.assertTrue(VAR_8) self.assertEqual(VAR_6, VAR_2) VAR_4 = "%s:%s" % (VAR_3.alg, VAR_3.version) self.assertEqual( VAR_7, "/_matrix/key/v2/server/%s" % (urllib.parse.quote(VAR_4),) ) VAR_26 = { "server_name": VAR_2, "old_verify_keys": {}, "valid_until_ts": 200 * 1000, "verify_keys": { VAR_4: { "key": signedjson.key.encode_verify_key_base64( VAR_3.verify_key ) } }, } sign_json(VAR_26, VAR_2, VAR_3) return VAR_26 self.http_client.get_json.side_effect = FUNC_10 class CLASS_1(CLASS_0): def FUNC_3(self, VAR_2: str, VAR_4: str) -> dict: VAR_10 = FakeChannel(self.site, self.reactor) VAR_11 = SynapseRequest(VAR_10) VAR_11.content = BytesIO(b"") VAR_11.requestReceived( b"GET", b"/_matrix/key/v2/query/%s/%s" % (VAR_2.encode("utf-8"), VAR_4.encode("utf-8")), b"1.1", ) VAR_10.await_result() self.assertEqual(VAR_10.code, 200) VAR_12 = VAR_10.json_body return VAR_12 def FUNC_4(self): VAR_13 = "remote.server" VAR_14 = signedjson.key.generate_signing_key("ver1") self.expect_outgoing_key_request(VAR_13, VAR_14) VAR_12 = self.make_notary_request(VAR_13, "ed25519:ver1") VAR_15 = VAR_12["server_keys"] self.assertEqual(len(VAR_15), 1) self.assertIn("ed25519:ver1", VAR_15[0]["verify_keys"]) self.assertEqual(len(VAR_15[0]["verify_keys"]), 1) self.assertIn(VAR_13, VAR_15[0]["signatures"]) self.assertIn(self.hs.hostname, VAR_15[0]["signatures"]) def FUNC_5(self): VAR_14 = signedjson.key.generate_signing_key("ver1") self.expect_outgoing_key_request(self.hs.hostname, VAR_14) VAR_12 = self.make_notary_request(self.hs.hostname, "ed25519:ver1") VAR_15 = VAR_12["server_keys"] self.assertEqual(len(VAR_15), 1) VAR_16 = VAR_15[0]["signatures"] self.assertEqual(len(VAR_16), 1) self.assertIn(self.hs.hostname, VAR_16) VAR_17 = VAR_16[self.hs.hostname] self.assertEqual(len(VAR_17), 2) self.assertIn("ed25519:ver1", VAR_15[0]["verify_keys"]) class CLASS_2(CLASS_0): def FUNC_6(self): VAR_18 = super().default_config() self.hs_signing_key = signedjson.key.generate_signing_key("kssk") VAR_19 = StringIO() signedjson.key.write_signing_keys(VAR_19, [self.hs_signing_key]) VAR_18["signing_key"] = VAR_19.getvalue() return VAR_18 def FUNC_7(self, VAR_0, VAR_1, VAR_5): self.http_client2 = Mock() VAR_18 = FUNC_6(name="keyclient") VAR_18["trusted_key_servers"] = [ { "server_name": self.hs.hostname, "verify_keys": { "ed25519:%s" % ( self.hs_signing_key.version, ): signedjson.key.encode_verify_key_base64( self.hs_signing_key.verify_key ) }, } ] self.hs2 = self.setup_test_homeserver( federation_http_client=self.http_client2, VAR_18=config ) async def FUNC_11(VAR_6, VAR_7, VAR_20): self.assertEqual(VAR_6, self.hs.hostname) self.assertEqual( VAR_7, "/_matrix/key/v2/query", ) VAR_10 = FakeChannel(self.site, self.reactor) VAR_11 = SynapseRequest(VAR_10) VAR_11.content = BytesIO(encode_canonical_json(VAR_20)) VAR_11.requestReceived( b"POST", VAR_7.encode("utf-8"), b"1.1", ) VAR_10.await_result() self.assertEqual(VAR_10.code, 200) VAR_12 = VAR_10.json_body return VAR_12 self.http_client2.post_json.side_effect = FUNC_11 def FUNC_4(self): VAR_14 = signedjson.key.generate_signing_key("abc") self.expect_outgoing_key_request("targetserver", VAR_14) VAR_21 = "ed25519:%s" % (VAR_14.version,) VAR_22 = PerspectivesKeyFetcher(self.hs2) VAR_23 = VAR_22.get_keys({"targetserver": {VAR_21: 1000}}) VAR_24 = self.get_success(VAR_23) self.assertIn("targetserver", VAR_24) VAR_25 = VAR_24["targetserver"][VAR_21] assert isinstance(VAR_25, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(VAR_25.verify_key), signedjson.key.encode_verify_key_base64(VAR_14.verify_key), ) def FUNC_8(self): VAR_14 = signedjson.key.generate_signing_key(random_string(5)) self.expect_outgoing_key_request(self.hs.hostname, VAR_14) VAR_21 = "ed25519:%s" % (VAR_14.version,) VAR_22 = PerspectivesKeyFetcher(self.hs2) VAR_23 = VAR_22.get_keys({self.hs.hostname: {VAR_21: 1000}}) VAR_24 = self.get_success(VAR_23) self.assertIn(self.hs.hostname, VAR_24) VAR_25 = VAR_24[self.hs.hostname][VAR_21] assert isinstance(VAR_25, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(VAR_25.verify_key), signedjson.key.encode_verify_key_base64(VAR_14.verify_key), ) def FUNC_9(self): self.expect_outgoing_key_request(self.hs.hostname, self.hs_signing_key) VAR_21 = "ed25519:%s" % (self.hs_signing_key.version,) VAR_22 = PerspectivesKeyFetcher(self.hs2) VAR_23 = VAR_22.get_keys({self.hs.hostname: {VAR_21: 1000}}) VAR_24 = self.get_success(VAR_23) self.assertIn(self.hs.hostname, VAR_24) VAR_25 = VAR_24[self.hs.hostname][VAR_21] assert isinstance(VAR_25, FetchKeyResult) self.assertEqual( signedjson.key.encode_verify_key_base64(VAR_25.verify_key), signedjson.key.encode_verify_key_base64(self.hs_signing_key.verify_key), )
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 19, 24, 26, 33, 37, 38, 43, 48, 55, 63, 78, 80, 81, 85, 101, 107, 111, 114, 115, 118, 123, 127, 128, 134, 135, 137, 138, 141, 145, 148, 149, 154, 156, 158, 177, 178, 179, 185, 189, 197, 199, 202, 204, 205, 208, 219, 222, 223, 224, 226, 227, 230, 241, 244, 247, 258, 140, 141, 142, 143, 144, 52, 53, 54, 84, 85, 86, 87, 103, 120, 201, 221, 243 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 19, 24, 26, 33, 37, 38, 43, 48, 55, 63, 78, 80, 81, 85, 101, 107, 111, 114, 115, 118, 123, 127, 128, 134, 135, 137, 138, 141, 145, 148, 149, 154, 156, 158, 177, 178, 179, 185, 189, 197, 199, 202, 204, 205, 208, 219, 222, 223, 224, 226, 227, 230, 241, 244, 247, 258, 140, 141, 142, 143, 144, 52, 53, 54, 84, 85, 86, 87, 103, 120, 201, 221, 243 ]
4CWE-601
import io import os import re from setuptools import find_packages, setup with io.open("flask_appbuilder/__init__.py", "rt", encoding="utf8") as f: version = re.search(r"__version__ = \"(.*?)\"", f.read()).group(1) def fpath(name): return os.path.join(os.path.dirname(__file__), name) def read(fname): return open(fpath(fname)).read() def desc(): return read("README.rst") setup( name="Flask-AppBuilder", version=version, url="https://github.com/dpgaspar/flask-appbuilder/", license="BSD", author="Daniel Vaz Gaspar", author_email="danielvazgaspar@gmail.com", description=( "Simple and rapid application development framework, built on top of Flask." " includes detailed security, auto CRUD generation for your models," " google charts and much more." ), long_description=desc(), long_description_content_type="text/x-rst", packages=find_packages(), package_data={"": ["LICENSE"]}, entry_points={ "flask.commands": ["fab=flask_appbuilder.cli:fab"], "console_scripts": ["fabmanager = flask_appbuilder.console:cli"], }, include_package_data=True, zip_safe=False, platforms="any", install_requires=[ "apispec[yaml]>=3.3, <4", "colorama>=0.3.9, <1", "click>=6.7, <9", "email_validator>=1.0.5, <2", "Flask>=0.12, <2", "Flask-Babel>=1, <2", "Flask-Login>=0.3, <0.5", "Flask-OpenID>=1.2.5, <2", # SQLAlchemy 1.4.0 breaks flask-sqlalchemy and sqlalchemy-utils "SQLAlchemy<1.4.0", "Flask-SQLAlchemy>=2.4, <3", "Flask-WTF>=0.14.2, <0.15.0", "Flask-JWT-Extended>=3.18, <4", "jsonschema>=3.0.1, <4", "marshmallow>=3, <4", "marshmallow-enum>=1.5.1, <2", "marshmallow-sqlalchemy>=0.22.0, <0.24.0", "python-dateutil>=2.3, <3", "prison>=0.1.3, <1.0.0", "PyJWT>=1.7.1, <2.0.0", "sqlalchemy-utils>=0.32.21, <1", ], extras_require={"jmespath": ["jmespath>=0.9.5"]}, tests_require=["nose>=1.0", "mockldap>=0.3.0"], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Software Development :: Libraries :: Python Modules", ], python_requires="~=3.6", test_suite="nose.collector", )
import io import os import re from setuptools import find_packages, setup with io.open("flask_appbuilder/__init__.py", "rt", encoding="utf8") as f: version = re.search(r"__version__ = \"(.*?)\"", f.read()).group(1) def fpath(name): return os.path.join(os.path.dirname(__file__), name) def read(fname): return open(fpath(fname)).read() def desc(): return read("README.rst") setup( name="Flask-AppBuilder", version=version, url="https://github.com/dpgaspar/flask-appbuilder/", license="BSD", author="Daniel Vaz Gaspar", author_email="danielvazgaspar@gmail.com", description=( "Simple and rapid application development framework, built on top of Flask." " includes detailed security, auto CRUD generation for your models," " google charts and much more." ), long_description=desc(), long_description_content_type="text/x-rst", packages=find_packages(), package_data={"": ["LICENSE"]}, entry_points={ "flask.commands": ["fab=flask_appbuilder.cli:fab"], "console_scripts": ["fabmanager = flask_appbuilder.console:cli"], }, include_package_data=True, zip_safe=False, platforms="any", install_requires=[ "apispec[yaml]>=3.3, <4", "colorama>=0.3.9, <1", "click>=6.7, <9", "email_validator>=1.0.5, <2", "Flask>=0.12, <2", "Flask-Babel>=1, <2", "Flask-Login>=0.3, <0.5", "Flask-OpenID>=1.2.5, <2", # SQLAlchemy 1.4.0 breaks flask-sqlalchemy and sqlalchemy-utils "SQLAlchemy<1.4.0", "Flask-SQLAlchemy>=2.4, <3", "Flask-WTF>=0.14.2, <0.15.0", "Flask-JWT-Extended>=3.18, <4", "jsonschema>=3.0.1, <4", "marshmallow>=3, <4", "marshmallow-enum>=1.5.1, <2", "marshmallow-sqlalchemy>=0.22.0, <0.24.0", "python-dateutil>=2.3, <3", "prison>=0.1.3, <1.0.0", "PyJWT>=1.7.1, <2.0.0", "sqlalchemy-utils>=0.32.21, <1", ], extras_require={ "jmespath": ["jmespath>=0.9.5"], "oauth": ["Authlib>=0.14, <1.0.0"], }, tests_require=["nose>=1.0", "mockldap>=0.3.0"], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Software Development :: Libraries :: Python Modules", ], python_requires="~=3.6", test_suite="nose.collector", )
open_redirect
{ "code": [ " extras_require={\"jmespath\": [\"jmespath>=0.9.5\"]}," ], "line_no": [ 70 ] }
{ "code": [ " extras_require={", " \"jmespath\": [\"jmespath>=0.9.5\"],", " \"oauth\": [\"Authlib>=0.14, <1.0.0\"],", " }," ], "line_no": [ 70, 71, 72, 73 ] }
import io import os import re from setuptools import find_packages, setup with io.open("flask_appbuilder/__init__.py", "rt", encoding="utf8") as f: VAR_2 = re.search(r"__version__ = \"(.*?)\"", f.read()).group(1) def FUNC_0(VAR_0): return os.path.join(os.path.dirname(__file__), VAR_0) def FUNC_1(VAR_1): return open(FUNC_0(VAR_1)).read() def FUNC_2(): return FUNC_1("README.rst") setup( VAR_0="Flask-AppBuilder", VAR_2=version, url="https://github.com/dpgaspar/flask-appbuilder/", license="BSD", author="Daniel Vaz Gaspar", author_email="danielvazgaspar@gmail.com", description=( "Simple and rapid application development framework, built on top of Flask." " includes detailed security, auto CRUD generation for your models," " google charts and much more." ), long_description=FUNC_2(), long_description_content_type="text/x-rst", packages=find_packages(), package_data={"": ["LICENSE"]}, entry_points={ "flask.commands": ["fab=flask_appbuilder.cli:fab"], "console_scripts": ["fabmanager = flask_appbuilder.console:cli"], }, include_package_data=True, zip_safe=False, platforms="any", install_requires=[ "apispec[yaml]>=3.3, <4", "colorama>=0.3.9, <1", "click>=6.7, <9", "email_validator>=1.0.5, <2", "Flask>=0.12, <2", "Flask-Babel>=1, <2", "Flask-Login>=0.3, <0.5", "Flask-OpenID>=1.2.5, <2", "SQLAlchemy<1.4.0", "Flask-SQLAlchemy>=2.4, <3", "Flask-WTF>=0.14.2, <0.15.0", "Flask-JWT-Extended>=3.18, <4", "jsonschema>=3.0.1, <4", "marshmallow>=3, <4", "marshmallow-enum>=1.5.1, <2", "marshmallow-sqlalchemy>=0.22.0, <0.24.0", "python-dateutil>=2.3, <3", "prison>=0.1.3, <1.0.0", "PyJWT>=1.7.1, <2.0.0", "sqlalchemy-utils>=0.32.21, <1", ], extras_require={"jmespath": ["jmespath>=0.9.5"]}, tests_require=["nose>=1.0", "mockldap>=0.3.0"], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Software Development :: Libraries :: Python Modules", ], python_requires="~=3.6", test_suite="nose.collector", )
import io import os import re from setuptools import find_packages, setup with io.open("flask_appbuilder/__init__.py", "rt", encoding="utf8") as f: VAR_2 = re.search(r"__version__ = \"(.*?)\"", f.read()).group(1) def FUNC_0(VAR_0): return os.path.join(os.path.dirname(__file__), VAR_0) def FUNC_1(VAR_1): return open(FUNC_0(VAR_1)).read() def FUNC_2(): return FUNC_1("README.rst") setup( VAR_0="Flask-AppBuilder", VAR_2=version, url="https://github.com/dpgaspar/flask-appbuilder/", license="BSD", author="Daniel Vaz Gaspar", author_email="danielvazgaspar@gmail.com", description=( "Simple and rapid application development framework, built on top of Flask." " includes detailed security, auto CRUD generation for your models," " google charts and much more." ), long_description=FUNC_2(), long_description_content_type="text/x-rst", packages=find_packages(), package_data={"": ["LICENSE"]}, entry_points={ "flask.commands": ["fab=flask_appbuilder.cli:fab"], "console_scripts": ["fabmanager = flask_appbuilder.console:cli"], }, include_package_data=True, zip_safe=False, platforms="any", install_requires=[ "apispec[yaml]>=3.3, <4", "colorama>=0.3.9, <1", "click>=6.7, <9", "email_validator>=1.0.5, <2", "Flask>=0.12, <2", "Flask-Babel>=1, <2", "Flask-Login>=0.3, <0.5", "Flask-OpenID>=1.2.5, <2", "SQLAlchemy<1.4.0", "Flask-SQLAlchemy>=2.4, <3", "Flask-WTF>=0.14.2, <0.15.0", "Flask-JWT-Extended>=3.18, <4", "jsonschema>=3.0.1, <4", "marshmallow>=3, <4", "marshmallow-enum>=1.5.1, <2", "marshmallow-sqlalchemy>=0.22.0, <0.24.0", "python-dateutil>=2.3, <3", "prison>=0.1.3, <1.0.0", "PyJWT>=1.7.1, <2.0.0", "sqlalchemy-utils>=0.32.21, <1", ], extras_require={ "jmespath": ["jmespath>=0.9.5"], "oauth": ["Authlib>=0.14, <1.0.0"], }, tests_require=["nose>=1.0", "mockldap>=0.3.0"], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Software Development :: Libraries :: Python Modules", ], python_requires="~=3.6", test_suite="nose.collector", )
[ 4, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 56, 86 ]
[ 4, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 56, 89 ]
5CWE-94
# -*- coding: utf-8 -*- """ eve.io.mongo.parser ~~~~~~~~~~~~~~~~~~~ This module implements a Python-to-Mongo syntax parser. Allows the MongoDB data-layer to seamlessly respond to a Python-like query. :copyright: (c) 2017 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ import ast import sys from datetime import datetime # noqa from bson import ObjectId # noqa def parse(expression): """ Given a python-like conditional statement, returns the equivalent mongo-like query expression. Conditional and boolean operators (==, <=, >=, !=, >, <) along with a couple function calls (ObjectId(), datetime()) are supported. """ v = MongoVisitor() try: v.visit(ast.parse(expression)) except SyntaxError as e: e = ParseError(e) e.__traceback__ = sys.exc_info()[2] raise e return v.mongo_query class ParseError(ValueError): pass class MongoVisitor(ast.NodeVisitor): """ Implements the python-to-mongo parser. Only Python conditional statements are supported, however nested, combined with most common compare and boolean operators (And and Or). Supported compare operators: ==, >, <, !=, >=, <= Supported boolean operators: And, Or """ op_mapper = { ast.Eq: '', ast.Gt: '$gt', ast.GtE: '$gte', ast.Lt: '$lt', ast.LtE: '$lte', ast.NotEq: '$ne', ast.Or: '$or', ast.And: '$and' } def visit_Module(self, node): """ Module handler, our entry point. """ self.mongo_query = {} self.ops = [] self.current_value = None # perform the magic. self.generic_visit(node) # if we didn't obtain a query, it is likely that an unsupported # python expression has been passed. if self.mongo_query == {}: raise ParseError("Only conditional statements with boolean " "(and, or) and comparison operators are " "supported.") def visit_Expr(self, node): """ Make sure that we are parsing compare or boolean operators """ if not (isinstance(node.value, ast.Compare) or isinstance(node.value, ast.BoolOp)): raise ParseError("Will only parse conditional statements") self.generic_visit(node) def visit_Compare(self, node): """ Compare operator handler. """ self.visit(node.left) left = self.current_value operator = self.op_mapper[node.ops[0].__class__] if node.ops else None if node.comparators: comparator = node.comparators[0] self.visit(comparator) if operator != '': value = {operator: self.current_value} else: value = self.current_value if self.ops: self.ops[-1].append({left: value}) else: self.mongo_query[left] = value def visit_BoolOp(self, node): """ Boolean operator handler. """ op = self.op_mapper[node.op.__class__] self.ops.append([]) for value in node.values: self.visit(value) c = self.ops.pop() if self.ops: self.ops[-1].append({op: c}) else: self.mongo_query[op] = c def visit_Call(self, node): """ A couple function calls are supported: bson's ObjectId() and datetime(). """ if isinstance(node.func, ast.Name): expr = None if node.func.id == 'ObjectId': expr = "('" + node.args[0].s + "')" elif node.func.id == 'datetime': values = [] for arg in node.args: values.append(str(arg.n)) expr = "(" + ", ".join(values) + ")" if expr: self.current_value = eval(node.func.id + expr) def visit_Attribute(self, node): """ Attribute handler ('Contact.Id'). """ self.visit(node.value) self.current_value += "." + node.attr def visit_Name(self, node): """ Names handler. """ self.current_value = node.id def visit_Num(self, node): """ Numbers handler. """ self.current_value = node.n def visit_Str(self, node): """ Strings handler. """ self.current_value = node.s
# -*- coding: utf-8 -*- """ eve.io.mongo.parser ~~~~~~~~~~~~~~~~~~~ This module implements a Python-to-Mongo syntax parser. Allows the MongoDB data-layer to seamlessly respond to a Python-like query. :copyright: (c) 2017 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ import ast import sys from datetime import datetime # noqa from bson import ObjectId # noqa def parse(expression): """ Given a python-like conditional statement, returns the equivalent mongo-like query expression. Conditional and boolean operators (==, <=, >=, !=, >, <) along with a couple function calls (ObjectId(), datetime()) are supported. """ v = MongoVisitor() try: v.visit(ast.parse(expression)) except SyntaxError as e: e = ParseError(e) e.__traceback__ = sys.exc_info()[2] raise e return v.mongo_query class ParseError(ValueError): pass class MongoVisitor(ast.NodeVisitor): """ Implements the python-to-mongo parser. Only Python conditional statements are supported, however nested, combined with most common compare and boolean operators (And and Or). Supported compare operators: ==, >, <, !=, >=, <= Supported boolean operators: And, Or """ op_mapper = { ast.Eq: '', ast.Gt: '$gt', ast.GtE: '$gte', ast.Lt: '$lt', ast.LtE: '$lte', ast.NotEq: '$ne', ast.Or: '$or', ast.And: '$and' } def visit_Module(self, node): """ Module handler, our entry point. """ self.mongo_query = {} self.ops = [] self.current_value = None # perform the magic. self.generic_visit(node) # if we didn't obtain a query, it is likely that an unsupported # python expression has been passed. if self.mongo_query == {}: raise ParseError("Only conditional statements with boolean " "(and, or) and comparison operators are " "supported.") def visit_Expr(self, node): """ Make sure that we are parsing compare or boolean operators """ if not (isinstance(node.value, ast.Compare) or isinstance(node.value, ast.BoolOp)): raise ParseError("Will only parse conditional statements") self.generic_visit(node) def visit_Compare(self, node): """ Compare operator handler. """ self.visit(node.left) left = self.current_value operator = self.op_mapper[node.ops[0].__class__] if node.ops else None if node.comparators: comparator = node.comparators[0] self.visit(comparator) if operator != '': value = {operator: self.current_value} else: value = self.current_value if self.ops: self.ops[-1].append({left: value}) else: self.mongo_query[left] = value def visit_BoolOp(self, node): """ Boolean operator handler. """ op = self.op_mapper[node.op.__class__] self.ops.append([]) for value in node.values: self.visit(value) c = self.ops.pop() if self.ops: self.ops[-1].append({op: c}) else: self.mongo_query[op] = c def visit_Call(self, node): """ A couple function calls are supported: bson's ObjectId() and datetime(). """ if isinstance(node.func, ast.Name): if node.func.id == 'ObjectId': try: self.current_value = ObjectId(node.args[0].s) except: pass elif node.func.id == 'datetime': values = [] for arg in node.args: values.append(arg.n) try: self.current_value = datetime(*values) except: pass def visit_Attribute(self, node): """ Attribute handler ('Contact.Id'). """ self.visit(node.value) self.current_value += "." + node.attr def visit_Name(self, node): """ Names handler. """ self.current_value = node.id def visit_Num(self, node): """ Numbers handler. """ self.current_value = node.n def visit_Str(self, node): """ Strings handler. """ self.current_value = node.s
remote_code_execution
{ "code": [ " expr = None", " expr = \"('\" + node.args[0].s + \"')\"", " values.append(str(arg.n))", " expr = \"(\" + \", \".join(values) + \")\"", " if expr:", " self.current_value = eval(node.func.id + expr)" ], "line_no": [ 125, 127, 131, 132, 133, 134 ] }
{ "code": [ " try:", " self.current_value = ObjectId(node.args[0].s)", " except:", " pass", " values.append(arg.n)", " try:", " except:" ], "line_no": [ 126, 127, 128, 129, 133, 134, 136 ] }
import ast import sys from datetime import datetime # noqa from bson import ObjectId # noqa def FUNC_0(VAR_0): VAR_1 = CLASS_1() try: VAR_1.visit(ast.parse(VAR_0)) except SyntaxError as VAR_8: e = CLASS_0(VAR_8) e.__traceback__ = sys.exc_info()[2] raise VAR_8 return VAR_1.mongo_query class CLASS_0(ValueError): pass class CLASS_1(ast.NodeVisitor): VAR_2 = { ast.Eq: '', ast.Gt: '$gt', ast.GtE: '$gte', ast.Lt: '$lt', ast.LtE: '$lte', ast.NotEq: '$ne', ast.Or: '$or', ast.And: '$and' } def FUNC_1(self, VAR_3): self.mongo_query = {} self.ops = [] self.current_value = None self.generic_visit(VAR_3) if self.mongo_query == {}: raise CLASS_0("Only conditional statements with boolean " "(and, or) and comparison operators are " "supported.") def FUNC_2(self, VAR_3): if not (isinstance(VAR_3.value, ast.Compare) or isinstance(VAR_3.value, ast.BoolOp)): raise CLASS_0("Will only FUNC_0 conditional statements") self.generic_visit(VAR_3) def FUNC_3(self, VAR_3): self.visit(VAR_3.left) VAR_4 = self.current_value VAR_5 = self.op_mapper[VAR_3.ops[0].__class__] if VAR_3.ops else None if VAR_3.comparators: VAR_9 = VAR_3.comparators[0] self.visit(VAR_9) if VAR_5 != '': VAR_10 = {VAR_5: self.current_value} else: VAR_10 = self.current_value if self.ops: self.ops[-1].append({VAR_4: VAR_10}) else: self.mongo_query[VAR_4] = VAR_10 def FUNC_4(self, VAR_3): VAR_6 = self.op_mapper[VAR_3.op.__class__] self.ops.append([]) for VAR_10 in VAR_3.values: self.visit(VAR_10) VAR_7 = self.ops.pop() if self.ops: self.ops[-1].append({VAR_6: VAR_7}) else: self.mongo_query[VAR_6] = VAR_7 def FUNC_5(self, VAR_3): if isinstance(VAR_3.func, ast.Name): VAR_11 = None if VAR_3.func.id == 'ObjectId': VAR_11 = "('" + VAR_3.args[0].s + "')" elif VAR_3.func.id == 'datetime': VAR_12 = [] for arg in VAR_3.args: VAR_12.append(str(arg.n)) VAR_11 = "(" + ", ".join(VAR_12) + ")" if VAR_11: self.current_value = eval(VAR_3.func.id + VAR_11) def FUNC_6(self, VAR_3): self.visit(VAR_3.value) self.current_value += "." + VAR_3.attr def FUNC_7(self, VAR_3): self.current_value = VAR_3.id def FUNC_8(self, VAR_3): self.current_value = VAR_3.n def FUNC_9(self, VAR_3): self.current_value = VAR_3.s
import ast import sys from datetime import datetime # noqa from bson import ObjectId # noqa def FUNC_0(VAR_0): VAR_1 = CLASS_1() try: VAR_1.visit(ast.parse(VAR_0)) except SyntaxError as VAR_8: e = CLASS_0(VAR_8) e.__traceback__ = sys.exc_info()[2] raise VAR_8 return VAR_1.mongo_query class CLASS_0(ValueError): pass class CLASS_1(ast.NodeVisitor): VAR_2 = { ast.Eq: '', ast.Gt: '$gt', ast.GtE: '$gte', ast.Lt: '$lt', ast.LtE: '$lte', ast.NotEq: '$ne', ast.Or: '$or', ast.And: '$and' } def FUNC_1(self, VAR_3): self.mongo_query = {} self.ops = [] self.current_value = None self.generic_visit(VAR_3) if self.mongo_query == {}: raise CLASS_0("Only conditional statements with boolean " "(and, or) and comparison operators are " "supported.") def FUNC_2(self, VAR_3): if not (isinstance(VAR_3.value, ast.Compare) or isinstance(VAR_3.value, ast.BoolOp)): raise CLASS_0("Will only FUNC_0 conditional statements") self.generic_visit(VAR_3) def FUNC_3(self, VAR_3): self.visit(VAR_3.left) VAR_4 = self.current_value VAR_5 = self.op_mapper[VAR_3.ops[0].__class__] if VAR_3.ops else None if VAR_3.comparators: VAR_9 = VAR_3.comparators[0] self.visit(VAR_9) if VAR_5 != '': VAR_10 = {VAR_5: self.current_value} else: VAR_10 = self.current_value if self.ops: self.ops[-1].append({VAR_4: VAR_10}) else: self.mongo_query[VAR_4] = VAR_10 def FUNC_4(self, VAR_3): VAR_6 = self.op_mapper[VAR_3.op.__class__] self.ops.append([]) for VAR_10 in VAR_3.values: self.visit(VAR_10) VAR_7 = self.ops.pop() if self.ops: self.ops[-1].append({VAR_6: VAR_7}) else: self.mongo_query[VAR_6] = VAR_7 def FUNC_5(self, VAR_3): if isinstance(VAR_3.func, ast.Name): if VAR_3.func.id == 'ObjectId': try: self.current_value = ObjectId(VAR_3.args[0].s) except: pass elif VAR_3.func.id == 'datetime': VAR_11 = [] for arg in VAR_3.args: VAR_11.append(arg.n) try: self.current_value = datetime(*VAR_11) except: pass def FUNC_6(self, VAR_3): self.visit(VAR_3.value) self.current_value += "." + VAR_3.attr def FUNC_7(self, VAR_3): self.current_value = VAR_3.id def FUNC_8(self, VAR_3): self.current_value = VAR_3.n def FUNC_9(self, VAR_3): self.current_value = VAR_3.s
[ 1, 2, 6, 9, 13, 18, 19, 34, 35, 38, 39, 44, 58, 65, 66, 68, 69, 70, 75, 83, 89, 91, 95, 100, 105, 113, 119, 135, 141, 146, 151, 156, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 21, 22, 23, 24, 25, 41, 42, 43, 44, 45, 46, 47, 60, 61, 77, 78, 85, 86, 107, 108, 121, 122, 123, 137, 138, 143, 144, 148, 149, 153, 154 ]
[ 1, 2, 6, 9, 13, 18, 19, 34, 35, 38, 39, 44, 58, 65, 66, 68, 69, 70, 75, 83, 89, 91, 95, 100, 105, 113, 119, 138, 144, 149, 154, 159, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 21, 22, 23, 24, 25, 41, 42, 43, 44, 45, 46, 47, 60, 61, 77, 78, 85, 86, 107, 108, 121, 122, 123, 140, 141, 146, 147, 151, 152, 156, 157 ]
4CWE-601
# -*- coding: utf-8 -*- import json from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from django.http import Http404, HttpResponse from django.contrib import messages from django.utils.html import escape from django.urls import reverse from djconfig import config from infinite_scroll_pagination.serializers import to_page_key from spirit.core.conf import settings from spirit.core import utils from spirit.core.utils.paginator import yt_paginate from spirit.core.utils.paginator.infinite_paginator import paginate from spirit.core.utils.views import is_ajax from spirit.topic.models import Topic from .models import TopicNotification from .forms import NotificationForm, NotificationCreationForm @require_POST @login_required def create(request, topic_id): topic = get_object_or_404( Topic.objects.for_access(request.user), pk=topic_id) form = NotificationCreationForm( user=request.user, topic=topic, data=request.POST) if form.is_valid(): form.save() else: messages.error(request, utils.render_form_errors(form)) return redirect(request.POST.get('next', topic.get_absolute_url())) @require_POST @login_required def update(request, pk): notification = get_object_or_404(TopicNotification, pk=pk, user=request.user) form = NotificationForm(data=request.POST, instance=notification) if form.is_valid(): form.save() else: messages.error(request, utils.render_form_errors(form)) return redirect(request.POST.get( 'next', notification.topic.get_absolute_url())) @login_required def index_ajax(request): if not is_ajax(request): return Http404() notifications = ( TopicNotification.objects .for_access(request.user) .order_by("is_read", "-date") .with_related_data()) notifications = notifications[:settings.ST_NOTIFICATIONS_PER_PAGE] notifications = [ {'user': escape(n.comment.user.st.nickname), 'action': n.action, 'title': escape(n.topic.title), 'url': n.get_absolute_url(), 'is_read': n.is_read} for n in notifications] return HttpResponse( json.dumps({'n': notifications}), content_type="application/json") @login_required def index_unread(request): notifications = ( TopicNotification.objects .for_access(request.user) .filter(is_read=False) .with_related_data()) page = paginate( request, query_set=notifications, lookup_field='date', page_var='p', per_page=settings.ST_NOTIFICATIONS_PER_PAGE) return render( request=request, template_name='spirit/topic/notification/index_unread.html', context={ 'page': page, 'next_page': to_page_key(**page.next_page())}) @login_required def index(request): notifications = yt_paginate( TopicNotification.objects .for_access(request.user) .with_related_data(), per_page=config.topics_per_page, page_number=request.GET.get('page', 1)) return render( request=request, template_name='spirit/topic/notification/index.html', context={'notifications': notifications}) @require_POST @login_required def mark_all_as_read(request): (TopicNotification.objects .for_access(request.user) .filter(is_read=False) .update(is_read=True)) return redirect(request.POST.get( 'next', reverse('spirit:topic:notification:index')))
# -*- coding: utf-8 -*- import json from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from django.views.decorators.http import require_POST from django.http import Http404, HttpResponse from django.contrib import messages from django.utils.html import escape from django.urls import reverse from djconfig import config from infinite_scroll_pagination.serializers import to_page_key from spirit.core.conf import settings from spirit.core import utils from spirit.core.utils.paginator import yt_paginate from spirit.core.utils.paginator.infinite_paginator import paginate from spirit.core.utils.views import is_ajax from spirit.core.utils.http import safe_redirect from spirit.topic.models import Topic from .models import TopicNotification from .forms import NotificationForm, NotificationCreationForm @require_POST @login_required def create(request, topic_id): topic = get_object_or_404( Topic.objects.for_access(request.user), pk=topic_id) form = NotificationCreationForm( user=request.user, topic=topic, data=request.POST) if form.is_valid(): form.save() else: messages.error(request, utils.render_form_errors(form)) return safe_redirect(request, 'next', topic.get_absolute_url(), method='POST') @require_POST @login_required def update(request, pk): notification = get_object_or_404(TopicNotification, pk=pk, user=request.user) form = NotificationForm(data=request.POST, instance=notification) if form.is_valid(): form.save() else: messages.error(request, utils.render_form_errors(form)) return safe_redirect( request, 'next', notification.topic.get_absolute_url(), method='POST') @login_required def index_ajax(request): if not is_ajax(request): return Http404() notifications = ( TopicNotification.objects .for_access(request.user) .order_by("is_read", "-date") .with_related_data()) notifications = notifications[:settings.ST_NOTIFICATIONS_PER_PAGE] notifications = [ {'user': escape(n.comment.user.st.nickname), 'action': n.action, 'title': escape(n.topic.title), 'url': n.get_absolute_url(), 'is_read': n.is_read} for n in notifications] return HttpResponse( json.dumps({'n': notifications}), content_type="application/json") @login_required def index_unread(request): notifications = ( TopicNotification.objects .for_access(request.user) .filter(is_read=False) .with_related_data()) page = paginate( request, query_set=notifications, lookup_field='date', page_var='p', per_page=settings.ST_NOTIFICATIONS_PER_PAGE) return render( request=request, template_name='spirit/topic/notification/index_unread.html', context={ 'page': page, 'next_page': to_page_key(**page.next_page())}) @login_required def index(request): notifications = yt_paginate( TopicNotification.objects .for_access(request.user) .with_related_data(), per_page=config.topics_per_page, page_number=request.GET.get('page', 1)) return render( request=request, template_name='spirit/topic/notification/index.html', context={'notifications': notifications}) @require_POST @login_required def mark_all_as_read(request): (TopicNotification.objects .for_access(request.user) .filter(is_read=False) .update(is_read=True)) return safe_redirect( request, 'next', reverse('spirit:topic:notification:index'), method='POST')
open_redirect
{ "code": [ "from django.shortcuts import render, redirect, get_object_or_404", " return redirect(request.POST.get('next', topic.get_absolute_url()))", " return redirect(request.POST.get(", " 'next', notification.topic.get_absolute_url()))", " return redirect(request.POST.get(", " 'next', reverse('spirit:topic:notification:index')))" ], "line_no": [ 6, 42, 56, 57, 127, 128 ] }
{ "code": [ "from django.shortcuts import render, get_object_or_404", "from spirit.core.utils.http import safe_redirect", " return safe_redirect(", " return safe_redirect(" ], "line_no": [ 6, 21, 57, 128 ] }
import json from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from django.http import Http404, HttpResponse from django.contrib import messages from django.utils.html import escape from django.urls import reverse from djconfig import config from infinite_scroll_pagination.serializers import to_page_key from spirit.core.conf import settings from spirit.core import utils from spirit.core.utils.paginator import yt_paginate from spirit.core.utils.paginator.infinite_paginator import paginate from spirit.core.utils.views import is_ajax from spirit.topic.models import Topic from .models import TopicNotification from .forms import NotificationForm, NotificationCreationForm @require_POST @login_required def FUNC_0(VAR_0, VAR_1): VAR_3 = get_object_or_404( Topic.objects.for_access(VAR_0.user), VAR_2=VAR_1) VAR_4 = NotificationCreationForm( user=VAR_0.user, VAR_3=topic, data=VAR_0.POST) if VAR_4.is_valid(): VAR_4.save() else: messages.error(VAR_0, utils.render_form_errors(VAR_4)) return redirect(VAR_0.POST.get('next', VAR_3.get_absolute_url())) @require_POST @login_required def FUNC_1(VAR_0, VAR_2): VAR_5 = get_object_or_404(TopicNotification, VAR_2=pk, user=VAR_0.user) VAR_4 = NotificationForm(data=VAR_0.POST, instance=VAR_5) if VAR_4.is_valid(): VAR_4.save() else: messages.error(VAR_0, utils.render_form_errors(VAR_4)) return redirect(VAR_0.POST.get( 'next', VAR_5.topic.get_absolute_url())) @login_required def FUNC_2(VAR_0): if not is_ajax(VAR_0): return Http404() VAR_6 = ( TopicNotification.objects .for_access(VAR_0.user) .order_by("is_read", "-date") .with_related_data()) VAR_6 = notifications[:settings.ST_NOTIFICATIONS_PER_PAGE] VAR_6 = [ {'user': escape(n.comment.user.st.nickname), 'action': n.action, 'title': escape(n.topic.title), 'url': n.get_absolute_url(), 'is_read': n.is_read} for n in VAR_6] return HttpResponse( json.dumps({'n': VAR_6}), content_type="application/json") @login_required def FUNC_3(VAR_0): VAR_6 = ( TopicNotification.objects .for_access(VAR_0.user) .filter(is_read=False) .with_related_data()) VAR_7 = paginate( VAR_0, query_set=VAR_6, lookup_field='date', page_var='p', per_page=settings.ST_NOTIFICATIONS_PER_PAGE) return render( VAR_0=request, template_name='spirit/VAR_3/VAR_5/FUNC_3.html', context={ 'page': VAR_7, 'next_page': to_page_key(**VAR_7.next_page())}) @login_required def FUNC_4(VAR_0): VAR_6 = yt_paginate( TopicNotification.objects .for_access(VAR_0.user) .with_related_data(), per_page=config.topics_per_page, page_number=VAR_0.GET.get('page', 1)) return render( VAR_0=request, template_name='spirit/VAR_3/VAR_5/FUNC_4.html', context={'notifications': VAR_6}) @require_POST @login_required def FUNC_5(VAR_0): (TopicNotification.objects .for_access(VAR_0.user) .filter(is_read=False) .update(is_read=True)) return redirect(VAR_0.POST.get( 'next', reverse('spirit:VAR_3:VAR_5:index')))
import json from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from django.views.decorators.http import require_POST from django.http import Http404, HttpResponse from django.contrib import messages from django.utils.html import escape from django.urls import reverse from djconfig import config from infinite_scroll_pagination.serializers import to_page_key from spirit.core.conf import settings from spirit.core import utils from spirit.core.utils.paginator import yt_paginate from spirit.core.utils.paginator.infinite_paginator import paginate from spirit.core.utils.views import is_ajax from spirit.core.utils.http import safe_redirect from spirit.topic.models import Topic from .models import TopicNotification from .forms import NotificationForm, NotificationCreationForm @require_POST @login_required def FUNC_0(VAR_0, VAR_1): VAR_3 = get_object_or_404( Topic.objects.for_access(VAR_0.user), VAR_2=VAR_1) VAR_4 = NotificationCreationForm( user=VAR_0.user, VAR_3=topic, data=VAR_0.POST) if VAR_4.is_valid(): VAR_4.save() else: messages.error(VAR_0, utils.render_form_errors(VAR_4)) return safe_redirect(VAR_0, 'next', VAR_3.get_absolute_url(), method='POST') @require_POST @login_required def FUNC_1(VAR_0, VAR_2): VAR_5 = get_object_or_404(TopicNotification, VAR_2=pk, user=VAR_0.user) VAR_4 = NotificationForm(data=VAR_0.POST, instance=VAR_5) if VAR_4.is_valid(): VAR_4.save() else: messages.error(VAR_0, utils.render_form_errors(VAR_4)) return safe_redirect( VAR_0, 'next', VAR_5.topic.get_absolute_url(), method='POST') @login_required def FUNC_2(VAR_0): if not is_ajax(VAR_0): return Http404() VAR_6 = ( TopicNotification.objects .for_access(VAR_0.user) .order_by("is_read", "-date") .with_related_data()) VAR_6 = notifications[:settings.ST_NOTIFICATIONS_PER_PAGE] VAR_6 = [ {'user': escape(n.comment.user.st.nickname), 'action': n.action, 'title': escape(n.topic.title), 'url': n.get_absolute_url(), 'is_read': n.is_read} for n in VAR_6] return HttpResponse( json.dumps({'n': VAR_6}), content_type="application/json") @login_required def FUNC_3(VAR_0): VAR_6 = ( TopicNotification.objects .for_access(VAR_0.user) .filter(is_read=False) .with_related_data()) VAR_7 = paginate( VAR_0, query_set=VAR_6, lookup_field='date', page_var='p', per_page=settings.ST_NOTIFICATIONS_PER_PAGE) return render( VAR_0=request, template_name='spirit/VAR_3/VAR_5/FUNC_3.html', context={ 'page': VAR_7, 'next_page': to_page_key(**VAR_7.next_page())}) @login_required def FUNC_4(VAR_0): VAR_6 = yt_paginate( TopicNotification.objects .for_access(VAR_0.user) .with_related_data(), per_page=config.topics_per_page, page_number=VAR_0.GET.get('page', 1)) return render( VAR_0=request, template_name='spirit/VAR_3/VAR_5/FUNC_4.html', context={'notifications': VAR_6}) @require_POST @login_required def FUNC_5(VAR_0): (TopicNotification.objects .for_access(VAR_0.user) .filter(is_read=False) .update(is_read=True)) return safe_redirect( VAR_0, 'next', reverse('spirit:VAR_3:VAR_5:index'), method='POST')
[ 1, 2, 4, 12, 15, 24, 25, 36, 41, 43, 44, 50, 55, 58, 59, 64, 78, 82, 83, 103, 104, 113, 118, 119, 129 ]
[ 1, 2, 4, 12, 15, 25, 26, 37, 42, 44, 45, 51, 56, 59, 60, 65, 79, 83, 84, 104, 105, 114, 119, 120, 130 ]
1CWE-79
""" Form Widget classes specific to the Django admin site. """ from __future__ import unicode_literals import copy from django import forms from django.contrib.admin.templatetags.admin_static import static from django.core.urlresolvers import reverse from django.forms.widgets import RadioFieldRenderer from django.forms.util import flatatt from django.utils.html import escape, format_html, format_html_join, smart_urlquote from django.utils.text import Truncator from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.utils.encoding import force_text from django.utils import six class FilteredSelectMultiple(forms.SelectMultiple): """ A SelectMultiple with a JavaScript filter interface. Note that the resulting JavaScript assumes that the jsi18n catalog has been loaded in the page """ @property def media(self): js = ["core.js", "SelectBox.js", "SelectFilter2.js"] return forms.Media(js=[static("admin/js/%s" % path) for path in js]) def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): self.verbose_name = verbose_name self.is_stacked = is_stacked super(FilteredSelectMultiple, self).__init__(attrs, choices) def render(self, name, value, attrs=None, choices=()): if attrs is None: attrs = {} attrs['class'] = 'selectfilter' if self.is_stacked: attrs['class'] += 'stacked' output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)] output.append('<script type="text/javascript">addEvent(window, "load", function(e) {') # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append('SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), static('admin/'))) return mark_safe(''.join(output)) class AdminDateWidget(forms.DateInput): @property def media(self): js = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(js=[static("admin/js/%s" % path) for path in js]) def __init__(self, attrs=None, format=None): final_attrs = {'class': 'vDateField', 'size': '10'} if attrs is not None: final_attrs.update(attrs) super(AdminDateWidget, self).__init__(attrs=final_attrs, format=format) class AdminTimeWidget(forms.TimeInput): @property def media(self): js = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(js=[static("admin/js/%s" % path) for path in js]) def __init__(self, attrs=None, format=None): final_attrs = {'class': 'vTimeField', 'size': '8'} if attrs is not None: final_attrs.update(attrs) super(AdminTimeWidget, self).__init__(attrs=final_attrs, format=format) class AdminSplitDateTime(forms.SplitDateTimeWidget): """ A SplitDateTime Widget that has some admin-specific styling. """ def __init__(self, attrs=None): widgets = [AdminDateWidget, AdminTimeWidget] # Note that we're calling MultiWidget, not SplitDateTimeWidget, because # we want to define widgets. forms.MultiWidget.__init__(self, widgets, attrs) def format_output(self, rendered_widgets): return format_html('<p class="datetime">{0} {1}<br />{2} {3}</p>', _('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1]) class AdminRadioFieldRenderer(RadioFieldRenderer): def render(self): """Outputs a <ul> for this set of radio fields.""" return format_html('<ul{0}>\n{1}\n</ul>', flatatt(self.attrs), format_html_join('\n', '<li>{0}</li>', ((force_text(w),) for w in self))) class AdminRadioSelect(forms.RadioSelect): renderer = AdminRadioFieldRenderer class AdminFileWidget(forms.ClearableFileInput): template_with_initial = ('<p class="file-upload">%s</p>' % forms.ClearableFileInput.template_with_initial) template_with_clear = ('<span class="clearable-file-input">%s</span>' % forms.ClearableFileInput.template_with_clear) def url_params_from_lookup_dict(lookups): """ Converts the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters """ params = {} if lookups and hasattr(lookups, 'items'): items = [] for k, v in lookups.items(): if callable(v): v = v() if isinstance(v, (tuple, list)): v = ','.join([str(x) for x in v]) elif isinstance(v, bool): # See django.db.fields.BooleanField.get_prep_lookup v = ('0', '1')[v] else: v = six.text_type(v) items.append((k, v)) params.update(dict(items)) return params class ForeignKeyRawIdWidget(forms.TextInput): """ A Widget for displaying ForeignKeys in the "raw_id" interface rather than in a <select> box. """ def __init__(self, rel, admin_site, attrs=None, using=None): self.rel = rel self.admin_site = admin_site self.db = using super(ForeignKeyRawIdWidget, self).__init__(attrs) def render(self, name, value, attrs=None): rel_to = self.rel.to if attrs is None: attrs = {} extra = [] if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite related_url = reverse('admin:%s_%s_changelist' % (rel_to._meta.app_label, rel_to._meta.model_name), current_app=self.admin_site.name) params = self.url_parameters() if params: url = '?' + '&amp;'.join(['%s=%s' % (k, v) for k, v in params.items()]) else: url = '' if "class" not in attrs: attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook. # TODO: "lookup_id_" is hard-coded here. This should instead use # the correct API to determine the ID dynamically. extra.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % (related_url, url, name)) extra.append('<img src="%s" width="16" height="16" alt="%s" /></a>' % (static('admin/img/selector-search.gif'), _('Lookup'))) output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)] + extra if value: output.append(self.label_for_value(value)) return mark_safe(''.join(output)) def base_url_parameters(self): return url_params_from_lookup_dict(self.rel.limit_choices_to) def url_parameters(self): from django.contrib.admin.views.main import TO_FIELD_VAR params = self.base_url_parameters() params.update({TO_FIELD_VAR: self.rel.get_related_field().name}) return params def label_for_value(self, value): key = self.rel.get_related_field().name try: obj = self.rel.to._default_manager.using(self.db).get(**{key: value}) return '&nbsp;<strong>%s</strong>' % escape(Truncator(obj).words(14, truncate='...')) except (ValueError, self.rel.to.DoesNotExist): return '' class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): """ A Widget for displaying ManyToMany ids in the "raw_id" interface rather than in a <select multiple> box. """ def render(self, name, value, attrs=None): if attrs is None: attrs = {} if self.rel.to in self.admin_site._registry: # The related object is registered with the same AdminSite attrs['class'] = 'vManyToManyRawIdAdminField' if value: value = ','.join([force_text(v) for v in value]) else: value = '' return super(ManyToManyRawIdWidget, self).render(name, value, attrs) def url_parameters(self): return self.base_url_parameters() def label_for_value(self, value): return '' def value_from_datadict(self, data, files, name): value = data.get(name) if value: return value.split(',') class RelatedFieldWidgetWrapper(forms.Widget): """ This class is a wrapper to a given widget to add the add icon for the admin interface. """ def __init__(self, widget, rel, admin_site, can_add_related=None): self.is_hidden = widget.is_hidden self.needs_multipart_form = widget.needs_multipart_form self.attrs = widget.attrs self.choices = widget.choices self.widget = widget self.rel = rel # Backwards compatible check for whether a user can add related # objects. if can_add_related is None: can_add_related = rel.to in admin_site._registry self.can_add_related = can_add_related # so we can check if the related object is registered with this AdminSite self.admin_site = admin_site def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj @property def media(self): return self.widget.media def render(self, name, value, *args, **kwargs): rel_to = self.rel.to info = (rel_to._meta.app_label, rel_to._meta.model_name) self.widget.choices = self.choices output = [self.widget.render(name, value, *args, **kwargs)] if self.can_add_related: related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name) # TODO: "add_id_" is hard-coded here. This should instead use the # correct API to determine the ID dynamically. output.append('<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % (related_url, name)) output.append('<img src="%s" width="10" height="10" alt="%s"/></a>' % (static('admin/img/icon_addlink.gif'), _('Add Another'))) return mark_safe(''.join(output)) def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs def value_from_datadict(self, data, files, name): return self.widget.value_from_datadict(data, files, name) def id_for_label(self, id_): return self.widget.id_for_label(id_) class AdminTextareaWidget(forms.Textarea): def __init__(self, attrs=None): final_attrs = {'class': 'vLargeTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextareaWidget, self).__init__(attrs=final_attrs) class AdminTextInputWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextInputWidget, self).__init__(attrs=final_attrs) class AdminEmailInputWidget(forms.EmailInput): def __init__(self, attrs=None): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminEmailInputWidget, self).__init__(attrs=final_attrs) class AdminURLFieldWidget(forms.URLInput): def __init__(self, attrs=None): final_attrs = {'class': 'vURLField'} if attrs is not None: final_attrs.update(attrs) super(AdminURLFieldWidget, self).__init__(attrs=final_attrs) def render(self, name, value, attrs=None): html = super(AdminURLFieldWidget, self).render(name, value, attrs) if value: value = force_text(self._format_value(value)) final_attrs = {'href': mark_safe(smart_urlquote(value))} html = format_html( '<p class="url">{0} <a {1}>{2}</a><br />{3} {4}</p>', _('Currently:'), flatatt(final_attrs), value, _('Change:'), html ) return html class AdminIntegerFieldWidget(forms.TextInput): class_name = 'vIntegerField' def __init__(self, attrs=None): final_attrs = {'class': self.class_name} if attrs is not None: final_attrs.update(attrs) super(AdminIntegerFieldWidget, self).__init__(attrs=final_attrs) class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): class_name = 'vBigIntegerField' class AdminCommaSeparatedIntegerFieldWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vCommaSeparatedIntegerField'} if attrs is not None: final_attrs.update(attrs) super(AdminCommaSeparatedIntegerFieldWidget, self).__init__(attrs=final_attrs)
""" Form Widget classes specific to the Django admin site. """ from __future__ import unicode_literals import copy from django import forms from django.contrib.admin.templatetags.admin_static import static from django.core.urlresolvers import reverse from django.forms.widgets import RadioFieldRenderer from django.forms.util import flatatt from django.utils.html import escape, format_html, format_html_join, smart_urlquote from django.utils.text import Truncator from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.utils.encoding import force_text from django.utils import six class FilteredSelectMultiple(forms.SelectMultiple): """ A SelectMultiple with a JavaScript filter interface. Note that the resulting JavaScript assumes that the jsi18n catalog has been loaded in the page """ @property def media(self): js = ["core.js", "SelectBox.js", "SelectFilter2.js"] return forms.Media(js=[static("admin/js/%s" % path) for path in js]) def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): self.verbose_name = verbose_name self.is_stacked = is_stacked super(FilteredSelectMultiple, self).__init__(attrs, choices) def render(self, name, value, attrs=None, choices=()): if attrs is None: attrs = {} attrs['class'] = 'selectfilter' if self.is_stacked: attrs['class'] += 'stacked' output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)] output.append('<script type="text/javascript">addEvent(window, "load", function(e) {') # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append('SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), static('admin/'))) return mark_safe(''.join(output)) class AdminDateWidget(forms.DateInput): @property def media(self): js = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(js=[static("admin/js/%s" % path) for path in js]) def __init__(self, attrs=None, format=None): final_attrs = {'class': 'vDateField', 'size': '10'} if attrs is not None: final_attrs.update(attrs) super(AdminDateWidget, self).__init__(attrs=final_attrs, format=format) class AdminTimeWidget(forms.TimeInput): @property def media(self): js = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(js=[static("admin/js/%s" % path) for path in js]) def __init__(self, attrs=None, format=None): final_attrs = {'class': 'vTimeField', 'size': '8'} if attrs is not None: final_attrs.update(attrs) super(AdminTimeWidget, self).__init__(attrs=final_attrs, format=format) class AdminSplitDateTime(forms.SplitDateTimeWidget): """ A SplitDateTime Widget that has some admin-specific styling. """ def __init__(self, attrs=None): widgets = [AdminDateWidget, AdminTimeWidget] # Note that we're calling MultiWidget, not SplitDateTimeWidget, because # we want to define widgets. forms.MultiWidget.__init__(self, widgets, attrs) def format_output(self, rendered_widgets): return format_html('<p class="datetime">{0} {1}<br />{2} {3}</p>', _('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1]) class AdminRadioFieldRenderer(RadioFieldRenderer): def render(self): """Outputs a <ul> for this set of radio fields.""" return format_html('<ul{0}>\n{1}\n</ul>', flatatt(self.attrs), format_html_join('\n', '<li>{0}</li>', ((force_text(w),) for w in self))) class AdminRadioSelect(forms.RadioSelect): renderer = AdminRadioFieldRenderer class AdminFileWidget(forms.ClearableFileInput): template_with_initial = ('<p class="file-upload">%s</p>' % forms.ClearableFileInput.template_with_initial) template_with_clear = ('<span class="clearable-file-input">%s</span>' % forms.ClearableFileInput.template_with_clear) def url_params_from_lookup_dict(lookups): """ Converts the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters """ params = {} if lookups and hasattr(lookups, 'items'): items = [] for k, v in lookups.items(): if callable(v): v = v() if isinstance(v, (tuple, list)): v = ','.join([str(x) for x in v]) elif isinstance(v, bool): # See django.db.fields.BooleanField.get_prep_lookup v = ('0', '1')[v] else: v = six.text_type(v) items.append((k, v)) params.update(dict(items)) return params class ForeignKeyRawIdWidget(forms.TextInput): """ A Widget for displaying ForeignKeys in the "raw_id" interface rather than in a <select> box. """ def __init__(self, rel, admin_site, attrs=None, using=None): self.rel = rel self.admin_site = admin_site self.db = using super(ForeignKeyRawIdWidget, self).__init__(attrs) def render(self, name, value, attrs=None): rel_to = self.rel.to if attrs is None: attrs = {} extra = [] if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite related_url = reverse('admin:%s_%s_changelist' % (rel_to._meta.app_label, rel_to._meta.model_name), current_app=self.admin_site.name) params = self.url_parameters() if params: url = '?' + '&amp;'.join(['%s=%s' % (k, v) for k, v in params.items()]) else: url = '' if "class" not in attrs: attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook. # TODO: "lookup_id_" is hard-coded here. This should instead use # the correct API to determine the ID dynamically. extra.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % (related_url, url, name)) extra.append('<img src="%s" width="16" height="16" alt="%s" /></a>' % (static('admin/img/selector-search.gif'), _('Lookup'))) output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)] + extra if value: output.append(self.label_for_value(value)) return mark_safe(''.join(output)) def base_url_parameters(self): return url_params_from_lookup_dict(self.rel.limit_choices_to) def url_parameters(self): from django.contrib.admin.views.main import TO_FIELD_VAR params = self.base_url_parameters() params.update({TO_FIELD_VAR: self.rel.get_related_field().name}) return params def label_for_value(self, value): key = self.rel.get_related_field().name try: obj = self.rel.to._default_manager.using(self.db).get(**{key: value}) return '&nbsp;<strong>%s</strong>' % escape(Truncator(obj).words(14, truncate='...')) except (ValueError, self.rel.to.DoesNotExist): return '' class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): """ A Widget for displaying ManyToMany ids in the "raw_id" interface rather than in a <select multiple> box. """ def render(self, name, value, attrs=None): if attrs is None: attrs = {} if self.rel.to in self.admin_site._registry: # The related object is registered with the same AdminSite attrs['class'] = 'vManyToManyRawIdAdminField' if value: value = ','.join([force_text(v) for v in value]) else: value = '' return super(ManyToManyRawIdWidget, self).render(name, value, attrs) def url_parameters(self): return self.base_url_parameters() def label_for_value(self, value): return '' def value_from_datadict(self, data, files, name): value = data.get(name) if value: return value.split(',') class RelatedFieldWidgetWrapper(forms.Widget): """ This class is a wrapper to a given widget to add the add icon for the admin interface. """ def __init__(self, widget, rel, admin_site, can_add_related=None): self.is_hidden = widget.is_hidden self.needs_multipart_form = widget.needs_multipart_form self.attrs = widget.attrs self.choices = widget.choices self.widget = widget self.rel = rel # Backwards compatible check for whether a user can add related # objects. if can_add_related is None: can_add_related = rel.to in admin_site._registry self.can_add_related = can_add_related # so we can check if the related object is registered with this AdminSite self.admin_site = admin_site def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj @property def media(self): return self.widget.media def render(self, name, value, *args, **kwargs): rel_to = self.rel.to info = (rel_to._meta.app_label, rel_to._meta.model_name) self.widget.choices = self.choices output = [self.widget.render(name, value, *args, **kwargs)] if self.can_add_related: related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name) # TODO: "add_id_" is hard-coded here. This should instead use the # correct API to determine the ID dynamically. output.append('<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % (related_url, name)) output.append('<img src="%s" width="10" height="10" alt="%s"/></a>' % (static('admin/img/icon_addlink.gif'), _('Add Another'))) return mark_safe(''.join(output)) def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs def value_from_datadict(self, data, files, name): return self.widget.value_from_datadict(data, files, name) def id_for_label(self, id_): return self.widget.id_for_label(id_) class AdminTextareaWidget(forms.Textarea): def __init__(self, attrs=None): final_attrs = {'class': 'vLargeTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextareaWidget, self).__init__(attrs=final_attrs) class AdminTextInputWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextInputWidget, self).__init__(attrs=final_attrs) class AdminEmailInputWidget(forms.EmailInput): def __init__(self, attrs=None): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminEmailInputWidget, self).__init__(attrs=final_attrs) class AdminURLFieldWidget(forms.URLInput): def __init__(self, attrs=None): final_attrs = {'class': 'vURLField'} if attrs is not None: final_attrs.update(attrs) super(AdminURLFieldWidget, self).__init__(attrs=final_attrs) def render(self, name, value, attrs=None): html = super(AdminURLFieldWidget, self).render(name, value, attrs) if value: value = force_text(self._format_value(value)) final_attrs = {'href': smart_urlquote(value)} html = format_html( '<p class="url">{0} <a{1}>{2}</a><br />{3} {4}</p>', _('Currently:'), flatatt(final_attrs), value, _('Change:'), html ) return html class AdminIntegerFieldWidget(forms.TextInput): class_name = 'vIntegerField' def __init__(self, attrs=None): final_attrs = {'class': self.class_name} if attrs is not None: final_attrs.update(attrs) super(AdminIntegerFieldWidget, self).__init__(attrs=final_attrs) class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): class_name = 'vBigIntegerField' class AdminCommaSeparatedIntegerFieldWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vCommaSeparatedIntegerField'} if attrs is not None: final_attrs.update(attrs) super(AdminCommaSeparatedIntegerFieldWidget, self).__init__(attrs=final_attrs)
xss
{ "code": [ " final_attrs = {'href': mark_safe(smart_urlquote(value))}", " '<p class=\"url\">{0} <a {1}>{2}</a><br />{3} {4}</p>'," ], "line_no": [ 308, 310 ] }
{ "code": [ " final_attrs = {'href': smart_urlquote(value)}", " '<p class=\"url\">{0} <a{1}>{2}</a><br />{3} {4}</p>'," ], "line_no": [ 308, 310 ] }
from __future__ import unicode_literals import copy from django import forms from django.contrib.admin.templatetags.admin_static import static from django.core.urlresolvers import reverse from django.forms.widgets import RadioFieldRenderer from django.forms.util import flatatt from django.utils.html import escape, format_html, format_html_join, smart_urlquote from django.utils.text import Truncator from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.utils.encoding import force_text from django.utils import six class CLASS_0(forms.SelectMultiple): @property def FUNC_1(self): VAR_26 = ["core.js", "SelectBox.js", "SelectFilter2.js"] return forms.Media(VAR_26=[static("admin/VAR_26/%s" % path) for path in VAR_26]) def __init__(self, VAR_1, VAR_2, VAR_3=None, VAR_4=()): self.verbose_name = VAR_1 self.is_stacked = VAR_2 super(CLASS_0, self).__init__(VAR_3, VAR_4) def FUNC_2(self, VAR_5, VAR_6, VAR_3=None, VAR_4=()): if VAR_3 is None: VAR_3 = {} attrs['class'] = 'selectfilter' if self.is_stacked: VAR_3['class'] += 'stacked' VAR_27 = [super(CLASS_0, self).render(VAR_5, VAR_6, VAR_3, VAR_4)] VAR_27.append('<script type="text/javascript">addEvent(window, "load", function(e) {') VAR_27.append('SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % (VAR_5, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), static('admin/'))) return mark_safe(''.join(VAR_27)) class CLASS_1(forms.DateInput): @property def FUNC_1(self): VAR_26 = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(VAR_26=[static("admin/VAR_26/%s" % path) for path in VAR_26]) def __init__(self, VAR_3=None, VAR_7=None): VAR_28 = {'class': 'vDateField', 'size': '10'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_1, self).__init__(VAR_3=VAR_28, VAR_7=format) class CLASS_2(forms.TimeInput): @property def FUNC_1(self): VAR_26 = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(VAR_26=[static("admin/VAR_26/%s" % path) for path in VAR_26]) def __init__(self, VAR_3=None, VAR_7=None): VAR_28 = {'class': 'vTimeField', 'size': '8'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_2, self).__init__(VAR_3=VAR_28, VAR_7=format) class CLASS_3(forms.SplitDateTimeWidget): def __init__(self, VAR_3=None): VAR_29 = [CLASS_1, CLASS_2] forms.MultiWidget.__init__(self, VAR_29, VAR_3) def FUNC_3(self, VAR_8): return format_html('<p class="datetime">{0} {1}<br />{2} {3}</p>', _('Date:'), VAR_8[0], _('Time:'), VAR_8[1]) class CLASS_4(RadioFieldRenderer): def FUNC_2(self): return format_html('<ul{0}>\n{1}\n</ul>', flatatt(self.attrs), format_html_join('\n', '<li>{0}</li>', ((force_text(w),) for w in self))) class CLASS_5(forms.RadioSelect): VAR_9 = CLASS_4 class CLASS_6(forms.ClearableFileInput): VAR_10 = ('<p class="file-upload">%s</p>' % forms.ClearableFileInput.template_with_initial) VAR_11 = ('<span class="clearable-file-input">%s</span>' % forms.ClearableFileInput.template_with_clear) def FUNC_0(VAR_0): VAR_12 = {} if VAR_0 and hasattr(VAR_0, 'items'): VAR_30 = [] for k, VAR_39 in VAR_0.items(): if callable(VAR_39): VAR_39 = VAR_39() if isinstance(VAR_39, (tuple, list)): VAR_39 = ','.join([str(x) for x in VAR_39]) elif isinstance(VAR_39, bool): VAR_39 = ('0', '1')[VAR_39] else: VAR_39 = six.text_type(VAR_39) VAR_30.append((k, VAR_39)) VAR_12.update(dict(VAR_30)) return VAR_12 class CLASS_7(forms.TextInput): def __init__(self, VAR_13, VAR_14, VAR_3=None, VAR_15=None): self.rel = VAR_13 self.admin_site = VAR_14 self.db = VAR_15 super(CLASS_7, self).__init__(VAR_3) def FUNC_2(self, VAR_5, VAR_6, VAR_3=None): VAR_31 = self.rel.to if VAR_3 is None: VAR_3 = {} VAR_32 = [] if VAR_31 in self.admin_site._registry: VAR_38 = reverse('admin:%s_%s_changelist' % (VAR_31._meta.app_label, VAR_31._meta.model_name), current_app=self.admin_site.name) VAR_12 = self.url_parameters() if VAR_12: VAR_40 = '?' + '&amp;'.join(['%s=%s' % (k, VAR_39) for k, VAR_39 in VAR_12.items()]) else: VAR_40 = '' if "class" not in VAR_3: attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook. VAR_32.append('<a href="%s%s" class="related-lookup" VAR_35="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % (VAR_38, VAR_40, VAR_5)) VAR_32.append('<img src="%s" width="16" height="16" alt="%s" /></a>' % (static('admin/img/selector-search.gif'), _('Lookup'))) VAR_27 = [super(CLASS_7, self).render(VAR_5, VAR_6, VAR_3)] + VAR_32 if VAR_6: VAR_27.append(self.label_for_value(VAR_6)) return mark_safe(''.join(VAR_27)) def FUNC_4(self): return FUNC_0(self.rel.limit_choices_to) def FUNC_5(self): from django.contrib.admin.views.main import TO_FIELD_VAR VAR_12 = self.base_url_parameters() VAR_12.update({TO_FIELD_VAR: self.rel.get_related_field().name}) return VAR_12 def FUNC_6(self, VAR_6): VAR_33 = self.rel.get_related_field().name try: VAR_34 = self.rel.to._default_manager.using(self.db).get(**{VAR_33: VAR_6}) return '&nbsp;<strong>%s</strong>' % escape(Truncator(VAR_34).words(14, truncate='...')) except (ValueError, self.rel.to.DoesNotExist): return '' class CLASS_8(CLASS_7): def FUNC_2(self, VAR_5, VAR_6, VAR_3=None): if VAR_3 is None: VAR_3 = {} if self.rel.to in self.admin_site._registry: VAR_3['class'] = 'vManyToManyRawIdAdminField' if VAR_6: VAR_6 = ','.join([force_text(VAR_39) for VAR_39 in VAR_6]) else: VAR_6 = '' return super(CLASS_8, self).render(VAR_5, VAR_6, VAR_3) def FUNC_5(self): return self.base_url_parameters() def FUNC_6(self, VAR_6): return '' def FUNC_7(self, VAR_16, VAR_17, VAR_5): VAR_6 = VAR_16.get(VAR_5) if VAR_6: return VAR_6.split(',') class CLASS_9(forms.Widget): def __init__(self, VAR_18, VAR_13, VAR_14, VAR_19=None): self.is_hidden = VAR_18.is_hidden self.needs_multipart_form = VAR_18.needs_multipart_form self.attrs = VAR_18.attrs self.choices = VAR_18.choices self.widget = VAR_18 self.rel = VAR_13 if VAR_19 is None: VAR_19 = VAR_13.to in VAR_14._registry self.can_add_related = VAR_19 self.admin_site = VAR_14 def __deepcopy__(self, VAR_20): VAR_34 = copy.copy(self) VAR_34.widget = copy.deepcopy(self.widget, VAR_20) VAR_34.attrs = self.widget.attrs VAR_20[VAR_35(self)] = VAR_34 return VAR_34 @property def FUNC_1(self): return self.widget.media def FUNC_2(self, VAR_5, VAR_6, *VAR_21, **VAR_22): VAR_31 = self.rel.to VAR_36 = (VAR_31._meta.app_label, VAR_31._meta.model_name) self.widget.choices = self.choices VAR_27 = [self.widget.render(VAR_5, VAR_6, *VAR_21, **VAR_22)] if self.can_add_related: VAR_38 = reverse('admin:%s_%s_add' % VAR_36, current_app=self.admin_site.name) VAR_27.append('<a href="%s" class="add-another" VAR_35="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % (VAR_38, VAR_5)) VAR_27.append('<img src="%s" width="10" height="10" alt="%s"/></a>' % (static('admin/img/icon_addlink.gif'), _('Add Another'))) return mark_safe(''.join(VAR_27)) self.attrs = self.widget.build_attrs(VAR_23=None, **VAR_22) return self.attrs def FUNC_7(self, VAR_16, VAR_17, VAR_5): return self.widget.value_from_datadict(VAR_16, VAR_17, VAR_5) def FUNC_9(self, VAR_24): return self.widget.id_for_label(VAR_24) class CLASS_10(forms.Textarea): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vLargeTextField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_10, self).__init__(VAR_3=VAR_28) class CLASS_11(forms.TextInput): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vTextField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_11, self).__init__(VAR_3=VAR_28) class CLASS_12(forms.EmailInput): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vTextField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_12, self).__init__(VAR_3=VAR_28) class CLASS_13(forms.URLInput): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vURLField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_13, self).__init__(VAR_3=VAR_28) def FUNC_2(self, VAR_5, VAR_6, VAR_3=None): VAR_37 = super(CLASS_13, self).render(VAR_5, VAR_6, VAR_3) if VAR_6: VAR_6 = force_text(self._format_value(VAR_6)) VAR_28 = {'href': mark_safe(smart_urlquote(VAR_6))} VAR_37 = format_html( '<p class="url">{0} <a {1}>{2}</a><br />{3} {4}</p>', _('Currently:'), flatatt(VAR_28), VAR_6, _('Change:'), VAR_37 ) return VAR_37 class CLASS_14(forms.TextInput): VAR_25 = 'vIntegerField' def __init__(self, VAR_3=None): VAR_28 = {'class': self.class_name} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_14, self).__init__(VAR_3=VAR_28) class CLASS_15(CLASS_14): VAR_25 = 'vBigIntegerField' class CLASS_16(forms.TextInput): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vCommaSeparatedIntegerField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_16, self).__init__(VAR_3=VAR_28)
from __future__ import unicode_literals import copy from django import forms from django.contrib.admin.templatetags.admin_static import static from django.core.urlresolvers import reverse from django.forms.widgets import RadioFieldRenderer from django.forms.util import flatatt from django.utils.html import escape, format_html, format_html_join, smart_urlquote from django.utils.text import Truncator from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.utils.encoding import force_text from django.utils import six class CLASS_0(forms.SelectMultiple): @property def FUNC_1(self): VAR_26 = ["core.js", "SelectBox.js", "SelectFilter2.js"] return forms.Media(VAR_26=[static("admin/VAR_26/%s" % path) for path in VAR_26]) def __init__(self, VAR_1, VAR_2, VAR_3=None, VAR_4=()): self.verbose_name = VAR_1 self.is_stacked = VAR_2 super(CLASS_0, self).__init__(VAR_3, VAR_4) def FUNC_2(self, VAR_5, VAR_6, VAR_3=None, VAR_4=()): if VAR_3 is None: VAR_3 = {} attrs['class'] = 'selectfilter' if self.is_stacked: VAR_3['class'] += 'stacked' VAR_27 = [super(CLASS_0, self).render(VAR_5, VAR_6, VAR_3, VAR_4)] VAR_27.append('<script type="text/javascript">addEvent(window, "load", function(e) {') VAR_27.append('SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % (VAR_5, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), static('admin/'))) return mark_safe(''.join(VAR_27)) class CLASS_1(forms.DateInput): @property def FUNC_1(self): VAR_26 = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(VAR_26=[static("admin/VAR_26/%s" % path) for path in VAR_26]) def __init__(self, VAR_3=None, VAR_7=None): VAR_28 = {'class': 'vDateField', 'size': '10'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_1, self).__init__(VAR_3=VAR_28, VAR_7=format) class CLASS_2(forms.TimeInput): @property def FUNC_1(self): VAR_26 = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(VAR_26=[static("admin/VAR_26/%s" % path) for path in VAR_26]) def __init__(self, VAR_3=None, VAR_7=None): VAR_28 = {'class': 'vTimeField', 'size': '8'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_2, self).__init__(VAR_3=VAR_28, VAR_7=format) class CLASS_3(forms.SplitDateTimeWidget): def __init__(self, VAR_3=None): VAR_29 = [CLASS_1, CLASS_2] forms.MultiWidget.__init__(self, VAR_29, VAR_3) def FUNC_3(self, VAR_8): return format_html('<p class="datetime">{0} {1}<br />{2} {3}</p>', _('Date:'), VAR_8[0], _('Time:'), VAR_8[1]) class CLASS_4(RadioFieldRenderer): def FUNC_2(self): return format_html('<ul{0}>\n{1}\n</ul>', flatatt(self.attrs), format_html_join('\n', '<li>{0}</li>', ((force_text(w),) for w in self))) class CLASS_5(forms.RadioSelect): VAR_9 = CLASS_4 class CLASS_6(forms.ClearableFileInput): VAR_10 = ('<p class="file-upload">%s</p>' % forms.ClearableFileInput.template_with_initial) VAR_11 = ('<span class="clearable-file-input">%s</span>' % forms.ClearableFileInput.template_with_clear) def FUNC_0(VAR_0): VAR_12 = {} if VAR_0 and hasattr(VAR_0, 'items'): VAR_30 = [] for k, VAR_39 in VAR_0.items(): if callable(VAR_39): VAR_39 = VAR_39() if isinstance(VAR_39, (tuple, list)): VAR_39 = ','.join([str(x) for x in VAR_39]) elif isinstance(VAR_39, bool): VAR_39 = ('0', '1')[VAR_39] else: VAR_39 = six.text_type(VAR_39) VAR_30.append((k, VAR_39)) VAR_12.update(dict(VAR_30)) return VAR_12 class CLASS_7(forms.TextInput): def __init__(self, VAR_13, VAR_14, VAR_3=None, VAR_15=None): self.rel = VAR_13 self.admin_site = VAR_14 self.db = VAR_15 super(CLASS_7, self).__init__(VAR_3) def FUNC_2(self, VAR_5, VAR_6, VAR_3=None): VAR_31 = self.rel.to if VAR_3 is None: VAR_3 = {} VAR_32 = [] if VAR_31 in self.admin_site._registry: VAR_38 = reverse('admin:%s_%s_changelist' % (VAR_31._meta.app_label, VAR_31._meta.model_name), current_app=self.admin_site.name) VAR_12 = self.url_parameters() if VAR_12: VAR_40 = '?' + '&amp;'.join(['%s=%s' % (k, VAR_39) for k, VAR_39 in VAR_12.items()]) else: VAR_40 = '' if "class" not in VAR_3: attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook. VAR_32.append('<a href="%s%s" class="related-lookup" VAR_35="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % (VAR_38, VAR_40, VAR_5)) VAR_32.append('<img src="%s" width="16" height="16" alt="%s" /></a>' % (static('admin/img/selector-search.gif'), _('Lookup'))) VAR_27 = [super(CLASS_7, self).render(VAR_5, VAR_6, VAR_3)] + VAR_32 if VAR_6: VAR_27.append(self.label_for_value(VAR_6)) return mark_safe(''.join(VAR_27)) def FUNC_4(self): return FUNC_0(self.rel.limit_choices_to) def FUNC_5(self): from django.contrib.admin.views.main import TO_FIELD_VAR VAR_12 = self.base_url_parameters() VAR_12.update({TO_FIELD_VAR: self.rel.get_related_field().name}) return VAR_12 def FUNC_6(self, VAR_6): VAR_33 = self.rel.get_related_field().name try: VAR_34 = self.rel.to._default_manager.using(self.db).get(**{VAR_33: VAR_6}) return '&nbsp;<strong>%s</strong>' % escape(Truncator(VAR_34).words(14, truncate='...')) except (ValueError, self.rel.to.DoesNotExist): return '' class CLASS_8(CLASS_7): def FUNC_2(self, VAR_5, VAR_6, VAR_3=None): if VAR_3 is None: VAR_3 = {} if self.rel.to in self.admin_site._registry: VAR_3['class'] = 'vManyToManyRawIdAdminField' if VAR_6: VAR_6 = ','.join([force_text(VAR_39) for VAR_39 in VAR_6]) else: VAR_6 = '' return super(CLASS_8, self).render(VAR_5, VAR_6, VAR_3) def FUNC_5(self): return self.base_url_parameters() def FUNC_6(self, VAR_6): return '' def FUNC_7(self, VAR_16, VAR_17, VAR_5): VAR_6 = VAR_16.get(VAR_5) if VAR_6: return VAR_6.split(',') class CLASS_9(forms.Widget): def __init__(self, VAR_18, VAR_13, VAR_14, VAR_19=None): self.is_hidden = VAR_18.is_hidden self.needs_multipart_form = VAR_18.needs_multipart_form self.attrs = VAR_18.attrs self.choices = VAR_18.choices self.widget = VAR_18 self.rel = VAR_13 if VAR_19 is None: VAR_19 = VAR_13.to in VAR_14._registry self.can_add_related = VAR_19 self.admin_site = VAR_14 def __deepcopy__(self, VAR_20): VAR_34 = copy.copy(self) VAR_34.widget = copy.deepcopy(self.widget, VAR_20) VAR_34.attrs = self.widget.attrs VAR_20[VAR_35(self)] = VAR_34 return VAR_34 @property def FUNC_1(self): return self.widget.media def FUNC_2(self, VAR_5, VAR_6, *VAR_21, **VAR_22): VAR_31 = self.rel.to VAR_36 = (VAR_31._meta.app_label, VAR_31._meta.model_name) self.widget.choices = self.choices VAR_27 = [self.widget.render(VAR_5, VAR_6, *VAR_21, **VAR_22)] if self.can_add_related: VAR_38 = reverse('admin:%s_%s_add' % VAR_36, current_app=self.admin_site.name) VAR_27.append('<a href="%s" class="add-another" VAR_35="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % (VAR_38, VAR_5)) VAR_27.append('<img src="%s" width="10" height="10" alt="%s"/></a>' % (static('admin/img/icon_addlink.gif'), _('Add Another'))) return mark_safe(''.join(VAR_27)) self.attrs = self.widget.build_attrs(VAR_23=None, **VAR_22) return self.attrs def FUNC_7(self, VAR_16, VAR_17, VAR_5): return self.widget.value_from_datadict(VAR_16, VAR_17, VAR_5) def FUNC_9(self, VAR_24): return self.widget.id_for_label(VAR_24) class CLASS_10(forms.Textarea): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vLargeTextField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_10, self).__init__(VAR_3=VAR_28) class CLASS_11(forms.TextInput): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vTextField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_11, self).__init__(VAR_3=VAR_28) class CLASS_12(forms.EmailInput): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vTextField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_12, self).__init__(VAR_3=VAR_28) class CLASS_13(forms.URLInput): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vURLField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_13, self).__init__(VAR_3=VAR_28) def FUNC_2(self, VAR_5, VAR_6, VAR_3=None): VAR_37 = super(CLASS_13, self).render(VAR_5, VAR_6, VAR_3) if VAR_6: VAR_6 = force_text(self._format_value(VAR_6)) VAR_28 = {'href': smart_urlquote(VAR_6)} VAR_37 = format_html( '<p class="url">{0} <a{1}>{2}</a><br />{3} {4}</p>', _('Currently:'), flatatt(VAR_28), VAR_6, _('Change:'), VAR_37 ) return VAR_37 class CLASS_14(forms.TextInput): VAR_25 = 'vIntegerField' def __init__(self, VAR_3=None): VAR_28 = {'class': self.class_name} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_14, self).__init__(VAR_3=VAR_28) class CLASS_15(CLASS_14): VAR_25 = 'vBigIntegerField' class CLASS_16(forms.TextInput): def __init__(self, VAR_3=None): VAR_28 = {'class': 'vCommaSeparatedIntegerField'} if VAR_3 is not None: VAR_28.update(VAR_3) super(CLASS_16, self).__init__(VAR_3=VAR_28)
[ 5, 7, 19, 20, 24, 32, 37, 46, 47, 51, 53, 58, 64, 66, 71, 77, 84, 85, 87, 92, 100, 103, 109, 124, 131, 142, 149, 154, 162, 163, 172, 175, 181, 189, 199, 206, 209, 212, 217, 218, 231, 232, 236, 238, 245, 249, 257, 258, 264, 269, 272, 275, 282, 289, 296, 303, 315, 316, 319, 325, 328, 335, 1, 2, 3, 22, 23, 24, 25, 26, 27, 79, 80, 81, 111, 112, 113, 114, 133, 134, 135, 136, 191, 192, 193, 194, 220, 221, 222, 223, 95, 265, 266 ]
[ 5, 7, 19, 20, 24, 32, 37, 46, 47, 51, 53, 58, 64, 66, 71, 77, 84, 85, 87, 92, 100, 103, 109, 124, 131, 142, 149, 154, 162, 163, 172, 175, 181, 189, 199, 206, 209, 212, 217, 218, 231, 232, 236, 238, 245, 249, 257, 258, 264, 269, 272, 275, 282, 289, 296, 303, 315, 316, 319, 325, 328, 335, 1, 2, 3, 22, 23, 24, 25, 26, 27, 79, 80, 81, 111, 112, 113, 114, 133, 134, 135, 136, 191, 192, 193, 194, 220, 221, 222, 223, 95, 265, 266 ]
5CWE-94
from dataclasses import asdict from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, cast import httpx from ..client import AuthenticatedClient, Client from ..errors import ApiResponseError from ..models.a_model import AModel from ..models.an_enum import AnEnum from ..models.body_upload_file_tests_upload_post import BodyUploadFileTestsUploadPost from ..models.http_validation_error import HTTPValidationError async def get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime], ) -> Union[ List[AModel], HTTPValidationError, ]: """ Get a list of things """ url = "{}/tests/".format(client.base_url,) headers: Dict[str, Any] = client.get_headers() json_an_enum_value = [] for an_enum_value_item_data in an_enum_value: an_enum_value_item = an_enum_value_item_data.value json_an_enum_value.append(an_enum_value_item) if isinstance(some_date, date): json_some_date = some_date.isoformat() else: json_some_date = some_date.isoformat() params: Dict[str, Any] = { "an_enum_value": json_an_enum_value, "some_date": json_some_date, } async with httpx.AsyncClient() as _client: response = await _client.get(url=url, headers=headers, params=params,) if response.status_code == 200: return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], response.json())] if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) async def upload_file_tests_upload_post( *, client: Client, multipart_data: BodyUploadFileTestsUploadPost, keep_alive: Optional[bool] = None, ) -> Union[ None, HTTPValidationError, ]: """ Upload a file """ url = "{}/tests/upload".format(client.base_url,) headers: Dict[str, Any] = client.get_headers() if keep_alive is not None: headers["keep-alive"] = keep_alive async with httpx.AsyncClient() as _client: response = await _client.post(url=url, headers=headers, files=multipart_data.to_dict(),) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) async def json_body_tests_json_body_post( *, client: Client, json_body: AModel, ) -> Union[ None, HTTPValidationError, ]: """ Try sending a JSON body """ url = "{}/tests/json_body".format(client.base_url,) headers: Dict[str, Any] = client.get_headers() json_json_body = json_body.to_dict() async with httpx.AsyncClient() as _client: response = await _client.post(url=url, headers=headers, json=json_json_body,) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response)
import datetime from dataclasses import asdict, field from typing import Any, Dict, List, Optional, Union, cast import httpx from ..client import AuthenticatedClient, Client from ..errors import ApiResponseError from ..models.a_model import AModel from ..models.an_enum import AnEnum from ..models.body_upload_file_tests_upload_post import BodyUploadFileTestsUploadPost from ..models.http_validation_error import HTTPValidationError async def get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[datetime.date, datetime.datetime], ) -> Union[ List[AModel], HTTPValidationError, ]: """ Get a list of things """ url = "{}/tests/".format(client.base_url,) headers: Dict[str, Any] = client.get_headers() json_an_enum_value = [] for an_enum_value_item_data in an_enum_value: an_enum_value_item = an_enum_value_item_data.value json_an_enum_value.append(an_enum_value_item) if isinstance(some_date, datetime.date): json_some_date = some_date.isoformat() else: json_some_date = some_date.isoformat() params: Dict[str, Any] = { "an_enum_value": json_an_enum_value, "some_date": json_some_date, } async with httpx.AsyncClient() as _client: response = await _client.get(url=url, headers=headers, params=params,) if response.status_code == 200: return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], response.json())] if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) async def upload_file_tests_upload_post( *, client: Client, multipart_data: BodyUploadFileTestsUploadPost, keep_alive: Optional[bool] = None, ) -> Union[ None, HTTPValidationError, ]: """ Upload a file """ url = "{}/tests/upload".format(client.base_url,) headers: Dict[str, Any] = client.get_headers() if keep_alive is not None: headers["keep-alive"] = keep_alive async with httpx.AsyncClient() as _client: response = await _client.post(url=url, headers=headers, files=multipart_data.to_dict(),) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) async def json_body_tests_json_body_post( *, client: Client, json_body: AModel, ) -> Union[ None, HTTPValidationError, ]: """ Try sending a JSON body """ url = "{}/tests/json_body".format(client.base_url,) headers: Dict[str, Any] = client.get_headers() json_json_body = json_body.to_dict() async with httpx.AsyncClient() as _client: response = await _client.post(url=url, headers=headers, json=json_json_body,) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) async def test_defaults_tests_test_defaults_post( *, client: Client, json_body: Dict[Any, Any], string_prop: Optional[str] = "the default string", datetime_prop: Optional[datetime.datetime] = datetime.datetime(1010, 10, 10, 0, 0), date_prop: Optional[datetime.date] = datetime.date(1010, 10, 10), float_prop: Optional[float] = 3.14, int_prop: Optional[int] = 7, boolean_prop: Optional[bool] = False, list_prop: Optional[List[AnEnum]] = field( default_factory=lambda: cast(Optional[List[AnEnum]], [AnEnum.FIRST_VALUE, AnEnum.SECOND_VALUE]) ), union_prop: Optional[Union[Optional[float], Optional[str]]] = "not a float", enum_prop: Optional[AnEnum] = None, ) -> Union[ None, HTTPValidationError, ]: """ """ url = "{}/tests/test_defaults".format(client.base_url,) headers: Dict[str, Any] = client.get_headers() json_datetime_prop = datetime_prop.isoformat() if datetime_prop else None json_date_prop = date_prop.isoformat() if date_prop else None if list_prop is None: json_list_prop = None else: json_list_prop = [] for list_prop_item_data in list_prop: list_prop_item = list_prop_item_data.value json_list_prop.append(list_prop_item) if union_prop is None: json_union_prop: Optional[Union[Optional[float], Optional[str]]] = None elif isinstance(union_prop, float): json_union_prop = union_prop else: json_union_prop = union_prop json_enum_prop = enum_prop.value if enum_prop else None params: Dict[str, Any] = {} if string_prop is not None: params["string_prop"] = string_prop if datetime_prop is not None: params["datetime_prop"] = json_datetime_prop if date_prop is not None: params["date_prop"] = json_date_prop if float_prop is not None: params["float_prop"] = float_prop if int_prop is not None: params["int_prop"] = int_prop if boolean_prop is not None: params["boolean_prop"] = boolean_prop if list_prop is not None: params["list_prop"] = json_list_prop if union_prop is not None: params["union_prop"] = json_union_prop if enum_prop is not None: params["enum_prop"] = json_enum_prop json_json_body = json_body async with httpx.AsyncClient() as _client: response = await _client.post(url=url, headers=headers, json=json_json_body, params=params,) if response.status_code == 200: return None if response.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response)
remote_code_execution
{ "code": [ "from dataclasses import asdict", "from datetime import date, datetime", " *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],", " if isinstance(some_date, date):" ], "line_no": [ 1, 2, 16, 32 ] }
{ "code": [ "import datetime", "from dataclasses import asdict, field", " *, client: Client, an_enum_value: List[AnEnum], some_date: Union[datetime.date, datetime.datetime],", " if isinstance(some_date, datetime.date):", "async def test_defaults_tests_test_defaults_post(", " *,", " client: Client,", " json_body: Dict[Any, Any],", " string_prop: Optional[str] = \"the default string\",", " datetime_prop: Optional[datetime.datetime] = datetime.datetime(1010, 10, 10, 0, 0),", " date_prop: Optional[datetime.date] = datetime.date(1010, 10, 10),", " float_prop: Optional[float] = 3.14,", " int_prop: Optional[int] = 7,", " boolean_prop: Optional[bool] = False,", " list_prop: Optional[List[AnEnum]] = field(", " default_factory=lambda: cast(Optional[List[AnEnum]], [AnEnum.FIRST_VALUE, AnEnum.SECOND_VALUE])", " ),", " union_prop: Optional[Union[Optional[float], Optional[str]]] = \"not a float\",", " enum_prop: Optional[AnEnum] = None,", ") -> Union[", " None, HTTPValidationError,", "]:", " \"\"\" \"\"\"", " url = \"{}/tests/test_defaults\".format(client.base_url,)", " headers: Dict[str, Any] = client.get_headers()", " json_datetime_prop = datetime_prop.isoformat() if datetime_prop else None", " json_date_prop = date_prop.isoformat() if date_prop else None", " if list_prop is None:", " json_list_prop = None", " else:", " json_list_prop = []", " for list_prop_item_data in list_prop:", " list_prop_item = list_prop_item_data.value", " json_list_prop.append(list_prop_item)", " if union_prop is None:", " json_union_prop: Optional[Union[Optional[float], Optional[str]]] = None", " elif isinstance(union_prop, float):", " json_union_prop = union_prop", " else:", " json_union_prop = union_prop", " json_enum_prop = enum_prop.value if enum_prop else None", " params: Dict[str, Any] = {}", " if string_prop is not None:", " params[\"string_prop\"] = string_prop", " if datetime_prop is not None:", " params[\"datetime_prop\"] = json_datetime_prop", " if date_prop is not None:", " params[\"date_prop\"] = json_date_prop", " if float_prop is not None:", " params[\"float_prop\"] = float_prop", " if int_prop is not None:", " params[\"int_prop\"] = int_prop", " if boolean_prop is not None:", " params[\"boolean_prop\"] = boolean_prop", " if list_prop is not None:", " params[\"list_prop\"] = json_list_prop", " if union_prop is not None:", " params[\"union_prop\"] = json_union_prop", " if enum_prop is not None:", " params[\"enum_prop\"] = json_enum_prop", " json_json_body = json_body", " async with httpx.AsyncClient() as _client:", " response = await _client.post(url=url, headers=headers, json=json_json_body, params=params,)", " if response.status_code == 200:", " return None", " if response.status_code == 422:", " return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json()))", " else:", " raise ApiResponseError(response=response)" ], "line_no": [ 1, 2, 16, 32, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 121, 122, 124, 126, 128, 130, 131, 132, 133, 134, 135, 137, 139, 140, 141, 142, 143, 144, 146, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 168, 170, 171, 173, 174, 175, 176, 177, 178 ] }
from dataclasses import asdict from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, cast import httpx from ..client import AuthenticatedClient, Client from ..errors import ApiResponseError from ..models.a_model import AModel from ..models.an_enum import AnEnum from ..models.body_upload_file_tests_upload_post import BodyUploadFileTestsUploadPost from ..models.http_validation_error import HTTPValidationError async def FUNC_0( *, VAR_0: Client, VAR_1: List[AnEnum], VAR_2: Union[date, datetime], ) -> Union[ List[AModel], HTTPValidationError, ]: VAR_6 = "{}/tests/".format(VAR_0.base_url,) VAR_12: Dict[str, Any] = VAR_0.get_headers() VAR_7 = [] for an_enum_value_item_data in VAR_1: VAR_9 = an_enum_value_item_data.value VAR_7.append(VAR_9) if isinstance(VAR_2, date): VAR_10 = VAR_2.isoformat() else: VAR_10 = VAR_2.isoformat() params: Dict[str, Any] = { "an_enum_value": VAR_7, "some_date": VAR_10, } async with httpx.AsyncClient() as _client: VAR_11 = await _client.get(VAR_6=url, VAR_12=headers, params=params,) if VAR_11.status_code == 200: return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], VAR_11.json())] if VAR_11.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_11.json())) else: raise ApiResponseError(VAR_11=response) async def FUNC_1( *, VAR_0: Client, VAR_3: BodyUploadFileTestsUploadPost, VAR_4: Optional[bool] = None, ) -> Union[ None, HTTPValidationError, ]: VAR_6 = "{}/tests/upload".format(VAR_0.base_url,) VAR_12: Dict[str, Any] = VAR_0.get_headers() if VAR_4 is not None: VAR_12["keep-alive"] = VAR_4 async with httpx.AsyncClient() as _client: VAR_11 = await _client.post(VAR_6=url, VAR_12=headers, files=VAR_3.to_dict(),) if VAR_11.status_code == 200: return None if VAR_11.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_11.json())) else: raise ApiResponseError(VAR_11=response) async def FUNC_2( *, VAR_0: Client, VAR_5: AModel, ) -> Union[ None, HTTPValidationError, ]: VAR_6 = "{}/tests/json_body".format(VAR_0.base_url,) VAR_12: Dict[str, Any] = VAR_0.get_headers() VAR_8 = VAR_5.to_dict() async with httpx.AsyncClient() as _client: VAR_11 = await _client.post(VAR_6=url, VAR_12=headers, json=VAR_8,) if VAR_11.status_code == 200: return None if VAR_11.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_11.json())) else: raise ApiResponseError(VAR_11=response)
import datetime from dataclasses import asdict, field from typing import Any, Dict, List, Optional, Union, cast import httpx from ..client import AuthenticatedClient, Client from ..errors import ApiResponseError from ..models.a_model import AModel from ..models.an_enum import AnEnum from ..models.body_upload_file_tests_upload_post import BodyUploadFileTestsUploadPost from ..models.http_validation_error import HTTPValidationError async def FUNC_0( *, VAR_0: Client, VAR_1: List[AnEnum], VAR_2: Union[datetime.date, datetime.datetime], ) -> Union[ List[AModel], HTTPValidationError, ]: VAR_15 = "{}/tests/".format(VAR_0.base_url,) VAR_24: Dict[str, Any] = VAR_0.get_headers() VAR_16 = [] for an_enum_value_item_data in VAR_1: VAR_21 = an_enum_value_item_data.value VAR_16.append(VAR_21) if isinstance(VAR_2, datetime.date): VAR_22 = VAR_2.isoformat() else: VAR_22 = VAR_2.isoformat() VAR_26: Dict[str, Any] = { "an_enum_value": VAR_16, "some_date": VAR_22, } async with httpx.AsyncClient() as _client: VAR_23 = await _client.get(VAR_15=url, VAR_24=headers, VAR_26=params,) if VAR_23.status_code == 200: return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], VAR_23.json())] if VAR_23.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_23.json())) else: raise ApiResponseError(VAR_23=response) async def FUNC_1( *, VAR_0: Client, VAR_3: BodyUploadFileTestsUploadPost, VAR_4: Optional[bool] = None, ) -> Union[ None, HTTPValidationError, ]: VAR_15 = "{}/tests/upload".format(VAR_0.base_url,) VAR_24: Dict[str, Any] = VAR_0.get_headers() if VAR_4 is not None: VAR_24["keep-alive"] = VAR_4 async with httpx.AsyncClient() as _client: VAR_23 = await _client.post(VAR_15=url, VAR_24=headers, files=VAR_3.to_dict(),) if VAR_23.status_code == 200: return None if VAR_23.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_23.json())) else: raise ApiResponseError(VAR_23=response) async def FUNC_2( *, VAR_0: Client, VAR_5: AModel, ) -> Union[ None, HTTPValidationError, ]: VAR_15 = "{}/tests/json_body".format(VAR_0.base_url,) VAR_24: Dict[str, Any] = VAR_0.get_headers() VAR_17 = VAR_5.to_dict() async with httpx.AsyncClient() as _client: VAR_23 = await _client.post(VAR_15=url, VAR_24=headers, json=VAR_17,) if VAR_23.status_code == 200: return None if VAR_23.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_23.json())) else: raise ApiResponseError(VAR_23=response) async def FUNC_3( *, VAR_0: Client, VAR_5: Dict[Any, Any], VAR_6: Optional[str] = "the default string", VAR_7: Optional[datetime.datetime] = datetime.datetime(1010, 10, 10, 0, 0), VAR_8: Optional[datetime.date] = datetime.date(1010, 10, 10), VAR_9: Optional[float] = 3.14, VAR_10: Optional[int] = 7, VAR_11: Optional[bool] = False, VAR_12: Optional[List[AnEnum]] = field( default_factory=lambda: cast(Optional[List[AnEnum]], [AnEnum.FIRST_VALUE, AnEnum.SECOND_VALUE]) ), VAR_13: Optional[Union[Optional[float], Optional[str]]] = "not a float", VAR_14: Optional[AnEnum] = None, ) -> Union[ None, HTTPValidationError, ]: VAR_15 = "{}/tests/test_defaults".format(VAR_0.base_url,) VAR_24: Dict[str, Any] = VAR_0.get_headers() VAR_18 = VAR_7.isoformat() if VAR_7 else None VAR_19 = VAR_8.isoformat() if VAR_8 else None if VAR_12 is None: VAR_25 = None else: VAR_25 = [] for list_prop_item_data in VAR_12: VAR_27 = list_prop_item_data.value VAR_25.append(VAR_27) if VAR_13 is None: VAR_28: Optional[Union[Optional[float], Optional[str]]] = None elif isinstance(VAR_13, float): VAR_28 = VAR_13 else: VAR_28 = VAR_13 VAR_20 = VAR_14.value if VAR_14 else None VAR_26: Dict[str, Any] = {} if VAR_6 is not None: VAR_26["string_prop"] = VAR_6 if VAR_7 is not None: VAR_26["datetime_prop"] = VAR_18 if VAR_8 is not None: VAR_26["date_prop"] = VAR_19 if VAR_9 is not None: VAR_26["float_prop"] = VAR_9 if VAR_10 is not None: VAR_26["int_prop"] = VAR_10 if VAR_11 is not None: VAR_26["boolean_prop"] = VAR_11 if VAR_12 is not None: VAR_26["list_prop"] = VAR_25 if VAR_13 is not None: VAR_26["union_prop"] = VAR_28 if VAR_14 is not None: VAR_26["enum_prop"] = VAR_20 VAR_17 = VAR_5 async with httpx.AsyncClient() as _client: VAR_23 = await _client.post(VAR_15=url, VAR_24=headers, json=VAR_17, VAR_26=params,) if VAR_23.status_code == 200: return None if VAR_23.status_code == 422: return HTTPValidationError.from_dict(cast(Dict[str, Any], VAR_23.json())) else: raise ApiResponseError(VAR_23=response)
[ 4, 6, 13, 14, 20, 23, 25, 29, 31, 34, 37, 42, 45, 52, 53, 59, 62, 66, 69, 76, 77, 83, 86, 88, 90, 93, 100, 21, 60, 84 ]
[ 4, 6, 13, 14, 20, 23, 25, 29, 31, 34, 37, 42, 45, 52, 53, 59, 62, 66, 69, 76, 77, 83, 86, 88, 90, 93, 100, 101, 120, 123, 125, 127, 129, 136, 138, 145, 147, 167, 169, 172, 179, 21, 60, 84, 121 ]
3CWE-352
import asyncio import enum import inspect import json from typing import ( Any, Callable, Coroutine, Dict, List, Optional, Sequence, Set, Type, Union, ) from fastapi import params from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.types import DecoratedCallable from fastapi.utils import ( create_cloned_field, create_response_field, generate_operation_id_for_path, get_value_or_default, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import BaseRoute from starlette.routing import Mount as Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): return res.dict( by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } return res async def serialize_response( *, field: Optional[ModelField] = None, response_content: Any, include: Optional[Union[SetIntStr, DictIntStrAny]] = None, exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) else: return jsonable_encoder(response_content) async def run_endpoint_function( *, dependant: Dependant, values: Dict[str, Any], is_coroutine: bool ) -> Any: # Only called by get_request_handler. Has been split into its own function to # facilitate profiling endpoints, since inner functions are harder to profile. assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: return await dependant.call(**values) else: return await run_in_threadpool(dependant.call, **values) def get_request_handler( dependant: Dependant, body_field: Optional[ModelField] = None, status_code: int = 200, response_class: Union[Type[Response], DefaultPlaceholder] = Default(JSONResponse), response_field: Optional[ModelField] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, dependency_overrides_provider: Optional[Any] = None, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.field_info, params.Form) if isinstance(response_class, DefaultPlaceholder): actual_response_class: Type[Response] = response_class.value else: actual_response_class = response_class async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except json.JSONDecodeError as e: raise RequestValidationError([ErrorWrapper(e, ("body", e.pos))], body=e.doc) except Exception as e: raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = await serialize_response( field=response_field, response_content=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, exclude_unset=response_model_exclude_unset, exclude_defaults=response_model_exclude_defaults, exclude_none=response_model_exclude_none, is_coroutine=is_coroutine, ) response = actual_response_class( content=response_data, status_code=status_code, background=background_tasks, # type: ignore # in Starlette ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable[..., Any], *, name: Optional[str] = None, dependency_overrides_provider: Optional[Any] = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path(path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable[..., Any], *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, name: Optional[str] = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), dependency_overrides_provider: Optional[Any] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> None: # normalise enums e.g. http.HTTPStatus if isinstance(status_code, enum.IntEnum): status_code = int(status_code) self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.path_regex, self.path_format, self.param_convertors = compile_path(path) if methods is None: methods = ["GET"] self.methods: Set[str] = set([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: assert ( status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id self.response_field = create_response_field( name=response_name, type_=self.response_model ) # Create a clone of the field, so that a Pydantic submodel is not returned # as is just because it's an instance of a subclass of a more limited class # e.g. UserInDB (containing hashed_password) could be a subclass of User # that doesn't have the hashed_password. But because it's a subclass, it # would pass the validation and be returned as is. # By being a new field, no inheritance will be passed as is. A new model # will be always created. self.secure_cloned_response_field: Optional[ ModelField ] = create_cloned_field(self.response_field) else: self.response_field = None # type: ignore self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "") # if a "form feed" character (page break) is found in the description text, # truncate description text to the content preceding the first "form feed" self.description = self.description.split("\f")[0] self.response_description = response_description self.responses = responses or {} response_fields = {} for additional_status_code, response in self.responses.items(): assert isinstance(response, dict), "An additional response must be a dict" model = response.get("model") if model: assert ( additional_status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_response_field(name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields else: self.response_fields = {} self.deprecated = deprecated self.operation_id = operation_id self.response_model_include = response_model_include self.response_model_exclude = response_model_exclude self.response_model_by_alias = response_model_by_alias self.response_model_exclude_unset = response_model_exclude_unset self.response_model_exclude_defaults = response_model_exclude_defaults self.response_model_exclude_none = response_model_exclude_none self.include_in_schema = include_in_schema self.response_class = response_class assert callable(endpoint), "An endpoint must be a callable" self.dependant = get_dependant(path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) self.body_field = get_body_field(dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.secure_cloned_response_field, response_model_include=self.response_model_include, response_model_exclude=self.response_model_exclude, response_model_by_alias=self.response_model_by_alias, response_model_exclude_unset=self.response_model_exclude_unset, response_model_exclude_defaults=self.response_model_exclude_defaults, response_model_exclude_none=self.response_model_exclude_none, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, *, prefix: str = "", tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, routes: Optional[List[routing.BaseRoute]] = None, redirect_slashes: bool = True, default: Optional[ASGIApp] = None, dependency_overrides_provider: Optional[Any] = None, route_class: Type[APIRoute] = APIRoute, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, ) -> None: super().__init__( routes=routes, # type: ignore # in Starlette redirect_slashes=redirect_slashes, default=default, # type: ignore # in Starlette on_startup=on_startup, # type: ignore # in Starlette on_shutdown=on_shutdown, # type: ignore # in Starlette ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[str] = tags or [] self.dependencies = list(dependencies or []) or [] self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class def add_api_route( self, path: str, endpoint: Callable[..., Any], *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None ) -> None: route = APIWebSocketRoute( path, endpoint=endpoint, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: str, name: Optional[str] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) # type: ignore # in Starlette self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def put( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def post( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def delete( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def options( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def head( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def patch( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def trace( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, )
import asyncio import email.message import enum import inspect import json from typing import ( Any, Callable, Coroutine, Dict, List, Optional, Sequence, Set, Type, Union, ) from fastapi import params from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.types import DecoratedCallable from fastapi.utils import ( create_cloned_field, create_response_field, generate_operation_id_for_path, get_value_or_default, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField, Undefined from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import BaseRoute from starlette.routing import Mount as Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): return res.dict( by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } return res async def serialize_response( *, field: Optional[ModelField] = None, response_content: Any, include: Optional[Union[SetIntStr, DictIntStrAny]] = None, exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) else: return jsonable_encoder(response_content) async def run_endpoint_function( *, dependant: Dependant, values: Dict[str, Any], is_coroutine: bool ) -> Any: # Only called by get_request_handler. Has been split into its own function to # facilitate profiling endpoints, since inner functions are harder to profile. assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: return await dependant.call(**values) else: return await run_in_threadpool(dependant.call, **values) def get_request_handler( dependant: Dependant, body_field: Optional[ModelField] = None, status_code: int = 200, response_class: Union[Type[Response], DefaultPlaceholder] = Default(JSONResponse), response_field: Optional[ModelField] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, dependency_overrides_provider: Optional[Any] = None, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.field_info, params.Form) if isinstance(response_class, DefaultPlaceholder): actual_response_class: Type[Response] = response_class.value else: actual_response_class = response_class async def app(request: Request) -> Response: try: body: Any = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: json_body: Any = Undefined content_type_value = request.headers.get("content-type") if content_type_value: message = email.message.Message() message["content-type"] = content_type_value if message.get_content_maintype() == "application": subtype = message.get_content_subtype() if subtype == "json" or subtype.endswith("+json"): json_body = await request.json() if json_body != Undefined: body = json_body else: body = body_bytes except json.JSONDecodeError as e: raise RequestValidationError([ErrorWrapper(e, ("body", e.pos))], body=e.doc) except Exception as e: raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = await serialize_response( field=response_field, response_content=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, exclude_unset=response_model_exclude_unset, exclude_defaults=response_model_exclude_defaults, exclude_none=response_model_exclude_none, is_coroutine=is_coroutine, ) response = actual_response_class( content=response_data, status_code=status_code, background=background_tasks, # type: ignore # in Starlette ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable[..., Any], *, name: Optional[str] = None, dependency_overrides_provider: Optional[Any] = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path(path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable[..., Any], *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, name: Optional[str] = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), dependency_overrides_provider: Optional[Any] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> None: # normalise enums e.g. http.HTTPStatus if isinstance(status_code, enum.IntEnum): status_code = int(status_code) self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.path_regex, self.path_format, self.param_convertors = compile_path(path) if methods is None: methods = ["GET"] self.methods: Set[str] = set([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: assert ( status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id self.response_field = create_response_field( name=response_name, type_=self.response_model ) # Create a clone of the field, so that a Pydantic submodel is not returned # as is just because it's an instance of a subclass of a more limited class # e.g. UserInDB (containing hashed_password) could be a subclass of User # that doesn't have the hashed_password. But because it's a subclass, it # would pass the validation and be returned as is. # By being a new field, no inheritance will be passed as is. A new model # will be always created. self.secure_cloned_response_field: Optional[ ModelField ] = create_cloned_field(self.response_field) else: self.response_field = None # type: ignore self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "") # if a "form feed" character (page break) is found in the description text, # truncate description text to the content preceding the first "form feed" self.description = self.description.split("\f")[0] self.response_description = response_description self.responses = responses or {} response_fields = {} for additional_status_code, response in self.responses.items(): assert isinstance(response, dict), "An additional response must be a dict" model = response.get("model") if model: assert ( additional_status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_response_field(name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields else: self.response_fields = {} self.deprecated = deprecated self.operation_id = operation_id self.response_model_include = response_model_include self.response_model_exclude = response_model_exclude self.response_model_by_alias = response_model_by_alias self.response_model_exclude_unset = response_model_exclude_unset self.response_model_exclude_defaults = response_model_exclude_defaults self.response_model_exclude_none = response_model_exclude_none self.include_in_schema = include_in_schema self.response_class = response_class assert callable(endpoint), "An endpoint must be a callable" self.dependant = get_dependant(path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) self.body_field = get_body_field(dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.secure_cloned_response_field, response_model_include=self.response_model_include, response_model_exclude=self.response_model_exclude, response_model_by_alias=self.response_model_by_alias, response_model_exclude_unset=self.response_model_exclude_unset, response_model_exclude_defaults=self.response_model_exclude_defaults, response_model_exclude_none=self.response_model_exclude_none, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, *, prefix: str = "", tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, routes: Optional[List[routing.BaseRoute]] = None, redirect_slashes: bool = True, default: Optional[ASGIApp] = None, dependency_overrides_provider: Optional[Any] = None, route_class: Type[APIRoute] = APIRoute, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, ) -> None: super().__init__( routes=routes, # type: ignore # in Starlette redirect_slashes=redirect_slashes, default=default, # type: ignore # in Starlette on_startup=on_startup, # type: ignore # in Starlette on_shutdown=on_shutdown, # type: ignore # in Starlette ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[str] = tags or [] self.dependencies = list(dependencies or []) or [] self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class def add_api_route( self, path: str, endpoint: Callable[..., Any], *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None ) -> None: route = APIWebSocketRoute( path, endpoint=endpoint, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: str, name: Optional[str] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) # type: ignore # in Starlette self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def put( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def post( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def delete( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def options( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def head( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def patch( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, ) def trace( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: int = 200, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, )
xsrf
{ "code": [ "from pydantic.fields import ModelField", " body = None", " body = await request.json()" ], "line_no": [ 39, 177, 184 ] }
{ "code": [ "import email.message", "from pydantic.fields import ModelField, Undefined", " body: Any = None", " json_body: Any = Undefined", " content_type_value = request.headers.get(\"content-type\")", " if content_type_value:", " message = email.message.Message()", " message[\"content-type\"] = content_type_value", " if message.get_content_maintype() == \"application\":", " subtype = message.get_content_subtype()", " if subtype == \"json\" or subtype.endswith(\"+json\"):", " json_body = await request.json()", " if json_body != Undefined:", " body = json_body", " else:", " body = body_bytes" ], "line_no": [ 2, 40, 178, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197 ] }
import asyncio import enum import inspect import json from typing import ( Any, Callable, Coroutine, Dict, List, Optional, Sequence, Set, Type, Union, ) from fastapi import params from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.types import DecoratedCallable from fastapi.utils import ( create_cloned_field, create_response_field, generate_operation_id_for_path, get_value_or_default, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import BaseRoute from starlette.routing import Mount as Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def FUNC_0( VAR_0: Any, *, VAR_1: bool, VAR_2: bool = False, VAR_3: bool = False, ) -> Any: if isinstance(VAR_0, BaseModel): return VAR_0.dict( VAR_8=True, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) elif isinstance(VAR_0, list): return [ FUNC_0( item, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) for item in VAR_0 ] elif isinstance(VAR_0, dict): return { k: FUNC_0( v, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) for k, v in VAR_0.items() } return VAR_0 async def FUNC_1( *, VAR_4: Optional[ModelField] = None, VAR_5: Any, VAR_6: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_7: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_8: bool = True, VAR_1: bool = False, VAR_2: bool = False, VAR_3: bool = False, VAR_9: bool = True, ) -> Any: if VAR_4: VAR_51 = [] VAR_5 = FUNC_0( VAR_5, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) if VAR_9: VAR_67, VAR_68 = VAR_4.validate(VAR_5, {}, loc=("response",)) else: VAR_67, VAR_68 = await run_in_threadpool( VAR_4.validate, VAR_5, {}, loc=("response",) ) if isinstance(VAR_68, ErrorWrapper): VAR_51.append(VAR_68) elif isinstance(VAR_68, list): VAR_51.extend(VAR_68) if VAR_51: raise ValidationError(VAR_51, VAR_4.type_) return jsonable_encoder( VAR_67, VAR_6=include, VAR_7=exclude, VAR_8=by_alias, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) else: return jsonable_encoder(VAR_5) async def FUNC_2( *, VAR_10: Dependant, VAR_11: Dict[str, Any], VAR_9: bool ) -> Any: assert VAR_10.call is not None, "dependant.call must be a function" if VAR_9: return await VAR_10.call(**VAR_11) else: return await run_in_threadpool(VAR_10.call, **VAR_11) def FUNC_3( VAR_10: Dependant, VAR_12: Optional[ModelField] = None, VAR_13: int = 200, VAR_14: Union[Type[Response], DefaultPlaceholder] = Default(JSONResponse), VAR_15: Optional[ModelField] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_22: Optional[Any] = None, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert VAR_10.call is not None, "dependant.call must be a function" VAR_9 = asyncio.iscoroutinefunction(VAR_10.call) VAR_23 = VAR_12 and isinstance(VAR_12.field_info, params.Form) if isinstance(VAR_14, DefaultPlaceholder): VAR_52: Type[Response] = VAR_14.value else: VAR_52 = VAR_14 async def FUNC_5(VAR_24: Request) -> Response: try: VAR_69 = None if VAR_12: if VAR_23: VAR_69 = await VAR_24.form() else: VAR_77 = await VAR_24.body() if VAR_77: VAR_69 = await VAR_24.json() except json.JSONDecodeError as e: raise RequestValidationError([ErrorWrapper(e, ("body", e.pos))], VAR_69=e.doc) except Exception as e: raise HTTPException( VAR_13=400, detail="There was an error parsing the body" ) from e VAR_53 = await solve_dependencies( VAR_24=request, VAR_10=dependant, VAR_69=body, VAR_22=dependency_overrides_provider, ) VAR_11, VAR_51, VAR_54, VAR_55, VAR_56 = VAR_53 if VAR_51: raise RequestValidationError(VAR_51, VAR_69=body) else: VAR_70 = await FUNC_2( VAR_10=dependant, VAR_11=values, VAR_9=is_coroutine ) if isinstance(VAR_70, Response): if VAR_70.background is None: VAR_70.background = VAR_54 return VAR_70 VAR_71 = await FUNC_1( VAR_4=VAR_15, VAR_5=VAR_70, VAR_6=VAR_16, VAR_7=VAR_17, VAR_8=VAR_18, VAR_1=VAR_19, VAR_2=VAR_20, VAR_3=VAR_21, VAR_9=is_coroutine, ) VAR_72 = VAR_52( content=VAR_71, VAR_13=status_code, background=VAR_54, # type: ignore # in Starlette ) VAR_72.headers.raw.extend(VAR_55.headers.raw) if VAR_55.status_code: VAR_72.status_code = VAR_55.status_code return VAR_72 return FUNC_5 def FUNC_4( VAR_10: Dependant, VAR_22: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def FUNC_5(VAR_25: WebSocket) -> None: VAR_53 = await solve_dependencies( VAR_24=VAR_25, VAR_10=dependant, VAR_22=dependency_overrides_provider, ) VAR_11, VAR_51, VAR_56, VAR_57, VAR_58 = VAR_53 if VAR_51: await VAR_25.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(VAR_51) assert VAR_10.call is not None, "dependant.call must be a function" await VAR_10.call(**VAR_11) return FUNC_5 class CLASS_0(routing.WebSocketRoute): def __init__( self, VAR_26: str, VAR_27: Callable[..., Any], *, VAR_28: Optional[str] = None, VAR_22: Optional[Any] = None, ) -> None: self.path = VAR_26 self.endpoint = VAR_27 self.name = get_name(VAR_27) if VAR_28 is None else VAR_28 self.dependant = get_dependant(VAR_26=path, call=self.endpoint) self.app = websocket_session( FUNC_4( VAR_10=self.dependant, VAR_22=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path(VAR_26) class CLASS_1(routing.Route): def __init__( self, VAR_26: str, VAR_27: Callable[..., Any], *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_28: Optional[str] = None, VAR_37: Optional[Union[Set[str], List[str]]] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), VAR_22: Optional[Any] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> None: if isinstance(VAR_13, enum.IntEnum): VAR_13 = int(VAR_13) self.path = VAR_26 self.endpoint = VAR_27 self.name = get_name(VAR_27) if VAR_28 is None else VAR_28 self.path_regex, self.path_format, self.param_convertors = compile_path(VAR_26) if VAR_37 is None: VAR_37 = ["GET"] self.methods: Set[str] = set([method.upper() for method in VAR_37]) self.unique_id = generate_operation_id_for_path( VAR_28=self.name, VAR_26=self.path_format, method=list(VAR_37)[0] ) self.response_model = VAR_29 if self.response_model: assert ( VAR_13 not in STATUS_CODES_WITH_NO_BODY ), f"Status code {VAR_13} must not have a VAR_72 body" VAR_73 = "Response_" + self.unique_id self.response_field = create_response_field( VAR_28=VAR_73, type_=self.response_model ) self.secure_cloned_response_field: Optional[ ModelField ] = create_cloned_field(self.response_field) else: self.response_field = None # type: ignore self.secure_cloned_response_field = None self.status_code = VAR_13 self.tags = VAR_30 or [] if VAR_31: self.dependencies = list(VAR_31) else: self.dependencies = [] self.summary = VAR_32 self.description = VAR_33 or inspect.cleandoc(self.endpoint.__doc__ or "") self.description = self.description.split("\f")[0] self.response_description = VAR_34 self.responses = VAR_35 or {} VAR_59 = {} for VAR_75, VAR_72 in self.responses.items(): assert isinstance(VAR_72, dict), "An additional VAR_72 must be a dict" VAR_74 = VAR_72.get("model") if VAR_74: assert ( VAR_75 not in STATUS_CODES_WITH_NO_BODY ), f"Status code {VAR_75} must not have a VAR_72 body" VAR_73 = f"Response_{VAR_75}VAR_56{self.unique_id}" VAR_15 = create_response_field(VAR_28=VAR_73, type_=VAR_74) VAR_59[VAR_75] = VAR_15 if VAR_59: self.response_fields: Dict[Union[int, str], ModelField] = VAR_59 else: self.response_fields = {} self.deprecated = VAR_36 self.operation_id = VAR_38 self.response_model_include = VAR_16 self.response_model_exclude = VAR_17 self.response_model_by_alias = VAR_18 self.response_model_exclude_unset = VAR_19 self.response_model_exclude_defaults = VAR_20 self.response_model_exclude_none = VAR_21 self.include_in_schema = VAR_39 self.response_class = VAR_14 assert callable(VAR_27), "An VAR_27 must be a callable" self.dependant = get_dependant(VAR_26=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, VAR_26=self.path_format), ) self.body_field = get_body_field(VAR_10=self.dependant, VAR_28=self.unique_id) self.dependency_overrides_provider = VAR_22 self.callbacks = VAR_40 self.app = request_response(self.get_route_handler()) def FUNC_6(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: return FUNC_3( VAR_10=self.dependant, VAR_12=self.body_field, VAR_13=self.status_code, VAR_14=self.response_class, VAR_15=self.secure_cloned_response_field, VAR_16=self.response_model_include, VAR_17=self.response_model_exclude, VAR_18=self.response_model_by_alias, VAR_19=self.response_model_exclude_unset, VAR_20=self.response_model_exclude_defaults, VAR_21=self.response_model_exclude_none, VAR_22=self.dependency_overrides_provider, ) class CLASS_2(routing.Router): def __init__( self, *, VAR_41: str = "", VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_42: Type[Response] = Default(JSONResponse), VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_40: Optional[List[BaseRoute]] = None, VAR_43: Optional[List[routing.BaseRoute]] = None, VAR_44: bool = True, VAR_45: Optional[ASGIApp] = None, VAR_22: Optional[Any] = None, VAR_46: Type[CLASS_1] = APIRoute, VAR_47: Optional[Sequence[Callable[[], Any]]] = None, VAR_48: Optional[Sequence[Callable[[], Any]]] = None, VAR_36: Optional[bool] = None, VAR_39: bool = True, ) -> None: super().__init__( VAR_43=routes, # type: ignore # in Starlette VAR_44=redirect_slashes, VAR_45=default, # type: ignore # in Starlette VAR_47=on_startup, # type: ignore # in Starlette VAR_48=on_shutdown, # type: ignore # in Starlette ) if VAR_41: assert VAR_41.startswith("/"), "A VAR_26 VAR_41 must start with '/'" assert not VAR_41.endswith( "/" ), "A VAR_26 VAR_41 must not end with '/', as the VAR_43 will start with '/'" self.prefix = VAR_41 self.tags: List[str] = VAR_30 or [] self.dependencies = list(VAR_31 or []) or [] self.deprecated = VAR_36 self.include_in_schema = VAR_39 self.responses = VAR_35 or {} self.callbacks = VAR_40 or [] self.dependency_overrides_provider = VAR_22 self.route_class = VAR_46 self.default_response_class = VAR_42 def FUNC_7( self, VAR_26: str, VAR_27: Callable[..., Any], *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_37: Optional[Union[Set[str], List[str]]] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), VAR_28: Optional[str] = None, VAR_49: Optional[Type[CLASS_1]] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> None: VAR_46 = VAR_49 or self.route_class VAR_35 = VAR_35 or {} VAR_60 = {**self.responses, **VAR_35} VAR_61 = get_value_or_default( VAR_14, self.default_response_class ) VAR_62 = self.tags.copy() if VAR_30: VAR_62.extend(VAR_30) VAR_63 = self.dependencies.copy() if VAR_31: VAR_63.extend(VAR_31) VAR_64 = self.callbacks.copy() if VAR_40: VAR_64.extend(VAR_40) VAR_65 = VAR_46( self.prefix + VAR_26, VAR_27=endpoint, VAR_29=response_model, VAR_13=status_code, VAR_30=VAR_62, VAR_31=VAR_63, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=VAR_60, VAR_36=deprecated or self.deprecated, VAR_37=methods, VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema and self.include_in_schema, VAR_14=VAR_61, VAR_28=name, VAR_22=self.dependency_overrides_provider, VAR_40=VAR_64, ) self.routes.append(VAR_65) def FUNC_8( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_37: Optional[List[str]] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def FUNC_20(VAR_66: DecoratedCallable) -> DecoratedCallable: self.add_api_route( VAR_26, VAR_66, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=methods, VAR_38=operation_id, VAR_16=VAR_16, VAR_17=VAR_17, VAR_18=VAR_18, VAR_19=VAR_19, VAR_20=VAR_20, VAR_21=VAR_21, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) return VAR_66 return FUNC_20 def FUNC_9( self, VAR_26: str, VAR_27: Callable[..., Any], VAR_28: Optional[str] = None ) -> None: VAR_65 = CLASS_0( VAR_26, VAR_27=endpoint, VAR_28=name, VAR_22=self.dependency_overrides_provider, ) self.routes.append(VAR_65) def VAR_25( self, VAR_26: str, VAR_28: Optional[str] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def FUNC_20(VAR_66: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route(VAR_26, VAR_66, VAR_28=name) return VAR_66 return FUNC_20 def FUNC_11( self, VAR_50: "APIRouter", *, VAR_41: str = "", VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_42: Type[Response] = Default(JSONResponse), VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_40: Optional[List[BaseRoute]] = None, VAR_36: Optional[bool] = None, VAR_39: bool = True, ) -> None: if VAR_41: assert VAR_41.startswith("/"), "A VAR_26 VAR_41 must start with '/'" assert not VAR_41.endswith( "/" ), "A VAR_26 VAR_41 must not end with '/', as the VAR_43 will start with '/'" else: for r in VAR_50.routes: VAR_26 = getattr(r, "path") VAR_28 = getattr(r, "name", "unknown") if VAR_26 is not None and not VAR_26: raise Exception( f"Prefix and VAR_26 cannot be both empty (VAR_26 operation: {VAR_28})" ) if VAR_35 is None: VAR_35 = {} for VAR_65 in VAR_50.routes: if isinstance(VAR_65, CLASS_1): VAR_60 = {**VAR_35, **VAR_65.responses} VAR_76 = get_value_or_default( VAR_65.response_class, VAR_50.default_response_class, VAR_42, self.default_response_class, ) VAR_62 = [] if VAR_30: VAR_62.extend(VAR_30) if VAR_65.tags: VAR_62.extend(VAR_65.tags) VAR_63: List[params.Depends] = [] if VAR_31: VAR_63.extend(VAR_31) if VAR_65.dependencies: VAR_63.extend(VAR_65.dependencies) VAR_64 = [] if VAR_40: VAR_64.extend(VAR_40) if VAR_65.callbacks: VAR_64.extend(VAR_65.callbacks) self.add_api_route( VAR_41 + VAR_65.path, VAR_65.endpoint, VAR_29=VAR_65.response_model, VAR_13=VAR_65.status_code, VAR_30=VAR_62, VAR_31=VAR_63, VAR_32=VAR_65.summary, VAR_33=VAR_65.description, VAR_34=VAR_65.response_description, VAR_35=VAR_60, VAR_36=VAR_65.deprecated or VAR_36 or self.deprecated, VAR_37=VAR_65.methods, VAR_38=VAR_65.operation_id, VAR_16=VAR_65.response_model_include, VAR_17=VAR_65.response_model_exclude, VAR_18=VAR_65.response_model_by_alias, VAR_19=VAR_65.response_model_exclude_unset, VAR_20=VAR_65.response_model_exclude_defaults, VAR_21=VAR_65.response_model_exclude_none, VAR_39=VAR_65.include_in_schema and self.include_in_schema and VAR_39, VAR_14=VAR_76, VAR_28=VAR_65.name, VAR_49=type(VAR_65), VAR_40=VAR_64, ) elif isinstance(VAR_65, routing.Route): VAR_37 = list(VAR_65.methods or []) # type: ignore # in Starlette self.add_route( VAR_41 + VAR_65.path, VAR_65.endpoint, VAR_37=methods, VAR_39=VAR_65.include_in_schema, VAR_28=VAR_65.name, ) elif isinstance(VAR_65, CLASS_0): self.add_api_websocket_route( VAR_41 + VAR_65.path, VAR_65.endpoint, VAR_28=VAR_65.name ) elif isinstance(VAR_65, routing.WebSocketRoute): self.add_websocket_route( VAR_41 + VAR_65.path, VAR_65.endpoint, VAR_28=VAR_65.name ) for handler in VAR_50.on_startup: self.add_event_handler("startup", handler) for handler in VAR_50.on_shutdown: self.add_event_handler("shutdown", handler) def FUNC_12( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["GET"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_13( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["PUT"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_14( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["POST"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_15( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["DELETE"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_16( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["OPTIONS"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_17( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["HEAD"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_18( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["PATCH"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_19( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["TRACE"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, )
import asyncio import email.message import enum import inspect import json from typing import ( Any, Callable, Coroutine, Dict, List, Optional, Sequence, Set, Type, Union, ) from fastapi import params from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.types import DecoratedCallable from fastapi.utils import ( create_cloned_field, create_response_field, generate_operation_id_for_path, get_value_or_default, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField, Undefined from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import BaseRoute from starlette.routing import Mount as Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def FUNC_0( VAR_0: Any, *, VAR_1: bool, VAR_2: bool = False, VAR_3: bool = False, ) -> Any: if isinstance(VAR_0, BaseModel): return VAR_0.dict( VAR_8=True, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) elif isinstance(VAR_0, list): return [ FUNC_0( item, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) for item in VAR_0 ] elif isinstance(VAR_0, dict): return { k: FUNC_0( v, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) for k, v in VAR_0.items() } return VAR_0 async def FUNC_1( *, VAR_4: Optional[ModelField] = None, VAR_5: Any, VAR_6: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_7: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_8: bool = True, VAR_1: bool = False, VAR_2: bool = False, VAR_3: bool = False, VAR_9: bool = True, ) -> Any: if VAR_4: VAR_51 = [] VAR_5 = FUNC_0( VAR_5, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) if VAR_9: VAR_67, VAR_68 = VAR_4.validate(VAR_5, {}, loc=("response",)) else: VAR_67, VAR_68 = await run_in_threadpool( VAR_4.validate, VAR_5, {}, loc=("response",) ) if isinstance(VAR_68, ErrorWrapper): VAR_51.append(VAR_68) elif isinstance(VAR_68, list): VAR_51.extend(VAR_68) if VAR_51: raise ValidationError(VAR_51, VAR_4.type_) return jsonable_encoder( VAR_67, VAR_6=include, VAR_7=exclude, VAR_8=by_alias, VAR_1=exclude_unset, VAR_2=exclude_defaults, VAR_3=exclude_none, ) else: return jsonable_encoder(VAR_5) async def FUNC_2( *, VAR_10: Dependant, VAR_11: Dict[str, Any], VAR_9: bool ) -> Any: assert VAR_10.call is not None, "dependant.call must be a function" if VAR_9: return await VAR_10.call(**VAR_11) else: return await run_in_threadpool(VAR_10.call, **VAR_11) def FUNC_3( VAR_10: Dependant, VAR_12: Optional[ModelField] = None, VAR_13: int = 200, VAR_14: Union[Type[Response], DefaultPlaceholder] = Default(JSONResponse), VAR_15: Optional[ModelField] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_22: Optional[Any] = None, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert VAR_10.call is not None, "dependant.call must be a function" VAR_9 = asyncio.iscoroutinefunction(VAR_10.call) VAR_23 = VAR_12 and isinstance(VAR_12.field_info, params.Form) if isinstance(VAR_14, DefaultPlaceholder): VAR_52: Type[Response] = VAR_14.value else: VAR_52 = VAR_14 async def FUNC_5(VAR_24: Request) -> Response: try: VAR_76: Any = None if VAR_12: if VAR_23: VAR_76 = await VAR_24.form() else: VAR_77 = await VAR_24.body() if VAR_77: VAR_81: Any = Undefined VAR_78 = VAR_24.headers.get("content-type") if VAR_78: VAR_79 = email.message.Message() VAR_79["content-type"] = VAR_78 if VAR_79.get_content_maintype() == "application": VAR_80 = VAR_79.get_content_subtype() if VAR_80 == "json" or VAR_80.endswith("+json"): VAR_81 = await VAR_24.json() if VAR_81 != Undefined: VAR_76 = VAR_81 else: VAR_76 = VAR_77 except json.JSONDecodeError as e: raise RequestValidationError([ErrorWrapper(e, ("body", e.pos))], VAR_76=e.doc) except Exception as e: raise HTTPException( VAR_13=400, detail="There was an error parsing the body" ) from e VAR_53 = await solve_dependencies( VAR_24=request, VAR_10=dependant, VAR_76=body, VAR_22=dependency_overrides_provider, ) VAR_11, VAR_51, VAR_54, VAR_55, VAR_56 = VAR_53 if VAR_51: raise RequestValidationError(VAR_51, VAR_76=body) else: VAR_69 = await FUNC_2( VAR_10=dependant, VAR_11=values, VAR_9=is_coroutine ) if isinstance(VAR_69, Response): if VAR_69.background is None: VAR_69.background = VAR_54 return VAR_69 VAR_70 = await FUNC_1( VAR_4=VAR_15, VAR_5=VAR_69, VAR_6=VAR_16, VAR_7=VAR_17, VAR_8=VAR_18, VAR_1=VAR_19, VAR_2=VAR_20, VAR_3=VAR_21, VAR_9=is_coroutine, ) VAR_71 = VAR_52( content=VAR_70, VAR_13=status_code, background=VAR_54, # type: ignore # in Starlette ) VAR_71.headers.raw.extend(VAR_55.headers.raw) if VAR_55.status_code: VAR_71.status_code = VAR_55.status_code return VAR_71 return FUNC_5 def FUNC_4( VAR_10: Dependant, VAR_22: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def FUNC_5(VAR_25: WebSocket) -> None: VAR_53 = await solve_dependencies( VAR_24=VAR_25, VAR_10=dependant, VAR_22=dependency_overrides_provider, ) VAR_11, VAR_51, VAR_56, VAR_57, VAR_58 = VAR_53 if VAR_51: await VAR_25.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(VAR_51) assert VAR_10.call is not None, "dependant.call must be a function" await VAR_10.call(**VAR_11) return FUNC_5 class CLASS_0(routing.WebSocketRoute): def __init__( self, VAR_26: str, VAR_27: Callable[..., Any], *, VAR_28: Optional[str] = None, VAR_22: Optional[Any] = None, ) -> None: self.path = VAR_26 self.endpoint = VAR_27 self.name = get_name(VAR_27) if VAR_28 is None else VAR_28 self.dependant = get_dependant(VAR_26=path, call=self.endpoint) self.app = websocket_session( FUNC_4( VAR_10=self.dependant, VAR_22=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path(VAR_26) class CLASS_1(routing.Route): def __init__( self, VAR_26: str, VAR_27: Callable[..., Any], *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_28: Optional[str] = None, VAR_37: Optional[Union[Set[str], List[str]]] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), VAR_22: Optional[Any] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> None: if isinstance(VAR_13, enum.IntEnum): VAR_13 = int(VAR_13) self.path = VAR_26 self.endpoint = VAR_27 self.name = get_name(VAR_27) if VAR_28 is None else VAR_28 self.path_regex, self.path_format, self.param_convertors = compile_path(VAR_26) if VAR_37 is None: VAR_37 = ["GET"] self.methods: Set[str] = set([method.upper() for method in VAR_37]) self.unique_id = generate_operation_id_for_path( VAR_28=self.name, VAR_26=self.path_format, method=list(VAR_37)[0] ) self.response_model = VAR_29 if self.response_model: assert ( VAR_13 not in STATUS_CODES_WITH_NO_BODY ), f"Status code {VAR_13} must not have a VAR_71 body" VAR_72 = "Response_" + self.unique_id self.response_field = create_response_field( VAR_28=VAR_72, type_=self.response_model ) self.secure_cloned_response_field: Optional[ ModelField ] = create_cloned_field(self.response_field) else: self.response_field = None # type: ignore self.secure_cloned_response_field = None self.status_code = VAR_13 self.tags = VAR_30 or [] if VAR_31: self.dependencies = list(VAR_31) else: self.dependencies = [] self.summary = VAR_32 self.description = VAR_33 or inspect.cleandoc(self.endpoint.__doc__ or "") self.description = self.description.split("\f")[0] self.response_description = VAR_34 self.responses = VAR_35 or {} VAR_59 = {} for VAR_74, VAR_71 in self.responses.items(): assert isinstance(VAR_71, dict), "An additional VAR_71 must be a dict" VAR_73 = VAR_71.get("model") if VAR_73: assert ( VAR_74 not in STATUS_CODES_WITH_NO_BODY ), f"Status code {VAR_74} must not have a VAR_71 body" VAR_72 = f"Response_{VAR_74}VAR_56{self.unique_id}" VAR_15 = create_response_field(VAR_28=VAR_72, type_=VAR_73) VAR_59[VAR_74] = VAR_15 if VAR_59: self.response_fields: Dict[Union[int, str], ModelField] = VAR_59 else: self.response_fields = {} self.deprecated = VAR_36 self.operation_id = VAR_38 self.response_model_include = VAR_16 self.response_model_exclude = VAR_17 self.response_model_by_alias = VAR_18 self.response_model_exclude_unset = VAR_19 self.response_model_exclude_defaults = VAR_20 self.response_model_exclude_none = VAR_21 self.include_in_schema = VAR_39 self.response_class = VAR_14 assert callable(VAR_27), "An VAR_27 must be a callable" self.dependant = get_dependant(VAR_26=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, VAR_26=self.path_format), ) self.body_field = get_body_field(VAR_10=self.dependant, VAR_28=self.unique_id) self.dependency_overrides_provider = VAR_22 self.callbacks = VAR_40 self.app = request_response(self.get_route_handler()) def FUNC_6(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: return FUNC_3( VAR_10=self.dependant, VAR_12=self.body_field, VAR_13=self.status_code, VAR_14=self.response_class, VAR_15=self.secure_cloned_response_field, VAR_16=self.response_model_include, VAR_17=self.response_model_exclude, VAR_18=self.response_model_by_alias, VAR_19=self.response_model_exclude_unset, VAR_20=self.response_model_exclude_defaults, VAR_21=self.response_model_exclude_none, VAR_22=self.dependency_overrides_provider, ) class CLASS_2(routing.Router): def __init__( self, *, VAR_41: str = "", VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_42: Type[Response] = Default(JSONResponse), VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_40: Optional[List[BaseRoute]] = None, VAR_43: Optional[List[routing.BaseRoute]] = None, VAR_44: bool = True, VAR_45: Optional[ASGIApp] = None, VAR_22: Optional[Any] = None, VAR_46: Type[CLASS_1] = APIRoute, VAR_47: Optional[Sequence[Callable[[], Any]]] = None, VAR_48: Optional[Sequence[Callable[[], Any]]] = None, VAR_36: Optional[bool] = None, VAR_39: bool = True, ) -> None: super().__init__( VAR_43=routes, # type: ignore # in Starlette VAR_44=redirect_slashes, VAR_45=default, # type: ignore # in Starlette VAR_47=on_startup, # type: ignore # in Starlette VAR_48=on_shutdown, # type: ignore # in Starlette ) if VAR_41: assert VAR_41.startswith("/"), "A VAR_26 VAR_41 must start with '/'" assert not VAR_41.endswith( "/" ), "A VAR_26 VAR_41 must not end with '/', as the VAR_43 will start with '/'" self.prefix = VAR_41 self.tags: List[str] = VAR_30 or [] self.dependencies = list(VAR_31 or []) or [] self.deprecated = VAR_36 self.include_in_schema = VAR_39 self.responses = VAR_35 or {} self.callbacks = VAR_40 or [] self.dependency_overrides_provider = VAR_22 self.route_class = VAR_46 self.default_response_class = VAR_42 def FUNC_7( self, VAR_26: str, VAR_27: Callable[..., Any], *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_37: Optional[Union[Set[str], List[str]]] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), VAR_28: Optional[str] = None, VAR_49: Optional[Type[CLASS_1]] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> None: VAR_46 = VAR_49 or self.route_class VAR_35 = VAR_35 or {} VAR_60 = {**self.responses, **VAR_35} VAR_61 = get_value_or_default( VAR_14, self.default_response_class ) VAR_62 = self.tags.copy() if VAR_30: VAR_62.extend(VAR_30) VAR_63 = self.dependencies.copy() if VAR_31: VAR_63.extend(VAR_31) VAR_64 = self.callbacks.copy() if VAR_40: VAR_64.extend(VAR_40) VAR_65 = VAR_46( self.prefix + VAR_26, VAR_27=endpoint, VAR_29=response_model, VAR_13=status_code, VAR_30=VAR_62, VAR_31=VAR_63, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=VAR_60, VAR_36=deprecated or self.deprecated, VAR_37=methods, VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema and self.include_in_schema, VAR_14=VAR_61, VAR_28=name, VAR_22=self.dependency_overrides_provider, VAR_40=VAR_64, ) self.routes.append(VAR_65) def FUNC_8( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_37: Optional[List[str]] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def FUNC_20(VAR_66: DecoratedCallable) -> DecoratedCallable: self.add_api_route( VAR_26, VAR_66, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=methods, VAR_38=operation_id, VAR_16=VAR_16, VAR_17=VAR_17, VAR_18=VAR_18, VAR_19=VAR_19, VAR_20=VAR_20, VAR_21=VAR_21, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) return VAR_66 return FUNC_20 def FUNC_9( self, VAR_26: str, VAR_27: Callable[..., Any], VAR_28: Optional[str] = None ) -> None: VAR_65 = CLASS_0( VAR_26, VAR_27=endpoint, VAR_28=name, VAR_22=self.dependency_overrides_provider, ) self.routes.append(VAR_65) def VAR_25( self, VAR_26: str, VAR_28: Optional[str] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def FUNC_20(VAR_66: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route(VAR_26, VAR_66, VAR_28=name) return VAR_66 return FUNC_20 def FUNC_11( self, VAR_50: "APIRouter", *, VAR_41: str = "", VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_42: Type[Response] = Default(JSONResponse), VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_40: Optional[List[BaseRoute]] = None, VAR_36: Optional[bool] = None, VAR_39: bool = True, ) -> None: if VAR_41: assert VAR_41.startswith("/"), "A VAR_26 VAR_41 must start with '/'" assert not VAR_41.endswith( "/" ), "A VAR_26 VAR_41 must not end with '/', as the VAR_43 will start with '/'" else: for r in VAR_50.routes: VAR_26 = getattr(r, "path") VAR_28 = getattr(r, "name", "unknown") if VAR_26 is not None and not VAR_26: raise Exception( f"Prefix and VAR_26 cannot be both empty (VAR_26 operation: {VAR_28})" ) if VAR_35 is None: VAR_35 = {} for VAR_65 in VAR_50.routes: if isinstance(VAR_65, CLASS_1): VAR_60 = {**VAR_35, **VAR_65.responses} VAR_75 = get_value_or_default( VAR_65.response_class, VAR_50.default_response_class, VAR_42, self.default_response_class, ) VAR_62 = [] if VAR_30: VAR_62.extend(VAR_30) if VAR_65.tags: VAR_62.extend(VAR_65.tags) VAR_63: List[params.Depends] = [] if VAR_31: VAR_63.extend(VAR_31) if VAR_65.dependencies: VAR_63.extend(VAR_65.dependencies) VAR_64 = [] if VAR_40: VAR_64.extend(VAR_40) if VAR_65.callbacks: VAR_64.extend(VAR_65.callbacks) self.add_api_route( VAR_41 + VAR_65.path, VAR_65.endpoint, VAR_29=VAR_65.response_model, VAR_13=VAR_65.status_code, VAR_30=VAR_62, VAR_31=VAR_63, VAR_32=VAR_65.summary, VAR_33=VAR_65.description, VAR_34=VAR_65.response_description, VAR_35=VAR_60, VAR_36=VAR_65.deprecated or VAR_36 or self.deprecated, VAR_37=VAR_65.methods, VAR_38=VAR_65.operation_id, VAR_16=VAR_65.response_model_include, VAR_17=VAR_65.response_model_exclude, VAR_18=VAR_65.response_model_by_alias, VAR_19=VAR_65.response_model_exclude_unset, VAR_20=VAR_65.response_model_exclude_defaults, VAR_21=VAR_65.response_model_exclude_none, VAR_39=VAR_65.include_in_schema and self.include_in_schema and VAR_39, VAR_14=VAR_75, VAR_28=VAR_65.name, VAR_49=type(VAR_65), VAR_40=VAR_64, ) elif isinstance(VAR_65, routing.Route): VAR_37 = list(VAR_65.methods or []) # type: ignore # in Starlette self.add_route( VAR_41 + VAR_65.path, VAR_65.endpoint, VAR_37=methods, VAR_39=VAR_65.include_in_schema, VAR_28=VAR_65.name, ) elif isinstance(VAR_65, CLASS_0): self.add_api_websocket_route( VAR_41 + VAR_65.path, VAR_65.endpoint, VAR_28=VAR_65.name ) elif isinstance(VAR_65, routing.WebSocketRoute): self.add_websocket_route( VAR_41 + VAR_65.path, VAR_65.endpoint, VAR_28=VAR_65.name ) for handler in VAR_50.on_startup: self.add_event_handler("startup", handler) for handler in VAR_50.on_shutdown: self.add_event_handler("shutdown", handler) def FUNC_12( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["GET"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_13( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["PUT"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_14( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["POST"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_15( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["DELETE"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_16( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["OPTIONS"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_17( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["HEAD"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_18( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["PATCH"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, ) def FUNC_19( self, VAR_26: str, *, VAR_29: Optional[Type[Any]] = None, VAR_13: int = 200, VAR_30: Optional[List[str]] = None, VAR_31: Optional[Sequence[params.Depends]] = None, VAR_32: Optional[str] = None, VAR_33: Optional[str] = None, VAR_34: str = "Successful Response", VAR_35: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, VAR_36: Optional[bool] = None, VAR_38: Optional[str] = None, VAR_16: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_17: Optional[Union[SetIntStr, DictIntStrAny]] = None, VAR_18: bool = True, VAR_19: bool = False, VAR_20: bool = False, VAR_21: bool = False, VAR_39: bool = True, VAR_14: Type[Response] = Default(JSONResponse), VAR_28: Optional[str] = None, VAR_40: Optional[List[BaseRoute]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( VAR_26=path, VAR_29=response_model, VAR_13=status_code, VAR_30=tags, VAR_31=dependencies, VAR_32=summary, VAR_33=description, VAR_34=response_description, VAR_35=responses, VAR_36=deprecated, VAR_37=["TRACE"], VAR_38=operation_id, VAR_16=response_model_include, VAR_17=response_model_exclude, VAR_18=response_model_by_alias, VAR_19=response_model_exclude_unset, VAR_20=response_model_exclude_defaults, VAR_21=response_model_exclude_none, VAR_39=include_in_schema, VAR_14=response_class, VAR_28=name, VAR_40=callbacks, )
[ 17, 56, 57, 93, 94, 138, 139, 143, 144, 146, 151, 152, 174, 204, 229, 231, 232, 248, 250, 251, 272, 273, 305, 327, 328, 329, 330, 331, 332, 333, 348, 349, 378, 390, 406, 407, 450, 523, 577, 579, 590, 597, 599, 701, 751, 801, 851, 901, 951, 1001, 1051, 1077, 1102 ]
[ 18, 57, 58, 94, 95, 139, 140, 144, 145, 147, 152, 153, 175, 217, 242, 244, 245, 261, 263, 264, 285, 286, 318, 340, 341, 342, 343, 344, 345, 346, 361, 362, 391, 403, 419, 420, 463, 536, 590, 592, 603, 610, 612, 714, 764, 814, 864, 914, 964, 1014, 1064, 1090, 1115 ]
5CWE-94
""" A FastAPI app used to create an OpenAPI document for end-to-end testing """ import json from datetime import date, datetime from enum import Enum from pathlib import Path from typing import Any, Dict, List, Union from fastapi import APIRouter, FastAPI, File, Header, Query, UploadFile from pydantic import BaseModel app = FastAPI(title="My Test API", description="An API for testing openapi-python-client",) @app.get("/ping", response_model=bool) async def ping(): """ A quick check to see if the system is running """ return True test_router = APIRouter() class AnEnum(Enum): """ For testing Enums in all the ways they can be used """ FIRST_VALUE = "FIRST_VALUE" SECOND_VALUE = "SECOND_VALUE" class DifferentEnum(Enum): FIRST_VALUE = "DIFFERENT" SECOND_VALUE = "OTHER" class OtherModel(BaseModel): """ A different model for calling from TestModel """ a_value: str class AModel(BaseModel): """ A Model for testing all the ways custom objects can be used """ an_enum_value: AnEnum nested_list_of_enums: List[List[DifferentEnum]] = [] some_dict: Dict[str, str] = {} aCamelDateTime: Union[datetime, date] a_date: date @test_router.get("/", response_model=List[AModel], operation_id="getUserList") def get_list(an_enum_value: List[AnEnum] = Query(...), some_date: Union[date, datetime] = Query(...)): """ Get a list of things """ return @test_router.post("/upload") async def upload_file(some_file: UploadFile = File(...), keep_alive: bool = Header(None)): """ Upload a file """ data = await some_file.read() return (some_file.filename, some_file.content_type, data) @test_router.post("/json_body") def json_body(body: AModel): """ Try sending a JSON body """ return app.include_router(test_router, prefix="/tests", tags=["tests"]) def generate_openapi_json(): path = Path(__file__).parent / "openapi.json" path.write_text(json.dumps(app.openapi(), indent=4)) if __name__ == "__main__": generate_openapi_json()
""" A FastAPI app used to create an OpenAPI document for end-to-end testing """ import json from datetime import date, datetime from enum import Enum from pathlib import Path from typing import Any, Dict, List, Union from fastapi import APIRouter, Body, FastAPI, File, Header, Query, UploadFile from pydantic import BaseModel app = FastAPI(title="My Test API", description="An API for testing openapi-python-client",) @app.get("/ping", response_model=bool) async def ping(): """ A quick check to see if the system is running """ return True test_router = APIRouter() class AnEnum(Enum): """ For testing Enums in all the ways they can be used """ FIRST_VALUE = "FIRST_VALUE" SECOND_VALUE = "SECOND_VALUE" class DifferentEnum(Enum): FIRST_VALUE = "DIFFERENT" SECOND_VALUE = "OTHER" class OtherModel(BaseModel): """ A different model for calling from TestModel """ a_value: str class AModel(BaseModel): """ A Model for testing all the ways custom objects can be used """ an_enum_value: AnEnum nested_list_of_enums: List[List[DifferentEnum]] = [] some_dict: Dict[str, str] aCamelDateTime: Union[datetime, date] a_date: date @test_router.get("/", response_model=List[AModel], operation_id="getUserList") def get_list( an_enum_value: List[AnEnum] = Query(...), some_date: Union[date, datetime] = Query(...), ): """ Get a list of things """ return @test_router.post("/upload") async def upload_file(some_file: UploadFile = File(...), keep_alive: bool = Header(None)): """ Upload a file """ data = await some_file.read() return (some_file.filename, some_file.content_type, data) @test_router.post("/json_body") def json_body(body: AModel): """ Try sending a JSON body """ return @test_router.post("/test_defaults") def test_defaults( string_prop: str = Query(default="the default string"), datetime_prop: datetime = Query(default=datetime(1010, 10, 10)), date_prop: date = Query(default=date(1010, 10, 10)), float_prop: float = Query(default=3.14), int_prop: int = Query(default=7), boolean_prop: bool = Query(default=False), list_prop: List[AnEnum] = Query(default=[AnEnum.FIRST_VALUE, AnEnum.SECOND_VALUE]), union_prop: Union[float, str] = Query(default="not a float"), enum_prop: AnEnum = Query(default=AnEnum.FIRST_VALUE), dict_prop: Dict[str, str] = Body(default={"key": "val"}), ): return app.include_router(test_router, prefix="/tests", tags=["tests"]) def generate_openapi_json(): path = Path(__file__).parent / "openapi.json" path.write_text(json.dumps(app.openapi(), indent=4)) if __name__ == "__main__": generate_openapi_json()
remote_code_execution
{ "code": [ "from fastapi import APIRouter, FastAPI, File, Header, Query, UploadFile", " some_dict: Dict[str, str] = {}", "def get_list(an_enum_value: List[AnEnum] = Query(...), some_date: Union[date, datetime] = Query(...)):" ], "line_no": [ 8, 46, 52 ] }
{ "code": [ "from fastapi import APIRouter, Body, FastAPI, File, Header, Query, UploadFile", " some_dict: Dict[str, str]", "def get_list(", "):", "def test_defaults(", " string_prop: str = Query(default=\"the default string\"),", " datetime_prop: datetime = Query(default=datetime(1010, 10, 10)),", " float_prop: float = Query(default=3.14),", " int_prop: int = Query(default=7),", " boolean_prop: bool = Query(default=False),", " union_prop: Union[float, str] = Query(default=\"not a float\"),", " enum_prop: AnEnum = Query(default=AnEnum.FIRST_VALUE),", " dict_prop: Dict[str, str] = Body(default={\"key\": \"val\"}),", "):", " return" ], "line_no": [ 8, 46, 52, 54, 73, 74, 75, 77, 78, 79, 81, 82, 83, 84, 85 ] }
import json from datetime import date, datetime from enum import Enum from pathlib import Path from typing import Any, Dict, List, Union from fastapi import APIRouter, FastAPI, File, Header, Query, UploadFile from pydantic import BaseModel VAR_0 = FastAPI(title="My Test API", description="An API for testing openapi-python-client",) @VAR_0.get("/ping", response_model=bool) async def FUNC_0(): return True VAR_1 = APIRouter() class CLASS_0(Enum): VAR_7 = "FIRST_VALUE" VAR_8 = "SECOND_VALUE" class CLASS_1(Enum): VAR_7 = "DIFFERENT" VAR_8 = "OTHER" class CLASS_2(BaseModel): a_value: str class CLASS_3(BaseModel): VAR_2: CLASS_0 nested_list_of_enums: List[List[CLASS_1]] = [] some_dict: Dict[str, str] = {} aCamelDateTime: Union[datetime, date] a_date: date @VAR_1.get("/", response_model=List[CLASS_3], operation_id="getUserList") def FUNC_1(VAR_2: List[CLASS_0] = Query(...), VAR_3: Union[date, datetime] = Query(...)): return @VAR_1.post("/upload") async def FUNC_2(VAR_4: UploadFile = File(...), VAR_5: bool = Header(None)): VAR_9 = await VAR_4.read() return (VAR_4.filename, VAR_4.content_type, VAR_9) @VAR_1.post("/json_body") def FUNC_3(VAR_6: CLASS_3): return VAR_0.include_router(VAR_1, prefix="/tests", tags=["tests"]) def FUNC_4(): VAR_10 = Path(__file__).parent / "openapi.json" VAR_10.write_text(json.dumps(VAR_0.openapi(), indent=4)) if __name__ == "__main__": FUNC_4()
import json from datetime import date, datetime from enum import Enum from pathlib import Path from typing import Any, Dict, List, Union from fastapi import APIRouter, Body, FastAPI, File, Header, Query, UploadFile from pydantic import BaseModel VAR_0 = FastAPI(title="My Test API", description="An API for testing openapi-python-client",) @VAR_0.get("/ping", response_model=bool) async def FUNC_0(): return True VAR_1 = APIRouter() class CLASS_0(Enum): VAR_17 = "FIRST_VALUE" VAR_18 = "SECOND_VALUE" class CLASS_1(Enum): VAR_17 = "DIFFERENT" VAR_18 = "OTHER" class CLASS_2(BaseModel): a_value: str class CLASS_3(BaseModel): VAR_2: CLASS_0 nested_list_of_enums: List[List[CLASS_1]] = [] some_dict: Dict[str, str] aCamelDateTime: Union[datetime, date] a_date: date @VAR_1.get("/", response_model=List[CLASS_3], operation_id="getUserList") def FUNC_1( VAR_2: List[CLASS_0] = Query(...), VAR_3: Union[date, datetime] = Query(...), ): return @VAR_1.post("/upload") async def FUNC_2(VAR_4: UploadFile = File(...), VAR_5: bool = Header(None)): VAR_19 = await VAR_4.read() return (VAR_4.filename, VAR_4.content_type, VAR_19) @VAR_1.post("/json_body") def FUNC_3(VAR_6: CLASS_3): return @VAR_1.post("/test_defaults") def FUNC_4( VAR_7: str = Query(default="the default string"), VAR_8: datetime = Query(default=datetime(1010, 10, 10)), VAR_9: date = Query(default=date(1010, 10, 10)), VAR_10: float = Query(default=3.14), VAR_11: int = Query(default=7), VAR_12: bool = Query(default=False), VAR_13: List[CLASS_0] = Query(default=[CLASS_0.FIRST_VALUE, CLASS_0.SECOND_VALUE]), VAR_14: Union[float, str] = Query(default="not a float"), VAR_15: CLASS_0 = Query(default=CLASS_0.FIRST_VALUE), VAR_16: Dict[str, str] = Body(default={"key": "val"}), ): return VAR_0.include_router(VAR_1, prefix="/tests", tags=["tests"]) def FUNC_5(): VAR_20 = Path(__file__).parent / "openapi.json" VAR_20.write_text(json.dumps(VAR_0.openapi(), indent=4)) if __name__ == "__main__": FUNC_5()
[ 7, 10, 12, 13, 18, 19, 21, 22, 25, 28, 29, 33, 34, 37, 39, 40, 43, 49, 50, 55, 56, 62, 63, 68, 69, 71, 72, 76, 77, 80, 1, 16, 24, 36, 42, 53, 59, 66 ]
[ 7, 10, 12, 13, 18, 19, 21, 22, 25, 28, 29, 33, 34, 37, 39, 40, 43, 49, 50, 57, 58, 64, 65, 70, 71, 86, 87, 89, 90, 94, 95, 98, 1, 16, 24, 36, 42, 55, 61, 68 ]
1CWE-79
# -*- coding: iso-8859-1 -*- """ MoinMoin - feed some FCKeditor dialogues @copyright: 2005-2006 Bastian Blank, Florian Festi, Thomas Waldmann @license: GNU GPL, see COPYING for details. """ from MoinMoin import config, wikiutil from MoinMoin.action.AttachFile import _get_files from MoinMoin.Page import Page import re ############################################################################## ### Macro dialog ############################################################################## def macro_dialog(request): help = get_macro_help(request) request.write( '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Insert Macro</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="noindex,nofollow" name="robots"> <script src="%s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script> <script language="javascript"> var oEditor = window.parent.InnerDialogLoaded() ; var FCKLang = oEditor.FCKLang ; var FCKMacros = oEditor.FCKMacros ; window.onload = function () { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage( document ) ; OnChange( "BR" ); // Show the "Ok" button. window.parent.SetOkButton( true ) ; } function Ok() { if ( document.getElementById('txtName').value.length == 0 ) { alert( FCKLang.MacroErrNoName ) ; return false ; } FCKMacros.Add( txtName.value ) ; return true ; } function OnChange( sMacro ) { // sMacro = GetE("txtName").value; oHelp = GetE("help"); for (var i=0; i<oHelp.childNodes.length; i++) { var oDiv = oHelp.childNodes[i]; if (oDiv.nodeType==1) { // oDiv.style.display = (GetAttribute(oDiv, "id", "")==sMacro) ? '' : 'none'; if (GetAttribute(oDiv, "id", "") == sMacro) { oDiv.style.display = '' ; // alert("enabled div id " + sMacro) ; } else { oDiv.style.display = 'none' ; } } } } </script> </head> <body scroll="no" style="OVERFLOW: hidden"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td valign="top"> <span fckLang="MacroDlgName">Macro Name</span><br> <select id="txtName" size="10" onchange="OnChange(this.value);"> ''' % request.cfg.url_prefix_static) macros = [] for macro in macro_list(request): if macro == "BR": selected = ' selected="selected"' else: selected = '' if macro in help: macros.append('<option value="%s"%s>%s</option>' % (help[macro].group('prototype'), selected, macro)) else: macros.append('<option value="%s"%s>%s</option>' % (macro, selected, macro)) request.write('\n'.join(macros)) request.write(''' </select> </td> <td id="help">''') helptexts = [] for macro in macro_list(request): if macro in help: match = help[macro] prototype = match.group('prototype') helptext = match.group('help') else: prototype = macro helptext = "" helptexts.append( '''<div id="%s" style="DISPLAY: none"> <b>&lt;&lt;%s&gt;&gt;</b> <br/> <textarea style="color:#000000" cols="37" rows="10" disabled="disabled">%s</textarea> </div>''' % (prototype, prototype, helptext)) request.write(''.join(helptexts)) request.write(''' </td> </tr> </table> </td> </tr> </table> </body> </html> ''') def macro_list(request): from MoinMoin import macro macros = macro.getNames(request.cfg) macros.sort() return macros def get_macro_help(request): """ Read help texts from SystemPage('HelpOnMacros')""" helppage = wikiutil.getLocalizedPage(request, "HelpOnMacros") content = helppage.get_raw_body() macro_re = re.compile( r"\|\|(<.*?>)?\{\{\{" + r"<<(?P<prototype>(?P<macro>\w*).*)>>" + r"\}\}\}\s*\|\|" + r"[^|]*\|\|[^|]*\|\|<[^>]*>" + r"\s*(?P<help>.*?)\s*\|\|\s*(?P<example>.*?)\s*(<<[^>]*>>)*\s*\|\|$", re.U|re.M) help = {} for match in macro_re.finditer(content): help[match.group('macro')] = match return help ############################################################################## ### Link dialog ############################################################################## def page_list(request): from MoinMoin import search name = request.values.get("pagename", "") if name: searchresult = search.searchPages(request, 't:"%s"' % name) pages = [p.page_name for p in searchresult.hits] else: pages = [name] request.write( '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Insert Page Link</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="noindex,nofollow" name="robots"> </head> <body scroll="no" style="OVERFLOW: hidden"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="PageDlgName">Page name</span><br> <select id="txtName" size="1"> %s </select> </td> </tr> </table> </td> </tr> </table> </body> </html> ''' % "".join(["<option>%s</option>\n" % wikiutil.escape(p) for p in pages])) def link_dialog(request): # list of wiki pages name = request.values.get("pagename", "") if name: from MoinMoin import search # XXX error handling! searchresult = search.searchPages(request, 't:"%s"' % name) pages = [p.page_name for p in searchresult.hits] pages.sort() pages[0:0] = [name] page_list = ''' <tr> <td colspan=2> <select id="sctPagename" size="1" onchange="OnChangePagename(this.value);"> %s </select> <td> </tr> ''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(page), wikiutil.escape(page)) for page in pages]) else: page_list = "" # list of interwiki names interwiki_list = wikiutil.load_wikimap(request) interwiki = interwiki_list.keys() interwiki.sort() iwpreferred = request.cfg.interwiki_preferred[:] if not iwpreferred or iwpreferred and iwpreferred[-1] is not None: resultlist = iwpreferred for iw in interwiki: if not iw in iwpreferred: resultlist.append(iw) else: resultlist = iwpreferred[:-1] interwiki = "\n".join( ['<option value="%s">%s</option>' % (wikiutil.escape(key), wikiutil.escape(key)) for key in resultlist]) # wiki url url_prefix_static = request.cfg.url_prefix_static scriptname = request.script_root + '/' action = scriptname basepage = wikiutil.escape(request.page.page_name) request.write(u''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Name: fck_link.html * Link dialog window. * * Version: 2.0 FC (Preview) * Modified: 2005-02-18 23:55:22 * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta name="robots" content="index,nofollow"> <html> <head> <title>Link Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex,nofollow" /> <script src="%(url_prefix_static)s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinlink/fck_link.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <div id="divInfo" style="DISPLAY: none"> <span fckLang="DlgLnkType">Link Type</span><br /> <select id="cmbLinkType" onchange="SetLinkType(this.value);"> <option value="wiki" selected="selected">WikiPage</option> <option value="interwiki">Interwiki</option> <option value="url" fckLang="DlgLnkTypeURL">URL</option> </select> <br /> <br /> <div id="divLinkTypeWiki"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <form action=%(action)s method="GET"> <input type="hidden" name="action" value="fckdialog"> <input type="hidden" name="dialog" value="link"> <input type="hidden" id="basepage" name="basepage" value="%(basepage)s"> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="PageDlgName">Page Name</span><br> <input id="txtPagename" name="pagename" size="30" value="%(name)s"> </td> <td valign="bottom"> <input id=btnSearchpage type="submit" value="Search"> </td> </tr> %(page_list)s </table> </form> </td> </tr> </table> </div> <div id="divLinkTypeInterwiki"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="WikiDlgName">Wiki:PageName</span><br> <select id="sctInterwiki" size="1"> %(interwiki)s </select>: <input id="txtInterwikipagename"></input> </td> </tr> </table> </td> </tr> </table> </div> <div id="divLinkTypeUrl"> <table cellspacing="0" cellpadding="0" width="100%%" border="0"> <tr> <td nowrap="nowrap"> <span fckLang="DlgLnkProto">Protocol</span><br /> <select id="cmbLinkProtocol"> <option value="http://" selected="selected">http://</option> <option value="https://">https://</option> <option value="ftp://">ftp://</option> <option value="file://">file://</option> <option value="news://">news://</option> <option value="mailto:">mailto:</option> <option value="" fckLang="DlgLnkProtoOther">&lt;other&gt;</option> </select> </td> <td nowrap="nowrap">&nbsp;</td> <td nowrap="nowrap" width="100%%"> <span fckLang="DlgLnkURL">URL</span><br /> <input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" /> </td> </tr> </table> <br /> </div> </div> </body> </html> ''' % locals()) def attachment_dialog(request): """ Attachment dialog for GUI editor. """ """ Features: This dialog can... """ """ - list attachments in a drop down list """ """ - list attachments also for a different page than the current one """ """ - create new attachment """ _ = request.getText url_prefix_static = request.cfg.url_prefix_static # wiki url action = request.script_root + "/" # The following code lines implement the feature "list attachments for a different page". # Meaning of the variables: # - requestedPagename : Name of the page where attachments shall be listed from. # - attachmentsPagename : Name of the page where the attachments where retrieved from. # - destinationPagename : Name of the page where attachment will be placed on. requestedPagename = wikiutil.escape(request.values.get("requestedPagename", ""), quote=True) destinationPagename = wikiutil.escape(request.values.get("destinationPagename", request.page.page_name), quote=True) attachmentsPagename = requestedPagename or wikiutil.escape(request.page.page_name) attachments = _get_files(request, attachmentsPagename) attachments.sort() attachmentList = ''' <select id="sctAttachments" size="10" style="width:100%%;visibility:hidden;" onchange="OnAttachmentListChange();"> %s </select> ''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(attachment, quote=True), wikiutil.escape(attachment, quote=True)) for attachment in attachments]) # Translation of dialog texts. langAttachmentLocation = _("Attachment location") langPagename = _("Page name") langAttachmentname = _("Attachment name") langListAttachmentsButton = _("Refresh attachment list") langAttachmentList = _("List of attachments") if len(attachmentsPagename) > 50: shortenedPagename = "%s ... %s" % (attachmentsPagename[0:25], attachmentsPagename[-25:]) else: shortenedPagename = attachmentsPagename langAvailableAttachments = "%s: %s" % (_("Available attachments for page"), shortenedPagename) request.write(''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Name: fck_attachment.html * Attachment dialog window. * * Version: 2.0 FC (Preview) * Modified: 2005-02-18 23:55:22 * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta name="robots" content="index,nofollow"> <html> <head> <title>Attachment Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex,nofollow" /> <script src="%(url_prefix_static)s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinattachment/fck_attachment.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <form id="DlgAttachmentForm" name="DlgAttachmentForm" action=%(action)s method="GET"> <input type="hidden" name="action" value="fckdialog"> <input type="hidden" name="dialog" value="attachment"> <input type="hidden" id="requestedPagename" name="requestedPagename" value="%(requestedPagename)s"> <input type="hidden" id="attachmentsPagename" name="attachmentsPagename" value="%(attachmentsPagename)s"> <input type="hidden" id="destinationPagename" name="destinationPagename" value="%(destinationPagename)s"> <div id="divInfo" style="valign=top;"> <div id="divLinkTypeAttachment"> <fieldset> <legend>%(langAttachmentLocation)s</legend> <table cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td valign="bottom" style="width:90%%" style="padding-bottom:10px"> <span>%(langPagename)s</span><br> </td> </tr> <tr> <td valign="bottom" style="width:100%%" style="padding-bottom:10px;padding-right:10px;"> <input id="txtPagename" type="text" onkeyup="OnPagenameChange();" onchange="OnPagenameChange();" style="width:98%%"> </td> </tr> <tr> <td valign="bottom" style="width:90%%" style="padding-bottom:10px;"> <span>%(langAttachmentname)s</span><br> </td> </tr> <tr valign="bottom"> <td valign="bottom" style="width:100%%" style="padding-bottom:10px;padding-right:10px;"> <input id="txtAttachmentname" type="text" onkeyup="OnAttachmentnameChange();" onchange="OnPagenameChange();" style="width:98%%"><br> </td> </tr> </table> </fieldset> <fieldset> <legend>%(langAvailableAttachments)s</legend> <table cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td valign="bottom" style="width:100%%" style="padding-bottom:10px"> <input id="btnListAttachments" type="submit" value="%(langListAttachmentsButton)s"> </td> </tr> <tr> <td valign="top" style="padding-top:10px"> <label for="sctAttachments">%(langAttachmentList)s</label><br> %(attachmentList)s </td> </tr> </table> </fieldset> </div> </div> </form> </body> </html> ''' % locals()) ############################################################################## ### Image dialog ############################################################################## def image_dialog(request): url_prefix_static = request.cfg.url_prefix_static request.write(''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) * Florian Festi --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Link Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex,nofollow" /> <script src="%(url_prefix_static)s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinimage/fck_image.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <table cellspacing="0" cellpadding="0" width="100%%" border="0"> <tr> <td nowrap="nowrap"> <span fckLang="DlgLnkProto">Protocol</span><br /> <select id="cmbLinkProtocol" onchange="OnProtocolChange();"> <option value="attachment:" selected="selected">attachment:</option> <option value="http://">http://</option> <option value="https://">https://</option> <!-- crashes often: <option value="drawing:">drawing:</option> --> <option value="" fckLang="DlgLnkProtoOther">&lt;other&gt;</option> </select> </td> <td nowrap="nowrap">&nbsp;</td> <td nowrap="nowrap" width="100%%"> <span fckLang="DlgLnkURL">URL or File Name (attachment:)</span><br /> <input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" /> </td> </tr> <tr> <td colspan=2> <div id="divChkLink"> <input id="chkLink" type="checkbox"> Link to </div> </td> </table> </body> </html> ''' % locals()) ############################################################################# ### Main ############################################################################# def execute(pagename, request): dialog = request.values.get("dialog", "") if dialog == "macro": macro_dialog(request) elif dialog == "macrolist": macro_list(request) elif dialog == "pagelist": page_list(request) elif dialog == "link": link_dialog(request) elif dialog == "attachment": attachment_dialog(request) elif dialog == 'image': image_dialog(request) else: from MoinMoin.Page import Page request.theme.add_msg("Dialog unknown!", "error") Page(request, pagename).send_page()
# -*- coding: iso-8859-1 -*- """ MoinMoin - feed some FCKeditor dialogues @copyright: 2005-2006 Bastian Blank, Florian Festi, Thomas Waldmann @license: GNU GPL, see COPYING for details. """ from MoinMoin import config, wikiutil from MoinMoin.action.AttachFile import _get_files from MoinMoin.Page import Page import re ############################################################################## ### Macro dialog ############################################################################## def macro_dialog(request): help = get_macro_help(request) request.write( '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Insert Macro</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="noindex,nofollow" name="robots"> <script src="%s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script> <script language="javascript"> var oEditor = window.parent.InnerDialogLoaded() ; var FCKLang = oEditor.FCKLang ; var FCKMacros = oEditor.FCKMacros ; window.onload = function () { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage( document ) ; OnChange( "BR" ); // Show the "Ok" button. window.parent.SetOkButton( true ) ; } function Ok() { if ( document.getElementById('txtName').value.length == 0 ) { alert( FCKLang.MacroErrNoName ) ; return false ; } FCKMacros.Add( txtName.value ) ; return true ; } function OnChange( sMacro ) { // sMacro = GetE("txtName").value; oHelp = GetE("help"); for (var i=0; i<oHelp.childNodes.length; i++) { var oDiv = oHelp.childNodes[i]; if (oDiv.nodeType==1) { // oDiv.style.display = (GetAttribute(oDiv, "id", "")==sMacro) ? '' : 'none'; if (GetAttribute(oDiv, "id", "") == sMacro) { oDiv.style.display = '' ; // alert("enabled div id " + sMacro) ; } else { oDiv.style.display = 'none' ; } } } } </script> </head> <body scroll="no" style="OVERFLOW: hidden"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td valign="top"> <span fckLang="MacroDlgName">Macro Name</span><br> <select id="txtName" size="10" onchange="OnChange(this.value);"> ''' % request.cfg.url_prefix_static) macros = [] for macro in macro_list(request): if macro == "BR": selected = ' selected="selected"' else: selected = '' if macro in help: macros.append('<option value="%s"%s>%s</option>' % (help[macro].group('prototype'), selected, macro)) else: macros.append('<option value="%s"%s>%s</option>' % (macro, selected, macro)) request.write('\n'.join(macros)) request.write(''' </select> </td> <td id="help">''') helptexts = [] for macro in macro_list(request): if macro in help: match = help[macro] prototype = match.group('prototype') helptext = match.group('help') else: prototype = macro helptext = "" helptexts.append( '''<div id="%s" style="DISPLAY: none"> <b>&lt;&lt;%s&gt;&gt;</b> <br/> <textarea style="color:#000000" cols="37" rows="10" disabled="disabled">%s</textarea> </div>''' % (prototype, prototype, helptext)) request.write(''.join(helptexts)) request.write(''' </td> </tr> </table> </td> </tr> </table> </body> </html> ''') def macro_list(request): from MoinMoin import macro macros = macro.getNames(request.cfg) macros.sort() return macros def get_macro_help(request): """ Read help texts from SystemPage('HelpOnMacros')""" helppage = wikiutil.getLocalizedPage(request, "HelpOnMacros") content = helppage.get_raw_body() macro_re = re.compile( r"\|\|(<.*?>)?\{\{\{" + r"<<(?P<prototype>(?P<macro>\w*).*)>>" + r"\}\}\}\s*\|\|" + r"[^|]*\|\|[^|]*\|\|<[^>]*>" + r"\s*(?P<help>.*?)\s*\|\|\s*(?P<example>.*?)\s*(<<[^>]*>>)*\s*\|\|$", re.U|re.M) help = {} for match in macro_re.finditer(content): help[match.group('macro')] = match return help ############################################################################## ### Link dialog ############################################################################## def page_list(request): from MoinMoin import search name = request.values.get("pagename", "") if name: searchresult = search.searchPages(request, 't:"%s"' % name) pages = [p.page_name for p in searchresult.hits] else: pages = [name] request.write( '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Insert Page Link</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="noindex,nofollow" name="robots"> </head> <body scroll="no" style="OVERFLOW: hidden"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="PageDlgName">Page name</span><br> <select id="txtName" size="1"> %s </select> </td> </tr> </table> </td> </tr> </table> </body> </html> ''' % "".join(["<option>%s</option>\n" % wikiutil.escape(p) for p in pages])) def link_dialog(request): # list of wiki pages name = request.values.get("pagename", "") name_escaped = wikiutil.escape(name) if name: from MoinMoin import search # XXX error handling! searchresult = search.searchPages(request, 't:"%s"' % name) pages = [p.page_name for p in searchresult.hits] pages.sort() pages[0:0] = [name] page_list = ''' <tr> <td colspan=2> <select id="sctPagename" size="1" onchange="OnChangePagename(this.value);"> %s </select> <td> </tr> ''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(page), wikiutil.escape(page)) for page in pages]) else: page_list = "" # list of interwiki names interwiki_list = wikiutil.load_wikimap(request) interwiki = interwiki_list.keys() interwiki.sort() iwpreferred = request.cfg.interwiki_preferred[:] if not iwpreferred or iwpreferred and iwpreferred[-1] is not None: resultlist = iwpreferred for iw in interwiki: if not iw in iwpreferred: resultlist.append(iw) else: resultlist = iwpreferred[:-1] interwiki = "\n".join( ['<option value="%s">%s</option>' % (wikiutil.escape(key), wikiutil.escape(key)) for key in resultlist]) # wiki url url_prefix_static = request.cfg.url_prefix_static scriptname = request.script_root + '/' action = scriptname basepage = wikiutil.escape(request.page.page_name) request.write(u''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Name: fck_link.html * Link dialog window. * * Version: 2.0 FC (Preview) * Modified: 2005-02-18 23:55:22 * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta name="robots" content="index,nofollow"> <html> <head> <title>Link Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex,nofollow" /> <script src="%(url_prefix_static)s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinlink/fck_link.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <div id="divInfo" style="DISPLAY: none"> <span fckLang="DlgLnkType">Link Type</span><br /> <select id="cmbLinkType" onchange="SetLinkType(this.value);"> <option value="wiki" selected="selected">WikiPage</option> <option value="interwiki">Interwiki</option> <option value="url" fckLang="DlgLnkTypeURL">URL</option> </select> <br /> <br /> <div id="divLinkTypeWiki"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <form action=%(action)s method="GET"> <input type="hidden" name="action" value="fckdialog"> <input type="hidden" name="dialog" value="link"> <input type="hidden" id="basepage" name="basepage" value="%(basepage)s"> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="PageDlgName">Page Name</span><br> <input id="txtPagename" name="pagename" size="30" value="%(name_escaped)s"> </td> <td valign="bottom"> <input id=btnSearchpage type="submit" value="Search"> </td> </tr> %(page_list)s </table> </form> </td> </tr> </table> </div> <div id="divLinkTypeInterwiki"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="WikiDlgName">Wiki:PageName</span><br> <select id="sctInterwiki" size="1"> %(interwiki)s </select>: <input id="txtInterwikipagename"></input> </td> </tr> </table> </td> </tr> </table> </div> <div id="divLinkTypeUrl"> <table cellspacing="0" cellpadding="0" width="100%%" border="0"> <tr> <td nowrap="nowrap"> <span fckLang="DlgLnkProto">Protocol</span><br /> <select id="cmbLinkProtocol"> <option value="http://" selected="selected">http://</option> <option value="https://">https://</option> <option value="ftp://">ftp://</option> <option value="file://">file://</option> <option value="news://">news://</option> <option value="mailto:">mailto:</option> <option value="" fckLang="DlgLnkProtoOther">&lt;other&gt;</option> </select> </td> <td nowrap="nowrap">&nbsp;</td> <td nowrap="nowrap" width="100%%"> <span fckLang="DlgLnkURL">URL</span><br /> <input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" /> </td> </tr> </table> <br /> </div> </div> </body> </html> ''' % locals()) def attachment_dialog(request): """ Attachment dialog for GUI editor. """ """ Features: This dialog can... """ """ - list attachments in a drop down list """ """ - list attachments also for a different page than the current one """ """ - create new attachment """ _ = request.getText url_prefix_static = request.cfg.url_prefix_static # wiki url action = request.script_root + "/" # The following code lines implement the feature "list attachments for a different page". # Meaning of the variables: # - requestedPagename : Name of the page where attachments shall be listed from. # - attachmentsPagename : Name of the page where the attachments where retrieved from. # - destinationPagename : Name of the page where attachment will be placed on. requestedPagename = wikiutil.escape(request.values.get("requestedPagename", ""), quote=True) destinationPagename = wikiutil.escape(request.values.get("destinationPagename", request.page.page_name), quote=True) attachmentsPagename = requestedPagename or wikiutil.escape(request.page.page_name) attachments = _get_files(request, attachmentsPagename) attachments.sort() attachmentList = ''' <select id="sctAttachments" size="10" style="width:100%%;visibility:hidden;" onchange="OnAttachmentListChange();"> %s </select> ''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(attachment, quote=True), wikiutil.escape(attachment, quote=True)) for attachment in attachments]) # Translation of dialog texts. langAttachmentLocation = _("Attachment location") langPagename = _("Page name") langAttachmentname = _("Attachment name") langListAttachmentsButton = _("Refresh attachment list") langAttachmentList = _("List of attachments") if len(attachmentsPagename) > 50: shortenedPagename = "%s ... %s" % (attachmentsPagename[0:25], attachmentsPagename[-25:]) else: shortenedPagename = attachmentsPagename langAvailableAttachments = "%s: %s" % (_("Available attachments for page"), shortenedPagename) request.write(''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Name: fck_attachment.html * Attachment dialog window. * * Version: 2.0 FC (Preview) * Modified: 2005-02-18 23:55:22 * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta name="robots" content="index,nofollow"> <html> <head> <title>Attachment Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex,nofollow" /> <script src="%(url_prefix_static)s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinattachment/fck_attachment.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <form id="DlgAttachmentForm" name="DlgAttachmentForm" action=%(action)s method="GET"> <input type="hidden" name="action" value="fckdialog"> <input type="hidden" name="dialog" value="attachment"> <input type="hidden" id="requestedPagename" name="requestedPagename" value="%(requestedPagename)s"> <input type="hidden" id="attachmentsPagename" name="attachmentsPagename" value="%(attachmentsPagename)s"> <input type="hidden" id="destinationPagename" name="destinationPagename" value="%(destinationPagename)s"> <div id="divInfo" style="valign=top;"> <div id="divLinkTypeAttachment"> <fieldset> <legend>%(langAttachmentLocation)s</legend> <table cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td valign="bottom" style="width:90%%" style="padding-bottom:10px"> <span>%(langPagename)s</span><br> </td> </tr> <tr> <td valign="bottom" style="width:100%%" style="padding-bottom:10px;padding-right:10px;"> <input id="txtPagename" type="text" onkeyup="OnPagenameChange();" onchange="OnPagenameChange();" style="width:98%%"> </td> </tr> <tr> <td valign="bottom" style="width:90%%" style="padding-bottom:10px;"> <span>%(langAttachmentname)s</span><br> </td> </tr> <tr valign="bottom"> <td valign="bottom" style="width:100%%" style="padding-bottom:10px;padding-right:10px;"> <input id="txtAttachmentname" type="text" onkeyup="OnAttachmentnameChange();" onchange="OnPagenameChange();" style="width:98%%"><br> </td> </tr> </table> </fieldset> <fieldset> <legend>%(langAvailableAttachments)s</legend> <table cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td valign="bottom" style="width:100%%" style="padding-bottom:10px"> <input id="btnListAttachments" type="submit" value="%(langListAttachmentsButton)s"> </td> </tr> <tr> <td valign="top" style="padding-top:10px"> <label for="sctAttachments">%(langAttachmentList)s</label><br> %(attachmentList)s </td> </tr> </table> </fieldset> </div> </div> </form> </body> </html> ''' % locals()) ############################################################################## ### Image dialog ############################################################################## def image_dialog(request): url_prefix_static = request.cfg.url_prefix_static request.write(''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) * Florian Festi --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Link Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex,nofollow" /> <script src="%(url_prefix_static)s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinimage/fck_image.js" type="text/javascript"></script> <script src="%(url_prefix_static)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <table cellspacing="0" cellpadding="0" width="100%%" border="0"> <tr> <td nowrap="nowrap"> <span fckLang="DlgLnkProto">Protocol</span><br /> <select id="cmbLinkProtocol" onchange="OnProtocolChange();"> <option value="attachment:" selected="selected">attachment:</option> <option value="http://">http://</option> <option value="https://">https://</option> <!-- crashes often: <option value="drawing:">drawing:</option> --> <option value="" fckLang="DlgLnkProtoOther">&lt;other&gt;</option> </select> </td> <td nowrap="nowrap">&nbsp;</td> <td nowrap="nowrap" width="100%%"> <span fckLang="DlgLnkURL">URL or File Name (attachment:)</span><br /> <input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" /> </td> </tr> <tr> <td colspan=2> <div id="divChkLink"> <input id="chkLink" type="checkbox"> Link to </div> </td> </table> </body> </html> ''' % locals()) ############################################################################# ### Main ############################################################################# def execute(pagename, request): dialog = request.values.get("dialog", "") if dialog == "macro": macro_dialog(request) elif dialog == "macrolist": macro_list(request) elif dialog == "pagelist": page_list(request) elif dialog == "link": link_dialog(request) elif dialog == "attachment": attachment_dialog(request) elif dialog == 'image': image_dialog(request) else: from MoinMoin.Page import Page request.theme.add_msg("Dialog unknown!", "error") Page(request, pagename).send_page()
xss
{ "code": [ " <input id=\"txtPagename\" name=\"pagename\" size=\"30\" value=\"%(name)s\">" ], "line_no": [ 302 ] }
{ "code": [ " name_escaped = wikiutil.escape(name)", " <input id=\"txtPagename\" name=\"pagename\" size=\"30\" value=\"%(name_escaped)s\">" ], "line_no": [ 206, 303 ] }
from MoinMoin import config, wikiutil from MoinMoin.action.AttachFile import ._get_files from MoinMoin.Page import Page import re def FUNC_0(VAR_0): VAR_2 = FUNC_2(VAR_0) VAR_0.write( '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Insert Macro</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8"> <meta VAR_6="noindex,nofollow" VAR_8="robots"> <script src="%s/applets/FCKeditor/editor/VAR_28/common/fck_dialog_common.js" type="text/javascript"></script> <script language="javascript"> var oEditor = window.parent.InnerDialogLoaded() ; var FCKLang = oEditor.FCKLang ; var FCKMacros = oEditor.FCKMacros ; window.onload = function () { // First of all, translate the VAR_28 box texts oEditor.FCKLanguageManager.TranslatePage( document ) ; OnChange( "BR" ); // Show the "Ok" button. window.parent.SetOkButton( true ) ; } function Ok() { if ( document.getElementById('txtName').value.length == 0 ) { alert( FCKLang.MacroErrNoName ) ; return false ; } FCKMacros.Add( txtName.value ) ; return true ; } function OnChange( sMacro ) { // sMacro = GetE("txtName").value; oHelp = GetE("help"); for (var i=0; i<oHelp.childNodes.length; i++) { var oDiv = oHelp.childNodes[i]; if (oDiv.nodeType==1) { // oDiv.style.display = (GetAttribute(oDiv, "id", "")==sMacro) ? '' : 'none'; if (GetAttribute(oDiv, "id", "") == sMacro) { oDiv.style.display = '' ; // alert("enabled div id " + sMacro) ; } else { oDiv.style.display = 'none' ; } } } } </script> </head> <body scroll="no" style="OVERFLOW: hidden"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td valign="top"> <span fckLang="MacroDlgName">Macro Name</span><br> <select id="txtName" size="10" onchange="OnChange(this.value);"> ''' % VAR_0.cfg.url_prefix_static) VAR_3 = [] for macro in FUNC_1(VAR_0): if macro == "BR": VAR_35 = ' VAR_35="selected"' else: VAR_35 = '' if macro in VAR_2: VAR_3.append('<option value="%s"%s>%s</option>' % (VAR_2[macro].group('prototype'), VAR_35, macro)) else: VAR_3.append('<option value="%s"%s>%s</option>' % (macro, VAR_35, macro)) VAR_0.write('\n'.join(VAR_3)) VAR_0.write(''' </select> </td> <td id="help">''') VAR_4 = [] for macro in FUNC_1(VAR_0): if macro in VAR_2: VAR_29 = VAR_2[macro] VAR_36 = VAR_29.group('prototype') VAR_37 = VAR_29.group('help') else: VAR_36 = macro VAR_37 = "" VAR_4.append( '''<div id="%s" style="DISPLAY: none"> <b>&lt;&lt;%s&gt;&gt;</b> <br/> <textarea style="color:#000000" cols="37" rows="10" disabled="disabled">%s</textarea> </div>''' % (VAR_36, prototype, VAR_37)) VAR_0.write(''.join(VAR_4)) VAR_0.write(''' </td> </tr> </table> </td> </tr> </table> </body> </html> ''') def FUNC_1(VAR_0): from MoinMoin import macro VAR_3 = macro.getNames(VAR_0.cfg) VAR_3.sort() return VAR_3 def FUNC_2(VAR_0): VAR_5 = wikiutil.getLocalizedPage(VAR_0, "HelpOnMacros") VAR_6 = VAR_5.get_raw_body() VAR_7 = re.compile( r"\|\|(<.*?>)?\{\{\{" + r"<<(?P<VAR_36>(?P<macro>\w*).*)>>" + r"\}\}\}\s*\|\|" + r"[^|]*\|\|[^|]*\|\|<[^>]*>" + r"\s*(?P<VAR_2>.*?)\s*\|\|\s*(?P<example>.*?)\s*(<<[^>]*>>)*\s*\|\|$", re.U|re.M) VAR_2 = {} for VAR_29 in VAR_7.finditer(VAR_6): VAR_2[VAR_29.group('macro')] = VAR_29 return VAR_2 def VAR_32(VAR_0): from MoinMoin import search VAR_8 = VAR_0.values.get("pagename", "") if VAR_8: VAR_30 = search.searchPages(VAR_0, 't:"%s"' % VAR_8) VAR_31 = [p.page_name for p in VAR_30.hits] else: VAR_31 = [VAR_8] VAR_0.write( '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Insert Page Link</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8"> <meta VAR_6="noindex,nofollow" VAR_8="robots"> </head> <body scroll="no" style="OVERFLOW: hidden"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="PageDlgName">Page VAR_8</span><br> <select id="txtName" size="1"> %s </select> </td> </tr> </table> </td> </tr> </table> </body> </html> ''' % "".join(["<option>%s</option>\n" % wikiutil.escape(p) for p in VAR_31])) def FUNC_4(VAR_0): VAR_8 = VAR_0.values.get("pagename", "") if VAR_8: from MoinMoin import search VAR_30 = search.searchPages(VAR_0, 't:"%s"' % VAR_8) VAR_31 = [p.page_name for p in VAR_30.hits] VAR_31.sort() VAR_31[0:0] = [VAR_8] VAR_32 = ''' <tr> <td colspan=2> <select id="sctPagename" size="1" onchange="OnChangePagename(this.value);"> %s </select> <td> </tr> ''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(page), wikiutil.escape(page)) for page in VAR_31]) else: VAR_32 = "" VAR_9 = wikiutil.load_wikimap(VAR_0) VAR_10 = VAR_9.keys() VAR_10.sort() VAR_11 = VAR_0.cfg.interwiki_preferred[:] if not VAR_11 or VAR_11 and VAR_11[-1] is not None: VAR_33 = VAR_11 for iw in VAR_10: if not iw in VAR_11: VAR_33.append(iw) else: VAR_33 = VAR_11[:-1] VAR_10 = "\n".join( ['<option value="%s">%s</option>' % (wikiutil.escape(key), wikiutil.escape(key)) for key in VAR_33]) VAR_12 = VAR_0.cfg.url_prefix_static VAR_13 = VAR_0.script_root + '/' VAR_14 = VAR_13 VAR_15 = wikiutil.escape(VAR_0.page.page_name) VAR_0.write(u''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Name: fck_link.html * Link VAR_28 window. * * Version: 2.0 FC (Preview) * Modified: 2005-02-18 23:55:22 * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <meta http-equiv="Content-Type" VAR_6="text/html;charset=utf-8"> <meta VAR_8="robots" VAR_6="index,nofollow"> <html> <head> <title>Link Properties</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8" /> <meta VAR_8="robots" VAR_6="noindex,nofollow" /> <script src="%(VAR_12)s/applets/FCKeditor/editor/VAR_28/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(VAR_12)s/applets/moinFCKplugins/moinlink/fck_link.js" type="text/javascript"></script> <script src="%(VAR_12)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <div id="divInfo" style="DISPLAY: none"> <span fckLang="DlgLnkType">Link Type</span><br /> <select id="cmbLinkType" onchange="SetLinkType(this.value);"> <option value="wiki" VAR_35="selected">WikiPage</option> <option value="interwiki">Interwiki</option> <option value="url" fckLang="DlgLnkTypeURL">URL</option> </select> <br /> <br /> <div id="divLinkTypeWiki"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <form VAR_14=%(action)s method="GET"> <input type="hidden" VAR_8="action" value="fckdialog"> <input type="hidden" VAR_8="dialog" value="link"> <input type="hidden" id="basepage" VAR_8="basepage" value="%(VAR_15)s"> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="PageDlgName">Page Name</span><br> <input id="txtPagename" VAR_8="pagename" size="30" value="%(VAR_8)s"> </td> <td valign="bottom"> <input id=btnSearchpage type="submit" value="Search"> </td> </tr> %(VAR_32)s </table> </form> </td> </tr> </table> </div> <div id="divLinkTypeInterwiki"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="WikiDlgName">Wiki:PageName</span><br> <select id="sctInterwiki" size="1"> %(VAR_10)s </select>: <input id="txtInterwikipagename"></input> </td> </tr> </table> </td> </tr> </table> </div> <div id="divLinkTypeUrl"> <table cellspacing="0" cellpadding="0" width="100%%" border="0"> <tr> <td nowrap="nowrap"> <span fckLang="DlgLnkProto">Protocol</span><br /> <select id="cmbLinkProtocol"> <option value="http://" VAR_35="selected">http://</option> <option value="https://">https://</option> <option value="ftp://">ftp://</option> <option value="file://">file://</option> <option value="news://">news://</option> <option value="mailto:">mailto:</option> <option value="" fckLang="DlgLnkProtoOther">&lt;other&gt;</option> </select> </td> <td nowrap="nowrap">&nbsp;</td> <td nowrap="nowrap" width="100%%"> <span fckLang="DlgLnkURL">URL</span><br /> <input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" /> </td> </tr> </table> <br /> </div> </div> </body> </html> ''' % locals()) def FUNC_5(VAR_0): """ Features: This VAR_28 can... """ """ - list VAR_20 in a drop down list """ """ - list VAR_20 also for a different page than the current one """ """ - create new attachment """ VAR_16 = VAR_0.getText VAR_12 = VAR_0.cfg.url_prefix_static VAR_14 = VAR_0.script_root + "/" VAR_17 = wikiutil.escape(VAR_0.values.get("requestedPagename", ""), quote=True) VAR_18 = wikiutil.escape(VAR_0.values.get("destinationPagename", VAR_0.page.page_name), quote=True) VAR_19 = VAR_17 or wikiutil.escape(VAR_0.page.page_name) VAR_20 = _get_files(VAR_0, VAR_19) VAR_20.sort() VAR_21 = ''' <select id="sctAttachments" size="10" style="width:100%%;visibility:hidden;" onchange="OnAttachmentListChange();"> %s </select> ''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(attachment, quote=True), wikiutil.escape(attachment, quote=True)) for attachment in VAR_20]) VAR_22 = VAR_16("Attachment location") VAR_23 = VAR_16("Page name") VAR_24 = VAR_16("Attachment name") VAR_25 = VAR_16("Refresh attachment list") VAR_26 = VAR_16("List of attachments") if len(VAR_19) > 50: VAR_34 = "%s ... %s" % (VAR_19[0:25], VAR_19[-25:]) else: VAR_34 = VAR_19 VAR_27 = "%s: %s" % (VAR_16("Available VAR_20 for page"), VAR_34) VAR_0.write(''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Name: fck_attachment.html * Attachment VAR_28 window. * * Version: 2.0 FC (Preview) * Modified: 2005-02-18 23:55:22 * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <meta http-equiv="Content-Type" VAR_6="text/html;charset=utf-8"> <meta VAR_8="robots" VAR_6="index,nofollow"> <html> <head> <title>Attachment Properties</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8" /> <meta VAR_8="robots" VAR_6="noindex,nofollow" /> <script src="%(VAR_12)s/applets/FCKeditor/editor/VAR_28/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(VAR_12)s/applets/moinFCKplugins/moinattachment/fck_attachment.js" type="text/javascript"></script> <script src="%(VAR_12)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <form id="DlgAttachmentForm" VAR_8="DlgAttachmentForm" VAR_14=%(action)s method="GET"> <input type="hidden" VAR_8="action" value="fckdialog"> <input type="hidden" VAR_8="dialog" value="attachment"> <input type="hidden" id="requestedPagename" VAR_8="requestedPagename" value="%(VAR_17)s"> <input type="hidden" id="attachmentsPagename" VAR_8="attachmentsPagename" value="%(VAR_19)s"> <input type="hidden" id="destinationPagename" VAR_8="destinationPagename" value="%(VAR_18)s"> <div id="divInfo" style="valign=top;"> <div id="divLinkTypeAttachment"> <fieldset> <legend>%(VAR_22)s</legend> <table cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td valign="bottom" style="width:90%%" style="padding-bottom:10px"> <span>%(VAR_23)s</span><br> </td> </tr> <tr> <td valign="bottom" style="width:100%%" style="padding-bottom:10px;padding-right:10px;"> <input id="txtPagename" type="text" onkeyup="OnPagenameChange();" onchange="OnPagenameChange();" style="width:98%%"> </td> </tr> <tr> <td valign="bottom" style="width:90%%" style="padding-bottom:10px;"> <span>%(VAR_24)s</span><br> </td> </tr> <tr valign="bottom"> <td valign="bottom" style="width:100%%" style="padding-bottom:10px;padding-right:10px;"> <input id="txtAttachmentname" type="text" onkeyup="OnAttachmentnameChange();" onchange="OnPagenameChange();" style="width:98%%"><br> </td> </tr> </table> </fieldset> <fieldset> <legend>%(VAR_27)s</legend> <table cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td valign="bottom" style="width:100%%" style="padding-bottom:10px"> <input id="btnListAttachments" type="submit" value="%(VAR_25)s"> </td> </tr> <tr> <td valign="top" style="padding-top:10px"> <label for="sctAttachments">%(VAR_26)s</label><br> %(VAR_21)s </td> </tr> </table> </fieldset> </div> </div> </form> </body> </html> ''' % locals()) def FUNC_6(VAR_0): VAR_12 = VAR_0.cfg.url_prefix_static VAR_0.write(''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) * Florian Festi --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Link Properties</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8" /> <meta VAR_8="robots" VAR_6="noindex,nofollow" /> <script src="%(VAR_12)s/applets/FCKeditor/editor/VAR_28/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(VAR_12)s/applets/moinFCKplugins/moinimage/fck_image.js" type="text/javascript"></script> <script src="%(VAR_12)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <table cellspacing="0" cellpadding="0" width="100%%" border="0"> <tr> <td nowrap="nowrap"> <span fckLang="DlgLnkProto">Protocol</span><br /> <select id="cmbLinkProtocol" onchange="OnProtocolChange();"> <option value="attachment:" VAR_35="selected">attachment:</option> <option value="http://">http://</option> <option value="https://">https://</option> <!-- crashes often: <option value="drawing:">drawing:</option> --> <option value="" fckLang="DlgLnkProtoOther">&lt;other&gt;</option> </select> </td> <td nowrap="nowrap">&nbsp;</td> <td nowrap="nowrap" width="100%%"> <span fckLang="DlgLnkURL">URL or File Name (attachment:)</span><br /> <input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" /> </td> </tr> <tr> <td colspan=2> <div id="divChkLink"> <input id="chkLink" type="checkbox"> Link to </div> </td> </table> </body> </html> ''' % locals()) def FUNC_7(VAR_1, VAR_0): VAR_28 = VAR_0.values.get("dialog", "") if VAR_28 == "macro": FUNC_0(VAR_0) elif VAR_28 == "macrolist": FUNC_1(VAR_0) elif VAR_28 == "pagelist": VAR_32(VAR_0) elif VAR_28 == "link": FUNC_4(VAR_0) elif VAR_28 == "attachment": FUNC_5(VAR_0) elif VAR_28 == 'image': FUNC_6(VAR_0) else: from MoinMoin.Page import Page VAR_0.theme.add_msg("Dialog unknown!", "error") Page(VAR_0, VAR_1).send_page()
from MoinMoin import config, wikiutil from MoinMoin.action.AttachFile import ._get_files from MoinMoin.Page import Page import re def FUNC_0(VAR_0): VAR_2 = FUNC_2(VAR_0) VAR_0.write( '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Insert Macro</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8"> <meta VAR_6="noindex,nofollow" VAR_8="robots"> <script src="%s/applets/FCKeditor/editor/VAR_29/common/fck_dialog_common.js" type="text/javascript"></script> <script language="javascript"> var oEditor = window.parent.InnerDialogLoaded() ; var FCKLang = oEditor.FCKLang ; var FCKMacros = oEditor.FCKMacros ; window.onload = function () { // First of all, translate the VAR_29 box texts oEditor.FCKLanguageManager.TranslatePage( document ) ; OnChange( "BR" ); // Show the "Ok" button. window.parent.SetOkButton( true ) ; } function Ok() { if ( document.getElementById('txtName').value.length == 0 ) { alert( FCKLang.MacroErrNoName ) ; return false ; } FCKMacros.Add( txtName.value ) ; return true ; } function OnChange( sMacro ) { // sMacro = GetE("txtName").value; oHelp = GetE("help"); for (var i=0; i<oHelp.childNodes.length; i++) { var oDiv = oHelp.childNodes[i]; if (oDiv.nodeType==1) { // oDiv.style.display = (GetAttribute(oDiv, "id", "")==sMacro) ? '' : 'none'; if (GetAttribute(oDiv, "id", "") == sMacro) { oDiv.style.display = '' ; // alert("enabled div id " + sMacro) ; } else { oDiv.style.display = 'none' ; } } } } </script> </head> <body scroll="no" style="OVERFLOW: hidden"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td valign="top"> <span fckLang="MacroDlgName">Macro Name</span><br> <select id="txtName" size="10" onchange="OnChange(this.value);"> ''' % VAR_0.cfg.url_prefix_static) VAR_3 = [] for macro in FUNC_1(VAR_0): if macro == "BR": VAR_36 = ' VAR_36="selected"' else: VAR_36 = '' if macro in VAR_2: VAR_3.append('<option value="%s"%s>%s</option>' % (VAR_2[macro].group('prototype'), VAR_36, macro)) else: VAR_3.append('<option value="%s"%s>%s</option>' % (macro, VAR_36, macro)) VAR_0.write('\n'.join(VAR_3)) VAR_0.write(''' </select> </td> <td id="help">''') VAR_4 = [] for macro in FUNC_1(VAR_0): if macro in VAR_2: VAR_30 = VAR_2[macro] VAR_37 = VAR_30.group('prototype') VAR_38 = VAR_30.group('help') else: VAR_37 = macro VAR_38 = "" VAR_4.append( '''<div id="%s" style="DISPLAY: none"> <b>&lt;&lt;%s&gt;&gt;</b> <br/> <textarea style="color:#000000" cols="37" rows="10" disabled="disabled">%s</textarea> </div>''' % (VAR_37, prototype, VAR_38)) VAR_0.write(''.join(VAR_4)) VAR_0.write(''' </td> </tr> </table> </td> </tr> </table> </body> </html> ''') def FUNC_1(VAR_0): from MoinMoin import macro VAR_3 = macro.getNames(VAR_0.cfg) VAR_3.sort() return VAR_3 def FUNC_2(VAR_0): VAR_5 = wikiutil.getLocalizedPage(VAR_0, "HelpOnMacros") VAR_6 = VAR_5.get_raw_body() VAR_7 = re.compile( r"\|\|(<.*?>)?\{\{\{" + r"<<(?P<VAR_37>(?P<macro>\w*).*)>>" + r"\}\}\}\s*\|\|" + r"[^|]*\|\|[^|]*\|\|<[^>]*>" + r"\s*(?P<VAR_2>.*?)\s*\|\|\s*(?P<example>.*?)\s*(<<[^>]*>>)*\s*\|\|$", re.U|re.M) VAR_2 = {} for VAR_30 in VAR_7.finditer(VAR_6): VAR_2[VAR_30.group('macro')] = VAR_30 return VAR_2 def VAR_33(VAR_0): from MoinMoin import search VAR_8 = VAR_0.values.get("pagename", "") if VAR_8: VAR_31 = search.searchPages(VAR_0, 't:"%s"' % VAR_8) VAR_32 = [p.page_name for p in VAR_31.hits] else: VAR_32 = [VAR_8] VAR_0.write( '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Insert Page Link</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8"> <meta VAR_6="noindex,nofollow" VAR_8="robots"> </head> <body scroll="no" style="OVERFLOW: hidden"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="PageDlgName">Page VAR_8</span><br> <select id="txtName" size="1"> %s </select> </td> </tr> </table> </td> </tr> </table> </body> </html> ''' % "".join(["<option>%s</option>\n" % wikiutil.escape(p) for p in VAR_32])) def FUNC_4(VAR_0): VAR_8 = VAR_0.values.get("pagename", "") VAR_9 = wikiutil.escape(VAR_8) if VAR_8: from MoinMoin import search VAR_31 = search.searchPages(VAR_0, 't:"%s"' % VAR_8) VAR_32 = [p.page_name for p in VAR_31.hits] VAR_32.sort() VAR_32[0:0] = [VAR_8] VAR_33 = ''' <tr> <td colspan=2> <select id="sctPagename" size="1" onchange="OnChangePagename(this.value);"> %s </select> <td> </tr> ''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(page), wikiutil.escape(page)) for page in VAR_32]) else: VAR_33 = "" VAR_10 = wikiutil.load_wikimap(VAR_0) VAR_11 = VAR_10.keys() VAR_11.sort() VAR_12 = VAR_0.cfg.interwiki_preferred[:] if not VAR_12 or VAR_12 and VAR_12[-1] is not None: VAR_34 = VAR_12 for iw in VAR_11: if not iw in VAR_12: VAR_34.append(iw) else: VAR_34 = VAR_12[:-1] VAR_11 = "\n".join( ['<option value="%s">%s</option>' % (wikiutil.escape(key), wikiutil.escape(key)) for key in VAR_34]) VAR_13 = VAR_0.cfg.url_prefix_static VAR_14 = VAR_0.script_root + '/' VAR_15 = VAR_14 VAR_16 = wikiutil.escape(VAR_0.page.page_name) VAR_0.write(u''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Name: fck_link.html * Link VAR_29 window. * * Version: 2.0 FC (Preview) * Modified: 2005-02-18 23:55:22 * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <meta http-equiv="Content-Type" VAR_6="text/html;charset=utf-8"> <meta VAR_8="robots" VAR_6="index,nofollow"> <html> <head> <title>Link Properties</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8" /> <meta VAR_8="robots" VAR_6="noindex,nofollow" /> <script src="%(VAR_13)s/applets/FCKeditor/editor/VAR_29/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(VAR_13)s/applets/moinFCKplugins/moinlink/fck_link.js" type="text/javascript"></script> <script src="%(VAR_13)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <div id="divInfo" style="DISPLAY: none"> <span fckLang="DlgLnkType">Link Type</span><br /> <select id="cmbLinkType" onchange="SetLinkType(this.value);"> <option value="wiki" VAR_36="selected">WikiPage</option> <option value="interwiki">Interwiki</option> <option value="url" fckLang="DlgLnkTypeURL">URL</option> </select> <br /> <br /> <div id="divLinkTypeWiki"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <form VAR_15=%(action)s method="GET"> <input type="hidden" VAR_8="action" value="fckdialog"> <input type="hidden" VAR_8="dialog" value="link"> <input type="hidden" id="basepage" VAR_8="basepage" value="%(VAR_16)s"> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="PageDlgName">Page Name</span><br> <input id="txtPagename" VAR_8="pagename" size="30" value="%(VAR_9)s"> </td> <td valign="bottom"> <input id=btnSearchpage type="submit" value="Search"> </td> </tr> %(VAR_33)s </table> </form> </td> </tr> </table> </div> <div id="divLinkTypeInterwiki"> <table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="WikiDlgName">Wiki:PageName</span><br> <select id="sctInterwiki" size="1"> %(VAR_11)s </select>: <input id="txtInterwikipagename"></input> </td> </tr> </table> </td> </tr> </table> </div> <div id="divLinkTypeUrl"> <table cellspacing="0" cellpadding="0" width="100%%" border="0"> <tr> <td nowrap="nowrap"> <span fckLang="DlgLnkProto">Protocol</span><br /> <select id="cmbLinkProtocol"> <option value="http://" VAR_36="selected">http://</option> <option value="https://">https://</option> <option value="ftp://">ftp://</option> <option value="file://">file://</option> <option value="news://">news://</option> <option value="mailto:">mailto:</option> <option value="" fckLang="DlgLnkProtoOther">&lt;other&gt;</option> </select> </td> <td nowrap="nowrap">&nbsp;</td> <td nowrap="nowrap" width="100%%"> <span fckLang="DlgLnkURL">URL</span><br /> <input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" /> </td> </tr> </table> <br /> </div> </div> </body> </html> ''' % locals()) def FUNC_5(VAR_0): """ Features: This VAR_29 can... """ """ - list VAR_21 in a drop down list """ """ - list VAR_21 also for a different page than the current one """ """ - create new attachment """ VAR_17 = VAR_0.getText VAR_13 = VAR_0.cfg.url_prefix_static VAR_15 = VAR_0.script_root + "/" VAR_18 = wikiutil.escape(VAR_0.values.get("requestedPagename", ""), quote=True) VAR_19 = wikiutil.escape(VAR_0.values.get("destinationPagename", VAR_0.page.page_name), quote=True) VAR_20 = VAR_18 or wikiutil.escape(VAR_0.page.page_name) VAR_21 = _get_files(VAR_0, VAR_20) VAR_21.sort() VAR_22 = ''' <select id="sctAttachments" size="10" style="width:100%%;visibility:hidden;" onchange="OnAttachmentListChange();"> %s </select> ''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(attachment, quote=True), wikiutil.escape(attachment, quote=True)) for attachment in VAR_21]) VAR_23 = VAR_17("Attachment location") VAR_24 = VAR_17("Page name") VAR_25 = VAR_17("Attachment name") VAR_26 = VAR_17("Refresh attachment list") VAR_27 = VAR_17("List of attachments") if len(VAR_20) > 50: VAR_35 = "%s ... %s" % (VAR_20[0:25], VAR_20[-25:]) else: VAR_35 = VAR_20 VAR_28 = "%s: %s" % (VAR_17("Available VAR_21 for page"), VAR_35) VAR_0.write(''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Name: fck_attachment.html * Attachment VAR_29 window. * * Version: 2.0 FC (Preview) * Modified: 2005-02-18 23:55:22 * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <meta http-equiv="Content-Type" VAR_6="text/html;charset=utf-8"> <meta VAR_8="robots" VAR_6="index,nofollow"> <html> <head> <title>Attachment Properties</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8" /> <meta VAR_8="robots" VAR_6="noindex,nofollow" /> <script src="%(VAR_13)s/applets/FCKeditor/editor/VAR_29/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(VAR_13)s/applets/moinFCKplugins/moinattachment/fck_attachment.js" type="text/javascript"></script> <script src="%(VAR_13)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <form id="DlgAttachmentForm" VAR_8="DlgAttachmentForm" VAR_15=%(action)s method="GET"> <input type="hidden" VAR_8="action" value="fckdialog"> <input type="hidden" VAR_8="dialog" value="attachment"> <input type="hidden" id="requestedPagename" VAR_8="requestedPagename" value="%(VAR_18)s"> <input type="hidden" id="attachmentsPagename" VAR_8="attachmentsPagename" value="%(VAR_20)s"> <input type="hidden" id="destinationPagename" VAR_8="destinationPagename" value="%(VAR_19)s"> <div id="divInfo" style="valign=top;"> <div id="divLinkTypeAttachment"> <fieldset> <legend>%(VAR_23)s</legend> <table cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td valign="bottom" style="width:90%%" style="padding-bottom:10px"> <span>%(VAR_24)s</span><br> </td> </tr> <tr> <td valign="bottom" style="width:100%%" style="padding-bottom:10px;padding-right:10px;"> <input id="txtPagename" type="text" onkeyup="OnPagenameChange();" onchange="OnPagenameChange();" style="width:98%%"> </td> </tr> <tr> <td valign="bottom" style="width:90%%" style="padding-bottom:10px;"> <span>%(VAR_25)s</span><br> </td> </tr> <tr valign="bottom"> <td valign="bottom" style="width:100%%" style="padding-bottom:10px;padding-right:10px;"> <input id="txtAttachmentname" type="text" onkeyup="OnAttachmentnameChange();" onchange="OnPagenameChange();" style="width:98%%"><br> </td> </tr> </table> </fieldset> <fieldset> <legend>%(VAR_28)s</legend> <table cellSpacing="0" cellPadding="0" width="100%%" border="0"> <tr> <td valign="bottom" style="width:100%%" style="padding-bottom:10px"> <input id="btnListAttachments" type="submit" value="%(VAR_26)s"> </td> </tr> <tr> <td valign="top" style="padding-top:10px"> <label for="sctAttachments">%(VAR_27)s</label><br> %(VAR_22)s </td> </tr> </table> </fieldset> </div> </div> </form> </body> </html> ''' % locals()) def FUNC_6(VAR_0): VAR_13 = VAR_0.cfg.url_prefix_static VAR_0.write(''' <!-- * FCKeditor - The text editor for internet * Copyright (C) 2003-2004 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) * Florian Festi --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Link Properties</title> <meta http-equiv="Content-Type" VAR_6="text/html; charset=utf-8" /> <meta VAR_8="robots" VAR_6="noindex,nofollow" /> <script src="%(VAR_13)s/applets/FCKeditor/editor/VAR_29/common/fck_dialog_common.js" type="text/javascript"></script> <script src="%(VAR_13)s/applets/moinFCKplugins/moinimage/fck_image.js" type="text/javascript"></script> <script src="%(VAR_13)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script> </head> <body scroll="no" style="OVERFLOW: hidden"> <table cellspacing="0" cellpadding="0" width="100%%" border="0"> <tr> <td nowrap="nowrap"> <span fckLang="DlgLnkProto">Protocol</span><br /> <select id="cmbLinkProtocol" onchange="OnProtocolChange();"> <option value="attachment:" VAR_36="selected">attachment:</option> <option value="http://">http://</option> <option value="https://">https://</option> <!-- crashes often: <option value="drawing:">drawing:</option> --> <option value="" fckLang="DlgLnkProtoOther">&lt;other&gt;</option> </select> </td> <td nowrap="nowrap">&nbsp;</td> <td nowrap="nowrap" width="100%%"> <span fckLang="DlgLnkURL">URL or File Name (attachment:)</span><br /> <input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" /> </td> </tr> <tr> <td colspan=2> <div id="divChkLink"> <input id="chkLink" type="checkbox"> Link to </div> </td> </table> </body> </html> ''' % locals()) def FUNC_7(VAR_1, VAR_0): VAR_29 = VAR_0.values.get("dialog", "") if VAR_29 == "macro": FUNC_0(VAR_0) elif VAR_29 == "macrolist": FUNC_1(VAR_0) elif VAR_29 == "pagelist": VAR_33(VAR_0) elif VAR_29 == "link": FUNC_4(VAR_0) elif VAR_29 == "attachment": FUNC_5(VAR_0) elif VAR_29 == 'image': FUNC_6(VAR_0) else: from MoinMoin.Page import Page VAR_0.theme.add_msg("Dialog unknown!", "error") Page(VAR_0, VAR_1).send_page()
[ 1, 4, 8, 13, 14, 15, 16, 17, 29, 33, 38, 40, 44, 52, 56, 79, 92, 105, 111, 128, 140, 146, 161, 162, 163, 164, 165, 202, 204, 208, 210, 226, 227, 242, 243, 362, 363, 372, 373, 375, 376, 377, 378, 379, 380, 381, 384, 394, 395, 401, 407, 447, 497, 498, 499, 500, 501, 502, 559, 560, 561, 562, 563, 564, 567, 584, 585, 2, 3, 4, 5, 6, 7, 148, 365 ]
[ 1, 4, 8, 13, 14, 15, 16, 17, 29, 33, 38, 40, 44, 52, 56, 79, 92, 105, 111, 128, 140, 146, 161, 162, 163, 164, 165, 202, 204, 209, 211, 227, 228, 243, 244, 363, 364, 373, 374, 376, 377, 378, 379, 380, 381, 382, 385, 395, 396, 402, 408, 448, 498, 499, 500, 501, 502, 503, 560, 561, 562, 563, 564, 565, 568, 585, 586, 2, 3, 4, 5, 6, 7, 148, 366 ]
3CWE-352
import os import shutil import subprocess import sys import tempfile import traceback from pathlib import Path from typing import List from flask import Response, request from werkzeug.utils import secure_filename from archivy import click_web from .input_fields import FieldId logger = None def exec(command_path): """ Execute the command and stream the output from it as response :param command_path: """ command_path = "cli/" + command_path global logger logger = click_web.logger omitted = ["shell", "run", "routes", "create-admin"] root_command, *commands = command_path.split("/") cmd = ["archivy"] req_to_args = RequestToCommandArgs() # root command_index should not add a command cmd.extend(req_to_args.command_args(0)) for i, command in enumerate(commands): if command in omitted: return Response(status=400) cmd.append(command) cmd.extend(req_to_args.command_args(i + 1)) def _generate_output(): yield _create_cmd_header(commands) try: yield from _run_script_and_generate_stream(req_to_args, cmd) except Exception as e: # exited prematurely, show the error to user yield f"\nERROR: Got exception when reading output from script: {type(e)}\n" yield traceback.format_exc() raise return Response(_generate_output(), mimetype="text/plain") def _run_script_and_generate_stream( req_to_args: "RequestToCommandArgs", cmd: List[str] ): """ Execute the command the via Popen and yield output """ logger.info("Executing archivy command") if not os.environ.get("PYTHONIOENCODING"): # Fix unicode on windows os.environ["PYTHONIOENCODING"] = "UTF-8" process = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) logger.info("script running Pid: %d", process.pid) encoding = sys.getdefaultencoding() with process.stdout: for line in iter(process.stdout.readline, b""): yield line.decode(encoding) process.wait() # wait for the subprocess to exit logger.info("script finished Pid: %d", process.pid) for fi in req_to_args.field_infos: fi.after_script_executed() def _create_cmd_header(commands: List[str]): """ Generate a command header. Note: here we always allow to generate HTML as long as we have it between CLICK-WEB comments. This way the JS frontend can insert it in the correct place in the DOM. """ def generate(): yield "<!-- CLICK_WEB START HEADER -->" yield '<div class="command-line">Executing: {}</div>'.format("/".join(commands)) yield "<!-- CLICK_WEB END HEADER -->" # important yield this block as one string so it pushed to client in one go. # so the whole block can be treated as html. html_str = "\n".join(generate()) return html_str def _create_result_footer(req_to_args: "RequestToCommandArgs"): """ Generate a footer. Note: here we always allow to generate HTML as long as we have it between CLICK-WEB comments. This way the JS frontend can insert it in the correct place in the DOM. """ to_download = [ fi for fi in req_to_args.field_infos if fi.generate_download_link and fi.link_name ] # important yield this block as one string so it pushed to client in one go. # This is so the whole block can be treated as html if JS frontend. lines = [] lines.append("<!-- CLICK_WEB START FOOTER -->") if to_download: lines.append("<b>Result files:</b><br>") for fi in to_download: lines.append("<ul> ") lines.append(f"<li>{_get_download_link(fi)}<br>") lines.append("</ul>") else: lines.append("<b>DONE</b>") lines.append("<!-- CLICK_WEB END FOOTER -->") html_str = "\n".join(lines) yield html_str def _get_download_link(field_info): """Hack as url_for need request context""" rel_file_path = Path(field_info.file_path).relative_to(click_web.OUTPUT_FOLDER) uri = f"/static/results/{rel_file_path.as_posix()}" return f'<a href="{uri}">{field_info.link_name}</a>' class RequestToCommandArgs: def __init__(self): field_infos = [ FieldInfo.factory(key) for key in list(request.form.keys()) + list(request.files.keys()) ] # important to sort them so they will be in expected order on command line self.field_infos = list(sorted(field_infos)) def command_args(self, command_index) -> List[str]: """ Convert the post request into a list of command line arguments :param command_index: (int) the index for the command to get arguments for. :return: list of command line arguments for command at that cmd_index """ args = [] # only include relevant fields for this command index commands_field_infos = [ fi for fi in self.field_infos if fi.param.command_index == command_index ] commands_field_infos = sorted(commands_field_infos) for fi in commands_field_infos: # must be called mostly for saving and preparing file output. fi.before_script_execute() if fi.cmd_opt.startswith("--"): # it's an option args.extend(self._process_option(fi)) else: # argument(s) if isinstance(fi, FieldFileInfo): # it's a file, append the written temp file path # TODO: does file upload support multiple keys? In that case support it. args.append(fi.file_path) else: arg_values = request.form.getlist(fi.key) has_values = bool("".join(arg_values)) if has_values: if fi.param.nargs == -1: # Variadic argument, in html form each argument # is a separate line in a textarea. # treat each line we get from text area as a separate argument. for value in arg_values: values = value.splitlines() logger.info( f'variadic arguments, split into: "{values}"' ) args.extend(values) else: logger.info(f'arg_value: "{arg_values}"') args.extend(arg_values) return args def _process_option(self, field_info): vals = request.form.getlist(field_info.key) if field_info.is_file: if field_info.link_name: # it's a file, append the file path yield field_info.cmd_opt yield field_info.file_path elif field_info.param.param_type == "flag": # To work with flag that is default True # a hidden field with same name is also sent by form. # This is to detect if checkbox was not checked as then # we will get the field anyway with the "off flag" as value. if len(vals) == 1: off_flag = vals[0] flag_on_cmd_line = off_flag else: # we got both off and on flags, checkbox is checked. on_flag = vals[1] flag_on_cmd_line = on_flag yield flag_on_cmd_line elif "".join(vals): # opt with value, if option was given multiple times get the values for each. # flag options should always be set if we get them # for normal options they must have a non empty value yield field_info.cmd_opt for val in vals: if val: yield val else: # option with empty values, should not be added to command line. pass class FieldInfo: """ Extract information from the encoded form input field name the parts: [command_index].[opt_or_arg_index].[click_type].[html_input_type].[opt_or_arg_name] e.g. "0.0.option.text.text.--an-option" "0.1.argument.file[rb].text.an-argument" """ @staticmethod def factory(key): field_id = FieldId.from_string(key) is_file = field_id.click_type.startswith("file") is_path = field_id.click_type.startswith("path") is_uploaded = key in request.files if is_file: if is_uploaded: field_info = FieldFileInfo(field_id) else: field_info = FieldOutFileInfo(field_id) elif is_path: if is_uploaded: field_info = FieldPathInfo(field_id) else: field_info = FieldPathOutInfo(field_id) else: field_info = FieldInfo(field_id) return field_info def __init__(self, param: FieldId): self.param = param self.key = param.key "Type of option (file, text)" self.is_file = self.param.click_type.startswith("file") "The actual command line option (--debug)" self.cmd_opt = param.name self.generate_download_link = False def before_script_execute(self): pass def after_script_executed(self): pass def __str__(self): return str(self.param) def __lt__(self, other): "Make class sortable" return (self.param.command_index, self.param.param_index) < ( other.param.command_index, other.param.param_index, ) def __eq__(self, other): return self.key == other.key class FieldFileInfo(FieldInfo): """ Use for processing input fields of file type. Saves the posted data to a temp file. """ "temp dir is on class in order to be uniqe for each request" _temp_dir = None def __init__(self, fimeta): super().__init__(fimeta) # Extract the file mode that is in the type e.g file[rw] self.mode = self.param.click_type.split("[")[1][:-1] self.generate_download_link = True if "w" in self.mode else False self.link_name = f"{self.cmd_opt}.out" logger.info(f"File mode for {self.key} is {self.mode}") def before_script_execute(self): self.save() @classmethod def temp_dir(cls): if not cls._temp_dir: cls._temp_dir = tempfile.mkdtemp(dir=click_web.OUTPUT_FOLDER) logger.info(f"Temp dir: {cls._temp_dir}") return cls._temp_dir def save(self): logger.info("Saving...") logger.info("field value is a file! %s", self.key) file = request.files[self.key] # if user does not select file, browser also # submit a empty part without filename if file.filename == "": raise ValueError("No selected file") elif file and file.filename: filename = secure_filename(file.filename) name, suffix = os.path.splitext(filename) fd, filename = tempfile.mkstemp( dir=self.temp_dir(), prefix=name, suffix=suffix ) self.file_path = filename logger.info(f"Saving {self.key} to {filename}") file.save(filename) def __str__(self): res = [super().__str__()] res.append(f"file_path: {self.file_path}") return ", ".join(res) class FieldOutFileInfo(FieldFileInfo): """ Used when file option is just for output and form posted it as hidden or text field. Just create a empty temp file to give it's path to command. """ def __init__(self, fimeta): super().__init__(fimeta) if self.param.form_type == "text": self.link_name = request.form[self.key] # set the postfix to name name provided from form # this way it will at least have the same extension when downloaded self.file_suffix = request.form[self.key] else: # hidden no preferred file name can be provided by user self.file_suffix = ".out" def save(self): name = secure_filename(self.key) filename = tempfile.mkstemp( dir=self.temp_dir(), prefix=name, suffix=self.file_suffix ) logger.info(f"Creating empty file for {self.key} as {filename}") self.file_path = filename class FieldPathInfo(FieldFileInfo): """ Use for processing input fields of path type. Extracts the posted data to a temp folder. When script finished zip that folder and provide download link to zip file. """ def save(self): super().save() zip_extract_dir = tempfile.mkdtemp(dir=self.temp_dir()) logger.info(f"Extracting: {self.file_path} to {zip_extract_dir}") shutil.unpack_archive(self.file_path, zip_extract_dir, "zip") self.file_path = zip_extract_dir def after_script_executed(self): super().after_script_executed() fd, filename = tempfile.mkstemp(dir=self.temp_dir(), prefix=self.key) folder_path = self.file_path self.file_path = filename logger.info(f"Zipping {self.key} to {filename}") self.file_path = shutil.make_archive(self.file_path, "zip", folder_path) logger.info(f"Zip file created {self.file_path}") self.generate_download_link = True class FieldPathOutInfo(FieldOutFileInfo): """ Use for processing output fields of path type. Create a folder and use as path to script. When script finished zip that folder and provide download link to zip file. """ def save(self): super().save() self.file_path = tempfile.mkdtemp(dir=self.temp_dir()) def after_script_executed(self): super().after_script_executed() fd, filename = tempfile.mkstemp(dir=self.temp_dir(), prefix=self.key) folder_path = self.file_path self.file_path = filename logger.info(f"Zipping {self.key} to {filename}") self.file_path = shutil.make_archive(self.file_path, "zip", folder_path) logger.info(f"Zip file created {self.file_path}") self.generate_download_link = True
import os import shutil import subprocess import sys import tempfile import traceback from pathlib import Path from typing import List from flask import Response, request from werkzeug.utils import secure_filename from archivy import click_web from .input_fields import FieldId logger = None def exec(command_path): """ Execute the command and stream the output from it as response :param command_path: """ command_path = "cli/" + command_path global logger logger = click_web.logger omitted = ["shell", "run", "routes", "create-admin"] root_command, *commands = command_path.split("/") cmd = ["archivy"] req_to_args = RequestToCommandArgs() # root command_index should not add a command cmd.extend(req_to_args.command_args(0)) for i, command in enumerate(commands): if command in omitted: return Response(status=400) cmd.append(command) cmd.extend(req_to_args.command_args(i + 1)) def _generate_output(): yield _create_cmd_header(commands) try: yield from _run_script_and_generate_stream(req_to_args, cmd) except Exception as e: # exited prematurely, show the error to user yield f"\nERROR: Got exception when reading output from script: {type(e)}\n" yield traceback.format_exc() raise return Response(_generate_output(), mimetype="text/plain") def _run_script_and_generate_stream( req_to_args: "RequestToCommandArgs", cmd: List[str] ): """ Execute the command the via Popen and yield output """ logger.info("Executing archivy command") if not os.environ.get("PYTHONIOENCODING"): # Fix unicode on windows os.environ["PYTHONIOENCODING"] = "UTF-8" process = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) logger.info("script running Pid: %d", process.pid) encoding = sys.getdefaultencoding() with process.stdout: for line in iter(process.stdout.readline, b""): yield line.decode(encoding) process.wait() # wait for the subprocess to exit logger.info("script finished Pid: %d", process.pid) for fi in req_to_args.field_infos: fi.after_script_executed() def _create_cmd_header(commands: List[str]): """ Generate a command header. Note: here we always allow to generate HTML as long as we have it between CLICK-WEB comments. This way the JS frontend can insert it in the correct place in the DOM. """ def generate(): yield "<!-- CLICK_WEB START HEADER -->" yield '<div class="command-line">Executing: {}</div>'.format("/".join(commands)) yield "<!-- CLICK_WEB END HEADER -->" # important yield this block as one string so it pushed to client in one go. # so the whole block can be treated as html. html_str = "\n".join(generate()) return html_str def _create_result_footer(req_to_args: "RequestToCommandArgs"): """ Generate a footer. Note: here we always allow to generate HTML as long as we have it between CLICK-WEB comments. This way the JS frontend can insert it in the correct place in the DOM. """ to_download = [ fi for fi in req_to_args.field_infos if fi.generate_download_link and fi.link_name ] # important yield this block as one string so it pushed to client in one go. # This is so the whole block can be treated as html if JS frontend. lines = [] lines.append("<!-- CLICK_WEB START FOOTER -->") if to_download: lines.append("<b>Result files:</b><br>") for fi in to_download: lines.append("<ul> ") lines.append(f"<li>{_get_download_link(fi)}<br>") lines.append("</ul>") else: lines.append("<b>DONE</b>") lines.append("<!-- CLICK_WEB END FOOTER -->") html_str = "\n".join(lines) yield html_str def _get_download_link(field_info): """Hack as url_for need request context""" rel_file_path = Path(field_info.file_path).relative_to(click_web.OUTPUT_FOLDER) uri = f"/static/results/{rel_file_path.as_posix()}" return f'<a href="{uri}">{field_info.link_name}</a>' class RequestToCommandArgs: def __init__(self): keys = [key for key in list(request.form.keys()) + list(request.files.keys())] field_infos = [FieldInfo.factory(key) for key in keys if key != "csrf_token"] # important to sort them so they will be in expected order on command line self.field_infos = list(sorted(field_infos)) def command_args(self, command_index) -> List[str]: """ Convert the post request into a list of command line arguments :param command_index: (int) the index for the command to get arguments for. :return: list of command line arguments for command at that cmd_index """ args = [] # only include relevant fields for this command index commands_field_infos = [ fi for fi in self.field_infos if fi.param.command_index == command_index ] commands_field_infos = sorted(commands_field_infos) for fi in commands_field_infos: # must be called mostly for saving and preparing file output. fi.before_script_execute() if fi.cmd_opt.startswith("--"): # it's an option args.extend(self._process_option(fi)) else: # argument(s) if isinstance(fi, FieldFileInfo): # it's a file, append the written temp file path # TODO: does file upload support multiple keys? In that case support it. args.append(fi.file_path) else: arg_values = request.form.getlist(fi.key) has_values = bool("".join(arg_values)) if has_values: if fi.param.nargs == -1: # Variadic argument, in html form each argument # is a separate line in a textarea. # treat each line we get from text area as a separate argument. for value in arg_values: values = value.splitlines() logger.info( f'variadic arguments, split into: "{values}"' ) args.extend(values) else: logger.info(f'arg_value: "{arg_values}"') args.extend(arg_values) return args def _process_option(self, field_info): vals = request.form.getlist(field_info.key) if field_info.is_file: if field_info.link_name: # it's a file, append the file path yield field_info.cmd_opt yield field_info.file_path elif field_info.param.param_type == "flag": # To work with flag that is default True # a hidden field with same name is also sent by form. # This is to detect if checkbox was not checked as then # we will get the field anyway with the "off flag" as value. if len(vals) == 1: off_flag = vals[0] flag_on_cmd_line = off_flag else: # we got both off and on flags, checkbox is checked. on_flag = vals[1] flag_on_cmd_line = on_flag yield flag_on_cmd_line elif "".join(vals): # opt with value, if option was given multiple times get the values for each. # flag options should always be set if we get them # for normal options they must have a non empty value yield field_info.cmd_opt for val in vals: if val: yield val else: # option with empty values, should not be added to command line. pass class FieldInfo: """ Extract information from the encoded form input field name the parts: [command_index].[opt_or_arg_index].[click_type].[html_input_type].[opt_or_arg_name] e.g. "0.0.option.text.text.--an-option" "0.1.argument.file[rb].text.an-argument" """ @staticmethod def factory(key): field_id = FieldId.from_string(key) is_file = field_id.click_type.startswith("file") is_path = field_id.click_type.startswith("path") is_uploaded = key in request.files if is_file: if is_uploaded: field_info = FieldFileInfo(field_id) else: field_info = FieldOutFileInfo(field_id) elif is_path: if is_uploaded: field_info = FieldPathInfo(field_id) else: field_info = FieldPathOutInfo(field_id) else: field_info = FieldInfo(field_id) return field_info def __init__(self, param: FieldId): self.param = param self.key = param.key "Type of option (file, text)" self.is_file = self.param.click_type.startswith("file") "The actual command line option (--debug)" self.cmd_opt = param.name self.generate_download_link = False def before_script_execute(self): pass def after_script_executed(self): pass def __str__(self): return str(self.param) def __lt__(self, other): "Make class sortable" return (self.param.command_index, self.param.param_index) < ( other.param.command_index, other.param.param_index, ) def __eq__(self, other): return self.key == other.key class FieldFileInfo(FieldInfo): """ Use for processing input fields of file type. Saves the posted data to a temp file. """ "temp dir is on class in order to be uniqe for each request" _temp_dir = None def __init__(self, fimeta): super().__init__(fimeta) # Extract the file mode that is in the type e.g file[rw] self.mode = self.param.click_type.split("[")[1][:-1] self.generate_download_link = True if "w" in self.mode else False self.link_name = f"{self.cmd_opt}.out" logger.info(f"File mode for {self.key} is {self.mode}") def before_script_execute(self): self.save() @classmethod def temp_dir(cls): if not cls._temp_dir: cls._temp_dir = tempfile.mkdtemp(dir=click_web.OUTPUT_FOLDER) logger.info(f"Temp dir: {cls._temp_dir}") return cls._temp_dir def save(self): logger.info("Saving...") logger.info("field value is a file! %s", self.key) file = request.files[self.key] # if user does not select file, browser also # submit a empty part without filename if file.filename == "": raise ValueError("No selected file") elif file and file.filename: filename = secure_filename(file.filename) name, suffix = os.path.splitext(filename) fd, filename = tempfile.mkstemp( dir=self.temp_dir(), prefix=name, suffix=suffix ) self.file_path = filename logger.info(f"Saving {self.key} to {filename}") file.save(filename) def __str__(self): res = [super().__str__()] res.append(f"file_path: {self.file_path}") return ", ".join(res) class FieldOutFileInfo(FieldFileInfo): """ Used when file option is just for output and form posted it as hidden or text field. Just create a empty temp file to give it's path to command. """ def __init__(self, fimeta): super().__init__(fimeta) if self.param.form_type == "text": self.link_name = request.form[self.key] # set the postfix to name name provided from form # this way it will at least have the same extension when downloaded self.file_suffix = request.form[self.key] else: # hidden no preferred file name can be provided by user self.file_suffix = ".out" def save(self): name = secure_filename(self.key) filename = tempfile.mkstemp( dir=self.temp_dir(), prefix=name, suffix=self.file_suffix ) logger.info(f"Creating empty file for {self.key} as {filename}") self.file_path = filename class FieldPathInfo(FieldFileInfo): """ Use for processing input fields of path type. Extracts the posted data to a temp folder. When script finished zip that folder and provide download link to zip file. """ def save(self): super().save() zip_extract_dir = tempfile.mkdtemp(dir=self.temp_dir()) logger.info(f"Extracting: {self.file_path} to {zip_extract_dir}") shutil.unpack_archive(self.file_path, zip_extract_dir, "zip") self.file_path = zip_extract_dir def after_script_executed(self): super().after_script_executed() fd, filename = tempfile.mkstemp(dir=self.temp_dir(), prefix=self.key) folder_path = self.file_path self.file_path = filename logger.info(f"Zipping {self.key} to {filename}") self.file_path = shutil.make_archive(self.file_path, "zip", folder_path) logger.info(f"Zip file created {self.file_path}") self.generate_download_link = True class FieldPathOutInfo(FieldOutFileInfo): """ Use for processing output fields of path type. Create a folder and use as path to script. When script finished zip that folder and provide download link to zip file. """ def save(self): super().save() self.file_path = tempfile.mkdtemp(dir=self.temp_dir()) def after_script_executed(self): super().after_script_executed() fd, filename = tempfile.mkstemp(dir=self.temp_dir(), prefix=self.key) folder_path = self.file_path self.file_path = filename logger.info(f"Zipping {self.key} to {filename}") self.file_path = shutil.make_archive(self.file_path, "zip", folder_path) logger.info(f"Zip file created {self.file_path}") self.generate_download_link = True
xsrf
{ "code": [ " field_infos = [", " FieldInfo.factory(key)", " for key in list(request.form.keys()) + list(request.files.keys())", " ]" ], "line_no": [ 140, 141, 142, 143 ] }
{ "code": [ " keys = [key for key in list(request.form.keys()) + list(request.files.keys())]", " field_infos = [FieldInfo.factory(key) for key in keys if key != \"csrf_token\"]" ], "line_no": [ 140, 141 ] }
import .os import shutil import subprocess import sys import tempfile import traceback from pathlib import Path from typing import List from flask import Response, request from werkzeug.utils import secure_filename from archivy import click_web from .input_fields import FieldId VAR_0 = None def FUNC_0(VAR_1): VAR_1 = "cli/" + VAR_1 global VAR_0 logger = click_web.logger VAR_6 = ["shell", "run", "routes", "create-admin"] VAR_7, *VAR_4 = VAR_1.split("/") VAR_3 = ["archivy"] VAR_2 = CLASS_0() VAR_3.extend(VAR_2.command_args(0)) for i, command in enumerate(VAR_4): if command in VAR_6: return Response(status=400) VAR_3.append(command) VAR_3.extend(VAR_2.command_args(i + 1)) def FUNC_5(): yield FUNC_2(VAR_4) try: yield from FUNC_1(VAR_2, VAR_3) except Exception as e: yield f"\nERROR: Got exception when reading output from script: {type(e)}\n" yield traceback.format_exc() raise return Response(FUNC_5(), mimetype="text/plain") def FUNC_1( VAR_2: "RequestToCommandArgs", VAR_3: List[str] ): VAR_0.info("Executing archivy command") if not VAR_22.environ.get("PYTHONIOENCODING"): VAR_22.environ["PYTHONIOENCODING"] = "UTF-8" VAR_8 = subprocess.Popen( VAR_3, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) VAR_0.info("script running Pid: %d", VAR_8.pid) VAR_9 = sys.getdefaultencoding() with VAR_8.stdout: for line in iter(VAR_8.stdout.readline, b""): yield line.decode(VAR_9) VAR_8.wait() # wait for the subprocess to exit VAR_0.info("script finished Pid: %d", VAR_8.pid) for fi in VAR_2.field_infos: fi.after_script_executed() def FUNC_2(VAR_4: List[str]): def FUNC_6(): yield "<!-- CLICK_WEB START HEADER -->" yield '<div class="command-line">Executing: {}</div>'.format("/".join(VAR_4)) yield "<!-- CLICK_WEB END HEADER -->" VAR_10 = "\n".join(FUNC_6()) return VAR_10 def FUNC_3(VAR_2: "RequestToCommandArgs"): VAR_11 = [ fi for fi in VAR_2.field_infos if fi.generate_download_link and fi.link_name ] VAR_12 = [] lines.append("<!-- CLICK_WEB START FOOTER -->") if VAR_11: VAR_12.append("<b>Result files:</b><br>") for fi in VAR_11: VAR_12.append("<ul> ") VAR_12.append(f"<li>{FUNC_4(fi)}<br>") VAR_12.append("</ul>") else: VAR_12.append("<b>DONE</b>") VAR_12.append("<!-- CLICK_WEB END FOOTER -->") VAR_10 = "\n".join(VAR_12) yield VAR_10 def FUNC_4(VAR_5): VAR_13 = Path(VAR_5.file_path).relative_to(click_web.OUTPUT_FOLDER) VAR_14 = f"/static/results/{VAR_13.as_posix()}" return f'<a href="{VAR_14}">{VAR_5.link_name}</a>' class CLASS_0: def __init__(self): VAR_23 = [ CLASS_1.factory(VAR_16) for VAR_16 in list(request.form.keys()) + list(request.files.keys()) ] self.field_infos = list(sorted(VAR_23)) def FUNC_7(self, VAR_15) -> List[str]: VAR_24 = [] VAR_25 = [ fi for fi in self.field_infos if fi.param.command_index == VAR_15 ] VAR_25 = sorted(VAR_25) for fi in VAR_25: fi.before_script_execute() if fi.cmd_opt.startswith("--"): VAR_24.extend(self._process_option(fi)) else: if isinstance(fi, CLASS_2): VAR_24.append(fi.file_path) else: VAR_39 = request.form.getlist(fi.key) VAR_40 = bool("".join(VAR_39)) if VAR_40: if fi.param.nargs == -1: for value in VAR_39: VAR_44 = value.splitlines() VAR_0.info( f'variadic arguments, split into: "{VAR_44}"' ) VAR_24.extend(VAR_44) else: VAR_0.info(f'arg_value: "{VAR_39}"') VAR_24.extend(VAR_39) return VAR_24 def FUNC_8(self, VAR_5): VAR_26 = request.form.getlist(VAR_5.key) if VAR_5.is_file: if VAR_5.link_name: yield VAR_5.cmd_opt yield VAR_5.file_path elif VAR_5.param.param_type == "flag": if len(VAR_26) == 1: VAR_41 = VAR_26[0] VAR_42 = VAR_41 else: VAR_43 = VAR_26[1] VAR_42 = VAR_43 yield VAR_42 elif "".join(VAR_26): yield VAR_5.cmd_opt for val in VAR_26: if val: yield val else: pass class CLASS_1: @staticmethod def FUNC_9(VAR_16): VAR_27 = FieldId.from_string(VAR_16) VAR_28 = VAR_27.click_type.startswith("file") VAR_29 = VAR_27.click_type.startswith("path") VAR_30 = VAR_16 in request.files if VAR_28: if VAR_30: VAR_5 = CLASS_2(VAR_27) else: VAR_5 = CLASS_3(VAR_27) elif VAR_29: if VAR_30: VAR_5 = CLASS_4(VAR_27) else: VAR_5 = CLASS_5(VAR_27) else: VAR_5 = CLASS_1(VAR_27) return VAR_5 def __init__(self, VAR_17: FieldId): self.param = VAR_17 self.key = VAR_17.key "Type of option (VAR_31, text)" self.is_file = self.param.click_type.startswith("file") "The actual command line option (--debug)" self.cmd_opt = VAR_17.name self.generate_download_link = False def FUNC_10(self): pass def FUNC_11(self): pass def __str__(self): return str(self.param) return (self.param.command_index, self.param.param_index) < ( VAR_18.param.command_index, VAR_18.param.param_index, ) def __eq__(self, VAR_18): return self.key == VAR_18.key class CLASS_2(CLASS_1): "temp dir is on class in order to be uniqe for each request" VAR_19 = None def __init__(self, VAR_20): super().__init__(VAR_20) self.mode = self.param.click_type.split("[")[1][:-1] self.generate_download_link = True if "w" in self.mode else False self.link_name = f"{self.cmd_opt}.out" VAR_0.info(f"File mode for {self.key} is {self.mode}") def FUNC_10(self): self.save() @classmethod def FUNC_12(VAR_21): if not VAR_21._temp_dir: VAR_21._temp_dir = tempfile.mkdtemp(dir=click_web.OUTPUT_FOLDER) VAR_0.info(f"Temp dir: {VAR_21._temp_dir}") return VAR_21._temp_dir def FUNC_13(self): VAR_0.info("Saving...") VAR_0.info("field value is a VAR_31! %s", self.key) VAR_31 = request.files[self.key] if VAR_31.filename == "": raise ValueError("No selected file") elif VAR_31 and VAR_31.filename: VAR_34 = secure_filename(VAR_31.filename) VAR_33, VAR_38 = VAR_22.path.splitext(VAR_34) VAR_36, VAR_34 = tempfile.mkstemp( dir=self.temp_dir(), prefix=VAR_33, VAR_38=suffix ) self.file_path = VAR_34 VAR_0.info(f"Saving {self.key} to {VAR_34}") VAR_31.save(VAR_34) def __str__(self): VAR_32 = [super().__str__()] VAR_32.append(f"file_path: {self.file_path}") return ", ".join(VAR_32) class CLASS_3(CLASS_2): def __init__(self, VAR_20): super().__init__(VAR_20) if self.param.form_type == "text": self.link_name = request.form[self.key] self.file_suffix = request.form[self.key] else: self.file_suffix = ".out" def FUNC_13(self): VAR_33 = secure_filename(self.key) VAR_34 = tempfile.mkstemp( dir=self.temp_dir(), prefix=VAR_33, VAR_38=self.file_suffix ) VAR_0.info(f"Creating empty VAR_31 for {self.key} as {VAR_34}") self.file_path = VAR_34 class CLASS_4(CLASS_2): def FUNC_13(self): super().save() VAR_35 = tempfile.mkdtemp(dir=self.temp_dir()) VAR_0.info(f"Extracting: {self.file_path} to {VAR_35}") shutil.unpack_archive(self.file_path, VAR_35, "zip") self.file_path = VAR_35 def FUNC_11(self): super().after_script_executed() VAR_36, VAR_34 = tempfile.mkstemp(dir=self.temp_dir(), prefix=self.key) VAR_37 = self.file_path self.file_path = VAR_34 VAR_0.info(f"Zipping {self.key} to {VAR_34}") self.file_path = shutil.make_archive(self.file_path, "zip", VAR_37) VAR_0.info(f"Zip VAR_31 created {self.file_path}") self.generate_download_link = True class CLASS_5(CLASS_3): def FUNC_13(self): super().save() self.file_path = tempfile.mkdtemp(dir=self.temp_dir()) def FUNC_11(self): super().after_script_executed() VAR_36, VAR_34 = tempfile.mkstemp(dir=self.temp_dir(), prefix=self.key) VAR_37 = self.file_path self.file_path = VAR_34 VAR_0.info(f"Zipping {self.key} to {VAR_34}") self.file_path = shutil.make_archive(self.file_path, "zip", VAR_37) VAR_0.info(f"Zip VAR_31 created {self.file_path}") self.generate_download_link = True
import .os import shutil import subprocess import sys import tempfile import traceback from pathlib import Path from typing import List from flask import Response, request from werkzeug.utils import secure_filename from archivy import click_web from .input_fields import FieldId VAR_0 = None def FUNC_0(VAR_1): VAR_1 = "cli/" + VAR_1 global VAR_0 logger = click_web.logger VAR_6 = ["shell", "run", "routes", "create-admin"] VAR_7, *VAR_4 = VAR_1.split("/") VAR_3 = ["archivy"] VAR_2 = CLASS_0() VAR_3.extend(VAR_2.command_args(0)) for i, command in enumerate(VAR_4): if command in VAR_6: return Response(status=400) VAR_3.append(command) VAR_3.extend(VAR_2.command_args(i + 1)) def FUNC_5(): yield FUNC_2(VAR_4) try: yield from FUNC_1(VAR_2, VAR_3) except Exception as e: yield f"\nERROR: Got exception when reading output from script: {type(e)}\n" yield traceback.format_exc() raise return Response(FUNC_5(), mimetype="text/plain") def FUNC_1( VAR_2: "RequestToCommandArgs", VAR_3: List[str] ): VAR_0.info("Executing archivy command") if not VAR_22.environ.get("PYTHONIOENCODING"): VAR_22.environ["PYTHONIOENCODING"] = "UTF-8" VAR_8 = subprocess.Popen( VAR_3, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) VAR_0.info("script running Pid: %d", VAR_8.pid) VAR_9 = sys.getdefaultencoding() with VAR_8.stdout: for line in iter(VAR_8.stdout.readline, b""): yield line.decode(VAR_9) VAR_8.wait() # wait for the subprocess to exit VAR_0.info("script finished Pid: %d", VAR_8.pid) for fi in VAR_2.field_infos: fi.after_script_executed() def FUNC_2(VAR_4: List[str]): def FUNC_6(): yield "<!-- CLICK_WEB START HEADER -->" yield '<div class="command-line">Executing: {}</div>'.format("/".join(VAR_4)) yield "<!-- CLICK_WEB END HEADER -->" VAR_10 = "\n".join(FUNC_6()) return VAR_10 def FUNC_3(VAR_2: "RequestToCommandArgs"): VAR_11 = [ fi for fi in VAR_2.field_infos if fi.generate_download_link and fi.link_name ] VAR_12 = [] lines.append("<!-- CLICK_WEB START FOOTER -->") if VAR_11: VAR_12.append("<b>Result files:</b><br>") for fi in VAR_11: VAR_12.append("<ul> ") VAR_12.append(f"<li>{FUNC_4(fi)}<br>") VAR_12.append("</ul>") else: VAR_12.append("<b>DONE</b>") VAR_12.append("<!-- CLICK_WEB END FOOTER -->") VAR_10 = "\n".join(VAR_12) yield VAR_10 def FUNC_4(VAR_5): VAR_13 = Path(VAR_5.file_path).relative_to(click_web.OUTPUT_FOLDER) VAR_14 = f"/static/results/{VAR_13.as_posix()}" return f'<a href="{VAR_14}">{VAR_5.link_name}</a>' class CLASS_0: def __init__(self): VAR_23 = [VAR_16 for VAR_16 in list(request.form.keys()) + list(request.files.keys())] VAR_24 = [CLASS_1.factory(VAR_16) for VAR_16 in VAR_23 if VAR_16 != "csrf_token"] self.field_infos = list(sorted(VAR_24)) def FUNC_7(self, VAR_15) -> List[str]: VAR_25 = [] VAR_26 = [ fi for fi in self.field_infos if fi.param.command_index == VAR_15 ] VAR_26 = sorted(VAR_26) for fi in VAR_26: fi.before_script_execute() if fi.cmd_opt.startswith("--"): VAR_25.extend(self._process_option(fi)) else: if isinstance(fi, CLASS_2): VAR_25.append(fi.file_path) else: VAR_40 = request.form.getlist(fi.key) VAR_41 = bool("".join(VAR_40)) if VAR_41: if fi.param.nargs == -1: for value in VAR_40: VAR_45 = value.splitlines() VAR_0.info( f'variadic arguments, split into: "{VAR_45}"' ) VAR_25.extend(VAR_45) else: VAR_0.info(f'arg_value: "{VAR_40}"') VAR_25.extend(VAR_40) return VAR_25 def FUNC_8(self, VAR_5): VAR_27 = request.form.getlist(VAR_5.key) if VAR_5.is_file: if VAR_5.link_name: yield VAR_5.cmd_opt yield VAR_5.file_path elif VAR_5.param.param_type == "flag": if len(VAR_27) == 1: VAR_42 = VAR_27[0] VAR_43 = VAR_42 else: VAR_44 = VAR_27[1] VAR_43 = VAR_44 yield VAR_43 elif "".join(VAR_27): yield VAR_5.cmd_opt for val in VAR_27: if val: yield val else: pass class CLASS_1: @staticmethod def FUNC_9(VAR_16): VAR_28 = FieldId.from_string(VAR_16) VAR_29 = VAR_28.click_type.startswith("file") VAR_30 = VAR_28.click_type.startswith("path") VAR_31 = VAR_16 in request.files if VAR_29: if VAR_31: VAR_5 = CLASS_2(VAR_28) else: VAR_5 = CLASS_3(VAR_28) elif VAR_30: if VAR_31: VAR_5 = CLASS_4(VAR_28) else: VAR_5 = CLASS_5(VAR_28) else: VAR_5 = CLASS_1(VAR_28) return VAR_5 def __init__(self, VAR_17: FieldId): self.param = VAR_17 self.key = VAR_17.key "Type of option (VAR_32, text)" self.is_file = self.param.click_type.startswith("file") "The actual command line option (--debug)" self.cmd_opt = VAR_17.name self.generate_download_link = False def FUNC_10(self): pass def FUNC_11(self): pass def __str__(self): return str(self.param) return (self.param.command_index, self.param.param_index) < ( VAR_18.param.command_index, VAR_18.param.param_index, ) def __eq__(self, VAR_18): return self.key == VAR_18.key class CLASS_2(CLASS_1): "temp dir is on class in order to be uniqe for each request" VAR_19 = None def __init__(self, VAR_20): super().__init__(VAR_20) self.mode = self.param.click_type.split("[")[1][:-1] self.generate_download_link = True if "w" in self.mode else False self.link_name = f"{self.cmd_opt}.out" VAR_0.info(f"File mode for {self.key} is {self.mode}") def FUNC_10(self): self.save() @classmethod def FUNC_12(VAR_21): if not VAR_21._temp_dir: VAR_21._temp_dir = tempfile.mkdtemp(dir=click_web.OUTPUT_FOLDER) VAR_0.info(f"Temp dir: {VAR_21._temp_dir}") return VAR_21._temp_dir def FUNC_13(self): VAR_0.info("Saving...") VAR_0.info("field value is a VAR_32! %s", self.key) VAR_32 = request.files[self.key] if VAR_32.filename == "": raise ValueError("No selected file") elif VAR_32 and VAR_32.filename: VAR_35 = secure_filename(VAR_32.filename) VAR_34, VAR_39 = VAR_22.path.splitext(VAR_35) VAR_37, VAR_35 = tempfile.mkstemp( dir=self.temp_dir(), prefix=VAR_34, VAR_39=suffix ) self.file_path = VAR_35 VAR_0.info(f"Saving {self.key} to {VAR_35}") VAR_32.save(VAR_35) def __str__(self): VAR_33 = [super().__str__()] VAR_33.append(f"file_path: {self.file_path}") return ", ".join(VAR_33) class CLASS_3(CLASS_2): def __init__(self, VAR_20): super().__init__(VAR_20) if self.param.form_type == "text": self.link_name = request.form[self.key] self.file_suffix = request.form[self.key] else: self.file_suffix = ".out" def FUNC_13(self): VAR_34 = secure_filename(self.key) VAR_35 = tempfile.mkstemp( dir=self.temp_dir(), prefix=VAR_34, VAR_39=self.file_suffix ) VAR_0.info(f"Creating empty VAR_32 for {self.key} as {VAR_35}") self.file_path = VAR_35 class CLASS_4(CLASS_2): def FUNC_13(self): super().save() VAR_36 = tempfile.mkdtemp(dir=self.temp_dir()) VAR_0.info(f"Extracting: {self.file_path} to {VAR_36}") shutil.unpack_archive(self.file_path, VAR_36, "zip") self.file_path = VAR_36 def FUNC_11(self): super().after_script_executed() VAR_37, VAR_35 = tempfile.mkstemp(dir=self.temp_dir(), prefix=self.key) VAR_38 = self.file_path self.file_path = VAR_35 VAR_0.info(f"Zipping {self.key} to {VAR_35}") self.file_path = shutil.make_archive(self.file_path, "zip", VAR_38) VAR_0.info(f"Zip VAR_32 created {self.file_path}") self.generate_download_link = True class CLASS_5(CLASS_3): def FUNC_13(self): super().save() self.file_path = tempfile.mkdtemp(dir=self.temp_dir()) def FUNC_11(self): super().after_script_executed() VAR_37, VAR_35 = tempfile.mkstemp(dir=self.temp_dir(), prefix=self.key) VAR_38 = self.file_path self.file_path = VAR_35 VAR_0.info(f"Zipping {self.key} to {VAR_35}") self.file_path = shutil.make_archive(self.file_path, "zip", VAR_38) VAR_0.info(f"Zip VAR_32 created {self.file_path}") self.generate_download_link = True
[ 9, 12, 14, 16, 18, 19, 28, 33, 40, 46, 50, 52, 53, 62, 64, 69, 74, 79, 80, 88, 93, 94, 95, 98, 99, 112, 113, 122, 128, 129, 132, 136, 137, 144, 146, 150, 155, 156, 161, 163, 164, 166, 168, 170, 172, 174, 175, 182, 183, 184, 195, 200, 204, 205, 206, 207, 212, 215, 218, 219, 220, 226, 228, 229, 239, 259, 263, 266, 269, 271, 274, 277, 280, 287, 290, 291, 297, 300, 303, 307, 309, 312, 319, 322, 325, 326, 332, 339, 341, 345, 346, 352, 357, 358, 361, 363, 366, 372, 373, 380, 384, 388, 394, 399, 400, 407, 411, 421, 21, 22, 23, 24, 57, 58, 59, 82, 83, 84, 85, 86, 87, 101, 102, 103, 104, 105, 106, 131, 231, 232, 233, 234, 235, 236, 237, 238, 293, 294, 295, 296, 348, 349, 350, 351, 375, 376, 377, 378, 379, 402, 403, 404, 405, 406, 148, 149, 150, 151, 152, 153, 281, 282 ]
[ 9, 12, 14, 16, 18, 19, 28, 33, 40, 46, 50, 52, 53, 62, 64, 69, 74, 79, 80, 88, 93, 94, 95, 98, 99, 112, 113, 122, 128, 129, 132, 136, 137, 142, 144, 148, 153, 154, 159, 161, 162, 164, 166, 168, 170, 172, 173, 180, 181, 182, 193, 198, 202, 203, 204, 205, 210, 213, 216, 217, 218, 224, 226, 227, 237, 257, 261, 264, 267, 269, 272, 275, 278, 285, 288, 289, 295, 298, 301, 305, 307, 310, 317, 320, 323, 324, 330, 337, 339, 343, 344, 350, 355, 356, 359, 361, 364, 370, 371, 378, 382, 386, 392, 397, 398, 405, 409, 419, 21, 22, 23, 24, 57, 58, 59, 82, 83, 84, 85, 86, 87, 101, 102, 103, 104, 105, 106, 131, 229, 230, 231, 232, 233, 234, 235, 236, 291, 292, 293, 294, 346, 347, 348, 349, 373, 374, 375, 376, 377, 400, 401, 402, 403, 404, 146, 147, 148, 149, 150, 151, 279, 280 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2018 New Vector # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock from twisted.internet.defer import Deferred import synapse.rest.admin from synapse.logging.context import make_deferred_yieldable from synapse.rest.client.v1 import login, room from synapse.rest.client.v2_alpha import receipts from tests.unittest import HomeserverTestCase, override_config class HTTPPusherTests(HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, receipts.register_servlets, ] user_id = True hijack_auth = False def make_homeserver(self, reactor, clock): self.push_attempts = [] m = Mock() def post_json_get_json(url, body): d = Deferred() self.push_attempts.append((d, url, body)) return make_deferred_yieldable(d) m.post_json_get_json = post_json_get_json config = self.default_config() config["start_pushers"] = True hs = self.setup_test_homeserver(config=config, proxied_http_client=m) return hs def test_sends_http(self): """ The HTTP pusher will send pushes for each message to a HTTP endpoint when configured to do so. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other user joins self.helper.join(room=room, user=other_user_id, tok=other_access_token) # The other user sends some messages self.helper.send(room, body="Hi!", tok=other_access_token) self.helper.send(room, body="There!", tok=other_access_token) # Get the stream ordering before it gets sent pushers = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": user_id}) ) pushers = list(pushers) self.assertEqual(len(pushers), 1) last_stream_ordering = pushers[0]["last_stream_ordering"] # Advance time a bit, so the pusher will register something has happened self.pump() # It hasn't succeeded yet, so the stream ordering shouldn't have moved pushers = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": user_id}) ) pushers = list(pushers) self.assertEqual(len(pushers), 1) self.assertEqual(last_stream_ordering, pushers[0]["last_stream_ordering"]) # One push was attempted to be sent -- it'll be the first message self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual( self.push_attempts[0][2]["notification"]["content"]["body"], "Hi!" ) # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # The stream ordering has increased pushers = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": user_id}) ) pushers = list(pushers) self.assertEqual(len(pushers), 1) self.assertTrue(pushers[0]["last_stream_ordering"] > last_stream_ordering) last_stream_ordering = pushers[0]["last_stream_ordering"] # Now it'll try and send the second push message, which will be the second one self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual( self.push_attempts[1][2]["notification"]["content"]["body"], "There!" ) # Make the second push succeed self.push_attempts[1][0].callback({}) self.pump() # The stream ordering has increased, again pushers = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": user_id}) ) pushers = list(pushers) self.assertEqual(len(pushers), 1) self.assertTrue(pushers[0]["last_stream_ordering"] > last_stream_ordering) def test_sends_high_priority_for_encrypted(self): """ The HTTP pusher will send pushes at high priority if they correspond to an encrypted message. This will happen both in 1:1 rooms and larger rooms. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register a third user yet_another_user_id = self.register_user("yetanotheruser", "pass") yet_another_access_token = self.login("yetanotheruser", "pass") # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other user joins self.helper.join(room=room, user=other_user_id, tok=other_access_token) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send an encrypted event # I know there'd normally be set-up of an encrypted room first # but this will do for our purposes self.helper.send_event( room, "m.room.encrypted", content={ "algorithm": "m.megolm.v1.aes-sha2", "sender_key": "6lImKbzK51MzWLwHh8tUM3UBBSBrLlgup/OOCGTvumM", "ciphertext": "AwgAErABoRxwpMipdgiwXgu46rHiWQ0DmRj0qUlPrMraBUDk" "leTnJRljpuc7IOhsYbLY3uo2WI0ab/ob41sV+3JEIhODJPqH" "TK7cEZaIL+/up9e+dT9VGF5kRTWinzjkeqO8FU5kfdRjm+3w" "0sy3o1OCpXXCfO+faPhbV/0HuK4ndx1G+myNfK1Nk/CxfMcT" "BT+zDS/Df/QePAHVbrr9uuGB7fW8ogW/ulnydgZPRluusFGv" "J3+cg9LoPpZPAmv5Me3ec7NtdlfN0oDZ0gk3TiNkkhsxDG9Y" "YcNzl78USI0q8+kOV26Bu5dOBpU4WOuojXZHJlP5lMgdzLLl" "EQ0", "session_id": "IigqfNWLL+ez/Is+Duwp2s4HuCZhFG9b9CZKTYHtQ4A", "device_id": "AHQDUSTAAA", }, tok=other_access_token, ) # Advance time a bit, so the pusher will register something has happened self.pump() # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it with high priority self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") # Add yet another person — we want to make this room not a 1:1 # (as encrypted messages in a 1:1 currently have tweaks applied # so it doesn't properly exercise the condition of all encrypted # messages need to be high). self.helper.join( room=room, user=yet_another_user_id, tok=yet_another_access_token ) # Check no push notifications are sent regarding the membership changes # (that would confuse the test) self.pump() self.assertEqual(len(self.push_attempts), 1) # Send another encrypted event self.helper.send_event( room, "m.room.encrypted", content={ "ciphertext": "AwgAEoABtEuic/2DF6oIpNH+q/PonzlhXOVho8dTv0tzFr5m" "9vTo50yabx3nxsRlP2WxSqa8I07YftP+EKWCWJvTkg6o7zXq" "6CK+GVvLQOVgK50SfvjHqJXN+z1VEqj+5mkZVN/cAgJzoxcH" "zFHkwDPJC8kQs47IHd8EO9KBUK4v6+NQ1uE/BIak4qAf9aS/" "kI+f0gjn9IY9K6LXlah82A/iRyrIrxkCkE/n0VfvLhaWFecC" "sAWTcMLoF6fh1Jpke95mljbmFSpsSd/eEQw", "device_id": "SRCFTWTHXO", "session_id": "eMA+bhGczuTz1C5cJR1YbmrnnC6Goni4lbvS5vJ1nG4", "algorithm": "m.megolm.v1.aes-sha2", "sender_key": "rC/XSIAiYrVGSuaHMop8/pTZbku4sQKBZwRwukgnN1c", }, tok=other_access_token, ) # Advance time a bit, so the pusher will register something has happened self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "high") def test_sends_high_priority_for_one_to_one_only(self): """ The HTTP pusher will send pushes at high priority if they correspond to a message in a one-to-one room. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register a third user yet_another_user_id = self.register_user("yetanotheruser", "pass") yet_another_access_token = self.login("yetanotheruser", "pass") # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other user joins self.helper.join(room=room, user=other_user_id, tok=other_access_token) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send a message self.helper.send(room, body="Hi!", tok=other_access_token) # Advance time a bit, so the pusher will register something has happened self.pump() # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it with high priority — this is a one-to-one room self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") # Yet another user joins self.helper.join( room=room, user=yet_another_user_id, tok=yet_another_access_token ) # Check no push notifications are sent regarding the membership changes # (that would confuse the test) self.pump() self.assertEqual(len(self.push_attempts), 1) # Send another event self.helper.send(room, body="Welcome!", tok=other_access_token) # Advance time a bit, so the pusher will register something has happened self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") # check that this is low-priority self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def test_sends_high_priority_for_mention(self): """ The HTTP pusher will send pushes at high priority if they correspond to a message containing the user's display name. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register a third user yet_another_user_id = self.register_user("yetanotheruser", "pass") yet_another_access_token = self.login("yetanotheruser", "pass") # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other users join self.helper.join(room=room, user=other_user_id, tok=other_access_token) self.helper.join( room=room, user=yet_another_user_id, tok=yet_another_access_token ) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send a message self.helper.send(room, body="Oh, user, hello!", tok=other_access_token) # Advance time a bit, so the pusher will register something has happened self.pump() # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it with high priority self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") # Send another event, this time with no mention self.helper.send(room, body="Are you there?", tok=other_access_token) # Advance time a bit, so the pusher will register something has happened self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") # check that this is low-priority self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def test_sends_high_priority_for_atroom(self): """ The HTTP pusher will send pushes at high priority if they correspond to a message that contains @room. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register a third user yet_another_user_id = self.register_user("yetanotheruser", "pass") yet_another_access_token = self.login("yetanotheruser", "pass") # Create a room (as other_user so the power levels are compatible with # other_user sending @room). room = self.helper.create_room_as(other_user_id, tok=other_access_token) # The other users join self.helper.join(room=room, user=user_id, tok=access_token) self.helper.join( room=room, user=yet_another_user_id, tok=yet_another_access_token ) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send a message self.helper.send( room, body="@room eeek! There's a spider on the table!", tok=other_access_token, ) # Advance time a bit, so the pusher will register something has happened self.pump() # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it with high priority self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") # Send another event, this time as someone without the power of @room self.helper.send( room, body="@room the spider is gone", tok=yet_another_access_token ) # Advance time a bit, so the pusher will register something has happened self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") # check that this is low-priority self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def test_push_unread_count_group_by_room(self): """ The HTTP pusher will group unread count by number of unread rooms. """ # Carry out common push count tests and setup self._test_push_unread_count() # Carry out our option-value specific test # # This push should still only contain an unread count of 1 (for 1 unread room) self.assertEqual( self.push_attempts[5][2]["notification"]["counts"]["unread"], 1 ) @override_config({"push": {"group_unread_count_by_room": False}}) def test_push_unread_count_message_count(self): """ The HTTP pusher will send the total unread message count. """ # Carry out common push count tests and setup self._test_push_unread_count() # Carry out our option-value specific test # # We're counting every unread message, so there should now be 4 since the # last read receipt self.assertEqual( self.push_attempts[5][2]["notification"]["counts"]["unread"], 4 ) def _test_push_unread_count(self): """ Tests that the correct unread count appears in sent push notifications Note that: * Sending messages will cause push notifications to go out to relevant users * Sending a read receipt will cause a "badge update" notification to go out to the user that sent the receipt """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("other_user", "pass") other_access_token = self.login("other_user", "pass") # Create a room (as other_user) room_id = self.helper.create_room_as(other_user_id, tok=other_access_token) # The user to get notified joins self.helper.join(room=room_id, user=user_id, tok=access_token) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send a message response = self.helper.send( room_id, body="Hello there!", tok=other_access_token ) # To get an unread count, the user who is getting notified has to have a read # position in the room. We'll set the read position to this event in a moment first_message_event_id = response["event_id"] # Advance time a bit (so the pusher will register something has happened) and # make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") # Check that the unread count for the room is 0 # # The unread count is zero as the user has no read receipt in the room yet self.assertEqual( self.push_attempts[0][2]["notification"]["counts"]["unread"], 0 ) # Now set the user's read receipt position to the first event # # This will actually trigger a new notification to be sent out so that # even if the user does not receive another message, their unread # count goes down request, channel = self.make_request( "POST", "/rooms/%s/receipt/m.read/%s" % (room_id, first_message_event_id), {}, access_token=access_token, ) self.assertEqual(channel.code, 200, channel.json_body) # Advance time and make the push succeed self.push_attempts[1][0].callback({}) self.pump() # Unread count is still zero as we've read the only message in the room self.assertEqual(len(self.push_attempts), 2) self.assertEqual( self.push_attempts[1][2]["notification"]["counts"]["unread"], 0 ) # Send another message self.helper.send( room_id, body="How's the weather today?", tok=other_access_token ) # Advance time and make the push succeed self.push_attempts[2][0].callback({}) self.pump() # This push should contain an unread count of 1 as there's now been one # message since our last read receipt self.assertEqual(len(self.push_attempts), 3) self.assertEqual( self.push_attempts[2][2]["notification"]["counts"]["unread"], 1 ) # Since we're grouping by room, sending more messages shouldn't increase the # unread count, as they're all being sent in the same room self.helper.send(room_id, body="Hello?", tok=other_access_token) # Advance time and make the push succeed self.pump() self.push_attempts[3][0].callback({}) self.helper.send(room_id, body="Hello??", tok=other_access_token) # Advance time and make the push succeed self.pump() self.push_attempts[4][0].callback({}) self.helper.send(room_id, body="HELLO???", tok=other_access_token) # Advance time and make the push succeed self.pump() self.push_attempts[5][0].callback({}) self.assertEqual(len(self.push_attempts), 6)
# -*- coding: utf-8 -*- # Copyright 2018 New Vector # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock from twisted.internet.defer import Deferred import synapse.rest.admin from synapse.logging.context import make_deferred_yieldable from synapse.rest.client.v1 import login, room from synapse.rest.client.v2_alpha import receipts from tests.unittest import HomeserverTestCase, override_config class HTTPPusherTests(HomeserverTestCase): servlets = [ synapse.rest.admin.register_servlets_for_client_rest_resource, room.register_servlets, login.register_servlets, receipts.register_servlets, ] user_id = True hijack_auth = False def make_homeserver(self, reactor, clock): self.push_attempts = [] m = Mock() def post_json_get_json(url, body): d = Deferred() self.push_attempts.append((d, url, body)) return make_deferred_yieldable(d) m.post_json_get_json = post_json_get_json config = self.default_config() config["start_pushers"] = True hs = self.setup_test_homeserver( config=config, proxied_blacklisted_http_client=m ) return hs def test_sends_http(self): """ The HTTP pusher will send pushes for each message to a HTTP endpoint when configured to do so. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other user joins self.helper.join(room=room, user=other_user_id, tok=other_access_token) # The other user sends some messages self.helper.send(room, body="Hi!", tok=other_access_token) self.helper.send(room, body="There!", tok=other_access_token) # Get the stream ordering before it gets sent pushers = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": user_id}) ) pushers = list(pushers) self.assertEqual(len(pushers), 1) last_stream_ordering = pushers[0]["last_stream_ordering"] # Advance time a bit, so the pusher will register something has happened self.pump() # It hasn't succeeded yet, so the stream ordering shouldn't have moved pushers = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": user_id}) ) pushers = list(pushers) self.assertEqual(len(pushers), 1) self.assertEqual(last_stream_ordering, pushers[0]["last_stream_ordering"]) # One push was attempted to be sent -- it'll be the first message self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual( self.push_attempts[0][2]["notification"]["content"]["body"], "Hi!" ) # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # The stream ordering has increased pushers = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": user_id}) ) pushers = list(pushers) self.assertEqual(len(pushers), 1) self.assertTrue(pushers[0]["last_stream_ordering"] > last_stream_ordering) last_stream_ordering = pushers[0]["last_stream_ordering"] # Now it'll try and send the second push message, which will be the second one self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual( self.push_attempts[1][2]["notification"]["content"]["body"], "There!" ) # Make the second push succeed self.push_attempts[1][0].callback({}) self.pump() # The stream ordering has increased, again pushers = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": user_id}) ) pushers = list(pushers) self.assertEqual(len(pushers), 1) self.assertTrue(pushers[0]["last_stream_ordering"] > last_stream_ordering) def test_sends_high_priority_for_encrypted(self): """ The HTTP pusher will send pushes at high priority if they correspond to an encrypted message. This will happen both in 1:1 rooms and larger rooms. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register a third user yet_another_user_id = self.register_user("yetanotheruser", "pass") yet_another_access_token = self.login("yetanotheruser", "pass") # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other user joins self.helper.join(room=room, user=other_user_id, tok=other_access_token) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send an encrypted event # I know there'd normally be set-up of an encrypted room first # but this will do for our purposes self.helper.send_event( room, "m.room.encrypted", content={ "algorithm": "m.megolm.v1.aes-sha2", "sender_key": "6lImKbzK51MzWLwHh8tUM3UBBSBrLlgup/OOCGTvumM", "ciphertext": "AwgAErABoRxwpMipdgiwXgu46rHiWQ0DmRj0qUlPrMraBUDk" "leTnJRljpuc7IOhsYbLY3uo2WI0ab/ob41sV+3JEIhODJPqH" "TK7cEZaIL+/up9e+dT9VGF5kRTWinzjkeqO8FU5kfdRjm+3w" "0sy3o1OCpXXCfO+faPhbV/0HuK4ndx1G+myNfK1Nk/CxfMcT" "BT+zDS/Df/QePAHVbrr9uuGB7fW8ogW/ulnydgZPRluusFGv" "J3+cg9LoPpZPAmv5Me3ec7NtdlfN0oDZ0gk3TiNkkhsxDG9Y" "YcNzl78USI0q8+kOV26Bu5dOBpU4WOuojXZHJlP5lMgdzLLl" "EQ0", "session_id": "IigqfNWLL+ez/Is+Duwp2s4HuCZhFG9b9CZKTYHtQ4A", "device_id": "AHQDUSTAAA", }, tok=other_access_token, ) # Advance time a bit, so the pusher will register something has happened self.pump() # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it with high priority self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") # Add yet another person — we want to make this room not a 1:1 # (as encrypted messages in a 1:1 currently have tweaks applied # so it doesn't properly exercise the condition of all encrypted # messages need to be high). self.helper.join( room=room, user=yet_another_user_id, tok=yet_another_access_token ) # Check no push notifications are sent regarding the membership changes # (that would confuse the test) self.pump() self.assertEqual(len(self.push_attempts), 1) # Send another encrypted event self.helper.send_event( room, "m.room.encrypted", content={ "ciphertext": "AwgAEoABtEuic/2DF6oIpNH+q/PonzlhXOVho8dTv0tzFr5m" "9vTo50yabx3nxsRlP2WxSqa8I07YftP+EKWCWJvTkg6o7zXq" "6CK+GVvLQOVgK50SfvjHqJXN+z1VEqj+5mkZVN/cAgJzoxcH" "zFHkwDPJC8kQs47IHd8EO9KBUK4v6+NQ1uE/BIak4qAf9aS/" "kI+f0gjn9IY9K6LXlah82A/iRyrIrxkCkE/n0VfvLhaWFecC" "sAWTcMLoF6fh1Jpke95mljbmFSpsSd/eEQw", "device_id": "SRCFTWTHXO", "session_id": "eMA+bhGczuTz1C5cJR1YbmrnnC6Goni4lbvS5vJ1nG4", "algorithm": "m.megolm.v1.aes-sha2", "sender_key": "rC/XSIAiYrVGSuaHMop8/pTZbku4sQKBZwRwukgnN1c", }, tok=other_access_token, ) # Advance time a bit, so the pusher will register something has happened self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "high") def test_sends_high_priority_for_one_to_one_only(self): """ The HTTP pusher will send pushes at high priority if they correspond to a message in a one-to-one room. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register a third user yet_another_user_id = self.register_user("yetanotheruser", "pass") yet_another_access_token = self.login("yetanotheruser", "pass") # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other user joins self.helper.join(room=room, user=other_user_id, tok=other_access_token) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send a message self.helper.send(room, body="Hi!", tok=other_access_token) # Advance time a bit, so the pusher will register something has happened self.pump() # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it with high priority — this is a one-to-one room self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") # Yet another user joins self.helper.join( room=room, user=yet_another_user_id, tok=yet_another_access_token ) # Check no push notifications are sent regarding the membership changes # (that would confuse the test) self.pump() self.assertEqual(len(self.push_attempts), 1) # Send another event self.helper.send(room, body="Welcome!", tok=other_access_token) # Advance time a bit, so the pusher will register something has happened self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") # check that this is low-priority self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def test_sends_high_priority_for_mention(self): """ The HTTP pusher will send pushes at high priority if they correspond to a message containing the user's display name. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register a third user yet_another_user_id = self.register_user("yetanotheruser", "pass") yet_another_access_token = self.login("yetanotheruser", "pass") # Create a room room = self.helper.create_room_as(user_id, tok=access_token) # The other users join self.helper.join(room=room, user=other_user_id, tok=other_access_token) self.helper.join( room=room, user=yet_another_user_id, tok=yet_another_access_token ) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send a message self.helper.send(room, body="Oh, user, hello!", tok=other_access_token) # Advance time a bit, so the pusher will register something has happened self.pump() # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it with high priority self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") # Send another event, this time with no mention self.helper.send(room, body="Are you there?", tok=other_access_token) # Advance time a bit, so the pusher will register something has happened self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") # check that this is low-priority self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def test_sends_high_priority_for_atroom(self): """ The HTTP pusher will send pushes at high priority if they correspond to a message that contains @room. """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("otheruser", "pass") other_access_token = self.login("otheruser", "pass") # Register a third user yet_another_user_id = self.register_user("yetanotheruser", "pass") yet_another_access_token = self.login("yetanotheruser", "pass") # Create a room (as other_user so the power levels are compatible with # other_user sending @room). room = self.helper.create_room_as(other_user_id, tok=other_access_token) # The other users join self.helper.join(room=room, user=user_id, tok=access_token) self.helper.join( room=room, user=yet_another_user_id, tok=yet_another_access_token ) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send a message self.helper.send( room, body="@room eeek! There's a spider on the table!", tok=other_access_token, ) # Advance time a bit, so the pusher will register something has happened self.pump() # Make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it with high priority self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") # Send another event, this time as someone without the power of @room self.helper.send( room, body="@room the spider is gone", tok=yet_another_access_token ) # Advance time a bit, so the pusher will register something has happened self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") # check that this is low-priority self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def test_push_unread_count_group_by_room(self): """ The HTTP pusher will group unread count by number of unread rooms. """ # Carry out common push count tests and setup self._test_push_unread_count() # Carry out our option-value specific test # # This push should still only contain an unread count of 1 (for 1 unread room) self.assertEqual( self.push_attempts[5][2]["notification"]["counts"]["unread"], 1 ) @override_config({"push": {"group_unread_count_by_room": False}}) def test_push_unread_count_message_count(self): """ The HTTP pusher will send the total unread message count. """ # Carry out common push count tests and setup self._test_push_unread_count() # Carry out our option-value specific test # # We're counting every unread message, so there should now be 4 since the # last read receipt self.assertEqual( self.push_attempts[5][2]["notification"]["counts"]["unread"], 4 ) def _test_push_unread_count(self): """ Tests that the correct unread count appears in sent push notifications Note that: * Sending messages will cause push notifications to go out to relevant users * Sending a read receipt will cause a "badge update" notification to go out to the user that sent the receipt """ # Register the user who gets notified user_id = self.register_user("user", "pass") access_token = self.login("user", "pass") # Register the user who sends the message other_user_id = self.register_user("other_user", "pass") other_access_token = self.login("other_user", "pass") # Create a room (as other_user) room_id = self.helper.create_room_as(other_user_id, tok=other_access_token) # The user to get notified joins self.helper.join(room=room_id, user=user_id, tok=access_token) # Register the pusher user_tuple = self.get_success( self.hs.get_datastore().get_user_by_access_token(access_token) ) token_id = user_tuple.token_id self.get_success( self.hs.get_pusherpool().add_pusher( user_id=user_id, access_token=token_id, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) # Send a message response = self.helper.send( room_id, body="Hello there!", tok=other_access_token ) # To get an unread count, the user who is getting notified has to have a read # position in the room. We'll set the read position to this event in a moment first_message_event_id = response["event_id"] # Advance time a bit (so the pusher will register something has happened) and # make the push succeed self.push_attempts[0][0].callback({}) self.pump() # Check our push made it self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") # Check that the unread count for the room is 0 # # The unread count is zero as the user has no read receipt in the room yet self.assertEqual( self.push_attempts[0][2]["notification"]["counts"]["unread"], 0 ) # Now set the user's read receipt position to the first event # # This will actually trigger a new notification to be sent out so that # even if the user does not receive another message, their unread # count goes down request, channel = self.make_request( "POST", "/rooms/%s/receipt/m.read/%s" % (room_id, first_message_event_id), {}, access_token=access_token, ) self.assertEqual(channel.code, 200, channel.json_body) # Advance time and make the push succeed self.push_attempts[1][0].callback({}) self.pump() # Unread count is still zero as we've read the only message in the room self.assertEqual(len(self.push_attempts), 2) self.assertEqual( self.push_attempts[1][2]["notification"]["counts"]["unread"], 0 ) # Send another message self.helper.send( room_id, body="How's the weather today?", tok=other_access_token ) # Advance time and make the push succeed self.push_attempts[2][0].callback({}) self.pump() # This push should contain an unread count of 1 as there's now been one # message since our last read receipt self.assertEqual(len(self.push_attempts), 3) self.assertEqual( self.push_attempts[2][2]["notification"]["counts"]["unread"], 1 ) # Since we're grouping by room, sending more messages shouldn't increase the # unread count, as they're all being sent in the same room self.helper.send(room_id, body="Hello?", tok=other_access_token) # Advance time and make the push succeed self.pump() self.push_attempts[3][0].callback({}) self.helper.send(room_id, body="Hello??", tok=other_access_token) # Advance time and make the push succeed self.pump() self.push_attempts[4][0].callback({}) self.helper.send(room_id, body="HELLO???", tok=other_access_token) # Advance time and make the push succeed self.pump() self.push_attempts[5][0].callback({}) self.assertEqual(len(self.push_attempts), 6)
open_redirect
{ "code": [ " hs = self.setup_test_homeserver(config=config, proxied_http_client=m)" ], "line_no": [ 52 ] }
{ "code": [ " hs = self.setup_test_homeserver(", " )" ], "line_no": [ 52, 54 ] }
from mock import Mock from twisted.internet.defer import Deferred import synapse.rest.admin from synapse.logging.context import .make_deferred_yieldable from synapse.rest.client.v1 import login, VAR_15 from synapse.rest.client.v2_alpha import receipts from tests.unittest import HomeserverTestCase, override_config class CLASS_0(HomeserverTestCase): VAR_0 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_15.register_servlets, login.register_servlets, receipts.register_servlets, ] VAR_1 = True VAR_2 = False def FUNC_0(self, VAR_3, VAR_4): self.push_attempts = [] VAR_5 = Mock() def FUNC_9(VAR_6, VAR_7): VAR_25 = Deferred() self.push_attempts.append((VAR_25, VAR_6, VAR_7)) return make_deferred_yieldable(VAR_25) VAR_5.post_json_get_json = FUNC_9 VAR_8 = self.default_config() VAR_8["start_pushers"] = True VAR_9 = self.setup_test_homeserver(VAR_8=config, proxied_http_client=VAR_5) return VAR_9 def FUNC_1(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) VAR_15 = self.helper.create_room_as(VAR_1, tok=VAR_10) self.helper.join(VAR_15=room, user=VAR_11, tok=VAR_12) self.helper.send(VAR_15, VAR_7="Hi!", tok=VAR_12) self.helper.send(VAR_15, VAR_7="There!", tok=VAR_12) VAR_16 = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": VAR_1}) ) VAR_16 = list(VAR_16) self.assertEqual(len(VAR_16), 1) VAR_17 = VAR_16[0]["last_stream_ordering"] self.pump() VAR_16 = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": VAR_1}) ) VAR_16 = list(VAR_16) self.assertEqual(len(VAR_16), 1) self.assertEqual(VAR_17, VAR_16[0]["last_stream_ordering"]) self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual( self.push_attempts[0][2]["notification"]["content"]["body"], "Hi!" ) self.push_attempts[0][0].callback({}) self.pump() VAR_16 = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": VAR_1}) ) VAR_16 = list(VAR_16) self.assertEqual(len(VAR_16), 1) self.assertTrue(VAR_16[0]["last_stream_ordering"] > VAR_17) VAR_17 = VAR_16[0]["last_stream_ordering"] self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual( self.push_attempts[1][2]["notification"]["content"]["body"], "There!" ) self.push_attempts[1][0].callback({}) self.pump() VAR_16 = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": VAR_1}) ) VAR_16 = list(VAR_16) self.assertEqual(len(VAR_16), 1) self.assertTrue(VAR_16[0]["last_stream_ordering"] > VAR_17) def FUNC_2(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_18 = self.register_user("yetanotheruser", "pass") VAR_19 = self.login("yetanotheruser", "pass") VAR_15 = self.helper.create_room_as(VAR_1, tok=VAR_10) self.helper.join(VAR_15=room, user=VAR_11, tok=VAR_12) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) self.helper.send_event( VAR_15, "m.room.encrypted", content={ "algorithm": "m.megolm.v1.aes-sha2", "sender_key": "6lImKbzK51MzWLwHh8tUM3UBBSBrLlgup/OOCGTvumM", "ciphertext": "AwgAErABoRxwpMipdgiwXgu46rHiWQ0DmRj0qUlPrMraBUDk" "leTnJRljpuc7IOhsYbLY3uo2WI0ab/ob41sV+3JEIhODJPqH" "TK7cEZaIL+/up9e+dT9VGF5kRTWinzjkeqO8FU5kfdRjm+3w" "0sy3o1OCpXXCfO+faPhbV/0HuK4ndx1G+myNfK1Nk/CxfMcT" "BT+zDS/Df/QePAHVbrr9uuGB7fW8ogW/ulnydgZPRluusFGv" "J3+cg9LoPpZPAmv5Me3ec7NtdlfN0oDZ0gk3TiNkkhsxDG9Y" "YcNzl78USI0q8+kOV26Bu5dOBpU4WOuojXZHJlP5lMgdzLLl" "EQ0", "session_id": "IigqfNWLL+ez/Is+Duwp2s4HuCZhFG9b9CZKTYHtQ4A", "device_id": "AHQDUSTAAA", }, tok=VAR_12, ) self.pump() self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") self.helper.join( VAR_15=room, user=VAR_18, tok=VAR_19 ) self.pump() self.assertEqual(len(self.push_attempts), 1) self.helper.send_event( VAR_15, "m.room.encrypted", content={ "ciphertext": "AwgAEoABtEuic/2DF6oIpNH+q/PonzlhXOVho8dTv0tzFr5m" "9vTo50yabx3nxsRlP2WxSqa8I07YftP+EKWCWJvTkg6o7zXq" "6CK+GVvLQOVgK50SfvjHqJXN+z1VEqj+5mkZVN/cAgJzoxcH" "zFHkwDPJC8kQs47IHd8EO9KBUK4v6+NQ1uE/BIak4qAf9aS/" "kI+f0gjn9IY9K6LXlah82A/iRyrIrxkCkE/n0VfvLhaWFecC" "sAWTcMLoF6fh1Jpke95mljbmFSpsSd/eEQw", "device_id": "SRCFTWTHXO", "session_id": "eMA+bhGczuTz1C5cJR1YbmrnnC6Goni4lbvS5vJ1nG4", "algorithm": "m.megolm.v1.aes-sha2", "sender_key": "rC/XSIAiYrVGSuaHMop8/pTZbku4sQKBZwRwukgnN1c", }, tok=VAR_12, ) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "high") def FUNC_3(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_18 = self.register_user("yetanotheruser", "pass") VAR_19 = self.login("yetanotheruser", "pass") VAR_15 = self.helper.create_room_as(VAR_1, tok=VAR_10) self.helper.join(VAR_15=room, user=VAR_11, tok=VAR_12) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) self.helper.send(VAR_15, VAR_7="Hi!", tok=VAR_12) self.pump() self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") self.helper.join( VAR_15=room, user=VAR_18, tok=VAR_19 ) self.pump() self.assertEqual(len(self.push_attempts), 1) self.helper.send(VAR_15, VAR_7="Welcome!", tok=VAR_12) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def FUNC_4(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_18 = self.register_user("yetanotheruser", "pass") VAR_19 = self.login("yetanotheruser", "pass") VAR_15 = self.helper.create_room_as(VAR_1, tok=VAR_10) self.helper.join(VAR_15=room, user=VAR_11, tok=VAR_12) self.helper.join( VAR_15=room, user=VAR_18, tok=VAR_19 ) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) self.helper.send(VAR_15, VAR_7="Oh, user, hello!", tok=VAR_12) self.pump() self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") self.helper.send(VAR_15, VAR_7="Are you there?", tok=VAR_12) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def FUNC_5(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_18 = self.register_user("yetanotheruser", "pass") VAR_19 = self.login("yetanotheruser", "pass") VAR_15 = self.helper.create_room_as(VAR_11, tok=VAR_12) self.helper.join(VAR_15=room, user=VAR_1, tok=VAR_10) self.helper.join( VAR_15=room, user=VAR_18, tok=VAR_19 ) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) self.helper.send( VAR_15, VAR_7="@VAR_15 eeek! There's a spider on the table!", tok=VAR_12, ) self.pump() self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") self.helper.send( VAR_15, VAR_7="@VAR_15 the spider is gone", tok=VAR_19 ) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def FUNC_6(self): self._test_push_unread_count() self.assertEqual( self.push_attempts[5][2]["notification"]["counts"]["unread"], 1 ) @override_config({"push": {"group_unread_count_by_room": False}}) def FUNC_7(self): self._test_push_unread_count() self.assertEqual( self.push_attempts[5][2]["notification"]["counts"]["unread"], 4 ) def FUNC_8(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("other_user", "pass") VAR_12 = self.login("other_user", "pass") VAR_20 = self.helper.create_room_as(VAR_11, tok=VAR_12) self.helper.join(VAR_15=VAR_20, user=VAR_1, tok=VAR_10) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) VAR_21 = self.helper.send( VAR_20, VAR_7="Hello there!", tok=VAR_12 ) VAR_22 = VAR_21["event_id"] self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual( self.push_attempts[0][2]["notification"]["counts"]["unread"], 0 ) VAR_23, VAR_24 = self.make_request( "POST", "/rooms/%s/receipt/VAR_5.read/%s" % (VAR_20, VAR_22), {}, VAR_10=access_token, ) self.assertEqual(VAR_24.code, 200, VAR_24.json_body) self.push_attempts[1][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual( self.push_attempts[1][2]["notification"]["counts"]["unread"], 0 ) self.helper.send( VAR_20, VAR_7="How's the weather today?", tok=VAR_12 ) self.push_attempts[2][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 3) self.assertEqual( self.push_attempts[2][2]["notification"]["counts"]["unread"], 1 ) self.helper.send(VAR_20, VAR_7="Hello?", tok=VAR_12) self.pump() self.push_attempts[3][0].callback({}) self.helper.send(VAR_20, VAR_7="Hello??", tok=VAR_12) self.pump() self.push_attempts[4][0].callback({}) self.helper.send(VAR_20, VAR_7="HELLO???", tok=VAR_12) self.pump() self.push_attempts[5][0].callback({}) self.assertEqual(len(self.push_attempts), 6)
from mock import Mock from twisted.internet.defer import Deferred import synapse.rest.admin from synapse.logging.context import .make_deferred_yieldable from synapse.rest.client.v1 import login, VAR_15 from synapse.rest.client.v2_alpha import receipts from tests.unittest import HomeserverTestCase, override_config class CLASS_0(HomeserverTestCase): VAR_0 = [ synapse.rest.admin.register_servlets_for_client_rest_resource, VAR_15.register_servlets, login.register_servlets, receipts.register_servlets, ] VAR_1 = True VAR_2 = False def FUNC_0(self, VAR_3, VAR_4): self.push_attempts = [] VAR_5 = Mock() def FUNC_9(VAR_6, VAR_7): VAR_25 = Deferred() self.push_attempts.append((VAR_25, VAR_6, VAR_7)) return make_deferred_yieldable(VAR_25) VAR_5.post_json_get_json = FUNC_9 VAR_8 = self.default_config() VAR_8["start_pushers"] = True VAR_9 = self.setup_test_homeserver( VAR_8=config, proxied_blacklisted_http_client=VAR_5 ) return VAR_9 def FUNC_1(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) VAR_15 = self.helper.create_room_as(VAR_1, tok=VAR_10) self.helper.join(VAR_15=room, user=VAR_11, tok=VAR_12) self.helper.send(VAR_15, VAR_7="Hi!", tok=VAR_12) self.helper.send(VAR_15, VAR_7="There!", tok=VAR_12) VAR_16 = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": VAR_1}) ) VAR_16 = list(VAR_16) self.assertEqual(len(VAR_16), 1) VAR_17 = VAR_16[0]["last_stream_ordering"] self.pump() VAR_16 = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": VAR_1}) ) VAR_16 = list(VAR_16) self.assertEqual(len(VAR_16), 1) self.assertEqual(VAR_17, VAR_16[0]["last_stream_ordering"]) self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual( self.push_attempts[0][2]["notification"]["content"]["body"], "Hi!" ) self.push_attempts[0][0].callback({}) self.pump() VAR_16 = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": VAR_1}) ) VAR_16 = list(VAR_16) self.assertEqual(len(VAR_16), 1) self.assertTrue(VAR_16[0]["last_stream_ordering"] > VAR_17) VAR_17 = VAR_16[0]["last_stream_ordering"] self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual( self.push_attempts[1][2]["notification"]["content"]["body"], "There!" ) self.push_attempts[1][0].callback({}) self.pump() VAR_16 = self.get_success( self.hs.get_datastore().get_pushers_by({"user_name": VAR_1}) ) VAR_16 = list(VAR_16) self.assertEqual(len(VAR_16), 1) self.assertTrue(VAR_16[0]["last_stream_ordering"] > VAR_17) def FUNC_2(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_18 = self.register_user("yetanotheruser", "pass") VAR_19 = self.login("yetanotheruser", "pass") VAR_15 = self.helper.create_room_as(VAR_1, tok=VAR_10) self.helper.join(VAR_15=room, user=VAR_11, tok=VAR_12) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) self.helper.send_event( VAR_15, "m.room.encrypted", content={ "algorithm": "m.megolm.v1.aes-sha2", "sender_key": "6lImKbzK51MzWLwHh8tUM3UBBSBrLlgup/OOCGTvumM", "ciphertext": "AwgAErABoRxwpMipdgiwXgu46rHiWQ0DmRj0qUlPrMraBUDk" "leTnJRljpuc7IOhsYbLY3uo2WI0ab/ob41sV+3JEIhODJPqH" "TK7cEZaIL+/up9e+dT9VGF5kRTWinzjkeqO8FU5kfdRjm+3w" "0sy3o1OCpXXCfO+faPhbV/0HuK4ndx1G+myNfK1Nk/CxfMcT" "BT+zDS/Df/QePAHVbrr9uuGB7fW8ogW/ulnydgZPRluusFGv" "J3+cg9LoPpZPAmv5Me3ec7NtdlfN0oDZ0gk3TiNkkhsxDG9Y" "YcNzl78USI0q8+kOV26Bu5dOBpU4WOuojXZHJlP5lMgdzLLl" "EQ0", "session_id": "IigqfNWLL+ez/Is+Duwp2s4HuCZhFG9b9CZKTYHtQ4A", "device_id": "AHQDUSTAAA", }, tok=VAR_12, ) self.pump() self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") self.helper.join( VAR_15=room, user=VAR_18, tok=VAR_19 ) self.pump() self.assertEqual(len(self.push_attempts), 1) self.helper.send_event( VAR_15, "m.room.encrypted", content={ "ciphertext": "AwgAEoABtEuic/2DF6oIpNH+q/PonzlhXOVho8dTv0tzFr5m" "9vTo50yabx3nxsRlP2WxSqa8I07YftP+EKWCWJvTkg6o7zXq" "6CK+GVvLQOVgK50SfvjHqJXN+z1VEqj+5mkZVN/cAgJzoxcH" "zFHkwDPJC8kQs47IHd8EO9KBUK4v6+NQ1uE/BIak4qAf9aS/" "kI+f0gjn9IY9K6LXlah82A/iRyrIrxkCkE/n0VfvLhaWFecC" "sAWTcMLoF6fh1Jpke95mljbmFSpsSd/eEQw", "device_id": "SRCFTWTHXO", "session_id": "eMA+bhGczuTz1C5cJR1YbmrnnC6Goni4lbvS5vJ1nG4", "algorithm": "m.megolm.v1.aes-sha2", "sender_key": "rC/XSIAiYrVGSuaHMop8/pTZbku4sQKBZwRwukgnN1c", }, tok=VAR_12, ) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "high") def FUNC_3(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_18 = self.register_user("yetanotheruser", "pass") VAR_19 = self.login("yetanotheruser", "pass") VAR_15 = self.helper.create_room_as(VAR_1, tok=VAR_10) self.helper.join(VAR_15=room, user=VAR_11, tok=VAR_12) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) self.helper.send(VAR_15, VAR_7="Hi!", tok=VAR_12) self.pump() self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") self.helper.join( VAR_15=room, user=VAR_18, tok=VAR_19 ) self.pump() self.assertEqual(len(self.push_attempts), 1) self.helper.send(VAR_15, VAR_7="Welcome!", tok=VAR_12) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def FUNC_4(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_18 = self.register_user("yetanotheruser", "pass") VAR_19 = self.login("yetanotheruser", "pass") VAR_15 = self.helper.create_room_as(VAR_1, tok=VAR_10) self.helper.join(VAR_15=room, user=VAR_11, tok=VAR_12) self.helper.join( VAR_15=room, user=VAR_18, tok=VAR_19 ) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) self.helper.send(VAR_15, VAR_7="Oh, user, hello!", tok=VAR_12) self.pump() self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") self.helper.send(VAR_15, VAR_7="Are you there?", tok=VAR_12) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def FUNC_5(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("otheruser", "pass") VAR_12 = self.login("otheruser", "pass") VAR_18 = self.register_user("yetanotheruser", "pass") VAR_19 = self.login("yetanotheruser", "pass") VAR_15 = self.helper.create_room_as(VAR_11, tok=VAR_12) self.helper.join(VAR_15=room, user=VAR_1, tok=VAR_10) self.helper.join( VAR_15=room, user=VAR_18, tok=VAR_19 ) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) self.helper.send( VAR_15, VAR_7="@VAR_15 eeek! There's a spider on the table!", tok=VAR_12, ) self.pump() self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual(self.push_attempts[0][2]["notification"]["prio"], "high") self.helper.send( VAR_15, VAR_7="@VAR_15 the spider is gone", tok=VAR_19 ) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual(self.push_attempts[1][1], "example.com") self.assertEqual(self.push_attempts[1][2]["notification"]["prio"], "low") def FUNC_6(self): self._test_push_unread_count() self.assertEqual( self.push_attempts[5][2]["notification"]["counts"]["unread"], 1 ) @override_config({"push": {"group_unread_count_by_room": False}}) def FUNC_7(self): self._test_push_unread_count() self.assertEqual( self.push_attempts[5][2]["notification"]["counts"]["unread"], 4 ) def FUNC_8(self): VAR_1 = self.register_user("user", "pass") VAR_10 = self.login("user", "pass") VAR_11 = self.register_user("other_user", "pass") VAR_12 = self.login("other_user", "pass") VAR_20 = self.helper.create_room_as(VAR_11, tok=VAR_12) self.helper.join(VAR_15=VAR_20, user=VAR_1, tok=VAR_10) VAR_13 = self.get_success( self.hs.get_datastore().get_user_by_access_token(VAR_10) ) VAR_14 = VAR_13.token_id self.get_success( self.hs.get_pusherpool().add_pusher( VAR_1=user_id, VAR_10=VAR_14, kind="http", app_id="m.http", app_display_name="HTTP Push Notifications", device_display_name="pushy push", pushkey="a@example.com", lang=None, data={"url": "example.com"}, ) ) VAR_21 = self.helper.send( VAR_20, VAR_7="Hello there!", tok=VAR_12 ) VAR_22 = VAR_21["event_id"] self.push_attempts[0][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 1) self.assertEqual(self.push_attempts[0][1], "example.com") self.assertEqual( self.push_attempts[0][2]["notification"]["counts"]["unread"], 0 ) VAR_23, VAR_24 = self.make_request( "POST", "/rooms/%s/receipt/VAR_5.read/%s" % (VAR_20, VAR_22), {}, VAR_10=access_token, ) self.assertEqual(VAR_24.code, 200, VAR_24.json_body) self.push_attempts[1][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 2) self.assertEqual( self.push_attempts[1][2]["notification"]["counts"]["unread"], 0 ) self.helper.send( VAR_20, VAR_7="How's the weather today?", tok=VAR_12 ) self.push_attempts[2][0].callback({}) self.pump() self.assertEqual(len(self.push_attempts), 3) self.assertEqual( self.push_attempts[2][2]["notification"]["counts"]["unread"], 1 ) self.helper.send(VAR_20, VAR_7="Hello?", tok=VAR_12) self.pump() self.push_attempts[3][0].callback({}) self.helper.send(VAR_20, VAR_7="Hello??", tok=VAR_12) self.pump() self.push_attempts[4][0].callback({}) self.helper.send(VAR_20, VAR_7="HELLO???", tok=VAR_12) self.pump() self.push_attempts[5][0].callback({}) self.assertEqual(len(self.push_attempts), 6)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 23, 25, 26, 36, 39, 41, 46, 48, 51, 53, 55, 61, 64, 65, 68, 69, 74, 88, 89, 91, 92, 94, 95, 98, 99, 106, 107, 109, 110, 117, 118, 124, 125, 128, 129, 137, 138, 144, 145, 148, 149, 156, 163, 166, 167, 170, 171, 174, 175, 177, 178, 180, 181, 186, 200, 201, 202, 203, 223, 224, 226, 227, 230, 231, 235, 236, 237, 238, 239, 243, 244, 245, 248, 249, 267, 268, 273, 279, 282, 283, 286, 287, 290, 291, 293, 294, 296, 297, 302, 316, 317, 319, 320, 322, 323, 326, 327, 331, 332, 336, 337, 338, 341, 342, 344, 345, 349, 350, 352, 358, 361, 362, 365, 366, 369, 370, 372, 373, 378, 379, 384, 398, 399, 401, 402, 404, 405, 408, 409, 413, 414, 416, 417, 421, 422, 424, 430, 433, 434, 437, 438, 441, 442, 443, 445, 446, 451, 452, 457, 471, 472, 478, 479, 481, 482, 485, 486, 490, 491, 495, 496, 500, 501, 503, 508, 510, 511, 512, 513, 517, 523, 525, 526, 527, 528, 529, 533, 537, 543, 546, 547, 550, 551, 553, 554, 556, 557, 562, 576, 577, 581, 582, 584, 585, 586, 589, 590, 593, 594, 595, 596, 600, 601, 602, 603, 604, 605, 613, 614, 617, 618, 623, 624, 628, 629, 632, 633, 634, 639, 640, 641, 643, 644, 647, 649, 650, 653, 655, 656, 659, 661, 57, 58, 59, 60, 158, 159, 160, 161, 162, 275, 276, 277, 278, 354, 355, 356, 357, 426, 427, 428, 429, 505, 506, 507, 520, 521, 522, 535, 536, 537, 538, 539, 540, 541, 542 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 23, 25, 26, 36, 39, 41, 46, 48, 51, 55, 57, 63, 66, 67, 70, 71, 76, 90, 91, 93, 94, 96, 97, 100, 101, 108, 109, 111, 112, 119, 120, 126, 127, 130, 131, 139, 140, 146, 147, 150, 151, 158, 165, 168, 169, 172, 173, 176, 177, 179, 180, 182, 183, 188, 202, 203, 204, 205, 225, 226, 228, 229, 232, 233, 237, 238, 239, 240, 241, 245, 246, 247, 250, 251, 269, 270, 275, 281, 284, 285, 288, 289, 292, 293, 295, 296, 298, 299, 304, 318, 319, 321, 322, 324, 325, 328, 329, 333, 334, 338, 339, 340, 343, 344, 346, 347, 351, 352, 354, 360, 363, 364, 367, 368, 371, 372, 374, 375, 380, 381, 386, 400, 401, 403, 404, 406, 407, 410, 411, 415, 416, 418, 419, 423, 424, 426, 432, 435, 436, 439, 440, 443, 444, 445, 447, 448, 453, 454, 459, 473, 474, 480, 481, 483, 484, 487, 488, 492, 493, 497, 498, 502, 503, 505, 510, 512, 513, 514, 515, 519, 525, 527, 528, 529, 530, 531, 535, 539, 545, 548, 549, 552, 553, 555, 556, 558, 559, 564, 578, 579, 583, 584, 586, 587, 588, 591, 592, 595, 596, 597, 598, 602, 603, 604, 605, 606, 607, 615, 616, 619, 620, 625, 626, 630, 631, 634, 635, 636, 641, 642, 643, 645, 646, 649, 651, 652, 655, 657, 658, 661, 663, 59, 60, 61, 62, 160, 161, 162, 163, 164, 277, 278, 279, 280, 356, 357, 358, 359, 428, 429, 430, 431, 507, 508, 509, 522, 523, 524, 537, 538, 539, 540, 541, 542, 543, 544 ]
3CWE-352
from unittest.mock import patch import pytest from fastapi.testclient import TestClient from docs_src.body.tutorial001 import app client = TestClient(app) openapi_schema = { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, "description": {"title": "Description", "type": "string"}, "tax": {"title": "Tax", "type": "number"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": {"type": "string"}, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == openapi_schema price_missing = { "detail": [ { "loc": ["body", "price"], "msg": "field required", "type": "value_error.missing", } ] } price_not_float = { "detail": [ { "loc": ["body", "price"], "msg": "value is not a valid float", "type": "type_error.float", } ] } name_price_missing = { "detail": [ { "loc": ["body", "name"], "msg": "field required", "type": "value_error.missing", }, { "loc": ["body", "price"], "msg": "field required", "type": "value_error.missing", }, ] } body_missing = { "detail": [ {"loc": ["body"], "msg": "field required", "type": "value_error.missing"} ] } @pytest.mark.parametrize( "path,body,expected_status,expected_response", [ ( "/items/", {"name": "Foo", "price": 50.5}, 200, {"name": "Foo", "price": 50.5, "description": None, "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5"}, 200, {"name": "Foo", "price": 50.5, "description": None, "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5", "description": "Some Foo"}, 200, {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, 200, {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": 0.3}, ), ("/items/", {"name": "Foo"}, 422, price_missing), ("/items/", {"name": "Foo", "price": "twenty"}, 422, price_not_float), ("/items/", {}, 422, name_price_missing), ("/items/", None, 422, body_missing), ], ) def test_post_body(path, body, expected_status, expected_response): response = client.post(path, json=body) assert response.status_code == expected_status assert response.json() == expected_response def test_post_broken_body(): response = client.post("/items/", data={"name": "Foo", "price": 50.5}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "ctx": { "colno": 1, "doc": "name=Foo&price=50.5", "lineno": 1, "msg": "Expecting value", "pos": 0, }, "loc": ["body", 0], "msg": "Expecting value: line 1 column 1 (char 0)", "type": "value_error.jsondecode", } ] } with patch("json.loads", side_effect=Exception): response = client.post("/items/", json={"test": "test2"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "There was an error parsing the body"}
from unittest.mock import patch import pytest from fastapi.testclient import TestClient from docs_src.body.tutorial001 import app client = TestClient(app) openapi_schema = { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, "description": {"title": "Description", "type": "string"}, "tax": {"title": "Tax", "type": "number"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": {"type": "string"}, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == openapi_schema price_missing = { "detail": [ { "loc": ["body", "price"], "msg": "field required", "type": "value_error.missing", } ] } price_not_float = { "detail": [ { "loc": ["body", "price"], "msg": "value is not a valid float", "type": "type_error.float", } ] } name_price_missing = { "detail": [ { "loc": ["body", "name"], "msg": "field required", "type": "value_error.missing", }, { "loc": ["body", "price"], "msg": "field required", "type": "value_error.missing", }, ] } body_missing = { "detail": [ {"loc": ["body"], "msg": "field required", "type": "value_error.missing"} ] } @pytest.mark.parametrize( "path,body,expected_status,expected_response", [ ( "/items/", {"name": "Foo", "price": 50.5}, 200, {"name": "Foo", "price": 50.5, "description": None, "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5"}, 200, {"name": "Foo", "price": 50.5, "description": None, "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5", "description": "Some Foo"}, 200, {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, 200, {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": 0.3}, ), ("/items/", {"name": "Foo"}, 422, price_missing), ("/items/", {"name": "Foo", "price": "twenty"}, 422, price_not_float), ("/items/", {}, 422, name_price_missing), ("/items/", None, 422, body_missing), ], ) def test_post_body(path, body, expected_status, expected_response): response = client.post(path, json=body) assert response.status_code == expected_status assert response.json() == expected_response def test_post_broken_body(): response = client.post( "/items/", headers={"content-type": "application/json"}, data="{some broken json}", ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", 1], "msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", "type": "value_error.jsondecode", "ctx": { "msg": "Expecting property name enclosed in double quotes", "doc": "{some broken json}", "pos": 1, "lineno": 1, "colno": 2, }, } ] } def test_post_form_for_json(): response = client.post("/items/", data={"name": "Foo", "price": 50.5}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body"], "msg": "value is not a valid dict", "type": "type_error.dict", } ] } def test_explicit_content_type(): response = client.post( "/items/", data='{"name": "Foo", "price": 50.5}', headers={"Content-Type": "application/json"}, ) assert response.status_code == 200, response.text def test_geo_json(): response = client.post( "/items/", data='{"name": "Foo", "price": 50.5}', headers={"Content-Type": "application/geo+json"}, ) assert response.status_code == 200, response.text def test_wrong_headers(): data = '{"name": "Foo", "price": 50.5}' invalid_dict = { "detail": [ { "loc": ["body"], "msg": "value is not a valid dict", "type": "type_error.dict", } ] } response = client.post("/items/", data=data, headers={"Content-Type": "text/plain"}) assert response.status_code == 422, response.text assert response.json() == invalid_dict response = client.post( "/items/", data=data, headers={"Content-Type": "application/geo+json-seq"} ) assert response.status_code == 422, response.text assert response.json() == invalid_dict response = client.post( "/items/", data=data, headers={"Content-Type": "application/not-really-json"} ) assert response.status_code == 422, response.text assert response.json() == invalid_dict def test_other_exceptions(): with patch("json.loads", side_effect=Exception): response = client.post("/items/", json={"test": "test2"}) assert response.status_code == 400, response.text
xsrf
{ "code": [ " response = client.post(\"/items/\", data={\"name\": \"Foo\", \"price\": 50.5})", " \"colno\": 1,", " \"doc\": \"name=Foo&price=50.5\",", " \"msg\": \"Expecting value\",", " \"pos\": 0,", " \"loc\": [\"body\", 0],", " \"msg\": \"Expecting value: line 1 column 1 (char 0)\",", " \"type\": \"value_error.jsondecode\",", " assert response.json() == {\"detail\": \"There was an error parsing the body\"}" ], "line_no": [ 176, 182, 183, 185, 186, 188, 189, 190, 197 ] }
{ "code": [ " response = client.post(", " \"/items/\",", " headers={\"content-type\": \"application/json\"},", " data=\"{some broken json}\",", " )", " \"loc\": [\"body\", 1],", " \"msg\": \"Expecting property name enclosed in double quotes: line 1 column 2 (char 1)\",", " \"type\": \"value_error.jsondecode\",", " \"msg\": \"Expecting property name enclosed in double quotes\",", " \"doc\": \"{some broken json}\",", " \"pos\": 1,", " \"colno\": 2,", "def test_post_form_for_json():", " response = client.post(\"/items/\", data={\"name\": \"Foo\", \"price\": 50.5})", " assert response.status_code == 422, response.text", " assert response.json() == {", " \"detail\": [", " {", " \"loc\": [\"body\"],", " \"msg\": \"value is not a valid dict\",", " \"type\": \"type_error.dict\",", " }", " ]", " }", "def test_explicit_content_type():", " response = client.post(", " \"/items/\",", " data='{\"name\": \"Foo\", \"price\": 50.5}',", " headers={\"Content-Type\": \"application/json\"},", " )", " assert response.status_code == 200, response.text", "def test_geo_json():", " response = client.post(", " \"/items/\",", " data='{\"name\": \"Foo\", \"price\": 50.5}',", " headers={\"Content-Type\": \"application/geo+json\"},", " )", " assert response.status_code == 200, response.text", "def test_wrong_headers():", " data = '{\"name\": \"Foo\", \"price\": 50.5}'", " invalid_dict = {", " \"detail\": [", " {", " \"loc\": [\"body\"],", " \"msg\": \"value is not a valid dict\",", " \"type\": \"type_error.dict\",", " }", " ]", " }", " response = client.post(\"/items/\", data=data, headers={\"Content-Type\": \"text/plain\"})", " assert response.status_code == 422, response.text", " assert response.json() == invalid_dict", " response = client.post(", " \"/items/\", data=data, headers={\"Content-Type\": \"application/geo+json-seq\"}", " )", " assert response.status_code == 422, response.text", " assert response.json() == invalid_dict", " response = client.post(", " \"/items/\", data=data, headers={\"Content-Type\": \"application/not-really-json\"}", " )", " assert response.status_code == 422, response.text", " assert response.json() == invalid_dict", "def test_other_exceptions():" ], "line_no": [ 176, 177, 178, 179, 180, 185, 186, 187, 189, 190, 191, 193, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 214, 215, 216, 217, 218, 219, 220, 223, 224, 225, 226, 227, 228, 229, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 244, 245, 246, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 260 ] }
from unittest.mock import patch import pytest from fastapi.testclient import TestClient from docs_src.body.tutorial001 import app VAR_0 = TestClient(app) VAR_1 = { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, "description": {"title": "Description", "type": "string"}, "tax": {"title": "Tax", "type": "number"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": {"type": "string"}, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, } def FUNC_0(): VAR_10 = VAR_0.get("/openapi.json") assert VAR_10.status_code == 200, VAR_10.text assert VAR_10.json() == VAR_1 VAR_2 = { "detail": [ { "loc": ["body", "price"], "msg": "field required", "type": "value_error.missing", } ] } VAR_3 = { "detail": [ { "loc": ["body", "price"], "msg": "value is not a valid float", "type": "type_error.float", } ] } VAR_4 = { "detail": [ { "loc": ["body", "name"], "msg": "field required", "type": "value_error.missing", }, { "loc": ["body", "price"], "msg": "field required", "type": "value_error.missing", }, ] } VAR_5 = { "detail": [ {"loc": ["body"], "msg": "field required", "type": "value_error.missing"} ] } @pytest.mark.parametrize( "path,VAR_7,VAR_8,expected_response", [ ( "/items/", {"name": "Foo", "price": 50.5}, 200, {"name": "Foo", "price": 50.5, "description": None, "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5"}, 200, {"name": "Foo", "price": 50.5, "description": None, "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5", "description": "Some Foo"}, 200, {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, 200, {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": 0.3}, ), ("/items/", {"name": "Foo"}, 422, VAR_2), ("/items/", {"name": "Foo", "price": "twenty"}, 422, VAR_3), ("/items/", {}, 422, VAR_4), ("/items/", None, 422, VAR_5), ], ) def FUNC_1(VAR_6, VAR_7, VAR_8, VAR_9): VAR_10 = VAR_0.post(VAR_6, json=VAR_7) assert VAR_10.status_code == VAR_8 assert VAR_10.json() == VAR_9 def FUNC_2(): VAR_10 = VAR_0.post("/items/", data={"name": "Foo", "price": 50.5}) assert VAR_10.status_code == 422, VAR_10.text assert VAR_10.json() == { "detail": [ { "ctx": { "colno": 1, "doc": "name=Foo&price=50.5", "lineno": 1, "msg": "Expecting value", "pos": 0, }, "loc": ["body", 0], "msg": "Expecting value: line 1 column 1 (char 0)", "type": "value_error.jsondecode", } ] } with patch("json.loads", side_effect=Exception): VAR_10 = VAR_0.post("/items/", json={"test": "test2"}) assert VAR_10.status_code == 400, VAR_10.text assert VAR_10.json() == {"detail": "There was an error parsing the body"}
from unittest.mock import patch import pytest from fastapi.testclient import TestClient from docs_src.body.tutorial001 import app VAR_0 = TestClient(app) VAR_1 = { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, "description": {"title": "Description", "type": "string"}, "tax": {"title": "Tax", "type": "number"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": {"type": "string"}, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, } def FUNC_0(): VAR_10 = VAR_0.get("/openapi.json") assert VAR_10.status_code == 200, VAR_10.text assert VAR_10.json() == VAR_1 VAR_2 = { "detail": [ { "loc": ["body", "price"], "msg": "field required", "type": "value_error.missing", } ] } VAR_3 = { "detail": [ { "loc": ["body", "price"], "msg": "value is not a valid float", "type": "type_error.float", } ] } VAR_4 = { "detail": [ { "loc": ["body", "name"], "msg": "field required", "type": "value_error.missing", }, { "loc": ["body", "price"], "msg": "field required", "type": "value_error.missing", }, ] } VAR_5 = { "detail": [ {"loc": ["body"], "msg": "field required", "type": "value_error.missing"} ] } @pytest.mark.parametrize( "path,VAR_7,VAR_8,expected_response", [ ( "/items/", {"name": "Foo", "price": 50.5}, 200, {"name": "Foo", "price": 50.5, "description": None, "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5"}, 200, {"name": "Foo", "price": 50.5, "description": None, "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5", "description": "Some Foo"}, 200, {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": None}, ), ( "/items/", {"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, 200, {"name": "Foo", "price": 50.5, "description": "Some Foo", "tax": 0.3}, ), ("/items/", {"name": "Foo"}, 422, VAR_2), ("/items/", {"name": "Foo", "price": "twenty"}, 422, VAR_3), ("/items/", {}, 422, VAR_4), ("/items/", None, 422, VAR_5), ], ) def FUNC_1(VAR_6, VAR_7, VAR_8, VAR_9): VAR_10 = VAR_0.post(VAR_6, json=VAR_7) assert VAR_10.status_code == VAR_8 assert VAR_10.json() == VAR_9 def FUNC_2(): VAR_10 = VAR_0.post( "/items/", headers={"content-type": "application/json"}, VAR_11="{some broken json}", ) assert VAR_10.status_code == 422, VAR_10.text assert VAR_10.json() == { "detail": [ { "loc": ["body", 1], "msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", "type": "value_error.jsondecode", "ctx": { "msg": "Expecting property name enclosed in double quotes", "doc": "{some broken json}", "pos": 1, "lineno": 1, "colno": 2, }, } ] } def FUNC_3(): VAR_10 = VAR_0.post("/items/", VAR_11={"name": "Foo", "price": 50.5}) assert VAR_10.status_code == 422, VAR_10.text assert VAR_10.json() == { "detail": [ { "loc": ["body"], "msg": "value is not a valid dict", "type": "type_error.dict", } ] } def FUNC_4(): VAR_10 = VAR_0.post( "/items/", VAR_11='{"name": "Foo", "price": 50.5}', headers={"Content-Type": "application/json"}, ) assert VAR_10.status_code == 200, VAR_10.text def FUNC_5(): VAR_10 = VAR_0.post( "/items/", VAR_11='{"name": "Foo", "price": 50.5}', headers={"Content-Type": "application/geo+json"}, ) assert VAR_10.status_code == 200, VAR_10.text def FUNC_6(): VAR_11 = '{"name": "Foo", "price": 50.5}' VAR_12 = { "detail": [ { "loc": ["body"], "msg": "value is not a valid dict", "type": "type_error.dict", } ] } VAR_10 = VAR_0.post("/items/", VAR_11=data, headers={"Content-Type": "text/plain"}) assert VAR_10.status_code == 422, VAR_10.text assert VAR_10.json() == VAR_12 VAR_10 = VAR_0.post( "/items/", VAR_11=data, headers={"Content-Type": "application/geo+json-seq"} ) assert VAR_10.status_code == 422, VAR_10.text assert VAR_10.json() == VAR_12 VAR_10 = VAR_0.post( "/items/", VAR_11=data, headers={"Content-Type": "application/not-really-json"} ) assert VAR_10.status_code == 422, VAR_10.text assert VAR_10.json() == VAR_12 def FUNC_7(): with patch("json.loads", side_effect=Exception): VAR_10 = VAR_0.post("/items/", json={"test": "test2"}) assert VAR_10.status_code == 400, VAR_10.text
[ 2, 5, 7, 9, 86, 87, 92, 93, 103, 113, 128, 134, 135, 173, 174, 198 ]
[ 2, 5, 7, 9, 86, 87, 92, 93, 103, 113, 128, 134, 135, 173, 174, 198, 199, 212, 213, 221, 222, 230, 231, 243, 247, 258, 259, 264 ]
1CWE-79
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # import copy import json import re from datetime import date, datetime, timedelta from typing import Dict, List from crispy_forms.bootstrap import InlineCheckboxes, InlineRadios, Tab, TabHolder from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Field, Fieldset, Layout from django import forms from django.conf import settings from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError from django.core.validators import FileExtensionValidator from django.db.models import Q from django.forms import model_to_dict from django.forms.models import ModelChoiceIterator from django.forms.utils import from_current_timezone from django.template.loader import render_to_string from django.urls import reverse from django.utils import timezone from django.utils.http import urlencode from django.utils.safestring import mark_safe from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from translation_finder import DiscoveryResult, discover from weblate.auth.models import Group, User from weblate.checks.flags import Flags from weblate.checks.models import CHECKS from weblate.checks.utils import highlight_string from weblate.formats.models import EXPORTERS, FILE_FORMATS from weblate.glossary.forms import GlossaryAddMixin from weblate.lang.data import BASIC_LANGUAGES from weblate.lang.models import Language from weblate.machinery import MACHINE_TRANSLATION_SERVICES from weblate.trans.defines import COMPONENT_NAME_LENGTH, REPO_LENGTH from weblate.trans.filter import FILTERS, get_filter_choice from weblate.trans.models import ( Announcement, Change, Component, Label, Project, ProjectToken, Unit, ) from weblate.trans.specialchars import RTL_CHARS_DATA, get_special_chars from weblate.trans.util import check_upload_method_permissions, is_repo_link from weblate.trans.validators import validate_check_flags from weblate.utils.antispam import is_spam from weblate.utils.errors import report_error from weblate.utils.forms import ( ColorWidget, ContextDiv, EmailField, SearchField, SortedSelect, SortedSelectMultiple, UsernameField, ) from weblate.utils.hash import checksum_to_hash, hash_to_checksum from weblate.utils.search import parse_query from weblate.utils.state import ( STATE_APPROVED, STATE_CHOICES, STATE_EMPTY, STATE_FUZZY, STATE_READONLY, STATE_TRANSLATED, ) from weblate.utils.validators import validate_file_extension from weblate.vcs.models import VCS_REGISTRY BUTTON_TEMPLATE = """ <button class="btn btn-default {0}" title="{1}" {2}>{3}</button> """ RADIO_TEMPLATE = """ <label class="btn btn-default {0}" title="{1}"> <input type="radio" name="{2}" value="{3}" {4}/> {5} </label> """ GROUP_TEMPLATE = """ <div class="btn-group btn-group-xs" {0}>{1}</div> """ TOOLBAR_TEMPLATE = """ <div class="btn-toolbar pull-right flip editor-toolbar">{0}</div> """ class MarkdownTextarea(forms.Textarea): def __init__(self, **kwargs): kwargs["attrs"] = { "dir": "auto", "class": "markdown-editor highlight-editor", "data-mode": "markdown", } super().__init__(**kwargs) class WeblateDateInput(forms.DateInput): def __init__(self, datepicker=True, **kwargs): attrs = {"type": "date"} if datepicker: attrs["data-provide"] = "datepicker" attrs["data-date-format"] = "yyyy-mm-dd" super().__init__(attrs=attrs, format="%Y-%m-%d", **kwargs) class WeblateDateField(forms.DateField): def __init__(self, datepicker=True, **kwargs): if "widget" not in kwargs: kwargs["widget"] = WeblateDateInput(datepicker=datepicker) super().__init__(**kwargs) def to_python(self, value): """Produce timezone aware datetime with 00:00:00 as time.""" value = super().to_python(value) if isinstance(value, date): return from_current_timezone( datetime(value.year, value.month, value.day, 0, 0, 0) ) return value class ChecksumField(forms.CharField): """Field for handling checksum IDs for translation.""" def __init__(self, *args, **kwargs): kwargs["widget"] = forms.HiddenInput super().__init__(*args, **kwargs) def clean(self, value): super().clean(value) if not value: return None try: return checksum_to_hash(value) except ValueError: raise ValidationError(_("Invalid checksum specified!")) class UserField(forms.CharField): def clean(self, value): if not value: return None try: return User.objects.get(Q(username=value) | Q(email=value)) except User.DoesNotExist: raise ValidationError(_("Could not find any such user.")) except User.MultipleObjectsReturned: raise ValidationError(_("More possible users were found.")) class QueryField(forms.CharField): def __init__(self, **kwargs): if "label" not in kwargs: kwargs["label"] = _("Query") if "required" not in kwargs: kwargs["required"] = False super().__init__(**kwargs) def clean(self, value): if not value: if self.required: raise ValidationError(_("Missing query string.")) return "" try: parse_query(value) return value except Exception as error: report_error() raise ValidationError(_("Could not parse query string: {}").format(error)) class FlagField(forms.CharField): default_validators = [validate_check_flags] class PluralTextarea(forms.Textarea): """Text-area extension which possibly handles plurals.""" def __init__(self, *args, **kwargs): self.profile = None super().__init__(*args, **kwargs) def get_rtl_toolbar(self, fieldname): groups = [] # Special chars chars = [] for name, char, value in RTL_CHARS_DATA: chars.append( BUTTON_TEMPLATE.format( "specialchar", name, 'data-value="{}"'.format( value.encode("ascii", "xmlcharrefreplace").decode("ascii") ), char, ) ) groups.append(GROUP_TEMPLATE.format("", "\n".join(chars))) return TOOLBAR_TEMPLATE.format("\n".join(groups)) def get_rtl_toggle(self, language, fieldname): if language.direction != "rtl": return "" # RTL/LTR switch rtl_name = f"rtl-{fieldname}" rtl_switch = [ RADIO_TEMPLATE.format( "direction-toggle active", gettext("Toggle text direction"), rtl_name, "rtl", 'checked="checked"', "RTL", ), RADIO_TEMPLATE.format( "direction-toggle", gettext("Toggle text direction"), rtl_name, "ltr", "", "LTR", ), ] groups = [GROUP_TEMPLATE.format('data-toggle="buttons"', "\n".join(rtl_switch))] return mark_safe(TOOLBAR_TEMPLATE.format("\n".join(groups))) def get_toolbar(self, language, fieldname, unit, idx, source): """Return toolbar HTML code.""" profile = self.profile groups = [] # Special chars chars = [ BUTTON_TEMPLATE.format( "specialchar", name, 'data-value="{}"'.format( value.encode("ascii", "xmlcharrefreplace").decode("ascii") ), char, ) for name, char, value in get_special_chars( language, profile.special_chars, unit.source ) ] groups.append(GROUP_TEMPLATE.format("", "\n".join(chars))) result = TOOLBAR_TEMPLATE.format("\n".join(groups)) if language.direction == "rtl": result = self.get_rtl_toolbar(fieldname) + result return mark_safe(result) def render(self, name, value, attrs=None, renderer=None, **kwargs): """Render all textareas with correct plural labels.""" unit = value values = unit.get_target_plurals() lang = unit.translation.language plural = unit.translation.plural tabindex = self.attrs["tabindex"] placeables = [hl[2] for hl in highlight_string(unit.source_string, unit)] # Need to add extra class attrs["class"] = "translation-editor form-control highlight-editor" attrs["tabindex"] = tabindex attrs["lang"] = lang.code attrs["dir"] = lang.direction attrs["rows"] = 3 attrs["data-max"] = unit.get_max_length() attrs["data-mode"] = unit.edit_mode attrs["data-placeables"] = "|".join(re.escape(pl) for pl in placeables if pl) if unit.readonly: attrs["readonly"] = 1 # Okay we have more strings ret = [] plurals = unit.get_source_plurals() base_id = f"id_{unit.checksum}" for idx, val in enumerate(values): # Generate ID fieldname = f"{name}_{idx}" fieldid = f"{base_id}_{idx}" attrs["id"] = fieldid attrs["tabindex"] = tabindex + idx if idx and len(plurals) > 1: source = plurals[1] else: source = plurals[0] # Render textare textarea = super().render(fieldname, val, attrs, renderer, **kwargs) # Label for plural label = str(unit.translation.language) if len(values) != 1: label = f"{label}, {plural.get_plural_label(idx)}" ret.append( render_to_string( "snippets/editor.html", { "toolbar": self.get_toolbar(lang, fieldid, unit, idx, source), "fieldid": fieldid, "label": mark_safe(label), "textarea": textarea, "max_length": attrs["data-max"], "length": len(val), "source_length": len(source), "rtl_toggle": self.get_rtl_toggle(lang, fieldid), }, ) ) # Show plural formula for more strings if len(values) > 1: ret.append( render_to_string( "snippets/plural-formula.html", {"plural": plural, "user": self.profile.user}, ) ) # Join output return mark_safe("".join(ret)) def value_from_datadict(self, data, files, name): """Return processed plurals as a list.""" ret = [] for idx in range(0, 10): fieldname = f"{name}_{idx:d}" if fieldname not in data: break ret.append(data.get(fieldname, "")) return [r.replace("\r", "") for r in ret] class PluralField(forms.CharField): """Renderer for the plural field. The only difference from CharField is that it does not force value to be string. """ def __init__(self, max_length=None, min_length=None, **kwargs): kwargs["label"] = "" super().__init__(widget=PluralTextarea, **kwargs) def to_python(self, value): """Return list or string as returned by PluralTextarea.""" return value def clean(self, value): value = super().clean(value) if not value or (self.required and not any(value)): raise ValidationError(_("Missing translated string!")) return value class FilterField(forms.ChoiceField): def __init__(self, *args, **kwargs): kwargs["label"] = _("Search filter") if "required" not in kwargs: kwargs["required"] = False kwargs["choices"] = get_filter_choice() kwargs["error_messages"] = { "invalid_choice": _("Please choose a valid filter type.") } super().__init__(*args, **kwargs) def to_python(self, value): if value == "untranslated": return "todo" return super().to_python(value) class ChecksumForm(forms.Form): """Form for handling checksum IDs for translation.""" checksum = ChecksumField(required=True) def __init__(self, unit_set, *args, **kwargs): self.unit_set = unit_set super().__init__(*args, **kwargs) def clean_checksum(self): """Validate whether checksum is valid and fetches unit for it.""" if "checksum" not in self.cleaned_data: return unit_set = self.unit_set try: self.cleaned_data["unit"] = unit_set.filter( id_hash=self.cleaned_data["checksum"] )[0] except (Unit.DoesNotExist, IndexError): raise ValidationError( _("The string you wanted to translate is no longer available.") ) class UnitForm(forms.Form): def __init__(self, unit: Unit, *args, **kwargs): self.unit = unit super().__init__(*args, **kwargs) class FuzzyField(forms.BooleanField): help_as_icon = True def __init__(self, *args, **kwargs): kwargs["label"] = _("Needs editing") kwargs["help_text"] = _( 'Strings are usually marked as "Needs editing" after the source ' "string is updated, or when marked as such manually." ) super().__init__(*args, **kwargs) self.widget.attrs["class"] = "fuzzy_checkbox" class TranslationForm(UnitForm): """Form used for translation of single string.""" contentsum = ChecksumField(required=True) translationsum = ChecksumField(required=True) target = PluralField(required=False) fuzzy = FuzzyField(required=False) review = forms.ChoiceField( label=_("Review state"), choices=[ (STATE_FUZZY, _("Needs editing")), (STATE_TRANSLATED, _("Waiting for review")), (STATE_APPROVED, _("Approved")), ], required=False, widget=forms.RadioSelect, ) explanation = forms.CharField( widget=MarkdownTextarea, label=_("Explanation"), help_text=_( "Additional explanation to clarify meaning or usage of the string." ), max_length=1000, required=False, ) def __init__(self, user, unit: Unit, *args, **kwargs): if unit is not None: kwargs["initial"] = { "checksum": unit.checksum, "contentsum": hash_to_checksum(unit.content_hash), "translationsum": hash_to_checksum(unit.get_target_hash()), "target": unit, "fuzzy": unit.fuzzy, "review": unit.state, "explanation": unit.explanation, } kwargs["auto_id"] = f"id_{unit.checksum}_%s" tabindex = kwargs.pop("tabindex", 100) super().__init__(unit, *args, **kwargs) if unit.readonly: for field in ["target", "fuzzy", "review"]: self.fields[field].widget.attrs["readonly"] = 1 self.fields["review"].choices = [ (STATE_READONLY, _("Read only")), ] self.user = user self.fields["target"].widget.attrs["tabindex"] = tabindex self.fields["target"].widget.profile = user.profile self.fields["review"].widget.attrs["class"] = "review_radio" # Avoid failing validation on untranslated string if args: self.fields["review"].choices.append((STATE_EMPTY, "")) self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_tag = False self.helper.disable_csrf = True self.helper.layout = Layout( Field("target"), Field("fuzzy"), Field("contentsum"), Field("translationsum"), InlineRadios("review"), Field("explanation"), ) if unit and user.has_perm("unit.review", unit.translation): self.fields["fuzzy"].widget = forms.HiddenInput() else: self.fields["review"].widget = forms.HiddenInput() if not unit.translation.component.is_glossary: self.fields["explanation"].widget = forms.HiddenInput() def clean(self): super().clean() # Check required fields required = {"target", "contentsum", "translationsum"} if not required.issubset(self.cleaned_data): return unit = self.unit if self.cleaned_data["contentsum"] != unit.content_hash: raise ValidationError( _( "Source string has been changed meanwhile. " "Please check your changes." ) ) if self.cleaned_data["translationsum"] != unit.get_target_hash(): raise ValidationError( _( "Translation of the string has been changed meanwhile. " "Please check your changes." ) ) max_length = unit.get_max_length() for text in self.cleaned_data["target"]: if len(text) > max_length: raise ValidationError(_("Translation text too long!")) if self.user.has_perm( "unit.review", unit.translation ) and self.cleaned_data.get("review"): self.cleaned_data["state"] = int(self.cleaned_data["review"]) elif self.cleaned_data["fuzzy"]: self.cleaned_data["state"] = STATE_FUZZY else: self.cleaned_data["state"] = STATE_TRANSLATED class ZenTranslationForm(TranslationForm): checksum = ChecksumField(required=True) def __init__(self, user, unit, *args, **kwargs): super().__init__(user, unit, *args, **kwargs) self.helper.form_action = reverse( "save_zen", kwargs=unit.translation.get_reverse_url_kwargs() ) self.helper.form_tag = True self.helper.disable_csrf = False self.helper.layout.append(Field("checksum")) class DownloadForm(forms.Form): q = QueryField() format = forms.ChoiceField( label=_("File format"), choices=[(x.name, x.verbose) for x in EXPORTERS.values()], initial="po", required=True, widget=forms.RadioSelect, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( SearchField("q"), InlineRadios("format"), ) class SimpleUploadForm(forms.Form): """Base form for uploading a file.""" file = forms.FileField(label=_("File"), validators=[validate_file_extension]) method = forms.ChoiceField( label=_("File upload mode"), choices=( ("translate", _("Add as translation")), ("approve", _("Add as approved translation")), ("suggest", _("Add as suggestion")), ("fuzzy", _("Add as translation needing edit")), ("replace", _("Replace existing translation file")), ("source", _("Update source strings")), ("add", _("Add new strings")), ), widget=forms.RadioSelect, required=True, ) fuzzy = forms.ChoiceField( label=_("Processing of strings needing edit"), choices=( ("", _("Do not import")), ("process", _("Import as string needing edit")), ("approve", _("Import as translated")), ), required=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False @staticmethod def get_field_doc(field): return ("user/files", f"upload-{field.name}") def remove_translation_choice(self, value): """Remove add as translation choice.""" choices = self.fields["method"].choices self.fields["method"].choices = [ choice for choice in choices if choice[0] != value ] class UploadForm(SimpleUploadForm): """Upload form with the option to overwrite current messages.""" conflicts = forms.ChoiceField( label=_("Conflict handling"), help_text=_( "Whether to overwrite existing translations if the string is " "already translated." ), choices=( ("", _("Update only untranslated strings")), ("replace-translated", _("Update translated strings")), ("replace-approved", _("Update translated and approved strings")), ), required=False, initial="replace-translated", ) class ExtraUploadForm(UploadForm): """Advanced upload form for users who can override authorship.""" author_name = forms.CharField(label=_("Author name")) author_email = EmailField(label=_("Author e-mail")) def get_upload_form(user, translation, *args, **kwargs): """Return correct upload form based on user permissions.""" if user.has_perm("upload.authorship", translation): form = ExtraUploadForm kwargs["initial"] = {"author_name": user.full_name, "author_email": user.email} elif user.has_perm("upload.overwrite", translation): form = UploadForm else: form = SimpleUploadForm result = form(*args, **kwargs) for method in [x[0] for x in result.fields["method"].choices]: if not check_upload_method_permissions(user, translation, method): result.remove_translation_choice(method) # Remove approved choice for non review projects if not user.has_perm("unit.review", translation) and not form == SimpleUploadForm: result.fields["conflicts"].choices = [ choice for choice in result.fields["conflicts"].choices if choice[0] != "approved" ] return result class SearchForm(forms.Form): """Text searching form.""" # pylint: disable=invalid-name q = QueryField() sort_by = forms.CharField(required=False, widget=forms.HiddenInput) checksum = ChecksumField(required=False) offset = forms.IntegerField(min_value=-1, required=False, widget=forms.HiddenInput) offset_kwargs = {} def __init__(self, user, language=None, show_builder=True, **kwargs): """Generate choices for other component in same project.""" self.user = user self.language = language super().__init__(**kwargs) self.helper = FormHelper(self) self.helper.disable_csrf = True self.helper.form_tag = False self.helper.layout = Layout( Div( Field("offset", **self.offset_kwargs), SearchField("q"), Field("sort_by", template="snippets/sort-field.html"), css_class="btn-toolbar", role="toolbar", ), ContextDiv( template="snippets/query-builder.html", context={ "user": self.user, "month_ago": timezone.now() - timedelta(days=31), "show_builder": show_builder, "language": self.language, }, ), Field("checksum"), ) def get_name(self): """Return verbose name for a search.""" return FILTERS.get_search_name(self.cleaned_data.get("q", "")) def get_search_query(self): return self.cleaned_data["q"] def clean_offset(self): if self.cleaned_data.get("offset") is None: self.cleaned_data["offset"] = 1 return self.cleaned_data["offset"] def items(self): items = [] # Skip checksum and offset as these change ignored = {"offset", "checksum"} for param in sorted(self.cleaned_data): value = self.cleaned_data[param] # We don't care about empty values or ignored if value is None or param in ignored: continue if isinstance(value, bool): # Only store true values if value: items.append((param, "1")) elif isinstance(value, int): # Avoid storing 0 values if value > 0: items.append((param, str(value))) elif isinstance(value, datetime): # Convert date to string items.append((param, value.date().isoformat())) elif isinstance(value, list): for val in value: items.append((param, val)) elif isinstance(value, User): items.append((param, value.username)) else: # It should be string here if value: items.append((param, value)) return items def urlencode(self): return urlencode(self.items()) def reset_offset(self): """Reset offset to avoid using form as default for new search.""" data = copy.copy(self.data) data["offset"] = "1" data["checksum"] = "" self.data = data return self class PositionSearchForm(SearchForm): offset = forms.IntegerField(min_value=-1, required=False) offset_kwargs = {"template": "snippets/position-field.html"} class MergeForm(UnitForm): """Simple form for merging translation of two units.""" merge = forms.IntegerField() def clean(self): super().clean() if "merge" not in self.cleaned_data: return None try: unit = self.unit translation = unit.translation project = translation.component.project self.cleaned_data["merge_unit"] = merge_unit = Unit.objects.get( pk=self.cleaned_data["merge"], translation__component__project=project, translation__language=translation.language, ) # Compare in Python to ensure case sensitiveness on MySQL if not translation.is_source and unit.source != merge_unit.source: raise ValidationError(_("Could not find merged string.")) except Unit.DoesNotExist: raise ValidationError(_("Could not find merged string.")) return self.cleaned_data class RevertForm(UnitForm): """Form for reverting edits.""" revert = forms.IntegerField() def clean(self): super().clean() if "revert" not in self.cleaned_data: return None try: self.cleaned_data["revert_change"] = Change.objects.get( pk=self.cleaned_data["revert"], unit=self.unit ) except Change.DoesNotExist: raise ValidationError(_("Could not find reverted change.")) return self.cleaned_data class AutoForm(forms.Form): """Automatic translation form.""" mode = forms.ChoiceField( label=_("Automatic translation mode"), choices=[ ("suggest", _("Add as suggestion")), ("translate", _("Add as translation")), ("fuzzy", _("Add as needing edit")), ], initial="suggest", ) filter_type = FilterField( required=True, initial="todo", help_text=_( "Please note that translating all strings will " "discard all existing translations." ), ) auto_source = forms.ChoiceField( label=_("Automatic translation source"), choices=[ ("others", _("Other translation components")), ("mt", _("Machine translation")), ], initial="others", ) component = forms.ChoiceField( label=_("Components"), required=False, help_text=_( "Turn on contribution to shared translation memory for the project to " "get access to additional components." ), initial="", ) engines = forms.MultipleChoiceField( label=_("Machine translation engines"), choices=[], required=False ) threshold = forms.IntegerField( label=_("Score threshold"), initial=80, min_value=1, max_value=100 ) def __init__(self, obj, *args, **kwargs): """Generate choices for other component in same project.""" super().__init__(*args, **kwargs) self.obj = obj # Add components from other projects with enabled shared TM self.components = obj.project.component_set.filter( source_language=obj.source_language ) | Component.objects.filter( source_language_id=obj.source_language_id, project__contribute_shared_tm=True, ).exclude( project=obj.project ) # Fetching is faster than doing count on possibly thousands of components if len(self.components.values_list("id")[:30]) == 30: # Do not show choices when too many self.fields["component"] = forms.CharField( required=False, label=_("Components"), help_text=_( "Enter component to use as source, " "keep blank to use all components in current project." ), ) else: choices = [ (s.id, str(s)) for s in self.components.order_project().prefetch_related("project") ] self.fields["component"].choices = [ ("", _("All components in current project")) ] + choices self.fields["engines"].choices = [ (key, mt.name) for key, mt in MACHINE_TRANSLATION_SERVICES.items() ] if "weblate" in MACHINE_TRANSLATION_SERVICES.keys(): self.fields["engines"].initial = "weblate" use_types = {"all", "nottranslated", "todo", "fuzzy", "check:inconsistent"} self.fields["filter_type"].choices = [ x for x in self.fields["filter_type"].choices if x[0] in use_types ] self.helper = FormHelper(self) self.helper.layout = Layout( Field("mode"), Field("filter_type"), InlineRadios("auto_source", id="select_auto_source"), Div("component", css_id="auto_source_others"), Div("engines", "threshold", css_id="auto_source_mt"), ) def clean_component(self): component = self.cleaned_data["component"] if not component: return None if component.isdigit(): try: result = self.components.get(pk=component) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) else: slashes = component.count("/") if slashes == 0: try: result = self.components.get( slug=component, project=self.obj.project ) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) elif slashes == 1: project_slug, component_slug = component.split("/") try: result = self.components.get( slug=component_slug, project__slug=project_slug ) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) else: raise ValidationError(_("Please provide valid component slug!")) return result.pk class CommentForm(forms.Form): """Simple commenting form.""" scope = forms.ChoiceField( label=_("Scope"), help_text=_( "Is your comment specific to this " "translation or generic for all of them?" ), choices=( ( "report", _("Report issue with the source string"), ), ( "global", _("Source string comment, suggestions for changes to this string"), ), ( "translation", _("Translation comment, discussions with other translators"), ), ), ) comment = forms.CharField( widget=MarkdownTextarea, label=_("New comment"), help_text=_("You can use Markdown and mention users by @username."), max_length=1000, ) def __init__(self, project, *args, **kwargs): super().__init__(*args, **kwargs) # Remove bug report in case source review is not enabled if not project.source_review: self.fields["scope"].choices = self.fields["scope"].choices[1:] class EngageForm(forms.Form): """Form to choose language for engagement widgets.""" lang = forms.ChoiceField(required=False, choices=[("", _("All languages"))]) component = forms.ChoiceField(required=False, choices=[("", _("All components"))]) def __init__(self, user, project, *args, **kwargs): """Dynamically generate choices for used languages in project.""" super().__init__(*args, **kwargs) self.fields["lang"].choices += project.languages.as_choices() self.fields["component"].choices += ( project.component_set.filter_access(user) .order() .values_list("slug", "name") ) class NewLanguageOwnerForm(forms.Form): """Form for requesting new language.""" lang = forms.MultipleChoiceField( label=_("Languages"), choices=[], widget=forms.SelectMultiple ) def get_lang_objects(self): return Language.objects.exclude( Q(translation__component=self.component) | Q(component=self.component) ) def __init__(self, component, *args, **kwargs): super().__init__(*args, **kwargs) self.component = component languages = self.get_lang_objects() self.fields["lang"].choices = languages.as_choices() class NewLanguageForm(NewLanguageOwnerForm): """Form for requesting new language.""" lang = forms.ChoiceField(label=_("Language"), choices=[], widget=forms.Select) def get_lang_objects(self): codes = BASIC_LANGUAGES if settings.BASIC_LANGUAGES is not None: codes = settings.BASIC_LANGUAGES return super().get_lang_objects().filter(code__in=codes) def __init__(self, component, *args, **kwargs): super().__init__(component, *args, **kwargs) self.fields["lang"].choices = [("", _("Please choose"))] + self.fields[ "lang" ].choices def clean_lang(self): # Compatibility with NewLanguageOwnerForm return [self.cleaned_data["lang"]] def get_new_language_form(request, component): """Return new language form for user.""" if not request.user.has_perm("translation.add", component): raise PermissionDenied() if request.user.has_perm("translation.add_more", component): return NewLanguageOwnerForm return NewLanguageForm class ContextForm(forms.ModelForm): class Meta: model = Unit fields = ("explanation", "labels", "extra_flags") widgets = { "labels": forms.CheckboxSelectMultiple(), "explanation": MarkdownTextarea, } doc_links = { "explanation": ("admin/translating", "additional-explanation"), "labels": ("devel/translations", "labels"), "extra_flags": ("admin/translating", "additional-flags"), } def get_field_doc(self, field): return self.doc_links[field.name] def __init__(self, data=None, instance=None, user=None, **kwargs): kwargs["initial"] = { "labels": Label.objects.filter( Q(unit=instance) | Q(unit__source_unit=instance) ) } super().__init__(data=data, instance=instance, **kwargs) project = instance.translation.component.project self.fields["labels"].queryset = project.label_set.all() self.helper = FormHelper(self) self.helper.disable_csrf = True self.helper.form_tag = False self.helper.layout = Layout( Field("explanation"), Field("labels"), ContextDiv( template="snippets/labels_description.html", context={"project": project, "user": user}, ), Field("extra_flags"), ) def save(self, commit=True): if commit: self.instance.save(same_content=True) self._save_m2m() return self.instance return super().save(commit) class UserManageForm(forms.Form): user = UserField( label=_("User to add"), help_text=_( "Please type in an existing Weblate account name or e-mail address." ), ) class UserBlockForm(forms.Form): user = UserField( label=_("User to block"), help_text=_( "Please type in an existing Weblate account name or e-mail address." ), ) expiry = forms.ChoiceField( label=_("Block duration"), choices=( ("", _("Block user until I unblock them")), ("1", _("Block user for one day")), ("7", _("Block user for one week")), ("30", _("Block user for one month")), ), required=False, ) class ReportsForm(forms.Form): style = forms.ChoiceField( label=_("Report format"), help_text=_("Choose file format for the report"), choices=( ("rst", _("reStructuredText")), ("json", _("JSON")), ("html", _("HTML")), ), ) period = forms.ChoiceField( label=_("Report period"), choices=( ("30days", _("Last 30 days")), ("this-month", _("This month")), ("month", _("Last month")), ("this-year", _("This year")), ("year", _("Last year")), ("", _("As specified")), ), required=False, ) start_date = WeblateDateField( label=_("Starting date"), required=False, datepicker=False ) end_date = WeblateDateField( label=_("Ending date"), required=False, datepicker=False ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Field("style"), Field("period"), Div( "start_date", "end_date", css_class="input-group input-daterange", data_provide="datepicker", data_date_format="yyyy-mm-dd", ), ) def clean(self): super().clean() # Invalid value, skip rest of the validation if "period" not in self.cleaned_data: return # Handle predefined periods if self.cleaned_data["period"] == "30days": end = timezone.now() start = end - timedelta(days=30) elif self.cleaned_data["period"] == "month": end = timezone.now().replace(day=1) - timedelta(days=1) start = end.replace(day=1) elif self.cleaned_data["period"] == "this-month": end = timezone.now().replace(day=1) + timedelta(days=31) end = end.replace(day=1) - timedelta(days=1) start = end.replace(day=1) elif self.cleaned_data["period"] == "year": year = timezone.now().year - 1 end = timezone.make_aware(datetime(year, 12, 31)) start = timezone.make_aware(datetime(year, 1, 1)) elif self.cleaned_data["period"] == "this-year": year = timezone.now().year end = timezone.make_aware(datetime(year, 12, 31)) start = timezone.make_aware(datetime(year, 1, 1)) else: # Validate custom period if not self.cleaned_data.get("start_date"): raise ValidationError({"start_date": _("Missing date!")}) if not self.cleaned_data.get("end_date"): raise ValidationError({"end_date": _("Missing date!")}) start = self.cleaned_data["start_date"] end = self.cleaned_data["end_date"] # Sanitize timestamps self.cleaned_data["start_date"] = start.replace( hour=0, minute=0, second=0, microsecond=0 ) self.cleaned_data["end_date"] = end.replace( hour=23, minute=59, second=59, microsecond=999999 ) # Final validation if self.cleaned_data["start_date"] > self.cleaned_data["end_date"]: msg = _("Starting date has to be before ending date!") raise ValidationError({"start_date": msg, "end_date": msg}) class CleanRepoMixin: def clean_repo(self): repo = self.cleaned_data.get("repo") if not repo or not is_repo_link(repo) or "/" not in repo[10:]: return repo project, component = repo[10:].split("/", 1) try: obj = Component.objects.get( slug__iexact=component, project__slug__iexact=project ) except Component.DoesNotExist: return repo if not self.request.user.has_perm("component.edit", obj): raise ValidationError( _("You do not have permission to access this component!") ) return repo class SettingsBaseForm(CleanRepoMixin, forms.ModelForm): """Component base form.""" class Meta: model = Component fields = [] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request self.helper = FormHelper() self.helper.form_tag = False class SelectChecksWidget(SortedSelectMultiple): def __init__(self, attrs=None, choices=()): choices = CHECKS.get_choices() super().__init__(attrs=attrs, choices=choices) def value_from_datadict(self, data, files, name): value = super().value_from_datadict(data, files, name) if isinstance(value, str): return json.loads(value) return value def format_value(self, value): value = super().format_value(value) if isinstance(value, str): return value return json.dumps(value) class SelectChecksField(forms.CharField): def to_python(self, value): return value class ComponentDocsMixin: @staticmethod def get_field_doc(field): return ("admin/projects", f"component-{field.name}") class ProjectDocsMixin: @staticmethod def get_field_doc(field): return ("admin/projects", f"project-{field.name}") class SpamCheckMixin: def spam_check(self, value): if is_spam(value, self.request): raise ValidationError(_("This field has been identified as spam!")) class ComponentAntispamMixin(SpamCheckMixin): def clean_agreement(self): value = self.cleaned_data["agreement"] self.spam_check(value) return value class ProjectAntispamMixin(SpamCheckMixin): def clean_web(self): value = self.cleaned_data["web"] self.spam_check(value) return value def clean_instructions(self): value = self.cleaned_data["instructions"] self.spam_check(value) return value class ComponentSettingsForm( SettingsBaseForm, ComponentDocsMixin, ComponentAntispamMixin ): """Component settings form.""" class Meta: model = Component fields = ( "name", "report_source_bugs", "license", "agreement", "allow_translation_propagation", "enable_suggestions", "suggestion_voting", "suggestion_autoaccept", "priority", "check_flags", "enforced_checks", "commit_message", "add_message", "delete_message", "merge_message", "addon_message", "vcs", "repo", "branch", "push", "push_branch", "repoweb", "push_on_commit", "commit_pending_age", "merge_style", "file_format", "edit_template", "new_lang", "language_code_style", "source_language", "new_base", "filemask", "template", "intermediate", "language_regex", "variant_regex", "restricted", "auto_lock_error", "links", "manage_units", "is_glossary", "glossary_color", ) widgets = { "enforced_checks": SelectChecksWidget, "source_language": SortedSelect, } field_classes = {"enforced_checks": SelectChecksField} def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) if self.hide_restricted: self.fields["restricted"].widget = forms.HiddenInput() self.fields["links"].queryset = request.user.managed_projects.exclude( pk=self.instance.pk ) self.helper.layout = Layout( TabHolder( Tab( _("Basic"), Fieldset(_("Name"), "name"), Fieldset(_("License"), "license", "agreement"), Fieldset(_("Upstream links"), "report_source_bugs"), Fieldset( _("Listing and access"), "priority", "restricted", "links", ), Fieldset( _("Glossary"), "is_glossary", "glossary_color", ), css_id="basic", ), Tab( _("Translation"), Fieldset( _("Suggestions"), "enable_suggestions", "suggestion_voting", "suggestion_autoaccept", ), Fieldset( _("Translation settings"), "allow_translation_propagation", "manage_units", "check_flags", "variant_regex", "enforced_checks", ), css_id="translation", ), Tab( _("Version control"), Fieldset( _("Locations"), Div(template="trans/repo_help.html"), "vcs", "repo", "branch", "push", "push_branch", "repoweb", ), Fieldset( _("Version control settings"), "push_on_commit", "commit_pending_age", "merge_style", "auto_lock_error", ), css_id="vcs", ), Tab( _("Commit messages"), Fieldset( _("Commit messages"), ContextDiv( template="trans/messages_help.html", context={"user": request.user}, ), "commit_message", "add_message", "delete_message", "merge_message", "addon_message", ), css_id="messages", ), Tab( _("Files"), Fieldset( _("Translation files"), "file_format", "filemask", "language_regex", "source_language", ), Fieldset( _("Monolingual translations"), "template", "edit_template", "intermediate", ), Fieldset( _("Adding new languages"), "new_base", "new_lang", "language_code_style", ), css_id="files", ), template="layout/pills.html", ) ) vcses = ( "git", "gerrit", "github", "gitlab", "pagure", "local", "git-force-push", ) if self.instance.vcs not in vcses: vcses = (self.instance.vcs,) self.fields["vcs"].choices = [ c for c in self.fields["vcs"].choices if c[0] in vcses ] @property def hide_restricted(self): user = self.request.user if user.is_superuser: return False if settings.OFFER_HOSTING: return True return not any( "component.edit" in permissions for permissions, _langs in user.component_permissions[self.instance.pk] ) def clean(self): data = self.cleaned_data if self.hide_restricted: data["restricted"] = self.instance.restricted class ComponentCreateForm(SettingsBaseForm, ComponentDocsMixin, ComponentAntispamMixin): """Component creation form.""" class Meta: model = Component fields = [ "project", "name", "slug", "vcs", "repo", "branch", "push", "push_branch", "repoweb", "file_format", "filemask", "template", "edit_template", "intermediate", "new_base", "license", "new_lang", "language_code_style", "language_regex", "source_language", "is_glossary", ] widgets = {"source_language": SortedSelect} class ComponentNameForm(forms.Form, ComponentDocsMixin, ComponentAntispamMixin): name = forms.CharField( label=_("Component name"), max_length=COMPONENT_NAME_LENGTH, help_text=_("Display name"), ) slug = forms.SlugField( label=_("URL slug"), max_length=COMPONENT_NAME_LENGTH, help_text=_("Name used in URLs and filenames."), ) is_glossary = forms.BooleanField( label=_("Use as a glossary"), required=False, ) def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.request = request class ComponentSelectForm(ComponentNameForm): component = forms.ModelChoiceField( queryset=Component.objects.none(), label=_("Component"), help_text=_("Select existing component to copy configuration from."), ) def __init__(self, request, *args, **kwargs): if "instance" in kwargs: kwargs.pop("instance") if "auto_id" not in kwargs: kwargs["auto_id"] = "id_existing_%s" super().__init__(request, *args, **kwargs) class ComponentBranchForm(ComponentSelectForm): branch = forms.ChoiceField(label=_("Repository branch")) branch_data: Dict[int, List[str]] = {} instance = None def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_branch_%s" super().__init__(*args, **kwargs) def clean_component(self): component = self.cleaned_data["component"] self.fields["branch"].choices = [(x, x) for x in self.branch_data[component.pk]] return component def clean(self): form_fields = ("branch", "slug", "name") data = self.cleaned_data component = data.get("component") if not component or any(field not in data for field in form_fields): return kwargs = model_to_dict(component, exclude=["id", "links"]) # We need a object, not integer here kwargs["source_language"] = component.source_language kwargs["project"] = component.project for field in form_fields: kwargs[field] = data[field] self.instance = Component(**kwargs) try: self.instance.full_clean() except ValidationError as error: # Can not raise directly as this will contain errors # from fields not present here result = {NON_FIELD_ERRORS: []} for key, value in error.message_dict.items(): if key in self.fields: result[key] = value else: result[NON_FIELD_ERRORS].extend(value) raise ValidationError(error.messages) class ComponentProjectForm(ComponentNameForm): project = forms.ModelChoiceField( queryset=Project.objects.none(), label=_("Project") ) source_language = forms.ModelChoiceField( widget=SortedSelect, label=_("Source language"), help_text=_("Language used for source strings in all components"), queryset=Language.objects.all(), ) def __init__(self, request, *args, **kwargs): if "instance" in kwargs: kwargs.pop("instance") super().__init__(request, *args, **kwargs) # It might be overriden based on preset project self.fields["source_language"].initial = Language.objects.default_language self.request = request self.helper = FormHelper() self.helper.form_tag = False self.instance = None def clean(self): if "project" not in self.cleaned_data: return project = self.cleaned_data["project"] name = self.cleaned_data.get("name") if name and project.component_set.filter(name__iexact=name).exists(): raise ValidationError( {"name": _("Component with the same name already exists.")} ) slug = self.cleaned_data.get("slug") if slug and project.component_set.filter(slug__iexact=slug).exists(): raise ValidationError( {"slug": _("Component with the same name already exists.")} ) class ComponentScratchCreateForm(ComponentProjectForm): file_format = forms.ChoiceField( label=_("File format"), initial="po-mono", choices=FILE_FORMATS.get_choices( cond=lambda x: bool(x.new_translation) or hasattr(x, "update_bilingual") ), ) def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_scratchcreate_%s" super().__init__(*args, **kwargs) class ComponentZipCreateForm(ComponentProjectForm): zipfile = forms.FileField( label=_("ZIP file containing translations"), validators=[FileExtensionValidator(allowed_extensions=["zip"])], widget=forms.FileInput(attrs={"accept": ".zip,application/zip"}), ) field_order = ["zipfile", "project", "name", "slug"] def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_zipcreate_%s" super().__init__(*args, **kwargs) class ComponentDocCreateForm(ComponentProjectForm): docfile = forms.FileField( label=_("Document to translate"), validators=[validate_file_extension], ) field_order = ["docfile", "project", "name", "slug"] def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_doccreate_%s" super().__init__(*args, **kwargs) class ComponentInitCreateForm(CleanRepoMixin, ComponentProjectForm): """Component creation form. This is mostly copy from Component model. Probably should be extracted to standalone Repository model... """ project = forms.ModelChoiceField( queryset=Project.objects.none(), label=_("Project") ) vcs = forms.ChoiceField( label=_("Version control system"), help_text=_( "Version control system to use to access your " "repository with translations." ), choices=VCS_REGISTRY.get_choices(exclude={"local"}), initial=settings.DEFAULT_VCS, ) repo = forms.CharField( label=_("Source code repository"), max_length=REPO_LENGTH, help_text=_( "URL of a repository, use weblate://project/component " "for sharing with other component." ), ) branch = forms.CharField( label=_("Repository branch"), max_length=REPO_LENGTH, help_text=_("Repository branch to translate"), required=False, ) def clean_instance(self, data): params = copy.copy(data) if "discovery" in params: params.pop("discovery") instance = Component(**params) instance.clean_fields(exclude=("filemask", "file_format", "license")) instance.validate_unique() instance.clean_repo() self.instance = instance # Create linked repos automatically repo = instance.suggest_repo_link() if repo: data["repo"] = repo data["branch"] = "" self.clean_instance(data) def clean(self): self.clean_instance(self.cleaned_data) class ComponentDiscoverForm(ComponentInitCreateForm): discovery = forms.ChoiceField( label=_("Choose translation files to import"), choices=[("manual", _("Specify configuration manually"))], required=True, widget=forms.RadioSelect, ) def render_choice(self, value): context = copy.copy(value) try: format_cls = FILE_FORMATS[value["file_format"]] context["file_format_name"] = format_cls.name context["valid"] = True except KeyError: context["file_format_name"] = value["file_format"] context["valid"] = False context["origin"] = value.meta["origin"] return render_to_string("trans/discover-choice.html", context) def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) for field, value in self.fields.items(): if field == "discovery": continue value.widget = forms.HiddenInput() # Allow all VCS now (to handle zip file upload case) self.fields["vcs"].choices = VCS_REGISTRY.get_choices() self.discovered = self.perform_discovery(request, kwargs) for i, value in enumerate(self.discovered): self.fields["discovery"].choices.append((i, self.render_choice(value))) def perform_discovery(self, request, kwargs): if "data" in kwargs and "create_discovery" in request.session: discovered = [] for i, data in enumerate(request.session["create_discovery"]): item = DiscoveryResult(data) item.meta = request.session["create_discovery_meta"][i] discovered.append(item) return discovered try: self.clean_instance(kwargs["initial"]) discovered = self.discover() if not discovered: discovered = self.discover(eager=True) except ValidationError: discovered = [] request.session["create_discovery"] = discovered request.session["create_discovery_meta"] = [x.meta for x in discovered] return discovered def discover(self, eager: bool = False): return discover( self.instance.full_path, source_language=self.instance.source_language.code, eager=eager, ) def clean(self): super().clean() discovery = self.cleaned_data.get("discovery") if discovery and discovery != "manual": self.cleaned_data.update(self.discovered[int(discovery)]) class ComponentRenameForm(SettingsBaseForm, ComponentDocsMixin): """Component rename form.""" class Meta: model = Component fields = ["slug"] class ComponentMoveForm(SettingsBaseForm, ComponentDocsMixin): """Component rename form.""" class Meta: model = Component fields = ["project"] def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) self.fields["project"].queryset = request.user.managed_projects class ProjectSettingsForm(SettingsBaseForm, ProjectDocsMixin, ProjectAntispamMixin): """Project settings form.""" class Meta: model = Project fields = ( "name", "web", "instructions", "set_language_team", "use_shared_tm", "contribute_shared_tm", "enable_hooks", "language_aliases", "access_control", "translation_review", "source_review", ) widgets = { "access_control": forms.RadioSelect, "instructions": MarkdownTextarea, "language_aliases": forms.TextInput, } def clean(self): data = self.cleaned_data if settings.OFFER_HOSTING: data["contribute_shared_tm"] = data["use_shared_tm"] if ( "access_control" not in data or data["access_control"] is None or data["access_control"] == "" ): data["access_control"] = self.instance.access_control access = data["access_control"] self.changed_access = access != self.instance.access_control if self.changed_access and not self.user_can_change_access: raise ValidationError( { "access_control": _( "You do not have permission to change project access control." ) } ) if self.changed_access and access in ( Project.ACCESS_PUBLIC, Project.ACCESS_PROTECTED, ): unlicensed = self.instance.component_set.filter(license="") if unlicensed: raise ValidationError( { "access_control": _( "You must specify a license for these components " "to make them publicly accessible: %s" ) % ", ".join(unlicensed.values_list("name", flat=True)) } ) def save(self, commit: bool = True): super().save(commit=commit) if self.changed_access: Change.objects.create( project=self.instance, action=Change.ACTION_ACCESS_EDIT, user=self.user, details={"access_control": self.instance.access_control}, ) def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) self.user = request.user self.user_can_change_access = request.user.has_perm( "billing:project.permissions", self.instance ) self.changed_access = False self.helper.form_tag = False if not self.user_can_change_access: disabled = {"disabled": True} self.fields["access_control"].required = False self.fields["access_control"].help_text = _( "You do not have permission to change project access control." ) else: disabled = {} self.helper.layout = Layout( TabHolder( Tab( _("Basic"), "name", "web", "instructions", css_id="basic", ), Tab( _("Access"), InlineRadios( "access_control", template="%s/layout/radioselect_access.html", **disabled, ), css_id="access", ), Tab( _("Workflow"), "set_language_team", "use_shared_tm", "contribute_shared_tm", "enable_hooks", "language_aliases", "translation_review", "source_review", css_id="workflow", ), Tab( _("Components"), ContextDiv( template="snippets/project-component-settings.html", context={"object": self.instance, "user": request.user}, ), css_id="components", ), template="layout/pills.html", ) ) if settings.OFFER_HOSTING: self.fields["contribute_shared_tm"].widget = forms.HiddenInput() self.fields["use_shared_tm"].help_text = _( "Uses and contributes to the pool of shared translations " "between projects." ) self.fields["access_control"].choices = [ choice for choice in self.fields["access_control"].choices if choice[0] != Project.ACCESS_CUSTOM ] class ProjectRenameForm(SettingsBaseForm, ProjectDocsMixin): """Project rename form.""" class Meta: model = Project fields = ["slug"] class ProjectCreateForm(SettingsBaseForm, ProjectDocsMixin, ProjectAntispamMixin): """Project creation form.""" # This is fake field with is either hidden or configured # in the view billing = forms.ModelChoiceField( label=_("Billing"), queryset=User.objects.none(), required=True, empty_label=None, ) class Meta: model = Project fields = ("name", "slug", "web", "instructions") class ReplaceForm(forms.Form): q = QueryField( required=False, help_text=_("Optional additional filter on the strings") ) search = forms.CharField( label=_("Search string"), min_length=1, required=True, strip=False, help_text=_("Case sensitive string to search for and replace."), ) replacement = forms.CharField( label=_("Replacement string"), min_length=1, required=True, strip=False ) def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_replace_%s" super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( SearchField("q"), Field("search"), Field("replacement"), Div(template="snippets/replace-help.html"), ) class ReplaceConfirmForm(forms.Form): units = forms.ModelMultipleChoiceField(queryset=Unit.objects.none(), required=False) confirm = forms.BooleanField(required=True, initial=True, widget=forms.HiddenInput) def __init__(self, units, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["units"].queryset = units class MatrixLanguageForm(forms.Form): """Form for requesting new language.""" lang = forms.MultipleChoiceField( label=_("Languages"), choices=[], widget=forms.SelectMultiple ) def __init__(self, component, *args, **kwargs): super().__init__(*args, **kwargs) languages = Language.objects.filter(translation__component=component).exclude( pk=component.source_language_id ) self.fields["lang"].choices = languages.as_choices() class NewUnitBaseForm(forms.Form): variant = forms.ModelChoiceField( Unit.objects.none(), widget=forms.HiddenInput, required=False, ) def __init__(self, translation, user, *args, **kwargs): super().__init__(*args, **kwargs) self.translation = translation self.fields["variant"].queryset = translation.unit_set.all() self.user = user def clean(self): try: data = self.as_kwargs() except KeyError: # Probably some fields validation has failed return self.translation.validate_new_unit_data(**data) def get_glossary_flags(self): return "" def as_kwargs(self): flags = Flags() flags.merge(self.get_glossary_flags()) variant = self.cleaned_data.get("variant") if variant: flags.set_value("variant", variant.source) return { "context": self.cleaned_data.get("context", ""), "source": self.cleaned_data["source"], "target": self.cleaned_data.get("target"), "extra_flags": flags.format(), "explanation": self.cleaned_data.get("explanation", ""), "auto_context": self.cleaned_data.get("auto_context", False), } class NewMonolingualUnitForm(NewUnitBaseForm): context = forms.CharField( label=_("Translation key"), help_text=_( "Key used to identify string in translation file. " "File format specific rules might apply." ), required=True, ) source = PluralField( label=_("Source language text"), help_text=_( "You can edit this later, as with any other string in " "the source language." ), required=True, ) def __init__(self, translation, user, *args, **kwargs): super().__init__(translation, user, *args, **kwargs) self.fields["context"].widget.attrs["tabindex"] = 99 self.fields["source"].widget.attrs["tabindex"] = 100 self.fields["source"].widget.profile = user.profile self.fields["source"].initial = Unit(translation=translation, id_hash=0) class NewBilingualSourceUnitForm(NewUnitBaseForm): context = forms.CharField( label=_("Context"), help_text=_("Optional context to clarify the source strings."), required=False, ) auto_context = forms.BooleanField( required=False, initial=True, label=_("Automatically adjust context when same string already exists."), ) source = PluralField( label=_("Source string"), required=True, ) def __init__(self, translation, user, *args, **kwargs): super().__init__(translation, user, *args, **kwargs) self.fields["context"].widget.attrs["tabindex"] = 99 self.fields["context"].label = translation.component.context_label self.fields["source"].widget.attrs["tabindex"] = 100 self.fields["source"].widget.profile = user.profile self.fields["source"].initial = Unit( translation=translation.component.source_translation, id_hash=0 ) class NewBilingualUnitForm(NewBilingualSourceUnitForm): target = PluralField( label=_("Translated string"), help_text=_( "You can edit this later, as with any other string in the translation." ), required=True, ) def __init__(self, translation, user, *args, **kwargs): super().__init__(translation, user, *args, **kwargs) self.fields["target"].widget.attrs["tabindex"] = 101 self.fields["target"].widget.profile = user.profile self.fields["target"].initial = Unit(translation=translation, id_hash=0) class NewBilingualGlossarySourceUnitForm(GlossaryAddMixin, NewBilingualSourceUnitForm): def __init__(self, translation, user, *args, **kwargs): if kwargs["initial"] is None: kwargs["initial"] = {} kwargs["initial"]["terminology"] = True super().__init__(translation, user, *args, **kwargs) class NewBilingualGlossaryUnitForm(GlossaryAddMixin, NewBilingualUnitForm): pass def get_new_unit_form(translation, user, data=None, initial=None): if translation.component.has_template(): return NewMonolingualUnitForm(translation, user, data=data, initial=initial) if translation.component.is_glossary: if translation.is_source: return NewBilingualGlossarySourceUnitForm( translation, user, data=data, initial=initial ) return NewBilingualGlossaryUnitForm( translation, user, data=data, initial=initial ) if translation.is_source: return NewBilingualSourceUnitForm(translation, user, data=data, initial=initial) return NewBilingualUnitForm(translation, user, data=data, initial=initial) class CachedQueryIterator(ModelChoiceIterator): """ Choice iterator for cached querysets. It assumes the queryset is reused and avoids using iterator or count queries. """ def __iter__(self): if self.field.empty_label is not None: yield ("", self.field.empty_label) for obj in self.queryset: yield self.choice(obj) def __len__(self): return len(self.queryset) + (1 if self.field.empty_label is not None else 0) def __bool__(self): return self.field.empty_label is not None or bool(self.queryset) class CachedModelMultipleChoiceField(forms.ModelMultipleChoiceField): iterator = CachedQueryIterator def _get_queryset(self): return self._queryset def _set_queryset(self, queryset): self._queryset = queryset self.widget.choices = self.choices queryset = property(_get_queryset, _set_queryset) class BulkEditForm(forms.Form): q = QueryField(required=True) state = forms.ChoiceField( label=_("State to set"), choices=((-1, _("Do not change")),) + STATE_CHOICES ) add_flags = FlagField(label=_("Translation flags to add"), required=False) remove_flags = FlagField(label=_("Translation flags to remove"), required=False) add_labels = CachedModelMultipleChoiceField( queryset=Label.objects.none(), label=_("Labels to add"), widget=forms.CheckboxSelectMultiple(), required=False, ) remove_labels = CachedModelMultipleChoiceField( queryset=Label.objects.none(), label=_("Labels to remove"), widget=forms.CheckboxSelectMultiple(), required=False, ) def __init__(self, user, obj, *args, **kwargs): project = kwargs.pop("project") kwargs["auto_id"] = "id_bulk_%s" super().__init__(*args, **kwargs) labels = project.label_set.all() if labels: self.fields["remove_labels"].queryset = labels self.fields["add_labels"].queryset = labels excluded = {STATE_EMPTY, STATE_READONLY} if user is not None and not user.has_perm("unit.review", obj): excluded.add(STATE_APPROVED) # Filter offered states self.fields["state"].choices = [ x for x in self.fields["state"].choices if x[0] not in excluded ] self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div(template="snippets/bulk-help.html"), SearchField("q"), Field("state"), Field("add_flags"), Field("remove_flags"), ) if labels: self.helper.layout.append(InlineCheckboxes("add_labels")) self.helper.layout.append(InlineCheckboxes("remove_labels")) class ContributorAgreementForm(forms.Form): confirm = forms.BooleanField( label=_("I accept the contributor agreement"), required=True ) next = forms.CharField(required=False, widget=forms.HiddenInput) class BaseDeleteForm(forms.Form): confirm = forms.CharField(required=True) warning_template = "" def __init__(self, obj, *args, **kwargs): super().__init__(*args, **kwargs) self.obj = obj self.helper = FormHelper(self) self.helper.layout = Layout( ContextDiv( template=self.warning_template, css_class="form-group", context={"object": obj}, ), Field("confirm"), ) self.helper.form_tag = False def clean(self): if self.cleaned_data.get("confirm") != self.obj.full_slug: raise ValidationError( _("The slug does not match the one marked for deletion!") ) class TranslationDeleteForm(BaseDeleteForm): confirm = forms.CharField( label=_("Removal confirmation"), help_text=_("Please type in the full slug of the translation to confirm."), required=True, ) warning_template = "trans/delete-translation.html" class ComponentDeleteForm(BaseDeleteForm): confirm = forms.CharField( label=_("Removal confirmation"), help_text=_("Please type in the full slug of the component to confirm."), required=True, ) warning_template = "trans/delete-component.html" class ProjectDeleteForm(BaseDeleteForm): confirm = forms.CharField( label=_("Removal confirmation"), help_text=_("Please type in the slug of the project to confirm."), required=True, ) warning_template = "trans/delete-project.html" class ProjectLanguageDeleteForm(BaseDeleteForm): confirm = forms.CharField( label=_("Removal confirmation"), help_text=_("Please type in the slug of the project and language to confirm."), required=True, ) warning_template = "trans/delete-project-language.html" class AnnouncementForm(forms.ModelForm): """Component base form.""" class Meta: model = Announcement fields = ["message", "category", "expiry", "notify"] widgets = { "expiry": WeblateDateInput(), "message": MarkdownTextarea, } class ChangesForm(forms.Form): project = forms.ChoiceField(label=_("Project"), choices=[("", "")], required=False) lang = forms.ChoiceField(label=_("Language"), choices=[("", "")], required=False) action = forms.MultipleChoiceField( label=_("Action"), required=False, widget=SortedSelectMultiple, choices=Change.ACTION_CHOICES, ) user = UsernameField(label=_("Author username"), required=False, help_text=None) start_date = WeblateDateField( label=_("Starting date"), required=False, datepicker=False ) end_date = WeblateDateField( label=_("Ending date"), required=False, datepicker=False ) def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["lang"].choices += Language.objects.have_translation().as_choices() self.fields["project"].choices += [ (project.slug, project.name) for project in request.user.allowed_projects ] class LabelForm(forms.ModelForm): class Meta: model = Label fields = ("name", "color") widgets = {"color": ColorWidget()} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False class ProjectTokenDeleteForm(forms.Form): token = forms.ModelChoiceField( ProjectToken.objects.none(), widget=forms.HiddenInput, required=True, ) def __init__(self, project, *args, **kwargs): self.project = project super().__init__(*args, **kwargs) self.fields["token"].queryset = project.projecttoken_set.all() class ProjectTokenCreateForm(forms.ModelForm): class Meta: model = ProjectToken fields = ["name", "expires", "project"] widgets = { "expires": WeblateDateInput(), "project": forms.HiddenInput, } def __init__(self, project, *args, **kwargs): self.project = project kwargs["initial"] = {"project": project} super().__init__(*args, **kwargs) def clean_project(self): if self.project != self.cleaned_data["project"]: raise ValidationError("Invalid project!") return self.cleaned_data["project"] def clean_expires(self): expires = self.cleaned_data["expires"] expires = expires.replace(hour=23, minute=59, second=59, microsecond=999999) if expires < timezone.now(): raise forms.ValidationError(gettext("Expiry cannot be in the past!")) return expires class ProjectGroupDeleteForm(forms.Form): group = forms.ModelChoiceField( Group.objects.none(), widget=forms.HiddenInput, required=True, ) def __init__(self, project, *args, **kwargs): self.project = project super().__init__(*args, **kwargs) self.fields["group"].queryset = project.defined_groups.all() class ProjectUserGroupForm(UserManageForm): groups = forms.ModelMultipleChoiceField( Group.objects.none(), widget=forms.CheckboxSelectMultiple, label=_("Teams"), required=False, ) def __init__(self, project, *args, **kwargs): self.project = project super().__init__(*args, **kwargs) self.fields["user"].widget = forms.HiddenInput() self.fields["groups"].queryset = project.defined_groups.all()
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # import copy import json import re from datetime import date, datetime, timedelta from typing import Dict, List from crispy_forms.bootstrap import InlineCheckboxes, InlineRadios, Tab, TabHolder from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Field, Fieldset, Layout from django import forms from django.conf import settings from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError from django.core.validators import FileExtensionValidator from django.db.models import Q from django.forms import model_to_dict from django.forms.models import ModelChoiceIterator from django.forms.utils import from_current_timezone from django.template.loader import render_to_string from django.urls import reverse from django.utils import timezone from django.utils.html import escape from django.utils.http import urlencode from django.utils.safestring import mark_safe from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from translation_finder import DiscoveryResult, discover from weblate.auth.models import Group, User from weblate.checks.flags import Flags from weblate.checks.models import CHECKS from weblate.checks.utils import highlight_string from weblate.formats.models import EXPORTERS, FILE_FORMATS from weblate.glossary.forms import GlossaryAddMixin from weblate.lang.data import BASIC_LANGUAGES from weblate.lang.models import Language from weblate.machinery import MACHINE_TRANSLATION_SERVICES from weblate.trans.defines import COMPONENT_NAME_LENGTH, REPO_LENGTH from weblate.trans.filter import FILTERS, get_filter_choice from weblate.trans.models import ( Announcement, Change, Component, Label, Project, ProjectToken, Unit, ) from weblate.trans.specialchars import RTL_CHARS_DATA, get_special_chars from weblate.trans.util import check_upload_method_permissions, is_repo_link from weblate.trans.validators import validate_check_flags from weblate.utils.antispam import is_spam from weblate.utils.errors import report_error from weblate.utils.forms import ( ColorWidget, ContextDiv, EmailField, SearchField, SortedSelect, SortedSelectMultiple, UsernameField, ) from weblate.utils.hash import checksum_to_hash, hash_to_checksum from weblate.utils.search import parse_query from weblate.utils.state import ( STATE_APPROVED, STATE_CHOICES, STATE_EMPTY, STATE_FUZZY, STATE_READONLY, STATE_TRANSLATED, ) from weblate.utils.validators import validate_file_extension from weblate.vcs.models import VCS_REGISTRY BUTTON_TEMPLATE = """ <button class="btn btn-default {0}" title="{1}" {2}>{3}</button> """ RADIO_TEMPLATE = """ <label class="btn btn-default {0}" title="{1}"> <input type="radio" name="{2}" value="{3}" {4}/> {5} </label> """ GROUP_TEMPLATE = """ <div class="btn-group btn-group-xs" {0}>{1}</div> """ TOOLBAR_TEMPLATE = """ <div class="btn-toolbar pull-right flip editor-toolbar">{0}</div> """ class MarkdownTextarea(forms.Textarea): def __init__(self, **kwargs): kwargs["attrs"] = { "dir": "auto", "class": "markdown-editor highlight-editor", "data-mode": "markdown", } super().__init__(**kwargs) class WeblateDateInput(forms.DateInput): def __init__(self, datepicker=True, **kwargs): attrs = {"type": "date"} if datepicker: attrs["data-provide"] = "datepicker" attrs["data-date-format"] = "yyyy-mm-dd" super().__init__(attrs=attrs, format="%Y-%m-%d", **kwargs) class WeblateDateField(forms.DateField): def __init__(self, datepicker=True, **kwargs): if "widget" not in kwargs: kwargs["widget"] = WeblateDateInput(datepicker=datepicker) super().__init__(**kwargs) def to_python(self, value): """Produce timezone aware datetime with 00:00:00 as time.""" value = super().to_python(value) if isinstance(value, date): return from_current_timezone( datetime(value.year, value.month, value.day, 0, 0, 0) ) return value class ChecksumField(forms.CharField): """Field for handling checksum IDs for translation.""" def __init__(self, *args, **kwargs): kwargs["widget"] = forms.HiddenInput super().__init__(*args, **kwargs) def clean(self, value): super().clean(value) if not value: return None try: return checksum_to_hash(value) except ValueError: raise ValidationError(_("Invalid checksum specified!")) class UserField(forms.CharField): def clean(self, value): if not value: return None try: return User.objects.get(Q(username=value) | Q(email=value)) except User.DoesNotExist: raise ValidationError(_("Could not find any such user.")) except User.MultipleObjectsReturned: raise ValidationError(_("More possible users were found.")) class QueryField(forms.CharField): def __init__(self, **kwargs): if "label" not in kwargs: kwargs["label"] = _("Query") if "required" not in kwargs: kwargs["required"] = False super().__init__(**kwargs) def clean(self, value): if not value: if self.required: raise ValidationError(_("Missing query string.")) return "" try: parse_query(value) return value except Exception as error: report_error() raise ValidationError(_("Could not parse query string: {}").format(error)) class FlagField(forms.CharField): default_validators = [validate_check_flags] class PluralTextarea(forms.Textarea): """Text-area extension which possibly handles plurals.""" def __init__(self, *args, **kwargs): self.profile = None super().__init__(*args, **kwargs) def get_rtl_toolbar(self, fieldname): groups = [] # Special chars chars = [] for name, char, value in RTL_CHARS_DATA: chars.append( BUTTON_TEMPLATE.format( "specialchar", name, 'data-value="{}"'.format( value.encode("ascii", "xmlcharrefreplace").decode("ascii") ), char, ) ) groups.append(GROUP_TEMPLATE.format("", "\n".join(chars))) return TOOLBAR_TEMPLATE.format("\n".join(groups)) def get_rtl_toggle(self, language, fieldname): if language.direction != "rtl": return "" # RTL/LTR switch rtl_name = f"rtl-{fieldname}" rtl_switch = [ RADIO_TEMPLATE.format( "direction-toggle active", gettext("Toggle text direction"), rtl_name, "rtl", 'checked="checked"', "RTL", ), RADIO_TEMPLATE.format( "direction-toggle", gettext("Toggle text direction"), rtl_name, "ltr", "", "LTR", ), ] groups = [GROUP_TEMPLATE.format('data-toggle="buttons"', "\n".join(rtl_switch))] return mark_safe(TOOLBAR_TEMPLATE.format("\n".join(groups))) def get_toolbar(self, language, fieldname, unit, idx, source): """Return toolbar HTML code.""" profile = self.profile groups = [] # Special chars chars = [ BUTTON_TEMPLATE.format( "specialchar", name, 'data-value="{}"'.format( value.encode("ascii", "xmlcharrefreplace").decode("ascii") ), char, ) for name, char, value in get_special_chars( language, profile.special_chars, unit.source ) ] groups.append(GROUP_TEMPLATE.format("", "\n".join(chars))) result = TOOLBAR_TEMPLATE.format("\n".join(groups)) if language.direction == "rtl": result = self.get_rtl_toolbar(fieldname) + result return mark_safe(result) def render(self, name, value, attrs=None, renderer=None, **kwargs): """Render all textareas with correct plural labels.""" unit = value values = unit.get_target_plurals() lang = unit.translation.language plural = unit.translation.plural tabindex = self.attrs["tabindex"] placeables = [hl[2] for hl in highlight_string(unit.source_string, unit)] # Need to add extra class attrs["class"] = "translation-editor form-control highlight-editor" attrs["tabindex"] = tabindex attrs["lang"] = lang.code attrs["dir"] = lang.direction attrs["rows"] = 3 attrs["data-max"] = unit.get_max_length() attrs["data-mode"] = unit.edit_mode attrs["data-placeables"] = "|".join(re.escape(pl) for pl in placeables if pl) if unit.readonly: attrs["readonly"] = 1 # Okay we have more strings ret = [] plurals = unit.get_source_plurals() base_id = f"id_{unit.checksum}" for idx, val in enumerate(values): # Generate ID fieldname = f"{name}_{idx}" fieldid = f"{base_id}_{idx}" attrs["id"] = fieldid attrs["tabindex"] = tabindex + idx if idx and len(plurals) > 1: source = plurals[1] else: source = plurals[0] # Render textare textarea = super().render(fieldname, val, attrs, renderer, **kwargs) # Label for plural label = escape(unit.translation.language) if len(values) != 1: label = f"{label}, {plural.get_plural_label(idx)}" ret.append( render_to_string( "snippets/editor.html", { "toolbar": self.get_toolbar(lang, fieldid, unit, idx, source), "fieldid": fieldid, "label": mark_safe(label), "textarea": textarea, "max_length": attrs["data-max"], "length": len(val), "source_length": len(source), "rtl_toggle": self.get_rtl_toggle(lang, fieldid), }, ) ) # Show plural formula for more strings if len(values) > 1: ret.append( render_to_string( "snippets/plural-formula.html", {"plural": plural, "user": self.profile.user}, ) ) # Join output return mark_safe("".join(ret)) def value_from_datadict(self, data, files, name): """Return processed plurals as a list.""" ret = [] for idx in range(0, 10): fieldname = f"{name}_{idx:d}" if fieldname not in data: break ret.append(data.get(fieldname, "")) return [r.replace("\r", "") for r in ret] class PluralField(forms.CharField): """Renderer for the plural field. The only difference from CharField is that it does not force value to be string. """ def __init__(self, max_length=None, min_length=None, **kwargs): kwargs["label"] = "" super().__init__(widget=PluralTextarea, **kwargs) def to_python(self, value): """Return list or string as returned by PluralTextarea.""" return value def clean(self, value): value = super().clean(value) if not value or (self.required and not any(value)): raise ValidationError(_("Missing translated string!")) return value class FilterField(forms.ChoiceField): def __init__(self, *args, **kwargs): kwargs["label"] = _("Search filter") if "required" not in kwargs: kwargs["required"] = False kwargs["choices"] = get_filter_choice() kwargs["error_messages"] = { "invalid_choice": _("Please choose a valid filter type.") } super().__init__(*args, **kwargs) def to_python(self, value): if value == "untranslated": return "todo" return super().to_python(value) class ChecksumForm(forms.Form): """Form for handling checksum IDs for translation.""" checksum = ChecksumField(required=True) def __init__(self, unit_set, *args, **kwargs): self.unit_set = unit_set super().__init__(*args, **kwargs) def clean_checksum(self): """Validate whether checksum is valid and fetches unit for it.""" if "checksum" not in self.cleaned_data: return unit_set = self.unit_set try: self.cleaned_data["unit"] = unit_set.filter( id_hash=self.cleaned_data["checksum"] )[0] except (Unit.DoesNotExist, IndexError): raise ValidationError( _("The string you wanted to translate is no longer available.") ) class UnitForm(forms.Form): def __init__(self, unit: Unit, *args, **kwargs): self.unit = unit super().__init__(*args, **kwargs) class FuzzyField(forms.BooleanField): help_as_icon = True def __init__(self, *args, **kwargs): kwargs["label"] = _("Needs editing") kwargs["help_text"] = _( 'Strings are usually marked as "Needs editing" after the source ' "string is updated, or when marked as such manually." ) super().__init__(*args, **kwargs) self.widget.attrs["class"] = "fuzzy_checkbox" class TranslationForm(UnitForm): """Form used for translation of single string.""" contentsum = ChecksumField(required=True) translationsum = ChecksumField(required=True) target = PluralField(required=False) fuzzy = FuzzyField(required=False) review = forms.ChoiceField( label=_("Review state"), choices=[ (STATE_FUZZY, _("Needs editing")), (STATE_TRANSLATED, _("Waiting for review")), (STATE_APPROVED, _("Approved")), ], required=False, widget=forms.RadioSelect, ) explanation = forms.CharField( widget=MarkdownTextarea, label=_("Explanation"), help_text=_( "Additional explanation to clarify meaning or usage of the string." ), max_length=1000, required=False, ) def __init__(self, user, unit: Unit, *args, **kwargs): if unit is not None: kwargs["initial"] = { "checksum": unit.checksum, "contentsum": hash_to_checksum(unit.content_hash), "translationsum": hash_to_checksum(unit.get_target_hash()), "target": unit, "fuzzy": unit.fuzzy, "review": unit.state, "explanation": unit.explanation, } kwargs["auto_id"] = f"id_{unit.checksum}_%s" tabindex = kwargs.pop("tabindex", 100) super().__init__(unit, *args, **kwargs) if unit.readonly: for field in ["target", "fuzzy", "review"]: self.fields[field].widget.attrs["readonly"] = 1 self.fields["review"].choices = [ (STATE_READONLY, _("Read only")), ] self.user = user self.fields["target"].widget.attrs["tabindex"] = tabindex self.fields["target"].widget.profile = user.profile self.fields["review"].widget.attrs["class"] = "review_radio" # Avoid failing validation on untranslated string if args: self.fields["review"].choices.append((STATE_EMPTY, "")) self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_tag = False self.helper.disable_csrf = True self.helper.layout = Layout( Field("target"), Field("fuzzy"), Field("contentsum"), Field("translationsum"), InlineRadios("review"), Field("explanation"), ) if unit and user.has_perm("unit.review", unit.translation): self.fields["fuzzy"].widget = forms.HiddenInput() else: self.fields["review"].widget = forms.HiddenInput() if not unit.translation.component.is_glossary: self.fields["explanation"].widget = forms.HiddenInput() def clean(self): super().clean() # Check required fields required = {"target", "contentsum", "translationsum"} if not required.issubset(self.cleaned_data): return unit = self.unit if self.cleaned_data["contentsum"] != unit.content_hash: raise ValidationError( _( "Source string has been changed meanwhile. " "Please check your changes." ) ) if self.cleaned_data["translationsum"] != unit.get_target_hash(): raise ValidationError( _( "Translation of the string has been changed meanwhile. " "Please check your changes." ) ) max_length = unit.get_max_length() for text in self.cleaned_data["target"]: if len(text) > max_length: raise ValidationError(_("Translation text too long!")) if self.user.has_perm( "unit.review", unit.translation ) and self.cleaned_data.get("review"): self.cleaned_data["state"] = int(self.cleaned_data["review"]) elif self.cleaned_data["fuzzy"]: self.cleaned_data["state"] = STATE_FUZZY else: self.cleaned_data["state"] = STATE_TRANSLATED class ZenTranslationForm(TranslationForm): checksum = ChecksumField(required=True) def __init__(self, user, unit, *args, **kwargs): super().__init__(user, unit, *args, **kwargs) self.helper.form_action = reverse( "save_zen", kwargs=unit.translation.get_reverse_url_kwargs() ) self.helper.form_tag = True self.helper.disable_csrf = False self.helper.layout.append(Field("checksum")) class DownloadForm(forms.Form): q = QueryField() format = forms.ChoiceField( label=_("File format"), choices=[(x.name, x.verbose) for x in EXPORTERS.values()], initial="po", required=True, widget=forms.RadioSelect, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( SearchField("q"), InlineRadios("format"), ) class SimpleUploadForm(forms.Form): """Base form for uploading a file.""" file = forms.FileField(label=_("File"), validators=[validate_file_extension]) method = forms.ChoiceField( label=_("File upload mode"), choices=( ("translate", _("Add as translation")), ("approve", _("Add as approved translation")), ("suggest", _("Add as suggestion")), ("fuzzy", _("Add as translation needing edit")), ("replace", _("Replace existing translation file")), ("source", _("Update source strings")), ("add", _("Add new strings")), ), widget=forms.RadioSelect, required=True, ) fuzzy = forms.ChoiceField( label=_("Processing of strings needing edit"), choices=( ("", _("Do not import")), ("process", _("Import as string needing edit")), ("approve", _("Import as translated")), ), required=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False @staticmethod def get_field_doc(field): return ("user/files", f"upload-{field.name}") def remove_translation_choice(self, value): """Remove add as translation choice.""" choices = self.fields["method"].choices self.fields["method"].choices = [ choice for choice in choices if choice[0] != value ] class UploadForm(SimpleUploadForm): """Upload form with the option to overwrite current messages.""" conflicts = forms.ChoiceField( label=_("Conflict handling"), help_text=_( "Whether to overwrite existing translations if the string is " "already translated." ), choices=( ("", _("Update only untranslated strings")), ("replace-translated", _("Update translated strings")), ("replace-approved", _("Update translated and approved strings")), ), required=False, initial="replace-translated", ) class ExtraUploadForm(UploadForm): """Advanced upload form for users who can override authorship.""" author_name = forms.CharField(label=_("Author name")) author_email = EmailField(label=_("Author e-mail")) def get_upload_form(user, translation, *args, **kwargs): """Return correct upload form based on user permissions.""" if user.has_perm("upload.authorship", translation): form = ExtraUploadForm kwargs["initial"] = {"author_name": user.full_name, "author_email": user.email} elif user.has_perm("upload.overwrite", translation): form = UploadForm else: form = SimpleUploadForm result = form(*args, **kwargs) for method in [x[0] for x in result.fields["method"].choices]: if not check_upload_method_permissions(user, translation, method): result.remove_translation_choice(method) # Remove approved choice for non review projects if not user.has_perm("unit.review", translation) and not form == SimpleUploadForm: result.fields["conflicts"].choices = [ choice for choice in result.fields["conflicts"].choices if choice[0] != "approved" ] return result class SearchForm(forms.Form): """Text searching form.""" # pylint: disable=invalid-name q = QueryField() sort_by = forms.CharField(required=False, widget=forms.HiddenInput) checksum = ChecksumField(required=False) offset = forms.IntegerField(min_value=-1, required=False, widget=forms.HiddenInput) offset_kwargs = {} def __init__(self, user, language=None, show_builder=True, **kwargs): """Generate choices for other component in same project.""" self.user = user self.language = language super().__init__(**kwargs) self.helper = FormHelper(self) self.helper.disable_csrf = True self.helper.form_tag = False self.helper.layout = Layout( Div( Field("offset", **self.offset_kwargs), SearchField("q"), Field("sort_by", template="snippets/sort-field.html"), css_class="btn-toolbar", role="toolbar", ), ContextDiv( template="snippets/query-builder.html", context={ "user": self.user, "month_ago": timezone.now() - timedelta(days=31), "show_builder": show_builder, "language": self.language, }, ), Field("checksum"), ) def get_name(self): """Return verbose name for a search.""" return FILTERS.get_search_name(self.cleaned_data.get("q", "")) def get_search_query(self): return self.cleaned_data["q"] def clean_offset(self): if self.cleaned_data.get("offset") is None: self.cleaned_data["offset"] = 1 return self.cleaned_data["offset"] def items(self): items = [] # Skip checksum and offset as these change ignored = {"offset", "checksum"} for param in sorted(self.cleaned_data): value = self.cleaned_data[param] # We don't care about empty values or ignored if value is None or param in ignored: continue if isinstance(value, bool): # Only store true values if value: items.append((param, "1")) elif isinstance(value, int): # Avoid storing 0 values if value > 0: items.append((param, str(value))) elif isinstance(value, datetime): # Convert date to string items.append((param, value.date().isoformat())) elif isinstance(value, list): for val in value: items.append((param, val)) elif isinstance(value, User): items.append((param, value.username)) else: # It should be string here if value: items.append((param, value)) return items def urlencode(self): return urlencode(self.items()) def reset_offset(self): """Reset offset to avoid using form as default for new search.""" data = copy.copy(self.data) data["offset"] = "1" data["checksum"] = "" self.data = data return self class PositionSearchForm(SearchForm): offset = forms.IntegerField(min_value=-1, required=False) offset_kwargs = {"template": "snippets/position-field.html"} class MergeForm(UnitForm): """Simple form for merging translation of two units.""" merge = forms.IntegerField() def clean(self): super().clean() if "merge" not in self.cleaned_data: return None try: unit = self.unit translation = unit.translation project = translation.component.project self.cleaned_data["merge_unit"] = merge_unit = Unit.objects.get( pk=self.cleaned_data["merge"], translation__component__project=project, translation__language=translation.language, ) # Compare in Python to ensure case sensitiveness on MySQL if not translation.is_source and unit.source != merge_unit.source: raise ValidationError(_("Could not find merged string.")) except Unit.DoesNotExist: raise ValidationError(_("Could not find merged string.")) return self.cleaned_data class RevertForm(UnitForm): """Form for reverting edits.""" revert = forms.IntegerField() def clean(self): super().clean() if "revert" not in self.cleaned_data: return None try: self.cleaned_data["revert_change"] = Change.objects.get( pk=self.cleaned_data["revert"], unit=self.unit ) except Change.DoesNotExist: raise ValidationError(_("Could not find reverted change.")) return self.cleaned_data class AutoForm(forms.Form): """Automatic translation form.""" mode = forms.ChoiceField( label=_("Automatic translation mode"), choices=[ ("suggest", _("Add as suggestion")), ("translate", _("Add as translation")), ("fuzzy", _("Add as needing edit")), ], initial="suggest", ) filter_type = FilterField( required=True, initial="todo", help_text=_( "Please note that translating all strings will " "discard all existing translations." ), ) auto_source = forms.ChoiceField( label=_("Automatic translation source"), choices=[ ("others", _("Other translation components")), ("mt", _("Machine translation")), ], initial="others", ) component = forms.ChoiceField( label=_("Components"), required=False, help_text=_( "Turn on contribution to shared translation memory for the project to " "get access to additional components." ), initial="", ) engines = forms.MultipleChoiceField( label=_("Machine translation engines"), choices=[], required=False ) threshold = forms.IntegerField( label=_("Score threshold"), initial=80, min_value=1, max_value=100 ) def __init__(self, obj, *args, **kwargs): """Generate choices for other component in same project.""" super().__init__(*args, **kwargs) self.obj = obj # Add components from other projects with enabled shared TM self.components = obj.project.component_set.filter( source_language=obj.source_language ) | Component.objects.filter( source_language_id=obj.source_language_id, project__contribute_shared_tm=True, ).exclude( project=obj.project ) # Fetching is faster than doing count on possibly thousands of components if len(self.components.values_list("id")[:30]) == 30: # Do not show choices when too many self.fields["component"] = forms.CharField( required=False, label=_("Components"), help_text=_( "Enter component to use as source, " "keep blank to use all components in current project." ), ) else: choices = [ (s.id, str(s)) for s in self.components.order_project().prefetch_related("project") ] self.fields["component"].choices = [ ("", _("All components in current project")) ] + choices self.fields["engines"].choices = [ (key, mt.name) for key, mt in MACHINE_TRANSLATION_SERVICES.items() ] if "weblate" in MACHINE_TRANSLATION_SERVICES.keys(): self.fields["engines"].initial = "weblate" use_types = {"all", "nottranslated", "todo", "fuzzy", "check:inconsistent"} self.fields["filter_type"].choices = [ x for x in self.fields["filter_type"].choices if x[0] in use_types ] self.helper = FormHelper(self) self.helper.layout = Layout( Field("mode"), Field("filter_type"), InlineRadios("auto_source", id="select_auto_source"), Div("component", css_id="auto_source_others"), Div("engines", "threshold", css_id="auto_source_mt"), ) def clean_component(self): component = self.cleaned_data["component"] if not component: return None if component.isdigit(): try: result = self.components.get(pk=component) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) else: slashes = component.count("/") if slashes == 0: try: result = self.components.get( slug=component, project=self.obj.project ) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) elif slashes == 1: project_slug, component_slug = component.split("/") try: result = self.components.get( slug=component_slug, project__slug=project_slug ) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) else: raise ValidationError(_("Please provide valid component slug!")) return result.pk class CommentForm(forms.Form): """Simple commenting form.""" scope = forms.ChoiceField( label=_("Scope"), help_text=_( "Is your comment specific to this " "translation or generic for all of them?" ), choices=( ( "report", _("Report issue with the source string"), ), ( "global", _("Source string comment, suggestions for changes to this string"), ), ( "translation", _("Translation comment, discussions with other translators"), ), ), ) comment = forms.CharField( widget=MarkdownTextarea, label=_("New comment"), help_text=_("You can use Markdown and mention users by @username."), max_length=1000, ) def __init__(self, project, *args, **kwargs): super().__init__(*args, **kwargs) # Remove bug report in case source review is not enabled if not project.source_review: self.fields["scope"].choices = self.fields["scope"].choices[1:] class EngageForm(forms.Form): """Form to choose language for engagement widgets.""" lang = forms.ChoiceField(required=False, choices=[("", _("All languages"))]) component = forms.ChoiceField(required=False, choices=[("", _("All components"))]) def __init__(self, user, project, *args, **kwargs): """Dynamically generate choices for used languages in project.""" super().__init__(*args, **kwargs) self.fields["lang"].choices += project.languages.as_choices() self.fields["component"].choices += ( project.component_set.filter_access(user) .order() .values_list("slug", "name") ) class NewLanguageOwnerForm(forms.Form): """Form for requesting new language.""" lang = forms.MultipleChoiceField( label=_("Languages"), choices=[], widget=forms.SelectMultiple ) def get_lang_objects(self): return Language.objects.exclude( Q(translation__component=self.component) | Q(component=self.component) ) def __init__(self, component, *args, **kwargs): super().__init__(*args, **kwargs) self.component = component languages = self.get_lang_objects() self.fields["lang"].choices = languages.as_choices() class NewLanguageForm(NewLanguageOwnerForm): """Form for requesting new language.""" lang = forms.ChoiceField(label=_("Language"), choices=[], widget=forms.Select) def get_lang_objects(self): codes = BASIC_LANGUAGES if settings.BASIC_LANGUAGES is not None: codes = settings.BASIC_LANGUAGES return super().get_lang_objects().filter(code__in=codes) def __init__(self, component, *args, **kwargs): super().__init__(component, *args, **kwargs) self.fields["lang"].choices = [("", _("Please choose"))] + self.fields[ "lang" ].choices def clean_lang(self): # Compatibility with NewLanguageOwnerForm return [self.cleaned_data["lang"]] def get_new_language_form(request, component): """Return new language form for user.""" if not request.user.has_perm("translation.add", component): raise PermissionDenied() if request.user.has_perm("translation.add_more", component): return NewLanguageOwnerForm return NewLanguageForm class ContextForm(forms.ModelForm): class Meta: model = Unit fields = ("explanation", "labels", "extra_flags") widgets = { "labels": forms.CheckboxSelectMultiple(), "explanation": MarkdownTextarea, } doc_links = { "explanation": ("admin/translating", "additional-explanation"), "labels": ("devel/translations", "labels"), "extra_flags": ("admin/translating", "additional-flags"), } def get_field_doc(self, field): return self.doc_links[field.name] def __init__(self, data=None, instance=None, user=None, **kwargs): kwargs["initial"] = { "labels": Label.objects.filter( Q(unit=instance) | Q(unit__source_unit=instance) ) } super().__init__(data=data, instance=instance, **kwargs) project = instance.translation.component.project self.fields["labels"].queryset = project.label_set.all() self.helper = FormHelper(self) self.helper.disable_csrf = True self.helper.form_tag = False self.helper.layout = Layout( Field("explanation"), Field("labels"), ContextDiv( template="snippets/labels_description.html", context={"project": project, "user": user}, ), Field("extra_flags"), ) def save(self, commit=True): if commit: self.instance.save(same_content=True) self._save_m2m() return self.instance return super().save(commit) class UserManageForm(forms.Form): user = UserField( label=_("User to add"), help_text=_( "Please type in an existing Weblate account name or e-mail address." ), ) class UserBlockForm(forms.Form): user = UserField( label=_("User to block"), help_text=_( "Please type in an existing Weblate account name or e-mail address." ), ) expiry = forms.ChoiceField( label=_("Block duration"), choices=( ("", _("Block user until I unblock them")), ("1", _("Block user for one day")), ("7", _("Block user for one week")), ("30", _("Block user for one month")), ), required=False, ) class ReportsForm(forms.Form): style = forms.ChoiceField( label=_("Report format"), help_text=_("Choose file format for the report"), choices=( ("rst", _("reStructuredText")), ("json", _("JSON")), ("html", _("HTML")), ), ) period = forms.ChoiceField( label=_("Report period"), choices=( ("30days", _("Last 30 days")), ("this-month", _("This month")), ("month", _("Last month")), ("this-year", _("This year")), ("year", _("Last year")), ("", _("As specified")), ), required=False, ) start_date = WeblateDateField( label=_("Starting date"), required=False, datepicker=False ) end_date = WeblateDateField( label=_("Ending date"), required=False, datepicker=False ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Field("style"), Field("period"), Div( "start_date", "end_date", css_class="input-group input-daterange", data_provide="datepicker", data_date_format="yyyy-mm-dd", ), ) def clean(self): super().clean() # Invalid value, skip rest of the validation if "period" not in self.cleaned_data: return # Handle predefined periods if self.cleaned_data["period"] == "30days": end = timezone.now() start = end - timedelta(days=30) elif self.cleaned_data["period"] == "month": end = timezone.now().replace(day=1) - timedelta(days=1) start = end.replace(day=1) elif self.cleaned_data["period"] == "this-month": end = timezone.now().replace(day=1) + timedelta(days=31) end = end.replace(day=1) - timedelta(days=1) start = end.replace(day=1) elif self.cleaned_data["period"] == "year": year = timezone.now().year - 1 end = timezone.make_aware(datetime(year, 12, 31)) start = timezone.make_aware(datetime(year, 1, 1)) elif self.cleaned_data["period"] == "this-year": year = timezone.now().year end = timezone.make_aware(datetime(year, 12, 31)) start = timezone.make_aware(datetime(year, 1, 1)) else: # Validate custom period if not self.cleaned_data.get("start_date"): raise ValidationError({"start_date": _("Missing date!")}) if not self.cleaned_data.get("end_date"): raise ValidationError({"end_date": _("Missing date!")}) start = self.cleaned_data["start_date"] end = self.cleaned_data["end_date"] # Sanitize timestamps self.cleaned_data["start_date"] = start.replace( hour=0, minute=0, second=0, microsecond=0 ) self.cleaned_data["end_date"] = end.replace( hour=23, minute=59, second=59, microsecond=999999 ) # Final validation if self.cleaned_data["start_date"] > self.cleaned_data["end_date"]: msg = _("Starting date has to be before ending date!") raise ValidationError({"start_date": msg, "end_date": msg}) class CleanRepoMixin: def clean_repo(self): repo = self.cleaned_data.get("repo") if not repo or not is_repo_link(repo) or "/" not in repo[10:]: return repo project, component = repo[10:].split("/", 1) try: obj = Component.objects.get( slug__iexact=component, project__slug__iexact=project ) except Component.DoesNotExist: return repo if not self.request.user.has_perm("component.edit", obj): raise ValidationError( _("You do not have permission to access this component!") ) return repo class SettingsBaseForm(CleanRepoMixin, forms.ModelForm): """Component base form.""" class Meta: model = Component fields = [] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request self.helper = FormHelper() self.helper.form_tag = False class SelectChecksWidget(SortedSelectMultiple): def __init__(self, attrs=None, choices=()): choices = CHECKS.get_choices() super().__init__(attrs=attrs, choices=choices) def value_from_datadict(self, data, files, name): value = super().value_from_datadict(data, files, name) if isinstance(value, str): return json.loads(value) return value def format_value(self, value): value = super().format_value(value) if isinstance(value, str): return value return json.dumps(value) class SelectChecksField(forms.CharField): def to_python(self, value): return value class ComponentDocsMixin: @staticmethod def get_field_doc(field): return ("admin/projects", f"component-{field.name}") class ProjectDocsMixin: @staticmethod def get_field_doc(field): return ("admin/projects", f"project-{field.name}") class SpamCheckMixin: def spam_check(self, value): if is_spam(value, self.request): raise ValidationError(_("This field has been identified as spam!")) class ComponentAntispamMixin(SpamCheckMixin): def clean_agreement(self): value = self.cleaned_data["agreement"] self.spam_check(value) return value class ProjectAntispamMixin(SpamCheckMixin): def clean_web(self): value = self.cleaned_data["web"] self.spam_check(value) return value def clean_instructions(self): value = self.cleaned_data["instructions"] self.spam_check(value) return value class ComponentSettingsForm( SettingsBaseForm, ComponentDocsMixin, ComponentAntispamMixin ): """Component settings form.""" class Meta: model = Component fields = ( "name", "report_source_bugs", "license", "agreement", "allow_translation_propagation", "enable_suggestions", "suggestion_voting", "suggestion_autoaccept", "priority", "check_flags", "enforced_checks", "commit_message", "add_message", "delete_message", "merge_message", "addon_message", "vcs", "repo", "branch", "push", "push_branch", "repoweb", "push_on_commit", "commit_pending_age", "merge_style", "file_format", "edit_template", "new_lang", "language_code_style", "source_language", "new_base", "filemask", "template", "intermediate", "language_regex", "variant_regex", "restricted", "auto_lock_error", "links", "manage_units", "is_glossary", "glossary_color", ) widgets = { "enforced_checks": SelectChecksWidget, "source_language": SortedSelect, } field_classes = {"enforced_checks": SelectChecksField} def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) if self.hide_restricted: self.fields["restricted"].widget = forms.HiddenInput() self.fields["links"].queryset = request.user.managed_projects.exclude( pk=self.instance.pk ) self.helper.layout = Layout( TabHolder( Tab( _("Basic"), Fieldset(_("Name"), "name"), Fieldset(_("License"), "license", "agreement"), Fieldset(_("Upstream links"), "report_source_bugs"), Fieldset( _("Listing and access"), "priority", "restricted", "links", ), Fieldset( _("Glossary"), "is_glossary", "glossary_color", ), css_id="basic", ), Tab( _("Translation"), Fieldset( _("Suggestions"), "enable_suggestions", "suggestion_voting", "suggestion_autoaccept", ), Fieldset( _("Translation settings"), "allow_translation_propagation", "manage_units", "check_flags", "variant_regex", "enforced_checks", ), css_id="translation", ), Tab( _("Version control"), Fieldset( _("Locations"), Div(template="trans/repo_help.html"), "vcs", "repo", "branch", "push", "push_branch", "repoweb", ), Fieldset( _("Version control settings"), "push_on_commit", "commit_pending_age", "merge_style", "auto_lock_error", ), css_id="vcs", ), Tab( _("Commit messages"), Fieldset( _("Commit messages"), ContextDiv( template="trans/messages_help.html", context={"user": request.user}, ), "commit_message", "add_message", "delete_message", "merge_message", "addon_message", ), css_id="messages", ), Tab( _("Files"), Fieldset( _("Translation files"), "file_format", "filemask", "language_regex", "source_language", ), Fieldset( _("Monolingual translations"), "template", "edit_template", "intermediate", ), Fieldset( _("Adding new languages"), "new_base", "new_lang", "language_code_style", ), css_id="files", ), template="layout/pills.html", ) ) vcses = ( "git", "gerrit", "github", "gitlab", "pagure", "local", "git-force-push", ) if self.instance.vcs not in vcses: vcses = (self.instance.vcs,) self.fields["vcs"].choices = [ c for c in self.fields["vcs"].choices if c[0] in vcses ] @property def hide_restricted(self): user = self.request.user if user.is_superuser: return False if settings.OFFER_HOSTING: return True return not any( "component.edit" in permissions for permissions, _langs in user.component_permissions[self.instance.pk] ) def clean(self): data = self.cleaned_data if self.hide_restricted: data["restricted"] = self.instance.restricted class ComponentCreateForm(SettingsBaseForm, ComponentDocsMixin, ComponentAntispamMixin): """Component creation form.""" class Meta: model = Component fields = [ "project", "name", "slug", "vcs", "repo", "branch", "push", "push_branch", "repoweb", "file_format", "filemask", "template", "edit_template", "intermediate", "new_base", "license", "new_lang", "language_code_style", "language_regex", "source_language", "is_glossary", ] widgets = {"source_language": SortedSelect} class ComponentNameForm(forms.Form, ComponentDocsMixin, ComponentAntispamMixin): name = forms.CharField( label=_("Component name"), max_length=COMPONENT_NAME_LENGTH, help_text=_("Display name"), ) slug = forms.SlugField( label=_("URL slug"), max_length=COMPONENT_NAME_LENGTH, help_text=_("Name used in URLs and filenames."), ) is_glossary = forms.BooleanField( label=_("Use as a glossary"), required=False, ) def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.request = request class ComponentSelectForm(ComponentNameForm): component = forms.ModelChoiceField( queryset=Component.objects.none(), label=_("Component"), help_text=_("Select existing component to copy configuration from."), ) def __init__(self, request, *args, **kwargs): if "instance" in kwargs: kwargs.pop("instance") if "auto_id" not in kwargs: kwargs["auto_id"] = "id_existing_%s" super().__init__(request, *args, **kwargs) class ComponentBranchForm(ComponentSelectForm): branch = forms.ChoiceField(label=_("Repository branch")) branch_data: Dict[int, List[str]] = {} instance = None def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_branch_%s" super().__init__(*args, **kwargs) def clean_component(self): component = self.cleaned_data["component"] self.fields["branch"].choices = [(x, x) for x in self.branch_data[component.pk]] return component def clean(self): form_fields = ("branch", "slug", "name") data = self.cleaned_data component = data.get("component") if not component or any(field not in data for field in form_fields): return kwargs = model_to_dict(component, exclude=["id", "links"]) # We need a object, not integer here kwargs["source_language"] = component.source_language kwargs["project"] = component.project for field in form_fields: kwargs[field] = data[field] self.instance = Component(**kwargs) try: self.instance.full_clean() except ValidationError as error: # Can not raise directly as this will contain errors # from fields not present here result = {NON_FIELD_ERRORS: []} for key, value in error.message_dict.items(): if key in self.fields: result[key] = value else: result[NON_FIELD_ERRORS].extend(value) raise ValidationError(error.messages) class ComponentProjectForm(ComponentNameForm): project = forms.ModelChoiceField( queryset=Project.objects.none(), label=_("Project") ) source_language = forms.ModelChoiceField( widget=SortedSelect, label=_("Source language"), help_text=_("Language used for source strings in all components"), queryset=Language.objects.all(), ) def __init__(self, request, *args, **kwargs): if "instance" in kwargs: kwargs.pop("instance") super().__init__(request, *args, **kwargs) # It might be overriden based on preset project self.fields["source_language"].initial = Language.objects.default_language self.request = request self.helper = FormHelper() self.helper.form_tag = False self.instance = None def clean(self): if "project" not in self.cleaned_data: return project = self.cleaned_data["project"] name = self.cleaned_data.get("name") if name and project.component_set.filter(name__iexact=name).exists(): raise ValidationError( {"name": _("Component with the same name already exists.")} ) slug = self.cleaned_data.get("slug") if slug and project.component_set.filter(slug__iexact=slug).exists(): raise ValidationError( {"slug": _("Component with the same name already exists.")} ) class ComponentScratchCreateForm(ComponentProjectForm): file_format = forms.ChoiceField( label=_("File format"), initial="po-mono", choices=FILE_FORMATS.get_choices( cond=lambda x: bool(x.new_translation) or hasattr(x, "update_bilingual") ), ) def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_scratchcreate_%s" super().__init__(*args, **kwargs) class ComponentZipCreateForm(ComponentProjectForm): zipfile = forms.FileField( label=_("ZIP file containing translations"), validators=[FileExtensionValidator(allowed_extensions=["zip"])], widget=forms.FileInput(attrs={"accept": ".zip,application/zip"}), ) field_order = ["zipfile", "project", "name", "slug"] def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_zipcreate_%s" super().__init__(*args, **kwargs) class ComponentDocCreateForm(ComponentProjectForm): docfile = forms.FileField( label=_("Document to translate"), validators=[validate_file_extension], ) field_order = ["docfile", "project", "name", "slug"] def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_doccreate_%s" super().__init__(*args, **kwargs) class ComponentInitCreateForm(CleanRepoMixin, ComponentProjectForm): """Component creation form. This is mostly copy from Component model. Probably should be extracted to standalone Repository model... """ project = forms.ModelChoiceField( queryset=Project.objects.none(), label=_("Project") ) vcs = forms.ChoiceField( label=_("Version control system"), help_text=_( "Version control system to use to access your " "repository with translations." ), choices=VCS_REGISTRY.get_choices(exclude={"local"}), initial=settings.DEFAULT_VCS, ) repo = forms.CharField( label=_("Source code repository"), max_length=REPO_LENGTH, help_text=_( "URL of a repository, use weblate://project/component " "for sharing with other component." ), ) branch = forms.CharField( label=_("Repository branch"), max_length=REPO_LENGTH, help_text=_("Repository branch to translate"), required=False, ) def clean_instance(self, data): params = copy.copy(data) if "discovery" in params: params.pop("discovery") instance = Component(**params) instance.clean_fields(exclude=("filemask", "file_format", "license")) instance.validate_unique() instance.clean_repo() self.instance = instance # Create linked repos automatically repo = instance.suggest_repo_link() if repo: data["repo"] = repo data["branch"] = "" self.clean_instance(data) def clean(self): self.clean_instance(self.cleaned_data) class ComponentDiscoverForm(ComponentInitCreateForm): discovery = forms.ChoiceField( label=_("Choose translation files to import"), choices=[("manual", _("Specify configuration manually"))], required=True, widget=forms.RadioSelect, ) def render_choice(self, value): context = copy.copy(value) try: format_cls = FILE_FORMATS[value["file_format"]] context["file_format_name"] = format_cls.name context["valid"] = True except KeyError: context["file_format_name"] = value["file_format"] context["valid"] = False context["origin"] = value.meta["origin"] return render_to_string("trans/discover-choice.html", context) def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) for field, value in self.fields.items(): if field == "discovery": continue value.widget = forms.HiddenInput() # Allow all VCS now (to handle zip file upload case) self.fields["vcs"].choices = VCS_REGISTRY.get_choices() self.discovered = self.perform_discovery(request, kwargs) for i, value in enumerate(self.discovered): self.fields["discovery"].choices.append((i, self.render_choice(value))) def perform_discovery(self, request, kwargs): if "data" in kwargs and "create_discovery" in request.session: discovered = [] for i, data in enumerate(request.session["create_discovery"]): item = DiscoveryResult(data) item.meta = request.session["create_discovery_meta"][i] discovered.append(item) return discovered try: self.clean_instance(kwargs["initial"]) discovered = self.discover() if not discovered: discovered = self.discover(eager=True) except ValidationError: discovered = [] request.session["create_discovery"] = discovered request.session["create_discovery_meta"] = [x.meta for x in discovered] return discovered def discover(self, eager: bool = False): return discover( self.instance.full_path, source_language=self.instance.source_language.code, eager=eager, ) def clean(self): super().clean() discovery = self.cleaned_data.get("discovery") if discovery and discovery != "manual": self.cleaned_data.update(self.discovered[int(discovery)]) class ComponentRenameForm(SettingsBaseForm, ComponentDocsMixin): """Component rename form.""" class Meta: model = Component fields = ["slug"] class ComponentMoveForm(SettingsBaseForm, ComponentDocsMixin): """Component rename form.""" class Meta: model = Component fields = ["project"] def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) self.fields["project"].queryset = request.user.managed_projects class ProjectSettingsForm(SettingsBaseForm, ProjectDocsMixin, ProjectAntispamMixin): """Project settings form.""" class Meta: model = Project fields = ( "name", "web", "instructions", "set_language_team", "use_shared_tm", "contribute_shared_tm", "enable_hooks", "language_aliases", "access_control", "translation_review", "source_review", ) widgets = { "access_control": forms.RadioSelect, "instructions": MarkdownTextarea, "language_aliases": forms.TextInput, } def clean(self): data = self.cleaned_data if settings.OFFER_HOSTING: data["contribute_shared_tm"] = data["use_shared_tm"] if ( "access_control" not in data or data["access_control"] is None or data["access_control"] == "" ): data["access_control"] = self.instance.access_control access = data["access_control"] self.changed_access = access != self.instance.access_control if self.changed_access and not self.user_can_change_access: raise ValidationError( { "access_control": _( "You do not have permission to change project access control." ) } ) if self.changed_access and access in ( Project.ACCESS_PUBLIC, Project.ACCESS_PROTECTED, ): unlicensed = self.instance.component_set.filter(license="") if unlicensed: raise ValidationError( { "access_control": _( "You must specify a license for these components " "to make them publicly accessible: %s" ) % ", ".join(unlicensed.values_list("name", flat=True)) } ) def save(self, commit: bool = True): super().save(commit=commit) if self.changed_access: Change.objects.create( project=self.instance, action=Change.ACTION_ACCESS_EDIT, user=self.user, details={"access_control": self.instance.access_control}, ) def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) self.user = request.user self.user_can_change_access = request.user.has_perm( "billing:project.permissions", self.instance ) self.changed_access = False self.helper.form_tag = False if not self.user_can_change_access: disabled = {"disabled": True} self.fields["access_control"].required = False self.fields["access_control"].help_text = _( "You do not have permission to change project access control." ) else: disabled = {} self.helper.layout = Layout( TabHolder( Tab( _("Basic"), "name", "web", "instructions", css_id="basic", ), Tab( _("Access"), InlineRadios( "access_control", template="%s/layout/radioselect_access.html", **disabled, ), css_id="access", ), Tab( _("Workflow"), "set_language_team", "use_shared_tm", "contribute_shared_tm", "enable_hooks", "language_aliases", "translation_review", "source_review", css_id="workflow", ), Tab( _("Components"), ContextDiv( template="snippets/project-component-settings.html", context={"object": self.instance, "user": request.user}, ), css_id="components", ), template="layout/pills.html", ) ) if settings.OFFER_HOSTING: self.fields["contribute_shared_tm"].widget = forms.HiddenInput() self.fields["use_shared_tm"].help_text = _( "Uses and contributes to the pool of shared translations " "between projects." ) self.fields["access_control"].choices = [ choice for choice in self.fields["access_control"].choices if choice[0] != Project.ACCESS_CUSTOM ] class ProjectRenameForm(SettingsBaseForm, ProjectDocsMixin): """Project rename form.""" class Meta: model = Project fields = ["slug"] class ProjectCreateForm(SettingsBaseForm, ProjectDocsMixin, ProjectAntispamMixin): """Project creation form.""" # This is fake field with is either hidden or configured # in the view billing = forms.ModelChoiceField( label=_("Billing"), queryset=User.objects.none(), required=True, empty_label=None, ) class Meta: model = Project fields = ("name", "slug", "web", "instructions") class ReplaceForm(forms.Form): q = QueryField( required=False, help_text=_("Optional additional filter on the strings") ) search = forms.CharField( label=_("Search string"), min_length=1, required=True, strip=False, help_text=_("Case sensitive string to search for and replace."), ) replacement = forms.CharField( label=_("Replacement string"), min_length=1, required=True, strip=False ) def __init__(self, *args, **kwargs): kwargs["auto_id"] = "id_replace_%s" super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( SearchField("q"), Field("search"), Field("replacement"), Div(template="snippets/replace-help.html"), ) class ReplaceConfirmForm(forms.Form): units = forms.ModelMultipleChoiceField(queryset=Unit.objects.none(), required=False) confirm = forms.BooleanField(required=True, initial=True, widget=forms.HiddenInput) def __init__(self, units, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["units"].queryset = units class MatrixLanguageForm(forms.Form): """Form for requesting new language.""" lang = forms.MultipleChoiceField( label=_("Languages"), choices=[], widget=forms.SelectMultiple ) def __init__(self, component, *args, **kwargs): super().__init__(*args, **kwargs) languages = Language.objects.filter(translation__component=component).exclude( pk=component.source_language_id ) self.fields["lang"].choices = languages.as_choices() class NewUnitBaseForm(forms.Form): variant = forms.ModelChoiceField( Unit.objects.none(), widget=forms.HiddenInput, required=False, ) def __init__(self, translation, user, *args, **kwargs): super().__init__(*args, **kwargs) self.translation = translation self.fields["variant"].queryset = translation.unit_set.all() self.user = user def clean(self): try: data = self.as_kwargs() except KeyError: # Probably some fields validation has failed return self.translation.validate_new_unit_data(**data) def get_glossary_flags(self): return "" def as_kwargs(self): flags = Flags() flags.merge(self.get_glossary_flags()) variant = self.cleaned_data.get("variant") if variant: flags.set_value("variant", variant.source) return { "context": self.cleaned_data.get("context", ""), "source": self.cleaned_data["source"], "target": self.cleaned_data.get("target"), "extra_flags": flags.format(), "explanation": self.cleaned_data.get("explanation", ""), "auto_context": self.cleaned_data.get("auto_context", False), } class NewMonolingualUnitForm(NewUnitBaseForm): context = forms.CharField( label=_("Translation key"), help_text=_( "Key used to identify string in translation file. " "File format specific rules might apply." ), required=True, ) source = PluralField( label=_("Source language text"), help_text=_( "You can edit this later, as with any other string in " "the source language." ), required=True, ) def __init__(self, translation, user, *args, **kwargs): super().__init__(translation, user, *args, **kwargs) self.fields["context"].widget.attrs["tabindex"] = 99 self.fields["source"].widget.attrs["tabindex"] = 100 self.fields["source"].widget.profile = user.profile self.fields["source"].initial = Unit(translation=translation, id_hash=0) class NewBilingualSourceUnitForm(NewUnitBaseForm): context = forms.CharField( label=_("Context"), help_text=_("Optional context to clarify the source strings."), required=False, ) auto_context = forms.BooleanField( required=False, initial=True, label=_("Automatically adjust context when same string already exists."), ) source = PluralField( label=_("Source string"), required=True, ) def __init__(self, translation, user, *args, **kwargs): super().__init__(translation, user, *args, **kwargs) self.fields["context"].widget.attrs["tabindex"] = 99 self.fields["context"].label = translation.component.context_label self.fields["source"].widget.attrs["tabindex"] = 100 self.fields["source"].widget.profile = user.profile self.fields["source"].initial = Unit( translation=translation.component.source_translation, id_hash=0 ) class NewBilingualUnitForm(NewBilingualSourceUnitForm): target = PluralField( label=_("Translated string"), help_text=_( "You can edit this later, as with any other string in the translation." ), required=True, ) def __init__(self, translation, user, *args, **kwargs): super().__init__(translation, user, *args, **kwargs) self.fields["target"].widget.attrs["tabindex"] = 101 self.fields["target"].widget.profile = user.profile self.fields["target"].initial = Unit(translation=translation, id_hash=0) class NewBilingualGlossarySourceUnitForm(GlossaryAddMixin, NewBilingualSourceUnitForm): def __init__(self, translation, user, *args, **kwargs): if kwargs["initial"] is None: kwargs["initial"] = {} kwargs["initial"]["terminology"] = True super().__init__(translation, user, *args, **kwargs) class NewBilingualGlossaryUnitForm(GlossaryAddMixin, NewBilingualUnitForm): pass def get_new_unit_form(translation, user, data=None, initial=None): if translation.component.has_template(): return NewMonolingualUnitForm(translation, user, data=data, initial=initial) if translation.component.is_glossary: if translation.is_source: return NewBilingualGlossarySourceUnitForm( translation, user, data=data, initial=initial ) return NewBilingualGlossaryUnitForm( translation, user, data=data, initial=initial ) if translation.is_source: return NewBilingualSourceUnitForm(translation, user, data=data, initial=initial) return NewBilingualUnitForm(translation, user, data=data, initial=initial) class CachedQueryIterator(ModelChoiceIterator): """ Choice iterator for cached querysets. It assumes the queryset is reused and avoids using iterator or count queries. """ def __iter__(self): if self.field.empty_label is not None: yield ("", self.field.empty_label) for obj in self.queryset: yield self.choice(obj) def __len__(self): return len(self.queryset) + (1 if self.field.empty_label is not None else 0) def __bool__(self): return self.field.empty_label is not None or bool(self.queryset) class CachedModelMultipleChoiceField(forms.ModelMultipleChoiceField): iterator = CachedQueryIterator def _get_queryset(self): return self._queryset def _set_queryset(self, queryset): self._queryset = queryset self.widget.choices = self.choices queryset = property(_get_queryset, _set_queryset) class BulkEditForm(forms.Form): q = QueryField(required=True) state = forms.ChoiceField( label=_("State to set"), choices=((-1, _("Do not change")),) + STATE_CHOICES ) add_flags = FlagField(label=_("Translation flags to add"), required=False) remove_flags = FlagField(label=_("Translation flags to remove"), required=False) add_labels = CachedModelMultipleChoiceField( queryset=Label.objects.none(), label=_("Labels to add"), widget=forms.CheckboxSelectMultiple(), required=False, ) remove_labels = CachedModelMultipleChoiceField( queryset=Label.objects.none(), label=_("Labels to remove"), widget=forms.CheckboxSelectMultiple(), required=False, ) def __init__(self, user, obj, *args, **kwargs): project = kwargs.pop("project") kwargs["auto_id"] = "id_bulk_%s" super().__init__(*args, **kwargs) labels = project.label_set.all() if labels: self.fields["remove_labels"].queryset = labels self.fields["add_labels"].queryset = labels excluded = {STATE_EMPTY, STATE_READONLY} if user is not None and not user.has_perm("unit.review", obj): excluded.add(STATE_APPROVED) # Filter offered states self.fields["state"].choices = [ x for x in self.fields["state"].choices if x[0] not in excluded ] self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div(template="snippets/bulk-help.html"), SearchField("q"), Field("state"), Field("add_flags"), Field("remove_flags"), ) if labels: self.helper.layout.append(InlineCheckboxes("add_labels")) self.helper.layout.append(InlineCheckboxes("remove_labels")) class ContributorAgreementForm(forms.Form): confirm = forms.BooleanField( label=_("I accept the contributor agreement"), required=True ) next = forms.CharField(required=False, widget=forms.HiddenInput) class BaseDeleteForm(forms.Form): confirm = forms.CharField(required=True) warning_template = "" def __init__(self, obj, *args, **kwargs): super().__init__(*args, **kwargs) self.obj = obj self.helper = FormHelper(self) self.helper.layout = Layout( ContextDiv( template=self.warning_template, css_class="form-group", context={"object": obj}, ), Field("confirm"), ) self.helper.form_tag = False def clean(self): if self.cleaned_data.get("confirm") != self.obj.full_slug: raise ValidationError( _("The slug does not match the one marked for deletion!") ) class TranslationDeleteForm(BaseDeleteForm): confirm = forms.CharField( label=_("Removal confirmation"), help_text=_("Please type in the full slug of the translation to confirm."), required=True, ) warning_template = "trans/delete-translation.html" class ComponentDeleteForm(BaseDeleteForm): confirm = forms.CharField( label=_("Removal confirmation"), help_text=_("Please type in the full slug of the component to confirm."), required=True, ) warning_template = "trans/delete-component.html" class ProjectDeleteForm(BaseDeleteForm): confirm = forms.CharField( label=_("Removal confirmation"), help_text=_("Please type in the slug of the project to confirm."), required=True, ) warning_template = "trans/delete-project.html" class ProjectLanguageDeleteForm(BaseDeleteForm): confirm = forms.CharField( label=_("Removal confirmation"), help_text=_("Please type in the slug of the project and language to confirm."), required=True, ) warning_template = "trans/delete-project-language.html" class AnnouncementForm(forms.ModelForm): """Component base form.""" class Meta: model = Announcement fields = ["message", "category", "expiry", "notify"] widgets = { "expiry": WeblateDateInput(), "message": MarkdownTextarea, } class ChangesForm(forms.Form): project = forms.ChoiceField(label=_("Project"), choices=[("", "")], required=False) lang = forms.ChoiceField(label=_("Language"), choices=[("", "")], required=False) action = forms.MultipleChoiceField( label=_("Action"), required=False, widget=SortedSelectMultiple, choices=Change.ACTION_CHOICES, ) user = UsernameField(label=_("Author username"), required=False, help_text=None) start_date = WeblateDateField( label=_("Starting date"), required=False, datepicker=False ) end_date = WeblateDateField( label=_("Ending date"), required=False, datepicker=False ) def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["lang"].choices += Language.objects.have_translation().as_choices() self.fields["project"].choices += [ (project.slug, project.name) for project in request.user.allowed_projects ] class LabelForm(forms.ModelForm): class Meta: model = Label fields = ("name", "color") widgets = {"color": ColorWidget()} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False class ProjectTokenDeleteForm(forms.Form): token = forms.ModelChoiceField( ProjectToken.objects.none(), widget=forms.HiddenInput, required=True, ) def __init__(self, project, *args, **kwargs): self.project = project super().__init__(*args, **kwargs) self.fields["token"].queryset = project.projecttoken_set.all() class ProjectTokenCreateForm(forms.ModelForm): class Meta: model = ProjectToken fields = ["name", "expires", "project"] widgets = { "expires": WeblateDateInput(), "project": forms.HiddenInput, } def __init__(self, project, *args, **kwargs): self.project = project kwargs["initial"] = {"project": project} super().__init__(*args, **kwargs) def clean_project(self): if self.project != self.cleaned_data["project"]: raise ValidationError("Invalid project!") return self.cleaned_data["project"] def clean_expires(self): expires = self.cleaned_data["expires"] expires = expires.replace(hour=23, minute=59, second=59, microsecond=999999) if expires < timezone.now(): raise forms.ValidationError(gettext("Expiry cannot be in the past!")) return expires class ProjectGroupDeleteForm(forms.Form): group = forms.ModelChoiceField( Group.objects.none(), widget=forms.HiddenInput, required=True, ) def __init__(self, project, *args, **kwargs): self.project = project super().__init__(*args, **kwargs) self.fields["group"].queryset = project.defined_groups.all() class ProjectUserGroupForm(UserManageForm): groups = forms.ModelMultipleChoiceField( Group.objects.none(), widget=forms.CheckboxSelectMultiple, label=_("Teams"), required=False, ) def __init__(self, project, *args, **kwargs): self.project = project super().__init__(*args, **kwargs) self.fields["user"].widget = forms.HiddenInput() self.fields["groups"].queryset = project.defined_groups.all()
xss
{ "code": [ " label = str(unit.translation.language)" ], "line_no": [ 321 ] }
{ "code": [ "from django.utils.html import escape", " label = escape(unit.translation.language)" ], "line_no": [ 40, 322 ] }
import copy import json import re from datetime import date, datetime, timedelta from typing import Dict, List from crispy_forms.bootstrap import InlineCheckboxes, InlineRadios, Tab, TabHolder from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Field, Fieldset, Layout from django import .forms from django.conf import settings from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError from django.core.validators import FileExtensionValidator from django.db.models import Q from django.forms import .model_to_dict from django.forms.models import ModelChoiceIterator from django.forms.utils import from_current_timezone from django.template.loader import .render_to_string from django.urls import reverse from django.utils import timezone from django.utils.http import .urlencode from django.utils.safestring import mark_safe from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from translation_finder import DiscoveryResult, FUNC_33 from weblate.auth.models import Group, User from weblate.checks.flags import Flags from weblate.checks.models import CHECKS from weblate.checks.utils import highlight_string from weblate.formats.models import EXPORTERS, FILE_FORMATS from weblate.glossary.forms import GlossaryAddMixin from weblate.lang.data import BASIC_LANGUAGES from weblate.lang.models import Language from weblate.machinery import MACHINE_TRANSLATION_SERVICES from weblate.trans.defines import COMPONENT_NAME_LENGTH, REPO_LENGTH from weblate.trans.filter import FILTERS, get_filter_choice from weblate.trans.models import ( Announcement, Change, Component, Label, Project, ProjectToken, Unit, ) from weblate.trans.specialchars import RTL_CHARS_DATA, get_special_chars from weblate.trans.util import check_upload_method_permissions, is_repo_link from weblate.trans.validators import validate_check_flags from weblate.utils.antispam import is_spam from weblate.utils.errors import .report_error from weblate.utils.forms import ( ColorWidget, ContextDiv, EmailField, SearchField, SortedSelect, SortedSelectMultiple, UsernameField, ) from weblate.utils.hash import .checksum_to_hash, hash_to_checksum from weblate.utils.search import parse_query from weblate.utils.state import ( STATE_APPROVED, STATE_CHOICES, STATE_EMPTY, STATE_FUZZY, STATE_READONLY, STATE_TRANSLATED, ) from weblate.utils.validators import validate_file_extension from weblate.vcs.models import VCS_REGISTRY VAR_0 = """ <button class="btn btn-default {0}" title="{1}" {2}>{3}</button> """ VAR_1 = """ <VAR_134 class="btn btn-default {0}" title="{1}"> <input type="radio" VAR_20="{2}" VAR_13="{3}" {4}/> {5} </VAR_134> """ VAR_2 = """ <div class="btn-VAR_100 btn-VAR_100-xs" {0}>{1}</div> """ VAR_3 = """ <div class="btn-toolbar pull-right flip editor-toolbar">{0}</div> """ class CLASS_0(forms.Textarea): def __init__(self, **VAR_7): VAR_7["attrs"] = { "dir": "auto", "class": "markdown-editor highlight-editor", "data-mode": "markdown", } super().__init__(**VAR_7) class CLASS_1(forms.DateInput): def __init__(self, VAR_12=True, **VAR_7): VAR_21 = {"type": "date"} if VAR_12: VAR_21["data-provide"] = "datepicker" VAR_21["data-date-format"] = "yyyy-mm-dd" super().__init__(VAR_21=attrs, VAR_36="%Y-%m-%d", **VAR_7) class CLASS_2(forms.DateField): def __init__(self, VAR_12=True, **VAR_7): if "widget" not in VAR_7: VAR_7["widget"] = CLASS_1(VAR_12=datepicker) super().__init__(**VAR_7) def FUNC_3(self, VAR_13): VAR_13 = super().to_python(VAR_13) if isinstance(VAR_13, date): return from_current_timezone( datetime(VAR_13.year, VAR_13.month, VAR_13.day, 0, 0, 0) ) return VAR_13 class CLASS_3(forms.CharField): def __init__(self, *VAR_6, **VAR_7): VAR_7["widget"] = forms.HiddenInput super().__init__(*VAR_6, **VAR_7) def FUNC_4(self, VAR_13): super().clean(VAR_13) if not VAR_13: return None try: return checksum_to_hash(VAR_13) except ValueError: raise ValidationError(_("Invalid VAR_26 specified!")) class CLASS_4(forms.CharField): def FUNC_4(self, VAR_13): if not VAR_13: return None try: return User.objects.get(Q(username=VAR_13) | Q(email=VAR_13)) except User.DoesNotExist: raise ValidationError(_("Could not find any such VAR_4.")) except User.MultipleObjectsReturned: raise ValidationError(_("More possible users were found.")) class CLASS_5(forms.CharField): def __init__(self, **VAR_7): if "label" not in VAR_7: VAR_7["label"] = _("Query") if "required" not in VAR_7: VAR_7["required"] = False super().__init__(**VAR_7) def FUNC_4(self, VAR_13): if not VAR_13: if self.required: raise ValidationError(_("Missing query string.")) return "" try: parse_query(VAR_13) return VAR_13 except Exception as error: report_error() raise ValidationError(_("Could not parse query string: {}").format(error)) class CLASS_6(forms.CharField): VAR_14 = [validate_check_flags] class CLASS_7(forms.Textarea): def __init__(self, *VAR_6, **VAR_7): self.profile = None super().__init__(*VAR_6, **VAR_7) def FUNC_5(self, VAR_15): VAR_101 = [] chars = [] for VAR_20, char, VAR_13 in RTL_CHARS_DATA: VAR_102.append( VAR_0.format( "specialchar", VAR_20, 'data-VAR_13="{}"'.format( VAR_13.encode("ascii", "xmlcharrefreplace").decode("ascii") ), char, ) ) VAR_101.append(VAR_2.format("", "\n".join(VAR_102))) return VAR_3.format("\n".join(VAR_101)) def FUNC_6(self, VAR_16, VAR_15): if VAR_16.direction != "rtl": return "" VAR_103 = f"rtl-{VAR_15}" VAR_104 = [ VAR_1.format( "direction-toggle active", gettext("Toggle text direction"), VAR_103, "rtl", 'checked="checked"', "RTL", ), VAR_1.format( "direction-toggle", gettext("Toggle text direction"), VAR_103, "ltr", "", "LTR", ), ] VAR_101 = [VAR_2.format('data-toggle="buttons"', "\n".join(VAR_104))] return mark_safe(VAR_3.format("\n".join(VAR_101))) def FUNC_7(self, VAR_16, VAR_15, VAR_17, VAR_18, VAR_19): VAR_105 = self.profile VAR_101 = [] chars = [ VAR_0.format( "specialchar", VAR_20, 'data-VAR_13="{}"'.format( VAR_13.encode("ascii", "xmlcharrefreplace").decode("ascii") ), char, ) for VAR_20, char, VAR_13 in get_special_chars( VAR_16, VAR_105.special_chars, VAR_17.source ) ] VAR_101.append(VAR_2.format("", "\n".join(VAR_102))) VAR_43 = VAR_3.format("\n".join(VAR_101)) if VAR_16.direction == "rtl": VAR_43 = self.get_rtl_toolbar(VAR_15) + VAR_43 return mark_safe(VAR_43) def FUNC_8(self, VAR_20, VAR_13, VAR_21=None, VAR_22=None, **VAR_7): VAR_17 = VAR_13 VAR_106 = VAR_17.get_target_plurals() VAR_59 = VAR_17.translation.language VAR_107 = VAR_17.translation.plural VAR_108 = self.attrs["tabindex"] VAR_109 = [hl[2] for hl in highlight_string(VAR_17.source_string, VAR_17)] VAR_21["class"] = "translation-editor VAR_114-control highlight-editor" VAR_21["tabindex"] = VAR_108 VAR_21["lang"] = VAR_59.code VAR_21["dir"] = VAR_59.direction VAR_21["rows"] = 3 VAR_21["data-max"] = VAR_17.get_max_length() VAR_21["data-mode"] = VAR_17.edit_mode VAR_21["data-placeables"] = "|".join(re.escape(pl) for pl in VAR_109 if pl) if VAR_17.readonly: VAR_21["readonly"] = 1 VAR_110 = [] VAR_111 = VAR_17.get_source_plurals() VAR_112 = f"id_{VAR_17.checksum}" for VAR_18, val in enumerate(VAR_106): VAR_15 = f"{VAR_20}_{VAR_18}" VAR_132 = f"{VAR_112}_{VAR_18}" VAR_21["id"] = VAR_132 VAR_21["tabindex"] = VAR_108 + VAR_18 if VAR_18 and len(VAR_111) > 1: VAR_19 = VAR_111[1] else: VAR_19 = VAR_111[0] VAR_133 = super().render(VAR_15, val, VAR_21, VAR_22, **VAR_7) VAR_134 = str(VAR_17.translation.language) if len(VAR_106) != 1: VAR_134 = f"{VAR_134}, {VAR_107.get_plural_label(VAR_18)}" VAR_110.append( render_to_string( "snippets/editor.html", { "toolbar": self.get_toolbar(VAR_59, VAR_132, VAR_17, VAR_18, VAR_19), "fieldid": VAR_132, "label": mark_safe(VAR_134), "textarea": VAR_133, "max_length": VAR_21["data-max"], "length": len(val), "source_length": len(VAR_19), "rtl_toggle": self.get_rtl_toggle(VAR_59, VAR_132), }, ) ) if len(VAR_106) > 1: VAR_110.append( render_to_string( "snippets/VAR_107-formula.html", {"plural": VAR_107, "user": self.profile.user}, ) ) return mark_safe("".join(VAR_110)) def FUNC_9(self, VAR_10, VAR_23, VAR_20): VAR_110 = [] for VAR_18 in range(0, 10): VAR_15 = f"{VAR_20}_{VAR_18:d}" if VAR_15 not in VAR_10: break VAR_110.append(VAR_10.get(VAR_15, "")) return [r.replace("\r", "") for r in VAR_110] class CLASS_8(forms.CharField): def __init__(self, VAR_24=None, VAR_25=None, **VAR_7): VAR_7["label"] = "" super().__init__(widget=CLASS_7, **VAR_7) def FUNC_3(self, VAR_13): return VAR_13 def FUNC_4(self, VAR_13): VAR_13 = super().clean(VAR_13) if not VAR_13 or (self.required and not any(VAR_13)): raise ValidationError(_("Missing translated string!")) return VAR_13 class CLASS_9(forms.ChoiceField): def __init__(self, *VAR_6, **VAR_7): VAR_7["label"] = _("Search filter") if "required" not in VAR_7: VAR_7["required"] = False VAR_7["choices"] = get_filter_choice() VAR_7["error_messages"] = { "invalid_choice": _("Please choose a valid filter type.") } super().__init__(*VAR_6, **VAR_7) def FUNC_3(self, VAR_13): if VAR_13 == "untranslated": return "todo" return super().to_python(VAR_13) class CLASS_10(forms.Form): VAR_26 = CLASS_3(VAR_113=True) def __init__(self, VAR_27, *VAR_6, **VAR_7): self.unit_set = VAR_27 super().__init__(*VAR_6, **VAR_7) def FUNC_10(self): if "checksum" not in self.cleaned_data: return VAR_27 = self.unit_set try: self.cleaned_data["unit"] = VAR_27.filter( id_hash=self.cleaned_data["checksum"] )[0] except (Unit.DoesNotExist, IndexError): raise ValidationError( _("The string you wanted to translate is no longer available.") ) class CLASS_11(forms.Form): def __init__(self, VAR_17: Unit, *VAR_6, **VAR_7): self.unit = VAR_17 super().__init__(*VAR_6, **VAR_7) class CLASS_12(forms.BooleanField): VAR_28 = True def __init__(self, *VAR_6, **VAR_7): VAR_7["label"] = _("Needs editing") VAR_7["help_text"] = _( 'Strings are usually marked as "Needs editing" after the VAR_19 ' "string is updated, or when marked as such manually." ) super().__init__(*VAR_6, **VAR_7) self.widget.attrs["class"] = "fuzzy_checkbox" class CLASS_13(CLASS_11): VAR_29 = CLASS_3(VAR_113=True) VAR_30 = CLASS_3(VAR_113=True) VAR_31 = CLASS_8(VAR_113=False) VAR_32 = CLASS_12(VAR_113=False) VAR_33 = forms.ChoiceField( VAR_134=_("Review state"), VAR_68=[ (STATE_FUZZY, _("Needs editing")), (STATE_TRANSLATED, _("Waiting for review")), (STATE_APPROVED, _("Approved")), ], VAR_113=False, widget=forms.RadioSelect, ) VAR_34 = forms.CharField( widget=CLASS_0, VAR_134=_("Explanation"), help_text=_( "Additional VAR_34 to clarify meaning or usage of the string." ), VAR_24=1000, VAR_113=False, ) def __init__(self, VAR_4, VAR_17: Unit, *VAR_6, **VAR_7): if VAR_17 is not None: VAR_7["initial"] = { "checksum": VAR_17.checksum, "contentsum": hash_to_checksum(VAR_17.content_hash), "translationsum": hash_to_checksum(VAR_17.get_target_hash()), "target": VAR_17, "fuzzy": VAR_17.fuzzy, "review": VAR_17.state, "explanation": VAR_17.explanation, } VAR_7["auto_id"] = f"id_{VAR_17.checksum}_%s" VAR_108 = VAR_7.pop("tabindex", 100) super().__init__(VAR_17, *VAR_6, **VAR_7) if VAR_17.readonly: for VAR_39 in ["target", "fuzzy", "review"]: self.fields[VAR_39].widget.attrs["readonly"] = 1 self.fields["review"].choices = [ (STATE_READONLY, _("Read only")), ] self.user = VAR_4 self.fields["target"].widget.attrs["tabindex"] = VAR_108 self.fields["target"].widget.profile = VAR_4.profile self.fields["review"].widget.attrs["class"] = "review_radio" if VAR_6: self.fields["review"].choices.append((STATE_EMPTY, "")) self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_tag = False self.helper.disable_csrf = True self.helper.layout = Layout( Field("target"), Field("fuzzy"), Field("contentsum"), Field("translationsum"), InlineRadios("review"), Field("explanation"), ) if VAR_17 and VAR_4.has_perm("unit.review", VAR_17.translation): self.fields["fuzzy"].widget = forms.HiddenInput() else: self.fields["review"].widget = forms.HiddenInput() if not VAR_17.translation.component.is_glossary: self.fields["explanation"].widget = forms.HiddenInput() def FUNC_4(self): super().clean() VAR_113 = {"target", "contentsum", "translationsum"} if not VAR_113.issubset(self.cleaned_data): return VAR_17 = self.unit if self.cleaned_data["contentsum"] != VAR_17.content_hash: raise ValidationError( _( "Source string has been changed meanwhile. " "Please check your changes." ) ) if self.cleaned_data["translationsum"] != VAR_17.get_target_hash(): raise ValidationError( _( "Translation of the string has been changed meanwhile. " "Please check your changes." ) ) VAR_24 = VAR_17.get_max_length() for text in self.cleaned_data["target"]: if len(text) > VAR_24: raise ValidationError(_("Translation text too long!")) if self.user.has_perm( "unit.review", VAR_17.translation ) and self.cleaned_data.get("review"): self.cleaned_data["state"] = int(self.cleaned_data["review"]) elif self.cleaned_data["fuzzy"]: self.cleaned_data["state"] = STATE_FUZZY else: self.cleaned_data["state"] = STATE_TRANSLATED class CLASS_14(CLASS_13): VAR_26 = CLASS_3(VAR_113=True) def __init__(self, VAR_4, VAR_17, *VAR_6, **VAR_7): super().__init__(VAR_4, VAR_17, *VAR_6, **VAR_7) self.helper.form_action = reverse( "save_zen", VAR_7=VAR_17.translation.get_reverse_url_kwargs() ) self.helper.form_tag = True self.helper.disable_csrf = False self.helper.layout.append(Field("checksum")) class CLASS_15(forms.Form): VAR_35 = CLASS_5() VAR_36 = forms.ChoiceField( VAR_134=_("File format"), VAR_68=[(x.name, x.verbose) for x in EXPORTERS.values()], VAR_11="po", VAR_113=True, widget=forms.RadioSelect, ) def __init__(self, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( SearchField("q"), InlineRadios("format"), ) class CLASS_16(forms.Form): VAR_37 = forms.FileField(VAR_134=_("File"), validators=[validate_file_extension]) VAR_38 = forms.ChoiceField( VAR_134=_("File upload mode"), VAR_68=( ("translate", _("Add as translation")), ("approve", _("Add as approved translation")), ("suggest", _("Add as suggestion")), ("fuzzy", _("Add as VAR_5 needing edit")), ("replace", _("Replace existing VAR_5 file")), ("source", _("Update VAR_19 strings")), ("add", _("Add new strings")), ), widget=forms.RadioSelect, VAR_113=True, ) VAR_32 = forms.ChoiceField( VAR_134=_("Processing of strings needing edit"), VAR_68=( ("", _("Do not import")), ("process", _("Import as string needing edit")), ("approve", _("Import as translated")), ), VAR_113=False, ) def __init__(self, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False @staticmethod def FUNC_11(VAR_39): return ("user/files", f"upload-{VAR_39.name}") def FUNC_12(self, VAR_13): VAR_68 = self.fields["method"].choices self.fields["method"].choices = [ choice for choice in VAR_68 if choice[0] != VAR_13 ] class CLASS_17(CLASS_16): VAR_40 = forms.ChoiceField( VAR_134=_("Conflict handling"), help_text=_( "Whether to overwrite existing translations if the string is " "already translated." ), VAR_68=( ("", _("Update only untranslated strings")), ("replace-translated", _("Update translated strings")), ("replace-approved", _("Update translated and approved strings")), ), VAR_113=False, VAR_11="replace-translated", ) class CLASS_18(CLASS_17): VAR_41 = forms.CharField(VAR_134=_("Author name")) VAR_42 = EmailField(VAR_134=_("Author e-mail")) def FUNC_0(VAR_4, VAR_5, *VAR_6, **VAR_7): if VAR_4.has_perm("upload.authorship", VAR_5): VAR_114 = CLASS_18 VAR_7["initial"] = {"author_name": VAR_4.full_name, "author_email": VAR_4.email} elif VAR_4.has_perm("upload.overwrite", VAR_5): VAR_114 = CLASS_17 else: VAR_114 = CLASS_16 VAR_43 = VAR_114(*VAR_6, **VAR_7) for VAR_38 in [x[0] for x in VAR_43.fields["method"].choices]: if not check_upload_method_permissions(VAR_4, VAR_5, VAR_38): VAR_43.remove_translation_choice(VAR_38) if not VAR_4.has_perm("unit.review", VAR_5) and not VAR_114 == CLASS_16: VAR_43.fields["conflicts"].choices = [ choice for choice in VAR_43.fields["conflicts"].choices if choice[0] != "approved" ] return VAR_43 class CLASS_19(forms.Form): VAR_35 = CLASS_5() VAR_44 = forms.CharField(VAR_113=False, widget=forms.HiddenInput) VAR_26 = CLASS_3(VAR_113=False) VAR_45 = forms.IntegerField(min_value=-1, VAR_113=False, widget=forms.HiddenInput) VAR_46 = {} def __init__(self, VAR_4, VAR_16=None, VAR_47=True, **VAR_7): self.user = VAR_4 self.language = VAR_16 super().__init__(**VAR_7) self.helper = FormHelper(self) self.helper.disable_csrf = True self.helper.form_tag = False self.helper.layout = Layout( Div( Field("offset", **self.offset_kwargs), SearchField("q"), Field("sort_by", template="snippets/sort-VAR_39.html"), css_class="btn-toolbar", role="toolbar", ), ContextDiv( template="snippets/query-builder.html", VAR_87={ "user": self.user, "month_ago": timezone.now() - timedelta(days=31), "show_builder": VAR_47, "language": self.language, }, ), Field("checksum"), ) def FUNC_13(self): return FILTERS.get_search_name(self.cleaned_data.get("q", "")) def FUNC_14(self): return self.cleaned_data["q"] def FUNC_15(self): if self.cleaned_data.get("offset") is None: self.cleaned_data["offset"] = 1 return self.cleaned_data["offset"] def VAR_115(self): VAR_115 = [] VAR_116 = {"offset", "checksum"} for param in sorted(self.cleaned_data): VAR_13 = self.cleaned_data[param] if VAR_13 is None or param in VAR_116: continue if isinstance(VAR_13, bool): if VAR_13: VAR_115.append((param, "1")) elif isinstance(VAR_13, int): if VAR_13 > 0: VAR_115.append((param, str(VAR_13))) elif isinstance(VAR_13, datetime): VAR_115.append((param, VAR_13.date().isoformat())) elif isinstance(VAR_13, list): for val in VAR_13: VAR_115.append((param, val)) elif isinstance(VAR_13, User): VAR_115.append((param, VAR_13.username)) else: if VAR_13: VAR_115.append((param, VAR_13)) return VAR_115 def FUNC_17(self): return FUNC_17(self.items()) def FUNC_18(self): VAR_10 = copy.copy(self.data) VAR_10["offset"] = "1" VAR_10["checksum"] = "" self.data = VAR_10 return self class CLASS_20(CLASS_19): VAR_45 = forms.IntegerField(min_value=-1, VAR_113=False) VAR_46 = {"template": "snippets/position-VAR_39.html"} class CLASS_21(CLASS_11): VAR_48 = forms.IntegerField() def FUNC_4(self): super().clean() if "merge" not in self.cleaned_data: return None try: VAR_17 = self.unit VAR_5 = VAR_17.translation VAR_58 = VAR_5.component.project self.cleaned_data["merge_unit"] = VAR_135 = Unit.objects.get( pk=self.cleaned_data["merge"], translation__component__project=VAR_58, translation__language=VAR_5.language, ) if not VAR_5.is_source and VAR_17.source != VAR_135.source: raise ValidationError(_("Could not find merged string.")) except Unit.DoesNotExist: raise ValidationError(_("Could not find merged string.")) return self.cleaned_data class CLASS_22(CLASS_11): VAR_49 = forms.IntegerField() def FUNC_4(self): super().clean() if "revert" not in self.cleaned_data: return None try: self.cleaned_data["revert_change"] = Change.objects.get( pk=self.cleaned_data["revert"], VAR_17=self.unit ) except Change.DoesNotExist: raise ValidationError(_("Could not find reverted change.")) return self.cleaned_data class CLASS_23(forms.Form): VAR_50 = forms.ChoiceField( VAR_134=_("Automatic VAR_5 mode"), VAR_68=[ ("suggest", _("Add as suggestion")), ("translate", _("Add as translation")), ("fuzzy", _("Add as needing edit")), ], VAR_11="suggest", ) VAR_51 = CLASS_9( VAR_113=True, VAR_11="todo", help_text=_( "Please note that translating all strings will " "discard all existing translations." ), ) VAR_52 = forms.ChoiceField( VAR_134=_("Automatic VAR_5 source"), VAR_68=[ ("others", _("Other VAR_5 components")), ("mt", _("Machine translation")), ], VAR_11="others", ) VAR_9 = forms.ChoiceField( VAR_134=_("Components"), VAR_113=False, help_text=_( "Turn on contribution to shared VAR_5 memory for the VAR_58 to " "get VAR_127 to additional components." ), VAR_11="", ) VAR_53 = forms.MultipleChoiceField( VAR_134=_("Machine VAR_5 engines"), VAR_68=[], VAR_113=False ) VAR_54 = forms.IntegerField( VAR_134=_("Score threshold"), VAR_11=80, min_value=1, max_value=100 ) def __init__(self, VAR_55, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.obj = VAR_55 self.components = VAR_55.project.component_set.filter( VAR_72=VAR_55.source_language ) | Component.objects.filter( source_language_id=VAR_55.source_language_id, project__contribute_shared_tm=True, ).exclude( VAR_58=VAR_55.project ) if len(self.components.values_list("id")[:30]) == 30: self.fields["component"] = forms.CharField( VAR_113=False, VAR_134=_("Components"), help_text=_( "Enter VAR_9 to use as VAR_19, " "keep blank to use all components in current VAR_58." ), ) else: VAR_68 = [ (s.id, str(s)) for s in self.components.order_project().prefetch_related("project") ] self.fields["component"].choices = [ ("", _("All components in current project")) ] + VAR_68 self.fields["engines"].choices = [ (VAR_148, mt.name) for VAR_148, mt in MACHINE_TRANSLATION_SERVICES.items() ] if "weblate" in MACHINE_TRANSLATION_SERVICES.keys(): self.fields["engines"].initial = "weblate" VAR_117 = {"all", "nottranslated", "todo", "fuzzy", "check:inconsistent"} self.fields["filter_type"].choices = [ x for x in self.fields["filter_type"].choices if x[0] in VAR_117 ] self.helper = FormHelper(self) self.helper.layout = Layout( Field("mode"), Field("filter_type"), InlineRadios("auto_source", id="select_auto_source"), Div("component", css_id="auto_source_others"), Div("engines", "threshold", css_id="auto_source_mt"), ) def FUNC_19(self): VAR_9 = self.cleaned_data["component"] if not VAR_9: return None if VAR_9.isdigit(): try: VAR_43 = self.components.get(pk=VAR_9) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) else: VAR_136 = VAR_9.count("/") if VAR_136 == 0: try: VAR_43 = self.components.get( VAR_69=VAR_9, VAR_58=self.obj.project ) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) elif VAR_136 == 1: VAR_145, VAR_146 = VAR_9.split("/") try: VAR_43 = self.components.get( VAR_69=VAR_146, project__slug=VAR_145 ) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) else: raise ValidationError(_("Please provide valid VAR_9 VAR_69!")) return VAR_43.pk class CLASS_24(forms.Form): VAR_56 = forms.ChoiceField( VAR_134=_("Scope"), help_text=_( "Is your VAR_57 specific to this " "translation or generic for all of them?" ), VAR_68=( ( "report", _("Report issue with the VAR_19 string"), ), ( "global", _("Source string VAR_57, suggestions for changes to this string"), ), ( "translation", _("Translation VAR_57, discussions with other translators"), ), ), ) VAR_57 = forms.CharField( widget=CLASS_0, VAR_134=_("New comment"), help_text=_("You can use Markdown and mention users by @username."), VAR_24=1000, ) def __init__(self, VAR_58, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) if not VAR_58.source_review: self.fields["scope"].choices = self.fields["scope"].choices[1:] class CLASS_25(forms.Form): VAR_59 = forms.ChoiceField(VAR_113=False, VAR_68=[("", _("All languages"))]) VAR_9 = forms.ChoiceField(VAR_113=False, VAR_68=[("", _("All components"))]) def __init__(self, VAR_4, VAR_58, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.fields["lang"].choices += VAR_58.languages.as_choices() self.fields["component"].choices += ( VAR_58.component_set.filter_access(VAR_4) .order() .values_list("slug", "name") ) class CLASS_26(forms.Form): VAR_59 = forms.MultipleChoiceField( VAR_134=_("Languages"), VAR_68=[], widget=forms.SelectMultiple ) def FUNC_20(self): return Language.objects.exclude( Q(translation__component=self.component) | Q(VAR_9=self.component) ) def __init__(self, VAR_9, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.component = VAR_9 VAR_118 = self.get_lang_objects() self.fields["lang"].choices = VAR_118.as_choices() class CLASS_27(CLASS_26): VAR_59 = forms.ChoiceField(VAR_134=_("Language"), VAR_68=[], widget=forms.Select) def FUNC_20(self): VAR_119 = BASIC_LANGUAGES if settings.BASIC_LANGUAGES is not None: VAR_119 = settings.BASIC_LANGUAGES return super().get_lang_objects().filter(code__in=VAR_119) def __init__(self, VAR_9, *VAR_6, **VAR_7): super().__init__(VAR_9, *VAR_6, **VAR_7) self.fields["lang"].choices = [("", _("Please choose"))] + self.fields[ "lang" ].choices def FUNC_21(self): return [self.cleaned_data["lang"]] def FUNC_1(VAR_8, VAR_9): if not VAR_8.user.has_perm("translation.add", VAR_9): raise PermissionDenied() if VAR_8.user.has_perm("translation.add_more", VAR_9): return CLASS_26 return CLASS_27 class CLASS_28(forms.ModelForm): class CLASS_82: VAR_120 = Unit VAR_121 = ("explanation", "labels", "extra_flags") VAR_122 = { "labels": forms.CheckboxSelectMultiple(), "explanation": CLASS_0, } VAR_60 = { "explanation": ("admin/translating", "additional-explanation"), "labels": ("devel/translations", "labels"), "extra_flags": ("admin/translating", "additional-flags"), } def FUNC_11(self, VAR_39): return self.doc_links[VAR_39.name] def __init__(self, VAR_10=None, VAR_61=None, VAR_4=None, **VAR_7): VAR_7["initial"] = { "labels": Label.objects.filter( Q(VAR_17=VAR_61) | Q(unit__source_unit=VAR_61) ) } super().__init__(VAR_10=data, VAR_61=instance, **VAR_7) VAR_58 = VAR_61.translation.component.project self.fields["labels"].queryset = VAR_58.label_set.all() self.helper = FormHelper(self) self.helper.disable_csrf = True self.helper.form_tag = False self.helper.layout = Layout( Field("explanation"), Field("labels"), ContextDiv( template="snippets/labels_description.html", VAR_87={"project": VAR_58, "user": VAR_4}, ), Field("extra_flags"), ) def FUNC_22(self, VAR_62=True): if VAR_62: self.instance.save(same_content=True) self._save_m2m() return self.instance return super().save(VAR_62) class CLASS_29(forms.Form): VAR_4 = CLASS_4( VAR_134=_("User to add"), help_text=_( "Please type in an existing Weblate account VAR_20 or e-mail address." ), ) class CLASS_30(forms.Form): VAR_4 = CLASS_4( VAR_134=_("User to block"), help_text=_( "Please type in an existing Weblate account VAR_20 or e-mail address." ), ) VAR_63 = forms.ChoiceField( VAR_134=_("Block duration"), VAR_68=( ("", _("Block VAR_4 until I unblock them")), ("1", _("Block VAR_4 for one day")), ("7", _("Block VAR_4 for one week")), ("30", _("Block VAR_4 for one month")), ), VAR_113=False, ) class CLASS_31(forms.Form): VAR_64 = forms.ChoiceField( VAR_134=_("Report format"), help_text=_("Choose VAR_37 VAR_36 for the report"), VAR_68=( ("rst", _("reStructuredText")), ("json", _("JSON")), ("html", _("HTML")), ), ) VAR_65 = forms.ChoiceField( VAR_134=_("Report period"), VAR_68=( ("30days", _("Last 30 days")), ("this-month", _("This month")), ("month", _("Last month")), ("this-year", _("This year")), ("year", _("Last year")), ("", _("As specified")), ), VAR_113=False, ) VAR_66 = CLASS_2( VAR_134=_("Starting date"), VAR_113=False, VAR_12=False ) VAR_67 = CLASS_2( VAR_134=_("Ending date"), VAR_113=False, VAR_12=False ) def __init__(self, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Field("style"), Field("period"), Div( "start_date", "end_date", css_class="input-VAR_100 input-daterange", data_provide="datepicker", data_date_format="yyyy-mm-dd", ), ) def FUNC_4(self): super().clean() if "period" not in self.cleaned_data: return if self.cleaned_data["period"] == "30days": VAR_137 = timezone.now() VAR_138 = VAR_137 - timedelta(days=30) elif self.cleaned_data["period"] == "month": VAR_137 = timezone.now().replace(day=1) - timedelta(days=1) VAR_138 = VAR_137.replace(day=1) elif self.cleaned_data["period"] == "this-month": VAR_137 = timezone.now().replace(day=1) + timedelta(days=31) VAR_137 = VAR_137.replace(day=1) - timedelta(days=1) VAR_138 = VAR_137.replace(day=1) elif self.cleaned_data["period"] == "year": VAR_147 = timezone.now().year - 1 VAR_137 = timezone.make_aware(datetime(VAR_147, 12, 31)) VAR_138 = timezone.make_aware(datetime(VAR_147, 1, 1)) elif self.cleaned_data["period"] == "this-year": VAR_147 = timezone.now().year VAR_137 = timezone.make_aware(datetime(VAR_147, 12, 31)) VAR_138 = timezone.make_aware(datetime(VAR_147, 1, 1)) else: if not self.cleaned_data.get("start_date"): raise ValidationError({"start_date": _("Missing date!")}) if not self.cleaned_data.get("end_date"): raise ValidationError({"end_date": _("Missing date!")}) VAR_138 = self.cleaned_data["start_date"] VAR_137 = self.cleaned_data["end_date"] self.cleaned_data["start_date"] = VAR_138.replace( hour=0, minute=0, second=0, microsecond=0 ) self.cleaned_data["end_date"] = VAR_137.replace( hour=23, minute=59, second=59, microsecond=999999 ) if self.cleaned_data["start_date"] > self.cleaned_data["end_date"]: VAR_139 = _("Starting date has to be before ending date!") raise ValidationError({"start_date": VAR_139, "end_date": VAR_139}) class CLASS_32: def FUNC_23(self): VAR_78 = self.cleaned_data.get("repo") if not VAR_78 or not is_repo_link(VAR_78) or "/" not in VAR_78[10:]: return VAR_78 VAR_58, VAR_9 = VAR_78[10:].split("/", 1) try: VAR_55 = Component.objects.get( slug__iexact=VAR_9, project__slug__iexact=VAR_58 ) except Component.DoesNotExist: return VAR_78 if not self.request.user.has_perm("component.edit", VAR_55): raise ValidationError( _("You do not have permission to VAR_127 this VAR_9!") ) return VAR_78 class CLASS_33(CLASS_32, forms.ModelForm): class CLASS_82: VAR_120 = Component VAR_121 = [] def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.request = VAR_8 self.helper = FormHelper() self.helper.form_tag = False class CLASS_34(SortedSelectMultiple): def __init__(self, VAR_21=None, VAR_68=()): VAR_68 = CHECKS.get_choices() super().__init__(VAR_21=attrs, VAR_68=choices) def FUNC_9(self, VAR_10, VAR_23, VAR_20): VAR_13 = super().value_from_datadict(VAR_10, VAR_23, VAR_20) if isinstance(VAR_13, str): return json.loads(VAR_13) return VAR_13 def FUNC_24(self, VAR_13): VAR_13 = super().format_value(VAR_13) if isinstance(VAR_13, str): return VAR_13 return json.dumps(VAR_13) class CLASS_35(forms.CharField): def FUNC_3(self, VAR_13): return VAR_13 class CLASS_36: @staticmethod def FUNC_11(VAR_39): return ("admin/projects", f"component-{VAR_39.name}") class CLASS_37: @staticmethod def FUNC_11(VAR_39): return ("admin/projects", f"project-{VAR_39.name}") class CLASS_38: def FUNC_25(self, VAR_13): if is_spam(VAR_13, self.request): raise ValidationError(_("This VAR_39 has been identified as spam!")) class CLASS_39(CLASS_38): def FUNC_26(self): VAR_13 = self.cleaned_data["agreement"] self.spam_check(VAR_13) return VAR_13 class CLASS_40(CLASS_38): def FUNC_27(self): VAR_13 = self.cleaned_data["web"] self.spam_check(VAR_13) return VAR_13 def FUNC_28(self): VAR_13 = self.cleaned_data["instructions"] self.spam_check(VAR_13) return VAR_13 class CLASS_41( CLASS_33, CLASS_36, CLASS_39 ): class CLASS_82: VAR_120 = Component VAR_121 = ( "name", "report_source_bugs", "license", "agreement", "allow_translation_propagation", "enable_suggestions", "suggestion_voting", "suggestion_autoaccept", "priority", "check_flags", "enforced_checks", "commit_message", "add_message", "delete_message", "merge_message", "addon_message", "vcs", "repo", "branch", "push", "push_branch", "repoweb", "push_on_commit", "commit_pending_age", "merge_style", "file_format", "edit_template", "new_lang", "language_code_style", "source_language", "new_base", "filemask", "template", "intermediate", "language_regex", "variant_regex", "restricted", "auto_lock_error", "links", "manage_units", "is_glossary", "glossary_color", ) VAR_122 = { "enforced_checks": CLASS_34, "source_language": SortedSelect, } VAR_123 = {"enforced_checks": CLASS_35} def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(VAR_8, *VAR_6, **VAR_7) if self.hide_restricted: self.fields["restricted"].widget = forms.HiddenInput() self.fields["links"].queryset = VAR_8.user.managed_projects.exclude( pk=self.instance.pk ) self.helper.layout = Layout( TabHolder( Tab( _("Basic"), Fieldset(_("Name"), "name"), Fieldset(_("License"), "license", "agreement"), Fieldset(_("Upstream links"), "report_source_bugs"), Fieldset( _("Listing and access"), "priority", "restricted", "links", ), Fieldset( _("Glossary"), "is_glossary", "glossary_color", ), css_id="basic", ), Tab( _("Translation"), Fieldset( _("Suggestions"), "enable_suggestions", "suggestion_voting", "suggestion_autoaccept", ), Fieldset( _("Translation settings"), "allow_translation_propagation", "manage_units", "check_flags", "variant_regex", "enforced_checks", ), css_id="translation", ), Tab( _("Version control"), Fieldset( _("Locations"), Div(template="trans/repo_help.html"), "vcs", "repo", "branch", "push", "push_branch", "repoweb", ), Fieldset( _("Version control settings"), "push_on_commit", "commit_pending_age", "merge_style", "auto_lock_error", ), css_id="vcs", ), Tab( _("Commit messages"), Fieldset( _("Commit messages"), ContextDiv( template="trans/messages_help.html", VAR_87={"user": VAR_8.user}, ), "commit_message", "add_message", "delete_message", "merge_message", "addon_message", ), css_id="messages", ), Tab( _("Files"), Fieldset( _("Translation files"), "file_format", "filemask", "language_regex", "source_language", ), Fieldset( _("Monolingual translations"), "template", "edit_template", "intermediate", ), Fieldset( _("Adding new languages"), "new_base", "new_lang", "language_code_style", ), css_id="files", ), template="layout/pills.html", ) ) VAR_124 = ( "git", "gerrit", "github", "gitlab", "pagure", "local", "git-force-push", ) if self.instance.vcs not in VAR_124: vcses = (self.instance.vcs,) self.fields["vcs"].choices = [ c for c in self.fields["vcs"].choices if c[0] in VAR_124 ] @property def FUNC_29(self): VAR_4 = self.request.user if VAR_4.is_superuser: return False if settings.OFFER_HOSTING: return True return not any( "component.edit" in permissions for permissions, _langs in VAR_4.component_permissions[self.instance.pk] ) def FUNC_4(self): VAR_10 = self.cleaned_data if self.hide_restricted: VAR_10["restricted"] = self.instance.restricted class CLASS_42(CLASS_33, CLASS_36, CLASS_39): class CLASS_82: VAR_120 = Component VAR_121 = [ "project", "name", "slug", "vcs", "repo", "branch", "push", "push_branch", "repoweb", "file_format", "filemask", "template", "edit_template", "intermediate", "new_base", "license", "new_lang", "language_code_style", "language_regex", "source_language", "is_glossary", ] VAR_122 = {"source_language": SortedSelect} class CLASS_43(forms.Form, CLASS_36, CLASS_39): VAR_20 = forms.CharField( VAR_134=_("Component name"), VAR_24=COMPONENT_NAME_LENGTH, help_text=_("Display name"), ) VAR_69 = forms.SlugField( VAR_134=_("URL slug"), VAR_24=COMPONENT_NAME_LENGTH, help_text=_("Name used in URLs and filenames."), ) VAR_70 = forms.BooleanField( VAR_134=_("Use as a glossary"), VAR_113=False, ) def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper() self.helper.form_tag = False self.request = VAR_8 class CLASS_44(CLASS_43): VAR_9 = forms.ModelChoiceField( VAR_90=Component.objects.none(), VAR_134=_("Component"), help_text=_("Select existing VAR_9 to copy configuration from."), ) def __init__(self, VAR_8, *VAR_6, **VAR_7): if "instance" in VAR_7: kwargs.pop("instance") if "auto_id" not in VAR_7: VAR_7["auto_id"] = "id_existing_%s" super().__init__(VAR_8, *VAR_6, **VAR_7) class CLASS_45(CLASS_44): VAR_71 = forms.ChoiceField(VAR_134=_("Repository branch")) branch_data: Dict[int, List[str]] = {} VAR_61 = None def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_branch_%s" super().__init__(*VAR_6, **VAR_7) def FUNC_19(self): VAR_9 = self.cleaned_data["component"] self.fields["branch"].choices = [(x, x) for x in self.branch_data[VAR_9.pk]] return VAR_9 def FUNC_4(self): VAR_125 = ("branch", "slug", "name") VAR_10 = self.cleaned_data VAR_9 = VAR_10.get("component") if not VAR_9 or any(VAR_39 not in VAR_10 for VAR_39 in VAR_125): return VAR_7 = model_to_dict(VAR_9, exclude=["id", "links"]) VAR_7["source_language"] = VAR_9.source_language VAR_7["project"] = VAR_9.project for VAR_39 in VAR_125: VAR_7[VAR_39] = VAR_10[VAR_39] self.instance = Component(**VAR_7) try: self.instance.full_clean() except ValidationError as error: VAR_43 = {NON_FIELD_ERRORS: []} for VAR_148, VAR_13 in error.message_dict.items(): if VAR_148 in self.fields: VAR_43[VAR_148] = VAR_13 else: VAR_43[NON_FIELD_ERRORS].extend(VAR_13) raise ValidationError(error.messages) class CLASS_46(CLASS_43): VAR_58 = forms.ModelChoiceField( VAR_90=Project.objects.none(), VAR_134=_("Project") ) VAR_72 = forms.ModelChoiceField( widget=SortedSelect, VAR_134=_("Source language"), help_text=_("Language used for VAR_19 strings in all components"), VAR_90=Language.objects.all(), ) def __init__(self, VAR_8, *VAR_6, **VAR_7): if "instance" in VAR_7: kwargs.pop("instance") super().__init__(VAR_8, *VAR_6, **VAR_7) self.fields["source_language"].initial = Language.objects.default_language self.request = VAR_8 self.helper = FormHelper() self.helper.form_tag = False self.instance = None def FUNC_4(self): if "project" not in self.cleaned_data: return VAR_58 = self.cleaned_data["project"] VAR_20 = self.cleaned_data.get("name") if VAR_20 and VAR_58.component_set.filter(name__iexact=VAR_20).exists(): raise ValidationError( {"name": _("Component with the same VAR_20 already exists.")} ) VAR_69 = self.cleaned_data.get("slug") if VAR_69 and VAR_58.component_set.filter(slug__iexact=VAR_69).exists(): raise ValidationError( {"slug": _("Component with the same VAR_20 already exists.")} ) class CLASS_47(CLASS_46): VAR_73 = forms.ChoiceField( VAR_134=_("File format"), VAR_11="po-mono", VAR_68=FILE_FORMATS.get_choices( cond=lambda x: bool(x.new_translation) or hasattr(x, "update_bilingual") ), ) def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_scratchcreate_%s" super().__init__(*VAR_6, **VAR_7) class CLASS_48(CLASS_46): VAR_74 = forms.FileField( VAR_134=_("ZIP VAR_37 containing translations"), validators=[FileExtensionValidator(allowed_extensions=["zip"])], widget=forms.FileInput(VAR_21={"accept": ".zip,application/zip"}), ) VAR_75 = ["zipfile", "project", "name", "slug"] def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_zipcreate_%s" super().__init__(*VAR_6, **VAR_7) class CLASS_49(CLASS_46): VAR_76 = forms.FileField( VAR_134=_("Document to translate"), validators=[validate_file_extension], ) VAR_75 = ["docfile", "project", "name", "slug"] def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_doccreate_%s" super().__init__(*VAR_6, **VAR_7) class CLASS_50(CLASS_32, CLASS_46): VAR_58 = forms.ModelChoiceField( VAR_90=Project.objects.none(), VAR_134=_("Project") ) VAR_77 = forms.ChoiceField( VAR_134=_("Version control system"), help_text=_( "Version control system to use to VAR_127 your " "repository with translations." ), VAR_68=VCS_REGISTRY.get_choices(exclude={"local"}), VAR_11=settings.DEFAULT_VCS, ) VAR_78 = forms.CharField( VAR_134=_("Source code repository"), VAR_24=REPO_LENGTH, help_text=_( "URL of a repository, use weblate://VAR_58/VAR_9 " "for sharing with other VAR_9." ), ) VAR_71 = forms.CharField( VAR_134=_("Repository branch"), VAR_24=REPO_LENGTH, help_text=_("Repository VAR_71 to translate"), VAR_113=False, ) def FUNC_30(self, VAR_10): VAR_126 = copy.copy(VAR_10) if "discovery" in VAR_126: params.pop("discovery") VAR_61 = Component(**VAR_126) VAR_61.clean_fields(exclude=("filemask", "file_format", "license")) VAR_61.validate_unique() VAR_61.clean_repo() self.instance = VAR_61 VAR_78 = VAR_61.suggest_repo_link() if VAR_78: VAR_10["repo"] = VAR_78 VAR_10["branch"] = "" self.clean_instance(VAR_10) def FUNC_4(self): self.clean_instance(self.cleaned_data) class CLASS_51(CLASS_50): VAR_79 = forms.ChoiceField( VAR_134=_("Choose VAR_5 VAR_23 to import"), VAR_68=[("manual", _("Specify configuration manually"))], VAR_113=True, widget=forms.RadioSelect, ) def FUNC_31(self, VAR_13): VAR_87 = copy.copy(VAR_13) try: VAR_140 = FILE_FORMATS[VAR_13["file_format"]] VAR_87["file_format_name"] = VAR_140.name VAR_87["valid"] = True except KeyError: VAR_87["file_format_name"] = VAR_13["file_format"] VAR_87["valid"] = False VAR_87["origin"] = VAR_13.meta["origin"] return render_to_string("trans/FUNC_33-choice.html", VAR_87) def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(VAR_8, *VAR_6, **VAR_7) for VAR_39, VAR_13 in self.fields.items(): if VAR_39 == "discovery": continue VAR_13.widget = forms.HiddenInput() self.fields["vcs"].choices = VCS_REGISTRY.get_choices() self.discovered = self.perform_discovery(VAR_8, VAR_7) for i, VAR_13 in enumerate(self.discovered): self.fields["discovery"].choices.append((i, self.render_choice(VAR_13))) def FUNC_32(self, VAR_8, VAR_7): if "data" in VAR_7 and "create_discovery" in VAR_8.session: VAR_141 = [] for i, VAR_10 in enumerate(VAR_8.session["create_discovery"]): VAR_144 = DiscoveryResult(VAR_10) VAR_144.meta = VAR_8.session["create_discovery_meta"][i] VAR_141.append(VAR_144) return VAR_141 try: self.clean_instance(VAR_7["initial"]) VAR_141 = self.discover() if not VAR_141: discovered = self.discover(VAR_80=True) except ValidationError: VAR_141 = [] VAR_8.session["create_discovery"] = VAR_141 VAR_8.session["create_discovery_meta"] = [x.meta for x in VAR_141] return VAR_141 def FUNC_33(self, VAR_80: bool = False): return FUNC_33( self.instance.full_path, VAR_72=self.instance.source_language.code, VAR_80=eager, ) def FUNC_4(self): super().clean() VAR_79 = self.cleaned_data.get("discovery") if VAR_79 and VAR_79 != "manual": self.cleaned_data.update(self.discovered[int(VAR_79)]) class CLASS_52(CLASS_33, CLASS_36): class CLASS_82: VAR_120 = Component VAR_121 = ["slug"] class CLASS_53(CLASS_33, CLASS_36): class CLASS_82: VAR_120 = Component VAR_121 = ["project"] def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(VAR_8, *VAR_6, **VAR_7) self.fields["project"].queryset = VAR_8.user.managed_projects class CLASS_54(CLASS_33, CLASS_37, CLASS_40): class CLASS_82: VAR_120 = Project VAR_121 = ( "name", "web", "instructions", "set_language_team", "use_shared_tm", "contribute_shared_tm", "enable_hooks", "language_aliases", "access_control", "translation_review", "source_review", ) VAR_122 = { "access_control": forms.RadioSelect, "instructions": CLASS_0, "language_aliases": forms.TextInput, } def FUNC_4(self): VAR_10 = self.cleaned_data if settings.OFFER_HOSTING: VAR_10["contribute_shared_tm"] = VAR_10["use_shared_tm"] if ( "access_control" not in VAR_10 or VAR_10["access_control"] is None or VAR_10["access_control"] == "" ): VAR_10["access_control"] = self.instance.access_control VAR_127 = VAR_10["access_control"] self.changed_access = VAR_127 != self.instance.access_control if self.changed_access and not self.user_can_change_access: raise ValidationError( { "access_control": _( "You do not have permission to change VAR_58 VAR_127 control." ) } ) if self.changed_access and VAR_127 in ( Project.ACCESS_PUBLIC, Project.ACCESS_PROTECTED, ): VAR_142 = self.instance.component_set.filter(license="") if VAR_142: raise ValidationError( { "access_control": _( "You must specify a license for these components " "to make them publicly accessible: %s" ) % ", ".join(VAR_142.values_list("name", flat=True)) } ) def FUNC_22(self, VAR_62: bool = True): super().save(VAR_62=commit) if self.changed_access: Change.objects.create( VAR_58=self.instance, VAR_98=Change.ACTION_ACCESS_EDIT, VAR_4=self.user, details={"access_control": self.instance.access_control}, ) def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(VAR_8, *VAR_6, **VAR_7) self.user = VAR_8.user self.user_can_change_access = VAR_8.user.has_perm( "billing:VAR_58.permissions", self.instance ) self.changed_access = False self.helper.form_tag = False if not self.user_can_change_access: VAR_143 = {"disabled": True} self.fields["access_control"].required = False self.fields["access_control"].help_text = _( "You do not have permission to change VAR_58 VAR_127 control." ) else: VAR_143 = {} self.helper.layout = Layout( TabHolder( Tab( _("Basic"), "name", "web", "instructions", css_id="basic", ), Tab( _("Access"), InlineRadios( "access_control", template="%s/layout/radioselect_access.html", **VAR_143, ), css_id="access", ), Tab( _("Workflow"), "set_language_team", "use_shared_tm", "contribute_shared_tm", "enable_hooks", "language_aliases", "translation_review", "source_review", css_id="workflow", ), Tab( _("Components"), ContextDiv( template="snippets/VAR_58-VAR_9-settings.html", VAR_87={"object": self.instance, "user": VAR_8.user}, ), css_id="components", ), template="layout/pills.html", ) ) if settings.OFFER_HOSTING: self.fields["contribute_shared_tm"].widget = forms.HiddenInput() self.fields["use_shared_tm"].help_text = _( "Uses and contributes to the pool of shared translations " "between projects." ) self.fields["access_control"].choices = [ choice for choice in self.fields["access_control"].choices if choice[0] != Project.ACCESS_CUSTOM ] class CLASS_55(CLASS_33, CLASS_37): class CLASS_82: VAR_120 = Project VAR_121 = ["slug"] class CLASS_56(CLASS_33, CLASS_37, CLASS_40): VAR_81 = forms.ModelChoiceField( VAR_134=_("Billing"), VAR_90=User.objects.none(), VAR_113=True, empty_label=None, ) class CLASS_82: VAR_120 = Project VAR_121 = ("name", "slug", "web", "instructions") class CLASS_57(forms.Form): VAR_35 = CLASS_5( VAR_113=False, help_text=_("Optional additional filter on the strings") ) VAR_82 = forms.CharField( VAR_134=_("Search string"), VAR_25=1, VAR_113=True, strip=False, help_text=_("Case sensitive string to VAR_82 for and replace."), ) VAR_83 = forms.CharField( VAR_134=_("Replacement string"), VAR_25=1, VAR_113=True, strip=False ) def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_replace_%s" super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( SearchField("q"), Field("search"), Field("replacement"), Div(template="snippets/replace-help.html"), ) class CLASS_58(forms.Form): VAR_84 = forms.ModelMultipleChoiceField(VAR_90=Unit.objects.none(), VAR_113=False) VAR_85 = forms.BooleanField(VAR_113=True, VAR_11=True, widget=forms.HiddenInput) def __init__(self, VAR_84, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.fields["units"].queryset = VAR_84 class CLASS_59(forms.Form): VAR_59 = forms.MultipleChoiceField( VAR_134=_("Languages"), VAR_68=[], widget=forms.SelectMultiple ) def __init__(self, VAR_9, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) VAR_118 = Language.objects.filter(translation__component=VAR_9).exclude( pk=VAR_9.source_language_id ) self.fields["lang"].choices = VAR_118.as_choices() class CLASS_60(forms.Form): VAR_86 = forms.ModelChoiceField( Unit.objects.none(), widget=forms.HiddenInput, VAR_113=False, ) def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.translation = VAR_5 self.fields["variant"].queryset = VAR_5.unit_set.all() self.user = VAR_4 def FUNC_4(self): try: VAR_10 = self.as_kwargs() except KeyError: return self.translation.validate_new_unit_data(**VAR_10) def FUNC_34(self): return "" def FUNC_35(self): VAR_128 = Flags() VAR_128.merge(self.get_glossary_flags()) VAR_86 = self.cleaned_data.get("variant") if VAR_86: VAR_128.set_value("variant", VAR_86.source) return { "context": self.cleaned_data.get("context", ""), "source": self.cleaned_data["source"], "target": self.cleaned_data.get("target"), "extra_flags": VAR_128.format(), "explanation": self.cleaned_data.get("explanation", ""), "auto_context": self.cleaned_data.get("auto_context", False), } class CLASS_61(CLASS_60): VAR_87 = forms.CharField( VAR_134=_("Translation key"), help_text=_( "Key used to identify string in VAR_5 VAR_37. " "File VAR_36 specific rules might apply." ), VAR_113=True, ) VAR_19 = CLASS_8( VAR_134=_("Source VAR_16 text"), help_text=_( "You can edit this later, as with any other string in " "the VAR_19 VAR_16." ), VAR_113=True, ) def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): super().__init__(VAR_5, VAR_4, *VAR_6, **VAR_7) self.fields["context"].widget.attrs["tabindex"] = 99 self.fields["source"].widget.attrs["tabindex"] = 100 self.fields["source"].widget.profile = VAR_4.profile self.fields["source"].initial = Unit(VAR_5=translation, id_hash=0) class CLASS_62(CLASS_60): VAR_87 = forms.CharField( VAR_134=_("Context"), help_text=_("Optional VAR_87 to clarify the VAR_19 strings."), VAR_113=False, ) VAR_88 = forms.BooleanField( VAR_113=False, VAR_11=True, VAR_134=_("Automatically adjust VAR_87 when same string already exists."), ) VAR_19 = CLASS_8( VAR_134=_("Source string"), VAR_113=True, ) def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): super().__init__(VAR_5, VAR_4, *VAR_6, **VAR_7) self.fields["context"].widget.attrs["tabindex"] = 99 self.fields["context"].label = VAR_5.component.context_label self.fields["source"].widget.attrs["tabindex"] = 100 self.fields["source"].widget.profile = VAR_4.profile self.fields["source"].initial = Unit( VAR_5=VAR_5.component.source_translation, id_hash=0 ) class CLASS_63(CLASS_62): VAR_31 = CLASS_8( VAR_134=_("Translated string"), help_text=_( "You can edit this later, as with any other string in the VAR_5." ), VAR_113=True, ) def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): super().__init__(VAR_5, VAR_4, *VAR_6, **VAR_7) self.fields["target"].widget.attrs["tabindex"] = 101 self.fields["target"].widget.profile = VAR_4.profile self.fields["target"].initial = Unit(VAR_5=translation, id_hash=0) class CLASS_64(GlossaryAddMixin, CLASS_62): def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): if VAR_7["initial"] is None: VAR_7["initial"] = {} VAR_7["initial"]["terminology"] = True super().__init__(VAR_5, VAR_4, *VAR_6, **VAR_7) class CLASS_65(GlossaryAddMixin, CLASS_63): pass def FUNC_2(VAR_5, VAR_4, VAR_10=None, VAR_11=None): if VAR_5.component.has_template(): return CLASS_61(VAR_5, VAR_4, VAR_10=data, VAR_11=initial) if VAR_5.component.is_glossary: if VAR_5.is_source: return CLASS_64( VAR_5, VAR_4, VAR_10=data, VAR_11=initial ) return CLASS_65( VAR_5, VAR_4, VAR_10=data, VAR_11=initial ) if VAR_5.is_source: return CLASS_62(VAR_5, VAR_4, VAR_10=data, VAR_11=initial) return CLASS_63(VAR_5, VAR_4, VAR_10=data, VAR_11=initial) class CLASS_66(ModelChoiceIterator): def __iter__(self): if self.field.empty_label is not None: yield ("", self.field.empty_label) for VAR_55 in self.queryset: yield self.choice(VAR_55) def __len__(self): return len(self.queryset) + (1 if self.field.empty_label is not None else 0) def __bool__(self): return self.field.empty_label is not None or bool(self.queryset) class CLASS_67(forms.ModelMultipleChoiceField): VAR_89 = CLASS_66 def FUNC_36(self): return self._queryset def FUNC_37(self, VAR_90): self._queryset = VAR_90 self.widget.choices = self.choices VAR_90 = property(FUNC_36, FUNC_37) class CLASS_68(forms.Form): VAR_35 = CLASS_5(VAR_113=True) VAR_91 = forms.ChoiceField( VAR_134=_("State to set"), VAR_68=((-1, _("Do not change")),) + STATE_CHOICES ) VAR_92 = CLASS_6(VAR_134=_("Translation VAR_128 to add"), VAR_113=False) VAR_93 = CLASS_6(VAR_134=_("Translation VAR_128 to remove"), VAR_113=False) VAR_94 = CLASS_67( VAR_90=Label.objects.none(), VAR_134=_("Labels to add"), widget=forms.CheckboxSelectMultiple(), VAR_113=False, ) VAR_95 = CLASS_67( VAR_90=Label.objects.none(), VAR_134=_("Labels to remove"), widget=forms.CheckboxSelectMultiple(), VAR_113=False, ) def __init__(self, VAR_4, VAR_55, *VAR_6, **VAR_7): VAR_58 = VAR_7.pop("project") VAR_7["auto_id"] = "id_bulk_%s" super().__init__(*VAR_6, **VAR_7) VAR_129 = VAR_58.label_set.all() if VAR_129: self.fields["remove_labels"].queryset = VAR_129 self.fields["add_labels"].queryset = VAR_129 VAR_130 = {STATE_EMPTY, STATE_READONLY} if VAR_4 is not None and not VAR_4.has_perm("unit.review", VAR_55): VAR_130.add(STATE_APPROVED) self.fields["state"].choices = [ x for x in self.fields["state"].choices if x[0] not in VAR_130 ] self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div(template="snippets/bulk-help.html"), SearchField("q"), Field("state"), Field("add_flags"), Field("remove_flags"), ) if VAR_129: self.helper.layout.append(InlineCheckboxes("add_labels")) self.helper.layout.append(InlineCheckboxes("remove_labels")) class CLASS_69(forms.Form): VAR_85 = forms.BooleanField( VAR_134=_("I accept the contributor agreement"), VAR_113=True ) VAR_96 = forms.CharField(VAR_113=False, widget=forms.HiddenInput) class CLASS_70(forms.Form): VAR_85 = forms.CharField(VAR_113=True) VAR_97 = "" def __init__(self, VAR_55, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.obj = VAR_55 self.helper = FormHelper(self) self.helper.layout = Layout( ContextDiv( template=self.warning_template, css_class="form-group", VAR_87={"object": VAR_55}, ), Field("confirm"), ) self.helper.form_tag = False def FUNC_4(self): if self.cleaned_data.get("confirm") != self.obj.full_slug: raise ValidationError( _("The VAR_69 does not match the one marked for deletion!") ) class CLASS_71(CLASS_70): VAR_85 = forms.CharField( VAR_134=_("Removal confirmation"), help_text=_("Please type in the full VAR_69 of the VAR_5 to VAR_85."), VAR_113=True, ) VAR_97 = "trans/delete-VAR_5.html" class CLASS_72(CLASS_70): VAR_85 = forms.CharField( VAR_134=_("Removal confirmation"), help_text=_("Please type in the full VAR_69 of the VAR_9 to VAR_85."), VAR_113=True, ) VAR_97 = "trans/delete-VAR_9.html" class CLASS_73(CLASS_70): VAR_85 = forms.CharField( VAR_134=_("Removal confirmation"), help_text=_("Please type in the VAR_69 of the VAR_58 to VAR_85."), VAR_113=True, ) VAR_97 = "trans/delete-VAR_58.html" class CLASS_74(CLASS_70): VAR_85 = forms.CharField( VAR_134=_("Removal confirmation"), help_text=_("Please type in the VAR_69 of the VAR_58 and VAR_16 to VAR_85."), VAR_113=True, ) VAR_97 = "trans/delete-VAR_58-VAR_16.html" class CLASS_75(forms.ModelForm): class CLASS_82: VAR_120 = Announcement VAR_121 = ["message", "category", "expiry", "notify"] VAR_122 = { "expiry": CLASS_1(), "message": CLASS_0, } class CLASS_76(forms.Form): VAR_58 = forms.ChoiceField(VAR_134=_("Project"), VAR_68=[("", "")], VAR_113=False) VAR_59 = forms.ChoiceField(VAR_134=_("Language"), VAR_68=[("", "")], VAR_113=False) VAR_98 = forms.MultipleChoiceField( VAR_134=_("Action"), VAR_113=False, widget=SortedSelectMultiple, VAR_68=Change.ACTION_CHOICES, ) VAR_4 = UsernameField(VAR_134=_("Author username"), VAR_113=False, help_text=None) VAR_66 = CLASS_2( VAR_134=_("Starting date"), VAR_113=False, VAR_12=False ) VAR_67 = CLASS_2( VAR_134=_("Ending date"), VAR_113=False, VAR_12=False ) def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.fields["lang"].choices += Language.objects.have_translation().as_choices() self.fields["project"].choices += [ (VAR_58.slug, VAR_58.name) for VAR_58 in VAR_8.user.allowed_projects ] class CLASS_77(forms.ModelForm): class CLASS_82: VAR_120 = Label VAR_121 = ("name", "color") VAR_122 = {"color": ColorWidget()} def __init__(self, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False class CLASS_78(forms.Form): VAR_99 = forms.ModelChoiceField( ProjectToken.objects.none(), widget=forms.HiddenInput, VAR_113=True, ) def __init__(self, VAR_58, *VAR_6, **VAR_7): self.project = VAR_58 super().__init__(*VAR_6, **VAR_7) self.fields["token"].queryset = VAR_58.projecttoken_set.all() class CLASS_79(forms.ModelForm): class CLASS_82: VAR_120 = ProjectToken VAR_121 = ["name", "expires", "project"] VAR_122 = { "expires": CLASS_1(), "project": forms.HiddenInput, } def __init__(self, VAR_58, *VAR_6, **VAR_7): self.project = VAR_58 VAR_7["initial"] = {"project": VAR_58} super().__init__(*VAR_6, **VAR_7) def FUNC_38(self): if self.project != self.cleaned_data["project"]: raise ValidationError("Invalid VAR_58!") return self.cleaned_data["project"] def FUNC_39(self): VAR_131 = self.cleaned_data["expires"] VAR_131 = expires.replace(hour=23, minute=59, second=59, microsecond=999999) if VAR_131 < timezone.now(): raise forms.ValidationError(gettext("Expiry cannot be in the past!")) return VAR_131 class CLASS_80(forms.Form): VAR_100 = forms.ModelChoiceField( Group.objects.none(), widget=forms.HiddenInput, VAR_113=True, ) def __init__(self, VAR_58, *VAR_6, **VAR_7): self.project = VAR_58 super().__init__(*VAR_6, **VAR_7) self.fields["group"].queryset = VAR_58.defined_groups.all() class CLASS_81(CLASS_29): VAR_101 = forms.ModelMultipleChoiceField( Group.objects.none(), widget=forms.CheckboxSelectMultiple, VAR_134=_("Teams"), VAR_113=False, ) def __init__(self, VAR_58, *VAR_6, **VAR_7): self.project = VAR_58 super().__init__(*VAR_6, **VAR_7) self.fields["user"].widget = forms.HiddenInput() self.fields["groups"].queryset = VAR_58.defined_groups.all()
import copy import json import re from datetime import date, datetime, timedelta from typing import Dict, List from crispy_forms.bootstrap import InlineCheckboxes, InlineRadios, Tab, TabHolder from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Field, Fieldset, Layout from django import .forms from django.conf import settings from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError from django.core.validators import FileExtensionValidator from django.db.models import Q from django.forms import .model_to_dict from django.forms.models import ModelChoiceIterator from django.forms.utils import from_current_timezone from django.template.loader import .render_to_string from django.urls import reverse from django.utils import timezone from django.utils.html import escape from django.utils.http import .urlencode from django.utils.safestring import mark_safe from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from translation_finder import DiscoveryResult, FUNC_33 from weblate.auth.models import Group, User from weblate.checks.flags import Flags from weblate.checks.models import CHECKS from weblate.checks.utils import highlight_string from weblate.formats.models import EXPORTERS, FILE_FORMATS from weblate.glossary.forms import GlossaryAddMixin from weblate.lang.data import BASIC_LANGUAGES from weblate.lang.models import Language from weblate.machinery import MACHINE_TRANSLATION_SERVICES from weblate.trans.defines import COMPONENT_NAME_LENGTH, REPO_LENGTH from weblate.trans.filter import FILTERS, get_filter_choice from weblate.trans.models import ( Announcement, Change, Component, Label, Project, ProjectToken, Unit, ) from weblate.trans.specialchars import RTL_CHARS_DATA, get_special_chars from weblate.trans.util import check_upload_method_permissions, is_repo_link from weblate.trans.validators import validate_check_flags from weblate.utils.antispam import is_spam from weblate.utils.errors import .report_error from weblate.utils.forms import ( ColorWidget, ContextDiv, EmailField, SearchField, SortedSelect, SortedSelectMultiple, UsernameField, ) from weblate.utils.hash import .checksum_to_hash, hash_to_checksum from weblate.utils.search import parse_query from weblate.utils.state import ( STATE_APPROVED, STATE_CHOICES, STATE_EMPTY, STATE_FUZZY, STATE_READONLY, STATE_TRANSLATED, ) from weblate.utils.validators import validate_file_extension from weblate.vcs.models import VCS_REGISTRY VAR_0 = """ <button class="btn btn-default {0}" title="{1}" {2}>{3}</button> """ VAR_1 = """ <VAR_134 class="btn btn-default {0}" title="{1}"> <input type="radio" VAR_20="{2}" VAR_13="{3}" {4}/> {5} </VAR_134> """ VAR_2 = """ <div class="btn-VAR_100 btn-VAR_100-xs" {0}>{1}</div> """ VAR_3 = """ <div class="btn-toolbar pull-right flip editor-toolbar">{0}</div> """ class CLASS_0(forms.Textarea): def __init__(self, **VAR_7): VAR_7["attrs"] = { "dir": "auto", "class": "markdown-editor highlight-editor", "data-mode": "markdown", } super().__init__(**VAR_7) class CLASS_1(forms.DateInput): def __init__(self, VAR_12=True, **VAR_7): VAR_21 = {"type": "date"} if VAR_12: VAR_21["data-provide"] = "datepicker" VAR_21["data-date-format"] = "yyyy-mm-dd" super().__init__(VAR_21=attrs, VAR_36="%Y-%m-%d", **VAR_7) class CLASS_2(forms.DateField): def __init__(self, VAR_12=True, **VAR_7): if "widget" not in VAR_7: VAR_7["widget"] = CLASS_1(VAR_12=datepicker) super().__init__(**VAR_7) def FUNC_3(self, VAR_13): VAR_13 = super().to_python(VAR_13) if isinstance(VAR_13, date): return from_current_timezone( datetime(VAR_13.year, VAR_13.month, VAR_13.day, 0, 0, 0) ) return VAR_13 class CLASS_3(forms.CharField): def __init__(self, *VAR_6, **VAR_7): VAR_7["widget"] = forms.HiddenInput super().__init__(*VAR_6, **VAR_7) def FUNC_4(self, VAR_13): super().clean(VAR_13) if not VAR_13: return None try: return checksum_to_hash(VAR_13) except ValueError: raise ValidationError(_("Invalid VAR_26 specified!")) class CLASS_4(forms.CharField): def FUNC_4(self, VAR_13): if not VAR_13: return None try: return User.objects.get(Q(username=VAR_13) | Q(email=VAR_13)) except User.DoesNotExist: raise ValidationError(_("Could not find any such VAR_4.")) except User.MultipleObjectsReturned: raise ValidationError(_("More possible users were found.")) class CLASS_5(forms.CharField): def __init__(self, **VAR_7): if "label" not in VAR_7: VAR_7["label"] = _("Query") if "required" not in VAR_7: VAR_7["required"] = False super().__init__(**VAR_7) def FUNC_4(self, VAR_13): if not VAR_13: if self.required: raise ValidationError(_("Missing query string.")) return "" try: parse_query(VAR_13) return VAR_13 except Exception as error: report_error() raise ValidationError(_("Could not parse query string: {}").format(error)) class CLASS_6(forms.CharField): VAR_14 = [validate_check_flags] class CLASS_7(forms.Textarea): def __init__(self, *VAR_6, **VAR_7): self.profile = None super().__init__(*VAR_6, **VAR_7) def FUNC_5(self, VAR_15): VAR_101 = [] chars = [] for VAR_20, char, VAR_13 in RTL_CHARS_DATA: VAR_102.append( VAR_0.format( "specialchar", VAR_20, 'data-VAR_13="{}"'.format( VAR_13.encode("ascii", "xmlcharrefreplace").decode("ascii") ), char, ) ) VAR_101.append(VAR_2.format("", "\n".join(VAR_102))) return VAR_3.format("\n".join(VAR_101)) def FUNC_6(self, VAR_16, VAR_15): if VAR_16.direction != "rtl": return "" VAR_103 = f"rtl-{VAR_15}" VAR_104 = [ VAR_1.format( "direction-toggle active", gettext("Toggle text direction"), VAR_103, "rtl", 'checked="checked"', "RTL", ), VAR_1.format( "direction-toggle", gettext("Toggle text direction"), VAR_103, "ltr", "", "LTR", ), ] VAR_101 = [VAR_2.format('data-toggle="buttons"', "\n".join(VAR_104))] return mark_safe(VAR_3.format("\n".join(VAR_101))) def FUNC_7(self, VAR_16, VAR_15, VAR_17, VAR_18, VAR_19): VAR_105 = self.profile VAR_101 = [] chars = [ VAR_0.format( "specialchar", VAR_20, 'data-VAR_13="{}"'.format( VAR_13.encode("ascii", "xmlcharrefreplace").decode("ascii") ), char, ) for VAR_20, char, VAR_13 in get_special_chars( VAR_16, VAR_105.special_chars, VAR_17.source ) ] VAR_101.append(VAR_2.format("", "\n".join(VAR_102))) VAR_43 = VAR_3.format("\n".join(VAR_101)) if VAR_16.direction == "rtl": VAR_43 = self.get_rtl_toolbar(VAR_15) + VAR_43 return mark_safe(VAR_43) def FUNC_8(self, VAR_20, VAR_13, VAR_21=None, VAR_22=None, **VAR_7): VAR_17 = VAR_13 VAR_106 = VAR_17.get_target_plurals() VAR_59 = VAR_17.translation.language VAR_107 = VAR_17.translation.plural VAR_108 = self.attrs["tabindex"] VAR_109 = [hl[2] for hl in highlight_string(VAR_17.source_string, VAR_17)] VAR_21["class"] = "translation-editor VAR_114-control highlight-editor" VAR_21["tabindex"] = VAR_108 VAR_21["lang"] = VAR_59.code VAR_21["dir"] = VAR_59.direction VAR_21["rows"] = 3 VAR_21["data-max"] = VAR_17.get_max_length() VAR_21["data-mode"] = VAR_17.edit_mode VAR_21["data-placeables"] = "|".join(re.escape(pl) for pl in VAR_109 if pl) if VAR_17.readonly: VAR_21["readonly"] = 1 VAR_110 = [] VAR_111 = VAR_17.get_source_plurals() VAR_112 = f"id_{VAR_17.checksum}" for VAR_18, val in enumerate(VAR_106): VAR_15 = f"{VAR_20}_{VAR_18}" VAR_132 = f"{VAR_112}_{VAR_18}" VAR_21["id"] = VAR_132 VAR_21["tabindex"] = VAR_108 + VAR_18 if VAR_18 and len(VAR_111) > 1: VAR_19 = VAR_111[1] else: VAR_19 = VAR_111[0] VAR_133 = super().render(VAR_15, val, VAR_21, VAR_22, **VAR_7) VAR_134 = escape(VAR_17.translation.language) if len(VAR_106) != 1: VAR_134 = f"{VAR_134}, {VAR_107.get_plural_label(VAR_18)}" VAR_110.append( render_to_string( "snippets/editor.html", { "toolbar": self.get_toolbar(VAR_59, VAR_132, VAR_17, VAR_18, VAR_19), "fieldid": VAR_132, "label": mark_safe(VAR_134), "textarea": VAR_133, "max_length": VAR_21["data-max"], "length": len(val), "source_length": len(VAR_19), "rtl_toggle": self.get_rtl_toggle(VAR_59, VAR_132), }, ) ) if len(VAR_106) > 1: VAR_110.append( render_to_string( "snippets/VAR_107-formula.html", {"plural": VAR_107, "user": self.profile.user}, ) ) return mark_safe("".join(VAR_110)) def FUNC_9(self, VAR_10, VAR_23, VAR_20): VAR_110 = [] for VAR_18 in range(0, 10): VAR_15 = f"{VAR_20}_{VAR_18:d}" if VAR_15 not in VAR_10: break VAR_110.append(VAR_10.get(VAR_15, "")) return [r.replace("\r", "") for r in VAR_110] class CLASS_8(forms.CharField): def __init__(self, VAR_24=None, VAR_25=None, **VAR_7): VAR_7["label"] = "" super().__init__(widget=CLASS_7, **VAR_7) def FUNC_3(self, VAR_13): return VAR_13 def FUNC_4(self, VAR_13): VAR_13 = super().clean(VAR_13) if not VAR_13 or (self.required and not any(VAR_13)): raise ValidationError(_("Missing translated string!")) return VAR_13 class CLASS_9(forms.ChoiceField): def __init__(self, *VAR_6, **VAR_7): VAR_7["label"] = _("Search filter") if "required" not in VAR_7: VAR_7["required"] = False VAR_7["choices"] = get_filter_choice() VAR_7["error_messages"] = { "invalid_choice": _("Please choose a valid filter type.") } super().__init__(*VAR_6, **VAR_7) def FUNC_3(self, VAR_13): if VAR_13 == "untranslated": return "todo" return super().to_python(VAR_13) class CLASS_10(forms.Form): VAR_26 = CLASS_3(VAR_113=True) def __init__(self, VAR_27, *VAR_6, **VAR_7): self.unit_set = VAR_27 super().__init__(*VAR_6, **VAR_7) def FUNC_10(self): if "checksum" not in self.cleaned_data: return VAR_27 = self.unit_set try: self.cleaned_data["unit"] = VAR_27.filter( id_hash=self.cleaned_data["checksum"] )[0] except (Unit.DoesNotExist, IndexError): raise ValidationError( _("The string you wanted to translate is no longer available.") ) class CLASS_11(forms.Form): def __init__(self, VAR_17: Unit, *VAR_6, **VAR_7): self.unit = VAR_17 super().__init__(*VAR_6, **VAR_7) class CLASS_12(forms.BooleanField): VAR_28 = True def __init__(self, *VAR_6, **VAR_7): VAR_7["label"] = _("Needs editing") VAR_7["help_text"] = _( 'Strings are usually marked as "Needs editing" after the VAR_19 ' "string is updated, or when marked as such manually." ) super().__init__(*VAR_6, **VAR_7) self.widget.attrs["class"] = "fuzzy_checkbox" class CLASS_13(CLASS_11): VAR_29 = CLASS_3(VAR_113=True) VAR_30 = CLASS_3(VAR_113=True) VAR_31 = CLASS_8(VAR_113=False) VAR_32 = CLASS_12(VAR_113=False) VAR_33 = forms.ChoiceField( VAR_134=_("Review state"), VAR_68=[ (STATE_FUZZY, _("Needs editing")), (STATE_TRANSLATED, _("Waiting for review")), (STATE_APPROVED, _("Approved")), ], VAR_113=False, widget=forms.RadioSelect, ) VAR_34 = forms.CharField( widget=CLASS_0, VAR_134=_("Explanation"), help_text=_( "Additional VAR_34 to clarify meaning or usage of the string." ), VAR_24=1000, VAR_113=False, ) def __init__(self, VAR_4, VAR_17: Unit, *VAR_6, **VAR_7): if VAR_17 is not None: VAR_7["initial"] = { "checksum": VAR_17.checksum, "contentsum": hash_to_checksum(VAR_17.content_hash), "translationsum": hash_to_checksum(VAR_17.get_target_hash()), "target": VAR_17, "fuzzy": VAR_17.fuzzy, "review": VAR_17.state, "explanation": VAR_17.explanation, } VAR_7["auto_id"] = f"id_{VAR_17.checksum}_%s" VAR_108 = VAR_7.pop("tabindex", 100) super().__init__(VAR_17, *VAR_6, **VAR_7) if VAR_17.readonly: for VAR_39 in ["target", "fuzzy", "review"]: self.fields[VAR_39].widget.attrs["readonly"] = 1 self.fields["review"].choices = [ (STATE_READONLY, _("Read only")), ] self.user = VAR_4 self.fields["target"].widget.attrs["tabindex"] = VAR_108 self.fields["target"].widget.profile = VAR_4.profile self.fields["review"].widget.attrs["class"] = "review_radio" if VAR_6: self.fields["review"].choices.append((STATE_EMPTY, "")) self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_tag = False self.helper.disable_csrf = True self.helper.layout = Layout( Field("target"), Field("fuzzy"), Field("contentsum"), Field("translationsum"), InlineRadios("review"), Field("explanation"), ) if VAR_17 and VAR_4.has_perm("unit.review", VAR_17.translation): self.fields["fuzzy"].widget = forms.HiddenInput() else: self.fields["review"].widget = forms.HiddenInput() if not VAR_17.translation.component.is_glossary: self.fields["explanation"].widget = forms.HiddenInput() def FUNC_4(self): super().clean() VAR_113 = {"target", "contentsum", "translationsum"} if not VAR_113.issubset(self.cleaned_data): return VAR_17 = self.unit if self.cleaned_data["contentsum"] != VAR_17.content_hash: raise ValidationError( _( "Source string has been changed meanwhile. " "Please check your changes." ) ) if self.cleaned_data["translationsum"] != VAR_17.get_target_hash(): raise ValidationError( _( "Translation of the string has been changed meanwhile. " "Please check your changes." ) ) VAR_24 = VAR_17.get_max_length() for text in self.cleaned_data["target"]: if len(text) > VAR_24: raise ValidationError(_("Translation text too long!")) if self.user.has_perm( "unit.review", VAR_17.translation ) and self.cleaned_data.get("review"): self.cleaned_data["state"] = int(self.cleaned_data["review"]) elif self.cleaned_data["fuzzy"]: self.cleaned_data["state"] = STATE_FUZZY else: self.cleaned_data["state"] = STATE_TRANSLATED class CLASS_14(CLASS_13): VAR_26 = CLASS_3(VAR_113=True) def __init__(self, VAR_4, VAR_17, *VAR_6, **VAR_7): super().__init__(VAR_4, VAR_17, *VAR_6, **VAR_7) self.helper.form_action = reverse( "save_zen", VAR_7=VAR_17.translation.get_reverse_url_kwargs() ) self.helper.form_tag = True self.helper.disable_csrf = False self.helper.layout.append(Field("checksum")) class CLASS_15(forms.Form): VAR_35 = CLASS_5() VAR_36 = forms.ChoiceField( VAR_134=_("File format"), VAR_68=[(x.name, x.verbose) for x in EXPORTERS.values()], VAR_11="po", VAR_113=True, widget=forms.RadioSelect, ) def __init__(self, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( SearchField("q"), InlineRadios("format"), ) class CLASS_16(forms.Form): VAR_37 = forms.FileField(VAR_134=_("File"), validators=[validate_file_extension]) VAR_38 = forms.ChoiceField( VAR_134=_("File upload mode"), VAR_68=( ("translate", _("Add as translation")), ("approve", _("Add as approved translation")), ("suggest", _("Add as suggestion")), ("fuzzy", _("Add as VAR_5 needing edit")), ("replace", _("Replace existing VAR_5 file")), ("source", _("Update VAR_19 strings")), ("add", _("Add new strings")), ), widget=forms.RadioSelect, VAR_113=True, ) VAR_32 = forms.ChoiceField( VAR_134=_("Processing of strings needing edit"), VAR_68=( ("", _("Do not import")), ("process", _("Import as string needing edit")), ("approve", _("Import as translated")), ), VAR_113=False, ) def __init__(self, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False @staticmethod def FUNC_11(VAR_39): return ("user/files", f"upload-{VAR_39.name}") def FUNC_12(self, VAR_13): VAR_68 = self.fields["method"].choices self.fields["method"].choices = [ choice for choice in VAR_68 if choice[0] != VAR_13 ] class CLASS_17(CLASS_16): VAR_40 = forms.ChoiceField( VAR_134=_("Conflict handling"), help_text=_( "Whether to overwrite existing translations if the string is " "already translated." ), VAR_68=( ("", _("Update only untranslated strings")), ("replace-translated", _("Update translated strings")), ("replace-approved", _("Update translated and approved strings")), ), VAR_113=False, VAR_11="replace-translated", ) class CLASS_18(CLASS_17): VAR_41 = forms.CharField(VAR_134=_("Author name")) VAR_42 = EmailField(VAR_134=_("Author e-mail")) def FUNC_0(VAR_4, VAR_5, *VAR_6, **VAR_7): if VAR_4.has_perm("upload.authorship", VAR_5): VAR_114 = CLASS_18 VAR_7["initial"] = {"author_name": VAR_4.full_name, "author_email": VAR_4.email} elif VAR_4.has_perm("upload.overwrite", VAR_5): VAR_114 = CLASS_17 else: VAR_114 = CLASS_16 VAR_43 = VAR_114(*VAR_6, **VAR_7) for VAR_38 in [x[0] for x in VAR_43.fields["method"].choices]: if not check_upload_method_permissions(VAR_4, VAR_5, VAR_38): VAR_43.remove_translation_choice(VAR_38) if not VAR_4.has_perm("unit.review", VAR_5) and not VAR_114 == CLASS_16: VAR_43.fields["conflicts"].choices = [ choice for choice in VAR_43.fields["conflicts"].choices if choice[0] != "approved" ] return VAR_43 class CLASS_19(forms.Form): VAR_35 = CLASS_5() VAR_44 = forms.CharField(VAR_113=False, widget=forms.HiddenInput) VAR_26 = CLASS_3(VAR_113=False) VAR_45 = forms.IntegerField(min_value=-1, VAR_113=False, widget=forms.HiddenInput) VAR_46 = {} def __init__(self, VAR_4, VAR_16=None, VAR_47=True, **VAR_7): self.user = VAR_4 self.language = VAR_16 super().__init__(**VAR_7) self.helper = FormHelper(self) self.helper.disable_csrf = True self.helper.form_tag = False self.helper.layout = Layout( Div( Field("offset", **self.offset_kwargs), SearchField("q"), Field("sort_by", template="snippets/sort-VAR_39.html"), css_class="btn-toolbar", role="toolbar", ), ContextDiv( template="snippets/query-builder.html", VAR_87={ "user": self.user, "month_ago": timezone.now() - timedelta(days=31), "show_builder": VAR_47, "language": self.language, }, ), Field("checksum"), ) def FUNC_13(self): return FILTERS.get_search_name(self.cleaned_data.get("q", "")) def FUNC_14(self): return self.cleaned_data["q"] def FUNC_15(self): if self.cleaned_data.get("offset") is None: self.cleaned_data["offset"] = 1 return self.cleaned_data["offset"] def VAR_115(self): VAR_115 = [] VAR_116 = {"offset", "checksum"} for param in sorted(self.cleaned_data): VAR_13 = self.cleaned_data[param] if VAR_13 is None or param in VAR_116: continue if isinstance(VAR_13, bool): if VAR_13: VAR_115.append((param, "1")) elif isinstance(VAR_13, int): if VAR_13 > 0: VAR_115.append((param, str(VAR_13))) elif isinstance(VAR_13, datetime): VAR_115.append((param, VAR_13.date().isoformat())) elif isinstance(VAR_13, list): for val in VAR_13: VAR_115.append((param, val)) elif isinstance(VAR_13, User): VAR_115.append((param, VAR_13.username)) else: if VAR_13: VAR_115.append((param, VAR_13)) return VAR_115 def FUNC_17(self): return FUNC_17(self.items()) def FUNC_18(self): VAR_10 = copy.copy(self.data) VAR_10["offset"] = "1" VAR_10["checksum"] = "" self.data = VAR_10 return self class CLASS_20(CLASS_19): VAR_45 = forms.IntegerField(min_value=-1, VAR_113=False) VAR_46 = {"template": "snippets/position-VAR_39.html"} class CLASS_21(CLASS_11): VAR_48 = forms.IntegerField() def FUNC_4(self): super().clean() if "merge" not in self.cleaned_data: return None try: VAR_17 = self.unit VAR_5 = VAR_17.translation VAR_58 = VAR_5.component.project self.cleaned_data["merge_unit"] = VAR_135 = Unit.objects.get( pk=self.cleaned_data["merge"], translation__component__project=VAR_58, translation__language=VAR_5.language, ) if not VAR_5.is_source and VAR_17.source != VAR_135.source: raise ValidationError(_("Could not find merged string.")) except Unit.DoesNotExist: raise ValidationError(_("Could not find merged string.")) return self.cleaned_data class CLASS_22(CLASS_11): VAR_49 = forms.IntegerField() def FUNC_4(self): super().clean() if "revert" not in self.cleaned_data: return None try: self.cleaned_data["revert_change"] = Change.objects.get( pk=self.cleaned_data["revert"], VAR_17=self.unit ) except Change.DoesNotExist: raise ValidationError(_("Could not find reverted change.")) return self.cleaned_data class CLASS_23(forms.Form): VAR_50 = forms.ChoiceField( VAR_134=_("Automatic VAR_5 mode"), VAR_68=[ ("suggest", _("Add as suggestion")), ("translate", _("Add as translation")), ("fuzzy", _("Add as needing edit")), ], VAR_11="suggest", ) VAR_51 = CLASS_9( VAR_113=True, VAR_11="todo", help_text=_( "Please note that translating all strings will " "discard all existing translations." ), ) VAR_52 = forms.ChoiceField( VAR_134=_("Automatic VAR_5 source"), VAR_68=[ ("others", _("Other VAR_5 components")), ("mt", _("Machine translation")), ], VAR_11="others", ) VAR_9 = forms.ChoiceField( VAR_134=_("Components"), VAR_113=False, help_text=_( "Turn on contribution to shared VAR_5 memory for the VAR_58 to " "get VAR_127 to additional components." ), VAR_11="", ) VAR_53 = forms.MultipleChoiceField( VAR_134=_("Machine VAR_5 engines"), VAR_68=[], VAR_113=False ) VAR_54 = forms.IntegerField( VAR_134=_("Score threshold"), VAR_11=80, min_value=1, max_value=100 ) def __init__(self, VAR_55, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.obj = VAR_55 self.components = VAR_55.project.component_set.filter( VAR_72=VAR_55.source_language ) | Component.objects.filter( source_language_id=VAR_55.source_language_id, project__contribute_shared_tm=True, ).exclude( VAR_58=VAR_55.project ) if len(self.components.values_list("id")[:30]) == 30: self.fields["component"] = forms.CharField( VAR_113=False, VAR_134=_("Components"), help_text=_( "Enter VAR_9 to use as VAR_19, " "keep blank to use all components in current VAR_58." ), ) else: VAR_68 = [ (s.id, str(s)) for s in self.components.order_project().prefetch_related("project") ] self.fields["component"].choices = [ ("", _("All components in current project")) ] + VAR_68 self.fields["engines"].choices = [ (VAR_148, mt.name) for VAR_148, mt in MACHINE_TRANSLATION_SERVICES.items() ] if "weblate" in MACHINE_TRANSLATION_SERVICES.keys(): self.fields["engines"].initial = "weblate" VAR_117 = {"all", "nottranslated", "todo", "fuzzy", "check:inconsistent"} self.fields["filter_type"].choices = [ x for x in self.fields["filter_type"].choices if x[0] in VAR_117 ] self.helper = FormHelper(self) self.helper.layout = Layout( Field("mode"), Field("filter_type"), InlineRadios("auto_source", id="select_auto_source"), Div("component", css_id="auto_source_others"), Div("engines", "threshold", css_id="auto_source_mt"), ) def FUNC_19(self): VAR_9 = self.cleaned_data["component"] if not VAR_9: return None if VAR_9.isdigit(): try: VAR_43 = self.components.get(pk=VAR_9) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) else: VAR_136 = VAR_9.count("/") if VAR_136 == 0: try: VAR_43 = self.components.get( VAR_69=VAR_9, VAR_58=self.obj.project ) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) elif VAR_136 == 1: VAR_145, VAR_146 = VAR_9.split("/") try: VAR_43 = self.components.get( VAR_69=VAR_146, project__slug=VAR_145 ) except Component.DoesNotExist: raise ValidationError(_("Component not found!")) else: raise ValidationError(_("Please provide valid VAR_9 VAR_69!")) return VAR_43.pk class CLASS_24(forms.Form): VAR_56 = forms.ChoiceField( VAR_134=_("Scope"), help_text=_( "Is your VAR_57 specific to this " "translation or generic for all of them?" ), VAR_68=( ( "report", _("Report issue with the VAR_19 string"), ), ( "global", _("Source string VAR_57, suggestions for changes to this string"), ), ( "translation", _("Translation VAR_57, discussions with other translators"), ), ), ) VAR_57 = forms.CharField( widget=CLASS_0, VAR_134=_("New comment"), help_text=_("You can use Markdown and mention users by @username."), VAR_24=1000, ) def __init__(self, VAR_58, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) if not VAR_58.source_review: self.fields["scope"].choices = self.fields["scope"].choices[1:] class CLASS_25(forms.Form): VAR_59 = forms.ChoiceField(VAR_113=False, VAR_68=[("", _("All languages"))]) VAR_9 = forms.ChoiceField(VAR_113=False, VAR_68=[("", _("All components"))]) def __init__(self, VAR_4, VAR_58, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.fields["lang"].choices += VAR_58.languages.as_choices() self.fields["component"].choices += ( VAR_58.component_set.filter_access(VAR_4) .order() .values_list("slug", "name") ) class CLASS_26(forms.Form): VAR_59 = forms.MultipleChoiceField( VAR_134=_("Languages"), VAR_68=[], widget=forms.SelectMultiple ) def FUNC_20(self): return Language.objects.exclude( Q(translation__component=self.component) | Q(VAR_9=self.component) ) def __init__(self, VAR_9, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.component = VAR_9 VAR_118 = self.get_lang_objects() self.fields["lang"].choices = VAR_118.as_choices() class CLASS_27(CLASS_26): VAR_59 = forms.ChoiceField(VAR_134=_("Language"), VAR_68=[], widget=forms.Select) def FUNC_20(self): VAR_119 = BASIC_LANGUAGES if settings.BASIC_LANGUAGES is not None: VAR_119 = settings.BASIC_LANGUAGES return super().get_lang_objects().filter(code__in=VAR_119) def __init__(self, VAR_9, *VAR_6, **VAR_7): super().__init__(VAR_9, *VAR_6, **VAR_7) self.fields["lang"].choices = [("", _("Please choose"))] + self.fields[ "lang" ].choices def FUNC_21(self): return [self.cleaned_data["lang"]] def FUNC_1(VAR_8, VAR_9): if not VAR_8.user.has_perm("translation.add", VAR_9): raise PermissionDenied() if VAR_8.user.has_perm("translation.add_more", VAR_9): return CLASS_26 return CLASS_27 class CLASS_28(forms.ModelForm): class CLASS_82: VAR_120 = Unit VAR_121 = ("explanation", "labels", "extra_flags") VAR_122 = { "labels": forms.CheckboxSelectMultiple(), "explanation": CLASS_0, } VAR_60 = { "explanation": ("admin/translating", "additional-explanation"), "labels": ("devel/translations", "labels"), "extra_flags": ("admin/translating", "additional-flags"), } def FUNC_11(self, VAR_39): return self.doc_links[VAR_39.name] def __init__(self, VAR_10=None, VAR_61=None, VAR_4=None, **VAR_7): VAR_7["initial"] = { "labels": Label.objects.filter( Q(VAR_17=VAR_61) | Q(unit__source_unit=VAR_61) ) } super().__init__(VAR_10=data, VAR_61=instance, **VAR_7) VAR_58 = VAR_61.translation.component.project self.fields["labels"].queryset = VAR_58.label_set.all() self.helper = FormHelper(self) self.helper.disable_csrf = True self.helper.form_tag = False self.helper.layout = Layout( Field("explanation"), Field("labels"), ContextDiv( template="snippets/labels_description.html", VAR_87={"project": VAR_58, "user": VAR_4}, ), Field("extra_flags"), ) def FUNC_22(self, VAR_62=True): if VAR_62: self.instance.save(same_content=True) self._save_m2m() return self.instance return super().save(VAR_62) class CLASS_29(forms.Form): VAR_4 = CLASS_4( VAR_134=_("User to add"), help_text=_( "Please type in an existing Weblate account VAR_20 or e-mail address." ), ) class CLASS_30(forms.Form): VAR_4 = CLASS_4( VAR_134=_("User to block"), help_text=_( "Please type in an existing Weblate account VAR_20 or e-mail address." ), ) VAR_63 = forms.ChoiceField( VAR_134=_("Block duration"), VAR_68=( ("", _("Block VAR_4 until I unblock them")), ("1", _("Block VAR_4 for one day")), ("7", _("Block VAR_4 for one week")), ("30", _("Block VAR_4 for one month")), ), VAR_113=False, ) class CLASS_31(forms.Form): VAR_64 = forms.ChoiceField( VAR_134=_("Report format"), help_text=_("Choose VAR_37 VAR_36 for the report"), VAR_68=( ("rst", _("reStructuredText")), ("json", _("JSON")), ("html", _("HTML")), ), ) VAR_65 = forms.ChoiceField( VAR_134=_("Report period"), VAR_68=( ("30days", _("Last 30 days")), ("this-month", _("This month")), ("month", _("Last month")), ("this-year", _("This year")), ("year", _("Last year")), ("", _("As specified")), ), VAR_113=False, ) VAR_66 = CLASS_2( VAR_134=_("Starting date"), VAR_113=False, VAR_12=False ) VAR_67 = CLASS_2( VAR_134=_("Ending date"), VAR_113=False, VAR_12=False ) def __init__(self, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Field("style"), Field("period"), Div( "start_date", "end_date", css_class="input-VAR_100 input-daterange", data_provide="datepicker", data_date_format="yyyy-mm-dd", ), ) def FUNC_4(self): super().clean() if "period" not in self.cleaned_data: return if self.cleaned_data["period"] == "30days": VAR_137 = timezone.now() VAR_138 = VAR_137 - timedelta(days=30) elif self.cleaned_data["period"] == "month": VAR_137 = timezone.now().replace(day=1) - timedelta(days=1) VAR_138 = VAR_137.replace(day=1) elif self.cleaned_data["period"] == "this-month": VAR_137 = timezone.now().replace(day=1) + timedelta(days=31) VAR_137 = VAR_137.replace(day=1) - timedelta(days=1) VAR_138 = VAR_137.replace(day=1) elif self.cleaned_data["period"] == "year": VAR_147 = timezone.now().year - 1 VAR_137 = timezone.make_aware(datetime(VAR_147, 12, 31)) VAR_138 = timezone.make_aware(datetime(VAR_147, 1, 1)) elif self.cleaned_data["period"] == "this-year": VAR_147 = timezone.now().year VAR_137 = timezone.make_aware(datetime(VAR_147, 12, 31)) VAR_138 = timezone.make_aware(datetime(VAR_147, 1, 1)) else: if not self.cleaned_data.get("start_date"): raise ValidationError({"start_date": _("Missing date!")}) if not self.cleaned_data.get("end_date"): raise ValidationError({"end_date": _("Missing date!")}) VAR_138 = self.cleaned_data["start_date"] VAR_137 = self.cleaned_data["end_date"] self.cleaned_data["start_date"] = VAR_138.replace( hour=0, minute=0, second=0, microsecond=0 ) self.cleaned_data["end_date"] = VAR_137.replace( hour=23, minute=59, second=59, microsecond=999999 ) if self.cleaned_data["start_date"] > self.cleaned_data["end_date"]: VAR_139 = _("Starting date has to be before ending date!") raise ValidationError({"start_date": VAR_139, "end_date": VAR_139}) class CLASS_32: def FUNC_23(self): VAR_78 = self.cleaned_data.get("repo") if not VAR_78 or not is_repo_link(VAR_78) or "/" not in VAR_78[10:]: return VAR_78 VAR_58, VAR_9 = VAR_78[10:].split("/", 1) try: VAR_55 = Component.objects.get( slug__iexact=VAR_9, project__slug__iexact=VAR_58 ) except Component.DoesNotExist: return VAR_78 if not self.request.user.has_perm("component.edit", VAR_55): raise ValidationError( _("You do not have permission to VAR_127 this VAR_9!") ) return VAR_78 class CLASS_33(CLASS_32, forms.ModelForm): class CLASS_82: VAR_120 = Component VAR_121 = [] def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.request = VAR_8 self.helper = FormHelper() self.helper.form_tag = False class CLASS_34(SortedSelectMultiple): def __init__(self, VAR_21=None, VAR_68=()): VAR_68 = CHECKS.get_choices() super().__init__(VAR_21=attrs, VAR_68=choices) def FUNC_9(self, VAR_10, VAR_23, VAR_20): VAR_13 = super().value_from_datadict(VAR_10, VAR_23, VAR_20) if isinstance(VAR_13, str): return json.loads(VAR_13) return VAR_13 def FUNC_24(self, VAR_13): VAR_13 = super().format_value(VAR_13) if isinstance(VAR_13, str): return VAR_13 return json.dumps(VAR_13) class CLASS_35(forms.CharField): def FUNC_3(self, VAR_13): return VAR_13 class CLASS_36: @staticmethod def FUNC_11(VAR_39): return ("admin/projects", f"component-{VAR_39.name}") class CLASS_37: @staticmethod def FUNC_11(VAR_39): return ("admin/projects", f"project-{VAR_39.name}") class CLASS_38: def FUNC_25(self, VAR_13): if is_spam(VAR_13, self.request): raise ValidationError(_("This VAR_39 has been identified as spam!")) class CLASS_39(CLASS_38): def FUNC_26(self): VAR_13 = self.cleaned_data["agreement"] self.spam_check(VAR_13) return VAR_13 class CLASS_40(CLASS_38): def FUNC_27(self): VAR_13 = self.cleaned_data["web"] self.spam_check(VAR_13) return VAR_13 def FUNC_28(self): VAR_13 = self.cleaned_data["instructions"] self.spam_check(VAR_13) return VAR_13 class CLASS_41( CLASS_33, CLASS_36, CLASS_39 ): class CLASS_82: VAR_120 = Component VAR_121 = ( "name", "report_source_bugs", "license", "agreement", "allow_translation_propagation", "enable_suggestions", "suggestion_voting", "suggestion_autoaccept", "priority", "check_flags", "enforced_checks", "commit_message", "add_message", "delete_message", "merge_message", "addon_message", "vcs", "repo", "branch", "push", "push_branch", "repoweb", "push_on_commit", "commit_pending_age", "merge_style", "file_format", "edit_template", "new_lang", "language_code_style", "source_language", "new_base", "filemask", "template", "intermediate", "language_regex", "variant_regex", "restricted", "auto_lock_error", "links", "manage_units", "is_glossary", "glossary_color", ) VAR_122 = { "enforced_checks": CLASS_34, "source_language": SortedSelect, } VAR_123 = {"enforced_checks": CLASS_35} def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(VAR_8, *VAR_6, **VAR_7) if self.hide_restricted: self.fields["restricted"].widget = forms.HiddenInput() self.fields["links"].queryset = VAR_8.user.managed_projects.exclude( pk=self.instance.pk ) self.helper.layout = Layout( TabHolder( Tab( _("Basic"), Fieldset(_("Name"), "name"), Fieldset(_("License"), "license", "agreement"), Fieldset(_("Upstream links"), "report_source_bugs"), Fieldset( _("Listing and access"), "priority", "restricted", "links", ), Fieldset( _("Glossary"), "is_glossary", "glossary_color", ), css_id="basic", ), Tab( _("Translation"), Fieldset( _("Suggestions"), "enable_suggestions", "suggestion_voting", "suggestion_autoaccept", ), Fieldset( _("Translation settings"), "allow_translation_propagation", "manage_units", "check_flags", "variant_regex", "enforced_checks", ), css_id="translation", ), Tab( _("Version control"), Fieldset( _("Locations"), Div(template="trans/repo_help.html"), "vcs", "repo", "branch", "push", "push_branch", "repoweb", ), Fieldset( _("Version control settings"), "push_on_commit", "commit_pending_age", "merge_style", "auto_lock_error", ), css_id="vcs", ), Tab( _("Commit messages"), Fieldset( _("Commit messages"), ContextDiv( template="trans/messages_help.html", VAR_87={"user": VAR_8.user}, ), "commit_message", "add_message", "delete_message", "merge_message", "addon_message", ), css_id="messages", ), Tab( _("Files"), Fieldset( _("Translation files"), "file_format", "filemask", "language_regex", "source_language", ), Fieldset( _("Monolingual translations"), "template", "edit_template", "intermediate", ), Fieldset( _("Adding new languages"), "new_base", "new_lang", "language_code_style", ), css_id="files", ), template="layout/pills.html", ) ) VAR_124 = ( "git", "gerrit", "github", "gitlab", "pagure", "local", "git-force-push", ) if self.instance.vcs not in VAR_124: vcses = (self.instance.vcs,) self.fields["vcs"].choices = [ c for c in self.fields["vcs"].choices if c[0] in VAR_124 ] @property def FUNC_29(self): VAR_4 = self.request.user if VAR_4.is_superuser: return False if settings.OFFER_HOSTING: return True return not any( "component.edit" in permissions for permissions, _langs in VAR_4.component_permissions[self.instance.pk] ) def FUNC_4(self): VAR_10 = self.cleaned_data if self.hide_restricted: VAR_10["restricted"] = self.instance.restricted class CLASS_42(CLASS_33, CLASS_36, CLASS_39): class CLASS_82: VAR_120 = Component VAR_121 = [ "project", "name", "slug", "vcs", "repo", "branch", "push", "push_branch", "repoweb", "file_format", "filemask", "template", "edit_template", "intermediate", "new_base", "license", "new_lang", "language_code_style", "language_regex", "source_language", "is_glossary", ] VAR_122 = {"source_language": SortedSelect} class CLASS_43(forms.Form, CLASS_36, CLASS_39): VAR_20 = forms.CharField( VAR_134=_("Component name"), VAR_24=COMPONENT_NAME_LENGTH, help_text=_("Display name"), ) VAR_69 = forms.SlugField( VAR_134=_("URL slug"), VAR_24=COMPONENT_NAME_LENGTH, help_text=_("Name used in URLs and filenames."), ) VAR_70 = forms.BooleanField( VAR_134=_("Use as a glossary"), VAR_113=False, ) def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper() self.helper.form_tag = False self.request = VAR_8 class CLASS_44(CLASS_43): VAR_9 = forms.ModelChoiceField( VAR_90=Component.objects.none(), VAR_134=_("Component"), help_text=_("Select existing VAR_9 to copy configuration from."), ) def __init__(self, VAR_8, *VAR_6, **VAR_7): if "instance" in VAR_7: kwargs.pop("instance") if "auto_id" not in VAR_7: VAR_7["auto_id"] = "id_existing_%s" super().__init__(VAR_8, *VAR_6, **VAR_7) class CLASS_45(CLASS_44): VAR_71 = forms.ChoiceField(VAR_134=_("Repository branch")) branch_data: Dict[int, List[str]] = {} VAR_61 = None def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_branch_%s" super().__init__(*VAR_6, **VAR_7) def FUNC_19(self): VAR_9 = self.cleaned_data["component"] self.fields["branch"].choices = [(x, x) for x in self.branch_data[VAR_9.pk]] return VAR_9 def FUNC_4(self): VAR_125 = ("branch", "slug", "name") VAR_10 = self.cleaned_data VAR_9 = VAR_10.get("component") if not VAR_9 or any(VAR_39 not in VAR_10 for VAR_39 in VAR_125): return VAR_7 = model_to_dict(VAR_9, exclude=["id", "links"]) VAR_7["source_language"] = VAR_9.source_language VAR_7["project"] = VAR_9.project for VAR_39 in VAR_125: VAR_7[VAR_39] = VAR_10[VAR_39] self.instance = Component(**VAR_7) try: self.instance.full_clean() except ValidationError as error: VAR_43 = {NON_FIELD_ERRORS: []} for VAR_148, VAR_13 in error.message_dict.items(): if VAR_148 in self.fields: VAR_43[VAR_148] = VAR_13 else: VAR_43[NON_FIELD_ERRORS].extend(VAR_13) raise ValidationError(error.messages) class CLASS_46(CLASS_43): VAR_58 = forms.ModelChoiceField( VAR_90=Project.objects.none(), VAR_134=_("Project") ) VAR_72 = forms.ModelChoiceField( widget=SortedSelect, VAR_134=_("Source language"), help_text=_("Language used for VAR_19 strings in all components"), VAR_90=Language.objects.all(), ) def __init__(self, VAR_8, *VAR_6, **VAR_7): if "instance" in VAR_7: kwargs.pop("instance") super().__init__(VAR_8, *VAR_6, **VAR_7) self.fields["source_language"].initial = Language.objects.default_language self.request = VAR_8 self.helper = FormHelper() self.helper.form_tag = False self.instance = None def FUNC_4(self): if "project" not in self.cleaned_data: return VAR_58 = self.cleaned_data["project"] VAR_20 = self.cleaned_data.get("name") if VAR_20 and VAR_58.component_set.filter(name__iexact=VAR_20).exists(): raise ValidationError( {"name": _("Component with the same VAR_20 already exists.")} ) VAR_69 = self.cleaned_data.get("slug") if VAR_69 and VAR_58.component_set.filter(slug__iexact=VAR_69).exists(): raise ValidationError( {"slug": _("Component with the same VAR_20 already exists.")} ) class CLASS_47(CLASS_46): VAR_73 = forms.ChoiceField( VAR_134=_("File format"), VAR_11="po-mono", VAR_68=FILE_FORMATS.get_choices( cond=lambda x: bool(x.new_translation) or hasattr(x, "update_bilingual") ), ) def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_scratchcreate_%s" super().__init__(*VAR_6, **VAR_7) class CLASS_48(CLASS_46): VAR_74 = forms.FileField( VAR_134=_("ZIP VAR_37 containing translations"), validators=[FileExtensionValidator(allowed_extensions=["zip"])], widget=forms.FileInput(VAR_21={"accept": ".zip,application/zip"}), ) VAR_75 = ["zipfile", "project", "name", "slug"] def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_zipcreate_%s" super().__init__(*VAR_6, **VAR_7) class CLASS_49(CLASS_46): VAR_76 = forms.FileField( VAR_134=_("Document to translate"), validators=[validate_file_extension], ) VAR_75 = ["docfile", "project", "name", "slug"] def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_doccreate_%s" super().__init__(*VAR_6, **VAR_7) class CLASS_50(CLASS_32, CLASS_46): VAR_58 = forms.ModelChoiceField( VAR_90=Project.objects.none(), VAR_134=_("Project") ) VAR_77 = forms.ChoiceField( VAR_134=_("Version control system"), help_text=_( "Version control system to use to VAR_127 your " "repository with translations." ), VAR_68=VCS_REGISTRY.get_choices(exclude={"local"}), VAR_11=settings.DEFAULT_VCS, ) VAR_78 = forms.CharField( VAR_134=_("Source code repository"), VAR_24=REPO_LENGTH, help_text=_( "URL of a repository, use weblate://VAR_58/VAR_9 " "for sharing with other VAR_9." ), ) VAR_71 = forms.CharField( VAR_134=_("Repository branch"), VAR_24=REPO_LENGTH, help_text=_("Repository VAR_71 to translate"), VAR_113=False, ) def FUNC_30(self, VAR_10): VAR_126 = copy.copy(VAR_10) if "discovery" in VAR_126: params.pop("discovery") VAR_61 = Component(**VAR_126) VAR_61.clean_fields(exclude=("filemask", "file_format", "license")) VAR_61.validate_unique() VAR_61.clean_repo() self.instance = VAR_61 VAR_78 = VAR_61.suggest_repo_link() if VAR_78: VAR_10["repo"] = VAR_78 VAR_10["branch"] = "" self.clean_instance(VAR_10) def FUNC_4(self): self.clean_instance(self.cleaned_data) class CLASS_51(CLASS_50): VAR_79 = forms.ChoiceField( VAR_134=_("Choose VAR_5 VAR_23 to import"), VAR_68=[("manual", _("Specify configuration manually"))], VAR_113=True, widget=forms.RadioSelect, ) def FUNC_31(self, VAR_13): VAR_87 = copy.copy(VAR_13) try: VAR_140 = FILE_FORMATS[VAR_13["file_format"]] VAR_87["file_format_name"] = VAR_140.name VAR_87["valid"] = True except KeyError: VAR_87["file_format_name"] = VAR_13["file_format"] VAR_87["valid"] = False VAR_87["origin"] = VAR_13.meta["origin"] return render_to_string("trans/FUNC_33-choice.html", VAR_87) def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(VAR_8, *VAR_6, **VAR_7) for VAR_39, VAR_13 in self.fields.items(): if VAR_39 == "discovery": continue VAR_13.widget = forms.HiddenInput() self.fields["vcs"].choices = VCS_REGISTRY.get_choices() self.discovered = self.perform_discovery(VAR_8, VAR_7) for i, VAR_13 in enumerate(self.discovered): self.fields["discovery"].choices.append((i, self.render_choice(VAR_13))) def FUNC_32(self, VAR_8, VAR_7): if "data" in VAR_7 and "create_discovery" in VAR_8.session: VAR_141 = [] for i, VAR_10 in enumerate(VAR_8.session["create_discovery"]): VAR_144 = DiscoveryResult(VAR_10) VAR_144.meta = VAR_8.session["create_discovery_meta"][i] VAR_141.append(VAR_144) return VAR_141 try: self.clean_instance(VAR_7["initial"]) VAR_141 = self.discover() if not VAR_141: discovered = self.discover(VAR_80=True) except ValidationError: VAR_141 = [] VAR_8.session["create_discovery"] = VAR_141 VAR_8.session["create_discovery_meta"] = [x.meta for x in VAR_141] return VAR_141 def FUNC_33(self, VAR_80: bool = False): return FUNC_33( self.instance.full_path, VAR_72=self.instance.source_language.code, VAR_80=eager, ) def FUNC_4(self): super().clean() VAR_79 = self.cleaned_data.get("discovery") if VAR_79 and VAR_79 != "manual": self.cleaned_data.update(self.discovered[int(VAR_79)]) class CLASS_52(CLASS_33, CLASS_36): class CLASS_82: VAR_120 = Component VAR_121 = ["slug"] class CLASS_53(CLASS_33, CLASS_36): class CLASS_82: VAR_120 = Component VAR_121 = ["project"] def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(VAR_8, *VAR_6, **VAR_7) self.fields["project"].queryset = VAR_8.user.managed_projects class CLASS_54(CLASS_33, CLASS_37, CLASS_40): class CLASS_82: VAR_120 = Project VAR_121 = ( "name", "web", "instructions", "set_language_team", "use_shared_tm", "contribute_shared_tm", "enable_hooks", "language_aliases", "access_control", "translation_review", "source_review", ) VAR_122 = { "access_control": forms.RadioSelect, "instructions": CLASS_0, "language_aliases": forms.TextInput, } def FUNC_4(self): VAR_10 = self.cleaned_data if settings.OFFER_HOSTING: VAR_10["contribute_shared_tm"] = VAR_10["use_shared_tm"] if ( "access_control" not in VAR_10 or VAR_10["access_control"] is None or VAR_10["access_control"] == "" ): VAR_10["access_control"] = self.instance.access_control VAR_127 = VAR_10["access_control"] self.changed_access = VAR_127 != self.instance.access_control if self.changed_access and not self.user_can_change_access: raise ValidationError( { "access_control": _( "You do not have permission to change VAR_58 VAR_127 control." ) } ) if self.changed_access and VAR_127 in ( Project.ACCESS_PUBLIC, Project.ACCESS_PROTECTED, ): VAR_142 = self.instance.component_set.filter(license="") if VAR_142: raise ValidationError( { "access_control": _( "You must specify a license for these components " "to make them publicly accessible: %s" ) % ", ".join(VAR_142.values_list("name", flat=True)) } ) def FUNC_22(self, VAR_62: bool = True): super().save(VAR_62=commit) if self.changed_access: Change.objects.create( VAR_58=self.instance, VAR_98=Change.ACTION_ACCESS_EDIT, VAR_4=self.user, details={"access_control": self.instance.access_control}, ) def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(VAR_8, *VAR_6, **VAR_7) self.user = VAR_8.user self.user_can_change_access = VAR_8.user.has_perm( "billing:VAR_58.permissions", self.instance ) self.changed_access = False self.helper.form_tag = False if not self.user_can_change_access: VAR_143 = {"disabled": True} self.fields["access_control"].required = False self.fields["access_control"].help_text = _( "You do not have permission to change VAR_58 VAR_127 control." ) else: VAR_143 = {} self.helper.layout = Layout( TabHolder( Tab( _("Basic"), "name", "web", "instructions", css_id="basic", ), Tab( _("Access"), InlineRadios( "access_control", template="%s/layout/radioselect_access.html", **VAR_143, ), css_id="access", ), Tab( _("Workflow"), "set_language_team", "use_shared_tm", "contribute_shared_tm", "enable_hooks", "language_aliases", "translation_review", "source_review", css_id="workflow", ), Tab( _("Components"), ContextDiv( template="snippets/VAR_58-VAR_9-settings.html", VAR_87={"object": self.instance, "user": VAR_8.user}, ), css_id="components", ), template="layout/pills.html", ) ) if settings.OFFER_HOSTING: self.fields["contribute_shared_tm"].widget = forms.HiddenInput() self.fields["use_shared_tm"].help_text = _( "Uses and contributes to the pool of shared translations " "between projects." ) self.fields["access_control"].choices = [ choice for choice in self.fields["access_control"].choices if choice[0] != Project.ACCESS_CUSTOM ] class CLASS_55(CLASS_33, CLASS_37): class CLASS_82: VAR_120 = Project VAR_121 = ["slug"] class CLASS_56(CLASS_33, CLASS_37, CLASS_40): VAR_81 = forms.ModelChoiceField( VAR_134=_("Billing"), VAR_90=User.objects.none(), VAR_113=True, empty_label=None, ) class CLASS_82: VAR_120 = Project VAR_121 = ("name", "slug", "web", "instructions") class CLASS_57(forms.Form): VAR_35 = CLASS_5( VAR_113=False, help_text=_("Optional additional filter on the strings") ) VAR_82 = forms.CharField( VAR_134=_("Search string"), VAR_25=1, VAR_113=True, strip=False, help_text=_("Case sensitive string to VAR_82 for and replace."), ) VAR_83 = forms.CharField( VAR_134=_("Replacement string"), VAR_25=1, VAR_113=True, strip=False ) def __init__(self, *VAR_6, **VAR_7): VAR_7["auto_id"] = "id_replace_%s" super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( SearchField("q"), Field("search"), Field("replacement"), Div(template="snippets/replace-help.html"), ) class CLASS_58(forms.Form): VAR_84 = forms.ModelMultipleChoiceField(VAR_90=Unit.objects.none(), VAR_113=False) VAR_85 = forms.BooleanField(VAR_113=True, VAR_11=True, widget=forms.HiddenInput) def __init__(self, VAR_84, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.fields["units"].queryset = VAR_84 class CLASS_59(forms.Form): VAR_59 = forms.MultipleChoiceField( VAR_134=_("Languages"), VAR_68=[], widget=forms.SelectMultiple ) def __init__(self, VAR_9, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) VAR_118 = Language.objects.filter(translation__component=VAR_9).exclude( pk=VAR_9.source_language_id ) self.fields["lang"].choices = VAR_118.as_choices() class CLASS_60(forms.Form): VAR_86 = forms.ModelChoiceField( Unit.objects.none(), widget=forms.HiddenInput, VAR_113=False, ) def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.translation = VAR_5 self.fields["variant"].queryset = VAR_5.unit_set.all() self.user = VAR_4 def FUNC_4(self): try: VAR_10 = self.as_kwargs() except KeyError: return self.translation.validate_new_unit_data(**VAR_10) def FUNC_34(self): return "" def FUNC_35(self): VAR_128 = Flags() VAR_128.merge(self.get_glossary_flags()) VAR_86 = self.cleaned_data.get("variant") if VAR_86: VAR_128.set_value("variant", VAR_86.source) return { "context": self.cleaned_data.get("context", ""), "source": self.cleaned_data["source"], "target": self.cleaned_data.get("target"), "extra_flags": VAR_128.format(), "explanation": self.cleaned_data.get("explanation", ""), "auto_context": self.cleaned_data.get("auto_context", False), } class CLASS_61(CLASS_60): VAR_87 = forms.CharField( VAR_134=_("Translation key"), help_text=_( "Key used to identify string in VAR_5 VAR_37. " "File VAR_36 specific rules might apply." ), VAR_113=True, ) VAR_19 = CLASS_8( VAR_134=_("Source VAR_16 text"), help_text=_( "You can edit this later, as with any other string in " "the VAR_19 VAR_16." ), VAR_113=True, ) def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): super().__init__(VAR_5, VAR_4, *VAR_6, **VAR_7) self.fields["context"].widget.attrs["tabindex"] = 99 self.fields["source"].widget.attrs["tabindex"] = 100 self.fields["source"].widget.profile = VAR_4.profile self.fields["source"].initial = Unit(VAR_5=translation, id_hash=0) class CLASS_62(CLASS_60): VAR_87 = forms.CharField( VAR_134=_("Context"), help_text=_("Optional VAR_87 to clarify the VAR_19 strings."), VAR_113=False, ) VAR_88 = forms.BooleanField( VAR_113=False, VAR_11=True, VAR_134=_("Automatically adjust VAR_87 when same string already exists."), ) VAR_19 = CLASS_8( VAR_134=_("Source string"), VAR_113=True, ) def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): super().__init__(VAR_5, VAR_4, *VAR_6, **VAR_7) self.fields["context"].widget.attrs["tabindex"] = 99 self.fields["context"].label = VAR_5.component.context_label self.fields["source"].widget.attrs["tabindex"] = 100 self.fields["source"].widget.profile = VAR_4.profile self.fields["source"].initial = Unit( VAR_5=VAR_5.component.source_translation, id_hash=0 ) class CLASS_63(CLASS_62): VAR_31 = CLASS_8( VAR_134=_("Translated string"), help_text=_( "You can edit this later, as with any other string in the VAR_5." ), VAR_113=True, ) def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): super().__init__(VAR_5, VAR_4, *VAR_6, **VAR_7) self.fields["target"].widget.attrs["tabindex"] = 101 self.fields["target"].widget.profile = VAR_4.profile self.fields["target"].initial = Unit(VAR_5=translation, id_hash=0) class CLASS_64(GlossaryAddMixin, CLASS_62): def __init__(self, VAR_5, VAR_4, *VAR_6, **VAR_7): if VAR_7["initial"] is None: VAR_7["initial"] = {} VAR_7["initial"]["terminology"] = True super().__init__(VAR_5, VAR_4, *VAR_6, **VAR_7) class CLASS_65(GlossaryAddMixin, CLASS_63): pass def FUNC_2(VAR_5, VAR_4, VAR_10=None, VAR_11=None): if VAR_5.component.has_template(): return CLASS_61(VAR_5, VAR_4, VAR_10=data, VAR_11=initial) if VAR_5.component.is_glossary: if VAR_5.is_source: return CLASS_64( VAR_5, VAR_4, VAR_10=data, VAR_11=initial ) return CLASS_65( VAR_5, VAR_4, VAR_10=data, VAR_11=initial ) if VAR_5.is_source: return CLASS_62(VAR_5, VAR_4, VAR_10=data, VAR_11=initial) return CLASS_63(VAR_5, VAR_4, VAR_10=data, VAR_11=initial) class CLASS_66(ModelChoiceIterator): def __iter__(self): if self.field.empty_label is not None: yield ("", self.field.empty_label) for VAR_55 in self.queryset: yield self.choice(VAR_55) def __len__(self): return len(self.queryset) + (1 if self.field.empty_label is not None else 0) def __bool__(self): return self.field.empty_label is not None or bool(self.queryset) class CLASS_67(forms.ModelMultipleChoiceField): VAR_89 = CLASS_66 def FUNC_36(self): return self._queryset def FUNC_37(self, VAR_90): self._queryset = VAR_90 self.widget.choices = self.choices VAR_90 = property(FUNC_36, FUNC_37) class CLASS_68(forms.Form): VAR_35 = CLASS_5(VAR_113=True) VAR_91 = forms.ChoiceField( VAR_134=_("State to set"), VAR_68=((-1, _("Do not change")),) + STATE_CHOICES ) VAR_92 = CLASS_6(VAR_134=_("Translation VAR_128 to add"), VAR_113=False) VAR_93 = CLASS_6(VAR_134=_("Translation VAR_128 to remove"), VAR_113=False) VAR_94 = CLASS_67( VAR_90=Label.objects.none(), VAR_134=_("Labels to add"), widget=forms.CheckboxSelectMultiple(), VAR_113=False, ) VAR_95 = CLASS_67( VAR_90=Label.objects.none(), VAR_134=_("Labels to remove"), widget=forms.CheckboxSelectMultiple(), VAR_113=False, ) def __init__(self, VAR_4, VAR_55, *VAR_6, **VAR_7): VAR_58 = VAR_7.pop("project") VAR_7["auto_id"] = "id_bulk_%s" super().__init__(*VAR_6, **VAR_7) VAR_129 = VAR_58.label_set.all() if VAR_129: self.fields["remove_labels"].queryset = VAR_129 self.fields["add_labels"].queryset = VAR_129 VAR_130 = {STATE_EMPTY, STATE_READONLY} if VAR_4 is not None and not VAR_4.has_perm("unit.review", VAR_55): VAR_130.add(STATE_APPROVED) self.fields["state"].choices = [ x for x in self.fields["state"].choices if x[0] not in VAR_130 ] self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div(template="snippets/bulk-help.html"), SearchField("q"), Field("state"), Field("add_flags"), Field("remove_flags"), ) if VAR_129: self.helper.layout.append(InlineCheckboxes("add_labels")) self.helper.layout.append(InlineCheckboxes("remove_labels")) class CLASS_69(forms.Form): VAR_85 = forms.BooleanField( VAR_134=_("I accept the contributor agreement"), VAR_113=True ) VAR_96 = forms.CharField(VAR_113=False, widget=forms.HiddenInput) class CLASS_70(forms.Form): VAR_85 = forms.CharField(VAR_113=True) VAR_97 = "" def __init__(self, VAR_55, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.obj = VAR_55 self.helper = FormHelper(self) self.helper.layout = Layout( ContextDiv( template=self.warning_template, css_class="form-group", VAR_87={"object": VAR_55}, ), Field("confirm"), ) self.helper.form_tag = False def FUNC_4(self): if self.cleaned_data.get("confirm") != self.obj.full_slug: raise ValidationError( _("The VAR_69 does not match the one marked for deletion!") ) class CLASS_71(CLASS_70): VAR_85 = forms.CharField( VAR_134=_("Removal confirmation"), help_text=_("Please type in the full VAR_69 of the VAR_5 to VAR_85."), VAR_113=True, ) VAR_97 = "trans/delete-VAR_5.html" class CLASS_72(CLASS_70): VAR_85 = forms.CharField( VAR_134=_("Removal confirmation"), help_text=_("Please type in the full VAR_69 of the VAR_9 to VAR_85."), VAR_113=True, ) VAR_97 = "trans/delete-VAR_9.html" class CLASS_73(CLASS_70): VAR_85 = forms.CharField( VAR_134=_("Removal confirmation"), help_text=_("Please type in the VAR_69 of the VAR_58 to VAR_85."), VAR_113=True, ) VAR_97 = "trans/delete-VAR_58.html" class CLASS_74(CLASS_70): VAR_85 = forms.CharField( VAR_134=_("Removal confirmation"), help_text=_("Please type in the VAR_69 of the VAR_58 and VAR_16 to VAR_85."), VAR_113=True, ) VAR_97 = "trans/delete-VAR_58-VAR_16.html" class CLASS_75(forms.ModelForm): class CLASS_82: VAR_120 = Announcement VAR_121 = ["message", "category", "expiry", "notify"] VAR_122 = { "expiry": CLASS_1(), "message": CLASS_0, } class CLASS_76(forms.Form): VAR_58 = forms.ChoiceField(VAR_134=_("Project"), VAR_68=[("", "")], VAR_113=False) VAR_59 = forms.ChoiceField(VAR_134=_("Language"), VAR_68=[("", "")], VAR_113=False) VAR_98 = forms.MultipleChoiceField( VAR_134=_("Action"), VAR_113=False, widget=SortedSelectMultiple, VAR_68=Change.ACTION_CHOICES, ) VAR_4 = UsernameField(VAR_134=_("Author username"), VAR_113=False, help_text=None) VAR_66 = CLASS_2( VAR_134=_("Starting date"), VAR_113=False, VAR_12=False ) VAR_67 = CLASS_2( VAR_134=_("Ending date"), VAR_113=False, VAR_12=False ) def __init__(self, VAR_8, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.fields["lang"].choices += Language.objects.have_translation().as_choices() self.fields["project"].choices += [ (VAR_58.slug, VAR_58.name) for VAR_58 in VAR_8.user.allowed_projects ] class CLASS_77(forms.ModelForm): class CLASS_82: VAR_120 = Label VAR_121 = ("name", "color") VAR_122 = {"color": ColorWidget()} def __init__(self, *VAR_6, **VAR_7): super().__init__(*VAR_6, **VAR_7) self.helper = FormHelper(self) self.helper.form_tag = False class CLASS_78(forms.Form): VAR_99 = forms.ModelChoiceField( ProjectToken.objects.none(), widget=forms.HiddenInput, VAR_113=True, ) def __init__(self, VAR_58, *VAR_6, **VAR_7): self.project = VAR_58 super().__init__(*VAR_6, **VAR_7) self.fields["token"].queryset = VAR_58.projecttoken_set.all() class CLASS_79(forms.ModelForm): class CLASS_82: VAR_120 = ProjectToken VAR_121 = ["name", "expires", "project"] VAR_122 = { "expires": CLASS_1(), "project": forms.HiddenInput, } def __init__(self, VAR_58, *VAR_6, **VAR_7): self.project = VAR_58 VAR_7["initial"] = {"project": VAR_58} super().__init__(*VAR_6, **VAR_7) def FUNC_38(self): if self.project != self.cleaned_data["project"]: raise ValidationError("Invalid VAR_58!") return self.cleaned_data["project"] def FUNC_39(self): VAR_131 = self.cleaned_data["expires"] VAR_131 = expires.replace(hour=23, minute=59, second=59, microsecond=999999) if VAR_131 < timezone.now(): raise forms.ValidationError(gettext("Expiry cannot be in the past!")) return VAR_131 class CLASS_80(forms.Form): VAR_100 = forms.ModelChoiceField( Group.objects.none(), widget=forms.HiddenInput, VAR_113=True, ) def __init__(self, VAR_58, *VAR_6, **VAR_7): self.project = VAR_58 super().__init__(*VAR_6, **VAR_7) self.fields["group"].queryset = VAR_58.defined_groups.all() class CLASS_81(CLASS_29): VAR_101 = forms.ModelMultipleChoiceField( Group.objects.none(), widget=forms.CheckboxSelectMultiple, VAR_134=_("Teams"), VAR_113=False, ) def __init__(self, VAR_58, *VAR_6, **VAR_7): self.project = VAR_58 super().__init__(*VAR_6, **VAR_7) self.fields["user"].widget = forms.HiddenInput() self.fields["groups"].queryset = VAR_58.defined_groups.all()
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 25, 45, 92, 108, 109, 118, 119, 127, 128, 134, 143, 144, 147, 151, 160, 161, 172, 173, 181, 193, 194, 197, 198, 201, 205, 208, 209, 222, 225, 229, 230, 252, 257, 258, 272, 274, 276, 279, 281, 290, 291, 302, 303, 308, 317, 318, 320, 339, 340, 348, 349, 351, 361, 362, 365, 368, 372, 376, 382, 383, 394, 399, 400, 403, 405, 409, 414, 416, 425, 426, 431, 432, 435, 444, 445, 448, 472, 497, 518, 521, 522, 526, 528, 536, 544, 557, 558, 561, 570, 571, 581, 590, 591, 594, 619, 624, 628, 635, 636, 639, 654, 655, 658, 661, 662, 676, 684, 685, 688, 689, 695, 701, 724, 728, 731, 736, 739, 743, 747, 751, 755, 763, 767, 770, 778, 779, 783, 784, 787, 789, 803, 809, 810, 813, 815, 827, 828, 831, 872, 877, 878, 887, 888, 890, 904, 908, 914, 916, 920, 929, 959, 960, 963, 991, 994, 997, 998, 1001, 1004, 1008, 1015, 1016, 1019, 1023, 1028, 1034, 1035, 1038, 1040, 1046, 1052, 1054, 1056, 1057, 1065, 1066, 1075, 1081, 1084, 1106, 1113, 1114, 1122, 1123, 1141, 1142, 1171, 1187, 1190, 1193, 1194, 1214, 1221, 1228, 1232, 1233, 1251, 1252, 1255, 1259, 1265, 1266, 1271, 1277, 1283, 1284, 1288, 1289, 1294, 1295, 1300, 1301, 1306, 1307, 1313, 1314, 1320, 1325, 1326, 1331, 1383, 1506, 1518, 1523, 1524, 1527, 1554, 1555, 1571, 1577, 1578, 1585, 1592, 1593, 1596, 1599, 1603, 1608, 1616, 1625, 1626, 1634, 1635, 1646, 1651, 1657, 1672, 1673, 1682, 1686, 1687, 1694, 1696, 1700, 1701, 1707, 1709, 1713, 1714, 1717, 1721, 1748, 1753, 1759, 1760, 1766, 1769, 1770, 1778, 1790, 1797, 1802, 1821, 1828, 1834, 1835, 1838, 1842, 1843, 1846, 1850, 1854, 1855, 1858, 1879, 1891, 1893, 1917, 1927, 1984, 1996, 1997, 2000, 2004, 2005, 2008, 2009, 2010, 2017, 2021, 2022, 2037, 2049, 2050, 2054, 2058, 2059, 2062, 2066, 2073, 2074, 2081, 2087, 2092, 2095, 2098, 2113, 2114, 2132, 2139, 2140, 2156, 2166, 2167, 2176, 2182, 2183, 2190, 2191, 2194, 2195, 2210, 2211, 2215, 2218, 2224, 2227, 2230, 2231, 2234, 2237, 2241, 2243, 2244, 2264, 2273, 2277, 2278, 2282, 2295, 2296, 2302, 2303, 2307, 2321, 2327, 2328, 2336, 2337, 2345, 2346, 2354, 2355, 2363, 2364, 2367, 2375, 2376, 2393, 2400, 2401, 2407, 2412, 2413, 2420, 2425, 2426, 2435, 2440, 2445, 2452, 2453, 2460, 2465, 2466, 2474, 2480, 146, 200, 364, 365, 366, 367, 402, 447, 593, 638, 657, 664, 687, 786, 812, 830, 962, 1000, 1018, 1037, 1059, 1254, 1330, 1526, 1716, 1717, 1718, 1719, 1720, 1837, 1845, 1857, 1999, 2007, 2061, 2213, 2214, 2215, 2216, 2217, 2366, 136, 254, 283, 353, 374, 411, 630, 697, 726, 772, 874, 1006 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 25, 46, 93, 109, 110, 119, 120, 128, 129, 135, 144, 145, 148, 152, 161, 162, 173, 174, 182, 194, 195, 198, 199, 202, 206, 209, 210, 223, 226, 230, 231, 253, 258, 259, 273, 275, 277, 280, 282, 291, 292, 303, 304, 309, 318, 319, 321, 340, 341, 349, 350, 352, 362, 363, 366, 369, 373, 377, 383, 384, 395, 400, 401, 404, 406, 410, 415, 417, 426, 427, 432, 433, 436, 445, 446, 449, 473, 498, 519, 522, 523, 527, 529, 537, 545, 558, 559, 562, 571, 572, 582, 591, 592, 595, 620, 625, 629, 636, 637, 640, 655, 656, 659, 662, 663, 677, 685, 686, 689, 690, 696, 702, 725, 729, 732, 737, 740, 744, 748, 752, 756, 764, 768, 771, 779, 780, 784, 785, 788, 790, 804, 810, 811, 814, 816, 828, 829, 832, 873, 878, 879, 888, 889, 891, 905, 909, 915, 917, 921, 930, 960, 961, 964, 992, 995, 998, 999, 1002, 1005, 1009, 1016, 1017, 1020, 1024, 1029, 1035, 1036, 1039, 1041, 1047, 1053, 1055, 1057, 1058, 1066, 1067, 1076, 1082, 1085, 1107, 1114, 1115, 1123, 1124, 1142, 1143, 1172, 1188, 1191, 1194, 1195, 1215, 1222, 1229, 1233, 1234, 1252, 1253, 1256, 1260, 1266, 1267, 1272, 1278, 1284, 1285, 1289, 1290, 1295, 1296, 1301, 1302, 1307, 1308, 1314, 1315, 1321, 1326, 1327, 1332, 1384, 1507, 1519, 1524, 1525, 1528, 1555, 1556, 1572, 1578, 1579, 1586, 1593, 1594, 1597, 1600, 1604, 1609, 1617, 1626, 1627, 1635, 1636, 1647, 1652, 1658, 1673, 1674, 1683, 1687, 1688, 1695, 1697, 1701, 1702, 1708, 1710, 1714, 1715, 1718, 1722, 1749, 1754, 1760, 1761, 1767, 1770, 1771, 1779, 1791, 1798, 1803, 1822, 1829, 1835, 1836, 1839, 1843, 1844, 1847, 1851, 1855, 1856, 1859, 1880, 1892, 1894, 1918, 1928, 1985, 1997, 1998, 2001, 2005, 2006, 2009, 2010, 2011, 2018, 2022, 2023, 2038, 2050, 2051, 2055, 2059, 2060, 2063, 2067, 2074, 2075, 2082, 2088, 2093, 2096, 2099, 2114, 2115, 2133, 2140, 2141, 2157, 2167, 2168, 2177, 2183, 2184, 2191, 2192, 2195, 2196, 2211, 2212, 2216, 2219, 2225, 2228, 2231, 2232, 2235, 2238, 2242, 2244, 2245, 2265, 2274, 2278, 2279, 2283, 2296, 2297, 2303, 2304, 2308, 2322, 2328, 2329, 2337, 2338, 2346, 2347, 2355, 2356, 2364, 2365, 2368, 2376, 2377, 2394, 2401, 2402, 2408, 2413, 2414, 2421, 2426, 2427, 2436, 2441, 2446, 2453, 2454, 2461, 2466, 2467, 2475, 2481, 147, 201, 365, 366, 367, 368, 403, 448, 594, 639, 658, 665, 688, 787, 813, 831, 963, 1001, 1019, 1038, 1060, 1255, 1331, 1527, 1717, 1718, 1719, 1720, 1721, 1838, 1846, 1858, 2000, 2008, 2062, 2214, 2215, 2216, 2217, 2218, 2367, 137, 255, 284, 354, 375, 412, 631, 698, 727, 773, 875, 1007 ]
1CWE-79
from typing import Any, List import bleach from .rest_api import ValidationError allowed_tags_strict = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "del", "ins", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables "div", ] allowed_tags_permissive = allowed_tags_strict + [ "video", ] def allow_all(tag: str, name: str, value: str) -> bool: return True allowed_attributes = allow_all allowed_styles = [ "color", "background-color", "height", "width", "text-align", "vertical-align", "float", "text-decoration", "margin", "padding", "line-height", "max-width", "min-width", "max-height", "min-height", "overflow", "word-break", "word-wrap", ] def validate_html_strict(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ return base_validate_html(html, allowed_tags_strict) def validate_html_permissive(html: str) -> str: """ See validate_html_strict, but allows some more tags, like iframes and videos. Do not use on validation for normal users, only for admins! """ return base_validate_html(html, allowed_tags_permissive) def base_validate_html(html: str, allowed_tags: List[str]) -> str: """ For internal use only. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles ) def validate_json(json: Any, max_depth: int) -> Any: """ Traverses through the JSON structure (dicts and lists) and runs validate_html_strict on every found string. Give max-depth to protect against stack-overflows. This should be the maximum nested depth of the object expected. """ if max_depth == 0: raise ValidationError({"detail": "The JSON is too nested."}) if isinstance(json, dict): return {key: validate_json(value, max_depth - 1) for key, value in json.items()} if isinstance(json, list): return [validate_json(item, max_depth - 1) for item in json] if isinstance(json, str): return validate_html_strict(json) return json
from typing import Any, List import bleach from .rest_api import ValidationError allowed_tags_strict = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "del", "ins", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables "div", ] allowed_tags_permissive = allowed_tags_strict + [ "video", ] allowed_attributes = [ "align", "alt", "autoplay", "background", "bgcolor", "border", "class", "colspan", "controls", "dir", "height", "hidden", "href", "hreflang", "id", "lang", "loop", "muted", "poster", "preload", "rel", "rowspan", "scope", "sizes", "src", "srcset", "start", "style", "target", "title", "width", ] allowed_styles = [ "color", "background-color", "height", "width", "text-align", "vertical-align", "float", "text-decoration", "margin", "padding", "line-height", "max-width", "min-width", "max-height", "min-height", "overflow", "word-break", "word-wrap", ] def validate_html_strict(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ return base_validate_html(html, allowed_tags_strict) def validate_html_permissive(html: str) -> str: """ See validate_html_strict, but allows some more tags, like iframes and videos. Do not use on validation for normal users, only for admins! """ return base_validate_html(html, allowed_tags_permissive) def base_validate_html(html: str, allowed_tags: List[str]) -> str: """ For internal use only. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles ) def validate_json(json: Any, max_depth: int) -> Any: """ Traverses through the JSON structure (dicts and lists) and runs validate_html_strict on every found string. Give max-depth to protect against stack-overflows. This should be the maximum nested depth of the object expected. """ if max_depth == 0: raise ValidationError({"detail": "The JSON is too nested."}) if isinstance(json, dict): return {key: validate_json(value, max_depth - 1) for key, value in json.items()} if isinstance(json, list): return [validate_json(item, max_depth - 1) for item in json] if isinstance(json, str): return validate_html_strict(json) return json
xss
{ "code": [ "def allow_all(tag: str, name: str, value: str) -> bool:", " return True", "allowed_attributes = allow_all" ], "line_no": [ 47, 48, 51 ] }
{ "code": [ " \"align\",", " \"alt\",", " \"background\",", " \"bgcolor\",", " \"border\",", " \"class\",", " \"colspan\",", " \"controls\",", " \"dir\",", " \"height\",", " \"hidden\",", " \"href\",", " \"hreflang\",", " \"id\",", " \"lang\",", " \"loop\",", " \"muted\",", " \"poster\",", " \"preload\",", " \"rel\",", " \"rowspan\",", " \"scope\",", " \"sizes\",", " \"src\",", " \"start\",", " \"style\",", " \"title\",", "]" ], "line_no": [ 47, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 73, 74, 76, 78 ] }
from typing import Any, List import bleach from .rest_api import ValidationError VAR_0 = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "del", "ins", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables "div", ] VAR_1 = VAR_0 + [ "video", ] def FUNC_0(VAR_2: str, VAR_3: str, VAR_4: str) -> bool: return True VAR_5 = FUNC_0 VAR_6 = [ "color", "background-color", "height", "width", "text-align", "vertical-align", "float", "text-decoration", "margin", "padding", "line-height", "max-width", "min-width", "max-height", "min-height", "overflow", "word-break", "word-wrap", ] def FUNC_1(VAR_7: str) -> str: return FUNC_3(VAR_7, VAR_0) def FUNC_2(VAR_7: str) -> str: return FUNC_3(VAR_7, VAR_1) def FUNC_3(VAR_7: str, VAR_8: List[str]) -> str: VAR_7 = html.replace("\t", "") return bleach.clean( VAR_7, tags=VAR_8, attributes=VAR_5, styles=VAR_6 ) def FUNC_4(VAR_9: Any, VAR_10: int) -> Any: if VAR_10 == 0: raise ValidationError({"detail": "The JSON is too nested."}) if isinstance(VAR_9, dict): return {key: FUNC_4(VAR_4, VAR_10 - 1) for key, VAR_4 in VAR_9.items()} if isinstance(VAR_9, list): return [FUNC_4(item, VAR_10 - 1) for item in VAR_9] if isinstance(VAR_9, str): return FUNC_1(VAR_9) return VAR_9
from typing import Any, List import bleach from .rest_api import ValidationError VAR_0 = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "del", "ins", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables "div", ] VAR_1 = VAR_0 + [ "video", ] VAR_2 = [ "align", "alt", "autoplay", "background", "bgcolor", "border", "class", "colspan", "controls", "dir", "height", "hidden", "href", "hreflang", "id", "lang", "loop", "muted", "poster", "preload", "rel", "rowspan", "scope", "sizes", "src", "srcset", "start", "style", "target", "title", "width", ] VAR_3 = [ "color", "background-color", "height", "width", "text-align", "vertical-align", "float", "text-decoration", "margin", "padding", "line-height", "max-width", "min-width", "max-height", "min-height", "overflow", "word-break", "word-wrap", ] def FUNC_0(VAR_4: str) -> str: return FUNC_2(VAR_4, VAR_0) def FUNC_1(VAR_4: str) -> str: return FUNC_2(VAR_4, VAR_1) def FUNC_2(VAR_4: str, VAR_5: List[str]) -> str: VAR_4 = html.replace("\t", "") return bleach.clean( VAR_4, tags=VAR_5, attributes=VAR_2, styles=VAR_3 ) def FUNC_3(VAR_6: Any, VAR_7: int) -> Any: if VAR_7 == 0: raise ValidationError({"detail": "The JSON is too nested."}) if isinstance(VAR_6, dict): return {key: FUNC_3(value, VAR_7 - 1) for key, value in VAR_6.items()} if isinstance(VAR_6, list): return [FUNC_3(item, VAR_7 - 1) for item in VAR_6] if isinstance(VAR_6, str): return FUNC_0(VAR_6) return VAR_6
[ 2, 4, 6, 7, 45, 46, 49, 50, 72, 73, 81, 82, 89, 90, 99, 100, 105, 109, 112, 119, 121, 75, 76, 77, 78, 79, 84, 85, 86, 87, 92, 93, 94, 102, 103, 104, 105, 106, 107, 108 ]
[ 2, 4, 6, 7, 45, 79, 100, 101, 109, 110, 117, 118, 127, 128, 133, 137, 140, 147, 149, 103, 104, 105, 106, 107, 112, 113, 114, 115, 120, 121, 122, 130, 131, 132, 133, 134, 135, 136 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cgi import logging import random import sys import urllib.parse from io import BytesIO from typing import Callable, Dict, List, Optional, Tuple, Union import attr import treq from canonicaljson import encode_canonical_json from prometheus_client import Counter from signedjson.sign import sign_json from zope.interface import implementer from twisted.internet import defer from twisted.internet.error import DNSLookupError from twisted.internet.interfaces import IReactorPluggableNameResolver, IReactorTime from twisted.internet.task import _EPSILON, Cooperator from twisted.web.http_headers import Headers from twisted.web.iweb import IBodyProducer, IResponse import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( FederationDeniedError, HttpResponseException, RequestSendFailed, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, IPBlacklistingResolver, encode_query_args, readBodyToFile, ) from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.logging.context import make_deferred_yieldable from synapse.logging.opentracing import ( inject_active_span_byte_dict, set_tag, start_active_span, tags, ) from synapse.types import JsonDict from synapse.util import json_decoder from synapse.util.async_helpers import timeout_deferred from synapse.util.metrics import Measure logger = logging.getLogger(__name__) outgoing_requests_counter = Counter( "synapse_http_matrixfederationclient_requests", "", ["method"] ) incoming_responses_counter = Counter( "synapse_http_matrixfederationclient_responses", "", ["method", "code"] ) MAX_LONG_RETRIES = 10 MAX_SHORT_RETRIES = 3 MAXINT = sys.maxsize _next_id = 1 QueryArgs = Dict[str, Union[str, List[str]]] @attr.s(slots=True, frozen=True) class MatrixFederationRequest: method = attr.ib(type=str) """HTTP method """ path = attr.ib(type=str) """HTTP path """ destination = attr.ib(type=str) """The remote server to send the HTTP request to. """ json = attr.ib(default=None, type=Optional[JsonDict]) """JSON to send in the body. """ json_callback = attr.ib(default=None, type=Optional[Callable[[], JsonDict]]) """A callback to generate the JSON. """ query = attr.ib(default=None, type=Optional[dict]) """Query arguments. """ txn_id = attr.ib(default=None, type=Optional[str]) """Unique ID for this request (for logging) """ uri = attr.ib(init=False, type=bytes) """The URI of this request """ def __attrs_post_init__(self) -> None: global _next_id txn_id = "%s-O-%s" % (self.method, _next_id) _next_id = (_next_id + 1) % (MAXINT - 1) object.__setattr__(self, "txn_id", txn_id) destination_bytes = self.destination.encode("ascii") path_bytes = self.path.encode("ascii") if self.query: query_bytes = encode_query_args(self.query) else: query_bytes = b"" # The object is frozen so we can pre-compute this. uri = urllib.parse.urlunparse( (b"matrix", destination_bytes, path_bytes, None, query_bytes, b"") ) object.__setattr__(self, "uri", uri) def get_json(self) -> Optional[JsonDict]: if self.json_callback: return self.json_callback() return self.json async def _handle_json_response( reactor: IReactorTime, timeout_sec: float, request: MatrixFederationRequest, response: IResponse, start_ms: int, ) -> JsonDict: """ Reads the JSON body of a response, with a timeout Args: reactor: twisted reactor, for the timeout timeout_sec: number of seconds to wait for response to complete request: the request that triggered the response response: response to the request start_ms: Timestamp when request was made Returns: The parsed JSON response """ try: check_content_type_is_json(response.headers) # Use the custom JSON decoder (partially re-implements treq.json_content). d = treq.text_content(response, encoding="utf-8") d.addCallback(json_decoder.decode) d = timeout_deferred(d, timeout=timeout_sec, reactor=reactor) body = await make_deferred_yieldable(d) except defer.TimeoutError as e: logger.warning( "{%s} [%s] Timed out reading response - %s %s", request.txn_id, request.destination, request.method, request.uri.decode("ascii"), ) raise RequestSendFailed(e, can_retry=True) from e except Exception as e: logger.warning( "{%s} [%s] Error reading response %s %s: %s", request.txn_id, request.destination, request.method, request.uri.decode("ascii"), e, ) raise time_taken_secs = reactor.seconds() - start_ms / 1000 logger.info( "{%s} [%s] Completed request: %d %s in %.2f secs - %s %s", request.txn_id, request.destination, response.code, response.phrase.decode("ascii", errors="replace"), time_taken_secs, request.method, request.uri.decode("ascii"), ) return body class MatrixFederationHttpClient: """HTTP client used to talk to other homeservers over the federation protocol. Send client certificates and signs requests. Attributes: agent (twisted.web.client.Agent): The twisted Agent used to send the requests. """ def __init__(self, hs, tls_client_options_factory): self.hs = hs self.signing_key = hs.signing_key self.server_name = hs.hostname real_reactor = hs.get_reactor() # We need to use a DNS resolver which filters out blacklisted IP # addresses, to prevent DNS rebinding. nameResolver = IPBlacklistingResolver( real_reactor, None, hs.config.federation_ip_range_blacklist ) @implementer(IReactorPluggableNameResolver) class Reactor: def __getattr__(_self, attr): if attr == "nameResolver": return nameResolver else: return getattr(real_reactor, attr) self.reactor = Reactor() user_agent = hs.version_string if hs.config.user_agent_suffix: user_agent = "%s %s" % (user_agent, hs.config.user_agent_suffix) user_agent = user_agent.encode("ascii") self.agent = MatrixFederationAgent( self.reactor, tls_client_options_factory, user_agent ) # Use a BlacklistingAgentWrapper to prevent circumventing the IP # blacklist via IP literals in server names self.agent = BlacklistingAgentWrapper( self.agent, ip_blacklist=hs.config.federation_ip_range_blacklist, ) self.clock = hs.get_clock() self._store = hs.get_datastore() self.version_string_bytes = hs.version_string.encode("ascii") self.default_timeout = 60 def schedule(x): self.reactor.callLater(_EPSILON, x) self._cooperator = Cooperator(scheduler=schedule) async def _send_request_with_optional_trailing_slash( self, request: MatrixFederationRequest, try_trailing_slash_on_400: bool = False, **send_request_args ) -> IResponse: """Wrapper for _send_request which can optionally retry the request upon receiving a combination of a 400 HTTP response code and a 'M_UNRECOGNIZED' errcode. This is a workaround for Synapse <= v0.99.3 due to #3622. Args: request: details of request to be sent try_trailing_slash_on_400: Whether on receiving a 400 'M_UNRECOGNIZED' from the server to retry the request with a trailing slash appended to the request path. send_request_args: A dictionary of arguments to pass to `_send_request()`. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). Returns: Parsed JSON response body. """ try: response = await self._send_request(request, **send_request_args) except HttpResponseException as e: # Received an HTTP error > 300. Check if it meets the requirements # to retry with a trailing slash if not try_trailing_slash_on_400: raise if e.code != 400 or e.to_synapse_error().errcode != "M_UNRECOGNIZED": raise # Retry with a trailing slash if we received a 400 with # 'M_UNRECOGNIZED' which some endpoints can return when omitting a # trailing slash on Synapse <= v0.99.3. logger.info("Retrying request with trailing slash") # Request is frozen so we create a new instance request = attr.evolve(request, path=request.path + "/") response = await self._send_request(request, **send_request_args) return response async def _send_request( self, request: MatrixFederationRequest, retry_on_dns_fail: bool = True, timeout: Optional[int] = None, long_retries: bool = False, ignore_backoff: bool = False, backoff_on_404: bool = False, ) -> IResponse: """ Sends a request to the given server. Args: request: details of request to be sent retry_on_dns_fail: true if the request should be retied on DNS failures timeout: number of milliseconds to wait for the response headers (including connecting to the server), *for each attempt*. 60s by default. long_retries: whether to use the long retry algorithm. The regular retry algorithm makes 4 attempts, with intervals [0.5s, 1s, 2s]. The long retry algorithm makes 11 attempts, with intervals [4s, 16s, 60s, 60s, ...] Both algorithms add -20%/+40% jitter to the retry intervals. Note that the above intervals are *in addition* to the time spent waiting for the request to complete (up to `timeout` ms). NB: the long retry algorithm takes over 20 minutes to complete, with a default timeout of 60s! ignore_backoff: true to ignore the historical backoff data and try the request anyway. backoff_on_404: Back off if we get a 404 Returns: Resolves with the HTTP response object on success. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ if timeout: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout if ( self.hs.config.federation_domain_whitelist is not None and request.destination not in self.hs.config.federation_domain_whitelist ): raise FederationDeniedError(request.destination) limiter = await synapse.util.retryutils.get_retry_limiter( request.destination, self.clock, self._store, backoff_on_404=backoff_on_404, ignore_backoff=ignore_backoff, ) method_bytes = request.method.encode("ascii") destination_bytes = request.destination.encode("ascii") path_bytes = request.path.encode("ascii") if request.query: query_bytes = encode_query_args(request.query) else: query_bytes = b"" scope = start_active_span( "outgoing-federation-request", tags={ tags.SPAN_KIND: tags.SPAN_KIND_RPC_CLIENT, tags.PEER_ADDRESS: request.destination, tags.HTTP_METHOD: request.method, tags.HTTP_URL: request.path, }, finish_on_close=True, ) # Inject the span into the headers headers_dict = {} # type: Dict[bytes, List[bytes]] inject_active_span_byte_dict(headers_dict, request.destination) headers_dict[b"User-Agent"] = [self.version_string_bytes] with limiter, scope: # XXX: Would be much nicer to retry only at the transaction-layer # (once we have reliable transactions in place) if long_retries: retries_left = MAX_LONG_RETRIES else: retries_left = MAX_SHORT_RETRIES url_bytes = request.uri url_str = url_bytes.decode("ascii") url_to_sign_bytes = urllib.parse.urlunparse( (b"", b"", path_bytes, None, query_bytes, b"") ) while True: try: json = request.get_json() if json: headers_dict[b"Content-Type"] = [b"application/json"] auth_headers = self.build_auth_headers( destination_bytes, method_bytes, url_to_sign_bytes, json ) data = encode_canonical_json(json) producer = QuieterFileBodyProducer( BytesIO(data), cooperator=self._cooperator ) # type: Optional[IBodyProducer] else: producer = None auth_headers = self.build_auth_headers( destination_bytes, method_bytes, url_to_sign_bytes ) headers_dict[b"Authorization"] = auth_headers logger.debug( "{%s} [%s] Sending request: %s %s; timeout %fs", request.txn_id, request.destination, request.method, url_str, _sec_timeout, ) outgoing_requests_counter.labels(request.method).inc() try: with Measure(self.clock, "outbound_request"): # we don't want all the fancy cookie and redirect handling # that treq.request gives: just use the raw Agent. request_deferred = self.agent.request( method_bytes, url_bytes, headers=Headers(headers_dict), bodyProducer=producer, ) request_deferred = timeout_deferred( request_deferred, timeout=_sec_timeout, reactor=self.reactor, ) response = await request_deferred except DNSLookupError as e: raise RequestSendFailed(e, can_retry=retry_on_dns_fail) from e except Exception as e: raise RequestSendFailed(e, can_retry=True) from e incoming_responses_counter.labels( request.method, response.code ).inc() set_tag(tags.HTTP_STATUS_CODE, response.code) response_phrase = response.phrase.decode("ascii", errors="replace") if 200 <= response.code < 300: logger.debug( "{%s} [%s] Got response headers: %d %s", request.txn_id, request.destination, response.code, response_phrase, ) pass else: logger.info( "{%s} [%s] Got response headers: %d %s", request.txn_id, request.destination, response.code, response_phrase, ) # :'( # Update transactions table? d = treq.content(response) d = timeout_deferred( d, timeout=_sec_timeout, reactor=self.reactor ) try: body = await make_deferred_yieldable(d) except Exception as e: # Eh, we're already going to raise an exception so lets # ignore if this fails. logger.warning( "{%s} [%s] Failed to get error response: %s %s: %s", request.txn_id, request.destination, request.method, url_str, _flatten_response_never_received(e), ) body = None exc = HttpResponseException( response.code, response_phrase, body ) # Retry if the error is a 429 (Too Many Requests), # otherwise just raise a standard HttpResponseException if response.code == 429: raise RequestSendFailed(exc, can_retry=True) from exc else: raise exc break except RequestSendFailed as e: logger.info( "{%s} [%s] Request failed: %s %s: %s", request.txn_id, request.destination, request.method, url_str, _flatten_response_never_received(e.inner_exception), ) if not e.can_retry: raise if retries_left and not timeout: if long_retries: delay = 4 ** (MAX_LONG_RETRIES + 1 - retries_left) delay = min(delay, 60) delay *= random.uniform(0.8, 1.4) else: delay = 0.5 * 2 ** (MAX_SHORT_RETRIES - retries_left) delay = min(delay, 2) delay *= random.uniform(0.8, 1.4) logger.debug( "{%s} [%s] Waiting %ss before re-sending...", request.txn_id, request.destination, delay, ) await self.clock.sleep(delay) retries_left -= 1 else: raise except Exception as e: logger.warning( "{%s} [%s] Request failed: %s %s: %s", request.txn_id, request.destination, request.method, url_str, _flatten_response_never_received(e), ) raise return response def build_auth_headers( self, destination: Optional[bytes], method: bytes, url_bytes: bytes, content: Optional[JsonDict] = None, destination_is: Optional[bytes] = None, ) -> List[bytes]: """ Builds the Authorization headers for a federation request Args: destination: The destination homeserver of the request. May be None if the destination is an identity server, in which case destination_is must be non-None. method: The HTTP method of the request url_bytes: The URI path of the request content: The body of the request destination_is: As 'destination', but if the destination is an identity server Returns: A list of headers to be added as "Authorization:" headers """ request = { "method": method.decode("ascii"), "uri": url_bytes.decode("ascii"), "origin": self.server_name, } if destination is not None: request["destination"] = destination.decode("ascii") if destination_is is not None: request["destination_is"] = destination_is.decode("ascii") if content is not None: request["content"] = content request = sign_json(request, self.server_name, self.signing_key) auth_headers = [] for key, sig in request["signatures"][self.server_name].items(): auth_headers.append( ( 'X-Matrix origin=%s,key="%s",sig="%s"' % (self.server_name, key, sig) ).encode("ascii") ) return auth_headers async def put_json( self, destination: str, path: str, args: Optional[QueryArgs] = None, data: Optional[JsonDict] = None, json_data_callback: Optional[Callable[[], JsonDict]] = None, long_retries: bool = False, timeout: Optional[int] = None, ignore_backoff: bool = False, backoff_on_404: bool = False, try_trailing_slash_on_400: bool = False, ) -> Union[JsonDict, list]: """ Sends the specified json data using PUT Args: destination: The remote server to send the HTTP request to. path: The HTTP path. args: query params data: A dict containing the data that will be used as the request body. This will be encoded as JSON. json_data_callback: A callable returning the dict to use as the request body. long_retries: whether to use the long retry algorithm. See docs on _send_request for details. timeout: number of milliseconds to wait for the response. self._default_timeout (60s) by default. Note that we may make several attempts to send the request; this timeout applies to the time spent waiting for response headers for *each* attempt (including connection time) as well as the time spent reading the response body after a 200 response. ignore_backoff: true to ignore the historical backoff data and try the request anyway. backoff_on_404: True if we should count a 404 response as a failure of the server (and should therefore back off future requests). try_trailing_slash_on_400: True if on a 400 M_UNRECOGNIZED response we should try appending a trailing slash to the end of the request. Workaround for #3622 in Synapse <= v0.99.3. This will be attempted before backing off if backing off has been enabled. Returns: Succeeds when we get a 2xx HTTP response. The result will be the decoded JSON body. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="PUT", destination=destination, path=path, query=args, json_callback=json_data_callback, json=data, ) start_ms = self.clock.time_msec() response = await self._send_request_with_optional_trailing_slash( request, try_trailing_slash_on_400, backoff_on_404=backoff_on_404, ignore_backoff=ignore_backoff, long_retries=long_retries, timeout=timeout, ) if timeout is not None: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout body = await _handle_json_response( self.reactor, _sec_timeout, request, response, start_ms ) return body async def post_json( self, destination: str, path: str, data: Optional[JsonDict] = None, long_retries: bool = False, timeout: Optional[int] = None, ignore_backoff: bool = False, args: Optional[QueryArgs] = None, ) -> Union[JsonDict, list]: """ Sends the specified json data using POST Args: destination: The remote server to send the HTTP request to. path: The HTTP path. data: A dict containing the data that will be used as the request body. This will be encoded as JSON. long_retries: whether to use the long retry algorithm. See docs on _send_request for details. timeout: number of milliseconds to wait for the response. self._default_timeout (60s) by default. Note that we may make several attempts to send the request; this timeout applies to the time spent waiting for response headers for *each* attempt (including connection time) as well as the time spent reading the response body after a 200 response. ignore_backoff: true to ignore the historical backoff data and try the request anyway. args: query params Returns: dict|list: Succeeds when we get a 2xx HTTP response. The result will be the decoded JSON body. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="POST", destination=destination, path=path, query=args, json=data ) start_ms = self.clock.time_msec() response = await self._send_request( request, long_retries=long_retries, timeout=timeout, ignore_backoff=ignore_backoff, ) if timeout: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout body = await _handle_json_response( self.reactor, _sec_timeout, request, response, start_ms, ) return body async def get_json( self, destination: str, path: str, args: Optional[QueryArgs] = None, retry_on_dns_fail: bool = True, timeout: Optional[int] = None, ignore_backoff: bool = False, try_trailing_slash_on_400: bool = False, ) -> Union[JsonDict, list]: """ GETs some json from the given host homeserver and path Args: destination: The remote server to send the HTTP request to. path: The HTTP path. args: A dictionary used to create query strings, defaults to None. timeout: number of milliseconds to wait for the response. self._default_timeout (60s) by default. Note that we may make several attempts to send the request; this timeout applies to the time spent waiting for response headers for *each* attempt (including connection time) as well as the time spent reading the response body after a 200 response. ignore_backoff: true to ignore the historical backoff data and try the request anyway. try_trailing_slash_on_400: True if on a 400 M_UNRECOGNIZED response we should try appending a trailing slash to the end of the request. Workaround for #3622 in Synapse <= v0.99.3. Returns: Succeeds when we get a 2xx HTTP response. The result will be the decoded JSON body. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="GET", destination=destination, path=path, query=args ) start_ms = self.clock.time_msec() response = await self._send_request_with_optional_trailing_slash( request, try_trailing_slash_on_400, backoff_on_404=False, ignore_backoff=ignore_backoff, retry_on_dns_fail=retry_on_dns_fail, timeout=timeout, ) if timeout is not None: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout body = await _handle_json_response( self.reactor, _sec_timeout, request, response, start_ms ) return body async def delete_json( self, destination: str, path: str, long_retries: bool = False, timeout: Optional[int] = None, ignore_backoff: bool = False, args: Optional[QueryArgs] = None, ) -> Union[JsonDict, list]: """Send a DELETE request to the remote expecting some json response Args: destination: The remote server to send the HTTP request to. path: The HTTP path. long_retries: whether to use the long retry algorithm. See docs on _send_request for details. timeout: number of milliseconds to wait for the response. self._default_timeout (60s) by default. Note that we may make several attempts to send the request; this timeout applies to the time spent waiting for response headers for *each* attempt (including connection time) as well as the time spent reading the response body after a 200 response. ignore_backoff: true to ignore the historical backoff data and try the request anyway. args: query params Returns: Succeeds when we get a 2xx HTTP response. The result will be the decoded JSON body. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="DELETE", destination=destination, path=path, query=args ) start_ms = self.clock.time_msec() response = await self._send_request( request, long_retries=long_retries, timeout=timeout, ignore_backoff=ignore_backoff, ) if timeout is not None: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout body = await _handle_json_response( self.reactor, _sec_timeout, request, response, start_ms ) return body async def get_file( self, destination: str, path: str, output_stream, args: Optional[QueryArgs] = None, retry_on_dns_fail: bool = True, max_size: Optional[int] = None, ignore_backoff: bool = False, ) -> Tuple[int, Dict[bytes, List[bytes]]]: """GETs a file from a given homeserver Args: destination: The remote server to send the HTTP request to. path: The HTTP path to GET. output_stream: File to write the response body to. args: Optional dictionary used to create the query string. ignore_backoff: true to ignore the historical backoff data and try the request anyway. Returns: Resolves with an (int,dict) tuple of the file length and a dict of the response headers. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="GET", destination=destination, path=path, query=args ) response = await self._send_request( request, retry_on_dns_fail=retry_on_dns_fail, ignore_backoff=ignore_backoff ) headers = dict(response.headers.getAllRawHeaders()) try: d = readBodyToFile(response, output_stream, max_size) d.addTimeout(self.default_timeout, self.reactor) length = await make_deferred_yieldable(d) except Exception as e: logger.warning( "{%s} [%s] Error reading response: %s", request.txn_id, request.destination, e, ) raise logger.info( "{%s} [%s] Completed: %d %s [%d bytes] %s %s", request.txn_id, request.destination, response.code, response.phrase.decode("ascii", errors="replace"), length, request.method, request.uri.decode("ascii"), ) return (length, headers) def _flatten_response_never_received(e): if hasattr(e, "reasons"): reasons = ", ".join( _flatten_response_never_received(f.value) for f in e.reasons ) return "%s:[%s]" % (type(e).__name__, reasons) else: return repr(e) def check_content_type_is_json(headers: Headers) -> None: """ Check that a set of HTTP headers have a Content-Type header, and that it is application/json. Args: headers: headers to check Raises: RequestSendFailed: if the Content-Type header is missing or isn't JSON """ c_type = headers.getRawHeaders(b"Content-Type") if c_type is None: raise RequestSendFailed( RuntimeError("No Content-Type header received from remote server"), can_retry=False, ) c_type = c_type[0].decode("ascii") # only the first header val, options = cgi.parse_header(c_type) if val != "application/json": raise RequestSendFailed( RuntimeError( "Remote server sent Content-Type header of '%s', not 'application/json'" % c_type, ), can_retry=False, )
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cgi import logging import random import sys import urllib.parse from io import BytesIO from typing import Callable, Dict, List, Optional, Tuple, Union import attr import treq from canonicaljson import encode_canonical_json from prometheus_client import Counter from signedjson.sign import sign_json from twisted.internet import defer from twisted.internet.error import DNSLookupError from twisted.internet.interfaces import IReactorTime from twisted.internet.task import _EPSILON, Cooperator from twisted.web.http_headers import Headers from twisted.web.iweb import IBodyProducer, IResponse import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( FederationDeniedError, HttpResponseException, RequestSendFailed, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, BlacklistingReactorWrapper, encode_query_args, readBodyToFile, ) from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.logging.context import make_deferred_yieldable from synapse.logging.opentracing import ( inject_active_span_byte_dict, set_tag, start_active_span, tags, ) from synapse.types import JsonDict from synapse.util import json_decoder from synapse.util.async_helpers import timeout_deferred from synapse.util.metrics import Measure logger = logging.getLogger(__name__) outgoing_requests_counter = Counter( "synapse_http_matrixfederationclient_requests", "", ["method"] ) incoming_responses_counter = Counter( "synapse_http_matrixfederationclient_responses", "", ["method", "code"] ) MAX_LONG_RETRIES = 10 MAX_SHORT_RETRIES = 3 MAXINT = sys.maxsize _next_id = 1 QueryArgs = Dict[str, Union[str, List[str]]] @attr.s(slots=True, frozen=True) class MatrixFederationRequest: method = attr.ib(type=str) """HTTP method """ path = attr.ib(type=str) """HTTP path """ destination = attr.ib(type=str) """The remote server to send the HTTP request to. """ json = attr.ib(default=None, type=Optional[JsonDict]) """JSON to send in the body. """ json_callback = attr.ib(default=None, type=Optional[Callable[[], JsonDict]]) """A callback to generate the JSON. """ query = attr.ib(default=None, type=Optional[dict]) """Query arguments. """ txn_id = attr.ib(default=None, type=Optional[str]) """Unique ID for this request (for logging) """ uri = attr.ib(init=False, type=bytes) """The URI of this request """ def __attrs_post_init__(self) -> None: global _next_id txn_id = "%s-O-%s" % (self.method, _next_id) _next_id = (_next_id + 1) % (MAXINT - 1) object.__setattr__(self, "txn_id", txn_id) destination_bytes = self.destination.encode("ascii") path_bytes = self.path.encode("ascii") if self.query: query_bytes = encode_query_args(self.query) else: query_bytes = b"" # The object is frozen so we can pre-compute this. uri = urllib.parse.urlunparse( (b"matrix", destination_bytes, path_bytes, None, query_bytes, b"") ) object.__setattr__(self, "uri", uri) def get_json(self) -> Optional[JsonDict]: if self.json_callback: return self.json_callback() return self.json async def _handle_json_response( reactor: IReactorTime, timeout_sec: float, request: MatrixFederationRequest, response: IResponse, start_ms: int, ) -> JsonDict: """ Reads the JSON body of a response, with a timeout Args: reactor: twisted reactor, for the timeout timeout_sec: number of seconds to wait for response to complete request: the request that triggered the response response: response to the request start_ms: Timestamp when request was made Returns: The parsed JSON response """ try: check_content_type_is_json(response.headers) # Use the custom JSON decoder (partially re-implements treq.json_content). d = treq.text_content(response, encoding="utf-8") d.addCallback(json_decoder.decode) d = timeout_deferred(d, timeout=timeout_sec, reactor=reactor) body = await make_deferred_yieldable(d) except defer.TimeoutError as e: logger.warning( "{%s} [%s] Timed out reading response - %s %s", request.txn_id, request.destination, request.method, request.uri.decode("ascii"), ) raise RequestSendFailed(e, can_retry=True) from e except Exception as e: logger.warning( "{%s} [%s] Error reading response %s %s: %s", request.txn_id, request.destination, request.method, request.uri.decode("ascii"), e, ) raise time_taken_secs = reactor.seconds() - start_ms / 1000 logger.info( "{%s} [%s] Completed request: %d %s in %.2f secs - %s %s", request.txn_id, request.destination, response.code, response.phrase.decode("ascii", errors="replace"), time_taken_secs, request.method, request.uri.decode("ascii"), ) return body class MatrixFederationHttpClient: """HTTP client used to talk to other homeservers over the federation protocol. Send client certificates and signs requests. Attributes: agent (twisted.web.client.Agent): The twisted Agent used to send the requests. """ def __init__(self, hs, tls_client_options_factory): self.hs = hs self.signing_key = hs.signing_key self.server_name = hs.hostname # We need to use a DNS resolver which filters out blacklisted IP # addresses, to prevent DNS rebinding. self.reactor = BlacklistingReactorWrapper( hs.get_reactor(), None, hs.config.federation_ip_range_blacklist ) user_agent = hs.version_string if hs.config.user_agent_suffix: user_agent = "%s %s" % (user_agent, hs.config.user_agent_suffix) user_agent = user_agent.encode("ascii") self.agent = MatrixFederationAgent( self.reactor, tls_client_options_factory, user_agent, hs.config.federation_ip_range_blacklist, ) # Use a BlacklistingAgentWrapper to prevent circumventing the IP # blacklist via IP literals in server names self.agent = BlacklistingAgentWrapper( self.agent, ip_blacklist=hs.config.federation_ip_range_blacklist, ) self.clock = hs.get_clock() self._store = hs.get_datastore() self.version_string_bytes = hs.version_string.encode("ascii") self.default_timeout = 60 def schedule(x): self.reactor.callLater(_EPSILON, x) self._cooperator = Cooperator(scheduler=schedule) async def _send_request_with_optional_trailing_slash( self, request: MatrixFederationRequest, try_trailing_slash_on_400: bool = False, **send_request_args ) -> IResponse: """Wrapper for _send_request which can optionally retry the request upon receiving a combination of a 400 HTTP response code and a 'M_UNRECOGNIZED' errcode. This is a workaround for Synapse <= v0.99.3 due to #3622. Args: request: details of request to be sent try_trailing_slash_on_400: Whether on receiving a 400 'M_UNRECOGNIZED' from the server to retry the request with a trailing slash appended to the request path. send_request_args: A dictionary of arguments to pass to `_send_request()`. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). Returns: Parsed JSON response body. """ try: response = await self._send_request(request, **send_request_args) except HttpResponseException as e: # Received an HTTP error > 300. Check if it meets the requirements # to retry with a trailing slash if not try_trailing_slash_on_400: raise if e.code != 400 or e.to_synapse_error().errcode != "M_UNRECOGNIZED": raise # Retry with a trailing slash if we received a 400 with # 'M_UNRECOGNIZED' which some endpoints can return when omitting a # trailing slash on Synapse <= v0.99.3. logger.info("Retrying request with trailing slash") # Request is frozen so we create a new instance request = attr.evolve(request, path=request.path + "/") response = await self._send_request(request, **send_request_args) return response async def _send_request( self, request: MatrixFederationRequest, retry_on_dns_fail: bool = True, timeout: Optional[int] = None, long_retries: bool = False, ignore_backoff: bool = False, backoff_on_404: bool = False, ) -> IResponse: """ Sends a request to the given server. Args: request: details of request to be sent retry_on_dns_fail: true if the request should be retied on DNS failures timeout: number of milliseconds to wait for the response headers (including connecting to the server), *for each attempt*. 60s by default. long_retries: whether to use the long retry algorithm. The regular retry algorithm makes 4 attempts, with intervals [0.5s, 1s, 2s]. The long retry algorithm makes 11 attempts, with intervals [4s, 16s, 60s, 60s, ...] Both algorithms add -20%/+40% jitter to the retry intervals. Note that the above intervals are *in addition* to the time spent waiting for the request to complete (up to `timeout` ms). NB: the long retry algorithm takes over 20 minutes to complete, with a default timeout of 60s! ignore_backoff: true to ignore the historical backoff data and try the request anyway. backoff_on_404: Back off if we get a 404 Returns: Resolves with the HTTP response object on success. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ if timeout: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout if ( self.hs.config.federation_domain_whitelist is not None and request.destination not in self.hs.config.federation_domain_whitelist ): raise FederationDeniedError(request.destination) limiter = await synapse.util.retryutils.get_retry_limiter( request.destination, self.clock, self._store, backoff_on_404=backoff_on_404, ignore_backoff=ignore_backoff, ) method_bytes = request.method.encode("ascii") destination_bytes = request.destination.encode("ascii") path_bytes = request.path.encode("ascii") if request.query: query_bytes = encode_query_args(request.query) else: query_bytes = b"" scope = start_active_span( "outgoing-federation-request", tags={ tags.SPAN_KIND: tags.SPAN_KIND_RPC_CLIENT, tags.PEER_ADDRESS: request.destination, tags.HTTP_METHOD: request.method, tags.HTTP_URL: request.path, }, finish_on_close=True, ) # Inject the span into the headers headers_dict = {} # type: Dict[bytes, List[bytes]] inject_active_span_byte_dict(headers_dict, request.destination) headers_dict[b"User-Agent"] = [self.version_string_bytes] with limiter, scope: # XXX: Would be much nicer to retry only at the transaction-layer # (once we have reliable transactions in place) if long_retries: retries_left = MAX_LONG_RETRIES else: retries_left = MAX_SHORT_RETRIES url_bytes = request.uri url_str = url_bytes.decode("ascii") url_to_sign_bytes = urllib.parse.urlunparse( (b"", b"", path_bytes, None, query_bytes, b"") ) while True: try: json = request.get_json() if json: headers_dict[b"Content-Type"] = [b"application/json"] auth_headers = self.build_auth_headers( destination_bytes, method_bytes, url_to_sign_bytes, json ) data = encode_canonical_json(json) producer = QuieterFileBodyProducer( BytesIO(data), cooperator=self._cooperator ) # type: Optional[IBodyProducer] else: producer = None auth_headers = self.build_auth_headers( destination_bytes, method_bytes, url_to_sign_bytes ) headers_dict[b"Authorization"] = auth_headers logger.debug( "{%s} [%s] Sending request: %s %s; timeout %fs", request.txn_id, request.destination, request.method, url_str, _sec_timeout, ) outgoing_requests_counter.labels(request.method).inc() try: with Measure(self.clock, "outbound_request"): # we don't want all the fancy cookie and redirect handling # that treq.request gives: just use the raw Agent. request_deferred = self.agent.request( method_bytes, url_bytes, headers=Headers(headers_dict), bodyProducer=producer, ) request_deferred = timeout_deferred( request_deferred, timeout=_sec_timeout, reactor=self.reactor, ) response = await request_deferred except DNSLookupError as e: raise RequestSendFailed(e, can_retry=retry_on_dns_fail) from e except Exception as e: raise RequestSendFailed(e, can_retry=True) from e incoming_responses_counter.labels( request.method, response.code ).inc() set_tag(tags.HTTP_STATUS_CODE, response.code) response_phrase = response.phrase.decode("ascii", errors="replace") if 200 <= response.code < 300: logger.debug( "{%s} [%s] Got response headers: %d %s", request.txn_id, request.destination, response.code, response_phrase, ) pass else: logger.info( "{%s} [%s] Got response headers: %d %s", request.txn_id, request.destination, response.code, response_phrase, ) # :'( # Update transactions table? d = treq.content(response) d = timeout_deferred( d, timeout=_sec_timeout, reactor=self.reactor ) try: body = await make_deferred_yieldable(d) except Exception as e: # Eh, we're already going to raise an exception so lets # ignore if this fails. logger.warning( "{%s} [%s] Failed to get error response: %s %s: %s", request.txn_id, request.destination, request.method, url_str, _flatten_response_never_received(e), ) body = None exc = HttpResponseException( response.code, response_phrase, body ) # Retry if the error is a 429 (Too Many Requests), # otherwise just raise a standard HttpResponseException if response.code == 429: raise RequestSendFailed(exc, can_retry=True) from exc else: raise exc break except RequestSendFailed as e: logger.info( "{%s} [%s] Request failed: %s %s: %s", request.txn_id, request.destination, request.method, url_str, _flatten_response_never_received(e.inner_exception), ) if not e.can_retry: raise if retries_left and not timeout: if long_retries: delay = 4 ** (MAX_LONG_RETRIES + 1 - retries_left) delay = min(delay, 60) delay *= random.uniform(0.8, 1.4) else: delay = 0.5 * 2 ** (MAX_SHORT_RETRIES - retries_left) delay = min(delay, 2) delay *= random.uniform(0.8, 1.4) logger.debug( "{%s} [%s] Waiting %ss before re-sending...", request.txn_id, request.destination, delay, ) await self.clock.sleep(delay) retries_left -= 1 else: raise except Exception as e: logger.warning( "{%s} [%s] Request failed: %s %s: %s", request.txn_id, request.destination, request.method, url_str, _flatten_response_never_received(e), ) raise return response def build_auth_headers( self, destination: Optional[bytes], method: bytes, url_bytes: bytes, content: Optional[JsonDict] = None, destination_is: Optional[bytes] = None, ) -> List[bytes]: """ Builds the Authorization headers for a federation request Args: destination: The destination homeserver of the request. May be None if the destination is an identity server, in which case destination_is must be non-None. method: The HTTP method of the request url_bytes: The URI path of the request content: The body of the request destination_is: As 'destination', but if the destination is an identity server Returns: A list of headers to be added as "Authorization:" headers """ request = { "method": method.decode("ascii"), "uri": url_bytes.decode("ascii"), "origin": self.server_name, } if destination is not None: request["destination"] = destination.decode("ascii") if destination_is is not None: request["destination_is"] = destination_is.decode("ascii") if content is not None: request["content"] = content request = sign_json(request, self.server_name, self.signing_key) auth_headers = [] for key, sig in request["signatures"][self.server_name].items(): auth_headers.append( ( 'X-Matrix origin=%s,key="%s",sig="%s"' % (self.server_name, key, sig) ).encode("ascii") ) return auth_headers async def put_json( self, destination: str, path: str, args: Optional[QueryArgs] = None, data: Optional[JsonDict] = None, json_data_callback: Optional[Callable[[], JsonDict]] = None, long_retries: bool = False, timeout: Optional[int] = None, ignore_backoff: bool = False, backoff_on_404: bool = False, try_trailing_slash_on_400: bool = False, ) -> Union[JsonDict, list]: """ Sends the specified json data using PUT Args: destination: The remote server to send the HTTP request to. path: The HTTP path. args: query params data: A dict containing the data that will be used as the request body. This will be encoded as JSON. json_data_callback: A callable returning the dict to use as the request body. long_retries: whether to use the long retry algorithm. See docs on _send_request for details. timeout: number of milliseconds to wait for the response. self._default_timeout (60s) by default. Note that we may make several attempts to send the request; this timeout applies to the time spent waiting for response headers for *each* attempt (including connection time) as well as the time spent reading the response body after a 200 response. ignore_backoff: true to ignore the historical backoff data and try the request anyway. backoff_on_404: True if we should count a 404 response as a failure of the server (and should therefore back off future requests). try_trailing_slash_on_400: True if on a 400 M_UNRECOGNIZED response we should try appending a trailing slash to the end of the request. Workaround for #3622 in Synapse <= v0.99.3. This will be attempted before backing off if backing off has been enabled. Returns: Succeeds when we get a 2xx HTTP response. The result will be the decoded JSON body. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="PUT", destination=destination, path=path, query=args, json_callback=json_data_callback, json=data, ) start_ms = self.clock.time_msec() response = await self._send_request_with_optional_trailing_slash( request, try_trailing_slash_on_400, backoff_on_404=backoff_on_404, ignore_backoff=ignore_backoff, long_retries=long_retries, timeout=timeout, ) if timeout is not None: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout body = await _handle_json_response( self.reactor, _sec_timeout, request, response, start_ms ) return body async def post_json( self, destination: str, path: str, data: Optional[JsonDict] = None, long_retries: bool = False, timeout: Optional[int] = None, ignore_backoff: bool = False, args: Optional[QueryArgs] = None, ) -> Union[JsonDict, list]: """ Sends the specified json data using POST Args: destination: The remote server to send the HTTP request to. path: The HTTP path. data: A dict containing the data that will be used as the request body. This will be encoded as JSON. long_retries: whether to use the long retry algorithm. See docs on _send_request for details. timeout: number of milliseconds to wait for the response. self._default_timeout (60s) by default. Note that we may make several attempts to send the request; this timeout applies to the time spent waiting for response headers for *each* attempt (including connection time) as well as the time spent reading the response body after a 200 response. ignore_backoff: true to ignore the historical backoff data and try the request anyway. args: query params Returns: dict|list: Succeeds when we get a 2xx HTTP response. The result will be the decoded JSON body. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="POST", destination=destination, path=path, query=args, json=data ) start_ms = self.clock.time_msec() response = await self._send_request( request, long_retries=long_retries, timeout=timeout, ignore_backoff=ignore_backoff, ) if timeout: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout body = await _handle_json_response( self.reactor, _sec_timeout, request, response, start_ms, ) return body async def get_json( self, destination: str, path: str, args: Optional[QueryArgs] = None, retry_on_dns_fail: bool = True, timeout: Optional[int] = None, ignore_backoff: bool = False, try_trailing_slash_on_400: bool = False, ) -> Union[JsonDict, list]: """ GETs some json from the given host homeserver and path Args: destination: The remote server to send the HTTP request to. path: The HTTP path. args: A dictionary used to create query strings, defaults to None. timeout: number of milliseconds to wait for the response. self._default_timeout (60s) by default. Note that we may make several attempts to send the request; this timeout applies to the time spent waiting for response headers for *each* attempt (including connection time) as well as the time spent reading the response body after a 200 response. ignore_backoff: true to ignore the historical backoff data and try the request anyway. try_trailing_slash_on_400: True if on a 400 M_UNRECOGNIZED response we should try appending a trailing slash to the end of the request. Workaround for #3622 in Synapse <= v0.99.3. Returns: Succeeds when we get a 2xx HTTP response. The result will be the decoded JSON body. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="GET", destination=destination, path=path, query=args ) start_ms = self.clock.time_msec() response = await self._send_request_with_optional_trailing_slash( request, try_trailing_slash_on_400, backoff_on_404=False, ignore_backoff=ignore_backoff, retry_on_dns_fail=retry_on_dns_fail, timeout=timeout, ) if timeout is not None: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout body = await _handle_json_response( self.reactor, _sec_timeout, request, response, start_ms ) return body async def delete_json( self, destination: str, path: str, long_retries: bool = False, timeout: Optional[int] = None, ignore_backoff: bool = False, args: Optional[QueryArgs] = None, ) -> Union[JsonDict, list]: """Send a DELETE request to the remote expecting some json response Args: destination: The remote server to send the HTTP request to. path: The HTTP path. long_retries: whether to use the long retry algorithm. See docs on _send_request for details. timeout: number of milliseconds to wait for the response. self._default_timeout (60s) by default. Note that we may make several attempts to send the request; this timeout applies to the time spent waiting for response headers for *each* attempt (including connection time) as well as the time spent reading the response body after a 200 response. ignore_backoff: true to ignore the historical backoff data and try the request anyway. args: query params Returns: Succeeds when we get a 2xx HTTP response. The result will be the decoded JSON body. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="DELETE", destination=destination, path=path, query=args ) start_ms = self.clock.time_msec() response = await self._send_request( request, long_retries=long_retries, timeout=timeout, ignore_backoff=ignore_backoff, ) if timeout is not None: _sec_timeout = timeout / 1000 else: _sec_timeout = self.default_timeout body = await _handle_json_response( self.reactor, _sec_timeout, request, response, start_ms ) return body async def get_file( self, destination: str, path: str, output_stream, args: Optional[QueryArgs] = None, retry_on_dns_fail: bool = True, max_size: Optional[int] = None, ignore_backoff: bool = False, ) -> Tuple[int, Dict[bytes, List[bytes]]]: """GETs a file from a given homeserver Args: destination: The remote server to send the HTTP request to. path: The HTTP path to GET. output_stream: File to write the response body to. args: Optional dictionary used to create the query string. ignore_backoff: true to ignore the historical backoff data and try the request anyway. Returns: Resolves with an (int,dict) tuple of the file length and a dict of the response headers. Raises: HttpResponseException: If we get an HTTP response code >= 300 (except 429). NotRetryingDestination: If we are not yet ready to retry this server. FederationDeniedError: If this destination is not on our federation whitelist RequestSendFailed: If there were problems connecting to the remote, due to e.g. DNS failures, connection timeouts etc. """ request = MatrixFederationRequest( method="GET", destination=destination, path=path, query=args ) response = await self._send_request( request, retry_on_dns_fail=retry_on_dns_fail, ignore_backoff=ignore_backoff ) headers = dict(response.headers.getAllRawHeaders()) try: d = readBodyToFile(response, output_stream, max_size) d.addTimeout(self.default_timeout, self.reactor) length = await make_deferred_yieldable(d) except Exception as e: logger.warning( "{%s} [%s] Error reading response: %s", request.txn_id, request.destination, e, ) raise logger.info( "{%s} [%s] Completed: %d %s [%d bytes] %s %s", request.txn_id, request.destination, response.code, response.phrase.decode("ascii", errors="replace"), length, request.method, request.uri.decode("ascii"), ) return (length, headers) def _flatten_response_never_received(e): if hasattr(e, "reasons"): reasons = ", ".join( _flatten_response_never_received(f.value) for f in e.reasons ) return "%s:[%s]" % (type(e).__name__, reasons) else: return repr(e) def check_content_type_is_json(headers: Headers) -> None: """ Check that a set of HTTP headers have a Content-Type header, and that it is application/json. Args: headers: headers to check Raises: RequestSendFailed: if the Content-Type header is missing or isn't JSON """ c_type = headers.getRawHeaders(b"Content-Type") if c_type is None: raise RequestSendFailed( RuntimeError("No Content-Type header received from remote server"), can_retry=False, ) c_type = c_type[0].decode("ascii") # only the first header val, options = cgi.parse_header(c_type) if val != "application/json": raise RequestSendFailed( RuntimeError( "Remote server sent Content-Type header of '%s', not 'application/json'" % c_type, ), can_retry=False, )
open_redirect
{ "code": [ "from zope.interface import implementer", "from twisted.internet.interfaces import IReactorPluggableNameResolver, IReactorTime", " IPBlacklistingResolver,", " real_reactor = hs.get_reactor()", " nameResolver = IPBlacklistingResolver(", " real_reactor, None, hs.config.federation_ip_range_blacklist", " @implementer(IReactorPluggableNameResolver)", " class Reactor:", " def __getattr__(_self, attr):", " if attr == \"nameResolver\":", " return nameResolver", " else:", " return getattr(real_reactor, attr)", " self.reactor = Reactor()", " self.reactor, tls_client_options_factory, user_agent" ], "line_no": [ 29, 33, 48, 224, 228, 229, 232, 233, 234, 235, 236, 237, 238, 240, 248 ] }
{ "code": [ "from twisted.internet.interfaces import IReactorTime", " BlacklistingReactorWrapper,", " hs.get_reactor(), None, hs.config.federation_ip_range_blacklist", " self.reactor,", " tls_client_options_factory,", " user_agent,", " hs.config.federation_ip_range_blacklist," ], "line_no": [ 32, 47, 226, 235, 236, 237, 238 ] }
import cgi import logging import random import sys import urllib.parse from io import BytesIO from typing import Callable, Dict, List, Optional, Tuple, Union import .attr import treq from canonicaljson import .encode_canonical_json from prometheus_client import Counter from signedjson.sign import sign_json from zope.interface import implementer from twisted.internet import .defer from twisted.internet.error import DNSLookupError from twisted.internet.interfaces import IReactorPluggableNameResolver, IReactorTime from twisted.internet.task import _EPSILON, Cooperator from twisted.web.http_headers import Headers from twisted.web.iweb import IBodyProducer, IResponse import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( FederationDeniedError, HttpResponseException, RequestSendFailed, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, IPBlacklistingResolver, encode_query_args, readBodyToFile, ) from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.logging.context import make_deferred_yieldable from synapse.logging.opentracing import ( inject_active_span_byte_dict, set_tag, start_active_span, tags, ) from synapse.types import JsonDict from synapse.util import .json_decoder from synapse.util.async_helpers import .timeout_deferred from synapse.util.metrics import Measure VAR_0 = logging.getLogger(__name__) VAR_1 = Counter( "synapse_http_matrixfederationclient_requests", "", ["method"] ) VAR_2 = Counter( "synapse_http_matrixfederationclient_responses", "", ["method", "code"] ) VAR_3 = 10 VAR_4 = 3 VAR_5 = sys.maxsize VAR_6 = 1 VAR_7 = Dict[str, Union[str, List[str]]] @VAR_60.s(slots=True, frozen=True) class CLASS_0: VAR_15 = VAR_60.ib(type=str) """HTTP VAR_15 """ VAR_16 = VAR_60.ib(type=str) """HTTP VAR_16 """ VAR_17 = VAR_60.ib(type=str) """The remote server to send the HTTP VAR_10 to. """ VAR_18 = VAR_60.ib(default=None, type=Optional[JsonDict]) """JSON to send in the VAR_47. """ VAR_19 = VAR_60.ib(default=None, type=Optional[Callable[[], JsonDict]]) """A callback to generate the JSON. """ VAR_20 = VAR_60.ib(default=None, type=Optional[dict]) """Query arguments. """ VAR_21 = VAR_60.ib(default=None, type=Optional[str]) """Unique ID for this VAR_10 (for logging) """ VAR_22 = VAR_60.ib(init=False, type=bytes) """The URI of this VAR_10 """ def __attrs_post_init__(self) -> None: global VAR_6 VAR_21 = "%s-O-%s" % (self.method, VAR_6) _next_id = (VAR_6 + 1) % (VAR_5 - 1) object.__setattr__(self, "txn_id", VAR_21) VAR_44 = self.destination.encode("ascii") VAR_45 = self.path.encode("ascii") if self.query: VAR_58 = encode_query_args(self.query) else: VAR_58 = b"" VAR_22 = urllib.parse.urlunparse( (b"matrix", VAR_44, VAR_45, None, VAR_58, b"") ) object.__setattr__(self, "uri", VAR_22) def FUNC_3(self) -> Optional[JsonDict]: if self.json_callback: return self.json_callback() return self.json async def FUNC_0( VAR_8: IReactorTime, VAR_9: float, VAR_10: CLASS_0, VAR_11: IResponse, VAR_12: int, ) -> JsonDict: try: FUNC_2(VAR_11.headers) VAR_46 = treq.text_content(VAR_11, encoding="utf-8") VAR_46.addCallback(json_decoder.decode) VAR_46 = timeout_deferred(VAR_46, VAR_29=VAR_9, VAR_8=reactor) VAR_47 = await make_deferred_yieldable(VAR_46) except defer.TimeoutError as VAR_13: VAR_0.warning( "{%s} [%s] Timed out reading VAR_11 - %s %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_10.uri.decode("ascii"), ) raise RequestSendFailed(VAR_13, can_retry=True) from VAR_13 except Exception as VAR_13: VAR_0.warning( "{%s} [%s] Error reading VAR_11 %s %s: %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_10.uri.decode("ascii"), VAR_13, ) raise VAR_23 = VAR_8.seconds() - VAR_12 / 1000 VAR_0.info( "{%s} [%s] Completed VAR_10: %VAR_46 %s in %.2f secs - %s %s", VAR_10.txn_id, VAR_10.destination, VAR_11.code, VAR_11.phrase.decode("ascii", errors="replace"), VAR_23, VAR_10.method, VAR_10.uri.decode("ascii"), ) return VAR_47 class CLASS_1: def __init__(self, VAR_24, VAR_25): self.hs = VAR_24 self.signing_key = VAR_24.signing_key self.server_name = VAR_24.hostname VAR_48 = VAR_24.get_reactor() VAR_49 = IPBlacklistingResolver( VAR_48, None, VAR_24.config.federation_ip_range_blacklist ) @implementer(IReactorPluggableNameResolver) class CLASS_2: def __getattr__(VAR_59, VAR_60): if VAR_60 == "nameResolver": return VAR_49 else: return getattr(VAR_48, VAR_60) self.reactor = CLASS_2() VAR_50 = VAR_24.version_string if VAR_24.config.user_agent_suffix: VAR_50 = "%s %s" % (VAR_50, VAR_24.config.user_agent_suffix) VAR_50 = user_agent.encode("ascii") self.agent = MatrixFederationAgent( self.reactor, VAR_25, VAR_50 ) self.agent = BlacklistingAgentWrapper( self.agent, ip_blacklist=VAR_24.config.federation_ip_range_blacklist, ) self.clock = VAR_24.get_clock() self._store = VAR_24.get_datastore() self.version_string_bytes = VAR_24.version_string.encode("ascii") self.default_timeout = 60 def FUNC_11(VAR_51): self.reactor.callLater(_EPSILON, VAR_51) self._cooperator = Cooperator(scheduler=FUNC_11) async def FUNC_4( self, VAR_10: CLASS_0, VAR_26: bool = False, **VAR_27 ) -> IResponse: try: VAR_11 = await self._send_request(VAR_10, **VAR_27) except HttpResponseException as VAR_13: if not VAR_26: raise if VAR_13.code != 400 or VAR_13.to_synapse_error().errcode != "M_UNRECOGNIZED": raise VAR_0.info("Retrying VAR_10 with trailing slash") VAR_10 = VAR_60.evolve(VAR_10, VAR_16=VAR_10.path + "/") VAR_11 = await self._send_request(VAR_10, **VAR_27) return VAR_11 async def FUNC_5( self, VAR_10: CLASS_0, VAR_28: bool = True, VAR_29: Optional[int] = None, VAR_30: bool = False, VAR_31: bool = False, VAR_32: bool = False, ) -> IResponse: if VAR_29: VAR_61 = VAR_29 / 1000 else: VAR_61 = self.default_timeout if ( self.hs.config.federation_domain_whitelist is not None and VAR_10.destination not in self.hs.config.federation_domain_whitelist ): raise FederationDeniedError(VAR_10.destination) VAR_52 = await synapse.util.retryutils.get_retry_limiter( VAR_10.destination, self.clock, self._store, VAR_32=backoff_on_404, VAR_31=ignore_backoff, ) VAR_53 = VAR_10.method.encode("ascii") VAR_44 = VAR_10.destination.encode("ascii") VAR_45 = VAR_10.path.encode("ascii") if VAR_10.query: VAR_58 = encode_query_args(VAR_10.query) else: VAR_58 = b"" VAR_54 = start_active_span( "outgoing-federation-request", tags={ tags.SPAN_KIND: tags.SPAN_KIND_RPC_CLIENT, tags.PEER_ADDRESS: VAR_10.destination, tags.HTTP_METHOD: VAR_10.method, tags.HTTP_URL: VAR_10.path, }, finish_on_close=True, ) VAR_55 = {} # type: Dict[bytes, List[bytes]] inject_active_span_byte_dict(VAR_55, VAR_10.destination) VAR_55[b"User-Agent"] = [self.version_string_bytes] with VAR_52, VAR_54: if VAR_30: VAR_65 = VAR_3 else: VAR_65 = VAR_4 VAR_33 = VAR_10.uri VAR_62 = VAR_33.decode("ascii") VAR_63 = urllib.parse.urlunparse( (b"", b"", VAR_45, None, VAR_58, b"") ) while True: try: VAR_18 = VAR_10.get_json() if VAR_18: VAR_55[b"Content-Type"] = [b"application/json"] VAR_56 = self.build_auth_headers( VAR_44, VAR_53, VAR_63, VAR_18 ) VAR_37 = encode_canonical_json(VAR_18) VAR_67 = QuieterFileBodyProducer( BytesIO(VAR_37), cooperator=self._cooperator ) # type: Optional[IBodyProducer] else: VAR_67 = None VAR_56 = self.build_auth_headers( VAR_44, VAR_53, VAR_63 ) VAR_55[b"Authorization"] = VAR_56 VAR_0.debug( "{%s} [%s] Sending VAR_10: %s %s; VAR_29 %fs", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_62, VAR_61, ) VAR_1.labels(VAR_10.method).inc() try: with Measure(self.clock, "outbound_request"): VAR_69 = self.agent.request( VAR_53, VAR_33, VAR_14=Headers(VAR_55), bodyProducer=VAR_67, ) VAR_69 = timeout_deferred( VAR_69, VAR_29=VAR_61, VAR_8=self.reactor, ) VAR_11 = await VAR_69 except DNSLookupError as VAR_13: raise RequestSendFailed(VAR_13, can_retry=VAR_28) from VAR_13 except Exception as VAR_13: raise RequestSendFailed(VAR_13, can_retry=True) from VAR_13 VAR_2.labels( VAR_10.method, VAR_11.code ).inc() set_tag(tags.HTTP_STATUS_CODE, VAR_11.code) VAR_66 = VAR_11.phrase.decode("ascii", errors="replace") if 200 <= VAR_11.code < 300: VAR_0.debug( "{%s} [%s] Got VAR_11 VAR_14: %VAR_46 %s", VAR_10.txn_id, VAR_10.destination, VAR_11.code, VAR_66, ) pass else: VAR_0.info( "{%s} [%s] Got VAR_11 VAR_14: %VAR_46 %s", VAR_10.txn_id, VAR_10.destination, VAR_11.code, VAR_66, ) VAR_46 = treq.content(VAR_11) VAR_46 = timeout_deferred( VAR_46, VAR_29=VAR_61, VAR_8=self.reactor ) try: VAR_47 = await make_deferred_yieldable(VAR_46) except Exception as VAR_13: VAR_0.warning( "{%s} [%s] Failed to get error VAR_11: %s %s: %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_62, FUNC_1(VAR_13), ) VAR_47 = None VAR_68 = HttpResponseException( VAR_11.code, VAR_66, VAR_47 ) if VAR_11.code == 429: raise RequestSendFailed(VAR_68, can_retry=True) from VAR_68 else: raise VAR_68 break except RequestSendFailed as VAR_13: VAR_0.info( "{%s} [%s] Request failed: %s %s: %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_62, FUNC_1(VAR_13.inner_exception), ) if not VAR_13.can_retry: raise if VAR_65 and not VAR_29: if VAR_30: VAR_70 = 4 ** (VAR_3 + 1 - VAR_65) VAR_70 = min(VAR_70, 60) VAR_70 *= random.uniform(0.8, 1.4) else: VAR_70 = 0.5 * 2 ** (VAR_4 - VAR_65) VAR_70 = min(VAR_70, 2) VAR_70 *= random.uniform(0.8, 1.4) VAR_0.debug( "{%s} [%s] Waiting %ss before re-sending...", VAR_10.txn_id, VAR_10.destination, VAR_70, ) await self.clock.sleep(VAR_70) VAR_65 -= 1 else: raise except Exception as VAR_13: VAR_0.warning( "{%s} [%s] Request failed: %s %s: %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_62, FUNC_1(VAR_13), ) raise return VAR_11 def FUNC_6( self, VAR_17: Optional[bytes], VAR_15: bytes, VAR_33: bytes, VAR_34: Optional[JsonDict] = None, VAR_35: Optional[bytes] = None, ) -> List[bytes]: VAR_10 = { "method": VAR_15.decode("ascii"), "uri": VAR_33.decode("ascii"), "origin": self.server_name, } if VAR_17 is not None: VAR_10["destination"] = VAR_17.decode("ascii") if VAR_35 is not None: VAR_10["destination_is"] = VAR_35.decode("ascii") if VAR_34 is not None: VAR_10["content"] = VAR_34 VAR_10 = sign_json(VAR_10, self.server_name, self.signing_key) VAR_56 = [] for key, sig in VAR_10["signatures"][self.server_name].items(): VAR_56.append( ( 'X-Matrix origin=%s,key="%s",sig="%s"' % (self.server_name, key, sig) ).encode("ascii") ) return VAR_56 async def FUNC_7( self, VAR_17: str, VAR_16: str, VAR_36: Optional[VAR_7] = None, VAR_37: Optional[JsonDict] = None, VAR_38: Optional[Callable[[], JsonDict]] = None, VAR_30: bool = False, VAR_29: Optional[int] = None, VAR_31: bool = False, VAR_32: bool = False, VAR_26: bool = False, ) -> Union[JsonDict, list]: VAR_10 = CLASS_0( VAR_15="PUT", VAR_17=destination, VAR_16=path, VAR_20=VAR_36, VAR_19=VAR_38, VAR_18=VAR_37, ) VAR_12 = self.clock.time_msec() VAR_11 = await self._send_request_with_optional_trailing_slash( VAR_10, VAR_26, VAR_32=backoff_on_404, VAR_31=ignore_backoff, VAR_30=long_retries, VAR_29=timeout, ) if VAR_29 is not None: VAR_61 = VAR_29 / 1000 else: VAR_61 = self.default_timeout VAR_47 = await FUNC_0( self.reactor, VAR_61, VAR_10, VAR_11, VAR_12 ) return VAR_47 async def FUNC_8( self, VAR_17: str, VAR_16: str, VAR_37: Optional[JsonDict] = None, VAR_30: bool = False, VAR_29: Optional[int] = None, VAR_31: bool = False, VAR_36: Optional[VAR_7] = None, ) -> Union[JsonDict, list]: VAR_10 = CLASS_0( VAR_15="POST", VAR_17=destination, VAR_16=path, VAR_20=VAR_36, VAR_18=VAR_37 ) VAR_12 = self.clock.time_msec() VAR_11 = await self._send_request( VAR_10, VAR_30=long_retries, VAR_29=timeout, VAR_31=ignore_backoff, ) if VAR_29: VAR_61 = VAR_29 / 1000 else: VAR_61 = self.default_timeout VAR_47 = await FUNC_0( self.reactor, VAR_61, VAR_10, VAR_11, VAR_12, ) return VAR_47 async def FUNC_3( self, VAR_17: str, VAR_16: str, VAR_36: Optional[VAR_7] = None, VAR_28: bool = True, VAR_29: Optional[int] = None, VAR_31: bool = False, VAR_26: bool = False, ) -> Union[JsonDict, list]: VAR_10 = CLASS_0( VAR_15="GET", VAR_17=destination, VAR_16=path, VAR_20=VAR_36 ) VAR_12 = self.clock.time_msec() VAR_11 = await self._send_request_with_optional_trailing_slash( VAR_10, VAR_26, VAR_32=False, VAR_31=ignore_backoff, VAR_28=retry_on_dns_fail, VAR_29=timeout, ) if VAR_29 is not None: VAR_61 = VAR_29 / 1000 else: VAR_61 = self.default_timeout VAR_47 = await FUNC_0( self.reactor, VAR_61, VAR_10, VAR_11, VAR_12 ) return VAR_47 async def FUNC_9( self, VAR_17: str, VAR_16: str, VAR_30: bool = False, VAR_29: Optional[int] = None, VAR_31: bool = False, VAR_36: Optional[VAR_7] = None, ) -> Union[JsonDict, list]: VAR_10 = CLASS_0( VAR_15="DELETE", VAR_17=destination, VAR_16=path, VAR_20=VAR_36 ) VAR_12 = self.clock.time_msec() VAR_11 = await self._send_request( VAR_10, VAR_30=long_retries, VAR_29=timeout, VAR_31=ignore_backoff, ) if VAR_29 is not None: VAR_61 = VAR_29 / 1000 else: VAR_61 = self.default_timeout VAR_47 = await FUNC_0( self.reactor, VAR_61, VAR_10, VAR_11, VAR_12 ) return VAR_47 async def FUNC_10( self, VAR_17: str, VAR_16: str, VAR_39, VAR_36: Optional[VAR_7] = None, VAR_28: bool = True, VAR_40: Optional[int] = None, VAR_31: bool = False, ) -> Tuple[int, Dict[bytes, List[bytes]]]: VAR_10 = CLASS_0( VAR_15="GET", VAR_17=destination, VAR_16=path, VAR_20=VAR_36 ) VAR_11 = await self._send_request( VAR_10, VAR_28=retry_on_dns_fail, VAR_31=ignore_backoff ) VAR_14 = dict(VAR_11.headers.getAllRawHeaders()) try: VAR_46 = readBodyToFile(VAR_11, VAR_39, VAR_40) VAR_46.addTimeout(self.default_timeout, self.reactor) VAR_64 = await make_deferred_yieldable(VAR_46) except Exception as VAR_13: VAR_0.warning( "{%s} [%s] Error reading VAR_11: %s", VAR_10.txn_id, VAR_10.destination, VAR_13, ) raise VAR_0.info( "{%s} [%s] Completed: %VAR_46 %s [%VAR_46 bytes] %s %s", VAR_10.txn_id, VAR_10.destination, VAR_11.code, VAR_11.phrase.decode("ascii", errors="replace"), VAR_64, VAR_10.method, VAR_10.uri.decode("ascii"), ) return (VAR_64, VAR_14) def FUNC_1(VAR_13): if hasattr(VAR_13, "reasons"): VAR_57 = ", ".join( FUNC_1(f.value) for f in VAR_13.reasons ) return "%s:[%s]" % (type(VAR_13).__name__, VAR_57) else: return repr(VAR_13) def FUNC_2(VAR_14: Headers) -> None: VAR_41 = VAR_14.getRawHeaders(b"Content-Type") if VAR_41 is None: raise RequestSendFailed( RuntimeError("No Content-Type header received from remote server"), can_retry=False, ) VAR_41 = c_type[0].decode("ascii") # only the first header VAR_42, VAR_43 = cgi.parse_header(VAR_41) if VAR_42 != "application/json": raise RequestSendFailed( RuntimeError( "Remote server sent Content-Type header of '%s', not 'application/json'" % VAR_41, ), can_retry=False, )
import cgi import logging import random import sys import urllib.parse from io import BytesIO from typing import Callable, Dict, List, Optional, Tuple, Union import attr import treq from canonicaljson import .encode_canonical_json from prometheus_client import Counter from signedjson.sign import sign_json from twisted.internet import .defer from twisted.internet.error import DNSLookupError from twisted.internet.interfaces import IReactorTime from twisted.internet.task import _EPSILON, Cooperator from twisted.web.http_headers import Headers from twisted.web.iweb import IBodyProducer, IResponse import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( FederationDeniedError, HttpResponseException, RequestSendFailed, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, BlacklistingReactorWrapper, encode_query_args, readBodyToFile, ) from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.logging.context import make_deferred_yieldable from synapse.logging.opentracing import ( inject_active_span_byte_dict, set_tag, start_active_span, tags, ) from synapse.types import JsonDict from synapse.util import .json_decoder from synapse.util.async_helpers import .timeout_deferred from synapse.util.metrics import Measure VAR_0 = logging.getLogger(__name__) VAR_1 = Counter( "synapse_http_matrixfederationclient_requests", "", ["method"] ) VAR_2 = Counter( "synapse_http_matrixfederationclient_responses", "", ["method", "code"] ) VAR_3 = 10 VAR_4 = 3 VAR_5 = sys.maxsize VAR_6 = 1 VAR_7 = Dict[str, Union[str, List[str]]] @attr.s(slots=True, frozen=True) class CLASS_0: VAR_15 = attr.ib(type=str) """HTTP VAR_15 """ VAR_16 = attr.ib(type=str) """HTTP VAR_16 """ VAR_17 = attr.ib(type=str) """The remote server to send the HTTP VAR_10 to. """ VAR_18 = attr.ib(default=None, type=Optional[JsonDict]) """JSON to send in the VAR_47. """ VAR_19 = attr.ib(default=None, type=Optional[Callable[[], JsonDict]]) """A callback to generate the JSON. """ VAR_20 = attr.ib(default=None, type=Optional[dict]) """Query arguments. """ VAR_21 = attr.ib(default=None, type=Optional[str]) """Unique ID for this VAR_10 (for logging) """ VAR_22 = attr.ib(init=False, type=bytes) """The URI of this VAR_10 """ def __attrs_post_init__(self) -> None: global VAR_6 VAR_21 = "%s-O-%s" % (self.method, VAR_6) _next_id = (VAR_6 + 1) % (VAR_5 - 1) object.__setattr__(self, "txn_id", VAR_21) VAR_44 = self.destination.encode("ascii") VAR_45 = self.path.encode("ascii") if self.query: VAR_56 = encode_query_args(self.query) else: VAR_56 = b"" VAR_22 = urllib.parse.urlunparse( (b"matrix", VAR_44, VAR_45, None, VAR_56, b"") ) object.__setattr__(self, "uri", VAR_22) def FUNC_3(self) -> Optional[JsonDict]: if self.json_callback: return self.json_callback() return self.json async def FUNC_0( VAR_8: IReactorTime, VAR_9: float, VAR_10: CLASS_0, VAR_11: IResponse, VAR_12: int, ) -> JsonDict: try: FUNC_2(VAR_11.headers) VAR_46 = treq.text_content(VAR_11, encoding="utf-8") VAR_46.addCallback(json_decoder.decode) VAR_46 = timeout_deferred(VAR_46, VAR_29=VAR_9, VAR_8=reactor) VAR_47 = await make_deferred_yieldable(VAR_46) except defer.TimeoutError as VAR_13: VAR_0.warning( "{%s} [%s] Timed out reading VAR_11 - %s %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_10.uri.decode("ascii"), ) raise RequestSendFailed(VAR_13, can_retry=True) from VAR_13 except Exception as VAR_13: VAR_0.warning( "{%s} [%s] Error reading VAR_11 %s %s: %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_10.uri.decode("ascii"), VAR_13, ) raise VAR_23 = VAR_8.seconds() - VAR_12 / 1000 VAR_0.info( "{%s} [%s] Completed VAR_10: %VAR_46 %s in %.2f secs - %s %s", VAR_10.txn_id, VAR_10.destination, VAR_11.code, VAR_11.phrase.decode("ascii", errors="replace"), VAR_23, VAR_10.method, VAR_10.uri.decode("ascii"), ) return VAR_47 class CLASS_1: def __init__(self, VAR_24, VAR_25): self.hs = VAR_24 self.signing_key = VAR_24.signing_key self.server_name = VAR_24.hostname self.reactor = BlacklistingReactorWrapper( VAR_24.get_reactor(), None, VAR_24.config.federation_ip_range_blacklist ) VAR_48 = VAR_24.version_string if VAR_24.config.user_agent_suffix: VAR_48 = "%s %s" % (VAR_48, VAR_24.config.user_agent_suffix) VAR_48 = user_agent.encode("ascii") self.agent = MatrixFederationAgent( self.reactor, VAR_25, VAR_48, VAR_24.config.federation_ip_range_blacklist, ) self.agent = BlacklistingAgentWrapper( self.agent, ip_blacklist=VAR_24.config.federation_ip_range_blacklist, ) self.clock = VAR_24.get_clock() self._store = VAR_24.get_datastore() self.version_string_bytes = VAR_24.version_string.encode("ascii") self.default_timeout = 60 def FUNC_11(VAR_49): self.reactor.callLater(_EPSILON, VAR_49) self._cooperator = Cooperator(scheduler=FUNC_11) async def FUNC_4( self, VAR_10: CLASS_0, VAR_26: bool = False, **VAR_27 ) -> IResponse: try: VAR_11 = await self._send_request(VAR_10, **VAR_27) except HttpResponseException as VAR_13: if not VAR_26: raise if VAR_13.code != 400 or VAR_13.to_synapse_error().errcode != "M_UNRECOGNIZED": raise VAR_0.info("Retrying VAR_10 with trailing slash") VAR_10 = attr.evolve(VAR_10, VAR_16=VAR_10.path + "/") VAR_11 = await self._send_request(VAR_10, **VAR_27) return VAR_11 async def FUNC_5( self, VAR_10: CLASS_0, VAR_28: bool = True, VAR_29: Optional[int] = None, VAR_30: bool = False, VAR_31: bool = False, VAR_32: bool = False, ) -> IResponse: if VAR_29: VAR_57 = VAR_29 / 1000 else: VAR_57 = self.default_timeout if ( self.hs.config.federation_domain_whitelist is not None and VAR_10.destination not in self.hs.config.federation_domain_whitelist ): raise FederationDeniedError(VAR_10.destination) VAR_50 = await synapse.util.retryutils.get_retry_limiter( VAR_10.destination, self.clock, self._store, VAR_32=backoff_on_404, VAR_31=ignore_backoff, ) VAR_51 = VAR_10.method.encode("ascii") VAR_44 = VAR_10.destination.encode("ascii") VAR_45 = VAR_10.path.encode("ascii") if VAR_10.query: VAR_56 = encode_query_args(VAR_10.query) else: VAR_56 = b"" VAR_52 = start_active_span( "outgoing-federation-request", tags={ tags.SPAN_KIND: tags.SPAN_KIND_RPC_CLIENT, tags.PEER_ADDRESS: VAR_10.destination, tags.HTTP_METHOD: VAR_10.method, tags.HTTP_URL: VAR_10.path, }, finish_on_close=True, ) VAR_53 = {} # type: Dict[bytes, List[bytes]] inject_active_span_byte_dict(VAR_53, VAR_10.destination) VAR_53[b"User-Agent"] = [self.version_string_bytes] with VAR_50, VAR_52: if VAR_30: VAR_61 = VAR_3 else: VAR_61 = VAR_4 VAR_33 = VAR_10.uri VAR_58 = VAR_33.decode("ascii") VAR_59 = urllib.parse.urlunparse( (b"", b"", VAR_45, None, VAR_56, b"") ) while True: try: VAR_18 = VAR_10.get_json() if VAR_18: VAR_53[b"Content-Type"] = [b"application/json"] VAR_54 = self.build_auth_headers( VAR_44, VAR_51, VAR_59, VAR_18 ) VAR_37 = encode_canonical_json(VAR_18) VAR_63 = QuieterFileBodyProducer( BytesIO(VAR_37), cooperator=self._cooperator ) # type: Optional[IBodyProducer] else: VAR_63 = None VAR_54 = self.build_auth_headers( VAR_44, VAR_51, VAR_59 ) VAR_53[b"Authorization"] = VAR_54 VAR_0.debug( "{%s} [%s] Sending VAR_10: %s %s; VAR_29 %fs", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_58, VAR_57, ) VAR_1.labels(VAR_10.method).inc() try: with Measure(self.clock, "outbound_request"): VAR_65 = self.agent.request( VAR_51, VAR_33, VAR_14=Headers(VAR_53), bodyProducer=VAR_63, ) VAR_65 = timeout_deferred( VAR_65, VAR_29=VAR_57, VAR_8=self.reactor, ) VAR_11 = await VAR_65 except DNSLookupError as VAR_13: raise RequestSendFailed(VAR_13, can_retry=VAR_28) from VAR_13 except Exception as VAR_13: raise RequestSendFailed(VAR_13, can_retry=True) from VAR_13 VAR_2.labels( VAR_10.method, VAR_11.code ).inc() set_tag(tags.HTTP_STATUS_CODE, VAR_11.code) VAR_62 = VAR_11.phrase.decode("ascii", errors="replace") if 200 <= VAR_11.code < 300: VAR_0.debug( "{%s} [%s] Got VAR_11 VAR_14: %VAR_46 %s", VAR_10.txn_id, VAR_10.destination, VAR_11.code, VAR_62, ) pass else: VAR_0.info( "{%s} [%s] Got VAR_11 VAR_14: %VAR_46 %s", VAR_10.txn_id, VAR_10.destination, VAR_11.code, VAR_62, ) VAR_46 = treq.content(VAR_11) VAR_46 = timeout_deferred( VAR_46, VAR_29=VAR_57, VAR_8=self.reactor ) try: VAR_47 = await make_deferred_yieldable(VAR_46) except Exception as VAR_13: VAR_0.warning( "{%s} [%s] Failed to get error VAR_11: %s %s: %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_58, FUNC_1(VAR_13), ) VAR_47 = None VAR_64 = HttpResponseException( VAR_11.code, VAR_62, VAR_47 ) if VAR_11.code == 429: raise RequestSendFailed(VAR_64, can_retry=True) from VAR_64 else: raise VAR_64 break except RequestSendFailed as VAR_13: VAR_0.info( "{%s} [%s] Request failed: %s %s: %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_58, FUNC_1(VAR_13.inner_exception), ) if not VAR_13.can_retry: raise if VAR_61 and not VAR_29: if VAR_30: VAR_66 = 4 ** (VAR_3 + 1 - VAR_61) VAR_66 = min(VAR_66, 60) VAR_66 *= random.uniform(0.8, 1.4) else: VAR_66 = 0.5 * 2 ** (VAR_4 - VAR_61) VAR_66 = min(VAR_66, 2) VAR_66 *= random.uniform(0.8, 1.4) VAR_0.debug( "{%s} [%s] Waiting %ss before re-sending...", VAR_10.txn_id, VAR_10.destination, VAR_66, ) await self.clock.sleep(VAR_66) VAR_61 -= 1 else: raise except Exception as VAR_13: VAR_0.warning( "{%s} [%s] Request failed: %s %s: %s", VAR_10.txn_id, VAR_10.destination, VAR_10.method, VAR_58, FUNC_1(VAR_13), ) raise return VAR_11 def FUNC_6( self, VAR_17: Optional[bytes], VAR_15: bytes, VAR_33: bytes, VAR_34: Optional[JsonDict] = None, VAR_35: Optional[bytes] = None, ) -> List[bytes]: VAR_10 = { "method": VAR_15.decode("ascii"), "uri": VAR_33.decode("ascii"), "origin": self.server_name, } if VAR_17 is not None: VAR_10["destination"] = VAR_17.decode("ascii") if VAR_35 is not None: VAR_10["destination_is"] = VAR_35.decode("ascii") if VAR_34 is not None: VAR_10["content"] = VAR_34 VAR_10 = sign_json(VAR_10, self.server_name, self.signing_key) VAR_54 = [] for key, sig in VAR_10["signatures"][self.server_name].items(): VAR_54.append( ( 'X-Matrix origin=%s,key="%s",sig="%s"' % (self.server_name, key, sig) ).encode("ascii") ) return VAR_54 async def FUNC_7( self, VAR_17: str, VAR_16: str, VAR_36: Optional[VAR_7] = None, VAR_37: Optional[JsonDict] = None, VAR_38: Optional[Callable[[], JsonDict]] = None, VAR_30: bool = False, VAR_29: Optional[int] = None, VAR_31: bool = False, VAR_32: bool = False, VAR_26: bool = False, ) -> Union[JsonDict, list]: VAR_10 = CLASS_0( VAR_15="PUT", VAR_17=destination, VAR_16=path, VAR_20=VAR_36, VAR_19=VAR_38, VAR_18=VAR_37, ) VAR_12 = self.clock.time_msec() VAR_11 = await self._send_request_with_optional_trailing_slash( VAR_10, VAR_26, VAR_32=backoff_on_404, VAR_31=ignore_backoff, VAR_30=long_retries, VAR_29=timeout, ) if VAR_29 is not None: VAR_57 = VAR_29 / 1000 else: VAR_57 = self.default_timeout VAR_47 = await FUNC_0( self.reactor, VAR_57, VAR_10, VAR_11, VAR_12 ) return VAR_47 async def FUNC_8( self, VAR_17: str, VAR_16: str, VAR_37: Optional[JsonDict] = None, VAR_30: bool = False, VAR_29: Optional[int] = None, VAR_31: bool = False, VAR_36: Optional[VAR_7] = None, ) -> Union[JsonDict, list]: VAR_10 = CLASS_0( VAR_15="POST", VAR_17=destination, VAR_16=path, VAR_20=VAR_36, VAR_18=VAR_37 ) VAR_12 = self.clock.time_msec() VAR_11 = await self._send_request( VAR_10, VAR_30=long_retries, VAR_29=timeout, VAR_31=ignore_backoff, ) if VAR_29: VAR_57 = VAR_29 / 1000 else: VAR_57 = self.default_timeout VAR_47 = await FUNC_0( self.reactor, VAR_57, VAR_10, VAR_11, VAR_12, ) return VAR_47 async def FUNC_3( self, VAR_17: str, VAR_16: str, VAR_36: Optional[VAR_7] = None, VAR_28: bool = True, VAR_29: Optional[int] = None, VAR_31: bool = False, VAR_26: bool = False, ) -> Union[JsonDict, list]: VAR_10 = CLASS_0( VAR_15="GET", VAR_17=destination, VAR_16=path, VAR_20=VAR_36 ) VAR_12 = self.clock.time_msec() VAR_11 = await self._send_request_with_optional_trailing_slash( VAR_10, VAR_26, VAR_32=False, VAR_31=ignore_backoff, VAR_28=retry_on_dns_fail, VAR_29=timeout, ) if VAR_29 is not None: VAR_57 = VAR_29 / 1000 else: VAR_57 = self.default_timeout VAR_47 = await FUNC_0( self.reactor, VAR_57, VAR_10, VAR_11, VAR_12 ) return VAR_47 async def FUNC_9( self, VAR_17: str, VAR_16: str, VAR_30: bool = False, VAR_29: Optional[int] = None, VAR_31: bool = False, VAR_36: Optional[VAR_7] = None, ) -> Union[JsonDict, list]: VAR_10 = CLASS_0( VAR_15="DELETE", VAR_17=destination, VAR_16=path, VAR_20=VAR_36 ) VAR_12 = self.clock.time_msec() VAR_11 = await self._send_request( VAR_10, VAR_30=long_retries, VAR_29=timeout, VAR_31=ignore_backoff, ) if VAR_29 is not None: VAR_57 = VAR_29 / 1000 else: VAR_57 = self.default_timeout VAR_47 = await FUNC_0( self.reactor, VAR_57, VAR_10, VAR_11, VAR_12 ) return VAR_47 async def FUNC_10( self, VAR_17: str, VAR_16: str, VAR_39, VAR_36: Optional[VAR_7] = None, VAR_28: bool = True, VAR_40: Optional[int] = None, VAR_31: bool = False, ) -> Tuple[int, Dict[bytes, List[bytes]]]: VAR_10 = CLASS_0( VAR_15="GET", VAR_17=destination, VAR_16=path, VAR_20=VAR_36 ) VAR_11 = await self._send_request( VAR_10, VAR_28=retry_on_dns_fail, VAR_31=ignore_backoff ) VAR_14 = dict(VAR_11.headers.getAllRawHeaders()) try: VAR_46 = readBodyToFile(VAR_11, VAR_39, VAR_40) VAR_46.addTimeout(self.default_timeout, self.reactor) VAR_60 = await make_deferred_yieldable(VAR_46) except Exception as VAR_13: VAR_0.warning( "{%s} [%s] Error reading VAR_11: %s", VAR_10.txn_id, VAR_10.destination, VAR_13, ) raise VAR_0.info( "{%s} [%s] Completed: %VAR_46 %s [%VAR_46 bytes] %s %s", VAR_10.txn_id, VAR_10.destination, VAR_11.code, VAR_11.phrase.decode("ascii", errors="replace"), VAR_60, VAR_10.method, VAR_10.uri.decode("ascii"), ) return (VAR_60, VAR_14) def FUNC_1(VAR_13): if hasattr(VAR_13, "reasons"): VAR_55 = ", ".join( FUNC_1(f.value) for f in VAR_13.reasons ) return "%s:[%s]" % (type(VAR_13).__name__, VAR_55) else: return repr(VAR_13) def FUNC_2(VAR_14: Headers) -> None: VAR_41 = VAR_14.getRawHeaders(b"Content-Type") if VAR_41 is None: raise RequestSendFailed( RuntimeError("No Content-Type header received from remote server"), can_retry=False, ) VAR_41 = c_type[0].decode("ascii") # only the first header VAR_42, VAR_43 = cgi.parse_header(VAR_41) if VAR_42 != "application/json": raise RequestSendFailed( RuntimeError( "Remote server sent Content-Type header of '%s', not 'application/json'" % VAR_41, ), can_retry=False, )
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 23, 30, 37, 64, 66, 73, 74, 78, 79, 81, 82, 84, 85, 91, 95, 99, 103, 107, 111, 115, 119, 124, 126, 133, 134, 139, 144, 145, 155, 162, 168, 169, 173, 194, 196, 208, 209, 213, 218, 223, 225, 226, 227, 231, 239, 241, 246, 250, 251, 252, 256, 261, 264, 266, 277, 284, 288, 295, 296, 299, 302, 303, 304, 305, 307, 308, 310, 312, 314, 326, 329, 331, 335, 337, 340, 343, 345, 348, 351, 354, 356, 359, 374, 380, 388, 396, 407, 408, 411, 413, 415, 416, 421, 424, 428, 446, 448, 457, 459, 462, 463, 470, 476, 482, 486, 489, 507, 508, 513, 517, 518, 528, 532, 533, 534, 539, 550, 553, 563, 570, 575, 587, 607, 616, 619, 622, 625, 627, 629, 638, 653, 662, 665, 668, 673, 684, 688, 707, 709, 718, 723, 727, 729, 741, 744, 746, 749, 752, 755, 760, 763, 768, 779, 783, 785, 792, 797, 802, 814, 817, 819, 822, 825, 830, 833, 840, 854, 856, 865, 870, 874, 876, 887, 891, 894, 897, 902, 905, 910, 924, 926, 933, 938, 943, 962, 966, 980, 984, 986, 1010, 1011, 1017, 1021, 1022, 1027, 1030, 1033, 1041, 1052, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 211, 212, 213, 214, 215, 216, 217, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 23, 29, 36, 63, 65, 72, 73, 77, 78, 80, 81, 83, 84, 90, 94, 98, 102, 106, 110, 114, 118, 123, 125, 132, 133, 138, 143, 144, 154, 161, 167, 168, 172, 193, 195, 207, 208, 212, 217, 222, 223, 224, 228, 233, 240, 241, 242, 246, 251, 254, 256, 267, 274, 278, 285, 286, 289, 292, 293, 294, 295, 297, 298, 300, 302, 304, 316, 319, 321, 325, 327, 330, 333, 335, 338, 341, 344, 346, 349, 364, 370, 378, 386, 397, 398, 401, 403, 405, 406, 411, 414, 418, 436, 438, 447, 449, 452, 453, 460, 466, 472, 476, 479, 497, 498, 503, 507, 508, 518, 522, 523, 524, 529, 540, 543, 553, 560, 565, 577, 597, 606, 609, 612, 615, 617, 619, 628, 643, 652, 655, 658, 663, 674, 678, 697, 699, 708, 713, 717, 719, 731, 734, 736, 739, 742, 745, 750, 753, 758, 769, 773, 775, 782, 787, 792, 804, 807, 809, 812, 815, 820, 823, 830, 844, 846, 855, 860, 864, 866, 877, 881, 884, 887, 892, 895, 900, 914, 916, 923, 928, 933, 952, 956, 970, 974, 976, 1000, 1001, 1007, 1011, 1012, 1017, 1020, 1023, 1031, 1042, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 210, 211, 212, 213, 214, 215, 216, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import errno import logging import os import shutil from typing import IO, Dict, List, Optional, Tuple import twisted.internet.error import twisted.web.http from twisted.web.http import Request from twisted.web.resource import Resource from synapse.api.errors import ( FederationDeniedError, HttpResponseException, NotFoundError, RequestSendFailed, SynapseError, ) from synapse.config._base import ConfigError from synapse.logging.context import defer_to_thread from synapse.metrics.background_process_metrics import run_as_background_process from synapse.util.async_helpers import Linearizer from synapse.util.retryutils import NotRetryingDestination from synapse.util.stringutils import random_string from ._base import ( FileInfo, Responder, get_filename_from_headers, respond_404, respond_with_responder, ) from .config_resource import MediaConfigResource from .download_resource import DownloadResource from .filepath import MediaFilePaths from .media_storage import MediaStorage from .preview_url_resource import PreviewUrlResource from .storage_provider import StorageProviderWrapper from .thumbnail_resource import ThumbnailResource from .thumbnailer import Thumbnailer, ThumbnailError from .upload_resource import UploadResource logger = logging.getLogger(__name__) UPDATE_RECENTLY_ACCESSED_TS = 60 * 1000 class MediaRepository: def __init__(self, hs): self.hs = hs self.auth = hs.get_auth() self.client = hs.get_http_client() self.clock = hs.get_clock() self.server_name = hs.hostname self.store = hs.get_datastore() self.max_upload_size = hs.config.max_upload_size self.max_image_pixels = hs.config.max_image_pixels self.primary_base_path = hs.config.media_store_path self.filepaths = MediaFilePaths(self.primary_base_path) self.dynamic_thumbnails = hs.config.dynamic_thumbnails self.thumbnail_requirements = hs.config.thumbnail_requirements self.remote_media_linearizer = Linearizer(name="media_remote") self.recently_accessed_remotes = set() self.recently_accessed_locals = set() self.federation_domain_whitelist = hs.config.federation_domain_whitelist # List of StorageProviders where we should search for media and # potentially upload to. storage_providers = [] for clz, provider_config, wrapper_config in hs.config.media_storage_providers: backend = clz(hs, provider_config) provider = StorageProviderWrapper( backend, store_local=wrapper_config.store_local, store_remote=wrapper_config.store_remote, store_synchronous=wrapper_config.store_synchronous, ) storage_providers.append(provider) self.media_storage = MediaStorage( self.hs, self.primary_base_path, self.filepaths, storage_providers ) self.clock.looping_call( self._start_update_recently_accessed, UPDATE_RECENTLY_ACCESSED_TS ) def _start_update_recently_accessed(self): return run_as_background_process( "update_recently_accessed_media", self._update_recently_accessed ) async def _update_recently_accessed(self): remote_media = self.recently_accessed_remotes self.recently_accessed_remotes = set() local_media = self.recently_accessed_locals self.recently_accessed_locals = set() await self.store.update_cached_last_access_time( local_media, remote_media, self.clock.time_msec() ) def mark_recently_accessed(self, server_name, media_id): """Mark the given media as recently accessed. Args: server_name (str|None): Origin server of media, or None if local media_id (str): The media ID of the content """ if server_name: self.recently_accessed_remotes.add((server_name, media_id)) else: self.recently_accessed_locals.add(media_id) async def create_content( self, media_type: str, upload_name: Optional[str], content: IO, content_length: int, auth_user: str, ) -> str: """Store uploaded content for a local user and return the mxc URL Args: media_type: The content type of the file. upload_name: The name of the file, if provided. content: A file like object that is the content to store content_length: The length of the content auth_user: The user_id of the uploader Returns: The mxc url of the stored content """ media_id = random_string(24) file_info = FileInfo(server_name=None, file_id=media_id) fname = await self.media_storage.store_file(content, file_info) logger.info("Stored local media in file %r", fname) await self.store.store_local_media( media_id=media_id, media_type=media_type, time_now_ms=self.clock.time_msec(), upload_name=upload_name, media_length=content_length, user_id=auth_user, ) await self._generate_thumbnails(None, media_id, media_id, media_type) return "mxc://%s/%s" % (self.server_name, media_id) async def get_local_media( self, request: Request, media_id: str, name: Optional[str] ) -> None: """Responds to reqests for local media, if exists, or returns 404. Args: request: The incoming request. media_id: The media ID of the content. (This is the same as the file_id for local content.) name: Optional name that, if specified, will be used as the filename in the Content-Disposition header of the response. Returns: Resolves once a response has successfully been written to request """ media_info = await self.store.get_local_media(media_id) if not media_info or media_info["quarantined_by"]: respond_404(request) return self.mark_recently_accessed(None, media_id) media_type = media_info["media_type"] media_length = media_info["media_length"] upload_name = name if name else media_info["upload_name"] url_cache = media_info["url_cache"] file_info = FileInfo(None, media_id, url_cache=url_cache) responder = await self.media_storage.fetch_media(file_info) await respond_with_responder( request, responder, media_type, media_length, upload_name ) async def get_remote_media( self, request: Request, server_name: str, media_id: str, name: Optional[str] ) -> None: """Respond to requests for remote media. Args: request: The incoming request. server_name: Remote server_name where the media originated. media_id: The media ID of the content (as defined by the remote server). name: Optional name that, if specified, will be used as the filename in the Content-Disposition header of the response. Returns: Resolves once a response has successfully been written to request """ if ( self.federation_domain_whitelist is not None and server_name not in self.federation_domain_whitelist ): raise FederationDeniedError(server_name) self.mark_recently_accessed(server_name, media_id) # We linearize here to ensure that we don't try and download remote # media multiple times concurrently key = (server_name, media_id) with (await self.remote_media_linearizer.queue(key)): responder, media_info = await self._get_remote_media_impl( server_name, media_id ) # We deliberately stream the file outside the lock if responder: media_type = media_info["media_type"] media_length = media_info["media_length"] upload_name = name if name else media_info["upload_name"] await respond_with_responder( request, responder, media_type, media_length, upload_name ) else: respond_404(request) async def get_remote_media_info(self, server_name: str, media_id: str) -> dict: """Gets the media info associated with the remote file, downloading if necessary. Args: server_name: Remote server_name where the media originated. media_id: The media ID of the content (as defined by the remote server). Returns: The media info of the file """ if ( self.federation_domain_whitelist is not None and server_name not in self.federation_domain_whitelist ): raise FederationDeniedError(server_name) # We linearize here to ensure that we don't try and download remote # media multiple times concurrently key = (server_name, media_id) with (await self.remote_media_linearizer.queue(key)): responder, media_info = await self._get_remote_media_impl( server_name, media_id ) # Ensure we actually use the responder so that it releases resources if responder: with responder: pass return media_info async def _get_remote_media_impl( self, server_name: str, media_id: str ) -> Tuple[Optional[Responder], dict]: """Looks for media in local cache, if not there then attempt to download from remote server. Args: server_name (str): Remote server_name where the media originated. media_id (str): The media ID of the content (as defined by the remote server). Returns: A tuple of responder and the media info of the file. """ media_info = await self.store.get_cached_remote_media(server_name, media_id) # file_id is the ID we use to track the file locally. If we've already # seen the file then reuse the existing ID, otherwise genereate a new # one. # If we have an entry in the DB, try and look for it if media_info: file_id = media_info["filesystem_id"] file_info = FileInfo(server_name, file_id) if media_info["quarantined_by"]: logger.info("Media is quarantined") raise NotFoundError() responder = await self.media_storage.fetch_media(file_info) if responder: return responder, media_info # Failed to find the file anywhere, lets download it. try: media_info = await self._download_remote_file(server_name, media_id,) except SynapseError: raise except Exception as e: # An exception may be because we downloaded media in another # process, so let's check if we magically have the media. media_info = await self.store.get_cached_remote_media(server_name, media_id) if not media_info: raise e file_id = media_info["filesystem_id"] file_info = FileInfo(server_name, file_id) # We generate thumbnails even if another process downloaded the media # as a) it's conceivable that the other download request dies before it # generates thumbnails, but mainly b) we want to be sure the thumbnails # have finished being generated before responding to the client, # otherwise they'll request thumbnails and get a 404 if they're not # ready yet. await self._generate_thumbnails( server_name, media_id, file_id, media_info["media_type"] ) responder = await self.media_storage.fetch_media(file_info) return responder, media_info async def _download_remote_file(self, server_name: str, media_id: str,) -> dict: """Attempt to download the remote file from the given server name, using the given file_id as the local id. Args: server_name: Originating server media_id: The media ID of the content (as defined by the remote server). This is different than the file_id, which is locally generated. file_id: Local file ID Returns: The media info of the file. """ file_id = random_string(24) file_info = FileInfo(server_name=server_name, file_id=file_id) with self.media_storage.store_into_file(file_info) as (f, fname, finish): request_path = "/".join( ("/_matrix/media/r0/download", server_name, media_id) ) try: length, headers = await self.client.get_file( server_name, request_path, output_stream=f, max_size=self.max_upload_size, args={ # tell the remote server to 404 if it doesn't # recognise the server_name, to make sure we don't # end up with a routing loop. "allow_remote": "false" }, ) except RequestSendFailed as e: logger.warning( "Request failed fetching remote media %s/%s: %r", server_name, media_id, e, ) raise SynapseError(502, "Failed to fetch remote media") except HttpResponseException as e: logger.warning( "HTTP error fetching remote media %s/%s: %s", server_name, media_id, e.response, ) if e.code == twisted.web.http.NOT_FOUND: raise e.to_synapse_error() raise SynapseError(502, "Failed to fetch remote media") except SynapseError: logger.warning( "Failed to fetch remote media %s/%s", server_name, media_id ) raise except NotRetryingDestination: logger.warning("Not retrying destination %r", server_name) raise SynapseError(502, "Failed to fetch remote media") except Exception: logger.exception( "Failed to fetch remote media %s/%s", server_name, media_id ) raise SynapseError(502, "Failed to fetch remote media") await finish() media_type = headers[b"Content-Type"][0].decode("ascii") upload_name = get_filename_from_headers(headers) time_now_ms = self.clock.time_msec() # Multiple remote media download requests can race (when using # multiple media repos), so this may throw a violation constraint # exception. If it does we'll delete the newly downloaded file from # disk (as we're in the ctx manager). # # However: we've already called `finish()` so we may have also # written to the storage providers. This is preferable to the # alternative where we call `finish()` *after* this, where we could # end up having an entry in the DB but fail to write the files to # the storage providers. await self.store.store_cached_remote_media( origin=server_name, media_id=media_id, media_type=media_type, time_now_ms=self.clock.time_msec(), upload_name=upload_name, media_length=length, filesystem_id=file_id, ) logger.info("Stored remote media in file %r", fname) media_info = { "media_type": media_type, "media_length": length, "upload_name": upload_name, "created_ts": time_now_ms, "filesystem_id": file_id, } return media_info def _get_thumbnail_requirements(self, media_type): return self.thumbnail_requirements.get(media_type, ()) def _generate_thumbnail(self, thumbnailer, t_width, t_height, t_method, t_type): m_width = thumbnailer.width m_height = thumbnailer.height if m_width * m_height >= self.max_image_pixels: logger.info( "Image too large to thumbnail %r x %r > %r", m_width, m_height, self.max_image_pixels, ) return if thumbnailer.transpose_method is not None: m_width, m_height = thumbnailer.transpose() if t_method == "crop": t_byte_source = thumbnailer.crop(t_width, t_height, t_type) elif t_method == "scale": t_width, t_height = thumbnailer.aspect(t_width, t_height) t_width = min(m_width, t_width) t_height = min(m_height, t_height) t_byte_source = thumbnailer.scale(t_width, t_height, t_type) else: t_byte_source = None return t_byte_source async def generate_local_exact_thumbnail( self, media_id: str, t_width: int, t_height: int, t_method: str, t_type: str, url_cache: str, ) -> Optional[str]: input_path = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(None, media_id, url_cache=url_cache) ) try: thumbnailer = Thumbnailer(input_path) except ThumbnailError as e: logger.warning( "Unable to generate a thumbnail for local media %s using a method of %s and type of %s: %s", media_id, t_method, t_type, e, ) return None t_byte_source = await defer_to_thread( self.hs.get_reactor(), self._generate_thumbnail, thumbnailer, t_width, t_height, t_method, t_type, ) if t_byte_source: try: file_info = FileInfo( server_name=None, file_id=media_id, url_cache=url_cache, thumbnail=True, thumbnail_width=t_width, thumbnail_height=t_height, thumbnail_method=t_method, thumbnail_type=t_type, ) output_path = await self.media_storage.store_file( t_byte_source, file_info ) finally: t_byte_source.close() logger.info("Stored thumbnail in file %r", output_path) t_len = os.path.getsize(output_path) await self.store.store_local_thumbnail( media_id, t_width, t_height, t_type, t_method, t_len ) return output_path # Could not generate thumbnail. return None async def generate_remote_exact_thumbnail( self, server_name: str, file_id: str, media_id: str, t_width: int, t_height: int, t_method: str, t_type: str, ) -> Optional[str]: input_path = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(server_name, file_id, url_cache=False) ) try: thumbnailer = Thumbnailer(input_path) except ThumbnailError as e: logger.warning( "Unable to generate a thumbnail for remote media %s from %s using a method of %s and type of %s: %s", media_id, server_name, t_method, t_type, e, ) return None t_byte_source = await defer_to_thread( self.hs.get_reactor(), self._generate_thumbnail, thumbnailer, t_width, t_height, t_method, t_type, ) if t_byte_source: try: file_info = FileInfo( server_name=server_name, file_id=file_id, thumbnail=True, thumbnail_width=t_width, thumbnail_height=t_height, thumbnail_method=t_method, thumbnail_type=t_type, ) output_path = await self.media_storage.store_file( t_byte_source, file_info ) finally: t_byte_source.close() logger.info("Stored thumbnail in file %r", output_path) t_len = os.path.getsize(output_path) await self.store.store_remote_media_thumbnail( server_name, media_id, file_id, t_width, t_height, t_type, t_method, t_len, ) return output_path # Could not generate thumbnail. return None async def _generate_thumbnails( self, server_name: Optional[str], media_id: str, file_id: str, media_type: str, url_cache: bool = False, ) -> Optional[dict]: """Generate and store thumbnails for an image. Args: server_name: The server name if remote media, else None if local media_id: The media ID of the content. (This is the same as the file_id for local content) file_id: Local file ID media_type: The content type of the file url_cache: If we are thumbnailing images downloaded for the URL cache, used exclusively by the url previewer Returns: Dict with "width" and "height" keys of original image or None if the media cannot be thumbnailed. """ requirements = self._get_thumbnail_requirements(media_type) if not requirements: return None input_path = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(server_name, file_id, url_cache=url_cache) ) try: thumbnailer = Thumbnailer(input_path) except ThumbnailError as e: logger.warning( "Unable to generate thumbnails for remote media %s from %s of type %s: %s", media_id, server_name, media_type, e, ) return None m_width = thumbnailer.width m_height = thumbnailer.height if m_width * m_height >= self.max_image_pixels: logger.info( "Image too large to thumbnail %r x %r > %r", m_width, m_height, self.max_image_pixels, ) return None if thumbnailer.transpose_method is not None: m_width, m_height = await defer_to_thread( self.hs.get_reactor(), thumbnailer.transpose ) # We deduplicate the thumbnail sizes by ignoring the cropped versions if # they have the same dimensions of a scaled one. thumbnails = {} # type: Dict[Tuple[int, int, str], str] for r_width, r_height, r_method, r_type in requirements: if r_method == "crop": thumbnails.setdefault((r_width, r_height, r_type), r_method) elif r_method == "scale": t_width, t_height = thumbnailer.aspect(r_width, r_height) t_width = min(m_width, t_width) t_height = min(m_height, t_height) thumbnails[(t_width, t_height, r_type)] = r_method # Now we generate the thumbnails for each dimension, store it for (t_width, t_height, t_type), t_method in thumbnails.items(): # Generate the thumbnail if t_method == "crop": t_byte_source = await defer_to_thread( self.hs.get_reactor(), thumbnailer.crop, t_width, t_height, t_type ) elif t_method == "scale": t_byte_source = await defer_to_thread( self.hs.get_reactor(), thumbnailer.scale, t_width, t_height, t_type ) else: logger.error("Unrecognized method: %r", t_method) continue if not t_byte_source: continue file_info = FileInfo( server_name=server_name, file_id=file_id, thumbnail=True, thumbnail_width=t_width, thumbnail_height=t_height, thumbnail_method=t_method, thumbnail_type=t_type, url_cache=url_cache, ) with self.media_storage.store_into_file(file_info) as (f, fname, finish): try: await self.media_storage.write_to_file(t_byte_source, f) await finish() finally: t_byte_source.close() t_len = os.path.getsize(fname) # Write to database if server_name: # Multiple remote media download requests can race (when # using multiple media repos), so this may throw a violation # constraint exception. If it does we'll delete the newly # generated thumbnail from disk (as we're in the ctx # manager). # # However: we've already called `finish()` so we may have # also written to the storage providers. This is preferable # to the alternative where we call `finish()` *after* this, # where we could end up having an entry in the DB but fail # to write the files to the storage providers. try: await self.store.store_remote_media_thumbnail( server_name, media_id, file_id, t_width, t_height, t_type, t_method, t_len, ) except Exception as e: thumbnail_exists = await self.store.get_remote_media_thumbnail( server_name, media_id, t_width, t_height, t_type, ) if not thumbnail_exists: raise e else: await self.store.store_local_thumbnail( media_id, t_width, t_height, t_type, t_method, t_len ) return {"width": m_width, "height": m_height} async def delete_old_remote_media(self, before_ts): old_media = await self.store.get_remote_media_before(before_ts) deleted = 0 for media in old_media: origin = media["media_origin"] media_id = media["media_id"] file_id = media["filesystem_id"] key = (origin, media_id) logger.info("Deleting: %r", key) # TODO: Should we delete from the backup store with (await self.remote_media_linearizer.queue(key)): full_path = self.filepaths.remote_media_filepath(origin, file_id) try: os.remove(full_path) except OSError as e: logger.warning("Failed to remove file: %r", full_path) if e.errno == errno.ENOENT: pass else: continue thumbnail_dir = self.filepaths.remote_media_thumbnail_dir( origin, file_id ) shutil.rmtree(thumbnail_dir, ignore_errors=True) await self.store.delete_remote_media(origin, media_id) deleted += 1 return {"deleted": deleted} async def delete_local_media(self, media_id: str) -> Tuple[List[str], int]: """ Delete the given local or remote media ID from this server Args: media_id: The media ID to delete. Returns: A tuple of (list of deleted media IDs, total deleted media IDs). """ return await self._remove_local_media_from_disk([media_id]) async def delete_old_local_media( self, before_ts: int, size_gt: int = 0, keep_profiles: bool = True, ) -> Tuple[List[str], int]: """ Delete local or remote media from this server by size and timestamp. Removes media files, any thumbnails and cached URLs. Args: before_ts: Unix timestamp in ms. Files that were last used before this timestamp will be deleted size_gt: Size of the media in bytes. Files that are larger will be deleted keep_profiles: Switch to delete also files that are still used in image data (e.g user profile, room avatar) If false these files will be deleted Returns: A tuple of (list of deleted media IDs, total deleted media IDs). """ old_media = await self.store.get_local_media_before( before_ts, size_gt, keep_profiles, ) return await self._remove_local_media_from_disk(old_media) async def _remove_local_media_from_disk( self, media_ids: List[str] ) -> Tuple[List[str], int]: """ Delete local or remote media from this server. Removes media files, any thumbnails and cached URLs. Args: media_ids: List of media_id to delete Returns: A tuple of (list of deleted media IDs, total deleted media IDs). """ removed_media = [] for media_id in media_ids: logger.info("Deleting media with ID '%s'", media_id) full_path = self.filepaths.local_media_filepath(media_id) try: os.remove(full_path) except OSError as e: logger.warning("Failed to remove file: %r: %s", full_path, e) if e.errno == errno.ENOENT: pass else: continue thumbnail_dir = self.filepaths.local_media_thumbnail_dir(media_id) shutil.rmtree(thumbnail_dir, ignore_errors=True) await self.store.delete_remote_media(self.server_name, media_id) await self.store.delete_url_cache((media_id,)) await self.store.delete_url_cache_media((media_id,)) removed_media.append(media_id) return removed_media, len(removed_media) class MediaRepositoryResource(Resource): """File uploading and downloading. Uploads are POSTed to a resource which returns a token which is used to GET the download:: => POST /_matrix/media/r0/upload HTTP/1.1 Content-Type: <media-type> Content-Length: <content-length> <media> <= HTTP/1.1 200 OK Content-Type: application/json { "content_uri": "mxc://<server-name>/<media-id>" } => GET /_matrix/media/r0/download/<server-name>/<media-id> HTTP/1.1 <= HTTP/1.1 200 OK Content-Type: <media-type> Content-Disposition: attachment;filename=<upload-filename> <media> Clients can get thumbnails by supplying a desired width and height and thumbnailing method:: => GET /_matrix/media/r0/thumbnail/<server_name> /<media-id>?width=<w>&height=<h>&method=<m> HTTP/1.1 <= HTTP/1.1 200 OK Content-Type: image/jpeg or image/png <thumbnail> The thumbnail methods are "crop" and "scale". "scale" trys to return an image where either the width or the height is smaller than the requested size. The client should then scale and letterbox the image if it needs to fit within a given rectangle. "crop" trys to return an image where the width and height are close to the requested size and the aspect matches the requested size. The client should scale the image if it needs to fit within a given rectangle. """ def __init__(self, hs): # If we're not configured to use it, raise if we somehow got here. if not hs.config.can_load_media_repo: raise ConfigError("Synapse is not configured to use a media repo.") super().__init__() media_repo = hs.get_media_repository() self.putChild(b"upload", UploadResource(hs, media_repo)) self.putChild(b"download", DownloadResource(hs, media_repo)) self.putChild( b"thumbnail", ThumbnailResource(hs, media_repo, media_repo.media_storage) ) if hs.config.url_preview_enabled: self.putChild( b"preview_url", PreviewUrlResource(hs, media_repo, media_repo.media_storage), ) self.putChild(b"config", MediaConfigResource(hs))
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import errno import logging import os import shutil from typing import IO, Dict, List, Optional, Tuple import twisted.internet.error import twisted.web.http from twisted.web.http import Request from twisted.web.resource import Resource from synapse.api.errors import ( FederationDeniedError, HttpResponseException, NotFoundError, RequestSendFailed, SynapseError, ) from synapse.config._base import ConfigError from synapse.logging.context import defer_to_thread from synapse.metrics.background_process_metrics import run_as_background_process from synapse.util.async_helpers import Linearizer from synapse.util.retryutils import NotRetryingDestination from synapse.util.stringutils import random_string from ._base import ( FileInfo, Responder, get_filename_from_headers, respond_404, respond_with_responder, ) from .config_resource import MediaConfigResource from .download_resource import DownloadResource from .filepath import MediaFilePaths from .media_storage import MediaStorage from .preview_url_resource import PreviewUrlResource from .storage_provider import StorageProviderWrapper from .thumbnail_resource import ThumbnailResource from .thumbnailer import Thumbnailer, ThumbnailError from .upload_resource import UploadResource logger = logging.getLogger(__name__) UPDATE_RECENTLY_ACCESSED_TS = 60 * 1000 class MediaRepository: def __init__(self, hs): self.hs = hs self.auth = hs.get_auth() self.client = hs.get_federation_http_client() self.clock = hs.get_clock() self.server_name = hs.hostname self.store = hs.get_datastore() self.max_upload_size = hs.config.max_upload_size self.max_image_pixels = hs.config.max_image_pixels self.primary_base_path = hs.config.media_store_path self.filepaths = MediaFilePaths(self.primary_base_path) self.dynamic_thumbnails = hs.config.dynamic_thumbnails self.thumbnail_requirements = hs.config.thumbnail_requirements self.remote_media_linearizer = Linearizer(name="media_remote") self.recently_accessed_remotes = set() self.recently_accessed_locals = set() self.federation_domain_whitelist = hs.config.federation_domain_whitelist # List of StorageProviders where we should search for media and # potentially upload to. storage_providers = [] for clz, provider_config, wrapper_config in hs.config.media_storage_providers: backend = clz(hs, provider_config) provider = StorageProviderWrapper( backend, store_local=wrapper_config.store_local, store_remote=wrapper_config.store_remote, store_synchronous=wrapper_config.store_synchronous, ) storage_providers.append(provider) self.media_storage = MediaStorage( self.hs, self.primary_base_path, self.filepaths, storage_providers ) self.clock.looping_call( self._start_update_recently_accessed, UPDATE_RECENTLY_ACCESSED_TS ) def _start_update_recently_accessed(self): return run_as_background_process( "update_recently_accessed_media", self._update_recently_accessed ) async def _update_recently_accessed(self): remote_media = self.recently_accessed_remotes self.recently_accessed_remotes = set() local_media = self.recently_accessed_locals self.recently_accessed_locals = set() await self.store.update_cached_last_access_time( local_media, remote_media, self.clock.time_msec() ) def mark_recently_accessed(self, server_name, media_id): """Mark the given media as recently accessed. Args: server_name (str|None): Origin server of media, or None if local media_id (str): The media ID of the content """ if server_name: self.recently_accessed_remotes.add((server_name, media_id)) else: self.recently_accessed_locals.add(media_id) async def create_content( self, media_type: str, upload_name: Optional[str], content: IO, content_length: int, auth_user: str, ) -> str: """Store uploaded content for a local user and return the mxc URL Args: media_type: The content type of the file. upload_name: The name of the file, if provided. content: A file like object that is the content to store content_length: The length of the content auth_user: The user_id of the uploader Returns: The mxc url of the stored content """ media_id = random_string(24) file_info = FileInfo(server_name=None, file_id=media_id) fname = await self.media_storage.store_file(content, file_info) logger.info("Stored local media in file %r", fname) await self.store.store_local_media( media_id=media_id, media_type=media_type, time_now_ms=self.clock.time_msec(), upload_name=upload_name, media_length=content_length, user_id=auth_user, ) await self._generate_thumbnails(None, media_id, media_id, media_type) return "mxc://%s/%s" % (self.server_name, media_id) async def get_local_media( self, request: Request, media_id: str, name: Optional[str] ) -> None: """Responds to reqests for local media, if exists, or returns 404. Args: request: The incoming request. media_id: The media ID of the content. (This is the same as the file_id for local content.) name: Optional name that, if specified, will be used as the filename in the Content-Disposition header of the response. Returns: Resolves once a response has successfully been written to request """ media_info = await self.store.get_local_media(media_id) if not media_info or media_info["quarantined_by"]: respond_404(request) return self.mark_recently_accessed(None, media_id) media_type = media_info["media_type"] media_length = media_info["media_length"] upload_name = name if name else media_info["upload_name"] url_cache = media_info["url_cache"] file_info = FileInfo(None, media_id, url_cache=url_cache) responder = await self.media_storage.fetch_media(file_info) await respond_with_responder( request, responder, media_type, media_length, upload_name ) async def get_remote_media( self, request: Request, server_name: str, media_id: str, name: Optional[str] ) -> None: """Respond to requests for remote media. Args: request: The incoming request. server_name: Remote server_name where the media originated. media_id: The media ID of the content (as defined by the remote server). name: Optional name that, if specified, will be used as the filename in the Content-Disposition header of the response. Returns: Resolves once a response has successfully been written to request """ if ( self.federation_domain_whitelist is not None and server_name not in self.federation_domain_whitelist ): raise FederationDeniedError(server_name) self.mark_recently_accessed(server_name, media_id) # We linearize here to ensure that we don't try and download remote # media multiple times concurrently key = (server_name, media_id) with (await self.remote_media_linearizer.queue(key)): responder, media_info = await self._get_remote_media_impl( server_name, media_id ) # We deliberately stream the file outside the lock if responder: media_type = media_info["media_type"] media_length = media_info["media_length"] upload_name = name if name else media_info["upload_name"] await respond_with_responder( request, responder, media_type, media_length, upload_name ) else: respond_404(request) async def get_remote_media_info(self, server_name: str, media_id: str) -> dict: """Gets the media info associated with the remote file, downloading if necessary. Args: server_name: Remote server_name where the media originated. media_id: The media ID of the content (as defined by the remote server). Returns: The media info of the file """ if ( self.federation_domain_whitelist is not None and server_name not in self.federation_domain_whitelist ): raise FederationDeniedError(server_name) # We linearize here to ensure that we don't try and download remote # media multiple times concurrently key = (server_name, media_id) with (await self.remote_media_linearizer.queue(key)): responder, media_info = await self._get_remote_media_impl( server_name, media_id ) # Ensure we actually use the responder so that it releases resources if responder: with responder: pass return media_info async def _get_remote_media_impl( self, server_name: str, media_id: str ) -> Tuple[Optional[Responder], dict]: """Looks for media in local cache, if not there then attempt to download from remote server. Args: server_name (str): Remote server_name where the media originated. media_id (str): The media ID of the content (as defined by the remote server). Returns: A tuple of responder and the media info of the file. """ media_info = await self.store.get_cached_remote_media(server_name, media_id) # file_id is the ID we use to track the file locally. If we've already # seen the file then reuse the existing ID, otherwise genereate a new # one. # If we have an entry in the DB, try and look for it if media_info: file_id = media_info["filesystem_id"] file_info = FileInfo(server_name, file_id) if media_info["quarantined_by"]: logger.info("Media is quarantined") raise NotFoundError() responder = await self.media_storage.fetch_media(file_info) if responder: return responder, media_info # Failed to find the file anywhere, lets download it. try: media_info = await self._download_remote_file(server_name, media_id,) except SynapseError: raise except Exception as e: # An exception may be because we downloaded media in another # process, so let's check if we magically have the media. media_info = await self.store.get_cached_remote_media(server_name, media_id) if not media_info: raise e file_id = media_info["filesystem_id"] file_info = FileInfo(server_name, file_id) # We generate thumbnails even if another process downloaded the media # as a) it's conceivable that the other download request dies before it # generates thumbnails, but mainly b) we want to be sure the thumbnails # have finished being generated before responding to the client, # otherwise they'll request thumbnails and get a 404 if they're not # ready yet. await self._generate_thumbnails( server_name, media_id, file_id, media_info["media_type"] ) responder = await self.media_storage.fetch_media(file_info) return responder, media_info async def _download_remote_file(self, server_name: str, media_id: str,) -> dict: """Attempt to download the remote file from the given server name, using the given file_id as the local id. Args: server_name: Originating server media_id: The media ID of the content (as defined by the remote server). This is different than the file_id, which is locally generated. file_id: Local file ID Returns: The media info of the file. """ file_id = random_string(24) file_info = FileInfo(server_name=server_name, file_id=file_id) with self.media_storage.store_into_file(file_info) as (f, fname, finish): request_path = "/".join( ("/_matrix/media/r0/download", server_name, media_id) ) try: length, headers = await self.client.get_file( server_name, request_path, output_stream=f, max_size=self.max_upload_size, args={ # tell the remote server to 404 if it doesn't # recognise the server_name, to make sure we don't # end up with a routing loop. "allow_remote": "false" }, ) except RequestSendFailed as e: logger.warning( "Request failed fetching remote media %s/%s: %r", server_name, media_id, e, ) raise SynapseError(502, "Failed to fetch remote media") except HttpResponseException as e: logger.warning( "HTTP error fetching remote media %s/%s: %s", server_name, media_id, e.response, ) if e.code == twisted.web.http.NOT_FOUND: raise e.to_synapse_error() raise SynapseError(502, "Failed to fetch remote media") except SynapseError: logger.warning( "Failed to fetch remote media %s/%s", server_name, media_id ) raise except NotRetryingDestination: logger.warning("Not retrying destination %r", server_name) raise SynapseError(502, "Failed to fetch remote media") except Exception: logger.exception( "Failed to fetch remote media %s/%s", server_name, media_id ) raise SynapseError(502, "Failed to fetch remote media") await finish() media_type = headers[b"Content-Type"][0].decode("ascii") upload_name = get_filename_from_headers(headers) time_now_ms = self.clock.time_msec() # Multiple remote media download requests can race (when using # multiple media repos), so this may throw a violation constraint # exception. If it does we'll delete the newly downloaded file from # disk (as we're in the ctx manager). # # However: we've already called `finish()` so we may have also # written to the storage providers. This is preferable to the # alternative where we call `finish()` *after* this, where we could # end up having an entry in the DB but fail to write the files to # the storage providers. await self.store.store_cached_remote_media( origin=server_name, media_id=media_id, media_type=media_type, time_now_ms=self.clock.time_msec(), upload_name=upload_name, media_length=length, filesystem_id=file_id, ) logger.info("Stored remote media in file %r", fname) media_info = { "media_type": media_type, "media_length": length, "upload_name": upload_name, "created_ts": time_now_ms, "filesystem_id": file_id, } return media_info def _get_thumbnail_requirements(self, media_type): return self.thumbnail_requirements.get(media_type, ()) def _generate_thumbnail(self, thumbnailer, t_width, t_height, t_method, t_type): m_width = thumbnailer.width m_height = thumbnailer.height if m_width * m_height >= self.max_image_pixels: logger.info( "Image too large to thumbnail %r x %r > %r", m_width, m_height, self.max_image_pixels, ) return if thumbnailer.transpose_method is not None: m_width, m_height = thumbnailer.transpose() if t_method == "crop": t_byte_source = thumbnailer.crop(t_width, t_height, t_type) elif t_method == "scale": t_width, t_height = thumbnailer.aspect(t_width, t_height) t_width = min(m_width, t_width) t_height = min(m_height, t_height) t_byte_source = thumbnailer.scale(t_width, t_height, t_type) else: t_byte_source = None return t_byte_source async def generate_local_exact_thumbnail( self, media_id: str, t_width: int, t_height: int, t_method: str, t_type: str, url_cache: str, ) -> Optional[str]: input_path = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(None, media_id, url_cache=url_cache) ) try: thumbnailer = Thumbnailer(input_path) except ThumbnailError as e: logger.warning( "Unable to generate a thumbnail for local media %s using a method of %s and type of %s: %s", media_id, t_method, t_type, e, ) return None t_byte_source = await defer_to_thread( self.hs.get_reactor(), self._generate_thumbnail, thumbnailer, t_width, t_height, t_method, t_type, ) if t_byte_source: try: file_info = FileInfo( server_name=None, file_id=media_id, url_cache=url_cache, thumbnail=True, thumbnail_width=t_width, thumbnail_height=t_height, thumbnail_method=t_method, thumbnail_type=t_type, ) output_path = await self.media_storage.store_file( t_byte_source, file_info ) finally: t_byte_source.close() logger.info("Stored thumbnail in file %r", output_path) t_len = os.path.getsize(output_path) await self.store.store_local_thumbnail( media_id, t_width, t_height, t_type, t_method, t_len ) return output_path # Could not generate thumbnail. return None async def generate_remote_exact_thumbnail( self, server_name: str, file_id: str, media_id: str, t_width: int, t_height: int, t_method: str, t_type: str, ) -> Optional[str]: input_path = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(server_name, file_id, url_cache=False) ) try: thumbnailer = Thumbnailer(input_path) except ThumbnailError as e: logger.warning( "Unable to generate a thumbnail for remote media %s from %s using a method of %s and type of %s: %s", media_id, server_name, t_method, t_type, e, ) return None t_byte_source = await defer_to_thread( self.hs.get_reactor(), self._generate_thumbnail, thumbnailer, t_width, t_height, t_method, t_type, ) if t_byte_source: try: file_info = FileInfo( server_name=server_name, file_id=file_id, thumbnail=True, thumbnail_width=t_width, thumbnail_height=t_height, thumbnail_method=t_method, thumbnail_type=t_type, ) output_path = await self.media_storage.store_file( t_byte_source, file_info ) finally: t_byte_source.close() logger.info("Stored thumbnail in file %r", output_path) t_len = os.path.getsize(output_path) await self.store.store_remote_media_thumbnail( server_name, media_id, file_id, t_width, t_height, t_type, t_method, t_len, ) return output_path # Could not generate thumbnail. return None async def _generate_thumbnails( self, server_name: Optional[str], media_id: str, file_id: str, media_type: str, url_cache: bool = False, ) -> Optional[dict]: """Generate and store thumbnails for an image. Args: server_name: The server name if remote media, else None if local media_id: The media ID of the content. (This is the same as the file_id for local content) file_id: Local file ID media_type: The content type of the file url_cache: If we are thumbnailing images downloaded for the URL cache, used exclusively by the url previewer Returns: Dict with "width" and "height" keys of original image or None if the media cannot be thumbnailed. """ requirements = self._get_thumbnail_requirements(media_type) if not requirements: return None input_path = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(server_name, file_id, url_cache=url_cache) ) try: thumbnailer = Thumbnailer(input_path) except ThumbnailError as e: logger.warning( "Unable to generate thumbnails for remote media %s from %s of type %s: %s", media_id, server_name, media_type, e, ) return None m_width = thumbnailer.width m_height = thumbnailer.height if m_width * m_height >= self.max_image_pixels: logger.info( "Image too large to thumbnail %r x %r > %r", m_width, m_height, self.max_image_pixels, ) return None if thumbnailer.transpose_method is not None: m_width, m_height = await defer_to_thread( self.hs.get_reactor(), thumbnailer.transpose ) # We deduplicate the thumbnail sizes by ignoring the cropped versions if # they have the same dimensions of a scaled one. thumbnails = {} # type: Dict[Tuple[int, int, str], str] for r_width, r_height, r_method, r_type in requirements: if r_method == "crop": thumbnails.setdefault((r_width, r_height, r_type), r_method) elif r_method == "scale": t_width, t_height = thumbnailer.aspect(r_width, r_height) t_width = min(m_width, t_width) t_height = min(m_height, t_height) thumbnails[(t_width, t_height, r_type)] = r_method # Now we generate the thumbnails for each dimension, store it for (t_width, t_height, t_type), t_method in thumbnails.items(): # Generate the thumbnail if t_method == "crop": t_byte_source = await defer_to_thread( self.hs.get_reactor(), thumbnailer.crop, t_width, t_height, t_type ) elif t_method == "scale": t_byte_source = await defer_to_thread( self.hs.get_reactor(), thumbnailer.scale, t_width, t_height, t_type ) else: logger.error("Unrecognized method: %r", t_method) continue if not t_byte_source: continue file_info = FileInfo( server_name=server_name, file_id=file_id, thumbnail=True, thumbnail_width=t_width, thumbnail_height=t_height, thumbnail_method=t_method, thumbnail_type=t_type, url_cache=url_cache, ) with self.media_storage.store_into_file(file_info) as (f, fname, finish): try: await self.media_storage.write_to_file(t_byte_source, f) await finish() finally: t_byte_source.close() t_len = os.path.getsize(fname) # Write to database if server_name: # Multiple remote media download requests can race (when # using multiple media repos), so this may throw a violation # constraint exception. If it does we'll delete the newly # generated thumbnail from disk (as we're in the ctx # manager). # # However: we've already called `finish()` so we may have # also written to the storage providers. This is preferable # to the alternative where we call `finish()` *after* this, # where we could end up having an entry in the DB but fail # to write the files to the storage providers. try: await self.store.store_remote_media_thumbnail( server_name, media_id, file_id, t_width, t_height, t_type, t_method, t_len, ) except Exception as e: thumbnail_exists = await self.store.get_remote_media_thumbnail( server_name, media_id, t_width, t_height, t_type, ) if not thumbnail_exists: raise e else: await self.store.store_local_thumbnail( media_id, t_width, t_height, t_type, t_method, t_len ) return {"width": m_width, "height": m_height} async def delete_old_remote_media(self, before_ts): old_media = await self.store.get_remote_media_before(before_ts) deleted = 0 for media in old_media: origin = media["media_origin"] media_id = media["media_id"] file_id = media["filesystem_id"] key = (origin, media_id) logger.info("Deleting: %r", key) # TODO: Should we delete from the backup store with (await self.remote_media_linearizer.queue(key)): full_path = self.filepaths.remote_media_filepath(origin, file_id) try: os.remove(full_path) except OSError as e: logger.warning("Failed to remove file: %r", full_path) if e.errno == errno.ENOENT: pass else: continue thumbnail_dir = self.filepaths.remote_media_thumbnail_dir( origin, file_id ) shutil.rmtree(thumbnail_dir, ignore_errors=True) await self.store.delete_remote_media(origin, media_id) deleted += 1 return {"deleted": deleted} async def delete_local_media(self, media_id: str) -> Tuple[List[str], int]: """ Delete the given local or remote media ID from this server Args: media_id: The media ID to delete. Returns: A tuple of (list of deleted media IDs, total deleted media IDs). """ return await self._remove_local_media_from_disk([media_id]) async def delete_old_local_media( self, before_ts: int, size_gt: int = 0, keep_profiles: bool = True, ) -> Tuple[List[str], int]: """ Delete local or remote media from this server by size and timestamp. Removes media files, any thumbnails and cached URLs. Args: before_ts: Unix timestamp in ms. Files that were last used before this timestamp will be deleted size_gt: Size of the media in bytes. Files that are larger will be deleted keep_profiles: Switch to delete also files that are still used in image data (e.g user profile, room avatar) If false these files will be deleted Returns: A tuple of (list of deleted media IDs, total deleted media IDs). """ old_media = await self.store.get_local_media_before( before_ts, size_gt, keep_profiles, ) return await self._remove_local_media_from_disk(old_media) async def _remove_local_media_from_disk( self, media_ids: List[str] ) -> Tuple[List[str], int]: """ Delete local or remote media from this server. Removes media files, any thumbnails and cached URLs. Args: media_ids: List of media_id to delete Returns: A tuple of (list of deleted media IDs, total deleted media IDs). """ removed_media = [] for media_id in media_ids: logger.info("Deleting media with ID '%s'", media_id) full_path = self.filepaths.local_media_filepath(media_id) try: os.remove(full_path) except OSError as e: logger.warning("Failed to remove file: %r: %s", full_path, e) if e.errno == errno.ENOENT: pass else: continue thumbnail_dir = self.filepaths.local_media_thumbnail_dir(media_id) shutil.rmtree(thumbnail_dir, ignore_errors=True) await self.store.delete_remote_media(self.server_name, media_id) await self.store.delete_url_cache((media_id,)) await self.store.delete_url_cache_media((media_id,)) removed_media.append(media_id) return removed_media, len(removed_media) class MediaRepositoryResource(Resource): """File uploading and downloading. Uploads are POSTed to a resource which returns a token which is used to GET the download:: => POST /_matrix/media/r0/upload HTTP/1.1 Content-Type: <media-type> Content-Length: <content-length> <media> <= HTTP/1.1 200 OK Content-Type: application/json { "content_uri": "mxc://<server-name>/<media-id>" } => GET /_matrix/media/r0/download/<server-name>/<media-id> HTTP/1.1 <= HTTP/1.1 200 OK Content-Type: <media-type> Content-Disposition: attachment;filename=<upload-filename> <media> Clients can get thumbnails by supplying a desired width and height and thumbnailing method:: => GET /_matrix/media/r0/thumbnail/<server_name> /<media-id>?width=<w>&height=<h>&method=<m> HTTP/1.1 <= HTTP/1.1 200 OK Content-Type: image/jpeg or image/png <thumbnail> The thumbnail methods are "crop" and "scale". "scale" trys to return an image where either the width or the height is smaller than the requested size. The client should then scale and letterbox the image if it needs to fit within a given rectangle. "crop" trys to return an image where the width and height are close to the requested size and the aspect matches the requested size. The client should scale the image if it needs to fit within a given rectangle. """ def __init__(self, hs): # If we're not configured to use it, raise if we somehow got here. if not hs.config.can_load_media_repo: raise ConfigError("Synapse is not configured to use a media repo.") super().__init__() media_repo = hs.get_media_repository() self.putChild(b"upload", UploadResource(hs, media_repo)) self.putChild(b"download", DownloadResource(hs, media_repo)) self.putChild( b"thumbnail", ThumbnailResource(hs, media_repo, media_repo.media_storage) ) if hs.config.url_preview_enabled: self.putChild( b"preview_url", PreviewUrlResource(hs, media_repo, media_repo.media_storage), ) self.putChild(b"config", MediaConfigResource(hs))
open_redirect
{ "code": [ " self.client = hs.get_http_client()" ], "line_no": [ 69 ] }
{ "code": [ " self.client = hs.get_federation_http_client()" ], "line_no": [ 69 ] }
import errno import logging import os import shutil from typing import IO, Dict, List, Optional, Tuple import twisted.internet.error import twisted.web.http from twisted.web.http import Request from twisted.web.resource import Resource from synapse.api.errors import ( FederationDeniedError, HttpResponseException, NotFoundError, RequestSendFailed, SynapseError, ) from synapse.config._base import ConfigError from synapse.logging.context import defer_to_thread from synapse.metrics.background_process_metrics import run_as_background_process from synapse.util.async_helpers import Linearizer from synapse.util.retryutils import NotRetryingDestination from synapse.util.stringutils import random_string from ._base import ( FileInfo, Responder, get_filename_from_headers, respond_404, respond_with_responder, ) from .config_resource import MediaConfigResource from .download_resource import DownloadResource from .filepath import MediaFilePaths from .media_storage import MediaStorage from .preview_url_resource import PreviewUrlResource from .storage_provider import StorageProviderWrapper from .thumbnail_resource import ThumbnailResource from .thumbnailer import Thumbnailer, ThumbnailError from .upload_resource import UploadResource VAR_0 = logging.getLogger(__name__) VAR_1 = 60 * 1000 class CLASS_0: def __init__(self, VAR_2): self.hs = VAR_2 self.auth = VAR_2.get_auth() self.client = VAR_2.get_http_client() self.clock = VAR_2.get_clock() self.server_name = VAR_2.hostname self.store = VAR_2.get_datastore() self.max_upload_size = VAR_2.config.max_upload_size self.max_image_pixels = VAR_2.config.max_image_pixels self.primary_base_path = VAR_2.config.media_store_path self.filepaths = MediaFilePaths(self.primary_base_path) self.dynamic_thumbnails = VAR_2.config.dynamic_thumbnails self.thumbnail_requirements = VAR_2.config.thumbnail_requirements self.remote_media_linearizer = Linearizer(VAR_11="media_remote") self.recently_accessed_remotes = set() self.recently_accessed_locals = set() self.federation_domain_whitelist = VAR_2.config.federation_domain_whitelist VAR_23 = [] for clz, provider_config, wrapper_config in VAR_2.config.media_storage_providers: VAR_42 = clz(VAR_2, provider_config) VAR_43 = StorageProviderWrapper( VAR_42, store_local=wrapper_config.store_local, store_remote=wrapper_config.store_remote, store_synchronous=wrapper_config.store_synchronous, ) VAR_23.append(VAR_43) self.media_storage = MediaStorage( self.hs, self.primary_base_path, self.filepaths, VAR_23 ) self.clock.looping_call( self._start_update_recently_accessed, VAR_1 ) def FUNC_0(self): return run_as_background_process( "update_recently_accessed_media", self._update_recently_accessed ) async def FUNC_1(self): VAR_24 = self.recently_accessed_remotes self.recently_accessed_remotes = set() VAR_25 = self.recently_accessed_locals self.recently_accessed_locals = set() await self.store.update_cached_last_access_time( VAR_25, VAR_24, self.clock.time_msec() ) def FUNC_2(self, VAR_3, VAR_4): if VAR_3: self.recently_accessed_remotes.add((VAR_3, VAR_4)) else: self.recently_accessed_locals.add(VAR_4) async def FUNC_3( self, VAR_5: str, VAR_6: Optional[str], VAR_7: IO, VAR_8: int, VAR_9: str, ) -> str: VAR_4 = random_string(24) VAR_26 = FileInfo(VAR_3=None, VAR_18=VAR_4) VAR_27 = await self.media_storage.store_file(VAR_7, VAR_26) VAR_0.info("Stored local media in file %r", VAR_27) await self.store.store_local_media( VAR_4=media_id, VAR_5=media_type, VAR_45=self.clock.time_msec(), VAR_6=upload_name, VAR_29=VAR_8, user_id=VAR_9, ) await self._generate_thumbnails(None, VAR_4, VAR_4, VAR_5) return "mxc://%s/%s" % (self.server_name, VAR_4) async def FUNC_4( self, VAR_10: Request, VAR_4: str, VAR_11: Optional[str] ) -> None: VAR_28 = await self.store.get_local_media(VAR_4) if not VAR_28 or VAR_28["quarantined_by"]: respond_404(VAR_10) return self.mark_recently_accessed(None, VAR_4) VAR_5 = VAR_28["media_type"] VAR_29 = VAR_28["media_length"] VAR_6 = VAR_11 if VAR_11 else VAR_28["upload_name"] VAR_17 = VAR_28["url_cache"] VAR_26 = FileInfo(None, VAR_4, VAR_17=url_cache) VAR_30 = await self.media_storage.fetch_media(VAR_26) await respond_with_responder( VAR_10, VAR_30, VAR_5, VAR_29, VAR_6 ) async def FUNC_5( self, VAR_10: Request, VAR_3: str, VAR_4: str, VAR_11: Optional[str] ) -> None: if ( self.federation_domain_whitelist is not None and VAR_3 not in self.federation_domain_whitelist ): raise FederationDeniedError(VAR_3) self.mark_recently_accessed(VAR_3, VAR_4) VAR_31 = (VAR_3, VAR_4) with (await self.remote_media_linearizer.queue(VAR_31)): VAR_30, VAR_28 = await self._get_remote_media_impl( VAR_3, VAR_4 ) if VAR_30: VAR_5 = VAR_28["media_type"] VAR_29 = VAR_28["media_length"] VAR_6 = VAR_11 if VAR_11 else VAR_28["upload_name"] await respond_with_responder( VAR_10, VAR_30, VAR_5, VAR_29, VAR_6 ) else: respond_404(VAR_10) async def FUNC_6(self, VAR_3: str, VAR_4: str) -> dict: if ( self.federation_domain_whitelist is not None and VAR_3 not in self.federation_domain_whitelist ): raise FederationDeniedError(VAR_3) VAR_31 = (VAR_3, VAR_4) with (await self.remote_media_linearizer.queue(VAR_31)): VAR_30, VAR_28 = await self._get_remote_media_impl( VAR_3, VAR_4 ) if VAR_30: with VAR_30: pass return VAR_28 async def FUNC_7( self, VAR_3: str, VAR_4: str ) -> Tuple[Optional[Responder], dict]: VAR_28 = await self.store.get_cached_remote_media(VAR_3, VAR_4) if VAR_28: VAR_18 = VAR_28["filesystem_id"] VAR_26 = FileInfo(VAR_3, VAR_18) if VAR_28["quarantined_by"]: VAR_0.info("Media is quarantined") raise NotFoundError() VAR_30 = await self.media_storage.fetch_media(VAR_26) if VAR_30: return VAR_30, VAR_28 try: VAR_28 = await self._download_remote_file(VAR_3, VAR_4,) except SynapseError: raise except Exception as e: VAR_28 = await self.store.get_cached_remote_media(VAR_3, VAR_4) if not VAR_28: raise e VAR_18 = VAR_28["filesystem_id"] VAR_26 = FileInfo(VAR_3, VAR_18) await self._generate_thumbnails( VAR_3, VAR_4, VAR_18, VAR_28["media_type"] ) VAR_30 = await self.media_storage.fetch_media(VAR_26) return VAR_30, VAR_28 async def FUNC_8(self, VAR_3: str, VAR_4: str,) -> dict: VAR_18 = random_string(24) VAR_26 = FileInfo(VAR_3=server_name, VAR_18=file_id) with self.media_storage.store_into_file(VAR_26) as (f, VAR_27, finish): VAR_44 = "/".join( ("/_matrix/media/r0/download", VAR_3, VAR_4) ) try: VAR_50, VAR_51 = await self.client.get_file( VAR_3, VAR_44, output_stream=f, max_size=self.max_upload_size, args={ "allow_remote": "false" }, ) except RequestSendFailed as e: VAR_0.warning( "Request failed fetching remote media %s/%s: %r", VAR_3, VAR_4, e, ) raise SynapseError(502, "Failed to fetch remote media") except HttpResponseException as e: VAR_0.warning( "HTTP error fetching remote media %s/%s: %s", VAR_3, VAR_4, e.response, ) if e.code == twisted.web.http.NOT_FOUND: raise e.to_synapse_error() raise SynapseError(502, "Failed to fetch remote media") except SynapseError: VAR_0.warning( "Failed to fetch remote media %s/%s", VAR_3, VAR_4 ) raise except NotRetryingDestination: VAR_0.warning("Not retrying destination %r", VAR_3) raise SynapseError(502, "Failed to fetch remote media") except Exception: VAR_0.exception( "Failed to fetch remote media %s/%s", VAR_3, VAR_4 ) raise SynapseError(502, "Failed to fetch remote media") await finish() VAR_5 = VAR_51[b"Content-Type"][0].decode("ascii") VAR_6 = get_filename_from_headers(VAR_51) VAR_45 = self.clock.time_msec() await self.store.store_cached_remote_media( VAR_47=VAR_3, VAR_4=media_id, VAR_5=media_type, VAR_45=self.clock.time_msec(), VAR_6=upload_name, VAR_29=VAR_50, filesystem_id=VAR_18, ) VAR_0.info("Stored remote media in file %r", VAR_27) VAR_28 = { "media_type": VAR_5, "media_length": VAR_50, "upload_name": VAR_6, "created_ts": VAR_45, "filesystem_id": VAR_18, } return VAR_28 def FUNC_9(self, VAR_5): return self.thumbnail_requirements.get(VAR_5, ()) def FUNC_10(self, VAR_12, VAR_13, VAR_14, VAR_15, VAR_16): VAR_32 = VAR_12.width VAR_33 = VAR_12.height if VAR_32 * VAR_33 >= self.max_image_pixels: VAR_0.info( "Image too large to thumbnail %r x %r > %r", VAR_32, VAR_33, self.max_image_pixels, ) return if VAR_12.transpose_method is not None: VAR_32, VAR_33 = VAR_12.transpose() if VAR_15 == "crop": VAR_35 = VAR_12.crop(VAR_13, VAR_14, VAR_16) elif VAR_15 == "scale": VAR_13, VAR_14 = VAR_12.aspect(VAR_13, VAR_14) VAR_13 = min(VAR_32, VAR_13) VAR_14 = min(VAR_33, VAR_14) VAR_35 = VAR_12.scale(VAR_13, VAR_14, VAR_16) else: VAR_35 = None return VAR_35 async def FUNC_11( self, VAR_4: str, VAR_13: int, VAR_14: int, VAR_15: str, VAR_16: str, VAR_17: str, ) -> Optional[str]: VAR_34 = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(None, VAR_4, VAR_17=url_cache) ) try: VAR_12 = Thumbnailer(VAR_34) except ThumbnailError as e: VAR_0.warning( "Unable to generate a thumbnail for local media %s using a method of %s and type of %s: %s", VAR_4, VAR_15, VAR_16, e, ) return None VAR_35 = await defer_to_thread( self.hs.get_reactor(), self._generate_thumbnail, VAR_12, VAR_13, VAR_14, VAR_15, VAR_16, ) if VAR_35: try: VAR_26 = FileInfo( VAR_3=None, VAR_18=VAR_4, VAR_17=url_cache, thumbnail=True, thumbnail_width=VAR_13, thumbnail_height=VAR_14, thumbnail_method=VAR_15, thumbnail_type=VAR_16, ) VAR_52 = await self.media_storage.store_file( VAR_35, VAR_26 ) finally: VAR_35.close() VAR_0.info("Stored thumbnail in file %r", VAR_52) VAR_46 = os.path.getsize(VAR_52) await self.store.store_local_thumbnail( VAR_4, VAR_13, VAR_14, VAR_16, VAR_15, VAR_46 ) return VAR_52 return None async def FUNC_12( self, VAR_3: str, VAR_18: str, VAR_4: str, VAR_13: int, VAR_14: int, VAR_15: str, VAR_16: str, ) -> Optional[str]: VAR_34 = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(VAR_3, VAR_18, VAR_17=False) ) try: VAR_12 = Thumbnailer(VAR_34) except ThumbnailError as e: VAR_0.warning( "Unable to generate a thumbnail for remote media %s from %s using a method of %s and type of %s: %s", VAR_4, VAR_3, VAR_15, VAR_16, e, ) return None VAR_35 = await defer_to_thread( self.hs.get_reactor(), self._generate_thumbnail, VAR_12, VAR_13, VAR_14, VAR_15, VAR_16, ) if VAR_35: try: VAR_26 = FileInfo( VAR_3=VAR_3, VAR_18=file_id, thumbnail=True, thumbnail_width=VAR_13, thumbnail_height=VAR_14, thumbnail_method=VAR_15, thumbnail_type=VAR_16, ) VAR_52 = await self.media_storage.store_file( VAR_35, VAR_26 ) finally: VAR_35.close() VAR_0.info("Stored thumbnail in file %r", VAR_52) VAR_46 = os.path.getsize(VAR_52) await self.store.store_remote_media_thumbnail( VAR_3, VAR_4, VAR_18, VAR_13, VAR_14, VAR_16, VAR_15, VAR_46, ) return VAR_52 return None async def FUNC_13( self, VAR_3: Optional[str], VAR_4: str, VAR_18: str, VAR_5: str, VAR_17: bool = False, ) -> Optional[dict]: VAR_36 = self._get_thumbnail_requirements(VAR_5) if not VAR_36: return None VAR_34 = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(VAR_3, VAR_18, VAR_17=url_cache) ) try: VAR_12 = Thumbnailer(VAR_34) except ThumbnailError as e: VAR_0.warning( "Unable to generate VAR_37 for remote media %s from %s of type %s: %s", VAR_4, VAR_3, VAR_5, e, ) return None VAR_32 = VAR_12.width VAR_33 = VAR_12.height if VAR_32 * VAR_33 >= self.max_image_pixels: VAR_0.info( "Image too large to thumbnail %r x %r > %r", VAR_32, VAR_33, self.max_image_pixels, ) return None if VAR_12.transpose_method is not None: VAR_32, VAR_33 = await defer_to_thread( self.hs.get_reactor(), VAR_12.transpose ) VAR_37 = {} # type: Dict[Tuple[int, int, str], str] for r_width, r_height, r_method, VAR_53 in VAR_36: if r_method == "crop": VAR_37.setdefault((r_width, r_height, VAR_53), r_method) elif r_method == "scale": VAR_13, VAR_14 = VAR_12.aspect(r_width, r_height) VAR_13 = min(VAR_32, VAR_13) VAR_14 = min(VAR_33, VAR_14) VAR_37[(VAR_13, VAR_14, VAR_53)] = r_method for (VAR_13, VAR_14, VAR_16), VAR_15 in VAR_37.items(): if VAR_15 == "crop": VAR_35 = await defer_to_thread( self.hs.get_reactor(), VAR_12.crop, VAR_13, VAR_14, VAR_16 ) elif VAR_15 == "scale": VAR_35 = await defer_to_thread( self.hs.get_reactor(), VAR_12.scale, VAR_13, VAR_14, VAR_16 ) else: VAR_0.error("Unrecognized method: %r", VAR_15) continue if not VAR_35: continue VAR_26 = FileInfo( VAR_3=VAR_3, VAR_18=file_id, thumbnail=True, thumbnail_width=VAR_13, thumbnail_height=VAR_14, thumbnail_method=VAR_15, thumbnail_type=VAR_16, VAR_17=url_cache, ) with self.media_storage.store_into_file(VAR_26) as (f, VAR_27, finish): try: await self.media_storage.write_to_file(VAR_35, f) await finish() finally: VAR_35.close() VAR_46 = os.path.getsize(VAR_27) if VAR_3: try: await self.store.store_remote_media_thumbnail( VAR_3, VAR_4, VAR_18, VAR_13, VAR_14, VAR_16, VAR_15, VAR_46, ) except Exception as e: VAR_54 = await self.store.get_remote_media_thumbnail( VAR_3, VAR_4, VAR_13, VAR_14, VAR_16, ) if not VAR_54: raise e else: await self.store.store_local_thumbnail( VAR_4, VAR_13, VAR_14, VAR_16, VAR_15, VAR_46 ) return {"width": VAR_32, "height": VAR_33} async def FUNC_14(self, VAR_19): VAR_38 = await self.store.get_remote_media_before(VAR_19) VAR_39 = 0 for media in VAR_38: VAR_47 = media["media_origin"] VAR_4 = media["media_id"] VAR_18 = media["filesystem_id"] VAR_31 = (VAR_47, VAR_4) VAR_0.info("Deleting: %r", VAR_31) with (await self.remote_media_linearizer.queue(VAR_31)): VAR_48 = self.filepaths.remote_media_filepath(VAR_47, VAR_18) try: os.remove(VAR_48) except OSError as e: VAR_0.warning("Failed to remove file: %r", VAR_48) if e.errno == errno.ENOENT: pass else: continue VAR_49 = self.filepaths.remote_media_thumbnail_dir( VAR_47, VAR_18 ) shutil.rmtree(VAR_49, ignore_errors=True) await self.store.delete_remote_media(VAR_47, VAR_4) VAR_39 += 1 return {"deleted": VAR_39} async def FUNC_15(self, VAR_4: str) -> Tuple[List[str], int]: return await self._remove_local_media_from_disk([VAR_4]) async def FUNC_16( self, VAR_19: int, VAR_20: int = 0, VAR_21: bool = True, ) -> Tuple[List[str], int]: VAR_38 = await self.store.get_local_media_before( VAR_19, VAR_20, VAR_21, ) return await self._remove_local_media_from_disk(VAR_38) async def FUNC_17( self, VAR_22: List[str] ) -> Tuple[List[str], int]: VAR_40 = [] for VAR_4 in VAR_22: VAR_0.info("Deleting media with ID '%s'", VAR_4) VAR_48 = self.filepaths.local_media_filepath(VAR_4) try: os.remove(VAR_48) except OSError as e: VAR_0.warning("Failed to remove file: %r: %s", VAR_48, e) if e.errno == errno.ENOENT: pass else: continue VAR_49 = self.filepaths.local_media_thumbnail_dir(VAR_4) shutil.rmtree(VAR_49, ignore_errors=True) await self.store.delete_remote_media(self.server_name, VAR_4) await self.store.delete_url_cache((VAR_4,)) await self.store.delete_url_cache_media((VAR_4,)) VAR_40.append(VAR_4) return VAR_40, len(VAR_40) class CLASS_1(Resource): def __init__(self, VAR_2): if not VAR_2.config.can_load_media_repo: raise ConfigError("Synapse is not configured to use a media repo.") super().__init__() VAR_41 = VAR_2.get_media_repository() self.putChild(b"upload", UploadResource(VAR_2, VAR_41)) self.putChild(b"download", DownloadResource(VAR_2, VAR_41)) self.putChild( b"thumbnail", ThumbnailResource(VAR_2, VAR_41, media_repo.media_storage) ) if VAR_2.config.url_preview_enabled: self.putChild( b"preview_url", PreviewUrlResource(VAR_2, VAR_41, media_repo.media_storage), ) self.putChild(b"config", MediaConfigResource(VAR_2))
import errno import logging import os import shutil from typing import IO, Dict, List, Optional, Tuple import twisted.internet.error import twisted.web.http from twisted.web.http import Request from twisted.web.resource import Resource from synapse.api.errors import ( FederationDeniedError, HttpResponseException, NotFoundError, RequestSendFailed, SynapseError, ) from synapse.config._base import ConfigError from synapse.logging.context import defer_to_thread from synapse.metrics.background_process_metrics import run_as_background_process from synapse.util.async_helpers import Linearizer from synapse.util.retryutils import NotRetryingDestination from synapse.util.stringutils import random_string from ._base import ( FileInfo, Responder, get_filename_from_headers, respond_404, respond_with_responder, ) from .config_resource import MediaConfigResource from .download_resource import DownloadResource from .filepath import MediaFilePaths from .media_storage import MediaStorage from .preview_url_resource import PreviewUrlResource from .storage_provider import StorageProviderWrapper from .thumbnail_resource import ThumbnailResource from .thumbnailer import Thumbnailer, ThumbnailError from .upload_resource import UploadResource VAR_0 = logging.getLogger(__name__) VAR_1 = 60 * 1000 class CLASS_0: def __init__(self, VAR_2): self.hs = VAR_2 self.auth = VAR_2.get_auth() self.client = VAR_2.get_federation_http_client() self.clock = VAR_2.get_clock() self.server_name = VAR_2.hostname self.store = VAR_2.get_datastore() self.max_upload_size = VAR_2.config.max_upload_size self.max_image_pixels = VAR_2.config.max_image_pixels self.primary_base_path = VAR_2.config.media_store_path self.filepaths = MediaFilePaths(self.primary_base_path) self.dynamic_thumbnails = VAR_2.config.dynamic_thumbnails self.thumbnail_requirements = VAR_2.config.thumbnail_requirements self.remote_media_linearizer = Linearizer(VAR_11="media_remote") self.recently_accessed_remotes = set() self.recently_accessed_locals = set() self.federation_domain_whitelist = VAR_2.config.federation_domain_whitelist VAR_23 = [] for clz, provider_config, wrapper_config in VAR_2.config.media_storage_providers: VAR_42 = clz(VAR_2, provider_config) VAR_43 = StorageProviderWrapper( VAR_42, store_local=wrapper_config.store_local, store_remote=wrapper_config.store_remote, store_synchronous=wrapper_config.store_synchronous, ) VAR_23.append(VAR_43) self.media_storage = MediaStorage( self.hs, self.primary_base_path, self.filepaths, VAR_23 ) self.clock.looping_call( self._start_update_recently_accessed, VAR_1 ) def FUNC_0(self): return run_as_background_process( "update_recently_accessed_media", self._update_recently_accessed ) async def FUNC_1(self): VAR_24 = self.recently_accessed_remotes self.recently_accessed_remotes = set() VAR_25 = self.recently_accessed_locals self.recently_accessed_locals = set() await self.store.update_cached_last_access_time( VAR_25, VAR_24, self.clock.time_msec() ) def FUNC_2(self, VAR_3, VAR_4): if VAR_3: self.recently_accessed_remotes.add((VAR_3, VAR_4)) else: self.recently_accessed_locals.add(VAR_4) async def FUNC_3( self, VAR_5: str, VAR_6: Optional[str], VAR_7: IO, VAR_8: int, VAR_9: str, ) -> str: VAR_4 = random_string(24) VAR_26 = FileInfo(VAR_3=None, VAR_18=VAR_4) VAR_27 = await self.media_storage.store_file(VAR_7, VAR_26) VAR_0.info("Stored local media in file %r", VAR_27) await self.store.store_local_media( VAR_4=media_id, VAR_5=media_type, VAR_45=self.clock.time_msec(), VAR_6=upload_name, VAR_29=VAR_8, user_id=VAR_9, ) await self._generate_thumbnails(None, VAR_4, VAR_4, VAR_5) return "mxc://%s/%s" % (self.server_name, VAR_4) async def FUNC_4( self, VAR_10: Request, VAR_4: str, VAR_11: Optional[str] ) -> None: VAR_28 = await self.store.get_local_media(VAR_4) if not VAR_28 or VAR_28["quarantined_by"]: respond_404(VAR_10) return self.mark_recently_accessed(None, VAR_4) VAR_5 = VAR_28["media_type"] VAR_29 = VAR_28["media_length"] VAR_6 = VAR_11 if VAR_11 else VAR_28["upload_name"] VAR_17 = VAR_28["url_cache"] VAR_26 = FileInfo(None, VAR_4, VAR_17=url_cache) VAR_30 = await self.media_storage.fetch_media(VAR_26) await respond_with_responder( VAR_10, VAR_30, VAR_5, VAR_29, VAR_6 ) async def FUNC_5( self, VAR_10: Request, VAR_3: str, VAR_4: str, VAR_11: Optional[str] ) -> None: if ( self.federation_domain_whitelist is not None and VAR_3 not in self.federation_domain_whitelist ): raise FederationDeniedError(VAR_3) self.mark_recently_accessed(VAR_3, VAR_4) VAR_31 = (VAR_3, VAR_4) with (await self.remote_media_linearizer.queue(VAR_31)): VAR_30, VAR_28 = await self._get_remote_media_impl( VAR_3, VAR_4 ) if VAR_30: VAR_5 = VAR_28["media_type"] VAR_29 = VAR_28["media_length"] VAR_6 = VAR_11 if VAR_11 else VAR_28["upload_name"] await respond_with_responder( VAR_10, VAR_30, VAR_5, VAR_29, VAR_6 ) else: respond_404(VAR_10) async def FUNC_6(self, VAR_3: str, VAR_4: str) -> dict: if ( self.federation_domain_whitelist is not None and VAR_3 not in self.federation_domain_whitelist ): raise FederationDeniedError(VAR_3) VAR_31 = (VAR_3, VAR_4) with (await self.remote_media_linearizer.queue(VAR_31)): VAR_30, VAR_28 = await self._get_remote_media_impl( VAR_3, VAR_4 ) if VAR_30: with VAR_30: pass return VAR_28 async def FUNC_7( self, VAR_3: str, VAR_4: str ) -> Tuple[Optional[Responder], dict]: VAR_28 = await self.store.get_cached_remote_media(VAR_3, VAR_4) if VAR_28: VAR_18 = VAR_28["filesystem_id"] VAR_26 = FileInfo(VAR_3, VAR_18) if VAR_28["quarantined_by"]: VAR_0.info("Media is quarantined") raise NotFoundError() VAR_30 = await self.media_storage.fetch_media(VAR_26) if VAR_30: return VAR_30, VAR_28 try: VAR_28 = await self._download_remote_file(VAR_3, VAR_4,) except SynapseError: raise except Exception as e: VAR_28 = await self.store.get_cached_remote_media(VAR_3, VAR_4) if not VAR_28: raise e VAR_18 = VAR_28["filesystem_id"] VAR_26 = FileInfo(VAR_3, VAR_18) await self._generate_thumbnails( VAR_3, VAR_4, VAR_18, VAR_28["media_type"] ) VAR_30 = await self.media_storage.fetch_media(VAR_26) return VAR_30, VAR_28 async def FUNC_8(self, VAR_3: str, VAR_4: str,) -> dict: VAR_18 = random_string(24) VAR_26 = FileInfo(VAR_3=server_name, VAR_18=file_id) with self.media_storage.store_into_file(VAR_26) as (f, VAR_27, finish): VAR_44 = "/".join( ("/_matrix/media/r0/download", VAR_3, VAR_4) ) try: VAR_50, VAR_51 = await self.client.get_file( VAR_3, VAR_44, output_stream=f, max_size=self.max_upload_size, args={ "allow_remote": "false" }, ) except RequestSendFailed as e: VAR_0.warning( "Request failed fetching remote media %s/%s: %r", VAR_3, VAR_4, e, ) raise SynapseError(502, "Failed to fetch remote media") except HttpResponseException as e: VAR_0.warning( "HTTP error fetching remote media %s/%s: %s", VAR_3, VAR_4, e.response, ) if e.code == twisted.web.http.NOT_FOUND: raise e.to_synapse_error() raise SynapseError(502, "Failed to fetch remote media") except SynapseError: VAR_0.warning( "Failed to fetch remote media %s/%s", VAR_3, VAR_4 ) raise except NotRetryingDestination: VAR_0.warning("Not retrying destination %r", VAR_3) raise SynapseError(502, "Failed to fetch remote media") except Exception: VAR_0.exception( "Failed to fetch remote media %s/%s", VAR_3, VAR_4 ) raise SynapseError(502, "Failed to fetch remote media") await finish() VAR_5 = VAR_51[b"Content-Type"][0].decode("ascii") VAR_6 = get_filename_from_headers(VAR_51) VAR_45 = self.clock.time_msec() await self.store.store_cached_remote_media( VAR_47=VAR_3, VAR_4=media_id, VAR_5=media_type, VAR_45=self.clock.time_msec(), VAR_6=upload_name, VAR_29=VAR_50, filesystem_id=VAR_18, ) VAR_0.info("Stored remote media in file %r", VAR_27) VAR_28 = { "media_type": VAR_5, "media_length": VAR_50, "upload_name": VAR_6, "created_ts": VAR_45, "filesystem_id": VAR_18, } return VAR_28 def FUNC_9(self, VAR_5): return self.thumbnail_requirements.get(VAR_5, ()) def FUNC_10(self, VAR_12, VAR_13, VAR_14, VAR_15, VAR_16): VAR_32 = VAR_12.width VAR_33 = VAR_12.height if VAR_32 * VAR_33 >= self.max_image_pixels: VAR_0.info( "Image too large to thumbnail %r x %r > %r", VAR_32, VAR_33, self.max_image_pixels, ) return if VAR_12.transpose_method is not None: VAR_32, VAR_33 = VAR_12.transpose() if VAR_15 == "crop": VAR_35 = VAR_12.crop(VAR_13, VAR_14, VAR_16) elif VAR_15 == "scale": VAR_13, VAR_14 = VAR_12.aspect(VAR_13, VAR_14) VAR_13 = min(VAR_32, VAR_13) VAR_14 = min(VAR_33, VAR_14) VAR_35 = VAR_12.scale(VAR_13, VAR_14, VAR_16) else: VAR_35 = None return VAR_35 async def FUNC_11( self, VAR_4: str, VAR_13: int, VAR_14: int, VAR_15: str, VAR_16: str, VAR_17: str, ) -> Optional[str]: VAR_34 = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(None, VAR_4, VAR_17=url_cache) ) try: VAR_12 = Thumbnailer(VAR_34) except ThumbnailError as e: VAR_0.warning( "Unable to generate a thumbnail for local media %s using a method of %s and type of %s: %s", VAR_4, VAR_15, VAR_16, e, ) return None VAR_35 = await defer_to_thread( self.hs.get_reactor(), self._generate_thumbnail, VAR_12, VAR_13, VAR_14, VAR_15, VAR_16, ) if VAR_35: try: VAR_26 = FileInfo( VAR_3=None, VAR_18=VAR_4, VAR_17=url_cache, thumbnail=True, thumbnail_width=VAR_13, thumbnail_height=VAR_14, thumbnail_method=VAR_15, thumbnail_type=VAR_16, ) VAR_52 = await self.media_storage.store_file( VAR_35, VAR_26 ) finally: VAR_35.close() VAR_0.info("Stored thumbnail in file %r", VAR_52) VAR_46 = os.path.getsize(VAR_52) await self.store.store_local_thumbnail( VAR_4, VAR_13, VAR_14, VAR_16, VAR_15, VAR_46 ) return VAR_52 return None async def FUNC_12( self, VAR_3: str, VAR_18: str, VAR_4: str, VAR_13: int, VAR_14: int, VAR_15: str, VAR_16: str, ) -> Optional[str]: VAR_34 = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(VAR_3, VAR_18, VAR_17=False) ) try: VAR_12 = Thumbnailer(VAR_34) except ThumbnailError as e: VAR_0.warning( "Unable to generate a thumbnail for remote media %s from %s using a method of %s and type of %s: %s", VAR_4, VAR_3, VAR_15, VAR_16, e, ) return None VAR_35 = await defer_to_thread( self.hs.get_reactor(), self._generate_thumbnail, VAR_12, VAR_13, VAR_14, VAR_15, VAR_16, ) if VAR_35: try: VAR_26 = FileInfo( VAR_3=VAR_3, VAR_18=file_id, thumbnail=True, thumbnail_width=VAR_13, thumbnail_height=VAR_14, thumbnail_method=VAR_15, thumbnail_type=VAR_16, ) VAR_52 = await self.media_storage.store_file( VAR_35, VAR_26 ) finally: VAR_35.close() VAR_0.info("Stored thumbnail in file %r", VAR_52) VAR_46 = os.path.getsize(VAR_52) await self.store.store_remote_media_thumbnail( VAR_3, VAR_4, VAR_18, VAR_13, VAR_14, VAR_16, VAR_15, VAR_46, ) return VAR_52 return None async def FUNC_13( self, VAR_3: Optional[str], VAR_4: str, VAR_18: str, VAR_5: str, VAR_17: bool = False, ) -> Optional[dict]: VAR_36 = self._get_thumbnail_requirements(VAR_5) if not VAR_36: return None VAR_34 = await self.media_storage.ensure_media_is_in_local_cache( FileInfo(VAR_3, VAR_18, VAR_17=url_cache) ) try: VAR_12 = Thumbnailer(VAR_34) except ThumbnailError as e: VAR_0.warning( "Unable to generate VAR_37 for remote media %s from %s of type %s: %s", VAR_4, VAR_3, VAR_5, e, ) return None VAR_32 = VAR_12.width VAR_33 = VAR_12.height if VAR_32 * VAR_33 >= self.max_image_pixels: VAR_0.info( "Image too large to thumbnail %r x %r > %r", VAR_32, VAR_33, self.max_image_pixels, ) return None if VAR_12.transpose_method is not None: VAR_32, VAR_33 = await defer_to_thread( self.hs.get_reactor(), VAR_12.transpose ) VAR_37 = {} # type: Dict[Tuple[int, int, str], str] for r_width, r_height, r_method, VAR_53 in VAR_36: if r_method == "crop": VAR_37.setdefault((r_width, r_height, VAR_53), r_method) elif r_method == "scale": VAR_13, VAR_14 = VAR_12.aspect(r_width, r_height) VAR_13 = min(VAR_32, VAR_13) VAR_14 = min(VAR_33, VAR_14) VAR_37[(VAR_13, VAR_14, VAR_53)] = r_method for (VAR_13, VAR_14, VAR_16), VAR_15 in VAR_37.items(): if VAR_15 == "crop": VAR_35 = await defer_to_thread( self.hs.get_reactor(), VAR_12.crop, VAR_13, VAR_14, VAR_16 ) elif VAR_15 == "scale": VAR_35 = await defer_to_thread( self.hs.get_reactor(), VAR_12.scale, VAR_13, VAR_14, VAR_16 ) else: VAR_0.error("Unrecognized method: %r", VAR_15) continue if not VAR_35: continue VAR_26 = FileInfo( VAR_3=VAR_3, VAR_18=file_id, thumbnail=True, thumbnail_width=VAR_13, thumbnail_height=VAR_14, thumbnail_method=VAR_15, thumbnail_type=VAR_16, VAR_17=url_cache, ) with self.media_storage.store_into_file(VAR_26) as (f, VAR_27, finish): try: await self.media_storage.write_to_file(VAR_35, f) await finish() finally: VAR_35.close() VAR_46 = os.path.getsize(VAR_27) if VAR_3: try: await self.store.store_remote_media_thumbnail( VAR_3, VAR_4, VAR_18, VAR_13, VAR_14, VAR_16, VAR_15, VAR_46, ) except Exception as e: VAR_54 = await self.store.get_remote_media_thumbnail( VAR_3, VAR_4, VAR_13, VAR_14, VAR_16, ) if not VAR_54: raise e else: await self.store.store_local_thumbnail( VAR_4, VAR_13, VAR_14, VAR_16, VAR_15, VAR_46 ) return {"width": VAR_32, "height": VAR_33} async def FUNC_14(self, VAR_19): VAR_38 = await self.store.get_remote_media_before(VAR_19) VAR_39 = 0 for media in VAR_38: VAR_47 = media["media_origin"] VAR_4 = media["media_id"] VAR_18 = media["filesystem_id"] VAR_31 = (VAR_47, VAR_4) VAR_0.info("Deleting: %r", VAR_31) with (await self.remote_media_linearizer.queue(VAR_31)): VAR_48 = self.filepaths.remote_media_filepath(VAR_47, VAR_18) try: os.remove(VAR_48) except OSError as e: VAR_0.warning("Failed to remove file: %r", VAR_48) if e.errno == errno.ENOENT: pass else: continue VAR_49 = self.filepaths.remote_media_thumbnail_dir( VAR_47, VAR_18 ) shutil.rmtree(VAR_49, ignore_errors=True) await self.store.delete_remote_media(VAR_47, VAR_4) VAR_39 += 1 return {"deleted": VAR_39} async def FUNC_15(self, VAR_4: str) -> Tuple[List[str], int]: return await self._remove_local_media_from_disk([VAR_4]) async def FUNC_16( self, VAR_19: int, VAR_20: int = 0, VAR_21: bool = True, ) -> Tuple[List[str], int]: VAR_38 = await self.store.get_local_media_before( VAR_19, VAR_20, VAR_21, ) return await self._remove_local_media_from_disk(VAR_38) async def FUNC_17( self, VAR_22: List[str] ) -> Tuple[List[str], int]: VAR_40 = [] for VAR_4 in VAR_22: VAR_0.info("Deleting media with ID '%s'", VAR_4) VAR_48 = self.filepaths.local_media_filepath(VAR_4) try: os.remove(VAR_48) except OSError as e: VAR_0.warning("Failed to remove file: %r: %s", VAR_48, e) if e.errno == errno.ENOENT: pass else: continue VAR_49 = self.filepaths.local_media_thumbnail_dir(VAR_4) shutil.rmtree(VAR_49, ignore_errors=True) await self.store.delete_remote_media(self.server_name, VAR_4) await self.store.delete_url_cache((VAR_4,)) await self.store.delete_url_cache_media((VAR_4,)) VAR_40.append(VAR_4) return VAR_40, len(VAR_40) class CLASS_1(Resource): def __init__(self, VAR_2): if not VAR_2.config.can_load_media_repo: raise ConfigError("Synapse is not configured to use a media repo.") super().__init__() VAR_41 = VAR_2.get_media_repository() self.putChild(b"upload", UploadResource(VAR_2, VAR_41)) self.putChild(b"download", DownloadResource(VAR_2, VAR_41)) self.putChild( b"thumbnail", ThumbnailResource(VAR_2, VAR_41, media_repo.media_storage) ) if VAR_2.config.url_preview_enabled: self.putChild( b"preview_url", PreviewUrlResource(VAR_2, VAR_41, media_repo.media_storage), ) self.putChild(b"config", MediaConfigResource(VAR_2))
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 22, 27, 41, 58, 60, 61, 63, 64, 75, 78, 81, 83, 86, 88, 89, 90, 92, 102, 106, 110, 115, 119, 122, 126, 129, 138, 148, 155, 159, 161, 163, 165, 167, 176, 178, 180, 185, 192, 200, 202, 207, 209, 214, 219, 226, 235, 237, 238, 239, 245, 246, 256, 260, 264, 273, 274, 275, 281, 282, 286, 288, 294, 299, 304, 305, 306, 307, 308, 309, 313, 317, 321, 322, 323, 329, 330, 334, 337, 338, 339, 340, 341, 342, 343, 347, 350, 354, 361, 365, 367, 369, 381, 382, 383, 395, 406, 420, 422, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 446, 448, 456, 458, 461, 465, 474, 477, 487, 489, 502, 514, 524, 537, 543, 545, 547, 551, 553, 554, 556, 570, 583, 593, 605, 611, 613, 615, 626, 628, 629, 631, 641, 650, 658, 662, 674, 677, 686, 691, 692, 693, 703, 704, 706, 718, 721, 732, 739, 741, 742, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 776, 778, 781, 783, 789, 791, 792, 793, 804, 809, 812, 814, 818, 825, 832, 847, 854, 872, 875, 877, 880, 882, 884, 885, 888, 891, 895, 897, 900, 902, 904, 908, 910, 913, 916, 919, 921, 930, 932, 935, 938, 950, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 128, 129, 130, 131, 132, 133, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 816, 817, 818, 819, 820, 821, 822, 823, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 851, 852, 853, 854, 855, 856, 857, 858, 859 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 22, 27, 41, 58, 60, 61, 63, 64, 75, 78, 81, 83, 86, 88, 89, 90, 92, 102, 106, 110, 115, 119, 122, 126, 129, 138, 148, 155, 159, 161, 163, 165, 167, 176, 178, 180, 185, 192, 200, 202, 207, 209, 214, 219, 226, 235, 237, 238, 239, 245, 246, 256, 260, 264, 273, 274, 275, 281, 282, 286, 288, 294, 299, 304, 305, 306, 307, 308, 309, 313, 317, 321, 322, 323, 329, 330, 334, 337, 338, 339, 340, 341, 342, 343, 347, 350, 354, 361, 365, 367, 369, 381, 382, 383, 395, 406, 420, 422, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 446, 448, 456, 458, 461, 465, 474, 477, 487, 489, 502, 514, 524, 537, 543, 545, 547, 551, 553, 554, 556, 570, 583, 593, 605, 611, 613, 615, 626, 628, 629, 631, 641, 650, 658, 662, 674, 677, 686, 691, 692, 693, 703, 704, 706, 718, 721, 732, 739, 741, 742, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 776, 778, 781, 783, 789, 791, 792, 793, 804, 809, 812, 814, 818, 825, 832, 847, 854, 872, 875, 877, 880, 882, 884, 885, 888, 891, 895, 897, 900, 902, 904, 908, 910, 913, 916, 919, 921, 930, 932, 935, 938, 950, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 128, 129, 130, 131, 132, 133, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 816, 817, 818, 819, 820, 821, 822, 823, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 851, 852, 853, 854, 855, 856, 857, 858, 859 ]
1CWE-79
# encoding: utf-8 from __future__ import unicode_literals from datetime import datetime, timedelta from unittest import TestCase from django import forms from django.conf import settings from django.contrib import admin from django.contrib.admin import widgets from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import CharField, DateField from django.test import TestCase as DjangoTestCase from django.test.utils import override_settings from django.utils import six from django.utils import translation from django.utils.html import conditional_escape from . import models from .widgetadmin import site as widget_admin_site admin_static_prefix = lambda: { 'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL, } class AdminFormfieldForDBFieldTests(TestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and verify that the returned formfield is appropriate. """ # Override any settings on the model admin class MyModelAdmin(admin.ModelAdmin): pass for k in admin_overrides: setattr(MyModelAdmin, k, admin_overrides[k]) # Construct the admin, and ask it for a formfield ma = MyModelAdmin(model, admin.site) ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None) # "unwrap" the widget wrapper, if needed if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper): widget = ff.widget.widget else: widget = ff.widget # Check that we got a field of the right type self.assertTrue( isinstance(widget, widgetclass), "Wrong widget for %s.%s: expected %s, got %s" % \ (model.__class__.__name__, fieldname, widgetclass, type(widget)) ) # Return the formfield so that other tests can continue return ff def testDateField(self): self.assertFormfield(models.Event, 'start_date', widgets.AdminDateWidget) def testDateTimeField(self): self.assertFormfield(models.Member, 'birthdate', widgets.AdminSplitDateTime) def testTimeField(self): self.assertFormfield(models.Event, 'start_time', widgets.AdminTimeWidget) def testTextField(self): self.assertFormfield(models.Event, 'description', widgets.AdminTextareaWidget) def testURLField(self): self.assertFormfield(models.Event, 'link', widgets.AdminURLFieldWidget) def testIntegerField(self): self.assertFormfield(models.Event, 'min_age', widgets.AdminIntegerFieldWidget) def testCharField(self): self.assertFormfield(models.Member, 'name', widgets.AdminTextInputWidget) def testEmailField(self): self.assertFormfield(models.Member, 'email', widgets.AdminEmailInputWidget) def testFileField(self): self.assertFormfield(models.Album, 'cover_art', widgets.AdminFileWidget) def testForeignKey(self): self.assertFormfield(models.Event, 'main_band', forms.Select) def testRawIDForeignKey(self): self.assertFormfield(models.Event, 'main_band', widgets.ForeignKeyRawIdWidget, raw_id_fields=['main_band']) def testRadioFieldsForeignKey(self): ff = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect, radio_fields={'main_band':admin.VERTICAL}) self.assertEqual(ff.empty_label, None) def testManyToMany(self): self.assertFormfield(models.Band, 'members', forms.SelectMultiple) def testRawIDManyTOMany(self): self.assertFormfield(models.Band, 'members', widgets.ManyToManyRawIdWidget, raw_id_fields=['members']) def testFilteredManyToMany(self): self.assertFormfield(models.Band, 'members', widgets.FilteredSelectMultiple, filter_vertical=['members']) def testFormfieldOverrides(self): self.assertFormfield(models.Event, 'start_date', forms.TextInput, formfield_overrides={DateField: {'widget': forms.TextInput}}) def testFormfieldOverridesWidgetInstances(self): """ Test that widget instances in formfield_overrides are not shared between different fields. (#19423) """ class BandAdmin(admin.ModelAdmin): formfield_overrides = { CharField: {'widget': forms.TextInput(attrs={'size':'10'})} } ma = BandAdmin(models.Band, admin.site) f1 = ma.formfield_for_dbfield(models.Band._meta.get_field('name'), request=None) f2 = ma.formfield_for_dbfield(models.Band._meta.get_field('style'), request=None) self.assertNotEqual(f1.widget, f2.widget) self.assertEqual(f1.widget.attrs['maxlength'], '100') self.assertEqual(f2.widget.attrs['maxlength'], '20') self.assertEqual(f2.widget.attrs['size'], '10') def testFieldWithChoices(self): self.assertFormfield(models.Member, 'gender', forms.Select) def testChoicesWithRadioFields(self): self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect, radio_fields={'gender':admin.VERTICAL}) def testInheritance(self): self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget) def test_m2m_widgets(self): """m2m fields help text as it applies to admin app (#9321).""" class AdvisorAdmin(admin.ModelAdmin): filter_vertical=['companies'] self.assertFormfield(models.Advisor, 'companies', widgets.FilteredSelectMultiple, filter_vertical=['companies']) ma = AdvisorAdmin(models.Advisor, admin.site) f = ma.formfield_for_dbfield(models.Advisor._meta.get_field('companies'), request=None) self.assertEqual(six.text_type(f.help_text), ' Hold down "Control", or "Command" on a Mac, to select more than one.') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase): fixtures = ["admin-widgets-users.xml"] def testFilterChoicesByRequestUser(self): """ Ensure the user can only see their own cars in the foreign key dropdown. """ self.client.login(username="super", password="secret") response = self.client.get("/widget_admin/admin_widgets/cartire/add/") self.assertNotContains(response, "BMW M3") self.assertContains(response, "Volkswagon Passat") @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminForeignKeyWidgetChangeList(DjangoTestCase): fixtures = ["admin-widgets-users.xml"] admin_root = '/widget_admin' def setUp(self): self.client.login(username="super", password="secret") def tearDown(self): self.client.logout() def test_changelist_foreignkey(self): response = self.client.get('%s/admin_widgets/car/' % self.admin_root) self.assertContains(response, '%s/auth/user/add/' % self.admin_root) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminForeignKeyRawIdWidget(DjangoTestCase): fixtures = ["admin-widgets-users.xml"] admin_root = '/widget_admin' def setUp(self): self.client.login(username="super", password="secret") def tearDown(self): self.client.logout() def test_nonexistent_target_id(self): band = models.Band.objects.create(name='Bogey Blues') pk = band.pk band.delete() post_data = { "main_band": '%s' % pk, } # Try posting with a non-existent pk in a raw id field: this # should result in an error message, not a server exception. response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, post_data) self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.') def test_invalid_target_id(self): for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234): # This should result in an error message, not a server exception. response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, {"main_band": test_str}) self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.') def test_url_params_from_lookup_dict_any_iterable(self): lookup1 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')}) lookup2 = widgets.url_params_from_lookup_dict({'color__in': ['red', 'blue']}) self.assertEqual(lookup1, {'color__in': 'red,blue'}) self.assertEqual(lookup1, lookup2) def test_url_params_from_lookup_dict_callable(self): def my_callable(): return 'works' lookup1 = widgets.url_params_from_lookup_dict({'myfield': my_callable}) lookup2 = widgets.url_params_from_lookup_dict({'myfield': my_callable()}) self.assertEqual(lookup1, lookup2) class FilteredSelectMultipleWidgetTest(DjangoTestCase): def test_render(self): w = widgets.FilteredSelectMultiple('test', False) self.assertHTMLEqual( conditional_escape(w.render('test', 'test')), '<select multiple="multiple" name="test" class="selectfilter">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 0, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix() ) def test_stacked_render(self): w = widgets.FilteredSelectMultiple('test', True) self.assertHTMLEqual( conditional_escape(w.render('test', 'test')), '<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix() ) class AdminDateWidgetTest(DjangoTestCase): def test_attrs(self): """ Ensure that user-supplied attrs are used. Refs #12073. """ w = widgets.AdminDateWidget() self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="2007-12-01" type="text" class="vDateField" name="test" size="10" />', ) # pass attrs to widget w = widgets.AdminDateWidget(attrs={'size': 20, 'class': 'myDateField'}) self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="2007-12-01" type="text" class="myDateField" name="test" size="20" />', ) class AdminTimeWidgetTest(DjangoTestCase): def test_attrs(self): """ Ensure that user-supplied attrs are used. Refs #12073. """ w = widgets.AdminTimeWidget() self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="09:30:00" type="text" class="vTimeField" name="test" size="8" />', ) # pass attrs to widget w = widgets.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'}) self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />', ) class AdminSplitDateTimeWidgetTest(DjangoTestCase): def test_render(self): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<p class="datetime">Date: <input value="2007-12-01" type="text" class="vDateField" name="test_0" size="10" /><br />Time: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>', ) def test_localization(self): w = widgets.AdminSplitDateTime() with self.settings(USE_L10N=True): with translation.override('de-at'): w.is_localized = True self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<p class="datetime">Datum: <input value="01.12.2007" type="text" class="vDateField" name="test_0" size="10" /><br />Zeit: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>', ) class AdminURLWidgetTest(DjangoTestCase): def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(w.render('test', '')), '<input class="vURLField" name="test" type="url" />' ) self.assertHTMLEqual( conditional_escape(w.render('test', 'http://example.com')), '<p class="url">Currently:<a href="http://example.com">http://example.com</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example.com" /></p>' ) def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(w.render('test', 'http://example-äüö.com')), '<p class="url">Currently:<a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example-äüö.com" /></p>' ) def test_render_quoting(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(w.render('test', 'http://example.com/<sometag>some text</sometag>')), '<p class="url">Currently:<a href="http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example.com/<sometag>some text</sometag>" /></p>' ) self.assertHTMLEqual( conditional_escape(w.render('test', 'http://example-äüö.com/<sometag>some text</sometag>')), '<p class="url">Currently:<a href="http://xn--example--7za4pnc.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example-äüö.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example-äüö.com/<sometag>some text</sometag>" /></p>' ) class AdminFileWidgetTest(DjangoTestCase): def test_render(self): band = models.Band.objects.create(name='Linkin Park') album = band.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) w = widgets.AdminFileWidget() self.assertHTMLEqual( conditional_escape(w.render('test', album.cover_art)), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">albums\hybrid_theory.jpg</a> <span class="clearable-file-input"><input type="checkbox" name="test-clear" id="test-clear_id" /> <label for="test-clear_id">Clear</label></span><br />Change: <input type="file" name="test" /></p>' % { 'STORAGE_URL': default_storage.url('') }, ) self.assertHTMLEqual( conditional_escape(w.render('test', SimpleUploadedFile('test', b'content'))), '<input type="file" name="test" />', ) class ForeignKeyRawIdWidgetTest(DjangoTestCase): def test_render(self): band = models.Band.objects.create(name='Linkin Park') band.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) rel = models.Album._meta.get_field('band').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('test', band.pk, attrs={})), '<input type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/band/?t=id" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Linkin Park</strong>' % dict(admin_static_prefix(), bandpk=band.pk) ) def test_relations_to_non_primary_key(self): # Check that ForeignKeyRawIdWidget works with fields which aren't # related to the model's primary key. apple = models.Inventory.objects.create(barcode=86, name='Apple') models.Inventory.objects.create(barcode=22, name='Pear') core = models.Inventory.objects.create( barcode=87, name='Core', parent=apple ) rel = models.Inventory._meta.get_field('parent').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('test', core.parent_id, attrs={}), '<input type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Apple</strong>' % admin_static_prefix() ) def test_fk_related_model_not_in_admin(self): # FK to a model not registered with admin site. Raw ID widget should # have no magnifying glass link. See #16542 big_honeycomb = models.Honeycomb.objects.create(location='Old tree') big_honeycomb.bee_set.create() rel = models.Bee._meta.get_field('honeycomb').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('honeycomb_widget', big_honeycomb.pk, attrs={})), '<input type="text" name="honeycomb_widget" value="%(hcombpk)s" />&nbsp;<strong>Honeycomb object</strong>' % {'hcombpk': big_honeycomb.pk} ) def test_fk_to_self_model_not_in_admin(self): # FK to self, not registered with admin site. Raw ID widget should have # no magnifying glass link. See #16542 subject1 = models.Individual.objects.create(name='Subject #1') models.Individual.objects.create(name='Child', parent=subject1) rel = models.Individual._meta.get_field('parent').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('individual_widget', subject1.pk, attrs={})), '<input type="text" name="individual_widget" value="%(subj1pk)s" />&nbsp;<strong>Individual object</strong>' % {'subj1pk': subject1.pk} ) def test_proper_manager_for_label_lookup(self): # see #9258 rel = models.Inventory._meta.get_field('parent').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) hidden = models.Inventory.objects.create( barcode=93, name='Hidden', hidden=True ) child_of_hidden = models.Inventory.objects.create( barcode=94, name='Child of hidden', parent=hidden ) self.assertHTMLEqual( w.render('test', child_of_hidden.parent_id, attrs={}), '<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Hidden</strong>' % admin_static_prefix() ) class ManyToManyRawIdWidgetTest(DjangoTestCase): def test_render(self): band = models.Band.objects.create(name='Linkin Park') m1 = models.Member.objects.create(name='Chester') m2 = models.Member.objects.create(name='Mike') band.members.add(m1, m2) rel = models.Band._meta.get_field('members').rel w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('test', [m1.pk, m2.pk], attrs={})), '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="/static/admin/img/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk, m2pk=m2.pk) ) self.assertHTMLEqual( conditional_escape(w.render('test', [m1.pk])), '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk) ) def test_m2m_related_model_not_in_admin(self): # M2M relationship with model not registered with admin site. Raw ID # widget should have no magnifying glass link. See #16542 consultor1 = models.Advisor.objects.create(name='Rockstar Techie') c1 = models.Company.objects.create(name='Doodle') c2 = models.Company.objects.create(name='Pear') consultor1.companies.add(c1, c2) rel = models.Advisor._meta.get_field('companies').rel w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('company_widget1', [c1.pk, c2.pk], attrs={})), '<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s" />' % {'c1pk': c1.pk, 'c2pk': c2.pk} ) self.assertHTMLEqual( conditional_escape(w.render('company_widget2', [c1.pk])), '<input type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': c1.pk} ) class RelatedFieldWidgetWrapperTests(DjangoTestCase): def test_no_can_add_related(self): rel = models.Individual._meta.get_field('parent').rel w = widgets.AdminRadioSelect() # Used to fail with a name error. w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site) self.assertFalse(w.can_add_related) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class DateTimePickerSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps fixtures = ['admin-widgets-users.xml'] urls = "admin_widgets.urls" webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver' def test_show_hide_date_time_picker_widgets(self): """ Ensure that pressing the ESC key closes the date and time picker widgets. Refs #17064. """ from selenium.webdriver.common.keys import Keys self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets self.selenium.get('%s%s' % (self.live_server_url, '/admin_widgets/member/add/')) # First, with the date picker widget --------------------------------- # Check that the date picker is hidden self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'none') # Click the calendar icon self.selenium.find_element_by_id('calendarlink0').click() # Check that the date picker is visible self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'block') # Press the ESC key self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) # Check that the date picker is hidden again self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'none') # Then, with the time picker widget ---------------------------------- # Check that the time picker is hidden self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'none') # Click the time icon self.selenium.find_element_by_id('clocklink0').click() # Check that the time picker is visible self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'block') # Press the ESC key self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) # Check that the time picker is hidden again self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'none') class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(TIME_ZONE='Asia/Singapore') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class DateTimePickerShortcutsSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps fixtures = ['admin-widgets-users.xml'] urls = "admin_widgets.urls" webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver' def test_date_time_picker_shortcuts(self): """ Ensure that date/time/datetime picker shortcuts work in the current time zone. Refs #20663. This test case is fairly tricky, it relies on selenium still running the browser in the default time zone "America/Chicago" despite `override_settings` changing the time zone to "Asia/Singapore". """ self.admin_login(username='super', password='secret', login_url='/') now = datetime.now() error_margin = timedelta(seconds=10) self.selenium.get('%s%s' % (self.live_server_url, '/admin_widgets/member/add/')) self.selenium.find_element_by_id('id_name').send_keys('test') # Click on the "today" and "now" shortcuts. shortcuts = self.selenium.find_elements_by_css_selector( '.field-birthdate .datetimeshortcuts') for shortcut in shortcuts: shortcut.find_element_by_tag_name('a').click() # Check that there is a time zone mismatch warning. # Warning: This would effectively fail if the TIME_ZONE defined in the # settings has the same UTC offset as "Asia/Singapore" because the # mismatch warning would be rightfully missing from the page. self.selenium.find_elements_by_css_selector( '.field-birthdate .timezonewarning') # Submit the form. self.selenium.find_element_by_tag_name('form').submit() self.wait_page_loaded() # Make sure that "now" in javascript is within 10 seconds # from "now" on the server side. member = models.Member.objects.get(name='test') self.assertGreater(member.birthdate, now - error_margin) self.assertLess(member.birthdate, now + error_margin) class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps fixtures = ['admin-widgets-users.xml'] urls = "admin_widgets.urls" webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver' def setUp(self): self.lisa = models.Student.objects.create(name='Lisa') self.john = models.Student.objects.create(name='John') self.bob = models.Student.objects.create(name='Bob') self.peter = models.Student.objects.create(name='Peter') self.jenny = models.Student.objects.create(name='Jenny') self.jason = models.Student.objects.create(name='Jason') self.cliff = models.Student.objects.create(name='Cliff') self.arthur = models.Student.objects.create(name='Arthur') self.school = models.School.objects.create(name='School of Awesome') super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp() def assertActiveButtons(self, mode, field_name, choose, remove, choose_all=None, remove_all=None): choose_link = '#id_%s_add_link' % field_name choose_all_link = '#id_%s_add_all_link' % field_name remove_link = '#id_%s_remove_link' % field_name remove_all_link = '#id_%s_remove_all_link' % field_name self.assertEqual(self.has_css_class(choose_link, 'active'), choose) self.assertEqual(self.has_css_class(remove_link, 'active'), remove) if mode == 'horizontal': self.assertEqual(self.has_css_class(choose_all_link, 'active'), choose_all) self.assertEqual(self.has_css_class(remove_all_link, 'active'), remove_all) def execute_basic_operations(self, mode, field_name): from_box = '#id_%s_from' % field_name to_box = '#id_%s_to' % field_name choose_link = 'id_%s_add_link' % field_name choose_all_link = 'id_%s_add_all_link' % field_name remove_link = 'id_%s_remove_link' % field_name remove_all_link = 'id_%s_remove_all_link' % field_name # Initial positions --------------------------------------------------- self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id)]) self.assertActiveButtons(mode, field_name, False, False, True, True) # Click 'Choose all' -------------------------------------------------- if mode == 'horizontal': self.selenium.find_element_by_id(choose_all_link).click() elif mode == 'vertical': # There 's no 'Choose all' button in vertical mode, so individually # select all options and click 'Choose'. for option in self.selenium.find_elements_by_css_selector(from_box + ' > option'): option.click() self.selenium.find_element_by_id(choose_link).click() self.assertSelectOptions(from_box, []) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertActiveButtons(mode, field_name, False, False, False, True) # Click 'Remove all' -------------------------------------------------- if mode == 'horizontal': self.selenium.find_element_by_id(remove_all_link).click() elif mode == 'vertical': # There 's no 'Remove all' button in vertical mode, so individually # select all options and click 'Remove'. for option in self.selenium.find_elements_by_css_selector(to_box + ' > option'): option.click() self.selenium.find_element_by_id(remove_link).click() self.assertSelectOptions(from_box, [str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertSelectOptions(to_box, []) self.assertActiveButtons(mode, field_name, False, False, True, False) # Choose some options ------------------------------------------------ self.get_select_option(from_box, str(self.lisa.id)).click() self.get_select_option(from_box, str(self.jason.id)).click() self.get_select_option(from_box, str(self.bob.id)).click() self.get_select_option(from_box, str(self.john.id)).click() self.assertActiveButtons(mode, field_name, True, False, True, False) self.selenium.find_element_by_id(choose_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions(from_box, [str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id)]) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.bob.id), str(self.jason.id), str(self.john.id)]) # Remove some options ------------------------------------------------- self.get_select_option(to_box, str(self.lisa.id)).click() self.get_select_option(to_box, str(self.bob.id)).click() self.assertActiveButtons(mode, field_name, False, True, True, True) self.selenium.find_element_by_id(remove_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions(from_box, [str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id)]) self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Choose some more options -------------------------------------------- self.get_select_option(from_box, str(self.arthur.id)).click() self.get_select_option(from_box, str(self.cliff.id)).click() self.selenium.find_element_by_id(choose_link).click() self.assertSelectOptions(from_box, [str(self.peter.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id)]) self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id), str(self.arthur.id), str(self.cliff.id)]) def test_basic(self): self.school.students = [self.lisa, self.peter] self.school.alumni = [self.lisa, self.peter] self.school.save() self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id)) self.wait_page_loaded() self.execute_basic_operations('vertical', 'students') self.execute_basic_operations('horizontal', 'alumni') # Save and check that everything is properly stored in the database --- self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john]) self.assertEqual(list(self.school.alumni.all()), [self.arthur, self.cliff, self.jason, self.john]) def test_filter(self): """ Ensure that typing in the search box filters out options displayed in the 'from' box. """ from selenium.webdriver.common.keys import Keys self.school.students = [self.lisa, self.peter] self.school.alumni = [self.lisa, self.peter] self.school.save() self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id)) for field_name in ['students', 'alumni']: from_box = '#id_%s_from' % field_name to_box = '#id_%s_to' % field_name choose_link = '#id_%s_add_link' % field_name remove_link = '#id_%s_remove_link' % field_name input = self.selenium.find_element_by_css_selector('#id_%s_input' % field_name) # Initial values self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) # Typing in some characters filters out non-matching options input.send_keys('a') self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) input.send_keys('R') self.assertSelectOptions(from_box, [str(self.arthur.id)]) # Clearing the text box makes the other options reappear input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) # ----------------------------------------------------------------- # Check that chosing a filtered option sends it properly to the # 'to' box. input.send_keys('a') self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) self.get_select_option(from_box, str(self.jason.id)).click() self.selenium.find_element_by_css_selector(choose_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id)]) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id), str(self.jason.id)]) self.get_select_option(to_box, str(self.lisa.id)).click() self.selenium.find_element_by_css_selector(remove_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.lisa.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) # Clear text box self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jenny.id), str(self.john.id), str(self.lisa.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) # Save and check that everything is properly stored in the database --- self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps fixtures = ['admin-widgets-users.xml'] urls = "admin_widgets.urls" webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver' def setUp(self): models.Band.objects.create(id=42, name='Bogey Blues') models.Band.objects.create(id=98, name='Green Potatoes') super(AdminRawIdWidgetSeleniumFirefoxTests, self).setUp() def test_foreignkey(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/event/add/')) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '') # Open the popup window and click on a band self.selenium.find_element_by_id('lookup_id_main_band').click() self.selenium.switch_to_window('id_main_band') self.wait_page_loaded() link = self.selenium.find_element_by_link_text('Bogey Blues') self.assertTrue('/band/42/' in link.get_attribute('href')) link.click() # The field now contains the selected band's id self.selenium.switch_to_window(main_window) self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '42') # Reopen the popup window and click on another band self.selenium.find_element_by_id('lookup_id_main_band').click() self.selenium.switch_to_window('id_main_band') self.wait_page_loaded() link = self.selenium.find_element_by_link_text('Green Potatoes') self.assertTrue('/band/98/' in link.get_attribute('href')) link.click() # The field now contains the other selected band's id self.selenium.switch_to_window(main_window) self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '98') def test_many_to_many(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/event/add/')) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '') # Open the popup window and click on a band self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.selenium.switch_to_window('id_supporting_bands') self.wait_page_loaded() link = self.selenium.find_element_by_link_text('Bogey Blues') self.assertTrue('/band/42/' in link.get_attribute('href')) link.click() # The field now contains the selected band's id self.selenium.switch_to_window(main_window) self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '42') # Reopen the popup window and click on another band self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.selenium.switch_to_window('id_supporting_bands') self.wait_page_loaded() link = self.selenium.find_element_by_link_text('Green Potatoes') self.assertTrue('/band/98/' in link.get_attribute('href')) link.click() # The field now contains the two selected bands' ids self.selenium.switch_to_window(main_window) self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '42,98') class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
# encoding: utf-8 from __future__ import unicode_literals from datetime import datetime, timedelta from unittest import TestCase from django import forms from django.conf import settings from django.contrib import admin from django.contrib.admin import widgets from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import CharField, DateField from django.test import TestCase as DjangoTestCase from django.test.utils import override_settings from django.utils import six from django.utils import translation from django.utils.html import conditional_escape from . import models from .widgetadmin import site as widget_admin_site admin_static_prefix = lambda: { 'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL, } class AdminFormfieldForDBFieldTests(TestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and verify that the returned formfield is appropriate. """ # Override any settings on the model admin class MyModelAdmin(admin.ModelAdmin): pass for k in admin_overrides: setattr(MyModelAdmin, k, admin_overrides[k]) # Construct the admin, and ask it for a formfield ma = MyModelAdmin(model, admin.site) ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None) # "unwrap" the widget wrapper, if needed if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper): widget = ff.widget.widget else: widget = ff.widget # Check that we got a field of the right type self.assertTrue( isinstance(widget, widgetclass), "Wrong widget for %s.%s: expected %s, got %s" % \ (model.__class__.__name__, fieldname, widgetclass, type(widget)) ) # Return the formfield so that other tests can continue return ff def testDateField(self): self.assertFormfield(models.Event, 'start_date', widgets.AdminDateWidget) def testDateTimeField(self): self.assertFormfield(models.Member, 'birthdate', widgets.AdminSplitDateTime) def testTimeField(self): self.assertFormfield(models.Event, 'start_time', widgets.AdminTimeWidget) def testTextField(self): self.assertFormfield(models.Event, 'description', widgets.AdminTextareaWidget) def testURLField(self): self.assertFormfield(models.Event, 'link', widgets.AdminURLFieldWidget) def testIntegerField(self): self.assertFormfield(models.Event, 'min_age', widgets.AdminIntegerFieldWidget) def testCharField(self): self.assertFormfield(models.Member, 'name', widgets.AdminTextInputWidget) def testEmailField(self): self.assertFormfield(models.Member, 'email', widgets.AdminEmailInputWidget) def testFileField(self): self.assertFormfield(models.Album, 'cover_art', widgets.AdminFileWidget) def testForeignKey(self): self.assertFormfield(models.Event, 'main_band', forms.Select) def testRawIDForeignKey(self): self.assertFormfield(models.Event, 'main_band', widgets.ForeignKeyRawIdWidget, raw_id_fields=['main_band']) def testRadioFieldsForeignKey(self): ff = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect, radio_fields={'main_band':admin.VERTICAL}) self.assertEqual(ff.empty_label, None) def testManyToMany(self): self.assertFormfield(models.Band, 'members', forms.SelectMultiple) def testRawIDManyTOMany(self): self.assertFormfield(models.Band, 'members', widgets.ManyToManyRawIdWidget, raw_id_fields=['members']) def testFilteredManyToMany(self): self.assertFormfield(models.Band, 'members', widgets.FilteredSelectMultiple, filter_vertical=['members']) def testFormfieldOverrides(self): self.assertFormfield(models.Event, 'start_date', forms.TextInput, formfield_overrides={DateField: {'widget': forms.TextInput}}) def testFormfieldOverridesWidgetInstances(self): """ Test that widget instances in formfield_overrides are not shared between different fields. (#19423) """ class BandAdmin(admin.ModelAdmin): formfield_overrides = { CharField: {'widget': forms.TextInput(attrs={'size':'10'})} } ma = BandAdmin(models.Band, admin.site) f1 = ma.formfield_for_dbfield(models.Band._meta.get_field('name'), request=None) f2 = ma.formfield_for_dbfield(models.Band._meta.get_field('style'), request=None) self.assertNotEqual(f1.widget, f2.widget) self.assertEqual(f1.widget.attrs['maxlength'], '100') self.assertEqual(f2.widget.attrs['maxlength'], '20') self.assertEqual(f2.widget.attrs['size'], '10') def testFieldWithChoices(self): self.assertFormfield(models.Member, 'gender', forms.Select) def testChoicesWithRadioFields(self): self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect, radio_fields={'gender':admin.VERTICAL}) def testInheritance(self): self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget) def test_m2m_widgets(self): """m2m fields help text as it applies to admin app (#9321).""" class AdvisorAdmin(admin.ModelAdmin): filter_vertical=['companies'] self.assertFormfield(models.Advisor, 'companies', widgets.FilteredSelectMultiple, filter_vertical=['companies']) ma = AdvisorAdmin(models.Advisor, admin.site) f = ma.formfield_for_dbfield(models.Advisor._meta.get_field('companies'), request=None) self.assertEqual(six.text_type(f.help_text), ' Hold down "Control", or "Command" on a Mac, to select more than one.') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase): fixtures = ["admin-widgets-users.xml"] def testFilterChoicesByRequestUser(self): """ Ensure the user can only see their own cars in the foreign key dropdown. """ self.client.login(username="super", password="secret") response = self.client.get("/widget_admin/admin_widgets/cartire/add/") self.assertNotContains(response, "BMW M3") self.assertContains(response, "Volkswagon Passat") @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminForeignKeyWidgetChangeList(DjangoTestCase): fixtures = ["admin-widgets-users.xml"] admin_root = '/widget_admin' def setUp(self): self.client.login(username="super", password="secret") def tearDown(self): self.client.logout() def test_changelist_foreignkey(self): response = self.client.get('%s/admin_widgets/car/' % self.admin_root) self.assertContains(response, '%s/auth/user/add/' % self.admin_root) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminForeignKeyRawIdWidget(DjangoTestCase): fixtures = ["admin-widgets-users.xml"] admin_root = '/widget_admin' def setUp(self): self.client.login(username="super", password="secret") def tearDown(self): self.client.logout() def test_nonexistent_target_id(self): band = models.Band.objects.create(name='Bogey Blues') pk = band.pk band.delete() post_data = { "main_band": '%s' % pk, } # Try posting with a non-existent pk in a raw id field: this # should result in an error message, not a server exception. response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, post_data) self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.') def test_invalid_target_id(self): for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234): # This should result in an error message, not a server exception. response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, {"main_band": test_str}) self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.') def test_url_params_from_lookup_dict_any_iterable(self): lookup1 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')}) lookup2 = widgets.url_params_from_lookup_dict({'color__in': ['red', 'blue']}) self.assertEqual(lookup1, {'color__in': 'red,blue'}) self.assertEqual(lookup1, lookup2) def test_url_params_from_lookup_dict_callable(self): def my_callable(): return 'works' lookup1 = widgets.url_params_from_lookup_dict({'myfield': my_callable}) lookup2 = widgets.url_params_from_lookup_dict({'myfield': my_callable()}) self.assertEqual(lookup1, lookup2) class FilteredSelectMultipleWidgetTest(DjangoTestCase): def test_render(self): w = widgets.FilteredSelectMultiple('test', False) self.assertHTMLEqual( conditional_escape(w.render('test', 'test')), '<select multiple="multiple" name="test" class="selectfilter">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 0, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix() ) def test_stacked_render(self): w = widgets.FilteredSelectMultiple('test', True) self.assertHTMLEqual( conditional_escape(w.render('test', 'test')), '<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix() ) class AdminDateWidgetTest(DjangoTestCase): def test_attrs(self): """ Ensure that user-supplied attrs are used. Refs #12073. """ w = widgets.AdminDateWidget() self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="2007-12-01" type="text" class="vDateField" name="test" size="10" />', ) # pass attrs to widget w = widgets.AdminDateWidget(attrs={'size': 20, 'class': 'myDateField'}) self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="2007-12-01" type="text" class="myDateField" name="test" size="20" />', ) class AdminTimeWidgetTest(DjangoTestCase): def test_attrs(self): """ Ensure that user-supplied attrs are used. Refs #12073. """ w = widgets.AdminTimeWidget() self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="09:30:00" type="text" class="vTimeField" name="test" size="8" />', ) # pass attrs to widget w = widgets.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'}) self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />', ) class AdminSplitDateTimeWidgetTest(DjangoTestCase): def test_render(self): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<p class="datetime">Date: <input value="2007-12-01" type="text" class="vDateField" name="test_0" size="10" /><br />Time: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>', ) def test_localization(self): w = widgets.AdminSplitDateTime() with self.settings(USE_L10N=True): with translation.override('de-at'): w.is_localized = True self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<p class="datetime">Datum: <input value="01.12.2007" type="text" class="vDateField" name="test_0" size="10" /><br />Zeit: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>', ) class AdminURLWidgetTest(DjangoTestCase): def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(w.render('test', '')), '<input class="vURLField" name="test" type="url" />' ) self.assertHTMLEqual( conditional_escape(w.render('test', 'http://example.com')), '<p class="url">Currently:<a href="http://example.com">http://example.com</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example.com" /></p>' ) def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(w.render('test', 'http://example-äüö.com')), '<p class="url">Currently: <a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example-äüö.com" /></p>' ) def test_render_quoting(self): # WARNING: Don't use assertHTMLEqual in that testcase! # assertHTMLEqual will get rid of some escapes which are tested here! w = widgets.AdminURLFieldWidget() self.assertEqual( w.render('test', 'http://example.com/<sometag>some text</sometag>'), '<p class="url">Currently: <a href="http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change: <input class="vURLField" name="test" type="url" value="http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;" /></p>' ) self.assertEqual( w.render('test', 'http://example-äüö.com/<sometag>some text</sometag>'), '<p class="url">Currently: <a href="http://xn--example--7za4pnc.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example-äüö.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change: <input class="vURLField" name="test" type="url" value="http://example-äüö.com/&lt;sometag&gt;some text&lt;/sometag&gt;" /></p>' ) self.assertEqual( w.render('test', 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"'), '<p class="url">Currently: <a href="http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)%3C/script%3E%22">http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;</a><br />Change: <input class="vURLField" name="test" type="url" value="http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;" /></p>' ) class AdminFileWidgetTest(DjangoTestCase): def test_render(self): band = models.Band.objects.create(name='Linkin Park') album = band.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) w = widgets.AdminFileWidget() self.assertHTMLEqual( conditional_escape(w.render('test', album.cover_art)), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">albums\hybrid_theory.jpg</a> <span class="clearable-file-input"><input type="checkbox" name="test-clear" id="test-clear_id" /> <label for="test-clear_id">Clear</label></span><br />Change: <input type="file" name="test" /></p>' % { 'STORAGE_URL': default_storage.url('') }, ) self.assertHTMLEqual( conditional_escape(w.render('test', SimpleUploadedFile('test', b'content'))), '<input type="file" name="test" />', ) class ForeignKeyRawIdWidgetTest(DjangoTestCase): def test_render(self): band = models.Band.objects.create(name='Linkin Park') band.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) rel = models.Album._meta.get_field('band').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('test', band.pk, attrs={})), '<input type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/band/?t=id" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Linkin Park</strong>' % dict(admin_static_prefix(), bandpk=band.pk) ) def test_relations_to_non_primary_key(self): # Check that ForeignKeyRawIdWidget works with fields which aren't # related to the model's primary key. apple = models.Inventory.objects.create(barcode=86, name='Apple') models.Inventory.objects.create(barcode=22, name='Pear') core = models.Inventory.objects.create( barcode=87, name='Core', parent=apple ) rel = models.Inventory._meta.get_field('parent').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('test', core.parent_id, attrs={}), '<input type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Apple</strong>' % admin_static_prefix() ) def test_fk_related_model_not_in_admin(self): # FK to a model not registered with admin site. Raw ID widget should # have no magnifying glass link. See #16542 big_honeycomb = models.Honeycomb.objects.create(location='Old tree') big_honeycomb.bee_set.create() rel = models.Bee._meta.get_field('honeycomb').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('honeycomb_widget', big_honeycomb.pk, attrs={})), '<input type="text" name="honeycomb_widget" value="%(hcombpk)s" />&nbsp;<strong>Honeycomb object</strong>' % {'hcombpk': big_honeycomb.pk} ) def test_fk_to_self_model_not_in_admin(self): # FK to self, not registered with admin site. Raw ID widget should have # no magnifying glass link. See #16542 subject1 = models.Individual.objects.create(name='Subject #1') models.Individual.objects.create(name='Child', parent=subject1) rel = models.Individual._meta.get_field('parent').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('individual_widget', subject1.pk, attrs={})), '<input type="text" name="individual_widget" value="%(subj1pk)s" />&nbsp;<strong>Individual object</strong>' % {'subj1pk': subject1.pk} ) def test_proper_manager_for_label_lookup(self): # see #9258 rel = models.Inventory._meta.get_field('parent').rel w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) hidden = models.Inventory.objects.create( barcode=93, name='Hidden', hidden=True ) child_of_hidden = models.Inventory.objects.create( barcode=94, name='Child of hidden', parent=hidden ) self.assertHTMLEqual( w.render('test', child_of_hidden.parent_id, attrs={}), '<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Hidden</strong>' % admin_static_prefix() ) class ManyToManyRawIdWidgetTest(DjangoTestCase): def test_render(self): band = models.Band.objects.create(name='Linkin Park') m1 = models.Member.objects.create(name='Chester') m2 = models.Member.objects.create(name='Mike') band.members.add(m1, m2) rel = models.Band._meta.get_field('members').rel w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('test', [m1.pk, m2.pk], attrs={})), '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="/static/admin/img/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk, m2pk=m2.pk) ) self.assertHTMLEqual( conditional_escape(w.render('test', [m1.pk])), '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk) ) def test_m2m_related_model_not_in_admin(self): # M2M relationship with model not registered with admin site. Raw ID # widget should have no magnifying glass link. See #16542 consultor1 = models.Advisor.objects.create(name='Rockstar Techie') c1 = models.Company.objects.create(name='Doodle') c2 = models.Company.objects.create(name='Pear') consultor1.companies.add(c1, c2) rel = models.Advisor._meta.get_field('companies').rel w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( conditional_escape(w.render('company_widget1', [c1.pk, c2.pk], attrs={})), '<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s" />' % {'c1pk': c1.pk, 'c2pk': c2.pk} ) self.assertHTMLEqual( conditional_escape(w.render('company_widget2', [c1.pk])), '<input type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': c1.pk} ) class RelatedFieldWidgetWrapperTests(DjangoTestCase): def test_no_can_add_related(self): rel = models.Individual._meta.get_field('parent').rel w = widgets.AdminRadioSelect() # Used to fail with a name error. w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site) self.assertFalse(w.can_add_related) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class DateTimePickerSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps fixtures = ['admin-widgets-users.xml'] urls = "admin_widgets.urls" webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver' def test_show_hide_date_time_picker_widgets(self): """ Ensure that pressing the ESC key closes the date and time picker widgets. Refs #17064. """ from selenium.webdriver.common.keys import Keys self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets self.selenium.get('%s%s' % (self.live_server_url, '/admin_widgets/member/add/')) # First, with the date picker widget --------------------------------- # Check that the date picker is hidden self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'none') # Click the calendar icon self.selenium.find_element_by_id('calendarlink0').click() # Check that the date picker is visible self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'block') # Press the ESC key self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) # Check that the date picker is hidden again self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'none') # Then, with the time picker widget ---------------------------------- # Check that the time picker is hidden self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'none') # Click the time icon self.selenium.find_element_by_id('clocklink0').click() # Check that the time picker is visible self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'block') # Press the ESC key self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) # Check that the time picker is hidden again self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'none') class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(TIME_ZONE='Asia/Singapore') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class DateTimePickerShortcutsSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps fixtures = ['admin-widgets-users.xml'] urls = "admin_widgets.urls" webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver' def test_date_time_picker_shortcuts(self): """ Ensure that date/time/datetime picker shortcuts work in the current time zone. Refs #20663. This test case is fairly tricky, it relies on selenium still running the browser in the default time zone "America/Chicago" despite `override_settings` changing the time zone to "Asia/Singapore". """ self.admin_login(username='super', password='secret', login_url='/') now = datetime.now() error_margin = timedelta(seconds=10) self.selenium.get('%s%s' % (self.live_server_url, '/admin_widgets/member/add/')) self.selenium.find_element_by_id('id_name').send_keys('test') # Click on the "today" and "now" shortcuts. shortcuts = self.selenium.find_elements_by_css_selector( '.field-birthdate .datetimeshortcuts') for shortcut in shortcuts: shortcut.find_element_by_tag_name('a').click() # Check that there is a time zone mismatch warning. # Warning: This would effectively fail if the TIME_ZONE defined in the # settings has the same UTC offset as "Asia/Singapore" because the # mismatch warning would be rightfully missing from the page. self.selenium.find_elements_by_css_selector( '.field-birthdate .timezonewarning') # Submit the form. self.selenium.find_element_by_tag_name('form').submit() self.wait_page_loaded() # Make sure that "now" in javascript is within 10 seconds # from "now" on the server side. member = models.Member.objects.get(name='test') self.assertGreater(member.birthdate, now - error_margin) self.assertLess(member.birthdate, now + error_margin) class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps fixtures = ['admin-widgets-users.xml'] urls = "admin_widgets.urls" webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver' def setUp(self): self.lisa = models.Student.objects.create(name='Lisa') self.john = models.Student.objects.create(name='John') self.bob = models.Student.objects.create(name='Bob') self.peter = models.Student.objects.create(name='Peter') self.jenny = models.Student.objects.create(name='Jenny') self.jason = models.Student.objects.create(name='Jason') self.cliff = models.Student.objects.create(name='Cliff') self.arthur = models.Student.objects.create(name='Arthur') self.school = models.School.objects.create(name='School of Awesome') super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp() def assertActiveButtons(self, mode, field_name, choose, remove, choose_all=None, remove_all=None): choose_link = '#id_%s_add_link' % field_name choose_all_link = '#id_%s_add_all_link' % field_name remove_link = '#id_%s_remove_link' % field_name remove_all_link = '#id_%s_remove_all_link' % field_name self.assertEqual(self.has_css_class(choose_link, 'active'), choose) self.assertEqual(self.has_css_class(remove_link, 'active'), remove) if mode == 'horizontal': self.assertEqual(self.has_css_class(choose_all_link, 'active'), choose_all) self.assertEqual(self.has_css_class(remove_all_link, 'active'), remove_all) def execute_basic_operations(self, mode, field_name): from_box = '#id_%s_from' % field_name to_box = '#id_%s_to' % field_name choose_link = 'id_%s_add_link' % field_name choose_all_link = 'id_%s_add_all_link' % field_name remove_link = 'id_%s_remove_link' % field_name remove_all_link = 'id_%s_remove_all_link' % field_name # Initial positions --------------------------------------------------- self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id)]) self.assertActiveButtons(mode, field_name, False, False, True, True) # Click 'Choose all' -------------------------------------------------- if mode == 'horizontal': self.selenium.find_element_by_id(choose_all_link).click() elif mode == 'vertical': # There 's no 'Choose all' button in vertical mode, so individually # select all options and click 'Choose'. for option in self.selenium.find_elements_by_css_selector(from_box + ' > option'): option.click() self.selenium.find_element_by_id(choose_link).click() self.assertSelectOptions(from_box, []) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertActiveButtons(mode, field_name, False, False, False, True) # Click 'Remove all' -------------------------------------------------- if mode == 'horizontal': self.selenium.find_element_by_id(remove_all_link).click() elif mode == 'vertical': # There 's no 'Remove all' button in vertical mode, so individually # select all options and click 'Remove'. for option in self.selenium.find_elements_by_css_selector(to_box + ' > option'): option.click() self.selenium.find_element_by_id(remove_link).click() self.assertSelectOptions(from_box, [str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertSelectOptions(to_box, []) self.assertActiveButtons(mode, field_name, False, False, True, False) # Choose some options ------------------------------------------------ self.get_select_option(from_box, str(self.lisa.id)).click() self.get_select_option(from_box, str(self.jason.id)).click() self.get_select_option(from_box, str(self.bob.id)).click() self.get_select_option(from_box, str(self.john.id)).click() self.assertActiveButtons(mode, field_name, True, False, True, False) self.selenium.find_element_by_id(choose_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions(from_box, [str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id)]) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.bob.id), str(self.jason.id), str(self.john.id)]) # Remove some options ------------------------------------------------- self.get_select_option(to_box, str(self.lisa.id)).click() self.get_select_option(to_box, str(self.bob.id)).click() self.assertActiveButtons(mode, field_name, False, True, True, True) self.selenium.find_element_by_id(remove_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions(from_box, [str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id)]) self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Choose some more options -------------------------------------------- self.get_select_option(from_box, str(self.arthur.id)).click() self.get_select_option(from_box, str(self.cliff.id)).click() self.selenium.find_element_by_id(choose_link).click() self.assertSelectOptions(from_box, [str(self.peter.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id)]) self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id), str(self.arthur.id), str(self.cliff.id)]) def test_basic(self): self.school.students = [self.lisa, self.peter] self.school.alumni = [self.lisa, self.peter] self.school.save() self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id)) self.wait_page_loaded() self.execute_basic_operations('vertical', 'students') self.execute_basic_operations('horizontal', 'alumni') # Save and check that everything is properly stored in the database --- self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john]) self.assertEqual(list(self.school.alumni.all()), [self.arthur, self.cliff, self.jason, self.john]) def test_filter(self): """ Ensure that typing in the search box filters out options displayed in the 'from' box. """ from selenium.webdriver.common.keys import Keys self.school.students = [self.lisa, self.peter] self.school.alumni = [self.lisa, self.peter] self.school.save() self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id)) for field_name in ['students', 'alumni']: from_box = '#id_%s_from' % field_name to_box = '#id_%s_to' % field_name choose_link = '#id_%s_add_link' % field_name remove_link = '#id_%s_remove_link' % field_name input = self.selenium.find_element_by_css_selector('#id_%s_input' % field_name) # Initial values self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) # Typing in some characters filters out non-matching options input.send_keys('a') self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) input.send_keys('R') self.assertSelectOptions(from_box, [str(self.arthur.id)]) # Clearing the text box makes the other options reappear input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) # ----------------------------------------------------------------- # Check that chosing a filtered option sends it properly to the # 'to' box. input.send_keys('a') self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) self.get_select_option(from_box, str(self.jason.id)).click() self.selenium.find_element_by_css_selector(choose_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id)]) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id), str(self.jason.id)]) self.get_select_option(to_box, str(self.lisa.id)).click() self.selenium.find_element_by_css_selector(remove_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.lisa.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) # Clear text box self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jenny.id), str(self.john.id), str(self.lisa.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) # Save and check that everything is properly stored in the database --- self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps fixtures = ['admin-widgets-users.xml'] urls = "admin_widgets.urls" webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver' def setUp(self): models.Band.objects.create(id=42, name='Bogey Blues') models.Band.objects.create(id=98, name='Green Potatoes') super(AdminRawIdWidgetSeleniumFirefoxTests, self).setUp() def test_foreignkey(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/event/add/')) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '') # Open the popup window and click on a band self.selenium.find_element_by_id('lookup_id_main_band').click() self.selenium.switch_to_window('id_main_band') self.wait_page_loaded() link = self.selenium.find_element_by_link_text('Bogey Blues') self.assertTrue('/band/42/' in link.get_attribute('href')) link.click() # The field now contains the selected band's id self.selenium.switch_to_window(main_window) self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '42') # Reopen the popup window and click on another band self.selenium.find_element_by_id('lookup_id_main_band').click() self.selenium.switch_to_window('id_main_band') self.wait_page_loaded() link = self.selenium.find_element_by_link_text('Green Potatoes') self.assertTrue('/band/98/' in link.get_attribute('href')) link.click() # The field now contains the other selected band's id self.selenium.switch_to_window(main_window) self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '98') def test_many_to_many(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/event/add/')) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '') # Open the popup window and click on a band self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.selenium.switch_to_window('id_supporting_bands') self.wait_page_loaded() link = self.selenium.find_element_by_link_text('Bogey Blues') self.assertTrue('/band/42/' in link.get_attribute('href')) link.click() # The field now contains the selected band's id self.selenium.switch_to_window(main_window) self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '42') # Reopen the popup window and click on another band self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.selenium.switch_to_window('id_supporting_bands') self.wait_page_loaded() link = self.selenium.find_element_by_link_text('Green Potatoes') self.assertTrue('/band/98/' in link.get_attribute('href')) link.click() # The field now contains the two selected bands' ids self.selenium.switch_to_window(main_window) self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '42,98') class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
xss
{ "code": [ " '<p class=\"url\">Currently:<a href=\"http://xn--example--7za4pnc.com\">http://example-äüö.com</a><br />Change:<input class=\"vURLField\" name=\"test\" type=\"url\" value=\"http://example-äüö.com\" /></p>'", " self.assertHTMLEqual(", " conditional_escape(w.render('test', 'http://example.com/<sometag>some text</sometag>')),", " '<p class=\"url\">Currently:<a href=\"http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E\">http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change:<input class=\"vURLField\" name=\"test\" type=\"url\" value=\"http://example.com/<sometag>some text</sometag>\" /></p>'", " self.assertHTMLEqual(", " conditional_escape(w.render('test', 'http://example-äüö.com/<sometag>some text</sometag>')),", " '<p class=\"url\">Currently:<a href=\"http://xn--example--7za4pnc.com/%3Csometag%3Esome%20text%3C/sometag%3E\">http://example-äüö.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change:<input class=\"vURLField\" name=\"test\" type=\"url\" value=\"http://example-äüö.com/<sometag>some text</sometag>\" /></p>'" ], "line_no": [ 324, 329, 330, 331, 333, 334, 335 ] }
{ "code": [ " '<p class=\"url\">Currently: <a href=\"http://xn--example--7za4pnc.com\">http://example-äüö.com</a><br />Change:<input class=\"vURLField\" name=\"test\" type=\"url\" value=\"http://example-äüö.com\" /></p>'", " self.assertEqual(", " w.render('test', 'http://example.com/<sometag>some text</sometag>'),", " '<p class=\"url\">Currently: <a href=\"http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E\">http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change: <input class=\"vURLField\" name=\"test\" type=\"url\" value=\"http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;\" /></p>'", " self.assertEqual(", " w.render('test', 'http://example-äüö.com/<sometag>some text</sometag>'),", " )", " self.assertEqual(", " w.render('test', 'http://www.example.com/%C3%A4\"><script>alert(\"XSS!\")</script>\"'),", " '<p class=\"url\">Currently: <a href=\"http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)%3C/script%3E%22\">http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;</a><br />Change: <input class=\"vURLField\" name=\"test\" type=\"url\" value=\"http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;\" /></p>'" ], "line_no": [ 324, 331, 332, 333, 335, 336, 338, 339, 340, 341 ] }
from __future__ import unicode_literals from datetime import datetime, timedelta from unittest import TestCase from django import .forms from django.conf import settings from django.contrib import admin from django.contrib.admin import .widgets from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import CharField, DateField from django.test import TestCase as DjangoTestCase from django.test.utils import override_settings from django.utils import six from django.utils import translation from django.utils.html import conditional_escape from . import .models from .widgetadmin import site as widget_admin_site VAR_0 = lambda: { 'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL, } class CLASS_0(TestCase): def FUNC_0(self, VAR_1, VAR_2, VAR_3, **VAR_4): class CLASS_25(admin.ModelAdmin): pass for k in VAR_4: setattr(CLASS_25, k, VAR_4[k]) VAR_16 = CLASS_25(VAR_1, admin.site) VAR_17 = VAR_16.formfield_for_dbfield(VAR_1._meta.get_field(VAR_2), request=None) if isinstance(VAR_17.widget, widgets.RelatedFieldWidgetWrapper): VAR_53 = VAR_17.widget.widget else: VAR_53 = VAR_17.widget self.assertTrue( isinstance(VAR_53, VAR_3), "Wrong VAR_53 for %s.%s: expected %s, got %s" % \ (VAR_1.__class__.__name__, VAR_2, VAR_3, type(VAR_53)) ) return VAR_17 def FUNC_1(self): self.assertFormfield(models.Event, 'start_date', widgets.AdminDateWidget) def FUNC_2(self): self.assertFormfield(models.Member, 'birthdate', widgets.AdminSplitDateTime) def FUNC_3(self): self.assertFormfield(models.Event, 'start_time', widgets.AdminTimeWidget) def FUNC_4(self): self.assertFormfield(models.Event, 'description', widgets.AdminTextareaWidget) def FUNC_5(self): self.assertFormfield(models.Event, 'link', widgets.AdminURLFieldWidget) def FUNC_6(self): self.assertFormfield(models.Event, 'min_age', widgets.AdminIntegerFieldWidget) def FUNC_7(self): self.assertFormfield(models.Member, 'name', widgets.AdminTextInputWidget) def FUNC_8(self): self.assertFormfield(models.Member, 'email', widgets.AdminEmailInputWidget) def FUNC_9(self): self.assertFormfield(models.Album, 'cover_art', widgets.AdminFileWidget) def FUNC_10(self): self.assertFormfield(models.Event, 'main_band', forms.Select) def FUNC_11(self): self.assertFormfield(models.Event, 'main_band', widgets.ForeignKeyRawIdWidget, raw_id_fields=['main_band']) def FUNC_12(self): VAR_17 = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect, radio_fields={'main_band':admin.VERTICAL}) self.assertEqual(VAR_17.empty_label, None) def FUNC_13(self): self.assertFormfield(models.Band, 'members', forms.SelectMultiple) def FUNC_14(self): self.assertFormfield(models.Band, 'members', widgets.ManyToManyRawIdWidget, raw_id_fields=['members']) def FUNC_15(self): self.assertFormfield(models.Band, 'members', widgets.FilteredSelectMultiple, VAR_55=['members']) def FUNC_16(self): self.assertFormfield(models.Event, 'start_date', forms.TextInput, VAR_54={DateField: {'widget': forms.TextInput}}) def FUNC_17(self): class CLASS_26(admin.ModelAdmin): VAR_54 = { CharField: {'widget': forms.TextInput(attrs={'size':'10'})} } VAR_16 = CLASS_26(models.Band, admin.site) VAR_18 = VAR_16.formfield_for_dbfield(models.Band._meta.get_field('name'), request=None) VAR_19 = VAR_16.formfield_for_dbfield(models.Band._meta.get_field('style'), request=None) self.assertNotEqual(VAR_18.widget, VAR_19.widget) self.assertEqual(VAR_18.widget.attrs['maxlength'], '100') self.assertEqual(VAR_19.widget.attrs['maxlength'], '20') self.assertEqual(VAR_19.widget.attrs['size'], '10') def FUNC_18(self): self.assertFormfield(models.Member, 'gender', forms.Select) def FUNC_19(self): self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect, radio_fields={'gender':admin.VERTICAL}) def FUNC_20(self): self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget) def FUNC_21(self): class CLASS_27(admin.ModelAdmin): VAR_55=['companies'] self.assertFormfield(models.Advisor, 'companies', widgets.FilteredSelectMultiple, VAR_55=['companies']) VAR_16 = CLASS_27(models.Advisor, admin.site) VAR_20 = VAR_16.formfield_for_dbfield(models.Advisor._meta.get_field('companies'), request=None) self.assertEqual(six.text_type(VAR_20.help_text), ' Hold down "Control", or "Command" on a Mac, to select more than one.') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_1(DjangoTestCase): VAR_5 = ["admin-widgets-users.xml"] def FUNC_22(self): self.client.login(username="super", password="secret") VAR_21 = self.client.get("/widget_admin/admin_widgets/cartire/add/") self.assertNotContains(VAR_21, "BMW M3") self.assertContains(VAR_21, "Volkswagon Passat") @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_2(DjangoTestCase): VAR_5 = ["admin-widgets-users.xml"] VAR_6 = '/widget_admin' def FUNC_23(self): self.client.login(username="super", password="secret") def FUNC_24(self): self.client.logout() def FUNC_25(self): VAR_21 = self.client.get('%s/admin_widgets/car/' % self.admin_root) self.assertContains(VAR_21, '%s/auth/user/add/' % self.admin_root) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_3(DjangoTestCase): VAR_5 = ["admin-widgets-users.xml"] VAR_6 = '/widget_admin' def FUNC_23(self): self.client.login(username="super", password="secret") def FUNC_24(self): self.client.logout() def FUNC_26(self): VAR_22 = models.Band.objects.create(name='Bogey Blues') VAR_23 = VAR_22.pk VAR_22.delete() VAR_24 = { "main_band": '%s' % VAR_23, } VAR_21 = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, VAR_24) self.assertContains(VAR_21, 'Select a valid choice. That choice is not one of the available choices.') def FUNC_27(self): for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234): VAR_21 = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, {"main_band": test_str}) self.assertContains(VAR_21, 'Select a valid choice. That choice is not one of the available choices.') def FUNC_28(self): VAR_25 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')}) VAR_26 = widgets.url_params_from_lookup_dict({'color__in': ['red', 'blue']}) self.assertEqual(VAR_25, {'color__in': 'red,blue'}) self.assertEqual(VAR_25, VAR_26) def FUNC_29(self): def FUNC_50(): return 'works' VAR_25 = widgets.url_params_from_lookup_dict({'myfield': FUNC_50}) VAR_26 = widgets.url_params_from_lookup_dict({'myfield': FUNC_50()}) self.assertEqual(VAR_25, VAR_26) class CLASS_4(DjangoTestCase): def FUNC_30(self): VAR_27 = widgets.FilteredSelectMultiple('test', False) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'test')), '<select multiple="multiple" name="test" class="selectfilter">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 0, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % VAR_0() ) def FUNC_31(self): VAR_27 = widgets.FilteredSelectMultiple('test', True) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'test')), '<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % VAR_0() ) class CLASS_5(DjangoTestCase): def FUNC_32(self): VAR_27 = widgets.AdminDateWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<VAR_56 value="2007-12-01" type="text" class="vDateField" name="test" size="10" />', ) VAR_27 = widgets.AdminDateWidget(attrs={'size': 20, 'class': 'myDateField'}) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<VAR_56 value="2007-12-01" type="text" class="myDateField" name="test" size="20" />', ) class CLASS_6(DjangoTestCase): def FUNC_32(self): VAR_27 = widgets.AdminTimeWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<VAR_56 value="09:30:00" type="text" class="vTimeField" name="test" size="8" />', ) VAR_27 = widgets.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'}) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<VAR_56 value="09:30:00" type="text" class="myTimeField" name="test" size="20" />', ) class CLASS_7(DjangoTestCase): def FUNC_30(self): VAR_27 = widgets.AdminSplitDateTime() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<p class="datetime">Date: <VAR_56 value="2007-12-01" type="text" class="vDateField" name="test_0" size="10" /><br />Time: <VAR_56 value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>', ) def FUNC_33(self): VAR_27 = widgets.AdminSplitDateTime() with self.settings(USE_L10N=True): with translation.override('de-at'): VAR_27.is_localized = True self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<p class="datetime">Datum: <VAR_56 value="01.12.2007" type="text" class="vDateField" name="test_0" size="10" /><br />Zeit: <VAR_56 value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>', ) class CLASS_8(DjangoTestCase): def FUNC_30(self): VAR_27 = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', '')), '<VAR_56 class="vURLField" name="test" type="url" />' ) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'http://example.com')), '<p class="url">Currently:<a href="http://example.com">http://example.com</a><br />Change:<VAR_56 class="vURLField" name="test" type="url" value="http://example.com" /></p>' ) def FUNC_34(self): VAR_27 = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'http://example-äüö.com')), '<p class="url">Currently:<a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<VAR_56 class="vURLField" name="test" type="url" value="http://example-äüö.com" /></p>' ) def FUNC_35(self): VAR_27 = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'http://example.com/<sometag>some text</sometag>')), '<p class="url">Currently:<a href="http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change:<VAR_56 class="vURLField" name="test" type="url" value="http://example.com/<sometag>some text</sometag>" /></p>' ) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'http://example-äüö.com/<sometag>some text</sometag>')), '<p class="url">Currently:<a href="http://xn--example--7za4pnc.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example-äüö.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change:<VAR_56 class="vURLField" name="test" type="url" value="http://example-äüö.com/<sometag>some text</sometag>" /></p>' ) class CLASS_9(DjangoTestCase): def FUNC_30(self): VAR_22 = models.Band.objects.create(name='Linkin Park') VAR_28 = VAR_22.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) VAR_27 = widgets.AdminFileWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', VAR_28.cover_art)), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">albums\hybrid_theory.jpg</a> <span class="clearable-file-input"><VAR_56 type="checkbox" name="test-clear" id="test-clear_id" /> <label for="test-clear_id">Clear</label></span><br />Change: <VAR_56 type="file" name="test" /></p>' % { 'STORAGE_URL': default_storage.url('') }, ) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', SimpleUploadedFile('test', b'content'))), '<VAR_56 type="file" name="test" />', ) class CLASS_10(DjangoTestCase): def FUNC_30(self): VAR_22 = models.Band.objects.create(name='Linkin Park') VAR_22.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) VAR_29 = models.Album._meta.get_field('band').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', VAR_22.pk, attrs={})), '<VAR_56 type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/VAR_22/?t=id" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Linkin Park</strong>' % dict(VAR_0(), bandpk=VAR_22.pk) ) def FUNC_36(self): VAR_30 = models.Inventory.objects.create(barcode=86, name='Apple') models.Inventory.objects.create(barcode=22, name='Pear') VAR_31 = models.Inventory.objects.create( barcode=87, name='Core', parent=VAR_30 ) VAR_29 = models.Inventory._meta.get_field('parent').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( VAR_27.render('test', VAR_31.parent_id, attrs={}), '<VAR_56 type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Apple</strong>' % VAR_0() ) def FUNC_37(self): VAR_32 = models.Honeycomb.objects.create(location='Old tree') VAR_32.bee_set.create() VAR_29 = models.Bee._meta.get_field('honeycomb').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('honeycomb_widget', VAR_32.pk, attrs={})), '<VAR_56 type="text" name="honeycomb_widget" value="%(hcombpk)s" />&nbsp;<strong>Honeycomb object</strong>' % {'hcombpk': VAR_32.pk} ) def FUNC_38(self): VAR_33 = models.Individual.objects.create(name='Subject #1') models.Individual.objects.create(name='Child', parent=VAR_33) VAR_29 = models.Individual._meta.get_field('parent').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('individual_widget', VAR_33.pk, attrs={})), '<VAR_56 type="text" name="individual_widget" value="%(subj1pk)s" />&nbsp;<strong>Individual object</strong>' % {'subj1pk': VAR_33.pk} ) def FUNC_39(self): VAR_29 = models.Inventory._meta.get_field('parent').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) VAR_34 = models.Inventory.objects.create( barcode=93, name='Hidden', VAR_34=True ) VAR_35 = models.Inventory.objects.create( barcode=94, name='Child of hidden', parent=VAR_34 ) self.assertHTMLEqual( VAR_27.render('test', VAR_35.parent_id, attrs={}), '<VAR_56 type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Hidden</strong>' % VAR_0() ) class CLASS_11(DjangoTestCase): def FUNC_30(self): VAR_22 = models.Band.objects.create(name='Linkin Park') VAR_36 = models.Member.objects.create(name='Chester') VAR_37 = models.Member.objects.create(name='Mike') VAR_22.members.add(VAR_36, VAR_37) VAR_29 = models.Band._meta.get_field('members').rel VAR_27 = widgets.ManyToManyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', [VAR_36.pk, VAR_37.pk], attrs={})), '<VAR_56 type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/VAR_44/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="/static/admin/img/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(VAR_0(), m1pk=VAR_36.pk, m2pk=VAR_37.pk) ) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', [VAR_36.pk])), '<VAR_56 type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/VAR_44/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(VAR_0(), m1pk=VAR_36.pk) ) def FUNC_40(self): VAR_38 = models.Advisor.objects.create(name='Rockstar Techie') VAR_39 = models.Company.objects.create(name='Doodle') VAR_40 = models.Company.objects.create(name='Pear') VAR_38.companies.add(VAR_39, VAR_40) VAR_29 = models.Advisor._meta.get_field('companies').rel VAR_27 = widgets.ManyToManyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('company_widget1', [VAR_39.pk, VAR_40.pk], attrs={})), '<VAR_56 type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s" />' % {'c1pk': VAR_39.pk, 'c2pk': VAR_40.pk} ) self.assertHTMLEqual( conditional_escape(VAR_27.render('company_widget2', [VAR_39.pk])), '<VAR_56 type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': VAR_39.pk} ) class CLASS_12(DjangoTestCase): def FUNC_41(self): VAR_29 = models.Individual._meta.get_field('parent').rel VAR_27 = widgets.AdminRadioSelect() VAR_27 = widgets.RelatedFieldWidgetWrapper(VAR_27, VAR_29, widget_admin_site) self.assertFalse(VAR_27.can_add_related) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_13(AdminSeleniumWebDriverTestCase): VAR_7 = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps VAR_5 = ['admin-widgets-users.xml'] VAR_8 = "admin_widgets.urls" VAR_9 = 'selenium.webdriver.firefox.webdriver.WebDriver' def FUNC_42(self): from selenium.webdriver.common.keys import Keys self.admin_login(username='super', password='secret', login_url='/') self.selenium.get('%s%s' % (self.live_server_url, '/admin_widgets/VAR_44/add/')) self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'none') self.selenium.find_element_by_id('calendarlink0').click() self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'block') self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'none') self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'none') self.selenium.find_element_by_id('clocklink0').click() self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'block') self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'none') class CLASS_14(CLASS_13): VAR_9 = 'selenium.webdriver.chrome.webdriver.WebDriver' class CLASS_15(CLASS_13): VAR_9 = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(TIME_ZONE='Asia/Singapore') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_16(AdminSeleniumWebDriverTestCase): VAR_7 = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps VAR_5 = ['admin-widgets-users.xml'] VAR_8 = "admin_widgets.urls" VAR_9 = 'selenium.webdriver.firefox.webdriver.WebDriver' def FUNC_43(self): self.admin_login(username='super', password='secret', login_url='/') VAR_41 = datetime.now() VAR_42 = timedelta(seconds=10) self.selenium.get('%s%s' % (self.live_server_url, '/admin_widgets/VAR_44/add/')) self.selenium.find_element_by_id('id_name').send_keys('test') VAR_43 = self.selenium.find_elements_by_css_selector( '.field-birthdate .datetimeshortcuts') for shortcut in VAR_43: shortcut.find_element_by_tag_name('a').click() self.selenium.find_elements_by_css_selector( '.field-birthdate .timezonewarning') self.selenium.find_element_by_tag_name('form').submit() self.wait_page_loaded() VAR_44 = models.Member.objects.get(name='test') self.assertGreater(VAR_44.birthdate, VAR_41 - VAR_42) self.assertLess(VAR_44.birthdate, VAR_41 + VAR_42) class CLASS_17(CLASS_16): VAR_9 = 'selenium.webdriver.chrome.webdriver.WebDriver' class CLASS_18(CLASS_16): VAR_9 = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_19(AdminSeleniumWebDriverTestCase): VAR_7 = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps VAR_5 = ['admin-widgets-users.xml'] VAR_8 = "admin_widgets.urls" VAR_9 = 'selenium.webdriver.firefox.webdriver.WebDriver' def FUNC_23(self): self.lisa = models.Student.objects.create(name='Lisa') self.john = models.Student.objects.create(name='John') self.bob = models.Student.objects.create(name='Bob') self.peter = models.Student.objects.create(name='Peter') self.jenny = models.Student.objects.create(name='Jenny') self.jason = models.Student.objects.create(name='Jason') self.cliff = models.Student.objects.create(name='Cliff') self.arthur = models.Student.objects.create(name='Arthur') self.school = models.School.objects.create(name='School of Awesome') super(CLASS_19, self).setUp() def FUNC_44(self, VAR_10, VAR_11, VAR_12, VAR_13, VAR_14=None, VAR_15=None): VAR_45 = '#id_%s_add_link' % VAR_11 VAR_46 = '#id_%s_add_all_link' % VAR_11 VAR_47 = '#id_%s_remove_link' % VAR_11 VAR_48 = '#id_%s_remove_all_link' % VAR_11 self.assertEqual(self.has_css_class(VAR_45, 'active'), VAR_12) self.assertEqual(self.has_css_class(VAR_47, 'active'), VAR_13) if VAR_10 == 'horizontal': self.assertEqual(self.has_css_class(VAR_46, 'active'), VAR_14) self.assertEqual(self.has_css_class(VAR_48, 'active'), VAR_15) def FUNC_45(self, VAR_10, VAR_11): VAR_49 = '#id_%s_from' % VAR_11 VAR_50 = '#id_%s_to' % VAR_11 VAR_45 = 'id_%s_add_link' % VAR_11 VAR_46 = 'id_%s_add_all_link' % VAR_11 VAR_47 = 'id_%s_remove_link' % VAR_11 VAR_48 = 'id_%s_remove_all_link' % VAR_11 self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertSelectOptions(VAR_50, [str(self.lisa.id), str(self.peter.id)]) self.assertActiveButtons(VAR_10, VAR_11, False, False, True, True) if VAR_10 == 'horizontal': self.selenium.find_element_by_id(VAR_46).click() elif VAR_10 == 'vertical': for option in self.selenium.find_elements_by_css_selector(VAR_49 + ' > option'): option.click() self.selenium.find_element_by_id(VAR_45).click() self.assertSelectOptions(VAR_49, []) self.assertSelectOptions(VAR_50, [str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertActiveButtons(VAR_10, VAR_11, False, False, False, True) if VAR_10 == 'horizontal': self.selenium.find_element_by_id(VAR_48).click() elif VAR_10 == 'vertical': for option in self.selenium.find_elements_by_css_selector(VAR_50 + ' > option'): option.click() self.selenium.find_element_by_id(VAR_47).click() self.assertSelectOptions(VAR_49, [str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertSelectOptions(VAR_50, []) self.assertActiveButtons(VAR_10, VAR_11, False, False, True, False) self.get_select_option(VAR_49, str(self.lisa.id)).click() self.get_select_option(VAR_49, str(self.jason.id)).click() self.get_select_option(VAR_49, str(self.bob.id)).click() self.get_select_option(VAR_49, str(self.john.id)).click() self.assertActiveButtons(VAR_10, VAR_11, True, False, True, False) self.selenium.find_element_by_id(VAR_45).click() self.assertActiveButtons(VAR_10, VAR_11, False, False, True, True) self.assertSelectOptions(VAR_49, [str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id)]) self.assertSelectOptions(VAR_50, [str(self.lisa.id), str(self.bob.id), str(self.jason.id), str(self.john.id)]) self.get_select_option(VAR_50, str(self.lisa.id)).click() self.get_select_option(VAR_50, str(self.bob.id)).click() self.assertActiveButtons(VAR_10, VAR_11, False, True, True, True) self.selenium.find_element_by_id(VAR_47).click() self.assertActiveButtons(VAR_10, VAR_11, False, False, True, True) self.assertSelectOptions(VAR_49, [str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id)]) self.assertSelectOptions(VAR_50, [str(self.jason.id), str(self.john.id)]) self.get_select_option(VAR_49, str(self.arthur.id)).click() self.get_select_option(VAR_49, str(self.cliff.id)).click() self.selenium.find_element_by_id(VAR_45).click() self.assertSelectOptions(VAR_49, [str(self.peter.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id)]) self.assertSelectOptions(VAR_50, [str(self.jason.id), str(self.john.id), str(self.arthur.id), str(self.cliff.id)]) def FUNC_46(self): self.school.students = [self.lisa, self.peter] self.school.alumni = [self.lisa, self.peter] self.school.save() self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id)) self.wait_page_loaded() self.execute_basic_operations('vertical', 'students') self.execute_basic_operations('horizontal', 'alumni') self.selenium.find_element_by_xpath('//VAR_56[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john]) self.assertEqual(list(self.school.alumni.all()), [self.arthur, self.cliff, self.jason, self.john]) def FUNC_47(self): from selenium.webdriver.common.keys import Keys self.school.students = [self.lisa, self.peter] self.school.alumni = [self.lisa, self.peter] self.school.save() self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id)) for VAR_11 in ['students', 'alumni']: VAR_49 = '#id_%s_from' % VAR_11 VAR_50 = '#id_%s_to' % VAR_11 VAR_45 = '#id_%s_add_link' % VAR_11 VAR_47 = '#id_%s_remove_link' % VAR_11 VAR_56 = self.selenium.find_element_by_css_selector('#id_%s_input' % VAR_11) self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) VAR_56.send_keys('a') self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.jason.id)]) VAR_56.send_keys('R') self.assertSelectOptions(VAR_49, [str(self.arthur.id)]) VAR_56.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.jason.id)]) VAR_56.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) VAR_56.send_keys('a') self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.jason.id)]) self.get_select_option(VAR_49, str(self.jason.id)).click() self.selenium.find_element_by_css_selector(VAR_45).click() self.assertSelectOptions(VAR_49, [str(self.arthur.id)]) self.assertSelectOptions(VAR_50, [str(self.lisa.id), str(self.peter.id), str(self.jason.id)]) self.get_select_option(VAR_50, str(self.lisa.id)).click() self.selenium.find_element_by_css_selector(VAR_47).click() self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.lisa.id)]) self.assertSelectOptions(VAR_50, [str(self.peter.id), str(self.jason.id)]) VAR_56.send_keys([Keys.BACK_SPACE]) # Clear text box self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jenny.id), str(self.john.id), str(self.lisa.id)]) self.assertSelectOptions(VAR_50, [str(self.peter.id), str(self.jason.id)]) self.selenium.find_element_by_xpath('//VAR_56[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) class CLASS_20(CLASS_19): VAR_9 = 'selenium.webdriver.chrome.webdriver.WebDriver' class CLASS_21(CLASS_19): VAR_9 = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_22(AdminSeleniumWebDriverTestCase): VAR_7 = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps VAR_5 = ['admin-widgets-users.xml'] VAR_8 = "admin_widgets.urls" VAR_9 = 'selenium.webdriver.firefox.webdriver.WebDriver' def FUNC_23(self): models.Band.objects.create(id=42, name='Bogey Blues') models.Band.objects.create(id=98, name='Green Potatoes') super(CLASS_22, self).setUp() def FUNC_48(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/event/add/')) VAR_51 = self.selenium.current_window_handle self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '') self.selenium.find_element_by_id('lookup_id_main_band').click() self.selenium.switch_to_window('id_main_band') self.wait_page_loaded() VAR_52 = self.selenium.find_element_by_link_text('Bogey Blues') self.assertTrue('/VAR_22/42/' in VAR_52.get_attribute('href')) VAR_52.click() self.selenium.switch_to_window(VAR_51) self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '42') self.selenium.find_element_by_id('lookup_id_main_band').click() self.selenium.switch_to_window('id_main_band') self.wait_page_loaded() VAR_52 = self.selenium.find_element_by_link_text('Green Potatoes') self.assertTrue('/VAR_22/98/' in VAR_52.get_attribute('href')) VAR_52.click() self.selenium.switch_to_window(VAR_51) self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '98') def FUNC_49(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/event/add/')) VAR_51 = self.selenium.current_window_handle self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '') self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.selenium.switch_to_window('id_supporting_bands') self.wait_page_loaded() VAR_52 = self.selenium.find_element_by_link_text('Bogey Blues') self.assertTrue('/VAR_22/42/' in VAR_52.get_attribute('href')) VAR_52.click() self.selenium.switch_to_window(VAR_51) self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '42') self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.selenium.switch_to_window('id_supporting_bands') self.wait_page_loaded() VAR_52 = self.selenium.find_element_by_link_text('Green Potatoes') self.assertTrue('/VAR_22/98/' in VAR_52.get_attribute('href')) VAR_52.click() self.selenium.switch_to_window(VAR_51) self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '42,98') class CLASS_23(CLASS_22): VAR_9 = 'selenium.webdriver.chrome.webdriver.WebDriver' class CLASS_24(CLASS_22): VAR_9 = 'selenium.webdriver.ie.webdriver.WebDriver'
from __future__ import unicode_literals from datetime import datetime, timedelta from unittest import TestCase from django import .forms from django.conf import settings from django.contrib import admin from django.contrib.admin import .widgets from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import CharField, DateField from django.test import TestCase as DjangoTestCase from django.test.utils import override_settings from django.utils import six from django.utils import translation from django.utils.html import conditional_escape from . import .models from .widgetadmin import site as widget_admin_site VAR_0 = lambda: { 'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL, } class CLASS_0(TestCase): def FUNC_0(self, VAR_1, VAR_2, VAR_3, **VAR_4): class CLASS_25(admin.ModelAdmin): pass for k in VAR_4: setattr(CLASS_25, k, VAR_4[k]) VAR_16 = CLASS_25(VAR_1, admin.site) VAR_17 = VAR_16.formfield_for_dbfield(VAR_1._meta.get_field(VAR_2), request=None) if isinstance(VAR_17.widget, widgets.RelatedFieldWidgetWrapper): VAR_53 = VAR_17.widget.widget else: VAR_53 = VAR_17.widget self.assertTrue( isinstance(VAR_53, VAR_3), "Wrong VAR_53 for %s.%s: expected %s, got %s" % \ (VAR_1.__class__.__name__, VAR_2, VAR_3, type(VAR_53)) ) return VAR_17 def FUNC_1(self): self.assertFormfield(models.Event, 'start_date', widgets.AdminDateWidget) def FUNC_2(self): self.assertFormfield(models.Member, 'birthdate', widgets.AdminSplitDateTime) def FUNC_3(self): self.assertFormfield(models.Event, 'start_time', widgets.AdminTimeWidget) def FUNC_4(self): self.assertFormfield(models.Event, 'description', widgets.AdminTextareaWidget) def FUNC_5(self): self.assertFormfield(models.Event, 'link', widgets.AdminURLFieldWidget) def FUNC_6(self): self.assertFormfield(models.Event, 'min_age', widgets.AdminIntegerFieldWidget) def FUNC_7(self): self.assertFormfield(models.Member, 'name', widgets.AdminTextInputWidget) def FUNC_8(self): self.assertFormfield(models.Member, 'email', widgets.AdminEmailInputWidget) def FUNC_9(self): self.assertFormfield(models.Album, 'cover_art', widgets.AdminFileWidget) def FUNC_10(self): self.assertFormfield(models.Event, 'main_band', forms.Select) def FUNC_11(self): self.assertFormfield(models.Event, 'main_band', widgets.ForeignKeyRawIdWidget, raw_id_fields=['main_band']) def FUNC_12(self): VAR_17 = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect, radio_fields={'main_band':admin.VERTICAL}) self.assertEqual(VAR_17.empty_label, None) def FUNC_13(self): self.assertFormfield(models.Band, 'members', forms.SelectMultiple) def FUNC_14(self): self.assertFormfield(models.Band, 'members', widgets.ManyToManyRawIdWidget, raw_id_fields=['members']) def FUNC_15(self): self.assertFormfield(models.Band, 'members', widgets.FilteredSelectMultiple, VAR_55=['members']) def FUNC_16(self): self.assertFormfield(models.Event, 'start_date', forms.TextInput, VAR_54={DateField: {'widget': forms.TextInput}}) def FUNC_17(self): class CLASS_26(admin.ModelAdmin): VAR_54 = { CharField: {'widget': forms.TextInput(attrs={'size':'10'})} } VAR_16 = CLASS_26(models.Band, admin.site) VAR_18 = VAR_16.formfield_for_dbfield(models.Band._meta.get_field('name'), request=None) VAR_19 = VAR_16.formfield_for_dbfield(models.Band._meta.get_field('style'), request=None) self.assertNotEqual(VAR_18.widget, VAR_19.widget) self.assertEqual(VAR_18.widget.attrs['maxlength'], '100') self.assertEqual(VAR_19.widget.attrs['maxlength'], '20') self.assertEqual(VAR_19.widget.attrs['size'], '10') def FUNC_18(self): self.assertFormfield(models.Member, 'gender', forms.Select) def FUNC_19(self): self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect, radio_fields={'gender':admin.VERTICAL}) def FUNC_20(self): self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget) def FUNC_21(self): class CLASS_27(admin.ModelAdmin): VAR_55=['companies'] self.assertFormfield(models.Advisor, 'companies', widgets.FilteredSelectMultiple, VAR_55=['companies']) VAR_16 = CLASS_27(models.Advisor, admin.site) VAR_20 = VAR_16.formfield_for_dbfield(models.Advisor._meta.get_field('companies'), request=None) self.assertEqual(six.text_type(VAR_20.help_text), ' Hold down "Control", or "Command" on a Mac, to select more than one.') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_1(DjangoTestCase): VAR_5 = ["admin-widgets-users.xml"] def FUNC_22(self): self.client.login(username="super", password="secret") VAR_21 = self.client.get("/widget_admin/admin_widgets/cartire/add/") self.assertNotContains(VAR_21, "BMW M3") self.assertContains(VAR_21, "Volkswagon Passat") @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_2(DjangoTestCase): VAR_5 = ["admin-widgets-users.xml"] VAR_6 = '/widget_admin' def FUNC_23(self): self.client.login(username="super", password="secret") def FUNC_24(self): self.client.logout() def FUNC_25(self): VAR_21 = self.client.get('%s/admin_widgets/car/' % self.admin_root) self.assertContains(VAR_21, '%s/auth/user/add/' % self.admin_root) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_3(DjangoTestCase): VAR_5 = ["admin-widgets-users.xml"] VAR_6 = '/widget_admin' def FUNC_23(self): self.client.login(username="super", password="secret") def FUNC_24(self): self.client.logout() def FUNC_26(self): VAR_22 = models.Band.objects.create(name='Bogey Blues') VAR_23 = VAR_22.pk VAR_22.delete() VAR_24 = { "main_band": '%s' % VAR_23, } VAR_21 = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, VAR_24) self.assertContains(VAR_21, 'Select a valid choice. That choice is not one of the available choices.') def FUNC_27(self): for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234): VAR_21 = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, {"main_band": test_str}) self.assertContains(VAR_21, 'Select a valid choice. That choice is not one of the available choices.') def FUNC_28(self): VAR_25 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')}) VAR_26 = widgets.url_params_from_lookup_dict({'color__in': ['red', 'blue']}) self.assertEqual(VAR_25, {'color__in': 'red,blue'}) self.assertEqual(VAR_25, VAR_26) def FUNC_29(self): def FUNC_50(): return 'works' VAR_25 = widgets.url_params_from_lookup_dict({'myfield': FUNC_50}) VAR_26 = widgets.url_params_from_lookup_dict({'myfield': FUNC_50()}) self.assertEqual(VAR_25, VAR_26) class CLASS_4(DjangoTestCase): def FUNC_30(self): VAR_27 = widgets.FilteredSelectMultiple('test', False) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'test')), '<select multiple="multiple" name="test" class="selectfilter">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 0, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % VAR_0() ) def FUNC_31(self): VAR_27 = widgets.FilteredSelectMultiple('test', True) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'test')), '<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % VAR_0() ) class CLASS_5(DjangoTestCase): def FUNC_32(self): VAR_27 = widgets.AdminDateWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<VAR_56 value="2007-12-01" type="text" class="vDateField" name="test" size="10" />', ) VAR_27 = widgets.AdminDateWidget(attrs={'size': 20, 'class': 'myDateField'}) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<VAR_56 value="2007-12-01" type="text" class="myDateField" name="test" size="20" />', ) class CLASS_6(DjangoTestCase): def FUNC_32(self): VAR_27 = widgets.AdminTimeWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<VAR_56 value="09:30:00" type="text" class="vTimeField" name="test" size="8" />', ) VAR_27 = widgets.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'}) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<VAR_56 value="09:30:00" type="text" class="myTimeField" name="test" size="20" />', ) class CLASS_7(DjangoTestCase): def FUNC_30(self): VAR_27 = widgets.AdminSplitDateTime() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<p class="datetime">Date: <VAR_56 value="2007-12-01" type="text" class="vDateField" name="test_0" size="10" /><br />Time: <VAR_56 value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>', ) def FUNC_33(self): VAR_27 = widgets.AdminSplitDateTime() with self.settings(USE_L10N=True): with translation.override('de-at'): VAR_27.is_localized = True self.assertHTMLEqual( conditional_escape(VAR_27.render('test', datetime(2007, 12, 1, 9, 30))), '<p class="datetime">Datum: <VAR_56 value="01.12.2007" type="text" class="vDateField" name="test_0" size="10" /><br />Zeit: <VAR_56 value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>', ) class CLASS_8(DjangoTestCase): def FUNC_30(self): VAR_27 = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', '')), '<VAR_56 class="vURLField" name="test" type="url" />' ) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'http://example.com')), '<p class="url">Currently:<a href="http://example.com">http://example.com</a><br />Change:<VAR_56 class="vURLField" name="test" type="url" value="http://example.com" /></p>' ) def FUNC_34(self): VAR_27 = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', 'http://example-äüö.com')), '<p class="url">Currently: <a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<VAR_56 class="vURLField" name="test" type="url" value="http://example-äüö.com" /></p>' ) def FUNC_35(self): VAR_27 = widgets.AdminURLFieldWidget() self.assertEqual( VAR_27.render('test', 'http://example.com/<sometag>some text</sometag>'), '<p class="url">Currently: <a href="http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change: <VAR_56 class="vURLField" name="test" type="url" value="http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;" /></p>' ) self.assertEqual( VAR_27.render('test', 'http://example-äüö.com/<sometag>some text</sometag>'), '<p class="url">Currently: <a href="http://xn--example--7za4pnc.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example-äüö.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change: <VAR_56 class="vURLField" name="test" type="url" value="http://example-äüö.com/&lt;sometag&gt;some text&lt;/sometag&gt;" /></p>' ) self.assertEqual( VAR_27.render('test', 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"'), '<p class="url">Currently: <a href="http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)%3C/script%3E%22">http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;</a><br />Change: <VAR_56 class="vURLField" name="test" type="url" value="http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;" /></p>' ) class CLASS_9(DjangoTestCase): def FUNC_30(self): VAR_22 = models.Band.objects.create(name='Linkin Park') VAR_28 = VAR_22.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) VAR_27 = widgets.AdminFileWidget() self.assertHTMLEqual( conditional_escape(VAR_27.render('test', VAR_28.cover_art)), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">albums\hybrid_theory.jpg</a> <span class="clearable-file-input"><VAR_56 type="checkbox" name="test-clear" id="test-clear_id" /> <label for="test-clear_id">Clear</label></span><br />Change: <VAR_56 type="file" name="test" /></p>' % { 'STORAGE_URL': default_storage.url('') }, ) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', SimpleUploadedFile('test', b'content'))), '<VAR_56 type="file" name="test" />', ) class CLASS_10(DjangoTestCase): def FUNC_30(self): VAR_22 = models.Band.objects.create(name='Linkin Park') VAR_22.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) VAR_29 = models.Album._meta.get_field('band').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', VAR_22.pk, attrs={})), '<VAR_56 type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/VAR_22/?t=id" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Linkin Park</strong>' % dict(VAR_0(), bandpk=VAR_22.pk) ) def FUNC_36(self): VAR_30 = models.Inventory.objects.create(barcode=86, name='Apple') models.Inventory.objects.create(barcode=22, name='Pear') VAR_31 = models.Inventory.objects.create( barcode=87, name='Core', parent=VAR_30 ) VAR_29 = models.Inventory._meta.get_field('parent').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( VAR_27.render('test', VAR_31.parent_id, attrs={}), '<VAR_56 type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Apple</strong>' % VAR_0() ) def FUNC_37(self): VAR_32 = models.Honeycomb.objects.create(location='Old tree') VAR_32.bee_set.create() VAR_29 = models.Bee._meta.get_field('honeycomb').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('honeycomb_widget', VAR_32.pk, attrs={})), '<VAR_56 type="text" name="honeycomb_widget" value="%(hcombpk)s" />&nbsp;<strong>Honeycomb object</strong>' % {'hcombpk': VAR_32.pk} ) def FUNC_38(self): VAR_33 = models.Individual.objects.create(name='Subject #1') models.Individual.objects.create(name='Child', parent=VAR_33) VAR_29 = models.Individual._meta.get_field('parent').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('individual_widget', VAR_33.pk, attrs={})), '<VAR_56 type="text" name="individual_widget" value="%(subj1pk)s" />&nbsp;<strong>Individual object</strong>' % {'subj1pk': VAR_33.pk} ) def FUNC_39(self): VAR_29 = models.Inventory._meta.get_field('parent').rel VAR_27 = widgets.ForeignKeyRawIdWidget(VAR_29, widget_admin_site) VAR_34 = models.Inventory.objects.create( barcode=93, name='Hidden', VAR_34=True ) VAR_35 = models.Inventory.objects.create( barcode=94, name='Child of hidden', parent=VAR_34 ) self.assertHTMLEqual( VAR_27.render('test', VAR_35.parent_id, attrs={}), '<VAR_56 type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Hidden</strong>' % VAR_0() ) class CLASS_11(DjangoTestCase): def FUNC_30(self): VAR_22 = models.Band.objects.create(name='Linkin Park') VAR_36 = models.Member.objects.create(name='Chester') VAR_37 = models.Member.objects.create(name='Mike') VAR_22.members.add(VAR_36, VAR_37) VAR_29 = models.Band._meta.get_field('members').rel VAR_27 = widgets.ManyToManyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', [VAR_36.pk, VAR_37.pk], attrs={})), '<VAR_56 type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/VAR_44/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="/static/admin/img/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(VAR_0(), m1pk=VAR_36.pk, m2pk=VAR_37.pk) ) self.assertHTMLEqual( conditional_escape(VAR_27.render('test', [VAR_36.pk])), '<VAR_56 type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/VAR_44/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(VAR_0(), m1pk=VAR_36.pk) ) def FUNC_40(self): VAR_38 = models.Advisor.objects.create(name='Rockstar Techie') VAR_39 = models.Company.objects.create(name='Doodle') VAR_40 = models.Company.objects.create(name='Pear') VAR_38.companies.add(VAR_39, VAR_40) VAR_29 = models.Advisor._meta.get_field('companies').rel VAR_27 = widgets.ManyToManyRawIdWidget(VAR_29, widget_admin_site) self.assertHTMLEqual( conditional_escape(VAR_27.render('company_widget1', [VAR_39.pk, VAR_40.pk], attrs={})), '<VAR_56 type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s" />' % {'c1pk': VAR_39.pk, 'c2pk': VAR_40.pk} ) self.assertHTMLEqual( conditional_escape(VAR_27.render('company_widget2', [VAR_39.pk])), '<VAR_56 type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': VAR_39.pk} ) class CLASS_12(DjangoTestCase): def FUNC_41(self): VAR_29 = models.Individual._meta.get_field('parent').rel VAR_27 = widgets.AdminRadioSelect() VAR_27 = widgets.RelatedFieldWidgetWrapper(VAR_27, VAR_29, widget_admin_site) self.assertFalse(VAR_27.can_add_related) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_13(AdminSeleniumWebDriverTestCase): VAR_7 = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps VAR_5 = ['admin-widgets-users.xml'] VAR_8 = "admin_widgets.urls" VAR_9 = 'selenium.webdriver.firefox.webdriver.WebDriver' def FUNC_42(self): from selenium.webdriver.common.keys import Keys self.admin_login(username='super', password='secret', login_url='/') self.selenium.get('%s%s' % (self.live_server_url, '/admin_widgets/VAR_44/add/')) self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'none') self.selenium.find_element_by_id('calendarlink0').click() self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'block') self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) self.assertEqual( self.get_css_value('#calendarbox0', 'display'), 'none') self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'none') self.selenium.find_element_by_id('clocklink0').click() self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'block') self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) self.assertEqual( self.get_css_value('#clockbox0', 'display'), 'none') class CLASS_14(CLASS_13): VAR_9 = 'selenium.webdriver.chrome.webdriver.WebDriver' class CLASS_15(CLASS_13): VAR_9 = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(TIME_ZONE='Asia/Singapore') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_16(AdminSeleniumWebDriverTestCase): VAR_7 = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps VAR_5 = ['admin-widgets-users.xml'] VAR_8 = "admin_widgets.urls" VAR_9 = 'selenium.webdriver.firefox.webdriver.WebDriver' def FUNC_43(self): self.admin_login(username='super', password='secret', login_url='/') VAR_41 = datetime.now() VAR_42 = timedelta(seconds=10) self.selenium.get('%s%s' % (self.live_server_url, '/admin_widgets/VAR_44/add/')) self.selenium.find_element_by_id('id_name').send_keys('test') VAR_43 = self.selenium.find_elements_by_css_selector( '.field-birthdate .datetimeshortcuts') for shortcut in VAR_43: shortcut.find_element_by_tag_name('a').click() self.selenium.find_elements_by_css_selector( '.field-birthdate .timezonewarning') self.selenium.find_element_by_tag_name('form').submit() self.wait_page_loaded() VAR_44 = models.Member.objects.get(name='test') self.assertGreater(VAR_44.birthdate, VAR_41 - VAR_42) self.assertLess(VAR_44.birthdate, VAR_41 + VAR_42) class CLASS_17(CLASS_16): VAR_9 = 'selenium.webdriver.chrome.webdriver.WebDriver' class CLASS_18(CLASS_16): VAR_9 = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_19(AdminSeleniumWebDriverTestCase): VAR_7 = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps VAR_5 = ['admin-widgets-users.xml'] VAR_8 = "admin_widgets.urls" VAR_9 = 'selenium.webdriver.firefox.webdriver.WebDriver' def FUNC_23(self): self.lisa = models.Student.objects.create(name='Lisa') self.john = models.Student.objects.create(name='John') self.bob = models.Student.objects.create(name='Bob') self.peter = models.Student.objects.create(name='Peter') self.jenny = models.Student.objects.create(name='Jenny') self.jason = models.Student.objects.create(name='Jason') self.cliff = models.Student.objects.create(name='Cliff') self.arthur = models.Student.objects.create(name='Arthur') self.school = models.School.objects.create(name='School of Awesome') super(CLASS_19, self).setUp() def FUNC_44(self, VAR_10, VAR_11, VAR_12, VAR_13, VAR_14=None, VAR_15=None): VAR_45 = '#id_%s_add_link' % VAR_11 VAR_46 = '#id_%s_add_all_link' % VAR_11 VAR_47 = '#id_%s_remove_link' % VAR_11 VAR_48 = '#id_%s_remove_all_link' % VAR_11 self.assertEqual(self.has_css_class(VAR_45, 'active'), VAR_12) self.assertEqual(self.has_css_class(VAR_47, 'active'), VAR_13) if VAR_10 == 'horizontal': self.assertEqual(self.has_css_class(VAR_46, 'active'), VAR_14) self.assertEqual(self.has_css_class(VAR_48, 'active'), VAR_15) def FUNC_45(self, VAR_10, VAR_11): VAR_49 = '#id_%s_from' % VAR_11 VAR_50 = '#id_%s_to' % VAR_11 VAR_45 = 'id_%s_add_link' % VAR_11 VAR_46 = 'id_%s_add_all_link' % VAR_11 VAR_47 = 'id_%s_remove_link' % VAR_11 VAR_48 = 'id_%s_remove_all_link' % VAR_11 self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertSelectOptions(VAR_50, [str(self.lisa.id), str(self.peter.id)]) self.assertActiveButtons(VAR_10, VAR_11, False, False, True, True) if VAR_10 == 'horizontal': self.selenium.find_element_by_id(VAR_46).click() elif VAR_10 == 'vertical': for option in self.selenium.find_elements_by_css_selector(VAR_49 + ' > option'): option.click() self.selenium.find_element_by_id(VAR_45).click() self.assertSelectOptions(VAR_49, []) self.assertSelectOptions(VAR_50, [str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertActiveButtons(VAR_10, VAR_11, False, False, False, True) if VAR_10 == 'horizontal': self.selenium.find_element_by_id(VAR_48).click() elif VAR_10 == 'vertical': for option in self.selenium.find_elements_by_css_selector(VAR_50 + ' > option'): option.click() self.selenium.find_element_by_id(VAR_47).click() self.assertSelectOptions(VAR_49, [str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) self.assertSelectOptions(VAR_50, []) self.assertActiveButtons(VAR_10, VAR_11, False, False, True, False) self.get_select_option(VAR_49, str(self.lisa.id)).click() self.get_select_option(VAR_49, str(self.jason.id)).click() self.get_select_option(VAR_49, str(self.bob.id)).click() self.get_select_option(VAR_49, str(self.john.id)).click() self.assertActiveButtons(VAR_10, VAR_11, True, False, True, False) self.selenium.find_element_by_id(VAR_45).click() self.assertActiveButtons(VAR_10, VAR_11, False, False, True, True) self.assertSelectOptions(VAR_49, [str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id)]) self.assertSelectOptions(VAR_50, [str(self.lisa.id), str(self.bob.id), str(self.jason.id), str(self.john.id)]) self.get_select_option(VAR_50, str(self.lisa.id)).click() self.get_select_option(VAR_50, str(self.bob.id)).click() self.assertActiveButtons(VAR_10, VAR_11, False, True, True, True) self.selenium.find_element_by_id(VAR_47).click() self.assertActiveButtons(VAR_10, VAR_11, False, False, True, True) self.assertSelectOptions(VAR_49, [str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id)]) self.assertSelectOptions(VAR_50, [str(self.jason.id), str(self.john.id)]) self.get_select_option(VAR_49, str(self.arthur.id)).click() self.get_select_option(VAR_49, str(self.cliff.id)).click() self.selenium.find_element_by_id(VAR_45).click() self.assertSelectOptions(VAR_49, [str(self.peter.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id)]) self.assertSelectOptions(VAR_50, [str(self.jason.id), str(self.john.id), str(self.arthur.id), str(self.cliff.id)]) def FUNC_46(self): self.school.students = [self.lisa, self.peter] self.school.alumni = [self.lisa, self.peter] self.school.save() self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id)) self.wait_page_loaded() self.execute_basic_operations('vertical', 'students') self.execute_basic_operations('horizontal', 'alumni') self.selenium.find_element_by_xpath('//VAR_56[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john]) self.assertEqual(list(self.school.alumni.all()), [self.arthur, self.cliff, self.jason, self.john]) def FUNC_47(self): from selenium.webdriver.common.keys import Keys self.school.students = [self.lisa, self.peter] self.school.alumni = [self.lisa, self.peter] self.school.save() self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id)) for VAR_11 in ['students', 'alumni']: VAR_49 = '#id_%s_from' % VAR_11 VAR_50 = '#id_%s_to' % VAR_11 VAR_45 = '#id_%s_add_link' % VAR_11 VAR_47 = '#id_%s_remove_link' % VAR_11 VAR_56 = self.selenium.find_element_by_css_selector('#id_%s_input' % VAR_11) self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) VAR_56.send_keys('a') self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.jason.id)]) VAR_56.send_keys('R') self.assertSelectOptions(VAR_49, [str(self.arthur.id)]) VAR_56.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.jason.id)]) VAR_56.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id)]) VAR_56.send_keys('a') self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.jason.id)]) self.get_select_option(VAR_49, str(self.jason.id)).click() self.selenium.find_element_by_css_selector(VAR_45).click() self.assertSelectOptions(VAR_49, [str(self.arthur.id)]) self.assertSelectOptions(VAR_50, [str(self.lisa.id), str(self.peter.id), str(self.jason.id)]) self.get_select_option(VAR_50, str(self.lisa.id)).click() self.selenium.find_element_by_css_selector(VAR_47).click() self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.lisa.id)]) self.assertSelectOptions(VAR_50, [str(self.peter.id), str(self.jason.id)]) VAR_56.send_keys([Keys.BACK_SPACE]) # Clear text box self.assertSelectOptions(VAR_49, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jenny.id), str(self.john.id), str(self.lisa.id)]) self.assertSelectOptions(VAR_50, [str(self.peter.id), str(self.jason.id)]) self.selenium.find_element_by_xpath('//VAR_56[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) class CLASS_20(CLASS_19): VAR_9 = 'selenium.webdriver.chrome.webdriver.WebDriver' class CLASS_21(CLASS_19): VAR_9 = 'selenium.webdriver.ie.webdriver.WebDriver' @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class CLASS_22(AdminSeleniumWebDriverTestCase): VAR_7 = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps VAR_5 = ['admin-widgets-users.xml'] VAR_8 = "admin_widgets.urls" VAR_9 = 'selenium.webdriver.firefox.webdriver.WebDriver' def FUNC_23(self): models.Band.objects.create(id=42, name='Bogey Blues') models.Band.objects.create(id=98, name='Green Potatoes') super(CLASS_22, self).setUp() def FUNC_48(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/event/add/')) VAR_51 = self.selenium.current_window_handle self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '') self.selenium.find_element_by_id('lookup_id_main_band').click() self.selenium.switch_to_window('id_main_band') self.wait_page_loaded() VAR_52 = self.selenium.find_element_by_link_text('Bogey Blues') self.assertTrue('/VAR_22/42/' in VAR_52.get_attribute('href')) VAR_52.click() self.selenium.switch_to_window(VAR_51) self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '42') self.selenium.find_element_by_id('lookup_id_main_band').click() self.selenium.switch_to_window('id_main_band') self.wait_page_loaded() VAR_52 = self.selenium.find_element_by_link_text('Green Potatoes') self.assertTrue('/VAR_22/98/' in VAR_52.get_attribute('href')) VAR_52.click() self.selenium.switch_to_window(VAR_51) self.assertEqual( self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '98') def FUNC_49(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get( '%s%s' % (self.live_server_url, '/admin_widgets/event/add/')) VAR_51 = self.selenium.current_window_handle self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '') self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.selenium.switch_to_window('id_supporting_bands') self.wait_page_loaded() VAR_52 = self.selenium.find_element_by_link_text('Bogey Blues') self.assertTrue('/VAR_22/42/' in VAR_52.get_attribute('href')) VAR_52.click() self.selenium.switch_to_window(VAR_51) self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '42') self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.selenium.switch_to_window('id_supporting_bands') self.wait_page_loaded() VAR_52 = self.selenium.find_element_by_link_text('Green Potatoes') self.assertTrue('/VAR_22/98/' in VAR_52.get_attribute('href')) VAR_52.click() self.selenium.switch_to_window(VAR_51) self.assertEqual( self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '42,98') class CLASS_23(CLASS_22): VAR_9 = 'selenium.webdriver.chrome.webdriver.WebDriver' class CLASS_24(CLASS_22): VAR_9 = 'selenium.webdriver.ie.webdriver.WebDriver'
[ 1, 3, 6, 20, 23, 24, 28, 33, 39, 44, 45, 48, 49, 54, 55, 61, 62, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 98, 103, 106, 110, 114, 118, 135, 138, 142, 145, 150, 156, 157, 161, 170, 171, 176, 179, 182, 186, 187, 192, 195, 198, 206, 207, 212, 214, 216, 219, 222, 228, 235, 236, 244, 251, 263, 269, 281, 287, 295, 298, 306, 307, 319, 326, 337, 338, 345, 351, 356, 357, 365, 371, 373, 374, 386, 388, 389, 393, 399, 401, 402, 406, 412, 414, 417, 428, 429, 433, 438, 444, 449, 451, 452, 454, 459, 465, 470, 475, 478, 479, 480, 483, 488, 496, 498, 501, 502, 503, 506, 508, 511, 513, 516, 517, 518, 521, 523, 526, 528, 531, 534, 537, 538, 546, 551, 557, 560, 563, 565, 566, 569, 572, 573, 574, 575, 576, 579, 580, 583, 584, 585, 589, 592, 595, 596, 599, 604, 616, 628, 636, 637, 645, 646, 650, 651, 662, 663, 667, 668, 679, 680, 688, 695, 696, 702, 709, 710, 714, 721, 726, 730, 734, 735, 743, 750, 754, 758, 759, 766, 767, 772, 773, 778, 779, 787, 788, 789, 790, 799, 806, 814, 815, 823, 826, 829, 830, 837, 842, 848, 849, 853, 854, 861, 862, 867, 868, 875, 876, 881, 887, 888, 892, 893, 900, 901, 906, 907, 914, 915, 920, 923, 926, 30, 31, 32, 35, 36, 37, 38, 120, 121, 122, 123, 147, 163, 164, 165, 254, 255, 256, 257, 272, 273, 274, 275, 490, 491, 492, 493, 494, 548, 549, 550, 551, 552, 553, 554, 555, 745, 746, 747, 748 ]
[ 1, 3, 6, 20, 23, 24, 28, 33, 39, 44, 45, 48, 49, 54, 55, 61, 62, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 98, 103, 106, 110, 114, 118, 135, 138, 142, 145, 150, 156, 157, 161, 170, 171, 176, 179, 182, 186, 187, 192, 195, 198, 206, 207, 212, 214, 216, 219, 222, 228, 235, 236, 244, 251, 263, 269, 281, 287, 295, 298, 306, 307, 319, 326, 328, 329, 343, 344, 351, 357, 362, 363, 371, 377, 379, 380, 392, 394, 395, 399, 405, 407, 408, 412, 418, 420, 423, 434, 435, 439, 444, 450, 455, 457, 458, 460, 465, 471, 476, 481, 484, 485, 486, 489, 494, 502, 504, 507, 508, 509, 512, 514, 517, 519, 522, 523, 524, 527, 529, 532, 534, 537, 540, 543, 544, 552, 557, 563, 566, 569, 571, 572, 575, 578, 579, 580, 581, 582, 585, 586, 589, 590, 591, 595, 598, 601, 602, 605, 610, 622, 634, 642, 643, 651, 652, 656, 657, 668, 669, 673, 674, 685, 686, 694, 701, 702, 708, 715, 716, 720, 727, 732, 736, 740, 741, 749, 756, 760, 764, 765, 772, 773, 778, 779, 784, 785, 793, 794, 795, 796, 805, 812, 820, 821, 829, 832, 835, 836, 843, 848, 854, 855, 859, 860, 867, 868, 873, 874, 881, 882, 887, 893, 894, 898, 899, 906, 907, 912, 913, 920, 921, 926, 929, 932, 30, 31, 32, 35, 36, 37, 38, 120, 121, 122, 123, 147, 163, 164, 165, 254, 255, 256, 257, 272, 273, 274, 275, 496, 497, 498, 499, 500, 554, 555, 556, 557, 558, 559, 560, 561, 751, 752, 753, 754 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock from canonicaljson import json from twisted.internet import defer from synapse.api.constants import EventTypes, Membership from synapse.api.room_versions import RoomVersions from synapse.types import RoomID, UserID from tests import unittest from tests.utils import create_room class RedactionTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): config = self.default_config() config["redaction_retention_period"] = "30d" return self.setup_test_homeserver( resource_for_federation=Mock(), http_client=None, config=config ) def prepare(self, reactor, clock, hs): self.store = hs.get_datastore() self.storage = hs.get_storage() self.event_builder_factory = hs.get_event_builder_factory() self.event_creation_handler = hs.get_event_creation_handler() self.u_alice = UserID.from_string("@alice:test") self.u_bob = UserID.from_string("@bob:test") self.room1 = RoomID.from_string("!abc123:test") self.get_success( create_room(hs, self.room1.to_string(), self.u_alice.to_string()) ) self.depth = 1 def inject_room_member( self, room, user, membership, replaces_state=None, extra_content={} ): content = {"membership": membership} content.update(extra_content) builder = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Member, "sender": user.to_string(), "state_key": user.to_string(), "room_id": room.to_string(), "content": content, }, ) event, context = self.get_success( self.event_creation_handler.create_new_client_event(builder) ) self.get_success(self.storage.persistence.persist_event(event, context)) return event def inject_message(self, room, user, body): self.depth += 1 builder = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Message, "sender": user.to_string(), "state_key": user.to_string(), "room_id": room.to_string(), "content": {"body": body, "msgtype": "message"}, }, ) event, context = self.get_success( self.event_creation_handler.create_new_client_event(builder) ) self.get_success(self.storage.persistence.persist_event(event, context)) return event def inject_redaction(self, room, event_id, user, reason): builder = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": user.to_string(), "state_key": user.to_string(), "room_id": room.to_string(), "content": {"reason": reason}, "redacts": event_id, }, ) event, context = self.get_success( self.event_creation_handler.create_new_client_event(builder) ) self.get_success(self.storage.persistence.persist_event(event, context)) return event def test_redact(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) msg_event = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) # Check event has not been redacted: event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {"body": "t", "msgtype": "message"}, }, event, ) self.assertFalse("redacted_because" in event.unsigned) # Redact event reason = "Because I said so" self.get_success( self.inject_redaction(self.room1, msg_event.event_id, self.u_alice, reason) ) event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertEqual(msg_event.event_id, event.event_id) self.assertTrue("redacted_because" in event.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {}, }, event, ) self.assertObjectHasAttributes( { "type": EventTypes.Redaction, "user_id": self.u_alice.to_string(), "content": {"reason": reason}, }, event.unsigned["redacted_because"], ) def test_redact_join(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) msg_event = self.get_success( self.inject_room_member( self.room1, self.u_bob, Membership.JOIN, extra_content={"blue": "red"} ) ) event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Member, "user_id": self.u_bob.to_string(), "content": {"membership": Membership.JOIN, "blue": "red"}, }, event, ) self.assertFalse(hasattr(event, "redacted_because")) # Redact event reason = "Because I said so" self.get_success( self.inject_redaction(self.room1, msg_event.event_id, self.u_alice, reason) ) # Check redaction event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertTrue("redacted_because" in event.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Member, "user_id": self.u_bob.to_string(), "content": {"membership": Membership.JOIN}, }, event, ) self.assertObjectHasAttributes( { "type": EventTypes.Redaction, "user_id": self.u_alice.to_string(), "content": {"reason": reason}, }, event.unsigned["redacted_because"], ) def test_circular_redaction(self): redaction_event_id1 = "$redaction1_id:test" redaction_event_id2 = "$redaction2_id:test" class EventIdManglingBuilder: def __init__(self, base_builder, event_id): self._base_builder = base_builder self._event_id = event_id @defer.inlineCallbacks def build(self, prev_event_ids, auth_event_ids): built_event = yield defer.ensureDeferred( self._base_builder.build(prev_event_ids, auth_event_ids) ) built_event._event_id = self._event_id built_event._dict["event_id"] = self._event_id assert built_event.event_id == self._event_id return built_event @property def room_id(self): return self._base_builder.room_id @property def type(self): return self._base_builder.type event_1, context_1 = self.get_success( self.event_creation_handler.create_new_client_event( EventIdManglingBuilder( self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "test"}, "redacts": redaction_event_id2, }, ), redaction_event_id1, ) ) ) self.get_success(self.storage.persistence.persist_event(event_1, context_1)) event_2, context_2 = self.get_success( self.event_creation_handler.create_new_client_event( EventIdManglingBuilder( self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "test"}, "redacts": redaction_event_id1, }, ), redaction_event_id2, ) ) ) self.get_success(self.storage.persistence.persist_event(event_2, context_2)) # fetch one of the redactions fetched = self.get_success(self.store.get_event(redaction_event_id1)) # it should have been redacted self.assertEqual(fetched.unsigned["redacted_by"], redaction_event_id2) self.assertEqual( fetched.unsigned["redacted_because"].event_id, redaction_event_id2 ) def test_redact_censor(self): """Test that a redacted event gets censored in the DB after a month """ self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) msg_event = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) # Check event has not been redacted: event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {"body": "t", "msgtype": "message"}, }, event, ) self.assertFalse("redacted_because" in event.unsigned) # Redact event reason = "Because I said so" self.get_success( self.inject_redaction(self.room1, msg_event.event_id, self.u_alice, reason) ) event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertTrue("redacted_because" in event.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {}, }, event, ) event_json = self.get_success( self.store.db_pool.simple_select_one_onecol( table="event_json", keyvalues={"event_id": msg_event.event_id}, retcol="json", ) ) self.assert_dict( {"content": {"body": "t", "msgtype": "message"}}, json.loads(event_json) ) # Advance by 30 days, then advance again to ensure that the looping call # for updating the stream position gets called and then the looping call # for the censoring gets called. self.reactor.advance(60 * 60 * 24 * 31) self.reactor.advance(60 * 60 * 2) event_json = self.get_success( self.store.db_pool.simple_select_one_onecol( table="event_json", keyvalues={"event_id": msg_event.event_id}, retcol="json", ) ) self.assert_dict({"content": {}}, json.loads(event_json)) def test_redact_redaction(self): """Tests that we can redact a redaction and can fetch it again. """ self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) msg_event = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) first_redact_event = self.get_success( self.inject_redaction( self.room1, msg_event.event_id, self.u_alice, "Redacting message" ) ) self.get_success( self.inject_redaction( self.room1, first_redact_event.event_id, self.u_alice, "Redacting redaction", ) ) # Now lets jump to the future where we have censored the redaction event # in the DB. self.reactor.advance(60 * 60 * 24 * 31) # We just want to check that fetching the event doesn't raise an exception. self.get_success( self.store.get_event(first_redact_event.event_id, allow_none=True) ) def test_store_redacted_redaction(self): """Tests that we can store a redacted redaction. """ self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) builder = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "foo"}, }, ) redaction_event, context = self.get_success( self.event_creation_handler.create_new_client_event(builder) ) self.get_success( self.storage.persistence.persist_event(redaction_event, context) ) # Now lets jump to the future where we have censored the redaction event # in the DB. self.reactor.advance(60 * 60 * 24 * 31) # We just want to check that fetching the event doesn't raise an exception. self.get_success( self.store.get_event(redaction_event.event_id, allow_none=True) )
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock from canonicaljson import json from twisted.internet import defer from synapse.api.constants import EventTypes, Membership from synapse.api.room_versions import RoomVersions from synapse.types import RoomID, UserID from tests import unittest from tests.utils import create_room class RedactionTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): config = self.default_config() config["redaction_retention_period"] = "30d" return self.setup_test_homeserver( resource_for_federation=Mock(), federation_http_client=None, config=config ) def prepare(self, reactor, clock, hs): self.store = hs.get_datastore() self.storage = hs.get_storage() self.event_builder_factory = hs.get_event_builder_factory() self.event_creation_handler = hs.get_event_creation_handler() self.u_alice = UserID.from_string("@alice:test") self.u_bob = UserID.from_string("@bob:test") self.room1 = RoomID.from_string("!abc123:test") self.get_success( create_room(hs, self.room1.to_string(), self.u_alice.to_string()) ) self.depth = 1 def inject_room_member( self, room, user, membership, replaces_state=None, extra_content={} ): content = {"membership": membership} content.update(extra_content) builder = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Member, "sender": user.to_string(), "state_key": user.to_string(), "room_id": room.to_string(), "content": content, }, ) event, context = self.get_success( self.event_creation_handler.create_new_client_event(builder) ) self.get_success(self.storage.persistence.persist_event(event, context)) return event def inject_message(self, room, user, body): self.depth += 1 builder = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Message, "sender": user.to_string(), "state_key": user.to_string(), "room_id": room.to_string(), "content": {"body": body, "msgtype": "message"}, }, ) event, context = self.get_success( self.event_creation_handler.create_new_client_event(builder) ) self.get_success(self.storage.persistence.persist_event(event, context)) return event def inject_redaction(self, room, event_id, user, reason): builder = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": user.to_string(), "state_key": user.to_string(), "room_id": room.to_string(), "content": {"reason": reason}, "redacts": event_id, }, ) event, context = self.get_success( self.event_creation_handler.create_new_client_event(builder) ) self.get_success(self.storage.persistence.persist_event(event, context)) return event def test_redact(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) msg_event = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) # Check event has not been redacted: event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {"body": "t", "msgtype": "message"}, }, event, ) self.assertFalse("redacted_because" in event.unsigned) # Redact event reason = "Because I said so" self.get_success( self.inject_redaction(self.room1, msg_event.event_id, self.u_alice, reason) ) event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertEqual(msg_event.event_id, event.event_id) self.assertTrue("redacted_because" in event.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {}, }, event, ) self.assertObjectHasAttributes( { "type": EventTypes.Redaction, "user_id": self.u_alice.to_string(), "content": {"reason": reason}, }, event.unsigned["redacted_because"], ) def test_redact_join(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) msg_event = self.get_success( self.inject_room_member( self.room1, self.u_bob, Membership.JOIN, extra_content={"blue": "red"} ) ) event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Member, "user_id": self.u_bob.to_string(), "content": {"membership": Membership.JOIN, "blue": "red"}, }, event, ) self.assertFalse(hasattr(event, "redacted_because")) # Redact event reason = "Because I said so" self.get_success( self.inject_redaction(self.room1, msg_event.event_id, self.u_alice, reason) ) # Check redaction event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertTrue("redacted_because" in event.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Member, "user_id": self.u_bob.to_string(), "content": {"membership": Membership.JOIN}, }, event, ) self.assertObjectHasAttributes( { "type": EventTypes.Redaction, "user_id": self.u_alice.to_string(), "content": {"reason": reason}, }, event.unsigned["redacted_because"], ) def test_circular_redaction(self): redaction_event_id1 = "$redaction1_id:test" redaction_event_id2 = "$redaction2_id:test" class EventIdManglingBuilder: def __init__(self, base_builder, event_id): self._base_builder = base_builder self._event_id = event_id @defer.inlineCallbacks def build(self, prev_event_ids, auth_event_ids): built_event = yield defer.ensureDeferred( self._base_builder.build(prev_event_ids, auth_event_ids) ) built_event._event_id = self._event_id built_event._dict["event_id"] = self._event_id assert built_event.event_id == self._event_id return built_event @property def room_id(self): return self._base_builder.room_id @property def type(self): return self._base_builder.type event_1, context_1 = self.get_success( self.event_creation_handler.create_new_client_event( EventIdManglingBuilder( self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "test"}, "redacts": redaction_event_id2, }, ), redaction_event_id1, ) ) ) self.get_success(self.storage.persistence.persist_event(event_1, context_1)) event_2, context_2 = self.get_success( self.event_creation_handler.create_new_client_event( EventIdManglingBuilder( self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "test"}, "redacts": redaction_event_id1, }, ), redaction_event_id2, ) ) ) self.get_success(self.storage.persistence.persist_event(event_2, context_2)) # fetch one of the redactions fetched = self.get_success(self.store.get_event(redaction_event_id1)) # it should have been redacted self.assertEqual(fetched.unsigned["redacted_by"], redaction_event_id2) self.assertEqual( fetched.unsigned["redacted_because"].event_id, redaction_event_id2 ) def test_redact_censor(self): """Test that a redacted event gets censored in the DB after a month """ self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) msg_event = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) # Check event has not been redacted: event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {"body": "t", "msgtype": "message"}, }, event, ) self.assertFalse("redacted_because" in event.unsigned) # Redact event reason = "Because I said so" self.get_success( self.inject_redaction(self.room1, msg_event.event_id, self.u_alice, reason) ) event = self.get_success(self.store.get_event(msg_event.event_id)) self.assertTrue("redacted_because" in event.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {}, }, event, ) event_json = self.get_success( self.store.db_pool.simple_select_one_onecol( table="event_json", keyvalues={"event_id": msg_event.event_id}, retcol="json", ) ) self.assert_dict( {"content": {"body": "t", "msgtype": "message"}}, json.loads(event_json) ) # Advance by 30 days, then advance again to ensure that the looping call # for updating the stream position gets called and then the looping call # for the censoring gets called. self.reactor.advance(60 * 60 * 24 * 31) self.reactor.advance(60 * 60 * 2) event_json = self.get_success( self.store.db_pool.simple_select_one_onecol( table="event_json", keyvalues={"event_id": msg_event.event_id}, retcol="json", ) ) self.assert_dict({"content": {}}, json.loads(event_json)) def test_redact_redaction(self): """Tests that we can redact a redaction and can fetch it again. """ self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) msg_event = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) first_redact_event = self.get_success( self.inject_redaction( self.room1, msg_event.event_id, self.u_alice, "Redacting message" ) ) self.get_success( self.inject_redaction( self.room1, first_redact_event.event_id, self.u_alice, "Redacting redaction", ) ) # Now lets jump to the future where we have censored the redaction event # in the DB. self.reactor.advance(60 * 60 * 24 * 31) # We just want to check that fetching the event doesn't raise an exception. self.get_success( self.store.get_event(first_redact_event.event_id, allow_none=True) ) def test_store_redacted_redaction(self): """Tests that we can store a redacted redaction. """ self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) builder = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "foo"}, }, ) redaction_event, context = self.get_success( self.event_creation_handler.create_new_client_event(builder) ) self.get_success( self.storage.persistence.persist_event(redaction_event, context) ) # Now lets jump to the future where we have censored the redaction event # in the DB. self.reactor.advance(60 * 60 * 24 * 31) # We just want to check that fetching the event doesn't raise an exception. self.get_success( self.store.get_event(redaction_event.event_id, allow_none=True) )
open_redirect
{ "code": [ " resource_for_federation=Mock(), http_client=None, config=config" ], "line_no": [ 37 ] }
{ "code": [ " resource_for_federation=Mock(), federation_http_client=None, config=config" ], "line_no": [ 37 ] }
from mock import Mock from canonicaljson import json from twisted.internet import defer from synapse.api.constants import EventTypes, Membership from synapse.api.room_versions import RoomVersions from synapse.types import RoomID, UserID from tests import unittest from tests.utils import create_room class CLASS_0(unittest.HomeserverTestCase): def FUNC_0(self, VAR_0, VAR_1): VAR_11 = self.default_config() VAR_11["redaction_retention_period"] = "30d" return self.setup_test_homeserver( resource_for_federation=Mock(), http_client=None, VAR_11=config ) def FUNC_1(self, VAR_0, VAR_1, VAR_2): self.store = VAR_2.get_datastore() self.storage = VAR_2.get_storage() self.event_builder_factory = VAR_2.get_event_builder_factory() self.event_creation_handler = VAR_2.get_event_creation_handler() self.u_alice = UserID.from_string("@alice:test") self.u_bob = UserID.from_string("@bob:test") self.room1 = RoomID.from_string("!abc123:test") self.get_success( create_room(VAR_2, self.room1.to_string(), self.u_alice.to_string()) ) self.depth = 1 def FUNC_2( self, VAR_3, VAR_4, VAR_5, VAR_6=None, VAR_7={} ): VAR_12 = {"membership": VAR_5} VAR_12.update(VAR_7) VAR_13 = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Member, "sender": VAR_4.to_string(), "state_key": VAR_4.to_string(), "room_id": VAR_3.to_string(), "content": VAR_12, }, ) VAR_14, VAR_15 = self.get_success( self.event_creation_handler.create_new_client_event(VAR_13) ) self.get_success(self.storage.persistence.persist_event(VAR_14, VAR_15)) return VAR_14 def FUNC_3(self, VAR_3, VAR_4, VAR_8): self.depth += 1 VAR_13 = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Message, "sender": VAR_4.to_string(), "state_key": VAR_4.to_string(), "room_id": VAR_3.to_string(), "content": {"body": VAR_8, "msgtype": "message"}, }, ) VAR_14, VAR_15 = self.get_success( self.event_creation_handler.create_new_client_event(VAR_13) ) self.get_success(self.storage.persistence.persist_event(VAR_14, VAR_15)) return VAR_14 def FUNC_4(self, VAR_3, VAR_9, VAR_4, VAR_10): VAR_13 = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": VAR_4.to_string(), "state_key": VAR_4.to_string(), "room_id": VAR_3.to_string(), "content": {"reason": VAR_10}, "redacts": VAR_9, }, ) VAR_14, VAR_15 = self.get_success( self.event_creation_handler.create_new_client_event(VAR_13) ) self.get_success(self.storage.persistence.persist_event(VAR_14, VAR_15)) return VAR_14 def FUNC_5(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_16 = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {"body": "t", "msgtype": "message"}, }, VAR_14, ) self.assertFalse("redacted_because" in VAR_14.unsigned) VAR_10 = "Because I said so" self.get_success( self.inject_redaction(self.room1, VAR_16.event_id, self.u_alice, VAR_10) ) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertEqual(VAR_16.event_id, VAR_14.event_id) self.assertTrue("redacted_because" in VAR_14.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {}, }, VAR_14, ) self.assertObjectHasAttributes( { "type": EventTypes.Redaction, "user_id": self.u_alice.to_string(), "content": {"reason": VAR_10}, }, VAR_14.unsigned["redacted_because"], ) def FUNC_6(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_16 = self.get_success( self.inject_room_member( self.room1, self.u_bob, Membership.JOIN, VAR_7={"blue": "red"} ) ) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Member, "user_id": self.u_bob.to_string(), "content": {"membership": Membership.JOIN, "blue": "red"}, }, VAR_14, ) self.assertFalse(hasattr(VAR_14, "redacted_because")) VAR_10 = "Because I said so" self.get_success( self.inject_redaction(self.room1, VAR_16.event_id, self.u_alice, VAR_10) ) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertTrue("redacted_because" in VAR_14.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Member, "user_id": self.u_bob.to_string(), "content": {"membership": Membership.JOIN}, }, VAR_14, ) self.assertObjectHasAttributes( { "type": EventTypes.Redaction, "user_id": self.u_alice.to_string(), "content": {"reason": VAR_10}, }, VAR_14.unsigned["redacted_because"], ) def FUNC_7(self): VAR_17 = "$redaction1_id:test" VAR_18 = "$redaction2_id:test" class CLASS_1: def __init__(self, VAR_27, VAR_9): self._base_builder = VAR_27 self._event_id = VAR_9 @defer.inlineCallbacks def FUNC_11(self, VAR_28, VAR_29): VAR_30 = yield defer.ensureDeferred( self._base_builder.build(VAR_28, VAR_29) ) VAR_30._event_id = self._event_id VAR_30._dict["event_id"] = self._event_id assert VAR_30.event_id == self._event_id return VAR_30 @property def FUNC_12(self): return self._base_builder.room_id @property def FUNC_13(self): return self._base_builder.type VAR_19, VAR_20 = self.get_success( self.event_creation_handler.create_new_client_event( CLASS_1( self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "test"}, "redacts": VAR_18, }, ), VAR_17, ) ) ) self.get_success(self.storage.persistence.persist_event(VAR_19, VAR_20)) VAR_21, VAR_22 = self.get_success( self.event_creation_handler.create_new_client_event( CLASS_1( self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "test"}, "redacts": VAR_17, }, ), VAR_18, ) ) ) self.get_success(self.storage.persistence.persist_event(VAR_21, VAR_22)) VAR_23 = self.get_success(self.store.get_event(VAR_17)) self.assertEqual(VAR_23.unsigned["redacted_by"], VAR_18) self.assertEqual( VAR_23.unsigned["redacted_because"].event_id, VAR_18 ) def FUNC_8(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_16 = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {"body": "t", "msgtype": "message"}, }, VAR_14, ) self.assertFalse("redacted_because" in VAR_14.unsigned) VAR_10 = "Because I said so" self.get_success( self.inject_redaction(self.room1, VAR_16.event_id, self.u_alice, VAR_10) ) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertTrue("redacted_because" in VAR_14.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {}, }, VAR_14, ) VAR_24 = self.get_success( self.store.db_pool.simple_select_one_onecol( table="event_json", keyvalues={"event_id": VAR_16.event_id}, retcol="json", ) ) self.assert_dict( {"content": {"body": "t", "msgtype": "message"}}, json.loads(VAR_24) ) self.reactor.advance(60 * 60 * 24 * 31) self.reactor.advance(60 * 60 * 2) VAR_24 = self.get_success( self.store.db_pool.simple_select_one_onecol( table="event_json", keyvalues={"event_id": VAR_16.event_id}, retcol="json", ) ) self.assert_dict({"content": {}}, json.loads(VAR_24)) def FUNC_9(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_16 = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) VAR_25 = self.get_success( self.inject_redaction( self.room1, VAR_16.event_id, self.u_alice, "Redacting message" ) ) self.get_success( self.inject_redaction( self.room1, VAR_25.event_id, self.u_alice, "Redacting redaction", ) ) self.reactor.advance(60 * 60 * 24 * 31) self.get_success( self.store.get_event(VAR_25.event_id, allow_none=True) ) def FUNC_10(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_13 = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "foo"}, }, ) VAR_26, VAR_15 = self.get_success( self.event_creation_handler.create_new_client_event(VAR_13) ) self.get_success( self.storage.persistence.persist_event(VAR_26, VAR_15) ) self.reactor.advance(60 * 60 * 24 * 31) self.get_success( self.store.get_event(VAR_26.event_id, allow_none=True) )
from mock import Mock from canonicaljson import json from twisted.internet import defer from synapse.api.constants import EventTypes, Membership from synapse.api.room_versions import RoomVersions from synapse.types import RoomID, UserID from tests import unittest from tests.utils import create_room class CLASS_0(unittest.HomeserverTestCase): def FUNC_0(self, VAR_0, VAR_1): VAR_11 = self.default_config() VAR_11["redaction_retention_period"] = "30d" return self.setup_test_homeserver( resource_for_federation=Mock(), federation_http_client=None, VAR_11=config ) def FUNC_1(self, VAR_0, VAR_1, VAR_2): self.store = VAR_2.get_datastore() self.storage = VAR_2.get_storage() self.event_builder_factory = VAR_2.get_event_builder_factory() self.event_creation_handler = VAR_2.get_event_creation_handler() self.u_alice = UserID.from_string("@alice:test") self.u_bob = UserID.from_string("@bob:test") self.room1 = RoomID.from_string("!abc123:test") self.get_success( create_room(VAR_2, self.room1.to_string(), self.u_alice.to_string()) ) self.depth = 1 def FUNC_2( self, VAR_3, VAR_4, VAR_5, VAR_6=None, VAR_7={} ): VAR_12 = {"membership": VAR_5} VAR_12.update(VAR_7) VAR_13 = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Member, "sender": VAR_4.to_string(), "state_key": VAR_4.to_string(), "room_id": VAR_3.to_string(), "content": VAR_12, }, ) VAR_14, VAR_15 = self.get_success( self.event_creation_handler.create_new_client_event(VAR_13) ) self.get_success(self.storage.persistence.persist_event(VAR_14, VAR_15)) return VAR_14 def FUNC_3(self, VAR_3, VAR_4, VAR_8): self.depth += 1 VAR_13 = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Message, "sender": VAR_4.to_string(), "state_key": VAR_4.to_string(), "room_id": VAR_3.to_string(), "content": {"body": VAR_8, "msgtype": "message"}, }, ) VAR_14, VAR_15 = self.get_success( self.event_creation_handler.create_new_client_event(VAR_13) ) self.get_success(self.storage.persistence.persist_event(VAR_14, VAR_15)) return VAR_14 def FUNC_4(self, VAR_3, VAR_9, VAR_4, VAR_10): VAR_13 = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": VAR_4.to_string(), "state_key": VAR_4.to_string(), "room_id": VAR_3.to_string(), "content": {"reason": VAR_10}, "redacts": VAR_9, }, ) VAR_14, VAR_15 = self.get_success( self.event_creation_handler.create_new_client_event(VAR_13) ) self.get_success(self.storage.persistence.persist_event(VAR_14, VAR_15)) return VAR_14 def FUNC_5(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_16 = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {"body": "t", "msgtype": "message"}, }, VAR_14, ) self.assertFalse("redacted_because" in VAR_14.unsigned) VAR_10 = "Because I said so" self.get_success( self.inject_redaction(self.room1, VAR_16.event_id, self.u_alice, VAR_10) ) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertEqual(VAR_16.event_id, VAR_14.event_id) self.assertTrue("redacted_because" in VAR_14.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {}, }, VAR_14, ) self.assertObjectHasAttributes( { "type": EventTypes.Redaction, "user_id": self.u_alice.to_string(), "content": {"reason": VAR_10}, }, VAR_14.unsigned["redacted_because"], ) def FUNC_6(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_16 = self.get_success( self.inject_room_member( self.room1, self.u_bob, Membership.JOIN, VAR_7={"blue": "red"} ) ) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Member, "user_id": self.u_bob.to_string(), "content": {"membership": Membership.JOIN, "blue": "red"}, }, VAR_14, ) self.assertFalse(hasattr(VAR_14, "redacted_because")) VAR_10 = "Because I said so" self.get_success( self.inject_redaction(self.room1, VAR_16.event_id, self.u_alice, VAR_10) ) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertTrue("redacted_because" in VAR_14.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Member, "user_id": self.u_bob.to_string(), "content": {"membership": Membership.JOIN}, }, VAR_14, ) self.assertObjectHasAttributes( { "type": EventTypes.Redaction, "user_id": self.u_alice.to_string(), "content": {"reason": VAR_10}, }, VAR_14.unsigned["redacted_because"], ) def FUNC_7(self): VAR_17 = "$redaction1_id:test" VAR_18 = "$redaction2_id:test" class CLASS_1: def __init__(self, VAR_27, VAR_9): self._base_builder = VAR_27 self._event_id = VAR_9 @defer.inlineCallbacks def FUNC_11(self, VAR_28, VAR_29): VAR_30 = yield defer.ensureDeferred( self._base_builder.build(VAR_28, VAR_29) ) VAR_30._event_id = self._event_id VAR_30._dict["event_id"] = self._event_id assert VAR_30.event_id == self._event_id return VAR_30 @property def FUNC_12(self): return self._base_builder.room_id @property def FUNC_13(self): return self._base_builder.type VAR_19, VAR_20 = self.get_success( self.event_creation_handler.create_new_client_event( CLASS_1( self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "test"}, "redacts": VAR_18, }, ), VAR_17, ) ) ) self.get_success(self.storage.persistence.persist_event(VAR_19, VAR_20)) VAR_21, VAR_22 = self.get_success( self.event_creation_handler.create_new_client_event( CLASS_1( self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "test"}, "redacts": VAR_17, }, ), VAR_18, ) ) ) self.get_success(self.storage.persistence.persist_event(VAR_21, VAR_22)) VAR_23 = self.get_success(self.store.get_event(VAR_17)) self.assertEqual(VAR_23.unsigned["redacted_by"], VAR_18) self.assertEqual( VAR_23.unsigned["redacted_because"].event_id, VAR_18 ) def FUNC_8(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_16 = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {"body": "t", "msgtype": "message"}, }, VAR_14, ) self.assertFalse("redacted_because" in VAR_14.unsigned) VAR_10 = "Because I said so" self.get_success( self.inject_redaction(self.room1, VAR_16.event_id, self.u_alice, VAR_10) ) VAR_14 = self.get_success(self.store.get_event(VAR_16.event_id)) self.assertTrue("redacted_because" in VAR_14.unsigned) self.assertObjectHasAttributes( { "type": EventTypes.Message, "user_id": self.u_alice.to_string(), "content": {}, }, VAR_14, ) VAR_24 = self.get_success( self.store.db_pool.simple_select_one_onecol( table="event_json", keyvalues={"event_id": VAR_16.event_id}, retcol="json", ) ) self.assert_dict( {"content": {"body": "t", "msgtype": "message"}}, json.loads(VAR_24) ) self.reactor.advance(60 * 60 * 24 * 31) self.reactor.advance(60 * 60 * 2) VAR_24 = self.get_success( self.store.db_pool.simple_select_one_onecol( table="event_json", keyvalues={"event_id": VAR_16.event_id}, retcol="json", ) ) self.assert_dict({"content": {}}, json.loads(VAR_24)) def FUNC_9(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_16 = self.get_success(self.inject_message(self.room1, self.u_alice, "t")) VAR_25 = self.get_success( self.inject_redaction( self.room1, VAR_16.event_id, self.u_alice, "Redacting message" ) ) self.get_success( self.inject_redaction( self.room1, VAR_25.event_id, self.u_alice, "Redacting redaction", ) ) self.reactor.advance(60 * 60 * 24 * 31) self.get_success( self.store.get_event(VAR_25.event_id, allow_none=True) ) def FUNC_10(self): self.get_success( self.inject_room_member(self.room1, self.u_alice, Membership.JOIN) ) VAR_13 = self.event_builder_factory.for_room_version( RoomVersions.V1, { "type": EventTypes.Redaction, "sender": self.u_alice.to_string(), "room_id": self.room1.to_string(), "content": {"reason": "foo"}, }, ) VAR_26, VAR_15 = self.get_success( self.event_creation_handler.create_new_client_event(VAR_13) ) self.get_success( self.storage.persistence.persist_event(VAR_26, VAR_15) ) self.reactor.advance(60 * 60 * 24 * 31) self.get_success( self.store.get_event(VAR_26.event_id, allow_none=True) )
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 21, 23, 27, 30, 31, 39, 45, 48, 50, 54, 56, 72, 76, 78, 80, 83, 94, 98, 100, 102, 115, 119, 121, 123, 128, 130, 131, 133, 142, 144, 145, 150, 152, 154, 156, 165, 174, 179, 185, 187, 196, 198, 199, 204, 205, 206, 208, 210, 219, 228, 232, 237, 243, 247, 249, 253, 257, 275, 277, 296, 297, 299, 300, 305, 309, 313, 315, 316, 318, 327, 329, 330, 335, 337, 339, 348, 356, 360, 361, 362, 363, 366, 374, 376, 380, 384, 386, 392, 401, 402, 403, 405, 406, 410, 414, 418, 428, 432, 436, 437, 438, 440, 441, 445, 307, 308, 378, 379, 412, 413 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 21, 23, 27, 30, 31, 39, 45, 48, 50, 54, 56, 72, 76, 78, 80, 83, 94, 98, 100, 102, 115, 119, 121, 123, 128, 130, 131, 133, 142, 144, 145, 150, 152, 154, 156, 165, 174, 179, 185, 187, 196, 198, 199, 204, 205, 206, 208, 210, 219, 228, 232, 237, 243, 247, 249, 253, 257, 275, 277, 296, 297, 299, 300, 305, 309, 313, 315, 316, 318, 327, 329, 330, 335, 337, 339, 348, 356, 360, 361, 362, 363, 366, 374, 376, 380, 384, 386, 392, 401, 402, 403, 405, 406, 410, 414, 418, 428, 432, 436, 437, 438, 440, 441, 445, 307, 308, 378, 379, 412, 413 ]
1CWE-79
from collections import OrderedDict import django.forms from django.utils.translation import gettext_lazy as _ from wagtail.admin.forms import WagtailAdminPageForm from wagtail.contrib.forms.utils import get_field_clean_name class BaseForm(django.forms.Form): def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') self.user = kwargs.pop('user', None) self.page = kwargs.pop('page', None) super().__init__(*args, **kwargs) class FormBuilder: def __init__(self, fields): self.fields = fields def create_singleline_field(self, field, options): # TODO: This is a default value - it may need to be changed options['max_length'] = 255 return django.forms.CharField(**options) def create_multiline_field(self, field, options): return django.forms.CharField(widget=django.forms.Textarea, **options) def create_date_field(self, field, options): return django.forms.DateField(**options) def create_datetime_field(self, field, options): return django.forms.DateTimeField(**options) def create_email_field(self, field, options): return django.forms.EmailField(**options) def create_url_field(self, field, options): return django.forms.URLField(**options) def create_number_field(self, field, options): return django.forms.DecimalField(**options) def create_dropdown_field(self, field, options): options['choices'] = map( lambda x: (x.strip(), x.strip()), field.choices.split(',') ) return django.forms.ChoiceField(**options) def create_multiselect_field(self, field, options): options['choices'] = map( lambda x: (x.strip(), x.strip()), field.choices.split(',') ) return django.forms.MultipleChoiceField(**options) def create_radio_field(self, field, options): options['choices'] = map( lambda x: (x.strip(), x.strip()), field.choices.split(',') ) return django.forms.ChoiceField(widget=django.forms.RadioSelect, **options) def create_checkboxes_field(self, field, options): options['choices'] = [(x.strip(), x.strip()) for x in field.choices.split(',')] options['initial'] = [x.strip() for x in field.default_value.split(',')] return django.forms.MultipleChoiceField( widget=django.forms.CheckboxSelectMultiple, **options ) def create_checkbox_field(self, field, options): return django.forms.BooleanField(**options) def create_hidden_field(self, field, options): return django.forms.CharField(widget=django.forms.HiddenInput, **options) def get_create_field_function(self, type): """ Takes string of field type and returns a Django Form Field Instance. Assumes form field creation functions are in the format: 'create_fieldtype_field' """ create_field_function = getattr(self, 'create_%s_field' % type, None) if create_field_function: return create_field_function else: import inspect method_list = [ f[0] for f in inspect.getmembers(self.__class__, inspect.isfunction) if f[0].startswith('create_') and f[0].endswith('_field') ] raise AttributeError( "Could not find function matching format \ create_<fieldname>_field for type: " + type, "Must be one of: " + ", ".join(method_list) ) @property def formfields(self): formfields = OrderedDict() for field in self.fields: options = self.get_field_options(field) create_field = self.get_create_field_function(field.field_type) formfields[field.clean_name] = create_field(field, options) return formfields def get_field_options(self, field): options = {} options['label'] = field.label options['help_text'] = field.help_text options['required'] = field.required options['initial'] = field.default_value return options def get_form_class(self): return type(str('WagtailForm'), (BaseForm,), self.formfields) class SelectDateForm(django.forms.Form): date_from = django.forms.DateTimeField( required=False, widget=django.forms.DateInput(attrs={'placeholder': _('Date from')}) ) date_to = django.forms.DateTimeField( required=False, widget=django.forms.DateInput(attrs={'placeholder': _('Date to')}) ) class WagtailAdminFormPageForm(WagtailAdminPageForm): def clean(self): super().clean() # Check for dupe form field labels - fixes #585 if 'form_fields' in self.formsets: _forms = self.formsets['form_fields'].forms for f in _forms: f.is_valid() for i, form in enumerate(_forms): if 'label' in form.changed_data: label = form.cleaned_data.get('label') clean_name = get_field_clean_name(label) for idx, ff in enumerate(_forms): # Exclude self ff_clean_name = get_field_clean_name(ff.cleaned_data.get('label')) if idx != i and clean_name == ff_clean_name: form.add_error( 'label', django.forms.ValidationError(_('There is another field with the label %s, please change one of them.' % label)) )
from collections import OrderedDict import django.forms from django.conf import settings from django.utils.html import conditional_escape from django.utils.translation import gettext_lazy as _ from wagtail.admin.forms import WagtailAdminPageForm from wagtail.contrib.forms.utils import get_field_clean_name class BaseForm(django.forms.Form): def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') self.user = kwargs.pop('user', None) self.page = kwargs.pop('page', None) super().__init__(*args, **kwargs) class FormBuilder: def __init__(self, fields): self.fields = fields def create_singleline_field(self, field, options): # TODO: This is a default value - it may need to be changed options['max_length'] = 255 return django.forms.CharField(**options) def create_multiline_field(self, field, options): return django.forms.CharField(widget=django.forms.Textarea, **options) def create_date_field(self, field, options): return django.forms.DateField(**options) def create_datetime_field(self, field, options): return django.forms.DateTimeField(**options) def create_email_field(self, field, options): return django.forms.EmailField(**options) def create_url_field(self, field, options): return django.forms.URLField(**options) def create_number_field(self, field, options): return django.forms.DecimalField(**options) def create_dropdown_field(self, field, options): options['choices'] = map( lambda x: (x.strip(), x.strip()), field.choices.split(',') ) return django.forms.ChoiceField(**options) def create_multiselect_field(self, field, options): options['choices'] = map( lambda x: (x.strip(), x.strip()), field.choices.split(',') ) return django.forms.MultipleChoiceField(**options) def create_radio_field(self, field, options): options['choices'] = map( lambda x: (x.strip(), x.strip()), field.choices.split(',') ) return django.forms.ChoiceField(widget=django.forms.RadioSelect, **options) def create_checkboxes_field(self, field, options): options['choices'] = [(x.strip(), x.strip()) for x in field.choices.split(',')] options['initial'] = [x.strip() for x in field.default_value.split(',')] return django.forms.MultipleChoiceField( widget=django.forms.CheckboxSelectMultiple, **options ) def create_checkbox_field(self, field, options): return django.forms.BooleanField(**options) def create_hidden_field(self, field, options): return django.forms.CharField(widget=django.forms.HiddenInput, **options) def get_create_field_function(self, type): """ Takes string of field type and returns a Django Form Field Instance. Assumes form field creation functions are in the format: 'create_fieldtype_field' """ create_field_function = getattr(self, 'create_%s_field' % type, None) if create_field_function: return create_field_function else: import inspect method_list = [ f[0] for f in inspect.getmembers(self.__class__, inspect.isfunction) if f[0].startswith('create_') and f[0].endswith('_field') ] raise AttributeError( "Could not find function matching format \ create_<fieldname>_field for type: " + type, "Must be one of: " + ", ".join(method_list) ) @property def formfields(self): formfields = OrderedDict() for field in self.fields: options = self.get_field_options(field) create_field = self.get_create_field_function(field.field_type) formfields[field.clean_name] = create_field(field, options) return formfields def get_field_options(self, field): options = {} options['label'] = field.label if getattr(settings, 'WAGTAILFORMS_HELP_TEXT_ALLOW_HTML', False): options['help_text'] = field.help_text else: options['help_text'] = conditional_escape(field.help_text) options['required'] = field.required options['initial'] = field.default_value return options def get_form_class(self): return type(str('WagtailForm'), (BaseForm,), self.formfields) class SelectDateForm(django.forms.Form): date_from = django.forms.DateTimeField( required=False, widget=django.forms.DateInput(attrs={'placeholder': _('Date from')}) ) date_to = django.forms.DateTimeField( required=False, widget=django.forms.DateInput(attrs={'placeholder': _('Date to')}) ) class WagtailAdminFormPageForm(WagtailAdminPageForm): def clean(self): super().clean() # Check for dupe form field labels - fixes #585 if 'form_fields' in self.formsets: _forms = self.formsets['form_fields'].forms for f in _forms: f.is_valid() for i, form in enumerate(_forms): if 'label' in form.changed_data: label = form.cleaned_data.get('label') clean_name = get_field_clean_name(label) for idx, ff in enumerate(_forms): # Exclude self ff_clean_name = get_field_clean_name(ff.cleaned_data.get('label')) if idx != i and clean_name == ff_clean_name: form.add_error( 'label', django.forms.ValidationError(_('There is another field with the label %s, please change one of them.' % label)) )
xss
{ "code": [ " options['help_text'] = field.help_text" ], "line_no": [ 117 ] }
{ "code": [ "from django.conf import settings", " if getattr(settings, 'WAGTAILFORMS_HELP_TEXT_ALLOW_HTML', False):", " options['help_text'] = field.help_text", " options['help_text'] = conditional_escape(field.help_text)" ], "line_no": [ 4, 119, 120, 122 ] }
from collections import OrderedDict import django.forms from django.utils.translation import gettext_lazy as _ from wagtail.admin.forms import WagtailAdminPageForm from wagtail.contrib.forms.utils import get_field_clean_name class CLASS_0(django.forms.Form): def __init__(self, *VAR_0, **VAR_1): kwargs.setdefault('label_suffix', '') self.user = VAR_1.pop('user', None) self.page = VAR_1.pop('page', None) super().__init__(*VAR_0, **VAR_1) class CLASS_1: def __init__(self, VAR_2): self.fields = VAR_2 def FUNC_0(self, VAR_3, VAR_4): VAR_4['max_length'] = 255 return django.forms.CharField(**VAR_4) def FUNC_1(self, VAR_3, VAR_4): return django.forms.CharField(widget=django.forms.Textarea, **VAR_4) def FUNC_2(self, VAR_3, VAR_4): return django.forms.DateField(**VAR_4) def FUNC_3(self, VAR_3, VAR_4): return django.forms.DateTimeField(**VAR_4) def FUNC_4(self, VAR_3, VAR_4): return django.forms.EmailField(**VAR_4) def FUNC_5(self, VAR_3, VAR_4): return django.forms.URLField(**VAR_4) def FUNC_6(self, VAR_3, VAR_4): return django.forms.DecimalField(**VAR_4) def FUNC_7(self, VAR_3, VAR_4): VAR_4['choices'] = map( lambda x: (x.strip(), x.strip()), VAR_3.choices.split(',') ) return django.forms.ChoiceField(**VAR_4) def FUNC_8(self, VAR_3, VAR_4): VAR_4['choices'] = map( lambda x: (x.strip(), x.strip()), VAR_3.choices.split(',') ) return django.forms.MultipleChoiceField(**VAR_4) def FUNC_9(self, VAR_3, VAR_4): VAR_4['choices'] = map( lambda x: (x.strip(), x.strip()), VAR_3.choices.split(',') ) return django.forms.ChoiceField(widget=django.forms.RadioSelect, **VAR_4) def FUNC_10(self, VAR_3, VAR_4): VAR_4['choices'] = [(x.strip(), x.strip()) for x in VAR_3.choices.split(',')] VAR_4['initial'] = [x.strip() for x in VAR_3.default_value.split(',')] return django.forms.MultipleChoiceField( widget=django.forms.CheckboxSelectMultiple, **VAR_4 ) def FUNC_11(self, VAR_3, VAR_4): return django.forms.BooleanField(**VAR_4) def FUNC_12(self, VAR_3, VAR_4): return django.forms.CharField(widget=django.forms.HiddenInput, **VAR_4) def FUNC_13(self, VAR_5): VAR_8 = getattr(self, 'create_%s_field' % VAR_5, None) if VAR_8: return VAR_8 else: import inspect VAR_10 = [ f[0] for f in inspect.getmembers(self.__class__, inspect.isfunction) if f[0].startswith('create_') and f[0].endswith('_field') ] raise AttributeError( "Could not find function matching format \ create_<fieldname>_field for VAR_5: " + VAR_5, "Must be one of: " + ", ".join(VAR_10) ) @property def VAR_9(self): VAR_9 = OrderedDict() for VAR_3 in self.fields: VAR_4 = self.get_field_options(VAR_3) VAR_11 = self.get_create_field_function(VAR_3.field_type) VAR_9[VAR_3.clean_name] = VAR_11(VAR_3, VAR_4) return VAR_9 def FUNC_15(self, VAR_3): VAR_4 = {} VAR_4['label'] = VAR_3.label VAR_4['help_text'] = VAR_3.help_text VAR_4['required'] = VAR_3.required VAR_4['initial'] = VAR_3.default_value return VAR_4 def FUNC_16(self): return VAR_5(str('WagtailForm'), (CLASS_0,), self.formfields) class CLASS_2(django.forms.Form): VAR_6 = django.forms.DateTimeField( required=False, widget=django.forms.DateInput(attrs={'placeholder': _('Date from')}) ) VAR_7 = django.forms.DateTimeField( required=False, widget=django.forms.DateInput(attrs={'placeholder': _('Date to')}) ) class CLASS_3(WagtailAdminPageForm): def FUNC_17(self): super().clean() if 'form_fields' in self.formsets: VAR_12 = self.formsets['form_fields'].forms for f in VAR_12: f.is_valid() for i, form in enumerate(VAR_12): if 'label' in form.changed_data: VAR_13 = form.cleaned_data.get('label') VAR_14 = get_field_clean_name(VAR_13) for idx, ff in enumerate(VAR_12): VAR_15 = get_field_clean_name(ff.cleaned_data.get('label')) if idx != i and VAR_14 == VAR_15: form.add_error( 'label', django.forms.ValidationError(_('There is another VAR_3 with the VAR_13 %s, please change one of them.' % VAR_13)) )
from collections import OrderedDict import django.forms from django.conf import settings from django.utils.html import conditional_escape from django.utils.translation import gettext_lazy as _ from wagtail.admin.forms import WagtailAdminPageForm from wagtail.contrib.forms.utils import get_field_clean_name class CLASS_0(django.forms.Form): def __init__(self, *VAR_0, **VAR_1): kwargs.setdefault('label_suffix', '') self.user = VAR_1.pop('user', None) self.page = VAR_1.pop('page', None) super().__init__(*VAR_0, **VAR_1) class CLASS_1: def __init__(self, VAR_2): self.fields = VAR_2 def FUNC_0(self, VAR_3, VAR_4): VAR_4['max_length'] = 255 return django.forms.CharField(**VAR_4) def FUNC_1(self, VAR_3, VAR_4): return django.forms.CharField(widget=django.forms.Textarea, **VAR_4) def FUNC_2(self, VAR_3, VAR_4): return django.forms.DateField(**VAR_4) def FUNC_3(self, VAR_3, VAR_4): return django.forms.DateTimeField(**VAR_4) def FUNC_4(self, VAR_3, VAR_4): return django.forms.EmailField(**VAR_4) def FUNC_5(self, VAR_3, VAR_4): return django.forms.URLField(**VAR_4) def FUNC_6(self, VAR_3, VAR_4): return django.forms.DecimalField(**VAR_4) def FUNC_7(self, VAR_3, VAR_4): VAR_4['choices'] = map( lambda x: (x.strip(), x.strip()), VAR_3.choices.split(',') ) return django.forms.ChoiceField(**VAR_4) def FUNC_8(self, VAR_3, VAR_4): VAR_4['choices'] = map( lambda x: (x.strip(), x.strip()), VAR_3.choices.split(',') ) return django.forms.MultipleChoiceField(**VAR_4) def FUNC_9(self, VAR_3, VAR_4): VAR_4['choices'] = map( lambda x: (x.strip(), x.strip()), VAR_3.choices.split(',') ) return django.forms.ChoiceField(widget=django.forms.RadioSelect, **VAR_4) def FUNC_10(self, VAR_3, VAR_4): VAR_4['choices'] = [(x.strip(), x.strip()) for x in VAR_3.choices.split(',')] VAR_4['initial'] = [x.strip() for x in VAR_3.default_value.split(',')] return django.forms.MultipleChoiceField( widget=django.forms.CheckboxSelectMultiple, **VAR_4 ) def FUNC_11(self, VAR_3, VAR_4): return django.forms.BooleanField(**VAR_4) def FUNC_12(self, VAR_3, VAR_4): return django.forms.CharField(widget=django.forms.HiddenInput, **VAR_4) def FUNC_13(self, VAR_5): VAR_8 = getattr(self, 'create_%s_field' % VAR_5, None) if VAR_8: return VAR_8 else: import inspect VAR_10 = [ f[0] for f in inspect.getmembers(self.__class__, inspect.isfunction) if f[0].startswith('create_') and f[0].endswith('_field') ] raise AttributeError( "Could not find function matching format \ create_<fieldname>_field for VAR_5: " + VAR_5, "Must be one of: " + ", ".join(VAR_10) ) @property def VAR_9(self): VAR_9 = OrderedDict() for VAR_3 in self.fields: VAR_4 = self.get_field_options(VAR_3) VAR_11 = self.get_create_field_function(VAR_3.field_type) VAR_9[VAR_3.clean_name] = VAR_11(VAR_3, VAR_4) return VAR_9 def FUNC_15(self, VAR_3): VAR_4 = {} VAR_4['label'] = VAR_3.label if getattr(settings, 'WAGTAILFORMS_HELP_TEXT_ALLOW_HTML', False): VAR_4['help_text'] = VAR_3.help_text else: VAR_4['help_text'] = conditional_escape(VAR_3.help_text) VAR_4['required'] = VAR_3.required VAR_4['initial'] = VAR_3.default_value return VAR_4 def FUNC_16(self): return VAR_5(str('WagtailForm'), (CLASS_0,), self.formfields) class CLASS_2(django.forms.Form): VAR_6 = django.forms.DateTimeField( required=False, widget=django.forms.DateInput(attrs={'placeholder': _('Date from')}) ) VAR_7 = django.forms.DateTimeField( required=False, widget=django.forms.DateInput(attrs={'placeholder': _('Date to')}) ) class CLASS_3(WagtailAdminPageForm): def FUNC_17(self): super().clean() if 'form_fields' in self.formsets: VAR_12 = self.formsets['form_fields'].forms for f in VAR_12: f.is_valid() for i, form in enumerate(VAR_12): if 'label' in form.changed_data: VAR_13 = form.cleaned_data.get('label') VAR_14 = get_field_clean_name(VAR_13) for idx, ff in enumerate(VAR_12): VAR_15 = get_field_clean_name(ff.cleaned_data.get('label')) if idx != i and VAR_14 == VAR_15: form.add_error( 'label', django.forms.ValidationError(_('There is another VAR_3 with the VAR_13 %s, please change one of them.' % VAR_13)) )
[ 2, 5, 8, 9, 13, 16, 18, 19, 23, 25, 28, 31, 34, 37, 40, 43, 46, 53, 60, 67, 74, 77, 80, 102, 106, 111, 113, 121, 124, 125, 135, 136, 138, 140, 142, 143, 148, 154, 161, 82, 83, 84, 85, 86 ]
[ 2, 7, 10, 11, 15, 18, 20, 21, 25, 27, 30, 33, 36, 39, 42, 45, 48, 55, 62, 69, 76, 79, 82, 104, 108, 113, 115, 126, 129, 130, 140, 141, 143, 145, 147, 148, 153, 159, 166, 84, 85, 86, 87, 88 ]
3CWE-352
# -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, # andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, # falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, # ruben-herold, marblepebble, JackED42, SiphonSquirrel, # apetresc, nanu-c, mutschler # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import division, print_function, unicode_literals import sys import platform import sqlite3 from collections import OrderedDict import babel, pytz, requests, sqlalchemy import werkzeug, flask, flask_login, flask_principal, jinja2 from flask_babel import gettext as _ from . import db, calibre_db, converter, uploader, server, isoLanguages, constants from .render_template import render_title_template try: from flask_login import __version__ as flask_loginVersion except ImportError: from flask_login.__about__ import __version__ as flask_loginVersion try: # pylint: disable=unused-import import unidecode # _() necessary to make babel aware of string for translation unidecode_version = _(u'installed') except ImportError: unidecode_version = _(u'not installed') try: from flask_dance import __version__ as flask_danceVersion except ImportError: flask_danceVersion = None try: from greenlet import __version__ as greenlet_Version except ImportError: greenlet_Version = None try: from scholarly import scholarly scholarly_version = _(u'installed') except ImportError: scholarly_version = _(u'not installed') from . import services about = flask.Blueprint('about', __name__) _VERSIONS = OrderedDict( Platform = '{0[0]} {0[2]} {0[3]} {0[4]} {0[5]}'.format(platform.uname()), Python=sys.version, Calibre_Web=constants.STABLE_VERSION['version'] + ' - ' + constants.NIGHTLY_VERSION[0].replace('%','%%') + ' - ' + constants.NIGHTLY_VERSION[1].replace('%','%%'), WebServer=server.VERSION, Flask=flask.__version__, Flask_Login=flask_loginVersion, Flask_Principal=flask_principal.__version__, Werkzeug=werkzeug.__version__, Babel=babel.__version__, Jinja2=jinja2.__version__, Requests=requests.__version__, SqlAlchemy=sqlalchemy.__version__, pySqlite=sqlite3.version, SQLite=sqlite3.sqlite_version, iso639=isoLanguages.__version__, pytz=pytz.__version__, Unidecode = unidecode_version, Scholarly = scholarly_version, Flask_SimpleLDAP = u'installed' if bool(services.ldap) else None, python_LDAP = services.ldapVersion if bool(services.ldapVersion) else None, Goodreads = u'installed' if bool(services.goodreads_support) else None, jsonschema = services.SyncToken.__version__ if bool(services.SyncToken) else None, flask_dance = flask_danceVersion, greenlet = greenlet_Version ) _VERSIONS.update(uploader.get_versions()) def collect_stats(): _VERSIONS['ebook converter'] = _(converter.get_calibre_version()) _VERSIONS['unrar'] = _(converter.get_unrar_version()) _VERSIONS['kepubify'] = _(converter.get_kepubify_version()) return _VERSIONS @about.route("/stats") @flask_login.login_required def stats(): counter = calibre_db.session.query(db.Books).count() authors = calibre_db.session.query(db.Authors).count() categorys = calibre_db.session.query(db.Tags).count() series = calibre_db.session.query(db.Series).count() return render_title_template('stats.html', bookcounter=counter, authorcounter=authors, versions=collect_stats(), categorycounter=categorys, seriecounter=series, title=_(u"Statistics"), page="stat")
# -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, # andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, # falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, # ruben-herold, marblepebble, JackED42, SiphonSquirrel, # apetresc, nanu-c, mutschler # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import division, print_function, unicode_literals import sys import platform import sqlite3 from collections import OrderedDict import babel, pytz, requests, sqlalchemy import werkzeug, flask, flask_login, flask_principal, jinja2 from flask_babel import gettext as _ try: from flask_wtf import __version__ as flaskwtf_version except ImportError: flaskwtf_version = _(u'not installed') from . import db, calibre_db, converter, uploader, server, isoLanguages, constants from .render_template import render_title_template try: from flask_login import __version__ as flask_loginVersion except ImportError: from flask_login.__about__ import __version__ as flask_loginVersion try: # pylint: disable=unused-import import unidecode # _() necessary to make babel aware of string for translation unidecode_version = _(u'installed') except ImportError: unidecode_version = _(u'not installed') try: from flask_dance import __version__ as flask_danceVersion except ImportError: flask_danceVersion = None try: from greenlet import __version__ as greenlet_Version except ImportError: greenlet_Version = None try: from scholarly import scholarly scholarly_version = _(u'installed') except ImportError: scholarly_version = _(u'not installed') from . import services about = flask.Blueprint('about', __name__) _VERSIONS = OrderedDict( Platform = '{0[0]} {0[2]} {0[3]} {0[4]} {0[5]}'.format(platform.uname()), Python=sys.version, Calibre_Web=constants.STABLE_VERSION['version'] + ' - ' + constants.NIGHTLY_VERSION[0].replace('%','%%') + ' - ' + constants.NIGHTLY_VERSION[1].replace('%','%%'), WebServer=server.VERSION, Flask=flask.__version__, Flask_Login=flask_loginVersion, Flask_Principal=flask_principal.__version__, Flask_WTF=flaskwtf_version, Werkzeug=werkzeug.__version__, Babel=babel.__version__, Jinja2=jinja2.__version__, Requests=requests.__version__, SqlAlchemy=sqlalchemy.__version__, pySqlite=sqlite3.version, SQLite=sqlite3.sqlite_version, iso639=isoLanguages.__version__, pytz=pytz.__version__, Unidecode=unidecode_version, Scholarly=scholarly_version, Flask_SimpleLDAP=u'installed' if bool(services.ldap) else None, python_LDAP=services.ldapVersion if bool(services.ldapVersion) else None, Goodreads=u'installed' if bool(services.goodreads_support) else None, jsonschema=services.SyncToken.__version__ if bool(services.SyncToken) else None, flask_dance=flask_danceVersion, greenlet=greenlet_Version ) _VERSIONS.update(uploader.get_versions()) def collect_stats(): _VERSIONS['ebook converter'] = _(converter.get_calibre_version()) _VERSIONS['unrar'] = _(converter.get_unrar_version()) _VERSIONS['kepubify'] = _(converter.get_kepubify_version()) return _VERSIONS @about.route("/stats") @flask_login.login_required def stats(): counter = calibre_db.session.query(db.Books).count() authors = calibre_db.session.query(db.Authors).count() categorys = calibre_db.session.query(db.Tags).count() series = calibre_db.session.query(db.Series).count() return render_title_template('stats.html', bookcounter=counter, authorcounter=authors, versions=collect_stats(), categorycounter=categorys, seriecounter=series, title=_(u"Statistics"), page="stat")
xsrf
{ "code": [ " Unidecode = unidecode_version,", " Scholarly = scholarly_version,", " Flask_SimpleLDAP = u'installed' if bool(services.ldap) else None,", " python_LDAP = services.ldapVersion if bool(services.ldapVersion) else None,", " Goodreads = u'installed' if bool(services.goodreads_support) else None,", " jsonschema = services.SyncToken.__version__ if bool(services.SyncToken) else None,", " flask_dance = flask_danceVersion,", " greenlet = greenlet_Version" ], "line_no": [ 87, 88, 89, 90, 91, 92, 93, 94 ] }
{ "code": [ " from flask_wtf import __version__ as flaskwtf_version", "except ImportError:", " flaskwtf_version = _(u'not installed')", " Flask_WTF=flaskwtf_version,", " Unidecode=unidecode_version,", " Scholarly=scholarly_version,", " Flask_SimpleLDAP=u'installed' if bool(services.ldap) else None,", " python_LDAP=services.ldapVersion if bool(services.ldapVersion) else None,", " Goodreads=u'installed' if bool(services.goodreads_support) else None,", " flask_dance=flask_danceVersion,", " greenlet=greenlet_Version" ], "line_no": [ 33, 34, 35, 82, 92, 93, 94, 95, 96, 98, 99 ] }
from __future__ import division, print_function, unicode_literals import sys import platform import sqlite3 from collections import OrderedDict import babel, pytz, requests, sqlalchemy import werkzeug, flask, flask_login, flask_principal, jinja2 from flask_babel import gettext as _ from . import db, calibre_db, converter, uploader, server, isoLanguages, constants from .render_template import render_title_template try: from flask_login import __version__ as flask_loginVersion except ImportError: from flask_login.__about__ import __version__ as flask_loginVersion try: import unidecode VAR_2 = _(u'installed') except ImportError: VAR_2 = _(u'not installed') try: from flask_dance import __version__ as VAR_8 except ImportError: VAR_8 = None try: from greenlet import __version__ as VAR_9 except ImportError: VAR_9 = None try: from scholarly import scholarly VAR_3 = _(u'installed') except ImportError: VAR_3 = _(u'not installed') from . import services VAR_0 = flask.Blueprint('about', __name__) VAR_1 = OrderedDict( Platform = '{0[0]} {0[2]} {0[3]} {0[4]} {0[5]}'.format(platform.uname()), Python=sys.version, Calibre_Web=constants.STABLE_VERSION['version'] + ' - ' + constants.NIGHTLY_VERSION[0].replace('%','%%') + ' - ' + constants.NIGHTLY_VERSION[1].replace('%','%%'), WebServer=server.VERSION, Flask=flask.__version__, Flask_Login=flask_loginVersion, Flask_Principal=flask_principal.__version__, Werkzeug=werkzeug.__version__, Babel=babel.__version__, Jinja2=jinja2.__version__, Requests=requests.__version__, SqlAlchemy=sqlalchemy.__version__, pySqlite=sqlite3.version, SQLite=sqlite3.sqlite_version, iso639=isoLanguages.__version__, pytz=pytz.__version__, Unidecode = VAR_2, Scholarly = VAR_3, Flask_SimpleLDAP = u'installed' if bool(services.ldap) else None, python_LDAP = services.ldapVersion if bool(services.ldapVersion) else None, Goodreads = u'installed' if bool(services.goodreads_support) else None, jsonschema = services.SyncToken.__version__ if bool(services.SyncToken) else None, flask_dance = VAR_8, greenlet = VAR_9 ) VAR_1.update(uploader.get_versions()) def FUNC_0(): VAR_1['ebook converter'] = _(converter.get_calibre_version()) VAR_1['unrar'] = _(converter.get_unrar_version()) VAR_1['kepubify'] = _(converter.get_kepubify_version()) return VAR_1 @VAR_0.route("/stats") @flask_login.login_required def FUNC_1(): VAR_4 = calibre_db.session.query(db.Books).count() VAR_5 = calibre_db.session.query(db.Authors).count() VAR_6 = calibre_db.session.query(db.Tags).count() VAR_7 = calibre_db.session.query(db.Series).count() return render_title_template('stats.html', bookcounter=VAR_4, authorcounter=VAR_5, versions=FUNC_0(), categorycounter=VAR_6, seriecounter=VAR_7, title=_(u"Statistics"), page="stat")
from __future__ import division, print_function, unicode_literals import sys import platform import sqlite3 from collections import OrderedDict import babel, pytz, requests, sqlalchemy import werkzeug, flask, flask_login, flask_principal, jinja2 from flask_babel import gettext as _ try: from flask_wtf import __version__ as VAR_8 except ImportError: VAR_8 = _(u'not installed') from . import db, calibre_db, converter, uploader, server, isoLanguages, constants from .render_template import render_title_template try: from flask_login import __version__ as flask_loginVersion except ImportError: from flask_login.__about__ import __version__ as flask_loginVersion try: import unidecode VAR_2 = _(u'installed') except ImportError: VAR_2 = _(u'not installed') try: from flask_dance import __version__ as VAR_9 except ImportError: VAR_9 = None try: from greenlet import __version__ as VAR_10 except ImportError: VAR_10 = None try: from scholarly import scholarly VAR_3 = _(u'installed') except ImportError: VAR_3 = _(u'not installed') from . import services VAR_0 = flask.Blueprint('about', __name__) VAR_1 = OrderedDict( Platform = '{0[0]} {0[2]} {0[3]} {0[4]} {0[5]}'.format(platform.uname()), Python=sys.version, Calibre_Web=constants.STABLE_VERSION['version'] + ' - ' + constants.NIGHTLY_VERSION[0].replace('%','%%') + ' - ' + constants.NIGHTLY_VERSION[1].replace('%','%%'), WebServer=server.VERSION, Flask=flask.__version__, Flask_Login=flask_loginVersion, Flask_Principal=flask_principal.__version__, Flask_WTF=VAR_8, Werkzeug=werkzeug.__version__, Babel=babel.__version__, Jinja2=jinja2.__version__, Requests=requests.__version__, SqlAlchemy=sqlalchemy.__version__, pySqlite=sqlite3.version, SQLite=sqlite3.sqlite_version, iso639=isoLanguages.__version__, pytz=pytz.__version__, Unidecode=VAR_2, Scholarly=VAR_3, Flask_SimpleLDAP=u'installed' if bool(services.ldap) else None, python_LDAP=services.ldapVersion if bool(services.ldapVersion) else None, Goodreads=u'installed' if bool(services.goodreads_support) else None, jsonschema=services.SyncToken.__version__ if bool(services.SyncToken) else None, flask_dance=VAR_9, greenlet=VAR_10 ) VAR_1.update(uploader.get_versions()) def FUNC_0(): VAR_1['ebook converter'] = _(converter.get_calibre_version()) VAR_1['unrar'] = _(converter.get_unrar_version()) VAR_1['kepubify'] = _(converter.get_kepubify_version()) return VAR_1 @VAR_0.route("/stats") @flask_login.login_required def FUNC_1(): VAR_4 = calibre_db.session.query(db.Books).count() VAR_5 = calibre_db.session.query(db.Authors).count() VAR_6 = calibre_db.session.query(db.Tags).count() VAR_7 = calibre_db.session.query(db.Series).count() return render_title_template('stats.html', bookcounter=VAR_4, authorcounter=VAR_5, versions=FUNC_0(), categorycounter=VAR_6, seriecounter=VAR_7, title=_(u"Statistics"), page="stat")
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 28, 32, 40, 42, 46, 51, 56, 62, 64, 66, 67, 97, 98, 104, 114, 115, 116 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 28, 36, 44, 46, 50, 55, 60, 66, 68, 70, 71, 102, 103, 109, 119, 120, 121 ]
1CWE-79
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2 # This file is part of Checkmk (https://checkmk.com). It is subject to the terms and # conditions defined in the file COPYING, which is part of this source code package. from html import escape as html_escape import re from typing import Union from six import ensure_str from cmk.gui.utils.html import HTML #. # .--Escaper-------------------------------------------------------------. # | _____ | # | | ____|___ ___ __ _ _ __ ___ _ __ | # | | _| / __|/ __/ _` | '_ \ / _ \ '__| | # | | |___\__ \ (_| (_| | |_) | __/ | | # | |_____|___/\___\__,_| .__/ \___|_| | # | |_| | # +----------------------------------------------------------------------+ # | | # '---------------------------------------------------------------------- # TODO: Figure out if this should actually be HTMLTagValue or HTMLContent or... # All the HTML-related types are slightly chaotic... EscapableEntity = Union[None, int, HTML, str] _UNESCAPER_TEXT = re.compile( r'&lt;(/?)(h1|h2|b|tt|i|u|br(?: /)?|nobr(?: /)?|pre|a|sup|p|li|ul|ol)&gt;') _QUOTE = re.compile(r"(?:&quot;|&#x27;)") _A_HREF = re.compile(r'&lt;a href=((?:&quot;|&#x27;).*?(?:&quot;|&#x27;))&gt;') # TODO: Cleanup the accepted types! def escape_attribute(value: EscapableEntity) -> str: """Escape HTML attributes. For example: replace '"' with '&quot;', '<' with '&lt;'. This code is slow. Works on str and unicode without changing the type. Also works on things that can be converted with '%s'. Args: value: Examples: >>> escape_attribute("Hello this is <b>dog</b>!") 'Hello this is &lt;b&gt;dog&lt;/b&gt;!' >>> escape_attribute("Hello this is <foo>dog</foo>!") 'Hello this is &lt;foo&gt;dog&lt;/foo&gt;!' Returns: """ attr_type = type(value) if value is None: return u'' if attr_type == int: return str(value) if isinstance(value, HTML): return value.__html__() # This is HTML code which must not be escaped if isinstance(attr_type, str): return html_escape(value, quote=True) if isinstance(attr_type, bytes): # TODO: Not in the signature! return html_escape(ensure_str(value), quote=True) # TODO: What is this case for? Exception? return html_escape(u"%s" % value, quote=True) # TODO: Not in the signature! def unescape_attributes(value: str) -> str: # In python3 use html.unescape return ensure_str(value # .replace("&amp;", "&") # .replace("&quot;", "\"") # .replace("&lt;", "<") # .replace("&gt;", ">")) def escape_text(text: EscapableEntity) -> str: """Escape HTML text We only strip some tags and allow some simple tags such as <h1>, <b> or <i> to be part of the string. This is useful for messages where we want to keep formatting options. (Formerly known as 'permissive_attrencode') Args: text: Examples: >>> escape_text("Hello this is dog!") 'Hello this is dog!' This is lame. >>> escape_text("Hello this <a href=\"\">is dog</a>!") 'Hello this &lt;a href=&gt;is dog</a>!' Returns: """ if isinstance(text, HTML): return text.__html__() text = escape_attribute(text) text = _UNESCAPER_TEXT.sub(r'<\1\2>', text) for a_href in _A_HREF.finditer(text): text = text.replace(a_href.group(0), u"<a href=%s>" % _QUOTE.sub(u"\"", a_href.group(1))) return text.replace(u"&amp;nbsp;", u"&nbsp;") def strip_scripts(ht: str) -> str: """Strip script tags from text. This function does not handle all the possible edge cases. Beware. Args: ht: A text with possible html in it. Examples: >>> strip_scripts('') '' >>> strip_scripts('foo <script>baz</script> bar') 'foo bar' Edge cases. >>> strip_scripts('foo <scr<script></script>ipt>alert()</SCRIPT> bar') 'foo bar' Returns: A text without html in it. """ prev = None while prev != ht: prev = ht x = ht.lower().find('<script') if x == -1: break y = ht.lower().find('</script') if y == -1: break ht = ht[0:x] + ht[y + 9:] return ht def strip_tags(ht: EscapableEntity) -> str: """Strip all HTML tags from a text. Args: ht: A text with possible HTML tags in it. Examples: >>> strip_tags("<b>foobar</b> blah") 'foobar blah' Edge cases. >>> strip_tags("<p<b<>re>foobar</</b>b> blah") 're>foobarb> blah' Returns: A string without working HTML tags. """ if isinstance(ht, HTML): ht = ht.__html__() if not isinstance(ht, str): return u"%s" % ht ht = ensure_str(ht) while True: x = ht.find('<') if x == -1: break y = ht.find('>', x) if y == -1: break ht = ht[0:x] + ht[y + 1:] return ht.replace("&nbsp;", " ")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2 # This file is part of Checkmk (https://checkmk.com). It is subject to the terms and # conditions defined in the file COPYING, which is part of this source code package. from html import escape as html_escape import re from typing import Union from six import ensure_str from cmk.gui.utils.html import HTML #. # .--Escaper-------------------------------------------------------------. # | _____ | # | | ____|___ ___ __ _ _ __ ___ _ __ | # | | _| / __|/ __/ _` | '_ \ / _ \ '__| | # | | |___\__ \ (_| (_| | |_) | __/ | | # | |_____|___/\___\__,_| .__/ \___|_| | # | |_| | # +----------------------------------------------------------------------+ # | | # '---------------------------------------------------------------------- # TODO: Figure out if this should actually be HTMLTagValue or HTMLContent or... # All the HTML-related types are slightly chaotic... EscapableEntity = Union[None, int, HTML, str] _UNESCAPER_TEXT = re.compile( r'&lt;(/?)(h1|h2|b|tt|i|u|br(?: /)?|nobr(?: /)?|pre|a|sup|p|li|ul|ol)&gt;') _A_HREF = re.compile( r'&lt;a href=(?:(?:&quot;|&#x27;)(.*?)(?:&quot;|&#x27;))(?: target=(?:(?:&quot;|&#x27;)(.*?)(?:&quot;|&#x27;)))?&gt;' ) # TODO: Cleanup the accepted types! def escape_attribute(value: EscapableEntity) -> str: """Escape HTML attributes. For example: replace '"' with '&quot;', '<' with '&lt;'. This code is slow. Works on str and unicode without changing the type. Also works on things that can be converted with '%s'. Args: value: Examples: >>> escape_attribute("Hello this is <b>dog</b>!") 'Hello this is &lt;b&gt;dog&lt;/b&gt;!' >>> escape_attribute("Hello this is <foo>dog</foo>!") 'Hello this is &lt;foo&gt;dog&lt;/foo&gt;!' Returns: """ attr_type = type(value) if value is None: return u'' if attr_type == int: return str(value) if isinstance(value, HTML): return value.__html__() # This is HTML code which must not be escaped if isinstance(attr_type, str): return html_escape(value, quote=True) if isinstance(attr_type, bytes): # TODO: Not in the signature! return html_escape(ensure_str(value), quote=True) # TODO: What is this case for? Exception? return html_escape(u"%s" % value, quote=True) # TODO: Not in the signature! def unescape_attributes(value: str) -> str: # In python3 use html.unescape return ensure_str(value # .replace("&amp;", "&") # .replace("&quot;", "\"") # .replace("&lt;", "<") # .replace("&gt;", ">")) def escape_text(text: EscapableEntity) -> str: """Escape HTML text We only strip some tags and allow some simple tags such as <h1>, <b> or <i> to be part of the string. This is useful for messages where we want to keep formatting options. (Formerly known as 'permissive_attrencode') Args: text: Examples: >>> escape_text("Hello this is dog!") 'Hello this is dog!' This is lame. >>> escape_text("Hello this <a href=\"\">is dog</a>!") 'Hello this &lt;a href=&gt;is dog</a>!' Returns: """ if isinstance(text, HTML): return text.__html__() text = escape_attribute(text) text = _UNESCAPER_TEXT.sub(r'<\1\2>', text) for a_href in _A_HREF.finditer(text): href = a_href.group(1) target = a_href.group(2) if target: unescaped_tag = "<a href=\"%s\" target=\"%s\">" % (href, target) else: unescaped_tag = "<a href=\"%s\">" % href text = text.replace(a_href.group(0), unescaped_tag) return text.replace("&amp;nbsp;", u"&nbsp;") def strip_scripts(ht: str) -> str: """Strip script tags from text. This function does not handle all the possible edge cases. Beware. Args: ht: A text with possible html in it. Examples: >>> strip_scripts('') '' >>> strip_scripts('foo <script>baz</script> bar') 'foo bar' Edge cases. >>> strip_scripts('foo <scr<script></script>ipt>alert()</SCRIPT> bar') 'foo bar' Returns: A text without html in it. """ prev = None while prev != ht: prev = ht x = ht.lower().find('<script') if x == -1: break y = ht.lower().find('</script') if y == -1: break ht = ht[0:x] + ht[y + 9:] return ht def strip_tags(ht: EscapableEntity) -> str: """Strip all HTML tags from a text. Args: ht: A text with possible HTML tags in it. Examples: >>> strip_tags("<b>foobar</b> blah") 'foobar blah' Edge cases. >>> strip_tags("<p<b<>re>foobar</</b>b> blah") 're>foobarb> blah' Returns: A string without working HTML tags. """ if isinstance(ht, HTML): ht = ht.__html__() if not isinstance(ht, str): return u"%s" % ht ht = ensure_str(ht) while True: x = ht.find('<') if x == -1: break y = ht.find('>', x) if y == -1: break ht = ht[0:x] + ht[y + 1:] return ht.replace("&nbsp;", " ")
xss
{ "code": [ " text = text.replace(a_href.group(0), u\"<a href=%s>\" % _QUOTE.sub(u\"\\\"\", a_href.group(1)))", " return text.replace(u\"&amp;nbsp;\", u\"&nbsp;\")" ], "line_no": [ 114, 115 ] }
{ "code": [ "_A_HREF = re.compile(", " href = a_href.group(1)", " if target:", " else:", " text = text.replace(a_href.group(0), unescaped_tag)" ], "line_no": [ 33, 115, 118, 120, 123 ] }
from html import escape as html_escape import re from typing import Union from six import ensure_str from cmk.gui.utils.html import HTML VAR_0 = Union[None, int, HTML, str] VAR_1 = re.compile( r'&lt;(/?)(h1|h2|b|tt|i|u|br(?: /)?|nobr(?: /)?|pre|a|sup|p|li|ul|ol)&gt;') VAR_2 = re.compile(r"(?:&quot;|&#x27;)") VAR_3 = re.compile(r'&lt;a href=((?:&quot;|&#x27;).*?(?:&quot;|&#x27;))&gt;') def FUNC_0(VAR_4: VAR_0) -> str: VAR_7 = type(VAR_4) if VAR_4 is None: return u'' if VAR_7 == int: return str(VAR_4) if isinstance(VAR_4, HTML): return VAR_4.__html__() # This is HTML code which must not be escaped if isinstance(VAR_7, str): return html_escape(VAR_4, quote=True) if isinstance(VAR_7, bytes): # TODO: Not in the signature! return html_escape(ensure_str(VAR_4), quote=True) return html_escape(u"%s" % VAR_4, quote=True) # TODO: Not in the signature! def FUNC_1(VAR_4: str) -> str: return ensure_str(VAR_4 # .replace("&amp;", "&") # .replace("&quot;", "\"") # .replace("&lt;", "<") # .replace("&gt;", ">")) def FUNC_2(VAR_5: VAR_0) -> str: if isinstance(VAR_5, HTML): return VAR_5.__html__() VAR_5 = FUNC_0(VAR_5) VAR_5 = VAR_1.sub(r'<\1\2>', VAR_5) for a_href in VAR_3.finditer(VAR_5): VAR_5 = VAR_5.replace(a_href.group(0), u"<a href=%s>" % VAR_2.sub(u"\"", a_href.group(1))) return VAR_5.replace(u"&amp;nbsp;", u"&nbsp;") def FUNC_3(VAR_6: str) -> str: VAR_8 = None while VAR_8 != VAR_6: VAR_8 = VAR_6 VAR_9 = VAR_6.lower().find('<script') if VAR_9 == -1: break VAR_10 = VAR_6.lower().find('</script') if VAR_10 == -1: break VAR_6 = ht[0:VAR_9] + VAR_6[VAR_10 + 9:] return VAR_6 def FUNC_4(VAR_6: VAR_0) -> str: if isinstance(VAR_6, HTML): VAR_6 = VAR_6.__html__() if not isinstance(VAR_6, str): return u"%s" % VAR_6 ht = ensure_str(VAR_6) while True: VAR_9 = VAR_6.find('<') if VAR_9 == -1: break VAR_10 = VAR_6.find('>', VAR_9) if VAR_10 == -1: break VAR_6 = ht[0:VAR_9] + VAR_6[VAR_10 + 1:] return VAR_6.replace("&nbsp;", " ")
from html import escape as html_escape import re from typing import Union from six import ensure_str from cmk.gui.utils.html import HTML VAR_0 = Union[None, int, HTML, str] VAR_1 = re.compile( r'&lt;(/?)(h1|h2|b|tt|i|u|br(?: /)?|nobr(?: /)?|pre|a|sup|p|li|ul|ol)&gt;') VAR_2 = re.compile( r'&lt;a VAR_8=(?:(?:&quot;|&#x27;)(.*?)(?:&quot;|&#x27;))(?: VAR_9=(?:(?:&quot;|&#x27;)(.*?)(?:&quot;|&#x27;)))?&gt;' ) def FUNC_0(VAR_3: VAR_0) -> str: VAR_6 = type(VAR_3) if VAR_3 is None: return u'' if VAR_6 == int: return str(VAR_3) if isinstance(VAR_3, HTML): return VAR_3.__html__() # This is HTML code which must not be escaped if isinstance(VAR_6, str): return html_escape(VAR_3, quote=True) if isinstance(VAR_6, bytes): # TODO: Not in the signature! return html_escape(ensure_str(VAR_3), quote=True) return html_escape(u"%s" % VAR_3, quote=True) # TODO: Not in the signature! def FUNC_1(VAR_3: str) -> str: return ensure_str(VAR_3 # .replace("&amp;", "&") # .replace("&quot;", "\"") # .replace("&lt;", "<") # .replace("&gt;", ">")) def FUNC_2(VAR_4: VAR_0) -> str: if isinstance(VAR_4, HTML): return VAR_4.__html__() VAR_4 = FUNC_0(VAR_4) VAR_4 = VAR_1.sub(r'<\1\2>', VAR_4) for a_href in VAR_2.finditer(VAR_4): VAR_8 = a_href.group(1) VAR_9 = a_href.group(2) if VAR_9: VAR_12 = "<a VAR_8=\"%s\" VAR_9=\"%s\">" % (VAR_8, VAR_9) else: VAR_12 = "<a VAR_8=\"%s\">" % VAR_8 VAR_4 = VAR_4.replace(a_href.group(0), VAR_12) return VAR_4.replace("&amp;nbsp;", u"&nbsp;") def FUNC_3(VAR_5: str) -> str: VAR_7 = None while VAR_7 != VAR_5: VAR_7 = VAR_5 VAR_10 = VAR_5.lower().find('<script') if VAR_10 == -1: break VAR_11 = VAR_5.lower().find('</script') if VAR_11 == -1: break VAR_5 = ht[0:VAR_10] + VAR_5[VAR_11 + 9:] return VAR_5 def FUNC_4(VAR_5: VAR_0) -> str: if isinstance(VAR_5, HTML): VAR_5 = VAR_5.__html__() if not isinstance(VAR_5, str): return u"%s" % VAR_5 ht = ensure_str(VAR_5) while True: VAR_10 = VAR_5.find('<') if VAR_10 == -1: break VAR_11 = VAR_5.find('>', VAR_10) if VAR_11 == -1: break VAR_5 = ht[0:VAR_10] + VAR_5[VAR_11 + 1:] return VAR_5.replace("&nbsp;", " ")
[ 1, 2, 3, 4, 5, 6, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 35, 36, 37, 40, 44, 47, 49, 52, 55, 56, 58, 71, 73, 74, 76, 82, 83, 86, 91, 94, 96, 99, 101, 104, 106, 110, 116, 117, 120, 122, 125, 129, 132, 134, 137, 140, 152, 154, 155, 158, 161, 165, 167, 170, 173, 177, 180, 182, 192, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174 ]
[ 1, 2, 3, 4, 5, 6, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 36, 37, 38, 41, 45, 48, 50, 53, 56, 57, 59, 72, 74, 75, 77, 83, 84, 87, 92, 95, 97, 100, 102, 105, 107, 111, 117, 122, 125, 126, 129, 131, 134, 138, 141, 143, 146, 149, 161, 163, 164, 167, 170, 174, 176, 179, 182, 186, 189, 191, 201, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183 ]
4CWE-601
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 OpenMarket Ltd # Copyright 2020 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import contextlib import logging import sys from typing import Dict, Iterable, Optional, Set from typing_extensions import ContextManager from twisted.internet import address, reactor import synapse import synapse.events from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError from synapse.api.urls import ( CLIENT_API_PREFIX, FEDERATION_PREFIX, LEGACY_MEDIA_PREFIX, MEDIA_PREFIX, SERVER_KEY_V2_PREFIX, ) from synapse.app import _base from synapse.config._base import ConfigError from synapse.config.homeserver import HomeServerConfig from synapse.config.logger import setup_logging from synapse.config.server import ListenerConfig from synapse.federation import send_queue from synapse.federation.transport.server import TransportLayerServer from synapse.handlers.presence import ( BasePresenceHandler, PresenceState, get_interested_parties, ) from synapse.http.server import JsonResource, OptionsResource from synapse.http.servlet import RestServlet, parse_json_object_from_request from synapse.http.site import SynapseSite from synapse.logging.context import LoggingContext from synapse.metrics import METRICS_PREFIX, MetricsResource, RegistryProxy from synapse.metrics.background_process_metrics import run_as_background_process from synapse.replication.http import REPLICATION_PREFIX, ReplicationRestResource from synapse.replication.http.presence import ( ReplicationBumpPresenceActiveTime, ReplicationPresenceSetState, ) from synapse.replication.slave.storage._base import BaseSlavedStore from synapse.replication.slave.storage.account_data import SlavedAccountDataStore from synapse.replication.slave.storage.appservice import SlavedApplicationServiceStore from synapse.replication.slave.storage.client_ips import SlavedClientIpStore from synapse.replication.slave.storage.deviceinbox import SlavedDeviceInboxStore from synapse.replication.slave.storage.devices import SlavedDeviceStore from synapse.replication.slave.storage.directory import DirectoryStore from synapse.replication.slave.storage.events import SlavedEventStore from synapse.replication.slave.storage.filtering import SlavedFilteringStore from synapse.replication.slave.storage.groups import SlavedGroupServerStore from synapse.replication.slave.storage.keys import SlavedKeyStore from synapse.replication.slave.storage.presence import SlavedPresenceStore from synapse.replication.slave.storage.profile import SlavedProfileStore from synapse.replication.slave.storage.push_rule import SlavedPushRuleStore from synapse.replication.slave.storage.pushers import SlavedPusherStore from synapse.replication.slave.storage.receipts import SlavedReceiptsStore from synapse.replication.slave.storage.registration import SlavedRegistrationStore from synapse.replication.slave.storage.room import RoomStore from synapse.replication.slave.storage.transactions import SlavedTransactionStore from synapse.replication.tcp.client import ReplicationDataHandler from synapse.replication.tcp.commands import ClearUserSyncsCommand from synapse.replication.tcp.streams import ( AccountDataStream, DeviceListsStream, GroupServerStream, PresenceStream, PushersStream, PushRulesStream, ReceiptsStream, TagAccountDataStream, ToDeviceStream, ) from synapse.rest.admin import register_servlets_for_media_repo from synapse.rest.client.v1 import events from synapse.rest.client.v1.initial_sync import InitialSyncRestServlet from synapse.rest.client.v1.login import LoginRestServlet from synapse.rest.client.v1.profile import ( ProfileAvatarURLRestServlet, ProfileDisplaynameRestServlet, ProfileRestServlet, ) from synapse.rest.client.v1.push_rule import PushRuleRestServlet from synapse.rest.client.v1.room import ( JoinedRoomMemberListRestServlet, JoinRoomAliasServlet, PublicRoomListRestServlet, RoomEventContextServlet, RoomInitialSyncRestServlet, RoomMemberListRestServlet, RoomMembershipRestServlet, RoomMessageListRestServlet, RoomSendEventRestServlet, RoomStateEventRestServlet, RoomStateRestServlet, RoomTypingRestServlet, ) from synapse.rest.client.v1.voip import VoipRestServlet from synapse.rest.client.v2_alpha import groups, sync, user_directory from synapse.rest.client.v2_alpha._base import client_patterns from synapse.rest.client.v2_alpha.account import ThreepidRestServlet from synapse.rest.client.v2_alpha.account_data import ( AccountDataServlet, RoomAccountDataServlet, ) from synapse.rest.client.v2_alpha.keys import KeyChangesServlet, KeyQueryServlet from synapse.rest.client.v2_alpha.register import RegisterRestServlet from synapse.rest.client.versions import VersionsRestServlet from synapse.rest.health import HealthResource from synapse.rest.key.v2 import KeyApiV2Resource from synapse.server import HomeServer, cache_in_self from synapse.storage.databases.main.censor_events import CensorEventsStore from synapse.storage.databases.main.client_ips import ClientIpWorkerStore from synapse.storage.databases.main.media_repository import MediaRepositoryStore from synapse.storage.databases.main.metrics import ServerMetricsStore from synapse.storage.databases.main.monthly_active_users import ( MonthlyActiveUsersWorkerStore, ) from synapse.storage.databases.main.presence import UserPresenceState from synapse.storage.databases.main.search import SearchWorkerStore from synapse.storage.databases.main.stats import StatsStore from synapse.storage.databases.main.transactions import TransactionWorkerStore from synapse.storage.databases.main.ui_auth import UIAuthWorkerStore from synapse.storage.databases.main.user_directory import UserDirectoryStore from synapse.types import ReadReceipt from synapse.util.async_helpers import Linearizer from synapse.util.httpresourcetree import create_resource_tree from synapse.util.manhole import manhole from synapse.util.versionstring import get_version_string logger = logging.getLogger("synapse.app.generic_worker") class PresenceStatusStubServlet(RestServlet): """If presence is disabled this servlet can be used to stub out setting presence status. """ PATTERNS = client_patterns("/presence/(?P<user_id>[^/]*)/status") def __init__(self, hs): super().__init__() self.auth = hs.get_auth() async def on_GET(self, request, user_id): await self.auth.get_user_by_req(request) return 200, {"presence": "offline"} async def on_PUT(self, request, user_id): await self.auth.get_user_by_req(request) return 200, {} class KeyUploadServlet(RestServlet): """An implementation of the `KeyUploadServlet` that responds to read only requests, but otherwise proxies through to the master instance. """ PATTERNS = client_patterns("/keys/upload(/(?P<device_id>[^/]+))?$") def __init__(self, hs): """ Args: hs (synapse.server.HomeServer): server """ super().__init__() self.auth = hs.get_auth() self.store = hs.get_datastore() self.http_client = hs.get_simple_http_client() self.main_uri = hs.config.worker_main_http_uri async def on_POST(self, request, device_id): requester = await self.auth.get_user_by_req(request, allow_guest=True) user_id = requester.user.to_string() body = parse_json_object_from_request(request) if device_id is not None: # passing the device_id here is deprecated; however, we allow it # for now for compatibility with older clients. if requester.device_id is not None and device_id != requester.device_id: logger.warning( "Client uploading keys for a different device " "(logged in as %s, uploading for %s)", requester.device_id, device_id, ) else: device_id = requester.device_id if device_id is None: raise SynapseError( 400, "To upload keys, you must pass device_id when authenticating" ) if body: # They're actually trying to upload something, proxy to main synapse. # Proxy headers from the original request, such as the auth headers # (in case the access token is there) and the original IP / # User-Agent of the request. headers = { header: request.requestHeaders.getRawHeaders(header, []) for header in (b"Authorization", b"User-Agent") } # Add the previous hop the the X-Forwarded-For header. x_forwarded_for = request.requestHeaders.getRawHeaders( b"X-Forwarded-For", [] ) if isinstance(request.client, (address.IPv4Address, address.IPv6Address)): previous_host = request.client.host.encode("ascii") # If the header exists, add to the comma-separated list of the first # instance of the header. Otherwise, generate a new header. if x_forwarded_for: x_forwarded_for = [ x_forwarded_for[0] + b", " + previous_host ] + x_forwarded_for[1:] else: x_forwarded_for = [previous_host] headers[b"X-Forwarded-For"] = x_forwarded_for try: result = await self.http_client.post_json_get_json( self.main_uri + request.uri.decode("ascii"), body, headers=headers ) except HttpResponseException as e: raise e.to_synapse_error() from e except RequestSendFailed as e: raise SynapseError(502, "Failed to talk to master") from e return 200, result else: # Just interested in counts. result = await self.store.count_e2e_one_time_keys(user_id, device_id) return 200, {"one_time_key_counts": result} class _NullContextManager(ContextManager[None]): """A context manager which does nothing.""" def __exit__(self, exc_type, exc_val, exc_tb): pass UPDATE_SYNCING_USERS_MS = 10 * 1000 class GenericWorkerPresence(BasePresenceHandler): def __init__(self, hs): super().__init__(hs) self.hs = hs self.is_mine_id = hs.is_mine_id self.http_client = hs.get_simple_http_client() self._presence_enabled = hs.config.use_presence # The number of ongoing syncs on this process, by user id. # Empty if _presence_enabled is false. self._user_to_num_current_syncs = {} # type: Dict[str, int] self.notifier = hs.get_notifier() self.instance_id = hs.get_instance_id() # user_id -> last_sync_ms. Lists the users that have stopped syncing # but we haven't notified the master of that yet self.users_going_offline = {} self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(hs) self._set_state_client = ReplicationPresenceSetState.make_client(hs) self._send_stop_syncing_loop = self.clock.looping_call( self.send_stop_syncing, UPDATE_SYNCING_USERS_MS ) hs.get_reactor().addSystemEventTrigger( "before", "shutdown", run_as_background_process, "generic_presence.on_shutdown", self._on_shutdown, ) def _on_shutdown(self): if self._presence_enabled: self.hs.get_tcp_replication().send_command( ClearUserSyncsCommand(self.instance_id) ) def send_user_sync(self, user_id, is_syncing, last_sync_ms): if self._presence_enabled: self.hs.get_tcp_replication().send_user_sync( self.instance_id, user_id, is_syncing, last_sync_ms ) def mark_as_coming_online(self, user_id): """A user has started syncing. Send a UserSync to the master, unless they had recently stopped syncing. Args: user_id (str) """ going_offline = self.users_going_offline.pop(user_id, None) if not going_offline: # Safe to skip because we haven't yet told the master they were offline self.send_user_sync(user_id, True, self.clock.time_msec()) def mark_as_going_offline(self, user_id): """A user has stopped syncing. We wait before notifying the master as its likely they'll come back soon. This allows us to avoid sending a stopped syncing immediately followed by a started syncing notification to the master Args: user_id (str) """ self.users_going_offline[user_id] = self.clock.time_msec() def send_stop_syncing(self): """Check if there are any users who have stopped syncing a while ago and haven't come back yet. If there are poke the master about them. """ now = self.clock.time_msec() for user_id, last_sync_ms in list(self.users_going_offline.items()): if now - last_sync_ms > UPDATE_SYNCING_USERS_MS: self.users_going_offline.pop(user_id, None) self.send_user_sync(user_id, False, last_sync_ms) async def user_syncing( self, user_id: str, affect_presence: bool ) -> ContextManager[None]: """Record that a user is syncing. Called by the sync and events servlets to record that a user has connected to this worker and is waiting for some events. """ if not affect_presence or not self._presence_enabled: return _NullContextManager() curr_sync = self._user_to_num_current_syncs.get(user_id, 0) self._user_to_num_current_syncs[user_id] = curr_sync + 1 # If we went from no in flight sync to some, notify replication if self._user_to_num_current_syncs[user_id] == 1: self.mark_as_coming_online(user_id) def _end(): # We check that the user_id is in user_to_num_current_syncs because # user_to_num_current_syncs may have been cleared if we are # shutting down. if user_id in self._user_to_num_current_syncs: self._user_to_num_current_syncs[user_id] -= 1 # If we went from one in flight sync to non, notify replication if self._user_to_num_current_syncs[user_id] == 0: self.mark_as_going_offline(user_id) @contextlib.contextmanager def _user_syncing(): try: yield finally: _end() return _user_syncing() async def notify_from_replication(self, states, stream_id): parties = await get_interested_parties(self.store, states) room_ids_to_states, users_to_states = parties self.notifier.on_new_event( "presence_key", stream_id, rooms=room_ids_to_states.keys(), users=users_to_states.keys(), ) async def process_replication_rows(self, token, rows): states = [ UserPresenceState( row.user_id, row.state, row.last_active_ts, row.last_federation_update_ts, row.last_user_sync_ts, row.status_msg, row.currently_active, ) for row in rows ] for state in states: self.user_to_current_state[state.user_id] = state stream_id = token await self.notify_from_replication(states, stream_id) def get_currently_syncing_users_for_replication(self) -> Iterable[str]: return [ user_id for user_id, count in self._user_to_num_current_syncs.items() if count > 0 ] async def set_state(self, target_user, state, ignore_status_msg=False): """Set the presence state of the user. """ presence = state["presence"] valid_presence = ( PresenceState.ONLINE, PresenceState.UNAVAILABLE, PresenceState.OFFLINE, ) if presence not in valid_presence: raise SynapseError(400, "Invalid presence state") user_id = target_user.to_string() # If presence is disabled, no-op if not self.hs.config.use_presence: return # Proxy request to master await self._set_state_client( user_id=user_id, state=state, ignore_status_msg=ignore_status_msg ) async def bump_presence_active_time(self, user): """We've seen the user do something that indicates they're interacting with the app. """ # If presence is disabled, no-op if not self.hs.config.use_presence: return # Proxy request to master user_id = user.to_string() await self._bump_active_client(user_id=user_id) class GenericWorkerSlavedStore( # FIXME(#3714): We need to add UserDirectoryStore as we write directly # rather than going via the correct worker. UserDirectoryStore, StatsStore, UIAuthWorkerStore, SlavedDeviceInboxStore, SlavedDeviceStore, SlavedReceiptsStore, SlavedPushRuleStore, SlavedGroupServerStore, SlavedAccountDataStore, SlavedPusherStore, CensorEventsStore, ClientIpWorkerStore, SlavedEventStore, SlavedKeyStore, RoomStore, DirectoryStore, SlavedApplicationServiceStore, SlavedRegistrationStore, SlavedTransactionStore, SlavedProfileStore, SlavedClientIpStore, SlavedPresenceStore, SlavedFilteringStore, MonthlyActiveUsersWorkerStore, MediaRepositoryStore, ServerMetricsStore, SearchWorkerStore, TransactionWorkerStore, BaseSlavedStore, ): pass class GenericWorkerServer(HomeServer): DATASTORE_CLASS = GenericWorkerSlavedStore def _listen_http(self, listener_config: ListenerConfig): port = listener_config.port bind_addresses = listener_config.bind_addresses assert listener_config.http_options is not None site_tag = listener_config.http_options.tag if site_tag is None: site_tag = port # We always include a health resource. resources = {"/health": HealthResource()} for res in listener_config.http_options.resources: for name in res.names: if name == "metrics": resources[METRICS_PREFIX] = MetricsResource(RegistryProxy) elif name == "client": resource = JsonResource(self, canonical_json=False) PublicRoomListRestServlet(self).register(resource) RoomMemberListRestServlet(self).register(resource) JoinedRoomMemberListRestServlet(self).register(resource) RoomStateRestServlet(self).register(resource) RoomEventContextServlet(self).register(resource) RoomMessageListRestServlet(self).register(resource) RegisterRestServlet(self).register(resource) LoginRestServlet(self).register(resource) ThreepidRestServlet(self).register(resource) KeyQueryServlet(self).register(resource) KeyChangesServlet(self).register(resource) VoipRestServlet(self).register(resource) PushRuleRestServlet(self).register(resource) VersionsRestServlet(self).register(resource) RoomSendEventRestServlet(self).register(resource) RoomMembershipRestServlet(self).register(resource) RoomStateEventRestServlet(self).register(resource) JoinRoomAliasServlet(self).register(resource) ProfileAvatarURLRestServlet(self).register(resource) ProfileDisplaynameRestServlet(self).register(resource) ProfileRestServlet(self).register(resource) KeyUploadServlet(self).register(resource) AccountDataServlet(self).register(resource) RoomAccountDataServlet(self).register(resource) RoomTypingRestServlet(self).register(resource) sync.register_servlets(self, resource) events.register_servlets(self, resource) InitialSyncRestServlet(self).register(resource) RoomInitialSyncRestServlet(self).register(resource) user_directory.register_servlets(self, resource) # If presence is disabled, use the stub servlet that does # not allow sending presence if not self.config.use_presence: PresenceStatusStubServlet(self).register(resource) groups.register_servlets(self, resource) resources.update({CLIENT_API_PREFIX: resource}) elif name == "federation": resources.update({FEDERATION_PREFIX: TransportLayerServer(self)}) elif name == "media": if self.config.can_load_media_repo: media_repo = self.get_media_repository_resource() # We need to serve the admin servlets for media on the # worker. admin_resource = JsonResource(self, canonical_json=False) register_servlets_for_media_repo(self, admin_resource) resources.update( { MEDIA_PREFIX: media_repo, LEGACY_MEDIA_PREFIX: media_repo, "/_synapse/admin": admin_resource, } ) else: logger.warning( "A 'media' listener is configured but the media" " repository is disabled. Ignoring." ) if name == "openid" and "federation" not in res.names: # Only load the openid resource separately if federation resource # is not specified since federation resource includes openid # resource. resources.update( { FEDERATION_PREFIX: TransportLayerServer( self, servlet_groups=["openid"] ) } ) if name in ["keys", "federation"]: resources[SERVER_KEY_V2_PREFIX] = KeyApiV2Resource(self) if name == "replication": resources[REPLICATION_PREFIX] = ReplicationRestResource(self) root_resource = create_resource_tree(resources, OptionsResource()) _base.listen_tcp( bind_addresses, port, SynapseSite( "synapse.access.http.%s" % (site_tag,), site_tag, listener_config, root_resource, self.version_string, ), reactor=self.get_reactor(), ) logger.info("Synapse worker now listening on port %d", port) def start_listening(self, listeners: Iterable[ListenerConfig]): for listener in listeners: if listener.type == "http": self._listen_http(listener) elif listener.type == "manhole": _base.listen_tcp( listener.bind_addresses, listener.port, manhole( username="matrix", password="rabbithole", globals={"hs": self} ), ) elif listener.type == "metrics": if not self.get_config().enable_metrics: logger.warning( ( "Metrics listener configured, but " "enable_metrics is not True!" ) ) else: _base.listen_metrics(listener.bind_addresses, listener.port) else: logger.warning("Unsupported listener type: %s", listener.type) self.get_tcp_replication().start_replication(self) async def remove_pusher(self, app_id, push_key, user_id): self.get_tcp_replication().send_remove_pusher(app_id, push_key, user_id) @cache_in_self def get_replication_data_handler(self): return GenericWorkerReplicationHandler(self) @cache_in_self def get_presence_handler(self): return GenericWorkerPresence(self) class GenericWorkerReplicationHandler(ReplicationDataHandler): def __init__(self, hs): super().__init__(hs) self.store = hs.get_datastore() self.presence_handler = hs.get_presence_handler() # type: GenericWorkerPresence self.notifier = hs.get_notifier() self.notify_pushers = hs.config.start_pushers self.pusher_pool = hs.get_pusherpool() self.send_handler = None # type: Optional[FederationSenderHandler] if hs.config.send_federation: self.send_handler = FederationSenderHandler(hs) async def on_rdata(self, stream_name, instance_name, token, rows): await super().on_rdata(stream_name, instance_name, token, rows) await self._process_and_notify(stream_name, instance_name, token, rows) async def _process_and_notify(self, stream_name, instance_name, token, rows): try: if self.send_handler: await self.send_handler.process_replication_rows( stream_name, token, rows ) if stream_name == PushRulesStream.NAME: self.notifier.on_new_event( "push_rules_key", token, users=[row.user_id for row in rows] ) elif stream_name in (AccountDataStream.NAME, TagAccountDataStream.NAME): self.notifier.on_new_event( "account_data_key", token, users=[row.user_id for row in rows] ) elif stream_name == ReceiptsStream.NAME: self.notifier.on_new_event( "receipt_key", token, rooms=[row.room_id for row in rows] ) await self.pusher_pool.on_new_receipts( token, token, {row.room_id for row in rows} ) elif stream_name == ToDeviceStream.NAME: entities = [row.entity for row in rows if row.entity.startswith("@")] if entities: self.notifier.on_new_event("to_device_key", token, users=entities) elif stream_name == DeviceListsStream.NAME: all_room_ids = set() # type: Set[str] for row in rows: if row.entity.startswith("@"): room_ids = await self.store.get_rooms_for_user(row.entity) all_room_ids.update(room_ids) self.notifier.on_new_event("device_list_key", token, rooms=all_room_ids) elif stream_name == PresenceStream.NAME: await self.presence_handler.process_replication_rows(token, rows) elif stream_name == GroupServerStream.NAME: self.notifier.on_new_event( "groups_key", token, users=[row.user_id for row in rows] ) elif stream_name == PushersStream.NAME: for row in rows: if row.deleted: self.stop_pusher(row.user_id, row.app_id, row.pushkey) else: await self.start_pusher(row.user_id, row.app_id, row.pushkey) except Exception: logger.exception("Error processing replication") async def on_position(self, stream_name: str, instance_name: str, token: int): await super().on_position(stream_name, instance_name, token) # Also call on_rdata to ensure that stream positions are properly reset. await self.on_rdata(stream_name, instance_name, token, []) def stop_pusher(self, user_id, app_id, pushkey): if not self.notify_pushers: return key = "%s:%s" % (app_id, pushkey) pushers_for_user = self.pusher_pool.pushers.get(user_id, {}) pusher = pushers_for_user.pop(key, None) if pusher is None: return logger.info("Stopping pusher %r / %r", user_id, key) pusher.on_stop() async def start_pusher(self, user_id, app_id, pushkey): if not self.notify_pushers: return key = "%s:%s" % (app_id, pushkey) logger.info("Starting pusher %r / %r", user_id, key) return await self.pusher_pool.start_pusher_by_id(app_id, pushkey, user_id) def on_remote_server_up(self, server: str): """Called when get a new REMOTE_SERVER_UP command.""" # Let's wake up the transaction queue for the server in case we have # pending stuff to send to it. if self.send_handler: self.send_handler.wake_destination(server) class FederationSenderHandler: """Processes the fedration replication stream This class is only instantiate on the worker responsible for sending outbound federation transactions. It receives rows from the replication stream and forwards the appropriate entries to the FederationSender class. """ def __init__(self, hs: GenericWorkerServer): self.store = hs.get_datastore() self._is_mine_id = hs.is_mine_id self.federation_sender = hs.get_federation_sender() self._hs = hs # Stores the latest position in the federation stream we've gotten up # to. This is always set before we use it. self.federation_position = None self._fed_position_linearizer = Linearizer(name="_fed_position_linearizer") def on_start(self): # There may be some events that are persisted but haven't been sent, # so send them now. self.federation_sender.notify_new_events( self.store.get_room_max_stream_ordering() ) def wake_destination(self, server: str): self.federation_sender.wake_destination(server) async def process_replication_rows(self, stream_name, token, rows): # The federation stream contains things that we want to send out, e.g. # presence, typing, etc. if stream_name == "federation": send_queue.process_rows_for_federation(self.federation_sender, rows) await self.update_token(token) # ... and when new receipts happen elif stream_name == ReceiptsStream.NAME: await self._on_new_receipts(rows) # ... as well as device updates and messages elif stream_name == DeviceListsStream.NAME: # The entities are either user IDs (starting with '@') whose devices # have changed, or remote servers that we need to tell about # changes. hosts = {row.entity for row in rows if not row.entity.startswith("@")} for host in hosts: self.federation_sender.send_device_messages(host) elif stream_name == ToDeviceStream.NAME: # The to_device stream includes stuff to be pushed to both local # clients and remote servers, so we ignore entities that start with # '@' (since they'll be local users rather than destinations). hosts = {row.entity for row in rows if not row.entity.startswith("@")} for host in hosts: self.federation_sender.send_device_messages(host) async def _on_new_receipts(self, rows): """ Args: rows (Iterable[synapse.replication.tcp.streams.ReceiptsStream.ReceiptsStreamRow]): new receipts to be processed """ for receipt in rows: # we only want to send on receipts for our own users if not self._is_mine_id(receipt.user_id): continue receipt_info = ReadReceipt( receipt.room_id, receipt.receipt_type, receipt.user_id, [receipt.event_id], receipt.data, ) await self.federation_sender.send_read_receipt(receipt_info) async def update_token(self, token): """Update the record of where we have processed to in the federation stream. Called after we have processed a an update received over replication. Sends a FEDERATION_ACK back to the master, and stores the token that we have processed in `federation_stream_position` so that we can restart where we left off. """ self.federation_position = token # We save and send the ACK to master asynchronously, so we don't block # processing on persistence. We don't need to do this operation for # every single RDATA we receive, we just need to do it periodically. if self._fed_position_linearizer.is_queued(None): # There is already a task queued up to save and send the token, so # no need to queue up another task. return run_as_background_process("_save_and_send_ack", self._save_and_send_ack) async def _save_and_send_ack(self): """Save the current federation position in the database and send an ACK to master with where we're up to. """ try: # We linearize here to ensure we don't have races updating the token # # XXX this appears to be redundant, since the ReplicationCommandHandler # has a linearizer which ensures that we only process one line of # replication data at a time. Should we remove it, or is it doing useful # service for robustness? Or could we replace it with an assertion that # we're not being re-entered? with (await self._fed_position_linearizer.queue(None)): # We persist and ack the same position, so we take a copy of it # here as otherwise it can get modified from underneath us. current_position = self.federation_position await self.store.update_federation_out_pos( "federation", current_position ) # We ACK this token over replication so that the master can drop # its in memory queues self._hs.get_tcp_replication().send_federation_ack(current_position) except Exception: logger.exception("Error updating federation stream position") def start(config_options): try: config = HomeServerConfig.load_config("Synapse worker", config_options) except ConfigError as e: sys.stderr.write("\n" + str(e) + "\n") sys.exit(1) # For backwards compatibility let any of the old app names. assert config.worker_app in ( "synapse.app.appservice", "synapse.app.client_reader", "synapse.app.event_creator", "synapse.app.federation_reader", "synapse.app.federation_sender", "synapse.app.frontend_proxy", "synapse.app.generic_worker", "synapse.app.media_repository", "synapse.app.pusher", "synapse.app.synchrotron", "synapse.app.user_dir", ) if config.worker_app == "synapse.app.appservice": if config.appservice.notify_appservices: sys.stderr.write( "\nThe appservices must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``notify_appservices: false`` to the main config" "\n" ) sys.exit(1) # Force the appservice to start since they will be disabled in the main config config.appservice.notify_appservices = True else: # For other worker types we force this to off. config.appservice.notify_appservices = False if config.worker_app == "synapse.app.pusher": if config.server.start_pushers: sys.stderr.write( "\nThe pushers must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``start_pushers: false`` to the main config" "\n" ) sys.exit(1) # Force the pushers to start since they will be disabled in the main config config.server.start_pushers = True else: # For other worker types we force this to off. config.server.start_pushers = False if config.worker_app == "synapse.app.user_dir": if config.server.update_user_directory: sys.stderr.write( "\nThe update_user_directory must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``update_user_directory: false`` to the main config" "\n" ) sys.exit(1) # Force the pushers to start since they will be disabled in the main config config.server.update_user_directory = True else: # For other worker types we force this to off. config.server.update_user_directory = False if config.worker_app == "synapse.app.federation_sender": if config.worker.send_federation: sys.stderr.write( "\nThe send_federation must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``send_federation: false`` to the main config" "\n" ) sys.exit(1) # Force the pushers to start since they will be disabled in the main config config.worker.send_federation = True else: # For other worker types we force this to off. config.worker.send_federation = False synapse.events.USE_FROZEN_DICTS = config.use_frozen_dicts hs = GenericWorkerServer( config.server_name, config=config, version_string="Synapse/" + get_version_string(synapse), ) setup_logging(hs, config, use_worker_options=True) hs.setup() # Ensure the replication streamer is always started in case we write to any # streams. Will no-op if no streams can be written to by this worker. hs.get_replication_streamer() reactor.addSystemEventTrigger( "before", "startup", _base.start, hs, config.worker_listeners ) _base.start_worker_reactor("synapse-generic-worker", config) if __name__ == "__main__": with LoggingContext("main"): start(sys.argv[1:])
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 OpenMarket Ltd # Copyright 2020 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import contextlib import logging import sys from typing import Dict, Iterable, Optional, Set from typing_extensions import ContextManager from twisted.internet import address, reactor import synapse import synapse.events from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError from synapse.api.urls import ( CLIENT_API_PREFIX, FEDERATION_PREFIX, LEGACY_MEDIA_PREFIX, MEDIA_PREFIX, SERVER_KEY_V2_PREFIX, ) from synapse.app import _base from synapse.config._base import ConfigError from synapse.config.homeserver import HomeServerConfig from synapse.config.logger import setup_logging from synapse.config.server import ListenerConfig from synapse.federation import send_queue from synapse.federation.transport.server import TransportLayerServer from synapse.handlers.presence import ( BasePresenceHandler, PresenceState, get_interested_parties, ) from synapse.http.server import JsonResource, OptionsResource from synapse.http.servlet import RestServlet, parse_json_object_from_request from synapse.http.site import SynapseSite from synapse.logging.context import LoggingContext from synapse.metrics import METRICS_PREFIX, MetricsResource, RegistryProxy from synapse.metrics.background_process_metrics import run_as_background_process from synapse.replication.http import REPLICATION_PREFIX, ReplicationRestResource from synapse.replication.http.presence import ( ReplicationBumpPresenceActiveTime, ReplicationPresenceSetState, ) from synapse.replication.slave.storage._base import BaseSlavedStore from synapse.replication.slave.storage.account_data import SlavedAccountDataStore from synapse.replication.slave.storage.appservice import SlavedApplicationServiceStore from synapse.replication.slave.storage.client_ips import SlavedClientIpStore from synapse.replication.slave.storage.deviceinbox import SlavedDeviceInboxStore from synapse.replication.slave.storage.devices import SlavedDeviceStore from synapse.replication.slave.storage.directory import DirectoryStore from synapse.replication.slave.storage.events import SlavedEventStore from synapse.replication.slave.storage.filtering import SlavedFilteringStore from synapse.replication.slave.storage.groups import SlavedGroupServerStore from synapse.replication.slave.storage.keys import SlavedKeyStore from synapse.replication.slave.storage.presence import SlavedPresenceStore from synapse.replication.slave.storage.profile import SlavedProfileStore from synapse.replication.slave.storage.push_rule import SlavedPushRuleStore from synapse.replication.slave.storage.pushers import SlavedPusherStore from synapse.replication.slave.storage.receipts import SlavedReceiptsStore from synapse.replication.slave.storage.registration import SlavedRegistrationStore from synapse.replication.slave.storage.room import RoomStore from synapse.replication.slave.storage.transactions import SlavedTransactionStore from synapse.replication.tcp.client import ReplicationDataHandler from synapse.replication.tcp.commands import ClearUserSyncsCommand from synapse.replication.tcp.streams import ( AccountDataStream, DeviceListsStream, GroupServerStream, PresenceStream, PushersStream, PushRulesStream, ReceiptsStream, TagAccountDataStream, ToDeviceStream, ) from synapse.rest.admin import register_servlets_for_media_repo from synapse.rest.client.v1 import events from synapse.rest.client.v1.initial_sync import InitialSyncRestServlet from synapse.rest.client.v1.login import LoginRestServlet from synapse.rest.client.v1.profile import ( ProfileAvatarURLRestServlet, ProfileDisplaynameRestServlet, ProfileRestServlet, ) from synapse.rest.client.v1.push_rule import PushRuleRestServlet from synapse.rest.client.v1.room import ( JoinedRoomMemberListRestServlet, JoinRoomAliasServlet, PublicRoomListRestServlet, RoomEventContextServlet, RoomInitialSyncRestServlet, RoomMemberListRestServlet, RoomMembershipRestServlet, RoomMessageListRestServlet, RoomSendEventRestServlet, RoomStateEventRestServlet, RoomStateRestServlet, RoomTypingRestServlet, ) from synapse.rest.client.v1.voip import VoipRestServlet from synapse.rest.client.v2_alpha import groups, sync, user_directory from synapse.rest.client.v2_alpha._base import client_patterns from synapse.rest.client.v2_alpha.account import ThreepidRestServlet from synapse.rest.client.v2_alpha.account_data import ( AccountDataServlet, RoomAccountDataServlet, ) from synapse.rest.client.v2_alpha.keys import KeyChangesServlet, KeyQueryServlet from synapse.rest.client.v2_alpha.register import RegisterRestServlet from synapse.rest.client.versions import VersionsRestServlet from synapse.rest.health import HealthResource from synapse.rest.key.v2 import KeyApiV2Resource from synapse.server import HomeServer, cache_in_self from synapse.storage.databases.main.censor_events import CensorEventsStore from synapse.storage.databases.main.client_ips import ClientIpWorkerStore from synapse.storage.databases.main.media_repository import MediaRepositoryStore from synapse.storage.databases.main.metrics import ServerMetricsStore from synapse.storage.databases.main.monthly_active_users import ( MonthlyActiveUsersWorkerStore, ) from synapse.storage.databases.main.presence import UserPresenceState from synapse.storage.databases.main.search import SearchWorkerStore from synapse.storage.databases.main.stats import StatsStore from synapse.storage.databases.main.transactions import TransactionWorkerStore from synapse.storage.databases.main.ui_auth import UIAuthWorkerStore from synapse.storage.databases.main.user_directory import UserDirectoryStore from synapse.types import ReadReceipt from synapse.util.async_helpers import Linearizer from synapse.util.httpresourcetree import create_resource_tree from synapse.util.manhole import manhole from synapse.util.versionstring import get_version_string logger = logging.getLogger("synapse.app.generic_worker") class PresenceStatusStubServlet(RestServlet): """If presence is disabled this servlet can be used to stub out setting presence status. """ PATTERNS = client_patterns("/presence/(?P<user_id>[^/]*)/status") def __init__(self, hs): super().__init__() self.auth = hs.get_auth() async def on_GET(self, request, user_id): await self.auth.get_user_by_req(request) return 200, {"presence": "offline"} async def on_PUT(self, request, user_id): await self.auth.get_user_by_req(request) return 200, {} class KeyUploadServlet(RestServlet): """An implementation of the `KeyUploadServlet` that responds to read only requests, but otherwise proxies through to the master instance. """ PATTERNS = client_patterns("/keys/upload(/(?P<device_id>[^/]+))?$") def __init__(self, hs): """ Args: hs (synapse.server.HomeServer): server """ super().__init__() self.auth = hs.get_auth() self.store = hs.get_datastore() self.http_client = hs.get_simple_http_client() self.main_uri = hs.config.worker_main_http_uri async def on_POST(self, request, device_id): requester = await self.auth.get_user_by_req(request, allow_guest=True) user_id = requester.user.to_string() body = parse_json_object_from_request(request) if device_id is not None: # passing the device_id here is deprecated; however, we allow it # for now for compatibility with older clients. if requester.device_id is not None and device_id != requester.device_id: logger.warning( "Client uploading keys for a different device " "(logged in as %s, uploading for %s)", requester.device_id, device_id, ) else: device_id = requester.device_id if device_id is None: raise SynapseError( 400, "To upload keys, you must pass device_id when authenticating" ) if body: # They're actually trying to upload something, proxy to main synapse. # Proxy headers from the original request, such as the auth headers # (in case the access token is there) and the original IP / # User-Agent of the request. headers = { header: request.requestHeaders.getRawHeaders(header, []) for header in (b"Authorization", b"User-Agent") } # Add the previous hop the the X-Forwarded-For header. x_forwarded_for = request.requestHeaders.getRawHeaders( b"X-Forwarded-For", [] ) if isinstance(request.client, (address.IPv4Address, address.IPv6Address)): previous_host = request.client.host.encode("ascii") # If the header exists, add to the comma-separated list of the first # instance of the header. Otherwise, generate a new header. if x_forwarded_for: x_forwarded_for = [ x_forwarded_for[0] + b", " + previous_host ] + x_forwarded_for[1:] else: x_forwarded_for = [previous_host] headers[b"X-Forwarded-For"] = x_forwarded_for try: result = await self.http_client.post_json_get_json( self.main_uri + request.uri.decode("ascii"), body, headers=headers ) except HttpResponseException as e: raise e.to_synapse_error() from e except RequestSendFailed as e: raise SynapseError(502, "Failed to talk to master") from e return 200, result else: # Just interested in counts. result = await self.store.count_e2e_one_time_keys(user_id, device_id) return 200, {"one_time_key_counts": result} class _NullContextManager(ContextManager[None]): """A context manager which does nothing.""" def __exit__(self, exc_type, exc_val, exc_tb): pass UPDATE_SYNCING_USERS_MS = 10 * 1000 class GenericWorkerPresence(BasePresenceHandler): def __init__(self, hs): super().__init__(hs) self.hs = hs self.is_mine_id = hs.is_mine_id self._presence_enabled = hs.config.use_presence # The number of ongoing syncs on this process, by user id. # Empty if _presence_enabled is false. self._user_to_num_current_syncs = {} # type: Dict[str, int] self.notifier = hs.get_notifier() self.instance_id = hs.get_instance_id() # user_id -> last_sync_ms. Lists the users that have stopped syncing # but we haven't notified the master of that yet self.users_going_offline = {} self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(hs) self._set_state_client = ReplicationPresenceSetState.make_client(hs) self._send_stop_syncing_loop = self.clock.looping_call( self.send_stop_syncing, UPDATE_SYNCING_USERS_MS ) hs.get_reactor().addSystemEventTrigger( "before", "shutdown", run_as_background_process, "generic_presence.on_shutdown", self._on_shutdown, ) def _on_shutdown(self): if self._presence_enabled: self.hs.get_tcp_replication().send_command( ClearUserSyncsCommand(self.instance_id) ) def send_user_sync(self, user_id, is_syncing, last_sync_ms): if self._presence_enabled: self.hs.get_tcp_replication().send_user_sync( self.instance_id, user_id, is_syncing, last_sync_ms ) def mark_as_coming_online(self, user_id): """A user has started syncing. Send a UserSync to the master, unless they had recently stopped syncing. Args: user_id (str) """ going_offline = self.users_going_offline.pop(user_id, None) if not going_offline: # Safe to skip because we haven't yet told the master they were offline self.send_user_sync(user_id, True, self.clock.time_msec()) def mark_as_going_offline(self, user_id): """A user has stopped syncing. We wait before notifying the master as its likely they'll come back soon. This allows us to avoid sending a stopped syncing immediately followed by a started syncing notification to the master Args: user_id (str) """ self.users_going_offline[user_id] = self.clock.time_msec() def send_stop_syncing(self): """Check if there are any users who have stopped syncing a while ago and haven't come back yet. If there are poke the master about them. """ now = self.clock.time_msec() for user_id, last_sync_ms in list(self.users_going_offline.items()): if now - last_sync_ms > UPDATE_SYNCING_USERS_MS: self.users_going_offline.pop(user_id, None) self.send_user_sync(user_id, False, last_sync_ms) async def user_syncing( self, user_id: str, affect_presence: bool ) -> ContextManager[None]: """Record that a user is syncing. Called by the sync and events servlets to record that a user has connected to this worker and is waiting for some events. """ if not affect_presence or not self._presence_enabled: return _NullContextManager() curr_sync = self._user_to_num_current_syncs.get(user_id, 0) self._user_to_num_current_syncs[user_id] = curr_sync + 1 # If we went from no in flight sync to some, notify replication if self._user_to_num_current_syncs[user_id] == 1: self.mark_as_coming_online(user_id) def _end(): # We check that the user_id is in user_to_num_current_syncs because # user_to_num_current_syncs may have been cleared if we are # shutting down. if user_id in self._user_to_num_current_syncs: self._user_to_num_current_syncs[user_id] -= 1 # If we went from one in flight sync to non, notify replication if self._user_to_num_current_syncs[user_id] == 0: self.mark_as_going_offline(user_id) @contextlib.contextmanager def _user_syncing(): try: yield finally: _end() return _user_syncing() async def notify_from_replication(self, states, stream_id): parties = await get_interested_parties(self.store, states) room_ids_to_states, users_to_states = parties self.notifier.on_new_event( "presence_key", stream_id, rooms=room_ids_to_states.keys(), users=users_to_states.keys(), ) async def process_replication_rows(self, token, rows): states = [ UserPresenceState( row.user_id, row.state, row.last_active_ts, row.last_federation_update_ts, row.last_user_sync_ts, row.status_msg, row.currently_active, ) for row in rows ] for state in states: self.user_to_current_state[state.user_id] = state stream_id = token await self.notify_from_replication(states, stream_id) def get_currently_syncing_users_for_replication(self) -> Iterable[str]: return [ user_id for user_id, count in self._user_to_num_current_syncs.items() if count > 0 ] async def set_state(self, target_user, state, ignore_status_msg=False): """Set the presence state of the user. """ presence = state["presence"] valid_presence = ( PresenceState.ONLINE, PresenceState.UNAVAILABLE, PresenceState.OFFLINE, ) if presence not in valid_presence: raise SynapseError(400, "Invalid presence state") user_id = target_user.to_string() # If presence is disabled, no-op if not self.hs.config.use_presence: return # Proxy request to master await self._set_state_client( user_id=user_id, state=state, ignore_status_msg=ignore_status_msg ) async def bump_presence_active_time(self, user): """We've seen the user do something that indicates they're interacting with the app. """ # If presence is disabled, no-op if not self.hs.config.use_presence: return # Proxy request to master user_id = user.to_string() await self._bump_active_client(user_id=user_id) class GenericWorkerSlavedStore( # FIXME(#3714): We need to add UserDirectoryStore as we write directly # rather than going via the correct worker. UserDirectoryStore, StatsStore, UIAuthWorkerStore, SlavedDeviceInboxStore, SlavedDeviceStore, SlavedReceiptsStore, SlavedPushRuleStore, SlavedGroupServerStore, SlavedAccountDataStore, SlavedPusherStore, CensorEventsStore, ClientIpWorkerStore, SlavedEventStore, SlavedKeyStore, RoomStore, DirectoryStore, SlavedApplicationServiceStore, SlavedRegistrationStore, SlavedTransactionStore, SlavedProfileStore, SlavedClientIpStore, SlavedPresenceStore, SlavedFilteringStore, MonthlyActiveUsersWorkerStore, MediaRepositoryStore, ServerMetricsStore, SearchWorkerStore, TransactionWorkerStore, BaseSlavedStore, ): pass class GenericWorkerServer(HomeServer): DATASTORE_CLASS = GenericWorkerSlavedStore def _listen_http(self, listener_config: ListenerConfig): port = listener_config.port bind_addresses = listener_config.bind_addresses assert listener_config.http_options is not None site_tag = listener_config.http_options.tag if site_tag is None: site_tag = port # We always include a health resource. resources = {"/health": HealthResource()} for res in listener_config.http_options.resources: for name in res.names: if name == "metrics": resources[METRICS_PREFIX] = MetricsResource(RegistryProxy) elif name == "client": resource = JsonResource(self, canonical_json=False) PublicRoomListRestServlet(self).register(resource) RoomMemberListRestServlet(self).register(resource) JoinedRoomMemberListRestServlet(self).register(resource) RoomStateRestServlet(self).register(resource) RoomEventContextServlet(self).register(resource) RoomMessageListRestServlet(self).register(resource) RegisterRestServlet(self).register(resource) LoginRestServlet(self).register(resource) ThreepidRestServlet(self).register(resource) KeyQueryServlet(self).register(resource) KeyChangesServlet(self).register(resource) VoipRestServlet(self).register(resource) PushRuleRestServlet(self).register(resource) VersionsRestServlet(self).register(resource) RoomSendEventRestServlet(self).register(resource) RoomMembershipRestServlet(self).register(resource) RoomStateEventRestServlet(self).register(resource) JoinRoomAliasServlet(self).register(resource) ProfileAvatarURLRestServlet(self).register(resource) ProfileDisplaynameRestServlet(self).register(resource) ProfileRestServlet(self).register(resource) KeyUploadServlet(self).register(resource) AccountDataServlet(self).register(resource) RoomAccountDataServlet(self).register(resource) RoomTypingRestServlet(self).register(resource) sync.register_servlets(self, resource) events.register_servlets(self, resource) InitialSyncRestServlet(self).register(resource) RoomInitialSyncRestServlet(self).register(resource) user_directory.register_servlets(self, resource) # If presence is disabled, use the stub servlet that does # not allow sending presence if not self.config.use_presence: PresenceStatusStubServlet(self).register(resource) groups.register_servlets(self, resource) resources.update({CLIENT_API_PREFIX: resource}) elif name == "federation": resources.update({FEDERATION_PREFIX: TransportLayerServer(self)}) elif name == "media": if self.config.can_load_media_repo: media_repo = self.get_media_repository_resource() # We need to serve the admin servlets for media on the # worker. admin_resource = JsonResource(self, canonical_json=False) register_servlets_for_media_repo(self, admin_resource) resources.update( { MEDIA_PREFIX: media_repo, LEGACY_MEDIA_PREFIX: media_repo, "/_synapse/admin": admin_resource, } ) else: logger.warning( "A 'media' listener is configured but the media" " repository is disabled. Ignoring." ) if name == "openid" and "federation" not in res.names: # Only load the openid resource separately if federation resource # is not specified since federation resource includes openid # resource. resources.update( { FEDERATION_PREFIX: TransportLayerServer( self, servlet_groups=["openid"] ) } ) if name in ["keys", "federation"]: resources[SERVER_KEY_V2_PREFIX] = KeyApiV2Resource(self) if name == "replication": resources[REPLICATION_PREFIX] = ReplicationRestResource(self) root_resource = create_resource_tree(resources, OptionsResource()) _base.listen_tcp( bind_addresses, port, SynapseSite( "synapse.access.http.%s" % (site_tag,), site_tag, listener_config, root_resource, self.version_string, ), reactor=self.get_reactor(), ) logger.info("Synapse worker now listening on port %d", port) def start_listening(self, listeners: Iterable[ListenerConfig]): for listener in listeners: if listener.type == "http": self._listen_http(listener) elif listener.type == "manhole": _base.listen_tcp( listener.bind_addresses, listener.port, manhole( username="matrix", password="rabbithole", globals={"hs": self} ), ) elif listener.type == "metrics": if not self.get_config().enable_metrics: logger.warning( ( "Metrics listener configured, but " "enable_metrics is not True!" ) ) else: _base.listen_metrics(listener.bind_addresses, listener.port) else: logger.warning("Unsupported listener type: %s", listener.type) self.get_tcp_replication().start_replication(self) async def remove_pusher(self, app_id, push_key, user_id): self.get_tcp_replication().send_remove_pusher(app_id, push_key, user_id) @cache_in_self def get_replication_data_handler(self): return GenericWorkerReplicationHandler(self) @cache_in_self def get_presence_handler(self): return GenericWorkerPresence(self) class GenericWorkerReplicationHandler(ReplicationDataHandler): def __init__(self, hs): super().__init__(hs) self.store = hs.get_datastore() self.presence_handler = hs.get_presence_handler() # type: GenericWorkerPresence self.notifier = hs.get_notifier() self.notify_pushers = hs.config.start_pushers self.pusher_pool = hs.get_pusherpool() self.send_handler = None # type: Optional[FederationSenderHandler] if hs.config.send_federation: self.send_handler = FederationSenderHandler(hs) async def on_rdata(self, stream_name, instance_name, token, rows): await super().on_rdata(stream_name, instance_name, token, rows) await self._process_and_notify(stream_name, instance_name, token, rows) async def _process_and_notify(self, stream_name, instance_name, token, rows): try: if self.send_handler: await self.send_handler.process_replication_rows( stream_name, token, rows ) if stream_name == PushRulesStream.NAME: self.notifier.on_new_event( "push_rules_key", token, users=[row.user_id for row in rows] ) elif stream_name in (AccountDataStream.NAME, TagAccountDataStream.NAME): self.notifier.on_new_event( "account_data_key", token, users=[row.user_id for row in rows] ) elif stream_name == ReceiptsStream.NAME: self.notifier.on_new_event( "receipt_key", token, rooms=[row.room_id for row in rows] ) await self.pusher_pool.on_new_receipts( token, token, {row.room_id for row in rows} ) elif stream_name == ToDeviceStream.NAME: entities = [row.entity for row in rows if row.entity.startswith("@")] if entities: self.notifier.on_new_event("to_device_key", token, users=entities) elif stream_name == DeviceListsStream.NAME: all_room_ids = set() # type: Set[str] for row in rows: if row.entity.startswith("@"): room_ids = await self.store.get_rooms_for_user(row.entity) all_room_ids.update(room_ids) self.notifier.on_new_event("device_list_key", token, rooms=all_room_ids) elif stream_name == PresenceStream.NAME: await self.presence_handler.process_replication_rows(token, rows) elif stream_name == GroupServerStream.NAME: self.notifier.on_new_event( "groups_key", token, users=[row.user_id for row in rows] ) elif stream_name == PushersStream.NAME: for row in rows: if row.deleted: self.stop_pusher(row.user_id, row.app_id, row.pushkey) else: await self.start_pusher(row.user_id, row.app_id, row.pushkey) except Exception: logger.exception("Error processing replication") async def on_position(self, stream_name: str, instance_name: str, token: int): await super().on_position(stream_name, instance_name, token) # Also call on_rdata to ensure that stream positions are properly reset. await self.on_rdata(stream_name, instance_name, token, []) def stop_pusher(self, user_id, app_id, pushkey): if not self.notify_pushers: return key = "%s:%s" % (app_id, pushkey) pushers_for_user = self.pusher_pool.pushers.get(user_id, {}) pusher = pushers_for_user.pop(key, None) if pusher is None: return logger.info("Stopping pusher %r / %r", user_id, key) pusher.on_stop() async def start_pusher(self, user_id, app_id, pushkey): if not self.notify_pushers: return key = "%s:%s" % (app_id, pushkey) logger.info("Starting pusher %r / %r", user_id, key) return await self.pusher_pool.start_pusher_by_id(app_id, pushkey, user_id) def on_remote_server_up(self, server: str): """Called when get a new REMOTE_SERVER_UP command.""" # Let's wake up the transaction queue for the server in case we have # pending stuff to send to it. if self.send_handler: self.send_handler.wake_destination(server) class FederationSenderHandler: """Processes the fedration replication stream This class is only instantiate on the worker responsible for sending outbound federation transactions. It receives rows from the replication stream and forwards the appropriate entries to the FederationSender class. """ def __init__(self, hs: GenericWorkerServer): self.store = hs.get_datastore() self._is_mine_id = hs.is_mine_id self.federation_sender = hs.get_federation_sender() self._hs = hs # Stores the latest position in the federation stream we've gotten up # to. This is always set before we use it. self.federation_position = None self._fed_position_linearizer = Linearizer(name="_fed_position_linearizer") def on_start(self): # There may be some events that are persisted but haven't been sent, # so send them now. self.federation_sender.notify_new_events( self.store.get_room_max_stream_ordering() ) def wake_destination(self, server: str): self.federation_sender.wake_destination(server) async def process_replication_rows(self, stream_name, token, rows): # The federation stream contains things that we want to send out, e.g. # presence, typing, etc. if stream_name == "federation": send_queue.process_rows_for_federation(self.federation_sender, rows) await self.update_token(token) # ... and when new receipts happen elif stream_name == ReceiptsStream.NAME: await self._on_new_receipts(rows) # ... as well as device updates and messages elif stream_name == DeviceListsStream.NAME: # The entities are either user IDs (starting with '@') whose devices # have changed, or remote servers that we need to tell about # changes. hosts = {row.entity for row in rows if not row.entity.startswith("@")} for host in hosts: self.federation_sender.send_device_messages(host) elif stream_name == ToDeviceStream.NAME: # The to_device stream includes stuff to be pushed to both local # clients and remote servers, so we ignore entities that start with # '@' (since they'll be local users rather than destinations). hosts = {row.entity for row in rows if not row.entity.startswith("@")} for host in hosts: self.federation_sender.send_device_messages(host) async def _on_new_receipts(self, rows): """ Args: rows (Iterable[synapse.replication.tcp.streams.ReceiptsStream.ReceiptsStreamRow]): new receipts to be processed """ for receipt in rows: # we only want to send on receipts for our own users if not self._is_mine_id(receipt.user_id): continue receipt_info = ReadReceipt( receipt.room_id, receipt.receipt_type, receipt.user_id, [receipt.event_id], receipt.data, ) await self.federation_sender.send_read_receipt(receipt_info) async def update_token(self, token): """Update the record of where we have processed to in the federation stream. Called after we have processed a an update received over replication. Sends a FEDERATION_ACK back to the master, and stores the token that we have processed in `federation_stream_position` so that we can restart where we left off. """ self.federation_position = token # We save and send the ACK to master asynchronously, so we don't block # processing on persistence. We don't need to do this operation for # every single RDATA we receive, we just need to do it periodically. if self._fed_position_linearizer.is_queued(None): # There is already a task queued up to save and send the token, so # no need to queue up another task. return run_as_background_process("_save_and_send_ack", self._save_and_send_ack) async def _save_and_send_ack(self): """Save the current federation position in the database and send an ACK to master with where we're up to. """ try: # We linearize here to ensure we don't have races updating the token # # XXX this appears to be redundant, since the ReplicationCommandHandler # has a linearizer which ensures that we only process one line of # replication data at a time. Should we remove it, or is it doing useful # service for robustness? Or could we replace it with an assertion that # we're not being re-entered? with (await self._fed_position_linearizer.queue(None)): # We persist and ack the same position, so we take a copy of it # here as otherwise it can get modified from underneath us. current_position = self.federation_position await self.store.update_federation_out_pos( "federation", current_position ) # We ACK this token over replication so that the master can drop # its in memory queues self._hs.get_tcp_replication().send_federation_ack(current_position) except Exception: logger.exception("Error updating federation stream position") def start(config_options): try: config = HomeServerConfig.load_config("Synapse worker", config_options) except ConfigError as e: sys.stderr.write("\n" + str(e) + "\n") sys.exit(1) # For backwards compatibility let any of the old app names. assert config.worker_app in ( "synapse.app.appservice", "synapse.app.client_reader", "synapse.app.event_creator", "synapse.app.federation_reader", "synapse.app.federation_sender", "synapse.app.frontend_proxy", "synapse.app.generic_worker", "synapse.app.media_repository", "synapse.app.pusher", "synapse.app.synchrotron", "synapse.app.user_dir", ) if config.worker_app == "synapse.app.appservice": if config.appservice.notify_appservices: sys.stderr.write( "\nThe appservices must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``notify_appservices: false`` to the main config" "\n" ) sys.exit(1) # Force the appservice to start since they will be disabled in the main config config.appservice.notify_appservices = True else: # For other worker types we force this to off. config.appservice.notify_appservices = False if config.worker_app == "synapse.app.pusher": if config.server.start_pushers: sys.stderr.write( "\nThe pushers must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``start_pushers: false`` to the main config" "\n" ) sys.exit(1) # Force the pushers to start since they will be disabled in the main config config.server.start_pushers = True else: # For other worker types we force this to off. config.server.start_pushers = False if config.worker_app == "synapse.app.user_dir": if config.server.update_user_directory: sys.stderr.write( "\nThe update_user_directory must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``update_user_directory: false`` to the main config" "\n" ) sys.exit(1) # Force the pushers to start since they will be disabled in the main config config.server.update_user_directory = True else: # For other worker types we force this to off. config.server.update_user_directory = False if config.worker_app == "synapse.app.federation_sender": if config.worker.send_federation: sys.stderr.write( "\nThe send_federation must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``send_federation: false`` to the main config" "\n" ) sys.exit(1) # Force the pushers to start since they will be disabled in the main config config.worker.send_federation = True else: # For other worker types we force this to off. config.worker.send_federation = False synapse.events.USE_FROZEN_DICTS = config.use_frozen_dicts hs = GenericWorkerServer( config.server_name, config=config, version_string="Synapse/" + get_version_string(synapse), ) setup_logging(hs, config, use_worker_options=True) hs.setup() # Ensure the replication streamer is always started in case we write to any # streams. Will no-op if no streams can be written to by this worker. hs.get_replication_streamer() reactor.addSystemEventTrigger( "before", "startup", _base.start, hs, config.worker_listeners ) _base.start_worker_reactor("synapse-generic-worker", config) if __name__ == "__main__": with LoggingContext("main"): start(sys.argv[1:])
open_redirect
{ "code": [ " self.http_client = hs.get_simple_http_client()" ], "line_no": [ 269 ] }
{ "code": [], "line_no": [] }
import contextlib import logging import sys from typing import Dict, Iterable, Optional, Set from typing_extensions import ContextManager from twisted.internet import address, reactor import synapse import synapse.events from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError from synapse.api.urls import ( CLIENT_API_PREFIX, FEDERATION_PREFIX, LEGACY_MEDIA_PREFIX, MEDIA_PREFIX, VAR_57, ) from synapse.app import _base from synapse.config._base import ConfigError from synapse.config.homeserver import HomeServerConfig from synapse.config.logger import setup_logging from synapse.config.server import ListenerConfig from synapse.federation import send_queue from synapse.federation.transport.server import TransportLayerServer from synapse.handlers.presence import ( BasePresenceHandler, PresenceState, get_interested_parties, ) from synapse.http.server import JsonResource, OptionsResource from synapse.http.servlet import RestServlet, parse_json_object_from_request from synapse.http.site import SynapseSite from synapse.logging.context import LoggingContext from synapse.metrics import .METRICS_PREFIX, MetricsResource, RegistryProxy from synapse.metrics.background_process_metrics import run_as_background_process from synapse.replication.http import .REPLICATION_PREFIX, ReplicationRestResource from synapse.replication.http.presence import ( ReplicationBumpPresenceActiveTime, ReplicationPresenceSetState, ) from synapse.replication.slave.storage._base import BaseSlavedStore from synapse.replication.slave.storage.account_data import SlavedAccountDataStore from synapse.replication.slave.storage.appservice import SlavedApplicationServiceStore from synapse.replication.slave.storage.client_ips import SlavedClientIpStore from synapse.replication.slave.storage.deviceinbox import SlavedDeviceInboxStore from synapse.replication.slave.storage.devices import SlavedDeviceStore from synapse.replication.slave.storage.directory import DirectoryStore from synapse.replication.slave.storage.events import SlavedEventStore from synapse.replication.slave.storage.filtering import SlavedFilteringStore from synapse.replication.slave.storage.groups import SlavedGroupServerStore from synapse.replication.slave.storage.keys import SlavedKeyStore from synapse.replication.slave.storage.presence import SlavedPresenceStore from synapse.replication.slave.storage.profile import SlavedProfileStore from synapse.replication.slave.storage.push_rule import SlavedPushRuleStore from synapse.replication.slave.storage.pushers import SlavedPusherStore from synapse.replication.slave.storage.receipts import SlavedReceiptsStore from synapse.replication.slave.storage.registration import SlavedRegistrationStore from synapse.replication.slave.storage.room import RoomStore from synapse.replication.slave.storage.transactions import SlavedTransactionStore from synapse.replication.tcp.client import ReplicationDataHandler from synapse.replication.tcp.commands import ClearUserSyncsCommand from synapse.replication.tcp.streams import ( AccountDataStream, DeviceListsStream, GroupServerStream, PresenceStream, PushersStream, PushRulesStream, ReceiptsStream, TagAccountDataStream, ToDeviceStream, ) from synapse.rest.admin import register_servlets_for_media_repo from synapse.rest.client.v1 import events from synapse.rest.client.v1.initial_sync import InitialSyncRestServlet from synapse.rest.client.v1.login import LoginRestServlet from synapse.rest.client.v1.profile import ( ProfileAvatarURLRestServlet, ProfileDisplaynameRestServlet, ProfileRestServlet, ) from synapse.rest.client.v1.push_rule import PushRuleRestServlet from synapse.rest.client.v1.room import ( JoinedRoomMemberListRestServlet, JoinRoomAliasServlet, PublicRoomListRestServlet, RoomEventContextServlet, RoomInitialSyncRestServlet, RoomMemberListRestServlet, RoomMembershipRestServlet, RoomMessageListRestServlet, RoomSendEventRestServlet, RoomStateEventRestServlet, RoomStateRestServlet, RoomTypingRestServlet, ) from synapse.rest.client.v1.voip import VoipRestServlet from synapse.rest.client.v2_alpha import groups, sync, user_directory from synapse.rest.client.v2_alpha._base import client_patterns from synapse.rest.client.v2_alpha.account import ThreepidRestServlet from synapse.rest.client.v2_alpha.account_data import ( AccountDataServlet, RoomAccountDataServlet, ) from synapse.rest.client.v2_alpha.keys import KeyChangesServlet, KeyQueryServlet from synapse.rest.client.v2_alpha.register import RegisterRestServlet from synapse.rest.client.versions import VersionsRestServlet from synapse.rest.health import HealthResource from synapse.rest.key.v2 import KeyApiV2Resource from synapse.server import HomeServer, cache_in_self from synapse.storage.databases.main.censor_events import CensorEventsStore from synapse.storage.databases.main.client_ips import ClientIpWorkerStore from synapse.storage.databases.main.media_repository import MediaRepositoryStore from synapse.storage.databases.main.metrics import ServerMetricsStore from synapse.storage.databases.main.monthly_active_users import ( MonthlyActiveUsersWorkerStore, ) from synapse.storage.databases.main.presence import UserPresenceState from synapse.storage.databases.main.search import SearchWorkerStore from synapse.storage.databases.main.stats import StatsStore from synapse.storage.databases.main.transactions import TransactionWorkerStore from synapse.storage.databases.main.ui_auth import UIAuthWorkerStore from synapse.storage.databases.main.user_directory import UserDirectoryStore from synapse.types import ReadReceipt from synapse.util.async_helpers import Linearizer from synapse.util.httpresourcetree import create_resource_tree from synapse.util.manhole import manhole from synapse.util.versionstring import get_version_string VAR_0 = logging.getLogger("synapse.app.generic_worker") class CLASS_0(RestServlet): VAR_3 = client_patterns("/VAR_39/(?P<VAR_6>[^/]*)/status") def __init__(self, VAR_4): super().__init__() self.auth = VAR_4.get_auth() async def FUNC_1(self, VAR_5, VAR_6): await self.auth.get_user_by_req(VAR_5) return 200, {"presence": "offline"} async def FUNC_2(self, VAR_5, VAR_6): await self.auth.get_user_by_req(VAR_5) return 200, {} class CLASS_1(RestServlet): VAR_3 = client_patterns("/keys/upload(/(?P<VAR_7>[^/]+))?$") def __init__(self, VAR_4): super().__init__() self.auth = VAR_4.get_auth() self.store = VAR_4.get_datastore() self.http_client = VAR_4.get_simple_http_client() self.main_uri = VAR_4.config.worker_main_http_uri async def FUNC_3(self, VAR_5, VAR_7): VAR_31 = await self.auth.get_user_by_req(VAR_5, allow_guest=True) VAR_6 = VAR_31.user.to_string() VAR_32 = parse_json_object_from_request(VAR_5) if VAR_7 is not None: if VAR_31.device_id is not None and VAR_7 != VAR_31.device_id: VAR_0.warning( "Client uploading keys for a different device " "(logged in as %s, uploading for %s)", VAR_31.device_id, VAR_7, ) else: VAR_7 = VAR_31.device_id if VAR_7 is None: raise SynapseError( 400, "To upload keys, you must pass VAR_7 when authenticating" ) if VAR_32: VAR_50 = { header: VAR_5.requestHeaders.getRawHeaders(header, []) for header in (b"Authorization", b"User-Agent") } VAR_51 = VAR_5.requestHeaders.getRawHeaders( b"X-Forwarded-For", [] ) if isinstance(VAR_5.client, (address.IPv4Address, address.IPv6Address)): VAR_54 = VAR_5.client.host.encode("ascii") if VAR_51: VAR_51 = [ VAR_51[0] + b", " + VAR_54 ] + VAR_51[1:] else: VAR_51 = [VAR_54] VAR_50[b"X-Forwarded-For"] = VAR_51 try: VAR_52 = await self.http_client.post_json_get_json( self.main_uri + VAR_5.uri.decode("ascii"), VAR_32, VAR_50=headers ) except HttpResponseException as e: raise e.to_synapse_error() from e except RequestSendFailed as e: raise SynapseError(502, "Failed to talk to master") from e return 200, VAR_52 else: VAR_52 = await self.store.count_e2e_one_time_keys(VAR_6, VAR_7) return 200, {"one_time_key_counts": VAR_52} class CLASS_2(ContextManager[None]): def __exit__(self, VAR_8, VAR_9, VAR_10): pass VAR_1 = 10 * 1000 class CLASS_3(BasePresenceHandler): def __init__(self, VAR_4): super().__init__(VAR_4) self.hs = VAR_4 self.is_mine_id = VAR_4.is_mine_id self.http_client = VAR_4.get_simple_http_client() self._presence_enabled = VAR_4.config.use_presence self._user_to_num_current_syncs = {} # type: Dict[str, int] self.notifier = VAR_4.get_notifier() self.instance_id = VAR_4.get_instance_id() self.users_going_offline = {} self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(VAR_4) self._set_state_client = ReplicationPresenceSetState.make_client(VAR_4) self._send_stop_syncing_loop = self.clock.looping_call( self.send_stop_syncing, VAR_1 ) VAR_4.get_reactor().addSystemEventTrigger( "before", "shutdown", run_as_background_process, "generic_presence.on_shutdown", self._on_shutdown, ) def FUNC_4(self): if self._presence_enabled: self.hs.get_tcp_replication().send_command( ClearUserSyncsCommand(self.instance_id) ) def FUNC_5(self, VAR_6, VAR_11, VAR_12): if self._presence_enabled: self.hs.get_tcp_replication().send_user_sync( self.instance_id, VAR_6, VAR_11, VAR_12 ) def FUNC_6(self, VAR_6): VAR_33 = self.users_going_offline.pop(VAR_6, None) if not VAR_33: self.send_user_sync(VAR_6, True, self.clock.time_msec()) def FUNC_7(self, VAR_6): self.users_going_offline[VAR_6] = self.clock.time_msec() def FUNC_8(self): VAR_34 = self.clock.time_msec() for VAR_6, VAR_12 in list(self.users_going_offline.items()): if VAR_34 - VAR_12 > VAR_1: self.users_going_offline.pop(VAR_6, None) self.send_user_sync(VAR_6, False, VAR_12) async def FUNC_9( self, VAR_6: str, VAR_13: bool ) -> ContextManager[None]: if not VAR_13 or not self._presence_enabled: return CLASS_2() VAR_35 = self._user_to_num_current_syncs.get(VAR_6, 0) self._user_to_num_current_syncs[VAR_6] = VAR_35 + 1 if self._user_to_num_current_syncs[VAR_6] == 1: self.mark_as_coming_online(VAR_6) def FUNC_31(): if VAR_6 in self._user_to_num_current_syncs: self._user_to_num_current_syncs[VAR_6] -= 1 if self._user_to_num_current_syncs[VAR_6] == 0: self.mark_as_going_offline(VAR_6) @contextlib.contextmanager def FUNC_32(): try: yield finally: FUNC_31() return FUNC_32() async def FUNC_10(self, VAR_14, VAR_15): VAR_36 = await get_interested_parties(self.store, VAR_14) VAR_37, VAR_38 = VAR_36 self.notifier.on_new_event( "presence_key", VAR_15, rooms=VAR_37.keys(), users=VAR_38.keys(), ) async def FUNC_11(self, VAR_16, VAR_17): VAR_14 = [ UserPresenceState( row.user_id, row.state, row.last_active_ts, row.last_federation_update_ts, row.last_user_sync_ts, row.status_msg, row.currently_active, ) for row in VAR_17 ] for VAR_19 in VAR_14: self.user_to_current_state[VAR_19.user_id] = VAR_19 VAR_15 = VAR_16 await self.notify_from_replication(VAR_14, VAR_15) def FUNC_12(self) -> Iterable[str]: return [ VAR_6 for VAR_6, count in self._user_to_num_current_syncs.items() if count > 0 ] async def FUNC_13(self, VAR_18, VAR_19, VAR_20=False): VAR_39 = VAR_19["presence"] VAR_40 = ( PresenceState.ONLINE, PresenceState.UNAVAILABLE, PresenceState.OFFLINE, ) if VAR_39 not in VAR_40: raise SynapseError(400, "Invalid VAR_39 state") VAR_6 = VAR_18.to_string() if not self.hs.config.use_presence: return await self._set_state_client( VAR_6=user_id, VAR_19=state, VAR_20=ignore_status_msg ) async def FUNC_14(self, VAR_21): if not self.hs.config.use_presence: return VAR_6 = VAR_21.to_string() await self._bump_active_client(VAR_6=user_id) class CLASS_4( UserDirectoryStore, StatsStore, UIAuthWorkerStore, SlavedDeviceInboxStore, SlavedDeviceStore, SlavedReceiptsStore, SlavedPushRuleStore, SlavedGroupServerStore, SlavedAccountDataStore, SlavedPusherStore, CensorEventsStore, ClientIpWorkerStore, SlavedEventStore, SlavedKeyStore, RoomStore, DirectoryStore, SlavedApplicationServiceStore, SlavedRegistrationStore, SlavedTransactionStore, SlavedProfileStore, SlavedClientIpStore, SlavedPresenceStore, SlavedFilteringStore, MonthlyActiveUsersWorkerStore, MediaRepositoryStore, ServerMetricsStore, SearchWorkerStore, TransactionWorkerStore, BaseSlavedStore, ): pass class CLASS_5(HomeServer): VAR_22 = CLASS_4 def FUNC_15(self, VAR_23: ListenerConfig): VAR_41 = VAR_23.port VAR_42 = VAR_23.bind_addresses assert VAR_23.http_options is not None VAR_43 = VAR_23.http_options.tag if VAR_43 is None: VAR_43 = VAR_41 VAR_44 = {"/health": HealthResource()} for res in VAR_23.http_options.resources: for name in res.names: if name == "metrics": VAR_44[VAR_56] = MetricsResource(RegistryProxy) elif name == "client": VAR_60 = JsonResource(self, canonical_json=False) PublicRoomListRestServlet(self).register(VAR_60) RoomMemberListRestServlet(self).register(VAR_60) JoinedRoomMemberListRestServlet(self).register(VAR_60) RoomStateRestServlet(self).register(VAR_60) RoomEventContextServlet(self).register(VAR_60) RoomMessageListRestServlet(self).register(VAR_60) RegisterRestServlet(self).register(VAR_60) LoginRestServlet(self).register(VAR_60) ThreepidRestServlet(self).register(VAR_60) KeyQueryServlet(self).register(VAR_60) KeyChangesServlet(self).register(VAR_60) VoipRestServlet(self).register(VAR_60) PushRuleRestServlet(self).register(VAR_60) VersionsRestServlet(self).register(VAR_60) RoomSendEventRestServlet(self).register(VAR_60) RoomMembershipRestServlet(self).register(VAR_60) RoomStateEventRestServlet(self).register(VAR_60) JoinRoomAliasServlet(self).register(VAR_60) ProfileAvatarURLRestServlet(self).register(VAR_60) ProfileDisplaynameRestServlet(self).register(VAR_60) ProfileRestServlet(self).register(VAR_60) CLASS_1(self).register(VAR_60) AccountDataServlet(self).register(VAR_60) RoomAccountDataServlet(self).register(VAR_60) RoomTypingRestServlet(self).register(VAR_60) sync.register_servlets(self, VAR_60) events.register_servlets(self, VAR_60) InitialSyncRestServlet(self).register(VAR_60) RoomInitialSyncRestServlet(self).register(VAR_60) user_directory.register_servlets(self, VAR_60) if not self.config.use_presence: CLASS_0(self).register(VAR_60) groups.register_servlets(self, VAR_60) VAR_44.update({CLIENT_API_PREFIX: VAR_60}) elif name == "federation": VAR_44.update({FEDERATION_PREFIX: TransportLayerServer(self)}) elif name == "media": if self.config.can_load_media_repo: VAR_63 = self.get_media_repository_resource() VAR_64 = JsonResource(self, canonical_json=False) register_servlets_for_media_repo(self, VAR_64) VAR_44.update( { MEDIA_PREFIX: VAR_63, LEGACY_MEDIA_PREFIX: VAR_63, "/_synapse/admin": VAR_64, } ) else: VAR_0.warning( "A 'media' listener is configured but the media" " repository is disabled. Ignoring." ) if name == "openid" and "federation" not in res.names: VAR_44.update( { FEDERATION_PREFIX: TransportLayerServer( self, servlet_groups=["openid"] ) } ) if name in ["keys", "federation"]: VAR_44[VAR_57] = KeyApiV2Resource(self) if name == "replication": VAR_44[VAR_58] = ReplicationRestResource(self) VAR_45 = create_resource_tree(VAR_44, OptionsResource()) _base.listen_tcp( VAR_42, VAR_41, SynapseSite( "synapse.access.http.%s" % (VAR_43,), site_tag, VAR_23, VAR_45, self.version_string, ), reactor=self.get_reactor(), ) VAR_0.info("Synapse worker VAR_34 listening on VAR_41 %d", VAR_41) def FUNC_16(self, VAR_24: Iterable[ListenerConfig]): for listener in VAR_24: if listener.type == "http": self._listen_http(listener) elif listener.type == "manhole": _base.listen_tcp( listener.bind_addresses, listener.port, manhole( username="matrix", password="rabbithole", globals={"hs": self} ), ) elif listener.type == "metrics": if not self.get_config().enable_metrics: VAR_0.warning( ( "Metrics listener configured, but " "enable_metrics is not True!" ) ) else: _base.listen_metrics(listener.bind_addresses, listener.port) else: VAR_0.warning("Unsupported listener type: %s", listener.type) self.get_tcp_replication().start_replication(self) async def FUNC_17(self, VAR_25, VAR_26, VAR_6): self.get_tcp_replication().send_remove_pusher(VAR_25, VAR_26, VAR_6) @cache_in_self def FUNC_18(self): return CLASS_6(self) @cache_in_self def FUNC_19(self): return CLASS_3(self) class CLASS_6(ReplicationDataHandler): def __init__(self, VAR_4): super().__init__(VAR_4) self.store = VAR_4.get_datastore() self.presence_handler = VAR_4.get_presence_handler() # type: CLASS_3 self.notifier = VAR_4.get_notifier() self.notify_pushers = VAR_4.config.start_pushers self.pusher_pool = VAR_4.get_pusherpool() self.send_handler = None # type: Optional[CLASS_7] if VAR_4.config.send_federation: self.send_handler = CLASS_7(VAR_4) async def FUNC_20(self, VAR_27, VAR_28, VAR_16, VAR_17): await super().on_rdata(VAR_27, VAR_28, VAR_16, VAR_17) await self._process_and_notify(VAR_27, VAR_28, VAR_16, VAR_17) async def FUNC_21(self, VAR_27, VAR_28, VAR_16, VAR_17): try: if self.send_handler: await self.send_handler.process_replication_rows( VAR_27, VAR_16, VAR_17 ) if VAR_27 == PushRulesStream.NAME: self.notifier.on_new_event( "push_rules_key", VAR_16, users=[row.user_id for row in VAR_17] ) elif VAR_27 in (AccountDataStream.NAME, TagAccountDataStream.NAME): self.notifier.on_new_event( "account_data_key", VAR_16, users=[row.user_id for row in VAR_17] ) elif VAR_27 == ReceiptsStream.NAME: self.notifier.on_new_event( "receipt_key", VAR_16, rooms=[row.room_id for row in VAR_17] ) await self.pusher_pool.on_new_receipts( VAR_16, VAR_16, {row.room_id for row in VAR_17} ) elif VAR_27 == ToDeviceStream.NAME: VAR_61 = [row.entity for row in VAR_17 if row.entity.startswith("@")] if VAR_61: self.notifier.on_new_event("to_device_key", VAR_16, users=VAR_61) elif VAR_27 == DeviceListsStream.NAME: VAR_62 = set() # type: Set[str] for row in VAR_17: if row.entity.startswith("@"): VAR_65 = await self.store.get_rooms_for_user(row.entity) VAR_62.update(VAR_65) self.notifier.on_new_event("device_list_key", VAR_16, rooms=VAR_62) elif VAR_27 == PresenceStream.NAME: await self.presence_handler.process_replication_rows(VAR_16, VAR_17) elif VAR_27 == GroupServerStream.NAME: self.notifier.on_new_event( "groups_key", VAR_16, users=[row.user_id for row in VAR_17] ) elif VAR_27 == PushersStream.NAME: for row in VAR_17: if row.deleted: self.stop_pusher(row.user_id, row.app_id, row.pushkey) else: await self.start_pusher(row.user_id, row.app_id, row.pushkey) except Exception: VAR_0.exception("Error processing replication") async def FUNC_22(self, VAR_27: str, VAR_28: str, VAR_16: int): await super().on_position(VAR_27, VAR_28, VAR_16) await self.on_rdata(VAR_27, VAR_28, VAR_16, []) def FUNC_23(self, VAR_6, VAR_25, VAR_29): if not self.notify_pushers: return VAR_46 = "%s:%s" % (VAR_25, VAR_29) VAR_47 = self.pusher_pool.pushers.get(VAR_6, {}) VAR_48 = VAR_47.pop(VAR_46, None) if VAR_48 is None: return VAR_0.info("Stopping VAR_48 %r / %r", VAR_6, VAR_46) VAR_48.on_stop() async def FUNC_24(self, VAR_6, VAR_25, VAR_29): if not self.notify_pushers: return VAR_46 = "%s:%s" % (VAR_25, VAR_29) VAR_0.info("Starting VAR_48 %r / %r", VAR_6, VAR_46) return await self.pusher_pool.start_pusher_by_id(VAR_25, VAR_29, VAR_6) def FUNC_25(self, VAR_30: str): if self.send_handler: self.send_handler.wake_destination(VAR_30) class CLASS_7: def __init__(self, VAR_4: CLASS_5): self.store = VAR_4.get_datastore() self._is_mine_id = VAR_4.is_mine_id self.federation_sender = VAR_4.get_federation_sender() self._hs = VAR_4 self.federation_position = None self._fed_position_linearizer = Linearizer(name="_fed_position_linearizer") def FUNC_26(self): self.federation_sender.notify_new_events( self.store.get_room_max_stream_ordering() ) def FUNC_27(self, VAR_30: str): self.federation_sender.wake_destination(VAR_30) async def FUNC_11(self, VAR_27, VAR_16, VAR_17): if VAR_27 == "federation": send_queue.process_rows_for_federation(self.federation_sender, VAR_17) await self.update_token(VAR_16) elif VAR_27 == ReceiptsStream.NAME: await self._on_new_receipts(VAR_17) elif VAR_27 == DeviceListsStream.NAME: VAR_59 = {row.entity for row in VAR_17 if not row.entity.startswith("@")} for host in VAR_59: self.federation_sender.send_device_messages(host) elif VAR_27 == ToDeviceStream.NAME: VAR_59 = {row.entity for row in VAR_17 if not row.entity.startswith("@")} for host in VAR_59: self.federation_sender.send_device_messages(host) async def FUNC_28(self, VAR_17): for receipt in VAR_17: if not self._is_mine_id(receipt.user_id): continue VAR_53 = ReadReceipt( receipt.room_id, receipt.receipt_type, receipt.user_id, [receipt.event_id], receipt.data, ) await self.federation_sender.send_read_receipt(VAR_53) async def FUNC_29(self, VAR_16): self.federation_position = VAR_16 if self._fed_position_linearizer.is_queued(None): return run_as_background_process("_save_and_send_ack", self._save_and_send_ack) async def FUNC_30(self): try: with (await self._fed_position_linearizer.queue(None)): VAR_55 = self.federation_position await self.store.update_federation_out_pos( "federation", VAR_55 ) self._hs.get_tcp_replication().send_federation_ack(VAR_55) except Exception: VAR_0.exception("Error updating federation stream position") def FUNC_0(VAR_2): try: VAR_49 = HomeServerConfig.load_config("Synapse worker", VAR_2) except ConfigError as e: sys.stderr.write("\n" + str(e) + "\n") sys.exit(1) assert VAR_49.worker_app in ( "synapse.app.appservice", "synapse.app.client_reader", "synapse.app.event_creator", "synapse.app.federation_reader", "synapse.app.federation_sender", "synapse.app.frontend_proxy", "synapse.app.generic_worker", "synapse.app.media_repository", "synapse.app.pusher", "synapse.app.synchrotron", "synapse.app.user_dir", ) if VAR_49.worker_app == "synapse.app.appservice": if VAR_49.appservice.notify_appservices: sys.stderr.write( "\nThe appservices must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``notify_appservices: false`` to the main config" "\n" ) sys.exit(1) VAR_49.appservice.notify_appservices = True else: VAR_49.appservice.notify_appservices = False if VAR_49.worker_app == "synapse.app.pusher": if VAR_49.server.start_pushers: sys.stderr.write( "\nThe pushers must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``start_pushers: false`` to the main config" "\n" ) sys.exit(1) VAR_49.server.start_pushers = True else: VAR_49.server.start_pushers = False if VAR_49.worker_app == "synapse.app.user_dir": if VAR_49.server.update_user_directory: sys.stderr.write( "\nThe update_user_directory must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``update_user_directory: false`` to the main config" "\n" ) sys.exit(1) VAR_49.server.update_user_directory = True else: VAR_49.server.update_user_directory = False if VAR_49.worker_app == "synapse.app.federation_sender": if VAR_49.worker.send_federation: sys.stderr.write( "\nThe send_federation must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``send_federation: false`` to the main config" "\n" ) sys.exit(1) VAR_49.worker.send_federation = True else: VAR_49.worker.send_federation = False synapse.events.USE_FROZEN_DICTS = VAR_49.use_frozen_dicts VAR_4 = CLASS_5( VAR_49.server_name, VAR_49=config, version_string="Synapse/" + get_version_string(synapse), ) setup_logging(VAR_4, VAR_49, use_worker_options=True) VAR_4.setup() VAR_4.get_replication_streamer() reactor.addSystemEventTrigger( "before", "startup", _base.start, VAR_4, VAR_49.worker_listeners ) _base.start_worker_reactor("synapse-generic-worker", VAR_49) if __name__ == "__main__": with LoggingContext("main"): FUNC_0(sys.argv[1:])
import contextlib import logging import sys from typing import Dict, Iterable, Optional, Set from typing_extensions import ContextManager from twisted.internet import address, reactor import synapse import synapse.events from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError from synapse.api.urls import ( CLIENT_API_PREFIX, FEDERATION_PREFIX, LEGACY_MEDIA_PREFIX, MEDIA_PREFIX, VAR_57, ) from synapse.app import _base from synapse.config._base import ConfigError from synapse.config.homeserver import HomeServerConfig from synapse.config.logger import setup_logging from synapse.config.server import ListenerConfig from synapse.federation import send_queue from synapse.federation.transport.server import TransportLayerServer from synapse.handlers.presence import ( BasePresenceHandler, PresenceState, get_interested_parties, ) from synapse.http.server import JsonResource, OptionsResource from synapse.http.servlet import RestServlet, parse_json_object_from_request from synapse.http.site import SynapseSite from synapse.logging.context import LoggingContext from synapse.metrics import .METRICS_PREFIX, MetricsResource, RegistryProxy from synapse.metrics.background_process_metrics import run_as_background_process from synapse.replication.http import .REPLICATION_PREFIX, ReplicationRestResource from synapse.replication.http.presence import ( ReplicationBumpPresenceActiveTime, ReplicationPresenceSetState, ) from synapse.replication.slave.storage._base import BaseSlavedStore from synapse.replication.slave.storage.account_data import SlavedAccountDataStore from synapse.replication.slave.storage.appservice import SlavedApplicationServiceStore from synapse.replication.slave.storage.client_ips import SlavedClientIpStore from synapse.replication.slave.storage.deviceinbox import SlavedDeviceInboxStore from synapse.replication.slave.storage.devices import SlavedDeviceStore from synapse.replication.slave.storage.directory import DirectoryStore from synapse.replication.slave.storage.events import SlavedEventStore from synapse.replication.slave.storage.filtering import SlavedFilteringStore from synapse.replication.slave.storage.groups import SlavedGroupServerStore from synapse.replication.slave.storage.keys import SlavedKeyStore from synapse.replication.slave.storage.presence import SlavedPresenceStore from synapse.replication.slave.storage.profile import SlavedProfileStore from synapse.replication.slave.storage.push_rule import SlavedPushRuleStore from synapse.replication.slave.storage.pushers import SlavedPusherStore from synapse.replication.slave.storage.receipts import SlavedReceiptsStore from synapse.replication.slave.storage.registration import SlavedRegistrationStore from synapse.replication.slave.storage.room import RoomStore from synapse.replication.slave.storage.transactions import SlavedTransactionStore from synapse.replication.tcp.client import ReplicationDataHandler from synapse.replication.tcp.commands import ClearUserSyncsCommand from synapse.replication.tcp.streams import ( AccountDataStream, DeviceListsStream, GroupServerStream, PresenceStream, PushersStream, PushRulesStream, ReceiptsStream, TagAccountDataStream, ToDeviceStream, ) from synapse.rest.admin import register_servlets_for_media_repo from synapse.rest.client.v1 import events from synapse.rest.client.v1.initial_sync import InitialSyncRestServlet from synapse.rest.client.v1.login import LoginRestServlet from synapse.rest.client.v1.profile import ( ProfileAvatarURLRestServlet, ProfileDisplaynameRestServlet, ProfileRestServlet, ) from synapse.rest.client.v1.push_rule import PushRuleRestServlet from synapse.rest.client.v1.room import ( JoinedRoomMemberListRestServlet, JoinRoomAliasServlet, PublicRoomListRestServlet, RoomEventContextServlet, RoomInitialSyncRestServlet, RoomMemberListRestServlet, RoomMembershipRestServlet, RoomMessageListRestServlet, RoomSendEventRestServlet, RoomStateEventRestServlet, RoomStateRestServlet, RoomTypingRestServlet, ) from synapse.rest.client.v1.voip import VoipRestServlet from synapse.rest.client.v2_alpha import groups, sync, user_directory from synapse.rest.client.v2_alpha._base import client_patterns from synapse.rest.client.v2_alpha.account import ThreepidRestServlet from synapse.rest.client.v2_alpha.account_data import ( AccountDataServlet, RoomAccountDataServlet, ) from synapse.rest.client.v2_alpha.keys import KeyChangesServlet, KeyQueryServlet from synapse.rest.client.v2_alpha.register import RegisterRestServlet from synapse.rest.client.versions import VersionsRestServlet from synapse.rest.health import HealthResource from synapse.rest.key.v2 import KeyApiV2Resource from synapse.server import HomeServer, cache_in_self from synapse.storage.databases.main.censor_events import CensorEventsStore from synapse.storage.databases.main.client_ips import ClientIpWorkerStore from synapse.storage.databases.main.media_repository import MediaRepositoryStore from synapse.storage.databases.main.metrics import ServerMetricsStore from synapse.storage.databases.main.monthly_active_users import ( MonthlyActiveUsersWorkerStore, ) from synapse.storage.databases.main.presence import UserPresenceState from synapse.storage.databases.main.search import SearchWorkerStore from synapse.storage.databases.main.stats import StatsStore from synapse.storage.databases.main.transactions import TransactionWorkerStore from synapse.storage.databases.main.ui_auth import UIAuthWorkerStore from synapse.storage.databases.main.user_directory import UserDirectoryStore from synapse.types import ReadReceipt from synapse.util.async_helpers import Linearizer from synapse.util.httpresourcetree import create_resource_tree from synapse.util.manhole import manhole from synapse.util.versionstring import get_version_string VAR_0 = logging.getLogger("synapse.app.generic_worker") class CLASS_0(RestServlet): VAR_3 = client_patterns("/VAR_39/(?P<VAR_6>[^/]*)/status") def __init__(self, VAR_4): super().__init__() self.auth = VAR_4.get_auth() async def FUNC_1(self, VAR_5, VAR_6): await self.auth.get_user_by_req(VAR_5) return 200, {"presence": "offline"} async def FUNC_2(self, VAR_5, VAR_6): await self.auth.get_user_by_req(VAR_5) return 200, {} class CLASS_1(RestServlet): VAR_3 = client_patterns("/keys/upload(/(?P<VAR_7>[^/]+))?$") def __init__(self, VAR_4): super().__init__() self.auth = VAR_4.get_auth() self.store = VAR_4.get_datastore() self.http_client = VAR_4.get_simple_http_client() self.main_uri = VAR_4.config.worker_main_http_uri async def FUNC_3(self, VAR_5, VAR_7): VAR_31 = await self.auth.get_user_by_req(VAR_5, allow_guest=True) VAR_6 = VAR_31.user.to_string() VAR_32 = parse_json_object_from_request(VAR_5) if VAR_7 is not None: if VAR_31.device_id is not None and VAR_7 != VAR_31.device_id: VAR_0.warning( "Client uploading keys for a different device " "(logged in as %s, uploading for %s)", VAR_31.device_id, VAR_7, ) else: VAR_7 = VAR_31.device_id if VAR_7 is None: raise SynapseError( 400, "To upload keys, you must pass VAR_7 when authenticating" ) if VAR_32: VAR_50 = { header: VAR_5.requestHeaders.getRawHeaders(header, []) for header in (b"Authorization", b"User-Agent") } VAR_51 = VAR_5.requestHeaders.getRawHeaders( b"X-Forwarded-For", [] ) if isinstance(VAR_5.client, (address.IPv4Address, address.IPv6Address)): VAR_54 = VAR_5.client.host.encode("ascii") if VAR_51: VAR_51 = [ VAR_51[0] + b", " + VAR_54 ] + VAR_51[1:] else: VAR_51 = [VAR_54] VAR_50[b"X-Forwarded-For"] = VAR_51 try: VAR_52 = await self.http_client.post_json_get_json( self.main_uri + VAR_5.uri.decode("ascii"), VAR_32, VAR_50=headers ) except HttpResponseException as e: raise e.to_synapse_error() from e except RequestSendFailed as e: raise SynapseError(502, "Failed to talk to master") from e return 200, VAR_52 else: VAR_52 = await self.store.count_e2e_one_time_keys(VAR_6, VAR_7) return 200, {"one_time_key_counts": VAR_52} class CLASS_2(ContextManager[None]): def __exit__(self, VAR_8, VAR_9, VAR_10): pass VAR_1 = 10 * 1000 class CLASS_3(BasePresenceHandler): def __init__(self, VAR_4): super().__init__(VAR_4) self.hs = VAR_4 self.is_mine_id = VAR_4.is_mine_id self._presence_enabled = VAR_4.config.use_presence self._user_to_num_current_syncs = {} # type: Dict[str, int] self.notifier = VAR_4.get_notifier() self.instance_id = VAR_4.get_instance_id() self.users_going_offline = {} self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(VAR_4) self._set_state_client = ReplicationPresenceSetState.make_client(VAR_4) self._send_stop_syncing_loop = self.clock.looping_call( self.send_stop_syncing, VAR_1 ) VAR_4.get_reactor().addSystemEventTrigger( "before", "shutdown", run_as_background_process, "generic_presence.on_shutdown", self._on_shutdown, ) def FUNC_4(self): if self._presence_enabled: self.hs.get_tcp_replication().send_command( ClearUserSyncsCommand(self.instance_id) ) def FUNC_5(self, VAR_6, VAR_11, VAR_12): if self._presence_enabled: self.hs.get_tcp_replication().send_user_sync( self.instance_id, VAR_6, VAR_11, VAR_12 ) def FUNC_6(self, VAR_6): VAR_33 = self.users_going_offline.pop(VAR_6, None) if not VAR_33: self.send_user_sync(VAR_6, True, self.clock.time_msec()) def FUNC_7(self, VAR_6): self.users_going_offline[VAR_6] = self.clock.time_msec() def FUNC_8(self): VAR_34 = self.clock.time_msec() for VAR_6, VAR_12 in list(self.users_going_offline.items()): if VAR_34 - VAR_12 > VAR_1: self.users_going_offline.pop(VAR_6, None) self.send_user_sync(VAR_6, False, VAR_12) async def FUNC_9( self, VAR_6: str, VAR_13: bool ) -> ContextManager[None]: if not VAR_13 or not self._presence_enabled: return CLASS_2() VAR_35 = self._user_to_num_current_syncs.get(VAR_6, 0) self._user_to_num_current_syncs[VAR_6] = VAR_35 + 1 if self._user_to_num_current_syncs[VAR_6] == 1: self.mark_as_coming_online(VAR_6) def FUNC_31(): if VAR_6 in self._user_to_num_current_syncs: self._user_to_num_current_syncs[VAR_6] -= 1 if self._user_to_num_current_syncs[VAR_6] == 0: self.mark_as_going_offline(VAR_6) @contextlib.contextmanager def FUNC_32(): try: yield finally: FUNC_31() return FUNC_32() async def FUNC_10(self, VAR_14, VAR_15): VAR_36 = await get_interested_parties(self.store, VAR_14) VAR_37, VAR_38 = VAR_36 self.notifier.on_new_event( "presence_key", VAR_15, rooms=VAR_37.keys(), users=VAR_38.keys(), ) async def FUNC_11(self, VAR_16, VAR_17): VAR_14 = [ UserPresenceState( row.user_id, row.state, row.last_active_ts, row.last_federation_update_ts, row.last_user_sync_ts, row.status_msg, row.currently_active, ) for row in VAR_17 ] for VAR_19 in VAR_14: self.user_to_current_state[VAR_19.user_id] = VAR_19 VAR_15 = VAR_16 await self.notify_from_replication(VAR_14, VAR_15) def FUNC_12(self) -> Iterable[str]: return [ VAR_6 for VAR_6, count in self._user_to_num_current_syncs.items() if count > 0 ] async def FUNC_13(self, VAR_18, VAR_19, VAR_20=False): VAR_39 = VAR_19["presence"] VAR_40 = ( PresenceState.ONLINE, PresenceState.UNAVAILABLE, PresenceState.OFFLINE, ) if VAR_39 not in VAR_40: raise SynapseError(400, "Invalid VAR_39 state") VAR_6 = VAR_18.to_string() if not self.hs.config.use_presence: return await self._set_state_client( VAR_6=user_id, VAR_19=state, VAR_20=ignore_status_msg ) async def FUNC_14(self, VAR_21): if not self.hs.config.use_presence: return VAR_6 = VAR_21.to_string() await self._bump_active_client(VAR_6=user_id) class CLASS_4( UserDirectoryStore, StatsStore, UIAuthWorkerStore, SlavedDeviceInboxStore, SlavedDeviceStore, SlavedReceiptsStore, SlavedPushRuleStore, SlavedGroupServerStore, SlavedAccountDataStore, SlavedPusherStore, CensorEventsStore, ClientIpWorkerStore, SlavedEventStore, SlavedKeyStore, RoomStore, DirectoryStore, SlavedApplicationServiceStore, SlavedRegistrationStore, SlavedTransactionStore, SlavedProfileStore, SlavedClientIpStore, SlavedPresenceStore, SlavedFilteringStore, MonthlyActiveUsersWorkerStore, MediaRepositoryStore, ServerMetricsStore, SearchWorkerStore, TransactionWorkerStore, BaseSlavedStore, ): pass class CLASS_5(HomeServer): VAR_22 = CLASS_4 def FUNC_15(self, VAR_23: ListenerConfig): VAR_41 = VAR_23.port VAR_42 = VAR_23.bind_addresses assert VAR_23.http_options is not None VAR_43 = VAR_23.http_options.tag if VAR_43 is None: VAR_43 = VAR_41 VAR_44 = {"/health": HealthResource()} for res in VAR_23.http_options.resources: for name in res.names: if name == "metrics": VAR_44[VAR_56] = MetricsResource(RegistryProxy) elif name == "client": VAR_60 = JsonResource(self, canonical_json=False) PublicRoomListRestServlet(self).register(VAR_60) RoomMemberListRestServlet(self).register(VAR_60) JoinedRoomMemberListRestServlet(self).register(VAR_60) RoomStateRestServlet(self).register(VAR_60) RoomEventContextServlet(self).register(VAR_60) RoomMessageListRestServlet(self).register(VAR_60) RegisterRestServlet(self).register(VAR_60) LoginRestServlet(self).register(VAR_60) ThreepidRestServlet(self).register(VAR_60) KeyQueryServlet(self).register(VAR_60) KeyChangesServlet(self).register(VAR_60) VoipRestServlet(self).register(VAR_60) PushRuleRestServlet(self).register(VAR_60) VersionsRestServlet(self).register(VAR_60) RoomSendEventRestServlet(self).register(VAR_60) RoomMembershipRestServlet(self).register(VAR_60) RoomStateEventRestServlet(self).register(VAR_60) JoinRoomAliasServlet(self).register(VAR_60) ProfileAvatarURLRestServlet(self).register(VAR_60) ProfileDisplaynameRestServlet(self).register(VAR_60) ProfileRestServlet(self).register(VAR_60) CLASS_1(self).register(VAR_60) AccountDataServlet(self).register(VAR_60) RoomAccountDataServlet(self).register(VAR_60) RoomTypingRestServlet(self).register(VAR_60) sync.register_servlets(self, VAR_60) events.register_servlets(self, VAR_60) InitialSyncRestServlet(self).register(VAR_60) RoomInitialSyncRestServlet(self).register(VAR_60) user_directory.register_servlets(self, VAR_60) if not self.config.use_presence: CLASS_0(self).register(VAR_60) groups.register_servlets(self, VAR_60) VAR_44.update({CLIENT_API_PREFIX: VAR_60}) elif name == "federation": VAR_44.update({FEDERATION_PREFIX: TransportLayerServer(self)}) elif name == "media": if self.config.can_load_media_repo: VAR_63 = self.get_media_repository_resource() VAR_64 = JsonResource(self, canonical_json=False) register_servlets_for_media_repo(self, VAR_64) VAR_44.update( { MEDIA_PREFIX: VAR_63, LEGACY_MEDIA_PREFIX: VAR_63, "/_synapse/admin": VAR_64, } ) else: VAR_0.warning( "A 'media' listener is configured but the media" " repository is disabled. Ignoring." ) if name == "openid" and "federation" not in res.names: VAR_44.update( { FEDERATION_PREFIX: TransportLayerServer( self, servlet_groups=["openid"] ) } ) if name in ["keys", "federation"]: VAR_44[VAR_57] = KeyApiV2Resource(self) if name == "replication": VAR_44[VAR_58] = ReplicationRestResource(self) VAR_45 = create_resource_tree(VAR_44, OptionsResource()) _base.listen_tcp( VAR_42, VAR_41, SynapseSite( "synapse.access.http.%s" % (VAR_43,), site_tag, VAR_23, VAR_45, self.version_string, ), reactor=self.get_reactor(), ) VAR_0.info("Synapse worker VAR_34 listening on VAR_41 %d", VAR_41) def FUNC_16(self, VAR_24: Iterable[ListenerConfig]): for listener in VAR_24: if listener.type == "http": self._listen_http(listener) elif listener.type == "manhole": _base.listen_tcp( listener.bind_addresses, listener.port, manhole( username="matrix", password="rabbithole", globals={"hs": self} ), ) elif listener.type == "metrics": if not self.get_config().enable_metrics: VAR_0.warning( ( "Metrics listener configured, but " "enable_metrics is not True!" ) ) else: _base.listen_metrics(listener.bind_addresses, listener.port) else: VAR_0.warning("Unsupported listener type: %s", listener.type) self.get_tcp_replication().start_replication(self) async def FUNC_17(self, VAR_25, VAR_26, VAR_6): self.get_tcp_replication().send_remove_pusher(VAR_25, VAR_26, VAR_6) @cache_in_self def FUNC_18(self): return CLASS_6(self) @cache_in_self def FUNC_19(self): return CLASS_3(self) class CLASS_6(ReplicationDataHandler): def __init__(self, VAR_4): super().__init__(VAR_4) self.store = VAR_4.get_datastore() self.presence_handler = VAR_4.get_presence_handler() # type: CLASS_3 self.notifier = VAR_4.get_notifier() self.notify_pushers = VAR_4.config.start_pushers self.pusher_pool = VAR_4.get_pusherpool() self.send_handler = None # type: Optional[CLASS_7] if VAR_4.config.send_federation: self.send_handler = CLASS_7(VAR_4) async def FUNC_20(self, VAR_27, VAR_28, VAR_16, VAR_17): await super().on_rdata(VAR_27, VAR_28, VAR_16, VAR_17) await self._process_and_notify(VAR_27, VAR_28, VAR_16, VAR_17) async def FUNC_21(self, VAR_27, VAR_28, VAR_16, VAR_17): try: if self.send_handler: await self.send_handler.process_replication_rows( VAR_27, VAR_16, VAR_17 ) if VAR_27 == PushRulesStream.NAME: self.notifier.on_new_event( "push_rules_key", VAR_16, users=[row.user_id for row in VAR_17] ) elif VAR_27 in (AccountDataStream.NAME, TagAccountDataStream.NAME): self.notifier.on_new_event( "account_data_key", VAR_16, users=[row.user_id for row in VAR_17] ) elif VAR_27 == ReceiptsStream.NAME: self.notifier.on_new_event( "receipt_key", VAR_16, rooms=[row.room_id for row in VAR_17] ) await self.pusher_pool.on_new_receipts( VAR_16, VAR_16, {row.room_id for row in VAR_17} ) elif VAR_27 == ToDeviceStream.NAME: VAR_61 = [row.entity for row in VAR_17 if row.entity.startswith("@")] if VAR_61: self.notifier.on_new_event("to_device_key", VAR_16, users=VAR_61) elif VAR_27 == DeviceListsStream.NAME: VAR_62 = set() # type: Set[str] for row in VAR_17: if row.entity.startswith("@"): VAR_65 = await self.store.get_rooms_for_user(row.entity) VAR_62.update(VAR_65) self.notifier.on_new_event("device_list_key", VAR_16, rooms=VAR_62) elif VAR_27 == PresenceStream.NAME: await self.presence_handler.process_replication_rows(VAR_16, VAR_17) elif VAR_27 == GroupServerStream.NAME: self.notifier.on_new_event( "groups_key", VAR_16, users=[row.user_id for row in VAR_17] ) elif VAR_27 == PushersStream.NAME: for row in VAR_17: if row.deleted: self.stop_pusher(row.user_id, row.app_id, row.pushkey) else: await self.start_pusher(row.user_id, row.app_id, row.pushkey) except Exception: VAR_0.exception("Error processing replication") async def FUNC_22(self, VAR_27: str, VAR_28: str, VAR_16: int): await super().on_position(VAR_27, VAR_28, VAR_16) await self.on_rdata(VAR_27, VAR_28, VAR_16, []) def FUNC_23(self, VAR_6, VAR_25, VAR_29): if not self.notify_pushers: return VAR_46 = "%s:%s" % (VAR_25, VAR_29) VAR_47 = self.pusher_pool.pushers.get(VAR_6, {}) VAR_48 = VAR_47.pop(VAR_46, None) if VAR_48 is None: return VAR_0.info("Stopping VAR_48 %r / %r", VAR_6, VAR_46) VAR_48.on_stop() async def FUNC_24(self, VAR_6, VAR_25, VAR_29): if not self.notify_pushers: return VAR_46 = "%s:%s" % (VAR_25, VAR_29) VAR_0.info("Starting VAR_48 %r / %r", VAR_6, VAR_46) return await self.pusher_pool.start_pusher_by_id(VAR_25, VAR_29, VAR_6) def FUNC_25(self, VAR_30: str): if self.send_handler: self.send_handler.wake_destination(VAR_30) class CLASS_7: def __init__(self, VAR_4: CLASS_5): self.store = VAR_4.get_datastore() self._is_mine_id = VAR_4.is_mine_id self.federation_sender = VAR_4.get_federation_sender() self._hs = VAR_4 self.federation_position = None self._fed_position_linearizer = Linearizer(name="_fed_position_linearizer") def FUNC_26(self): self.federation_sender.notify_new_events( self.store.get_room_max_stream_ordering() ) def FUNC_27(self, VAR_30: str): self.federation_sender.wake_destination(VAR_30) async def FUNC_11(self, VAR_27, VAR_16, VAR_17): if VAR_27 == "federation": send_queue.process_rows_for_federation(self.federation_sender, VAR_17) await self.update_token(VAR_16) elif VAR_27 == ReceiptsStream.NAME: await self._on_new_receipts(VAR_17) elif VAR_27 == DeviceListsStream.NAME: VAR_59 = {row.entity for row in VAR_17 if not row.entity.startswith("@")} for host in VAR_59: self.federation_sender.send_device_messages(host) elif VAR_27 == ToDeviceStream.NAME: VAR_59 = {row.entity for row in VAR_17 if not row.entity.startswith("@")} for host in VAR_59: self.federation_sender.send_device_messages(host) async def FUNC_28(self, VAR_17): for receipt in VAR_17: if not self._is_mine_id(receipt.user_id): continue VAR_53 = ReadReceipt( receipt.room_id, receipt.receipt_type, receipt.user_id, [receipt.event_id], receipt.data, ) await self.federation_sender.send_read_receipt(VAR_53) async def FUNC_29(self, VAR_16): self.federation_position = VAR_16 if self._fed_position_linearizer.is_queued(None): return run_as_background_process("_save_and_send_ack", self._save_and_send_ack) async def FUNC_30(self): try: with (await self._fed_position_linearizer.queue(None)): VAR_55 = self.federation_position await self.store.update_federation_out_pos( "federation", VAR_55 ) self._hs.get_tcp_replication().send_federation_ack(VAR_55) except Exception: VAR_0.exception("Error updating federation stream position") def FUNC_0(VAR_2): try: VAR_49 = HomeServerConfig.load_config("Synapse worker", VAR_2) except ConfigError as e: sys.stderr.write("\n" + str(e) + "\n") sys.exit(1) assert VAR_49.worker_app in ( "synapse.app.appservice", "synapse.app.client_reader", "synapse.app.event_creator", "synapse.app.federation_reader", "synapse.app.federation_sender", "synapse.app.frontend_proxy", "synapse.app.generic_worker", "synapse.app.media_repository", "synapse.app.pusher", "synapse.app.synchrotron", "synapse.app.user_dir", ) if VAR_49.worker_app == "synapse.app.appservice": if VAR_49.appservice.notify_appservices: sys.stderr.write( "\nThe appservices must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``notify_appservices: false`` to the main config" "\n" ) sys.exit(1) VAR_49.appservice.notify_appservices = True else: VAR_49.appservice.notify_appservices = False if VAR_49.worker_app == "synapse.app.pusher": if VAR_49.server.start_pushers: sys.stderr.write( "\nThe pushers must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``start_pushers: false`` to the main config" "\n" ) sys.exit(1) VAR_49.server.start_pushers = True else: VAR_49.server.start_pushers = False if VAR_49.worker_app == "synapse.app.user_dir": if VAR_49.server.update_user_directory: sys.stderr.write( "\nThe update_user_directory must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``update_user_directory: false`` to the main config" "\n" ) sys.exit(1) VAR_49.server.update_user_directory = True else: VAR_49.server.update_user_directory = False if VAR_49.worker_app == "synapse.app.federation_sender": if VAR_49.worker.send_federation: sys.stderr.write( "\nThe send_federation must be disabled in the main synapse process" "\nbefore they can be run in a separate worker." "\nPlease add ``send_federation: false`` to the main config" "\n" ) sys.exit(1) VAR_49.worker.send_federation = True else: VAR_49.worker.send_federation = False synapse.events.USE_FROZEN_DICTS = VAR_49.use_frozen_dicts VAR_4 = CLASS_5( VAR_49.server_name, VAR_49=config, version_string="Synapse/" + get_version_string(synapse), ) setup_logging(VAR_4, VAR_49, use_worker_options=True) VAR_4.setup() VAR_4.get_replication_streamer() reactor.addSystemEventTrigger( "before", "startup", _base.start, VAR_4, VAR_49.worker_listeners ) _base.start_worker_reactor("synapse-generic-worker", VAR_49) if __name__ == "__main__": with LoggingContext("main"): FUNC_0(sys.argv[1:])
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 23, 25, 147, 149, 150, 155, 157, 161, 165, 169, 170, 175, 177, 188, 193, 195, 196, 206, 211, 213, 214, 215, 216, 217, 222, 228, 229, 237, 246, 249, 252, 253, 256, 259, 260, 262, 263, 270, 272, 273, 274, 276, 279, 280, 281, 283, 286, 290, 298, 304, 310, 314, 320, 322, 328, 333, 343, 348, 354, 357, 358, 361, 363, 364, 365, 368, 369, 372, 379, 381, 385, 392, 406, 409, 412, 419, 424, 432, 434, 435, 438, 439, 443, 448, 451, 452, 455, 456, 458, 459, 491, 492, 495, 499, 501, 505, 506, 508, 515, 541, 546, 548, 549, 550, 553, 555, 562, 563, 564, 567, 580, 582, 583, 584, 592, 595, 598, 600, 613, 615, 640, 642, 645, 649, 653, 654, 658, 662, 665, 669, 673, 680, 721, 724, 726, 730, 738, 742, 746, 749, 750, 751, 754, 755, 758, 763, 769, 770, 771, 773, 775, 777, 778, 782, 785, 787, 788, 792, 793, 796, 797, 799, 800, 801, 805, 807, 808, 809, 813, 821, 832, 835, 841, 842, 843, 844, 845, 847, 848, 850, 852, 858, 859, 860, 861, 862, 863, 864, 865, 867, 868, 870, 874, 875, 876, 880, 881, 888, 889, 903, 913, 914, 917, 919, 929, 930, 933, 935, 945, 946, 949, 951, 961, 962, 965, 967, 969, 975, 977, 979, 980, 981, 983, 987, 989, 990, 994, 152, 153, 154, 172, 173, 174, 255, 757, 758, 759, 760, 761, 762, 179, 180, 181, 182, 312, 313, 314, 315, 316, 317, 324, 325, 326, 327, 328, 329, 330, 331, 335, 336, 337, 347, 348, 349, 350, 351, 421, 422, 445, 446, 447, 748, 815, 816, 817, 818, 819, 834, 835, 836, 837, 838, 839, 854, 855, 856 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 23, 25, 147, 149, 150, 155, 157, 161, 165, 169, 170, 175, 177, 188, 193, 195, 196, 206, 211, 213, 214, 215, 216, 217, 222, 228, 229, 237, 246, 249, 252, 253, 256, 259, 260, 262, 263, 269, 271, 272, 273, 275, 278, 279, 280, 282, 285, 289, 297, 303, 309, 313, 319, 321, 327, 332, 342, 347, 353, 356, 357, 360, 362, 363, 364, 367, 368, 371, 378, 380, 384, 391, 405, 408, 411, 418, 423, 431, 433, 434, 437, 438, 442, 447, 450, 451, 454, 455, 457, 458, 490, 491, 494, 498, 500, 504, 505, 507, 514, 540, 545, 547, 548, 549, 552, 554, 561, 562, 563, 566, 579, 581, 582, 583, 591, 594, 597, 599, 612, 614, 639, 641, 644, 648, 652, 653, 657, 661, 664, 668, 672, 679, 720, 723, 725, 729, 737, 741, 745, 748, 749, 750, 753, 754, 757, 762, 768, 769, 770, 772, 774, 776, 777, 781, 784, 786, 787, 791, 792, 795, 796, 798, 799, 800, 804, 806, 807, 808, 812, 820, 831, 834, 840, 841, 842, 843, 844, 846, 847, 849, 851, 857, 858, 859, 860, 861, 862, 863, 864, 866, 867, 869, 873, 874, 875, 879, 880, 887, 888, 902, 912, 913, 916, 918, 928, 929, 932, 934, 944, 945, 948, 950, 960, 961, 964, 966, 968, 974, 976, 978, 979, 980, 982, 986, 988, 989, 993, 152, 153, 154, 172, 173, 174, 255, 756, 757, 758, 759, 760, 761, 179, 180, 181, 182, 311, 312, 313, 314, 315, 316, 323, 324, 325, 326, 327, 328, 329, 330, 334, 335, 336, 346, 347, 348, 349, 350, 420, 421, 444, 445, 446, 747, 814, 815, 816, 817, 818, 833, 834, 835, 836, 837, 838, 853, 854, 855 ]
0CWE-22
# -*- coding: utf-8 -*- ############################################################################## # 2011 E2OpenPlugins # # # # This file is open source software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License version 2 as # # published by the Free Software Foundation. # # # ############################################################################## import os import re import glob from urllib import quote import json from twisted.web import static, resource, http from Components.config import config from Tools.Directories import fileExists def new_getRequestHostname(self): host = self.getHeader(b'host') if host: if host[0]=='[': return host.split(']',1)[0] + "]" return host.split(':', 1)[0].encode('ascii') return self.getHost().host.encode('ascii') http.Request.getRequestHostname = new_getRequestHostname class FileController(resource.Resource): def render(self, request): action = "download" if "action" in request.args: action = request.args["action"][0] if "file" in request.args: filename = request.args["file"][0].decode('utf-8', 'ignore').encode('utf-8') filename = re.sub("^/+", "/", os.path.realpath(filename)) if not os.path.exists(filename): return "File '%s' not found" % (filename) if action == "stream": name = "stream" if "name" in request.args: name = request.args["name"][0] port = config.OpenWebif.port.value proto = 'http' if request.isSecure(): port = config.OpenWebif.https_port.value proto = 'https' ourhost = request.getHeader('host') m = re.match('.+\:(\d+)$', ourhost) if m is not None: port = m.group(1) response = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?action=download&file=%s" % (name, proto, request.getRequestHostname(), port, quote(filename)) request.setHeader("Content-Disposition", 'attachment;filename="%s.m3u"' % name) request.setHeader("Content-Type", "application/x-mpegurl") return response elif action == "delete": request.setResponseCode(http.OK) return "TODO: DELETE FILE: %s" % (filename) elif action == "download": request.setHeader("Content-Disposition", "attachment;filename=\"%s\"" % (filename.split('/')[-1])) rfile = static.File(filename, defaultType = "application/octet-stream") return rfile.render(request) else: return "wrong action parameter" if "dir" in request.args: path = request.args["dir"][0] pattern = '*' data = [] if "pattern" in request.args: pattern = request.args["pattern"][0] directories = [] files = [] if fileExists(path): try: files = glob.glob(path+'/'+pattern) except: files = [] files.sort() tmpfiles = files[:] for x in tmpfiles: if os.path.isdir(x): directories.append(x + '/') files.remove(x) data.append({"result": True,"dirs": directories,"files": files}) else: data.append({"result": False,"message": "path %s not exits" % (path)}) request.setHeader("content-type", "application/json; charset=utf-8") return json.dumps(data, indent=2)
# -*- coding: utf-8 -*- ############################################################################## # 2011 E2OpenPlugins # # # # This file is open source software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License version 2 as # # published by the Free Software Foundation. # # # ############################################################################## import os import re import glob from urllib import quote import json from twisted.web import static, resource, http from Components.config import config from Tools.Directories import fileExists from utilities import lenient_force_utf_8, sanitise_filename_slashes def new_getRequestHostname(self): host = self.getHeader(b'host') if host: if host[0]=='[': return host.split(']',1)[0] + "]" return host.split(':', 1)[0].encode('ascii') return self.getHost().host.encode('ascii') http.Request.getRequestHostname = new_getRequestHostname class FileController(resource.Resource): def render(self, request): action = "download" if "action" in request.args: action = request.args["action"][0] if "file" in request.args: filename = lenient_force_utf_8(request.args["file"][0]) filename = sanitise_filename_slashes(os.path.realpath(filename)) if not os.path.exists(filename): return "File '%s' not found" % (filename) if action == "stream": name = "stream" if "name" in request.args: name = request.args["name"][0] port = config.OpenWebif.port.value proto = 'http' if request.isSecure(): port = config.OpenWebif.https_port.value proto = 'https' ourhost = request.getHeader('host') m = re.match('.+\:(\d+)$', ourhost) if m is not None: port = m.group(1) response = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?action=download&file=%s" % (name, proto, request.getRequestHostname(), port, quote(filename)) request.setHeader("Content-Disposition", 'attachment;filename="%s.m3u"' % name) request.setHeader("Content-Type", "application/x-mpegurl") return response elif action == "delete": request.setResponseCode(http.OK) return "TODO: DELETE FILE: %s" % (filename) elif action == "download": request.setHeader("Content-Disposition", "attachment;filename=\"%s\"" % (filename.split('/')[-1])) rfile = static.File(filename, defaultType = "application/octet-stream") return rfile.render(request) else: return "wrong action parameter" if "dir" in request.args: path = request.args["dir"][0] pattern = '*' data = [] if "pattern" in request.args: pattern = request.args["pattern"][0] directories = [] files = [] if fileExists(path): try: files = glob.glob(path+'/'+pattern) except: files = [] files.sort() tmpfiles = files[:] for x in tmpfiles: if os.path.isdir(x): directories.append(x + '/') files.remove(x) data.append({"result": True,"dirs": directories,"files": files}) else: data.append({"result": False,"message": "path %s not exits" % (path)}) request.setHeader("content-type", "application/json; charset=utf-8") return json.dumps(data, indent=2)
path_disclosure
{ "code": [ "\t\t\tfilename = request.args[\"file\"][0].decode('utf-8', 'ignore').encode('utf-8')", "\t\t\tfilename = re.sub(\"^/+\", \"/\", os.path.realpath(filename))" ], "line_no": [ 41, 42 ] }
{ "code": [ "\t\t\tfilename = lenient_force_utf_8(request.args[\"file\"][0])", "\t\t\tfilename = sanitise_filename_slashes(os.path.realpath(filename))" ], "line_no": [ 43, 44 ] }
import os import re import glob from urllib import quote import json from twisted.web import static, resource, http from Components.config import config from Tools.Directories import fileExists def FUNC_0(self): VAR_0 = self.getHeader(b'host') if VAR_0: if VAR_0[0]=='[': return VAR_0.split(']',1)[0] + "]" return VAR_0.split(':', 1)[0].encode('ascii') return self.getHost().host.encode('ascii') http.Request.getRequestHostname = FUNC_0 class CLASS_0(resource.Resource): def FUNC_1(self, VAR_1): VAR_2 = "download" if "action" in VAR_1.args: VAR_2 = VAR_1.args["action"][0] if "file" in VAR_1.args: VAR_3 = VAR_1.args["file"][0].decode('utf-8', 'ignore').encode('utf-8') VAR_3 = re.sub("^/+", "/", os.path.realpath(VAR_3)) if not os.path.exists(VAR_3): return "File '%s' not found" % (VAR_3) if VAR_2 == "stream": VAR_9 = "stream" if "name" in VAR_1.args: VAR_9 = VAR_1.args["name"][0] VAR_10 = config.OpenWebif.port.value VAR_11 = 'http' if VAR_1.isSecure(): VAR_10 = config.OpenWebif.https_port.value VAR_11 = 'https' VAR_12 = VAR_1.getHeader('host') VAR_13 = re.match('.+\:(\d+)$', VAR_12) if VAR_13 is not None: VAR_10 = VAR_13.group(1) VAR_14 = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?VAR_2=download&file=%s" % (VAR_9, VAR_11, VAR_1.getRequestHostname(), VAR_10, quote(VAR_3)) VAR_1.setHeader("Content-Disposition", 'attachment;VAR_3="%s.m3u"' % VAR_9) VAR_1.setHeader("Content-Type", "application/x-mpegurl") return VAR_14 elif VAR_2 == "delete": VAR_1.setResponseCode(http.OK) return "TODO: DELETE FILE: %s" % (VAR_3) elif VAR_2 == "download": VAR_1.setHeader("Content-Disposition", "attachment;VAR_3=\"%s\"" % (VAR_3.split('/')[-1])) VAR_16 = static.File(VAR_3, defaultType = "application/octet-stream") return VAR_16.render(VAR_1) else: return "wrong VAR_2 parameter" if "dir" in VAR_1.args: VAR_4 = VAR_1.args["dir"][0] VAR_5 = '*' VAR_6 = [] if "pattern" in VAR_1.args: VAR_5 = VAR_1.args["pattern"][0] VAR_7 = [] VAR_8 = [] if fileExists(VAR_4): try: VAR_8 = glob.glob(VAR_4+'/'+VAR_5) except: VAR_8 = [] files.sort() VAR_15 = VAR_8[:] for x in VAR_15: if os.path.isdir(x): VAR_7.append(x + '/') VAR_8.remove(x) VAR_6.append({"result": True,"dirs": VAR_7,"files": VAR_8}) else: VAR_6.append({"result": False,"message": "path %s not exits" % (VAR_4)}) VAR_1.setHeader("content-type", "application/json; charset=utf-8") return json.dumps(VAR_6, indent=2)
import os import re import glob from urllib import quote import json from twisted.web import static, resource, http from Components.config import config from Tools.Directories import fileExists from utilities import lenient_force_utf_8, sanitise_filename_slashes def FUNC_0(self): VAR_0 = self.getHeader(b'host') if VAR_0: if VAR_0[0]=='[': return VAR_0.split(']',1)[0] + "]" return VAR_0.split(':', 1)[0].encode('ascii') return self.getHost().host.encode('ascii') http.Request.getRequestHostname = FUNC_0 class CLASS_0(resource.Resource): def FUNC_1(self, VAR_1): VAR_2 = "download" if "action" in VAR_1.args: VAR_2 = VAR_1.args["action"][0] if "file" in VAR_1.args: VAR_3 = lenient_force_utf_8(VAR_1.args["file"][0]) VAR_3 = sanitise_filename_slashes(os.path.realpath(VAR_3)) if not os.path.exists(VAR_3): return "File '%s' not found" % (VAR_3) if VAR_2 == "stream": VAR_9 = "stream" if "name" in VAR_1.args: VAR_9 = VAR_1.args["name"][0] VAR_10 = config.OpenWebif.port.value VAR_11 = 'http' if VAR_1.isSecure(): VAR_10 = config.OpenWebif.https_port.value VAR_11 = 'https' VAR_12 = VAR_1.getHeader('host') VAR_13 = re.match('.+\:(\d+)$', VAR_12) if VAR_13 is not None: VAR_10 = VAR_13.group(1) VAR_14 = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?VAR_2=download&file=%s" % (VAR_9, VAR_11, VAR_1.getRequestHostname(), VAR_10, quote(VAR_3)) VAR_1.setHeader("Content-Disposition", 'attachment;VAR_3="%s.m3u"' % VAR_9) VAR_1.setHeader("Content-Type", "application/x-mpegurl") return VAR_14 elif VAR_2 == "delete": VAR_1.setResponseCode(http.OK) return "TODO: DELETE FILE: %s" % (VAR_3) elif VAR_2 == "download": VAR_1.setHeader("Content-Disposition", "attachment;VAR_3=\"%s\"" % (VAR_3.split('/')[-1])) VAR_16 = static.File(VAR_3, defaultType = "application/octet-stream") return VAR_16.render(VAR_1) else: return "wrong VAR_2 parameter" if "dir" in VAR_1.args: VAR_4 = VAR_1.args["dir"][0] VAR_5 = '*' VAR_6 = [] if "pattern" in VAR_1.args: VAR_5 = VAR_1.args["pattern"][0] VAR_7 = [] VAR_8 = [] if fileExists(VAR_4): try: VAR_8 = glob.glob(VAR_4+'/'+VAR_5) except: VAR_8 = [] files.sort() VAR_15 = VAR_8[:] for x in VAR_15: if os.path.isdir(x): VAR_7.append(x + '/') VAR_8.remove(x) VAR_6.append({"result": True,"dirs": VAR_7,"files": VAR_8}) else: VAR_6.append({"result": False,"message": "path %s not exits" % (VAR_4)}) VAR_1.setHeader("content-type", "application/json; charset=utf-8") return json.dumps(VAR_6, indent=2)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 17, 19, 22, 30, 32, 33, 39, 43, 46, 51, 61, 75, 100 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 17, 19, 23, 24, 32, 34, 35, 41, 45, 48, 53, 63, 77, 102 ]
0CWE-22
import ast import base64 import io import logging import random from html import escape from os import remove import magic from flask import Flask, abort, request from PIL import Image app = Flask(__name__) app.logger.setLevel(logging.DEBUG) app.config["MAX_CONTENT_LENGTH"] = 2 * (10**5) # allow a maximum of 200kb length. no image is (usually) larger than 200kb, so this is good. def get_config(): f = open("config", "r") conf = ast.literal_eval(f.read()) f.close() cache_size = conf["max_cache_size"] host = conf["host"] port = conf["port"] return cache_size, host, port def allowed_file(enc_data): mimetype = magic.from_buffer(enc_data, mime=True) if mimetype[:5] != "image": return enc_data, False else: return enc_data, True @app.route("/") def index(): return "<h1>401 - Unauthorised</h1>" @app.errorhandler(404) def errorhandle(e): return abort(401) @app.route("/Y2hlY2tfY2FjaGVkX2ZpbGVz", methods=["POST"]) def check_cache(): # Explanation on Caching # -- BV # Originally, I was going to have the script cache here, where it actually checks the cache. However, # I soon realised that the all_files file is only modified in the other function to add to the file. # Because of this, we only really need to check the cache status there, and see if it is over the # cache limit in that function. The only thing we have to do here in relation to caching is moving items # to the end of the array. f = open("all_files", "r") db = ast.literal_eval(f.read()) f.close() tmp = request.json x = str({"title": tmp["title"], "singer": tmp["singer"], "album": tmp["album"]}) data = ast.literal_eval(x) if data["title"][:9] == "[PAUSED] ": data["title"] = data["title"][9::] del tmp if type(data) != dict: typeprov = type(data) print( "Not provided a dict, instead a " + str(typeprov) + " was provided. Returning NoneType." ) return "None" for key in db: print(f"Analysing data {data} against item(s) {key[0]}.") if data == key[0]: print("Found match for " + str(data) + " in database.") # caching new_data = [] for y in db: if y[0] == data: x = y else: new_data.append(y) new_data.append(x) f = open("all_files", "w") f.write(str(new_data)) f.close() print("Returning dictionary: " + str(key)) return str(key) print("No match found. Returning NoneType.") return "None" @app.route("/bGVhdmVfcmlnaHRfbm93", methods=["POST"]) def uploadimage(): # print(request.json) if not request.json or "image" not in request.json: print("No data sent or no image provided. Aborting with 400.") abort(400) im_b64 = request.json["image"] img_bytes = base64.b64decode(im_b64.encode("utf-8")) img_bytes, valid = allowed_file(img_bytes) if not valid: return escape({"entry": "False"}) img = Image.open(io.BytesIO(img_bytes)) file_ending = img.format print(f"File has filetype {file_ending}.") if file_ending == "JPEG": file_ending = ".jpg" else: file_ending = ".png" one_hundred_million = 100000000 lots_of_nine = 999999999 file_name = None f = open("all_files", "r") all_files = ast.literal_eval(f.read()) f.close() attempt = 0 while file_name is None or file_name in all_files: if attempt <= 1000: file_name = random.randint(one_hundred_million, lots_of_nine) file_name = base64.b64encode(str(file_name).encode("utf-8")).decode("utf-8") print(f"Trying new file name: {file_name}") else: attempt = 0 one_hundred_million += 100000 lots_of_nine += 1000000 while one_hundred_million >= lots_of_nine: one_hundred_million -= 10000 one_hundred_million -= 10000 print(f"Successful file name: {file_name}") title = request.json["title"] if title[:9] == "[PAUSED] ": title = title[9::] singer = request.json["singer"] album = request.json["album"] file_db_entry = [ {"title": title, "singer": singer, "album": album}, file_name, file_ending, ] print(f"New db entry: {file_db_entry}") all_files.append(file_db_entry) # caching # we want a limit of X amount of files as defined by the config # 1. see how long the list is # 2. if it is over get_config()'s cache limit, delete value [0] # 3. delete it on disk. cache, x, y = get_config() del x del y length = len(all_files) while ( length > cache ): # if it is not over the limit, it will skip. if it is, it does this. # if we have gone over our cache limit, let's delete the first entry. filename = all_files[0][1] + all_files[0][2] remove(filename) del all_files[0] length = len(all_files) f = open("all_files", "w") f.write(str(all_files)) f.close() file_name = file_name + file_ending img.save(file_name) print(f"Saved {file_name} from {file_db_entry}.") print(f"Returning {file_db_entry}.") return escape(str({"entry": file_db_entry})) def run_server_api(): cache, host, port = get_config() app.run(host=host, port=port) if __name__ == "__main__": run_server_api()
import ast import base64 import io import logging import random from html import escape from os import remove import werkzeug.utils import magic from flask import Flask, abort, request from PIL import Image app = Flask(__name__) app.logger.setLevel(logging.DEBUG) app.config["MAX_CONTENT_LENGTH"] = 2 * (10**5) # allow a maximum of 200kb length. no image is (usually) larger than 200kb, so this is good. def get_config(): f = open("config", "r") conf = ast.literal_eval(f.read()) f.close() cache_size = conf["max_cache_size"] host = conf["host"] port = conf["port"] return cache_size, host, port def allowed_file(enc_data): mimetype = magic.from_buffer(enc_data, mime=True) if mimetype[:5] != "image": return enc_data, False else: return enc_data, True @app.route("/") def index(): return "<h1>401 - Unauthorised</h1>" @app.errorhandler(404) def errorhandle(e): return abort(401) @app.route("/Y2hlY2tfY2FjaGVkX2ZpbGVz", methods=["POST"]) def check_cache(): # Explanation on Caching # -- BV # Originally, I was going to have the script cache here, where it actually checks the cache. However, # I soon realised that the all_files file is only modified in the other function to add to the file. # Because of this, we only really need to check the cache status there, and see if it is over the # cache limit in that function. The only thing we have to do here in relation to caching is moving items # to the end of the array. f = open("all_files", "r") db = ast.literal_eval(f.read()) f.close() tmp = request.json x = str({"title": tmp["title"], "singer": tmp["singer"], "album": tmp["album"]}) data = ast.literal_eval(x) if data["title"][:9] == "[PAUSED] ": data["title"] = data["title"][9::] del tmp if type(data) != dict: typeprov = type(data) print( "Not provided a dict, instead a " + str(typeprov) + " was provided. Returning NoneType." ) return "None" for key in db: print(f"Analysing data {data} against item(s) {key[0]}.") if data == key[0]: print("Found match for " + str(data) + " in database.") # caching new_data = [] for y in db: if y[0] == data: x = y else: new_data.append(y) new_data.append(x) f = open("all_files", "w") f.write(str(new_data)) f.close() print("Returning dictionary: " + str(key)) return str(key) print("No match found. Returning NoneType.") return "None" @app.route("/bGVhdmVfcmlnaHRfbm93", methods=["POST"]) def uploadimage(): # print(request.json) if not request.json or "image" not in request.json: print("No data sent or no image provided. Aborting with 400.") abort(400) im_b64 = request.json["image"] img_bytes = base64.b64decode(im_b64.encode("utf-8")) img_bytes, valid = allowed_file(img_bytes) if not valid: return escape({"entry": "False"}) img = Image.open(io.BytesIO(img_bytes)) file_ending = img.format print(f"File has filetype {file_ending}.") if file_ending == "JPEG": file_ending = ".jpg" else: file_ending = ".png" one_hundred_million = 100000000 lots_of_nine = 999999999 file_name = None f = open("all_files", "r") all_files = ast.literal_eval(f.read()) f.close() attempt = 0 while file_name is None or file_name in all_files: if attempt <= 1000: file_name = random.randint(one_hundred_million, lots_of_nine) file_name = base64.b64encode(str(file_name).encode("utf-8")).decode("utf-8") print(f"Trying new file name: {file_name}") else: attempt = 0 one_hundred_million += 100000 lots_of_nine += 1000000 while one_hundred_million >= lots_of_nine: one_hundred_million -= 10000 one_hundred_million -= 10000 print(f"Successful file name: {file_name}") title = request.json["title"] if title[:9] == "[PAUSED] ": title = title[9::] singer = request.json["singer"] album = request.json["album"] file_db_entry = [ {"title": title, "singer": singer, "album": album}, file_name, file_ending, ] print(f"New db entry: {file_db_entry}") all_files.append(file_db_entry) # caching # we want a limit of X amount of files as defined by the config # 1. see how long the list is # 2. if it is over get_config()'s cache limit, delete value [0] # 3. delete it on disk. cache, x, y = get_config() del x del y length = len(all_files) while ( length > cache ): # if it is not over the limit, it will skip. if it is, it does this. # if we have gone over our cache limit, let's delete the first entry. filename = all_files[0][1] + all_files[0][2] remove(werkzeug.utils.secure_filename(filename)) del all_files[0] length = len(all_files) f = open("all_files", "w") f.write(str(all_files)) f.close() file_name = file_name + file_ending img.save(file_name) print(f"Saved {file_name} from {file_db_entry}.") print(f"Returning {file_db_entry}.") return escape(str({"entry": file_db_entry})) def run_server_api(): cache, host, port = get_config() app.run(host=host, port=port) if __name__ == "__main__": run_server_api()
path_disclosure
{ "code": [ " remove(filename)" ], "line_no": [ 192 ] }
{ "code": [ " remove(werkzeug.utils.secure_filename(filename))" ], "line_no": [ 192 ] }
import ast import base64 import io import logging import random from html import .escape from os import remove import magic from flask import Flask, abort, request from PIL import Image VAR_0 = Flask(__name__) VAR_0.logger.setLevel(logging.DEBUG) VAR_0.config["MAX_CONTENT_LENGTH"] = 2 * (10**5) def FUNC_0(): VAR_3 = open("config", "r") VAR_4 = ast.literal_eval(VAR_3.read()) VAR_3.close() VAR_5 = VAR_4["max_cache_size"] VAR_6 = VAR_4["host"] VAR_7 = VAR_4["port"] return VAR_5, VAR_6, VAR_7 def FUNC_1(VAR_1): VAR_8 = magic.from_buffer(VAR_1, mime=True) if VAR_8[:5] != "image": return VAR_1, False else: return VAR_1, True @VAR_0.route("/") def FUNC_2(): return "<h1>401 - Unauthorised</h1>" @VAR_0.errorhandler(404) def FUNC_3(VAR_2): return abort(401) @VAR_0.route("/Y2hlY2tfY2FjaGVkX2ZpbGVz", methods=["POST"]) def FUNC_4(): VAR_3 = open("all_files", "r") VAR_9 = ast.literal_eval(VAR_3.read()) VAR_3.close() VAR_10 = request.json VAR_11 = str({"title": VAR_10["title"], "singer": VAR_10["singer"], "album": VAR_10["album"]}) VAR_12 = ast.literal_eval(VAR_11) if VAR_12["title"][:9] == "[PAUSED] ": VAR_12["title"] = VAR_12["title"][9::] del VAR_10 if type(VAR_12) != dict: VAR_30 = type(VAR_12) print( "Not provided a dict, instead a " + str(VAR_30) + " was provided. Returning NoneType." ) return "None" for key in VAR_9: print(f"Analysing VAR_12 {data} against item(s) {key[0]}.") if VAR_12 == key[0]: print("Found match for " + str(VAR_12) + " in database.") VAR_32 = [] for VAR_28 in VAR_9: if VAR_28[0] == VAR_12: VAR_11 = VAR_28 else: VAR_32.append(VAR_28) VAR_32.append(VAR_11) VAR_3 = open("all_files", "w") VAR_3.write(str(VAR_32)) VAR_3.close() print("Returning dictionary: " + str(key)) return str(key) print("No match found. Returning NoneType.") return "None" @VAR_0.route("/bGVhdmVfcmlnaHRfbm93", methods=["POST"]) def FUNC_5(): if not request.json or "image" not in request.json: print("No VAR_12 sent or no image provided. Aborting with 400.") abort(400) VAR_13 = request.json["image"] VAR_14 = base64.b64decode(VAR_13.encode("utf-8")) VAR_14, VAR_15 = FUNC_1(VAR_14) if not VAR_15: return escape({"entry": "False"}) VAR_16 = Image.open(io.BytesIO(VAR_14)) VAR_17 = VAR_16.format print(f"File has filetype {VAR_17}.") if VAR_17 == "JPEG": VAR_17 = ".jpg" else: VAR_17 = ".png" VAR_18 = 100000000 VAR_19 = 999999999 VAR_20 = None VAR_3 = open("all_files", "r") VAR_21 = ast.literal_eval(VAR_3.read()) VAR_3.close() VAR_22 = 0 while VAR_20 is None or VAR_20 in VAR_21: if VAR_22 <= 1000: VAR_20 = random.randint(VAR_18, VAR_19) VAR_20 = base64.b64encode(str(VAR_20).encode("utf-8")).decode("utf-8") print(f"Trying new file name: {VAR_20}") else: VAR_22 = 0 VAR_18 += 100000 VAR_19 += 1000000 while VAR_18 >= VAR_19: VAR_18 -= 10000 VAR_18 -= 10000 print(f"Successful file name: {VAR_20}") VAR_23 = request.json["title"] if VAR_23[:9] == "[PAUSED] ": VAR_23 = title[9::] VAR_24 = request.json["singer"] VAR_25 = request.json["album"] VAR_26 = [ {"title": VAR_23, "singer": VAR_24, "album": VAR_25}, VAR_20, VAR_17, ] print(f"New VAR_9 entry: {VAR_26}") VAR_21.append(VAR_26) VAR_27, VAR_11, VAR_28 = FUNC_0() del VAR_11 del VAR_28 VAR_29 = len(VAR_21) while ( VAR_29 > VAR_27 ): # if it is not over the limit, it will skip. if it is, it does this. VAR_31 = VAR_21[0][1] + VAR_21[0][2] remove(VAR_31) del VAR_21[0] VAR_29 = len(VAR_21) VAR_3 = open("all_files", "w") VAR_3.write(str(VAR_21)) VAR_3.close() VAR_20 = VAR_20 + VAR_17 VAR_16.save(VAR_20) print(f"Saved {VAR_20} from {VAR_26}.") print(f"Returning {VAR_26}.") return escape(str({"entry": VAR_26})) def FUNC_6(): VAR_27, VAR_6, VAR_7 = FUNC_0() VAR_0.run(VAR_6=host, VAR_7=port) if __name__ == "__main__": FUNC_6()
import ast import base64 import io import logging import random from html import .escape from os import remove import werkzeug.utils import magic from flask import Flask, abort, request from PIL import Image VAR_0 = Flask(__name__) VAR_0.logger.setLevel(logging.DEBUG) VAR_0.config["MAX_CONTENT_LENGTH"] = 2 * (10**5) def FUNC_0(): VAR_3 = open("config", "r") VAR_4 = ast.literal_eval(VAR_3.read()) VAR_3.close() VAR_5 = VAR_4["max_cache_size"] VAR_6 = VAR_4["host"] VAR_7 = VAR_4["port"] return VAR_5, VAR_6, VAR_7 def FUNC_1(VAR_1): VAR_8 = magic.from_buffer(VAR_1, mime=True) if VAR_8[:5] != "image": return VAR_1, False else: return VAR_1, True @VAR_0.route("/") def FUNC_2(): return "<h1>401 - Unauthorised</h1>" @VAR_0.errorhandler(404) def FUNC_3(VAR_2): return abort(401) @VAR_0.route("/Y2hlY2tfY2FjaGVkX2ZpbGVz", methods=["POST"]) def FUNC_4(): VAR_3 = open("all_files", "r") VAR_9 = ast.literal_eval(VAR_3.read()) VAR_3.close() VAR_10 = request.json VAR_11 = str({"title": VAR_10["title"], "singer": VAR_10["singer"], "album": VAR_10["album"]}) VAR_12 = ast.literal_eval(VAR_11) if VAR_12["title"][:9] == "[PAUSED] ": VAR_12["title"] = VAR_12["title"][9::] del VAR_10 if type(VAR_12) != dict: VAR_30 = type(VAR_12) print( "Not provided a dict, instead a " + str(VAR_30) + " was provided. Returning NoneType." ) return "None" for key in VAR_9: print(f"Analysing VAR_12 {data} against item(s) {key[0]}.") if VAR_12 == key[0]: print("Found match for " + str(VAR_12) + " in database.") VAR_32 = [] for VAR_28 in VAR_9: if VAR_28[0] == VAR_12: VAR_11 = VAR_28 else: VAR_32.append(VAR_28) VAR_32.append(VAR_11) VAR_3 = open("all_files", "w") VAR_3.write(str(VAR_32)) VAR_3.close() print("Returning dictionary: " + str(key)) return str(key) print("No match found. Returning NoneType.") return "None" @VAR_0.route("/bGVhdmVfcmlnaHRfbm93", methods=["POST"]) def FUNC_5(): if not request.json or "image" not in request.json: print("No VAR_12 sent or no image provided. Aborting with 400.") abort(400) VAR_13 = request.json["image"] VAR_14 = base64.b64decode(VAR_13.encode("utf-8")) VAR_14, VAR_15 = FUNC_1(VAR_14) if not VAR_15: return escape({"entry": "False"}) VAR_16 = Image.open(io.BytesIO(VAR_14)) VAR_17 = VAR_16.format print(f"File has filetype {VAR_17}.") if VAR_17 == "JPEG": VAR_17 = ".jpg" else: VAR_17 = ".png" VAR_18 = 100000000 VAR_19 = 999999999 VAR_20 = None VAR_3 = open("all_files", "r") VAR_21 = ast.literal_eval(VAR_3.read()) VAR_3.close() VAR_22 = 0 while VAR_20 is None or VAR_20 in VAR_21: if VAR_22 <= 1000: VAR_20 = random.randint(VAR_18, VAR_19) VAR_20 = base64.b64encode(str(VAR_20).encode("utf-8")).decode("utf-8") print(f"Trying new file name: {VAR_20}") else: VAR_22 = 0 VAR_18 += 100000 VAR_19 += 1000000 while VAR_18 >= VAR_19: VAR_18 -= 10000 VAR_18 -= 10000 print(f"Successful file name: {VAR_20}") VAR_23 = request.json["title"] if VAR_23[:9] == "[PAUSED] ": VAR_23 = title[9::] VAR_24 = request.json["singer"] VAR_25 = request.json["album"] VAR_26 = [ {"title": VAR_23, "singer": VAR_24, "album": VAR_25}, VAR_20, VAR_17, ] print(f"New VAR_9 entry: {VAR_26}") VAR_21.append(VAR_26) VAR_27, VAR_11, VAR_28 = FUNC_0() del VAR_11 del VAR_28 VAR_29 = len(VAR_21) while ( VAR_29 > VAR_27 ): # if it is not over the limit, it will skip. if it is, it does this. VAR_31 = VAR_21[0][1] + VAR_21[0][2] remove(werkzeug.utils.secure_filename(VAR_31)) del VAR_21[0] VAR_29 = len(VAR_21) VAR_3 = open("all_files", "w") VAR_3.write(str(VAR_21)) VAR_3.close() VAR_20 = VAR_20 + VAR_17 VAR_16.save(VAR_20) print(f"Saved {VAR_20} from {VAR_26}.") print(f"Returning {VAR_26}.") return escape(str({"entry": VAR_26})) def FUNC_6(): VAR_27, VAR_6, VAR_7 = FUNC_0() VAR_0.run(VAR_6=host, VAR_7=port) if __name__ == "__main__": FUNC_6()
[ 8, 12, 16, 17, 18, 23, 27, 29, 30, 33, 38, 39, 43, 44, 48, 49, 52, 53, 54, 55, 56, 57, 58, 59, 63, 67, 70, 72, 81, 86, 87, 95, 99, 102, 105, 106, 109, 113, 120, 123, 128, 131, 133, 137, 139, 143, 145, 151, 154, 156, 158, 162, 165, 172, 174, 175, 176, 177, 178, 179, 180, 181, 185, 190, 195, 199, 201, 203, 207, 208, 212, 213, 216 ]
[ 12, 16, 17, 18, 23, 27, 29, 30, 33, 38, 39, 43, 44, 48, 49, 52, 53, 54, 55, 56, 57, 58, 59, 63, 67, 70, 72, 81, 86, 87, 95, 99, 102, 105, 106, 109, 113, 120, 123, 128, 131, 133, 137, 139, 143, 145, 151, 154, 156, 158, 162, 165, 172, 174, 175, 176, 177, 178, 179, 180, 181, 185, 190, 195, 199, 201, 203, 207, 208, 212, 213, 216 ]
1CWE-79
import tornado.ioloop import tornado.web import os #import sqlite3 import json import sys import rtxcomplete import traceback #class MainHandler(tornado.web.RequestHandler): # def get(self): # self.write("Hello, world") #print __file__ root = os.path.dirname(os.path.abspath(__file__)) rtxcomplete.load() #conn = sqlite3.connect('dict.db') #conn.enable_load_extension(True) #conn.load_extension("./spellfix") #cursor = conn.cursor() class autoSearch(tornado.web.RequestHandler): def get(self, arg,word=None): #print "match auto" try: limit = self.get_argument("limit") word = self.get_argument("word") callback = self.get_argument("callback") #jsonp result = rtxcomplete.prefix(word,limit) result = callback+"("+json.dumps(result)+");" #jsonp #result = json.dumps(result) #typeahead self.write(result) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) #print sys.exc_info()[2] self.write("error") class fuzzySearch(tornado.web.RequestHandler): def get(self, arg,word=None): #print "matched fuzzy" try: limit = self.get_argument("limit") word = self.get_argument("word") callback = self.get_argument("callback") #print word #cursor.execute("SELECT word FROM spell WHERE word MATCH \"" + word + "\" LIMIT " + limit) #cursor.execute("SELECT word FROM spell WHERE word MATCH \"" + word + "*\" LIMIT " + limit) result = rtxcomplete.fuzzy(word,limit); #rows = cursor.fetchall() #print type(rows) result = callback+"("+json.dumps(result)+");" #print arg, result #if (len(rows) > 0): self.write(result) #else: #self.write(callback+"("+json.dumps([["NO SUGGESTIONS"]])+");") #self.write(json.dumps(rows)) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) #print sys.exc_info()[:] self.write("error") class autofuzzySearch(tornado.web.RequestHandler): def get(self, arg,word=None): #print "matched autofuzzy" try: limit = self.get_argument("limit") word = self.get_argument("word") callback = self.get_argument("callback") #print word #cursor.execute("SELECT word FROM spell WHERE word MATCH \"" + word + "\" LIMIT " + limit) #cursor.execute("SELECT word FROM spell WHERE word MATCH \"" + word + "*\" LIMIT " + limit) result = rtxcomplete.autofuzzy(word,limit); #rows = cursor.fetchall() #print type(rows) result = callback+"("+json.dumps(result)+");" #print arg, result #if (len(rows) > 0): self.write(result) #else: #self.write(callback+"("+json.dumps([["NO SUGGESTIONS"]])+");") #self.write(json.dumps(rows)) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) #print sys.exc_info()[:] self.write("error") class nodesLikeSearch(tornado.web.RequestHandler): def get(self, arg,word=None): #try: if 1 == 1: limit = self.get_argument("limit") word = self.get_argument("word") callback = self.get_argument("callback") result = rtxcomplete.get_nodes_like(word,limit); result = callback+"("+json.dumps(result)+");" self.write(result) #except: # print(sys.exc_info()[:]) # traceback.print_tb(sys.exc_info()[-1]) # self.write("error") class defineSearch(tornado.web.RequestHandler): def get(self, arg,word=None): print("matched define search: not implemented") self.write("") def make_https_app(): return tornado.web.Application([ #(r"/", MainHandler), (r"/autofuzzy(.*)", autofuzzySearch), (r"/auto(.*)", autoSearch), (r"/fuzzy(.*)", fuzzySearch), (r"/define(.*)", defineSearch), (r"/nodeslike(.*)", nodesLikeSearch), (r"/(.*)", tornado.web.StaticFileHandler, {"path": root, "default_filename": "rtxcomplete.html"}), ], compress_response= True) class redirect_handler(tornado.web.RequestHandler): def prepare(self): if self.request.protocol == 'http': if self.request.host == "rtxcomplete.ixlab.org": self.redirect('https://'+self.request.host, permanent=False) def get(self): self.write("Looks like you're trying to access rtxcomplete at the wrong host name.") self.write("<br>Please make sure the address is correct: 'rtxcomplete.ixlab.org'") def make_redirect_app(): return tornado.web.Application([ (r'/', redirect_handler) ]) if __name__ == "__main__": print("root: " + root) if True: #FW/EWD: clean this up later http_app = make_https_app() http_server = tornado.httpserver.HTTPServer(http_app) http_server.listen(4999) else: redirect_app = make_redirect_app() redirect_app.listen(80) https_app = make_https_app() https_server = tornado.httpserver.HTTPServer(https_app, ssl_options={ "certfile": "/etc/letsencrypt/live/rtxcomplete.ixlab.org/fullchain.pem", "keyfile" : "/etc/letsencrypt/live/rtxcomplete.ixlab.org/privkey.pem", }) https_server.listen(443) tornado.ioloop.IOLoop.current().start()
import tornado.ioloop import tornado.web import os #import sqlite3 import json import sys import rtxcomplete import traceback import re root = os.path.dirname(os.path.abspath(__file__)) rtxcomplete.load() #### Sanitize the client-provided callback function name def sanitize_callback(callback): if callback is None or not isinstance(callback,str): return 'autocomplete_callback' match = re.match(r'([a-zA-Z0-9_]+).*$', callback) if match: callback = match.group(1) else: callback = 'autocomplete_callback' return callback class autoSearch(tornado.web.RequestHandler): def get(self, arg,word=None): try: limit = self.get_argument("limit") word = self.get_argument("word") callback = sanitize_callback(self.get_argument("callback")) result = rtxcomplete.prefix(word,limit) result = callback+"("+json.dumps(result)+");" self.write(result) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) #print sys.exc_info()[2] self.write("error") class fuzzySearch(tornado.web.RequestHandler): def get(self, arg,word=None): #print "matched fuzzy" try: limit = self.get_argument("limit") word = self.get_argument("word") callback = sanitize_callback(self.get_argument("callback")) #print word #cursor.execute("SELECT word FROM spell WHERE word MATCH \"" + word + "\" LIMIT " + limit) #cursor.execute("SELECT word FROM spell WHERE word MATCH \"" + word + "*\" LIMIT " + limit) result = rtxcomplete.fuzzy(word,limit); #rows = cursor.fetchall() #print type(rows) result = callback+"("+json.dumps(result)+");" #print arg, result #if (len(rows) > 0): self.write(result) #else: #self.write(callback+"("+json.dumps([["NO SUGGESTIONS"]])+");") #self.write(json.dumps(rows)) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) #print sys.exc_info()[:] self.write("error") class autofuzzySearch(tornado.web.RequestHandler): def get(self, arg,word=None): #print "matched autofuzzy" try: limit = self.get_argument("limit") word = self.get_argument("word") callback = sanitize_callback(self.get_argument("callback")) #print word #cursor.execute("SELECT word FROM spell WHERE word MATCH \"" + word + "\" LIMIT " + limit) #cursor.execute("SELECT word FROM spell WHERE word MATCH \"" + word + "*\" LIMIT " + limit) result = rtxcomplete.autofuzzy(word,limit); #rows = cursor.fetchall() #print type(rows) result = callback+"("+json.dumps(result)+");" #print arg, result #if (len(rows) > 0): self.write(result) #else: #self.write(callback+"("+json.dumps([["NO SUGGESTIONS"]])+");") #self.write(json.dumps(rows)) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) #print sys.exc_info()[:] self.write("error") class nodesLikeSearch(tornado.web.RequestHandler): def get(self, arg,word=None): try: limit = self.get_argument("limit") word = self.get_argument("word") callback = sanitize_callback(self.get_argument("callback")) result = rtxcomplete.get_nodes_like(word,limit); result = callback+"("+json.dumps(result)+");" self.write(result) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) self.write("error") class defineSearch(tornado.web.RequestHandler): def get(self, arg,word=None): print("matched define search: not implemented") self.write("") def make_https_app(): return tornado.web.Application([ #(r"/", MainHandler), (r"/autofuzzy(.*)", autofuzzySearch), (r"/auto(.*)", autoSearch), (r"/fuzzy(.*)", fuzzySearch), (r"/define(.*)", defineSearch), (r"/nodeslike(.*)", nodesLikeSearch), (r"/(.*)", tornado.web.StaticFileHandler, {"path": root, "default_filename": "rtxcomplete.html"}), ], compress_response= True) class redirect_handler(tornado.web.RequestHandler): def prepare(self): if self.request.protocol == 'http': if self.request.host == "rtxcomplete.ixlab.org": self.redirect('https://'+self.request.host, permanent=False) def get(self): self.write("Looks like you're trying to access rtxcomplete at the wrong host name.") self.write("<br>Please make sure the address is correct: 'rtxcomplete.ixlab.org'") def make_redirect_app(): return tornado.web.Application([ (r'/', redirect_handler) ]) if __name__ == "__main__": print("root: " + root) if True: #FW/EWD: clean this up later http_app = make_https_app() http_server = tornado.httpserver.HTTPServer(http_app) http_server.listen(4999) else: redirect_app = make_redirect_app() redirect_app.listen(80) https_app = make_https_app() https_server = tornado.httpserver.HTTPServer(https_app, ssl_options={ "certfile": "/etc/letsencrypt/live/rtxcomplete.ixlab.org/fullchain.pem", "keyfile" : "/etc/letsencrypt/live/rtxcomplete.ixlab.org/privkey.pem", }) https_server.listen(443) tornado.ioloop.IOLoop.current().start()
xss
{ "code": [ " callback = self.get_argument(\"callback\")", " callback = self.get_argument(\"callback\")", " if 1 == 1:", " callback = self.get_argument(\"callback\")" ], "line_no": [ 50, 76, 100, 103 ] }
{ "code": [ "def sanitize_callback(callback):", " return 'autocomplete_callback'", " if match:", " else:", " return callback", " callback = sanitize_callback(self.get_argument(\"callback\"))", " callback = sanitize_callback(self.get_argument(\"callback\"))", " try:", " callback = sanitize_callback(self.get_argument(\"callback\"))", " print(sys.exc_info()[:])", " self.write(\"error\")" ], "line_no": [ 16, 18, 20, 22, 24, 33, 53, 102, 105, 110, 112 ] }
import tornado.ioloop import tornado.web import os import json import sys import rtxcomplete import traceback VAR_0 = os.path.dirname(os.path.abspath(__file__)) rtxcomplete.load() class CLASS_0(tornado.web.RequestHandler): def FUNC_2(self, VAR_1,VAR_2=None): try: VAR_8 = self.get_argument("limit") VAR_2 = self.get_argument("word") VAR_9 = self.get_argument("callback") #jsonp VAR_10 = rtxcomplete.prefix(VAR_2,VAR_8) VAR_10 = VAR_9+"("+json.dumps(VAR_10)+");" #jsonp self.write(VAR_10) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) self.write("error") class CLASS_1(tornado.web.RequestHandler): def FUNC_2(self, VAR_1,VAR_2=None): try: VAR_8 = self.get_argument("limit") VAR_2 = self.get_argument("word") VAR_9 = self.get_argument("callback") VAR_10 = rtxcomplete.fuzzy(VAR_2,VAR_8); VAR_10 = VAR_9+"("+json.dumps(VAR_10)+");" self.write(VAR_10) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) self.write("error") class CLASS_2(tornado.web.RequestHandler): def FUNC_2(self, VAR_1,VAR_2=None): try: VAR_8 = self.get_argument("limit") VAR_2 = self.get_argument("word") VAR_9 = self.get_argument("callback") VAR_10 = rtxcomplete.autofuzzy(VAR_2,VAR_8); VAR_10 = VAR_9+"("+json.dumps(VAR_10)+");" self.write(VAR_10) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) self.write("error") class CLASS_3(tornado.web.RequestHandler): def FUNC_2(self, VAR_1,VAR_2=None): if 1 == 1: VAR_8 = self.get_argument("limit") VAR_2 = self.get_argument("word") VAR_9 = self.get_argument("callback") VAR_10 = rtxcomplete.get_nodes_like(VAR_2,VAR_8); VAR_10 = VAR_9+"("+json.dumps(VAR_10)+");" self.write(VAR_10) class CLASS_4(tornado.web.RequestHandler): def FUNC_2(self, VAR_1,VAR_2=None): print("matched define search: not implemented") self.write("") def FUNC_0(): return tornado.web.Application([ (r"/autofuzzy(.*)", CLASS_2), (r"/auto(.*)", CLASS_0), (r"/fuzzy(.*)", CLASS_1), (r"/define(.*)", CLASS_4), (r"/nodeslike(.*)", CLASS_3), (r"/(.*)", tornado.web.StaticFileHandler, {"path": VAR_0, "default_filename": "rtxcomplete.html"}), ], compress_response= True) class CLASS_5(tornado.web.RequestHandler): def FUNC_3(self): if self.request.protocol == 'http': if self.request.host == "rtxcomplete.ixlab.org": self.redirect('https://'+self.request.host, permanent=False) def FUNC_2(self): self.write("Looks like you're trying to access rtxcomplete at the wrong host name.") self.write("<br>Please make sure the address is correct: 'rtxcomplete.ixlab.org'") def FUNC_1(): return tornado.web.Application([ (r'/', CLASS_5) ]) if __name__ == "__main__": print("root: " + VAR_0) if True: #FW/EWD: clean this up later VAR_3 = FUNC_0() VAR_4 = tornado.httpserver.HTTPServer(VAR_3) VAR_4.listen(4999) else: VAR_5 = FUNC_1() VAR_5.listen(80) VAR_6 = FUNC_0() VAR_7 = tornado.httpserver.HTTPServer(VAR_6, ssl_options={ "certfile": "/etc/letsencrypt/live/rtxcomplete.ixlab.org/fullchain.pem", "keyfile" : "/etc/letsencrypt/live/rtxcomplete.ixlab.org/privkey.pem", }) VAR_7.listen(443) tornado.ioloop.IOLoop.current().start()
import tornado.ioloop import tornado.web import os import json import sys import rtxcomplete import traceback import re VAR_0 = os.path.dirname(os.path.abspath(__file__)) rtxcomplete.load() def FUNC_0(VAR_1): if VAR_1 is None or not isinstance(VAR_1,str): return 'autocomplete_callback' VAR_2 = re.match(r'([a-zA-Z0-9_]+).*$', VAR_1) if VAR_2: VAR_1 = VAR_2.group(1) else: VAR_1 = 'autocomplete_callback' return VAR_1 class CLASS_0(tornado.web.RequestHandler): def FUNC_3(self, VAR_3,VAR_4=None): try: VAR_10 = self.get_argument("limit") VAR_4 = self.get_argument("word") VAR_1 = FUNC_0(self.get_argument("callback")) VAR_11 = rtxcomplete.prefix(VAR_4,VAR_10) VAR_11 = VAR_1+"("+json.dumps(VAR_11)+");" self.write(VAR_11) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) self.write("error") class CLASS_1(tornado.web.RequestHandler): def FUNC_3(self, VAR_3,VAR_4=None): try: VAR_10 = self.get_argument("limit") VAR_4 = self.get_argument("word") VAR_1 = FUNC_0(self.get_argument("callback")) VAR_11 = rtxcomplete.fuzzy(VAR_4,VAR_10); VAR_11 = VAR_1+"("+json.dumps(VAR_11)+");" self.write(VAR_11) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) self.write("error") class CLASS_2(tornado.web.RequestHandler): def FUNC_3(self, VAR_3,VAR_4=None): try: VAR_10 = self.get_argument("limit") VAR_4 = self.get_argument("word") VAR_1 = FUNC_0(self.get_argument("callback")) VAR_11 = rtxcomplete.autofuzzy(VAR_4,VAR_10); VAR_11 = VAR_1+"("+json.dumps(VAR_11)+");" self.write(VAR_11) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) self.write("error") class CLASS_3(tornado.web.RequestHandler): def FUNC_3(self, VAR_3,VAR_4=None): try: VAR_10 = self.get_argument("limit") VAR_4 = self.get_argument("word") VAR_1 = FUNC_0(self.get_argument("callback")) VAR_11 = rtxcomplete.get_nodes_like(VAR_4,VAR_10); VAR_11 = VAR_1+"("+json.dumps(VAR_11)+");" self.write(VAR_11) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) self.write("error") class CLASS_4(tornado.web.RequestHandler): def FUNC_3(self, VAR_3,VAR_4=None): print("matched define search: not implemented") self.write("") def FUNC_1(): return tornado.web.Application([ (r"/autofuzzy(.*)", CLASS_2), (r"/auto(.*)", CLASS_0), (r"/fuzzy(.*)", CLASS_1), (r"/define(.*)", CLASS_4), (r"/nodeslike(.*)", CLASS_3), (r"/(.*)", tornado.web.StaticFileHandler, {"path": VAR_0, "default_filename": "rtxcomplete.html"}), ], compress_response= True) class CLASS_5(tornado.web.RequestHandler): def FUNC_4(self): if self.request.protocol == 'http': if self.request.host == "rtxcomplete.ixlab.org": self.redirect('https://'+self.request.host, permanent=False) def FUNC_3(self): self.write("Looks like you're trying to access rtxcomplete at the wrong host name.") self.write("<br>Please make sure the address is correct: 'rtxcomplete.ixlab.org'") def FUNC_2(): return tornado.web.Application([ (r'/', CLASS_5) ]) if __name__ == "__main__": print("root: " + VAR_0) if True: #FW/EWD: clean this up later VAR_5 = FUNC_1() VAR_6 = tornado.httpserver.HTTPServer(VAR_5) VAR_6.listen(4999) else: VAR_7 = FUNC_2() VAR_7.listen(80) VAR_8 = FUNC_1() VAR_9 = tornado.httpserver.HTTPServer(VAR_8, ssl_options={ "certfile": "/etc/letsencrypt/live/rtxcomplete.ixlab.org/fullchain.pem", "keyfile" : "/etc/letsencrypt/live/rtxcomplete.ixlab.org/privkey.pem", }) VAR_9.listen(443) tornado.ioloop.IOLoop.current().start()
[ 4, 9, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 23, 25, 30, 32, 34, 35, 37, 41, 43, 46, 51, 52, 53, 55, 56, 58, 59, 61, 62, 63, 67, 69, 72, 77, 78, 79, 81, 82, 84, 85, 87, 88, 89, 93, 95, 96, 99, 107, 108, 109, 110, 111, 112, 117, 120, 130, 136, 140, 145, 148, 153, 157, 164, 166 ]
[ 4, 10, 13, 14, 15, 25, 26, 28, 34, 36, 38, 40, 44, 46, 49, 54, 55, 56, 58, 59, 61, 62, 64, 65, 66, 70, 72, 75, 80, 81, 82, 84, 85, 87, 88, 90, 91, 92, 96, 98, 99, 113, 114, 119, 122, 132, 138, 142, 147, 150, 155, 159, 166, 168 ]
4CWE-601
from typing import Any, Callable, List, Optional from urllib.parse import urlparse from django.conf import settings from django.http import HttpResponse from django.urls import URLPattern, include, path, re_path from django.views.decorators import csrf from django.views.decorators.csrf import csrf_exempt from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView from posthog.api import ( api_not_found, authentication, capture, dashboard, decide, organizations_router, project_dashboards_router, projects_router, router, signup, user, ) from posthog.demo import demo from .utils import render_template from .views import health, login_required, preflight_check, robots_txt, security_txt, sso_login, stats ee_urlpatterns: List[Any] = [] try: from ee.urls import extend_api_router from ee.urls import urlpatterns as ee_urlpatterns except ImportError: pass else: extend_api_router(router, projects_router=projects_router, project_dashboards_router=project_dashboards_router) try: # See https://github.com/PostHog/posthog-cloud/blob/master/multi_tenancy/router.py from multi_tenancy.router import extend_api_router as extend_api_router_cloud # noqa except ImportError: pass else: extend_api_router_cloud(router, organizations_router=organizations_router, projects_router=projects_router) @csrf.ensure_csrf_cookie def home(request, *args, **kwargs): return render_template("index.html", request) def authorize_and_redirect(request): if not request.GET.get("redirect"): return HttpResponse("You need to pass a url to ?redirect=", status=401) if not request.META.get("HTTP_REFERER"): return HttpResponse('You need to make a request that includes the "Referer" header.', status=400) referer_url = urlparse(request.META["HTTP_REFERER"]) redirect_url = urlparse(request.GET["redirect"]) if referer_url.hostname != redirect_url.hostname: return HttpResponse(f"Can only redirect to the same domain as the referer: {referer_url.hostname}", status=400) if referer_url.scheme != redirect_url.scheme: return HttpResponse(f"Can only redirect to the same scheme as the referer: {referer_url.scheme}", status=400) if referer_url.port != redirect_url.port: return HttpResponse( f"Can only redirect to the same port as the referer: {referer_url.port or 'no port in URL'}", status=400 ) return render_template( "authorize_and_redirect.html", request=request, context={"domain": redirect_url.hostname, "redirect_url": request.GET["redirect"]}, ) def opt_slash_path(route: str, view: Callable, name: Optional[str] = None) -> URLPattern: """Catches path with or without trailing slash, taking into account query param and hash.""" # Ignoring the type because while name can be optional on re_path, mypy doesn't agree return re_path(fr"^{route}/?(?:[?#].*)?$", view, name=name) # type: ignore urlpatterns = [ path("api/schema/", SpectacularAPIView.as_view(), name="schema"), # Optional UI: path("api/schema/swagger-ui/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui"), path("api/schema/redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc"), # Health check probe endpoints for K8s # NOTE: We have _health, livez, and _readyz. _health is deprecated and # is only included for compatability with old installations. For new # operations livez and readyz should be used. opt_slash_path("_health", health), opt_slash_path("_stats", stats), opt_slash_path("_preflight", preflight_check), # ee *ee_urlpatterns, # api path("api/", include(router.urls)), opt_slash_path("api/user/redirect_to_site", user.redirect_to_site), opt_slash_path("api/user/test_slack_webhook", user.test_slack_webhook), opt_slash_path("api/signup", signup.SignupViewset.as_view()), opt_slash_path("api/social_signup", signup.SocialSignupViewset.as_view()), path("api/signup/<str:invite_id>/", signup.InviteSignupViewset.as_view()), path( "api/reset/<str:user_uuid>/", authentication.PasswordResetCompleteViewSet.as_view({"get": "retrieve", "post": "create"}), ), re_path(r"^api.+", api_not_found), path("authorize_and_redirect/", login_required(authorize_and_redirect)), path("shared_dashboard/<str:share_token>", dashboard.shared_dashboard), re_path(r"^demo.*", login_required(demo)), # ingestion opt_slash_path("decide", decide.get_decide), opt_slash_path("e", capture.get_event), opt_slash_path("engage", capture.get_event), opt_slash_path("track", capture.get_event), opt_slash_path("capture", capture.get_event), opt_slash_path("batch", capture.get_event), opt_slash_path("s", capture.get_event), # session recordings opt_slash_path("robots.txt", robots_txt), opt_slash_path(".well-known/security.txt", security_txt), # auth path("logout", authentication.logout, name="login"), path("signup/finish/", signup.finish_social_signup, name="signup_finish"), path( "login/<str:backend>/", sso_login, name="social_begin" ), # overrides from `social_django.urls` to validate proper license path("", include("social_django.urls", namespace="social")), ] if settings.TEST: # Used in posthog-js e2e tests @csrf_exempt def delete_events(request): from ee.clickhouse.sql.events import TRUNCATE_EVENTS_TABLE_SQL from posthog.client import sync_execute sync_execute(TRUNCATE_EVENTS_TABLE_SQL()) return HttpResponse() urlpatterns.append(path("delete_events/", delete_events)) # Routes added individually to remove login requirement frontend_unauthenticated_routes = [ "preflight", "signup", r"signup\/[A-Za-z0-9\-]*", "reset", "organization/billing/subscribed", "login", ] for route in frontend_unauthenticated_routes: urlpatterns.append(re_path(route, home)) urlpatterns.append(re_path(r"^.*", login_required(home)))
from typing import Any, Callable, List, Optional, cast from urllib.parse import urlparse from django.conf import settings from django.http import HttpRequest, HttpResponse from django.urls import URLPattern, include, path, re_path from django.views.decorators import csrf from django.views.decorators.csrf import csrf_exempt from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView from posthog.api import ( api_not_found, authentication, capture, dashboard, decide, organizations_router, project_dashboards_router, projects_router, router, signup, user, ) from posthog.api.decide import hostname_in_app_urls from posthog.demo import demo from posthog.models import User from .utils import render_template from .views import health, login_required, preflight_check, robots_txt, security_txt, sso_login, stats ee_urlpatterns: List[Any] = [] try: from ee.urls import extend_api_router from ee.urls import urlpatterns as ee_urlpatterns except ImportError: pass else: extend_api_router(router, projects_router=projects_router, project_dashboards_router=project_dashboards_router) try: # See https://github.com/PostHog/posthog-cloud/blob/master/multi_tenancy/router.py from multi_tenancy.router import extend_api_router as extend_api_router_cloud # noqa except ImportError: pass else: extend_api_router_cloud(router, organizations_router=organizations_router, projects_router=projects_router) @csrf.ensure_csrf_cookie def home(request, *args, **kwargs): return render_template("index.html", request) def authorize_and_redirect(request: HttpRequest) -> HttpResponse: if not request.GET.get("redirect"): return HttpResponse("You need to pass a url to ?redirect=", status=401) if not request.META.get("HTTP_REFERER"): return HttpResponse('You need to make a request that includes the "Referer" header.', status=400) current_team = cast(User, request.user).team referer_url = urlparse(request.META["HTTP_REFERER"]) redirect_url = urlparse(request.GET["redirect"]) if not current_team or not hostname_in_app_urls(current_team, redirect_url.hostname): return HttpResponse(f"Can only redirect to a permitted domain.", status=400) if referer_url.hostname != redirect_url.hostname: return HttpResponse(f"Can only redirect to the same domain as the referer: {referer_url.hostname}", status=400) if referer_url.scheme != redirect_url.scheme: return HttpResponse(f"Can only redirect to the same scheme as the referer: {referer_url.scheme}", status=400) if referer_url.port != redirect_url.port: return HttpResponse( f"Can only redirect to the same port as the referer: {referer_url.port or 'no port in URL'}", status=400 ) return render_template( "authorize_and_redirect.html", request=request, context={"domain": redirect_url.hostname, "redirect_url": request.GET["redirect"]}, ) def opt_slash_path(route: str, view: Callable, name: Optional[str] = None) -> URLPattern: """Catches path with or without trailing slash, taking into account query param and hash.""" # Ignoring the type because while name can be optional on re_path, mypy doesn't agree return re_path(fr"^{route}/?(?:[?#].*)?$", view, name=name) # type: ignore urlpatterns = [ path("api/schema/", SpectacularAPIView.as_view(), name="schema"), # Optional UI: path("api/schema/swagger-ui/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui"), path("api/schema/redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc"), # Health check probe endpoints for K8s # NOTE: We have _health, livez, and _readyz. _health is deprecated and # is only included for compatability with old installations. For new # operations livez and readyz should be used. opt_slash_path("_health", health), opt_slash_path("_stats", stats), opt_slash_path("_preflight", preflight_check), # ee *ee_urlpatterns, # api path("api/", include(router.urls)), opt_slash_path("api/user/redirect_to_site", user.redirect_to_site), opt_slash_path("api/user/test_slack_webhook", user.test_slack_webhook), opt_slash_path("api/signup", signup.SignupViewset.as_view()), opt_slash_path("api/social_signup", signup.SocialSignupViewset.as_view()), path("api/signup/<str:invite_id>/", signup.InviteSignupViewset.as_view()), path( "api/reset/<str:user_uuid>/", authentication.PasswordResetCompleteViewSet.as_view({"get": "retrieve", "post": "create"}), ), re_path(r"^api.+", api_not_found), path("authorize_and_redirect/", login_required(authorize_and_redirect)), path("shared_dashboard/<str:share_token>", dashboard.shared_dashboard), re_path(r"^demo.*", login_required(demo)), # ingestion opt_slash_path("decide", decide.get_decide), opt_slash_path("e", capture.get_event), opt_slash_path("engage", capture.get_event), opt_slash_path("track", capture.get_event), opt_slash_path("capture", capture.get_event), opt_slash_path("batch", capture.get_event), opt_slash_path("s", capture.get_event), # session recordings opt_slash_path("robots.txt", robots_txt), opt_slash_path(".well-known/security.txt", security_txt), # auth path("logout", authentication.logout, name="login"), path("signup/finish/", signup.finish_social_signup, name="signup_finish"), path( "login/<str:backend>/", sso_login, name="social_begin" ), # overrides from `social_django.urls` to validate proper license path("", include("social_django.urls", namespace="social")), ] if settings.TEST: # Used in posthog-js e2e tests @csrf_exempt def delete_events(request): from ee.clickhouse.sql.events import TRUNCATE_EVENTS_TABLE_SQL from posthog.client import sync_execute sync_execute(TRUNCATE_EVENTS_TABLE_SQL()) return HttpResponse() urlpatterns.append(path("delete_events/", delete_events)) # Routes added individually to remove login requirement frontend_unauthenticated_routes = [ "preflight", "signup", r"signup\/[A-Za-z0-9\-]*", "reset", "organization/billing/subscribed", "login", ] for route in frontend_unauthenticated_routes: urlpatterns.append(re_path(route, home)) urlpatterns.append(re_path(r"^.*", login_required(home)))
open_redirect
{ "code": [ "from typing import Any, Callable, List, Optional", "from django.http import HttpResponse", "def authorize_and_redirect(request):" ], "line_no": [ 1, 5, 53 ] }
{ "code": [ "from typing import Any, Callable, List, Optional, cast", "from django.http import HttpRequest, HttpResponse", "from posthog.api.decide import hostname_in_app_urls", "from posthog.models import User", "def authorize_and_redirect(request: HttpRequest) -> HttpResponse:", " if not current_team or not hostname_in_app_urls(current_team, redirect_url.hostname):", " return HttpResponse(f\"Can only redirect to a permitted domain.\", status=400)" ], "line_no": [ 1, 5, 24, 26, 55, 65, 66 ] }
from typing import Any, Callable, List, Optional from urllib.parse import urlparse from django.conf import settings from django.http import HttpResponse from django.urls import URLPattern, include, path, re_path from django.views.decorators import csrf from django.views.decorators.csrf import csrf_exempt from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView from posthog.api import ( api_not_found, authentication, capture, dashboard, decide, organizations_router, project_dashboards_router, projects_router, router, signup, user, ) from posthog.demo import demo from .utils import render_template from .views import health, login_required, preflight_check, robots_txt, security_txt, sso_login, stats ee_urlpatterns: List[Any] = [] try: from ee.urls import extend_api_router from ee.urls import .urlpatterns as ee_urlpatterns except ImportError: pass else: extend_api_router(router, projects_router=projects_router, project_dashboards_router=project_dashboards_router) try: from multi_tenancy.router import extend_api_router as extend_api_router_cloud # noqa except ImportError: pass else: extend_api_router_cloud(router, organizations_router=organizations_router, projects_router=projects_router) @csrf.ensure_csrf_cookie def FUNC_0(VAR_0, *VAR_1, **VAR_2): return render_template("index.html", VAR_0) def FUNC_1(VAR_0): if not VAR_0.GET.get("redirect"): return HttpResponse("You need to pass a url to ?redirect=", status=401) if not VAR_0.META.get("HTTP_REFERER"): return HttpResponse('You need to make a VAR_0 that includes the "Referer" header.', status=400) VAR_8 = urlparse(VAR_0.META["HTTP_REFERER"]) VAR_9 = urlparse(VAR_0.GET["redirect"]) if VAR_8.hostname != VAR_9.hostname: return HttpResponse(f"Can only redirect to the same domain as the referer: {VAR_8.hostname}", status=400) if VAR_8.scheme != VAR_9.scheme: return HttpResponse(f"Can only redirect to the same scheme as the referer: {VAR_8.scheme}", status=400) if VAR_8.port != VAR_9.port: return HttpResponse( f"Can only redirect to the same port as the referer: {VAR_8.port or 'no port in URL'}", status=400 ) return render_template( "authorize_and_redirect.html", VAR_0=request, context={"domain": VAR_9.hostname, "redirect_url": VAR_0.GET["redirect"]}, ) def FUNC_2(VAR_3: str, VAR_4: Callable, VAR_5: Optional[str] = None) -> URLPattern: return re_path(fr"^{VAR_3}/?(?:[?#].*)?$", VAR_4, VAR_5=name) # type: ignore VAR_6 = [ path("api/schema/", SpectacularAPIView.as_view(), VAR_5="schema"), path("api/schema/swagger-ui/", SpectacularSwaggerView.as_view(url_name="schema"), VAR_5="swagger-ui"), path("api/schema/redoc/", SpectacularRedocView.as_view(url_name="schema"), VAR_5="redoc"), FUNC_2("_health", health), FUNC_2("_stats", stats), FUNC_2("_preflight", preflight_check), *ee_urlpatterns, path("api/", include(router.urls)), FUNC_2("api/user/redirect_to_site", user.redirect_to_site), FUNC_2("api/user/test_slack_webhook", user.test_slack_webhook), FUNC_2("api/signup", signup.SignupViewset.as_view()), FUNC_2("api/social_signup", signup.SocialSignupViewset.as_view()), path("api/signup/<str:invite_id>/", signup.InviteSignupViewset.as_view()), path( "api/reset/<str:user_uuid>/", authentication.PasswordResetCompleteViewSet.as_view({"get": "retrieve", "post": "create"}), ), re_path(r"^api.+", api_not_found), path("authorize_and_redirect/", login_required(FUNC_1)), path("shared_dashboard/<str:share_token>", dashboard.shared_dashboard), re_path(r"^demo.*", login_required(demo)), FUNC_2("decide", decide.get_decide), FUNC_2("e", capture.get_event), FUNC_2("engage", capture.get_event), FUNC_2("track", capture.get_event), FUNC_2("capture", capture.get_event), FUNC_2("batch", capture.get_event), FUNC_2("s", capture.get_event), # session recordings FUNC_2("robots.txt", robots_txt), FUNC_2(".well-known/security.txt", security_txt), path("logout", authentication.logout, VAR_5="login"), path("signup/finish/", signup.finish_social_signup, VAR_5="signup_finish"), path( "login/<str:backend>/", sso_login, VAR_5="social_begin" ), # overrides from `social_django.urls` to validate proper license path("", include("social_django.urls", namespace="social")), ] if settings.TEST: @csrf_exempt def FUNC_3(VAR_0): from ee.clickhouse.sql.events import TRUNCATE_EVENTS_TABLE_SQL from posthog.client import sync_execute sync_execute(TRUNCATE_EVENTS_TABLE_SQL()) return HttpResponse() VAR_6.append(path("delete_events/", FUNC_3)) VAR_7 = [ "preflight", "signup", r"signup\/[A-Za-z0-9\-]*", "reset", "organization/billing/subscribed", "login", ] for VAR_3 in VAR_7: VAR_6.append(re_path(VAR_3, FUNC_0)) VAR_6.append(re_path(r"^.*", login_required(FUNC_0)))
from typing import Any, Callable, List, Optional, cast from urllib.parse import urlparse from django.conf import settings from django.http import HttpRequest, HttpResponse from django.urls import URLPattern, include, path, re_path from django.views.decorators import csrf from django.views.decorators.csrf import csrf_exempt from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView from posthog.api import ( api_not_found, authentication, capture, dashboard, decide, organizations_router, project_dashboards_router, projects_router, router, signup, user, ) from posthog.api.decide import hostname_in_app_urls from posthog.demo import demo from posthog.models import User from .utils import render_template from .views import health, login_required, preflight_check, robots_txt, security_txt, sso_login, stats ee_urlpatterns: List[Any] = [] try: from ee.urls import extend_api_router from ee.urls import .urlpatterns as ee_urlpatterns except ImportError: pass else: extend_api_router(router, projects_router=projects_router, project_dashboards_router=project_dashboards_router) try: from multi_tenancy.router import extend_api_router as extend_api_router_cloud # noqa except ImportError: pass else: extend_api_router_cloud(router, organizations_router=organizations_router, projects_router=projects_router) @csrf.ensure_csrf_cookie def FUNC_0(VAR_0, *VAR_1, **VAR_2): return render_template("index.html", VAR_0) def FUNC_1(VAR_0: HttpRequest) -> HttpResponse: if not VAR_0.GET.get("redirect"): return HttpResponse("You need to pass a url to ?redirect=", status=401) if not VAR_0.META.get("HTTP_REFERER"): return HttpResponse('You need to make a VAR_0 that includes the "Referer" header.', status=400) VAR_8 = cast(User, VAR_0.user).team VAR_9 = urlparse(VAR_0.META["HTTP_REFERER"]) VAR_10 = urlparse(VAR_0.GET["redirect"]) if not VAR_8 or not hostname_in_app_urls(VAR_8, VAR_10.hostname): return HttpResponse(f"Can only redirect to a permitted domain.", status=400) if VAR_9.hostname != VAR_10.hostname: return HttpResponse(f"Can only redirect to the same domain as the referer: {VAR_9.hostname}", status=400) if VAR_9.scheme != VAR_10.scheme: return HttpResponse(f"Can only redirect to the same scheme as the referer: {VAR_9.scheme}", status=400) if VAR_9.port != VAR_10.port: return HttpResponse( f"Can only redirect to the same port as the referer: {VAR_9.port or 'no port in URL'}", status=400 ) return render_template( "authorize_and_redirect.html", VAR_0=request, context={"domain": VAR_10.hostname, "redirect_url": VAR_0.GET["redirect"]}, ) def FUNC_2(VAR_3: str, VAR_4: Callable, VAR_5: Optional[str] = None) -> URLPattern: return re_path(fr"^{VAR_3}/?(?:[?#].*)?$", VAR_4, VAR_5=name) # type: ignore VAR_6 = [ path("api/schema/", SpectacularAPIView.as_view(), VAR_5="schema"), path("api/schema/swagger-ui/", SpectacularSwaggerView.as_view(url_name="schema"), VAR_5="swagger-ui"), path("api/schema/redoc/", SpectacularRedocView.as_view(url_name="schema"), VAR_5="redoc"), FUNC_2("_health", health), FUNC_2("_stats", stats), FUNC_2("_preflight", preflight_check), *ee_urlpatterns, path("api/", include(router.urls)), FUNC_2("api/user/redirect_to_site", user.redirect_to_site), FUNC_2("api/user/test_slack_webhook", user.test_slack_webhook), FUNC_2("api/signup", signup.SignupViewset.as_view()), FUNC_2("api/social_signup", signup.SocialSignupViewset.as_view()), path("api/signup/<str:invite_id>/", signup.InviteSignupViewset.as_view()), path( "api/reset/<str:user_uuid>/", authentication.PasswordResetCompleteViewSet.as_view({"get": "retrieve", "post": "create"}), ), re_path(r"^api.+", api_not_found), path("authorize_and_redirect/", login_required(FUNC_1)), path("shared_dashboard/<str:share_token>", dashboard.shared_dashboard), re_path(r"^demo.*", login_required(demo)), FUNC_2("decide", decide.get_decide), FUNC_2("e", capture.get_event), FUNC_2("engage", capture.get_event), FUNC_2("track", capture.get_event), FUNC_2("capture", capture.get_event), FUNC_2("batch", capture.get_event), FUNC_2("s", capture.get_event), # session recordings FUNC_2("robots.txt", robots_txt), FUNC_2(".well-known/security.txt", security_txt), path("logout", authentication.logout, VAR_5="login"), path("signup/finish/", signup.finish_social_signup, VAR_5="signup_finish"), path( "login/<str:backend>/", sso_login, VAR_5="social_begin" ), # overrides from `social_django.urls` to validate proper license path("", include("social_django.urls", namespace="social")), ] if settings.TEST: @csrf_exempt def FUNC_3(VAR_0): from ee.clickhouse.sql.events import TRUNCATE_EVENTS_TABLE_SQL from posthog.client import sync_execute sync_execute(TRUNCATE_EVENTS_TABLE_SQL()) return HttpResponse() VAR_6.append(path("delete_events/", FUNC_3)) VAR_7 = [ "preflight", "signup", r"signup\/[A-Za-z0-9\-]*", "reset", "organization/billing/subscribed", "login", ] for VAR_3 in VAR_7: VAR_6.append(re_path(VAR_3, FUNC_0)) VAR_6.append(re_path(r"^.*", login_required(FUNC_0)))
[ 3, 10, 25, 28, 37, 38, 40, 46, 47, 51, 52, 58, 61, 64, 67, 72, 78, 79, 82, 84, 85, 88, 91, 92, 93, 94, 98, 100, 115, 125, 133, 135, 136, 141, 144, 146, 147, 148, 159, 161, 81 ]
[ 3, 10, 27, 30, 39, 40, 42, 48, 49, 53, 54, 60, 64, 67, 70, 73, 78, 84, 85, 88, 90, 91, 94, 97, 98, 99, 100, 104, 106, 121, 131, 139, 141, 142, 147, 150, 152, 153, 154, 165, 167, 87 ]
4CWE-601
# -*- coding: utf-8 -*- from django.utils import timezone from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from django.utils.translation import gettext as _ from spirit.core.utils.views import is_post from spirit.core.utils.decorators import moderator_required from spirit.comment.models import Comment from spirit.topic.models import Topic @moderator_required def _moderate(request, pk, field_name, to_value, action=None, message=None): topic = get_object_or_404(Topic, pk=pk) if is_post(request): count = ( Topic.objects .filter(pk=pk) .exclude(**{field_name: to_value}) .update(**{ field_name: to_value, 'reindex_at': timezone.now()})) if count and action is not None: Comment.create_moderation_action( user=request.user, topic=topic, action=action) if message is not None: messages.info(request, message) return redirect(request.POST.get( 'next', topic.get_absolute_url())) return render( request=request, template_name='spirit/topic/moderate.html', context={'topic': topic}) def delete(request, pk): return _moderate( request=request, pk=pk, field_name='is_removed', to_value=True, message=_("The topic has been deleted")) def undelete(request, pk): return _moderate( request=request, pk=pk, field_name='is_removed', to_value=False, message=_("The topic has been undeleted")) def lock(request, pk): return _moderate( request=request, pk=pk, field_name='is_closed', to_value=True, action=Comment.CLOSED, message=_("The topic has been locked")) def unlock(request, pk): return _moderate( request=request, pk=pk, field_name='is_closed', to_value=False, action=Comment.UNCLOSED, message=_("The topic has been unlocked")) def pin(request, pk): return _moderate( request=request, pk=pk, field_name='is_pinned', to_value=True, action=Comment.PINNED, message=_("The topic has been pinned")) def unpin(request, pk): return _moderate( request=request, pk=pk, field_name='is_pinned', to_value=False, action=Comment.UNPINNED, message=_("The topic has been unpinned")) def global_pin(request, pk): return _moderate( request=request, pk=pk, field_name='is_globally_pinned', to_value=True, action=Comment.PINNED, message=_("The topic has been globally pinned")) def global_unpin(request, pk): return _moderate( request=request, pk=pk, field_name='is_globally_pinned', to_value=False, action=Comment.UNPINNED, message=_("The topic has been globally unpinned"))
# -*- coding: utf-8 -*- from django.utils import timezone from django.shortcuts import render, get_object_or_404 from django.contrib import messages from django.utils.translation import gettext as _ from spirit.core.utils.http import safe_redirect from spirit.core.utils.views import is_post from spirit.core.utils.decorators import moderator_required from spirit.comment.models import Comment from spirit.topic.models import Topic @moderator_required def _moderate(request, pk, field_name, to_value, action=None, message=None): topic = get_object_or_404(Topic, pk=pk) if is_post(request): count = ( Topic.objects .filter(pk=pk) .exclude(**{field_name: to_value}) .update(**{ field_name: to_value, 'reindex_at': timezone.now()})) if count and action is not None: Comment.create_moderation_action( user=request.user, topic=topic, action=action) if message is not None: messages.info(request, message) return safe_redirect(request, 'next', topic.get_absolute_url(), method='POST') return render( request=request, template_name='spirit/topic/moderate.html', context={'topic': topic}) def delete(request, pk): return _moderate( request=request, pk=pk, field_name='is_removed', to_value=True, message=_("The topic has been deleted")) def undelete(request, pk): return _moderate( request=request, pk=pk, field_name='is_removed', to_value=False, message=_("The topic has been undeleted")) def lock(request, pk): return _moderate( request=request, pk=pk, field_name='is_closed', to_value=True, action=Comment.CLOSED, message=_("The topic has been locked")) def unlock(request, pk): return _moderate( request=request, pk=pk, field_name='is_closed', to_value=False, action=Comment.UNCLOSED, message=_("The topic has been unlocked")) def pin(request, pk): return _moderate( request=request, pk=pk, field_name='is_pinned', to_value=True, action=Comment.PINNED, message=_("The topic has been pinned")) def unpin(request, pk): return _moderate( request=request, pk=pk, field_name='is_pinned', to_value=False, action=Comment.UNPINNED, message=_("The topic has been unpinned")) def global_pin(request, pk): return _moderate( request=request, pk=pk, field_name='is_globally_pinned', to_value=True, action=Comment.PINNED, message=_("The topic has been globally pinned")) def global_unpin(request, pk): return _moderate( request=request, pk=pk, field_name='is_globally_pinned', to_value=False, action=Comment.UNPINNED, message=_("The topic has been globally unpinned"))
open_redirect
{ "code": [ "from django.shortcuts import render, redirect, get_object_or_404", " return redirect(request.POST.get(", " 'next', topic.get_absolute_url()))" ], "line_no": [ 4, 36, 37 ] }
{ "code": [ "from django.shortcuts import render, get_object_or_404", "from spirit.core.utils.http import safe_redirect", " return safe_redirect(request, 'next', topic.get_absolute_url(), method='POST')" ], "line_no": [ 4, 8, 37 ] }
from django.utils import timezone from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import .messages from django.utils.translation import gettext as _ from spirit.core.utils.views import is_post from spirit.core.utils.decorators import moderator_required from spirit.comment.models import Comment from spirit.topic.models import Topic @moderator_required def FUNC_0(VAR_0, VAR_1, VAR_2, VAR_3, VAR_4=None, VAR_5=None): VAR_6 = get_object_or_404(Topic, VAR_1=pk) if is_post(VAR_0): VAR_7 = ( Topic.objects .filter(VAR_1=pk) .exclude(**{VAR_2: VAR_3}) .update(**{ VAR_2: VAR_3, 'reindex_at': timezone.now()})) if VAR_7 and VAR_4 is not None: Comment.create_moderation_action( user=VAR_0.user, VAR_6=topic, VAR_4=action) if VAR_5 is not None: messages.info(VAR_0, VAR_5) return redirect(VAR_0.POST.get( 'next', VAR_6.get_absolute_url())) return render( VAR_0=request, template_name='spirit/VAR_6/moderate.html', context={'topic': VAR_6}) def FUNC_1(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_removed', VAR_3=True, VAR_5=_("The VAR_6 has been deleted")) def FUNC_2(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_removed', VAR_3=False, VAR_5=_("The VAR_6 has been undeleted")) def FUNC_3(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_closed', VAR_3=True, VAR_4=Comment.CLOSED, VAR_5=_("The VAR_6 has been locked")) def FUNC_4(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_closed', VAR_3=False, VAR_4=Comment.UNCLOSED, VAR_5=_("The VAR_6 has been unlocked")) def FUNC_5(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_pinned', VAR_3=True, VAR_4=Comment.PINNED, VAR_5=_("The VAR_6 has been pinned")) def FUNC_6(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_pinned', VAR_3=False, VAR_4=Comment.UNPINNED, VAR_5=_("The VAR_6 has been unpinned")) def FUNC_7(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_globally_pinned', VAR_3=True, VAR_4=Comment.PINNED, VAR_5=_("The VAR_6 has been globally pinned")) def FUNC_8(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_globally_pinned', VAR_3=False, VAR_4=Comment.UNPINNED, VAR_5=_("The VAR_6 has been globally unpinned"))
from django.utils import timezone from django.shortcuts import render, get_object_or_404 from django.contrib import .messages from django.utils.translation import gettext as _ from spirit.core.utils.http import safe_redirect from spirit.core.utils.views import is_post from spirit.core.utils.decorators import moderator_required from spirit.comment.models import Comment from spirit.topic.models import Topic @moderator_required def FUNC_0(VAR_0, VAR_1, VAR_2, VAR_3, VAR_4=None, VAR_5=None): VAR_6 = get_object_or_404(Topic, VAR_1=pk) if is_post(VAR_0): VAR_7 = ( Topic.objects .filter(VAR_1=pk) .exclude(**{VAR_2: VAR_3}) .update(**{ VAR_2: VAR_3, 'reindex_at': timezone.now()})) if VAR_7 and VAR_4 is not None: Comment.create_moderation_action( user=VAR_0.user, VAR_6=topic, VAR_4=action) if VAR_5 is not None: messages.info(VAR_0, VAR_5) return safe_redirect(VAR_0, 'next', VAR_6.get_absolute_url(), method='POST') return render( VAR_0=request, template_name='spirit/VAR_6/moderate.html', context={'topic': VAR_6}) def FUNC_1(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_removed', VAR_3=True, VAR_5=_("The VAR_6 has been deleted")) def FUNC_2(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_removed', VAR_3=False, VAR_5=_("The VAR_6 has been undeleted")) def FUNC_3(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_closed', VAR_3=True, VAR_4=Comment.CLOSED, VAR_5=_("The VAR_6 has been locked")) def FUNC_4(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_closed', VAR_3=False, VAR_4=Comment.UNCLOSED, VAR_5=_("The VAR_6 has been unlocked")) def FUNC_5(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_pinned', VAR_3=True, VAR_4=Comment.PINNED, VAR_5=_("The VAR_6 has been pinned")) def FUNC_6(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_pinned', VAR_3=False, VAR_4=Comment.UNPINNED, VAR_5=_("The VAR_6 has been unpinned")) def FUNC_7(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_globally_pinned', VAR_3=True, VAR_4=Comment.PINNED, VAR_5=_("The VAR_6 has been globally pinned")) def FUNC_8(VAR_0, VAR_1): return FUNC_0( VAR_0=request, VAR_1=pk, VAR_2='is_globally_pinned', VAR_3=False, VAR_4=Comment.UNPINNED, VAR_5=_("The VAR_6 has been globally unpinned"))
[ 1, 2, 7, 12, 13, 17, 26, 32, 35, 38, 43, 44, 52, 53, 61, 62, 71, 72, 81, 82, 91, 92, 101, 102, 111, 112, 121 ]
[ 1, 2, 7, 13, 14, 18, 27, 33, 36, 38, 43, 44, 52, 53, 61, 62, 71, 72, 81, 82, 91, 92, 101, 102, 111, 112, 121 ]
4CWE-601
# Copyright 2014 Netflix, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from security_monkey import app, db from flask_wtf.csrf import generate_csrf from security_monkey.auth.models import RBACRole from security_monkey.decorators import crossdomain from flask_restful import fields, marshal, Resource, reqparse from flask_login import current_user ORIGINS = [ 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('WEB_PORT')), # Adding this next one so you can also access the dart UI by prepending /static to the path. 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('API_PORT')), 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('NGINX_PORT')), 'https://{}:80'.format(app.config.get('FQDN')) ] ##### Marshal Datastructures ##### # Used by RevisionGet, RevisionList, ItemList REVISION_FIELDS = { 'id': fields.Integer, 'date_created': fields.String, 'date_last_ephemeral_change': fields.String, 'active': fields.Boolean, 'item_id': fields.Integer } # Used by RevisionList, ItemGet, ItemList ITEM_FIELDS = { 'id': fields.Integer, 'region': fields.String, 'name': fields.String } # Used by ItemList, Justify AUDIT_FIELDS = { 'id': fields.Integer, 'score': fields.Integer, 'issue': fields.String, 'notes': fields.String, 'justified': fields.Boolean, 'justification': fields.String, 'justified_date': fields.String, 'item_id': fields.Integer } ## Single Use Marshal Objects ## # SINGLE USE - RevisionGet REVISION_COMMENT_FIELDS = { 'id': fields.Integer, 'revision_id': fields.Integer, 'date_created': fields.String, 'text': fields.String } # SINGLE USE - ItemGet ITEM_COMMENT_FIELDS = { 'id': fields.Integer, 'date_created': fields.String, 'text': fields.String, 'item_id': fields.Integer } # SINGLE USE - UserSettings USER_SETTINGS_FIELDS = { # 'id': fields.Integer, 'daily_audit_email': fields.Boolean, 'change_reports': fields.String } # SINGLE USE - AccountGet ACCOUNT_FIELDS = { 'id': fields.Integer, 'name': fields.String, 'identifier': fields.String, 'notes': fields.String, 'active': fields.Boolean, 'third_party': fields.Boolean, 'account_type': fields.String } USER_FIELDS = { 'id': fields.Integer, 'active': fields.Boolean, 'email': fields.String, 'role': fields.String, 'confirmed_at': fields.String, 'daily_audit_email': fields.Boolean, 'change_reports': fields.String, 'last_login_at': fields.String, 'current_login_at': fields.String, 'login_count': fields.Integer, 'last_login_ip': fields.String, 'current_login_ip': fields.String } ROLE_FIELDS = { 'id': fields.Integer, 'name': fields.String, 'description': fields.String, } WHITELIST_FIELDS = { 'id': fields.Integer, 'name': fields.String, 'notes': fields.String, 'cidr': fields.String } IGNORELIST_FIELDS = { 'id': fields.Integer, 'prefix': fields.String, 'notes': fields.String, } AUDITORSETTING_FIELDS = { 'id': fields.Integer, 'disabled': fields.Boolean, 'issue_text': fields.String } ITEM_LINK_FIELDS = { 'id': fields.Integer, 'name': fields.String } class AuthenticatedService(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() super(AuthenticatedService, self).__init__() self.auth_dict = dict() if current_user.is_authenticated(): roles_marshal = [] for role in current_user.roles: roles_marshal.append(marshal(role.__dict__, ROLE_FIELDS)) roles_marshal.append({"name": current_user.role}) for role in RBACRole.roles[current_user.role].get_parents(): roles_marshal.append({"name": role.name}) self.auth_dict = { "authenticated": True, "user": current_user.email, "roles": roles_marshal } else: if app.config.get('FRONTED_BY_NGINX'): url = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login') else: url = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login') self.auth_dict = { "authenticated": False, "user": None, "url": url } @app.after_request @crossdomain(allowed_origins=ORIGINS) def after(response): response.set_cookie('XSRF-COOKIE', generate_csrf()) return response
# Copyright 2014 Netflix, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from security_monkey import app, db from flask_wtf.csrf import generate_csrf from security_monkey.auth.models import RBACRole from security_monkey.decorators import crossdomain from flask_restful import fields, marshal, Resource, reqparse from flask_login import current_user ORIGINS = [ 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('WEB_PORT')), # Adding this next one so you can also access the dart UI by prepending /static to the path. 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('API_PORT')), 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('NGINX_PORT')), 'https://{}:80'.format(app.config.get('FQDN')) ] ##### Marshal Datastructures ##### # Used by RevisionGet, RevisionList, ItemList REVISION_FIELDS = { 'id': fields.Integer, 'date_created': fields.String, 'date_last_ephemeral_change': fields.String, 'active': fields.Boolean, 'item_id': fields.Integer } # Used by RevisionList, ItemGet, ItemList ITEM_FIELDS = { 'id': fields.Integer, 'region': fields.String, 'name': fields.String } # Used by ItemList, Justify AUDIT_FIELDS = { 'id': fields.Integer, 'score': fields.Integer, 'issue': fields.String, 'notes': fields.String, 'justified': fields.Boolean, 'justification': fields.String, 'justified_date': fields.String, 'item_id': fields.Integer } ## Single Use Marshal Objects ## # SINGLE USE - RevisionGet REVISION_COMMENT_FIELDS = { 'id': fields.Integer, 'revision_id': fields.Integer, 'date_created': fields.String, 'text': fields.String } # SINGLE USE - ItemGet ITEM_COMMENT_FIELDS = { 'id': fields.Integer, 'date_created': fields.String, 'text': fields.String, 'item_id': fields.Integer } # SINGLE USE - UserSettings USER_SETTINGS_FIELDS = { # 'id': fields.Integer, 'daily_audit_email': fields.Boolean, 'change_reports': fields.String } # SINGLE USE - AccountGet ACCOUNT_FIELDS = { 'id': fields.Integer, 'name': fields.String, 'identifier': fields.String, 'notes': fields.String, 'active': fields.Boolean, 'third_party': fields.Boolean, 'account_type': fields.String } USER_FIELDS = { 'id': fields.Integer, 'active': fields.Boolean, 'email': fields.String, 'role': fields.String, 'confirmed_at': fields.String, 'daily_audit_email': fields.Boolean, 'change_reports': fields.String, 'last_login_at': fields.String, 'current_login_at': fields.String, 'login_count': fields.Integer, 'last_login_ip': fields.String, 'current_login_ip': fields.String } ROLE_FIELDS = { 'id': fields.Integer, 'name': fields.String, 'description': fields.String, } WHITELIST_FIELDS = { 'id': fields.Integer, 'name': fields.String, 'notes': fields.String, 'cidr': fields.String } IGNORELIST_FIELDS = { 'id': fields.Integer, 'prefix': fields.String, 'notes': fields.String, } AUDITORSETTING_FIELDS = { 'id': fields.Integer, 'disabled': fields.Boolean, 'issue_text': fields.String } ITEM_LINK_FIELDS = { 'id': fields.Integer, 'name': fields.String } class AuthenticatedService(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() super(AuthenticatedService, self).__init__() self.auth_dict = dict() if current_user.is_authenticated: roles_marshal = [] for role in current_user.roles: roles_marshal.append(marshal(role.__dict__, ROLE_FIELDS)) roles_marshal.append({"name": current_user.role}) for role in RBACRole.roles[current_user.role].get_parents(): roles_marshal.append({"name": role.name}) self.auth_dict = { "authenticated": True, "user": current_user.email, "roles": roles_marshal } else: if app.config.get('FRONTED_BY_NGINX'): url = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login') else: url = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login') self.auth_dict = { "authenticated": False, "user": None, "url": url } @app.after_request @crossdomain(allowed_origins=ORIGINS) def after(response): response.set_cookie('XSRF-COOKIE', generate_csrf()) return response
open_redirect
{ "code": [ " if current_user.is_authenticated():" ], "line_no": [ 147 ] }
{ "code": [ " if current_user.is_authenticated:" ], "line_no": [ 147 ] }
from security_monkey import app, db from flask_wtf.csrf import generate_csrf from security_monkey.auth.models import RBACRole from security_monkey.decorators import crossdomain from flask_restful import fields, marshal, Resource, reqparse from flask_login import current_user VAR_0 = [ 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('WEB_PORT')), 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('API_PORT')), 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('NGINX_PORT')), 'https://{}:80'.format(app.config.get('FQDN')) ] VAR_1 = { 'id': fields.Integer, 'date_created': fields.String, 'date_last_ephemeral_change': fields.String, 'active': fields.Boolean, 'item_id': fields.Integer } VAR_2 = { 'id': fields.Integer, 'region': fields.String, 'name': fields.String } VAR_3 = { 'id': fields.Integer, 'score': fields.Integer, 'issue': fields.String, 'notes': fields.String, 'justified': fields.Boolean, 'justification': fields.String, 'justified_date': fields.String, 'item_id': fields.Integer } VAR_4 = { 'id': fields.Integer, 'revision_id': fields.Integer, 'date_created': fields.String, 'text': fields.String } VAR_5 = { 'id': fields.Integer, 'date_created': fields.String, 'text': fields.String, 'item_id': fields.Integer } VAR_6 = { 'daily_audit_email': fields.Boolean, 'change_reports': fields.String } VAR_7 = { 'id': fields.Integer, 'name': fields.String, 'identifier': fields.String, 'notes': fields.String, 'active': fields.Boolean, 'third_party': fields.Boolean, 'account_type': fields.String } VAR_8 = { 'id': fields.Integer, 'active': fields.Boolean, 'email': fields.String, 'role': fields.String, 'confirmed_at': fields.String, 'daily_audit_email': fields.Boolean, 'change_reports': fields.String, 'last_login_at': fields.String, 'current_login_at': fields.String, 'login_count': fields.Integer, 'last_login_ip': fields.String, 'current_login_ip': fields.String } VAR_9 = { 'id': fields.Integer, 'name': fields.String, 'description': fields.String, } VAR_10 = { 'id': fields.Integer, 'name': fields.String, 'notes': fields.String, 'cidr': fields.String } VAR_11 = { 'id': fields.Integer, 'prefix': fields.String, 'notes': fields.String, } VAR_12 = { 'id': fields.Integer, 'disabled': fields.Boolean, 'issue_text': fields.String } VAR_13 = { 'id': fields.Integer, 'name': fields.String } class CLASS_0(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() super(CLASS_0, self).__init__() self.auth_dict = dict() if current_user.is_authenticated(): VAR_15 = [] for role in current_user.roles: VAR_15.append(marshal(role.__dict__, VAR_9)) VAR_15.append({"name": current_user.role}) for role in RBACRole.roles[current_user.role].get_parents(): VAR_15.append({"name": role.name}) self.auth_dict = { "authenticated": True, "user": current_user.email, "roles": VAR_15 } else: if app.config.get('FRONTED_BY_NGINX'): VAR_16 = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login') else: VAR_16 = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login') self.auth_dict = { "authenticated": False, "user": None, "url": VAR_16 } @app.after_request @crossdomain(allowed_origins=VAR_0) def FUNC_0(VAR_14): response.set_cookie('XSRF-COOKIE', generate_csrf()) return VAR_14
from security_monkey import app, db from flask_wtf.csrf import generate_csrf from security_monkey.auth.models import RBACRole from security_monkey.decorators import crossdomain from flask_restful import fields, marshal, Resource, reqparse from flask_login import current_user VAR_0 = [ 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('WEB_PORT')), 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('API_PORT')), 'https://{}:{}'.format(app.config.get('FQDN'), app.config.get('NGINX_PORT')), 'https://{}:80'.format(app.config.get('FQDN')) ] VAR_1 = { 'id': fields.Integer, 'date_created': fields.String, 'date_last_ephemeral_change': fields.String, 'active': fields.Boolean, 'item_id': fields.Integer } VAR_2 = { 'id': fields.Integer, 'region': fields.String, 'name': fields.String } VAR_3 = { 'id': fields.Integer, 'score': fields.Integer, 'issue': fields.String, 'notes': fields.String, 'justified': fields.Boolean, 'justification': fields.String, 'justified_date': fields.String, 'item_id': fields.Integer } VAR_4 = { 'id': fields.Integer, 'revision_id': fields.Integer, 'date_created': fields.String, 'text': fields.String } VAR_5 = { 'id': fields.Integer, 'date_created': fields.String, 'text': fields.String, 'item_id': fields.Integer } VAR_6 = { 'daily_audit_email': fields.Boolean, 'change_reports': fields.String } VAR_7 = { 'id': fields.Integer, 'name': fields.String, 'identifier': fields.String, 'notes': fields.String, 'active': fields.Boolean, 'third_party': fields.Boolean, 'account_type': fields.String } VAR_8 = { 'id': fields.Integer, 'active': fields.Boolean, 'email': fields.String, 'role': fields.String, 'confirmed_at': fields.String, 'daily_audit_email': fields.Boolean, 'change_reports': fields.String, 'last_login_at': fields.String, 'current_login_at': fields.String, 'login_count': fields.Integer, 'last_login_ip': fields.String, 'current_login_ip': fields.String } VAR_9 = { 'id': fields.Integer, 'name': fields.String, 'description': fields.String, } VAR_10 = { 'id': fields.Integer, 'name': fields.String, 'notes': fields.String, 'cidr': fields.String } VAR_11 = { 'id': fields.Integer, 'prefix': fields.String, 'notes': fields.String, } VAR_12 = { 'id': fields.Integer, 'disabled': fields.Boolean, 'issue_text': fields.String } VAR_13 = { 'id': fields.Integer, 'name': fields.String } class CLASS_0(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() super(CLASS_0, self).__init__() self.auth_dict = dict() if current_user.is_authenticated: VAR_15 = [] for role in current_user.roles: VAR_15.append(marshal(role.__dict__, VAR_9)) VAR_15.append({"name": current_user.role}) for role in RBACRole.roles[current_user.role].get_parents(): VAR_15.append({"name": role.name}) self.auth_dict = { "authenticated": True, "user": current_user.email, "roles": VAR_15 } else: if app.config.get('FRONTED_BY_NGINX'): VAR_16 = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login') else: VAR_16 = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login') self.auth_dict = { "authenticated": False, "user": None, "url": VAR_16 } @app.after_request @crossdomain(allowed_origins=VAR_0) def FUNC_0(VAR_14): response.set_cookie('XSRF-COOKIE', generate_csrf()) return VAR_14
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 19, 22, 25, 30, 31, 32, 33, 41, 42, 48, 49, 60, 61, 62, 63, 70, 71, 78, 79, 81, 85, 86, 96, 111, 117, 124, 130, 136, 141, 151, 153, 156, 172, 173, 179 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 19, 22, 25, 30, 31, 32, 33, 41, 42, 48, 49, 60, 61, 62, 63, 70, 71, 78, 79, 81, 85, 86, 96, 111, 117, 124, 130, 136, 141, 151, 153, 156, 172, 173, 179 ]
1CWE-79
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import json, datetime from frappe import _, scrub import frappe.desk.query_report from frappe.utils import cint, cstr from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.modules import make_boilerplate from frappe.core.doctype.page.page import delete_custom_role from frappe.core.doctype.custom_role.custom_role import get_custom_allowed_roles from frappe.desk.reportview import append_totals_row from six import iteritems from frappe.utils.safe_exec import safe_exec class Report(Document): def validate(self): """only administrator can save standard report""" if not self.module: self.module = frappe.db.get_value("DocType", self.ref_doctype, "module") if not self.is_standard: self.is_standard = "No" if frappe.session.user=="Administrator" and getattr(frappe.local.conf, 'developer_mode',0)==1: self.is_standard = "Yes" if self.is_standard == "No": # allow only script manager to edit scripts if self.report_type != 'Report Builder': frappe.only_for('Script Manager', True) if frappe.db.get_value("Report", self.name, "is_standard") == "Yes": frappe.throw(_("Cannot edit a standard report. Please duplicate and create a new report")) if self.is_standard == "Yes" and frappe.session.user!="Administrator": frappe.throw(_("Only Administrator can save a standard report. Please rename and save.")) if self.report_type == "Report Builder": self.update_report_json() def before_insert(self): self.set_doctype_roles() def on_update(self): self.export_doc() def on_trash(self): if (self.is_standard == 'Yes' and not cint(getattr(frappe.local.conf, 'developer_mode', 0)) and not frappe.flags.in_patch): frappe.throw(_("You are not allowed to delete Standard Report")) delete_custom_role('report', self.name) def get_columns(self): return [d.as_dict(no_default_fields = True) for d in self.columns] def set_doctype_roles(self): if not self.get('roles') and self.is_standard == 'No': meta = frappe.get_meta(self.ref_doctype) if not meta.istable: roles = [{'role': d.role} for d in meta.permissions if d.permlevel==0] self.set('roles', roles) def is_permitted(self): """Returns true if Has Role is not set or the user is allowed.""" from frappe.utils import has_common allowed = [d.role for d in frappe.get_all("Has Role", fields=["role"], filters={"parent": self.name})] custom_roles = get_custom_allowed_roles('report', self.name) allowed.extend(custom_roles) if not allowed: return True if has_common(frappe.get_roles(), allowed): return True def update_report_json(self): if not self.json: self.json = '{}' def export_doc(self): if frappe.flags.in_import: return if self.is_standard == 'Yes' and (frappe.local.conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.name]], record_module=self.module, create_init=True) self.create_report_py() def create_report_py(self): if self.report_type == "Script Report": make_boilerplate("controller.py", self, {"name": self.name}) make_boilerplate("controller.js", self, {"name": self.name}) def execute_query_report(self, filters): if not self.query: frappe.throw(_("Must specify a Query to run"), title=_('Report Document Error')) if not self.query.lower().startswith("select"): frappe.throw(_("Query must be a SELECT"), title=_('Report Document Error')) result = [list(t) for t in frappe.db.sql(self.query, filters, debug=True)] columns = self.get_columns() or [cstr(c[0]) for c in frappe.db.get_description()] return [columns, result] def execute_script_report(self, filters): # save the timestamp to automatically set to prepared threshold = 30 res = [] start_time = datetime.datetime.now() # The JOB if self.is_standard == 'Yes': res = self.execute_module(filters) else: res = self.execute_script(filters) # automatically set as prepared execution_time = (datetime.datetime.now() - start_time).total_seconds() if execution_time > threshold and not self.prepared_report: self.db_set('prepared_report', 1) frappe.cache().hset('report_execution_time', self.name, execution_time) return res def execute_module(self, filters): # report in python module module = self.module or frappe.db.get_value("DocType", self.ref_doctype, "module") method_name = get_report_module_dotted_path(module, self.name) + ".execute" return frappe.get_attr(method_name)(frappe._dict(filters)) def execute_script(self, filters): # server script loc = {"filters": frappe._dict(filters), 'data':None, 'result':None} safe_exec(self.report_script, None, loc) if loc['data']: return loc['data'] else: return self.get_columns(), loc['result'] def get_data(self, filters=None, limit=None, user=None, as_dict=False, ignore_prepared_report=False): if self.report_type in ('Query Report', 'Script Report', 'Custom Report'): columns, result = self.run_query_report(filters, user, ignore_prepared_report) else: columns, result = self.run_standard_report(filters, limit, user) if as_dict: result = self.build_data_dict(result, columns) return columns, result def run_query_report(self, filters, user, ignore_prepared_report=False): columns, result = [], [] data = frappe.desk.query_report.run(self.name, filters=filters, user=user, ignore_prepared_report=ignore_prepared_report) for d in data.get('columns'): if isinstance(d, dict): col = frappe._dict(d) if not col.fieldname: col.fieldname = col.label columns.append(col) else: fieldtype, options = "Data", None parts = d.split(':') if len(parts) > 1: if parts[1]: fieldtype, options = parts[1], None if fieldtype and '/' in fieldtype: fieldtype, options = fieldtype.split('/') columns.append(frappe._dict(label=parts[0], fieldtype=fieldtype, fieldname=parts[0], options=options)) result += data.get('result') return columns, result def run_standard_report(self, filters, limit, user): params = json.loads(self.json) columns = self.get_standard_report_columns(params) result = [] order_by, group_by, group_by_args = self.get_standard_report_order_by(params) _result = frappe.get_list(self.ref_doctype, fields = [ get_group_by_field(group_by_args, c[1]) if c[0] == '_aggregate_column' and group_by_args else Report._format([c[1], c[0]]) for c in columns ], filters = self.get_standard_report_filters(params, filters), order_by = order_by, group_by = group_by, as_list = True, limit = limit, user = user) columns = self.build_standard_report_columns(columns, group_by_args) result = result + [list(d) for d in _result] if params.get('add_totals_row'): result = append_totals_row(result) return columns, result @staticmethod def _format(parts): # sort by is saved as DocType.fieldname, covert it to sql return '`tab{0}`.`{1}`'.format(*parts) def get_standard_report_columns(self, params): if params.get('fields'): columns = params.get('fields') elif params.get('columns'): columns = params.get('columns') elif params.get('fields'): columns = params.get('fields') else: columns = [['name', self.ref_doctype]] for df in frappe.get_meta(self.ref_doctype).fields: if df.in_list_view: columns.append([df.fieldname, self.ref_doctype]) return columns def get_standard_report_filters(self, params, filters): _filters = params.get('filters') or [] if filters: for key, value in iteritems(filters): condition, _value = '=', value if isinstance(value, (list, tuple)): condition, _value = value _filters.append([key, condition, _value]) return _filters def get_standard_report_order_by(self, params): group_by_args = None if params.get('sort_by'): order_by = Report._format(params.get('sort_by').split('.')) + ' ' + params.get('sort_order') elif params.get('order_by'): order_by = params.get('order_by') else: order_by = Report._format([self.ref_doctype, 'modified']) + ' desc' if params.get('sort_by_next'): order_by += ', ' + Report._format(params.get('sort_by_next').split('.')) + ' ' + params.get('sort_order_next') group_by = None if params.get('group_by'): group_by_args = frappe._dict(params['group_by']) group_by = group_by_args['group_by'] order_by = '_aggregate_column desc' return order_by, group_by, group_by_args def build_standard_report_columns(self, columns, group_by_args): _columns = [] for (fieldname, doctype) in columns: meta = frappe.get_meta(doctype) if meta.get_field(fieldname): field = meta.get_field(fieldname) else: if fieldname == '_aggregate_column': label = get_group_by_column_label(group_by_args, meta) else: label = meta.get_label(fieldname) field = frappe._dict(fieldname=fieldname, label=label) # since name is the primary key for a document, it will always be a Link datatype if fieldname == "name": field.fieldtype = "Link" field.options = doctype _columns.append(field) return _columns def build_data_dict(self, result, columns): data = [] for row in result: if isinstance(row, (list, tuple)): _row = frappe._dict() for i, val in enumerate(row): _row[columns[i].get('fieldname')] = val elif isinstance(row, dict): # no need to convert from dict to dict _row = frappe._dict(row) data.append(_row) return data @Document.whitelist def toggle_disable(self, disable): self.db_set("disabled", cint(disable)) @frappe.whitelist() def is_prepared_report_disabled(report): return frappe.db.get_value('Report', report, 'disable_prepared_report') or 0 def get_report_module_dotted_path(module, report_name): return frappe.local.module_app[scrub(module)] + "." + scrub(module) \ + ".report." + scrub(report_name) + "." + scrub(report_name) def get_group_by_field(args, doctype): if args['aggregate_function'] == 'count': group_by_field = 'count(*) as _aggregate_column' else: group_by_field = '{0}(`tab{1}`.{2}) as _aggregate_column'.format( args.aggregate_function, doctype, args.aggregate_on ) return group_by_field def get_group_by_column_label(args, meta): if args['aggregate_function'] == 'count': label = 'Count' else: sql_fn_map = { 'avg': 'Average', 'sum': 'Sum' } aggregate_on_label = meta.get_label(args.aggregate_on) label = _('{function} of {fieldlabel}').format( function=sql_fn_map[args.aggregate_function], fieldlabel = aggregate_on_label ) return label
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import json, datetime from frappe import _, scrub import frappe.desk.query_report from frappe.utils import cint, cstr from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.modules import make_boilerplate from frappe.core.doctype.page.page import delete_custom_role from frappe.core.doctype.custom_role.custom_role import get_custom_allowed_roles from frappe.desk.reportview import append_totals_row from six import iteritems from frappe.utils.safe_exec import safe_exec class Report(Document): def validate(self): """only administrator can save standard report""" if not self.module: self.module = frappe.db.get_value("DocType", self.ref_doctype, "module") if not self.is_standard: self.is_standard = "No" if frappe.session.user=="Administrator" and getattr(frappe.local.conf, 'developer_mode',0)==1: self.is_standard = "Yes" if self.is_standard == "No": # allow only script manager to edit scripts if self.report_type != 'Report Builder': frappe.only_for('Script Manager', True) if frappe.db.get_value("Report", self.name, "is_standard") == "Yes": frappe.throw(_("Cannot edit a standard report. Please duplicate and create a new report")) if self.is_standard == "Yes" and frappe.session.user!="Administrator": frappe.throw(_("Only Administrator can save a standard report. Please rename and save.")) if self.report_type == "Report Builder": self.update_report_json() def before_insert(self): self.set_doctype_roles() def on_update(self): self.export_doc() def on_trash(self): if (self.is_standard == 'Yes' and not cint(getattr(frappe.local.conf, 'developer_mode', 0)) and not frappe.flags.in_patch): frappe.throw(_("You are not allowed to delete Standard Report")) delete_custom_role('report', self.name) def get_columns(self): return [d.as_dict(no_default_fields = True) for d in self.columns] @frappe.whitelist() def set_doctype_roles(self): if not self.get('roles') and self.is_standard == 'No': meta = frappe.get_meta(self.ref_doctype) if not meta.istable: roles = [{'role': d.role} for d in meta.permissions if d.permlevel==0] self.set('roles', roles) def is_permitted(self): """Returns true if Has Role is not set or the user is allowed.""" from frappe.utils import has_common allowed = [d.role for d in frappe.get_all("Has Role", fields=["role"], filters={"parent": self.name})] custom_roles = get_custom_allowed_roles('report', self.name) allowed.extend(custom_roles) if not allowed: return True if has_common(frappe.get_roles(), allowed): return True def update_report_json(self): if not self.json: self.json = '{}' def export_doc(self): if frappe.flags.in_import: return if self.is_standard == 'Yes' and (frappe.local.conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.name]], record_module=self.module, create_init=True) self.create_report_py() def create_report_py(self): if self.report_type == "Script Report": make_boilerplate("controller.py", self, {"name": self.name}) make_boilerplate("controller.js", self, {"name": self.name}) def execute_query_report(self, filters): if not self.query: frappe.throw(_("Must specify a Query to run"), title=_('Report Document Error')) if not self.query.lower().startswith("select"): frappe.throw(_("Query must be a SELECT"), title=_('Report Document Error')) result = [list(t) for t in frappe.db.sql(self.query, filters, debug=True)] columns = self.get_columns() or [cstr(c[0]) for c in frappe.db.get_description()] return [columns, result] def execute_script_report(self, filters): # save the timestamp to automatically set to prepared threshold = 30 res = [] start_time = datetime.datetime.now() # The JOB if self.is_standard == 'Yes': res = self.execute_module(filters) else: res = self.execute_script(filters) # automatically set as prepared execution_time = (datetime.datetime.now() - start_time).total_seconds() if execution_time > threshold and not self.prepared_report: self.db_set('prepared_report', 1) frappe.cache().hset('report_execution_time', self.name, execution_time) return res def execute_module(self, filters): # report in python module module = self.module or frappe.db.get_value("DocType", self.ref_doctype, "module") method_name = get_report_module_dotted_path(module, self.name) + ".execute" return frappe.get_attr(method_name)(frappe._dict(filters)) def execute_script(self, filters): # server script loc = {"filters": frappe._dict(filters), 'data':None, 'result':None} safe_exec(self.report_script, None, loc) if loc['data']: return loc['data'] else: return self.get_columns(), loc['result'] def get_data(self, filters=None, limit=None, user=None, as_dict=False, ignore_prepared_report=False): if self.report_type in ('Query Report', 'Script Report', 'Custom Report'): columns, result = self.run_query_report(filters, user, ignore_prepared_report) else: columns, result = self.run_standard_report(filters, limit, user) if as_dict: result = self.build_data_dict(result, columns) return columns, result def run_query_report(self, filters, user, ignore_prepared_report=False): columns, result = [], [] data = frappe.desk.query_report.run(self.name, filters=filters, user=user, ignore_prepared_report=ignore_prepared_report) for d in data.get('columns'): if isinstance(d, dict): col = frappe._dict(d) if not col.fieldname: col.fieldname = col.label columns.append(col) else: fieldtype, options = "Data", None parts = d.split(':') if len(parts) > 1: if parts[1]: fieldtype, options = parts[1], None if fieldtype and '/' in fieldtype: fieldtype, options = fieldtype.split('/') columns.append(frappe._dict(label=parts[0], fieldtype=fieldtype, fieldname=parts[0], options=options)) result += data.get('result') return columns, result def run_standard_report(self, filters, limit, user): params = json.loads(self.json) columns = self.get_standard_report_columns(params) result = [] order_by, group_by, group_by_args = self.get_standard_report_order_by(params) _result = frappe.get_list(self.ref_doctype, fields = [ get_group_by_field(group_by_args, c[1]) if c[0] == '_aggregate_column' and group_by_args else Report._format([c[1], c[0]]) for c in columns ], filters = self.get_standard_report_filters(params, filters), order_by = order_by, group_by = group_by, as_list = True, limit = limit, user = user) columns = self.build_standard_report_columns(columns, group_by_args) result = result + [list(d) for d in _result] if params.get('add_totals_row'): result = append_totals_row(result) return columns, result @staticmethod def _format(parts): # sort by is saved as DocType.fieldname, covert it to sql return '`tab{0}`.`{1}`'.format(*parts) def get_standard_report_columns(self, params): if params.get('fields'): columns = params.get('fields') elif params.get('columns'): columns = params.get('columns') elif params.get('fields'): columns = params.get('fields') else: columns = [['name', self.ref_doctype]] for df in frappe.get_meta(self.ref_doctype).fields: if df.in_list_view: columns.append([df.fieldname, self.ref_doctype]) return columns def get_standard_report_filters(self, params, filters): _filters = params.get('filters') or [] if filters: for key, value in iteritems(filters): condition, _value = '=', value if isinstance(value, (list, tuple)): condition, _value = value _filters.append([key, condition, _value]) return _filters def get_standard_report_order_by(self, params): group_by_args = None if params.get('sort_by'): order_by = Report._format(params.get('sort_by').split('.')) + ' ' + params.get('sort_order') elif params.get('order_by'): order_by = params.get('order_by') else: order_by = Report._format([self.ref_doctype, 'modified']) + ' desc' if params.get('sort_by_next'): order_by += ', ' + Report._format(params.get('sort_by_next').split('.')) + ' ' + params.get('sort_order_next') group_by = None if params.get('group_by'): group_by_args = frappe._dict(params['group_by']) group_by = group_by_args['group_by'] order_by = '_aggregate_column desc' return order_by, group_by, group_by_args def build_standard_report_columns(self, columns, group_by_args): _columns = [] for (fieldname, doctype) in columns: meta = frappe.get_meta(doctype) if meta.get_field(fieldname): field = meta.get_field(fieldname) else: if fieldname == '_aggregate_column': label = get_group_by_column_label(group_by_args, meta) else: label = meta.get_label(fieldname) field = frappe._dict(fieldname=fieldname, label=label) # since name is the primary key for a document, it will always be a Link datatype if fieldname == "name": field.fieldtype = "Link" field.options = doctype _columns.append(field) return _columns def build_data_dict(self, result, columns): data = [] for row in result: if isinstance(row, (list, tuple)): _row = frappe._dict() for i, val in enumerate(row): _row[columns[i].get('fieldname')] = val elif isinstance(row, dict): # no need to convert from dict to dict _row = frappe._dict(row) data.append(_row) return data @frappe.whitelist() def toggle_disable(self, disable): self.db_set("disabled", cint(disable)) @frappe.whitelist() def is_prepared_report_disabled(report): return frappe.db.get_value('Report', report, 'disable_prepared_report') or 0 def get_report_module_dotted_path(module, report_name): return frappe.local.module_app[scrub(module)] + "." + scrub(module) \ + ".report." + scrub(report_name) + "." + scrub(report_name) def get_group_by_field(args, doctype): if args['aggregate_function'] == 'count': group_by_field = 'count(*) as _aggregate_column' else: group_by_field = '{0}(`tab{1}`.{2}) as _aggregate_column'.format( args.aggregate_function, doctype, args.aggregate_on ) return group_by_field def get_group_by_column_label(args, meta): if args['aggregate_function'] == 'count': label = 'Count' else: sql_fn_map = { 'avg': 'Average', 'sum': 'Sum' } aggregate_on_label = meta.get_label(args.aggregate_on) label = _('{function} of {fieldlabel}').format( function=sql_fn_map[args.aggregate_function], fieldlabel = aggregate_on_label ) return label
xss
{ "code": [ "\t@Document.whitelist" ], "line_no": [ 307 ] }
{ "code": [ "\t@frappe.whitelist()", "\t@frappe.whitelist()" ], "line_no": [ 61, 308 ] }
from __future__ import unicode_literals import frappe import json, datetime from frappe import _, scrub import frappe.desk.query_report from frappe.utils import cint, cstr from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.modules import make_boilerplate from frappe.core.doctype.page.page import delete_custom_role from frappe.core.doctype.custom_role.custom_role import get_custom_allowed_roles from frappe.desk.reportview import append_totals_row from six import .iteritems from frappe.utils.safe_exec import safe_exec class CLASS_0(Document): def FUNC_4(self): if not self.module: self.module = frappe.db.get_value("DocType", self.ref_doctype, "module") if not self.is_standard: self.is_standard = "No" if frappe.session.user=="Administrator" and getattr(frappe.local.conf, 'developer_mode',0)==1: self.is_standard = "Yes" if self.is_standard == "No": if self.report_type != 'Report Builder': frappe.only_for('Script Manager', True) if frappe.db.get_value("Report", self.name, "is_standard") == "Yes": frappe.throw(_("Cannot edit a standard VAR_0. Please duplicate and create a new report")) if self.is_standard == "Yes" and frappe.session.user!="Administrator": frappe.throw(_("Only Administrator can save a standard VAR_0. Please rename and save.")) if self.report_type == "Report Builder": self.update_report_json() def FUNC_5(self): self.set_doctype_roles() def FUNC_6(self): self.export_doc() def FUNC_7(self): if (self.is_standard == 'Yes' and not cint(getattr(frappe.local.conf, 'developer_mode', 0)) and not frappe.flags.in_patch): frappe.throw(_("You are not VAR_17 to delete Standard Report")) delete_custom_role('report', self.name) def FUNC_8(self): return [d.as_dict(no_default_fields = True) for d in self.columns] def FUNC_9(self): if not self.get('roles') and self.is_standard == 'No': VAR_5 = frappe.get_meta(self.ref_doctype) if not VAR_5.istable: VAR_35 = [{'role': d.role} for d in VAR_5.permissions if d.permlevel==0] self.set('roles', VAR_35) def FUNC_10(self): from frappe.utils import has_common VAR_17 = [d.role for d in frappe.get_all("Has Role", fields=["role"], VAR_6={"parent": self.name})] VAR_18 = get_custom_allowed_roles('report', self.name) VAR_17.extend(VAR_18) if not VAR_17: return True if has_common(frappe.get_roles(), VAR_17): return True def FUNC_11(self): if not self.json: self.json = '{}' def FUNC_12(self): if frappe.flags.in_import: return if self.is_standard == 'Yes' and (frappe.local.conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.name]], record_module=self.module, create_init=True) self.create_report_py() def FUNC_13(self): if self.report_type == "Script Report": make_boilerplate("controller.py", self, {"name": self.name}) make_boilerplate("controller.js", self, {"name": self.name}) def FUNC_14(self, VAR_6): if not self.query: frappe.throw(_("Must specify a Query to run"), title=_('Report Document Error')) if not self.query.lower().startswith("select"): frappe.throw(_("Query must be a SELECT"), title=_('Report Document Error')) VAR_15 = [list(t) for t in frappe.db.sql(self.query, VAR_6, debug=True)] VAR_13 = self.get_columns() or [cstr(c[0]) for c in frappe.db.get_description()] return [VAR_13, VAR_15] def FUNC_15(self, VAR_6): VAR_19 = 30 VAR_20 = [] VAR_21 = datetime.datetime.now() if self.is_standard == 'Yes': VAR_20 = self.execute_module(VAR_6) else: VAR_20 = self.execute_script(VAR_6) VAR_22 = (datetime.datetime.now() - VAR_21).total_seconds() if VAR_22 > VAR_19 and not self.prepared_report: self.db_set('prepared_report', 1) frappe.cache().hset('report_execution_time', self.name, VAR_22) return VAR_20 def FUNC_16(self, VAR_6): module = self.module or frappe.db.get_value("DocType", self.ref_doctype, "module") VAR_23 = FUNC_1(VAR_1, self.name) + ".execute" return frappe.get_attr(VAR_23)(frappe._dict(VAR_6)) def FUNC_17(self, VAR_6): VAR_24 = {"filters": frappe._dict(VAR_6), 'data':None, 'result':None} safe_exec(self.report_script, None, VAR_24) if VAR_24['data']: return VAR_24['data'] else: return self.get_columns(), VAR_24['result'] def FUNC_18(self, VAR_6=None, VAR_7=None, VAR_8=None, VAR_9=False, VAR_10=False): if self.report_type in ('Query Report', 'Script Report', 'Custom Report'): VAR_13, VAR_15 = self.run_query_report(VAR_6, VAR_8, VAR_10) else: VAR_13, VAR_15 = self.run_standard_report(VAR_6, VAR_7, VAR_8) if VAR_9: VAR_15 = self.build_data_dict(VAR_15, VAR_13) return VAR_13, VAR_15 def FUNC_19(self, VAR_6, VAR_8, VAR_10=False): VAR_13, VAR_15 = [], [] VAR_25 = frappe.desk.query_report.run(self.name, VAR_6=filters, VAR_8=user, VAR_10=ignore_prepared_report) for d in VAR_25.get('columns'): if isinstance(d, dict): VAR_36 = frappe._dict(d) if not VAR_36.fieldname: VAR_36.fieldname = VAR_36.label VAR_13.append(VAR_36) else: VAR_37, VAR_38 = "Data", None VAR_11 = d.split(':') if len(VAR_11) > 1: if VAR_11[1]: VAR_37, VAR_38 = VAR_11[1], None if VAR_37 and '/' in VAR_37: fieldtype, VAR_38 = VAR_37.split('/') VAR_13.append(frappe._dict(VAR_32=VAR_11[0], VAR_37=fieldtype, fieldname=VAR_11[0], VAR_38=options)) VAR_15 += VAR_25.get('result') return VAR_13, VAR_15 def FUNC_20(self, VAR_6, VAR_7, VAR_8): VAR_12 = json.loads(self.json) VAR_13 = self.get_standard_report_columns(VAR_12) VAR_15 = [] VAR_26, VAR_27, VAR_14 = self.get_standard_report_order_by(VAR_12) VAR_28 = frappe.get_list(self.ref_doctype, fields = [ FUNC_2(VAR_14, c[1]) if c[0] == '_aggregate_column' and VAR_14 else CLASS_0._format([c[1], c[0]]) for c in VAR_13 ], VAR_6 = self.get_standard_report_filters(VAR_12, VAR_6), VAR_26 = order_by, VAR_27 = group_by, as_list = True, VAR_7 = limit, VAR_8 = user) VAR_13 = self.build_standard_report_columns(VAR_13, VAR_14) VAR_15 = result + [list(d) for d in VAR_28] if VAR_12.get('add_totals_row'): VAR_15 = append_totals_row(VAR_15) return VAR_13, VAR_15 @staticmethod def FUNC_21(VAR_11): return '`tab{0}`.`{1}`'.format(*VAR_11) def FUNC_22(self, VAR_12): if VAR_12.get('fields'): VAR_13 = VAR_12.get('fields') elif VAR_12.get('columns'): VAR_13 = VAR_12.get('columns') elif VAR_12.get('fields'): VAR_13 = VAR_12.get('fields') else: VAR_13 = [['name', self.ref_doctype]] for df in frappe.get_meta(self.ref_doctype).fields: if df.in_list_view: VAR_13.append([df.fieldname, self.ref_doctype]) return VAR_13 def FUNC_23(self, VAR_12, VAR_6): VAR_29 = VAR_12.get('filters') or [] if VAR_6: for key, value in iteritems(VAR_6): VAR_39, VAR_40 = '=', value if isinstance(value, (list, tuple)): VAR_39, VAR_40 = value VAR_29.append([key, VAR_39, VAR_40]) return VAR_29 def FUNC_24(self, VAR_12): VAR_14 = None if VAR_12.get('sort_by'): VAR_26 = CLASS_0._format(VAR_12.get('sort_by').split('.')) + ' ' + VAR_12.get('sort_order') elif VAR_12.get('order_by'): VAR_26 = VAR_12.get('order_by') else: VAR_26 = CLASS_0._format([self.ref_doctype, 'modified']) + ' desc' if VAR_12.get('sort_by_next'): VAR_26 += ', ' + CLASS_0._format(VAR_12.get('sort_by_next').split('.')) + ' ' + VAR_12.get('sort_order_next') VAR_27 = None if VAR_12.get('group_by'): VAR_14 = frappe._dict(VAR_12['group_by']) VAR_27 = VAR_14['group_by'] VAR_26 = '_aggregate_column desc' return VAR_26, VAR_27, VAR_14 def FUNC_25(self, VAR_13, VAR_14): VAR_30 = [] for (fieldname, VAR_4) in VAR_13: VAR_5 = frappe.get_meta(VAR_4) if VAR_5.get_field(fieldname): VAR_41 = VAR_5.get_field(fieldname) else: if fieldname == '_aggregate_column': VAR_32 = FUNC_3(VAR_14, VAR_5) else: VAR_32 = VAR_5.get_label(fieldname) VAR_41 = frappe._dict(fieldname=fieldname, VAR_32=label) if fieldname == "name": VAR_41.fieldtype = "Link" VAR_41.options = VAR_4 VAR_30.append(VAR_41) return VAR_30 def FUNC_26(self, VAR_15, VAR_13): VAR_25 = [] for row in VAR_15: if isinstance(row, (list, tuple)): VAR_42 = frappe._dict() for VAR_43, val in enumerate(row): VAR_42[VAR_13[VAR_43].get('fieldname')] = val elif isinstance(row, dict): VAR_42 = frappe._dict(row) VAR_25.append(VAR_42) return VAR_25 @Document.whitelist def FUNC_27(self, VAR_16): self.db_set("disabled", cint(VAR_16)) @frappe.whitelist() def FUNC_0(VAR_0): return frappe.db.get_value('Report', VAR_0, 'disable_prepared_report') or 0 def FUNC_1(VAR_1, VAR_2): return frappe.local.module_app[scrub(VAR_1)] + "." + scrub(VAR_1) \ + ".report." + scrub(VAR_2) + "." + scrub(VAR_2) def FUNC_2(VAR_3, VAR_4): if VAR_3['aggregate_function'] == 'count': VAR_31 = 'count(*) as _aggregate_column' else: VAR_31 = '{0}(`tab{1}`.{2}) as _aggregate_column'.format( VAR_3.aggregate_function, VAR_4, VAR_3.aggregate_on ) return VAR_31 def FUNC_3(VAR_3, VAR_5): if VAR_3['aggregate_function'] == 'count': VAR_32 = 'Count' else: VAR_33 = { 'avg': 'Average', 'sum': 'Sum' } VAR_34 = VAR_5.get_label(VAR_3.aggregate_on) VAR_32 = _('{function} of {fieldlabel}').format( function=VAR_33[VAR_3.aggregate_function], fieldlabel = VAR_34 ) return VAR_32
from __future__ import unicode_literals import frappe import json, datetime from frappe import _, scrub import frappe.desk.query_report from frappe.utils import cint, cstr from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.modules import make_boilerplate from frappe.core.doctype.page.page import delete_custom_role from frappe.core.doctype.custom_role.custom_role import get_custom_allowed_roles from frappe.desk.reportview import append_totals_row from six import .iteritems from frappe.utils.safe_exec import safe_exec class CLASS_0(Document): def FUNC_4(self): if not self.module: self.module = frappe.db.get_value("DocType", self.ref_doctype, "module") if not self.is_standard: self.is_standard = "No" if frappe.session.user=="Administrator" and getattr(frappe.local.conf, 'developer_mode',0)==1: self.is_standard = "Yes" if self.is_standard == "No": if self.report_type != 'Report Builder': frappe.only_for('Script Manager', True) if frappe.db.get_value("Report", self.name, "is_standard") == "Yes": frappe.throw(_("Cannot edit a standard VAR_0. Please duplicate and create a new report")) if self.is_standard == "Yes" and frappe.session.user!="Administrator": frappe.throw(_("Only Administrator can save a standard VAR_0. Please rename and save.")) if self.report_type == "Report Builder": self.update_report_json() def FUNC_5(self): self.set_doctype_roles() def FUNC_6(self): self.export_doc() def FUNC_7(self): if (self.is_standard == 'Yes' and not cint(getattr(frappe.local.conf, 'developer_mode', 0)) and not frappe.flags.in_patch): frappe.throw(_("You are not VAR_17 to delete Standard Report")) delete_custom_role('report', self.name) def FUNC_8(self): return [d.as_dict(no_default_fields = True) for d in self.columns] @frappe.whitelist() def FUNC_9(self): if not self.get('roles') and self.is_standard == 'No': VAR_5 = frappe.get_meta(self.ref_doctype) if not VAR_5.istable: VAR_35 = [{'role': d.role} for d in VAR_5.permissions if d.permlevel==0] self.set('roles', VAR_35) def FUNC_10(self): from frappe.utils import has_common VAR_17 = [d.role for d in frappe.get_all("Has Role", fields=["role"], VAR_6={"parent": self.name})] VAR_18 = get_custom_allowed_roles('report', self.name) VAR_17.extend(VAR_18) if not VAR_17: return True if has_common(frappe.get_roles(), VAR_17): return True def FUNC_11(self): if not self.json: self.json = '{}' def FUNC_12(self): if frappe.flags.in_import: return if self.is_standard == 'Yes' and (frappe.local.conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.name]], record_module=self.module, create_init=True) self.create_report_py() def FUNC_13(self): if self.report_type == "Script Report": make_boilerplate("controller.py", self, {"name": self.name}) make_boilerplate("controller.js", self, {"name": self.name}) def FUNC_14(self, VAR_6): if not self.query: frappe.throw(_("Must specify a Query to run"), title=_('Report Document Error')) if not self.query.lower().startswith("select"): frappe.throw(_("Query must be a SELECT"), title=_('Report Document Error')) VAR_15 = [list(t) for t in frappe.db.sql(self.query, VAR_6, debug=True)] VAR_13 = self.get_columns() or [cstr(c[0]) for c in frappe.db.get_description()] return [VAR_13, VAR_15] def FUNC_15(self, VAR_6): VAR_19 = 30 VAR_20 = [] VAR_21 = datetime.datetime.now() if self.is_standard == 'Yes': VAR_20 = self.execute_module(VAR_6) else: VAR_20 = self.execute_script(VAR_6) VAR_22 = (datetime.datetime.now() - VAR_21).total_seconds() if VAR_22 > VAR_19 and not self.prepared_report: self.db_set('prepared_report', 1) frappe.cache().hset('report_execution_time', self.name, VAR_22) return VAR_20 def FUNC_16(self, VAR_6): module = self.module or frappe.db.get_value("DocType", self.ref_doctype, "module") VAR_23 = FUNC_1(VAR_1, self.name) + ".execute" return frappe.get_attr(VAR_23)(frappe._dict(VAR_6)) def FUNC_17(self, VAR_6): VAR_24 = {"filters": frappe._dict(VAR_6), 'data':None, 'result':None} safe_exec(self.report_script, None, VAR_24) if VAR_24['data']: return VAR_24['data'] else: return self.get_columns(), VAR_24['result'] def FUNC_18(self, VAR_6=None, VAR_7=None, VAR_8=None, VAR_9=False, VAR_10=False): if self.report_type in ('Query Report', 'Script Report', 'Custom Report'): VAR_13, VAR_15 = self.run_query_report(VAR_6, VAR_8, VAR_10) else: VAR_13, VAR_15 = self.run_standard_report(VAR_6, VAR_7, VAR_8) if VAR_9: VAR_15 = self.build_data_dict(VAR_15, VAR_13) return VAR_13, VAR_15 def FUNC_19(self, VAR_6, VAR_8, VAR_10=False): VAR_13, VAR_15 = [], [] VAR_25 = frappe.desk.query_report.run(self.name, VAR_6=filters, VAR_8=user, VAR_10=ignore_prepared_report) for d in VAR_25.get('columns'): if isinstance(d, dict): VAR_36 = frappe._dict(d) if not VAR_36.fieldname: VAR_36.fieldname = VAR_36.label VAR_13.append(VAR_36) else: VAR_37, VAR_38 = "Data", None VAR_11 = d.split(':') if len(VAR_11) > 1: if VAR_11[1]: VAR_37, VAR_38 = VAR_11[1], None if VAR_37 and '/' in VAR_37: fieldtype, VAR_38 = VAR_37.split('/') VAR_13.append(frappe._dict(VAR_32=VAR_11[0], VAR_37=fieldtype, fieldname=VAR_11[0], VAR_38=options)) VAR_15 += VAR_25.get('result') return VAR_13, VAR_15 def FUNC_20(self, VAR_6, VAR_7, VAR_8): VAR_12 = json.loads(self.json) VAR_13 = self.get_standard_report_columns(VAR_12) VAR_15 = [] VAR_26, VAR_27, VAR_14 = self.get_standard_report_order_by(VAR_12) VAR_28 = frappe.get_list(self.ref_doctype, fields = [ FUNC_2(VAR_14, c[1]) if c[0] == '_aggregate_column' and VAR_14 else CLASS_0._format([c[1], c[0]]) for c in VAR_13 ], VAR_6 = self.get_standard_report_filters(VAR_12, VAR_6), VAR_26 = order_by, VAR_27 = group_by, as_list = True, VAR_7 = limit, VAR_8 = user) VAR_13 = self.build_standard_report_columns(VAR_13, VAR_14) VAR_15 = result + [list(d) for d in VAR_28] if VAR_12.get('add_totals_row'): VAR_15 = append_totals_row(VAR_15) return VAR_13, VAR_15 @staticmethod def FUNC_21(VAR_11): return '`tab{0}`.`{1}`'.format(*VAR_11) def FUNC_22(self, VAR_12): if VAR_12.get('fields'): VAR_13 = VAR_12.get('fields') elif VAR_12.get('columns'): VAR_13 = VAR_12.get('columns') elif VAR_12.get('fields'): VAR_13 = VAR_12.get('fields') else: VAR_13 = [['name', self.ref_doctype]] for df in frappe.get_meta(self.ref_doctype).fields: if df.in_list_view: VAR_13.append([df.fieldname, self.ref_doctype]) return VAR_13 def FUNC_23(self, VAR_12, VAR_6): VAR_29 = VAR_12.get('filters') or [] if VAR_6: for key, value in iteritems(VAR_6): VAR_39, VAR_40 = '=', value if isinstance(value, (list, tuple)): VAR_39, VAR_40 = value VAR_29.append([key, VAR_39, VAR_40]) return VAR_29 def FUNC_24(self, VAR_12): VAR_14 = None if VAR_12.get('sort_by'): VAR_26 = CLASS_0._format(VAR_12.get('sort_by').split('.')) + ' ' + VAR_12.get('sort_order') elif VAR_12.get('order_by'): VAR_26 = VAR_12.get('order_by') else: VAR_26 = CLASS_0._format([self.ref_doctype, 'modified']) + ' desc' if VAR_12.get('sort_by_next'): VAR_26 += ', ' + CLASS_0._format(VAR_12.get('sort_by_next').split('.')) + ' ' + VAR_12.get('sort_order_next') VAR_27 = None if VAR_12.get('group_by'): VAR_14 = frappe._dict(VAR_12['group_by']) VAR_27 = VAR_14['group_by'] VAR_26 = '_aggregate_column desc' return VAR_26, VAR_27, VAR_14 def FUNC_25(self, VAR_13, VAR_14): VAR_30 = [] for (fieldname, VAR_4) in VAR_13: VAR_5 = frappe.get_meta(VAR_4) if VAR_5.get_field(fieldname): VAR_41 = VAR_5.get_field(fieldname) else: if fieldname == '_aggregate_column': VAR_32 = FUNC_3(VAR_14, VAR_5) else: VAR_32 = VAR_5.get_label(fieldname) VAR_41 = frappe._dict(fieldname=fieldname, VAR_32=label) if fieldname == "name": VAR_41.fieldtype = "Link" VAR_41.options = VAR_4 VAR_30.append(VAR_41) return VAR_30 def FUNC_26(self, VAR_15, VAR_13): VAR_25 = [] for row in VAR_15: if isinstance(row, (list, tuple)): VAR_42 = frappe._dict() for VAR_43, val in enumerate(row): VAR_42[VAR_13[VAR_43].get('fieldname')] = val elif isinstance(row, dict): VAR_42 = frappe._dict(row) VAR_25.append(VAR_42) return VAR_25 @frappe.whitelist() def FUNC_27(self, VAR_16): self.db_set("disabled", cint(VAR_16)) @frappe.whitelist() def FUNC_0(VAR_0): return frappe.db.get_value('Report', VAR_0, 'disable_prepared_report') or 0 def FUNC_1(VAR_1, VAR_2): return frappe.local.module_app[scrub(VAR_1)] + "." + scrub(VAR_1) \ + ".report." + scrub(VAR_2) + "." + scrub(VAR_2) def FUNC_2(VAR_3, VAR_4): if VAR_3['aggregate_function'] == 'count': VAR_31 = 'count(*) as _aggregate_column' else: VAR_31 = '{0}(`tab{1}`.{2}) as _aggregate_column'.format( VAR_3.aggregate_function, VAR_4, VAR_3.aggregate_on ) return VAR_31 def FUNC_3(VAR_3, VAR_5): if VAR_3['aggregate_function'] == 'count': VAR_32 = 'Count' else: VAR_33 = { 'avg': 'Average', 'sum': 'Sum' } VAR_34 = VAR_5.get_label(VAR_3.aggregate_on) VAR_32 = _('{function} of {fieldlabel}').format( function=VAR_33[VAR_3.aggregate_function], fieldlabel = VAR_34 ) return VAR_32
[ 1, 2, 3, 18, 19, 25, 30, 32, 35, 38, 41, 44, 47, 50, 57, 60, 67, 71, 74, 77, 80, 83, 87, 91, 95, 97, 102, 106, 109, 112, 114, 116, 119, 121, 122, 127, 128, 132, 134, 136, 138, 142, 144, 151, 157, 160, 162, 167, 182, 184, 186, 188, 194, 206, 208, 210, 213, 215, 218, 220, 233, 235, 238, 245, 247, 252, 257, 260, 266, 268, 271, 274, 282, 284, 285, 289, 292, 301, 304, 306, 310, 315, 319, 329, 331, 346, 22, 69 ]
[ 1, 2, 3, 18, 19, 25, 30, 32, 35, 38, 41, 44, 47, 50, 57, 60, 68, 72, 75, 78, 81, 84, 88, 92, 96, 98, 103, 107, 110, 113, 115, 117, 120, 122, 123, 128, 129, 133, 135, 137, 139, 143, 145, 152, 158, 161, 163, 168, 183, 185, 187, 189, 195, 207, 209, 211, 214, 216, 219, 221, 234, 236, 239, 246, 248, 253, 258, 261, 267, 269, 272, 275, 283, 285, 286, 290, 293, 302, 305, 307, 311, 316, 320, 330, 332, 347, 22, 70 ]
1CWE-79
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # from datetime import timedelta from django.urls import reverse from django.utils import timezone from weblate.trans.tests.test_views import ViewTestCase from weblate.trans.views.reports import generate_counts, generate_credits COUNTS_DATA = [ { "count": 1, "count_edit": 0, "count_new": 1, "name": "Weblate Test", "words": 2, "words_edit": 0, "words_new": 2, "chars": 14, "chars_edit": 0, "chars_new": 14, "email": "weblate@example.org", "t_chars": 14, "t_chars_edit": 0, "t_chars_new": 14, "t_words": 2, "t_words_edit": 0, "t_words_new": 2, "count_approve": 0, "words_approve": 0, "chars_approve": 0, "t_chars_approve": 0, "t_words_approve": 0, "edits": 14, "edits_approve": 0, "edits_edit": 0, "edits_new": 14, } ] class BaseReportsTest(ViewTestCase): def setUp(self): super().setUp() self.user.is_superuser = True self.user.save() def add_change(self): self.edit_unit("Hello, world!\n", "Nazdar svete!\n") class ReportsTest(BaseReportsTest): def test_credits_empty(self): data = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual(data, []) def test_credits_one(self, expected_count=1): self.add_change() data = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual( data, [{"Czech": [("weblate@example.org", "Weblate Test", expected_count)]}] ) def test_credits_more(self): self.edit_unit("Hello, world!\n", "Nazdar svete2!\n") self.test_credits_one(expected_count=2) def test_counts_one(self): self.add_change() data = generate_counts( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), component=self.component, ) self.assertEqual(data, COUNTS_DATA) class ReportsComponentTest(BaseReportsTest): def get_kwargs(self): return self.kw_component def get_credits(self, style): self.add_change() return self.client.post( reverse("credits", kwargs=self.get_kwargs()), { "period": "", "style": style, "start_date": "2000-01-01", "end_date": "2100-01-01", }, ) def test_credits_view_json(self): response = self.get_credits("json") self.assertEqual(response.status_code, 200) self.assertJSONEqual( response.content.decode(), [{"Czech": [["weblate@example.org", "Weblate Test", 1]]}], ) def test_credits_view_rst(self): response = self.get_credits("rst") self.assertEqual(response.status_code, 200) self.assertEqual( response.content.decode(), "\n\n* Czech\n\n * Weblate Test <weblate@example.org> (1)\n\n", ) def test_credits_view_html(self): response = self.get_credits("html") self.assertEqual(response.status_code, 200) self.assertHTMLEqual( response.content.decode(), "<table>\n" "<tr>\n<th>Czech</th>\n" '<td><ul><li><a href="mailto:weblate@example.org">' "Weblate Test</a> (1)</li></ul></td>\n</tr>\n" "</table>", ) def get_counts(self, style, **kwargs): self.add_change() params = { "style": style, "period": "", "start_date": "2000-01-01", "end_date": "2100-01-01", } params.update(kwargs) return self.client.post(reverse("counts", kwargs=self.get_kwargs()), params) def test_counts_view_json(self): response = self.get_counts("json") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), COUNTS_DATA) def test_counts_view_30days(self): response = self.get_counts("json", period="30days") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), COUNTS_DATA) def test_counts_view_this_month(self): response = self.get_counts("json", period="this-month") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), COUNTS_DATA) def test_counts_view_month(self): response = self.get_counts("json", period="month") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), []) def test_counts_view_year(self): response = self.get_counts("json", period="year") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), []) def test_counts_view_this_year(self): response = self.get_counts("json", period="this-year") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), COUNTS_DATA) def test_counts_view_rst(self): response = self.get_counts("rst") self.assertEqual(response.status_code, 200) self.assertContains(response, "weblate@example.org") def test_counts_view_html(self): response = self.get_counts("html") self.assertEqual(response.status_code, 200) self.assertHTMLEqual( response.content.decode(), """ <table> <tr> <th>Name</th> <th>Email</th> <th>Count total</th> <th>Edits total</th> <th>Source words total</th> <th>Source chars total</th> <th>Target words total</th> <th>Target chars total</th> <th>Count new</th> <th>Edits new</th> <th>Source words new</th> <th>Source chars new</th> <th>Target words new</th> <th>Target chars new</th> <th>Count approved</th> <th>Edits approved</th> <th>Source words approved</th> <th>Source chars approved</th> <th>Target words approved</th> <th>Target chars approved</th> <th>Count edited</th> <th>Edits edited</th> <th>Source words edited</th> <th>Source chars edited</th> <th>Target words edited</th> <th>Target chars edited</th> </tr> <tr> <td>Weblate Test</td> <td>weblate@example.org</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> </table> """, ) class ReportsProjectTest(ReportsComponentTest): def get_kwargs(self): return self.kw_project class ReportsGlobalTest(ReportsComponentTest): def get_kwargs(self): return {}
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # from datetime import timedelta from django.urls import reverse from django.utils import timezone from weblate.trans.tests.test_views import ViewTestCase from weblate.trans.views.reports import generate_counts, generate_credits COUNTS_DATA = [ { "count": 1, "count_edit": 0, "count_new": 1, "name": "Weblate <b>Test</b>", "words": 2, "words_edit": 0, "words_new": 2, "chars": 14, "chars_edit": 0, "chars_new": 14, "email": "weblate@example.org", "t_chars": 14, "t_chars_edit": 0, "t_chars_new": 14, "t_words": 2, "t_words_edit": 0, "t_words_new": 2, "count_approve": 0, "words_approve": 0, "chars_approve": 0, "t_chars_approve": 0, "t_words_approve": 0, "edits": 14, "edits_approve": 0, "edits_edit": 0, "edits_new": 14, } ] class BaseReportsTest(ViewTestCase): def setUp(self): super().setUp() self.user.is_superuser = True self.user.full_name = "Weblate <b>Test</b>" self.user.save() self.maxDiff = None def add_change(self): self.edit_unit("Hello, world!\n", "Nazdar svete!\n") class ReportsTest(BaseReportsTest): def test_credits_empty(self): data = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual(data, []) def test_credits_one(self, expected_count=1): self.add_change() data = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual( data, [ { "Czech": [ ("weblate@example.org", "Weblate <b>Test</b>", expected_count) ] } ], ) def test_credits_more(self): self.edit_unit("Hello, world!\n", "Nazdar svete2!\n") self.test_credits_one(expected_count=2) def test_counts_one(self): self.add_change() data = generate_counts( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), component=self.component, ) self.assertEqual(data, COUNTS_DATA) class ReportsComponentTest(BaseReportsTest): def get_kwargs(self): return self.kw_component def get_credits(self, style): self.add_change() return self.client.post( reverse("credits", kwargs=self.get_kwargs()), { "period": "", "style": style, "start_date": "2000-01-01", "end_date": "2100-01-01", }, ) def test_credits_view_json(self): response = self.get_credits("json") self.assertEqual(response.status_code, 200) self.assertJSONEqual( response.content.decode(), [{"Czech": [["weblate@example.org", "Weblate <b>Test</b>", 1]]}], ) def test_credits_view_rst(self): response = self.get_credits("rst") self.assertEqual(response.status_code, 200) self.assertEqual( response.content.decode(), """ * Czech * Weblate &lt;b&gt;Test&lt;/b&gt; <weblate@example.org> (1) """, ) def test_credits_view_html(self): response = self.get_credits("html") self.assertEqual(response.status_code, 200) self.assertHTMLEqual( response.content.decode(), "<table>\n" "<tr>\n<th>Czech</th>\n" '<td><ul><li><a href="mailto:weblate@example.org">' "Weblate &lt;b&gt;Test&lt;/b&gt;</a> (1)</li></ul></td>\n</tr>\n" "</table>", ) def get_counts(self, style, **kwargs): self.add_change() params = { "style": style, "period": "", "start_date": "2000-01-01", "end_date": "2100-01-01", } params.update(kwargs) return self.client.post(reverse("counts", kwargs=self.get_kwargs()), params) def test_counts_view_json(self): response = self.get_counts("json") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), COUNTS_DATA) def test_counts_view_30days(self): response = self.get_counts("json", period="30days") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), COUNTS_DATA) def test_counts_view_this_month(self): response = self.get_counts("json", period="this-month") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), COUNTS_DATA) def test_counts_view_month(self): response = self.get_counts("json", period="month") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), []) def test_counts_view_year(self): response = self.get_counts("json", period="year") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), []) def test_counts_view_this_year(self): response = self.get_counts("json", period="this-year") self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content.decode(), COUNTS_DATA) def test_counts_view_rst(self): response = self.get_counts("rst") self.assertEqual(response.status_code, 200) self.assertContains(response, "weblate@example.org") def test_counts_view_html(self): response = self.get_counts("html") self.assertEqual(response.status_code, 200) self.assertHTMLEqual( response.content.decode(), """ <table> <tr> <th>Name</th> <th>Email</th> <th>Count total</th> <th>Edits total</th> <th>Source words total</th> <th>Source chars total</th> <th>Target words total</th> <th>Target chars total</th> <th>Count new</th> <th>Edits new</th> <th>Source words new</th> <th>Source chars new</th> <th>Target words new</th> <th>Target chars new</th> <th>Count approved</th> <th>Edits approved</th> <th>Source words approved</th> <th>Source chars approved</th> <th>Target words approved</th> <th>Target chars approved</th> <th>Count edited</th> <th>Edits edited</th> <th>Source words edited</th> <th>Source chars edited</th> <th>Target words edited</th> <th>Target chars edited</th> </tr> <tr> <td>Weblate &lt;b&gt;Test&lt;/b&gt;</td> <td>weblate@example.org</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> </table> """, ) class ReportsProjectTest(ReportsComponentTest): def get_kwargs(self): return self.kw_project class ReportsGlobalTest(ReportsComponentTest): def get_kwargs(self): return {}
xss
{ "code": [ " \"name\": \"Weblate Test\",", " data, [{\"Czech\": [(\"weblate@example.org\", \"Weblate Test\", expected_count)]}]", " [{\"Czech\": [[\"weblate@example.org\", \"Weblate Test\", 1]]}],", " \"\\n\\n* Czech\\n\\n * Weblate Test <weblate@example.org> (1)\\n\\n\",", " \"Weblate Test</a> (1)</li></ul></td>\\n</tr>\\n\"", " <td>Weblate Test</td>" ], "line_no": [ 34, 90, 129, 137, 148, 234 ] }
{ "code": [ " \"name\": \"Weblate <b>Test</b>\",", " self.user.full_name = \"Weblate <b>Test</b>\"", " self.maxDiff = None", " [", " {", " \"Czech\": [", " ]", " }", " ],", " [{\"Czech\": [[\"weblate@example.org\", \"Weblate <b>Test</b>\", 1]]}],", " \"\"\"", "* Czech", " * Weblate &lt;b&gt;Test&lt;/b&gt; <weblate@example.org> (1)", "\"\"\",", " \"Weblate &lt;b&gt;Test&lt;/b&gt;</a> (1)</li></ul></td>\\n</tr>\\n\"", " <td>Weblate &lt;b&gt;Test&lt;/b&gt;</td>" ], "line_no": [ 34, 65, 67, 93, 94, 95, 97, 98, 99, 138, 146, 148, 150, 152, 163, 249 ] }
from datetime import timedelta from django.urls import reverse from django.utils import timezone from weblate.trans.tests.test_views import ViewTestCase from weblate.trans.views.reports import generate_counts, generate_credits VAR_0 = [ { "count": 1, "count_edit": 0, "count_new": 1, "name": "Weblate Test", "words": 2, "words_edit": 0, "words_new": 2, "chars": 14, "chars_edit": 0, "chars_new": 14, "email": "weblate@example.org", "t_chars": 14, "t_chars_edit": 0, "t_chars_new": 14, "t_words": 2, "t_words_edit": 0, "t_words_new": 2, "count_approve": 0, "words_approve": 0, "chars_approve": 0, "t_chars_approve": 0, "t_words_approve": 0, "edits": 14, "edits_approve": 0, "edits_edit": 0, "edits_new": 14, } ] class CLASS_0(ViewTestCase): def FUNC_0(self): super().setUp() self.user.is_superuser = True self.user.save() def FUNC_1(self): self.edit_unit("Hello, world!\n", "Nazdar svete!\n") class CLASS_1(CLASS_0): def FUNC_2(self): VAR_4 = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual(VAR_4, []) def FUNC_3(self, VAR_1=1): self.add_change() VAR_4 = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual( VAR_4, [{"Czech": [("weblate@example.org", "Weblate Test", VAR_1)]}] ) def FUNC_4(self): self.edit_unit("Hello, world!\n", "Nazdar svete2!\n") self.test_credits_one(VAR_1=2) def FUNC_5(self): self.add_change() VAR_4 = generate_counts( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), component=self.component, ) self.assertEqual(VAR_4, VAR_0) class CLASS_2(CLASS_0): def FUNC_6(self): return self.kw_component def FUNC_7(self, VAR_2): self.add_change() return self.client.post( reverse("credits", VAR_3=self.get_kwargs()), { "period": "", "style": VAR_2, "start_date": "2000-01-01", "end_date": "2100-01-01", }, ) def FUNC_8(self): VAR_5 = self.get_credits("json") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual( VAR_5.content.decode(), [{"Czech": [["weblate@example.org", "Weblate Test", 1]]}], ) def FUNC_9(self): VAR_5 = self.get_credits("rst") self.assertEqual(VAR_5.status_code, 200) self.assertEqual( VAR_5.content.decode(), "\n\n* Czech\n\n * Weblate Test <weblate@example.org> (1)\n\n", ) def FUNC_10(self): VAR_5 = self.get_credits("html") self.assertEqual(VAR_5.status_code, 200) self.assertHTMLEqual( VAR_5.content.decode(), "<table>\n" "<tr>\n<th>Czech</th>\n" '<td><ul><li><a href="mailto:weblate@example.org">' "Weblate Test</a> (1)</li></ul></td>\n</tr>\n" "</table>", ) def FUNC_11(self, VAR_2, **VAR_3): self.add_change() VAR_6 = { "style": VAR_2, "period": "", "start_date": "2000-01-01", "end_date": "2100-01-01", } VAR_6.update(VAR_3) return self.client.post(reverse("counts", VAR_3=self.get_kwargs()), VAR_6) def FUNC_12(self): VAR_5 = self.get_counts("json") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), VAR_0) def FUNC_13(self): VAR_5 = self.get_counts("json", period="30days") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), VAR_0) def FUNC_14(self): VAR_5 = self.get_counts("json", period="this-month") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), VAR_0) def FUNC_15(self): VAR_5 = self.get_counts("json", period="month") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), []) def FUNC_16(self): VAR_5 = self.get_counts("json", period="year") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), []) def FUNC_17(self): VAR_5 = self.get_counts("json", period="this-year") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), VAR_0) def FUNC_18(self): VAR_5 = self.get_counts("rst") self.assertEqual(VAR_5.status_code, 200) self.assertContains(VAR_5, "weblate@example.org") def FUNC_19(self): VAR_5 = self.get_counts("html") self.assertEqual(VAR_5.status_code, 200) self.assertHTMLEqual( VAR_5.content.decode(), """ <table> <tr> <th>Name</th> <th>Email</th> <th>Count total</th> <th>Edits total</th> <th>Source words total</th> <th>Source chars total</th> <th>Target words total</th> <th>Target chars total</th> <th>Count new</th> <th>Edits new</th> <th>Source words new</th> <th>Source chars new</th> <th>Target words new</th> <th>Target chars new</th> <th>Count approved</th> <th>Edits approved</th> <th>Source words approved</th> <th>Source chars approved</th> <th>Target words approved</th> <th>Target chars approved</th> <th>Count edited</th> <th>Edits edited</th> <th>Source words edited</th> <th>Source chars edited</th> <th>Target words edited</th> <th>Target chars edited</th> </tr> <tr> <td>Weblate Test</td> <td>weblate@example.org</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> </table> """, ) class CLASS_3(CLASS_2): def FUNC_6(self): return self.kw_project class CLASS_4(CLASS_2): def FUNC_6(self): return {}
from datetime import timedelta from django.urls import reverse from django.utils import timezone from weblate.trans.tests.test_views import ViewTestCase from weblate.trans.views.reports import generate_counts, generate_credits VAR_0 = [ { "count": 1, "count_edit": 0, "count_new": 1, "name": "Weblate <b>Test</b>", "words": 2, "words_edit": 0, "words_new": 2, "chars": 14, "chars_edit": 0, "chars_new": 14, "email": "weblate@example.org", "t_chars": 14, "t_chars_edit": 0, "t_chars_new": 14, "t_words": 2, "t_words_edit": 0, "t_words_new": 2, "count_approve": 0, "words_approve": 0, "chars_approve": 0, "t_chars_approve": 0, "t_words_approve": 0, "edits": 14, "edits_approve": 0, "edits_edit": 0, "edits_new": 14, } ] class CLASS_0(ViewTestCase): def FUNC_0(self): super().setUp() self.user.is_superuser = True self.user.full_name = "Weblate <b>Test</b>" self.user.save() self.maxDiff = None def FUNC_1(self): self.edit_unit("Hello, world!\n", "Nazdar svete!\n") class CLASS_1(CLASS_0): def FUNC_2(self): VAR_4 = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual(VAR_4, []) def FUNC_3(self, VAR_1=1): self.add_change() VAR_4 = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual( VAR_4, [ { "Czech": [ ("weblate@example.org", "Weblate <b>Test</b>", VAR_1) ] } ], ) def FUNC_4(self): self.edit_unit("Hello, world!\n", "Nazdar svete2!\n") self.test_credits_one(VAR_1=2) def FUNC_5(self): self.add_change() VAR_4 = generate_counts( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), component=self.component, ) self.assertEqual(VAR_4, VAR_0) class CLASS_2(CLASS_0): def FUNC_6(self): return self.kw_component def FUNC_7(self, VAR_2): self.add_change() return self.client.post( reverse("credits", VAR_3=self.get_kwargs()), { "period": "", "style": VAR_2, "start_date": "2000-01-01", "end_date": "2100-01-01", }, ) def FUNC_8(self): VAR_5 = self.get_credits("json") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual( VAR_5.content.decode(), [{"Czech": [["weblate@example.org", "Weblate <b>Test</b>", 1]]}], ) def FUNC_9(self): VAR_5 = self.get_credits("rst") self.assertEqual(VAR_5.status_code, 200) self.assertEqual( VAR_5.content.decode(), """ * Czech * Weblate &lt;b&gt;Test&lt;/b&gt; <weblate@example.org> (1) """, ) def FUNC_10(self): VAR_5 = self.get_credits("html") self.assertEqual(VAR_5.status_code, 200) self.assertHTMLEqual( VAR_5.content.decode(), "<table>\n" "<tr>\n<th>Czech</th>\n" '<td><ul><li><a href="mailto:weblate@example.org">' "Weblate &lt;b&gt;Test&lt;/b&gt;</a> (1)</li></ul></td>\n</tr>\n" "</table>", ) def FUNC_11(self, VAR_2, **VAR_3): self.add_change() VAR_6 = { "style": VAR_2, "period": "", "start_date": "2000-01-01", "end_date": "2100-01-01", } VAR_6.update(VAR_3) return self.client.post(reverse("counts", VAR_3=self.get_kwargs()), VAR_6) def FUNC_12(self): VAR_5 = self.get_counts("json") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), VAR_0) def FUNC_13(self): VAR_5 = self.get_counts("json", period="30days") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), VAR_0) def FUNC_14(self): VAR_5 = self.get_counts("json", period="this-month") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), VAR_0) def FUNC_15(self): VAR_5 = self.get_counts("json", period="month") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), []) def FUNC_16(self): VAR_5 = self.get_counts("json", period="year") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), []) def FUNC_17(self): VAR_5 = self.get_counts("json", period="this-year") self.assertEqual(VAR_5.status_code, 200) self.assertJSONEqual(VAR_5.content.decode(), VAR_0) def FUNC_18(self): VAR_5 = self.get_counts("rst") self.assertEqual(VAR_5.status_code, 200) self.assertContains(VAR_5, "weblate@example.org") def FUNC_19(self): VAR_5 = self.get_counts("html") self.assertEqual(VAR_5.status_code, 200) self.assertHTMLEqual( VAR_5.content.decode(), """ <table> <tr> <th>Name</th> <th>Email</th> <th>Count total</th> <th>Edits total</th> <th>Source words total</th> <th>Source chars total</th> <th>Target words total</th> <th>Target chars total</th> <th>Count new</th> <th>Edits new</th> <th>Source words new</th> <th>Source chars new</th> <th>Target words new</th> <th>Target chars new</th> <th>Count approved</th> <th>Edits approved</th> <th>Source words approved</th> <th>Source chars approved</th> <th>Target words approved</th> <th>Target chars approved</th> <th>Count edited</th> <th>Edits edited</th> <th>Source words edited</th> <th>Source chars edited</th> <th>Target words edited</th> <th>Target chars edited</th> </tr> <tr> <td>Weblate &lt;b&gt;Test&lt;/b&gt;</td> <td>weblate@example.org</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> </table> """, ) class CLASS_3(CLASS_2): def FUNC_6(self): return self.kw_project class CLASS_4(CLASS_2): def FUNC_6(self): return {}
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 25, 28, 59, 60, 66, 69, 70, 80, 92, 96, 106, 107, 111, 123, 131, 139, 151, 162, 167, 172, 177, 182, 187, 192, 197, 264, 265, 269, 270, 274 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 25, 28, 59, 60, 68, 71, 72, 82, 101, 105, 115, 116, 120, 132, 140, 147, 149, 151, 154, 166, 177, 182, 187, 192, 197, 202, 207, 212, 279, 280, 284, 285, 289 ]
3CWE-352
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2018 Antoni Boucher (antoyo) <bouanto@zoho.com> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. import os import attr import pytest import bs4 from PyQt5.QtCore import QUrl from PyQt5.QtNetwork import QNetworkRequest from qutebrowser.browser.webkit.network import filescheme from qutebrowser.utils import urlutils, utils @pytest.mark.parametrize('create_file, create_dir, filterfunc, expected', [ (True, False, os.path.isfile, True), (True, False, os.path.isdir, False), (False, True, os.path.isfile, False), (False, True, os.path.isdir, True), (False, False, os.path.isfile, False), (False, False, os.path.isdir, False), ]) def test_get_file_list(tmpdir, create_file, create_dir, filterfunc, expected): """Test get_file_list.""" path = tmpdir / 'foo' if create_file or create_dir: path.ensure(dir=create_dir) all_files = os.listdir(str(tmpdir)) result = filescheme.get_file_list(str(tmpdir), all_files, filterfunc) item = {'name': 'foo', 'absname': str(path)} assert (item in result) == expected class TestIsRoot: @pytest.mark.windows @pytest.mark.parametrize('directory, is_root', [ ('C:\\foo\\bar', False), ('C:\\foo\\', False), ('C:\\foo', False), ('C:\\', True) ]) def test_windows(self, directory, is_root): assert filescheme.is_root(directory) == is_root @pytest.mark.posix @pytest.mark.parametrize('directory, is_root', [ ('/foo/bar', False), ('/foo/', False), ('/foo', False), ('/', True) ]) def test_posix(self, directory, is_root): assert filescheme.is_root(directory) == is_root class TestParentDir: @pytest.mark.windows @pytest.mark.parametrize('directory, parent', [ ('C:\\foo\\bar', 'C:\\foo'), ('C:\\foo', 'C:\\'), ('C:\\foo\\', 'C:\\'), ('C:\\', 'C:\\'), ]) def test_windows(self, directory, parent): assert filescheme.parent_dir(directory) == parent @pytest.mark.posix @pytest.mark.parametrize('directory, parent', [ ('/home/foo', '/home'), ('/home', '/'), ('/home/', '/'), ('/', '/'), ]) def test_posix(self, directory, parent): assert filescheme.parent_dir(directory) == parent def _file_url(path): """Return a file:// url (as string) for the given LocalPath. Arguments: path: The filepath as LocalPath (as handled by py.path) """ return urlutils.file_url(str(path)) class TestDirbrowserHtml: @attr.s class Parsed: parent = attr.ib() folders = attr.ib() files = attr.ib() @attr.s class Item: link = attr.ib() text = attr.ib() @pytest.fixture def parser(self): """Provide a function to get a parsed dirbrowser document.""" def parse(path): html = filescheme.dirbrowser_html(path).decode('utf-8') soup = bs4.BeautifulSoup(html, 'html.parser') print(soup.prettify()) container = soup('div', id='dirbrowserContainer')[0] parent_elem = container('ul', class_='parent') if not parent_elem: parent = None else: parent = parent_elem[0].li.a.string folders = [] files = [] for li in container('ul', class_='folders')[0]('li'): item = self.Item(link=li.a['href'], text=str(li.a.string)) folders.append(item) for li in container('ul', class_='files')[0]('li'): item = self.Item(link=li.a['href'], text=str(li.a.string)) files.append(item) return self.Parsed(parent=parent, folders=folders, files=files) return parse def test_basic(self): html = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8') soup = bs4.BeautifulSoup(html, 'html.parser') print(soup.prettify()) container = soup.div assert container['id'] == 'dirbrowserContainer' title_elem = container('div', id='dirbrowserTitle')[0] title_text = title_elem('p', id='dirbrowserTitleText')[0].text assert title_text == 'Browse directory: {}'.format(os.getcwd()) def test_icons(self, monkeypatch): """Make sure icon paths are correct file:// URLs.""" monkeypatch.setattr(filescheme.jinja.utils, 'resource_filename', lambda name: '/test path/foo.svg') html = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8') soup = bs4.BeautifulSoup(html, 'html.parser') print(soup.prettify()) css = soup.html.head.style.string assert "background-image: url('file:///test%20path/foo.svg');" in css def test_empty(self, tmpdir, parser): parsed = parser(str(tmpdir)) assert parsed.parent assert not parsed.folders assert not parsed.files def test_files(self, tmpdir, parser): foo_file = tmpdir / 'foo' bar_file = tmpdir / 'bar' foo_file.ensure() bar_file.ensure() parsed = parser(str(tmpdir)) assert parsed.parent assert not parsed.folders foo_item = self.Item(_file_url(foo_file), foo_file.relto(tmpdir)) bar_item = self.Item(_file_url(bar_file), bar_file.relto(tmpdir)) assert parsed.files == [bar_item, foo_item] def test_html_special_chars(self, tmpdir, parser): special_file = tmpdir / 'foo&bar' special_file.ensure() parsed = parser(str(tmpdir)) item = self.Item(_file_url(special_file), special_file.relto(tmpdir)) assert parsed.files == [item] def test_dirs(self, tmpdir, parser): foo_dir = tmpdir / 'foo' bar_dir = tmpdir / 'bar' foo_dir.ensure(dir=True) bar_dir.ensure(dir=True) parsed = parser(str(tmpdir)) assert parsed.parent assert not parsed.files foo_item = self.Item(_file_url(foo_dir), foo_dir.relto(tmpdir)) bar_item = self.Item(_file_url(bar_dir), bar_dir.relto(tmpdir)) assert parsed.folders == [bar_item, foo_item] def test_mixed(self, tmpdir, parser): foo_file = tmpdir / 'foo' bar_dir = tmpdir / 'bar' foo_file.ensure() bar_dir.ensure(dir=True) parsed = parser(str(tmpdir)) foo_item = self.Item(_file_url(foo_file), foo_file.relto(tmpdir)) bar_item = self.Item(_file_url(bar_dir), bar_dir.relto(tmpdir)) assert parsed.parent assert parsed.files == [foo_item] assert parsed.folders == [bar_item] def test_root_dir(self, tmpdir, parser): root_dir = 'C:\\' if utils.is_windows else '/' parsed = parser(root_dir) assert not parsed.parent def test_oserror(self, mocker): m = mocker.patch('qutebrowser.browser.webkit.network.filescheme.' 'os.listdir') m.side_effect = OSError('Error message') html = filescheme.dirbrowser_html('').decode('utf-8') soup = bs4.BeautifulSoup(html, 'html.parser') print(soup.prettify()) error_msg = soup('p', id='error-message-text')[0].string assert error_msg == 'Error message' class TestFileSchemeHandler: def test_dir(self, tmpdir): url = QUrl.fromLocalFile(str(tmpdir)) req = QNetworkRequest(url) reply = filescheme.handler(req) # The URL will always use /, even on Windows - so we force this here # too. tmpdir_path = str(tmpdir).replace(os.sep, '/') assert reply.readAll() == filescheme.dirbrowser_html(tmpdir_path) def test_file(self, tmpdir): filename = tmpdir / 'foo' filename.ensure() url = QUrl.fromLocalFile(str(filename)) req = QNetworkRequest(url) reply = filescheme.handler(req) assert reply is None def test_unicode_encode_error(self, mocker): url = QUrl('file:///tmp/foo') req = QNetworkRequest(url) err = UnicodeEncodeError('ascii', '', 0, 2, 'foo') mocker.patch('os.path.isdir', side_effect=err) reply = filescheme.handler(req) assert reply is None
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2018 Antoni Boucher (antoyo) <bouanto@zoho.com> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. import os import attr import pytest import bs4 from PyQt5.QtCore import QUrl from PyQt5.QtNetwork import QNetworkRequest from qutebrowser.browser.webkit.network import filescheme from qutebrowser.utils import urlutils, utils @pytest.mark.parametrize('create_file, create_dir, filterfunc, expected', [ (True, False, os.path.isfile, True), (True, False, os.path.isdir, False), (False, True, os.path.isfile, False), (False, True, os.path.isdir, True), (False, False, os.path.isfile, False), (False, False, os.path.isdir, False), ]) def test_get_file_list(tmpdir, create_file, create_dir, filterfunc, expected): """Test get_file_list.""" path = tmpdir / 'foo' if create_file or create_dir: path.ensure(dir=create_dir) all_files = os.listdir(str(tmpdir)) result = filescheme.get_file_list(str(tmpdir), all_files, filterfunc) item = {'name': 'foo', 'absname': str(path)} assert (item in result) == expected class TestIsRoot: @pytest.mark.windows @pytest.mark.parametrize('directory, is_root', [ ('C:\\foo\\bar', False), ('C:\\foo\\', False), ('C:\\foo', False), ('C:\\', True) ]) def test_windows(self, directory, is_root): assert filescheme.is_root(directory) == is_root @pytest.mark.posix @pytest.mark.parametrize('directory, is_root', [ ('/foo/bar', False), ('/foo/', False), ('/foo', False), ('/', True) ]) def test_posix(self, directory, is_root): assert filescheme.is_root(directory) == is_root class TestParentDir: @pytest.mark.windows @pytest.mark.parametrize('directory, parent', [ ('C:\\foo\\bar', 'C:\\foo'), ('C:\\foo', 'C:\\'), ('C:\\foo\\', 'C:\\'), ('C:\\', 'C:\\'), ]) def test_windows(self, directory, parent): assert filescheme.parent_dir(directory) == parent @pytest.mark.posix @pytest.mark.parametrize('directory, parent', [ ('/home/foo', '/home'), ('/home', '/'), ('/home/', '/'), ('/', '/'), ]) def test_posix(self, directory, parent): assert filescheme.parent_dir(directory) == parent def _file_url(path): """Return a file:// url (as string) for the given LocalPath. Arguments: path: The filepath as LocalPath (as handled by py.path) """ return urlutils.file_url(str(path)) class TestDirbrowserHtml: @attr.s class Parsed: parent = attr.ib() folders = attr.ib() files = attr.ib() @attr.s class Item: link = attr.ib() text = attr.ib() @pytest.fixture def parser(self): """Provide a function to get a parsed dirbrowser document.""" def parse(path): html = filescheme.dirbrowser_html(path).decode('utf-8') soup = bs4.BeautifulSoup(html, 'html.parser') print(soup.prettify()) container = soup('div', id='dirbrowserContainer')[0] parent_elem = container('ul', class_='parent') if not parent_elem: parent = None else: parent = parent_elem[0].li.a.string folders = [] files = [] for li in container('ul', class_='folders')[0]('li'): item = self.Item(link=li.a['href'], text=str(li.a.string)) folders.append(item) for li in container('ul', class_='files')[0]('li'): item = self.Item(link=li.a['href'], text=str(li.a.string)) files.append(item) return self.Parsed(parent=parent, folders=folders, files=files) return parse def test_basic(self): html = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8') soup = bs4.BeautifulSoup(html, 'html.parser') print(soup.prettify()) container = soup.div assert container['id'] == 'dirbrowserContainer' title_elem = container('div', id='dirbrowserTitle')[0] title_text = title_elem('p', id='dirbrowserTitleText')[0].text assert title_text == 'Browse directory: {}'.format(os.getcwd()) def test_icons(self, monkeypatch): """Make sure icon paths are correct file:// URLs.""" monkeypatch.setattr(filescheme.jinja.utils, 'resource_filename', lambda name: '/test path/foo.svg') html = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8') soup = bs4.BeautifulSoup(html, 'html.parser') print(soup.prettify()) css = soup.html.head.style.string assert "background-image: url('file:///test%20path/foo.svg');" in css def test_empty(self, tmpdir, parser): parsed = parser(str(tmpdir)) assert parsed.parent assert not parsed.folders assert not parsed.files def test_files(self, tmpdir, parser): foo_file = tmpdir / 'foo' bar_file = tmpdir / 'bar' foo_file.ensure() bar_file.ensure() parsed = parser(str(tmpdir)) assert parsed.parent assert not parsed.folders foo_item = self.Item(_file_url(foo_file), foo_file.relto(tmpdir)) bar_item = self.Item(_file_url(bar_file), bar_file.relto(tmpdir)) assert parsed.files == [bar_item, foo_item] def test_html_special_chars(self, tmpdir, parser): special_file = tmpdir / 'foo&bar' special_file.ensure() parsed = parser(str(tmpdir)) item = self.Item(_file_url(special_file), special_file.relto(tmpdir)) assert parsed.files == [item] def test_dirs(self, tmpdir, parser): foo_dir = tmpdir / 'foo' bar_dir = tmpdir / 'bar' foo_dir.ensure(dir=True) bar_dir.ensure(dir=True) parsed = parser(str(tmpdir)) assert parsed.parent assert not parsed.files foo_item = self.Item(_file_url(foo_dir), foo_dir.relto(tmpdir)) bar_item = self.Item(_file_url(bar_dir), bar_dir.relto(tmpdir)) assert parsed.folders == [bar_item, foo_item] def test_mixed(self, tmpdir, parser): foo_file = tmpdir / 'foo' bar_dir = tmpdir / 'bar' foo_file.ensure() bar_dir.ensure(dir=True) parsed = parser(str(tmpdir)) foo_item = self.Item(_file_url(foo_file), foo_file.relto(tmpdir)) bar_item = self.Item(_file_url(bar_dir), bar_dir.relto(tmpdir)) assert parsed.parent assert parsed.files == [foo_item] assert parsed.folders == [bar_item] def test_root_dir(self, tmpdir, parser): root_dir = 'C:\\' if utils.is_windows else '/' parsed = parser(root_dir) assert not parsed.parent def test_oserror(self, mocker): m = mocker.patch('qutebrowser.browser.webkit.network.filescheme.' 'os.listdir') m.side_effect = OSError('Error message') html = filescheme.dirbrowser_html('').decode('utf-8') soup = bs4.BeautifulSoup(html, 'html.parser') print(soup.prettify()) error_msg = soup('p', id='error-message-text')[0].string assert error_msg == 'Error message' class TestFileSchemeHandler: def test_dir(self, tmpdir): url = QUrl.fromLocalFile(str(tmpdir)) req = QNetworkRequest(url) reply = filescheme.handler(req, None, None) # The URL will always use /, even on Windows - so we force this here # too. tmpdir_path = str(tmpdir).replace(os.sep, '/') assert reply.readAll() == filescheme.dirbrowser_html(tmpdir_path) def test_file(self, tmpdir): filename = tmpdir / 'foo' filename.ensure() url = QUrl.fromLocalFile(str(filename)) req = QNetworkRequest(url) reply = filescheme.handler(req, None, None) assert reply is None def test_unicode_encode_error(self, mocker): url = QUrl('file:///tmp/foo') req = QNetworkRequest(url) err = UnicodeEncodeError('ascii', '', 0, 2, 'foo') mocker.patch('os.path.isdir', side_effect=err) reply = filescheme.handler(req, None, None) assert reply is None
xsrf
{ "code": [ " reply = filescheme.handler(req)", " reply = filescheme.handler(req)", " reply = filescheme.handler(req)" ], "line_no": [ 251, 262, 272 ] }
{ "code": [ " reply = filescheme.handler(req, None, None)", " reply = filescheme.handler(req, None, None)", " reply = filescheme.handler(req, None, None)" ], "line_no": [ 251, 262, 272 ] }
import os import attr import pytest import bs4 from PyQt5.QtCore import QUrl from PyQt5.QtNetwork import QNetworkRequest from qutebrowser.browser.webkit.network import .filescheme from qutebrowser.utils import .urlutils, utils @pytest.mark.parametrize('create_file, VAR_2, VAR_3, expected', [ (True, False, os.path.isfile, True), (True, False, os.path.isdir, False), (False, True, os.path.isfile, False), (False, True, os.path.isdir, True), (False, False, os.path.isfile, False), (False, False, os.path.isdir, False), ]) def FUNC_0(VAR_0, VAR_1, VAR_2, VAR_3, VAR_4): VAR_5 = VAR_0 / 'foo' if VAR_1 or VAR_2: VAR_5.ensure(dir=VAR_2) VAR_6 = os.listdir(str(VAR_0)) VAR_7 = filescheme.get_file_list(str(VAR_0), VAR_6, VAR_3) VAR_8 = {'name': 'foo', 'absname': str(VAR_5)} assert (VAR_8 in VAR_7) == VAR_4 class CLASS_0: @pytest.mark.windows @pytest.mark.parametrize('directory, is_root', [ ('C:\\foo\\bar', False), ('C:\\foo\\', False), ('C:\\foo', False), ('C:\\', True) ]) def FUNC_2(self, VAR_9, VAR_10): assert filescheme.is_root(VAR_9) == VAR_10 @pytest.mark.posix @pytest.mark.parametrize('directory, is_root', [ ('/foo/bar', False), ('/foo/', False), ('/foo', False), ('/', True) ]) def FUNC_3(self, VAR_9, VAR_10): assert filescheme.is_root(VAR_9) == VAR_10 class CLASS_1: @pytest.mark.windows @pytest.mark.parametrize('directory, parent', [ ('C:\\foo\\bar', 'C:\\foo'), ('C:\\foo', 'C:\\'), ('C:\\foo\\', 'C:\\'), ('C:\\', 'C:\\'), ]) def FUNC_2(self, VAR_9, VAR_11): assert filescheme.parent_dir(VAR_9) == VAR_11 @pytest.mark.posix @pytest.mark.parametrize('directory, parent', [ ('/home/foo', '/home'), ('/home', '/'), ('/home/', '/'), ('/', '/'), ]) def FUNC_3(self, VAR_9, VAR_11): assert filescheme.parent_dir(VAR_9) == VAR_11 def FUNC_1(VAR_5): return urlutils.file_url(str(VAR_5)) class CLASS_2: @attr.s class CLASS_4: VAR_11 = attr.ib() VAR_15 = attr.ib() VAR_16 = attr.ib() @attr.s class CLASS_5: VAR_17 = attr.ib() VAR_18 = attr.ib() @pytest.fixture def VAR_13(self): def FUNC_17(VAR_5): VAR_19 = filescheme.dirbrowser_html(VAR_5).decode('utf-8') VAR_20 = bs4.BeautifulSoup(VAR_19, 'html.parser') print(VAR_20.prettify()) VAR_21 = VAR_20('div', id='dirbrowserContainer')[0] VAR_42 = VAR_21('ul', class_='parent') if not VAR_42: VAR_11 = None else: VAR_11 = VAR_42[0].li.a.string VAR_15 = [] VAR_16 = [] for li in VAR_21('ul', class_='folders')[0]('li'): VAR_8 = self.Item(VAR_17=li.a['href'], VAR_18=str(li.a.string)) VAR_15.append(VAR_8) for li in VAR_21('ul', class_='files')[0]('li'): VAR_8 = self.Item(VAR_17=li.a['href'], VAR_18=str(li.a.string)) VAR_16.append(VAR_8) return self.Parsed(VAR_11=parent, VAR_15=folders, VAR_16=files) return FUNC_17 def FUNC_5(self): VAR_19 = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8') VAR_20 = bs4.BeautifulSoup(VAR_19, 'html.parser') print(VAR_20.prettify()) VAR_21 = VAR_20.div assert VAR_21['id'] == 'dirbrowserContainer' VAR_22 = VAR_21('div', id='dirbrowserTitle')[0] VAR_23 = VAR_22('p', id='dirbrowserTitleText')[0].text assert VAR_23 == 'Browse VAR_9: {}'.format(os.getcwd()) def FUNC_6(self, VAR_12): VAR_12.setattr(filescheme.jinja.utils, 'resource_filename', lambda name: '/test VAR_5/foo.svg') VAR_19 = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8') VAR_20 = bs4.BeautifulSoup(VAR_19, 'html.parser') print(VAR_20.prettify()) VAR_24 = VAR_20.html.head.style.string assert "background-image: VAR_36('file:///test%20path/foo.svg');" in VAR_24 def FUNC_7(self, VAR_0, VAR_13): VAR_25 = VAR_13(str(VAR_0)) assert VAR_25.parent assert not VAR_25.folders assert not VAR_25.files def FUNC_8(self, VAR_0, VAR_13): VAR_26 = VAR_0 / 'foo' VAR_27 = VAR_0 / 'bar' VAR_26.ensure() VAR_27.ensure() VAR_25 = VAR_13(str(VAR_0)) assert VAR_25.parent assert not VAR_25.folders VAR_28 = self.Item(FUNC_1(VAR_26), foo_file.relto(VAR_0)) VAR_29 = self.Item(FUNC_1(VAR_27), bar_file.relto(VAR_0)) assert VAR_25.files == [VAR_29, VAR_28] def FUNC_9(self, VAR_0, VAR_13): VAR_30 = VAR_0 / 'foo&bar' VAR_30.ensure() VAR_25 = VAR_13(str(VAR_0)) VAR_8 = self.Item(FUNC_1(VAR_30), special_file.relto(VAR_0)) assert VAR_25.files == [VAR_8] def FUNC_10(self, VAR_0, VAR_13): VAR_31 = VAR_0 / 'foo' VAR_32 = VAR_0 / 'bar' VAR_31.ensure(dir=True) VAR_32.ensure(dir=True) VAR_25 = VAR_13(str(VAR_0)) assert VAR_25.parent assert not VAR_25.files VAR_28 = self.Item(FUNC_1(VAR_31), foo_dir.relto(VAR_0)) VAR_29 = self.Item(FUNC_1(VAR_32), bar_dir.relto(VAR_0)) assert VAR_25.folders == [VAR_29, VAR_28] def FUNC_11(self, VAR_0, VAR_13): VAR_26 = VAR_0 / 'foo' VAR_32 = VAR_0 / 'bar' VAR_26.ensure() VAR_32.ensure(dir=True) VAR_25 = VAR_13(str(VAR_0)) VAR_28 = self.Item(FUNC_1(VAR_26), foo_file.relto(VAR_0)) VAR_29 = self.Item(FUNC_1(VAR_32), bar_dir.relto(VAR_0)) assert VAR_25.parent assert VAR_25.files == [VAR_28] assert VAR_25.folders == [VAR_29] def FUNC_12(self, VAR_0, VAR_13): VAR_33 = 'C:\\' if utils.is_windows else '/' VAR_25 = VAR_13(VAR_33) assert not VAR_25.parent def FUNC_13(self, VAR_14): VAR_34 = VAR_14.patch('qutebrowser.browser.webkit.network.filescheme.' 'os.listdir') VAR_34.side_effect = OSError('Error message') VAR_19 = filescheme.dirbrowser_html('').decode('utf-8') VAR_20 = bs4.BeautifulSoup(VAR_19, 'html.parser') print(VAR_20.prettify()) VAR_35 = VAR_20('p', id='error-message-text')[0].string assert VAR_35 == 'Error message' class CLASS_3: def FUNC_14(self, VAR_0): VAR_36 = QUrl.fromLocalFile(str(VAR_0)) VAR_37 = QNetworkRequest(VAR_36) VAR_38 = filescheme.handler(VAR_37) VAR_39 = str(VAR_0).replace(os.sep, '/') assert VAR_38.readAll() == filescheme.dirbrowser_html(VAR_39) def FUNC_15(self, VAR_0): VAR_40 = VAR_0 / 'foo' VAR_40.ensure() VAR_36 = QUrl.fromLocalFile(str(VAR_40)) VAR_37 = QNetworkRequest(VAR_36) VAR_38 = filescheme.handler(VAR_37) assert VAR_38 is None def FUNC_16(self, VAR_14): VAR_36 = QUrl('file:///tmp/foo') VAR_37 = QNetworkRequest(VAR_36) VAR_41 = UnicodeEncodeError('ascii', '', 0, 2, 'foo') VAR_14.patch('os.path.isdir', side_effect=VAR_41) VAR_38 = filescheme.handler(VAR_37) assert VAR_38 is None
import os import attr import pytest import bs4 from PyQt5.QtCore import QUrl from PyQt5.QtNetwork import QNetworkRequest from qutebrowser.browser.webkit.network import .filescheme from qutebrowser.utils import .urlutils, utils @pytest.mark.parametrize('create_file, VAR_2, VAR_3, expected', [ (True, False, os.path.isfile, True), (True, False, os.path.isdir, False), (False, True, os.path.isfile, False), (False, True, os.path.isdir, True), (False, False, os.path.isfile, False), (False, False, os.path.isdir, False), ]) def FUNC_0(VAR_0, VAR_1, VAR_2, VAR_3, VAR_4): VAR_5 = VAR_0 / 'foo' if VAR_1 or VAR_2: VAR_5.ensure(dir=VAR_2) VAR_6 = os.listdir(str(VAR_0)) VAR_7 = filescheme.get_file_list(str(VAR_0), VAR_6, VAR_3) VAR_8 = {'name': 'foo', 'absname': str(VAR_5)} assert (VAR_8 in VAR_7) == VAR_4 class CLASS_0: @pytest.mark.windows @pytest.mark.parametrize('directory, is_root', [ ('C:\\foo\\bar', False), ('C:\\foo\\', False), ('C:\\foo', False), ('C:\\', True) ]) def FUNC_2(self, VAR_9, VAR_10): assert filescheme.is_root(VAR_9) == VAR_10 @pytest.mark.posix @pytest.mark.parametrize('directory, is_root', [ ('/foo/bar', False), ('/foo/', False), ('/foo', False), ('/', True) ]) def FUNC_3(self, VAR_9, VAR_10): assert filescheme.is_root(VAR_9) == VAR_10 class CLASS_1: @pytest.mark.windows @pytest.mark.parametrize('directory, parent', [ ('C:\\foo\\bar', 'C:\\foo'), ('C:\\foo', 'C:\\'), ('C:\\foo\\', 'C:\\'), ('C:\\', 'C:\\'), ]) def FUNC_2(self, VAR_9, VAR_11): assert filescheme.parent_dir(VAR_9) == VAR_11 @pytest.mark.posix @pytest.mark.parametrize('directory, parent', [ ('/home/foo', '/home'), ('/home', '/'), ('/home/', '/'), ('/', '/'), ]) def FUNC_3(self, VAR_9, VAR_11): assert filescheme.parent_dir(VAR_9) == VAR_11 def FUNC_1(VAR_5): return urlutils.file_url(str(VAR_5)) class CLASS_2: @attr.s class CLASS_4: VAR_11 = attr.ib() VAR_15 = attr.ib() VAR_16 = attr.ib() @attr.s class CLASS_5: VAR_17 = attr.ib() VAR_18 = attr.ib() @pytest.fixture def VAR_13(self): def FUNC_17(VAR_5): VAR_19 = filescheme.dirbrowser_html(VAR_5).decode('utf-8') VAR_20 = bs4.BeautifulSoup(VAR_19, 'html.parser') print(VAR_20.prettify()) VAR_21 = VAR_20('div', id='dirbrowserContainer')[0] VAR_42 = VAR_21('ul', class_='parent') if not VAR_42: VAR_11 = None else: VAR_11 = VAR_42[0].li.a.string VAR_15 = [] VAR_16 = [] for li in VAR_21('ul', class_='folders')[0]('li'): VAR_8 = self.Item(VAR_17=li.a['href'], VAR_18=str(li.a.string)) VAR_15.append(VAR_8) for li in VAR_21('ul', class_='files')[0]('li'): VAR_8 = self.Item(VAR_17=li.a['href'], VAR_18=str(li.a.string)) VAR_16.append(VAR_8) return self.Parsed(VAR_11=parent, VAR_15=folders, VAR_16=files) return FUNC_17 def FUNC_5(self): VAR_19 = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8') VAR_20 = bs4.BeautifulSoup(VAR_19, 'html.parser') print(VAR_20.prettify()) VAR_21 = VAR_20.div assert VAR_21['id'] == 'dirbrowserContainer' VAR_22 = VAR_21('div', id='dirbrowserTitle')[0] VAR_23 = VAR_22('p', id='dirbrowserTitleText')[0].text assert VAR_23 == 'Browse VAR_9: {}'.format(os.getcwd()) def FUNC_6(self, VAR_12): VAR_12.setattr(filescheme.jinja.utils, 'resource_filename', lambda name: '/test VAR_5/foo.svg') VAR_19 = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8') VAR_20 = bs4.BeautifulSoup(VAR_19, 'html.parser') print(VAR_20.prettify()) VAR_24 = VAR_20.html.head.style.string assert "background-image: VAR_36('file:///test%20path/foo.svg');" in VAR_24 def FUNC_7(self, VAR_0, VAR_13): VAR_25 = VAR_13(str(VAR_0)) assert VAR_25.parent assert not VAR_25.folders assert not VAR_25.files def FUNC_8(self, VAR_0, VAR_13): VAR_26 = VAR_0 / 'foo' VAR_27 = VAR_0 / 'bar' VAR_26.ensure() VAR_27.ensure() VAR_25 = VAR_13(str(VAR_0)) assert VAR_25.parent assert not VAR_25.folders VAR_28 = self.Item(FUNC_1(VAR_26), foo_file.relto(VAR_0)) VAR_29 = self.Item(FUNC_1(VAR_27), bar_file.relto(VAR_0)) assert VAR_25.files == [VAR_29, VAR_28] def FUNC_9(self, VAR_0, VAR_13): VAR_30 = VAR_0 / 'foo&bar' VAR_30.ensure() VAR_25 = VAR_13(str(VAR_0)) VAR_8 = self.Item(FUNC_1(VAR_30), special_file.relto(VAR_0)) assert VAR_25.files == [VAR_8] def FUNC_10(self, VAR_0, VAR_13): VAR_31 = VAR_0 / 'foo' VAR_32 = VAR_0 / 'bar' VAR_31.ensure(dir=True) VAR_32.ensure(dir=True) VAR_25 = VAR_13(str(VAR_0)) assert VAR_25.parent assert not VAR_25.files VAR_28 = self.Item(FUNC_1(VAR_31), foo_dir.relto(VAR_0)) VAR_29 = self.Item(FUNC_1(VAR_32), bar_dir.relto(VAR_0)) assert VAR_25.folders == [VAR_29, VAR_28] def FUNC_11(self, VAR_0, VAR_13): VAR_26 = VAR_0 / 'foo' VAR_32 = VAR_0 / 'bar' VAR_26.ensure() VAR_32.ensure(dir=True) VAR_25 = VAR_13(str(VAR_0)) VAR_28 = self.Item(FUNC_1(VAR_26), foo_file.relto(VAR_0)) VAR_29 = self.Item(FUNC_1(VAR_32), bar_dir.relto(VAR_0)) assert VAR_25.parent assert VAR_25.files == [VAR_28] assert VAR_25.folders == [VAR_29] def FUNC_12(self, VAR_0, VAR_13): VAR_33 = 'C:\\' if utils.is_windows else '/' VAR_25 = VAR_13(VAR_33) assert not VAR_25.parent def FUNC_13(self, VAR_14): VAR_34 = VAR_14.patch('qutebrowser.browser.webkit.network.filescheme.' 'os.listdir') VAR_34.side_effect = OSError('Error message') VAR_19 = filescheme.dirbrowser_html('').decode('utf-8') VAR_20 = bs4.BeautifulSoup(VAR_19, 'html.parser') print(VAR_20.prettify()) VAR_35 = VAR_20('p', id='error-message-text')[0].string assert VAR_35 == 'Error message' class CLASS_3: def FUNC_14(self, VAR_0): VAR_36 = QUrl.fromLocalFile(str(VAR_0)) VAR_37 = QNetworkRequest(VAR_36) VAR_38 = filescheme.handler(VAR_37, None, None) VAR_39 = str(VAR_0).replace(os.sep, '/') assert VAR_38.readAll() == filescheme.dirbrowser_html(VAR_39) def FUNC_15(self, VAR_0): VAR_40 = VAR_0 / 'foo' VAR_40.ensure() VAR_36 = QUrl.fromLocalFile(str(VAR_40)) VAR_37 = QNetworkRequest(VAR_36) VAR_38 = filescheme.handler(VAR_37, None, None) assert VAR_38 is None def FUNC_16(self, VAR_14): VAR_36 = QUrl('file:///tmp/foo') VAR_37 = QNetworkRequest(VAR_36) VAR_41 = UnicodeEncodeError('ascii', '', 0, 2, 'foo') VAR_14.patch('os.path.isdir', side_effect=VAR_41) VAR_38 = filescheme.handler(VAR_37, None, None) assert VAR_38 is None
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 27, 30, 31, 35, 38, 47, 49, 53, 54, 56, 66, 76, 77, 79, 89, 99, 100, 103, 108, 109, 111, 114, 118, 121, 124, 133, 139, 142, 146, 150, 152, 154, 164, 169, 173, 176, 182, 188, 195, 199, 203, 209, 216, 222, 229, 234, 244, 245, 247, 252, 253, 256, 264, 268, 271, 274, 43, 102, 103, 104, 105, 106, 127, 166 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 27, 30, 31, 35, 38, 47, 49, 53, 54, 56, 66, 76, 77, 79, 89, 99, 100, 103, 108, 109, 111, 114, 118, 121, 124, 133, 139, 142, 146, 150, 152, 154, 164, 169, 173, 176, 182, 188, 195, 199, 203, 209, 216, 222, 229, 234, 244, 245, 247, 252, 253, 256, 264, 268, 271, 274, 43, 102, 103, 104, 105, 106, 127, 166 ]
1CWE-79
from __future__ import absolute_import, unicode_literals from django import forms from django.apps import apps from django.template.loader import render_to_string from django.utils.safestring import mark_safe from .permissions import permission_tag_view class TagFormWidget(forms.SelectMultiple): option_template_name = 'tags/forms/widgets/tag_select_option.html' def __init__(self, *args, **kwargs): self.queryset = kwargs.pop('queryset') return super(TagFormWidget, self).__init__(*args, **kwargs) def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): result = super(TagFormWidget, self).create_option( name=name, value=value, label=label, selected=selected, index=index, subindex=subindex, attrs=attrs ) result['attrs']['data-color'] = self.queryset.get(pk=value).color return result def widget_document_tags(document, user): """ A tag widget that displays the tags for the given document """ AccessControlList = apps.get_model( app_label='acls', model_name='AccessControlList' ) result = ['<div class="tag-container">'] tags = AccessControlList.objects.filter_by_access( permission_tag_view, user, queryset=document.attached_tags().all() ) for tag in tags: result.append(widget_single_tag(tag)) result.append('</div>') return mark_safe(''.join(result)) def widget_single_tag(tag): return render_to_string('tags/tag_widget.html', {'tag': tag})
from __future__ import absolute_import, unicode_literals from django import forms from django.apps import apps from django.template.loader import render_to_string from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from .permissions import permission_tag_view class TagFormWidget(forms.SelectMultiple): option_template_name = 'tags/forms/widgets/tag_select_option.html' def __init__(self, *args, **kwargs): self.queryset = kwargs.pop('queryset') return super(TagFormWidget, self).__init__(*args, **kwargs) def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): result = super(TagFormWidget, self).create_option( name=name, value=value, label='{}'.format(conditional_escape(label)), selected=selected, index=index, subindex=subindex, attrs=attrs ) result['attrs']['data-color'] = self.queryset.get(pk=value).color return result def widget_document_tags(document, user): """ A tag widget that displays the tags for the given document """ AccessControlList = apps.get_model( app_label='acls', model_name='AccessControlList' ) result = ['<div class="tag-container">'] tags = AccessControlList.objects.filter_by_access( permission_tag_view, user, queryset=document.attached_tags().all() ) for tag in tags: result.append(widget_single_tag(tag)) result.append('</div>') return mark_safe(''.join(result)) def widget_single_tag(tag): return render_to_string('tags/tag_widget.html', {'tag': tag})
xss
{ "code": [ " name=name, value=value, label=label, selected=selected,", " index=index, subindex=subindex, attrs=attrs" ], "line_no": [ 20, 21 ] }
{ "code": [ "from django.utils.html import conditional_escape", " name=name, value=value, label='{}'.format(conditional_escape(label)),", " selected=selected, index=index, subindex=subindex, attrs=attrs" ], "line_no": [ 6, 21, 22 ] }
from __future__ import absolute_import, unicode_literals from django import forms from django.apps import apps from django.template.loader import render_to_string from django.utils.safestring import mark_safe from .permissions import permission_tag_view class CLASS_0(forms.SelectMultiple): VAR_3 = 'tags/forms/widgets/tag_select_option.html' def __init__(self, *VAR_4, **VAR_5): self.queryset = VAR_5.pop('queryset') return super(CLASS_0, self).__init__(*VAR_4, **VAR_5) def FUNC_2(self, VAR_6, VAR_7, VAR_8, VAR_9, VAR_10, VAR_11=None, VAR_12=None): VAR_14 = super(CLASS_0, self).create_option( VAR_6=name, VAR_7=value, VAR_8=label, VAR_9=selected, VAR_10=index, VAR_11=subindex, VAR_12=attrs ) VAR_14['attrs']['data-color'] = self.queryset.get(pk=VAR_7).color return VAR_14 def FUNC_0(VAR_0, VAR_1): VAR_13 = apps.get_model( app_label='acls', model_name='AccessControlList' ) VAR_14 = ['<div class="tag-container">'] VAR_15 = VAR_13.objects.filter_by_access( permission_tag_view, VAR_1, queryset=VAR_0.attached_tags().all() ) for VAR_2 in VAR_15: VAR_14.append(FUNC_1(VAR_2)) VAR_14.append('</div>') return mark_safe(''.join(VAR_14)) def FUNC_1(VAR_2): return render_to_string('tags/tag_widget.html', {'tag': VAR_2})
from __future__ import absolute_import, unicode_literals from django import forms from django.apps import apps from django.template.loader import render_to_string from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from .permissions import permission_tag_view class CLASS_0(forms.SelectMultiple): VAR_3 = 'tags/forms/widgets/tag_select_option.html' def __init__(self, *VAR_4, **VAR_5): self.queryset = VAR_5.pop('queryset') return super(CLASS_0, self).__init__(*VAR_4, **VAR_5) def FUNC_2(self, VAR_6, VAR_7, VAR_8, VAR_9, VAR_10, VAR_11=None, VAR_12=None): VAR_14 = super(CLASS_0, self).create_option( VAR_6=name, VAR_7=value, VAR_8='{}'.format(conditional_escape(VAR_8)), VAR_9=selected, VAR_10=index, VAR_11=subindex, VAR_12=attrs ) VAR_14['attrs']['data-color'] = self.queryset.get(pk=VAR_7).color return VAR_14 def FUNC_0(VAR_0, VAR_1): VAR_13 = apps.get_model( app_label='acls', model_name='AccessControlList' ) VAR_14 = ['<div class="tag-container">'] VAR_15 = VAR_13.objects.filter_by_access( permission_tag_view, VAR_1, queryset=VAR_0.attached_tags().all() ) for VAR_2 in VAR_15: VAR_14.append(FUNC_1(VAR_2)) VAR_14.append('</div>') return mark_safe(''.join(VAR_14)) def FUNC_1(VAR_2): return render_to_string('tags/tag_widget.html', {'tag': VAR_2})
[ 2, 7, 9, 10, 13, 17, 23, 25, 27, 28, 36, 38, 42, 45, 47, 49, 50, 53, 30, 31, 32 ]
[ 2, 8, 10, 11, 14, 18, 24, 26, 28, 29, 37, 39, 43, 46, 48, 50, 51, 54, 31, 32, 33 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock from twisted.internet import defer import synapse.types from synapse.api.errors import AuthError, SynapseError from synapse.types import UserID from tests import unittest from tests.test_utils import make_awaitable from tests.utils import setup_test_homeserver class ProfileTestCase(unittest.TestCase): """ Tests profile management. """ @defer.inlineCallbacks def setUp(self): self.mock_federation = Mock() self.mock_registry = Mock() self.query_handlers = {} def register_query_handler(query_type, handler): self.query_handlers[query_type] = handler self.mock_registry.register_query_handler = register_query_handler hs = yield setup_test_homeserver( self.addCleanup, http_client=None, resource_for_federation=Mock(), federation_client=self.mock_federation, federation_server=Mock(), federation_registry=self.mock_registry, ) self.store = hs.get_datastore() self.frank = UserID.from_string("@1234ABCD:test") self.bob = UserID.from_string("@4567:test") self.alice = UserID.from_string("@alice:remote") yield defer.ensureDeferred(self.store.create_profile(self.frank.localpart)) self.handler = hs.get_profile_handler() self.hs = hs @defer.inlineCallbacks def test_get_my_name(self): yield defer.ensureDeferred( self.store.set_profile_displayname(self.frank.localpart, "Frank") ) displayname = yield defer.ensureDeferred( self.handler.get_displayname(self.frank) ) self.assertEquals("Frank", displayname) @defer.inlineCallbacks def test_set_my_name(self): yield defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank Jr." ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank Jr.", ) # Set displayname again yield defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank" ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank", ) @defer.inlineCallbacks def test_set_my_name_if_disabled(self): self.hs.config.enable_set_displayname = False # Setting displayname for the first time is allowed yield defer.ensureDeferred( self.store.set_profile_displayname(self.frank.localpart, "Frank") ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank", ) # Setting displayname a second time is forbidden d = defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank Jr." ) ) yield self.assertFailure(d, SynapseError) @defer.inlineCallbacks def test_set_my_name_noauth(self): d = defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.bob), "Frank Jr." ) ) yield self.assertFailure(d, AuthError) @defer.inlineCallbacks def test_get_other_name(self): self.mock_federation.make_query.return_value = make_awaitable( {"displayname": "Alice"} ) displayname = yield defer.ensureDeferred( self.handler.get_displayname(self.alice) ) self.assertEquals(displayname, "Alice") self.mock_federation.make_query.assert_called_with( destination="remote", query_type="profile", args={"user_id": "@alice:remote", "field": "displayname"}, ignore_backoff=True, ) @defer.inlineCallbacks def test_incoming_fed_query(self): yield defer.ensureDeferred(self.store.create_profile("caroline")) yield defer.ensureDeferred( self.store.set_profile_displayname("caroline", "Caroline") ) response = yield defer.ensureDeferred( self.query_handlers["profile"]( {"user_id": "@caroline:test", "field": "displayname"} ) ) self.assertEquals({"displayname": "Caroline"}, response) @defer.inlineCallbacks def test_get_my_avatar(self): yield defer.ensureDeferred( self.store.set_profile_avatar_url( self.frank.localpart, "http://my.server/me.png" ) ) avatar_url = yield defer.ensureDeferred(self.handler.get_avatar_url(self.frank)) self.assertEquals("http://my.server/me.png", avatar_url) @defer.inlineCallbacks def test_set_my_avatar(self): yield defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/pic.gif", ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/pic.gif", ) # Set avatar again yield defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/me.png", ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/me.png", ) @defer.inlineCallbacks def test_set_my_avatar_if_disabled(self): self.hs.config.enable_set_avatar_url = False # Setting displayname for the first time is allowed yield defer.ensureDeferred( self.store.set_profile_avatar_url( self.frank.localpart, "http://my.server/me.png" ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/me.png", ) # Set avatar a second time is forbidden d = defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/pic.gif", ) ) yield self.assertFailure(d, SynapseError)
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mock import Mock from twisted.internet import defer import synapse.types from synapse.api.errors import AuthError, SynapseError from synapse.types import UserID from tests import unittest from tests.test_utils import make_awaitable from tests.utils import setup_test_homeserver class ProfileTestCase(unittest.TestCase): """ Tests profile management. """ @defer.inlineCallbacks def setUp(self): self.mock_federation = Mock() self.mock_registry = Mock() self.query_handlers = {} def register_query_handler(query_type, handler): self.query_handlers[query_type] = handler self.mock_registry.register_query_handler = register_query_handler hs = yield setup_test_homeserver( self.addCleanup, federation_http_client=None, resource_for_federation=Mock(), federation_client=self.mock_federation, federation_server=Mock(), federation_registry=self.mock_registry, ) self.store = hs.get_datastore() self.frank = UserID.from_string("@1234ABCD:test") self.bob = UserID.from_string("@4567:test") self.alice = UserID.from_string("@alice:remote") yield defer.ensureDeferred(self.store.create_profile(self.frank.localpart)) self.handler = hs.get_profile_handler() self.hs = hs @defer.inlineCallbacks def test_get_my_name(self): yield defer.ensureDeferred( self.store.set_profile_displayname(self.frank.localpart, "Frank") ) displayname = yield defer.ensureDeferred( self.handler.get_displayname(self.frank) ) self.assertEquals("Frank", displayname) @defer.inlineCallbacks def test_set_my_name(self): yield defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank Jr." ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank Jr.", ) # Set displayname again yield defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank" ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank", ) @defer.inlineCallbacks def test_set_my_name_if_disabled(self): self.hs.config.enable_set_displayname = False # Setting displayname for the first time is allowed yield defer.ensureDeferred( self.store.set_profile_displayname(self.frank.localpart, "Frank") ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank", ) # Setting displayname a second time is forbidden d = defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank Jr." ) ) yield self.assertFailure(d, SynapseError) @defer.inlineCallbacks def test_set_my_name_noauth(self): d = defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.bob), "Frank Jr." ) ) yield self.assertFailure(d, AuthError) @defer.inlineCallbacks def test_get_other_name(self): self.mock_federation.make_query.return_value = make_awaitable( {"displayname": "Alice"} ) displayname = yield defer.ensureDeferred( self.handler.get_displayname(self.alice) ) self.assertEquals(displayname, "Alice") self.mock_federation.make_query.assert_called_with( destination="remote", query_type="profile", args={"user_id": "@alice:remote", "field": "displayname"}, ignore_backoff=True, ) @defer.inlineCallbacks def test_incoming_fed_query(self): yield defer.ensureDeferred(self.store.create_profile("caroline")) yield defer.ensureDeferred( self.store.set_profile_displayname("caroline", "Caroline") ) response = yield defer.ensureDeferred( self.query_handlers["profile"]( {"user_id": "@caroline:test", "field": "displayname"} ) ) self.assertEquals({"displayname": "Caroline"}, response) @defer.inlineCallbacks def test_get_my_avatar(self): yield defer.ensureDeferred( self.store.set_profile_avatar_url( self.frank.localpart, "http://my.server/me.png" ) ) avatar_url = yield defer.ensureDeferred(self.handler.get_avatar_url(self.frank)) self.assertEquals("http://my.server/me.png", avatar_url) @defer.inlineCallbacks def test_set_my_avatar(self): yield defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/pic.gif", ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/pic.gif", ) # Set avatar again yield defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/me.png", ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/me.png", ) @defer.inlineCallbacks def test_set_my_avatar_if_disabled(self): self.hs.config.enable_set_avatar_url = False # Setting displayname for the first time is allowed yield defer.ensureDeferred( self.store.set_profile_avatar_url( self.frank.localpart, "http://my.server/me.png" ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/me.png", ) # Set avatar a second time is forbidden d = defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/pic.gif", ) ) yield self.assertFailure(d, SynapseError)
open_redirect
{ "code": [ " http_client=None," ], "line_no": [ 47 ] }
{ "code": [ " federation_http_client=None," ], "line_no": [ 47 ] }
from mock import Mock from twisted.internet import .defer import synapse.types from synapse.api.errors import AuthError, SynapseError from synapse.types import UserID from tests import unittest from tests.test_utils import make_awaitable from tests.utils import setup_test_homeserver class CLASS_0(unittest.TestCase): @defer.inlineCallbacks def FUNC_0(self): self.mock_federation = Mock() self.mock_registry = Mock() self.query_handlers = {} def FUNC_10(VAR_0, VAR_1): self.query_handlers[VAR_0] = VAR_1 self.mock_registry.register_query_handler = FUNC_10 VAR_2 = yield setup_test_homeserver( self.addCleanup, http_client=None, resource_for_federation=Mock(), federation_client=self.mock_federation, federation_server=Mock(), federation_registry=self.mock_registry, ) self.store = VAR_2.get_datastore() self.frank = UserID.from_string("@1234ABCD:test") self.bob = UserID.from_string("@4567:test") self.alice = UserID.from_string("@alice:remote") yield defer.ensureDeferred(self.store.create_profile(self.frank.localpart)) self.handler = VAR_2.get_profile_handler() self.hs = VAR_2 @defer.inlineCallbacks def FUNC_1(self): yield defer.ensureDeferred( self.store.set_profile_displayname(self.frank.localpart, "Frank") ) VAR_3 = yield defer.ensureDeferred( self.handler.get_displayname(self.frank) ) self.assertEquals("Frank", VAR_3) @defer.inlineCallbacks def FUNC_2(self): yield defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank Jr." ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank Jr.", ) yield defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank" ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank", ) @defer.inlineCallbacks def FUNC_3(self): self.hs.config.enable_set_displayname = False yield defer.ensureDeferred( self.store.set_profile_displayname(self.frank.localpart, "Frank") ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank", ) VAR_4 = defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank Jr." ) ) yield self.assertFailure(VAR_4, SynapseError) @defer.inlineCallbacks def FUNC_4(self): VAR_4 = defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.bob), "Frank Jr." ) ) yield self.assertFailure(VAR_4, AuthError) @defer.inlineCallbacks def FUNC_5(self): self.mock_federation.make_query.return_value = make_awaitable( {"displayname": "Alice"} ) VAR_3 = yield defer.ensureDeferred( self.handler.get_displayname(self.alice) ) self.assertEquals(VAR_3, "Alice") self.mock_federation.make_query.assert_called_with( destination="remote", VAR_0="profile", args={"user_id": "@alice:remote", "field": "displayname"}, ignore_backoff=True, ) @defer.inlineCallbacks def FUNC_6(self): yield defer.ensureDeferred(self.store.create_profile("caroline")) yield defer.ensureDeferred( self.store.set_profile_displayname("caroline", "Caroline") ) VAR_5 = yield defer.ensureDeferred( self.query_handlers["profile"]( {"user_id": "@caroline:test", "field": "displayname"} ) ) self.assertEquals({"displayname": "Caroline"}, VAR_5) @defer.inlineCallbacks def FUNC_7(self): yield defer.ensureDeferred( self.store.set_profile_avatar_url( self.frank.localpart, "http://my.server/me.png" ) ) VAR_6 = yield defer.ensureDeferred(self.handler.get_avatar_url(self.frank)) self.assertEquals("http://my.server/me.png", VAR_6) @defer.inlineCallbacks def FUNC_8(self): yield defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/pic.gif", ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/pic.gif", ) yield defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/me.png", ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/me.png", ) @defer.inlineCallbacks def FUNC_9(self): self.hs.config.enable_set_avatar_url = False yield defer.ensureDeferred( self.store.set_profile_avatar_url( self.frank.localpart, "http://my.server/me.png" ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/me.png", ) VAR_4 = defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/pic.gif", ) ) yield self.assertFailure(VAR_4, SynapseError)
from mock import Mock from twisted.internet import .defer import synapse.types from synapse.api.errors import AuthError, SynapseError from synapse.types import UserID from tests import unittest from tests.test_utils import make_awaitable from tests.utils import setup_test_homeserver class CLASS_0(unittest.TestCase): @defer.inlineCallbacks def FUNC_0(self): self.mock_federation = Mock() self.mock_registry = Mock() self.query_handlers = {} def FUNC_10(VAR_0, VAR_1): self.query_handlers[VAR_0] = VAR_1 self.mock_registry.register_query_handler = FUNC_10 VAR_2 = yield setup_test_homeserver( self.addCleanup, federation_http_client=None, resource_for_federation=Mock(), federation_client=self.mock_federation, federation_server=Mock(), federation_registry=self.mock_registry, ) self.store = VAR_2.get_datastore() self.frank = UserID.from_string("@1234ABCD:test") self.bob = UserID.from_string("@4567:test") self.alice = UserID.from_string("@alice:remote") yield defer.ensureDeferred(self.store.create_profile(self.frank.localpart)) self.handler = VAR_2.get_profile_handler() self.hs = VAR_2 @defer.inlineCallbacks def FUNC_1(self): yield defer.ensureDeferred( self.store.set_profile_displayname(self.frank.localpart, "Frank") ) VAR_3 = yield defer.ensureDeferred( self.handler.get_displayname(self.frank) ) self.assertEquals("Frank", VAR_3) @defer.inlineCallbacks def FUNC_2(self): yield defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank Jr." ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank Jr.", ) yield defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank" ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank", ) @defer.inlineCallbacks def FUNC_3(self): self.hs.config.enable_set_displayname = False yield defer.ensureDeferred( self.store.set_profile_displayname(self.frank.localpart, "Frank") ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_displayname(self.frank.localpart) ) ), "Frank", ) VAR_4 = defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.frank), "Frank Jr." ) ) yield self.assertFailure(VAR_4, SynapseError) @defer.inlineCallbacks def FUNC_4(self): VAR_4 = defer.ensureDeferred( self.handler.set_displayname( self.frank, synapse.types.create_requester(self.bob), "Frank Jr." ) ) yield self.assertFailure(VAR_4, AuthError) @defer.inlineCallbacks def FUNC_5(self): self.mock_federation.make_query.return_value = make_awaitable( {"displayname": "Alice"} ) VAR_3 = yield defer.ensureDeferred( self.handler.get_displayname(self.alice) ) self.assertEquals(VAR_3, "Alice") self.mock_federation.make_query.assert_called_with( destination="remote", VAR_0="profile", args={"user_id": "@alice:remote", "field": "displayname"}, ignore_backoff=True, ) @defer.inlineCallbacks def FUNC_6(self): yield defer.ensureDeferred(self.store.create_profile("caroline")) yield defer.ensureDeferred( self.store.set_profile_displayname("caroline", "Caroline") ) VAR_5 = yield defer.ensureDeferred( self.query_handlers["profile"]( {"user_id": "@caroline:test", "field": "displayname"} ) ) self.assertEquals({"displayname": "Caroline"}, VAR_5) @defer.inlineCallbacks def FUNC_7(self): yield defer.ensureDeferred( self.store.set_profile_avatar_url( self.frank.localpart, "http://my.server/me.png" ) ) VAR_6 = yield defer.ensureDeferred(self.handler.get_avatar_url(self.frank)) self.assertEquals("http://my.server/me.png", VAR_6) @defer.inlineCallbacks def FUNC_8(self): yield defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/pic.gif", ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/pic.gif", ) yield defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/me.png", ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/me.png", ) @defer.inlineCallbacks def FUNC_9(self): self.hs.config.enable_set_avatar_url = False yield defer.ensureDeferred( self.store.set_profile_avatar_url( self.frank.localpart, "http://my.server/me.png" ) ) self.assertEquals( ( yield defer.ensureDeferred( self.store.get_profile_avatar_url(self.frank.localpart) ) ), "http://my.server/me.png", ) VAR_4 = defer.ensureDeferred( self.handler.set_avatar_url( self.frank, synapse.types.create_requester(self.frank), "http://my.server/pic.gif", ) ) yield self.assertFailure(VAR_4, SynapseError)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 24, 28, 29, 32, 37, 39, 42, 44, 53, 55, 59, 61, 64, 70, 74, 76, 84, 93, 94, 100, 109, 113, 114, 118, 127, 128, 134, 136, 144, 146, 152, 156, 164, 171, 177, 179, 188, 190, 200, 209, 210, 218, 227, 231, 232, 238, 247, 248, 256, 258, 31 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 24, 28, 29, 32, 37, 39, 42, 44, 53, 55, 59, 61, 64, 70, 74, 76, 84, 93, 94, 100, 109, 113, 114, 118, 127, 128, 134, 136, 144, 146, 152, 156, 164, 171, 177, 179, 188, 190, 200, 209, 210, 218, 227, 231, 232, 238, 247, 248, 256, 258, 31 ]
4CWE-601
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.contrib import messages from django.utils.translation import gettext as _ from django.contrib.auth import get_user_model import spirit import django from spirit.category.models import Category from spirit.comment.flag.models import CommentFlag from spirit.comment.like.models import CommentLike from spirit.comment.models import Comment from spirit.topic.models import Topic from spirit.core.utils.views import is_post, post_data from spirit.core.utils.decorators import administrator_required from .forms import BasicConfigForm User = get_user_model() @administrator_required def config_basic(request): form = BasicConfigForm(data=post_data(request)) if is_post(request) and form.is_valid(): form.save() messages.info(request, _("Settings updated!")) return redirect(request.GET.get("next", request.get_full_path())) return render( request=request, template_name='spirit/admin/config_basic.html', context={'form': form}) @administrator_required def dashboard(request): # Strongly inaccurate counters below... context = { 'version': spirit.__version__, 'django_version': django.get_version(), 'category_count': Category.objects.all().count() - 1, # - private 'topics_count': Topic.objects.all().count(), 'comments_count': Comment.objects.all().count(), 'users_count': User.objects.all().count(), 'flags_count': CommentFlag.objects.filter(is_closed=False).count(), 'likes_count': CommentLike.objects.all().count() } return render(request, 'spirit/admin/dashboard.html', context)
# -*- coding: utf-8 -*- from django.shortcuts import render from django.contrib import messages from django.utils.translation import gettext as _ from django.contrib.auth import get_user_model import spirit import django from spirit.core.utils.http import safe_redirect from spirit.category.models import Category from spirit.comment.flag.models import CommentFlag from spirit.comment.like.models import CommentLike from spirit.comment.models import Comment from spirit.topic.models import Topic from spirit.core.utils.views import is_post, post_data from spirit.core.utils.decorators import administrator_required from .forms import BasicConfigForm User = get_user_model() @administrator_required def config_basic(request): form = BasicConfigForm(data=post_data(request)) if is_post(request) and form.is_valid(): form.save() messages.info(request, _("Settings updated!")) return safe_redirect(request, "next", request.get_full_path()) return render( request=request, template_name='spirit/admin/config_basic.html', context={'form': form}) @administrator_required def dashboard(request): # Strongly inaccurate counters below... context = { 'version': spirit.__version__, 'django_version': django.get_version(), 'category_count': Category.objects.all().count() - 1, # - private 'topics_count': Topic.objects.all().count(), 'comments_count': Comment.objects.all().count(), 'users_count': User.objects.all().count(), 'flags_count': CommentFlag.objects.filter(is_closed=False).count(), 'likes_count': CommentLike.objects.all().count() } return render(request, 'spirit/admin/dashboard.html', context)
open_redirect
{ "code": [ "from django.shortcuts import render, redirect", " return redirect(request.GET.get(\"next\", request.get_full_path()))" ], "line_no": [ 3, 28 ] }
{ "code": [ "from django.shortcuts import render", "from spirit.core.utils.http import safe_redirect", " return safe_redirect(request, \"next\", request.get_full_path())" ], "line_no": [ 3, 10, 29 ] }
from django.shortcuts import render, redirect from django.contrib import messages from django.utils.translation import gettext as _ from django.contrib.auth import get_user_model import spirit import django from spirit.category.models import Category from spirit.comment.flag.models import CommentFlag from spirit.comment.like.models import CommentLike from spirit.comment.models import Comment from spirit.topic.models import Topic from spirit.core.utils.views import is_post, post_data from spirit.core.utils.decorators import administrator_required from .forms import BasicConfigForm VAR_0 = get_user_model() @administrator_required def FUNC_0(VAR_1): VAR_2 = BasicConfigForm(data=post_data(VAR_1)) if is_post(VAR_1) and VAR_2.is_valid(): VAR_2.save() messages.info(VAR_1, _("Settings updated!")) return redirect(VAR_1.GET.get("next", VAR_1.get_full_path())) return render( VAR_1=request, template_name='spirit/admin/FUNC_0.html', VAR_3={'form': VAR_2}) @administrator_required def FUNC_1(VAR_1): VAR_3 = { 'version': spirit.__version__, 'django_version': django.get_version(), 'category_count': Category.objects.all().count() - 1, # - private 'topics_count': Topic.objects.all().count(), 'comments_count': Comment.objects.all().count(), 'users_count': VAR_0.objects.all().count(), 'flags_count': CommentFlag.objects.filter(is_closed=False).count(), 'likes_count': CommentLike.objects.all().count() } return render(VAR_1, 'spirit/admin/FUNC_1.html', VAR_3)
from django.shortcuts import render from django.contrib import messages from django.utils.translation import gettext as _ from django.contrib.auth import get_user_model import spirit import django from spirit.core.utils.http import safe_redirect from spirit.category.models import Category from spirit.comment.flag.models import CommentFlag from spirit.comment.like.models import CommentLike from spirit.comment.models import Comment from spirit.topic.models import Topic from spirit.core.utils.views import is_post, post_data from spirit.core.utils.decorators import administrator_required from .forms import BasicConfigForm VAR_0 = get_user_model() @administrator_required def FUNC_0(VAR_1): VAR_2 = BasicConfigForm(data=post_data(VAR_1)) if is_post(VAR_1) and VAR_2.is_valid(): VAR_2.save() messages.info(VAR_1, _("Settings updated!")) return safe_redirect(VAR_1, "next", VAR_1.get_full_path()) return render( VAR_1=request, template_name='spirit/admin/FUNC_0.html', VAR_3={'form': VAR_2}) @administrator_required def FUNC_1(VAR_1): VAR_3 = { 'version': spirit.__version__, 'django_version': django.get_version(), 'category_count': Category.objects.all().count() - 1, # - private 'topics_count': Topic.objects.all().count(), 'comments_count': Comment.objects.all().count(), 'users_count': VAR_0.objects.all().count(), 'flags_count': CommentFlag.objects.filter(is_closed=False).count(), 'likes_count': CommentLike.objects.all().count() } return render(VAR_1, 'spirit/admin/FUNC_1.html', VAR_3)
[ 1, 2, 7, 18, 20, 21, 33, 34, 37, 48, 50 ]
[ 1, 2, 7, 19, 21, 22, 34, 35, 38, 49, 51 ]
0CWE-22
############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ############################################################################## import unittest from chameleon.exc import ExpressionError import zope.component.testing from AccessControl import SecurityManager from AccessControl.SecurityManagement import noSecurityManager from Acquisition import Implicit from Products.PageTemplates.interfaces import IUnicodeEncodingConflictResolver from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.tests import util from Products.PageTemplates.unicodeconflictresolver import \ DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from zExceptions import NotFound from zope.component import provideUtility from zope.traversing.adapters import DefaultTraversable from .util import useChameleonEngine class AqPageTemplate(Implicit, PageTemplate): pass class Folder(util.Base): pass class UnitTestSecurityPolicy: """ Stub out the existing security policy for unit testing purposes. """ # Standard SecurityPolicy interface def validate(self, accessed=None, container=None, name=None, value=None, context=None, roles=None, *args, **kw): return 1 def checkPermission(self, permission, object, context): return 1 class HTMLTests(zope.component.testing.PlacelessSetup, unittest.TestCase): PREFIX = None def setUp(self): super().setUp() useChameleonEngine() zope.component.provideAdapter(DefaultTraversable, (None,)) provideUtility(DefaultUnicodeEncodingConflictResolver, IUnicodeEncodingConflictResolver) self.folder = f = Folder() f.laf = AqPageTemplate() f.t = AqPageTemplate() self.policy = UnitTestSecurityPolicy() self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy) noSecurityManager() # Use the new policy. def tearDown(self): super().tearDown() SecurityManager.setSecurityPolicy(self.oldPolicy) noSecurityManager() # Reset to old policy. def assert_expected(self, t, fname, *args, **kwargs): t.write(util.read_input(fname)) assert not t._v_errors, 'Template errors: %s' % t._v_errors if self.PREFIX is not None \ and util.exists_output(self.PREFIX + fname): fname = self.PREFIX + fname expect = util.read_output(fname) out = t(*args, **kwargs) util.check_html(expect, out) def assert_expected_unicode(self, t, fname, *args, **kwargs): t.write(util.read_input(fname)) assert not t._v_errors, 'Template errors: %s' % t._v_errors expect = util.read_output(fname) if not isinstance(expect, str): expect = str(expect, 'utf-8') out = t(*args, **kwargs) util.check_html(expect, out) def getProducts(self): return [ {'description': 'This is the tee for those who LOVE Zope. ' 'Show your heart on your tee.', 'price': 12.99, 'image': 'smlatee.jpg' }, {'description': 'This is the tee for Jim Fulton. ' 'He\'s the Zope Pope!', 'price': 11.99, 'image': 'smpztee.jpg' }, ] def test_1(self): self.assert_expected(self.folder.laf, 'TeeShopLAF.html') def test_2(self): self.folder.laf.write(util.read_input('TeeShopLAF.html')) self.assert_expected(self.folder.t, 'TeeShop2.html', getProducts=self.getProducts) def test_3(self): self.folder.laf.write(util.read_input('TeeShopLAF.html')) self.assert_expected(self.folder.t, 'TeeShop1.html', getProducts=self.getProducts) def testSimpleLoop(self): self.assert_expected(self.folder.t, 'Loop1.html') def testFancyLoop(self): self.assert_expected(self.folder.t, 'Loop2.html') def testGlobalsShadowLocals(self): self.assert_expected(self.folder.t, 'GlobalsShadowLocals.html') def testStringExpressions(self): self.assert_expected(self.folder.t, 'StringExpression.html') def testReplaceWithNothing(self): self.assert_expected(self.folder.t, 'CheckNothing.html') def testWithXMLHeader(self): self.assert_expected(self.folder.t, 'CheckWithXMLHeader.html') def testNotExpression(self): self.assert_expected(self.folder.t, 'CheckNotExpression.html') def testPathNothing(self): self.assert_expected(self.folder.t, 'CheckPathNothing.html') def testPathAlt(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def testPathTraverse(self): # need to perform this test with a "real" folder from OFS.Folder import Folder f = self.folder self.folder = Folder() self.folder.t, self.folder.laf = f.t, f.laf self.folder.laf.write('ok') self.assert_expected(self.folder.t, 'CheckPathTraverse.html') def testBatchIteration(self): self.assert_expected(self.folder.t, 'CheckBatchIteration.html') def testUnicodeInserts(self): self.assert_expected_unicode(self.folder.t, 'CheckUnicodeInserts.html') def testI18nTranslate(self): self.assert_expected(self.folder.t, 'CheckI18nTranslate.html') def testImportOldStyleClass(self): self.assert_expected(self.folder.t, 'CheckImportOldStyleClass.html') def testRepeatVariable(self): self.assert_expected(self.folder.t, 'RepeatVariable.html') def testBooleanAttributes(self): # Test rendering an attribute that should be empty or left out # if the value is non-True self.assert_expected(self.folder.t, 'BooleanAttributes.html') def testBooleanAttributesAndDefault(self): # Zope 2.9 and below support the semantics that an HTML # "boolean" attribute (e.g. 'selected', 'disabled', etc.) can # be used together with 'default'. self.assert_expected(self.folder.t, 'BooleanAttributesAndDefault.html') def testInterpolationInContent(self): # the chameleon template engine supports ``${path}`` # interpolations not only as part of ``string`` expressions # but globally self.assert_expected(self.folder.t, 'InterpolationInContent.html') def testBadExpression(self): t = self.folder.t t.write("<p tal:define='p a//b' />") with self.assertRaises(ExpressionError): t() def testPathAlternativesWithSpaces(self): self.assert_expected(self.folder.t, 'PathAlternativesWithSpaces.html') def testDefaultKeywordHandling(self): self.assert_expected(self.folder.t, 'Default.html') def testSwitch(self): self.assert_expected(self.folder.t, 'switch.html') def test_unicode_conflict_resolution(self): # override with the more "demanding" resolver provideUtility(PreferredCharsetResolver) t = PageTemplate() self.assert_expected(t, 'UnicodeResolution.html') def test_underscore_traversal(self): t = self.folder.t t.write('<p tal:define="p context/__class__" />') with self.assertRaises(NotFound): t() t.write('<p tal:define="p nocall: random/_itertools/repeat"/>') with self.assertRaises(NotFound): t() t.write('<p tal:content="random/_itertools/repeat/foobar"/>') with self.assertRaises(NotFound): t()
############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ############################################################################## import unittest from chameleon.exc import ExpressionError import zope.component.testing from AccessControl import SecurityManager from AccessControl.SecurityManagement import noSecurityManager from Acquisition import Implicit from Products.PageTemplates.interfaces import IUnicodeEncodingConflictResolver from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.tests import util from Products.PageTemplates.unicodeconflictresolver import \ DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from zExceptions import NotFound from zope.component import provideUtility from zope.location.interfaces import LocationError from zope.traversing.adapters import DefaultTraversable from .util import useChameleonEngine class AqPageTemplate(Implicit, PageTemplate): pass class AqZopePageTemplate(Implicit, ZopePageTemplate): pass class Folder(util.Base): pass class UnitTestSecurityPolicy: """ Stub out the existing security policy for unit testing purposes. """ # Standard SecurityPolicy interface def validate(self, accessed=None, container=None, name=None, value=None, context=None, roles=None, *args, **kw): return 1 def checkPermission(self, permission, object, context): return 1 class HTMLTests(zope.component.testing.PlacelessSetup, unittest.TestCase): PREFIX = None def setUp(self): super().setUp() useChameleonEngine() zope.component.provideAdapter(DefaultTraversable, (None,)) provideUtility(DefaultUnicodeEncodingConflictResolver, IUnicodeEncodingConflictResolver) self.folder = f = Folder() f.laf = AqPageTemplate() f.t = AqPageTemplate() f.z = AqZopePageTemplate('testing') self.policy = UnitTestSecurityPolicy() self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy) noSecurityManager() # Use the new policy. def tearDown(self): super().tearDown() SecurityManager.setSecurityPolicy(self.oldPolicy) noSecurityManager() # Reset to old policy. def assert_expected(self, t, fname, *args, **kwargs): t.write(util.read_input(fname)) assert not t._v_errors, 'Template errors: %s' % t._v_errors if self.PREFIX is not None \ and util.exists_output(self.PREFIX + fname): fname = self.PREFIX + fname expect = util.read_output(fname) out = t(*args, **kwargs) util.check_html(expect, out) def assert_expected_unicode(self, t, fname, *args, **kwargs): t.write(util.read_input(fname)) assert not t._v_errors, 'Template errors: %s' % t._v_errors expect = util.read_output(fname) if not isinstance(expect, str): expect = str(expect, 'utf-8') out = t(*args, **kwargs) util.check_html(expect, out) def getProducts(self): return [ {'description': 'This is the tee for those who LOVE Zope. ' 'Show your heart on your tee.', 'price': 12.99, 'image': 'smlatee.jpg' }, {'description': 'This is the tee for Jim Fulton. ' 'He\'s the Zope Pope!', 'price': 11.99, 'image': 'smpztee.jpg' }, ] def test_1(self): self.assert_expected(self.folder.laf, 'TeeShopLAF.html') def test_2(self): self.folder.laf.write(util.read_input('TeeShopLAF.html')) self.assert_expected(self.folder.t, 'TeeShop2.html', getProducts=self.getProducts) def test_3(self): self.folder.laf.write(util.read_input('TeeShopLAF.html')) self.assert_expected(self.folder.t, 'TeeShop1.html', getProducts=self.getProducts) def testSimpleLoop(self): self.assert_expected(self.folder.t, 'Loop1.html') def testFancyLoop(self): self.assert_expected(self.folder.t, 'Loop2.html') def testGlobalsShadowLocals(self): self.assert_expected(self.folder.t, 'GlobalsShadowLocals.html') def testStringExpressions(self): self.assert_expected(self.folder.t, 'StringExpression.html') def testReplaceWithNothing(self): self.assert_expected(self.folder.t, 'CheckNothing.html') def testWithXMLHeader(self): self.assert_expected(self.folder.t, 'CheckWithXMLHeader.html') def testNotExpression(self): self.assert_expected(self.folder.t, 'CheckNotExpression.html') def testPathNothing(self): self.assert_expected(self.folder.t, 'CheckPathNothing.html') def testPathAlt(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def testPathTraverse(self): # need to perform this test with a "real" folder from OFS.Folder import Folder f = self.folder self.folder = Folder() self.folder.t, self.folder.laf = f.t, f.laf self.folder.laf.write('ok') self.assert_expected(self.folder.t, 'CheckPathTraverse.html') def testBatchIteration(self): self.assert_expected(self.folder.t, 'CheckBatchIteration.html') def testUnicodeInserts(self): self.assert_expected_unicode(self.folder.t, 'CheckUnicodeInserts.html') def testI18nTranslate(self): self.assert_expected(self.folder.t, 'CheckI18nTranslate.html') def testImportOldStyleClass(self): self.assert_expected(self.folder.t, 'CheckImportOldStyleClass.html') def testRepeatVariable(self): self.assert_expected(self.folder.t, 'RepeatVariable.html') def testBooleanAttributes(self): # Test rendering an attribute that should be empty or left out # if the value is non-True self.assert_expected(self.folder.t, 'BooleanAttributes.html') def testBooleanAttributesAndDefault(self): # Zope 2.9 and below support the semantics that an HTML # "boolean" attribute (e.g. 'selected', 'disabled', etc.) can # be used together with 'default'. self.assert_expected(self.folder.t, 'BooleanAttributesAndDefault.html') def testInterpolationInContent(self): # the chameleon template engine supports ``${path}`` # interpolations not only as part of ``string`` expressions # but globally self.assert_expected(self.folder.t, 'InterpolationInContent.html') def testBadExpression(self): t = self.folder.t t.write("<p tal:define='p a//b' />") with self.assertRaises(ExpressionError): t() def testPathAlternativesWithSpaces(self): self.assert_expected(self.folder.t, 'PathAlternativesWithSpaces.html') def testDefaultKeywordHandling(self): self.assert_expected(self.folder.t, 'Default.html') def testSwitch(self): self.assert_expected(self.folder.t, 'switch.html') def test_unicode_conflict_resolution(self): # override with the more "demanding" resolver provideUtility(PreferredCharsetResolver) t = PageTemplate() self.assert_expected(t, 'UnicodeResolution.html') def test_underscore_traversal(self): t = self.folder.t t.write('<p tal:define="p context/__class__" />') with self.assertRaises(NotFound): t() t.write('<p tal:define="p nocall: random/_itertools/repeat"/>') with self.assertRaises((NotFound, LocationError)): t() t.write('<p tal:content="random/_itertools/repeat/foobar"/>') with self.assertRaises((NotFound, LocationError)): t() def test_module_traversal(self): t = self.folder.z # Need to reset to the standard security policy so AccessControl # checks are actually performed. The test setup initializes # a policy that circumvents those checks. SecurityManager.setSecurityPolicy(self.oldPolicy) noSecurityManager() # The getSecurityManager function is explicitly allowed content = ('<p tal:define="a nocall:%s"' ' tal:content="python: a().getUser().getUserName()"/>') t.write(content % 'modules/AccessControl/getSecurityManager') self.assertEqual(t(), '<p>Anonymous User</p>') # Anything else should be unreachable and raise NotFound: # Direct access through AccessControl t.write('<p tal:define="a nocall:modules/AccessControl/users"/>') with self.assertRaises(NotFound): t() # Indirect access through an intermediary variable content = ('<p tal:define="mod nocall:modules/AccessControl;' ' must_fail nocall:mod/users"/>') t.write(content) with self.assertRaises(NotFound): t() # Indirect access through an intermediary variable and a dictionary content = ('<p tal:define="mod nocall:modules/AccessControl;' ' a_dict python: {\'unsafe\': mod};' ' must_fail nocall: a_dict/unsafe/users"/>') t.write(content) with self.assertRaises(NotFound): t()
path_disclosure
{ "code": [ " with self.assertRaises(NotFound):" ], "line_no": [ 229 ] }
{ "code": [ "from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate", "class AqZopePageTemplate(Implicit, ZopePageTemplate):", " f.z = AqZopePageTemplate('testing')", " with self.assertRaises((NotFound, LocationError)):", " with self.assertRaises((NotFound, LocationError)):", " t()", " def test_module_traversal(self):", " t = self.folder.z", " SecurityManager.setSecurityPolicy(self.oldPolicy)", " noSecurityManager()", " content = ('<p tal:define=\"a nocall:%s\"'", " ' tal:content=\"python: a().getUser().getUserName()\"/>')", " t.write(content % 'modules/AccessControl/getSecurityManager')", " self.assertEqual(t(), '<p>Anonymous User</p>')", " t.write('<p tal:define=\"a nocall:modules/AccessControl/users\"/>')", " with self.assertRaises(NotFound):", " t()", " content = ('<p tal:define=\"mod nocall:modules/AccessControl;'", " ' must_fail nocall:mod/users\"/>')", " t.write(content)", " with self.assertRaises(NotFound):", " t()", " content = ('<p tal:define=\"mod nocall:modules/AccessControl;'", " ' a_dict python: {\\'unsafe\\': mod};'", " ' must_fail nocall: a_dict/unsafe/users\"/>')", " t.write(content)" ], "line_no": [ 29, 42, 83, 236, 240, 241, 243, 244, 249, 250, 253, 254, 255, 256, 260, 261, 262, 265, 266, 267, 268, 269, 272, 273, 274, 275 ] }
import unittest from chameleon.exc import ExpressionError import zope.component.testing from AccessControl import SecurityManager from AccessControl.SecurityManagement import noSecurityManager from Acquisition import Implicit from Products.PageTemplates.interfaces import IUnicodeEncodingConflictResolver from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.tests import util from Products.PageTemplates.unicodeconflictresolver import \ DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from zExceptions import NotFound from zope.component import provideUtility from zope.traversing.adapters import DefaultTraversable from .util import useChameleonEngine class CLASS_0(Implicit, PageTemplate): pass class CLASS_1(util.Base): pass class CLASS_2: def FUNC_0(self, VAR_0=None, VAR_1=None, VAR_2=None, VAR_3=None, VAR_4=None, VAR_5=None, *VAR_6, **VAR_7): return 1 def FUNC_1(self, VAR_8, VAR_9, VAR_4): return 1 class CLASS_3(zope.component.testing.PlacelessSetup, unittest.TestCase): VAR_10 = None def FUNC_2(self): super().setUp() useChameleonEngine() zope.component.provideAdapter(DefaultTraversable, (None,)) provideUtility(DefaultUnicodeEncodingConflictResolver, IUnicodeEncodingConflictResolver) self.folder = VAR_14 = CLASS_1() VAR_14.laf = CLASS_0() VAR_14.t = CLASS_0() self.policy = CLASS_2() self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy) noSecurityManager() # Use the new policy. def FUNC_3(self): super().tearDown() SecurityManager.setSecurityPolicy(self.oldPolicy) noSecurityManager() # Reset to old policy. def FUNC_4(self, VAR_11, VAR_12, *VAR_6, **VAR_13): VAR_11.write(util.read_input(VAR_12)) assert not VAR_11._v_errors, 'Template errors: %s' % VAR_11._v_errors if self.PREFIX is not None \ and util.exists_output(self.PREFIX + VAR_12): fname = self.PREFIX + VAR_12 VAR_15 = util.read_output(VAR_12) VAR_16 = VAR_11(*VAR_6, **VAR_13) util.check_html(VAR_15, VAR_16) def FUNC_5(self, VAR_11, VAR_12, *VAR_6, **VAR_13): VAR_11.write(util.read_input(VAR_12)) assert not VAR_11._v_errors, 'Template errors: %s' % VAR_11._v_errors VAR_15 = util.read_output(VAR_12) if not isinstance(VAR_15, str): VAR_15 = str(VAR_15, 'utf-8') VAR_16 = VAR_11(*VAR_6, **VAR_13) util.check_html(VAR_15, VAR_16) def FUNC_6(self): return [ {'description': 'This is the tee for those who LOVE Zope. ' 'Show your heart on your tee.', 'price': 12.99, 'image': 'smlatee.jpg' }, {'description': 'This is the tee for Jim Fulton. ' 'He\'s the Zope Pope!', 'price': 11.99, 'image': 'smpztee.jpg' }, ] def FUNC_7(self): self.assert_expected(self.folder.laf, 'TeeShopLAF.html') def FUNC_8(self): self.folder.laf.write(util.read_input('TeeShopLAF.html')) self.assert_expected(self.folder.t, 'TeeShop2.html', FUNC_6=self.getProducts) def FUNC_9(self): self.folder.laf.write(util.read_input('TeeShopLAF.html')) self.assert_expected(self.folder.t, 'TeeShop1.html', FUNC_6=self.getProducts) def FUNC_10(self): self.assert_expected(self.folder.t, 'Loop1.html') def FUNC_11(self): self.assert_expected(self.folder.t, 'Loop2.html') def FUNC_12(self): self.assert_expected(self.folder.t, 'GlobalsShadowLocals.html') def FUNC_13(self): self.assert_expected(self.folder.t, 'StringExpression.html') def FUNC_14(self): self.assert_expected(self.folder.t, 'CheckNothing.html') def FUNC_15(self): self.assert_expected(self.folder.t, 'CheckWithXMLHeader.html') def FUNC_16(self): self.assert_expected(self.folder.t, 'CheckNotExpression.html') def FUNC_17(self): self.assert_expected(self.folder.t, 'CheckPathNothing.html') def FUNC_18(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def FUNC_19(self): from OFS.Folder import .Folder VAR_14 = self.folder self.folder = CLASS_1() self.folder.t, self.folder.laf = VAR_14.t, VAR_14.laf self.folder.laf.write('ok') self.assert_expected(self.folder.t, 'CheckPathTraverse.html') def FUNC_20(self): self.assert_expected(self.folder.t, 'CheckBatchIteration.html') def FUNC_21(self): self.assert_expected_unicode(self.folder.t, 'CheckUnicodeInserts.html') def FUNC_22(self): self.assert_expected(self.folder.t, 'CheckI18nTranslate.html') def FUNC_23(self): self.assert_expected(self.folder.t, 'CheckImportOldStyleClass.html') def FUNC_24(self): self.assert_expected(self.folder.t, 'RepeatVariable.html') def FUNC_25(self): self.assert_expected(self.folder.t, 'BooleanAttributes.html') def FUNC_26(self): self.assert_expected(self.folder.t, 'BooleanAttributesAndDefault.html') def FUNC_27(self): self.assert_expected(self.folder.t, 'InterpolationInContent.html') def FUNC_28(self): VAR_11 = self.folder.t VAR_11.write("<p tal:define='p a//b' />") with self.assertRaises(ExpressionError): VAR_11() def FUNC_29(self): self.assert_expected(self.folder.t, 'PathAlternativesWithSpaces.html') def FUNC_30(self): self.assert_expected(self.folder.t, 'Default.html') def FUNC_31(self): self.assert_expected(self.folder.t, 'switch.html') def FUNC_32(self): provideUtility(PreferredCharsetResolver) VAR_11 = PageTemplate() self.assert_expected(VAR_11, 'UnicodeResolution.html') def FUNC_33(self): VAR_11 = self.folder.t VAR_11.write('<p tal:define="p VAR_4/__class__" />') with self.assertRaises(NotFound): VAR_11() VAR_11.write('<p tal:define="p nocall: random/_itertools/repeat"/>') with self.assertRaises(NotFound): VAR_11() VAR_11.write('<p tal:content="random/_itertools/repeat/foobar"/>') with self.assertRaises(NotFound): VAR_11()
import unittest from chameleon.exc import ExpressionError import zope.component.testing from AccessControl import SecurityManager from AccessControl.SecurityManagement import noSecurityManager from Acquisition import Implicit from Products.PageTemplates.interfaces import IUnicodeEncodingConflictResolver from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.tests import util from Products.PageTemplates.unicodeconflictresolver import \ DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from zExceptions import NotFound from zope.component import provideUtility from zope.location.interfaces import LocationError from zope.traversing.adapters import DefaultTraversable from .util import useChameleonEngine class CLASS_0(Implicit, PageTemplate): pass class CLASS_1(Implicit, ZopePageTemplate): pass class CLASS_2(util.Base): pass class CLASS_3: def FUNC_0(self, VAR_0=None, VAR_1=None, VAR_2=None, VAR_3=None, VAR_4=None, VAR_5=None, *VAR_6, **VAR_7): return 1 def FUNC_1(self, VAR_8, VAR_9, VAR_4): return 1 class CLASS_4(zope.component.testing.PlacelessSetup, unittest.TestCase): VAR_10 = None def FUNC_2(self): super().setUp() useChameleonEngine() zope.component.provideAdapter(DefaultTraversable, (None,)) provideUtility(DefaultUnicodeEncodingConflictResolver, IUnicodeEncodingConflictResolver) self.folder = VAR_14 = CLASS_2() VAR_14.laf = CLASS_0() VAR_14.t = CLASS_0() VAR_14.z = CLASS_1('testing') self.policy = CLASS_3() self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy) noSecurityManager() # Use the new policy. def FUNC_3(self): super().tearDown() SecurityManager.setSecurityPolicy(self.oldPolicy) noSecurityManager() # Reset to old policy. def FUNC_4(self, VAR_11, VAR_12, *VAR_6, **VAR_13): VAR_11.write(util.read_input(VAR_12)) assert not VAR_11._v_errors, 'Template errors: %s' % VAR_11._v_errors if self.PREFIX is not None \ and util.exists_output(self.PREFIX + VAR_12): fname = self.PREFIX + VAR_12 VAR_15 = util.read_output(VAR_12) VAR_16 = VAR_11(*VAR_6, **VAR_13) util.check_html(VAR_15, VAR_16) def FUNC_5(self, VAR_11, VAR_12, *VAR_6, **VAR_13): VAR_11.write(util.read_input(VAR_12)) assert not VAR_11._v_errors, 'Template errors: %s' % VAR_11._v_errors VAR_15 = util.read_output(VAR_12) if not isinstance(VAR_15, str): VAR_15 = str(VAR_15, 'utf-8') VAR_16 = VAR_11(*VAR_6, **VAR_13) util.check_html(VAR_15, VAR_16) def FUNC_6(self): return [ {'description': 'This is the tee for those who LOVE Zope. ' 'Show your heart on your tee.', 'price': 12.99, 'image': 'smlatee.jpg' }, {'description': 'This is the tee for Jim Fulton. ' 'He\'s the Zope Pope!', 'price': 11.99, 'image': 'smpztee.jpg' }, ] def FUNC_7(self): self.assert_expected(self.folder.laf, 'TeeShopLAF.html') def FUNC_8(self): self.folder.laf.write(util.read_input('TeeShopLAF.html')) self.assert_expected(self.folder.t, 'TeeShop2.html', FUNC_6=self.getProducts) def FUNC_9(self): self.folder.laf.write(util.read_input('TeeShopLAF.html')) self.assert_expected(self.folder.t, 'TeeShop1.html', FUNC_6=self.getProducts) def FUNC_10(self): self.assert_expected(self.folder.t, 'Loop1.html') def FUNC_11(self): self.assert_expected(self.folder.t, 'Loop2.html') def FUNC_12(self): self.assert_expected(self.folder.t, 'GlobalsShadowLocals.html') def FUNC_13(self): self.assert_expected(self.folder.t, 'StringExpression.html') def FUNC_14(self): self.assert_expected(self.folder.t, 'CheckNothing.html') def FUNC_15(self): self.assert_expected(self.folder.t, 'CheckWithXMLHeader.html') def FUNC_16(self): self.assert_expected(self.folder.t, 'CheckNotExpression.html') def FUNC_17(self): self.assert_expected(self.folder.t, 'CheckPathNothing.html') def FUNC_18(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def FUNC_19(self): from OFS.Folder import .Folder VAR_14 = self.folder self.folder = CLASS_2() self.folder.t, self.folder.laf = VAR_14.t, VAR_14.laf self.folder.laf.write('ok') self.assert_expected(self.folder.t, 'CheckPathTraverse.html') def FUNC_20(self): self.assert_expected(self.folder.t, 'CheckBatchIteration.html') def FUNC_21(self): self.assert_expected_unicode(self.folder.t, 'CheckUnicodeInserts.html') def FUNC_22(self): self.assert_expected(self.folder.t, 'CheckI18nTranslate.html') def FUNC_23(self): self.assert_expected(self.folder.t, 'CheckImportOldStyleClass.html') def FUNC_24(self): self.assert_expected(self.folder.t, 'RepeatVariable.html') def FUNC_25(self): self.assert_expected(self.folder.t, 'BooleanAttributes.html') def FUNC_26(self): self.assert_expected(self.folder.t, 'BooleanAttributesAndDefault.html') def FUNC_27(self): self.assert_expected(self.folder.t, 'InterpolationInContent.html') def FUNC_28(self): VAR_11 = self.folder.t VAR_11.write("<p tal:define='p a//b' />") with self.assertRaises(ExpressionError): VAR_11() def FUNC_29(self): self.assert_expected(self.folder.t, 'PathAlternativesWithSpaces.html') def FUNC_30(self): self.assert_expected(self.folder.t, 'Default.html') def FUNC_31(self): self.assert_expected(self.folder.t, 'switch.html') def FUNC_32(self): provideUtility(PreferredCharsetResolver) VAR_11 = PageTemplate() self.assert_expected(VAR_11, 'UnicodeResolution.html') def FUNC_33(self): VAR_11 = self.folder.t VAR_11.write('<p tal:define="p VAR_4/__class__" />') with self.assertRaises(NotFound): VAR_11() VAR_11.write('<p tal:define="p nocall: random/_itertools/repeat"/>') with self.assertRaises((NotFound, LocationError)): VAR_11() VAR_11.write('<p tal:VAR_17="random/_itertools/repeat/foobar"/>') with self.assertRaises((NotFound, LocationError)): VAR_11() def FUNC_34(self): VAR_11 = self.folder.z SecurityManager.setSecurityPolicy(self.oldPolicy) noSecurityManager() VAR_17 = ('<p tal:define="a nocall:%s"' ' tal:VAR_17="python: a().getUser().getUserName()"/>') VAR_11.write(VAR_17 % 'modules/AccessControl/getSecurityManager') self.assertEqual(VAR_11(), '<p>Anonymous User</p>') VAR_11.write('<p tal:define="a nocall:modules/AccessControl/users"/>') with self.assertRaises(NotFound): VAR_11() VAR_17 = ('<p tal:define="mod nocall:modules/AccessControl;' ' must_fail nocall:mod/users"/>') VAR_11.write(VAR_17) with self.assertRaises(NotFound): VAR_11() VAR_17 = ('<p tal:define="mod nocall:modules/AccessControl;' ' a_dict python: {\'unsafe\': mod};' ' must_fail nocall: a_dict/unsafe/users"/>') VAR_11.write(VAR_17) with self.assertRaises(NotFound): VAR_11()
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 17, 32, 34, 35, 38, 39, 42, 43, 48, 58, 61, 62, 65, 70, 73, 80, 85, 95, 104, 116, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 160, 167, 170, 173, 176, 179, 182, 184, 185, 187, 189, 190, 191, 193, 195, 196, 197, 199, 205, 208, 211, 214, 216, 220, 223, 227, 231, 235, 45, 46, 47 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 17, 34, 36, 37, 40, 41, 44, 45, 48, 49, 54, 64, 67, 68, 71, 76, 79, 87, 92, 102, 111, 123, 126, 129, 132, 135, 138, 141, 144, 147, 150, 153, 156, 159, 162, 165, 167, 174, 177, 180, 183, 186, 189, 191, 192, 194, 196, 197, 198, 200, 202, 203, 204, 206, 212, 215, 218, 221, 223, 227, 230, 234, 238, 242, 245, 246, 247, 248, 251, 252, 257, 258, 259, 263, 264, 270, 271, 278, 51, 52, 53 ]
4CWE-601
# -*- coding: utf-8 -*- # Copyright 2019 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import urllib.parse from typing import List, Optional from netaddr import AddrFormatError, IPAddress from zope.interface import implementer from twisted.internet import defer from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS from twisted.internet.interfaces import ( IProtocolFactory, IReactorCore, IStreamClientEndpoint, ) from twisted.web.client import URI, Agent, HTTPConnectionPool from twisted.web.http_headers import Headers from twisted.web.iweb import IAgent, IAgentEndpointFactory, IBodyProducer from synapse.crypto.context_factory import FederationPolicyForHTTPS from synapse.http.federation.srv_resolver import Server, SrvResolver from synapse.http.federation.well_known_resolver import WellKnownResolver from synapse.logging.context import make_deferred_yieldable, run_in_background from synapse.util import Clock logger = logging.getLogger(__name__) @implementer(IAgent) class MatrixFederationAgent: """An Agent-like thing which provides a `request` method which correctly handles resolving matrix server names when using matrix://. Handles standard https URIs as normal. Doesn't implement any retries. (Those are done in MatrixFederationHttpClient.) Args: reactor: twisted reactor to use for underlying requests tls_client_options_factory: factory to use for fetching client tls options, or none to disable TLS. user_agent: The user agent header to use for federation requests. _srv_resolver: SrvResolver implementation to use for looking up SRV records. None to use a default implementation. _well_known_resolver: WellKnownResolver to use to perform well-known lookups. None to use a default implementation. """ def __init__( self, reactor: IReactorCore, tls_client_options_factory: Optional[FederationPolicyForHTTPS], user_agent: bytes, _srv_resolver: Optional[SrvResolver] = None, _well_known_resolver: Optional[WellKnownResolver] = None, ): self._reactor = reactor self._clock = Clock(reactor) self._pool = HTTPConnectionPool(reactor) self._pool.retryAutomatically = False self._pool.maxPersistentPerHost = 5 self._pool.cachedConnectionTimeout = 2 * 60 self._agent = Agent.usingEndpointFactory( self._reactor, MatrixHostnameEndpointFactory( reactor, tls_client_options_factory, _srv_resolver ), pool=self._pool, ) self.user_agent = user_agent if _well_known_resolver is None: _well_known_resolver = WellKnownResolver( self._reactor, agent=Agent( self._reactor, pool=self._pool, contextFactory=tls_client_options_factory, ), user_agent=self.user_agent, ) self._well_known_resolver = _well_known_resolver @defer.inlineCallbacks def request( self, method: bytes, uri: bytes, headers: Optional[Headers] = None, bodyProducer: Optional[IBodyProducer] = None, ) -> defer.Deferred: """ Args: method: HTTP method: GET/POST/etc uri: Absolute URI to be retrieved headers: HTTP headers to send with the request, or None to send no extra headers. bodyProducer: An object which can generate bytes to make up the body of this request (for example, the properly encoded contents of a file for a file upload). Or None if the request is to have no body. Returns: Deferred[twisted.web.iweb.IResponse]: fires when the header of the response has been received (regardless of the response status code). Fails if there is any problem which prevents that response from being received (including problems that prevent the request from being sent). """ # We use urlparse as that will set `port` to None if there is no # explicit port. parsed_uri = urllib.parse.urlparse(uri) # There must be a valid hostname. assert parsed_uri.hostname # If this is a matrix:// URI check if the server has delegated matrix # traffic using well-known delegation. # # We have to do this here and not in the endpoint as we need to rewrite # the host header with the delegated server name. delegated_server = None if ( parsed_uri.scheme == b"matrix" and not _is_ip_literal(parsed_uri.hostname) and not parsed_uri.port ): well_known_result = yield defer.ensureDeferred( self._well_known_resolver.get_well_known(parsed_uri.hostname) ) delegated_server = well_known_result.delegated_server if delegated_server: # Ok, the server has delegated matrix traffic to somewhere else, so # lets rewrite the URL to replace the server with the delegated # server name. uri = urllib.parse.urlunparse( ( parsed_uri.scheme, delegated_server, parsed_uri.path, parsed_uri.params, parsed_uri.query, parsed_uri.fragment, ) ) parsed_uri = urllib.parse.urlparse(uri) # We need to make sure the host header is set to the netloc of the # server and that a user-agent is provided. if headers is None: headers = Headers() else: headers = headers.copy() if not headers.hasHeader(b"host"): headers.addRawHeader(b"host", parsed_uri.netloc) if not headers.hasHeader(b"user-agent"): headers.addRawHeader(b"user-agent", self.user_agent) res = yield make_deferred_yieldable( self._agent.request(method, uri, headers, bodyProducer) ) return res @implementer(IAgentEndpointFactory) class MatrixHostnameEndpointFactory: """Factory for MatrixHostnameEndpoint for parsing to an Agent. """ def __init__( self, reactor: IReactorCore, tls_client_options_factory: Optional[FederationPolicyForHTTPS], srv_resolver: Optional[SrvResolver], ): self._reactor = reactor self._tls_client_options_factory = tls_client_options_factory if srv_resolver is None: srv_resolver = SrvResolver() self._srv_resolver = srv_resolver def endpointForURI(self, parsed_uri): return MatrixHostnameEndpoint( self._reactor, self._tls_client_options_factory, self._srv_resolver, parsed_uri, ) @implementer(IStreamClientEndpoint) class MatrixHostnameEndpoint: """An endpoint that resolves matrix:// URLs using Matrix server name resolution (i.e. via SRV). Does not check for well-known delegation. Args: reactor: twisted reactor to use for underlying requests tls_client_options_factory: factory to use for fetching client tls options, or none to disable TLS. srv_resolver: The SRV resolver to use parsed_uri: The parsed URI that we're wanting to connect to. """ def __init__( self, reactor: IReactorCore, tls_client_options_factory: Optional[FederationPolicyForHTTPS], srv_resolver: SrvResolver, parsed_uri: URI, ): self._reactor = reactor self._parsed_uri = parsed_uri # set up the TLS connection params # # XXX disabling TLS is really only supported here for the benefit of the # unit tests. We should make the UTs cope with TLS rather than having to make # the code support the unit tests. if tls_client_options_factory is None: self._tls_options = None else: self._tls_options = tls_client_options_factory.get_options( self._parsed_uri.host ) self._srv_resolver = srv_resolver def connect(self, protocol_factory: IProtocolFactory) -> defer.Deferred: """Implements IStreamClientEndpoint interface """ return run_in_background(self._do_connect, protocol_factory) async def _do_connect(self, protocol_factory: IProtocolFactory) -> None: first_exception = None server_list = await self._resolve_server() for server in server_list: host = server.host port = server.port try: logger.debug("Connecting to %s:%i", host.decode("ascii"), port) endpoint = HostnameEndpoint(self._reactor, host, port) if self._tls_options: endpoint = wrapClientTLS(self._tls_options, endpoint) result = await make_deferred_yieldable( endpoint.connect(protocol_factory) ) return result except Exception as e: logger.info( "Failed to connect to %s:%i: %s", host.decode("ascii"), port, e ) if not first_exception: first_exception = e # We return the first failure because that's probably the most interesting. if first_exception: raise first_exception # This shouldn't happen as we should always have at least one host/port # to try and if that doesn't work then we'll have an exception. raise Exception("Failed to resolve server %r" % (self._parsed_uri.netloc,)) async def _resolve_server(self) -> List[Server]: """Resolves the server name to a list of hosts and ports to attempt to connect to. """ if self._parsed_uri.scheme != b"matrix": return [Server(host=self._parsed_uri.host, port=self._parsed_uri.port)] # Note: We don't do well-known lookup as that needs to have happened # before now, due to needing to rewrite the Host header of the HTTP # request. # We reparse the URI so that defaultPort is -1 rather than 80 parsed_uri = urllib.parse.urlparse(self._parsed_uri.toBytes()) host = parsed_uri.hostname port = parsed_uri.port # If there is an explicit port or the host is an IP address we bypass # SRV lookups and just use the given host/port. if port or _is_ip_literal(host): return [Server(host, port or 8448)] server_list = await self._srv_resolver.resolve_service(b"_matrix._tcp." + host) if server_list: return server_list # No SRV records, so we fallback to host and 8448 return [Server(host, 8448)] def _is_ip_literal(host: bytes) -> bool: """Test if the given host name is either an IPv4 or IPv6 literal. Args: host: The host name to check Returns: True if the hostname is an IP address literal. """ host_str = host.decode("ascii") try: IPAddress(host_str) return True except AddrFormatError: return False
# -*- coding: utf-8 -*- # Copyright 2019 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import urllib.parse from typing import List, Optional from netaddr import AddrFormatError, IPAddress, IPSet from zope.interface import implementer from twisted.internet import defer from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS from twisted.internet.interfaces import ( IProtocolFactory, IReactorCore, IStreamClientEndpoint, ) from twisted.web.client import URI, Agent, HTTPConnectionPool from twisted.web.http_headers import Headers from twisted.web.iweb import IAgent, IAgentEndpointFactory, IBodyProducer from synapse.crypto.context_factory import FederationPolicyForHTTPS from synapse.http.client import BlacklistingAgentWrapper from synapse.http.federation.srv_resolver import Server, SrvResolver from synapse.http.federation.well_known_resolver import WellKnownResolver from synapse.logging.context import make_deferred_yieldable, run_in_background from synapse.util import Clock logger = logging.getLogger(__name__) @implementer(IAgent) class MatrixFederationAgent: """An Agent-like thing which provides a `request` method which correctly handles resolving matrix server names when using matrix://. Handles standard https URIs as normal. Doesn't implement any retries. (Those are done in MatrixFederationHttpClient.) Args: reactor: twisted reactor to use for underlying requests tls_client_options_factory: factory to use for fetching client tls options, or none to disable TLS. user_agent: The user agent header to use for federation requests. _srv_resolver: SrvResolver implementation to use for looking up SRV records. None to use a default implementation. _well_known_resolver: WellKnownResolver to use to perform well-known lookups. None to use a default implementation. """ def __init__( self, reactor: IReactorCore, tls_client_options_factory: Optional[FederationPolicyForHTTPS], user_agent: bytes, ip_blacklist: IPSet, _srv_resolver: Optional[SrvResolver] = None, _well_known_resolver: Optional[WellKnownResolver] = None, ): self._reactor = reactor self._clock = Clock(reactor) self._pool = HTTPConnectionPool(reactor) self._pool.retryAutomatically = False self._pool.maxPersistentPerHost = 5 self._pool.cachedConnectionTimeout = 2 * 60 self._agent = Agent.usingEndpointFactory( self._reactor, MatrixHostnameEndpointFactory( reactor, tls_client_options_factory, _srv_resolver ), pool=self._pool, ) self.user_agent = user_agent if _well_known_resolver is None: # Note that the name resolver has already been wrapped in a # IPBlacklistingResolver by MatrixFederationHttpClient. _well_known_resolver = WellKnownResolver( self._reactor, agent=BlacklistingAgentWrapper( Agent( self._reactor, pool=self._pool, contextFactory=tls_client_options_factory, ), self._reactor, ip_blacklist=ip_blacklist, ), user_agent=self.user_agent, ) self._well_known_resolver = _well_known_resolver @defer.inlineCallbacks def request( self, method: bytes, uri: bytes, headers: Optional[Headers] = None, bodyProducer: Optional[IBodyProducer] = None, ) -> defer.Deferred: """ Args: method: HTTP method: GET/POST/etc uri: Absolute URI to be retrieved headers: HTTP headers to send with the request, or None to send no extra headers. bodyProducer: An object which can generate bytes to make up the body of this request (for example, the properly encoded contents of a file for a file upload). Or None if the request is to have no body. Returns: Deferred[twisted.web.iweb.IResponse]: fires when the header of the response has been received (regardless of the response status code). Fails if there is any problem which prevents that response from being received (including problems that prevent the request from being sent). """ # We use urlparse as that will set `port` to None if there is no # explicit port. parsed_uri = urllib.parse.urlparse(uri) # There must be a valid hostname. assert parsed_uri.hostname # If this is a matrix:// URI check if the server has delegated matrix # traffic using well-known delegation. # # We have to do this here and not in the endpoint as we need to rewrite # the host header with the delegated server name. delegated_server = None if ( parsed_uri.scheme == b"matrix" and not _is_ip_literal(parsed_uri.hostname) and not parsed_uri.port ): well_known_result = yield defer.ensureDeferred( self._well_known_resolver.get_well_known(parsed_uri.hostname) ) delegated_server = well_known_result.delegated_server if delegated_server: # Ok, the server has delegated matrix traffic to somewhere else, so # lets rewrite the URL to replace the server with the delegated # server name. uri = urllib.parse.urlunparse( ( parsed_uri.scheme, delegated_server, parsed_uri.path, parsed_uri.params, parsed_uri.query, parsed_uri.fragment, ) ) parsed_uri = urllib.parse.urlparse(uri) # We need to make sure the host header is set to the netloc of the # server and that a user-agent is provided. if headers is None: headers = Headers() else: headers = headers.copy() if not headers.hasHeader(b"host"): headers.addRawHeader(b"host", parsed_uri.netloc) if not headers.hasHeader(b"user-agent"): headers.addRawHeader(b"user-agent", self.user_agent) res = yield make_deferred_yieldable( self._agent.request(method, uri, headers, bodyProducer) ) return res @implementer(IAgentEndpointFactory) class MatrixHostnameEndpointFactory: """Factory for MatrixHostnameEndpoint for parsing to an Agent. """ def __init__( self, reactor: IReactorCore, tls_client_options_factory: Optional[FederationPolicyForHTTPS], srv_resolver: Optional[SrvResolver], ): self._reactor = reactor self._tls_client_options_factory = tls_client_options_factory if srv_resolver is None: srv_resolver = SrvResolver() self._srv_resolver = srv_resolver def endpointForURI(self, parsed_uri): return MatrixHostnameEndpoint( self._reactor, self._tls_client_options_factory, self._srv_resolver, parsed_uri, ) @implementer(IStreamClientEndpoint) class MatrixHostnameEndpoint: """An endpoint that resolves matrix:// URLs using Matrix server name resolution (i.e. via SRV). Does not check for well-known delegation. Args: reactor: twisted reactor to use for underlying requests tls_client_options_factory: factory to use for fetching client tls options, or none to disable TLS. srv_resolver: The SRV resolver to use parsed_uri: The parsed URI that we're wanting to connect to. """ def __init__( self, reactor: IReactorCore, tls_client_options_factory: Optional[FederationPolicyForHTTPS], srv_resolver: SrvResolver, parsed_uri: URI, ): self._reactor = reactor self._parsed_uri = parsed_uri # set up the TLS connection params # # XXX disabling TLS is really only supported here for the benefit of the # unit tests. We should make the UTs cope with TLS rather than having to make # the code support the unit tests. if tls_client_options_factory is None: self._tls_options = None else: self._tls_options = tls_client_options_factory.get_options( self._parsed_uri.host ) self._srv_resolver = srv_resolver def connect(self, protocol_factory: IProtocolFactory) -> defer.Deferred: """Implements IStreamClientEndpoint interface """ return run_in_background(self._do_connect, protocol_factory) async def _do_connect(self, protocol_factory: IProtocolFactory) -> None: first_exception = None server_list = await self._resolve_server() for server in server_list: host = server.host port = server.port try: logger.debug("Connecting to %s:%i", host.decode("ascii"), port) endpoint = HostnameEndpoint(self._reactor, host, port) if self._tls_options: endpoint = wrapClientTLS(self._tls_options, endpoint) result = await make_deferred_yieldable( endpoint.connect(protocol_factory) ) return result except Exception as e: logger.info( "Failed to connect to %s:%i: %s", host.decode("ascii"), port, e ) if not first_exception: first_exception = e # We return the first failure because that's probably the most interesting. if first_exception: raise first_exception # This shouldn't happen as we should always have at least one host/port # to try and if that doesn't work then we'll have an exception. raise Exception("Failed to resolve server %r" % (self._parsed_uri.netloc,)) async def _resolve_server(self) -> List[Server]: """Resolves the server name to a list of hosts and ports to attempt to connect to. """ if self._parsed_uri.scheme != b"matrix": return [Server(host=self._parsed_uri.host, port=self._parsed_uri.port)] # Note: We don't do well-known lookup as that needs to have happened # before now, due to needing to rewrite the Host header of the HTTP # request. # We reparse the URI so that defaultPort is -1 rather than 80 parsed_uri = urllib.parse.urlparse(self._parsed_uri.toBytes()) host = parsed_uri.hostname port = parsed_uri.port # If there is an explicit port or the host is an IP address we bypass # SRV lookups and just use the given host/port. if port or _is_ip_literal(host): return [Server(host, port or 8448)] server_list = await self._srv_resolver.resolve_service(b"_matrix._tcp." + host) if server_list: return server_list # No SRV records, so we fallback to host and 8448 return [Server(host, 8448)] def _is_ip_literal(host: bytes) -> bool: """Test if the given host name is either an IPv4 or IPv6 literal. Args: host: The host name to check Returns: True if the hostname is an IP address literal. """ host_str = host.decode("ascii") try: IPAddress(host_str) return True except AddrFormatError: return False
open_redirect
{ "code": [ "from netaddr import AddrFormatError, IPAddress", " agent=Agent(", " pool=self._pool,", " contextFactory=tls_client_options_factory," ], "line_no": [ 19, 95, 97, 98 ] }
{ "code": [ "from netaddr import AddrFormatError, IPAddress, IPSet", "from synapse.http.client import BlacklistingAgentWrapper", " ip_blacklist: IPSet,", " agent=BlacklistingAgentWrapper(", " Agent(", " self._reactor,", " contextFactory=tls_client_options_factory,", " ip_blacklist=ip_blacklist," ], "line_no": [ 19, 34, 74, 99, 100, 101, 103, 106 ] }
import logging import urllib.parse from typing import List, Optional from netaddr import AddrFormatError, IPAddress from zope.interface import implementer from twisted.internet import defer from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS from twisted.internet.interfaces import ( IProtocolFactory, IReactorCore, IStreamClientEndpoint, ) from twisted.web.client import URI, Agent, HTTPConnectionPool from twisted.web.http_headers import Headers from twisted.web.iweb import IAgent, IAgentEndpointFactory, IBodyProducer from synapse.crypto.context_factory import FederationPolicyForHTTPS from synapse.http.federation.srv_resolver import Server, SrvResolver from synapse.http.federation.well_known_resolver import WellKnownResolver from synapse.logging.context import make_deferred_yieldable, run_in_background from synapse.util import Clock VAR_0 = logging.getLogger(__name__) @implementer(IAgent) class CLASS_0: def __init__( self, VAR_2: IReactorCore, VAR_3: Optional[FederationPolicyForHTTPS], VAR_4: bytes, VAR_5: Optional[SrvResolver] = None, VAR_6: Optional[WellKnownResolver] = None, ): self._reactor = VAR_2 self._clock = Clock(VAR_2) self._pool = HTTPConnectionPool(VAR_2) self._pool.retryAutomatically = False self._pool.maxPersistentPerHost = 5 self._pool.cachedConnectionTimeout = 2 * 60 self._agent = Agent.usingEndpointFactory( self._reactor, CLASS_1( VAR_2, VAR_3, VAR_5 ), pool=self._pool, ) self.user_agent = VAR_4 if VAR_6 is None: VAR_6 = WellKnownResolver( self._reactor, agent=Agent( self._reactor, pool=self._pool, contextFactory=VAR_3, ), VAR_4=self.user_agent, ) self._well_known_resolver = VAR_6 @defer.inlineCallbacks def FUNC_1( self, VAR_7: bytes, VAR_8: bytes, VAR_9: Optional[Headers] = None, VAR_10: Optional[IBodyProducer] = None, ) -> defer.Deferred: VAR_12 = urllib.parse.urlparse(VAR_8) assert VAR_12.hostname VAR_15 = None if ( VAR_12.scheme == b"matrix" and not FUNC_0(VAR_12.hostname) and not VAR_12.port ): VAR_20 = yield defer.ensureDeferred( self._well_known_resolver.get_well_known(VAR_12.hostname) ) VAR_15 = VAR_20.delegated_server if VAR_15: VAR_8 = urllib.parse.urlunparse( ( VAR_12.scheme, VAR_15, VAR_12.path, VAR_12.params, VAR_12.query, VAR_12.fragment, ) ) VAR_12 = urllib.parse.urlparse(VAR_8) if VAR_9 is None: VAR_9 = Headers() else: VAR_9 = VAR_9.copy() if not VAR_9.hasHeader(b"host"): VAR_9.addRawHeader(b"host", VAR_12.netloc) if not VAR_9.hasHeader(b"user-agent"): VAR_9.addRawHeader(b"user-agent", self.user_agent) VAR_16 = yield make_deferred_yieldable( self._agent.request(VAR_7, VAR_8, VAR_9, VAR_10) ) return VAR_16 @implementer(IAgentEndpointFactory) class CLASS_1: def __init__( self, VAR_2: IReactorCore, VAR_3: Optional[FederationPolicyForHTTPS], VAR_11: Optional[SrvResolver], ): self._reactor = VAR_2 self._tls_client_options_factory = VAR_3 if VAR_11 is None: VAR_11 = SrvResolver() self._srv_resolver = VAR_11 def FUNC_2(self, VAR_12): return CLASS_2( self._reactor, self._tls_client_options_factory, self._srv_resolver, VAR_12, ) @implementer(IStreamClientEndpoint) class CLASS_2: def __init__( self, VAR_2: IReactorCore, VAR_3: Optional[FederationPolicyForHTTPS], VAR_11: SrvResolver, VAR_12: URI, ): self._reactor = VAR_2 self._parsed_uri = VAR_12 if VAR_3 is None: self._tls_options = None else: self._tls_options = VAR_3.get_options( self._parsed_uri.host ) self._srv_resolver = VAR_11 def FUNC_3(self, VAR_13: IProtocolFactory) -> defer.Deferred: return run_in_background(self._do_connect, VAR_13) async def FUNC_4(self, VAR_13: IProtocolFactory) -> None: VAR_17 = None VAR_18 = await self._resolve_server() for server in VAR_18: VAR_1 = server.host VAR_19 = server.port try: VAR_0.debug("Connecting to %s:%i", VAR_1.decode("ascii"), VAR_19) VAR_21 = HostnameEndpoint(self._reactor, VAR_1, VAR_19) if self._tls_options: VAR_21 = wrapClientTLS(self._tls_options, VAR_21) VAR_22 = await make_deferred_yieldable( VAR_21.connect(VAR_13) ) return VAR_22 except Exception as e: VAR_0.info( "Failed to FUNC_3 to %s:%i: %s", VAR_1.decode("ascii"), VAR_19, e ) if not VAR_17: first_exception = e if VAR_17: raise VAR_17 raise Exception("Failed to resolve server %r" % (self._parsed_uri.netloc,)) async def FUNC_5(self) -> List[Server]: if self._parsed_uri.scheme != b"matrix": return [Server(VAR_1=self._parsed_uri.host, VAR_19=self._parsed_uri.port)] VAR_12 = urllib.parse.urlparse(self._parsed_uri.toBytes()) VAR_1 = VAR_12.hostname VAR_19 = VAR_12.port if VAR_19 or FUNC_0(VAR_1): return [Server(VAR_1, VAR_19 or 8448)] VAR_18 = await self._srv_resolver.resolve_service(b"_matrix._tcp." + VAR_1) if VAR_18: return VAR_18 return [Server(VAR_1, 8448)] def FUNC_0(VAR_1: bytes) -> bool: VAR_14 = VAR_1.decode("ascii") try: IPAddress(VAR_14) return True except AddrFormatError: return False
import logging import urllib.parse from typing import List, Optional from netaddr import AddrFormatError, IPAddress, IPSet from zope.interface import implementer from twisted.internet import defer from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS from twisted.internet.interfaces import ( IProtocolFactory, IReactorCore, IStreamClientEndpoint, ) from twisted.web.client import URI, Agent, HTTPConnectionPool from twisted.web.http_headers import Headers from twisted.web.iweb import IAgent, IAgentEndpointFactory, IBodyProducer from synapse.crypto.context_factory import FederationPolicyForHTTPS from synapse.http.client import BlacklistingAgentWrapper from synapse.http.federation.srv_resolver import Server, SrvResolver from synapse.http.federation.well_known_resolver import WellKnownResolver from synapse.logging.context import make_deferred_yieldable, run_in_background from synapse.util import Clock VAR_0 = logging.getLogger(__name__) @implementer(IAgent) class CLASS_0: def __init__( self, VAR_2: IReactorCore, VAR_3: Optional[FederationPolicyForHTTPS], VAR_4: bytes, VAR_5: IPSet, VAR_6: Optional[SrvResolver] = None, VAR_7: Optional[WellKnownResolver] = None, ): self._reactor = VAR_2 self._clock = Clock(VAR_2) self._pool = HTTPConnectionPool(VAR_2) self._pool.retryAutomatically = False self._pool.maxPersistentPerHost = 5 self._pool.cachedConnectionTimeout = 2 * 60 self._agent = Agent.usingEndpointFactory( self._reactor, CLASS_1( VAR_2, VAR_3, VAR_6 ), pool=self._pool, ) self.user_agent = VAR_4 if VAR_7 is None: VAR_7 = WellKnownResolver( self._reactor, agent=BlacklistingAgentWrapper( Agent( self._reactor, pool=self._pool, contextFactory=VAR_3, ), self._reactor, VAR_5=ip_blacklist, ), VAR_4=self.user_agent, ) self._well_known_resolver = VAR_7 @defer.inlineCallbacks def FUNC_1( self, VAR_8: bytes, VAR_9: bytes, VAR_10: Optional[Headers] = None, VAR_11: Optional[IBodyProducer] = None, ) -> defer.Deferred: VAR_13 = urllib.parse.urlparse(VAR_9) assert VAR_13.hostname VAR_16 = None if ( VAR_13.scheme == b"matrix" and not FUNC_0(VAR_13.hostname) and not VAR_13.port ): VAR_21 = yield defer.ensureDeferred( self._well_known_resolver.get_well_known(VAR_13.hostname) ) VAR_16 = VAR_21.delegated_server if VAR_16: VAR_9 = urllib.parse.urlunparse( ( VAR_13.scheme, VAR_16, VAR_13.path, VAR_13.params, VAR_13.query, VAR_13.fragment, ) ) VAR_13 = urllib.parse.urlparse(VAR_9) if VAR_10 is None: VAR_10 = Headers() else: VAR_10 = VAR_10.copy() if not VAR_10.hasHeader(b"host"): VAR_10.addRawHeader(b"host", VAR_13.netloc) if not VAR_10.hasHeader(b"user-agent"): VAR_10.addRawHeader(b"user-agent", self.user_agent) VAR_17 = yield make_deferred_yieldable( self._agent.request(VAR_8, VAR_9, VAR_10, VAR_11) ) return VAR_17 @implementer(IAgentEndpointFactory) class CLASS_1: def __init__( self, VAR_2: IReactorCore, VAR_3: Optional[FederationPolicyForHTTPS], VAR_12: Optional[SrvResolver], ): self._reactor = VAR_2 self._tls_client_options_factory = VAR_3 if VAR_12 is None: VAR_12 = SrvResolver() self._srv_resolver = VAR_12 def FUNC_2(self, VAR_13): return CLASS_2( self._reactor, self._tls_client_options_factory, self._srv_resolver, VAR_13, ) @implementer(IStreamClientEndpoint) class CLASS_2: def __init__( self, VAR_2: IReactorCore, VAR_3: Optional[FederationPolicyForHTTPS], VAR_12: SrvResolver, VAR_13: URI, ): self._reactor = VAR_2 self._parsed_uri = VAR_13 if VAR_3 is None: self._tls_options = None else: self._tls_options = VAR_3.get_options( self._parsed_uri.host ) self._srv_resolver = VAR_12 def FUNC_3(self, VAR_14: IProtocolFactory) -> defer.Deferred: return run_in_background(self._do_connect, VAR_14) async def FUNC_4(self, VAR_14: IProtocolFactory) -> None: VAR_18 = None VAR_19 = await self._resolve_server() for server in VAR_19: VAR_1 = server.host VAR_20 = server.port try: VAR_0.debug("Connecting to %s:%i", VAR_1.decode("ascii"), VAR_20) VAR_22 = HostnameEndpoint(self._reactor, VAR_1, VAR_20) if self._tls_options: VAR_22 = wrapClientTLS(self._tls_options, VAR_22) VAR_23 = await make_deferred_yieldable( VAR_22.connect(VAR_14) ) return VAR_23 except Exception as e: VAR_0.info( "Failed to FUNC_3 to %s:%i: %s", VAR_1.decode("ascii"), VAR_20, e ) if not VAR_18: first_exception = e if VAR_18: raise VAR_18 raise Exception("Failed to resolve server %r" % (self._parsed_uri.netloc,)) async def FUNC_5(self) -> List[Server]: if self._parsed_uri.scheme != b"matrix": return [Server(VAR_1=self._parsed_uri.host, VAR_20=self._parsed_uri.port)] VAR_13 = urllib.parse.urlparse(self._parsed_uri.toBytes()) VAR_1 = VAR_13.hostname VAR_20 = VAR_13.port if VAR_20 or FUNC_0(VAR_1): return [Server(VAR_1, VAR_20 or 8448)] VAR_19 = await self._srv_resolver.resolve_service(b"_matrix._tcp." + VAR_1) if VAR_19: return VAR_19 return [Server(VAR_1, 8448)] def FUNC_0(VAR_1: bytes) -> bool: VAR_15 = VAR_1.decode("ascii") try: IPAddress(VAR_15) return True except AddrFormatError: return False
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 18, 21, 32, 38, 40, 41, 47, 49, 52, 55, 58, 62, 67, 82, 91, 102, 104, 131, 132, 134, 135, 137, 138, 139, 140, 141, 142, 153, 155, 156, 157, 169, 170, 171, 176, 181, 185, 187, 188, 193, 202, 205, 207, 215, 216, 221, 229, 238, 240, 241, 242, 243, 244, 245, 246, 253, 255, 259, 261, 264, 266, 270, 279, 287, 288, 291, 292, 293, 295, 300, 303, 304, 305, 306, 307, 308, 310, 313, 314, 315, 318, 320, 323, 324, 326, 327, 330, 333, 337, 339, 345, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 191, 192, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 329, 330, 331, 332, 333, 334, 335, 336, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 257, 258, 297, 298, 299 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 18, 21, 32, 39, 41, 42, 48, 50, 53, 56, 59, 63, 68, 84, 93, 95, 96, 110, 112, 139, 140, 142, 143, 145, 146, 147, 148, 149, 150, 161, 163, 164, 165, 177, 178, 179, 184, 189, 193, 195, 196, 201, 210, 213, 215, 223, 224, 229, 237, 246, 248, 249, 250, 251, 252, 253, 254, 261, 263, 267, 269, 272, 274, 278, 287, 295, 296, 299, 300, 301, 303, 308, 311, 312, 313, 314, 315, 316, 318, 321, 322, 323, 326, 328, 331, 332, 334, 335, 338, 341, 345, 347, 353, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 199, 200, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 337, 338, 339, 340, 341, 342, 343, 344, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 265, 266, 305, 306, 307 ]
3CWE-352
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2018-2019 shavitmichael, OzzieIsaacs # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """This module is used to control authentication/authorization of Kobo sync requests. This module also includes research notes into the auth protocol used by Kobo devices. Log-in: When first booting a Kobo device the user must sign into a Kobo (or affiliate) account. Upon successful sign-in, the user is redirected to https://auth.kobobooks.com/CrossDomainSignIn?id=<some id> which serves the following response: <script type='text/javascript'> location.href='kobo://UserAuthenticated?userId=<redacted>&userKey<redacted>&email=<redacted>&returnUrl=https%3a%2f%2fwww.kobo.com'; </script> And triggers the insertion of a userKey into the device's User table. Together, the device's DeviceId and UserKey act as an *irrevocable* authentication token to most (if not all) Kobo APIs. In fact, in most cases only the UserKey is required to authorize the API call. Changing Kobo password *does not* invalidate user keys! This is apparently a known issue for a few years now https://www.mobileread.com/forums/showpost.php?p=3476851&postcount=13 (although this poster hypothesised that Kobo could blacklist a DeviceId, many endpoints will still grant access given the userkey.) Official Kobo Store Api authorization: * For most of the endpoints we care about (sync, metadata, tags, etc), the userKey is passed in the x-kobo-userkey header, and is sufficient to authorize the API call. * Some endpoints (e.g: AnnotationService) instead make use of Bearer tokens pass through an authorization header. To get a BearerToken, the device makes a POST request to the v1/auth/device endpoint with the secret UserKey and the device's DeviceId. * The book download endpoint passes an auth token as a URL param instead of a header. Our implementation: We pretty much ignore all of the above. To authenticate the user, we generate a random and unique token that they append to the CalibreWeb Url when setting up the api_store setting on the device. Thus, every request from the device to the api_store will hit CalibreWeb with the auth_token in the url (e.g: https://mylibrary.com/<auth_token>/v1/library/sync). In addition, once authenticated we also set the login cookie on the response that will be sent back for the duration of the session to authorize subsequent API calls (in particular calls to non-Kobo specific endpoints such as the CalibreWeb book download). """ from binascii import hexlify from datetime import datetime from os import urandom from flask import g, Blueprint, url_for, abort, request from flask_login import login_user, current_user, login_required from flask_babel import gettext as _ from . import logger, config, calibre_db, db, helper, ub, lm from .render_template import render_title_template try: from functools import wraps except ImportError: pass # We're not using Python 3 log = logger.create() def register_url_value_preprocessor(kobo): @kobo.url_value_preprocessor # pylint: disable=unused-variable def pop_auth_token(__, values): g.auth_token = values.pop("auth_token") def disable_failed_auth_redirect_for_blueprint(bp): lm.blueprint_login_views[bp.name] = None def get_auth_token(): if "auth_token" in g: return g.get("auth_token") else: return None def requires_kobo_auth(f): @wraps(f) def inner(*args, **kwargs): auth_token = get_auth_token() if auth_token is not None: user = ( ub.session.query(ub.User) .join(ub.RemoteAuthToken) .filter(ub.RemoteAuthToken.auth_token == auth_token).filter(ub.RemoteAuthToken.token_type==1) .first() ) if user is not None: login_user(user) return f(*args, **kwargs) log.debug("Received Kobo request without a recognizable auth token.") return abort(401) return inner kobo_auth = Blueprint("kobo_auth", __name__, url_prefix="/kobo_auth") @kobo_auth.route("/generate_auth_token/<int:user_id>") @login_required def generate_auth_token(user_id): host_list = request.host.rsplit(':') if len(host_list) == 1: host = ':'.join(host_list) else: host = ':'.join(host_list[0:-1]) if host.startswith('127.') or host.lower() == 'localhost' or host.startswith('[::ffff:7f'): warning = _('PLease access calibre-web from non localhost to get valid api_endpoint for kobo device') return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), warning = warning ) else: # Invalidate any prevously generated Kobo Auth token for this user. auth_token = ub.session.query(ub.RemoteAuthToken).filter( ub.RemoteAuthToken.user_id == user_id ).filter(ub.RemoteAuthToken.token_type==1).first() if not auth_token: auth_token = ub.RemoteAuthToken() auth_token.user_id = user_id auth_token.expiration = datetime.max auth_token.auth_token = (hexlify(urandom(16))).decode("utf-8") auth_token.token_type = 1 ub.session.add(auth_token) ub.session_commit() books = calibre_db.session.query(db.Books).join(db.Data).all() for book in books: formats = [data.format for data in book.data] if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats: helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name) return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), kobo_auth_url=url_for( "kobo.TopLevelEndpoint", auth_token=auth_token.auth_token, _external=True ), warning = False ) @kobo_auth.route("/deleteauthtoken/<int:user_id>") @login_required def delete_auth_token(user_id): # Invalidate any prevously generated Kobo Auth token for this user. ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == user_id)\ .filter(ub.RemoteAuthToken.token_type==1).delete() return ub.session_commit()
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2018-2019 shavitmichael, OzzieIsaacs # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """This module is used to control authentication/authorization of Kobo sync requests. This module also includes research notes into the auth protocol used by Kobo devices. Log-in: When first booting a Kobo device the user must sign into a Kobo (or affiliate) account. Upon successful sign-in, the user is redirected to https://auth.kobobooks.com/CrossDomainSignIn?id=<some id> which serves the following response: <script type='text/javascript'> location.href='kobo://UserAuthenticated?userId=<redacted>&userKey<redacted>&email=<redacted>&returnUrl=https%3a%2f%2fwww.kobo.com'; </script> And triggers the insertion of a userKey into the device's User table. Together, the device's DeviceId and UserKey act as an *irrevocable* authentication token to most (if not all) Kobo APIs. In fact, in most cases only the UserKey is required to authorize the API call. Changing Kobo password *does not* invalidate user keys! This is apparently a known issue for a few years now https://www.mobileread.com/forums/showpost.php?p=3476851&postcount=13 (although this poster hypothesised that Kobo could blacklist a DeviceId, many endpoints will still grant access given the userkey.) Official Kobo Store Api authorization: * For most of the endpoints we care about (sync, metadata, tags, etc), the userKey is passed in the x-kobo-userkey header, and is sufficient to authorize the API call. * Some endpoints (e.g: AnnotationService) instead make use of Bearer tokens pass through an authorization header. To get a BearerToken, the device makes a POST request to the v1/auth/device endpoint with the secret UserKey and the device's DeviceId. * The book download endpoint passes an auth token as a URL param instead of a header. Our implementation: We pretty much ignore all of the above. To authenticate the user, we generate a random and unique token that they append to the CalibreWeb Url when setting up the api_store setting on the device. Thus, every request from the device to the api_store will hit CalibreWeb with the auth_token in the url (e.g: https://mylibrary.com/<auth_token>/v1/library/sync). In addition, once authenticated we also set the login cookie on the response that will be sent back for the duration of the session to authorize subsequent API calls (in particular calls to non-Kobo specific endpoints such as the CalibreWeb book download). """ from binascii import hexlify from datetime import datetime from os import urandom from functools import wraps from flask import g, Blueprint, url_for, abort, request from flask_login import login_user, current_user, login_required from flask_babel import gettext as _ from . import logger, config, calibre_db, db, helper, ub, lm from .render_template import render_title_template log = logger.create() def register_url_value_preprocessor(kobo): @kobo.url_value_preprocessor # pylint: disable=unused-variable def pop_auth_token(__, values): g.auth_token = values.pop("auth_token") def disable_failed_auth_redirect_for_blueprint(bp): lm.blueprint_login_views[bp.name] = None def get_auth_token(): if "auth_token" in g: return g.get("auth_token") else: return None def requires_kobo_auth(f): @wraps(f) def inner(*args, **kwargs): auth_token = get_auth_token() if auth_token is not None: user = ( ub.session.query(ub.User) .join(ub.RemoteAuthToken) .filter(ub.RemoteAuthToken.auth_token == auth_token).filter(ub.RemoteAuthToken.token_type==1) .first() ) if user is not None: login_user(user) return f(*args, **kwargs) log.debug("Received Kobo request without a recognizable auth token.") return abort(401) return inner kobo_auth = Blueprint("kobo_auth", __name__, url_prefix="/kobo_auth") @kobo_auth.route("/generate_auth_token/<int:user_id>") @login_required def generate_auth_token(user_id): host_list = request.host.rsplit(':') if len(host_list) == 1: host = ':'.join(host_list) else: host = ':'.join(host_list[0:-1]) if host.startswith('127.') or host.lower() == 'localhost' or host.startswith('[::ffff:7f'): warning = _('PLease access calibre-web from non localhost to get valid api_endpoint for kobo device') return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), warning = warning ) else: # Invalidate any prevously generated Kobo Auth token for this user. auth_token = ub.session.query(ub.RemoteAuthToken).filter( ub.RemoteAuthToken.user_id == user_id ).filter(ub.RemoteAuthToken.token_type==1).first() if not auth_token: auth_token = ub.RemoteAuthToken() auth_token.user_id = user_id auth_token.expiration = datetime.max auth_token.auth_token = (hexlify(urandom(16))).decode("utf-8") auth_token.token_type = 1 ub.session.add(auth_token) ub.session_commit() books = calibre_db.session.query(db.Books).join(db.Data).all() for book in books: formats = [data.format for data in book.data] if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats: helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name) return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), kobo_auth_url=url_for( "kobo.TopLevelEndpoint", auth_token=auth_token.auth_token, _external=True ), warning = False ) @kobo_auth.route("/deleteauthtoken/<int:user_id>", methods=["POST"]) @login_required def delete_auth_token(user_id): # Invalidate any prevously generated Kobo Auth token for this user. ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == user_id)\ .filter(ub.RemoteAuthToken.token_type==1).delete() return ub.session_commit()
xsrf
{ "code": [ "try:", " from functools import wraps", "except ImportError:", "@kobo_auth.route(\"/deleteauthtoken/<int:user_id>\")" ], "line_no": [ 73, 74, 75, 170 ] }
{ "code": [ "@kobo_auth.route(\"/deleteauthtoken/<int:user_id>\", methods=[\"POST\"])" ], "line_no": [ 166 ] }
from binascii import hexlify from datetime import datetime from os import urandom from flask import g, Blueprint, url_for, abort, request from flask_login import .login_user, current_user, login_required from flask_babel import gettext as _ from . import .logger, config, calibre_db, db, helper, ub, VAR_8 from .render_template import render_title_template try: from functools import wraps except ImportError: pass # We're not using Python 3 VAR_0 = logger.create() def FUNC_0(VAR_1): @kobo.url_value_preprocessor def FUNC_6(VAR_6, VAR_7): g.auth_token = VAR_7.pop("auth_token") def FUNC_1(VAR_2): VAR_8.blueprint_login_views[VAR_2.name] = None def FUNC_2(): if "auth_token" in g: return g.get("auth_token") else: return None def FUNC_3(VAR_3): @wraps(VAR_3) def FUNC_7(*VAR_9, **VAR_10): VAR_12 = FUNC_2() if VAR_12 is not None: VAR_16 = ( ub.session.query(ub.User) .join(ub.RemoteAuthToken) .filter(ub.RemoteAuthToken.auth_token == VAR_12).filter(ub.RemoteAuthToken.token_type==1) .first() ) if VAR_16 is not None: login_user(VAR_16) return VAR_3(*VAR_9, **VAR_10) VAR_0.debug("Received Kobo request without a recognizable auth token.") return abort(401) return FUNC_7 VAR_4 = Blueprint("kobo_auth", __name__, url_prefix="/kobo_auth") @VAR_4.route("/FUNC_4/<int:VAR_5>") @login_required def FUNC_4(VAR_5): VAR_11 = request.host.rsplit(':') if len(VAR_11) == 1: VAR_13 = ':'.join(VAR_11) else: VAR_13 = ':'.join(VAR_11[0:-1]) if VAR_13.startswith('127.') or VAR_13.lower() == 'localhost' or VAR_13.startswith('[::ffff:7f'): VAR_14 = _('PLease access calibre-web from non localhost to get valid api_endpoint for VAR_1 device') return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), VAR_14 = warning ) else: VAR_12 = ub.session.query(ub.RemoteAuthToken).filter( ub.RemoteAuthToken.user_id == VAR_5 ).filter(ub.RemoteAuthToken.token_type==1).first() if not VAR_12: VAR_12 = ub.RemoteAuthToken() VAR_12.user_id = VAR_5 VAR_12.expiration = datetime.max VAR_12.auth_token = (hexlify(urandom(16))).decode("utf-8") VAR_12.token_type = 1 ub.session.add(VAR_12) ub.session_commit() VAR_15 = calibre_db.session.query(db.Books).join(db.Data).all() for book in VAR_15: VAR_17 = [data.format for data in book.data] if not 'KEPUB' in VAR_17 and config.config_kepubifypath and 'EPUB' in VAR_17: helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name) return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), kobo_auth_url=url_for( "kobo.TopLevelEndpoint", VAR_12=auth_token.auth_token, _external=True ), VAR_14 = False ) @VAR_4.route("/deleteauthtoken/<int:VAR_5>") @login_required def FUNC_5(VAR_5): ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == VAR_5)\ .filter(ub.RemoteAuthToken.token_type==1).delete() return ub.session_commit()
from binascii import hexlify from datetime import datetime from os import urandom from functools import wraps from flask import g, Blueprint, url_for, abort, request from flask_login import .login_user, current_user, login_required from flask_babel import gettext as _ from . import .logger, config, calibre_db, db, helper, ub, VAR_8 from .render_template import render_title_template VAR_0 = logger.create() def FUNC_0(VAR_1): @kobo.url_value_preprocessor def FUNC_6(VAR_6, VAR_7): g.auth_token = VAR_7.pop("auth_token") def FUNC_1(VAR_2): VAR_8.blueprint_login_views[VAR_2.name] = None def FUNC_2(): if "auth_token" in g: return g.get("auth_token") else: return None def FUNC_3(VAR_3): @wraps(VAR_3) def FUNC_7(*VAR_9, **VAR_10): VAR_12 = FUNC_2() if VAR_12 is not None: VAR_16 = ( ub.session.query(ub.User) .join(ub.RemoteAuthToken) .filter(ub.RemoteAuthToken.auth_token == VAR_12).filter(ub.RemoteAuthToken.token_type==1) .first() ) if VAR_16 is not None: login_user(VAR_16) return VAR_3(*VAR_9, **VAR_10) VAR_0.debug("Received Kobo request without a recognizable auth token.") return abort(401) return FUNC_7 VAR_4 = Blueprint("kobo_auth", __name__, url_prefix="/kobo_auth") @VAR_4.route("/FUNC_4/<int:VAR_5>") @login_required def FUNC_4(VAR_5): VAR_11 = request.host.rsplit(':') if len(VAR_11) == 1: VAR_13 = ':'.join(VAR_11) else: VAR_13 = ':'.join(VAR_11[0:-1]) if VAR_13.startswith('127.') or VAR_13.lower() == 'localhost' or VAR_13.startswith('[::ffff:7f'): VAR_14 = _('PLease access calibre-web from non localhost to get valid api_endpoint for VAR_1 device') return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), VAR_14 = warning ) else: VAR_12 = ub.session.query(ub.RemoteAuthToken).filter( ub.RemoteAuthToken.user_id == VAR_5 ).filter(ub.RemoteAuthToken.token_type==1).first() if not VAR_12: VAR_12 = ub.RemoteAuthToken() VAR_12.user_id = VAR_5 VAR_12.expiration = datetime.max VAR_12.auth_token = (hexlify(urandom(16))).decode("utf-8") VAR_12.token_type = 1 ub.session.add(VAR_12) ub.session_commit() VAR_15 = calibre_db.session.query(db.Books).join(db.Data).all() for book in VAR_15: VAR_17 = [data.format for data in book.data] if not 'KEPUB' in VAR_17 and config.config_kepubifypath and 'EPUB' in VAR_17: helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name) return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), kobo_auth_url=url_for( "kobo.TopLevelEndpoint", VAR_12=auth_token.auth_token, _external=True ), VAR_14 = False ) @VAR_4.route("/deleteauthtoken/<int:VAR_5>", methods=["POST"]) @login_required def FUNC_5(VAR_5): ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == VAR_5)\ .filter(ub.RemoteAuthToken.token_type==1).delete() return ub.session_commit()
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 23, 33, 37, 42, 50, 61, 65, 69, 72, 77, 78, 80, 81, 84, 87, 88, 91, 92, 98, 99, 117, 118, 120, 121, 138, 142, 149, 152, 154, 159, 168, 169, 173, 176, 178, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 23, 33, 37, 42, 50, 61, 66, 70, 73, 74, 76, 77, 80, 83, 84, 87, 88, 94, 95, 113, 114, 116, 117, 134, 138, 145, 148, 150, 155, 164, 165, 169, 172, 174, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 ]
4CWE-601
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2011 University of Dundee & Open Microscopy Environment. # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Decorators for use with the webclient application. """ import logging import omeroweb.decorators from omero import constants from django.http import HttpResponse from django.conf import settings from django.core.urlresolvers import reverse from django.core.urlresolvers import NoReverseMatch from omeroweb.webclient.forms import GlobalSearchForm from omeroweb.utils import reverse_with_params from omeroweb.webgateway.marshal import eventContextMarshal logger = logging.getLogger(__name__) class login_required(omeroweb.decorators.login_required): """ webclient specific extension of the OMERO.web login_required() decorator. """ def __init__( self, ignore_login_fail=False, setGroupContext=False, login_redirect=None, **kwargs ): """ Initialises the decorator. """ super(login_required, self).__init__(**kwargs) self.ignore_login_fail = ignore_login_fail self.setGroupContext = setGroupContext self.login_redirect = login_redirect def on_logged_in(self, request, conn): """Called whenever the users is successfully logged in.""" super(login_required, self).on_logged_in(request, conn) self.prepare_session(request) if self.setGroupContext: if request.session.get("active_group"): conn.SERVICE_OPTS.setOmeroGroup(request.session.get("active_group")) else: conn.SERVICE_OPTS.setOmeroGroup(conn.getEventContext().groupId) def on_not_logged_in(self, request, url, error=None): """ This can be used to fail silently (not return 403, 500 etc. E.g. keepalive ping) """ if self.ignore_login_fail: return HttpResponse("Connection Failed") if self.login_redirect is not None: try: url = reverse(self.login_redirect) except Exception: pass return super(login_required, self).on_not_logged_in(request, url, error) def prepare_session(self, request): """Prepares various session variables.""" changes = False if request.session.get("callback") is None: request.session["callback"] = dict() changes = True if request.session.get("shares") is None: request.session["shares"] = dict() changes = True if changes: request.session.modified = True class render_response(omeroweb.decorators.render_response): """ Subclass for adding additional data to the 'context' dict passed to templates """ def prepare_context(self, request, context, *args, **kwargs): """ This allows templates to access the current eventContext and user from the L{omero.gateway.BlitzGateway}. E.g. <h1>{{ ome.user.getFullName }}</h1> If these are not required by the template, then they will not need to be loaded by the Blitz Gateway. The results are cached by Blitz Gateway, so repeated calls have no additional cost. We also process some values from settings and add these to the context. """ # we expect @login_required to pass us 'conn', but just in case... if "conn" not in kwargs: return conn = kwargs["conn"] # omero constants context["omero"] = { "constants": { "NSCOMPANIONFILE": constants.namespaces.NSCOMPANIONFILE, "ORIGINALMETADATA": constants.annotation.file.ORIGINALMETADATA, "NSCLIENTMAPANNOTATION": constants.metadata.NSCLIENTMAPANNOTATION, } } context.setdefault("ome", {}) # don't overwrite existing ome public_user = omeroweb.decorators.is_public_user(request) if public_user is not None: context["ome"]["is_public_user"] = public_user context["ome"]["eventContext"] = eventContextMarshal(conn.getEventContext()) context["ome"]["user"] = conn.getUser context["ome"]["user_id"] = request.session.get("user_id", conn.getUserId()) context["ome"]["group_id"] = request.session.get("group_id", None) context["ome"]["active_group"] = request.session.get( "active_group", conn.getEventContext().groupId ) context["global_search_form"] = GlobalSearchForm() context["ome"]["can_create"] = request.session.get("can_create", True) # UI server preferences if request.session.get("server_settings"): context["ome"]["email"] = request.session.get("server_settings").get( "email", False ) if request.session.get("server_settings").get("ui"): # don't overwrite existing ui context.setdefault("ui", {"tree": {}}) context["ui"]["orphans"] = ( request.session.get("server_settings") .get("ui", {}) .get("tree", {}) .get("orphans") ) context["ui"]["dropdown_menu"] = ( request.session.get("server_settings") .get("ui", {}) .get("menu", {}) .get("dropdown") ) context["ui"]["tree"]["type_order"] = ( request.session.get("server_settings") .get("ui", {}) .get("tree", {}) .get("type_order") ) self.load_settings(request, context, conn) def load_settings(self, request, context, conn): # Process various settings and add to the template context dict ping_interval = settings.PING_INTERVAL if ping_interval > 0: context["ping_interval"] = ping_interval top_links = settings.TOP_LINKS links = [] for tl in top_links: if len(tl) < 2: continue link = {} link["label"] = tl[0] link_id = tl[1] try: # test if complex dictionary view with args and query_string link["link"] = reverse_with_params(**link_id) except TypeError: # assume is only view name try: link["link"] = reverse(link_id) except NoReverseMatch: # assume we've been passed a url link["link"] = link_id # simply add optional attrs dict if len(tl) > 2: link["attrs"] = tl[2] links.append(link) context["ome"]["top_links"] = links if settings.TOP_LOGO: context["ome"]["logo_src"] = settings.TOP_LOGO if settings.TOP_LOGO_LINK: context["ome"]["logo_href"] = settings.TOP_LOGO_LINK metadata_panes = settings.METADATA_PANES context["ome"]["metadata_panes"] = metadata_panes right_plugins = settings.RIGHT_PLUGINS r_plugins = [] for rt in right_plugins: label = rt[0] include = rt[1] plugin_id = rt[2] r_plugins.append( {"label": label, "include": include, "plugin_id": plugin_id} ) context["ome"]["right_plugins"] = r_plugins center_plugins = settings.CENTER_PLUGINS c_plugins = [] for cp in center_plugins: label = cp[0] include = cp[1] plugin_id = cp[2] c_plugins.append( {"label": label, "include": include, "plugin_id": plugin_id} ) context["ome"]["center_plugins"] = c_plugins context["ome"]["user_dropdown"] = settings.USER_DROPDOWN
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2011 University of Dundee & Open Microscopy Environment. # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Decorators for use with the webclient application. """ import logging import omeroweb.decorators from omero import constants from django.http import HttpResponse from django.conf import settings from django.core.urlresolvers import reverse from django.core.urlresolvers import NoReverseMatch from omeroweb.webclient.forms import GlobalSearchForm from omeroweb.utils import reverse_with_params logger = logging.getLogger(__name__) class login_required(omeroweb.decorators.login_required): """ webclient specific extension of the OMERO.web login_required() decorator. """ def __init__( self, ignore_login_fail=False, setGroupContext=False, login_redirect=None, **kwargs ): """ Initialises the decorator. """ super(login_required, self).__init__(**kwargs) self.ignore_login_fail = ignore_login_fail self.setGroupContext = setGroupContext self.login_redirect = login_redirect def on_logged_in(self, request, conn): """Called whenever the users is successfully logged in.""" super(login_required, self).on_logged_in(request, conn) self.prepare_session(request) if self.setGroupContext: if request.session.get("active_group"): conn.SERVICE_OPTS.setOmeroGroup(request.session.get("active_group")) else: conn.SERVICE_OPTS.setOmeroGroup(conn.getEventContext().groupId) def on_not_logged_in(self, request, url, error=None): """ This can be used to fail silently (not return 403, 500 etc. E.g. keepalive ping) """ if self.ignore_login_fail: return HttpResponse("Connection Failed") if self.login_redirect is not None: try: url = reverse(self.login_redirect) except Exception: pass return super(login_required, self).on_not_logged_in(request, url, error) def prepare_session(self, request): """Prepares various session variables.""" changes = False if request.session.get("callback") is None: request.session["callback"] = dict() changes = True if request.session.get("shares") is None: request.session["shares"] = dict() changes = True if changes: request.session.modified = True class render_response(omeroweb.decorators.render_response): """ Subclass for adding additional data to the 'context' dict passed to templates """ def prepare_context(self, request, context, *args, **kwargs): """ This allows templates to access the current eventContext and user from the L{omero.gateway.BlitzGateway}. E.g. <h1>{{ ome.user.getFullName }}</h1> If these are not required by the template, then they will not need to be loaded by the Blitz Gateway. The results are cached by Blitz Gateway, so repeated calls have no additional cost. We also process some values from settings and add these to the context. """ super(render_response, self).prepare_context(request, context, *args, **kwargs) # we expect @login_required to pass us 'conn', but just in case... if "conn" not in kwargs: return conn = kwargs["conn"] # omero constants context["omero"] = { "constants": { "NSCOMPANIONFILE": constants.namespaces.NSCOMPANIONFILE, "ORIGINALMETADATA": constants.annotation.file.ORIGINALMETADATA, "NSCLIENTMAPANNOTATION": constants.metadata.NSCLIENTMAPANNOTATION, } } context.setdefault("ome", {}) # don't overwrite existing ome public_user = omeroweb.decorators.is_public_user(request) if public_user is not None: context["ome"]["is_public_user"] = public_user context["ome"]["user"] = conn.getUser context["ome"]["user_id"] = request.session.get("user_id", conn.getUserId()) context["ome"]["group_id"] = request.session.get("group_id", None) context["ome"]["active_group"] = request.session.get( "active_group", conn.getEventContext().groupId ) context["global_search_form"] = GlobalSearchForm() context["ome"]["can_create"] = request.session.get("can_create", True) # UI server preferences if request.session.get("server_settings"): context["ome"]["email"] = request.session.get("server_settings").get( "email", False ) if request.session.get("server_settings").get("ui"): # don't overwrite existing ui context.setdefault("ui", {"tree": {}}) context["ui"]["orphans"] = ( request.session.get("server_settings") .get("ui", {}) .get("tree", {}) .get("orphans") ) context["ui"]["dropdown_menu"] = ( request.session.get("server_settings") .get("ui", {}) .get("menu", {}) .get("dropdown") ) context["ui"]["tree"]["type_order"] = ( request.session.get("server_settings") .get("ui", {}) .get("tree", {}) .get("type_order") ) self.load_settings(request, context, conn) def load_settings(self, request, context, conn): # Process various settings and add to the template context dict ping_interval = settings.PING_INTERVAL if ping_interval > 0: context["ping_interval"] = ping_interval top_links = settings.TOP_LINKS links = [] for tl in top_links: if len(tl) < 2: continue link = {} link["label"] = tl[0] link_id = tl[1] try: # test if complex dictionary view with args and query_string link["link"] = reverse_with_params(**link_id) except TypeError: # assume is only view name try: link["link"] = reverse(link_id) except NoReverseMatch: # assume we've been passed a url link["link"] = link_id # simply add optional attrs dict if len(tl) > 2: link["attrs"] = tl[2] links.append(link) context["ome"]["top_links"] = links if settings.TOP_LOGO: context["ome"]["logo_src"] = settings.TOP_LOGO if settings.TOP_LOGO_LINK: context["ome"]["logo_href"] = settings.TOP_LOGO_LINK metadata_panes = settings.METADATA_PANES context["ome"]["metadata_panes"] = metadata_panes right_plugins = settings.RIGHT_PLUGINS r_plugins = [] for rt in right_plugins: label = rt[0] include = rt[1] plugin_id = rt[2] r_plugins.append( {"label": label, "include": include, "plugin_id": plugin_id} ) context["ome"]["right_plugins"] = r_plugins center_plugins = settings.CENTER_PLUGINS c_plugins = [] for cp in center_plugins: label = cp[0] include = cp[1] plugin_id = cp[2] c_plugins.append( {"label": label, "include": include, "plugin_id": plugin_id} ) context["ome"]["center_plugins"] = c_plugins context["ome"]["user_dropdown"] = settings.USER_DROPDOWN
open_redirect
{ "code": [ "from omeroweb.webgateway.marshal import eventContextMarshal", " context[\"ome\"][\"eventContext\"] = eventContextMarshal(conn.getEventContext())" ], "line_no": [ 38, 137 ] }
{ "code": [], "line_no": [] }
import logging import omeroweb.decorators from omero import constants from django.http import HttpResponse from django.conf import settings from django.core.urlresolvers import reverse from django.core.urlresolvers import NoReverseMatch from omeroweb.webclient.forms import GlobalSearchForm from omeroweb.utils import reverse_with_params from omeroweb.webgateway.marshal import eventContextMarshal VAR_0 = logging.getLogger(__name__) class CLASS_0(omeroweb.decorators.login_required): def __init__( self, VAR_1=False, VAR_2=False, VAR_3=None, **VAR_4 ): super(CLASS_0, self).__init__(**VAR_4) self.ignore_login_fail = VAR_1 self.setGroupContext = VAR_2 self.login_redirect = VAR_3 def FUNC_0(self, VAR_5, VAR_6): super(CLASS_0, self).on_logged_in(VAR_5, VAR_6) self.prepare_session(VAR_5) if self.setGroupContext: if VAR_5.session.get("active_group"): VAR_6.SERVICE_OPTS.setOmeroGroup(VAR_5.session.get("active_group")) else: VAR_6.SERVICE_OPTS.setOmeroGroup(VAR_6.getEventContext().groupId) def FUNC_1(self, VAR_5, VAR_7, VAR_8=None): if self.ignore_login_fail: return HttpResponse("Connection Failed") if self.login_redirect is not None: try: VAR_7 = reverse(self.login_redirect) except Exception: pass return super(CLASS_0, self).on_not_logged_in(VAR_5, VAR_7, VAR_8) def FUNC_2(self, VAR_5): VAR_11 = False if VAR_5.session.get("callback") is None: VAR_5.session["callback"] = dict() VAR_11 = True if VAR_5.session.get("shares") is None: VAR_5.session["shares"] = dict() VAR_11 = True if VAR_11: VAR_5.session.modified = True class CLASS_1(omeroweb.decorators.render_response): def FUNC_3(self, VAR_5, VAR_9, *VAR_10, **VAR_4): if "conn" not in VAR_4: return VAR_6 = VAR_4["conn"] VAR_9["omero"] = { "constants": { "NSCOMPANIONFILE": constants.namespaces.NSCOMPANIONFILE, "ORIGINALMETADATA": constants.annotation.file.ORIGINALMETADATA, "NSCLIENTMAPANNOTATION": constants.metadata.NSCLIENTMAPANNOTATION, } } VAR_9.setdefault("ome", {}) # don't overwrite existing ome VAR_12 = omeroweb.decorators.is_public_user(VAR_5) if VAR_12 is not None: VAR_9["ome"]["is_public_user"] = VAR_12 VAR_9["ome"]["eventContext"] = eventContextMarshal(VAR_6.getEventContext()) VAR_9["ome"]["user"] = VAR_6.getUser VAR_9["ome"]["user_id"] = VAR_5.session.get("user_id", VAR_6.getUserId()) VAR_9["ome"]["group_id"] = VAR_5.session.get("group_id", None) VAR_9["ome"]["active_group"] = VAR_5.session.get( "active_group", VAR_6.getEventContext().groupId ) VAR_9["global_search_form"] = GlobalSearchForm() VAR_9["ome"]["can_create"] = VAR_5.session.get("can_create", True) if VAR_5.session.get("server_settings"): VAR_9["ome"]["email"] = VAR_5.session.get("server_settings").get( "email", False ) if VAR_5.session.get("server_settings").get("ui"): VAR_9.setdefault("ui", {"tree": {}}) VAR_9["ui"]["orphans"] = ( VAR_5.session.get("server_settings") .get("ui", {}) .get("tree", {}) .get("orphans") ) VAR_9["ui"]["dropdown_menu"] = ( VAR_5.session.get("server_settings") .get("ui", {}) .get("menu", {}) .get("dropdown") ) VAR_9["ui"]["tree"]["type_order"] = ( VAR_5.session.get("server_settings") .get("ui", {}) .get("tree", {}) .get("type_order") ) self.load_settings(VAR_5, VAR_9, VAR_6) def FUNC_4(self, VAR_5, VAR_9, VAR_6): VAR_13 = settings.PING_INTERVAL if VAR_13 > 0: VAR_9["ping_interval"] = VAR_13 VAR_14 = settings.TOP_LINKS VAR_15 = [] for tl in VAR_14: if len(tl) < 2: continue VAR_21 = {} link["label"] = tl[0] VAR_22 = tl[1] try: VAR_21["link"] = reverse_with_params(**VAR_22) except TypeError: try: VAR_21["link"] = reverse(VAR_22) except NoReverseMatch: VAR_21["link"] = VAR_22 if len(tl) > 2: VAR_21["attrs"] = tl[2] VAR_15.append(VAR_21) VAR_9["ome"]["top_links"] = VAR_15 if settings.TOP_LOGO: VAR_9["ome"]["logo_src"] = settings.TOP_LOGO if settings.TOP_LOGO_LINK: VAR_9["ome"]["logo_href"] = settings.TOP_LOGO_LINK VAR_16 = settings.METADATA_PANES VAR_9["ome"]["metadata_panes"] = VAR_16 VAR_17 = settings.RIGHT_PLUGINS VAR_18 = [] for rt in VAR_17: VAR_23 = rt[0] VAR_24 = rt[1] VAR_25 = rt[2] VAR_18.append( {"label": VAR_23, "include": VAR_24, "plugin_id": VAR_25} ) VAR_9["ome"]["right_plugins"] = VAR_18 VAR_19 = settings.CENTER_PLUGINS VAR_20 = [] for cp in VAR_19: VAR_23 = cp[0] VAR_24 = cp[1] VAR_25 = cp[2] VAR_20.append( {"label": VAR_23, "include": VAR_24, "plugin_id": VAR_25} ) VAR_9["ome"]["center_plugins"] = VAR_20 VAR_9["ome"]["user_dropdown"] = settings.USER_DROPDOWN
import logging import omeroweb.decorators from omero import constants from django.http import HttpResponse from django.conf import settings from django.core.urlresolvers import reverse from django.core.urlresolvers import NoReverseMatch from omeroweb.webclient.forms import GlobalSearchForm from omeroweb.utils import reverse_with_params VAR_0 = logging.getLogger(__name__) class CLASS_0(omeroweb.decorators.login_required): def __init__( self, VAR_1=False, VAR_2=False, VAR_3=None, **VAR_4 ): super(CLASS_0, self).__init__(**VAR_4) self.ignore_login_fail = VAR_1 self.setGroupContext = VAR_2 self.login_redirect = VAR_3 def FUNC_0(self, VAR_5, VAR_6): super(CLASS_0, self).on_logged_in(VAR_5, VAR_6) self.prepare_session(VAR_5) if self.setGroupContext: if VAR_5.session.get("active_group"): VAR_6.SERVICE_OPTS.setOmeroGroup(VAR_5.session.get("active_group")) else: VAR_6.SERVICE_OPTS.setOmeroGroup(VAR_6.getEventContext().groupId) def FUNC_1(self, VAR_5, VAR_7, VAR_8=None): if self.ignore_login_fail: return HttpResponse("Connection Failed") if self.login_redirect is not None: try: VAR_7 = reverse(self.login_redirect) except Exception: pass return super(CLASS_0, self).on_not_logged_in(VAR_5, VAR_7, VAR_8) def FUNC_2(self, VAR_5): VAR_11 = False if VAR_5.session.get("callback") is None: VAR_5.session["callback"] = dict() VAR_11 = True if VAR_5.session.get("shares") is None: VAR_5.session["shares"] = dict() VAR_11 = True if VAR_11: VAR_5.session.modified = True class CLASS_1(omeroweb.decorators.render_response): def FUNC_3(self, VAR_5, VAR_9, *VAR_10, **VAR_4): super(CLASS_1, self).prepare_context(VAR_5, VAR_9, *VAR_10, **VAR_4) if "conn" not in VAR_4: return VAR_6 = VAR_4["conn"] VAR_9["omero"] = { "constants": { "NSCOMPANIONFILE": constants.namespaces.NSCOMPANIONFILE, "ORIGINALMETADATA": constants.annotation.file.ORIGINALMETADATA, "NSCLIENTMAPANNOTATION": constants.metadata.NSCLIENTMAPANNOTATION, } } VAR_9.setdefault("ome", {}) # don't overwrite existing ome VAR_12 = omeroweb.decorators.is_public_user(VAR_5) if VAR_12 is not None: VAR_9["ome"]["is_public_user"] = VAR_12 VAR_9["ome"]["user"] = VAR_6.getUser VAR_9["ome"]["user_id"] = VAR_5.session.get("user_id", VAR_6.getUserId()) VAR_9["ome"]["group_id"] = VAR_5.session.get("group_id", None) VAR_9["ome"]["active_group"] = VAR_5.session.get( "active_group", VAR_6.getEventContext().groupId ) VAR_9["global_search_form"] = GlobalSearchForm() VAR_9["ome"]["can_create"] = VAR_5.session.get("can_create", True) if VAR_5.session.get("server_settings"): VAR_9["ome"]["email"] = VAR_5.session.get("server_settings").get( "email", False ) if VAR_5.session.get("server_settings").get("ui"): VAR_9.setdefault("ui", {"tree": {}}) VAR_9["ui"]["orphans"] = ( VAR_5.session.get("server_settings") .get("ui", {}) .get("tree", {}) .get("orphans") ) VAR_9["ui"]["dropdown_menu"] = ( VAR_5.session.get("server_settings") .get("ui", {}) .get("menu", {}) .get("dropdown") ) VAR_9["ui"]["tree"]["type_order"] = ( VAR_5.session.get("server_settings") .get("ui", {}) .get("tree", {}) .get("type_order") ) self.load_settings(VAR_5, VAR_9, VAR_6) def FUNC_4(self, VAR_5, VAR_9, VAR_6): VAR_13 = settings.PING_INTERVAL if VAR_13 > 0: VAR_9["ping_interval"] = VAR_13 VAR_14 = settings.TOP_LINKS VAR_15 = [] for tl in VAR_14: if len(tl) < 2: continue VAR_21 = {} link["label"] = tl[0] VAR_22 = tl[1] try: VAR_21["link"] = reverse_with_params(**VAR_22) except TypeError: try: VAR_21["link"] = reverse(VAR_22) except NoReverseMatch: VAR_21["link"] = VAR_22 if len(tl) > 2: VAR_21["attrs"] = tl[2] VAR_15.append(VAR_21) VAR_9["ome"]["top_links"] = VAR_15 if settings.TOP_LOGO: VAR_9["ome"]["logo_src"] = settings.TOP_LOGO if settings.TOP_LOGO_LINK: VAR_9["ome"]["logo_href"] = settings.TOP_LOGO_LINK VAR_16 = settings.METADATA_PANES VAR_9["ome"]["metadata_panes"] = VAR_16 VAR_17 = settings.RIGHT_PLUGINS VAR_18 = [] for rt in VAR_17: VAR_23 = rt[0] VAR_24 = rt[1] VAR_25 = rt[2] VAR_18.append( {"label": VAR_23, "include": VAR_24, "plugin_id": VAR_25} ) VAR_9["ome"]["right_plugins"] = VAR_18 VAR_19 = settings.CENTER_PLUGINS VAR_20 = [] for cp in VAR_19: VAR_23 = cp[0] VAR_24 = cp[1] VAR_25 = cp[2] VAR_20.append( {"label": VAR_23, "include": VAR_24, "plugin_id": VAR_25} ) VAR_9["ome"]["center_plugins"] = VAR_20 VAR_9["ome"]["user_dropdown"] = settings.USER_DROPDOWN
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 25, 27, 30, 35, 39, 41, 42, 47, 62, 72, 86, 98, 99, 105, 118, 119, 123, 124, 132, 146, 152, 172, 174, 176, 177, 181, 191, 194, 198, 200, 205, 210, 213, 224, 235, 237, 22, 23, 24, 44, 45, 46, 101, 102, 103, 104, 55, 56, 57, 64, 74, 75, 76, 77, 88, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 25, 27, 30, 35, 38, 40, 41, 46, 61, 71, 85, 97, 98, 104, 117, 119, 120, 124, 125, 133, 146, 152, 172, 174, 176, 177, 181, 191, 194, 198, 200, 205, 210, 213, 224, 235, 237, 22, 23, 24, 43, 44, 45, 100, 101, 102, 103, 54, 55, 56, 63, 73, 74, 75, 76, 87, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116 ]
5CWE-94
import re import stringcase def _sanitize(value: str) -> str: return re.sub(r"[^\w _-]+", "", value) def group_title(value: str) -> str: value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip()) value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2).lower(), value) return value def snake_case(value: str) -> str: return stringcase.snakecase(group_title(_sanitize(value))) def pascal_case(value: str) -> str: return stringcase.pascalcase(_sanitize(value)) def kebab_case(value: str) -> str: return stringcase.spinalcase(group_title(_sanitize(value)))
import re from keyword import iskeyword import stringcase def sanitize(value: str) -> str: return re.sub(r"[^\w _\-]+", "", value) def fix_keywords(value: str) -> str: if iskeyword(value): return f"{value}_" return value def group_title(value: str) -> str: value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ \-_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip()) value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2).lower(), value) return value def snake_case(value: str) -> str: return fix_keywords(stringcase.snakecase(group_title(sanitize(value)))) def pascal_case(value: str) -> str: return fix_keywords(stringcase.pascalcase(sanitize(value))) def kebab_case(value: str) -> str: return fix_keywords(stringcase.spinalcase(group_title(sanitize(value)))) def remove_string_escapes(value: str) -> str: return value.replace('"', r"\"")
remote_code_execution
{ "code": [ "def _sanitize(value: str) -> str:", " return re.sub(r\"[^\\w _-]+\", \"\", value)", " value = re.sub(r\"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)\", lambda m: m.group(1).title() + m.group(2), value.strip())", " return stringcase.snakecase(group_title(_sanitize(value)))", " return stringcase.pascalcase(_sanitize(value))", " return stringcase.spinalcase(group_title(_sanitize(value)))" ], "line_no": [ 6, 7, 11, 17, 21, 25 ] }
{ "code": [ "def sanitize(value: str) -> str:", "def fix_keywords(value: str) -> str:", " if iskeyword(value):", " return f\"{value}_\"", " value = re.sub(r\"([A-Z]{2,})([A-Z][a-z]|[ \\-_]|$)\", lambda m: m.group(1).title() + m.group(2), value.strip())", " return fix_keywords(stringcase.snakecase(group_title(sanitize(value))))", " return fix_keywords(stringcase.pascalcase(sanitize(value)))", " return fix_keywords(stringcase.spinalcase(group_title(sanitize(value))))", "def remove_string_escapes(value: str) -> str:", " return value.replace('\"', r\"\\\"\")" ], "line_no": [ 7, 11, 12, 13, 18, 24, 28, 32, 35, 36 ] }
import re import stringcase def FUNC_0(VAR_0: str) -> str: return re.sub(r"[^\w _-]+", "", VAR_0) def FUNC_1(VAR_0: str) -> str: VAR_0 = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), VAR_0.strip()) VAR_0 = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2).lower(), VAR_0) return VAR_0 def FUNC_2(VAR_0: str) -> str: return stringcase.snakecase(FUNC_1(FUNC_0(VAR_0))) def FUNC_3(VAR_0: str) -> str: return stringcase.pascalcase(FUNC_0(VAR_0)) def FUNC_4(VAR_0: str) -> str: return stringcase.spinalcase(FUNC_1(FUNC_0(VAR_0)))
import re from keyword import iskeyword import stringcase def FUNC_0(VAR_0: str) -> str: return re.sub(r"[^\w _\-]+", "", VAR_0) def FUNC_1(VAR_0: str) -> str: if iskeyword(VAR_0): return f"{VAR_0}_" return VAR_0 def FUNC_2(VAR_0: str) -> str: VAR_0 = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ \-_]|$)", lambda m: m.group(1).title() + m.group(2), VAR_0.strip()) VAR_0 = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2).lower(), VAR_0) return VAR_0 def FUNC_3(VAR_0: str) -> str: return FUNC_1(stringcase.snakecase(FUNC_2(FUNC_0(VAR_0)))) def FUNC_4(VAR_0: str) -> str: return FUNC_1(stringcase.pascalcase(FUNC_0(VAR_0))) def FUNC_5(VAR_0: str) -> str: return FUNC_1(stringcase.spinalcase(FUNC_2(FUNC_0(VAR_0)))) def FUNC_6(VAR_0: str) -> str: return VAR_0.replace('"', r"\"")
[ 2, 4, 5, 8, 9, 14, 15, 18, 19, 22, 23, 26 ]
[ 3, 5, 6, 9, 10, 15, 16, 21, 22, 25, 26, 29, 30, 33, 34, 37 ]
1CWE-79
# ############################################################################## # Author: echel0n <echel0n@sickrage.ca> # URL: https://sickrage.ca/ # Git: https://git.sickrage.ca/SiCKRAGE/sickrage.git # - # This file is part of SiCKRAGE. # - # SiCKRAGE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # - # SiCKRAGE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # - # You should have received a copy of the GNU General Public License # along with SiCKRAGE. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import functools import time import traceback import types from concurrent.futures.thread import ThreadPoolExecutor from typing import Optional, Awaitable from urllib.parse import urlparse, urljoin from jose import ExpiredSignatureError from keycloak.exceptions import KeycloakClientError from mako.exceptions import RichTraceback from tornado import locale from tornado.web import RequestHandler import sickrage from sickrage.core.helpers import is_ip_whitelisted, torrent_webui_url class BaseHandler(RequestHandler): def __init__(self, application, request, **kwargs): super(BaseHandler, self).__init__(application, request, **kwargs) self.executor = ThreadPoolExecutor(thread_name_prefix='TORNADO-Thread') self.startTime = time.time() def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]: pass def get_user_locale(self): return locale.get(sickrage.app.config.gui.gui_lang) def write_error(self, status_code, **kwargs): if status_code not in [401, 404] and "exc_info" in kwargs: exc_info = kwargs["exc_info"] error = repr(exc_info[1]) sickrage.app.log.error(error) if self.settings.get("debug"): trace_info = ''.join([f"{line}<br>" for line in traceback.format_exception(*exc_info)]) request_info = ''.join([f"<strong>{k}</strong>: {v}<br>" for k, v in self.request.__dict__.items()]) self.set_header('Content-Type', 'text/html') return self.write(f"""<html> <title>{error}</title> <body> <button onclick="window.location='{sickrage.app.config.general.web_root}/logs/';">View Log(Errors)</button> <button onclick="window.location='{sickrage.app.config.general.web_root}/home/restart?pid={sickrage.app.pid}&force=1';">Restart SiCKRAGE</button> <button onclick="window.location='{sickrage.app.config.general.web_root}/logout';">Logout</button> <h2>Error</h2> <p>{error}</p> <h2>Traceback</h2> <p>{trace_info}</p> <h2>Request Info</h2> <p>{request_info}</p> </body> </html>""") def get_current_user(self): if is_ip_whitelisted(self.request.remote_ip): return True elif sickrage.app.config.general.sso_auth_enabled and sickrage.app.auth_server.health: try: access_token = self.get_secure_cookie('_sr_access_token') refresh_token = self.get_secure_cookie('_sr_refresh_token') if not all([access_token, refresh_token]): return certs = sickrage.app.auth_server.certs() if not certs: return try: return sickrage.app.auth_server.decode_token(access_token.decode("utf-8"), certs) except (KeycloakClientError, ExpiredSignatureError): token = sickrage.app.auth_server.refresh_token(refresh_token.decode("utf-8")) if not token: return self.set_secure_cookie('_sr_access_token', token['access_token']) self.set_secure_cookie('_sr_refresh_token', token['refresh_token']) return sickrage.app.auth_server.decode_token(token['access_token'], certs) except Exception as e: return elif sickrage.app.config.general.local_auth_enabled: cookie = self.get_secure_cookie('_sr').decode() if self.get_secure_cookie('_sr') else None if cookie == sickrage.app.config.general.api_v1_key: return True def render_string(self, template_name, **kwargs): template_kwargs = { 'title': "", 'header': "", 'topmenu': "", 'submenu': "", 'controller': "home", 'action': "index", 'srPID': sickrage.app.pid, 'srHttpsEnabled': sickrage.app.config.general.enable_https or bool(self.request.headers.get('X-Forwarded-Proto') == 'https'), 'srHost': self.request.headers.get('X-Forwarded-Host', self.request.host.split(':')[0]), 'srHttpPort': self.request.headers.get('X-Forwarded-Port', sickrage.app.config.general.web_port), 'srHttpsPort': sickrage.app.config.general.web_port, 'srHandleReverseProxy': sickrage.app.config.general.handle_reverse_proxy, 'srDefaultPage': sickrage.app.config.general.default_page.value, 'srWebRoot': sickrage.app.config.general.web_root, 'srLocale': self.get_user_locale().code, 'srLocaleDir': sickrage.LOCALE_DIR, 'srStartTime': self.startTime, 'makoStartTime': time.time(), 'overall_stats': None, 'torrent_webui_url': torrent_webui_url(), 'application': self.application, 'request': self.request, } template_kwargs.update(self.get_template_namespace()) template_kwargs.update(kwargs) try: return self.application.settings['templates'][template_name].render_unicode(**template_kwargs) except Exception: kwargs['title'] = _('HTTP Error 500') kwargs['header'] = _('HTTP Error 500') kwargs['backtrace'] = RichTraceback() template_kwargs.update(kwargs) sickrage.app.log.error("%s: %s" % (str(kwargs['backtrace'].error.__class__.__name__), kwargs['backtrace'].error)) return self.application.settings['templates']['errors/500.mako'].render_unicode(**template_kwargs) def render(self, template_name, **kwargs): self.write(self.render_string(template_name, **kwargs)) def set_default_headers(self): self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With") self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE, OPTIONS') self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') def redirect(self, url, permanent=True, status=None): if sickrage.app.config.general.web_root not in url: url = urljoin(sickrage.app.config.general.web_root + '/', url.lstrip('/')) super(BaseHandler, self).redirect(url, permanent, status) def previous_url(self): url = urlparse(self.request.headers.get("referer", "/{}/".format(sickrage.app.config.general.default_page.value))) return url._replace(scheme="", netloc="").geturl() def _genericMessage(self, subject, message): return self.render('generic_message.mako', message=message, subject=subject, title="", controller='root', action='genericmessage') def get_url(self, url): if sickrage.app.config.general.web_root not in url: url = urljoin(sickrage.app.config.general.web_root + '/', url.lstrip('/')) url = urljoin("{}://{}".format(self.request.protocol, self.request.host), url) return url def run_async(self, method): @functools.wraps(method) async def wrapper(self, *args, **kwargs): await sickrage.app.wserver.io_loop.run_in_executor(self.executor, functools.partial(method, *args, **kwargs)) return types.MethodType(wrapper, self) def prepare(self): method_name = self.request.method.lower() method = self.run_async(getattr(self, method_name)) setattr(self, method_name, method) def options(self, *args, **kwargs): self.set_status(204) self.finish()
# ############################################################################## # Author: echel0n <echel0n@sickrage.ca> # URL: https://sickrage.ca/ # Git: https://git.sickrage.ca/SiCKRAGE/sickrage.git # - # This file is part of SiCKRAGE. # - # SiCKRAGE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # - # SiCKRAGE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # - # You should have received a copy of the GNU General Public License # along with SiCKRAGE. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import functools import html import time import traceback import types from concurrent.futures.thread import ThreadPoolExecutor from typing import Optional, Awaitable from urllib.parse import urlparse, urljoin import bleach from jose import ExpiredSignatureError from keycloak.exceptions import KeycloakClientError from mako.exceptions import RichTraceback from tornado import locale, escape from tornado.web import RequestHandler import sickrage from sickrage.core.helpers import is_ip_whitelisted, torrent_webui_url class BaseHandler(RequestHandler): def __init__(self, application, request, **kwargs): super(BaseHandler, self).__init__(application, request, **kwargs) self.executor = ThreadPoolExecutor(thread_name_prefix='TORNADO-Thread') self.startTime = time.time() def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]: pass def get_user_locale(self): return locale.get(sickrage.app.config.gui.gui_lang) def write_error(self, status_code, **kwargs): if status_code not in [401, 404] and "exc_info" in kwargs: exc_info = kwargs["exc_info"] error = repr(exc_info[1]) sickrage.app.log.error(error) if self.settings.get("debug"): trace_info = ''.join([f"{line}<br>" for line in traceback.format_exception(*exc_info)]) request_info = ''.join([f"<strong>{k}</strong>: {v}<br>" for k, v in self.request.__dict__.items()]) self.set_header('Content-Type', 'text/html') return self.write(f"""<html> <title>{error}</title> <body> <button onclick="window.location='{sickrage.app.config.general.web_root}/logs/';">View Log(Errors)</button> <button onclick="window.location='{sickrage.app.config.general.web_root}/home/restart?pid={sickrage.app.pid}&force=1';">Restart SiCKRAGE</button> <button onclick="window.location='{sickrage.app.config.general.web_root}/logout';">Logout</button> <h2>Error</h2> <p>{error}</p> <h2>Traceback</h2> <p>{trace_info}</p> <h2>Request Info</h2> <p>{request_info}</p> </body> </html>""") def get_current_user(self): if is_ip_whitelisted(self.request.remote_ip): return True elif sickrage.app.config.general.sso_auth_enabled and sickrage.app.auth_server.health: try: access_token = self.get_secure_cookie('_sr_access_token') refresh_token = self.get_secure_cookie('_sr_refresh_token') if not all([access_token, refresh_token]): return certs = sickrage.app.auth_server.certs() if not certs: return try: return sickrage.app.auth_server.decode_token(access_token.decode("utf-8"), certs) except (KeycloakClientError, ExpiredSignatureError): token = sickrage.app.auth_server.refresh_token(refresh_token.decode("utf-8")) if not token: return self.set_secure_cookie('_sr_access_token', token['access_token']) self.set_secure_cookie('_sr_refresh_token', token['refresh_token']) return sickrage.app.auth_server.decode_token(token['access_token'], certs) except Exception as e: return elif sickrage.app.config.general.local_auth_enabled: cookie = self.get_secure_cookie('_sr').decode() if self.get_secure_cookie('_sr') else None if cookie == sickrage.app.config.general.api_v1_key: return True def render_string(self, template_name, **kwargs): template_kwargs = { 'title': "", 'header': "", 'topmenu': "", 'submenu': "", 'controller': "home", 'action': "index", 'srPID': sickrage.app.pid, 'srHttpsEnabled': sickrage.app.config.general.enable_https or bool(self.request.headers.get('X-Forwarded-Proto') == 'https'), 'srHost': self.request.headers.get('X-Forwarded-Host', self.request.host.split(':')[0]), 'srHttpPort': self.request.headers.get('X-Forwarded-Port', sickrage.app.config.general.web_port), 'srHttpsPort': sickrage.app.config.general.web_port, 'srHandleReverseProxy': sickrage.app.config.general.handle_reverse_proxy, 'srDefaultPage': sickrage.app.config.general.default_page.value, 'srWebRoot': sickrage.app.config.general.web_root, 'srLocale': self.get_user_locale().code, 'srLocaleDir': sickrage.LOCALE_DIR, 'srStartTime': self.startTime, 'makoStartTime': time.time(), 'overall_stats': None, 'torrent_webui_url': torrent_webui_url(), 'application': self.application, 'request': self.request, } template_kwargs.update(self.get_template_namespace()) template_kwargs.update(kwargs) try: return self.application.settings['templates'][template_name].render_unicode(**template_kwargs) except Exception: kwargs['title'] = _('HTTP Error 500') kwargs['header'] = _('HTTP Error 500') kwargs['backtrace'] = RichTraceback() template_kwargs.update(kwargs) sickrage.app.log.error("%s: %s" % (str(kwargs['backtrace'].error.__class__.__name__), kwargs['backtrace'].error)) return self.application.settings['templates']['errors/500.mako'].render_unicode(**template_kwargs) def render(self, template_name, **kwargs): self.write(self.render_string(template_name, **kwargs)) def set_default_headers(self): self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With") self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE, OPTIONS') self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') def redirect(self, url, permanent=True, status=None): if sickrage.app.config.general.web_root not in url: url = urljoin(sickrage.app.config.general.web_root + '/', url.lstrip('/')) super(BaseHandler, self).redirect(url, permanent, status) def previous_url(self): url = urlparse(self.request.headers.get("referer", "/{}/".format(sickrage.app.config.general.default_page.value))) return url._replace(scheme="", netloc="").geturl() def _genericMessage(self, subject, message): return self.render('generic_message.mako', message=message, subject=subject, title="", controller='root', action='genericmessage') def get_url(self, url): if sickrage.app.config.general.web_root not in url: url = urljoin(sickrage.app.config.general.web_root + '/', url.lstrip('/')) url = urljoin("{}://{}".format(self.request.protocol, self.request.host), url) return url def run_async(self, method): @functools.wraps(method) async def wrapper(self, *args, **kwargs): await sickrage.app.wserver.io_loop.run_in_executor(self.executor, functools.partial(method, *args, **kwargs)) return types.MethodType(wrapper, self) def prepare(self): method_name = self.request.method.lower() method = self.run_async(getattr(self, method_name)) setattr(self, method_name, method) def options(self, *args, **kwargs): self.set_status(204) self.finish() def get_argument(self, *args, **kwargs): value = super(BaseHandler, self).get_argument(*args, **kwargs) try: return bleach.clean(value) except TypeError: return value
xss
{ "code": [ "from tornado import locale" ], "line_no": [ 32 ] }
{ "code": [ "import html", "import bleach", " def get_argument(self, *args, **kwargs):", " value = super(BaseHandler, self).get_argument(*args, **kwargs)", " try:", " return bleach.clean(value)", " except TypeError:", " return value" ], "line_no": [ 22, 30, 202, 203, 205, 206, 207, 208 ] }
import functools import time import traceback import types from concurrent.futures.thread import ThreadPoolExecutor from typing import Optional, Awaitable from urllib.parse import .urlparse, urljoin from jose import ExpiredSignatureError from keycloak.exceptions import KeycloakClientError from mako.exceptions import RichTraceback from tornado import locale from tornado.web import RequestHandler import sickrage from sickrage.core.helpers import is_ip_whitelisted, torrent_webui_url class CLASS_0(RequestHandler): def __init__(self, VAR_0, VAR_1, **VAR_2): super(CLASS_0, self).__init__(VAR_0, VAR_1, **VAR_2) self.executor = ThreadPoolExecutor(thread_name_prefix='TORNADO-Thread') self.startTime = time.time() def FUNC_0(self, VAR_3: bytes) -> Optional[Awaitable[None]]: pass def FUNC_1(self): return locale.get(sickrage.app.config.gui.gui_lang) def FUNC_2(self, VAR_4, **VAR_2): if VAR_4 not in [401, 404] and "exc_info" in VAR_2: VAR_15 = VAR_2["exc_info"] VAR_16 = repr(VAR_15[1]) sickrage.app.log.error(VAR_16) if self.settings.get("debug"): VAR_17 = ''.join([f"{line}<br>" for line in traceback.format_exception(*VAR_15)]) VAR_18 = ''.join([f"<strong>{k}</strong>: {v}<br>" for k, v in self.request.__dict__.items()]) self.set_header('Content-Type', 'text/html') return self.write(f"""<html> <title>{VAR_16}</title> <body> <button onclick="window.location='{sickrage.app.config.general.web_root}/logs/';">View Log(Errors)</button> <button onclick="window.location='{sickrage.app.config.general.web_root}/home/restart?pid={sickrage.app.pid}&force=1';">Restart SiCKRAGE</button> <button onclick="window.location='{sickrage.app.config.general.web_root}/logout';">Logout</button> <h2>Error</h2> <p>{VAR_16}</p> <h2>Traceback</h2> <p>{VAR_17}</p> <h2>Request Info</h2> <p>{VAR_18}</p> </body> </html>""") def FUNC_3(self): if is_ip_whitelisted(self.request.remote_ip): return True elif sickrage.app.config.general.sso_auth_enabled and sickrage.app.auth_server.health: try: VAR_19 = self.get_secure_cookie('_sr_access_token') VAR_20 = self.get_secure_cookie('_sr_refresh_token') if not all([VAR_19, VAR_20]): return VAR_21 = sickrage.app.auth_server.certs() if not VAR_21: return try: return sickrage.app.auth_server.decode_token(VAR_19.decode("utf-8"), VAR_21) except (KeycloakClientError, ExpiredSignatureError): VAR_23 = sickrage.app.auth_server.refresh_token(VAR_20.decode("utf-8")) if not VAR_23: return self.set_secure_cookie('_sr_access_token', VAR_23['access_token']) self.set_secure_cookie('_sr_refresh_token', VAR_23['refresh_token']) return sickrage.app.auth_server.decode_token(VAR_23['access_token'], VAR_21) except Exception as e: return elif sickrage.app.config.general.local_auth_enabled: VAR_22 = self.get_secure_cookie('_sr').decode() if self.get_secure_cookie('_sr') else None if VAR_22 == sickrage.app.config.general.api_v1_key: return True def FUNC_4(self, VAR_5, **VAR_2): VAR_13 = { 'title': "", 'header': "", 'topmenu': "", 'submenu': "", 'controller': "home", 'action': "index", 'srPID': sickrage.app.pid, 'srHttpsEnabled': sickrage.app.config.general.enable_https or bool(self.request.headers.get('X-Forwarded-Proto') == 'https'), 'srHost': self.request.headers.get('X-Forwarded-Host', self.request.host.split(':')[0]), 'srHttpPort': self.request.headers.get('X-Forwarded-Port', sickrage.app.config.general.web_port), 'srHttpsPort': sickrage.app.config.general.web_port, 'srHandleReverseProxy': sickrage.app.config.general.handle_reverse_proxy, 'srDefaultPage': sickrage.app.config.general.default_page.value, 'srWebRoot': sickrage.app.config.general.web_root, 'srLocale': self.get_user_locale().code, 'srLocaleDir': sickrage.LOCALE_DIR, 'srStartTime': self.startTime, 'makoStartTime': time.time(), 'overall_stats': None, 'torrent_webui_url': torrent_webui_url(), 'application': self.application, 'request': self.request, } VAR_13.update(self.get_template_namespace()) VAR_13.update(VAR_2) try: return self.application.settings['templates'][VAR_5].render_unicode(**VAR_13) except Exception: VAR_2['title'] = _('HTTP Error 500') VAR_2['header'] = _('HTTP Error 500') VAR_2['backtrace'] = RichTraceback() VAR_13.update(VAR_2) sickrage.app.log.error("%s: %s" % (str(VAR_2['backtrace'].error.__class__.__name__), VAR_2['backtrace'].error)) return self.application.settings['templates']['errors/500.mako'].render_unicode(**VAR_13) def FUNC_5(self, VAR_5, **VAR_2): self.write(self.render_string(VAR_5, **VAR_2)) def FUNC_6(self): self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With") self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE, OPTIONS') self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') def FUNC_7(self, VAR_6, VAR_7=True, VAR_8=None): if sickrage.app.config.general.web_root not in VAR_6: url = urljoin(sickrage.app.config.general.web_root + '/', VAR_6.lstrip('/')) super(CLASS_0, self).redirect(VAR_6, VAR_7, VAR_8) def FUNC_8(self): VAR_6 = urlparse(self.request.headers.get("referer", "/{}/".format(sickrage.app.config.general.default_page.value))) return VAR_6._replace(scheme="", netloc="").geturl() def FUNC_9(self, VAR_9, VAR_10): return self.render('generic_message.mako', VAR_10=message, VAR_9=subject, title="", controller='root', action='genericmessage') def FUNC_10(self, VAR_6): if sickrage.app.config.general.web_root not in VAR_6: url = urljoin(sickrage.app.config.general.web_root + '/', VAR_6.lstrip('/')) VAR_6 = urljoin("{}://{}".format(self.request.protocol, self.request.host), VAR_6) return VAR_6 def FUNC_11(self, VAR_11): @functools.wraps(VAR_11) async def FUNC_14(self, *VAR_12, **VAR_2): await sickrage.app.wserver.io_loop.run_in_executor(self.executor, functools.partial(VAR_11, *VAR_12, **VAR_2)) return types.MethodType(FUNC_14, self) def FUNC_12(self): VAR_14 = self.request.method.lower() VAR_11 = self.run_async(getattr(self, VAR_14)) setattr(self, VAR_14, VAR_11) def FUNC_13(self, *VAR_12, **VAR_2): self.set_status(204) self.finish()
import functools import html import time import traceback import types from concurrent.futures.thread import ThreadPoolExecutor from typing import Optional, Awaitable from urllib.parse import .urlparse, urljoin import bleach from jose import ExpiredSignatureError from keycloak.exceptions import KeycloakClientError from mako.exceptions import RichTraceback from tornado import locale, escape from tornado.web import RequestHandler import sickrage from sickrage.core.helpers import is_ip_whitelisted, torrent_webui_url class CLASS_0(RequestHandler): def __init__(self, VAR_0, VAR_1, **VAR_2): super(CLASS_0, self).__init__(VAR_0, VAR_1, **VAR_2) self.executor = ThreadPoolExecutor(thread_name_prefix='TORNADO-Thread') self.startTime = time.time() def FUNC_0(self, VAR_3: bytes) -> Optional[Awaitable[None]]: pass def FUNC_1(self): return locale.get(sickrage.app.config.gui.gui_lang) def FUNC_2(self, VAR_4, **VAR_2): if VAR_4 not in [401, 404] and "exc_info" in VAR_2: VAR_16 = VAR_2["exc_info"] VAR_17 = repr(VAR_16[1]) sickrage.app.log.error(VAR_17) if self.settings.get("debug"): VAR_18 = ''.join([f"{line}<br>" for line in traceback.format_exception(*VAR_16)]) VAR_19 = ''.join([f"<strong>{k}</strong>: {v}<br>" for k, v in self.request.__dict__.items()]) self.set_header('Content-Type', 'text/html') return self.write(f"""<html> <title>{VAR_17}</title> <body> <button onclick="window.location='{sickrage.app.config.general.web_root}/logs/';">View Log(Errors)</button> <button onclick="window.location='{sickrage.app.config.general.web_root}/home/restart?pid={sickrage.app.pid}&force=1';">Restart SiCKRAGE</button> <button onclick="window.location='{sickrage.app.config.general.web_root}/logout';">Logout</button> <h2>Error</h2> <p>{VAR_17}</p> <h2>Traceback</h2> <p>{VAR_18}</p> <h2>Request Info</h2> <p>{VAR_19}</p> </body> </html>""") def FUNC_3(self): if is_ip_whitelisted(self.request.remote_ip): return True elif sickrage.app.config.general.sso_auth_enabled and sickrage.app.auth_server.health: try: VAR_20 = self.get_secure_cookie('_sr_access_token') VAR_21 = self.get_secure_cookie('_sr_refresh_token') if not all([VAR_20, VAR_21]): return VAR_22 = sickrage.app.auth_server.certs() if not VAR_22: return try: return sickrage.app.auth_server.decode_token(VAR_20.decode("utf-8"), VAR_22) except (KeycloakClientError, ExpiredSignatureError): VAR_24 = sickrage.app.auth_server.refresh_token(VAR_21.decode("utf-8")) if not VAR_24: return self.set_secure_cookie('_sr_access_token', VAR_24['access_token']) self.set_secure_cookie('_sr_refresh_token', VAR_24['refresh_token']) return sickrage.app.auth_server.decode_token(VAR_24['access_token'], VAR_22) except Exception as e: return elif sickrage.app.config.general.local_auth_enabled: VAR_23 = self.get_secure_cookie('_sr').decode() if self.get_secure_cookie('_sr') else None if VAR_23 == sickrage.app.config.general.api_v1_key: return True def FUNC_4(self, VAR_5, **VAR_2): VAR_13 = { 'title': "", 'header': "", 'topmenu': "", 'submenu': "", 'controller': "home", 'action': "index", 'srPID': sickrage.app.pid, 'srHttpsEnabled': sickrage.app.config.general.enable_https or bool(self.request.headers.get('X-Forwarded-Proto') == 'https'), 'srHost': self.request.headers.get('X-Forwarded-Host', self.request.host.split(':')[0]), 'srHttpPort': self.request.headers.get('X-Forwarded-Port', sickrage.app.config.general.web_port), 'srHttpsPort': sickrage.app.config.general.web_port, 'srHandleReverseProxy': sickrage.app.config.general.handle_reverse_proxy, 'srDefaultPage': sickrage.app.config.general.default_page.value, 'srWebRoot': sickrage.app.config.general.web_root, 'srLocale': self.get_user_locale().code, 'srLocaleDir': sickrage.LOCALE_DIR, 'srStartTime': self.startTime, 'makoStartTime': time.time(), 'overall_stats': None, 'torrent_webui_url': torrent_webui_url(), 'application': self.application, 'request': self.request, } VAR_13.update(self.get_template_namespace()) VAR_13.update(VAR_2) try: return self.application.settings['templates'][VAR_5].render_unicode(**VAR_13) except Exception: VAR_2['title'] = _('HTTP Error 500') VAR_2['header'] = _('HTTP Error 500') VAR_2['backtrace'] = RichTraceback() VAR_13.update(VAR_2) sickrage.app.log.error("%s: %s" % (str(VAR_2['backtrace'].error.__class__.__name__), VAR_2['backtrace'].error)) return self.application.settings['templates']['errors/500.mako'].render_unicode(**VAR_13) def FUNC_5(self, VAR_5, **VAR_2): self.write(self.render_string(VAR_5, **VAR_2)) def FUNC_6(self): self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With") self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE, OPTIONS') self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') def FUNC_7(self, VAR_6, VAR_7=True, VAR_8=None): if sickrage.app.config.general.web_root not in VAR_6: url = urljoin(sickrage.app.config.general.web_root + '/', VAR_6.lstrip('/')) super(CLASS_0, self).redirect(VAR_6, VAR_7, VAR_8) def FUNC_8(self): VAR_6 = urlparse(self.request.headers.get("referer", "/{}/".format(sickrage.app.config.general.default_page.value))) return VAR_6._replace(scheme="", netloc="").geturl() def FUNC_9(self, VAR_9, VAR_10): return self.render('generic_message.mako', VAR_10=message, VAR_9=subject, title="", controller='root', action='genericmessage') def FUNC_10(self, VAR_6): if sickrage.app.config.general.web_root not in VAR_6: url = urljoin(sickrage.app.config.general.web_root + '/', VAR_6.lstrip('/')) VAR_6 = urljoin("{}://{}".format(self.request.protocol, self.request.host), VAR_6) return VAR_6 def FUNC_11(self, VAR_11): @functools.wraps(VAR_11) async def FUNC_15(self, *VAR_12, **VAR_2): await sickrage.app.wserver.io_loop.run_in_executor(self.executor, functools.partial(VAR_11, *VAR_12, **VAR_2)) return types.MethodType(FUNC_15, self) def FUNC_12(self): VAR_14 = self.request.method.lower() VAR_11 = self.run_async(getattr(self, VAR_14)) setattr(self, VAR_14, VAR_11) def FUNC_13(self, *VAR_12, **VAR_2): self.set_status(204) self.finish() def FUNC_14(self, *VAR_12, **VAR_2): VAR_15 = super(CLASS_0, self).get_argument(*VAR_12, **VAR_2) try: return bleach.clean(VAR_15) except TypeError: return VAR_15
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 28, 34, 37, 38, 42, 44, 46, 49, 52, 57, 59, 63, 79, 89, 93, 100, 110, 136, 139, 147, 149, 151, 154, 160, 165, 169, 177, 183, 188, 190, 195, 199 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 29, 36, 39, 40, 44, 46, 48, 51, 54, 59, 61, 65, 81, 91, 95, 102, 112, 138, 141, 149, 151, 153, 156, 162, 167, 171, 179, 185, 190, 192, 197, 201, 204, 209 ]
5CWE-94
""" Generate modern Python clients from OpenAPI """ from __future__ import annotations import shutil import subprocess import sys from pathlib import Path from typing import Any, Dict, Optional, Sequence, Union import httpcore import httpx import yaml from jinja2 import Environment, PackageLoader from openapi_python_client import utils from .parser import GeneratorData, import_string_from_reference from .parser.errors import GeneratorError if sys.version_info.minor == 7: # version did not exist in 3.7, need to use a backport from importlib_metadata import version else: from importlib.metadata import version # type: ignore __version__ = version(__package__) def _get_project_for_url_or_path(url: Optional[str], path: Optional[Path]) -> Union[Project, GeneratorError]: data_dict = _get_document(url=url, path=path) if isinstance(data_dict, GeneratorError): return data_dict openapi = GeneratorData.from_dict(data_dict) if isinstance(openapi, GeneratorError): return openapi return Project(openapi=openapi) def create_new_client(*, url: Optional[str], path: Optional[Path]) -> Sequence[GeneratorError]: """ Generate the client library Returns: A list containing any errors encountered when generating. """ project = _get_project_for_url_or_path(url=url, path=path) if isinstance(project, GeneratorError): return [project] return project.build() def update_existing_client(*, url: Optional[str], path: Optional[Path]) -> Sequence[GeneratorError]: """ Update an existing client library Returns: A list containing any errors encountered when generating. """ project = _get_project_for_url_or_path(url=url, path=path) if isinstance(project, GeneratorError): return [project] return project.update() def _get_document(*, url: Optional[str], path: Optional[Path]) -> Union[Dict[str, Any], GeneratorError]: yaml_bytes: bytes if url is not None and path is not None: return GeneratorError(header="Provide URL or Path, not both.") if url is not None: try: response = httpx.get(url) yaml_bytes = response.content except (httpx.HTTPError, httpcore.NetworkError): return GeneratorError(header="Could not get OpenAPI document from provided URL") elif path is not None: yaml_bytes = path.read_bytes() else: return GeneratorError(header="No URL or Path provided") try: return yaml.safe_load(yaml_bytes) except yaml.YAMLError: return GeneratorError(header="Invalid YAML from provided source") class Project: TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{utils.kebab_case(openapi.title).lower()}-client" self.project_dir: Path = Path.cwd() / self.project_name self.package_name: str = self.package_name_override or self.project_name.replace("-", "_") self.package_dir: Path = self.project_dir / self.package_name self.package_description: str = f"A client library for accessing {self.openapi.title}" self.version: str = openapi.version self.env.filters.update(self.TEMPLATE_FILTERS) def build(self) -> Sequence[GeneratorError]: """ Create the project from templates """ print(f"Generating {self.project_name}") try: self.project_dir.mkdir() except FileExistsError: return [GeneratorError(detail="Directory already exists. Delete it or use the update command.")] self._create_package() self._build_metadata() self._build_models() self._build_api() self._reformat() return self._get_errors() def update(self) -> Sequence[GeneratorError]: """ Update an existing project """ if not self.package_dir.is_dir(): raise FileNotFoundError() print(f"Updating {self.project_name}") shutil.rmtree(self.package_dir) self._create_package() self._build_models() self._build_api() self._reformat() return self._get_errors() def _reformat(self) -> None: subprocess.run( "isort .", cwd=self.project_dir, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) subprocess.run("black .", cwd=self.project_dir, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _get_errors(self) -> Sequence[GeneratorError]: errors = [] for collection in self.openapi.endpoint_collections_by_tag.values(): errors.extend(collection.parse_errors) errors.extend(self.openapi.schemas.errors) return errors def _create_package(self) -> None: self.package_dir.mkdir() # Package __init__.py package_init = self.package_dir / "__init__.py" package_init_template = self.env.get_template("package_init.pyi") package_init.write_text(package_init_template.render(description=self.package_description)) pytyped = self.package_dir / "py.typed" pytyped.write_text("# Marker file for PEP 561") def _build_metadata(self) -> None: # Create a pyproject.toml file pyproject_template = self.env.get_template("pyproject.toml") pyproject_path = self.project_dir / "pyproject.toml" pyproject_path.write_text( pyproject_template.render( project_name=self.project_name, package_name=self.package_name, version=self.version, description=self.package_description, ) ) # README.md readme = self.project_dir / "README.md" readme_template = self.env.get_template("README.md") readme.write_text( readme_template.render( project_name=self.project_name, description=self.package_description, package_name=self.package_name ) ) # .gitignore git_ignore_path = self.project_dir / ".gitignore" git_ignore_template = self.env.get_template(".gitignore") git_ignore_path.write_text(git_ignore_template.render()) def _build_models(self) -> None: # Generate models models_dir = self.package_dir / "models" models_dir.mkdir() models_init = models_dir / "__init__.py" imports = [] types_template = self.env.get_template("types.py") types_path = models_dir / "types.py" types_path.write_text(types_template.render()) model_template = self.env.get_template("model.pyi") for model in self.openapi.schemas.models.values(): module_path = models_dir / f"{model.reference.module_name}.py" module_path.write_text(model_template.render(model=model)) imports.append(import_string_from_reference(model.reference)) # Generate enums enum_template = self.env.get_template("enum.pyi") for enum in self.openapi.enums.values(): module_path = models_dir / f"{enum.reference.module_name}.py" module_path.write_text(enum_template.render(enum=enum)) imports.append(import_string_from_reference(enum.reference)) models_init_template = self.env.get_template("models_init.pyi") models_init.write_text(models_init_template.render(imports=imports)) def _build_api(self) -> None: # Generate Client client_path = self.package_dir / "client.py" client_template = self.env.get_template("client.pyi") client_path.write_text(client_template.render()) # Generate endpoints api_dir = self.package_dir / "api" api_dir.mkdir() api_init = api_dir / "__init__.py" api_init.write_text('""" Contains synchronous methods for accessing the API """') async_api_dir = self.package_dir / "async_api" async_api_dir.mkdir() async_api_init = async_api_dir / "__init__.py" async_api_init.write_text('""" Contains async methods for accessing the API """') api_errors = self.package_dir / "errors.py" errors_template = self.env.get_template("errors.pyi") api_errors.write_text(errors_template.render()) endpoint_template = self.env.get_template("endpoint_module.pyi") async_endpoint_template = self.env.get_template("async_endpoint_module.pyi") for tag, collection in self.openapi.endpoint_collections_by_tag.items(): tag = utils.snake_case(tag) module_path = api_dir / f"{tag}.py" module_path.write_text(endpoint_template.render(collection=collection)) async_module_path = async_api_dir / f"{tag}.py" async_module_path.write_text(async_endpoint_template.render(collection=collection))
""" Generate modern Python clients from OpenAPI """ from __future__ import annotations import shutil import subprocess import sys from pathlib import Path from typing import Any, Dict, Optional, Sequence, Union import httpcore import httpx import yaml from jinja2 import Environment, PackageLoader from openapi_python_client import utils from .parser import GeneratorData, import_string_from_reference from .parser.errors import GeneratorError if sys.version_info.minor == 7: # version did not exist in 3.7, need to use a backport from importlib_metadata import version else: from importlib.metadata import version # type: ignore __version__ = version(__package__) def _get_project_for_url_or_path(url: Optional[str], path: Optional[Path]) -> Union[Project, GeneratorError]: data_dict = _get_document(url=url, path=path) if isinstance(data_dict, GeneratorError): return data_dict openapi = GeneratorData.from_dict(data_dict) if isinstance(openapi, GeneratorError): return openapi return Project(openapi=openapi) def create_new_client(*, url: Optional[str], path: Optional[Path]) -> Sequence[GeneratorError]: """ Generate the client library Returns: A list containing any errors encountered when generating. """ project = _get_project_for_url_or_path(url=url, path=path) if isinstance(project, GeneratorError): return [project] return project.build() def update_existing_client(*, url: Optional[str], path: Optional[Path]) -> Sequence[GeneratorError]: """ Update an existing client library Returns: A list containing any errors encountered when generating. """ project = _get_project_for_url_or_path(url=url, path=path) if isinstance(project, GeneratorError): return [project] return project.update() def _get_document(*, url: Optional[str], path: Optional[Path]) -> Union[Dict[str, Any], GeneratorError]: yaml_bytes: bytes if url is not None and path is not None: return GeneratorError(header="Provide URL or Path, not both.") if url is not None: try: response = httpx.get(url) yaml_bytes = response.content except (httpx.HTTPError, httpcore.NetworkError): return GeneratorError(header="Could not get OpenAPI document from provided URL") elif path is not None: yaml_bytes = path.read_bytes() else: return GeneratorError(header="No URL or Path provided") try: return yaml.safe_load(yaml_bytes) except yaml.YAMLError: return GeneratorError(header="Invalid YAML from provided source") class Project: TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{utils.kebab_case(openapi.title).lower()}-client" self.project_dir: Path = Path.cwd() / self.project_name self.package_name: str = self.package_name_override or self.project_name.replace("-", "_") self.package_dir: Path = self.project_dir / self.package_name self.package_description: str = utils.remove_string_escapes( f"A client library for accessing {self.openapi.title}" ) self.version: str = openapi.version self.env.filters.update(self.TEMPLATE_FILTERS) def build(self) -> Sequence[GeneratorError]: """ Create the project from templates """ print(f"Generating {self.project_name}") try: self.project_dir.mkdir() except FileExistsError: return [GeneratorError(detail="Directory already exists. Delete it or use the update command.")] self._create_package() self._build_metadata() self._build_models() self._build_api() self._reformat() return self._get_errors() def update(self) -> Sequence[GeneratorError]: """ Update an existing project """ if not self.package_dir.is_dir(): raise FileNotFoundError() print(f"Updating {self.project_name}") shutil.rmtree(self.package_dir) self._create_package() self._build_models() self._build_api() self._reformat() return self._get_errors() def _reformat(self) -> None: subprocess.run( "isort .", cwd=self.project_dir, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) subprocess.run("black .", cwd=self.project_dir, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _get_errors(self) -> Sequence[GeneratorError]: errors = [] for collection in self.openapi.endpoint_collections_by_tag.values(): errors.extend(collection.parse_errors) errors.extend(self.openapi.schemas.errors) return errors def _create_package(self) -> None: self.package_dir.mkdir() # Package __init__.py package_init = self.package_dir / "__init__.py" package_init_template = self.env.get_template("package_init.pyi") package_init.write_text(package_init_template.render(description=self.package_description)) pytyped = self.package_dir / "py.typed" pytyped.write_text("# Marker file for PEP 561") def _build_metadata(self) -> None: # Create a pyproject.toml file pyproject_template = self.env.get_template("pyproject.toml") pyproject_path = self.project_dir / "pyproject.toml" pyproject_path.write_text( pyproject_template.render( project_name=self.project_name, package_name=self.package_name, version=self.version, description=self.package_description, ) ) # README.md readme = self.project_dir / "README.md" readme_template = self.env.get_template("README.md") readme.write_text( readme_template.render( project_name=self.project_name, description=self.package_description, package_name=self.package_name ) ) # .gitignore git_ignore_path = self.project_dir / ".gitignore" git_ignore_template = self.env.get_template(".gitignore") git_ignore_path.write_text(git_ignore_template.render()) def _build_models(self) -> None: # Generate models models_dir = self.package_dir / "models" models_dir.mkdir() models_init = models_dir / "__init__.py" imports = [] types_template = self.env.get_template("types.py") types_path = models_dir / "types.py" types_path.write_text(types_template.render()) model_template = self.env.get_template("model.pyi") for model in self.openapi.schemas.models.values(): module_path = models_dir / f"{model.reference.module_name}.py" module_path.write_text(model_template.render(model=model)) imports.append(import_string_from_reference(model.reference)) # Generate enums enum_template = self.env.get_template("enum.pyi") for enum in self.openapi.enums.values(): module_path = models_dir / f"{enum.reference.module_name}.py" module_path.write_text(enum_template.render(enum=enum)) imports.append(import_string_from_reference(enum.reference)) models_init_template = self.env.get_template("models_init.pyi") models_init.write_text(models_init_template.render(imports=imports)) def _build_api(self) -> None: # Generate Client client_path = self.package_dir / "client.py" client_template = self.env.get_template("client.pyi") client_path.write_text(client_template.render()) # Generate endpoints api_dir = self.package_dir / "api" api_dir.mkdir() api_init = api_dir / "__init__.py" api_init.write_text('""" Contains synchronous methods for accessing the API """') async_api_dir = self.package_dir / "async_api" async_api_dir.mkdir() async_api_init = async_api_dir / "__init__.py" async_api_init.write_text('""" Contains async methods for accessing the API """') api_errors = self.package_dir / "errors.py" errors_template = self.env.get_template("errors.pyi") api_errors.write_text(errors_template.render()) endpoint_template = self.env.get_template("endpoint_module.pyi") async_endpoint_template = self.env.get_template("async_endpoint_module.pyi") for tag, collection in self.openapi.endpoint_collections_by_tag.items(): tag = utils.snake_case(tag) module_path = api_dir / f"{tag}.py" module_path.write_text(endpoint_template.render(collection=collection)) async_module_path = async_api_dir / f"{tag}.py" async_module_path.write_text(async_endpoint_template.render(collection=collection))
remote_code_execution
{ "code": [ " self.package_description: str = f\"A client library for accessing {self.openapi.title}\"" ], "line_no": [ 99 ] }
{ "code": [ " self.package_description: str = utils.remove_string_escapes(", " f\"A client library for accessing {self.openapi.title}\"" ], "line_no": [ 99, 100 ] }
from __future__ import annotations import shutil import subprocess import sys from pathlib import Path from typing import Any, Dict, Optional, Sequence, Union import httpcore import httpx import yaml from jinja2 import Environment, PackageLoader from openapi_python_client import utils from .parser import GeneratorData, import_string_from_reference from .parser.errors import GeneratorError if sys.version_info.minor == 7: # version did not exist in 3.7, need to use a backport from importlib_metadata import version else: from importlib.metadata import version # type: ignore __version__ = version(__package__) def FUNC_0(VAR_0: Optional[str], VAR_1: Optional[Path]) -> Union[CLASS_0, GeneratorError]: VAR_2 = FUNC_3(VAR_0=url, VAR_1=path) if isinstance(VAR_2, GeneratorError): return VAR_2 VAR_3 = GeneratorData.from_dict(VAR_2) if isinstance(VAR_3, GeneratorError): return VAR_3 return CLASS_0(VAR_3=openapi) def FUNC_1(*, VAR_0: Optional[str], VAR_1: Optional[Path]) -> Sequence[GeneratorError]: VAR_4 = FUNC_0(VAR_0=url, VAR_1=path) if isinstance(VAR_4, GeneratorError): return [VAR_4] return VAR_4.build() def FUNC_2(*, VAR_0: Optional[str], VAR_1: Optional[Path]) -> Sequence[GeneratorError]: VAR_4 = FUNC_0(VAR_0=url, VAR_1=path) if isinstance(VAR_4, GeneratorError): return [VAR_4] return VAR_4.update() def FUNC_3(*, VAR_0: Optional[str], VAR_1: Optional[Path]) -> Union[Dict[str, Any], GeneratorError]: VAR_35: bytes if VAR_0 is not None and VAR_1 is not None: return GeneratorError(header="Provide URL or Path, not both.") if VAR_0 is not None: try: VAR_34 = httpx.get(VAR_0) VAR_35 = VAR_34.content except (httpx.HTTPError, httpcore.NetworkError): return GeneratorError(header="Could not get OpenAPI document from provided URL") elif VAR_1 is not None: VAR_35 = VAR_1.read_bytes() else: return GeneratorError(header="No URL or Path provided") try: return yaml.safe_load(VAR_35) except yaml.YAMLError: return GeneratorError(header="Invalid YAML from provided source") class CLASS_0: VAR_5 = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None def __init__(self, *, VAR_3: GeneratorData) -> None: self.openapi: GeneratorData = VAR_3 self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{utils.kebab_case(VAR_3.title).lower()}-client" self.project_dir: Path = Path.cwd() / self.project_name self.package_name: str = self.package_name_override or self.project_name.replace("-", "_") self.package_dir: Path = self.project_dir / self.package_name self.package_description: str = f"A client library for accessing {self.openapi.title}" self.version: str = VAR_3.version self.env.filters.update(self.TEMPLATE_FILTERS) def FUNC_4(self) -> Sequence[GeneratorError]: print(f"Generating {self.project_name}") try: self.project_dir.mkdir() except FileExistsError: return [GeneratorError(detail="Directory already exists. Delete it or use the FUNC_5 command.")] self._create_package() self._build_metadata() self._build_models() self._build_api() self._reformat() return self._get_errors() def FUNC_5(self) -> Sequence[GeneratorError]: if not self.package_dir.is_dir(): raise FileNotFoundError() print(f"Updating {self.project_name}") shutil.rmtree(self.package_dir) self._create_package() self._build_models() self._build_api() self._reformat() return self._get_errors() def FUNC_6(self) -> None: subprocess.run( "isort .", cwd=self.project_dir, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) subprocess.run("black .", cwd=self.project_dir, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def FUNC_7(self) -> Sequence[GeneratorError]: VAR_6 = [] for collection in self.openapi.endpoint_collections_by_tag.values(): VAR_6.extend(collection.parse_errors) VAR_6.extend(self.openapi.schemas.errors) return VAR_6 def FUNC_8(self) -> None: self.package_dir.mkdir() VAR_7 = self.package_dir / "__init__.py" VAR_8 = self.env.get_template("package_init.pyi") VAR_7.write_text(VAR_8.render(description=self.package_description)) VAR_9 = self.package_dir / "py.typed" VAR_9.write_text("# Marker file for PEP 561") def FUNC_9(self) -> None: VAR_10 = self.env.get_template("pyproject.toml") VAR_11 = self.project_dir / "pyproject.toml" VAR_11.write_text( VAR_10.render( project_name=self.project_name, package_name=self.package_name, version=self.version, description=self.package_description, ) ) VAR_12 = self.project_dir / "README.md" VAR_13 = self.env.get_template("README.md") VAR_12.write_text( VAR_13.render( project_name=self.project_name, description=self.package_description, package_name=self.package_name ) ) VAR_14 = self.project_dir / ".gitignore" VAR_15 = self.env.get_template(".gitignore") VAR_14.write_text(VAR_15.render()) def FUNC_10(self) -> None: VAR_16 = self.package_dir / "models" VAR_16.mkdir() VAR_17 = VAR_16 / "__init__.py" VAR_18 = [] VAR_19 = self.env.get_template("types.py") VAR_20 = VAR_16 / "types.py" VAR_20.write_text(VAR_19.render()) VAR_21 = self.env.get_template("model.pyi") for model in self.openapi.schemas.models.values(): VAR_36 = VAR_16 / f"{model.reference.module_name}.py" VAR_36.write_text(VAR_21.render(model=model)) VAR_18.append(import_string_from_reference(model.reference)) VAR_22 = self.env.get_template("enum.pyi") for enum in self.openapi.enums.values(): VAR_36 = VAR_16 / f"{enum.reference.module_name}.py" VAR_36.write_text(VAR_22.render(enum=enum)) VAR_18.append(import_string_from_reference(enum.reference)) VAR_23 = self.env.get_template("models_init.pyi") VAR_17.write_text(VAR_23.render(VAR_18=imports)) def FUNC_11(self) -> None: VAR_24 = self.package_dir / "client.py" VAR_25 = self.env.get_template("client.pyi") VAR_24.write_text(VAR_25.render()) VAR_26 = self.package_dir / "api" VAR_26.mkdir() VAR_27 = VAR_26 / "__init__.py" VAR_27.write_text('""" Contains synchronous methods for accessing the API """') VAR_28 = self.package_dir / "async_api" VAR_28.mkdir() VAR_29 = VAR_28 / "__init__.py" VAR_29.write_text('""" Contains async methods for accessing the API """') VAR_30 = self.package_dir / "errors.py" VAR_31 = self.env.get_template("errors.pyi") VAR_30.write_text(VAR_31.render()) VAR_32 = self.env.get_template("endpoint_module.pyi") VAR_33 = self.env.get_template("async_endpoint_module.pyi") for VAR_37, collection in self.openapi.endpoint_collections_by_tag.items(): VAR_37 = utils.snake_case(VAR_37) VAR_36 = VAR_26 / f"{VAR_37}.py" VAR_36.write_text(VAR_32.render(collection=collection)) VAR_38 = VAR_28 / f"{VAR_37}.py" VAR_38.write_text(VAR_33.render(collection=collection))
from __future__ import annotations import shutil import subprocess import sys from pathlib import Path from typing import Any, Dict, Optional, Sequence, Union import httpcore import httpx import yaml from jinja2 import Environment, PackageLoader from openapi_python_client import utils from .parser import GeneratorData, import_string_from_reference from .parser.errors import GeneratorError if sys.version_info.minor == 7: # version did not exist in 3.7, need to use a backport from importlib_metadata import version else: from importlib.metadata import version # type: ignore __version__ = version(__package__) def FUNC_0(VAR_0: Optional[str], VAR_1: Optional[Path]) -> Union[CLASS_0, GeneratorError]: VAR_2 = FUNC_3(VAR_0=url, VAR_1=path) if isinstance(VAR_2, GeneratorError): return VAR_2 VAR_3 = GeneratorData.from_dict(VAR_2) if isinstance(VAR_3, GeneratorError): return VAR_3 return CLASS_0(VAR_3=openapi) def FUNC_1(*, VAR_0: Optional[str], VAR_1: Optional[Path]) -> Sequence[GeneratorError]: VAR_4 = FUNC_0(VAR_0=url, VAR_1=path) if isinstance(VAR_4, GeneratorError): return [VAR_4] return VAR_4.build() def FUNC_2(*, VAR_0: Optional[str], VAR_1: Optional[Path]) -> Sequence[GeneratorError]: VAR_4 = FUNC_0(VAR_0=url, VAR_1=path) if isinstance(VAR_4, GeneratorError): return [VAR_4] return VAR_4.update() def FUNC_3(*, VAR_0: Optional[str], VAR_1: Optional[Path]) -> Union[Dict[str, Any], GeneratorError]: VAR_35: bytes if VAR_0 is not None and VAR_1 is not None: return GeneratorError(header="Provide URL or Path, not both.") if VAR_0 is not None: try: VAR_34 = httpx.get(VAR_0) VAR_35 = VAR_34.content except (httpx.HTTPError, httpcore.NetworkError): return GeneratorError(header="Could not get OpenAPI document from provided URL") elif VAR_1 is not None: VAR_35 = VAR_1.read_bytes() else: return GeneratorError(header="No URL or Path provided") try: return yaml.safe_load(VAR_35) except yaml.YAMLError: return GeneratorError(header="Invalid YAML from provided source") class CLASS_0: VAR_5 = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None def __init__(self, *, VAR_3: GeneratorData) -> None: self.openapi: GeneratorData = VAR_3 self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{utils.kebab_case(VAR_3.title).lower()}-client" self.project_dir: Path = Path.cwd() / self.project_name self.package_name: str = self.package_name_override or self.project_name.replace("-", "_") self.package_dir: Path = self.project_dir / self.package_name self.package_description: str = utils.remove_string_escapes( f"A client library for accessing {self.openapi.title}" ) self.version: str = VAR_3.version self.env.filters.update(self.TEMPLATE_FILTERS) def FUNC_4(self) -> Sequence[GeneratorError]: print(f"Generating {self.project_name}") try: self.project_dir.mkdir() except FileExistsError: return [GeneratorError(detail="Directory already exists. Delete it or use the FUNC_5 command.")] self._create_package() self._build_metadata() self._build_models() self._build_api() self._reformat() return self._get_errors() def FUNC_5(self) -> Sequence[GeneratorError]: if not self.package_dir.is_dir(): raise FileNotFoundError() print(f"Updating {self.project_name}") shutil.rmtree(self.package_dir) self._create_package() self._build_models() self._build_api() self._reformat() return self._get_errors() def FUNC_6(self) -> None: subprocess.run( "isort .", cwd=self.project_dir, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) subprocess.run("black .", cwd=self.project_dir, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def FUNC_7(self) -> Sequence[GeneratorError]: VAR_6 = [] for collection in self.openapi.endpoint_collections_by_tag.values(): VAR_6.extend(collection.parse_errors) VAR_6.extend(self.openapi.schemas.errors) return VAR_6 def FUNC_8(self) -> None: self.package_dir.mkdir() VAR_7 = self.package_dir / "__init__.py" VAR_8 = self.env.get_template("package_init.pyi") VAR_7.write_text(VAR_8.render(description=self.package_description)) VAR_9 = self.package_dir / "py.typed" VAR_9.write_text("# Marker file for PEP 561") def FUNC_9(self) -> None: VAR_10 = self.env.get_template("pyproject.toml") VAR_11 = self.project_dir / "pyproject.toml" VAR_11.write_text( VAR_10.render( project_name=self.project_name, package_name=self.package_name, version=self.version, description=self.package_description, ) ) VAR_12 = self.project_dir / "README.md" VAR_13 = self.env.get_template("README.md") VAR_12.write_text( VAR_13.render( project_name=self.project_name, description=self.package_description, package_name=self.package_name ) ) VAR_14 = self.project_dir / ".gitignore" VAR_15 = self.env.get_template(".gitignore") VAR_14.write_text(VAR_15.render()) def FUNC_10(self) -> None: VAR_16 = self.package_dir / "models" VAR_16.mkdir() VAR_17 = VAR_16 / "__init__.py" VAR_18 = [] VAR_19 = self.env.get_template("types.py") VAR_20 = VAR_16 / "types.py" VAR_20.write_text(VAR_19.render()) VAR_21 = self.env.get_template("model.pyi") for model in self.openapi.schemas.models.values(): VAR_36 = VAR_16 / f"{model.reference.module_name}.py" VAR_36.write_text(VAR_21.render(model=model)) VAR_18.append(import_string_from_reference(model.reference)) VAR_22 = self.env.get_template("enum.pyi") for enum in self.openapi.enums.values(): VAR_36 = VAR_16 / f"{enum.reference.module_name}.py" VAR_36.write_text(VAR_22.render(enum=enum)) VAR_18.append(import_string_from_reference(enum.reference)) VAR_23 = self.env.get_template("models_init.pyi") VAR_17.write_text(VAR_23.render(VAR_18=imports)) def FUNC_11(self) -> None: VAR_24 = self.package_dir / "client.py" VAR_25 = self.env.get_template("client.pyi") VAR_24.write_text(VAR_25.render()) VAR_26 = self.package_dir / "api" VAR_26.mkdir() VAR_27 = VAR_26 / "__init__.py" VAR_27.write_text('""" Contains synchronous methods for accessing the API """') VAR_28 = self.package_dir / "async_api" VAR_28.mkdir() VAR_29 = VAR_28 / "__init__.py" VAR_29.write_text('""" Contains async methods for accessing the API """') VAR_30 = self.package_dir / "errors.py" VAR_31 = self.env.get_template("errors.pyi") VAR_30.write_text(VAR_31.render()) VAR_32 = self.env.get_template("endpoint_module.pyi") VAR_33 = self.env.get_template("async_endpoint_module.pyi") for VAR_37, collection in self.openapi.endpoint_collections_by_tag.items(): VAR_37 = utils.snake_case(VAR_37) VAR_36 = VAR_26 / f"{VAR_37}.py" VAR_36.write_text(VAR_32.render(collection=collection)) VAR_38 = VAR_28 / f"{VAR_37}.py" VAR_38.write_text(VAR_33.render(collection=collection))
[ 3, 9, 14, 16, 19, 24, 25, 27, 28, 37, 38, 42, 50, 51, 55, 63, 64, 83, 84, 89, 93, 96, 101, 103, 106, 118, 121, 131, 137, 144, 147, 149, 152, 155, 157, 168, 169, 177, 178, 182, 184, 189, 193, 199, 200, 206, 209, 211, 215, 216, 221, 226, 230, 239, 1, 40, 41, 42, 43, 44, 45, 53, 54, 55, 56, 57, 58, 105, 120 ]
[ 3, 9, 14, 16, 19, 24, 25, 27, 28, 37, 38, 42, 50, 51, 55, 63, 64, 83, 84, 89, 93, 96, 103, 105, 108, 120, 123, 133, 139, 146, 149, 151, 154, 157, 159, 170, 171, 179, 180, 184, 186, 191, 195, 201, 202, 208, 211, 213, 217, 218, 223, 228, 232, 241, 1, 40, 41, 42, 43, 44, 45, 53, 54, 55, 56, 57, 58, 107, 122 ]
0CWE-22
import os from django.core.files.base import ContentFile from django.core.files.uploadedfile import SimpleUploadedFile from s3file.middleware import S3FileMiddleware from s3file.storages import storage class TestS3FileMiddleware: def test_get_files_from_storage(self): content = b"test_get_files_from_storage" name = storage.save( "tmp/s3file/test_get_files_from_storage", ContentFile(content) ) files = S3FileMiddleware.get_files_from_storage( [os.path.join(storage.aws_location, name)] ) file = next(files) assert file.read() == content def test_process_request(self, rf): uploaded_file = SimpleUploadedFile("uploaded_file.txt", b"uploaded") request = rf.post("/", data={"file": uploaded_file}) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getlist("file") assert request.FILES.get("file").read() == b"uploaded" storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) request = rf.post( "/", data={ "file": "custom/location/tmp/s3file/s3_file.txt", "s3file": "file", }, ) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getlist("file") assert request.FILES.get("file").read() == b"s3file" def test_process_request__multiple_files(self, rf): storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) storage.save("tmp/s3file/s3_other_file.txt", ContentFile(b"other s3file")) request = rf.post( "/", data={ "file": [ "custom/location/tmp/s3file/s3_file.txt", "custom/location/tmp/s3file/s3_other_file.txt", ], "s3file": ["file", "other_file"], }, ) S3FileMiddleware(lambda x: None)(request) files = request.FILES.getlist("file") assert files[0].read() == b"s3file" assert files[1].read() == b"other s3file" def test_process_request__no_location(self, rf, settings): settings.AWS_LOCATION = "" uploaded_file = SimpleUploadedFile("uploaded_file.txt", b"uploaded") request = rf.post("/", data={"file": uploaded_file}) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getlist("file") assert request.FILES.get("file").read() == b"uploaded" storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) request = rf.post( "/", data={"file": "tmp/s3file/s3_file.txt", "s3file": "file"} ) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getlist("file") assert request.FILES.get("file").read() == b"s3file" def test_process_request__no_file(self, rf, caplog): request = rf.post("/", data={"file": "does_not_exist.txt", "s3file": "file"}) S3FileMiddleware(lambda x: None)(request) assert not request.FILES.getlist("file") assert "File not found: does_not_exist.txt" in caplog.text
import os import pytest from django.core.exceptions import PermissionDenied, SuspiciousFileOperation from django.core.files.base import ContentFile from django.core.files.uploadedfile import SimpleUploadedFile from s3file.middleware import S3FileMiddleware from s3file.storages import storage class TestS3FileMiddleware: def test_get_files_from_storage(self, freeze_upload_folder): content = b"test_get_files_from_storage" name = storage.save( "tmp/s3file/test_get_files_from_storage", ContentFile(content) ) files = S3FileMiddleware.get_files_from_storage( [os.path.join(storage.aws_location, name)], "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", ) file = next(files) assert file.read() == content def test_process_request(self, freeze_upload_folder, rf): uploaded_file = SimpleUploadedFile("uploaded_file.txt", b"uploaded") request = rf.post("/", data={"file": uploaded_file}) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getlist("file") assert request.FILES.get("file").read() == b"uploaded" storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) request = rf.post( "/", data={ "file": "custom/location/tmp/s3file/s3_file.txt", "s3file": "file", "file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", }, ) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getlist("file") assert request.FILES.get("file").read() == b"s3file" def test_process_request__location_escape(self, freeze_upload_folder, rf): storage.save("secrets/passwords.txt", ContentFile(b"keep this secret")) request = rf.post( "/", data={ "file": "custom/location/secrets/passwords.txt", "s3file": "file", "file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", }, ) with pytest.raises(PermissionDenied) as e: S3FileMiddleware(lambda x: None)(request) assert "Illegal signature!" in str(e.value) def test_process_request__multiple_files(self, freeze_upload_folder, rf): storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) storage.save("tmp/s3file/s3_other_file.txt", ContentFile(b"other s3file")) request = rf.post( "/", data={ "file": [ "custom/location/tmp/s3file/s3_file.txt", "custom/location/tmp/s3file/s3_other_file.txt", ], "file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", "other_file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", "s3file": ["file", "other_file"], }, ) S3FileMiddleware(lambda x: None)(request) files = request.FILES.getlist("file") assert files[0].read() == b"s3file" assert files[1].read() == b"other s3file" def test_process_request__no_location(self, freeze_upload_folder, rf, settings): settings.AWS_LOCATION = "" uploaded_file = SimpleUploadedFile("uploaded_file.txt", b"uploaded") request = rf.post("/", data={"file": uploaded_file}) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getlist("file") assert request.FILES.get("file").read() == b"uploaded" storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) request = rf.post( "/", data={ "file": f"tmp/s3file/s3_file.txt", "s3file": "file", "file-s3f-signature": "scjzm3N8njBQIVSGEhOchtM0TkGyb2U6OXGLVlRUZhY", }, ) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getlist("file") assert request.FILES.get("file").read() == b"s3file" def test_process_request__no_file(self, freeze_upload_folder, rf, caplog): request = rf.post( "/", data={ "file": "custom/location/tmp/s3file/does_not_exist.txt", "s3file": "file", "file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", }, ) S3FileMiddleware(lambda x: None)(request) assert not request.FILES.getlist("file") assert ( "File not found: custom/location/tmp/s3file/does_not_exist.txt" in caplog.text ) def test_process_request__no_signature(self, rf, caplog): request = rf.post( "/", data={"file": "tmp/s3file/does_not_exist.txt", "s3file": "file"} ) with pytest.raises(PermissionDenied) as e: S3FileMiddleware(lambda x: None)(request) def test_process_request__wrong_signature(self, rf, caplog): request = rf.post( "/", data={ "file": "tmp/s3file/does_not_exist.txt", "s3file": "file", "file-s3f-signature": "fake", }, ) with pytest.raises(PermissionDenied) as e: S3FileMiddleware(lambda x: None)(request)
path_disclosure
{ "code": [ " def test_get_files_from_storage(self):", " [os.path.join(storage.aws_location, name)]", " def test_process_request(self, rf):", " def test_process_request__multiple_files(self, rf):", " def test_process_request__no_location(self, rf, settings):", " \"/\", data={\"file\": \"tmp/s3file/s3_file.txt\", \"s3file\": \"file\"}", " def test_process_request__no_file(self, rf, caplog):", " request = rf.post(\"/\", data={\"file\": \"does_not_exist.txt\", \"s3file\": \"file\"})", " assert \"File not found: does_not_exist.txt\" in caplog.text" ], "line_no": [ 11, 17, 22, 41, 59, 69, 75, 76, 79 ] }
{ "code": [ "import pytest", "from django.core.exceptions import PermissionDenied, SuspiciousFileOperation", " def test_get_files_from_storage(self, freeze_upload_folder):", " [os.path.join(storage.aws_location, name)],", " \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",", " def test_process_request(self, freeze_upload_folder, rf):", " \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",", " def test_process_request__location_escape(self, freeze_upload_folder, rf):", " storage.save(\"secrets/passwords.txt\", ContentFile(b\"keep this secret\"))", " request = rf.post(", " \"/\",", " data={", " \"file\": \"custom/location/secrets/passwords.txt\",", " \"s3file\": \"file\",", " \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",", " },", " )", " with pytest.raises(PermissionDenied) as e:", " S3FileMiddleware(lambda x: None)(request)", " assert \"Illegal signature!\" in str(e.value)", " def test_process_request__multiple_files(self, freeze_upload_folder, rf):", " \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",", " \"other_file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",", " def test_process_request__no_location(self, freeze_upload_folder, rf, settings):", " \"/\",", " data={", " \"file\": f\"tmp/s3file/s3_file.txt\",", " \"s3file\": \"file\",", " \"file-s3f-signature\": \"scjzm3N8njBQIVSGEhOchtM0TkGyb2U6OXGLVlRUZhY\",", " },", " def test_process_request__no_file(self, freeze_upload_folder, rf, caplog):", " request = rf.post(", " \"/\",", " data={", " \"file\": \"custom/location/tmp/s3file/does_not_exist.txt\",", " \"s3file\": \"file\",", " \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",", " },", " )", " assert (", " \"File not found: custom/location/tmp/s3file/does_not_exist.txt\"", " in caplog.text", " )", " def test_process_request__no_signature(self, rf, caplog):", " request = rf.post(", " \"/\", data={\"file\": \"tmp/s3file/does_not_exist.txt\", \"s3file\": \"file\"}", " )", " with pytest.raises(PermissionDenied) as e:", " S3FileMiddleware(lambda x: None)(request)", " def test_process_request__wrong_signature(self, rf, caplog):", " request = rf.post(", " \"/\",", " data={", " \"file\": \"tmp/s3file/does_not_exist.txt\",", " \"s3file\": \"file\",", " \"file-s3f-signature\": \"fake\",", " },", " )", " with pytest.raises(PermissionDenied) as e:", " S3FileMiddleware(lambda x: None)(request)" ], "line_no": [ 3, 4, 13, 19, 20, 25, 38, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 59, 69, 70, 79, 89, 90, 91, 92, 93, 94, 100, 101, 102, 103, 104, 105, 106, 107, 108, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133 ] }
import os from django.core.files.base import ContentFile from django.core.files.uploadedfile import SimpleUploadedFile from s3file.middleware import S3FileMiddleware from s3file.storages import storage class CLASS_0: def FUNC_0(self): VAR_3 = b"test_get_files_from_storage" VAR_4 = storage.save( "tmp/s3file/test_get_files_from_storage", ContentFile(VAR_3) ) VAR_5 = S3FileMiddleware.get_files_from_storage( [os.path.join(storage.aws_location, VAR_4)] ) VAR_6 = next(VAR_5) assert VAR_6.read() == VAR_3 def FUNC_1(self, VAR_0): VAR_7 = SimpleUploadedFile("uploaded_file.txt", b"uploaded") VAR_8 = VAR_0.post("/", data={"file": VAR_7}) S3FileMiddleware(lambda x: None)(VAR_8) assert VAR_8.FILES.getlist("file") assert VAR_8.FILES.get("file").read() == b"uploaded" storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) VAR_8 = VAR_0.post( "/", data={ "file": "custom/location/tmp/s3file/s3_file.txt", "s3file": "file", }, ) S3FileMiddleware(lambda x: None)(VAR_8) assert VAR_8.FILES.getlist("file") assert VAR_8.FILES.get("file").read() == b"s3file" def FUNC_2(self, VAR_0): storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) storage.save("tmp/s3file/s3_other_file.txt", ContentFile(b"other s3file")) VAR_8 = VAR_0.post( "/", data={ "file": [ "custom/location/tmp/s3file/s3_file.txt", "custom/location/tmp/s3file/s3_other_file.txt", ], "s3file": ["file", "other_file"], }, ) S3FileMiddleware(lambda x: None)(VAR_8) VAR_5 = VAR_8.FILES.getlist("file") assert VAR_5[0].read() == b"s3file" assert VAR_5[1].read() == b"other s3file" def FUNC_3(self, VAR_0, VAR_1): settings.AWS_LOCATION = "" VAR_7 = SimpleUploadedFile("uploaded_file.txt", b"uploaded") VAR_8 = VAR_0.post("/", data={"file": VAR_7}) S3FileMiddleware(lambda x: None)(VAR_8) assert VAR_8.FILES.getlist("file") assert VAR_8.FILES.get("file").read() == b"uploaded" storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) VAR_8 = VAR_0.post( "/", data={"file": "tmp/s3file/s3_file.txt", "s3file": "file"} ) S3FileMiddleware(lambda x: None)(VAR_8) assert VAR_8.FILES.getlist("file") assert VAR_8.FILES.get("file").read() == b"s3file" def FUNC_4(self, VAR_0, VAR_2): VAR_8 = VAR_0.post("/", data={"file": "does_not_exist.txt", "s3file": "file"}) S3FileMiddleware(lambda x: None)(VAR_8) assert not VAR_8.FILES.getlist("file") assert "File not found: does_not_exist.txt" in VAR_2.text
import os import pytest from django.core.exceptions import PermissionDenied, SuspiciousFileOperation from django.core.files.base import ContentFile from django.core.files.uploadedfile import SimpleUploadedFile from s3file.middleware import S3FileMiddleware from s3file.storages import storage class CLASS_0: def FUNC_0(self, VAR_0): VAR_4 = b"test_get_files_from_storage" VAR_5 = storage.save( "tmp/s3file/test_get_files_from_storage", ContentFile(VAR_4) ) VAR_6 = S3FileMiddleware.get_files_from_storage( [os.path.join(storage.aws_location, VAR_5)], "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", ) VAR_7 = next(VAR_6) assert VAR_7.read() == VAR_4 def FUNC_1(self, VAR_0, VAR_1): VAR_8 = SimpleUploadedFile("uploaded_file.txt", b"uploaded") VAR_9 = VAR_1.post("/", data={"file": VAR_8}) S3FileMiddleware(lambda x: None)(VAR_9) assert VAR_9.FILES.getlist("file") assert VAR_9.FILES.get("file").read() == b"uploaded" storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) VAR_9 = VAR_1.post( "/", data={ "file": "custom/location/tmp/s3file/s3_file.txt", "s3file": "file", "file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", }, ) S3FileMiddleware(lambda x: None)(VAR_9) assert VAR_9.FILES.getlist("file") assert VAR_9.FILES.get("file").read() == b"s3file" def FUNC_2(self, VAR_0, VAR_1): storage.save("secrets/passwords.txt", ContentFile(b"keep this secret")) VAR_9 = VAR_1.post( "/", data={ "file": "custom/location/secrets/passwords.txt", "s3file": "file", "file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", }, ) with pytest.raises(PermissionDenied) as e: S3FileMiddleware(lambda x: None)(VAR_9) assert "Illegal signature!" in str(e.value) def FUNC_3(self, VAR_0, VAR_1): storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) storage.save("tmp/s3file/s3_other_file.txt", ContentFile(b"other s3file")) VAR_9 = VAR_1.post( "/", data={ "file": [ "custom/location/tmp/s3file/s3_file.txt", "custom/location/tmp/s3file/s3_other_file.txt", ], "file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", "other_file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", "s3file": ["file", "other_file"], }, ) S3FileMiddleware(lambda x: None)(VAR_9) VAR_6 = VAR_9.FILES.getlist("file") assert VAR_6[0].read() == b"s3file" assert VAR_6[1].read() == b"other s3file" def FUNC_4(self, VAR_0, VAR_1, VAR_2): settings.AWS_LOCATION = "" VAR_8 = SimpleUploadedFile("uploaded_file.txt", b"uploaded") VAR_9 = VAR_1.post("/", data={"file": VAR_8}) S3FileMiddleware(lambda x: None)(VAR_9) assert VAR_9.FILES.getlist("file") assert VAR_9.FILES.get("file").read() == b"uploaded" storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file")) VAR_9 = VAR_1.post( "/", data={ "file": f"tmp/s3file/s3_file.txt", "s3file": "file", "file-s3f-signature": "scjzm3N8njBQIVSGEhOchtM0TkGyb2U6OXGLVlRUZhY", }, ) S3FileMiddleware(lambda x: None)(VAR_9) assert VAR_9.FILES.getlist("file") assert VAR_9.FILES.get("file").read() == b"s3file" def FUNC_5(self, VAR_0, VAR_1, VAR_3): VAR_9 = VAR_1.post( "/", data={ "file": "custom/location/tmp/s3file/does_not_exist.txt", "s3file": "file", "file-s3f-signature": "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc", }, ) S3FileMiddleware(lambda x: None)(VAR_9) assert not VAR_9.FILES.getlist("file") assert ( "File not found: custom/location/tmp/s3file/does_not_exist.txt" in VAR_3.text ) def FUNC_6(self, VAR_1, VAR_3): VAR_9 = VAR_1.post( "/", data={"file": "tmp/s3file/does_not_exist.txt", "s3file": "file"} ) with pytest.raises(PermissionDenied) as e: S3FileMiddleware(lambda x: None)(VAR_9) def FUNC_7(self, VAR_1, VAR_3): VAR_9 = VAR_1.post( "/", data={ "file": "tmp/s3file/does_not_exist.txt", "s3file": "file", "file-s3f-signature": "fake", }, ) with pytest.raises(PermissionDenied) as e: S3FileMiddleware(lambda x: None)(VAR_9)
[ 2, 5, 8, 9, 21, 28, 40, 58, 66, 74, 80 ]
[ 2, 7, 10, 11, 24, 31, 44, 58, 78, 86, 99, 115, 122, 134 ]
4CWE-601
# -*- coding: utf-8 -*- from functools import wraps from django.core.exceptions import PermissionDenied from django.contrib.auth.views import redirect_to_login from django.shortcuts import redirect from spirit.core.conf import settings def moderator_required(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): user = request.user if not user.is_authenticated: return redirect_to_login(next=request.get_full_path(), login_url=settings.LOGIN_URL) if not user.st.is_moderator: raise PermissionDenied return view_func(request, *args, **kwargs) return wrapper def administrator_required(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): user = request.user if not user.is_authenticated: return redirect_to_login(next=request.get_full_path(), login_url=settings.LOGIN_URL) if not user.st.is_administrator: raise PermissionDenied return view_func(request, *args, **kwargs) return wrapper def guest_only(view_func): # TODO: test! @wraps(view_func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: return redirect(request.GET.get('next', request.user.st.get_absolute_url())) return view_func(request, *args, **kwargs) return wrapper
# -*- coding: utf-8 -*- from functools import wraps from django.core.exceptions import PermissionDenied from django.contrib.auth.views import redirect_to_login from spirit.core.conf import settings from spirit.core.utils.http import safe_redirect def moderator_required(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): user = request.user if not user.is_authenticated: return redirect_to_login(next=request.get_full_path(), login_url=settings.LOGIN_URL) if not user.st.is_moderator: raise PermissionDenied return view_func(request, *args, **kwargs) return wrapper def administrator_required(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): user = request.user if not user.is_authenticated: return redirect_to_login(next=request.get_full_path(), login_url=settings.LOGIN_URL) if not user.st.is_administrator: raise PermissionDenied return view_func(request, *args, **kwargs) return wrapper def guest_only(view_func): # TODO: test! @wraps(view_func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: return safe_redirect(request, 'next', request.user.st.get_absolute_url()) return view_func(request, *args, **kwargs) return wrapper
open_redirect
{ "code": [ "from django.shortcuts import redirect", " return redirect(request.GET.get('next', request.user.st.get_absolute_url()))" ], "line_no": [ 7, 51 ] }
{ "code": [ "from spirit.core.utils.http import safe_redirect", " return safe_redirect(request, 'next', request.user.st.get_absolute_url())" ], "line_no": [ 9, 51 ] }
from functools import wraps from django.core.exceptions import PermissionDenied from django.contrib.auth.views import redirect_to_login from django.shortcuts import redirect from spirit.core.conf import settings def FUNC_0(VAR_0): @wraps(VAR_0) def FUNC_3(VAR_1, *VAR_2, **VAR_3): VAR_4 = VAR_1.user if not VAR_4.is_authenticated: return redirect_to_login(next=VAR_1.get_full_path(), login_url=settings.LOGIN_URL) if not VAR_4.st.is_moderator: raise PermissionDenied return VAR_0(VAR_1, *VAR_2, **VAR_3) return FUNC_3 def FUNC_1(VAR_0): @wraps(VAR_0) def FUNC_3(VAR_1, *VAR_2, **VAR_3): VAR_4 = VAR_1.user if not VAR_4.is_authenticated: return redirect_to_login(next=VAR_1.get_full_path(), login_url=settings.LOGIN_URL) if not VAR_4.st.is_administrator: raise PermissionDenied return VAR_0(VAR_1, *VAR_2, **VAR_3) return FUNC_3 def FUNC_2(VAR_0): @wraps(VAR_0) def FUNC_3(VAR_1, *VAR_2, **VAR_3): if VAR_1.user.is_authenticated: return redirect(VAR_1.GET.get('next', VAR_1.user.st.get_absolute_url())) return VAR_0(VAR_1, *VAR_2, **VAR_3) return FUNC_3
from functools import wraps from django.core.exceptions import PermissionDenied from django.contrib.auth.views import redirect_to_login from spirit.core.conf import settings from spirit.core.utils.http import safe_redirect def FUNC_0(VAR_0): @wraps(VAR_0) def FUNC_3(VAR_1, *VAR_2, **VAR_3): VAR_4 = VAR_1.user if not VAR_4.is_authenticated: return redirect_to_login(next=VAR_1.get_full_path(), login_url=settings.LOGIN_URL) if not VAR_4.st.is_moderator: raise PermissionDenied return VAR_0(VAR_1, *VAR_2, **VAR_3) return FUNC_3 def FUNC_1(VAR_0): @wraps(VAR_0) def FUNC_3(VAR_1, *VAR_2, **VAR_3): VAR_4 = VAR_1.user if not VAR_4.is_authenticated: return redirect_to_login(next=VAR_1.get_full_path(), login_url=settings.LOGIN_URL) if not VAR_4.st.is_administrator: raise PermissionDenied return VAR_0(VAR_1, *VAR_2, **VAR_3) return FUNC_3 def FUNC_2(VAR_0): @wraps(VAR_0) def FUNC_3(VAR_1, *VAR_2, **VAR_3): if VAR_1.user.is_authenticated: return safe_redirect(VAR_1, 'next', VAR_1.user.st.get_absolute_url()) return VAR_0(VAR_1, *VAR_2, **VAR_3) return FUNC_3
[ 1, 2, 4, 8, 10, 11, 16, 20, 23, 25, 27, 28, 33, 37, 40, 42, 44, 45, 47, 52, 54, 56 ]
[ 1, 2, 4, 7, 10, 11, 16, 20, 23, 25, 27, 28, 33, 37, 40, 42, 44, 45, 47, 52, 54, 56 ]
0CWE-22
import json import os from contextlib import contextmanager import pytest from django.forms import ClearableFileInput from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.expected_conditions import staleness_of from selenium.webdriver.support.wait import WebDriverWait from s3file.storages import storage from tests.testapp.forms import UploadForm try: from django.urls import reverse except ImportError: # Django 1.8 support from django.core.urlresolvers import reverse @contextmanager def wait_for_page_load(driver, timeout=30): old_page = driver.find_element(By.TAG_NAME, "html") yield WebDriverWait(driver, timeout).until(staleness_of(old_page)) class TestS3FileInput: @property def url(self): return reverse("upload") @pytest.fixture def freeze(self, monkeypatch): """Freeze datetime and UUID.""" monkeypatch.setattr( "s3file.forms.S3FileInputMixin.upload_folder", os.path.join(storage.aws_location, "tmp"), ) def test_value_from_datadict(self, client, upload_file): print(storage.location) with open(upload_file) as f: uploaded_file = storage.save("test.jpg", f) response = client.post( reverse("upload"), { "file": json.dumps([uploaded_file]), "s3file": '["file"]', }, ) assert response.status_code == 201 def test_value_from_datadict_initial_data(self, filemodel): form = UploadForm(instance=filemodel) assert filemodel.file.name in form.as_p(), form.as_p() assert not form.is_valid() def test_file_does_not_exist_no_fallback(self, filemodel): form = UploadForm( data={"file": "foo.bar", "s3file": "file"}, instance=filemodel, ) assert form.is_valid() assert form.cleaned_data["file"] == filemodel.file def test_initial_no_file_uploaded(self, filemodel): form = UploadForm(data={"file": ""}, instance=filemodel) assert form.is_valid(), form.errors assert not form.has_changed() assert form.cleaned_data["file"] == filemodel.file def test_initial_fallback(self, filemodel): form = UploadForm(data={"file": ""}, instance=filemodel) assert form.is_valid() assert form.cleaned_data["file"] == filemodel.file def test_clear(self, filemodel): form = UploadForm(data={"file-clear": "1"}, instance=filemodel) assert form.is_valid() assert not form.cleaned_data["file"] def test_build_attr(self): assert set(ClearableFileInput().build_attrs({}).keys()) == { "class", "data-url", "data-fields-x-amz-algorithm", "data-fields-x-amz-date", "data-fields-x-amz-signature", "data-fields-x-amz-credential", "data-fields-policy", "data-fields-key", } assert ClearableFileInput().build_attrs({})["class"] == "s3file" assert ( ClearableFileInput().build_attrs({"class": "my-class"})["class"] == "my-class s3file" ) def test_get_conditions(self, freeze): conditions = ClearableFileInput().get_conditions(None) assert all( condition in conditions for condition in [ {"bucket": "test-bucket"}, {"success_action_status": "201"}, ["starts-with", "$key", "custom/location/tmp"], ["starts-with", "$Content-Type", ""], ] ), conditions def test_accept(self): widget = ClearableFileInput() assert "accept" not in widget.render(name="file", value="test.jpg") assert ["starts-with", "$Content-Type", ""] in widget.get_conditions(None) widget = ClearableFileInput(attrs={"accept": "image/*"}) assert 'accept="image/*"' in widget.render(name="file", value="test.jpg") assert ["starts-with", "$Content-Type", "image/"] in widget.get_conditions( "image/*" ) widget = ClearableFileInput(attrs={"accept": "image/jpeg"}) assert 'accept="image/jpeg"' in widget.render(name="file", value="test.jpg") assert {"Content-Type": "image/jpeg"} in widget.get_conditions("image/jpeg") widget = ClearableFileInput(attrs={"accept": "application/pdf,image/*"}) assert 'accept="application/pdf,image/*"' in widget.render( name="file", value="test.jpg", ) assert ["starts-with", "$Content-Type", ""] in widget.get_conditions( "application/pdf,image/*" ) assert {"Content-Type": "application/pdf"} not in widget.get_conditions( "application/pdf,image/*" ) def test_no_js_error(self, driver, live_server): driver.get(live_server + self.url) with pytest.raises(NoSuchElementException): error = driver.find_element(By.XPATH, "//body[@JSError]") pytest.fail(error.get_attribute("JSError")) def test_file_insert(self, request, driver, live_server, upload_file, freeze): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" with wait_for_page_load(driver, timeout=10): file_input.submit() assert storage.exists("tmp/%s.txt" % request.node.name) with pytest.raises(NoSuchElementException): error = driver.find_element(By.XPATH, "//body[@JSError]") pytest.fail(error.get_attribute("JSError")) def test_file_insert_submit_value(self, driver, live_server, upload_file, freeze): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//input[@name='save']") with wait_for_page_load(driver, timeout=10): save_button.click() assert "save" in driver.page_source driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//button[@name='save_continue']") with wait_for_page_load(driver, timeout=10): save_button.click() assert "save_continue" in driver.page_source assert "continue_value" in driver.page_source def test_progress(self, driver, live_server, upload_file, freeze): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//input[@name='save']") with wait_for_page_load(driver, timeout=10): save_button.click() assert "save" in driver.page_source driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//button[@name='save_continue']") with wait_for_page_load(driver, timeout=10): save_button.click() response = json.loads(driver.find_elements(By.CSS_SELECTOR, "pre")[0].text) assert response["POST"]["progress"] == "1" def test_multi_file( self, driver, live_server, freeze, upload_file, another_upload_file, yet_another_upload_file, ): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(" \n ".join([upload_file, another_upload_file])) file_input = driver.find_element(By.XPATH, "//input[@name='other_file']") file_input.send_keys(yet_another_upload_file) save_button = driver.find_element(By.XPATH, "//input[@name='save']") with wait_for_page_load(driver, timeout=10): save_button.click() response = json.loads(driver.find_elements(By.CSS_SELECTOR, "pre")[0].text) assert response["FILES"] == { "file": [ os.path.basename(upload_file), os.path.basename(another_upload_file), ], "other_file": [os.path.basename(yet_another_upload_file)], } def test_media(self): assert ClearableFileInput().media._js == ["s3file/js/s3file.js"] def test_upload_folder(self): assert "custom/location/tmp/s3file/" in ClearableFileInput().upload_folder assert len(os.path.basename(ClearableFileInput().upload_folder)) == 22
import json import os from contextlib import contextmanager import pytest from django.forms import ClearableFileInput from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.expected_conditions import staleness_of from selenium.webdriver.support.wait import WebDriverWait from s3file.storages import storage from tests.testapp.forms import UploadForm try: from django.urls import reverse except ImportError: # Django 1.8 support from django.core.urlresolvers import reverse @contextmanager def wait_for_page_load(driver, timeout=30): old_page = driver.find_element(By.TAG_NAME, "html") yield WebDriverWait(driver, timeout).until(staleness_of(old_page)) class TestS3FileInput: @property def url(self): return reverse("upload") def test_value_from_datadict(self, freeze_upload_folder, client, upload_file): with open(upload_file) as f: uploaded_file = storage.save(freeze_upload_folder / "test.jpg", f) response = client.post( reverse("upload"), { "file": f"custom/location/{uploaded_file}", "file-s3f-signature": "m94qBxBsnMIuIICiY133kX18KkllSPMVbhGAdAwNn1A", "s3file": "file", }, ) assert response.status_code == 201 def test_value_from_datadict_initial_data(self, filemodel): form = UploadForm(instance=filemodel) assert filemodel.file.name in form.as_p(), form.as_p() assert not form.is_valid() def test_file_does_not_exist_no_fallback(self, filemodel): form = UploadForm( data={"file": "foo.bar", "s3file": "file"}, instance=filemodel, ) assert form.is_valid() assert form.cleaned_data["file"] == filemodel.file def test_initial_no_file_uploaded(self, filemodel): form = UploadForm(data={"file": ""}, instance=filemodel) assert form.is_valid(), form.errors assert not form.has_changed() assert form.cleaned_data["file"] == filemodel.file def test_initial_fallback(self, filemodel): form = UploadForm(data={"file": ""}, instance=filemodel) assert form.is_valid() assert form.cleaned_data["file"] == filemodel.file def test_clear(self, filemodel): form = UploadForm(data={"file-clear": "1"}, instance=filemodel) assert form.is_valid() assert not form.cleaned_data["file"] def test_build_attr(self, freeze_upload_folder): assert set(ClearableFileInput().build_attrs({}).keys()) == { "class", "data-url", "data-fields-x-amz-algorithm", "data-fields-x-amz-date", "data-fields-x-amz-signature", "data-fields-x-amz-credential", "data-fields-policy", "data-fields-key", "data-s3f-signature", } assert ( ClearableFileInput().build_attrs({})["data-s3f-signature"] == "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc" ) assert ClearableFileInput().build_attrs({})["class"] == "s3file" assert ( ClearableFileInput().build_attrs({"class": "my-class"})["class"] == "my-class s3file" ) def test_get_conditions(self, freeze_upload_folder): conditions = ClearableFileInput().get_conditions(None) assert all( condition in conditions for condition in [ {"bucket": "test-bucket"}, {"success_action_status": "201"}, ["starts-with", "$key", "custom/location/tmp/s3file"], ["starts-with", "$Content-Type", ""], ] ), conditions def test_accept(self): widget = ClearableFileInput() assert "accept" not in widget.render(name="file", value="test.jpg") assert ["starts-with", "$Content-Type", ""] in widget.get_conditions(None) widget = ClearableFileInput(attrs={"accept": "image/*"}) assert 'accept="image/*"' in widget.render(name="file", value="test.jpg") assert ["starts-with", "$Content-Type", "image/"] in widget.get_conditions( "image/*" ) widget = ClearableFileInput(attrs={"accept": "image/jpeg"}) assert 'accept="image/jpeg"' in widget.render(name="file", value="test.jpg") assert {"Content-Type": "image/jpeg"} in widget.get_conditions("image/jpeg") widget = ClearableFileInput(attrs={"accept": "application/pdf,image/*"}) assert 'accept="application/pdf,image/*"' in widget.render( name="file", value="test.jpg", ) assert ["starts-with", "$Content-Type", ""] in widget.get_conditions( "application/pdf,image/*" ) assert {"Content-Type": "application/pdf"} not in widget.get_conditions( "application/pdf,image/*" ) def test_no_js_error(self, driver, live_server): driver.get(live_server + self.url) with pytest.raises(NoSuchElementException): error = driver.find_element(By.XPATH, "//body[@JSError]") pytest.fail(error.get_attribute("JSError")) def test_file_insert( self, request, driver, live_server, upload_file, freeze_upload_folder ): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" with wait_for_page_load(driver, timeout=10): file_input.submit() assert storage.exists("tmp/s3file/%s.txt" % request.node.name) with pytest.raises(NoSuchElementException): error = driver.find_element(By.XPATH, "//body[@JSError]") pytest.fail(error.get_attribute("JSError")) def test_file_insert_submit_value( self, driver, live_server, upload_file, freeze_upload_folder ): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//input[@name='save']") with wait_for_page_load(driver, timeout=10): save_button.click() assert "save" in driver.page_source driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//button[@name='save_continue']") with wait_for_page_load(driver, timeout=10): save_button.click() assert "save_continue" in driver.page_source assert "continue_value" in driver.page_source def test_progress(self, driver, live_server, upload_file, freeze_upload_folder): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//input[@name='save']") with wait_for_page_load(driver, timeout=10): save_button.click() assert "save" in driver.page_source driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//button[@name='save_continue']") with wait_for_page_load(driver, timeout=10): save_button.click() response = json.loads(driver.find_elements(By.CSS_SELECTOR, "pre")[0].text) assert response["POST"]["progress"] == "1" def test_multi_file( self, driver, live_server, freeze_upload_folder, upload_file, another_upload_file, yet_another_upload_file, ): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys( " \n ".join( [ str(freeze_upload_folder / upload_file), str(freeze_upload_folder / another_upload_file), ] ) ) file_input = driver.find_element(By.XPATH, "//input[@name='other_file']") file_input.send_keys(str(freeze_upload_folder / yet_another_upload_file)) save_button = driver.find_element(By.XPATH, "//input[@name='save']") with wait_for_page_load(driver, timeout=10): save_button.click() response = json.loads(driver.find_elements(By.CSS_SELECTOR, "pre")[0].text) assert response["FILES"] == { "file": [ os.path.basename(upload_file), os.path.basename(another_upload_file), ], "other_file": [os.path.basename(yet_another_upload_file)], } def test_media(self): assert ClearableFileInput().media._js == ["s3file/js/s3file.js"] def test_upload_folder(self): assert "custom/location/tmp/s3file/" in ClearableFileInput().upload_folder assert len(os.path.basename(ClearableFileInput().upload_folder)) == 22
path_disclosure
{ "code": [ " @pytest.fixture", " def freeze(self, monkeypatch):", " monkeypatch.setattr(", " \"s3file.forms.S3FileInputMixin.upload_folder\",", " os.path.join(storage.aws_location, \"tmp\"),", " )", " def test_value_from_datadict(self, client, upload_file):", " print(storage.location)", " uploaded_file = storage.save(\"test.jpg\", f)", " \"file\": json.dumps([uploaded_file]),", " \"s3file\": '[\"file\"]',", " def test_build_attr(self):", " def test_get_conditions(self, freeze):", " [\"starts-with\", \"$key\", \"custom/location/tmp\"],", " def test_file_insert(self, request, driver, live_server, upload_file, freeze):", " assert storage.exists(\"tmp/%s.txt\" % request.node.name)", " def test_file_insert_submit_value(self, driver, live_server, upload_file, freeze):", " def test_progress(self, driver, live_server, upload_file, freeze):", " freeze,", " file_input.send_keys(\" \\n \".join([upload_file, another_upload_file]))", " file_input.send_keys(yet_another_upload_file)" ], "line_no": [ 34, 35, 37, 38, 39, 40, 42, 43, 45, 49, 50, 85, 102, 109, 148, 155, 161, 181, 205, 212, 214 ] }
{ "code": [ " def test_value_from_datadict(self, freeze_upload_folder, client, upload_file):", " \"file\": f\"custom/location/{uploaded_file}\",", " \"s3file\": \"file\",", " def test_build_attr(self, freeze_upload_folder):", " \"data-s3f-signature\",", " assert (", " ClearableFileInput().build_attrs({})[\"data-s3f-signature\"]", " == \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\"", " )", " def test_get_conditions(self, freeze_upload_folder):", " [\"starts-with\", \"$key\", \"custom/location/tmp/s3file\"],", " def test_file_insert(", " self, request, driver, live_server, upload_file, freeze_upload_folder", " assert storage.exists(\"tmp/s3file/%s.txt\" % request.node.name)", " self, driver, live_server, upload_file, freeze_upload_folder", " ):", " def test_progress(self, driver, live_server, upload_file, freeze_upload_folder):", " freeze_upload_folder,", " file_input.send_keys(", " \" \\n \".join(", " [", " str(freeze_upload_folder / upload_file),", " str(freeze_upload_folder / another_upload_file),", " ]", " )", " )", " file_input.send_keys(str(freeze_upload_folder / yet_another_upload_file))" ], "line_no": [ 34, 40, 42, 77, 87, 89, 90, 91, 92, 99, 106, 145, 146, 154, 161, 162, 182, 206, 213, 214, 215, 216, 217, 218, 219, 220, 222 ] }
import json import os from contextlib import contextmanager import pytest from django.forms import ClearableFileInput from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.expected_conditions import staleness_of from selenium.webdriver.support.wait import WebDriverWait from s3file.storages import storage from tests.testapp.forms import UploadForm try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse @contextmanager def FUNC_0(VAR_0, VAR_1=30): VAR_2 = VAR_0.find_element(By.TAG_NAME, "html") yield WebDriverWait(VAR_0, VAR_1).until(staleness_of(VAR_2)) class CLASS_0: @property def FUNC_1(self): return reverse("upload") @pytest.fixture def VAR_7(self, VAR_3): VAR_3.setattr( "s3file.forms.S3FileInputMixin.upload_folder", os.path.join(storage.aws_location, "tmp"), ) def FUNC_3(self, VAR_4, VAR_5): print(storage.location) with open(VAR_5) as f: VAR_18 = storage.save("test.jpg", f) VAR_12 = VAR_4.post( reverse("upload"), { "file": json.dumps([VAR_18]), "s3file": '["file"]', }, ) assert VAR_12.status_code == 201 def FUNC_4(self, VAR_6): VAR_13 = UploadForm(instance=VAR_6) assert VAR_6.file.name in VAR_13.as_p(), VAR_13.as_p() assert not VAR_13.is_valid() def FUNC_5(self, VAR_6): VAR_13 = UploadForm( data={"file": "foo.bar", "s3file": "file"}, instance=VAR_6, ) assert VAR_13.is_valid() assert VAR_13.cleaned_data["file"] == VAR_6.file def FUNC_6(self, VAR_6): VAR_13 = UploadForm(data={"file": ""}, instance=VAR_6) assert VAR_13.is_valid(), VAR_13.errors assert not VAR_13.has_changed() assert VAR_13.cleaned_data["file"] == VAR_6.file def FUNC_7(self, VAR_6): VAR_13 = UploadForm(data={"file": ""}, instance=VAR_6) assert VAR_13.is_valid() assert VAR_13.cleaned_data["file"] == VAR_6.file def FUNC_8(self, VAR_6): VAR_13 = UploadForm(data={"file-clear": "1"}, instance=VAR_6) assert VAR_13.is_valid() assert not VAR_13.cleaned_data["file"] def FUNC_9(self): assert set(ClearableFileInput().build_attrs({}).keys()) == { "class", "data-url", "data-fields-x-amz-algorithm", "data-fields-x-amz-date", "data-fields-x-amz-signature", "data-fields-x-amz-credential", "data-fields-policy", "data-fields-key", } assert ClearableFileInput().build_attrs({})["class"] == "s3file" assert ( ClearableFileInput().build_attrs({"class": "my-class"})["class"] == "my-class s3file" ) def FUNC_10(self, VAR_7): VAR_14 = ClearableFileInput().get_conditions(None) assert all( condition in VAR_14 for condition in [ {"bucket": "test-bucket"}, {"success_action_status": "201"}, ["starts-with", "$key", "custom/location/tmp"], ["starts-with", "$Content-Type", ""], ] ), VAR_14 def FUNC_11(self): VAR_15 = ClearableFileInput() assert "accept" not in VAR_15.render(name="file", value="test.jpg") assert ["starts-with", "$Content-Type", ""] in VAR_15.get_conditions(None) VAR_15 = ClearableFileInput(attrs={"accept": "image/*"}) assert 'accept="image/*"' in VAR_15.render(name="file", value="test.jpg") assert ["starts-with", "$Content-Type", "image/"] in VAR_15.get_conditions( "image/*" ) VAR_15 = ClearableFileInput(attrs={"accept": "image/jpeg"}) assert 'accept="image/jpeg"' in VAR_15.render(name="file", value="test.jpg") assert {"Content-Type": "image/jpeg"} in VAR_15.get_conditions("image/jpeg") VAR_15 = ClearableFileInput(attrs={"accept": "application/pdf,image/*"}) assert 'accept="application/pdf,image/*"' in VAR_15.render( name="file", value="test.jpg", ) assert ["starts-with", "$Content-Type", ""] in VAR_15.get_conditions( "application/pdf,image/*" ) assert {"Content-Type": "application/pdf"} not in VAR_15.get_conditions( "application/pdf,image/*" ) def FUNC_12(self, VAR_0, VAR_8): VAR_0.get(VAR_8 + self.url) with pytest.raises(NoSuchElementException): VAR_19 = VAR_0.find_element(By.XPATH, "//body[@JSError]") pytest.fail(VAR_19.get_attribute("JSError")) def FUNC_13(self, VAR_9, VAR_0, VAR_8, VAR_5, VAR_7): VAR_0.get(VAR_8 + self.url) VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_16.send_keys(VAR_5) assert VAR_16.get_attribute("name") == "file" with FUNC_0(VAR_0, VAR_1=10): VAR_16.submit() assert storage.exists("tmp/%s.txt" % VAR_9.node.name) with pytest.raises(NoSuchElementException): VAR_19 = VAR_0.find_element(By.XPATH, "//body[@JSError]") pytest.fail(VAR_19.get_attribute("JSError")) def FUNC_14(self, VAR_0, VAR_8, VAR_5, VAR_7): VAR_0.get(VAR_8 + self.url) VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_16.send_keys(VAR_5) assert VAR_16.get_attribute("name") == "file" VAR_17 = VAR_0.find_element(By.XPATH, "//input[@name='save']") with FUNC_0(VAR_0, VAR_1=10): VAR_17.click() assert "save" in VAR_0.page_source VAR_0.get(VAR_8 + self.url) VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_16.send_keys(VAR_5) assert VAR_16.get_attribute("name") == "file" VAR_17 = VAR_0.find_element(By.XPATH, "//button[@name='save_continue']") with FUNC_0(VAR_0, VAR_1=10): VAR_17.click() assert "save_continue" in VAR_0.page_source assert "continue_value" in VAR_0.page_source def FUNC_15(self, VAR_0, VAR_8, VAR_5, VAR_7): VAR_0.get(VAR_8 + self.url) VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_16.send_keys(VAR_5) assert VAR_16.get_attribute("name") == "file" VAR_17 = VAR_0.find_element(By.XPATH, "//input[@name='save']") with FUNC_0(VAR_0, VAR_1=10): VAR_17.click() assert "save" in VAR_0.page_source VAR_0.get(VAR_8 + self.url) VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_16.send_keys(VAR_5) assert VAR_16.get_attribute("name") == "file" VAR_17 = VAR_0.find_element(By.XPATH, "//button[@name='save_continue']") with FUNC_0(VAR_0, VAR_1=10): VAR_17.click() VAR_12 = json.loads(VAR_0.find_elements(By.CSS_SELECTOR, "pre")[0].text) assert VAR_12["POST"]["progress"] == "1" def FUNC_16( self, VAR_0, VAR_8, VAR_7, VAR_5, VAR_10, VAR_11, ): VAR_0.get(VAR_8 + self.url) VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_16.send_keys(" \n ".join([VAR_5, VAR_10])) VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='other_file']") VAR_16.send_keys(VAR_11) VAR_17 = VAR_0.find_element(By.XPATH, "//input[@name='save']") with FUNC_0(VAR_0, VAR_1=10): VAR_17.click() VAR_12 = json.loads(VAR_0.find_elements(By.CSS_SELECTOR, "pre")[0].text) assert VAR_12["FILES"] == { "file": [ os.path.basename(VAR_5), os.path.basename(VAR_10), ], "other_file": [os.path.basename(VAR_11)], } def FUNC_17(self): assert ClearableFileInput().media._js == ["s3file/js/s3file.js"] def FUNC_18(self): assert "custom/location/tmp/s3file/" in ClearableFileInput().upload_folder assert len(os.path.basename(ClearableFileInput().upload_folder)) == 22
import json import os from contextlib import contextmanager import pytest from django.forms import ClearableFileInput from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.expected_conditions import staleness_of from selenium.webdriver.support.wait import WebDriverWait from s3file.storages import storage from tests.testapp.forms import UploadForm try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse @contextmanager def FUNC_0(VAR_0, VAR_1=30): VAR_2 = VAR_0.find_element(By.TAG_NAME, "html") yield WebDriverWait(VAR_0, VAR_1).until(staleness_of(VAR_2)) class CLASS_0: @property def FUNC_1(self): return reverse("upload") def FUNC_2(self, VAR_3, VAR_4, VAR_5): with open(VAR_5) as f: VAR_17 = storage.save(VAR_3 / "test.jpg", f) VAR_11 = VAR_4.post( reverse("upload"), { "file": f"custom/location/{VAR_17}", "file-s3f-signature": "m94qBxBsnMIuIICiY133kX18KkllSPMVbhGAdAwNn1A", "s3file": "file", }, ) assert VAR_11.status_code == 201 def FUNC_3(self, VAR_6): VAR_12 = UploadForm(instance=VAR_6) assert VAR_6.file.name in VAR_12.as_p(), VAR_12.as_p() assert not VAR_12.is_valid() def FUNC_4(self, VAR_6): VAR_12 = UploadForm( data={"file": "foo.bar", "s3file": "file"}, instance=VAR_6, ) assert VAR_12.is_valid() assert VAR_12.cleaned_data["file"] == VAR_6.file def FUNC_5(self, VAR_6): VAR_12 = UploadForm(data={"file": ""}, instance=VAR_6) assert VAR_12.is_valid(), VAR_12.errors assert not VAR_12.has_changed() assert VAR_12.cleaned_data["file"] == VAR_6.file def FUNC_6(self, VAR_6): VAR_12 = UploadForm(data={"file": ""}, instance=VAR_6) assert VAR_12.is_valid() assert VAR_12.cleaned_data["file"] == VAR_6.file def FUNC_7(self, VAR_6): VAR_12 = UploadForm(data={"file-clear": "1"}, instance=VAR_6) assert VAR_12.is_valid() assert not VAR_12.cleaned_data["file"] def FUNC_8(self, VAR_3): assert set(ClearableFileInput().build_attrs({}).keys()) == { "class", "data-url", "data-fields-x-amz-algorithm", "data-fields-x-amz-date", "data-fields-x-amz-signature", "data-fields-x-amz-credential", "data-fields-policy", "data-fields-key", "data-s3f-signature", } assert ( ClearableFileInput().build_attrs({})["data-s3f-signature"] == "tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc" ) assert ClearableFileInput().build_attrs({})["class"] == "s3file" assert ( ClearableFileInput().build_attrs({"class": "my-class"})["class"] == "my-class s3file" ) def FUNC_9(self, VAR_3): VAR_13 = ClearableFileInput().get_conditions(None) assert all( condition in VAR_13 for condition in [ {"bucket": "test-bucket"}, {"success_action_status": "201"}, ["starts-with", "$key", "custom/location/tmp/s3file"], ["starts-with", "$Content-Type", ""], ] ), VAR_13 def FUNC_10(self): VAR_14 = ClearableFileInput() assert "accept" not in VAR_14.render(name="file", value="test.jpg") assert ["starts-with", "$Content-Type", ""] in VAR_14.get_conditions(None) VAR_14 = ClearableFileInput(attrs={"accept": "image/*"}) assert 'accept="image/*"' in VAR_14.render(name="file", value="test.jpg") assert ["starts-with", "$Content-Type", "image/"] in VAR_14.get_conditions( "image/*" ) VAR_14 = ClearableFileInput(attrs={"accept": "image/jpeg"}) assert 'accept="image/jpeg"' in VAR_14.render(name="file", value="test.jpg") assert {"Content-Type": "image/jpeg"} in VAR_14.get_conditions("image/jpeg") VAR_14 = ClearableFileInput(attrs={"accept": "application/pdf,image/*"}) assert 'accept="application/pdf,image/*"' in VAR_14.render( name="file", value="test.jpg", ) assert ["starts-with", "$Content-Type", ""] in VAR_14.get_conditions( "application/pdf,image/*" ) assert {"Content-Type": "application/pdf"} not in VAR_14.get_conditions( "application/pdf,image/*" ) def FUNC_11(self, VAR_0, VAR_7): VAR_0.get(VAR_7 + self.url) with pytest.raises(NoSuchElementException): VAR_18 = VAR_0.find_element(By.XPATH, "//body[@JSError]") pytest.fail(VAR_18.get_attribute("JSError")) def FUNC_12( self, VAR_8, VAR_0, VAR_7, VAR_5, VAR_3 ): VAR_0.get(VAR_7 + self.url) VAR_15 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_15.send_keys(VAR_5) assert VAR_15.get_attribute("name") == "file" with FUNC_0(VAR_0, VAR_1=10): VAR_15.submit() assert storage.exists("tmp/s3file/%s.txt" % VAR_8.node.name) with pytest.raises(NoSuchElementException): VAR_18 = VAR_0.find_element(By.XPATH, "//body[@JSError]") pytest.fail(VAR_18.get_attribute("JSError")) def FUNC_13( self, VAR_0, VAR_7, VAR_5, VAR_3 ): VAR_0.get(VAR_7 + self.url) VAR_15 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_15.send_keys(VAR_5) assert VAR_15.get_attribute("name") == "file" VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='save']") with FUNC_0(VAR_0, VAR_1=10): VAR_16.click() assert "save" in VAR_0.page_source VAR_0.get(VAR_7 + self.url) VAR_15 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_15.send_keys(VAR_5) assert VAR_15.get_attribute("name") == "file" VAR_16 = VAR_0.find_element(By.XPATH, "//button[@name='save_continue']") with FUNC_0(VAR_0, VAR_1=10): VAR_16.click() assert "save_continue" in VAR_0.page_source assert "continue_value" in VAR_0.page_source def FUNC_14(self, VAR_0, VAR_7, VAR_5, VAR_3): VAR_0.get(VAR_7 + self.url) VAR_15 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_15.send_keys(VAR_5) assert VAR_15.get_attribute("name") == "file" VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='save']") with FUNC_0(VAR_0, VAR_1=10): VAR_16.click() assert "save" in VAR_0.page_source VAR_0.get(VAR_7 + self.url) VAR_15 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_15.send_keys(VAR_5) assert VAR_15.get_attribute("name") == "file" VAR_16 = VAR_0.find_element(By.XPATH, "//button[@name='save_continue']") with FUNC_0(VAR_0, VAR_1=10): VAR_16.click() VAR_11 = json.loads(VAR_0.find_elements(By.CSS_SELECTOR, "pre")[0].text) assert VAR_11["POST"]["progress"] == "1" def FUNC_15( self, VAR_0, VAR_7, VAR_3, VAR_5, VAR_9, VAR_10, ): VAR_0.get(VAR_7 + self.url) VAR_15 = VAR_0.find_element(By.XPATH, "//input[@name='file']") VAR_15.send_keys( " \n ".join( [ str(VAR_3 / VAR_5), str(VAR_3 / VAR_9), ] ) ) VAR_15 = VAR_0.find_element(By.XPATH, "//input[@name='other_file']") VAR_15.send_keys(str(VAR_3 / VAR_10)) VAR_16 = VAR_0.find_element(By.XPATH, "//input[@name='save']") with FUNC_0(VAR_0, VAR_1=10): VAR_16.click() VAR_11 = json.loads(VAR_0.find_elements(By.CSS_SELECTOR, "pre")[0].text) assert VAR_11["FILES"] == { "file": [ os.path.basename(VAR_5), os.path.basename(VAR_9), ], "other_file": [os.path.basename(VAR_10)], } def FUNC_16(self): assert ClearableFileInput().media._js == ["s3file/js/s3file.js"] def FUNC_17(self): assert "custom/location/tmp/s3file/" in ClearableFileInput().upload_folder assert len(os.path.basename(ClearableFileInput().upload_folder)) == 22
[ 4, 11, 14, 18, 20, 21, 27, 28, 33, 41, 53, 55, 60, 68, 74, 79, 84, 101, 113, 118, 124, 128, 140, 143, 147, 156, 160, 170, 180, 190, 200, 226, 229, 233, 36 ]
[ 4, 11, 14, 18, 20, 21, 27, 28, 33, 45, 47, 52, 60, 66, 71, 76, 98, 110, 115, 121, 125, 137, 140, 144, 155, 159, 171, 181, 191, 201, 234, 237, 241 ]
5CWE-94
""" Classes for Repo providers. Subclass the base class, ``RepoProvider``, to support different version control services and providers. .. note:: When adding a new repo provider, add it to the allowed values for repo providers in event-schemas/launch.json. """ from datetime import timedelta, datetime, timezone import json import os import time import urllib.parse import re import subprocess import escapism from prometheus_client import Gauge from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest from tornado.httputil import url_concat from traitlets import Dict, Unicode, Bool, default, List from traitlets.config import LoggingConfigurable from .utils import Cache GITHUB_RATE_LIMIT = Gauge('binderhub_github_rate_limit_remaining', 'GitHub rate limit remaining') SHA1_PATTERN = re.compile(r'[0-9a-f]{40}') def tokenize_spec(spec): """Tokenize a GitHub-style spec into parts, error if spec invalid.""" spec_parts = spec.split('/', 2) # allow ref to contain "/" if len(spec_parts) != 3: msg = 'Spec is not of the form "user/repo/ref", provided: "{spec}".'.format(spec=spec) if len(spec_parts) == 2 and spec_parts[-1] != 'master': msg += ' Did you mean "{spec}/master"?'.format(spec=spec) raise ValueError(msg) return spec_parts def strip_suffix(text, suffix): if text.endswith(suffix): text = text[:-(len(suffix))] return text class RepoProvider(LoggingConfigurable): """Base class for a repo provider""" name = Unicode( help=""" Descriptive human readable name of this repo provider. """ ) spec = Unicode( help=""" The spec for this builder to parse """ ) banned_specs = List( help=""" List of specs to blacklist building. Should be a list of regexes (not regex objects) that match specs which should be blacklisted """, config=True ) high_quota_specs = List( help=""" List of specs to assign a higher quota limit. Should be a list of regexes (not regex objects) that match specs which should have a higher quota """, config=True ) spec_config = List( help=""" List of dictionaries that define per-repository configuration. Each item in the list is a dictionary with two keys: pattern : string defines a regex pattern (not a regex object) that matches specs. config : dict a dictionary of "config_name: config_value" pairs that will be applied to any repository that matches `pattern` """, config=True ) unresolved_ref = Unicode() git_credentials = Unicode( "", help=""" Credentials (if any) to pass to git when cloning. """, config=True ) def is_banned(self): """ Return true if the given spec has been banned """ for banned in self.banned_specs: # Ignore case, because most git providers do not # count DS-100/textbook as different from ds-100/textbook if re.match(banned, self.spec, re.IGNORECASE): return True return False def has_higher_quota(self): """ Return true if the given spec has a higher quota """ for higher_quota in self.high_quota_specs: # Ignore case, because most git providers do not # count DS-100/textbook as different from ds-100/textbook if re.match(higher_quota, self.spec, re.IGNORECASE): return True return False def repo_config(self, settings): """ Return configuration for this repository. """ repo_config = {} # Defaults and simple overrides if self.has_higher_quota(): repo_config['quota'] = settings.get('per_repo_quota_higher') else: repo_config['quota'] = settings.get('per_repo_quota') # Spec regex-based configuration for item in self.spec_config: pattern = item.get('pattern', None) config = item.get('config', None) if not isinstance(pattern, str): raise ValueError( "Spec-pattern configuration expected " "a regex pattern string, not " "type %s" % type(pattern)) if not isinstance(config, dict): raise ValueError( "Spec-pattern configuration expected " "a specification configuration dict, not " "type %s" % type(config)) # Ignore case, because most git providers do not # count DS-100/textbook as different from ds-100/textbook if re.match(pattern, self.spec, re.IGNORECASE): repo_config.update(config) return repo_config async def get_resolved_ref(self): raise NotImplementedError("Must be overridden in child class") async def get_resolved_spec(self): """Return the spec with resolved ref.""" raise NotImplementedError("Must be overridden in child class") def get_repo_url(self): """Return the git clone-able repo URL""" raise NotImplementedError("Must be overridden in the child class") async def get_resolved_ref_url(self): """Return the URL of repository at this commit in history""" raise NotImplementedError("Must be overridden in child class") def get_build_slug(self): """Return a unique build slug""" raise NotImplementedError("Must be overriden in the child class") @staticmethod def sha1_validate(sha1): if not SHA1_PATTERN.match(sha1): raise ValueError("resolved_ref is not a valid sha1 hexadecimal hash") class FakeProvider(RepoProvider): """Fake provider for local testing of the UI """ labels = { "text": "Fake Provider", "tag_text": "Fake Ref", "ref_prop_disabled": True, "label_prop_disabled": True, } async def get_resolved_ref(self): return "1a2b3c4d5e6f" async def get_resolved_spec(self): return "fake/repo/1a2b3c4d5e6f" def get_repo_url(self): return "https://example.com/fake/repo.git" async def get_resolved_ref_url(self): return "https://example.com/fake/repo/tree/1a2b3c4d5e6f" def get_build_slug(self): return '{user}-{repo}'.format(user='Rick', repo='Morty') class ZenodoProvider(RepoProvider): """Provide contents of a Zenodo record Users must provide a spec consisting of the Zenodo DOI. """ name = Unicode("Zenodo") display_name = "Zenodo DOI" labels = { "text": "Zenodo DOI (10.5281/zenodo.3242074)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def get_resolved_ref(self): client = AsyncHTTPClient() req = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") r = await client.fetch(req) self.record_id = r.effective_url.rsplit("/", maxsplit=1)[1] return self.record_id async def get_resolved_spec(self): if not hasattr(self, 'record_id'): self.record_id = await self.get_resolved_ref() # zenodo registers a DOI which represents all versions of a software package # and it always resolves to latest version # for that case, we have to replace the version number in DOIs with # the specific (resolved) version (record_id) resolved_spec = self.spec.split("zenodo")[0] + "zenodo." + self.record_id return resolved_spec def get_repo_url(self): # While called repo URL, the return value of this function is passed # as argument to repo2docker, hence we return the spec as is. return self.spec async def get_resolved_ref_url(self): resolved_spec = await self.get_resolved_spec() return f"https://doi.org/{resolved_spec}" def get_build_slug(self): return "zenodo-{}".format(self.record_id) class FigshareProvider(RepoProvider): """Provide contents of a Figshare article Users must provide a spec consisting of the Figshare DOI. """ name = Unicode("Figshare") display_name = "Figshare DOI" url_regex = re.compile(r"(.*)/articles/([^/]+)/([^/]+)/(\d+)(/)?(\d+)?") labels = { "text": "Figshare DOI (10.6084/m9.figshare.9782777.v1)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def get_resolved_ref(self): client = AsyncHTTPClient() req = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") r = await client.fetch(req) match = self.url_regex.match(r.effective_url) article_id = match.groups()[3] article_version = match.groups()[5] if not article_version: article_version = "1" self.record_id = "{}.v{}".format(article_id, article_version) return self.record_id async def get_resolved_spec(self): if not hasattr(self, 'record_id'): self.record_id = await self.get_resolved_ref() # spec without version is accepted as version 1 - check get_resolved_ref method # for that case, we have to replace the version number in DOIs with # the specific (resolved) version (record_id) resolved_spec = self.spec.split("figshare")[0] + "figshare." + self.record_id return resolved_spec def get_repo_url(self): # While called repo URL, the return value of this function is passed # as argument to repo2docker, hence we return the spec as is. return self.spec async def get_resolved_ref_url(self): resolved_spec = await self.get_resolved_spec() return f"https://doi.org/{resolved_spec}" def get_build_slug(self): return "figshare-{}".format(self.record_id) class DataverseProvider(RepoProvider): name = Unicode("Dataverse") display_name = "Dataverse DOI" labels = { "text": "Dataverse DOI (10.7910/DVN/TJCLKP)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def get_resolved_ref(self): client = AsyncHTTPClient() req = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") r = await client.fetch(req) search_url = urllib.parse.urlunparse( urllib.parse.urlparse(r.effective_url)._replace( path="/api/datasets/:persistentId" ) ) req = HTTPRequest(search_url, user_agent="BinderHub") r = await client.fetch(req) resp = json.loads(r.body) assert resp["status"] == "OK" self.identifier = resp["data"]["identifier"] self.record_id = "{datasetId}.v{major}.{minor}".format( datasetId=resp["data"]["id"], major=resp["data"]["latestVersion"]["versionNumber"], minor=resp["data"]["latestVersion"]["versionMinorNumber"], ) # NOTE: data.protocol should be potentially prepended here # {protocol}:{authority}/{identifier} self.resolved_spec = "{authority}/{identifier}".format( authority=resp["data"]["authority"], identifier=resp["data"]["identifier"], ) self.resolved_ref_url = resp["data"]["persistentUrl"] return self.record_id async def get_resolved_spec(self): if not hasattr(self, 'resolved_spec'): await self.get_resolved_ref() return self.resolved_spec async def get_resolved_ref_url(self): if not hasattr(self, 'resolved_ref_url'): await self.get_resolved_ref() return self.resolved_ref_url def get_repo_url(self): # While called repo URL, the return value of this function is passed # as argument to repo2docker, hence we return the spec as is. return self.spec def get_build_slug(self): return "dataverse-" + escapism.escape(self.identifier, escape_char="-").lower() class HydroshareProvider(RepoProvider): """Provide contents of a Hydroshare resource Users must provide a spec consisting of the Hydroshare resource id. """ name = Unicode("Hydroshare") display_name = "Hydroshare resource" url_regex = re.compile(r".*([0-9a-f]{32}).*") labels = { "text": "Hydroshare resource id or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } def _parse_resource_id(self, spec): match = self.url_regex.match(spec) if not match: raise ValueError("The specified Hydroshare resource id was not recognized.") resource_id = match.groups()[0] return resource_id async def get_resolved_ref(self): client = AsyncHTTPClient() self.resource_id = self._parse_resource_id(self.spec) req = HTTPRequest("https://www.hydroshare.org/hsapi/resource/{}/scimeta/elements".format(self.resource_id), user_agent="BinderHub") r = await client.fetch(req) def parse_date(json_body): json_response = json.loads(json_body) date = next( item for item in json_response["dates"] if item["type"] == "modified" )["start_date"] # Hydroshare timestamp always returns the same timezone, so strip it date = date.split(".")[0] parsed_date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S") epoch = parsed_date.replace(tzinfo=timezone(timedelta(0))).timestamp() # truncate the timestamp return str(int(epoch)) # date last updated is only good for the day... probably need something finer eventually self.record_id = "{}.v{}".format(self.resource_id, parse_date(r.body)) return self.record_id async def get_resolved_spec(self): # Hydroshare does not provide a history, resolves to repo url return self.get_repo_url() async def get_resolved_ref_url(self): # Hydroshare does not provide a history, resolves to repo url return self.get_repo_url() def get_repo_url(self): self.resource_id = self._parse_resource_id(self.spec) return "https://www.hydroshare.org/resource/{}".format(self.resource_id) def get_build_slug(self): return "hydroshare-{}".format(self.record_id) class GitRepoProvider(RepoProvider): """Bare bones git repo provider. Users must provide a spec of the following form. <url-escaped-namespace>/<unresolved_ref> <url-escaped-namespace>/<resolved_ref> eg: https%3A%2F%2Fgithub.com%2Fjupyterhub%2Fzero-to-jupyterhub-k8s/master https%3A%2F%2Fgithub.com%2Fjupyterhub%2Fzero-to-jupyterhub-k8s/f7f3ff6d1bf708bdc12e5f10e18b2a90a4795603 This provider is typically used if you are deploying binderhub yourself and you require access to repositories that are not in one of the supported providers. """ name = Unicode("Git") display_name = "Git repository" labels = { "text": "Arbitrary git repository URL (http://git.example.com/repo)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.url, unresolved_ref = self.spec.split('/', 1) self.repo = urllib.parse.unquote(self.url) self.unresolved_ref = urllib.parse.unquote(unresolved_ref) if not self.unresolved_ref: raise ValueError("`unresolved_ref` must be specified as a query parameter for the basic git provider") async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref try: # Check if the reference is a valid SHA hash self.sha1_validate(self.unresolved_ref) except ValueError: # The ref is a head/tag and we resolve it using `git ls-remote` command = ["git", "ls-remote", self.repo, self.unresolved_ref] result = subprocess.run(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.returncode: raise RuntimeError("Unable to run git ls-remote to get the `resolved_ref`: {}".format(result.stderr)) if not result.stdout: return None resolved_ref = result.stdout.split(None, 1)[0] self.sha1_validate(resolved_ref) self.resolved_ref = resolved_ref else: # The ref already was a valid SHA hash self.resolved_ref = self.unresolved_ref return self.resolved_ref async def get_resolved_spec(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.url}/{self.resolved_ref}" def get_repo_url(self): return self.repo async def get_resolved_ref_url(self): # not possible to construct ref url of unknown git provider return self.get_repo_url() def get_build_slug(self): return self.repo class GitLabRepoProvider(RepoProvider): """GitLab provider. GitLab allows nested namespaces (eg. root/project/component/repo) thus we need to urlescape the namespace of this repo. Users must provide a spec that matches the following form. <url-escaped-namespace>/<unresolved_ref> eg: group%2Fproject%2Frepo/master """ name = Unicode('GitLab') display_name = "GitLab.com" hostname = Unicode('gitlab.com', config=True, help="""The host of the GitLab instance For personal GitLab servers. """ ) access_token = Unicode(config=True, help="""GitLab OAuth2 access token for authentication with the GitLab API For use with client_secret. Loaded from GITLAB_ACCESS_TOKEN env by default. """ ) @default('access_token') def _access_token_default(self): return os.getenv('GITLAB_ACCESS_TOKEN', '') private_token = Unicode(config=True, help="""GitLab private token for authentication with the GitLab API Loaded from GITLAB_PRIVATE_TOKEN env by default. """ ) @default('private_token') def _private_token_default(self): return os.getenv('GITLAB_PRIVATE_TOKEN', '') auth = Dict( help="""Auth parameters for the GitLab API access Populated from access_token, private_token """ ) @default('auth') def _default_auth(self): auth = {} for key in ('access_token', 'private_token'): value = getattr(self, key) if value: auth[key] = value return auth @default('git_credentials') def _default_git_credentials(self): if self.private_token: return r'username=binderhub\npassword={token}'.format(token=self.private_token) return "" labels = { "text": "GitLab.com repository or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.quoted_namespace, unresolved_ref = self.spec.split('/', 1) self.namespace = urllib.parse.unquote(self.quoted_namespace) self.unresolved_ref = urllib.parse.unquote(unresolved_ref) if not self.unresolved_ref: raise ValueError("An unresolved ref is required") async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref namespace = urllib.parse.quote(self.namespace, safe='') client = AsyncHTTPClient() api_url = "https://{hostname}/api/v4/projects/{namespace}/repository/commits/{ref}".format( hostname=self.hostname, namespace=namespace, ref=urllib.parse.quote(self.unresolved_ref, safe=''), ) self.log.debug("Fetching %s", api_url) if self.auth: # Add auth params. After logging! api_url = url_concat(api_url, self.auth) try: resp = await client.fetch(api_url, user_agent="BinderHub") except HTTPError as e: if e.code == 404: return None else: raise ref_info = json.loads(resp.body.decode('utf-8')) self.resolved_ref = ref_info['id'] return self.resolved_ref async def get_resolved_spec(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.quoted_namespace}/{self.resolved_ref}" def get_build_slug(self): # escape the name and replace dashes with something else. return '-'.join(p.replace('-', '_-') for p in self.namespace.split('/')) def get_repo_url(self): return f"https://{self.hostname}/{self.namespace}.git" async def get_resolved_ref_url(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"https://{self.hostname}/{self.namespace}/tree/{self.resolved_ref}" class GitHubRepoProvider(RepoProvider): """Repo provider for the GitHub service""" name = Unicode('GitHub') display_name = 'GitHub' # shared cache for resolved refs cache = Cache(1024) # separate cache with max age for 404 results # 404s don't have ETags, so we want them to expire at some point # to avoid caching a 404 forever since e.g. a missing repo or branch # may be created later cache_404 = Cache(1024, max_age=300) hostname = Unicode('github.com', config=True, help="""The GitHub hostname to use Only necessary if not github.com, e.g. GitHub Enterprise. """) api_base_path = Unicode('https://api.{hostname}', config=True, help="""The base path of the GitHub API Only necessary if not github.com, e.g. GitHub Enterprise. Can use {hostname} for substitution, e.g. 'https://{hostname}/api/v3' """) client_id = Unicode(config=True, help="""GitHub client id for authentication with the GitHub API For use with client_secret. Loaded from GITHUB_CLIENT_ID env by default. """ ) @default('client_id') def _client_id_default(self): return os.getenv('GITHUB_CLIENT_ID', '') client_secret = Unicode(config=True, help="""GitHub client secret for authentication with the GitHub API For use with client_id. Loaded from GITHUB_CLIENT_SECRET env by default. """ ) @default('client_secret') def _client_secret_default(self): return os.getenv('GITHUB_CLIENT_SECRET', '') access_token = Unicode(config=True, help="""GitHub access token for authentication with the GitHub API Loaded from GITHUB_ACCESS_TOKEN env by default. """ ) @default('access_token') def _access_token_default(self): return os.getenv('GITHUB_ACCESS_TOKEN', '') @default('git_credentials') def _default_git_credentials(self): if self.access_token: # Based on https://github.com/blog/1270-easier-builds-and-deployments-using-git-over-https-and-oauth # If client_id is specified, assuming access_token is personal access token. Otherwise, # assume oauth basic token. if self.client_id: return r'username={client_id}\npassword={token}'.format( client_id=self.client_id, token=self.access_token) else: return r'username={token}\npassword=x-oauth-basic'.format(token=self.access_token) return "" labels = { "text": "GitHub repository name or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user, self.repo, self.unresolved_ref = tokenize_spec(self.spec) self.repo = strip_suffix(self.repo, ".git") def get_repo_url(self): return f"https://{self.hostname}/{self.user}/{self.repo}" async def get_resolved_ref_url(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"https://{self.hostname}/{self.user}/{self.repo}/tree/{self.resolved_ref}" async def github_api_request(self, api_url, etag=None): client = AsyncHTTPClient() request_kwargs = {} if self.client_id and self.client_secret: request_kwargs.update( dict(auth_username=self.client_id, auth_password=self.client_secret) ) headers = {} # based on: https://developer.github.com/v3/#oauth2-token-sent-in-a-header if self.access_token: headers['Authorization'] = "token {token}".format(token=self.access_token) if etag: headers['If-None-Match'] = etag req = HTTPRequest( api_url, headers=headers, user_agent="BinderHub", **request_kwargs ) try: resp = await client.fetch(req) except HTTPError as e: if e.code == 304: resp = e.response elif ( e.code == 403 and e.response and 'x-ratelimit-remaining' in e.response.headers and e.response.headers.get('x-ratelimit-remaining') == '0' ): rate_limit = e.response.headers['x-ratelimit-limit'] reset_timestamp = int(e.response.headers['x-ratelimit-reset']) reset_seconds = int(reset_timestamp - time.time()) self.log.error( "GitHub Rate limit ({limit}) exceeded. Reset in {delta}.".format( limit=rate_limit, delta=timedelta(seconds=reset_seconds), ) ) # round expiry up to nearest 5 minutes minutes_until_reset = 5 * (1 + (reset_seconds // 60 // 5)) raise ValueError("GitHub rate limit exceeded. Try again in %i minutes." % minutes_until_reset ) # Status 422 is returned by the API when we try and resolve a non # existent reference elif e.code in (404, 422): return None else: raise if 'x-ratelimit-remaining' in resp.headers: # record and log github rate limit remaining = int(resp.headers['x-ratelimit-remaining']) rate_limit = int(resp.headers['x-ratelimit-limit']) reset_timestamp = int(resp.headers['x-ratelimit-reset']) # record with prometheus GITHUB_RATE_LIMIT.set(remaining) # log at different levels, depending on remaining fraction fraction = remaining / rate_limit if fraction < 0.2: log = self.log.warning elif fraction < 0.5: log = self.log.info else: log = self.log.debug # str(timedelta) looks like '00:32' delta = timedelta(seconds=int(reset_timestamp - time.time())) log("GitHub rate limit remaining {remaining}/{limit}. Reset in {delta}.".format( remaining=remaining, limit=rate_limit, delta=delta, )) return resp async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref api_url = "{api_base_path}/repos/{user}/{repo}/commits/{ref}".format( api_base_path=self.api_base_path.format(hostname=self.hostname), user=self.user, repo=self.repo, ref=self.unresolved_ref ) self.log.debug("Fetching %s", api_url) cached = self.cache.get(api_url) if cached: etag = cached['etag'] self.log.debug("Cache hit for %s: %s", api_url, etag) else: cache_404 = self.cache_404.get(api_url) if cache_404: self.log.debug("Cache hit for 404 on %s", api_url) return None etag = None resp = await self.github_api_request(api_url, etag=etag) if resp is None: self.log.debug("Caching 404 on %s", api_url) self.cache_404.set(api_url, True) return None if resp.code == 304: self.log.info("Using cached ref for %s: %s", api_url, cached['sha']) self.resolved_ref = cached['sha'] # refresh cache entry self.cache.move_to_end(api_url) return self.resolved_ref elif cached: self.log.debug("Cache outdated for %s", api_url) ref_info = json.loads(resp.body.decode('utf-8')) if 'sha' not in ref_info: # TODO: Figure out if we should raise an exception instead? self.log.warning("No sha for %s in %s", api_url, ref_info) self.resolved_ref = None return None # store resolved ref and cache for later self.resolved_ref = ref_info['sha'] self.cache.set( api_url, { 'etag': resp.headers.get('ETag'), 'sha': self.resolved_ref, }, ) return self.resolved_ref async def get_resolved_spec(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.user}/{self.repo}/{self.resolved_ref}" def get_build_slug(self): return '{user}-{repo}'.format(user=self.user, repo=self.repo) class GistRepoProvider(GitHubRepoProvider): """GitHub gist provider. Users must provide a spec that matches the following form (similar to github) [https://gist.github.com/]<username>/<gist-id>[/<ref>] The ref is optional, valid values are - a full sha1 of a ref in the history - master If master or no ref is specified the latest revision will be used. """ name = Unicode("Gist") display_name = "Gist" hostname = Unicode("gist.github.com") allow_secret_gist = Bool( default_value=False, config=True, help="Flag for allowing usages of secret Gists. The default behavior is to disallow secret gists.", ) labels = { "text": "Gist ID (username/gistId) or URL", "tag_text": "Git commit SHA", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *args, **kwargs): # We dont need to initialize entirely the same as github super(RepoProvider, self).__init__(*args, **kwargs) parts = self.spec.split('/') self.user, self.gist_id, *_ = parts if len(parts) > 2: self.unresolved_ref = parts[2] else: self.unresolved_ref = '' def get_repo_url(self): return f'https://{self.hostname}/{self.user}/{self.gist_id}.git' async def get_resolved_ref_url(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f'https://{self.hostname}/{self.user}/{self.gist_id}/{self.resolved_ref}' async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref api_url = f"https://api.github.com/gists/{self.gist_id}" self.log.debug("Fetching %s", api_url) resp = await self.github_api_request(api_url) if resp is None: return None ref_info = json.loads(resp.body.decode('utf-8')) if (not self.allow_secret_gist) and (not ref_info['public']): raise ValueError("You seem to want to use a secret Gist, but do not have permission to do so. " "To enable secret Gist support, set (or have an administrator set) " "'GistRepoProvider.allow_secret_gist = True'") all_versions = [e['version'] for e in ref_info['history']] if self.unresolved_ref in {"", "HEAD", "master"}: self.resolved_ref = all_versions[0] else: if self.unresolved_ref not in all_versions: return None else: self.resolved_ref = self.unresolved_ref return self.resolved_ref async def get_resolved_spec(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f'{self.user}/{self.gist_id}/{self.resolved_ref}' def get_build_slug(self): return self.gist_id
""" Classes for Repo providers. Subclass the base class, ``RepoProvider``, to support different version control services and providers. .. note:: When adding a new repo provider, add it to the allowed values for repo providers in event-schemas/launch.json. """ from datetime import timedelta, datetime, timezone import json import os import time import urllib.parse import re import subprocess import escapism from prometheus_client import Gauge from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest from tornado.httputil import url_concat from traitlets import Dict, Unicode, Bool, default, List from traitlets.config import LoggingConfigurable from .utils import Cache GITHUB_RATE_LIMIT = Gauge('binderhub_github_rate_limit_remaining', 'GitHub rate limit remaining') SHA1_PATTERN = re.compile(r'[0-9a-f]{40}') def tokenize_spec(spec): """Tokenize a GitHub-style spec into parts, error if spec invalid.""" spec_parts = spec.split('/', 2) # allow ref to contain "/" if len(spec_parts) != 3: msg = 'Spec is not of the form "user/repo/ref", provided: "{spec}".'.format(spec=spec) if len(spec_parts) == 2 and spec_parts[-1] != 'master': msg += ' Did you mean "{spec}/master"?'.format(spec=spec) raise ValueError(msg) return spec_parts def strip_suffix(text, suffix): if text.endswith(suffix): text = text[:-(len(suffix))] return text class RepoProvider(LoggingConfigurable): """Base class for a repo provider""" name = Unicode( help=""" Descriptive human readable name of this repo provider. """ ) spec = Unicode( help=""" The spec for this builder to parse """ ) banned_specs = List( help=""" List of specs to blacklist building. Should be a list of regexes (not regex objects) that match specs which should be blacklisted """, config=True ) high_quota_specs = List( help=""" List of specs to assign a higher quota limit. Should be a list of regexes (not regex objects) that match specs which should have a higher quota """, config=True ) spec_config = List( help=""" List of dictionaries that define per-repository configuration. Each item in the list is a dictionary with two keys: pattern : string defines a regex pattern (not a regex object) that matches specs. config : dict a dictionary of "config_name: config_value" pairs that will be applied to any repository that matches `pattern` """, config=True ) unresolved_ref = Unicode() git_credentials = Unicode( "", help=""" Credentials (if any) to pass to git when cloning. """, config=True ) def is_banned(self): """ Return true if the given spec has been banned """ for banned in self.banned_specs: # Ignore case, because most git providers do not # count DS-100/textbook as different from ds-100/textbook if re.match(banned, self.spec, re.IGNORECASE): return True return False def has_higher_quota(self): """ Return true if the given spec has a higher quota """ for higher_quota in self.high_quota_specs: # Ignore case, because most git providers do not # count DS-100/textbook as different from ds-100/textbook if re.match(higher_quota, self.spec, re.IGNORECASE): return True return False def repo_config(self, settings): """ Return configuration for this repository. """ repo_config = {} # Defaults and simple overrides if self.has_higher_quota(): repo_config['quota'] = settings.get('per_repo_quota_higher') else: repo_config['quota'] = settings.get('per_repo_quota') # Spec regex-based configuration for item in self.spec_config: pattern = item.get('pattern', None) config = item.get('config', None) if not isinstance(pattern, str): raise ValueError( "Spec-pattern configuration expected " "a regex pattern string, not " "type %s" % type(pattern)) if not isinstance(config, dict): raise ValueError( "Spec-pattern configuration expected " "a specification configuration dict, not " "type %s" % type(config)) # Ignore case, because most git providers do not # count DS-100/textbook as different from ds-100/textbook if re.match(pattern, self.spec, re.IGNORECASE): repo_config.update(config) return repo_config async def get_resolved_ref(self): raise NotImplementedError("Must be overridden in child class") async def get_resolved_spec(self): """Return the spec with resolved ref.""" raise NotImplementedError("Must be overridden in child class") def get_repo_url(self): """Return the git clone-able repo URL""" raise NotImplementedError("Must be overridden in the child class") async def get_resolved_ref_url(self): """Return the URL of repository at this commit in history""" raise NotImplementedError("Must be overridden in child class") def get_build_slug(self): """Return a unique build slug""" raise NotImplementedError("Must be overriden in the child class") @staticmethod def sha1_validate(sha1): if not SHA1_PATTERN.match(sha1): raise ValueError("resolved_ref is not a valid sha1 hexadecimal hash") class FakeProvider(RepoProvider): """Fake provider for local testing of the UI """ labels = { "text": "Fake Provider", "tag_text": "Fake Ref", "ref_prop_disabled": True, "label_prop_disabled": True, } async def get_resolved_ref(self): return "1a2b3c4d5e6f" async def get_resolved_spec(self): return "fake/repo/1a2b3c4d5e6f" def get_repo_url(self): return "https://example.com/fake/repo.git" async def get_resolved_ref_url(self): return "https://example.com/fake/repo/tree/1a2b3c4d5e6f" def get_build_slug(self): return '{user}-{repo}'.format(user='Rick', repo='Morty') class ZenodoProvider(RepoProvider): """Provide contents of a Zenodo record Users must provide a spec consisting of the Zenodo DOI. """ name = Unicode("Zenodo") display_name = "Zenodo DOI" labels = { "text": "Zenodo DOI (10.5281/zenodo.3242074)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def get_resolved_ref(self): client = AsyncHTTPClient() req = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") r = await client.fetch(req) self.record_id = r.effective_url.rsplit("/", maxsplit=1)[1] return self.record_id async def get_resolved_spec(self): if not hasattr(self, 'record_id'): self.record_id = await self.get_resolved_ref() # zenodo registers a DOI which represents all versions of a software package # and it always resolves to latest version # for that case, we have to replace the version number in DOIs with # the specific (resolved) version (record_id) resolved_spec = self.spec.split("zenodo")[0] + "zenodo." + self.record_id return resolved_spec def get_repo_url(self): # While called repo URL, the return value of this function is passed # as argument to repo2docker, hence we return the spec as is. return self.spec async def get_resolved_ref_url(self): resolved_spec = await self.get_resolved_spec() return f"https://doi.org/{resolved_spec}" def get_build_slug(self): return "zenodo-{}".format(self.record_id) class FigshareProvider(RepoProvider): """Provide contents of a Figshare article Users must provide a spec consisting of the Figshare DOI. """ name = Unicode("Figshare") display_name = "Figshare DOI" url_regex = re.compile(r"(.*)/articles/([^/]+)/([^/]+)/(\d+)(/)?(\d+)?") labels = { "text": "Figshare DOI (10.6084/m9.figshare.9782777.v1)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def get_resolved_ref(self): client = AsyncHTTPClient() req = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") r = await client.fetch(req) match = self.url_regex.match(r.effective_url) article_id = match.groups()[3] article_version = match.groups()[5] if not article_version: article_version = "1" self.record_id = "{}.v{}".format(article_id, article_version) return self.record_id async def get_resolved_spec(self): if not hasattr(self, 'record_id'): self.record_id = await self.get_resolved_ref() # spec without version is accepted as version 1 - check get_resolved_ref method # for that case, we have to replace the version number in DOIs with # the specific (resolved) version (record_id) resolved_spec = self.spec.split("figshare")[0] + "figshare." + self.record_id return resolved_spec def get_repo_url(self): # While called repo URL, the return value of this function is passed # as argument to repo2docker, hence we return the spec as is. return self.spec async def get_resolved_ref_url(self): resolved_spec = await self.get_resolved_spec() return f"https://doi.org/{resolved_spec}" def get_build_slug(self): return "figshare-{}".format(self.record_id) class DataverseProvider(RepoProvider): name = Unicode("Dataverse") display_name = "Dataverse DOI" labels = { "text": "Dataverse DOI (10.7910/DVN/TJCLKP)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def get_resolved_ref(self): client = AsyncHTTPClient() req = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") r = await client.fetch(req) search_url = urllib.parse.urlunparse( urllib.parse.urlparse(r.effective_url)._replace( path="/api/datasets/:persistentId" ) ) req = HTTPRequest(search_url, user_agent="BinderHub") r = await client.fetch(req) resp = json.loads(r.body) assert resp["status"] == "OK" self.identifier = resp["data"]["identifier"] self.record_id = "{datasetId}.v{major}.{minor}".format( datasetId=resp["data"]["id"], major=resp["data"]["latestVersion"]["versionNumber"], minor=resp["data"]["latestVersion"]["versionMinorNumber"], ) # NOTE: data.protocol should be potentially prepended here # {protocol}:{authority}/{identifier} self.resolved_spec = "{authority}/{identifier}".format( authority=resp["data"]["authority"], identifier=resp["data"]["identifier"], ) self.resolved_ref_url = resp["data"]["persistentUrl"] return self.record_id async def get_resolved_spec(self): if not hasattr(self, 'resolved_spec'): await self.get_resolved_ref() return self.resolved_spec async def get_resolved_ref_url(self): if not hasattr(self, 'resolved_ref_url'): await self.get_resolved_ref() return self.resolved_ref_url def get_repo_url(self): # While called repo URL, the return value of this function is passed # as argument to repo2docker, hence we return the spec as is. return self.spec def get_build_slug(self): return "dataverse-" + escapism.escape(self.identifier, escape_char="-").lower() class HydroshareProvider(RepoProvider): """Provide contents of a Hydroshare resource Users must provide a spec consisting of the Hydroshare resource id. """ name = Unicode("Hydroshare") display_name = "Hydroshare resource" url_regex = re.compile(r".*([0-9a-f]{32}).*") labels = { "text": "Hydroshare resource id or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } def _parse_resource_id(self, spec): match = self.url_regex.match(spec) if not match: raise ValueError("The specified Hydroshare resource id was not recognized.") resource_id = match.groups()[0] return resource_id async def get_resolved_ref(self): client = AsyncHTTPClient() self.resource_id = self._parse_resource_id(self.spec) req = HTTPRequest("https://www.hydroshare.org/hsapi/resource/{}/scimeta/elements".format(self.resource_id), user_agent="BinderHub") r = await client.fetch(req) def parse_date(json_body): json_response = json.loads(json_body) date = next( item for item in json_response["dates"] if item["type"] == "modified" )["start_date"] # Hydroshare timestamp always returns the same timezone, so strip it date = date.split(".")[0] parsed_date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S") epoch = parsed_date.replace(tzinfo=timezone(timedelta(0))).timestamp() # truncate the timestamp return str(int(epoch)) # date last updated is only good for the day... probably need something finer eventually self.record_id = "{}.v{}".format(self.resource_id, parse_date(r.body)) return self.record_id async def get_resolved_spec(self): # Hydroshare does not provide a history, resolves to repo url return self.get_repo_url() async def get_resolved_ref_url(self): # Hydroshare does not provide a history, resolves to repo url return self.get_repo_url() def get_repo_url(self): self.resource_id = self._parse_resource_id(self.spec) return "https://www.hydroshare.org/resource/{}".format(self.resource_id) def get_build_slug(self): return "hydroshare-{}".format(self.record_id) class GitRepoProvider(RepoProvider): """Bare bones git repo provider. Users must provide a spec of the following form. <url-escaped-namespace>/<unresolved_ref> <url-escaped-namespace>/<resolved_ref> eg: https%3A%2F%2Fgithub.com%2Fjupyterhub%2Fzero-to-jupyterhub-k8s/master https%3A%2F%2Fgithub.com%2Fjupyterhub%2Fzero-to-jupyterhub-k8s/f7f3ff6d1bf708bdc12e5f10e18b2a90a4795603 This provider is typically used if you are deploying binderhub yourself and you require access to repositories that are not in one of the supported providers. """ name = Unicode("Git") display_name = "Git repository" labels = { "text": "Arbitrary git repository URL (http://git.example.com/repo)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.url, unresolved_ref = self.spec.split('/', 1) self.repo = urllib.parse.unquote(self.url) self.unresolved_ref = urllib.parse.unquote(unresolved_ref) if not self.unresolved_ref: raise ValueError("`unresolved_ref` must be specified as a query parameter for the basic git provider") async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref try: # Check if the reference is a valid SHA hash self.sha1_validate(self.unresolved_ref) except ValueError: # The ref is a head/tag and we resolve it using `git ls-remote` command = ["git", "ls-remote", "--", self.repo, self.unresolved_ref] result = subprocess.run(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.returncode: raise RuntimeError("Unable to run git ls-remote to get the `resolved_ref`: {}".format(result.stderr)) if not result.stdout: return None resolved_ref = result.stdout.split(None, 1)[0] self.sha1_validate(resolved_ref) self.resolved_ref = resolved_ref else: # The ref already was a valid SHA hash self.resolved_ref = self.unresolved_ref return self.resolved_ref async def get_resolved_spec(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.url}/{self.resolved_ref}" def get_repo_url(self): return self.repo async def get_resolved_ref_url(self): # not possible to construct ref url of unknown git provider return self.get_repo_url() def get_build_slug(self): return self.repo class GitLabRepoProvider(RepoProvider): """GitLab provider. GitLab allows nested namespaces (eg. root/project/component/repo) thus we need to urlescape the namespace of this repo. Users must provide a spec that matches the following form. <url-escaped-namespace>/<unresolved_ref> eg: group%2Fproject%2Frepo/master """ name = Unicode('GitLab') display_name = "GitLab.com" hostname = Unicode('gitlab.com', config=True, help="""The host of the GitLab instance For personal GitLab servers. """ ) access_token = Unicode(config=True, help="""GitLab OAuth2 access token for authentication with the GitLab API For use with client_secret. Loaded from GITLAB_ACCESS_TOKEN env by default. """ ) @default('access_token') def _access_token_default(self): return os.getenv('GITLAB_ACCESS_TOKEN', '') private_token = Unicode(config=True, help="""GitLab private token for authentication with the GitLab API Loaded from GITLAB_PRIVATE_TOKEN env by default. """ ) @default('private_token') def _private_token_default(self): return os.getenv('GITLAB_PRIVATE_TOKEN', '') auth = Dict( help="""Auth parameters for the GitLab API access Populated from access_token, private_token """ ) @default('auth') def _default_auth(self): auth = {} for key in ('access_token', 'private_token'): value = getattr(self, key) if value: auth[key] = value return auth @default('git_credentials') def _default_git_credentials(self): if self.private_token: return r'username=binderhub\npassword={token}'.format(token=self.private_token) return "" labels = { "text": "GitLab.com repository or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.quoted_namespace, unresolved_ref = self.spec.split('/', 1) self.namespace = urllib.parse.unquote(self.quoted_namespace) self.unresolved_ref = urllib.parse.unquote(unresolved_ref) if not self.unresolved_ref: raise ValueError("An unresolved ref is required") async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref namespace = urllib.parse.quote(self.namespace, safe='') client = AsyncHTTPClient() api_url = "https://{hostname}/api/v4/projects/{namespace}/repository/commits/{ref}".format( hostname=self.hostname, namespace=namespace, ref=urllib.parse.quote(self.unresolved_ref, safe=''), ) self.log.debug("Fetching %s", api_url) if self.auth: # Add auth params. After logging! api_url = url_concat(api_url, self.auth) try: resp = await client.fetch(api_url, user_agent="BinderHub") except HTTPError as e: if e.code == 404: return None else: raise ref_info = json.loads(resp.body.decode('utf-8')) self.resolved_ref = ref_info['id'] return self.resolved_ref async def get_resolved_spec(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.quoted_namespace}/{self.resolved_ref}" def get_build_slug(self): # escape the name and replace dashes with something else. return '-'.join(p.replace('-', '_-') for p in self.namespace.split('/')) def get_repo_url(self): return f"https://{self.hostname}/{self.namespace}.git" async def get_resolved_ref_url(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"https://{self.hostname}/{self.namespace}/tree/{self.resolved_ref}" class GitHubRepoProvider(RepoProvider): """Repo provider for the GitHub service""" name = Unicode('GitHub') display_name = 'GitHub' # shared cache for resolved refs cache = Cache(1024) # separate cache with max age for 404 results # 404s don't have ETags, so we want them to expire at some point # to avoid caching a 404 forever since e.g. a missing repo or branch # may be created later cache_404 = Cache(1024, max_age=300) hostname = Unicode('github.com', config=True, help="""The GitHub hostname to use Only necessary if not github.com, e.g. GitHub Enterprise. """) api_base_path = Unicode('https://api.{hostname}', config=True, help="""The base path of the GitHub API Only necessary if not github.com, e.g. GitHub Enterprise. Can use {hostname} for substitution, e.g. 'https://{hostname}/api/v3' """) client_id = Unicode(config=True, help="""GitHub client id for authentication with the GitHub API For use with client_secret. Loaded from GITHUB_CLIENT_ID env by default. """ ) @default('client_id') def _client_id_default(self): return os.getenv('GITHUB_CLIENT_ID', '') client_secret = Unicode(config=True, help="""GitHub client secret for authentication with the GitHub API For use with client_id. Loaded from GITHUB_CLIENT_SECRET env by default. """ ) @default('client_secret') def _client_secret_default(self): return os.getenv('GITHUB_CLIENT_SECRET', '') access_token = Unicode(config=True, help="""GitHub access token for authentication with the GitHub API Loaded from GITHUB_ACCESS_TOKEN env by default. """ ) @default('access_token') def _access_token_default(self): return os.getenv('GITHUB_ACCESS_TOKEN', '') @default('git_credentials') def _default_git_credentials(self): if self.access_token: # Based on https://github.com/blog/1270-easier-builds-and-deployments-using-git-over-https-and-oauth # If client_id is specified, assuming access_token is personal access token. Otherwise, # assume oauth basic token. if self.client_id: return r'username={client_id}\npassword={token}'.format( client_id=self.client_id, token=self.access_token) else: return r'username={token}\npassword=x-oauth-basic'.format(token=self.access_token) return "" labels = { "text": "GitHub repository name or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user, self.repo, self.unresolved_ref = tokenize_spec(self.spec) self.repo = strip_suffix(self.repo, ".git") def get_repo_url(self): return f"https://{self.hostname}/{self.user}/{self.repo}" async def get_resolved_ref_url(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"https://{self.hostname}/{self.user}/{self.repo}/tree/{self.resolved_ref}" async def github_api_request(self, api_url, etag=None): client = AsyncHTTPClient() request_kwargs = {} if self.client_id and self.client_secret: request_kwargs.update( dict(auth_username=self.client_id, auth_password=self.client_secret) ) headers = {} # based on: https://developer.github.com/v3/#oauth2-token-sent-in-a-header if self.access_token: headers['Authorization'] = "token {token}".format(token=self.access_token) if etag: headers['If-None-Match'] = etag req = HTTPRequest( api_url, headers=headers, user_agent="BinderHub", **request_kwargs ) try: resp = await client.fetch(req) except HTTPError as e: if e.code == 304: resp = e.response elif ( e.code == 403 and e.response and 'x-ratelimit-remaining' in e.response.headers and e.response.headers.get('x-ratelimit-remaining') == '0' ): rate_limit = e.response.headers['x-ratelimit-limit'] reset_timestamp = int(e.response.headers['x-ratelimit-reset']) reset_seconds = int(reset_timestamp - time.time()) self.log.error( "GitHub Rate limit ({limit}) exceeded. Reset in {delta}.".format( limit=rate_limit, delta=timedelta(seconds=reset_seconds), ) ) # round expiry up to nearest 5 minutes minutes_until_reset = 5 * (1 + (reset_seconds // 60 // 5)) raise ValueError("GitHub rate limit exceeded. Try again in %i minutes." % minutes_until_reset ) # Status 422 is returned by the API when we try and resolve a non # existent reference elif e.code in (404, 422): return None else: raise if 'x-ratelimit-remaining' in resp.headers: # record and log github rate limit remaining = int(resp.headers['x-ratelimit-remaining']) rate_limit = int(resp.headers['x-ratelimit-limit']) reset_timestamp = int(resp.headers['x-ratelimit-reset']) # record with prometheus GITHUB_RATE_LIMIT.set(remaining) # log at different levels, depending on remaining fraction fraction = remaining / rate_limit if fraction < 0.2: log = self.log.warning elif fraction < 0.5: log = self.log.info else: log = self.log.debug # str(timedelta) looks like '00:32' delta = timedelta(seconds=int(reset_timestamp - time.time())) log("GitHub rate limit remaining {remaining}/{limit}. Reset in {delta}.".format( remaining=remaining, limit=rate_limit, delta=delta, )) return resp async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref api_url = "{api_base_path}/repos/{user}/{repo}/commits/{ref}".format( api_base_path=self.api_base_path.format(hostname=self.hostname), user=self.user, repo=self.repo, ref=self.unresolved_ref ) self.log.debug("Fetching %s", api_url) cached = self.cache.get(api_url) if cached: etag = cached['etag'] self.log.debug("Cache hit for %s: %s", api_url, etag) else: cache_404 = self.cache_404.get(api_url) if cache_404: self.log.debug("Cache hit for 404 on %s", api_url) return None etag = None resp = await self.github_api_request(api_url, etag=etag) if resp is None: self.log.debug("Caching 404 on %s", api_url) self.cache_404.set(api_url, True) return None if resp.code == 304: self.log.info("Using cached ref for %s: %s", api_url, cached['sha']) self.resolved_ref = cached['sha'] # refresh cache entry self.cache.move_to_end(api_url) return self.resolved_ref elif cached: self.log.debug("Cache outdated for %s", api_url) ref_info = json.loads(resp.body.decode('utf-8')) if 'sha' not in ref_info: # TODO: Figure out if we should raise an exception instead? self.log.warning("No sha for %s in %s", api_url, ref_info) self.resolved_ref = None return None # store resolved ref and cache for later self.resolved_ref = ref_info['sha'] self.cache.set( api_url, { 'etag': resp.headers.get('ETag'), 'sha': self.resolved_ref, }, ) return self.resolved_ref async def get_resolved_spec(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.user}/{self.repo}/{self.resolved_ref}" def get_build_slug(self): return '{user}-{repo}'.format(user=self.user, repo=self.repo) class GistRepoProvider(GitHubRepoProvider): """GitHub gist provider. Users must provide a spec that matches the following form (similar to github) [https://gist.github.com/]<username>/<gist-id>[/<ref>] The ref is optional, valid values are - a full sha1 of a ref in the history - master If master or no ref is specified the latest revision will be used. """ name = Unicode("Gist") display_name = "Gist" hostname = Unicode("gist.github.com") allow_secret_gist = Bool( default_value=False, config=True, help="Flag for allowing usages of secret Gists. The default behavior is to disallow secret gists.", ) labels = { "text": "Gist ID (username/gistId) or URL", "tag_text": "Git commit SHA", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *args, **kwargs): # We dont need to initialize entirely the same as github super(RepoProvider, self).__init__(*args, **kwargs) parts = self.spec.split('/') self.user, self.gist_id, *_ = parts if len(parts) > 2: self.unresolved_ref = parts[2] else: self.unresolved_ref = '' def get_repo_url(self): return f'https://{self.hostname}/{self.user}/{self.gist_id}.git' async def get_resolved_ref_url(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f'https://{self.hostname}/{self.user}/{self.gist_id}/{self.resolved_ref}' async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref api_url = f"https://api.github.com/gists/{self.gist_id}" self.log.debug("Fetching %s", api_url) resp = await self.github_api_request(api_url) if resp is None: return None ref_info = json.loads(resp.body.decode('utf-8')) if (not self.allow_secret_gist) and (not ref_info['public']): raise ValueError("You seem to want to use a secret Gist, but do not have permission to do so. " "To enable secret Gist support, set (or have an administrator set) " "'GistRepoProvider.allow_secret_gist = True'") all_versions = [e['version'] for e in ref_info['history']] if self.unresolved_ref in {"", "HEAD", "master"}: self.resolved_ref = all_versions[0] else: if self.unresolved_ref not in all_versions: return None else: self.resolved_ref = self.unresolved_ref return self.resolved_ref async def get_resolved_spec(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f'{self.user}/{self.gist_id}/{self.resolved_ref}' def get_build_slug(self): return self.gist_id
remote_code_execution
{ "code": [ " command = [\"git\", \"ls-remote\", self.repo, self.unresolved_ref]" ], "line_no": [ 487 ] }
{ "code": [ " command = [\"git\", \"ls-remote\", \"--\", self.repo, self.unresolved_ref]" ], "line_no": [ 487 ] }
from datetime import timedelta, datetime, timezone import json import os import time import urllib.parse import .re import subprocess import escapism from prometheus_client import Gauge from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest from tornado.httputil import url_concat from traitlets import Dict, Unicode, Bool, default, List from traitlets.config import LoggingConfigurable from .utils import Cache VAR_0 = Gauge('binderhub_github_rate_limit_remaining', 'GitHub rate limit remaining') VAR_1 = re.compile(r'[0-9a-f]{40}') def FUNC_0(VAR_2): VAR_5 = VAR_2.split('/', 2) # allow ref to contain "/" if len(VAR_5) != 3: VAR_31 = 'Spec is not of the form "user/repo/ref", provided: "{VAR_2}".'.format(VAR_2=spec) if len(VAR_5) == 2 and VAR_5[-1] != 'master': VAR_31 += ' Did you mean "{VAR_2}/master"?'.format(VAR_2=spec) raise ValueError(VAR_31) return VAR_5 def FUNC_1(VAR_3, VAR_4): if VAR_3.endswith(VAR_4): VAR_3 = text[:-(len(VAR_4))] return VAR_3 class CLASS_0(LoggingConfigurable): VAR_6 = Unicode( help=""" Descriptive human readable VAR_6 of this repo provider. """ ) VAR_2 = Unicode( help=""" The VAR_2 for this builder to parse """ ) VAR_7 = List( help=""" List of specs to blacklist building. Should be a list of regexes (not regex objects) that VAR_37 specs which should be blacklisted """, VAR_53=True ) VAR_8 = List( help=""" List of specs to assign a higher quota limit. Should be a list of regexes (not regex objects) that VAR_37 specs which should have a higher quota """, VAR_53=True ) VAR_9 = List( help=""" List of dictionaries that define per-repository configuration. Each item in the list is a dictionary with two keys: VAR_52 : string defines a regex VAR_52 (not a regex object) that matches specs. VAR_53 : dict a dictionary of "config_name: config_value" pairs that will be applied to any repository that matches `VAR_52` """, VAR_53=True ) VAR_10 = Unicode() VAR_11 = Unicode( "", help=""" Credentials (if any) to pass to git when cloning. """, VAR_53=True ) def FUNC_2(self): for banned in self.banned_specs: if re.match(banned, self.spec, re.IGNORECASE): return True return False def FUNC_3(self): for higher_quota in self.high_quota_specs: if re.match(higher_quota, self.spec, re.IGNORECASE): return True return False def VAR_32(self, VAR_12): VAR_32 = {} if self.has_higher_quota(): VAR_32['quota'] = VAR_12.get('per_repo_quota_higher') else: VAR_32['quota'] = VAR_12.get('per_repo_quota') for item in self.spec_config: VAR_52 = item.get('pattern', None) VAR_53 = item.get('config', None) if not isinstance(VAR_52, str): raise ValueError( "Spec-VAR_52 configuration expected " "a regex VAR_52 string, not " "type %s" % type(VAR_52)) if not isinstance(VAR_53, dict): raise ValueError( "Spec-VAR_52 configuration expected " "a specification configuration dict, not " "type %s" % type(VAR_53)) if re.match(VAR_52, self.spec, re.IGNORECASE): VAR_32.update(VAR_53) return VAR_32 async def FUNC_5(self): raise NotImplementedError("Must be overridden in child class") async def FUNC_6(self): raise NotImplementedError("Must be overridden in child class") def FUNC_7(self): raise NotImplementedError("Must be overridden in the child class") async def FUNC_8(self): raise NotImplementedError("Must be overridden in child class") def FUNC_9(self): raise NotImplementedError("Must be overriden in the child class") @staticmethod def FUNC_10(VAR_13): if not VAR_1.match(VAR_13): raise ValueError("resolved_ref is not a valid VAR_13 hexadecimal hash") class CLASS_1(CLASS_0): VAR_14 = { "text": "Fake Provider", "tag_text": "Fake Ref", "ref_prop_disabled": True, "label_prop_disabled": True, } async def FUNC_5(self): return "1a2b3c4d5e6f" async def FUNC_6(self): return "fake/repo/1a2b3c4d5e6f" def FUNC_7(self): return "https://example.com/fake/repo.git" async def FUNC_8(self): return "https://example.com/fake/repo/tree/1a2b3c4d5e6f" def FUNC_9(self): return '{user}-{repo}'.format(user='Rick', repo='Morty') class CLASS_2(CLASS_0): VAR_6 = Unicode("Zenodo") VAR_15 = "Zenodo DOI" VAR_14 = { "text": "Zenodo DOI (10.5281/zenodo.3242074)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def FUNC_5(self): VAR_33 = AsyncHTTPClient() VAR_34 = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) self.record_id = VAR_35.effective_url.rsplit("/", maxsplit=1)[1] return self.record_id async def FUNC_6(self): if not hasattr(self, 'record_id'): self.record_id = await self.get_resolved_ref() VAR_36 = self.spec.split("zenodo")[0] + "zenodo." + self.record_id return VAR_36 def FUNC_7(self): return self.spec async def FUNC_8(self): VAR_36 = await self.get_resolved_spec() return f"https://doi.org/{VAR_36}" def FUNC_9(self): return "zenodo-{}".format(self.record_id) class CLASS_3(CLASS_0): VAR_6 = Unicode("Figshare") VAR_15 = "Figshare DOI" VAR_16 = re.compile(r"(.*)/articles/([^/]+)/([^/]+)/(\d+)(/)?(\d+)?") VAR_14 = { "text": "Figshare DOI (10.6084/m9.figshare.9782777.v1)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def FUNC_5(self): VAR_33 = AsyncHTTPClient() VAR_34 = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) VAR_37 = self.url_regex.match(VAR_35.effective_url) VAR_38 = VAR_37.groups()[3] VAR_39 = VAR_37.groups()[5] if not VAR_39: article_version = "1" self.record_id = "{}.v{}".format(VAR_38, VAR_39) return self.record_id async def FUNC_6(self): if not hasattr(self, 'record_id'): self.record_id = await self.get_resolved_ref() VAR_36 = self.spec.split("figshare")[0] + "figshare." + self.record_id return VAR_36 def FUNC_7(self): return self.spec async def FUNC_8(self): VAR_36 = await self.get_resolved_spec() return f"https://doi.org/{VAR_36}" def FUNC_9(self): return "figshare-{}".format(self.record_id) class CLASS_4(CLASS_0): VAR_6 = Unicode("Dataverse") VAR_15 = "Dataverse DOI" VAR_14 = { "text": "Dataverse DOI (10.7910/DVN/TJCLKP)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def FUNC_5(self): VAR_33 = AsyncHTTPClient() VAR_34 = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) VAR_40 = urllib.parse.urlunparse( urllib.parse.urlparse(VAR_35.effective_url)._replace( path="/api/datasets/:persistentId" ) ) VAR_34 = HTTPRequest(VAR_40, user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) VAR_41 = json.loads(VAR_35.body) assert VAR_41["status"] == "OK" self.identifier = VAR_41["data"]["identifier"] self.record_id = "{datasetId}.v{major}.{minor}".format( datasetId=VAR_41["data"]["id"], major=VAR_41["data"]["latestVersion"]["versionNumber"], minor=VAR_41["data"]["latestVersion"]["versionMinorNumber"], ) self.resolved_spec = "{authority}/{identifier}".format( authority=VAR_41["data"]["authority"], identifier=VAR_41["data"]["identifier"], ) self.resolved_ref_url = VAR_41["data"]["persistentUrl"] return self.record_id async def FUNC_6(self): if not hasattr(self, 'resolved_spec'): await self.get_resolved_ref() return self.resolved_spec async def FUNC_8(self): if not hasattr(self, 'resolved_ref_url'): await self.get_resolved_ref() return self.resolved_ref_url def FUNC_7(self): return self.spec def FUNC_9(self): return "dataverse-" + escapism.escape(self.identifier, escape_char="-").lower() class CLASS_5(CLASS_0): VAR_6 = Unicode("Hydroshare") VAR_15 = "Hydroshare resource" VAR_16 = re.compile(r".*([0-9a-f]{32}).*") VAR_14 = { "text": "Hydroshare resource id or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } def FUNC_11(self, VAR_2): VAR_37 = self.url_regex.match(VAR_2) if not VAR_37: raise ValueError("The specified Hydroshare resource id was not recognized.") VAR_42 = VAR_37.groups()[0] return VAR_42 async def FUNC_5(self): VAR_33 = AsyncHTTPClient() self.resource_id = self._parse_resource_id(self.spec) VAR_34 = HTTPRequest("https://www.hydroshare.org/hsapi/resource/{}/scimeta/elements".format(self.resource_id), user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) def FUNC_19(VAR_43): VAR_54 = json.loads(VAR_43) VAR_55 = next( item for item in VAR_54["dates"] if item["type"] == "modified" )["start_date"] VAR_55 = date.split(".")[0] VAR_56 = datetime.strptime(VAR_55, "%Y-%m-%dT%H:%M:%S") VAR_57 = VAR_56.replace(tzinfo=timezone(timedelta(0))).timestamp() return str(int(VAR_57)) self.record_id = "{}.v{}".format(self.resource_id, FUNC_19(VAR_35.body)) return self.record_id async def FUNC_6(self): return self.get_repo_url() async def FUNC_8(self): return self.get_repo_url() def FUNC_7(self): self.resource_id = self._parse_resource_id(self.spec) return "https://www.hydroshare.org/resource/{}".format(self.resource_id) def FUNC_9(self): return "hydroshare-{}".format(self.record_id) class CLASS_6(CLASS_0): VAR_6 = Unicode("Git") VAR_15 = "Git repository" VAR_14 = { "text": "Arbitrary git repository URL (http://git.example.com/repo)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *VAR_17, **VAR_18): super().__init__(*VAR_17, **VAR_18) self.url, VAR_10 = self.spec.split('/', 1) self.repo = urllib.parse.unquote(self.url) self.unresolved_ref = urllib.parse.unquote(VAR_10) if not self.unresolved_ref: raise ValueError("`VAR_10` must be specified as a query parameter for the basic git provider") async def FUNC_5(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref try: self.sha1_validate(self.unresolved_ref) except ValueError: VAR_64 = ["git", "ls-remote", self.repo, self.unresolved_ref] VAR_65 = subprocess.run(VAR_64, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if VAR_65.returncode: raise RuntimeError("Unable to run git ls-remote to get the `VAR_66`: {}".format(VAR_65.stderr)) if not VAR_65.stdout: return None VAR_66 = VAR_65.stdout.split(None, 1)[0] self.sha1_validate(VAR_66) self.resolved_ref = VAR_66 else: self.resolved_ref = self.unresolved_ref return self.resolved_ref async def FUNC_6(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.url}/{self.resolved_ref}" def FUNC_7(self): return self.repo async def FUNC_8(self): return self.get_repo_url() def FUNC_9(self): return self.repo class CLASS_7(CLASS_0): VAR_6 = Unicode('GitLab') VAR_15 = "GitLab.com" VAR_19 = Unicode('gitlab.com', VAR_53=True, help="""The host of the GitLab instance For personal GitLab servers. """ ) VAR_20 = Unicode(VAR_53=True, help="""GitLab OAuth2 access token for authentication with the GitLab API For use with VAR_27. Loaded from GITLAB_ACCESS_TOKEN env by default. """ ) @default('access_token') def FUNC_12(self): return os.getenv('GITLAB_ACCESS_TOKEN', '') VAR_21 = Unicode(VAR_53=True, help="""GitLab private token for authentication with the GitLab API Loaded from GITLAB_PRIVATE_TOKEN env by default. """ ) @default('private_token') def FUNC_13(self): return os.getenv('GITLAB_PRIVATE_TOKEN', '') VAR_22 = Dict( help="""Auth parameters for the GitLab API access Populated from VAR_20, VAR_21 """ ) @default('auth') def FUNC_14(self): VAR_22 = {} for VAR_67 in ('access_token', 'private_token'): VAR_58 = getattr(self, VAR_67) if VAR_58: VAR_22[VAR_67] = VAR_58 return VAR_22 @default('git_credentials') def FUNC_15(self): if self.private_token: return r'username=binderhub\npassword={token}'.format(token=self.private_token) return "" VAR_14 = { "text": "GitLab.com repository or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *VAR_17, **VAR_18): super().__init__(*VAR_17, **VAR_18) self.quoted_namespace, VAR_10 = self.spec.split('/', 1) self.namespace = urllib.parse.unquote(self.quoted_namespace) self.unresolved_ref = urllib.parse.unquote(VAR_10) if not self.unresolved_ref: raise ValueError("An unresolved ref is required") async def FUNC_5(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref VAR_44 = urllib.parse.quote(self.namespace, safe='') VAR_33 = AsyncHTTPClient() VAR_28 = "https://{VAR_19}/api/v4/projects/{VAR_44}/repository/commits/{ref}".format( VAR_19=self.hostname, VAR_44=namespace, ref=urllib.parse.quote(self.unresolved_ref, safe=''), ) self.log.debug("Fetching %s", VAR_28) if self.auth: VAR_28 = url_concat(VAR_28, self.auth) try: VAR_41 = await VAR_33.fetch(VAR_28, user_agent="BinderHub") except HTTPError as e: if e.code == 404: return None else: raise VAR_45 = json.loads(VAR_41.body.decode('utf-8')) self.resolved_ref = VAR_45['id'] return self.resolved_ref async def FUNC_6(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.quoted_namespace}/{self.resolved_ref}" def FUNC_9(self): return '-'.join(p.replace('-', '_-') for p in self.namespace.split('/')) def FUNC_7(self): return f"https://{self.hostname}/{self.namespace}.git" async def FUNC_8(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"https://{self.hostname}/{self.namespace}/tree/{self.resolved_ref}" class CLASS_8(CLASS_0): VAR_6 = Unicode('GitHub') VAR_15 = 'GitHub' VAR_23 = Cache(1024) VAR_24 = Cache(1024, max_age=300) VAR_19 = Unicode('github.com', VAR_53=True, help="""The GitHub VAR_19 to use Only necessary if not github.com, e.g. GitHub Enterprise. """) VAR_25 = Unicode('https://api.{VAR_19}', VAR_53=True, help="""The base path of the GitHub API Only necessary if not github.com, e.g. GitHub Enterprise. Can use {VAR_19} for substitution, e.g. 'https://{VAR_19}/api/v3' """) VAR_26 = Unicode(VAR_53=True, help="""GitHub VAR_33 id for authentication with the GitHub API For use with VAR_27. Loaded from GITHUB_CLIENT_ID env by default. """ ) @default('client_id') def FUNC_16(self): return os.getenv('GITHUB_CLIENT_ID', '') VAR_27 = Unicode(VAR_53=True, help="""GitHub VAR_33 secret for authentication with the GitHub API For use with VAR_26. Loaded from GITHUB_CLIENT_SECRET env by default. """ ) @default('client_secret') def FUNC_17(self): return os.getenv('GITHUB_CLIENT_SECRET', '') VAR_20 = Unicode(VAR_53=True, help="""GitHub access token for authentication with the GitHub API Loaded from GITHUB_ACCESS_TOKEN env by default. """ ) @default('access_token') def FUNC_12(self): return os.getenv('GITHUB_ACCESS_TOKEN', '') @default('git_credentials') def FUNC_15(self): if self.access_token: if self.client_id: return r'username={VAR_26}\npassword={token}'.format( VAR_26=self.client_id, token=self.access_token) else: return r'username={token}\npassword=x-oauth-basic'.format(token=self.access_token) return "" VAR_14 = { "text": "GitHub repository VAR_6 or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *VAR_17, **VAR_18): super().__init__(*VAR_17, **VAR_18) self.user, self.repo, self.unresolved_ref = FUNC_0(self.spec) self.repo = FUNC_1(self.repo, ".git") def FUNC_7(self): return f"https://{self.hostname}/{self.user}/{self.repo}" async def FUNC_8(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"https://{self.hostname}/{self.user}/{self.repo}/tree/{self.resolved_ref}" async def FUNC_18(self, VAR_28, VAR_29=None): VAR_33 = AsyncHTTPClient() VAR_46 = {} if self.client_id and self.client_secret: VAR_46.update( dict(auth_username=self.client_id, auth_password=self.client_secret) ) VAR_47 = {} if self.access_token: VAR_47['Authorization'] = "token {token}".format(token=self.access_token) if VAR_29: VAR_47['If-None-Match'] = VAR_29 VAR_34 = HTTPRequest( VAR_28, VAR_47=headers, user_agent="BinderHub", **VAR_46 ) try: VAR_41 = await VAR_33.fetch(VAR_34) except HTTPError as e: if e.code == 304: VAR_41 = e.response elif ( e.code == 403 and e.response and 'x-ratelimit-remaining' in e.response.headers and e.response.headers.get('x-ratelimit-remaining') == '0' ): VAR_60 = e.response.headers['x-ratelimit-limit'] VAR_61 = int(e.response.headers['x-ratelimit-reset']) VAR_69 = int(VAR_61 - time.time()) self.log.error( "GitHub Rate limit ({limit}) exceeded. Reset in {VAR_63}.".format( limit=VAR_60, VAR_63=timedelta(seconds=VAR_69), ) ) VAR_70 = 5 * (1 + (VAR_69 // 60 // 5)) raise ValueError("GitHub rate limit exceeded. Try again in %i minutes." % VAR_70 ) elif e.code in (404, 422): return None else: raise if 'x-ratelimit-remaining' in VAR_41.headers: VAR_59 = int(VAR_41.headers['x-ratelimit-remaining']) VAR_60 = int(VAR_41.headers['x-ratelimit-limit']) VAR_61 = int(VAR_41.headers['x-ratelimit-reset']) VAR_0.set(VAR_59) fraction = VAR_59 / VAR_60 if VAR_62 < 0.2: VAR_68 = self.log.warning elif VAR_62 < 0.5: VAR_68 = self.log.info else: VAR_68 = self.log.debug VAR_63 = timedelta(seconds=int(VAR_61 - time.time())) VAR_68("GitHub rate limit VAR_59 {remaining}/{limit}. Reset in {VAR_63}.".format( VAR_59=remaining, limit=VAR_60, VAR_63=delta, )) return VAR_41 async def FUNC_5(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref VAR_28 = "{VAR_25}/repos/{user}/{repo}/commits/{ref}".format( VAR_25=self.api_base_path.format(VAR_19=self.hostname), user=self.user, repo=self.repo, ref=self.unresolved_ref ) self.log.debug("Fetching %s", VAR_28) VAR_48 = self.cache.get(VAR_28) if VAR_48: VAR_29 = VAR_48['etag'] self.log.debug("Cache hit for %s: %s", VAR_28, VAR_29) else: VAR_24 = self.cache_404.get(VAR_28) if VAR_24: self.log.debug("Cache hit for 404 on %s", VAR_28) return None VAR_29 = None VAR_41 = await self.github_api_request(VAR_28, VAR_29=etag) if VAR_41 is None: self.log.debug("Caching 404 on %s", VAR_28) self.cache_404.set(VAR_28, True) return None if VAR_41.code == 304: self.log.info("Using VAR_48 ref for %s: %s", VAR_28, VAR_48['sha']) self.resolved_ref = VAR_48['sha'] self.cache.move_to_end(VAR_28) return self.resolved_ref elif VAR_48: self.log.debug("Cache outdated for %s", VAR_28) VAR_45 = json.loads(VAR_41.body.decode('utf-8')) if 'sha' not in VAR_45: self.log.warning("No sha for %s in %s", VAR_28, VAR_45) self.resolved_ref = None return None self.resolved_ref = VAR_45['sha'] self.cache.set( VAR_28, { 'etag': VAR_41.headers.get('ETag'), 'sha': self.resolved_ref, }, ) return self.resolved_ref async def FUNC_6(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.user}/{self.repo}/{self.resolved_ref}" def FUNC_9(self): return '{user}-{repo}'.format(user=self.user, repo=self.repo) class CLASS_9(CLASS_8): VAR_6 = Unicode("Gist") VAR_15 = "Gist" VAR_19 = Unicode("gist.github.com") VAR_30 = Bool( default_value=False, VAR_53=True, help="Flag for allowing usages of secret Gists. The default behavior is to disallow secret gists.", ) VAR_14 = { "text": "Gist ID (username/gistId) or URL", "tag_text": "Git commit SHA", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *VAR_17, **VAR_18): super(CLASS_0, self).__init__(*VAR_17, **VAR_18) VAR_49 = self.spec.split('/') self.user, self.gist_id, *VAR_50 = VAR_49 if len(VAR_49) > 2: self.unresolved_ref = VAR_49[2] else: self.unresolved_ref = '' def FUNC_7(self): return f'https://{self.hostname}/{self.user}/{self.gist_id}.git' async def FUNC_8(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f'https://{self.hostname}/{self.user}/{self.gist_id}/{self.resolved_ref}' async def FUNC_5(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref VAR_28 = f"https://api.github.com/gists/{self.gist_id}" self.log.debug("Fetching %s", VAR_28) VAR_41 = await self.github_api_request(VAR_28) if VAR_41 is None: return None VAR_45 = json.loads(VAR_41.body.decode('utf-8')) if (not self.allow_secret_gist) and (not VAR_45['public']): raise ValueError("You seem to want to use a secret Gist, but do not have permission to do so. " "To enable secret Gist support, set (or have an administrator set) " "'GistRepoProvider.allow_secret_gist = True'") VAR_51 = [e['version'] for e in VAR_45['history']] if self.unresolved_ref in {"", "HEAD", "master"}: self.resolved_ref = VAR_51[0] else: if self.unresolved_ref not in VAR_51: return None else: self.resolved_ref = self.unresolved_ref return self.resolved_ref async def FUNC_6(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f'{self.user}/{self.gist_id}/{self.resolved_ref}' def FUNC_9(self): return self.gist_id
from datetime import timedelta, datetime, timezone import json import os import time import urllib.parse import .re import subprocess import escapism from prometheus_client import Gauge from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest from tornado.httputil import url_concat from traitlets import Dict, Unicode, Bool, default, List from traitlets.config import LoggingConfigurable from .utils import Cache VAR_0 = Gauge('binderhub_github_rate_limit_remaining', 'GitHub rate limit remaining') VAR_1 = re.compile(r'[0-9a-f]{40}') def FUNC_0(VAR_2): VAR_5 = VAR_2.split('/', 2) # allow ref to contain "/" if len(VAR_5) != 3: VAR_31 = 'Spec is not of the form "user/repo/ref", provided: "{VAR_2}".'.format(VAR_2=spec) if len(VAR_5) == 2 and VAR_5[-1] != 'master': VAR_31 += ' Did you mean "{VAR_2}/master"?'.format(VAR_2=spec) raise ValueError(VAR_31) return VAR_5 def FUNC_1(VAR_3, VAR_4): if VAR_3.endswith(VAR_4): VAR_3 = text[:-(len(VAR_4))] return VAR_3 class CLASS_0(LoggingConfigurable): VAR_6 = Unicode( help=""" Descriptive human readable VAR_6 of this repo provider. """ ) VAR_2 = Unicode( help=""" The VAR_2 for this builder to parse """ ) VAR_7 = List( help=""" List of specs to blacklist building. Should be a list of regexes (not regex objects) that VAR_37 specs which should be blacklisted """, VAR_53=True ) VAR_8 = List( help=""" List of specs to assign a higher quota limit. Should be a list of regexes (not regex objects) that VAR_37 specs which should have a higher quota """, VAR_53=True ) VAR_9 = List( help=""" List of dictionaries that define per-repository configuration. Each item in the list is a dictionary with two keys: VAR_52 : string defines a regex VAR_52 (not a regex object) that matches specs. VAR_53 : dict a dictionary of "config_name: config_value" pairs that will be applied to any repository that matches `VAR_52` """, VAR_53=True ) VAR_10 = Unicode() VAR_11 = Unicode( "", help=""" Credentials (if any) to pass to git when cloning. """, VAR_53=True ) def FUNC_2(self): for banned in self.banned_specs: if re.match(banned, self.spec, re.IGNORECASE): return True return False def FUNC_3(self): for higher_quota in self.high_quota_specs: if re.match(higher_quota, self.spec, re.IGNORECASE): return True return False def VAR_32(self, VAR_12): VAR_32 = {} if self.has_higher_quota(): VAR_32['quota'] = VAR_12.get('per_repo_quota_higher') else: VAR_32['quota'] = VAR_12.get('per_repo_quota') for item in self.spec_config: VAR_52 = item.get('pattern', None) VAR_53 = item.get('config', None) if not isinstance(VAR_52, str): raise ValueError( "Spec-VAR_52 configuration expected " "a regex VAR_52 string, not " "type %s" % type(VAR_52)) if not isinstance(VAR_53, dict): raise ValueError( "Spec-VAR_52 configuration expected " "a specification configuration dict, not " "type %s" % type(VAR_53)) if re.match(VAR_52, self.spec, re.IGNORECASE): VAR_32.update(VAR_53) return VAR_32 async def FUNC_5(self): raise NotImplementedError("Must be overridden in child class") async def FUNC_6(self): raise NotImplementedError("Must be overridden in child class") def FUNC_7(self): raise NotImplementedError("Must be overridden in the child class") async def FUNC_8(self): raise NotImplementedError("Must be overridden in child class") def FUNC_9(self): raise NotImplementedError("Must be overriden in the child class") @staticmethod def FUNC_10(VAR_13): if not VAR_1.match(VAR_13): raise ValueError("resolved_ref is not a valid VAR_13 hexadecimal hash") class CLASS_1(CLASS_0): VAR_14 = { "text": "Fake Provider", "tag_text": "Fake Ref", "ref_prop_disabled": True, "label_prop_disabled": True, } async def FUNC_5(self): return "1a2b3c4d5e6f" async def FUNC_6(self): return "fake/repo/1a2b3c4d5e6f" def FUNC_7(self): return "https://example.com/fake/repo.git" async def FUNC_8(self): return "https://example.com/fake/repo/tree/1a2b3c4d5e6f" def FUNC_9(self): return '{user}-{repo}'.format(user='Rick', repo='Morty') class CLASS_2(CLASS_0): VAR_6 = Unicode("Zenodo") VAR_15 = "Zenodo DOI" VAR_14 = { "text": "Zenodo DOI (10.5281/zenodo.3242074)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def FUNC_5(self): VAR_33 = AsyncHTTPClient() VAR_34 = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) self.record_id = VAR_35.effective_url.rsplit("/", maxsplit=1)[1] return self.record_id async def FUNC_6(self): if not hasattr(self, 'record_id'): self.record_id = await self.get_resolved_ref() VAR_36 = self.spec.split("zenodo")[0] + "zenodo." + self.record_id return VAR_36 def FUNC_7(self): return self.spec async def FUNC_8(self): VAR_36 = await self.get_resolved_spec() return f"https://doi.org/{VAR_36}" def FUNC_9(self): return "zenodo-{}".format(self.record_id) class CLASS_3(CLASS_0): VAR_6 = Unicode("Figshare") VAR_15 = "Figshare DOI" VAR_16 = re.compile(r"(.*)/articles/([^/]+)/([^/]+)/(\d+)(/)?(\d+)?") VAR_14 = { "text": "Figshare DOI (10.6084/m9.figshare.9782777.v1)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def FUNC_5(self): VAR_33 = AsyncHTTPClient() VAR_34 = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) VAR_37 = self.url_regex.match(VAR_35.effective_url) VAR_38 = VAR_37.groups()[3] VAR_39 = VAR_37.groups()[5] if not VAR_39: article_version = "1" self.record_id = "{}.v{}".format(VAR_38, VAR_39) return self.record_id async def FUNC_6(self): if not hasattr(self, 'record_id'): self.record_id = await self.get_resolved_ref() VAR_36 = self.spec.split("figshare")[0] + "figshare." + self.record_id return VAR_36 def FUNC_7(self): return self.spec async def FUNC_8(self): VAR_36 = await self.get_resolved_spec() return f"https://doi.org/{VAR_36}" def FUNC_9(self): return "figshare-{}".format(self.record_id) class CLASS_4(CLASS_0): VAR_6 = Unicode("Dataverse") VAR_15 = "Dataverse DOI" VAR_14 = { "text": "Dataverse DOI (10.7910/DVN/TJCLKP)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } async def FUNC_5(self): VAR_33 = AsyncHTTPClient() VAR_34 = HTTPRequest("https://doi.org/{}".format(self.spec), user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) VAR_40 = urllib.parse.urlunparse( urllib.parse.urlparse(VAR_35.effective_url)._replace( path="/api/datasets/:persistentId" ) ) VAR_34 = HTTPRequest(VAR_40, user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) VAR_41 = json.loads(VAR_35.body) assert VAR_41["status"] == "OK" self.identifier = VAR_41["data"]["identifier"] self.record_id = "{datasetId}.v{major}.{minor}".format( datasetId=VAR_41["data"]["id"], major=VAR_41["data"]["latestVersion"]["versionNumber"], minor=VAR_41["data"]["latestVersion"]["versionMinorNumber"], ) self.resolved_spec = "{authority}/{identifier}".format( authority=VAR_41["data"]["authority"], identifier=VAR_41["data"]["identifier"], ) self.resolved_ref_url = VAR_41["data"]["persistentUrl"] return self.record_id async def FUNC_6(self): if not hasattr(self, 'resolved_spec'): await self.get_resolved_ref() return self.resolved_spec async def FUNC_8(self): if not hasattr(self, 'resolved_ref_url'): await self.get_resolved_ref() return self.resolved_ref_url def FUNC_7(self): return self.spec def FUNC_9(self): return "dataverse-" + escapism.escape(self.identifier, escape_char="-").lower() class CLASS_5(CLASS_0): VAR_6 = Unicode("Hydroshare") VAR_15 = "Hydroshare resource" VAR_16 = re.compile(r".*([0-9a-f]{32}).*") VAR_14 = { "text": "Hydroshare resource id or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": True, "label_prop_disabled": True, } def FUNC_11(self, VAR_2): VAR_37 = self.url_regex.match(VAR_2) if not VAR_37: raise ValueError("The specified Hydroshare resource id was not recognized.") VAR_42 = VAR_37.groups()[0] return VAR_42 async def FUNC_5(self): VAR_33 = AsyncHTTPClient() self.resource_id = self._parse_resource_id(self.spec) VAR_34 = HTTPRequest("https://www.hydroshare.org/hsapi/resource/{}/scimeta/elements".format(self.resource_id), user_agent="BinderHub") VAR_35 = await VAR_33.fetch(VAR_34) def FUNC_19(VAR_43): VAR_54 = json.loads(VAR_43) VAR_55 = next( item for item in VAR_54["dates"] if item["type"] == "modified" )["start_date"] VAR_55 = date.split(".")[0] VAR_56 = datetime.strptime(VAR_55, "%Y-%m-%dT%H:%M:%S") VAR_57 = VAR_56.replace(tzinfo=timezone(timedelta(0))).timestamp() return str(int(VAR_57)) self.record_id = "{}.v{}".format(self.resource_id, FUNC_19(VAR_35.body)) return self.record_id async def FUNC_6(self): return self.get_repo_url() async def FUNC_8(self): return self.get_repo_url() def FUNC_7(self): self.resource_id = self._parse_resource_id(self.spec) return "https://www.hydroshare.org/resource/{}".format(self.resource_id) def FUNC_9(self): return "hydroshare-{}".format(self.record_id) class CLASS_6(CLASS_0): VAR_6 = Unicode("Git") VAR_15 = "Git repository" VAR_14 = { "text": "Arbitrary git repository URL (http://git.example.com/repo)", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *VAR_17, **VAR_18): super().__init__(*VAR_17, **VAR_18) self.url, VAR_10 = self.spec.split('/', 1) self.repo = urllib.parse.unquote(self.url) self.unresolved_ref = urllib.parse.unquote(VAR_10) if not self.unresolved_ref: raise ValueError("`VAR_10` must be specified as a query parameter for the basic git provider") async def FUNC_5(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref try: self.sha1_validate(self.unresolved_ref) except ValueError: VAR_64 = ["git", "ls-remote", "--", self.repo, self.unresolved_ref] VAR_65 = subprocess.run(VAR_64, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if VAR_65.returncode: raise RuntimeError("Unable to run git ls-remote to get the `VAR_66`: {}".format(VAR_65.stderr)) if not VAR_65.stdout: return None VAR_66 = VAR_65.stdout.split(None, 1)[0] self.sha1_validate(VAR_66) self.resolved_ref = VAR_66 else: self.resolved_ref = self.unresolved_ref return self.resolved_ref async def FUNC_6(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.url}/{self.resolved_ref}" def FUNC_7(self): return self.repo async def FUNC_8(self): return self.get_repo_url() def FUNC_9(self): return self.repo class CLASS_7(CLASS_0): VAR_6 = Unicode('GitLab') VAR_15 = "GitLab.com" VAR_19 = Unicode('gitlab.com', VAR_53=True, help="""The host of the GitLab instance For personal GitLab servers. """ ) VAR_20 = Unicode(VAR_53=True, help="""GitLab OAuth2 access token for authentication with the GitLab API For use with VAR_27. Loaded from GITLAB_ACCESS_TOKEN env by default. """ ) @default('access_token') def FUNC_12(self): return os.getenv('GITLAB_ACCESS_TOKEN', '') VAR_21 = Unicode(VAR_53=True, help="""GitLab private token for authentication with the GitLab API Loaded from GITLAB_PRIVATE_TOKEN env by default. """ ) @default('private_token') def FUNC_13(self): return os.getenv('GITLAB_PRIVATE_TOKEN', '') VAR_22 = Dict( help="""Auth parameters for the GitLab API access Populated from VAR_20, VAR_21 """ ) @default('auth') def FUNC_14(self): VAR_22 = {} for VAR_67 in ('access_token', 'private_token'): VAR_58 = getattr(self, VAR_67) if VAR_58: VAR_22[VAR_67] = VAR_58 return VAR_22 @default('git_credentials') def FUNC_15(self): if self.private_token: return r'username=binderhub\npassword={token}'.format(token=self.private_token) return "" VAR_14 = { "text": "GitLab.com repository or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *VAR_17, **VAR_18): super().__init__(*VAR_17, **VAR_18) self.quoted_namespace, VAR_10 = self.spec.split('/', 1) self.namespace = urllib.parse.unquote(self.quoted_namespace) self.unresolved_ref = urllib.parse.unquote(VAR_10) if not self.unresolved_ref: raise ValueError("An unresolved ref is required") async def FUNC_5(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref VAR_44 = urllib.parse.quote(self.namespace, safe='') VAR_33 = AsyncHTTPClient() VAR_28 = "https://{VAR_19}/api/v4/projects/{VAR_44}/repository/commits/{ref}".format( VAR_19=self.hostname, VAR_44=namespace, ref=urllib.parse.quote(self.unresolved_ref, safe=''), ) self.log.debug("Fetching %s", VAR_28) if self.auth: VAR_28 = url_concat(VAR_28, self.auth) try: VAR_41 = await VAR_33.fetch(VAR_28, user_agent="BinderHub") except HTTPError as e: if e.code == 404: return None else: raise VAR_45 = json.loads(VAR_41.body.decode('utf-8')) self.resolved_ref = VAR_45['id'] return self.resolved_ref async def FUNC_6(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.quoted_namespace}/{self.resolved_ref}" def FUNC_9(self): return '-'.join(p.replace('-', '_-') for p in self.namespace.split('/')) def FUNC_7(self): return f"https://{self.hostname}/{self.namespace}.git" async def FUNC_8(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"https://{self.hostname}/{self.namespace}/tree/{self.resolved_ref}" class CLASS_8(CLASS_0): VAR_6 = Unicode('GitHub') VAR_15 = 'GitHub' VAR_23 = Cache(1024) VAR_24 = Cache(1024, max_age=300) VAR_19 = Unicode('github.com', VAR_53=True, help="""The GitHub VAR_19 to use Only necessary if not github.com, e.g. GitHub Enterprise. """) VAR_25 = Unicode('https://api.{VAR_19}', VAR_53=True, help="""The base path of the GitHub API Only necessary if not github.com, e.g. GitHub Enterprise. Can use {VAR_19} for substitution, e.g. 'https://{VAR_19}/api/v3' """) VAR_26 = Unicode(VAR_53=True, help="""GitHub VAR_33 id for authentication with the GitHub API For use with VAR_27. Loaded from GITHUB_CLIENT_ID env by default. """ ) @default('client_id') def FUNC_16(self): return os.getenv('GITHUB_CLIENT_ID', '') VAR_27 = Unicode(VAR_53=True, help="""GitHub VAR_33 secret for authentication with the GitHub API For use with VAR_26. Loaded from GITHUB_CLIENT_SECRET env by default. """ ) @default('client_secret') def FUNC_17(self): return os.getenv('GITHUB_CLIENT_SECRET', '') VAR_20 = Unicode(VAR_53=True, help="""GitHub access token for authentication with the GitHub API Loaded from GITHUB_ACCESS_TOKEN env by default. """ ) @default('access_token') def FUNC_12(self): return os.getenv('GITHUB_ACCESS_TOKEN', '') @default('git_credentials') def FUNC_15(self): if self.access_token: if self.client_id: return r'username={VAR_26}\npassword={token}'.format( VAR_26=self.client_id, token=self.access_token) else: return r'username={token}\npassword=x-oauth-basic'.format(token=self.access_token) return "" VAR_14 = { "text": "GitHub repository VAR_6 or URL", "tag_text": "Git ref (branch, tag, or commit)", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *VAR_17, **VAR_18): super().__init__(*VAR_17, **VAR_18) self.user, self.repo, self.unresolved_ref = FUNC_0(self.spec) self.repo = FUNC_1(self.repo, ".git") def FUNC_7(self): return f"https://{self.hostname}/{self.user}/{self.repo}" async def FUNC_8(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"https://{self.hostname}/{self.user}/{self.repo}/tree/{self.resolved_ref}" async def FUNC_18(self, VAR_28, VAR_29=None): VAR_33 = AsyncHTTPClient() VAR_46 = {} if self.client_id and self.client_secret: VAR_46.update( dict(auth_username=self.client_id, auth_password=self.client_secret) ) VAR_47 = {} if self.access_token: VAR_47['Authorization'] = "token {token}".format(token=self.access_token) if VAR_29: VAR_47['If-None-Match'] = VAR_29 VAR_34 = HTTPRequest( VAR_28, VAR_47=headers, user_agent="BinderHub", **VAR_46 ) try: VAR_41 = await VAR_33.fetch(VAR_34) except HTTPError as e: if e.code == 304: VAR_41 = e.response elif ( e.code == 403 and e.response and 'x-ratelimit-remaining' in e.response.headers and e.response.headers.get('x-ratelimit-remaining') == '0' ): VAR_60 = e.response.headers['x-ratelimit-limit'] VAR_61 = int(e.response.headers['x-ratelimit-reset']) VAR_69 = int(VAR_61 - time.time()) self.log.error( "GitHub Rate limit ({limit}) exceeded. Reset in {VAR_63}.".format( limit=VAR_60, VAR_63=timedelta(seconds=VAR_69), ) ) VAR_70 = 5 * (1 + (VAR_69 // 60 // 5)) raise ValueError("GitHub rate limit exceeded. Try again in %i minutes." % VAR_70 ) elif e.code in (404, 422): return None else: raise if 'x-ratelimit-remaining' in VAR_41.headers: VAR_59 = int(VAR_41.headers['x-ratelimit-remaining']) VAR_60 = int(VAR_41.headers['x-ratelimit-limit']) VAR_61 = int(VAR_41.headers['x-ratelimit-reset']) VAR_0.set(VAR_59) fraction = VAR_59 / VAR_60 if VAR_62 < 0.2: VAR_68 = self.log.warning elif VAR_62 < 0.5: VAR_68 = self.log.info else: VAR_68 = self.log.debug VAR_63 = timedelta(seconds=int(VAR_61 - time.time())) VAR_68("GitHub rate limit VAR_59 {remaining}/{limit}. Reset in {VAR_63}.".format( VAR_59=remaining, limit=VAR_60, VAR_63=delta, )) return VAR_41 async def FUNC_5(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref VAR_28 = "{VAR_25}/repos/{user}/{repo}/commits/{ref}".format( VAR_25=self.api_base_path.format(VAR_19=self.hostname), user=self.user, repo=self.repo, ref=self.unresolved_ref ) self.log.debug("Fetching %s", VAR_28) VAR_48 = self.cache.get(VAR_28) if VAR_48: VAR_29 = VAR_48['etag'] self.log.debug("Cache hit for %s: %s", VAR_28, VAR_29) else: VAR_24 = self.cache_404.get(VAR_28) if VAR_24: self.log.debug("Cache hit for 404 on %s", VAR_28) return None VAR_29 = None VAR_41 = await self.github_api_request(VAR_28, VAR_29=etag) if VAR_41 is None: self.log.debug("Caching 404 on %s", VAR_28) self.cache_404.set(VAR_28, True) return None if VAR_41.code == 304: self.log.info("Using VAR_48 ref for %s: %s", VAR_28, VAR_48['sha']) self.resolved_ref = VAR_48['sha'] self.cache.move_to_end(VAR_28) return self.resolved_ref elif VAR_48: self.log.debug("Cache outdated for %s", VAR_28) VAR_45 = json.loads(VAR_41.body.decode('utf-8')) if 'sha' not in VAR_45: self.log.warning("No sha for %s in %s", VAR_28, VAR_45) self.resolved_ref = None return None self.resolved_ref = VAR_45['sha'] self.cache.set( VAR_28, { 'etag': VAR_41.headers.get('ETag'), 'sha': self.resolved_ref, }, ) return self.resolved_ref async def FUNC_6(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f"{self.user}/{self.repo}/{self.resolved_ref}" def FUNC_9(self): return '{user}-{repo}'.format(user=self.user, repo=self.repo) class CLASS_9(CLASS_8): VAR_6 = Unicode("Gist") VAR_15 = "Gist" VAR_19 = Unicode("gist.github.com") VAR_30 = Bool( default_value=False, VAR_53=True, help="Flag for allowing usages of secret Gists. The default behavior is to disallow secret gists.", ) VAR_14 = { "text": "Gist ID (username/gistId) or URL", "tag_text": "Git commit SHA", "ref_prop_disabled": False, "label_prop_disabled": False, } def __init__(self, *VAR_17, **VAR_18): super(CLASS_0, self).__init__(*VAR_17, **VAR_18) VAR_49 = self.spec.split('/') self.user, self.gist_id, *VAR_50 = VAR_49 if len(VAR_49) > 2: self.unresolved_ref = VAR_49[2] else: self.unresolved_ref = '' def FUNC_7(self): return f'https://{self.hostname}/{self.user}/{self.gist_id}.git' async def FUNC_8(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f'https://{self.hostname}/{self.user}/{self.gist_id}/{self.resolved_ref}' async def FUNC_5(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref VAR_28 = f"https://api.github.com/gists/{self.gist_id}" self.log.debug("Fetching %s", VAR_28) VAR_41 = await self.github_api_request(VAR_28) if VAR_41 is None: return None VAR_45 = json.loads(VAR_41.body.decode('utf-8')) if (not self.allow_secret_gist) and (not VAR_45['public']): raise ValueError("You seem to want to use a secret Gist, but do not have permission to do so. " "To enable secret Gist support, set (or have an administrator set) " "'GistRepoProvider.allow_secret_gist = True'") VAR_51 = [e['version'] for e in VAR_45['history']] if self.unresolved_ref in {"", "HEAD", "master"}: self.resolved_ref = VAR_51[0] else: if self.unresolved_ref not in VAR_51: return None else: self.resolved_ref = self.unresolved_ref return self.resolved_ref async def FUNC_6(self): if not hasattr(self, 'resolved_ref'): self.resolved_ref = await self.get_resolved_ref() return f'{self.user}/{self.gist_id}/{self.resolved_ref}' def FUNC_9(self): return self.gist_id
[ 3, 6, 17, 20, 23, 26, 28, 31, 32, 35, 42, 44, 45, 50, 51, 59, 65, 69, 74, 78, 83, 87, 89, 98, 100, 108, 114, 115, 119, 125, 126, 130, 136, 137, 142, 143, 157, 158, 162, 165, 169, 173, 177, 181, 186, 187, 197, 200, 203, 206, 209, 212, 213, 216, 220, 222, 229, 237, 241, 242, 243, 244, 247, 249, 250, 252, 256, 259, 260, 263, 267, 269, 271, 278, 284, 291, 293, 297, 298, 299, 300, 303, 305, 306, 308, 312, 315, 316, 319, 321, 328, 334, 343, 345, 352, 353, 354, 361, 366, 371, 373, 374, 376, 379, 380, 386, 388, 390, 397, 404, 411, 417, 421, 423, 426, 428, 430, 432, 434, 438, 441, 442, 445, 447, 450, 454, 458, 460, 462, 469, 477, 481, 483, 486, 497, 499, 501, 506, 509, 511, 513, 516, 517, 520, 523, 525, 529, 531, 533, 536, 540, 543, 551, 554, 561, 564, 576, 582, 589, 597, 601, 610, 612, 614, 622, 626, 631, 633, 635, 638, 643, 644, 648, 650, 651, 653, 654, 655, 656, 657, 659, 663, 667, 671, 674, 678, 681, 689, 692, 700, 703, 710, 714, 715, 716, 723, 730, 735, 738, 743, 746, 752, 754, 757, 763, 784, 786, 790, 791, 796, 798, 802, 803, 805, 806, 814, 815, 820, 822, 826, 842, 851, 856, 859, 863, 873, 878, 881, 882, 885, 887, 889, 893, 896, 898, 900, 902, 908, 915, 917, 925, 928, 933, 937, 940, 944, 946, 951, 960, 962, 967, 970, 1, 2, 3, 4, 5, 6, 7, 8, 9, 34, 53, 189, 190, 215, 216, 217, 218, 262, 263, 264, 265, 382, 383, 384, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 646, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 110, 111, 112, 121, 122, 123, 132, 133, 134, 167, 171, 175, 179 ]
[ 3, 6, 17, 20, 23, 26, 28, 31, 32, 35, 42, 44, 45, 50, 51, 59, 65, 69, 74, 78, 83, 87, 89, 98, 100, 108, 114, 115, 119, 125, 126, 130, 136, 137, 142, 143, 157, 158, 162, 165, 169, 173, 177, 181, 186, 187, 197, 200, 203, 206, 209, 212, 213, 216, 220, 222, 229, 237, 241, 242, 243, 244, 247, 249, 250, 252, 256, 259, 260, 263, 267, 269, 271, 278, 284, 291, 293, 297, 298, 299, 300, 303, 305, 306, 308, 312, 315, 316, 319, 321, 328, 334, 343, 345, 352, 353, 354, 361, 366, 371, 373, 374, 376, 379, 380, 386, 388, 390, 397, 404, 411, 417, 421, 423, 426, 428, 430, 432, 434, 438, 441, 442, 445, 447, 450, 454, 458, 460, 462, 469, 477, 481, 483, 486, 497, 499, 501, 506, 509, 511, 513, 516, 517, 520, 523, 525, 529, 531, 533, 536, 540, 543, 551, 554, 561, 564, 576, 582, 589, 597, 601, 610, 612, 614, 622, 626, 631, 633, 635, 638, 643, 644, 648, 650, 651, 653, 654, 655, 656, 657, 659, 663, 667, 671, 674, 678, 681, 689, 692, 700, 703, 710, 714, 715, 716, 723, 730, 735, 738, 743, 746, 752, 754, 757, 763, 784, 786, 790, 791, 796, 798, 802, 803, 805, 806, 814, 815, 820, 822, 826, 842, 851, 856, 859, 863, 873, 878, 881, 882, 885, 887, 889, 893, 896, 898, 900, 902, 908, 915, 917, 925, 928, 933, 937, 940, 944, 946, 951, 960, 962, 967, 970, 1, 2, 3, 4, 5, 6, 7, 8, 9, 34, 53, 189, 190, 215, 216, 217, 218, 262, 263, 264, 265, 382, 383, 384, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 646, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 110, 111, 112, 121, 122, 123, 132, 133, 134, 167, 171, 175, 179 ]
0CWE-22
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CherryMusic - a standalone music server # Copyright (c) 2012 - 2015 Tom Wallroth & Tilman Boerner # # Project page: # http://fomori.org/cherrymusic/ # Sources on github: # http://github.com/devsnd/cherrymusic/ # # CherryMusic is based on # jPlayer (GPL/MIT license) http://www.jplayer.org/ # CherryPy (BSD license) http://www.cherrypy.org/ # # licensed under GNU GPL version 3 (or later) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # """This class provides the api to talk to the client. It will then call the cherrymodel, to get the requested information""" import os # shouldn't have to list any folder in the future! import json import cherrypy import codecs import sys try: from urllib.parse import unquote except ImportError: from backport.urllib.parse import unquote try: from urllib import parse except ImportError: from backport.urllib import parse import audiotranscode from tinytag import TinyTag from cherrymusicserver import userdb from cherrymusicserver import log from cherrymusicserver import albumartfetcher from cherrymusicserver import service from cherrymusicserver.pathprovider import readRes from cherrymusicserver.pathprovider import albumArtFilePath import cherrymusicserver as cherry import cherrymusicserver.metainfo as metainfo from cherrymusicserver.util import Performance, MemoryZipFile from cherrymusicserver.ext import zipstream import time debug = True @service.user(model='cherrymodel', playlistdb='playlist', useroptions='useroptions', userdb='users') class HTTPHandler(object): def __init__(self, config): self.config = config template_main = 'res/dist/main.html' template_login = 'res/login.html' template_firstrun = 'res/firstrun.html' self.mainpage = readRes(template_main) self.loginpage = readRes(template_login) self.firstrunpage = readRes(template_firstrun) self.handlers = { 'search': self.api_search, 'rememberplaylist': self.api_rememberplaylist, 'saveplaylist': self.api_saveplaylist, 'loadplaylist': self.api_loadplaylist, 'generaterandomplaylist': self.api_generaterandomplaylist, 'deleteplaylist': self.api_deleteplaylist, 'getmotd': self.api_getmotd, 'restoreplaylist': self.api_restoreplaylist, 'getplayables': self.api_getplayables, 'getuserlist': self.api_getuserlist, 'adduser': self.api_adduser, 'userdelete': self.api_userdelete, 'userchangepassword': self.api_userchangepassword, 'showplaylists': self.api_showplaylists, 'logout': self.api_logout, 'downloadpls': self.api_downloadpls, 'downloadm3u': self.api_downloadm3u, 'getsonginfo': self.api_getsonginfo, 'getencoders': self.api_getencoders, 'getdecoders': self.api_getdecoders, 'transcodingenabled': self.api_transcodingenabled, 'updatedb': self.api_updatedb, 'getconfiguration': self.api_getconfiguration, 'compactlistdir': self.api_compactlistdir, 'listdir': self.api_listdir, 'fetchalbumart': self.api_fetchalbumart, 'fetchalbumarturls': self.api_fetchalbumarturls, 'albumart_set': self.api_albumart_set, 'heartbeat': self.api_heartbeat, 'getuseroptions': self.api_getuseroptions, 'setuseroption': self.api_setuseroption, 'changeplaylist': self.api_changeplaylist, 'downloadcheck': self.api_downloadcheck, 'setuseroptionfor': self.api_setuseroptionfor, } def issecure(self, url): return parse.urlparse(url).scheme == 'https' def getBaseUrl(self, redirect_unencrypted=False): ipAndPort = parse.urlparse(cherrypy.url()).netloc is_secure_connection = self.issecure(cherrypy.url()) ssl_enabled = cherry.config['server.ssl_enabled'] if ssl_enabled and not is_secure_connection: log.d(_('Not secure, redirecting...')) ip = ipAndPort[:ipAndPort.rindex(':')] url = 'https://' + ip + ':' + str(cherry.config['server.ssl_port']) if redirect_unencrypted: raise cherrypy.HTTPRedirect(url, 302) else: url = 'http://' + ipAndPort return url def index(self, *args, **kwargs): self.getBaseUrl(redirect_unencrypted=True) firstrun = 0 == self.userdb.getUserCount() show_page = self.mainpage #generated main.html from devel.html if 'devel' in kwargs: #reload pages everytime in devel mode show_page = readRes('res/devel.html') self.loginpage = readRes('res/login.html') self.firstrunpage = readRes('res/firstrun.html') if 'login' in kwargs: username = kwargs.get('username', '') password = kwargs.get('password', '') login_action = kwargs.get('login', '') if login_action == 'login': self.session_auth(username, password) if cherrypy.session['username']: username = cherrypy.session['username'] log.i(_('user {name} just logged in.').format(name=username)) elif login_action == 'create admin user': if firstrun: if username.strip() and password.strip(): self.userdb.addUser(username, password, True) self.session_auth(username, password) return show_page else: return "No, you can't." if firstrun: return self.firstrunpage else: if self.isAuthorized(): return show_page else: return self.loginpage index.exposed = True def isAuthorized(self): try: sessionUsername = cherrypy.session.get('username', None) sessionUserId = cherrypy.session.get('userid', -1) nameById = self.userdb.getNameById(sessionUserId) except (UnicodeDecodeError, ValueError) as e: # workaround for python2/python3 jump, filed bug in cherrypy # https://bitbucket.org/cherrypy/cherrypy/issue/1216/sessions-python2-3-compability-unsupported log.w(_(''' Dropping all sessions! Try not to change between python 2 and 3, everybody has to relogin now.''')) cherrypy.session.delete() sessionUsername = None if sessionUsername is None: if self.autoLoginActive(): cherrypy.session['username'] = self.userdb.getNameById(1) cherrypy.session['userid'] = 1 cherrypy.session['admin'] = True return True else: return False elif sessionUsername != nameById: self.api_logout(value=None) return False return True def autoLoginActive(self): is_loopback = cherrypy.request.remote.ip in ('127.0.0.1', '::1') if is_loopback and cherry.config['server.localhost_auto_login']: return True return False def session_auth(self, username, password): user = self.userdb.auth(username, password) allow_remote = cherry.config['server.permit_remote_admin_login'] is_loopback = cherrypy.request.remote.ip in ('127.0.0.1', '::1') if not is_loopback and user.isadmin and not allow_remote: log.i(_('Rejected remote admin login from user: {name}').format(name=user.name)) user = userdb.User.nobody() cherrypy.session['username'] = user.name cherrypy.session['userid'] = user.uid cherrypy.session['admin'] = user.isadmin def getUserId(self): try: return cherrypy.session['userid'] except KeyError: cherrypy.lib.sessions.expire() cherrypy.HTTPRedirect(cherrypy.url(), 302) return '' def trans(self, newformat, *path, **params): ''' Transcodes the track given as ``path`` into ``newformat``. Streams the response of the corresponding ``audiotranscode.AudioTranscode().transcodeStream()`` call. params: bitrate: int for kbps. None or < 1 for default ''' if not self.isAuthorized(): raise cherrypy.HTTPRedirect(self.getBaseUrl(), 302) cherrypy.session.release_lock() if cherry.config['media.transcode'] and path: # bitrate bitrate = params.pop('bitrate', None) or None # catch empty strings if bitrate: try: bitrate = max(0, int(bitrate)) or None # None if < 1 except (TypeError, ValueError): raise cherrypy.HTTPError(400, "Bad query: " "bitrate ({0!r}) must be an integer".format(str(bitrate))) # path path = os.path.sep.join(path) if sys.version_info < (3, 0): # workaround for #327 (cherrypy issue) path = path.decode('utf-8') # make it work with non-ascii else: path = codecs.decode(codecs.encode(path, 'latin1'), 'utf-8') fullpath = os.path.join(cherry.config['media.basedir'], path) starttime = int(params.pop('starttime', 0)) transcoder = audiotranscode.AudioTranscode() mimetype = audiotranscode.mime_type(newformat) cherrypy.response.headers["Content-Type"] = mimetype try: return transcoder.transcode_stream(fullpath, newformat, bitrate=bitrate, starttime=starttime) except (audiotranscode.TranscodeError, IOError) as e: raise cherrypy.HTTPError(404, e.value) trans.exposed = True trans._cp_config = {'response.stream': True} def api(self, *args, **kwargs): """calls the appropriate handler from the handlers dict, if available. handlers having noauth set to true do not need authentification to work. """ #check action action = args[0] if args else '' if not action in self.handlers: return "Error: no such action. '%s'" % action #authorize if not explicitly deactivated handler = self.handlers[action] needsAuth = not ('noauth' in dir(handler) and handler.noauth) if needsAuth and not self.isAuthorized(): raise cherrypy.HTTPError(401, 'Unauthorized') handler_args = {} if 'data' in kwargs: handler_args = json.loads(kwargs['data']) is_binary = ('binary' in dir(handler) and handler.binary) if is_binary: return handler(**handler_args) else: return json.dumps({'data': handler(**handler_args)}) api.exposed = True def download_check_files(self, filelist): # only admins and allowed users may download if not cherrypy.session['admin']: uo = self.useroptions.forUser(self.getUserId()) if not uo.getOptionValue('media.may_download'): return 'not_permitted' # make sure nobody tries to escape from basedir for f in filelist: if '/../' in f: return 'invalid_file' # make sure all files are smaller than maximum download size size_limit = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(filelist, size_limit): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e) def api_downloadcheck(self, filelist): status = self.download_check_files(filelist) if status == 'not_permitted': return """You are not allowed to download files.""" elif status == 'invalid_file': return "Error: invalid filename found in {list}".format(list=filelist) elif status == 'too_big': size_limit = cherry.config['media.maximum_download_size'] return """Can't download: Playlist is bigger than {maxsize} mB. The server administrator can change this configuration. """.format(maxsize=size_limit/1024/1024) elif status == 'ok': return status else: message = "Error status check for download: {status!r}".format(status=status) log.e(message) return message def download(self, value): if not self.isAuthorized(): raise cherrypy.HTTPError(401, 'Unauthorized') filelist = [filepath for filepath in json.loads(unquote(value))] dlstatus = self.download_check_files(filelist) if dlstatus == 'ok': _save_and_release_session() zipmime = 'application/x-zip-compressed' cherrypy.response.headers["Content-Type"] = zipmime zipname = 'attachment; filename="music.zip"' cherrypy.response.headers['Content-Disposition'] = zipname basedir = cherry.config['media.basedir'] fullpath_filelist = [os.path.join(basedir, f) for f in filelist] return zipstream.ZipStream(fullpath_filelist) else: return dlstatus download.exposed = True download._cp_config = {'response.stream': True} def api_getuseroptions(self): uo = self.useroptions.forUser(self.getUserId()) uco = uo.getChangableOptions() if cherrypy.session['admin']: uco['media'].update({'may_download': True}) else: uco['media'].update({'may_download': uo.getOptionValue('media.may_download')}) return uco def api_heartbeat(self): uo = self.useroptions.forUser(self.getUserId()) uo.setOption('last_time_online', int(time.time())) def api_setuseroption(self, optionkey, optionval): uo = self.useroptions.forUser(self.getUserId()) uo.setOption(optionkey, optionval) return "success" def api_setuseroptionfor(self, userid, optionkey, optionval): if cherrypy.session['admin']: uo = self.useroptions.forUser(userid) uo.setOption(optionkey, optionval) return "success" else: return "error: not permitted. Only admins can change other users options" def api_fetchalbumarturls(self, searchterm): if not cherrypy.session['admin']: raise cherrypy.HTTPError(401, 'Unauthorized') _save_and_release_session() fetcher = albumartfetcher.AlbumArtFetcher() imgurls = fetcher.fetchurls(searchterm) # show no more than 10 images return imgurls[:min(len(imgurls), 10)] def api_albumart_set(self, directory, imageurl): if not cherrypy.session['admin']: raise cherrypy.HTTPError(401, 'Unauthorized') b64imgpath = albumArtFilePath(directory) fetcher = albumartfetcher.AlbumArtFetcher() data, header = fetcher.retrieveData(imageurl) self.albumartcache_save(b64imgpath, data) def api_fetchalbumart(self, directory): _save_and_release_session() default_folder_image = "../res/img/folder.png" log.i('Fetching album art for: %s' % directory) filepath = os.path.join(cherry.config['media.basedir'], directory) if os.path.isfile(filepath): # if the given path is a file, try to get the image from ID3 tag = TinyTag.get(filepath, image=True) image_data = tag.get_image() if image_data: log.d('Image found in tag.') header = {'Content-Type': 'image/jpg', 'Content-Length': len(image_data)} cherrypy.response.headers.update(header) return image_data else: # if the file does not contain an image, display the image of the # parent directory directory = os.path.dirname(directory) #try getting a cached album art image b64imgpath = albumArtFilePath(directory) img_data = self.albumartcache_load(b64imgpath) if img_data: cherrypy.response.headers["Content-Length"] = len(img_data) return img_data #try getting album art inside local folder fetcher = albumartfetcher.AlbumArtFetcher() localpath = os.path.join(cherry.config['media.basedir'], directory) header, data, resized = fetcher.fetchLocal(localpath) if header: if resized: #cache resized image for next time self.albumartcache_save(b64imgpath, data) cherrypy.response.headers.update(header) return data elif cherry.config['media.fetch_album_art']: #fetch album art from online source try: foldername = os.path.basename(directory) keywords = foldername log.i(_("Fetching album art for keywords {keywords!r}").format(keywords=keywords)) header, data = fetcher.fetch(keywords) if header: cherrypy.response.headers.update(header) self.albumartcache_save(b64imgpath, data) return data else: # albumart fetcher failed, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) except: # albumart fetcher threw exception, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) else: # no local album art found, online fetching deactivated, show default raise cherrypy.HTTPRedirect(default_folder_image, 302) api_fetchalbumart.noauth = True api_fetchalbumart.binary = True def albumartcache_load(self, imgb64path): if os.path.exists(imgb64path): with open(imgb64path, 'rb') as f: return f.read() def albumartcache_save(self, path, data): with open(path, 'wb') as f: f.write(data) def api_compactlistdir(self, directory, filterstr=None): try: files_to_list = self.model.listdir(directory, filterstr) except ValueError: raise cherrypy.HTTPError(400, 'Bad Request') return [entry.to_dict() for entry in files_to_list] def api_listdir(self, directory): try: return [entry.to_dict() for entry in self.model.listdir(directory)] except ValueError: raise cherrypy.HTTPError(400, 'Bad Request') def api_search(self, searchstring): if not searchstring.strip(): jsonresults = '[]' else: with Performance(_('processing whole search request')): searchresults = self.model.search(searchstring.strip()) with Performance(_('rendering search results as json')): jsonresults = [entry.to_dict() for entry in searchresults] return jsonresults def api_rememberplaylist(self, playlist): cherrypy.session['playlist'] = playlist def api_saveplaylist(self, playlist, public, playlistname, overwrite=False): res = self.playlistdb.savePlaylist( userid=self.getUserId(), public=1 if public else 0, playlist=playlist, playlisttitle=playlistname, overwrite=overwrite) if res == "success": return res else: raise cherrypy.HTTPError(400, res) def api_deleteplaylist(self, playlistid): res = self.playlistdb.deletePlaylist(playlistid, self.getUserId(), override_owner=False) if res == "success": return res else: # not the ideal status code but we don't know the actual # cause without parsing res raise cherrypy.HTTPError(400, res) def api_loadplaylist(self, playlistid): return [entry.to_dict() for entry in self.playlistdb.loadPlaylist( playlistid=playlistid, userid=self.getUserId() )] def api_generaterandomplaylist(self): return [entry.to_dict() for entry in self.model.randomMusicEntries(50)] def api_changeplaylist(self, plid, attribute, value): if attribute == 'public': is_valid = type(value) == bool and type(plid) == int if is_valid: return self.playlistdb.setPublic(userid=self.getUserId(), plid=plid, public=value) def api_getmotd(self): if cherrypy.session['admin'] and cherry.config['general.update_notification']: _save_and_release_session() new_versions = self.model.check_for_updates() if new_versions: newest_version = new_versions[0]['version'] features = [] fixes = [] for version in new_versions: for update in version['features']: if update.startswith('FEATURE:'): features.append(update[len('FEATURE:'):]) elif update.startswith('FIX:'): fixes.append(update[len('FIX:'):]) elif update.startswith('FIXED:'): fixes.append(update[len('FIXED:'):]) retdata = {'type': 'update', 'data': {}} retdata['data']['version'] = newest_version retdata['data']['features'] = features retdata['data']['fixes'] = fixes return retdata return {'type': 'wisdom', 'data': self.model.motd()} def api_restoreplaylist(self): session_playlist = cherrypy.session.get('playlist', []) return session_playlist def api_getplayables(self): """DEPRECATED""" return json.dumps(cherry.config['media.playable']) def api_getuserlist(self): if cherrypy.session['admin']: userlist = self.userdb.getUserList() for user in userlist: if user['id'] == cherrypy.session['userid']: user['deletable'] = False user_options = self.useroptions.forUser(user['id']) t = user_options.getOptionValue('last_time_online') may_download = user_options.getOptionValue('media.may_download') user['last_time_online'] = t user['may_download'] = may_download sortfunc = lambda user: user['last_time_online'] userlist = sorted(userlist, key=sortfunc, reverse=True) return json.dumps({'time': int(time.time()), 'userlist': userlist}) else: return json.dumps({'time': 0, 'userlist': []}) def api_adduser(self, username, password, isadmin): if cherrypy.session['admin']: if self.userdb.addUser(username, password, isadmin): return 'added new user: %s' % username else: return 'error, cannot add new user!' % username else: return "You didn't think that would work, did you?" def api_userchangepassword(self, oldpassword, newpassword, username=''): isself = username == '' if isself: username = cherrypy.session['username'] authed_user = self.userdb.auth(username, oldpassword) is_authenticated = userdb.User.nobody() != authed_user if not is_authenticated: raise cherrypy.HTTPError(403, "Forbidden") if isself or cherrypy.session['admin']: return self.userdb.changePassword(username, newpassword) else: raise cherrypy.HTTPError(403, "Forbidden") def api_userdelete(self, userid): is_self = cherrypy.session['userid'] == userid if cherrypy.session['admin'] and not is_self: deleted = self.userdb.deleteUser(userid) return 'success' if deleted else 'failed' else: return "You didn't think that would work, did you?" def api_showplaylists(self, sortby="created", filterby=''): playlists = self.playlistdb.showPlaylists(self.getUserId(), filterby) curr_time = int(time.time()) is_reverse = False #translate userids to usernames: for pl in playlists: pl['username'] = self.userdb.getNameById(pl['userid']) pl['type'] = 'playlist' pl['age'] = curr_time - pl['created'] if sortby[0] == '-': is_reverse = True sortby = sortby[1:] if not sortby in ('username', 'age', 'title', 'default'): sortby = 'created' if sortby == 'default': sortby = 'age' is_reverse = False playlists = sorted(playlists, key=lambda x: x[sortby], reverse = is_reverse) return playlists def api_logout(self): cherrypy.lib.sessions.expire() api_logout.no_auth = True def api_downloadpls(self, plid, hostaddr): userid = self.getUserId() pls = self.playlistdb.createPLS(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) if pls and name: return self.serve_string_as_file(pls, name+'.pls') api_downloadpls.binary = True def api_downloadm3u(self, plid, hostaddr): userid = self.getUserId() pls = self.playlistdb.createM3U(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) if pls and name: return self.serve_string_as_file(pls, name+'.m3u') api_downloadm3u.binary = True def export_playlists(self, format, all=False, hostaddr=''): userid = self.getUserId() if not userid: raise cherrypy.HTTPError(401, _("Please log in")) hostaddr = (hostaddr.strip().rstrip('/') + cherry.config['server.rootpath']).rstrip('/') format = format.lower() if format == 'm3u': filemaker = self.playlistdb.createM3U elif format == 'pls': filemaker = self.playlistdb.createPLS else: raise cherrypy.HTTPError(400, _('Unknown playlist format: {format!r}').format(format=format)) playlists = self.playlistdb.showPlaylists(userid, include_public=all) if not playlists: raise cherrypy.HTTPError(404, _('No playlists found')) with MemoryZipFile() as zip: for pl in playlists: plid = pl['plid'] plstr = filemaker(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) + '.' + format if not pl['owner']: username = self.userdb.getNameById(pl['userid']) name = username + '/' + name zip.writestr(name, plstr) zipmime = 'application/x-zip-compressed' zipname = 'attachment; filename="playlists.zip"' cherrypy.response.headers["Content-Type"] = zipmime cherrypy.response.headers['Content-Disposition'] = zipname return zip.getbytes() export_playlists.exposed = True def api_getsonginfo(self, path): basedir = cherry.config['media.basedir'] abspath = os.path.join(basedir, path) return json.dumps(metainfo.getSongInfo(abspath).dict()) def api_getencoders(self): return json.dumps(audiotranscode.getEncoders()) def api_getdecoders(self): return json.dumps(audiotranscode.getDecoders()) def api_transcodingenabled(self): return json.dumps(cherry.config['media.transcode']) def api_updatedb(self): self.model.updateLibrary() return 'success' def api_getconfiguration(self): clientconfigkeys = { 'transcodingenabled': cherry.config['media.transcode'], 'fetchalbumart': cherry.config['media.fetch_album_art'], 'isadmin': cherrypy.session['admin'], 'username': cherrypy.session['username'], 'servepath': 'serve/', 'transcodepath': 'trans/', 'auto_login': self.autoLoginActive(), 'version': cherry.REPO_VERSION or cherry.VERSION, } if cherry.config['media.transcode']: decoders = list(self.model.transcoder.available_decoder_formats()) clientconfigkeys['getdecoders'] = decoders encoders = list(self.model.transcoder.available_encoder_formats()) clientconfigkeys['getencoders'] = encoders else: clientconfigkeys['getdecoders'] = [] clientconfigkeys['getencoders'] = [] return clientconfigkeys def serve_string_as_file(self, string, filename): content_disposition = 'attachment; filename="'+filename+'"' cherrypy.response.headers["Content-Type"] = "application/x-download" cherrypy.response.headers["Content-Disposition"] = content_disposition return codecs.encode(string, "UTF-8") def _save_and_release_session(): """ workaround to cleanly release FileSessions in Cherrypy >= 3.3 From https://github.com/devsnd/cherrymusic/issues/483: > CherryPy >=3.3.0 (up to current version, 3.6) makes it impossible to > explicitly release FileSession locks, because: > 1. FileSession.save() asserts that the session is locked; and > 2. _cptools.SessionTool always adds a hook to call sessions.save > before the response is finalized. > If we still want to release the session in a controller, I guess the > best way to work around this is to remove the hook before the > controller returns: """ cherrypy.session.save() hooks = cherrypy.serving.request.hooks['before_finalize'] forbidden = cherrypy.lib.sessions.save hooks[:] = [h for h in hooks if h.callback is not forbidden] # there's likely only one hook, since a 2nd call to save would always fail; # but let's be safe, and block all calls to save :)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CherryMusic - a standalone music server # Copyright (c) 2012 - 2015 Tom Wallroth & Tilman Boerner # # Project page: # http://fomori.org/cherrymusic/ # Sources on github: # http://github.com/devsnd/cherrymusic/ # # CherryMusic is based on # jPlayer (GPL/MIT license) http://www.jplayer.org/ # CherryPy (BSD license) http://www.cherrypy.org/ # # licensed under GNU GPL version 3 (or later) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # """This class provides the api to talk to the client. It will then call the cherrymodel, to get the requested information""" import os # shouldn't have to list any folder in the future! import json import cherrypy import codecs import sys try: from urllib.parse import unquote except ImportError: from backport.urllib.parse import unquote try: from urllib import parse except ImportError: from backport.urllib import parse import audiotranscode from tinytag import TinyTag from cherrymusicserver import userdb from cherrymusicserver import log from cherrymusicserver import albumartfetcher from cherrymusicserver import service from cherrymusicserver.pathprovider import readRes from cherrymusicserver.pathprovider import albumArtFilePath import cherrymusicserver as cherry import cherrymusicserver.metainfo as metainfo from cherrymusicserver.util import Performance, MemoryZipFile from cherrymusicserver.ext import zipstream import time debug = True @service.user(model='cherrymodel', playlistdb='playlist', useroptions='useroptions', userdb='users') class HTTPHandler(object): def __init__(self, config): self.config = config template_main = 'res/dist/main.html' template_login = 'res/login.html' template_firstrun = 'res/firstrun.html' self.mainpage = readRes(template_main) self.loginpage = readRes(template_login) self.firstrunpage = readRes(template_firstrun) self.handlers = { 'search': self.api_search, 'rememberplaylist': self.api_rememberplaylist, 'saveplaylist': self.api_saveplaylist, 'loadplaylist': self.api_loadplaylist, 'generaterandomplaylist': self.api_generaterandomplaylist, 'deleteplaylist': self.api_deleteplaylist, 'getmotd': self.api_getmotd, 'restoreplaylist': self.api_restoreplaylist, 'getplayables': self.api_getplayables, 'getuserlist': self.api_getuserlist, 'adduser': self.api_adduser, 'userdelete': self.api_userdelete, 'userchangepassword': self.api_userchangepassword, 'showplaylists': self.api_showplaylists, 'logout': self.api_logout, 'downloadpls': self.api_downloadpls, 'downloadm3u': self.api_downloadm3u, 'getsonginfo': self.api_getsonginfo, 'getencoders': self.api_getencoders, 'getdecoders': self.api_getdecoders, 'transcodingenabled': self.api_transcodingenabled, 'updatedb': self.api_updatedb, 'getconfiguration': self.api_getconfiguration, 'compactlistdir': self.api_compactlistdir, 'listdir': self.api_listdir, 'fetchalbumart': self.api_fetchalbumart, 'fetchalbumarturls': self.api_fetchalbumarturls, 'albumart_set': self.api_albumart_set, 'heartbeat': self.api_heartbeat, 'getuseroptions': self.api_getuseroptions, 'setuseroption': self.api_setuseroption, 'changeplaylist': self.api_changeplaylist, 'downloadcheck': self.api_downloadcheck, 'setuseroptionfor': self.api_setuseroptionfor, } def issecure(self, url): return parse.urlparse(url).scheme == 'https' def getBaseUrl(self, redirect_unencrypted=False): ipAndPort = parse.urlparse(cherrypy.url()).netloc is_secure_connection = self.issecure(cherrypy.url()) ssl_enabled = cherry.config['server.ssl_enabled'] if ssl_enabled and not is_secure_connection: log.d(_('Not secure, redirecting...')) ip = ipAndPort[:ipAndPort.rindex(':')] url = 'https://' + ip + ':' + str(cherry.config['server.ssl_port']) if redirect_unencrypted: raise cherrypy.HTTPRedirect(url, 302) else: url = 'http://' + ipAndPort return url def index(self, *args, **kwargs): self.getBaseUrl(redirect_unencrypted=True) firstrun = 0 == self.userdb.getUserCount() show_page = self.mainpage #generated main.html from devel.html if 'devel' in kwargs: #reload pages everytime in devel mode show_page = readRes('res/devel.html') self.loginpage = readRes('res/login.html') self.firstrunpage = readRes('res/firstrun.html') if 'login' in kwargs: username = kwargs.get('username', '') password = kwargs.get('password', '') login_action = kwargs.get('login', '') if login_action == 'login': self.session_auth(username, password) if cherrypy.session['username']: username = cherrypy.session['username'] log.i(_('user {name} just logged in.').format(name=username)) elif login_action == 'create admin user': if firstrun: if username.strip() and password.strip(): self.userdb.addUser(username, password, True) self.session_auth(username, password) return show_page else: return "No, you can't." if firstrun: return self.firstrunpage else: if self.isAuthorized(): return show_page else: return self.loginpage index.exposed = True def isAuthorized(self): try: sessionUsername = cherrypy.session.get('username', None) sessionUserId = cherrypy.session.get('userid', -1) nameById = self.userdb.getNameById(sessionUserId) except (UnicodeDecodeError, ValueError) as e: # workaround for python2/python3 jump, filed bug in cherrypy # https://bitbucket.org/cherrypy/cherrypy/issue/1216/sessions-python2-3-compability-unsupported log.w(_(''' Dropping all sessions! Try not to change between python 2 and 3, everybody has to relogin now.''')) cherrypy.session.delete() sessionUsername = None if sessionUsername is None: if self.autoLoginActive(): cherrypy.session['username'] = self.userdb.getNameById(1) cherrypy.session['userid'] = 1 cherrypy.session['admin'] = True return True else: return False elif sessionUsername != nameById: self.api_logout(value=None) return False return True def autoLoginActive(self): is_loopback = cherrypy.request.remote.ip in ('127.0.0.1', '::1') if is_loopback and cherry.config['server.localhost_auto_login']: return True return False def session_auth(self, username, password): user = self.userdb.auth(username, password) allow_remote = cherry.config['server.permit_remote_admin_login'] is_loopback = cherrypy.request.remote.ip in ('127.0.0.1', '::1') if not is_loopback and user.isadmin and not allow_remote: log.i(_('Rejected remote admin login from user: {name}').format(name=user.name)) user = userdb.User.nobody() cherrypy.session['username'] = user.name cherrypy.session['userid'] = user.uid cherrypy.session['admin'] = user.isadmin def getUserId(self): try: return cherrypy.session['userid'] except KeyError: cherrypy.lib.sessions.expire() cherrypy.HTTPRedirect(cherrypy.url(), 302) return '' def trans(self, newformat, *path, **params): ''' Transcodes the track given as ``path`` into ``newformat``. Streams the response of the corresponding ``audiotranscode.AudioTranscode().transcodeStream()`` call. params: bitrate: int for kbps. None or < 1 for default ''' if not self.isAuthorized(): raise cherrypy.HTTPRedirect(self.getBaseUrl(), 302) cherrypy.session.release_lock() if cherry.config['media.transcode'] and path: # bitrate bitrate = params.pop('bitrate', None) or None # catch empty strings if bitrate: try: bitrate = max(0, int(bitrate)) or None # None if < 1 except (TypeError, ValueError): raise cherrypy.HTTPError(400, "Bad query: " "bitrate ({0!r}) must be an integer".format(str(bitrate))) # path path = os.path.sep.join(path) if sys.version_info < (3, 0): # workaround for #327 (cherrypy issue) path = path.decode('utf-8') # make it work with non-ascii else: path = codecs.decode(codecs.encode(path, 'latin1'), 'utf-8') fullpath = os.path.join(cherry.config['media.basedir'], path) starttime = int(params.pop('starttime', 0)) transcoder = audiotranscode.AudioTranscode() mimetype = audiotranscode.mime_type(newformat) cherrypy.response.headers["Content-Type"] = mimetype try: return transcoder.transcode_stream(fullpath, newformat, bitrate=bitrate, starttime=starttime) except (audiotranscode.TranscodeError, IOError) as e: raise cherrypy.HTTPError(404, e.value) trans.exposed = True trans._cp_config = {'response.stream': True} def api(self, *args, **kwargs): """calls the appropriate handler from the handlers dict, if available. handlers having noauth set to true do not need authentification to work. """ #check action action = args[0] if args else '' if not action in self.handlers: return "Error: no such action. '%s'" % action #authorize if not explicitly deactivated handler = self.handlers[action] needsAuth = not ('noauth' in dir(handler) and handler.noauth) if needsAuth and not self.isAuthorized(): raise cherrypy.HTTPError(401, 'Unauthorized') handler_args = {} if 'data' in kwargs: handler_args = json.loads(kwargs['data']) is_binary = ('binary' in dir(handler) and handler.binary) if is_binary: return handler(**handler_args) else: return json.dumps({'data': handler(**handler_args)}) api.exposed = True def download_check_files(self, filelist): # only admins and allowed users may download if not cherrypy.session['admin']: uo = self.useroptions.forUser(self.getUserId()) if not uo.getOptionValue('media.may_download'): return 'not_permitted' # make sure nobody tries to escape from basedir for f in filelist: # don't allow to traverse up in the file system if '/../' in f or f.startswith('../'): return 'invalid_file' # CVE-2015-8309: do not allow absolute file paths if os.path.isabs(f): return 'invalid_file' # make sure all files are smaller than maximum download size size_limit = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(filelist, size_limit): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e) def api_downloadcheck(self, filelist): status = self.download_check_files(filelist) if status == 'not_permitted': return """You are not allowed to download files.""" elif status == 'invalid_file': return "Error: invalid filename found in {list}".format(list=filelist) elif status == 'too_big': size_limit = cherry.config['media.maximum_download_size'] return """Can't download: Playlist is bigger than {maxsize} mB. The server administrator can change this configuration. """.format(maxsize=size_limit/1024/1024) elif status == 'ok': return status else: message = "Error status check for download: {status!r}".format(status=status) log.e(message) return message def download(self, value): if not self.isAuthorized(): raise cherrypy.HTTPError(401, 'Unauthorized') filelist = [filepath for filepath in json.loads(unquote(value))] dlstatus = self.download_check_files(filelist) if dlstatus == 'ok': _save_and_release_session() zipmime = 'application/x-zip-compressed' cherrypy.response.headers["Content-Type"] = zipmime zipname = 'attachment; filename="music.zip"' cherrypy.response.headers['Content-Disposition'] = zipname basedir = cherry.config['media.basedir'] fullpath_filelist = [os.path.join(basedir, f) for f in filelist] return zipstream.ZipStream(fullpath_filelist) else: return dlstatus download.exposed = True download._cp_config = {'response.stream': True} def api_getuseroptions(self): uo = self.useroptions.forUser(self.getUserId()) uco = uo.getChangableOptions() if cherrypy.session['admin']: uco['media'].update({'may_download': True}) else: uco['media'].update({'may_download': uo.getOptionValue('media.may_download')}) return uco def api_heartbeat(self): uo = self.useroptions.forUser(self.getUserId()) uo.setOption('last_time_online', int(time.time())) def api_setuseroption(self, optionkey, optionval): uo = self.useroptions.forUser(self.getUserId()) uo.setOption(optionkey, optionval) return "success" def api_setuseroptionfor(self, userid, optionkey, optionval): if cherrypy.session['admin']: uo = self.useroptions.forUser(userid) uo.setOption(optionkey, optionval) return "success" else: return "error: not permitted. Only admins can change other users options" def api_fetchalbumarturls(self, searchterm): if not cherrypy.session['admin']: raise cherrypy.HTTPError(401, 'Unauthorized') _save_and_release_session() fetcher = albumartfetcher.AlbumArtFetcher() imgurls = fetcher.fetchurls(searchterm) # show no more than 10 images return imgurls[:min(len(imgurls), 10)] def api_albumart_set(self, directory, imageurl): if not cherrypy.session['admin']: raise cherrypy.HTTPError(401, 'Unauthorized') b64imgpath = albumArtFilePath(directory) fetcher = albumartfetcher.AlbumArtFetcher() data, header = fetcher.retrieveData(imageurl) self.albumartcache_save(b64imgpath, data) def api_fetchalbumart(self, directory): _save_and_release_session() default_folder_image = "../res/img/folder.png" log.i('Fetching album art for: %s' % directory) filepath = os.path.join(cherry.config['media.basedir'], directory) if os.path.isfile(filepath): # if the given path is a file, try to get the image from ID3 tag = TinyTag.get(filepath, image=True) image_data = tag.get_image() if image_data: log.d('Image found in tag.') header = {'Content-Type': 'image/jpg', 'Content-Length': len(image_data)} cherrypy.response.headers.update(header) return image_data else: # if the file does not contain an image, display the image of the # parent directory directory = os.path.dirname(directory) #try getting a cached album art image b64imgpath = albumArtFilePath(directory) img_data = self.albumartcache_load(b64imgpath) if img_data: cherrypy.response.headers["Content-Length"] = len(img_data) return img_data #try getting album art inside local folder fetcher = albumartfetcher.AlbumArtFetcher() localpath = os.path.join(cherry.config['media.basedir'], directory) header, data, resized = fetcher.fetchLocal(localpath) if header: if resized: #cache resized image for next time self.albumartcache_save(b64imgpath, data) cherrypy.response.headers.update(header) return data elif cherry.config['media.fetch_album_art']: #fetch album art from online source try: foldername = os.path.basename(directory) keywords = foldername log.i(_("Fetching album art for keywords {keywords!r}").format(keywords=keywords)) header, data = fetcher.fetch(keywords) if header: cherrypy.response.headers.update(header) self.albumartcache_save(b64imgpath, data) return data else: # albumart fetcher failed, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) except: # albumart fetcher threw exception, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) else: # no local album art found, online fetching deactivated, show default raise cherrypy.HTTPRedirect(default_folder_image, 302) api_fetchalbumart.noauth = True api_fetchalbumart.binary = True def albumartcache_load(self, imgb64path): if os.path.exists(imgb64path): with open(imgb64path, 'rb') as f: return f.read() def albumartcache_save(self, path, data): with open(path, 'wb') as f: f.write(data) def api_compactlistdir(self, directory, filterstr=None): try: files_to_list = self.model.listdir(directory, filterstr) except ValueError: raise cherrypy.HTTPError(400, 'Bad Request') return [entry.to_dict() for entry in files_to_list] def api_listdir(self, directory): try: return [entry.to_dict() for entry in self.model.listdir(directory)] except ValueError: raise cherrypy.HTTPError(400, 'Bad Request') def api_search(self, searchstring): if not searchstring.strip(): jsonresults = '[]' else: with Performance(_('processing whole search request')): searchresults = self.model.search(searchstring.strip()) with Performance(_('rendering search results as json')): jsonresults = [entry.to_dict() for entry in searchresults] return jsonresults def api_rememberplaylist(self, playlist): cherrypy.session['playlist'] = playlist def api_saveplaylist(self, playlist, public, playlistname, overwrite=False): res = self.playlistdb.savePlaylist( userid=self.getUserId(), public=1 if public else 0, playlist=playlist, playlisttitle=playlistname, overwrite=overwrite) if res == "success": return res else: raise cherrypy.HTTPError(400, res) def api_deleteplaylist(self, playlistid): res = self.playlistdb.deletePlaylist(playlistid, self.getUserId(), override_owner=False) if res == "success": return res else: # not the ideal status code but we don't know the actual # cause without parsing res raise cherrypy.HTTPError(400, res) def api_loadplaylist(self, playlistid): return [entry.to_dict() for entry in self.playlistdb.loadPlaylist( playlistid=playlistid, userid=self.getUserId() )] def api_generaterandomplaylist(self): return [entry.to_dict() for entry in self.model.randomMusicEntries(50)] def api_changeplaylist(self, plid, attribute, value): if attribute == 'public': is_valid = type(value) == bool and type(plid) == int if is_valid: return self.playlistdb.setPublic(userid=self.getUserId(), plid=plid, public=value) def api_getmotd(self): if cherrypy.session['admin'] and cherry.config['general.update_notification']: _save_and_release_session() new_versions = self.model.check_for_updates() if new_versions: newest_version = new_versions[0]['version'] features = [] fixes = [] for version in new_versions: for update in version['features']: if update.startswith('FEATURE:'): features.append(update[len('FEATURE:'):]) elif update.startswith('FIX:'): fixes.append(update[len('FIX:'):]) elif update.startswith('FIXED:'): fixes.append(update[len('FIXED:'):]) retdata = {'type': 'update', 'data': {}} retdata['data']['version'] = newest_version retdata['data']['features'] = features retdata['data']['fixes'] = fixes return retdata return {'type': 'wisdom', 'data': self.model.motd()} def api_restoreplaylist(self): session_playlist = cherrypy.session.get('playlist', []) return session_playlist def api_getplayables(self): """DEPRECATED""" return json.dumps(cherry.config['media.playable']) def api_getuserlist(self): if cherrypy.session['admin']: userlist = self.userdb.getUserList() for user in userlist: if user['id'] == cherrypy.session['userid']: user['deletable'] = False user_options = self.useroptions.forUser(user['id']) t = user_options.getOptionValue('last_time_online') may_download = user_options.getOptionValue('media.may_download') user['last_time_online'] = t user['may_download'] = may_download sortfunc = lambda user: user['last_time_online'] userlist = sorted(userlist, key=sortfunc, reverse=True) return json.dumps({'time': int(time.time()), 'userlist': userlist}) else: return json.dumps({'time': 0, 'userlist': []}) def api_adduser(self, username, password, isadmin): if cherrypy.session['admin']: if self.userdb.addUser(username, password, isadmin): return 'added new user: %s' % username else: return 'error, cannot add new user!' % username else: return "You didn't think that would work, did you?" def api_userchangepassword(self, oldpassword, newpassword, username=''): isself = username == '' if isself: username = cherrypy.session['username'] authed_user = self.userdb.auth(username, oldpassword) is_authenticated = userdb.User.nobody() != authed_user if not is_authenticated: raise cherrypy.HTTPError(403, "Forbidden") if isself or cherrypy.session['admin']: return self.userdb.changePassword(username, newpassword) else: raise cherrypy.HTTPError(403, "Forbidden") def api_userdelete(self, userid): is_self = cherrypy.session['userid'] == userid if cherrypy.session['admin'] and not is_self: deleted = self.userdb.deleteUser(userid) return 'success' if deleted else 'failed' else: return "You didn't think that would work, did you?" def api_showplaylists(self, sortby="created", filterby=''): playlists = self.playlistdb.showPlaylists(self.getUserId(), filterby) curr_time = int(time.time()) is_reverse = False #translate userids to usernames: for pl in playlists: pl['username'] = self.userdb.getNameById(pl['userid']) pl['type'] = 'playlist' pl['age'] = curr_time - pl['created'] if sortby[0] == '-': is_reverse = True sortby = sortby[1:] if not sortby in ('username', 'age', 'title', 'default'): sortby = 'created' if sortby == 'default': sortby = 'age' is_reverse = False playlists = sorted(playlists, key=lambda x: x[sortby], reverse = is_reverse) return playlists def api_logout(self): cherrypy.lib.sessions.expire() api_logout.no_auth = True def api_downloadpls(self, plid, hostaddr): userid = self.getUserId() pls = self.playlistdb.createPLS(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) if pls and name: return self.serve_string_as_file(pls, name+'.pls') api_downloadpls.binary = True def api_downloadm3u(self, plid, hostaddr): userid = self.getUserId() pls = self.playlistdb.createM3U(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) if pls and name: return self.serve_string_as_file(pls, name+'.m3u') api_downloadm3u.binary = True def export_playlists(self, format, all=False, hostaddr=''): userid = self.getUserId() if not userid: raise cherrypy.HTTPError(401, _("Please log in")) hostaddr = (hostaddr.strip().rstrip('/') + cherry.config['server.rootpath']).rstrip('/') format = format.lower() if format == 'm3u': filemaker = self.playlistdb.createM3U elif format == 'pls': filemaker = self.playlistdb.createPLS else: raise cherrypy.HTTPError(400, _('Unknown playlist format: {format!r}').format(format=format)) playlists = self.playlistdb.showPlaylists(userid, include_public=all) if not playlists: raise cherrypy.HTTPError(404, _('No playlists found')) with MemoryZipFile() as zip: for pl in playlists: plid = pl['plid'] plstr = filemaker(plid=plid, userid=userid, addrstr=hostaddr) name = self.playlistdb.getName(plid, userid) + '.' + format if not pl['owner']: username = self.userdb.getNameById(pl['userid']) name = username + '/' + name zip.writestr(name, plstr) zipmime = 'application/x-zip-compressed' zipname = 'attachment; filename="playlists.zip"' cherrypy.response.headers["Content-Type"] = zipmime cherrypy.response.headers['Content-Disposition'] = zipname return zip.getbytes() export_playlists.exposed = True def api_getsonginfo(self, path): basedir = cherry.config['media.basedir'] abspath = os.path.join(basedir, path) return json.dumps(metainfo.getSongInfo(abspath).dict()) def api_getencoders(self): return json.dumps(audiotranscode.getEncoders()) def api_getdecoders(self): return json.dumps(audiotranscode.getDecoders()) def api_transcodingenabled(self): return json.dumps(cherry.config['media.transcode']) def api_updatedb(self): self.model.updateLibrary() return 'success' def api_getconfiguration(self): clientconfigkeys = { 'transcodingenabled': cherry.config['media.transcode'], 'fetchalbumart': cherry.config['media.fetch_album_art'], 'isadmin': cherrypy.session['admin'], 'username': cherrypy.session['username'], 'servepath': 'serve/', 'transcodepath': 'trans/', 'auto_login': self.autoLoginActive(), 'version': cherry.REPO_VERSION or cherry.VERSION, } if cherry.config['media.transcode']: decoders = list(self.model.transcoder.available_decoder_formats()) clientconfigkeys['getdecoders'] = decoders encoders = list(self.model.transcoder.available_encoder_formats()) clientconfigkeys['getencoders'] = encoders else: clientconfigkeys['getdecoders'] = [] clientconfigkeys['getencoders'] = [] return clientconfigkeys def serve_string_as_file(self, string, filename): content_disposition = 'attachment; filename="'+filename+'"' cherrypy.response.headers["Content-Type"] = "application/x-download" cherrypy.response.headers["Content-Disposition"] = content_disposition return codecs.encode(string, "UTF-8") def _save_and_release_session(): """ workaround to cleanly release FileSessions in Cherrypy >= 3.3 From https://github.com/devsnd/cherrymusic/issues/483: > CherryPy >=3.3.0 (up to current version, 3.6) makes it impossible to > explicitly release FileSession locks, because: > 1. FileSession.save() asserts that the session is locked; and > 2. _cptools.SessionTool always adds a hook to call sessions.save > before the response is finalized. > If we still want to release the session in a controller, I guess the > best way to work around this is to remove the hook before the > controller returns: """ cherrypy.session.save() hooks = cherrypy.serving.request.hooks['before_finalize'] forbidden = cherrypy.lib.sessions.save hooks[:] = [h for h in hooks if h.callback is not forbidden] # there's likely only one hook, since a 2nd call to save would always fail; # but let's be safe, and block all calls to save :)
path_disclosure
{ "code": [ " if '/../' in f:" ], "line_no": [ 303 ] }
{ "code": [ " if '/../' in f or f.startswith('../'):", " if os.path.isabs(f):" ], "line_no": [ 304, 307 ] }
import os # shouldn't have to list any folder in the future! import json import .cherrypy import codecs import sys try: from urllib.parse import unquote except ImportError: from backport.urllib.parse import unquote try: from urllib import parse except ImportError: from backport.urllib import parse import audiotranscode from tinytag import TinyTag from cherrymusicserver import .userdb from cherrymusicserver import log from cherrymusicserver import albumartfetcher from cherrymusicserver import service from cherrymusicserver.pathprovider import readRes from cherrymusicserver.pathprovider import albumArtFilePath import cherrymusicserver as cherry import cherrymusicserver.metainfo as metainfo from cherrymusicserver.util import Performance, MemoryZipFile from cherrymusicserver.ext import zipstream import .time VAR_0 = True @service.user(model='cherrymodel', playlistdb='playlist', useroptions='useroptions', userdb='users') class CLASS_0(object): def __init__(self, VAR_1): self.config = VAR_1 VAR_42 = 'res/dist/main.html' VAR_43 = 'res/login.html' VAR_44 = 'res/VAR_48.html' self.mainpage = readRes(VAR_42) self.loginpage = readRes(VAR_43) self.firstrunpage = readRes(VAR_44) self.handlers = { 'search': self.api_search, 'rememberplaylist': self.api_rememberplaylist, 'saveplaylist': self.api_saveplaylist, 'loadplaylist': self.api_loadplaylist, 'generaterandomplaylist': self.api_generaterandomplaylist, 'deleteplaylist': self.api_deleteplaylist, 'getmotd': self.api_getmotd, 'restoreplaylist': self.api_restoreplaylist, 'getplayables': self.api_getplayables, 'getuserlist': self.api_getuserlist, 'adduser': self.api_adduser, 'userdelete': self.api_userdelete, 'userchangepassword': self.api_userchangepassword, 'showplaylists': self.api_showplaylists, 'logout': self.api_logout, 'downloadpls': self.api_downloadpls, 'downloadm3u': self.api_downloadm3u, 'getsonginfo': self.api_getsonginfo, 'getencoders': self.api_getencoders, 'getdecoders': self.api_getdecoders, 'transcodingenabled': self.api_transcodingenabled, 'updatedb': self.api_updatedb, 'getconfiguration': self.api_getconfiguration, 'compactlistdir': self.api_compactlistdir, 'listdir': self.api_listdir, 'fetchalbumart': self.api_fetchalbumart, 'fetchalbumarturls': self.api_fetchalbumarturls, 'albumart_set': self.api_albumart_set, 'heartbeat': self.api_heartbeat, 'getuseroptions': self.api_getuseroptions, 'setuseroption': self.api_setuseroption, 'changeplaylist': self.api_changeplaylist, 'downloadcheck': self.api_downloadcheck, 'setuseroptionfor': self.api_setuseroptionfor, } def FUNC_1(self, VAR_2): return parse.urlparse(VAR_2).scheme == 'https' def FUNC_2(self, VAR_3=False): VAR_45 = parse.urlparse(VAR_53.url()).netloc VAR_46 = self.issecure(VAR_53.url()) VAR_47 = cherry.config['server.ssl_enabled'] if VAR_47 and not VAR_46: log.d(_('Not secure, redirecting...')) VAR_88 = VAR_45[:ipAndPort.rindex(':')] VAR_2 = 'https://' + VAR_88 + ':' + str(cherry.config['server.ssl_port']) if VAR_3: raise VAR_53.HTTPRedirect(VAR_2, 302) else: VAR_2 = 'http://' + VAR_45 return VAR_2 def FUNC_3(self, *VAR_4, **VAR_5): self.getBaseUrl(VAR_3=True) VAR_48 = 0 == self.userdb.getUserCount() VAR_49 = self.mainpage #generated main.html from devel.html if 'devel' in VAR_5: VAR_49 = readRes('res/devel.html') self.loginpage = readRes('res/login.html') self.firstrunpage = readRes('res/VAR_48.html') if 'login' in VAR_5: VAR_6 = VAR_5.get('username', '') VAR_7 = VAR_5.get('password', '') VAR_89 = VAR_5.get('login', '') if VAR_89 == 'login': self.session_auth(VAR_6, VAR_7) if VAR_53.session['username']: VAR_6 = VAR_53.session['username'] log.i(_('user {VAR_81} just logged in.').format(VAR_81=VAR_6)) elif VAR_89 == 'create admin user': if VAR_48: if VAR_6.strip() and VAR_7.strip(): self.userdb.addUser(VAR_6, VAR_7, True) self.session_auth(VAR_6, VAR_7) return VAR_49 else: return "No, you can't." if VAR_48: return self.firstrunpage else: if self.isAuthorized(): return VAR_49 else: return self.loginpage FUNC_3.exposed = True def FUNC_4(self): try: VAR_90 = VAR_53.session.get('username', None) VAR_91 = VAR_53.session.get('userid', -1) VAR_92 = self.userdb.getNameById(VAR_91) except (UnicodeDecodeError, ValueError) as e: log.w(_(''' Dropping VAR_37 sessions! Try not to change between python 2 and 3, everybody has to relogin now.''')) VAR_53.session.delete() VAR_90 = None if VAR_90 is None: if self.autoLoginActive(): VAR_53.session['username'] = self.userdb.getNameById(1) VAR_53.session['userid'] = 1 VAR_53.session['admin'] = True return True else: return False elif VAR_90 != VAR_92: self.api_logout(VAR_12=None) return False return True def FUNC_5(self): VAR_50 = VAR_53.request.remote.ip in ('127.0.0.1', '::1') if VAR_50 and cherry.config['server.localhost_auto_login']: return True return False def FUNC_6(self, VAR_6, VAR_7): VAR_51 = self.userdb.auth(VAR_6, VAR_7) VAR_52 = cherry.config['server.permit_remote_admin_login'] VAR_50 = VAR_53.request.remote.ip in ('127.0.0.1', '::1') if not VAR_50 and VAR_51.isadmin and not VAR_52: log.i(_('Rejected remote admin login from VAR_51: {VAR_81}').format(VAR_81=VAR_51.name)) VAR_51 = userdb.User.nobody() VAR_53.session['username'] = VAR_51.name VAR_53.session['userid'] = VAR_51.uid VAR_53.session['admin'] = VAR_51.isadmin def FUNC_7(self): try: return VAR_53.session['userid'] except KeyError: VAR_53.lib.sessions.expire() VAR_53.HTTPRedirect(VAR_53.url(), 302) return '' def FUNC_8(self, VAR_8, *VAR_9, **VAR_10): if not self.isAuthorized(): raise VAR_53.HTTPRedirect(self.getBaseUrl(), 302) VAR_53.session.release_lock() if cherry.config['media.transcode'] and VAR_9: bitrate = VAR_10.pop('bitrate', None) or None # catch empty strings if VAR_93: try: VAR_93 = max(0, int(VAR_93)) or None # None if < 1 except (TypeError, ValueError): raise VAR_53.HTTPError(400, "Bad query: " "bitrate ({0!r}) must be an integer".format(str(VAR_93))) VAR_9 = os.path.sep.join(VAR_9) if sys.version_info < (3, 0): # workaround for #327 (VAR_53 issue) VAR_9 = path.decode('utf-8') # make it work with non-ascii else: VAR_9 = codecs.decode(codecs.encode(VAR_9, 'latin1'), 'utf-8') VAR_94 = os.path.join(cherry.config['media.basedir'], VAR_9) VAR_95 = int(VAR_10.pop('starttime', 0)) VAR_96 = audiotranscode.AudioTranscode() VAR_97 = audiotranscode.mime_type(VAR_8) VAR_53.response.headers["Content-Type"] = VAR_97 try: return VAR_96.transcode_stream(VAR_94, VAR_8, VAR_93=bitrate, VAR_95=starttime) except (audiotranscode.TranscodeError, IOError) as e: raise VAR_53.HTTPError(404, e.value) FUNC_8.exposed = True FUNC_8._cp_config = {'response.stream': True} def FUNC_9(self, *VAR_4, **VAR_5): VAR_54 = VAR_4[0] if VAR_4 else '' if not VAR_54 in self.handlers: return "Error: no such VAR_54. '%s'" % VAR_54 VAR_55 = self.handlers[VAR_54] VAR_56 = not ('noauth' in dir(VAR_55) and VAR_55.noauth) if VAR_56 and not self.isAuthorized(): raise VAR_53.HTTPError(401, 'Unauthorized') VAR_57 = {} if 'data' in VAR_5: VAR_57 = json.loads(VAR_5['data']) VAR_58 = ('binary' in dir(VAR_55) and VAR_55.binary) if VAR_58: return VAR_55(**VAR_57) else: return json.dumps({'data': VAR_55(**VAR_57)}) FUNC_9.exposed = True def FUNC_10(self, VAR_11): if not VAR_53.session['admin']: VAR_62 = self.useroptions.forUser(self.getUserId()) if not VAR_62.getOptionValue('media.may_download'): return 'not_permitted' for f in VAR_11: if '/../' in f: return 'invalid_file' VAR_59 = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(VAR_11, VAR_59): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e) def FUNC_11(self, VAR_11): VAR_60 = self.download_check_files(VAR_11) if VAR_60 == 'not_permitted': return """You are not allowed to FUNC_12 files.""" elif VAR_60 == 'invalid_file': return "Error: invalid VAR_39 found in {list}".format(list=VAR_11) elif VAR_60 == 'too_big': VAR_59 = cherry.config['media.maximum_download_size'] return """Can't FUNC_12: Playlist is bigger than {maxsize} mB. The server administrator can change this configuration. """.format(maxsize=VAR_59/1024/1024) elif VAR_60 == 'ok': return VAR_60 else: VAR_125 = "Error VAR_60 check for FUNC_12: {VAR_60!r}".format(VAR_60=status) log.e(VAR_125) return VAR_125 def FUNC_12(self, VAR_12): if not self.isAuthorized(): raise VAR_53.HTTPError(401, 'Unauthorized') VAR_11 = [VAR_69 for VAR_69 in json.loads(unquote(VAR_12))] VAR_61 = self.download_check_files(VAR_11) if VAR_61 == 'ok': FUNC_0() VAR_82 = 'application/x-zip-compressed' VAR_53.response.headers["Content-Type"] = VAR_82 VAR_83 = 'attachment; VAR_39="music.zip"' VAR_53.response.headers['Content-Disposition'] = VAR_83 VAR_84 = cherry.config['media.basedir'] VAR_98 = [os.path.join(VAR_84, f) for f in VAR_11] return zipstream.ZipStream(VAR_98) else: return VAR_61 FUNC_12.exposed = True FUNC_12._cp_config = {'response.stream': True} def FUNC_13(self): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_63 = VAR_62.getChangableOptions() if VAR_53.session['admin']: VAR_63['media'].update({'may_download': True}) else: VAR_63['media'].update({'may_download': VAR_62.getOptionValue('media.may_download')}) return VAR_63 def FUNC_14(self): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_62.setOption('last_time_online', int(time.time())) def FUNC_15(self, VAR_13, VAR_14): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_62.setOption(VAR_13, VAR_14) return "success" def FUNC_16(self, VAR_15, VAR_13, VAR_14): if VAR_53.session['admin']: VAR_62 = self.useroptions.forUser(VAR_15) VAR_62.setOption(VAR_13, VAR_14) return "success" else: return "error: not permitted. Only admins can change other users options" def FUNC_17(self, VAR_16): if not VAR_53.session['admin']: raise VAR_53.HTTPError(401, 'Unauthorized') FUNC_0() VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_65 = VAR_64.fetchurls(VAR_16) return VAR_65[:min(len(VAR_65), 10)] def FUNC_18(self, VAR_17, VAR_18): if not VAR_53.session['admin']: raise VAR_53.HTTPError(401, 'Unauthorized') VAR_66 = albumArtFilePath(VAR_17) VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_20, VAR_67 = VAR_64.retrieveData(VAR_18) self.albumartcache_save(VAR_66, VAR_20) def FUNC_19(self, VAR_17): FUNC_0() VAR_68 = "../VAR_73/img/folder.png" log.i('Fetching album art for: %s' % VAR_17) VAR_69 = os.path.join(cherry.config['media.basedir'], VAR_17) if os.path.isfile(VAR_69): VAR_99 = TinyTag.get(VAR_69, image=True) VAR_100 = VAR_99.get_image() if VAR_100: log.d('Image found in VAR_99.') VAR_67 = {'Content-Type': 'image/jpg', 'Content-Length': len(VAR_100)} VAR_53.response.headers.update(VAR_67) return VAR_100 else: directory = os.path.dirname(VAR_17) VAR_66 = albumArtFilePath(VAR_17) VAR_70 = self.albumartcache_load(VAR_66) if VAR_70: VAR_53.response.headers["Content-Length"] = len(VAR_70) return VAR_70 VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_71 = os.path.join(cherry.config['media.basedir'], VAR_17) VAR_67, VAR_20, VAR_72 = VAR_64.fetchLocal(VAR_71) if VAR_67: if VAR_72: self.albumartcache_save(VAR_66, VAR_20) VAR_53.response.headers.update(VAR_67) return VAR_20 elif cherry.config['media.fetch_album_art']: try: VAR_123 = os.path.basename(VAR_17) VAR_124 = VAR_123 log.i(_("Fetching album art for VAR_124 {keywords!r}").format(VAR_124=keywords)) VAR_67, VAR_20 = VAR_64.fetch(VAR_124) if VAR_67: VAR_53.response.headers.update(VAR_67) self.albumartcache_save(VAR_66, VAR_20) return VAR_20 else: raise VAR_53.HTTPRedirect(VAR_68, 302) except: raise VAR_53.HTTPRedirect(VAR_68, 302) else: raise VAR_53.HTTPRedirect(VAR_68, 302) FUNC_19.noauth = True FUNC_19.binary = True def FUNC_20(self, VAR_19): if os.path.exists(VAR_19): with open(VAR_19, 'rb') as f: return f.read() def FUNC_21(self, VAR_9, VAR_20): with open(VAR_9, 'wb') as f: f.write(VAR_20) def FUNC_22(self, VAR_17, VAR_21=None): try: VAR_101 = self.model.listdir(VAR_17, VAR_21) except ValueError: raise VAR_53.HTTPError(400, 'Bad Request') return [entry.to_dict() for entry in VAR_101] def FUNC_23(self, VAR_17): try: return [entry.to_dict() for entry in self.model.listdir(VAR_17)] except ValueError: raise VAR_53.HTTPError(400, 'Bad Request') def FUNC_24(self, VAR_22): if not VAR_22.strip(): VAR_102 = '[]' else: with Performance(_('processing whole search request')): VAR_114 = self.model.search(VAR_22.strip()) with Performance(_('rendering search results as json')): VAR_102 = [entry.to_dict() for entry in VAR_114] return VAR_102 def FUNC_25(self, VAR_23): VAR_53.session['playlist'] = VAR_23 def FUNC_26(self, VAR_23, VAR_24, VAR_25, VAR_26=False): VAR_73 = self.playlistdb.savePlaylist( VAR_15=self.getUserId(), VAR_24=1 if VAR_24 else 0, VAR_23=playlist, playlisttitle=VAR_25, VAR_26=overwrite) if VAR_73 == "success": return VAR_73 else: raise VAR_53.HTTPError(400, VAR_73) def FUNC_27(self, VAR_27): VAR_73 = self.playlistdb.deletePlaylist(VAR_27, self.getUserId(), override_owner=False) if VAR_73 == "success": return VAR_73 else: raise VAR_53.HTTPError(400, VAR_73) def FUNC_28(self, VAR_27): return [entry.to_dict() for entry in self.playlistdb.loadPlaylist( VAR_27=playlistid, VAR_15=self.getUserId() )] def FUNC_29(self): return [entry.to_dict() for entry in self.model.randomMusicEntries(50)] def FUNC_30(self, VAR_28, VAR_29, VAR_12): if VAR_29 == 'public': VAR_103 = type(VAR_12) == bool and type(VAR_28) == int if VAR_103: return self.playlistdb.setPublic(VAR_15=self.getUserId(), VAR_28=plid, VAR_24=VAR_12) def FUNC_31(self): if VAR_53.session['admin'] and cherry.config['general.update_notification']: FUNC_0() VAR_104 = self.model.check_for_updates() if VAR_104: VAR_115 = VAR_104[0]['version'] VAR_116 = [] VAR_117 = [] for version in VAR_104: for update in version['features']: if update.startswith('FEATURE:'): VAR_116.append(update[len('FEATURE:'):]) elif update.startswith('FIX:'): VAR_117.append(update[len('FIX:'):]) elif update.startswith('FIXED:'): VAR_117.append(update[len('FIXED:'):]) VAR_118 = {'type': 'update', 'data': {}} VAR_118['data']['version'] = VAR_115 VAR_118['data']['features'] = VAR_116 VAR_118['data']['fixes'] = VAR_117 return VAR_118 return {'type': 'wisdom', 'data': self.model.motd()} def FUNC_32(self): VAR_74 = VAR_53.session.get('playlist', []) return VAR_74 def FUNC_33(self): return json.dumps(cherry.config['media.playable']) def FUNC_34(self): if VAR_53.session['admin']: VAR_105 = self.userdb.getUserList() for VAR_51 in VAR_105: if VAR_51['id'] == VAR_53.session['userid']: VAR_51['deletable'] = False VAR_119 = self.useroptions.forUser(VAR_51['id']) VAR_120 = VAR_119.getOptionValue('last_time_online') VAR_121 = VAR_119.getOptionValue('media.may_download') VAR_51['last_time_online'] = VAR_120 VAR_51['may_download'] = VAR_121 VAR_106 = lambda VAR_51: VAR_51['last_time_online'] VAR_105 = sorted(VAR_105, key=VAR_106, reverse=True) return json.dumps({'time': int(time.time()), 'userlist': VAR_105}) else: return json.dumps({'time': 0, 'userlist': []}) def FUNC_35(self, VAR_6, VAR_7, VAR_30): if VAR_53.session['admin']: if self.userdb.addUser(VAR_6, VAR_7, VAR_30): return 'added new VAR_51: %s' % VAR_6 else: return 'error, cannot add new VAR_51!' % VAR_6 else: return "You didn't think that would work, did you?" def FUNC_36(self, VAR_31, VAR_32, VAR_6=''): VAR_75 = VAR_6 == '' if VAR_75: VAR_6 = VAR_53.session['username'] VAR_107 = self.userdb.auth(VAR_6, VAR_31) VAR_108 = userdb.User.nobody() != VAR_107 if not VAR_108: raise VAR_53.HTTPError(403, "Forbidden") if VAR_75 or VAR_53.session['admin']: return self.userdb.changePassword(VAR_6, VAR_32) else: raise VAR_53.HTTPError(403, "Forbidden") def FUNC_37(self, VAR_15): VAR_76 = VAR_53.session['userid'] == VAR_15 if VAR_53.session['admin'] and not VAR_76: VAR_109 = self.userdb.deleteUser(VAR_15) return 'success' if VAR_109 else 'failed' else: return "You didn't think that would work, did you?" def FUNC_38(self, VAR_33="created", VAR_34=''): VAR_77 = self.playlistdb.showPlaylists(self.getUserId(), VAR_34) VAR_78 = int(time.time()) VAR_79 = False for VAR_110 in VAR_77: VAR_110['username'] = self.userdb.getNameById(VAR_110['userid']) VAR_110['type'] = 'playlist' VAR_110['age'] = VAR_78 - VAR_110['created'] if VAR_33[0] == '-': VAR_79 = True VAR_33 = VAR_33[1:] if not VAR_33 in ('username', 'age', 'title', 'default'): VAR_33 = 'created' if VAR_33 == 'default': VAR_33 = 'age' VAR_79 = False VAR_77 = sorted(VAR_77, key=lambda x: x[VAR_33], reverse = VAR_79) return VAR_77 def FUNC_39(self): VAR_53.lib.sessions.expire() FUNC_39.no_auth = True def FUNC_40(self, VAR_28, VAR_35): VAR_15 = self.getUserId() VAR_80 = self.playlistdb.createPLS(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) if VAR_80 and VAR_81: return self.serve_string_as_file(VAR_80, VAR_81+'.pls') FUNC_40.binary = True def FUNC_41(self, VAR_28, VAR_35): VAR_15 = self.getUserId() VAR_80 = self.playlistdb.createM3U(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) if VAR_80 and VAR_81: return self.serve_string_as_file(VAR_80, VAR_81+'.m3u') FUNC_41.binary = True def FUNC_42(self, VAR_36, VAR_37=False, VAR_35=''): VAR_15 = self.getUserId() if not VAR_15: raise VAR_53.HTTPError(401, _("Please log in")) VAR_35 = (hostaddr.strip().rstrip('/') + cherry.config['server.rootpath']).rstrip('/') VAR_36 = format.lower() if VAR_36 == 'm3u': VAR_111 = self.playlistdb.createM3U elif VAR_36 == 'pls': VAR_111 = self.playlistdb.createPLS else: raise VAR_53.HTTPError(400, _('Unknown VAR_23 VAR_36: {format!r}').format(VAR_36=format)) VAR_77 = self.playlistdb.showPlaylists(VAR_15, include_public=VAR_37) if not VAR_77: raise VAR_53.HTTPError(404, _('No VAR_77 found')) with MemoryZipFile() as zip: for VAR_110 in VAR_77: VAR_28 = VAR_110['plid'] VAR_122 = VAR_111(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) + '.' + VAR_36 if not VAR_110['owner']: VAR_6 = self.userdb.getNameById(VAR_110['userid']) VAR_81 = VAR_6 + '/' + VAR_81 zip.writestr(VAR_81, VAR_122) VAR_82 = 'application/x-zip-compressed' VAR_83 = 'attachment; VAR_39="playlists.zip"' VAR_53.response.headers["Content-Type"] = VAR_82 VAR_53.response.headers['Content-Disposition'] = VAR_83 return zip.getbytes() FUNC_42.exposed = True def FUNC_43(self, VAR_9): VAR_84 = cherry.config['media.basedir'] VAR_85 = os.path.join(VAR_84, VAR_9) return json.dumps(metainfo.getSongInfo(VAR_85).dict()) def FUNC_44(self): return json.dumps(audiotranscode.getEncoders()) def FUNC_45(self): return json.dumps(audiotranscode.getDecoders()) def FUNC_46(self): return json.dumps(cherry.config['media.transcode']) def FUNC_47(self): self.model.updateLibrary() return 'success' def FUNC_48(self): VAR_86 = { 'transcodingenabled': cherry.config['media.transcode'], 'fetchalbumart': cherry.config['media.fetch_album_art'], 'isadmin': VAR_53.session['admin'], 'username': VAR_53.session['username'], 'servepath': 'serve/', 'transcodepath': 'trans/', 'auto_login': self.autoLoginActive(), 'version': cherry.REPO_VERSION or cherry.VERSION, } if cherry.config['media.transcode']: VAR_112 = list(self.model.transcoder.available_decoder_formats()) VAR_86['getdecoders'] = VAR_112 VAR_113 = list(self.model.transcoder.available_encoder_formats()) VAR_86['getencoders'] = VAR_113 else: VAR_86['getdecoders'] = [] VAR_86['getencoders'] = [] return VAR_86 def FUNC_49(self, VAR_38, VAR_39): VAR_87 = 'attachment; VAR_39="'+VAR_39+'"' VAR_53.response.headers["Content-Type"] = "application/x-download" VAR_53.response.headers["Content-Disposition"] = VAR_87 return codecs.encode(VAR_38, "UTF-8") def FUNC_0(): VAR_53.session.save() VAR_40 = VAR_53.serving.request.hooks['before_finalize'] VAR_41 = VAR_53.lib.sessions.save VAR_40[:] = [h for h in VAR_40 if h.callback is not VAR_41]
import os # shouldn't have to list any folder in the future! import json import .cherrypy import codecs import sys try: from urllib.parse import unquote except ImportError: from backport.urllib.parse import unquote try: from urllib import parse except ImportError: from backport.urllib import parse import audiotranscode from tinytag import TinyTag from cherrymusicserver import .userdb from cherrymusicserver import log from cherrymusicserver import albumartfetcher from cherrymusicserver import service from cherrymusicserver.pathprovider import readRes from cherrymusicserver.pathprovider import albumArtFilePath import cherrymusicserver as cherry import cherrymusicserver.metainfo as metainfo from cherrymusicserver.util import Performance, MemoryZipFile from cherrymusicserver.ext import zipstream import .time VAR_0 = True @service.user(model='cherrymodel', playlistdb='playlist', useroptions='useroptions', userdb='users') class CLASS_0(object): def __init__(self, VAR_1): self.config = VAR_1 VAR_42 = 'res/dist/main.html' VAR_43 = 'res/login.html' VAR_44 = 'res/VAR_48.html' self.mainpage = readRes(VAR_42) self.loginpage = readRes(VAR_43) self.firstrunpage = readRes(VAR_44) self.handlers = { 'search': self.api_search, 'rememberplaylist': self.api_rememberplaylist, 'saveplaylist': self.api_saveplaylist, 'loadplaylist': self.api_loadplaylist, 'generaterandomplaylist': self.api_generaterandomplaylist, 'deleteplaylist': self.api_deleteplaylist, 'getmotd': self.api_getmotd, 'restoreplaylist': self.api_restoreplaylist, 'getplayables': self.api_getplayables, 'getuserlist': self.api_getuserlist, 'adduser': self.api_adduser, 'userdelete': self.api_userdelete, 'userchangepassword': self.api_userchangepassword, 'showplaylists': self.api_showplaylists, 'logout': self.api_logout, 'downloadpls': self.api_downloadpls, 'downloadm3u': self.api_downloadm3u, 'getsonginfo': self.api_getsonginfo, 'getencoders': self.api_getencoders, 'getdecoders': self.api_getdecoders, 'transcodingenabled': self.api_transcodingenabled, 'updatedb': self.api_updatedb, 'getconfiguration': self.api_getconfiguration, 'compactlistdir': self.api_compactlistdir, 'listdir': self.api_listdir, 'fetchalbumart': self.api_fetchalbumart, 'fetchalbumarturls': self.api_fetchalbumarturls, 'albumart_set': self.api_albumart_set, 'heartbeat': self.api_heartbeat, 'getuseroptions': self.api_getuseroptions, 'setuseroption': self.api_setuseroption, 'changeplaylist': self.api_changeplaylist, 'downloadcheck': self.api_downloadcheck, 'setuseroptionfor': self.api_setuseroptionfor, } def FUNC_1(self, VAR_2): return parse.urlparse(VAR_2).scheme == 'https' def FUNC_2(self, VAR_3=False): VAR_45 = parse.urlparse(VAR_53.url()).netloc VAR_46 = self.issecure(VAR_53.url()) VAR_47 = cherry.config['server.ssl_enabled'] if VAR_47 and not VAR_46: log.d(_('Not secure, redirecting...')) VAR_88 = VAR_45[:ipAndPort.rindex(':')] VAR_2 = 'https://' + VAR_88 + ':' + str(cherry.config['server.ssl_port']) if VAR_3: raise VAR_53.HTTPRedirect(VAR_2, 302) else: VAR_2 = 'http://' + VAR_45 return VAR_2 def FUNC_3(self, *VAR_4, **VAR_5): self.getBaseUrl(VAR_3=True) VAR_48 = 0 == self.userdb.getUserCount() VAR_49 = self.mainpage #generated main.html from devel.html if 'devel' in VAR_5: VAR_49 = readRes('res/devel.html') self.loginpage = readRes('res/login.html') self.firstrunpage = readRes('res/VAR_48.html') if 'login' in VAR_5: VAR_6 = VAR_5.get('username', '') VAR_7 = VAR_5.get('password', '') VAR_89 = VAR_5.get('login', '') if VAR_89 == 'login': self.session_auth(VAR_6, VAR_7) if VAR_53.session['username']: VAR_6 = VAR_53.session['username'] log.i(_('user {VAR_81} just logged in.').format(VAR_81=VAR_6)) elif VAR_89 == 'create admin user': if VAR_48: if VAR_6.strip() and VAR_7.strip(): self.userdb.addUser(VAR_6, VAR_7, True) self.session_auth(VAR_6, VAR_7) return VAR_49 else: return "No, you can't." if VAR_48: return self.firstrunpage else: if self.isAuthorized(): return VAR_49 else: return self.loginpage FUNC_3.exposed = True def FUNC_4(self): try: VAR_90 = VAR_53.session.get('username', None) VAR_91 = VAR_53.session.get('userid', -1) VAR_92 = self.userdb.getNameById(VAR_91) except (UnicodeDecodeError, ValueError) as e: log.w(_(''' Dropping VAR_37 sessions! Try not to change between python 2 and 3, everybody has to relogin now.''')) VAR_53.session.delete() VAR_90 = None if VAR_90 is None: if self.autoLoginActive(): VAR_53.session['username'] = self.userdb.getNameById(1) VAR_53.session['userid'] = 1 VAR_53.session['admin'] = True return True else: return False elif VAR_90 != VAR_92: self.api_logout(VAR_12=None) return False return True def FUNC_5(self): VAR_50 = VAR_53.request.remote.ip in ('127.0.0.1', '::1') if VAR_50 and cherry.config['server.localhost_auto_login']: return True return False def FUNC_6(self, VAR_6, VAR_7): VAR_51 = self.userdb.auth(VAR_6, VAR_7) VAR_52 = cherry.config['server.permit_remote_admin_login'] VAR_50 = VAR_53.request.remote.ip in ('127.0.0.1', '::1') if not VAR_50 and VAR_51.isadmin and not VAR_52: log.i(_('Rejected remote admin login from VAR_51: {VAR_81}').format(VAR_81=VAR_51.name)) VAR_51 = userdb.User.nobody() VAR_53.session['username'] = VAR_51.name VAR_53.session['userid'] = VAR_51.uid VAR_53.session['admin'] = VAR_51.isadmin def FUNC_7(self): try: return VAR_53.session['userid'] except KeyError: VAR_53.lib.sessions.expire() VAR_53.HTTPRedirect(VAR_53.url(), 302) return '' def FUNC_8(self, VAR_8, *VAR_9, **VAR_10): if not self.isAuthorized(): raise VAR_53.HTTPRedirect(self.getBaseUrl(), 302) VAR_53.session.release_lock() if cherry.config['media.transcode'] and VAR_9: bitrate = VAR_10.pop('bitrate', None) or None # catch empty strings if VAR_93: try: VAR_93 = max(0, int(VAR_93)) or None # None if < 1 except (TypeError, ValueError): raise VAR_53.HTTPError(400, "Bad query: " "bitrate ({0!r}) must be an integer".format(str(VAR_93))) VAR_9 = os.path.sep.join(VAR_9) if sys.version_info < (3, 0): # workaround for #327 (VAR_53 issue) VAR_9 = path.decode('utf-8') # make it work with non-ascii else: VAR_9 = codecs.decode(codecs.encode(VAR_9, 'latin1'), 'utf-8') VAR_94 = os.path.join(cherry.config['media.basedir'], VAR_9) VAR_95 = int(VAR_10.pop('starttime', 0)) VAR_96 = audiotranscode.AudioTranscode() VAR_97 = audiotranscode.mime_type(VAR_8) VAR_53.response.headers["Content-Type"] = VAR_97 try: return VAR_96.transcode_stream(VAR_94, VAR_8, VAR_93=bitrate, VAR_95=starttime) except (audiotranscode.TranscodeError, IOError) as e: raise VAR_53.HTTPError(404, e.value) FUNC_8.exposed = True FUNC_8._cp_config = {'response.stream': True} def FUNC_9(self, *VAR_4, **VAR_5): VAR_54 = VAR_4[0] if VAR_4 else '' if not VAR_54 in self.handlers: return "Error: no such VAR_54. '%s'" % VAR_54 VAR_55 = self.handlers[VAR_54] VAR_56 = not ('noauth' in dir(VAR_55) and VAR_55.noauth) if VAR_56 and not self.isAuthorized(): raise VAR_53.HTTPError(401, 'Unauthorized') VAR_57 = {} if 'data' in VAR_5: VAR_57 = json.loads(VAR_5['data']) VAR_58 = ('binary' in dir(VAR_55) and VAR_55.binary) if VAR_58: return VAR_55(**VAR_57) else: return json.dumps({'data': VAR_55(**VAR_57)}) FUNC_9.exposed = True def FUNC_10(self, VAR_11): if not VAR_53.session['admin']: VAR_62 = self.useroptions.forUser(self.getUserId()) if not VAR_62.getOptionValue('media.may_download'): return 'not_permitted' for f in VAR_11: if '/../' in f or f.startswith('../'): return 'invalid_file' if os.path.isabs(f): return 'invalid_file' VAR_59 = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(VAR_11, VAR_59): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e) def FUNC_11(self, VAR_11): VAR_60 = self.download_check_files(VAR_11) if VAR_60 == 'not_permitted': return """You are not allowed to FUNC_12 files.""" elif VAR_60 == 'invalid_file': return "Error: invalid VAR_39 found in {list}".format(list=VAR_11) elif VAR_60 == 'too_big': VAR_59 = cherry.config['media.maximum_download_size'] return """Can't FUNC_12: Playlist is bigger than {maxsize} mB. The server administrator can change this configuration. """.format(maxsize=VAR_59/1024/1024) elif VAR_60 == 'ok': return VAR_60 else: VAR_125 = "Error VAR_60 check for FUNC_12: {VAR_60!r}".format(VAR_60=status) log.e(VAR_125) return VAR_125 def FUNC_12(self, VAR_12): if not self.isAuthorized(): raise VAR_53.HTTPError(401, 'Unauthorized') VAR_11 = [VAR_69 for VAR_69 in json.loads(unquote(VAR_12))] VAR_61 = self.download_check_files(VAR_11) if VAR_61 == 'ok': FUNC_0() VAR_82 = 'application/x-zip-compressed' VAR_53.response.headers["Content-Type"] = VAR_82 VAR_83 = 'attachment; VAR_39="music.zip"' VAR_53.response.headers['Content-Disposition'] = VAR_83 VAR_84 = cherry.config['media.basedir'] VAR_98 = [os.path.join(VAR_84, f) for f in VAR_11] return zipstream.ZipStream(VAR_98) else: return VAR_61 FUNC_12.exposed = True FUNC_12._cp_config = {'response.stream': True} def FUNC_13(self): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_63 = VAR_62.getChangableOptions() if VAR_53.session['admin']: VAR_63['media'].update({'may_download': True}) else: VAR_63['media'].update({'may_download': VAR_62.getOptionValue('media.may_download')}) return VAR_63 def FUNC_14(self): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_62.setOption('last_time_online', int(time.time())) def FUNC_15(self, VAR_13, VAR_14): VAR_62 = self.useroptions.forUser(self.getUserId()) VAR_62.setOption(VAR_13, VAR_14) return "success" def FUNC_16(self, VAR_15, VAR_13, VAR_14): if VAR_53.session['admin']: VAR_62 = self.useroptions.forUser(VAR_15) VAR_62.setOption(VAR_13, VAR_14) return "success" else: return "error: not permitted. Only admins can change other users options" def FUNC_17(self, VAR_16): if not VAR_53.session['admin']: raise VAR_53.HTTPError(401, 'Unauthorized') FUNC_0() VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_65 = VAR_64.fetchurls(VAR_16) return VAR_65[:min(len(VAR_65), 10)] def FUNC_18(self, VAR_17, VAR_18): if not VAR_53.session['admin']: raise VAR_53.HTTPError(401, 'Unauthorized') VAR_66 = albumArtFilePath(VAR_17) VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_20, VAR_67 = VAR_64.retrieveData(VAR_18) self.albumartcache_save(VAR_66, VAR_20) def FUNC_19(self, VAR_17): FUNC_0() VAR_68 = "../VAR_73/img/folder.png" log.i('Fetching album art for: %s' % VAR_17) VAR_69 = os.path.join(cherry.config['media.basedir'], VAR_17) if os.path.isfile(VAR_69): VAR_99 = TinyTag.get(VAR_69, image=True) VAR_100 = VAR_99.get_image() if VAR_100: log.d('Image found in VAR_99.') VAR_67 = {'Content-Type': 'image/jpg', 'Content-Length': len(VAR_100)} VAR_53.response.headers.update(VAR_67) return VAR_100 else: directory = os.path.dirname(VAR_17) VAR_66 = albumArtFilePath(VAR_17) VAR_70 = self.albumartcache_load(VAR_66) if VAR_70: VAR_53.response.headers["Content-Length"] = len(VAR_70) return VAR_70 VAR_64 = albumartfetcher.AlbumArtFetcher() VAR_71 = os.path.join(cherry.config['media.basedir'], VAR_17) VAR_67, VAR_20, VAR_72 = VAR_64.fetchLocal(VAR_71) if VAR_67: if VAR_72: self.albumartcache_save(VAR_66, VAR_20) VAR_53.response.headers.update(VAR_67) return VAR_20 elif cherry.config['media.fetch_album_art']: try: VAR_123 = os.path.basename(VAR_17) VAR_124 = VAR_123 log.i(_("Fetching album art for VAR_124 {keywords!r}").format(VAR_124=keywords)) VAR_67, VAR_20 = VAR_64.fetch(VAR_124) if VAR_67: VAR_53.response.headers.update(VAR_67) self.albumartcache_save(VAR_66, VAR_20) return VAR_20 else: raise VAR_53.HTTPRedirect(VAR_68, 302) except: raise VAR_53.HTTPRedirect(VAR_68, 302) else: raise VAR_53.HTTPRedirect(VAR_68, 302) FUNC_19.noauth = True FUNC_19.binary = True def FUNC_20(self, VAR_19): if os.path.exists(VAR_19): with open(VAR_19, 'rb') as f: return f.read() def FUNC_21(self, VAR_9, VAR_20): with open(VAR_9, 'wb') as f: f.write(VAR_20) def FUNC_22(self, VAR_17, VAR_21=None): try: VAR_101 = self.model.listdir(VAR_17, VAR_21) except ValueError: raise VAR_53.HTTPError(400, 'Bad Request') return [entry.to_dict() for entry in VAR_101] def FUNC_23(self, VAR_17): try: return [entry.to_dict() for entry in self.model.listdir(VAR_17)] except ValueError: raise VAR_53.HTTPError(400, 'Bad Request') def FUNC_24(self, VAR_22): if not VAR_22.strip(): VAR_102 = '[]' else: with Performance(_('processing whole search request')): VAR_114 = self.model.search(VAR_22.strip()) with Performance(_('rendering search results as json')): VAR_102 = [entry.to_dict() for entry in VAR_114] return VAR_102 def FUNC_25(self, VAR_23): VAR_53.session['playlist'] = VAR_23 def FUNC_26(self, VAR_23, VAR_24, VAR_25, VAR_26=False): VAR_73 = self.playlistdb.savePlaylist( VAR_15=self.getUserId(), VAR_24=1 if VAR_24 else 0, VAR_23=playlist, playlisttitle=VAR_25, VAR_26=overwrite) if VAR_73 == "success": return VAR_73 else: raise VAR_53.HTTPError(400, VAR_73) def FUNC_27(self, VAR_27): VAR_73 = self.playlistdb.deletePlaylist(VAR_27, self.getUserId(), override_owner=False) if VAR_73 == "success": return VAR_73 else: raise VAR_53.HTTPError(400, VAR_73) def FUNC_28(self, VAR_27): return [entry.to_dict() for entry in self.playlistdb.loadPlaylist( VAR_27=playlistid, VAR_15=self.getUserId() )] def FUNC_29(self): return [entry.to_dict() for entry in self.model.randomMusicEntries(50)] def FUNC_30(self, VAR_28, VAR_29, VAR_12): if VAR_29 == 'public': VAR_103 = type(VAR_12) == bool and type(VAR_28) == int if VAR_103: return self.playlistdb.setPublic(VAR_15=self.getUserId(), VAR_28=plid, VAR_24=VAR_12) def FUNC_31(self): if VAR_53.session['admin'] and cherry.config['general.update_notification']: FUNC_0() VAR_104 = self.model.check_for_updates() if VAR_104: VAR_115 = VAR_104[0]['version'] VAR_116 = [] VAR_117 = [] for version in VAR_104: for update in version['features']: if update.startswith('FEATURE:'): VAR_116.append(update[len('FEATURE:'):]) elif update.startswith('FIX:'): VAR_117.append(update[len('FIX:'):]) elif update.startswith('FIXED:'): VAR_117.append(update[len('FIXED:'):]) VAR_118 = {'type': 'update', 'data': {}} VAR_118['data']['version'] = VAR_115 VAR_118['data']['features'] = VAR_116 VAR_118['data']['fixes'] = VAR_117 return VAR_118 return {'type': 'wisdom', 'data': self.model.motd()} def FUNC_32(self): VAR_74 = VAR_53.session.get('playlist', []) return VAR_74 def FUNC_33(self): return json.dumps(cherry.config['media.playable']) def FUNC_34(self): if VAR_53.session['admin']: VAR_105 = self.userdb.getUserList() for VAR_51 in VAR_105: if VAR_51['id'] == VAR_53.session['userid']: VAR_51['deletable'] = False VAR_119 = self.useroptions.forUser(VAR_51['id']) VAR_120 = VAR_119.getOptionValue('last_time_online') VAR_121 = VAR_119.getOptionValue('media.may_download') VAR_51['last_time_online'] = VAR_120 VAR_51['may_download'] = VAR_121 VAR_106 = lambda VAR_51: VAR_51['last_time_online'] VAR_105 = sorted(VAR_105, key=VAR_106, reverse=True) return json.dumps({'time': int(time.time()), 'userlist': VAR_105}) else: return json.dumps({'time': 0, 'userlist': []}) def FUNC_35(self, VAR_6, VAR_7, VAR_30): if VAR_53.session['admin']: if self.userdb.addUser(VAR_6, VAR_7, VAR_30): return 'added new VAR_51: %s' % VAR_6 else: return 'error, cannot add new VAR_51!' % VAR_6 else: return "You didn't think that would work, did you?" def FUNC_36(self, VAR_31, VAR_32, VAR_6=''): VAR_75 = VAR_6 == '' if VAR_75: VAR_6 = VAR_53.session['username'] VAR_107 = self.userdb.auth(VAR_6, VAR_31) VAR_108 = userdb.User.nobody() != VAR_107 if not VAR_108: raise VAR_53.HTTPError(403, "Forbidden") if VAR_75 or VAR_53.session['admin']: return self.userdb.changePassword(VAR_6, VAR_32) else: raise VAR_53.HTTPError(403, "Forbidden") def FUNC_37(self, VAR_15): VAR_76 = VAR_53.session['userid'] == VAR_15 if VAR_53.session['admin'] and not VAR_76: VAR_109 = self.userdb.deleteUser(VAR_15) return 'success' if VAR_109 else 'failed' else: return "You didn't think that would work, did you?" def FUNC_38(self, VAR_33="created", VAR_34=''): VAR_77 = self.playlistdb.showPlaylists(self.getUserId(), VAR_34) VAR_78 = int(time.time()) VAR_79 = False for VAR_110 in VAR_77: VAR_110['username'] = self.userdb.getNameById(VAR_110['userid']) VAR_110['type'] = 'playlist' VAR_110['age'] = VAR_78 - VAR_110['created'] if VAR_33[0] == '-': VAR_79 = True VAR_33 = VAR_33[1:] if not VAR_33 in ('username', 'age', 'title', 'default'): VAR_33 = 'created' if VAR_33 == 'default': VAR_33 = 'age' VAR_79 = False VAR_77 = sorted(VAR_77, key=lambda x: x[VAR_33], reverse = VAR_79) return VAR_77 def FUNC_39(self): VAR_53.lib.sessions.expire() FUNC_39.no_auth = True def FUNC_40(self, VAR_28, VAR_35): VAR_15 = self.getUserId() VAR_80 = self.playlistdb.createPLS(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) if VAR_80 and VAR_81: return self.serve_string_as_file(VAR_80, VAR_81+'.pls') FUNC_40.binary = True def FUNC_41(self, VAR_28, VAR_35): VAR_15 = self.getUserId() VAR_80 = self.playlistdb.createM3U(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) if VAR_80 and VAR_81: return self.serve_string_as_file(VAR_80, VAR_81+'.m3u') FUNC_41.binary = True def FUNC_42(self, VAR_36, VAR_37=False, VAR_35=''): VAR_15 = self.getUserId() if not VAR_15: raise VAR_53.HTTPError(401, _("Please log in")) VAR_35 = (hostaddr.strip().rstrip('/') + cherry.config['server.rootpath']).rstrip('/') VAR_36 = format.lower() if VAR_36 == 'm3u': VAR_111 = self.playlistdb.createM3U elif VAR_36 == 'pls': VAR_111 = self.playlistdb.createPLS else: raise VAR_53.HTTPError(400, _('Unknown VAR_23 VAR_36: {format!r}').format(VAR_36=format)) VAR_77 = self.playlistdb.showPlaylists(VAR_15, include_public=VAR_37) if not VAR_77: raise VAR_53.HTTPError(404, _('No VAR_77 found')) with MemoryZipFile() as zip: for VAR_110 in VAR_77: VAR_28 = VAR_110['plid'] VAR_122 = VAR_111(VAR_28=plid, VAR_15=userid, addrstr=VAR_35) VAR_81 = self.playlistdb.getName(VAR_28, VAR_15) + '.' + VAR_36 if not VAR_110['owner']: VAR_6 = self.userdb.getNameById(VAR_110['userid']) VAR_81 = VAR_6 + '/' + VAR_81 zip.writestr(VAR_81, VAR_122) VAR_82 = 'application/x-zip-compressed' VAR_83 = 'attachment; VAR_39="playlists.zip"' VAR_53.response.headers["Content-Type"] = VAR_82 VAR_53.response.headers['Content-Disposition'] = VAR_83 return zip.getbytes() FUNC_42.exposed = True def FUNC_43(self, VAR_9): VAR_84 = cherry.config['media.basedir'] VAR_85 = os.path.join(VAR_84, VAR_9) return json.dumps(metainfo.getSongInfo(VAR_85).dict()) def FUNC_44(self): return json.dumps(audiotranscode.getEncoders()) def FUNC_45(self): return json.dumps(audiotranscode.getDecoders()) def FUNC_46(self): return json.dumps(cherry.config['media.transcode']) def FUNC_47(self): self.model.updateLibrary() return 'success' def FUNC_48(self): VAR_86 = { 'transcodingenabled': cherry.config['media.transcode'], 'fetchalbumart': cherry.config['media.fetch_album_art'], 'isadmin': VAR_53.session['admin'], 'username': VAR_53.session['username'], 'servepath': 'serve/', 'transcodepath': 'trans/', 'auto_login': self.autoLoginActive(), 'version': cherry.REPO_VERSION or cherry.VERSION, } if cherry.config['media.transcode']: VAR_112 = list(self.model.transcoder.available_decoder_formats()) VAR_86['getdecoders'] = VAR_112 VAR_113 = list(self.model.transcoder.available_encoder_formats()) VAR_86['getencoders'] = VAR_113 else: VAR_86['getdecoders'] = [] VAR_86['getencoders'] = [] return VAR_86 def FUNC_49(self, VAR_38, VAR_39): VAR_87 = 'attachment; VAR_39="'+VAR_39+'"' VAR_53.response.headers["Content-Type"] = "application/x-download" VAR_53.response.headers["Content-Disposition"] = VAR_87 return codecs.encode(VAR_38, "UTF-8") def FUNC_0(): VAR_53.session.save() VAR_40 = VAR_53.serving.request.hooks['before_finalize'] VAR_41 = VAR_53.lib.sessions.save VAR_40[:] = [h for h in VAR_40 if h.callback is not VAR_41]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 35, 41, 50, 51, 54, 64, 67, 69, 70, 76, 80, 84, 121, 124, 138, 144, 173, 180, 181, 199, 205, 216, 224, 227, 230, 238, 239, 247, 248, 255, 257, 268, 269, 275, 279, 292, 294, 296, 301, 305, 314, 332, 351, 360, 364, 369, 377, 384, 386, 394, 398, 401, 403, 412, 413, 415, 416, 422, 423, 427, 430, 435, 446, 449, 452, 456, 461, 465, 472, 478, 488, 491, 503, 511, 512, 514, 520, 523, 531, 554, 558, 562, 580, 589, 602, 610, 615, 630, 634, 642, 650, 656, 665, 669, 679, 686, 691, 694, 697, 700, 704, 725, 731, 732, 735, 737, 740, 742, 745, 754, 755, 756, 32, 33, 34, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 226, 227, 228, 229, 230, 231, 232, 233, 271, 272, 273, 274, 560 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 35, 41, 50, 51, 54, 64, 67, 69, 70, 76, 80, 84, 121, 124, 138, 144, 173, 180, 181, 199, 205, 216, 224, 227, 230, 238, 239, 247, 248, 255, 257, 268, 269, 275, 279, 292, 294, 296, 301, 303, 306, 309, 318, 336, 355, 364, 368, 373, 381, 388, 390, 398, 402, 405, 407, 416, 417, 419, 420, 426, 427, 431, 434, 439, 450, 453, 456, 460, 465, 469, 476, 482, 492, 495, 507, 515, 516, 518, 524, 527, 535, 558, 562, 566, 584, 593, 606, 614, 619, 634, 638, 646, 654, 660, 669, 673, 683, 690, 695, 698, 701, 704, 708, 729, 735, 736, 739, 741, 744, 746, 749, 758, 759, 760, 32, 33, 34, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 226, 227, 228, 229, 230, 231, 232, 233, 271, 272, 273, 274, 564 ]
1CWE-79
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.http.response import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.i18n import set_language from itertools import chain from shuup.apps.provides import get_provide_objects from .views.basket import BasketView from .views.category import AllCategoriesView, CategoryView from .views.checkout import get_checkout_view from .views.dashboard import DashboardView from .views.index import IndexView from .views.misc import ( force_anonymous_contact, force_company_contact, force_person_contact, stop_impersonating, toggle_all_seeing, ) from .views.order import OrderCompleteView from .views.payment import ProcessPaymentView from .views.product import ProductDetailView from .views.upload import media_upload # TODO: Check _not_here_yet URLs in this file def _not_here_yet(request, *args, **kwargs): return HttpResponse("Not here yet: %s (%r, %r)" % (request.path, args, kwargs), status=410) # Use a different js catalog function in front urlpatterns to prevent forcing # the shop language settings in admin js catalog. def front_javascript_catalog_all(request, domain="djangojs"): from shuup.utils.i18n import javascript_catalog_all return javascript_catalog_all(request, domain) checkout_view = get_checkout_view() urlpatterns = [ url(r"^set-language/$", csrf_exempt(set_language), name="set-language"), url(r"^i18n.js$", front_javascript_catalog_all, name="js-catalog"), url(r"^checkout/$", checkout_view, name="checkout"), url(r"^checkout/(?P<phase>.+)/$", checkout_view, name="checkout"), url(r"^basket/$", csrf_exempt(BasketView.as_view()), name="basket"), url(r"^dashboard/$", login_required(DashboardView.as_view()), name="dashboard"), url(r"^toggle-allseeing/$", login_required(toggle_all_seeing), name="toggle-all-seeing"), url(r"^force-anonymous-contact/$", login_required(force_anonymous_contact), name="force-anonymous-contact"), url(r"^force-company-contact/$", login_required(force_company_contact), name="force-company-contact"), url(r"^force-person-contact/$", login_required(force_person_contact), name="force-person-contact"), url(r"^stop-impersonating/$", login_required(stop_impersonating), name="stop-impersonating"), url(r"^upload-media/$", login_required(media_upload), name="media-upload"), url( r"^order/payment/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(ProcessPaymentView.as_view()), kwargs={"mode": "payment"}, name="order_process_payment", ), url( r"^order/process-payment/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(ProcessPaymentView.as_view()), kwargs={"mode": "return"}, name="order_process_payment_return", ), url( r"^order/payment-canceled/(?P<pk>.+?)/(?P<key>.+?)/$", ProcessPaymentView.as_view(), kwargs={"mode": "cancel"}, name="order_payment_canceled", ), url(r"^order/complete/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(OrderCompleteView.as_view()), name="order_complete"), url(r"^order/verification/(?P<pk>.+?)/(?P<key>.+?)/$", _not_here_yet, name="order_requires_verification"), url( r"^order/get-attachment/(?P<order_pk>\d+)/(?P<key>.+?)/(?P<att_pk>\d+)/", _not_here_yet, name="secure_attachment", ), url(r"^p/(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(ProductDetailView.as_view()), name="product"), url( r"^s/(?P<supplier_pk>\d+)-(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(ProductDetailView.as_view()), name="supplier-product", ), url(r"^c/$", csrf_exempt(AllCategoriesView.as_view()), name="all-categories"), url(r"^c/(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(CategoryView.as_view()), name="category"), ] # TODO: Document `front_urls_pre`, `front_urls` and `front_urls_post`. def _get_extension_urlpatterns(provide_category): return chain(*get_provide_objects(provide_category)) app_name = "shuup" urlpatterns = list( chain( *( _get_extension_urlpatterns("front_urls_pre"), urlpatterns, _get_extension_urlpatterns("front_urls"), [url(r"^$", IndexView.as_view(), name="index")], _get_extension_urlpatterns("front_urls_post"), ) ) )
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.http.response import HttpResponse from django.utils.html import escape from django.views.decorators.csrf import csrf_exempt from django.views.i18n import set_language from itertools import chain from shuup.apps.provides import get_provide_objects from .views.basket import BasketView from .views.category import AllCategoriesView, CategoryView from .views.checkout import get_checkout_view from .views.dashboard import DashboardView from .views.index import IndexView from .views.misc import ( force_anonymous_contact, force_company_contact, force_person_contact, stop_impersonating, toggle_all_seeing, ) from .views.order import OrderCompleteView from .views.payment import ProcessPaymentView from .views.product import ProductDetailView from .views.upload import media_upload # TODO: Check _not_here_yet URLs in this file def _not_here_yet(request, *args, **kwargs): return HttpResponse("Not here yet: %s (%r, %r)" % (request.path, escape(args), escape(kwargs)), status=410) # Use a different js catalog function in front urlpatterns to prevent forcing # the shop language settings in admin js catalog. def front_javascript_catalog_all(request, domain="djangojs"): from shuup.utils.i18n import javascript_catalog_all return javascript_catalog_all(request, domain) checkout_view = get_checkout_view() urlpatterns = [ url(r"^set-language/$", csrf_exempt(set_language), name="set-language"), url(r"^i18n.js$", front_javascript_catalog_all, name="js-catalog"), url(r"^checkout/$", checkout_view, name="checkout"), url(r"^checkout/(?P<phase>.+)/$", checkout_view, name="checkout"), url(r"^basket/$", csrf_exempt(BasketView.as_view()), name="basket"), url(r"^dashboard/$", login_required(DashboardView.as_view()), name="dashboard"), url(r"^toggle-allseeing/$", login_required(toggle_all_seeing), name="toggle-all-seeing"), url(r"^force-anonymous-contact/$", login_required(force_anonymous_contact), name="force-anonymous-contact"), url(r"^force-company-contact/$", login_required(force_company_contact), name="force-company-contact"), url(r"^force-person-contact/$", login_required(force_person_contact), name="force-person-contact"), url(r"^stop-impersonating/$", login_required(stop_impersonating), name="stop-impersonating"), url(r"^upload-media/$", login_required(media_upload), name="media-upload"), url( r"^order/payment/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(ProcessPaymentView.as_view()), kwargs={"mode": "payment"}, name="order_process_payment", ), url( r"^order/process-payment/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(ProcessPaymentView.as_view()), kwargs={"mode": "return"}, name="order_process_payment_return", ), url( r"^order/payment-canceled/(?P<pk>.+?)/(?P<key>.+?)/$", ProcessPaymentView.as_view(), kwargs={"mode": "cancel"}, name="order_payment_canceled", ), url(r"^order/complete/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(OrderCompleteView.as_view()), name="order_complete"), url(r"^order/verification/(?P<pk>.+?)/(?P<key>.+?)/$", _not_here_yet, name="order_requires_verification"), url( r"^order/get-attachment/(?P<order_pk>\d+)/(?P<key>.+?)/(?P<att_pk>\d+)/", _not_here_yet, name="secure_attachment", ), url(r"^p/(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(ProductDetailView.as_view()), name="product"), url( r"^s/(?P<supplier_pk>\d+)-(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(ProductDetailView.as_view()), name="supplier-product", ), url(r"^c/$", csrf_exempt(AllCategoriesView.as_view()), name="all-categories"), url(r"^c/(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(CategoryView.as_view()), name="category"), ] # TODO: Document `front_urls_pre`, `front_urls` and `front_urls_post`. def _get_extension_urlpatterns(provide_category): return chain(*get_provide_objects(provide_category)) app_name = "shuup" urlpatterns = list( chain( *( _get_extension_urlpatterns("front_urls_pre"), urlpatterns, _get_extension_urlpatterns("front_urls"), [url(r"^$", IndexView.as_view(), name="index")], _get_extension_urlpatterns("front_urls_post"), ) ) )
xss
{ "code": [ " return HttpResponse(\"Not here yet: %s (%r, %r)\" % (request.path, args, kwargs), status=410)" ], "line_no": [ 40 ] }
{ "code": [ "from django.utils.html import escape" ], "line_no": [ 13 ] }
from __future__ import unicode_literals from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.http.response import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.i18n import set_language from itertools import chain from shuup.apps.provides import get_provide_objects from .views.basket import BasketView from .views.category import AllCategoriesView, CategoryView from .views.checkout import get_checkout_view from .views.dashboard import DashboardView from .views.index import IndexView from .views.misc import ( force_anonymous_contact, force_company_contact, force_person_contact, stop_impersonating, toggle_all_seeing, ) from .views.order import OrderCompleteView from .views.payment import ProcessPaymentView from .views.product import ProductDetailView from .views.upload import media_upload def FUNC_0(VAR_0, *VAR_1, **VAR_2): return HttpResponse("Not here yet: %s (%r, %r)" % (VAR_0.path, VAR_1, VAR_2), status=410) def FUNC_1(VAR_0, VAR_3="djangojs"): from shuup.utils.i18n import javascript_catalog_all return javascript_catalog_all(VAR_0, VAR_3) VAR_4 = get_checkout_view() VAR_5 = [ url(r"^set-language/$", csrf_exempt(set_language), name="set-language"), url(r"^i18n.js$", FUNC_1, name="js-catalog"), url(r"^checkout/$", VAR_4, name="checkout"), url(r"^checkout/(?P<phase>.+)/$", VAR_4, name="checkout"), url(r"^basket/$", csrf_exempt(BasketView.as_view()), name="basket"), url(r"^dashboard/$", login_required(DashboardView.as_view()), name="dashboard"), url(r"^toggle-allseeing/$", login_required(toggle_all_seeing), name="toggle-all-seeing"), url(r"^force-anonymous-contact/$", login_required(force_anonymous_contact), name="force-anonymous-contact"), url(r"^force-company-contact/$", login_required(force_company_contact), name="force-company-contact"), url(r"^force-person-contact/$", login_required(force_person_contact), name="force-person-contact"), url(r"^stop-impersonating/$", login_required(stop_impersonating), name="stop-impersonating"), url(r"^upload-media/$", login_required(media_upload), name="media-upload"), url( r"^order/payment/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(ProcessPaymentView.as_view()), VAR_2={"mode": "payment"}, name="order_process_payment", ), url( r"^order/process-payment/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(ProcessPaymentView.as_view()), VAR_2={"mode": "return"}, name="order_process_payment_return", ), url( r"^order/payment-canceled/(?P<pk>.+?)/(?P<key>.+?)/$", ProcessPaymentView.as_view(), VAR_2={"mode": "cancel"}, name="order_payment_canceled", ), url(r"^order/complete/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(OrderCompleteView.as_view()), name="order_complete"), url(r"^order/verification/(?P<pk>.+?)/(?P<key>.+?)/$", FUNC_0, name="order_requires_verification"), url( r"^order/get-attachment/(?P<order_pk>\d+)/(?P<key>.+?)/(?P<att_pk>\d+)/", FUNC_0, name="secure_attachment", ), url(r"^p/(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(ProductDetailView.as_view()), name="product"), url( r"^s/(?P<supplier_pk>\d+)-(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(ProductDetailView.as_view()), name="supplier-product", ), url(r"^c/$", csrf_exempt(AllCategoriesView.as_view()), name="all-categories"), url(r"^c/(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(CategoryView.as_view()), name="category"), ] def FUNC_2(VAR_6): return chain(*get_provide_objects(VAR_6)) VAR_7 = "shuup" VAR_5 = list( chain( *( FUNC_2("front_urls_pre"), VAR_5, FUNC_2("front_urls"), [url(r"^$", IndexView.as_view(), name="index")], FUNC_2("front_urls_post"), ) ) )
from __future__ import unicode_literals from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.http.response import HttpResponse from django.utils.html import escape from django.views.decorators.csrf import csrf_exempt from django.views.i18n import set_language from itertools import chain from shuup.apps.provides import get_provide_objects from .views.basket import BasketView from .views.category import AllCategoriesView, CategoryView from .views.checkout import get_checkout_view from .views.dashboard import DashboardView from .views.index import IndexView from .views.misc import ( force_anonymous_contact, force_company_contact, force_person_contact, stop_impersonating, toggle_all_seeing, ) from .views.order import OrderCompleteView from .views.payment import ProcessPaymentView from .views.product import ProductDetailView from .views.upload import media_upload def FUNC_0(VAR_0, *VAR_1, **VAR_2): return HttpResponse("Not here yet: %s (%r, %r)" % (VAR_0.path, escape(VAR_1), escape(VAR_2)), status=410) def FUNC_1(VAR_0, VAR_3="djangojs"): from shuup.utils.i18n import javascript_catalog_all return javascript_catalog_all(VAR_0, VAR_3) VAR_4 = get_checkout_view() VAR_5 = [ url(r"^set-language/$", csrf_exempt(set_language), name="set-language"), url(r"^i18n.js$", FUNC_1, name="js-catalog"), url(r"^checkout/$", VAR_4, name="checkout"), url(r"^checkout/(?P<phase>.+)/$", VAR_4, name="checkout"), url(r"^basket/$", csrf_exempt(BasketView.as_view()), name="basket"), url(r"^dashboard/$", login_required(DashboardView.as_view()), name="dashboard"), url(r"^toggle-allseeing/$", login_required(toggle_all_seeing), name="toggle-all-seeing"), url(r"^force-anonymous-contact/$", login_required(force_anonymous_contact), name="force-anonymous-contact"), url(r"^force-company-contact/$", login_required(force_company_contact), name="force-company-contact"), url(r"^force-person-contact/$", login_required(force_person_contact), name="force-person-contact"), url(r"^stop-impersonating/$", login_required(stop_impersonating), name="stop-impersonating"), url(r"^upload-media/$", login_required(media_upload), name="media-upload"), url( r"^order/payment/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(ProcessPaymentView.as_view()), VAR_2={"mode": "payment"}, name="order_process_payment", ), url( r"^order/process-payment/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(ProcessPaymentView.as_view()), VAR_2={"mode": "return"}, name="order_process_payment_return", ), url( r"^order/payment-canceled/(?P<pk>.+?)/(?P<key>.+?)/$", ProcessPaymentView.as_view(), VAR_2={"mode": "cancel"}, name="order_payment_canceled", ), url(r"^order/complete/(?P<pk>.+?)/(?P<key>.+?)/$", csrf_exempt(OrderCompleteView.as_view()), name="order_complete"), url(r"^order/verification/(?P<pk>.+?)/(?P<key>.+?)/$", FUNC_0, name="order_requires_verification"), url( r"^order/get-attachment/(?P<order_pk>\d+)/(?P<key>.+?)/(?P<att_pk>\d+)/", FUNC_0, name="secure_attachment", ), url(r"^p/(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(ProductDetailView.as_view()), name="product"), url( r"^s/(?P<supplier_pk>\d+)-(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(ProductDetailView.as_view()), name="supplier-product", ), url(r"^c/$", csrf_exempt(AllCategoriesView.as_view()), name="all-categories"), url(r"^c/(?P<pk>\d+)-(?P<slug>.*)/$", csrf_exempt(CategoryView.as_view()), name="category"), ] def FUNC_2(VAR_6): return chain(*get_provide_objects(VAR_6)) VAR_7 = "shuup" VAR_5 = list( chain( *( FUNC_2("front_urls_pre"), VAR_5, FUNC_2("front_urls"), [url(r"^$", IndexView.as_view(), name="index")], FUNC_2("front_urls_post"), ) ) )
[ 1, 2, 3, 4, 5, 6, 7, 9, 16, 18, 35, 36, 37, 38, 41, 42, 43, 44, 47, 49, 50, 52, 53, 101, 102, 103, 104, 107, 108, 121 ]
[ 1, 2, 3, 4, 5, 6, 7, 9, 17, 19, 36, 37, 38, 39, 42, 43, 44, 45, 48, 50, 51, 53, 54, 102, 103, 104, 105, 108, 109, 122 ]
1CWE-79
# -*- coding: utf-8 -*- # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from os import path from synapse.config import ConfigError from ._base import Config DEFAULT_CONFIG = """\ # User Consent configuration # # for detailed instructions, see # https://github.com/matrix-org/synapse/blob/master/docs/consent_tracking.md # # Parts of this section are required if enabling the 'consent' resource under # 'listeners', in particular 'template_dir' and 'version'. # # 'template_dir' gives the location of the templates for the HTML forms. # This directory should contain one subdirectory per language (eg, 'en', 'fr'), # and each language directory should contain the policy document (named as # '<version>.html') and a success page (success.html). # # 'version' specifies the 'current' version of the policy document. It defines # the version to be served by the consent resource if there is no 'v' # parameter. # # 'server_notice_content', if enabled, will send a user a "Server Notice" # asking them to consent to the privacy policy. The 'server_notices' section # must also be configured for this to work. Notices will *not* be sent to # guest users unless 'send_server_notice_to_guests' is set to true. # # 'block_events_error', if set, will block any attempts to send events # until the user consents to the privacy policy. The value of the setting is # used as the text of the error. # # 'require_at_registration', if enabled, will add a step to the registration # process, similar to how captcha works. Users will be required to accept the # policy before their account is created. # # 'policy_name' is the display name of the policy users will see when registering # for an account. Has no effect unless `require_at_registration` is enabled. # Defaults to "Privacy Policy". # #user_consent: # template_dir: res/templates/privacy # version: 1.0 # server_notice_content: # msgtype: m.text # body: >- # To continue using this homeserver you must review and agree to the # terms and conditions at %(consent_uri)s # send_server_notice_to_guests: true # block_events_error: >- # To continue using this homeserver you must review and agree to the # terms and conditions at %(consent_uri)s # require_at_registration: false # policy_name: Privacy Policy # """ class ConsentConfig(Config): section = "consent" def __init__(self, *args): super().__init__(*args) self.user_consent_version = None self.user_consent_template_dir = None self.user_consent_server_notice_content = None self.user_consent_server_notice_to_guests = False self.block_events_without_consent_error = None self.user_consent_at_registration = False self.user_consent_policy_name = "Privacy Policy" def read_config(self, config, **kwargs): consent_config = config.get("user_consent") self.terms_template = self.read_templates(["terms.html"], autoescape=True)[0] if consent_config is None: return self.user_consent_version = str(consent_config["version"]) self.user_consent_template_dir = self.abspath(consent_config["template_dir"]) if not path.isdir(self.user_consent_template_dir): raise ConfigError( "Could not find template directory '%s'" % (self.user_consent_template_dir,) ) self.user_consent_server_notice_content = consent_config.get( "server_notice_content" ) self.block_events_without_consent_error = consent_config.get( "block_events_error" ) self.user_consent_server_notice_to_guests = bool( consent_config.get("send_server_notice_to_guests", False) ) self.user_consent_at_registration = bool( consent_config.get("require_at_registration", False) ) self.user_consent_policy_name = consent_config.get( "policy_name", "Privacy Policy" ) def generate_config_section(self, **kwargs): return DEFAULT_CONFIG
# -*- coding: utf-8 -*- # Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from os import path from synapse.config import ConfigError from ._base import Config DEFAULT_CONFIG = """\ # User Consent configuration # # for detailed instructions, see # https://github.com/matrix-org/synapse/blob/master/docs/consent_tracking.md # # Parts of this section are required if enabling the 'consent' resource under # 'listeners', in particular 'template_dir' and 'version'. # # 'template_dir' gives the location of the templates for the HTML forms. # This directory should contain one subdirectory per language (eg, 'en', 'fr'), # and each language directory should contain the policy document (named as # '<version>.html') and a success page (success.html). # # 'version' specifies the 'current' version of the policy document. It defines # the version to be served by the consent resource if there is no 'v' # parameter. # # 'server_notice_content', if enabled, will send a user a "Server Notice" # asking them to consent to the privacy policy. The 'server_notices' section # must also be configured for this to work. Notices will *not* be sent to # guest users unless 'send_server_notice_to_guests' is set to true. # # 'block_events_error', if set, will block any attempts to send events # until the user consents to the privacy policy. The value of the setting is # used as the text of the error. # # 'require_at_registration', if enabled, will add a step to the registration # process, similar to how captcha works. Users will be required to accept the # policy before their account is created. # # 'policy_name' is the display name of the policy users will see when registering # for an account. Has no effect unless `require_at_registration` is enabled. # Defaults to "Privacy Policy". # #user_consent: # template_dir: res/templates/privacy # version: 1.0 # server_notice_content: # msgtype: m.text # body: >- # To continue using this homeserver you must review and agree to the # terms and conditions at %(consent_uri)s # send_server_notice_to_guests: true # block_events_error: >- # To continue using this homeserver you must review and agree to the # terms and conditions at %(consent_uri)s # require_at_registration: false # policy_name: Privacy Policy # """ class ConsentConfig(Config): section = "consent" def __init__(self, *args): super().__init__(*args) self.user_consent_version = None self.user_consent_template_dir = None self.user_consent_server_notice_content = None self.user_consent_server_notice_to_guests = False self.block_events_without_consent_error = None self.user_consent_at_registration = False self.user_consent_policy_name = "Privacy Policy" def read_config(self, config, **kwargs): consent_config = config.get("user_consent") self.terms_template = self.read_template("terms.html") if consent_config is None: return self.user_consent_version = str(consent_config["version"]) self.user_consent_template_dir = self.abspath(consent_config["template_dir"]) if not path.isdir(self.user_consent_template_dir): raise ConfigError( "Could not find template directory '%s'" % (self.user_consent_template_dir,) ) self.user_consent_server_notice_content = consent_config.get( "server_notice_content" ) self.block_events_without_consent_error = consent_config.get( "block_events_error" ) self.user_consent_server_notice_to_guests = bool( consent_config.get("send_server_notice_to_guests", False) ) self.user_consent_at_registration = bool( consent_config.get("require_at_registration", False) ) self.user_consent_policy_name = consent_config.get( "policy_name", "Privacy Policy" ) def generate_config_section(self, **kwargs): return DEFAULT_CONFIG
xss
{ "code": [ " self.terms_template = self.read_templates([\"terms.html\"], autoescape=True)[0]" ], "line_no": [ 92 ] }
{ "code": [ " self.terms_template = self.read_template(\"terms.html\")" ], "line_no": [ 92 ] }
from os import path from synapse.config import ConfigError from ._base import Config VAR_0 = """\ """ class CLASS_0(Config): VAR_1 = "consent" def __init__(self, *VAR_2): super().__init__(*VAR_2) self.user_consent_version = None self.user_consent_template_dir = None self.user_consent_server_notice_content = None self.user_consent_server_notice_to_guests = False self.block_events_without_consent_error = None self.user_consent_at_registration = False self.user_consent_policy_name = "Privacy Policy" def FUNC_0(self, VAR_3, **VAR_4): VAR_5 = VAR_3.get("user_consent") self.terms_template = self.read_templates(["terms.html"], autoescape=True)[0] if VAR_5 is None: return self.user_consent_version = str(VAR_5["version"]) self.user_consent_template_dir = self.abspath(VAR_5["template_dir"]) if not path.isdir(self.user_consent_template_dir): raise ConfigError( "Could not find template directory '%s'" % (self.user_consent_template_dir,) ) self.user_consent_server_notice_content = VAR_5.get( "server_notice_content" ) self.block_events_without_consent_error = VAR_5.get( "block_events_error" ) self.user_consent_server_notice_to_guests = bool( VAR_5.get("send_server_notice_to_guests", False) ) self.user_consent_at_registration = bool( VAR_5.get("require_at_registration", False) ) self.user_consent_policy_name = VAR_5.get( "policy_name", "Privacy Policy" ) def FUNC_1(self, **VAR_4): return VAR_0
from os import path from synapse.config import ConfigError from ._base import Config VAR_0 = """\ """ class CLASS_0(Config): VAR_1 = "consent" def __init__(self, *VAR_2): super().__init__(*VAR_2) self.user_consent_version = None self.user_consent_template_dir = None self.user_consent_server_notice_content = None self.user_consent_server_notice_to_guests = False self.block_events_without_consent_error = None self.user_consent_at_registration = False self.user_consent_policy_name = "Privacy Policy" def FUNC_0(self, VAR_3, **VAR_4): VAR_5 = VAR_3.get("user_consent") self.terms_template = self.read_template("terms.html") if VAR_5 is None: return self.user_consent_version = str(VAR_5["version"]) self.user_consent_template_dir = self.abspath(VAR_5["template_dir"]) if not path.isdir(self.user_consent_template_dir): raise ConfigError( "Could not find template directory '%s'" % (self.user_consent_template_dir,) ) self.user_consent_server_notice_content = VAR_5.get( "server_notice_content" ) self.block_events_without_consent_error = VAR_5.get( "block_events_error" ) self.user_consent_server_notice_to_guests = bool( VAR_5.get("send_server_notice_to_guests", False) ) self.user_consent_at_registration = bool( VAR_5.get("require_at_registration", False) ) self.user_consent_policy_name = VAR_5.get( "policy_name", "Privacy Policy" ) def FUNC_1(self, **VAR_4): return VAR_0
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 73, 74, 76, 78, 81, 89, 93, 118, 121 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 73, 74, 76, 78, 81, 89, 93, 118, 121 ]
1CWE-79
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import base64 import datetime import logging import os import re from collections import defaultdict from flask import ( Response, abort, g, make_response, redirect, render_template, request, send_from_directory, url_for, ) import octoprint.plugin from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.filemanager import full_extension_tree, get_all_extensions from octoprint.server import ( # noqa: F401 BRANCH, DISPLAY_VERSION, LOCALES, NOT_MODIFIED, VERSION, app, debug, gettext, groupManager, pluginManager, preemptiveCache, userManager, ) from octoprint.server.util import has_permissions, require_login_with from octoprint.settings import settings from octoprint.util import sv, to_bytes, to_unicode from octoprint.util.version import get_python_version_string from . import util _logger = logging.getLogger(__name__) _templates = {} _plugin_names = None _plugin_vars = None _valid_id_re = re.compile("[a-z_]+") _valid_div_re = re.compile("[a-zA-Z_-]+") def _preemptive_unless(base_url=None, additional_unless=None): if base_url is None: base_url = request.url_root disabled_for_root = ( not settings().getBoolean(["devel", "cache", "preemptive"]) or base_url in settings().get(["server", "preemptiveCache", "exceptions"]) or not (base_url.startswith("http://") or base_url.startswith("https://")) ) recording_disabled = request.headers.get("X-Preemptive-Recording", "no") == "yes" if callable(additional_unless): return recording_disabled or disabled_for_root or additional_unless() else: return recording_disabled or disabled_for_root def _preemptive_data( key, path=None, base_url=None, data=None, additional_request_data=None ): if path is None: path = request.path if base_url is None: base_url = request.url_root d = { "path": path, "base_url": base_url, "query_string": "l10n={}".format(g.locale.language if g.locale else "en"), } if key != "_default": d["plugin"] = key # add data if we have any if data is not None: try: if callable(data): data = data() if data: if "query_string" in data: data["query_string"] = "l10n={}&{}".format( g.locale.language, data["query_string"] ) d.update(data) except Exception: _logger.exception( f"Error collecting data for preemptive cache from plugin {key}" ) # add additional request data if we have any if callable(additional_request_data): try: ard = additional_request_data() if ard: d.update({"_additional_request_data": ard}) except Exception: _logger.exception( "Error retrieving additional data for preemptive cache from plugin {}".format( key ) ) return d def _cache_key(ui, url=None, locale=None, additional_key_data=None): if url is None: url = request.base_url if locale is None: locale = g.locale.language if g.locale else "en" k = f"ui:{ui}:{url}:{locale}" if callable(additional_key_data): try: ak = additional_key_data() if ak: # we have some additional key components, let's attach them if not isinstance(ak, (list, tuple)): ak = [ak] k = "{}:{}".format(k, ":".join(ak)) except Exception: _logger.exception( "Error while trying to retrieve additional cache key parts for ui {}".format( ui ) ) return k def _valid_status_for_cache(status_code): return 200 <= status_code < 400 def _add_additional_assets(hook): result = [] for name, hook in pluginManager.get_hooks(hook).items(): try: assets = hook() if isinstance(assets, (tuple, list)): result += assets except Exception: _logger.exception( f"Error fetching theming CSS to include from plugin {name}", extra={"plugin": name}, ) return result @app.route("/login") @app.route("/login/") def login(): from flask_login import current_user redirect_url = request.args.get("redirect", request.script_root + url_for("index")) permissions = sorted( filter( lambda x: x is not None and isinstance(x, OctoPrintPermission), map( lambda x: getattr(Permissions, x.strip()), request.args.get("permissions", "").split(","), ), ), key=lambda x: x.get_name(), ) if not permissions: permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] user_id = request.args.get("user_id", "") if (not user_id or current_user.get_id() == user_id) and has_permissions( *permissions ): return redirect(redirect_url) render_kwargs = { "theming": [], "redirect_url": redirect_url, "permission_names": map(lambda x: x.get_name(), permissions), "user_id": user_id, "logged_in": not current_user.is_anonymous, } try: additional_assets = _add_additional_assets("octoprint.theming.login") # backwards compatibility to forcelogin & loginui plugins which were replaced by this built-in dialog additional_assets += _add_additional_assets("octoprint.plugin.forcelogin.theming") additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming") render_kwargs.update({"theming": additional_assets}) except Exception: _logger.exception("Error processing theming CSS, ignoring") return render_template("login.jinja2", **render_kwargs) @app.route("/recovery") @app.route("/recovery/") def recovery(): response = require_login_with(permissions=[Permissions.ADMIN]) if response: return response render_kwargs = {"theming": []} try: additional_assets = _add_additional_assets("octoprint.theming.recovery") render_kwargs.update({"theming": additional_assets}) except Exception: _logger.exception("Error processing theming CSS, ignoring") try: from octoprint.plugins.backup import MAX_UPLOAD_SIZE from octoprint.util import get_formatted_size render_kwargs.update( { "plugin_backup_max_upload_size": MAX_UPLOAD_SIZE, "plugin_backup_max_upload_size_str": get_formatted_size(MAX_UPLOAD_SIZE), } ) except Exception: _logger.exception("Error adding backup upload size info, ignoring") return render_template("recovery.jinja2", **render_kwargs) @app.route("/cached.gif") def in_cache(): url = request.base_url.replace("/cached.gif", "/") path = request.path.replace("/cached.gif", "/") base_url = request.url_root # select view from plugins and fall back on default view if no plugin will handle it ui_plugins = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for plugin in ui_plugins: try: if plugin.will_handle_ui(request): ui = plugin._identifier key = _cache_key( plugin._identifier, url=url, additional_key_data=plugin.get_ui_additional_key_data_for_cache, ) unless = _preemptive_unless( url, additional_unless=plugin.get_ui_preemptive_caching_additional_unless, ) data = _preemptive_data( plugin._identifier, path=path, base_url=base_url, data=plugin.get_ui_data_for_preemptive_caching, additional_request_data=plugin.get_ui_additional_request_data_for_preemptive_caching, ) break except Exception: _logger.exception( f"Error while calling plugin {plugin._identifier}, skipping it", extra={"plugin": plugin._identifier}, ) else: ui = "_default" key = _cache_key("_default", url=url) unless = _preemptive_unless(url) data = _preemptive_data("_default", path=path, base_url=base_url) response = make_response( bytes( base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7") ) ) response.headers["Content-Type"] = "image/gif" if unless or not preemptiveCache.has_record(data, root=path): _logger.info( "Preemptive cache not active for path {}, ui {} and data {!r}, signaling as cached".format( path, ui, data ) ) return response elif util.flask.is_in_cache(key): _logger.info(f"Found path {path} in cache (key: {key}), signaling as cached") return response elif util.flask.is_cache_bypassed(key): _logger.info( "Path {} was bypassed from cache (key: {}), signaling as cached".format( path, key ) ) return response else: _logger.debug(f"Path {path} not yet cached (key: {key}), signaling as missing") return abort(404) @app.route("/") def index(): from octoprint.server import connectivityChecker, printer global _templates, _plugin_names, _plugin_vars preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"]) locale = g.locale.language if g.locale else "en" # helper to check if wizards are active def wizard_active(templates): return templates is not None and bool(templates["wizard"]["order"]) # we force a refresh if the client forces one and we are not printing or if we have wizards cached client_refresh = util.flask.cache_check_headers() request_refresh = "_refresh" in request.values printing = printer.is_printing() if client_refresh and printing: logging.getLogger(__name__).warning( "Client requested cache refresh via cache-control headers but we are printing. " "Not invalidating caches due to resource limitation. Append ?_refresh=true to " "the URL if you absolutely require a refresh now" ) client_refresh = client_refresh and not printing force_refresh = ( client_refresh or request_refresh or wizard_active(_templates.get(locale)) ) # if we need to refresh our template cache or it's not yet set, process it fetch_template_data(refresh=force_refresh) now = datetime.datetime.utcnow() enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"]) enable_loading_animation = settings().getBoolean(["devel", "showLoadingAnimation"]) enable_sd_support = settings().get(["feature", "sdSupport"]) enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"]) and bool( settings().get(["webcam", "stream"]) ) enable_temperature_graph = settings().get(["feature", "temperatureGraph"]) sockjs_connect_timeout = settings().getInt(["devel", "sockJsConnectTimeout"]) def default_template_filter(template_type, template_key): if template_type == "tab": return template_key != "timelapse" or enable_timelapse else: return True default_additional_etag = [ enable_timelapse, enable_loading_animation, enable_sd_support, enable_webcam, enable_temperature_graph, sockjs_connect_timeout, connectivityChecker.online, wizard_active(_templates.get(locale)), ] + sorted( "{}:{}".format(to_unicode(k, errors="replace"), to_unicode(v, errors="replace")) for k, v in _plugin_vars.items() ) def get_preemptively_cached_view( key, view, data=None, additional_request_data=None, additional_unless=None ): if (data is None and additional_request_data is None) or g.locale is None: return view d = _preemptive_data( key, data=data, additional_request_data=additional_request_data ) def unless(): return _preemptive_unless( base_url=request.url_root, additional_unless=additional_unless ) # finally decorate our view return util.flask.preemptively_cached( cache=preemptiveCache, data=d, unless=unless )(view) def get_cached_view( key, view, additional_key_data=None, additional_files=None, additional_etag=None, custom_files=None, custom_etag=None, custom_lastmodified=None, ): if additional_etag is None: additional_etag = [] def cache_key(): return _cache_key(key, additional_key_data=additional_key_data) def collect_files(): if callable(custom_files): try: files = custom_files() if files: return files except Exception: _logger.exception( "Error while trying to retrieve tracked files for plugin {}".format( key ) ) files = _get_all_templates() files += _get_all_assets() files += _get_all_translationfiles( g.locale.language if g.locale else "en", "messages" ) if callable(additional_files): try: af = additional_files() if af: files += af except Exception: _logger.exception( "Error while trying to retrieve additional tracked files for plugin {}".format( key ) ) return sorted(set(files)) def compute_lastmodified(files): if callable(custom_lastmodified): try: lastmodified = custom_lastmodified() if lastmodified: return lastmodified except Exception: _logger.exception( "Error while trying to retrieve custom LastModified value for plugin {}".format( key ) ) return _compute_date(files) def compute_etag(files, lastmodified, additional=None): if callable(custom_etag): try: etag = custom_etag() if etag: return etag except Exception: _logger.exception( "Error while trying to retrieve custom ETag value for plugin {}".format( key ) ) if lastmodified and not isinstance(lastmodified, str): from werkzeug.http import http_date lastmodified = http_date(lastmodified) if additional is None: additional = [] import hashlib hash = hashlib.sha1() def hash_update(value): hash.update(to_bytes(value, encoding="utf-8", errors="replace")) hash_update(octoprint.__version__) hash_update(get_python_version_string()) hash_update(",".join(sorted(files))) if lastmodified: hash_update(lastmodified) for add in additional: hash_update(add) return hash.hexdigest() current_files = collect_files() current_lastmodified = compute_lastmodified(current_files) current_etag = compute_etag( files=current_files, lastmodified=current_lastmodified, additional=[cache_key()] + additional_etag, ) def check_etag_and_lastmodified(): lastmodified_ok = util.flask.check_lastmodified(current_lastmodified) etag_ok = util.flask.check_etag(current_etag) return lastmodified_ok and etag_ok def validate_cache(cached): return force_refresh or (current_etag != cached.get_etag()[0]) decorated_view = view decorated_view = util.flask.lastmodified(lambda _: current_lastmodified)( decorated_view ) decorated_view = util.flask.etagged(lambda _: current_etag)(decorated_view) decorated_view = util.flask.cached( timeout=-1, refreshif=validate_cache, key=cache_key, unless_response=lambda response: util.flask.cache_check_response_headers( response ) or util.flask.cache_check_status_code(response, _valid_status_for_cache), )(decorated_view) decorated_view = util.flask.with_client_revalidation(decorated_view) decorated_view = util.flask.conditional( check_etag_and_lastmodified, NOT_MODIFIED )(decorated_view) return decorated_view def plugin_view(p): cached = get_cached_view( p._identifier, p.on_ui_render, additional_key_data=p.get_ui_additional_key_data_for_cache, additional_files=p.get_ui_additional_tracked_files, custom_files=p.get_ui_custom_tracked_files, custom_etag=p.get_ui_custom_etag, custom_lastmodified=p.get_ui_custom_lastmodified, additional_etag=p.get_ui_additional_etag(default_additional_etag), ) if preemptive_cache_enabled and p.get_ui_preemptive_caching_enabled(): view = get_preemptively_cached_view( p._identifier, cached, p.get_ui_data_for_preemptive_caching, p.get_ui_additional_request_data_for_preemptive_caching, p.get_ui_preemptive_caching_additional_unless, ) else: view = cached template_filter = p.get_ui_custom_template_filter(default_template_filter) if template_filter is not None and callable(template_filter): filtered_templates = _filter_templates(_templates[locale], template_filter) else: filtered_templates = _templates[locale] render_kwargs = _get_render_kwargs( filtered_templates, _plugin_names, _plugin_vars, now ) return view(now, request, render_kwargs) def default_view(): filtered_templates = _filter_templates( _templates[locale], default_template_filter ) wizard = wizard_active(filtered_templates) accesscontrol_active = userManager.has_been_customized() render_kwargs = _get_render_kwargs( filtered_templates, _plugin_names, _plugin_vars, now ) render_kwargs.update( { "enableWebcam": enable_webcam, "enableTemperatureGraph": enable_temperature_graph, "enableAccessControl": True, "accessControlActive": accesscontrol_active, "enableLoadingAnimation": enable_loading_animation, "enableSdSupport": enable_sd_support, "sockJsConnectTimeout": sockjs_connect_timeout * 1000, "wizard": wizard, "online": connectivityChecker.online, "now": now, } ) # no plugin took an interest, we'll use the default UI def make_default_ui(): r = make_response(render_template("index.jinja2", **render_kwargs)) if wizard: # if we have active wizard dialogs, set non caching headers r = util.flask.add_non_caching_response_headers(r) return r cached = get_cached_view( "_default", make_default_ui, additional_etag=default_additional_etag ) preemptively_cached = get_preemptively_cached_view("_default", cached, {}, {}) return preemptively_cached() default_permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] response = None forced_view = request.headers.get("X-Force-View", None) if forced_view: # we have view forced by the preemptive cache _logger.debug(f"Forcing rendering of view {forced_view}") if forced_view != "_default": plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True) if plugin is not None and isinstance( plugin.implementation, octoprint.plugin.UiPlugin ): permissions = plugin.implementation.get_ui_permissions() response = require_login_with(permissions=permissions) if not response: response = plugin_view(plugin.implementation) if _logger.isEnabledFor(logging.DEBUG) and isinstance( response, Response ): response.headers[ "X-Ui-Plugin" ] = plugin.implementation._identifier else: response = require_login_with(permissions=default_permissions) if not response: response = default_view() if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): response.headers["X-Ui-Plugin"] = "_default" else: # select view from plugins and fall back on default view if no plugin will handle it ui_plugins = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for plugin in ui_plugins: try: if plugin.will_handle_ui(request): # plugin claims responsibility, let it render the UI permissions = plugin.get_ui_permissions() response = require_login_with(permissions=permissions) if not response: response = plugin_view(plugin) if response is not None: if _logger.isEnabledFor(logging.DEBUG) and isinstance( response, Response ): response.headers["X-Ui-Plugin"] = plugin._identifier break else: _logger.warning( "UiPlugin {} returned an empty response".format( plugin._identifier ) ) except Exception: _logger.exception( "Error while calling plugin {}, skipping it".format( plugin._identifier ), extra={"plugin": plugin._identifier}, ) else: response = require_login_with(permissions=default_permissions) if not response: response = default_view() if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): response.headers["X-Ui-Plugin"] = "_default" if response is None: return abort(404) return response def _get_render_kwargs(templates, plugin_names, plugin_vars, now): global _logger # ~~ a bunch of settings first_run = settings().getBoolean(["server", "firstRun"]) locales = {} for loc in LOCALES: try: locales[loc.language] = { "language": loc.language, "display": loc.display_name, "english": loc.english_name, } except Exception: _logger.exception("Error while collecting available locales") permissions = [permission.as_dict() for permission in Permissions.all()] filetypes = list(sorted(full_extension_tree().keys())) extensions = list(map(lambda ext: f".{ext}", get_all_extensions())) # ~~ prepare full set of template vars for rendering render_kwargs = { "debug": debug, "firstRun": first_run, "version": {"number": VERSION, "display": DISPLAY_VERSION, "branch": BRANCH}, "python_version": get_python_version_string(), "templates": templates, "pluginNames": plugin_names, "locales": locales, "permissions": permissions, "supportedFiletypes": filetypes, "supportedExtensions": extensions, } render_kwargs.update(plugin_vars) return render_kwargs def fetch_template_data(refresh=False): global _templates, _plugin_names, _plugin_vars locale = g.locale.language if g.locale else "en" if ( not refresh and _templates.get(locale) is not None and _plugin_names is not None and _plugin_vars is not None ): return _templates[locale], _plugin_names, _plugin_vars first_run = settings().getBoolean(["server", "firstRun"]) ##~~ prepare templates templates = defaultdict(lambda: {"order": [], "entries": {}}) # rules for transforming template configs to template entries template_rules = { "navbar": { "div": lambda x: "navbar_plugin_" + x, "template": lambda x: x + "_navbar.jinja2", "to_entry": lambda data: data, }, "sidebar": { "div": lambda x: "sidebar_plugin_" + x, "template": lambda x: x + "_sidebar.jinja2", "to_entry": lambda data: (data["name"], data), }, "tab": { "div": lambda x: "tab_plugin_" + x, "template": lambda x: x + "_tab.jinja2", "to_entry": lambda data: (data["name"], data), }, "settings": { "div": lambda x: "settings_plugin_" + x, "template": lambda x: x + "_settings.jinja2", "to_entry": lambda data: (data["name"], data), }, "usersettings": { "div": lambda x: "usersettings_plugin_" + x, "template": lambda x: x + "_usersettings.jinja2", "to_entry": lambda data: (data["name"], data), }, "wizard": { "div": lambda x: "wizard_plugin_" + x, "template": lambda x: x + "_wizard.jinja2", "to_entry": lambda data: (data["name"], data), }, "about": { "div": lambda x: "about_plugin_" + x, "template": lambda x: x + "_about.jinja2", "to_entry": lambda data: (data["name"], data), }, "generic": {"template": lambda x: x + ".jinja2", "to_entry": lambda data: data}, } # sorting orders def wizard_key_extractor(d, k): if d[1].get("_key", None) == "plugin_corewizard_acl": # Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and # that require to access APIs to function will run into errors since those APIs won't work before ACL # has been configured. See also #2140 return f"0:{to_unicode(d[0])}" elif d[1].get("mandatory", False): # Other mandatory steps come before the optional ones return f"1:{to_unicode(d[0])}" else: # Finally everything else return f"2:{to_unicode(d[0])}" template_sorting = { "navbar": {"add": "prepend", "key": None}, "sidebar": {"add": "append", "key": "name"}, "tab": {"add": "append", "key": "name"}, "settings": { "add": "custom_append", "key": "name", "custom_add_entries": lambda missing: { "section_plugins": (gettext("Plugins"), None) }, "custom_add_order": lambda missing: ["section_plugins"] + missing, }, "usersettings": {"add": "append", "key": "name"}, "wizard": {"add": "append", "key": "name", "key_extractor": wizard_key_extractor}, "about": {"add": "append", "key": "name"}, "generic": {"add": "append", "key": None}, } hooks = pluginManager.get_hooks("octoprint.ui.web.templatetypes") for name, hook in hooks.items(): try: result = hook(dict(template_sorting), dict(template_rules)) except Exception: _logger.exception( f"Error while retrieving custom template type " f"definitions from plugin {name}", extra={"plugin": name}, ) else: if not isinstance(result, list): continue for entry in result: if not isinstance(entry, tuple) or not len(entry) == 3: continue key, order, rule = entry # order defaults if "add" not in order: order["add"] = "prepend" if "key" not in order: order["key"] = "name" # rule defaults if "div" not in rule: # default div name: <hook plugin>_<template_key>_plugin_<plugin> div = f"{name}_{key}_plugin_" rule["div"] = lambda x: div + x if "template" not in rule: # default template name: <plugin>_plugin_<hook plugin>_<template key>.jinja2 template = f"_plugin_{name}_{key}.jinja2" rule["template"] = lambda x: x + template if "to_entry" not in rule: # default to_entry assumes existing "name" property to be used as label for 2-tuple entry data structure (<name>, <properties>) rule["to_entry"] = lambda data: (data["name"], data) template_rules["plugin_" + name + "_" + key] = rule template_sorting["plugin_" + name + "_" + key] = order template_types = list(template_rules.keys()) # navbar templates["navbar"]["entries"] = { "offlineindicator": { "template": "navbar/offlineindicator.jinja2", "_div": "navbar_offlineindicator", "custom_bindings": False, }, "settings": { "template": "navbar/settings.jinja2", "_div": "navbar_settings", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SETTINGS)", }, "systemmenu": { "template": "navbar/systemmenu.jinja2", "_div": "navbar_systemmenu", "classes": ["dropdown"], "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", "custom_bindings": False, }, "login": { "template": "navbar/login.jinja2", "_div": "navbar_login", "classes": ["dropdown"], "custom_bindings": False, }, } # sidebar templates["sidebar"]["entries"] = { "connection": ( gettext("Connection"), { "template": "sidebar/connection.jinja2", "_div": "connection", "icon": "signal", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.CONNECTION)", "template_header": "sidebar/connection_header.jinja2", }, ), "state": ( gettext("State"), { "template": "sidebar/state.jinja2", "_div": "state", "icon": "info-circle", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.STATUS)", }, ), "files": ( gettext("Files"), { "template": "sidebar/files.jinja2", "_div": "files", "icon": "list", "classes_content": ["overflow_visible"], "template_header": "sidebar/files_header.jinja2", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.FILES_LIST)", }, ), } # tabs templates["tab"]["entries"] = { "temperature": ( gettext("Temperature"), { "template": "tabs/temperature.jinja2", "_div": "temp", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)() && visible()", }, ), "control": ( gettext("Control"), { "template": "tabs/control.jinja2", "_div": "control", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.WEBCAM, access.permissions.CONTROL)", }, ), "terminal": ( gettext("Terminal"), { "template": "tabs/terminal.jinja2", "_div": "term", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.MONITOR_TERMINAL)", }, ), "timelapse": ( gettext("Timelapse"), { "template": "tabs/timelapse.jinja2", "_div": "timelapse", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.TIMELAPSE_LIST)", }, ), } # settings dialog templates["settings"]["entries"] = { "section_printer": (gettext("Printer"), None), "serial": ( gettext("Serial Connection"), { "template": "dialogs/settings/serialconnection.jinja2", "_div": "settings_serialConnection", "custom_bindings": False, }, ), "printerprofiles": ( gettext("Printer Profiles"), { "template": "dialogs/settings/printerprofiles.jinja2", "_div": "settings_printerProfiles", "custom_bindings": False, }, ), "temperatures": ( gettext("Temperatures"), { "template": "dialogs/settings/temperatures.jinja2", "_div": "settings_temperature", "custom_bindings": False, }, ), "terminalfilters": ( gettext("Terminal Filters"), { "template": "dialogs/settings/terminalfilters.jinja2", "_div": "settings_terminalFilters", "custom_bindings": False, }, ), "gcodescripts": ( gettext("GCODE Scripts"), { "template": "dialogs/settings/gcodescripts.jinja2", "_div": "settings_gcodeScripts", "custom_bindings": False, }, ), "section_features": (gettext("Features"), None), "features": ( gettext("Features"), { "template": "dialogs/settings/features.jinja2", "_div": "settings_features", "custom_bindings": False, }, ), "webcam": ( gettext("Webcam & Timelapse"), { "template": "dialogs/settings/webcam.jinja2", "_div": "settings_webcam", "custom_bindings": False, }, ), "api": ( gettext("API"), { "template": "dialogs/settings/api.jinja2", "_div": "settings_api", "custom_bindings": False, }, ), "section_octoprint": (gettext("OctoPrint"), None), "accesscontrol": ( gettext("Access Control"), { "template": "dialogs/settings/accesscontrol.jinja2", "_div": "settings_users", "custom_bindings": False, }, ), "folders": ( gettext("Folders"), { "template": "dialogs/settings/folders.jinja2", "_div": "settings_folders", "custom_bindings": False, }, ), "appearance": ( gettext("Appearance"), { "template": "dialogs/settings/appearance.jinja2", "_div": "settings_appearance", "custom_bindings": False, }, ), "server": ( gettext("Server"), { "template": "dialogs/settings/server.jinja2", "_div": "settings_server", "custom_bindings": False, }, ), } # user settings dialog templates["usersettings"]["entries"] = { "access": ( gettext("Access"), { "template": "dialogs/usersettings/access.jinja2", "_div": "usersettings_access", "custom_bindings": False, }, ), "interface": ( gettext("Interface"), { "template": "dialogs/usersettings/interface.jinja2", "_div": "usersettings_interface", "custom_bindings": False, }, ), } # wizard if first_run: def custom_insert_order(existing, missing): if "firstrunstart" in missing: missing.remove("firstrunstart") if "firstrunend" in missing: missing.remove("firstrunend") return ["firstrunstart"] + existing + missing + ["firstrunend"] template_sorting["wizard"].update( { "add": "custom_insert", "custom_insert_entries": lambda missing: {}, "custom_insert_order": custom_insert_order, } ) templates["wizard"]["entries"] = { "firstrunstart": ( gettext("Start"), { "template": "dialogs/wizard/firstrun_start.jinja2", "_div": "wizard_firstrun_start", }, ), "firstrunend": ( gettext("Finish"), { "template": "dialogs/wizard/firstrun_end.jinja2", "_div": "wizard_firstrun_end", }, ), } # about dialog templates["about"]["entries"] = { "about": ( "About OctoPrint", { "template": "dialogs/about/about.jinja2", "_div": "about_about", "custom_bindings": False, }, ), "license": ( "OctoPrint License", { "template": "dialogs/about/license.jinja2", "_div": "about_license", "custom_bindings": False, }, ), "thirdparty": ( "Third Party Licenses", { "template": "dialogs/about/thirdparty.jinja2", "_div": "about_thirdparty", "custom_bindings": False, }, ), "authors": ( "Authors", { "template": "dialogs/about/authors.jinja2", "_div": "about_authors", "custom_bindings": False, }, ), "supporters": ( "Supporters", { "template": "dialogs/about/supporters.jinja2", "_div": "about_sponsors", "custom_bindings": False, }, ), "systeminfo": ( "System Information", { "template": "dialogs/about/systeminfo.jinja2", "_div": "about_systeminfo", "custom_bindings": False, "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", }, ), } # extract data from template plugins template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin) plugin_vars = {} plugin_names = set() plugin_aliases = {} seen_wizards = settings().get(["server", "seenWizards"]) if not first_run else {} for implementation in template_plugins: name = implementation._identifier plugin_names.add(name) wizard_required = False wizard_ignored = False try: vars = implementation.get_template_vars() configs = implementation.get_template_configs() if isinstance(implementation, octoprint.plugin.WizardPlugin): wizard_required = implementation.is_wizard_required() wizard_ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored( seen_wizards, implementation ) except Exception: _logger.exception( "Error while retrieving template data for plugin {}, ignoring it".format( name ), extra={"plugin": name}, ) continue if not isinstance(vars, dict): vars = {} if not isinstance(configs, (list, tuple)): configs = [] for var_name, var_value in vars.items(): plugin_vars["plugin_" + name + "_" + var_name] = var_value try: includes = _process_template_configs( name, implementation, configs, template_rules ) except Exception: _logger.exception( "Error while processing template configs for plugin {}, ignoring it".format( name ), extra={"plugin": name}, ) if not wizard_required or wizard_ignored: includes["wizard"] = list() for t in template_types: plugin_aliases[t] = {} for include in includes[t]: if t == "navbar" or t == "generic": data = include else: data = include[1] key = data["_key"] if "replaces" in data: key = data["replaces"] plugin_aliases[t][data["_key"]] = data["replaces"] templates[t]["entries"][key] = include # ~~ order internal templates and plugins # make sure that # 1) we only have keys in our ordered list that we have entries for and # 2) we have all entries located somewhere within the order for t in template_types: default_order = ( settings().get( ["appearance", "components", "order", t], merged=True, config={} ) or [] ) configured_order = ( settings().get(["appearance", "components", "order", t], merged=True) or [] ) configured_disabled = ( settings().get(["appearance", "components", "disabled", t]) or [] ) # first create the ordered list of all component ids according to the configured order result = [] for x in configured_order: if x in plugin_aliases[t]: x = plugin_aliases[t][x] if ( x in templates[t]["entries"] and x not in configured_disabled and x not in result ): result.append(x) templates[t]["order"] = result # now append the entries from the default order that are not already in there templates[t]["order"] += [ x for x in default_order if x not in templates[t]["order"] and x in templates[t]["entries"] and x not in configured_disabled ] all_ordered = set(templates[t]["order"]) all_disabled = set(configured_disabled) # check if anything is missing, if not we are done here missing_in_order = ( set(templates[t]["entries"].keys()) .difference(all_ordered) .difference(all_disabled) ) if len(missing_in_order) == 0: continue # works with entries that are dicts and entries that are 2-tuples with the # entry data at index 1 def config_extractor(item, key, default_value=None): if isinstance(item, dict) and key in item: return item[key] if key in item else default_value elif ( isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1] ): return item[1][key] if key in item[1] else default_value return default_value # finally add anything that's not included in our order yet if template_sorting[t]["key"] is not None: # we'll use our config extractor as default key extractor extractor = config_extractor # if template type provides custom extractor, make sure its exceptions are handled if "key_extractor" in template_sorting[t] and callable( template_sorting[t]["key_extractor"] ): def create_safe_extractor(extractor): def f(x, k): try: return extractor(x, k) except Exception: _logger.exception( "Error while extracting sorting keys for template {}".format( t ) ) return None return f extractor = create_safe_extractor(template_sorting[t]["key_extractor"]) sort_key = template_sorting[t]["key"] def key_func(x): config = templates[t]["entries"][x] entry_order = config_extractor(config, "order", default_value=None) return ( entry_order is None, sv(entry_order), sv(extractor(config, sort_key)), ) sorted_missing = sorted(missing_in_order, key=key_func) else: def key_func(x): config = templates[t]["entries"][x] entry_order = config_extractor(config, "order", default_value=None) return entry_order is None, sv(entry_order) sorted_missing = sorted(missing_in_order, key=key_func) if template_sorting[t]["add"] == "prepend": templates[t]["order"] = sorted_missing + templates[t]["order"] elif template_sorting[t]["add"] == "append": templates[t]["order"] += sorted_missing elif ( template_sorting[t]["add"] == "custom_prepend" and "custom_add_entries" in template_sorting[t] and "custom_add_order" in template_sorting[t] ): templates[t]["entries"].update( template_sorting[t]["custom_add_entries"](sorted_missing) ) templates[t]["order"] = ( template_sorting[t]["custom_add_order"](sorted_missing) + templates[t]["order"] ) elif ( template_sorting[t]["add"] == "custom_append" and "custom_add_entries" in template_sorting[t] and "custom_add_order" in template_sorting[t] ): templates[t]["entries"].update( template_sorting[t]["custom_add_entries"](sorted_missing) ) templates[t]["order"] += template_sorting[t]["custom_add_order"]( sorted_missing ) elif ( template_sorting[t]["add"] == "custom_insert" and "custom_insert_entries" in template_sorting[t] and "custom_insert_order" in template_sorting[t] ): templates[t]["entries"].update( template_sorting[t]["custom_insert_entries"](sorted_missing) ) templates[t]["order"] = template_sorting[t]["custom_insert_order"]( templates[t]["order"], sorted_missing ) _templates[locale] = templates _plugin_names = plugin_names _plugin_vars = plugin_vars return templates, plugin_names, plugin_vars def _process_template_configs(name, implementation, configs, rules): from jinja2.exceptions import TemplateNotFound counters = defaultdict(lambda: 1) includes = defaultdict(list) for config in configs: if not isinstance(config, dict): continue if "type" not in config: continue template_type = config["type"] del config["type"] if template_type not in rules: continue rule = rules[template_type] data = _process_template_config( name, implementation, rule, config=config, counter=counters[template_type] ) if data is None: continue includes[template_type].append(rule["to_entry"](data)) counters[template_type] += 1 for template_type in rules: if len(includes[template_type]) == 0: # if no template of that type was added by the config, we'll try to use the default template name rule = rules[template_type] data = _process_template_config(name, implementation, rule) if data is not None: try: app.jinja_env.get_or_select_template(data["template"]) except TemplateNotFound: pass except Exception: _logger.exception( "Error in template {}, not going to include it".format( data["template"] ) ) else: includes[template_type].append(rule["to_entry"](data)) return includes def _process_template_config(name, implementation, rule, config=None, counter=1): if "mandatory" in rule: for mandatory in rule["mandatory"]: if mandatory not in config: return None if config is None: config = {} data = dict(config) if "suffix" not in data and counter > 1: data["suffix"] = "_%d" % counter if "div" in data: data["_div"] = data["div"] elif "div" in rule: data["_div"] = rule["div"](name) if "suffix" in data: data["_div"] = data["_div"] + data["suffix"] if not _valid_div_re.match(data["_div"]): _logger.warning( "Template config {} contains invalid div identifier {}, skipping it".format( name, data["_div"] ) ) return None if data.get("template"): data["template"] = implementation.template_folder_key + "/" + data["template"] else: data["template"] = ( implementation.template_folder_key + "/" + rule["template"](name) ) if data.get("template_header"): data["template_header"] = ( implementation.template_folder_key + "/" + data["template_header"] ) if "name" not in data: data["name"] = implementation._plugin_name if "custom_bindings" not in data or data["custom_bindings"]: data_bind = "allowBindings: true" if "data_bind" in data: data_bind = data_bind + ", " + data["data_bind"] data_bind = data_bind.replace('"', '\\"') data["data_bind"] = data_bind data["_key"] = "plugin_" + name if "suffix" in data: data["_key"] += data["suffix"] data["_plugin"] = name return data def _filter_templates(templates, template_filter): filtered_templates = {} for template_type, template_collection in templates.items(): filtered_entries = {} for template_key, template_entry in template_collection["entries"].items(): if template_filter(template_type, template_key): filtered_entries[template_key] = template_entry filtered_templates[template_type] = { "order": list( filter(lambda x: x in filtered_entries, template_collection["order"]) ), "entries": filtered_entries, } return filtered_templates @app.route("/robots.txt") def robotsTxt(): return send_from_directory(app.static_folder, "robots.txt") @app.route("/i18n/<string:locale>/<string:domain>.js") @util.flask.conditional(lambda: _check_etag_and_lastmodified_for_i18n(), NOT_MODIFIED) @util.flask.etagged( lambda _: _compute_etag_for_i18n( request.view_args["locale"], request.view_args["domain"] ) ) @util.flask.lastmodified( lambda _: _compute_date_for_i18n( request.view_args["locale"], request.view_args["domain"] ) ) def localeJs(locale, domain): messages = {} plural_expr = None if locale != "en": messages, plural_expr = _get_translations(locale, domain) catalog = { "messages": messages, "plural_expr": plural_expr, "locale": locale, "domain": domain, } from flask import Response return Response( render_template("i18n.js.jinja2", catalog=catalog), content_type="application/x-javascript; charset=utf-8", ) @app.route("/plugin_assets/<string:name>/<path:filename>") def plugin_assets(name, filename): return redirect(url_for("plugin." + name + ".static", filename=filename)) def _compute_etag_for_i18n(locale, domain, files=None, lastmodified=None): if files is None: files = _get_all_translationfiles(locale, domain) if lastmodified is None: lastmodified = _compute_date(files) if lastmodified and not isinstance(lastmodified, str): from werkzeug.http import http_date lastmodified = http_date(lastmodified) import hashlib hash = hashlib.sha1() def hash_update(value): hash.update(value.encode("utf-8")) hash_update(",".join(sorted(files))) if lastmodified: hash_update(lastmodified) return hash.hexdigest() def _compute_date_for_i18n(locale, domain): return _compute_date(_get_all_translationfiles(locale, domain)) def _compute_date(files): # Note, we do not expect everything in 'files' to exist. import stat from datetime import datetime from octoprint.util.tz import UTC_TZ max_timestamp = 0 for path in files: try: # try to stat file. If an exception is thrown, its because it does not exist. s = os.stat(path) if stat.S_ISREG(s.st_mode) and s.st_mtime > max_timestamp: # is a regular file and has a newer timestamp max_timestamp = s.st_mtime except Exception: # path does not exist. continue if max_timestamp: # we set the micros to 0 since microseconds are not speced for HTTP max_timestamp = ( datetime.fromtimestamp(max_timestamp) .replace(microsecond=0) .replace(tzinfo=UTC_TZ) ) return max_timestamp def _check_etag_and_lastmodified_for_i18n(): locale = request.view_args["locale"] domain = request.view_args["domain"] etag_ok = util.flask.check_etag( _compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]) ) lastmodified = _compute_date_for_i18n(locale, domain) lastmodified_ok = lastmodified is None or util.flask.check_lastmodified(lastmodified) return etag_ok and lastmodified_ok def _get_all_templates(): from octoprint.util.jinja import get_all_template_paths return get_all_template_paths(app.jinja_loader) def _get_all_assets(): from octoprint.util.jinja import get_all_asset_paths return get_all_asset_paths(app.jinja_env.assets_environment, verifyExist=False) def _get_all_translationfiles(locale, domain): from flask import _request_ctx_stack def get_po_path(basedir, locale, domain): return os.path.join(basedir, locale, "LC_MESSAGES", f"{domain}.po") po_files = [] user_base_path = os.path.join( settings().getBaseFolder("translations", check_writable=False) ) user_plugin_path = os.path.join(user_base_path, "_plugins") # plugin translations plugins = octoprint.plugin.plugin_manager().enabled_plugins for name, plugin in plugins.items(): dirs = [ os.path.join(user_plugin_path, name), os.path.join(plugin.location, "translations"), ] for dirname in dirs: po_files.append(get_po_path(dirname, locale, domain)) # core translations ctx = _request_ctx_stack.top base_path = os.path.join(ctx.app.root_path, "translations") dirs = [user_base_path, base_path] for dirname in dirs: po_files.append(get_po_path(dirname, locale, domain)) return po_files def _get_translations(locale, domain): from babel.messages.pofile import read_po from octoprint.util import dict_merge messages = {} plural_expr = None def messages_from_po(path, locale, domain): messages = {} with open(path, encoding="utf-8") as f: catalog = read_po(f, locale=locale, domain=domain) for message in catalog: message_id = message.id if isinstance(message_id, (list, tuple)): message_id = message_id[0] if message.string: messages[message_id] = message.string return messages, catalog.plural_expr po_files = _get_all_translationfiles(locale, domain) for po_file in po_files: if not os.path.exists(po_file): continue po_messages, plural_expr = messages_from_po(po_file, locale, domain) if po_messages is not None: messages = dict_merge(messages, po_messages, in_place=True) return messages, plural_expr
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import base64 import datetime import logging import os import re from collections import defaultdict from urllib.parse import urlparse from flask import ( Response, abort, g, make_response, redirect, render_template, request, send_from_directory, url_for, ) import octoprint.plugin from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.filemanager import full_extension_tree, get_all_extensions from octoprint.server import ( # noqa: F401 BRANCH, DISPLAY_VERSION, LOCALES, NOT_MODIFIED, VERSION, app, debug, gettext, groupManager, pluginManager, preemptiveCache, userManager, ) from octoprint.server.util import has_permissions, require_login_with from octoprint.settings import settings from octoprint.util import sv, to_bytes, to_unicode from octoprint.util.version import get_python_version_string from . import util _logger = logging.getLogger(__name__) _templates = {} _plugin_names = None _plugin_vars = None _valid_id_re = re.compile("[a-z_]+") _valid_div_re = re.compile("[a-zA-Z_-]+") def _preemptive_unless(base_url=None, additional_unless=None): if base_url is None: base_url = request.url_root disabled_for_root = ( not settings().getBoolean(["devel", "cache", "preemptive"]) or base_url in settings().get(["server", "preemptiveCache", "exceptions"]) or not (base_url.startswith("http://") or base_url.startswith("https://")) ) recording_disabled = request.headers.get("X-Preemptive-Recording", "no") == "yes" if callable(additional_unless): return recording_disabled or disabled_for_root or additional_unless() else: return recording_disabled or disabled_for_root def _preemptive_data( key, path=None, base_url=None, data=None, additional_request_data=None ): if path is None: path = request.path if base_url is None: base_url = request.url_root d = { "path": path, "base_url": base_url, "query_string": "l10n={}".format(g.locale.language if g.locale else "en"), } if key != "_default": d["plugin"] = key # add data if we have any if data is not None: try: if callable(data): data = data() if data: if "query_string" in data: data["query_string"] = "l10n={}&{}".format( g.locale.language, data["query_string"] ) d.update(data) except Exception: _logger.exception( f"Error collecting data for preemptive cache from plugin {key}" ) # add additional request data if we have any if callable(additional_request_data): try: ard = additional_request_data() if ard: d.update({"_additional_request_data": ard}) except Exception: _logger.exception( "Error retrieving additional data for preemptive cache from plugin {}".format( key ) ) return d def _cache_key(ui, url=None, locale=None, additional_key_data=None): if url is None: url = request.base_url if locale is None: locale = g.locale.language if g.locale else "en" k = f"ui:{ui}:{url}:{locale}" if callable(additional_key_data): try: ak = additional_key_data() if ak: # we have some additional key components, let's attach them if not isinstance(ak, (list, tuple)): ak = [ak] k = "{}:{}".format(k, ":".join(ak)) except Exception: _logger.exception( "Error while trying to retrieve additional cache key parts for ui {}".format( ui ) ) return k def _valid_status_for_cache(status_code): return 200 <= status_code < 400 def _add_additional_assets(hook): result = [] for name, hook in pluginManager.get_hooks(hook).items(): try: assets = hook() if isinstance(assets, (tuple, list)): result += assets except Exception: _logger.exception( f"Error fetching theming CSS to include from plugin {name}", extra={"plugin": name}, ) return result @app.route("/login") @app.route("/login/") def login(): from flask_login import current_user default_redirect_url = request.script_root + url_for("index") redirect_url = request.args.get("redirect", default_redirect_url) parsed = urlparse(redirect_url) # check if redirect url is valid if parsed.scheme != "" or parsed.netloc != "": _logger.warning( f"Got an invalid redirect URL with the login attempt, misconfiguration or attack attempt: {redirect_url}" ) redirect_url = default_redirect_url permissions = sorted( filter( lambda x: x is not None and isinstance(x, OctoPrintPermission), map( lambda x: getattr(Permissions, x.strip()), request.args.get("permissions", "").split(","), ), ), key=lambda x: x.get_name(), ) if not permissions: permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] user_id = request.args.get("user_id", "") if (not user_id or current_user.get_id() == user_id) and has_permissions( *permissions ): return redirect(redirect_url) render_kwargs = { "theming": [], "redirect_url": redirect_url, "permission_names": map(lambda x: x.get_name(), permissions), "user_id": user_id, "logged_in": not current_user.is_anonymous, } try: additional_assets = _add_additional_assets("octoprint.theming.login") # backwards compatibility to forcelogin & loginui plugins which were replaced by this built-in dialog additional_assets += _add_additional_assets("octoprint.plugin.forcelogin.theming") additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming") render_kwargs.update({"theming": additional_assets}) except Exception: _logger.exception("Error processing theming CSS, ignoring") return render_template("login.jinja2", **render_kwargs) @app.route("/recovery") @app.route("/recovery/") def recovery(): response = require_login_with(permissions=[Permissions.ADMIN]) if response: return response render_kwargs = {"theming": []} try: additional_assets = _add_additional_assets("octoprint.theming.recovery") render_kwargs.update({"theming": additional_assets}) except Exception: _logger.exception("Error processing theming CSS, ignoring") try: from octoprint.plugins.backup import MAX_UPLOAD_SIZE from octoprint.util import get_formatted_size render_kwargs.update( { "plugin_backup_max_upload_size": MAX_UPLOAD_SIZE, "plugin_backup_max_upload_size_str": get_formatted_size(MAX_UPLOAD_SIZE), } ) except Exception: _logger.exception("Error adding backup upload size info, ignoring") return render_template("recovery.jinja2", **render_kwargs) @app.route("/cached.gif") def in_cache(): url = request.base_url.replace("/cached.gif", "/") path = request.path.replace("/cached.gif", "/") base_url = request.url_root # select view from plugins and fall back on default view if no plugin will handle it ui_plugins = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for plugin in ui_plugins: try: if plugin.will_handle_ui(request): ui = plugin._identifier key = _cache_key( plugin._identifier, url=url, additional_key_data=plugin.get_ui_additional_key_data_for_cache, ) unless = _preemptive_unless( url, additional_unless=plugin.get_ui_preemptive_caching_additional_unless, ) data = _preemptive_data( plugin._identifier, path=path, base_url=base_url, data=plugin.get_ui_data_for_preemptive_caching, additional_request_data=plugin.get_ui_additional_request_data_for_preemptive_caching, ) break except Exception: _logger.exception( f"Error while calling plugin {plugin._identifier}, skipping it", extra={"plugin": plugin._identifier}, ) else: ui = "_default" key = _cache_key("_default", url=url) unless = _preemptive_unless(url) data = _preemptive_data("_default", path=path, base_url=base_url) response = make_response( bytes( base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7") ) ) response.headers["Content-Type"] = "image/gif" if unless or not preemptiveCache.has_record(data, root=path): _logger.info( "Preemptive cache not active for path {}, ui {} and data {!r}, signaling as cached".format( path, ui, data ) ) return response elif util.flask.is_in_cache(key): _logger.info(f"Found path {path} in cache (key: {key}), signaling as cached") return response elif util.flask.is_cache_bypassed(key): _logger.info( "Path {} was bypassed from cache (key: {}), signaling as cached".format( path, key ) ) return response else: _logger.debug(f"Path {path} not yet cached (key: {key}), signaling as missing") return abort(404) @app.route("/") def index(): from octoprint.server import connectivityChecker, printer global _templates, _plugin_names, _plugin_vars preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"]) locale = g.locale.language if g.locale else "en" # helper to check if wizards are active def wizard_active(templates): return templates is not None and bool(templates["wizard"]["order"]) # we force a refresh if the client forces one and we are not printing or if we have wizards cached client_refresh = util.flask.cache_check_headers() request_refresh = "_refresh" in request.values printing = printer.is_printing() if client_refresh and printing: logging.getLogger(__name__).warning( "Client requested cache refresh via cache-control headers but we are printing. " "Not invalidating caches due to resource limitation. Append ?_refresh=true to " "the URL if you absolutely require a refresh now" ) client_refresh = client_refresh and not printing force_refresh = ( client_refresh or request_refresh or wizard_active(_templates.get(locale)) ) # if we need to refresh our template cache or it's not yet set, process it fetch_template_data(refresh=force_refresh) now = datetime.datetime.utcnow() enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"]) enable_loading_animation = settings().getBoolean(["devel", "showLoadingAnimation"]) enable_sd_support = settings().get(["feature", "sdSupport"]) enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"]) and bool( settings().get(["webcam", "stream"]) ) enable_temperature_graph = settings().get(["feature", "temperatureGraph"]) sockjs_connect_timeout = settings().getInt(["devel", "sockJsConnectTimeout"]) def default_template_filter(template_type, template_key): if template_type == "tab": return template_key != "timelapse" or enable_timelapse else: return True default_additional_etag = [ enable_timelapse, enable_loading_animation, enable_sd_support, enable_webcam, enable_temperature_graph, sockjs_connect_timeout, connectivityChecker.online, wizard_active(_templates.get(locale)), ] + sorted( "{}:{}".format(to_unicode(k, errors="replace"), to_unicode(v, errors="replace")) for k, v in _plugin_vars.items() ) def get_preemptively_cached_view( key, view, data=None, additional_request_data=None, additional_unless=None ): if (data is None and additional_request_data is None) or g.locale is None: return view d = _preemptive_data( key, data=data, additional_request_data=additional_request_data ) def unless(): return _preemptive_unless( base_url=request.url_root, additional_unless=additional_unless ) # finally decorate our view return util.flask.preemptively_cached( cache=preemptiveCache, data=d, unless=unless )(view) def get_cached_view( key, view, additional_key_data=None, additional_files=None, additional_etag=None, custom_files=None, custom_etag=None, custom_lastmodified=None, ): if additional_etag is None: additional_etag = [] def cache_key(): return _cache_key(key, additional_key_data=additional_key_data) def collect_files(): if callable(custom_files): try: files = custom_files() if files: return files except Exception: _logger.exception( "Error while trying to retrieve tracked files for plugin {}".format( key ) ) files = _get_all_templates() files += _get_all_assets() files += _get_all_translationfiles( g.locale.language if g.locale else "en", "messages" ) if callable(additional_files): try: af = additional_files() if af: files += af except Exception: _logger.exception( "Error while trying to retrieve additional tracked files for plugin {}".format( key ) ) return sorted(set(files)) def compute_lastmodified(files): if callable(custom_lastmodified): try: lastmodified = custom_lastmodified() if lastmodified: return lastmodified except Exception: _logger.exception( "Error while trying to retrieve custom LastModified value for plugin {}".format( key ) ) return _compute_date(files) def compute_etag(files, lastmodified, additional=None): if callable(custom_etag): try: etag = custom_etag() if etag: return etag except Exception: _logger.exception( "Error while trying to retrieve custom ETag value for plugin {}".format( key ) ) if lastmodified and not isinstance(lastmodified, str): from werkzeug.http import http_date lastmodified = http_date(lastmodified) if additional is None: additional = [] import hashlib hash = hashlib.sha1() def hash_update(value): hash.update(to_bytes(value, encoding="utf-8", errors="replace")) hash_update(octoprint.__version__) hash_update(get_python_version_string()) hash_update(",".join(sorted(files))) if lastmodified: hash_update(lastmodified) for add in additional: hash_update(add) return hash.hexdigest() current_files = collect_files() current_lastmodified = compute_lastmodified(current_files) current_etag = compute_etag( files=current_files, lastmodified=current_lastmodified, additional=[cache_key()] + additional_etag, ) def check_etag_and_lastmodified(): lastmodified_ok = util.flask.check_lastmodified(current_lastmodified) etag_ok = util.flask.check_etag(current_etag) return lastmodified_ok and etag_ok def validate_cache(cached): return force_refresh or (current_etag != cached.get_etag()[0]) decorated_view = view decorated_view = util.flask.lastmodified(lambda _: current_lastmodified)( decorated_view ) decorated_view = util.flask.etagged(lambda _: current_etag)(decorated_view) decorated_view = util.flask.cached( timeout=-1, refreshif=validate_cache, key=cache_key, unless_response=lambda response: util.flask.cache_check_response_headers( response ) or util.flask.cache_check_status_code(response, _valid_status_for_cache), )(decorated_view) decorated_view = util.flask.with_client_revalidation(decorated_view) decorated_view = util.flask.conditional( check_etag_and_lastmodified, NOT_MODIFIED )(decorated_view) return decorated_view def plugin_view(p): cached = get_cached_view( p._identifier, p.on_ui_render, additional_key_data=p.get_ui_additional_key_data_for_cache, additional_files=p.get_ui_additional_tracked_files, custom_files=p.get_ui_custom_tracked_files, custom_etag=p.get_ui_custom_etag, custom_lastmodified=p.get_ui_custom_lastmodified, additional_etag=p.get_ui_additional_etag(default_additional_etag), ) if preemptive_cache_enabled and p.get_ui_preemptive_caching_enabled(): view = get_preemptively_cached_view( p._identifier, cached, p.get_ui_data_for_preemptive_caching, p.get_ui_additional_request_data_for_preemptive_caching, p.get_ui_preemptive_caching_additional_unless, ) else: view = cached template_filter = p.get_ui_custom_template_filter(default_template_filter) if template_filter is not None and callable(template_filter): filtered_templates = _filter_templates(_templates[locale], template_filter) else: filtered_templates = _templates[locale] render_kwargs = _get_render_kwargs( filtered_templates, _plugin_names, _plugin_vars, now ) return view(now, request, render_kwargs) def default_view(): filtered_templates = _filter_templates( _templates[locale], default_template_filter ) wizard = wizard_active(filtered_templates) accesscontrol_active = userManager.has_been_customized() render_kwargs = _get_render_kwargs( filtered_templates, _plugin_names, _plugin_vars, now ) render_kwargs.update( { "enableWebcam": enable_webcam, "enableTemperatureGraph": enable_temperature_graph, "enableAccessControl": True, "accessControlActive": accesscontrol_active, "enableLoadingAnimation": enable_loading_animation, "enableSdSupport": enable_sd_support, "sockJsConnectTimeout": sockjs_connect_timeout * 1000, "wizard": wizard, "online": connectivityChecker.online, "now": now, } ) # no plugin took an interest, we'll use the default UI def make_default_ui(): r = make_response(render_template("index.jinja2", **render_kwargs)) if wizard: # if we have active wizard dialogs, set non caching headers r = util.flask.add_non_caching_response_headers(r) return r cached = get_cached_view( "_default", make_default_ui, additional_etag=default_additional_etag ) preemptively_cached = get_preemptively_cached_view("_default", cached, {}, {}) return preemptively_cached() default_permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] response = None forced_view = request.headers.get("X-Force-View", None) if forced_view: # we have view forced by the preemptive cache _logger.debug(f"Forcing rendering of view {forced_view}") if forced_view != "_default": plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True) if plugin is not None and isinstance( plugin.implementation, octoprint.plugin.UiPlugin ): permissions = plugin.implementation.get_ui_permissions() response = require_login_with(permissions=permissions) if not response: response = plugin_view(plugin.implementation) if _logger.isEnabledFor(logging.DEBUG) and isinstance( response, Response ): response.headers[ "X-Ui-Plugin" ] = plugin.implementation._identifier else: response = require_login_with(permissions=default_permissions) if not response: response = default_view() if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): response.headers["X-Ui-Plugin"] = "_default" else: # select view from plugins and fall back on default view if no plugin will handle it ui_plugins = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for plugin in ui_plugins: try: if plugin.will_handle_ui(request): # plugin claims responsibility, let it render the UI permissions = plugin.get_ui_permissions() response = require_login_with(permissions=permissions) if not response: response = plugin_view(plugin) if response is not None: if _logger.isEnabledFor(logging.DEBUG) and isinstance( response, Response ): response.headers["X-Ui-Plugin"] = plugin._identifier break else: _logger.warning( "UiPlugin {} returned an empty response".format( plugin._identifier ) ) except Exception: _logger.exception( "Error while calling plugin {}, skipping it".format( plugin._identifier ), extra={"plugin": plugin._identifier}, ) else: response = require_login_with(permissions=default_permissions) if not response: response = default_view() if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response): response.headers["X-Ui-Plugin"] = "_default" if response is None: return abort(404) return response def _get_render_kwargs(templates, plugin_names, plugin_vars, now): global _logger # ~~ a bunch of settings first_run = settings().getBoolean(["server", "firstRun"]) locales = {} for loc in LOCALES: try: locales[loc.language] = { "language": loc.language, "display": loc.display_name, "english": loc.english_name, } except Exception: _logger.exception("Error while collecting available locales") permissions = [permission.as_dict() for permission in Permissions.all()] filetypes = list(sorted(full_extension_tree().keys())) extensions = list(map(lambda ext: f".{ext}", get_all_extensions())) # ~~ prepare full set of template vars for rendering render_kwargs = { "debug": debug, "firstRun": first_run, "version": {"number": VERSION, "display": DISPLAY_VERSION, "branch": BRANCH}, "python_version": get_python_version_string(), "templates": templates, "pluginNames": plugin_names, "locales": locales, "permissions": permissions, "supportedFiletypes": filetypes, "supportedExtensions": extensions, } render_kwargs.update(plugin_vars) return render_kwargs def fetch_template_data(refresh=False): global _templates, _plugin_names, _plugin_vars locale = g.locale.language if g.locale else "en" if ( not refresh and _templates.get(locale) is not None and _plugin_names is not None and _plugin_vars is not None ): return _templates[locale], _plugin_names, _plugin_vars first_run = settings().getBoolean(["server", "firstRun"]) ##~~ prepare templates templates = defaultdict(lambda: {"order": [], "entries": {}}) # rules for transforming template configs to template entries template_rules = { "navbar": { "div": lambda x: "navbar_plugin_" + x, "template": lambda x: x + "_navbar.jinja2", "to_entry": lambda data: data, }, "sidebar": { "div": lambda x: "sidebar_plugin_" + x, "template": lambda x: x + "_sidebar.jinja2", "to_entry": lambda data: (data["name"], data), }, "tab": { "div": lambda x: "tab_plugin_" + x, "template": lambda x: x + "_tab.jinja2", "to_entry": lambda data: (data["name"], data), }, "settings": { "div": lambda x: "settings_plugin_" + x, "template": lambda x: x + "_settings.jinja2", "to_entry": lambda data: (data["name"], data), }, "usersettings": { "div": lambda x: "usersettings_plugin_" + x, "template": lambda x: x + "_usersettings.jinja2", "to_entry": lambda data: (data["name"], data), }, "wizard": { "div": lambda x: "wizard_plugin_" + x, "template": lambda x: x + "_wizard.jinja2", "to_entry": lambda data: (data["name"], data), }, "about": { "div": lambda x: "about_plugin_" + x, "template": lambda x: x + "_about.jinja2", "to_entry": lambda data: (data["name"], data), }, "generic": {"template": lambda x: x + ".jinja2", "to_entry": lambda data: data}, } # sorting orders def wizard_key_extractor(d, k): if d[1].get("_key", None) == "plugin_corewizard_acl": # Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and # that require to access APIs to function will run into errors since those APIs won't work before ACL # has been configured. See also #2140 return f"0:{to_unicode(d[0])}" elif d[1].get("mandatory", False): # Other mandatory steps come before the optional ones return f"1:{to_unicode(d[0])}" else: # Finally everything else return f"2:{to_unicode(d[0])}" template_sorting = { "navbar": {"add": "prepend", "key": None}, "sidebar": {"add": "append", "key": "name"}, "tab": {"add": "append", "key": "name"}, "settings": { "add": "custom_append", "key": "name", "custom_add_entries": lambda missing: { "section_plugins": (gettext("Plugins"), None) }, "custom_add_order": lambda missing: ["section_plugins"] + missing, }, "usersettings": {"add": "append", "key": "name"}, "wizard": {"add": "append", "key": "name", "key_extractor": wizard_key_extractor}, "about": {"add": "append", "key": "name"}, "generic": {"add": "append", "key": None}, } hooks = pluginManager.get_hooks("octoprint.ui.web.templatetypes") for name, hook in hooks.items(): try: result = hook(dict(template_sorting), dict(template_rules)) except Exception: _logger.exception( f"Error while retrieving custom template type " f"definitions from plugin {name}", extra={"plugin": name}, ) else: if not isinstance(result, list): continue for entry in result: if not isinstance(entry, tuple) or not len(entry) == 3: continue key, order, rule = entry # order defaults if "add" not in order: order["add"] = "prepend" if "key" not in order: order["key"] = "name" # rule defaults if "div" not in rule: # default div name: <hook plugin>_<template_key>_plugin_<plugin> div = f"{name}_{key}_plugin_" rule["div"] = lambda x: div + x if "template" not in rule: # default template name: <plugin>_plugin_<hook plugin>_<template key>.jinja2 template = f"_plugin_{name}_{key}.jinja2" rule["template"] = lambda x: x + template if "to_entry" not in rule: # default to_entry assumes existing "name" property to be used as label for 2-tuple entry data structure (<name>, <properties>) rule["to_entry"] = lambda data: (data["name"], data) template_rules["plugin_" + name + "_" + key] = rule template_sorting["plugin_" + name + "_" + key] = order template_types = list(template_rules.keys()) # navbar templates["navbar"]["entries"] = { "offlineindicator": { "template": "navbar/offlineindicator.jinja2", "_div": "navbar_offlineindicator", "custom_bindings": False, }, "settings": { "template": "navbar/settings.jinja2", "_div": "navbar_settings", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SETTINGS)", }, "systemmenu": { "template": "navbar/systemmenu.jinja2", "_div": "navbar_systemmenu", "classes": ["dropdown"], "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", "custom_bindings": False, }, "login": { "template": "navbar/login.jinja2", "_div": "navbar_login", "classes": ["dropdown"], "custom_bindings": False, }, } # sidebar templates["sidebar"]["entries"] = { "connection": ( gettext("Connection"), { "template": "sidebar/connection.jinja2", "_div": "connection", "icon": "signal", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.CONNECTION)", "template_header": "sidebar/connection_header.jinja2", }, ), "state": ( gettext("State"), { "template": "sidebar/state.jinja2", "_div": "state", "icon": "info-circle", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.STATUS)", }, ), "files": ( gettext("Files"), { "template": "sidebar/files.jinja2", "_div": "files", "icon": "list", "classes_content": ["overflow_visible"], "template_header": "sidebar/files_header.jinja2", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.FILES_LIST)", }, ), } # tabs templates["tab"]["entries"] = { "temperature": ( gettext("Temperature"), { "template": "tabs/temperature.jinja2", "_div": "temp", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)() && visible()", }, ), "control": ( gettext("Control"), { "template": "tabs/control.jinja2", "_div": "control", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.WEBCAM, access.permissions.CONTROL)", }, ), "terminal": ( gettext("Terminal"), { "template": "tabs/terminal.jinja2", "_div": "term", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.MONITOR_TERMINAL)", }, ), "timelapse": ( gettext("Timelapse"), { "template": "tabs/timelapse.jinja2", "_div": "timelapse", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.TIMELAPSE_LIST)", }, ), } # settings dialog templates["settings"]["entries"] = { "section_printer": (gettext("Printer"), None), "serial": ( gettext("Serial Connection"), { "template": "dialogs/settings/serialconnection.jinja2", "_div": "settings_serialConnection", "custom_bindings": False, }, ), "printerprofiles": ( gettext("Printer Profiles"), { "template": "dialogs/settings/printerprofiles.jinja2", "_div": "settings_printerProfiles", "custom_bindings": False, }, ), "temperatures": ( gettext("Temperatures"), { "template": "dialogs/settings/temperatures.jinja2", "_div": "settings_temperature", "custom_bindings": False, }, ), "terminalfilters": ( gettext("Terminal Filters"), { "template": "dialogs/settings/terminalfilters.jinja2", "_div": "settings_terminalFilters", "custom_bindings": False, }, ), "gcodescripts": ( gettext("GCODE Scripts"), { "template": "dialogs/settings/gcodescripts.jinja2", "_div": "settings_gcodeScripts", "custom_bindings": False, }, ), "section_features": (gettext("Features"), None), "features": ( gettext("Features"), { "template": "dialogs/settings/features.jinja2", "_div": "settings_features", "custom_bindings": False, }, ), "webcam": ( gettext("Webcam & Timelapse"), { "template": "dialogs/settings/webcam.jinja2", "_div": "settings_webcam", "custom_bindings": False, }, ), "api": ( gettext("API"), { "template": "dialogs/settings/api.jinja2", "_div": "settings_api", "custom_bindings": False, }, ), "section_octoprint": (gettext("OctoPrint"), None), "accesscontrol": ( gettext("Access Control"), { "template": "dialogs/settings/accesscontrol.jinja2", "_div": "settings_users", "custom_bindings": False, }, ), "folders": ( gettext("Folders"), { "template": "dialogs/settings/folders.jinja2", "_div": "settings_folders", "custom_bindings": False, }, ), "appearance": ( gettext("Appearance"), { "template": "dialogs/settings/appearance.jinja2", "_div": "settings_appearance", "custom_bindings": False, }, ), "server": ( gettext("Server"), { "template": "dialogs/settings/server.jinja2", "_div": "settings_server", "custom_bindings": False, }, ), } # user settings dialog templates["usersettings"]["entries"] = { "access": ( gettext("Access"), { "template": "dialogs/usersettings/access.jinja2", "_div": "usersettings_access", "custom_bindings": False, }, ), "interface": ( gettext("Interface"), { "template": "dialogs/usersettings/interface.jinja2", "_div": "usersettings_interface", "custom_bindings": False, }, ), } # wizard if first_run: def custom_insert_order(existing, missing): if "firstrunstart" in missing: missing.remove("firstrunstart") if "firstrunend" in missing: missing.remove("firstrunend") return ["firstrunstart"] + existing + missing + ["firstrunend"] template_sorting["wizard"].update( { "add": "custom_insert", "custom_insert_entries": lambda missing: {}, "custom_insert_order": custom_insert_order, } ) templates["wizard"]["entries"] = { "firstrunstart": ( gettext("Start"), { "template": "dialogs/wizard/firstrun_start.jinja2", "_div": "wizard_firstrun_start", }, ), "firstrunend": ( gettext("Finish"), { "template": "dialogs/wizard/firstrun_end.jinja2", "_div": "wizard_firstrun_end", }, ), } # about dialog templates["about"]["entries"] = { "about": ( "About OctoPrint", { "template": "dialogs/about/about.jinja2", "_div": "about_about", "custom_bindings": False, }, ), "license": ( "OctoPrint License", { "template": "dialogs/about/license.jinja2", "_div": "about_license", "custom_bindings": False, }, ), "thirdparty": ( "Third Party Licenses", { "template": "dialogs/about/thirdparty.jinja2", "_div": "about_thirdparty", "custom_bindings": False, }, ), "authors": ( "Authors", { "template": "dialogs/about/authors.jinja2", "_div": "about_authors", "custom_bindings": False, }, ), "supporters": ( "Supporters", { "template": "dialogs/about/supporters.jinja2", "_div": "about_sponsors", "custom_bindings": False, }, ), "systeminfo": ( "System Information", { "template": "dialogs/about/systeminfo.jinja2", "_div": "about_systeminfo", "custom_bindings": False, "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", }, ), } # extract data from template plugins template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin) plugin_vars = {} plugin_names = set() plugin_aliases = {} seen_wizards = settings().get(["server", "seenWizards"]) if not first_run else {} for implementation in template_plugins: name = implementation._identifier plugin_names.add(name) wizard_required = False wizard_ignored = False try: vars = implementation.get_template_vars() configs = implementation.get_template_configs() if isinstance(implementation, octoprint.plugin.WizardPlugin): wizard_required = implementation.is_wizard_required() wizard_ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored( seen_wizards, implementation ) except Exception: _logger.exception( "Error while retrieving template data for plugin {}, ignoring it".format( name ), extra={"plugin": name}, ) continue if not isinstance(vars, dict): vars = {} if not isinstance(configs, (list, tuple)): configs = [] for var_name, var_value in vars.items(): plugin_vars["plugin_" + name + "_" + var_name] = var_value try: includes = _process_template_configs( name, implementation, configs, template_rules ) except Exception: _logger.exception( "Error while processing template configs for plugin {}, ignoring it".format( name ), extra={"plugin": name}, ) if not wizard_required or wizard_ignored: includes["wizard"] = list() for t in template_types: plugin_aliases[t] = {} for include in includes[t]: if t == "navbar" or t == "generic": data = include else: data = include[1] key = data["_key"] if "replaces" in data: key = data["replaces"] plugin_aliases[t][data["_key"]] = data["replaces"] templates[t]["entries"][key] = include # ~~ order internal templates and plugins # make sure that # 1) we only have keys in our ordered list that we have entries for and # 2) we have all entries located somewhere within the order for t in template_types: default_order = ( settings().get( ["appearance", "components", "order", t], merged=True, config={} ) or [] ) configured_order = ( settings().get(["appearance", "components", "order", t], merged=True) or [] ) configured_disabled = ( settings().get(["appearance", "components", "disabled", t]) or [] ) # first create the ordered list of all component ids according to the configured order result = [] for x in configured_order: if x in plugin_aliases[t]: x = plugin_aliases[t][x] if ( x in templates[t]["entries"] and x not in configured_disabled and x not in result ): result.append(x) templates[t]["order"] = result # now append the entries from the default order that are not already in there templates[t]["order"] += [ x for x in default_order if x not in templates[t]["order"] and x in templates[t]["entries"] and x not in configured_disabled ] all_ordered = set(templates[t]["order"]) all_disabled = set(configured_disabled) # check if anything is missing, if not we are done here missing_in_order = ( set(templates[t]["entries"].keys()) .difference(all_ordered) .difference(all_disabled) ) if len(missing_in_order) == 0: continue # works with entries that are dicts and entries that are 2-tuples with the # entry data at index 1 def config_extractor(item, key, default_value=None): if isinstance(item, dict) and key in item: return item[key] if key in item else default_value elif ( isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1] ): return item[1][key] if key in item[1] else default_value return default_value # finally add anything that's not included in our order yet if template_sorting[t]["key"] is not None: # we'll use our config extractor as default key extractor extractor = config_extractor # if template type provides custom extractor, make sure its exceptions are handled if "key_extractor" in template_sorting[t] and callable( template_sorting[t]["key_extractor"] ): def create_safe_extractor(extractor): def f(x, k): try: return extractor(x, k) except Exception: _logger.exception( "Error while extracting sorting keys for template {}".format( t ) ) return None return f extractor = create_safe_extractor(template_sorting[t]["key_extractor"]) sort_key = template_sorting[t]["key"] def key_func(x): config = templates[t]["entries"][x] entry_order = config_extractor(config, "order", default_value=None) return ( entry_order is None, sv(entry_order), sv(extractor(config, sort_key)), ) sorted_missing = sorted(missing_in_order, key=key_func) else: def key_func(x): config = templates[t]["entries"][x] entry_order = config_extractor(config, "order", default_value=None) return entry_order is None, sv(entry_order) sorted_missing = sorted(missing_in_order, key=key_func) if template_sorting[t]["add"] == "prepend": templates[t]["order"] = sorted_missing + templates[t]["order"] elif template_sorting[t]["add"] == "append": templates[t]["order"] += sorted_missing elif ( template_sorting[t]["add"] == "custom_prepend" and "custom_add_entries" in template_sorting[t] and "custom_add_order" in template_sorting[t] ): templates[t]["entries"].update( template_sorting[t]["custom_add_entries"](sorted_missing) ) templates[t]["order"] = ( template_sorting[t]["custom_add_order"](sorted_missing) + templates[t]["order"] ) elif ( template_sorting[t]["add"] == "custom_append" and "custom_add_entries" in template_sorting[t] and "custom_add_order" in template_sorting[t] ): templates[t]["entries"].update( template_sorting[t]["custom_add_entries"](sorted_missing) ) templates[t]["order"] += template_sorting[t]["custom_add_order"]( sorted_missing ) elif ( template_sorting[t]["add"] == "custom_insert" and "custom_insert_entries" in template_sorting[t] and "custom_insert_order" in template_sorting[t] ): templates[t]["entries"].update( template_sorting[t]["custom_insert_entries"](sorted_missing) ) templates[t]["order"] = template_sorting[t]["custom_insert_order"]( templates[t]["order"], sorted_missing ) _templates[locale] = templates _plugin_names = plugin_names _plugin_vars = plugin_vars return templates, plugin_names, plugin_vars def _process_template_configs(name, implementation, configs, rules): from jinja2.exceptions import TemplateNotFound counters = defaultdict(lambda: 1) includes = defaultdict(list) for config in configs: if not isinstance(config, dict): continue if "type" not in config: continue template_type = config["type"] del config["type"] if template_type not in rules: continue rule = rules[template_type] data = _process_template_config( name, implementation, rule, config=config, counter=counters[template_type] ) if data is None: continue includes[template_type].append(rule["to_entry"](data)) counters[template_type] += 1 for template_type in rules: if len(includes[template_type]) == 0: # if no template of that type was added by the config, we'll try to use the default template name rule = rules[template_type] data = _process_template_config(name, implementation, rule) if data is not None: try: app.jinja_env.get_or_select_template(data["template"]) except TemplateNotFound: pass except Exception: _logger.exception( "Error in template {}, not going to include it".format( data["template"] ) ) else: includes[template_type].append(rule["to_entry"](data)) return includes def _process_template_config(name, implementation, rule, config=None, counter=1): if "mandatory" in rule: for mandatory in rule["mandatory"]: if mandatory not in config: return None if config is None: config = {} data = dict(config) if "suffix" not in data and counter > 1: data["suffix"] = "_%d" % counter if "div" in data: data["_div"] = data["div"] elif "div" in rule: data["_div"] = rule["div"](name) if "suffix" in data: data["_div"] = data["_div"] + data["suffix"] if not _valid_div_re.match(data["_div"]): _logger.warning( "Template config {} contains invalid div identifier {}, skipping it".format( name, data["_div"] ) ) return None if data.get("template"): data["template"] = implementation.template_folder_key + "/" + data["template"] else: data["template"] = ( implementation.template_folder_key + "/" + rule["template"](name) ) if data.get("template_header"): data["template_header"] = ( implementation.template_folder_key + "/" + data["template_header"] ) if "name" not in data: data["name"] = implementation._plugin_name if "custom_bindings" not in data or data["custom_bindings"]: data_bind = "allowBindings: true" if "data_bind" in data: data_bind = data_bind + ", " + data["data_bind"] data_bind = data_bind.replace('"', '\\"') data["data_bind"] = data_bind data["_key"] = "plugin_" + name if "suffix" in data: data["_key"] += data["suffix"] data["_plugin"] = name return data def _filter_templates(templates, template_filter): filtered_templates = {} for template_type, template_collection in templates.items(): filtered_entries = {} for template_key, template_entry in template_collection["entries"].items(): if template_filter(template_type, template_key): filtered_entries[template_key] = template_entry filtered_templates[template_type] = { "order": list( filter(lambda x: x in filtered_entries, template_collection["order"]) ), "entries": filtered_entries, } return filtered_templates @app.route("/robots.txt") def robotsTxt(): return send_from_directory(app.static_folder, "robots.txt") @app.route("/i18n/<string:locale>/<string:domain>.js") @util.flask.conditional(lambda: _check_etag_and_lastmodified_for_i18n(), NOT_MODIFIED) @util.flask.etagged( lambda _: _compute_etag_for_i18n( request.view_args["locale"], request.view_args["domain"] ) ) @util.flask.lastmodified( lambda _: _compute_date_for_i18n( request.view_args["locale"], request.view_args["domain"] ) ) def localeJs(locale, domain): messages = {} plural_expr = None if locale != "en": messages, plural_expr = _get_translations(locale, domain) catalog = { "messages": messages, "plural_expr": plural_expr, "locale": locale, "domain": domain, } from flask import Response return Response( render_template("i18n.js.jinja2", catalog=catalog), content_type="application/x-javascript; charset=utf-8", ) @app.route("/plugin_assets/<string:name>/<path:filename>") def plugin_assets(name, filename): return redirect(url_for("plugin." + name + ".static", filename=filename)) def _compute_etag_for_i18n(locale, domain, files=None, lastmodified=None): if files is None: files = _get_all_translationfiles(locale, domain) if lastmodified is None: lastmodified = _compute_date(files) if lastmodified and not isinstance(lastmodified, str): from werkzeug.http import http_date lastmodified = http_date(lastmodified) import hashlib hash = hashlib.sha1() def hash_update(value): hash.update(value.encode("utf-8")) hash_update(",".join(sorted(files))) if lastmodified: hash_update(lastmodified) return hash.hexdigest() def _compute_date_for_i18n(locale, domain): return _compute_date(_get_all_translationfiles(locale, domain)) def _compute_date(files): # Note, we do not expect everything in 'files' to exist. import stat from datetime import datetime from octoprint.util.tz import UTC_TZ max_timestamp = 0 for path in files: try: # try to stat file. If an exception is thrown, its because it does not exist. s = os.stat(path) if stat.S_ISREG(s.st_mode) and s.st_mtime > max_timestamp: # is a regular file and has a newer timestamp max_timestamp = s.st_mtime except Exception: # path does not exist. continue if max_timestamp: # we set the micros to 0 since microseconds are not speced for HTTP max_timestamp = ( datetime.fromtimestamp(max_timestamp) .replace(microsecond=0) .replace(tzinfo=UTC_TZ) ) return max_timestamp def _check_etag_and_lastmodified_for_i18n(): locale = request.view_args["locale"] domain = request.view_args["domain"] etag_ok = util.flask.check_etag( _compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]) ) lastmodified = _compute_date_for_i18n(locale, domain) lastmodified_ok = lastmodified is None or util.flask.check_lastmodified(lastmodified) return etag_ok and lastmodified_ok def _get_all_templates(): from octoprint.util.jinja import get_all_template_paths return get_all_template_paths(app.jinja_loader) def _get_all_assets(): from octoprint.util.jinja import get_all_asset_paths return get_all_asset_paths(app.jinja_env.assets_environment, verifyExist=False) def _get_all_translationfiles(locale, domain): from flask import _request_ctx_stack def get_po_path(basedir, locale, domain): return os.path.join(basedir, locale, "LC_MESSAGES", f"{domain}.po") po_files = [] user_base_path = os.path.join( settings().getBaseFolder("translations", check_writable=False) ) user_plugin_path = os.path.join(user_base_path, "_plugins") # plugin translations plugins = octoprint.plugin.plugin_manager().enabled_plugins for name, plugin in plugins.items(): dirs = [ os.path.join(user_plugin_path, name), os.path.join(plugin.location, "translations"), ] for dirname in dirs: po_files.append(get_po_path(dirname, locale, domain)) # core translations ctx = _request_ctx_stack.top base_path = os.path.join(ctx.app.root_path, "translations") dirs = [user_base_path, base_path] for dirname in dirs: po_files.append(get_po_path(dirname, locale, domain)) return po_files def _get_translations(locale, domain): from babel.messages.pofile import read_po from octoprint.util import dict_merge messages = {} plural_expr = None def messages_from_po(path, locale, domain): messages = {} with open(path, encoding="utf-8") as f: catalog = read_po(f, locale=locale, domain=domain) for message in catalog: message_id = message.id if isinstance(message_id, (list, tuple)): message_id = message_id[0] if message.string: messages[message_id] = message.string return messages, catalog.plural_expr po_files = _get_all_translationfiles(locale, domain) for po_file in po_files: if not os.path.exists(po_file): continue po_messages, plural_expr = messages_from_po(po_file, locale, domain) if po_messages is not None: messages = dict_merge(messages, po_messages, in_place=True) return messages, plural_expr
xss
{ "code": [ " redirect_url = request.args.get(\"redirect\", request.script_root + url_for(\"index\"))" ], "line_no": [ 173 ] }
{ "code": [ " default_redirect_url = request.script_root + url_for(\"index\")", " redirect_url = request.args.get(\"redirect\", default_redirect_url)", " if parsed.scheme != \"\" or parsed.netloc != \"\":", " _logger.warning(", " f\"Got an invalid redirect URL with the login attempt, misconfiguration or attack attempt: {redirect_url}\"", " )", " redirect_url = default_redirect_url" ], "line_no": [ 174, 175, 178, 179, 180, 181, 182 ] }
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import base64 import .datetime import logging import os import .re from collections import .defaultdict from flask import ( Response, abort, g, make_response, redirect, render_template, request, send_from_directory, url_for, ) import octoprint.plugin from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.filemanager import .full_extension_tree, get_all_extensions from octoprint.server import ( # noqa: F401 BRANCH, DISPLAY_VERSION, LOCALES, NOT_MODIFIED, VERSION, app, debug, gettext, groupManager, pluginManager, preemptiveCache, userManager, ) from octoprint.server.util import has_permissions, require_login_with from octoprint.settings import .settings from octoprint.util import .sv, to_bytes, to_unicode from octoprint.util.version import get_python_version_string from . import util VAR_0 = logging.getLogger(__name__) VAR_1 = {} VAR_2 = None VAR_3 = None VAR_4 = re.compile("[a-z_]+") VAR_5 = re.compile("[a-zA-Z_-]+") def FUNC_0(VAR_6=None, VAR_7=None): if VAR_6 is None: VAR_6 = request.url_root VAR_35 = ( not settings().getBoolean(["devel", "cache", "preemptive"]) or VAR_6 in settings().get(["server", "preemptiveCache", "exceptions"]) or not (VAR_6.startswith("http://") or VAR_6.startswith("https://")) ) VAR_36 = request.headers.get("X-Preemptive-Recording", "no") == "yes" if callable(VAR_7): return VAR_36 or VAR_35 or VAR_7() else: return VAR_36 or VAR_35 def FUNC_1( VAR_8, VAR_9=None, VAR_6=None, VAR_10=None, VAR_11=None ): if VAR_9 is None: VAR_9 = request.path if VAR_6 is None: VAR_6 = request.url_root VAR_37 = { "path": VAR_9, "base_url": VAR_6, "query_string": "l10n={}".format(g.locale.language if g.locale else "en"), } if VAR_8 != "_default": VAR_37["plugin"] = VAR_8 if VAR_10 is not None: try: if callable(VAR_10): VAR_10 = VAR_10() if VAR_10: if "query_string" in VAR_10: VAR_10["query_string"] = "l10n={}&{}".format( g.locale.language, VAR_10["query_string"] ) VAR_37.update(VAR_10) except Exception: VAR_0.exception( f"Error collecting VAR_10 for preemptive cache from VAR_130 {VAR_8}" ) if callable(VAR_11): try: VAR_126 = VAR_11() if VAR_126: VAR_37.update({"_additional_request_data": VAR_126}) except Exception: VAR_0.exception( "Error retrieving VAR_101 VAR_10 for preemptive cache from VAR_130 {}".format( VAR_8 ) ) return VAR_37 def FUNC_2(VAR_12, VAR_13=None, VAR_14=None, VAR_15=None): if VAR_13 is None: VAR_13 = request.base_url if VAR_14 is None: VAR_14 = g.locale.language if g.locale else "en" VAR_38 = f"ui:{VAR_12}:{VAR_13}:{VAR_14}" if callable(VAR_15): try: VAR_127 = VAR_15() if VAR_127: if not isinstance(VAR_127, (list, tuple)): VAR_127 = [ak] VAR_38 = "{}:{}".format(VAR_38, ":".join(VAR_127)) except Exception: VAR_0.exception( "Error while trying to retrieve VAR_101 cache VAR_8 parts for VAR_12 {}".format( VAR_12 ) ) return VAR_38 def FUNC_3(VAR_16): return 200 <= VAR_16 < 400 def FUNC_4(VAR_17): VAR_39 = [] for VAR_23, VAR_17 in pluginManager.get_hooks(VAR_17).items(): try: VAR_128 = VAR_17() if isinstance(VAR_128, (tuple, list)): VAR_39 += VAR_128 except Exception: VAR_0.exception( f"Error fetching theming CSS to include from VAR_130 {VAR_23}", extra={"plugin": VAR_23}, ) return VAR_39 @app.route("/login") @app.route("/FUNC_5/") def FUNC_5(): from flask_login import current_user VAR_40 = request.args.get("redirect", request.script_root + url_for("index")) VAR_41 = sorted( filter( lambda VAR_136: VAR_136 is not None and isinstance(VAR_136, OctoPrintPermission), map( lambda VAR_136: getattr(Permissions, VAR_136.strip()), request.args.get("permissions", "").split(","), ), ), VAR_8=lambda VAR_136: x.get_name(), ) if not VAR_41: permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] VAR_42 = request.args.get("user_id", "") if (not VAR_42 or current_user.get_id() == VAR_42) and has_permissions( *VAR_41 ): return redirect(VAR_40) VAR_43 = { "theming": [], "redirect_url": VAR_40, "permission_names": map(lambda VAR_136: x.get_name(), VAR_41), "user_id": VAR_42, "logged_in": not current_user.is_anonymous, } try: VAR_99 = FUNC_4("octoprint.theming.login") VAR_99 += FUNC_4("octoprint.plugin.forcelogin.theming") VAR_99 += FUNC_4("octoprint.plugin.loginui.theming") VAR_43.update({"theming": VAR_99}) except Exception: VAR_0.exception("Error processing theming CSS, ignoring") return render_template("login.jinja2", **VAR_43) @app.route("/recovery") @app.route("/FUNC_6/") def FUNC_6(): VAR_44 = require_login_with(VAR_41=[Permissions.ADMIN]) if VAR_44: return VAR_44 VAR_43 = {"theming": []} try: VAR_99 = FUNC_4("octoprint.theming.recovery") VAR_43.update({"theming": VAR_99}) except Exception: VAR_0.exception("Error processing theming CSS, ignoring") try: from octoprint.plugins.backup import MAX_UPLOAD_SIZE from octoprint.util import get_formatted_size VAR_43.update( { "plugin_backup_max_upload_size": MAX_UPLOAD_SIZE, "plugin_backup_max_upload_size_str": get_formatted_size(MAX_UPLOAD_SIZE), } ) except Exception: VAR_0.exception("Error adding backup upload size info, ignoring") return render_template("recovery.jinja2", **VAR_43) @app.route("/VAR_105.gif") def FUNC_7(): VAR_13 = request.base_url.replace("/VAR_105.gif", "/") VAR_9 = request.path.replace("/VAR_105.gif", "/") VAR_6 = request.url_root VAR_45 = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for VAR_130 in VAR_45: try: if VAR_130.will_handle_ui(request): VAR_12 = VAR_130._identifier VAR_8 = FUNC_2( VAR_130._identifier, VAR_13=url, VAR_15=VAR_130.get_ui_additional_key_data_for_cache, ) VAR_100 = FUNC_0( VAR_13, VAR_7=VAR_130.get_ui_preemptive_caching_additional_unless, ) VAR_10 = FUNC_1( VAR_130._identifier, VAR_9=path, VAR_6=base_url, VAR_10=VAR_130.get_ui_data_for_preemptive_caching, VAR_11=VAR_130.get_ui_additional_request_data_for_preemptive_caching, ) break except Exception: VAR_0.exception( f"Error while calling VAR_130 {plugin._identifier}, skipping it", extra={"plugin": VAR_130._identifier}, ) else: VAR_12 = "_default" VAR_8 = FUNC_2("_default", VAR_13=url) VAR_100 = FUNC_0(VAR_13) VAR_10 = FUNC_1("_default", VAR_9=path, VAR_6=base_url) VAR_44 = make_response( bytes( base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7") ) ) VAR_44.headers["Content-Type"] = "image/gif" if VAR_100 or not preemptiveCache.has_record(VAR_10, root=VAR_9): VAR_0.info( "Preemptive cache not active for VAR_9 {}, VAR_12 {} and VAR_10 {!VAR_129}, signaling as cached".format( VAR_9, VAR_12, VAR_10 ) ) return VAR_44 elif util.flask.is_in_cache(VAR_8): VAR_0.info(f"Found VAR_9 {VAR_9} in cache (VAR_8: {VAR_8}), signaling as cached") return VAR_44 elif util.flask.is_cache_bypassed(VAR_8): VAR_0.info( "Path {} was bypassed from cache (VAR_8: {}), signaling as cached".format( VAR_9, VAR_8 ) ) return VAR_44 else: VAR_0.debug(f"Path {VAR_9} not yet VAR_105 (VAR_8: {VAR_8}), signaling as missing") return abort(404) @app.route("/") def FUNC_8(): from octoprint.server import connectivityChecker, printer global VAR_1, VAR_2, VAR_3 VAR_46 = settings().getBoolean(["devel", "cache", "preemptive"]) VAR_14 = g.locale.language if g.locale else "en" def FUNC_25(VAR_18): return VAR_18 is not None and bool(VAR_18["wizard"]["order"]) VAR_47 = util.flask.cache_check_headers() VAR_48 = "_refresh" in request.values VAR_49 = printer.is_printing() if VAR_47 and VAR_49: logging.getLogger(__name__).warning( "Client requested cache VAR_22 via cache-control headers but we are VAR_49. " "Not invalidating caches due to resource limitation. Append ?_refresh=true to " "the URL if you absolutely require a VAR_22 now" ) VAR_47 = VAR_47 and not VAR_49 VAR_50 = ( VAR_47 or VAR_48 or FUNC_25(VAR_1.get(VAR_14)) ) FUNC_10(VAR_22=VAR_50) VAR_21 = datetime.datetime.utcnow() VAR_51 = settings().getBoolean(["webcam", "timelapseEnabled"]) VAR_52 = settings().getBoolean(["devel", "showLoadingAnimation"]) VAR_53 = settings().get(["feature", "sdSupport"]) VAR_54 = settings().getBoolean(["webcam", "webcamEnabled"]) and bool( settings().get(["webcam", "stream"]) ) VAR_55 = settings().get(["feature", "temperatureGraph"]) VAR_56 = settings().getInt(["devel", "sockJsConnectTimeout"]) def FUNC_26(VAR_57, VAR_58): if VAR_57 == "tab": return VAR_58 != "timelapse" or VAR_51 else: return True VAR_59 = [ VAR_51, VAR_52, VAR_53, VAR_54, VAR_55, VAR_56, connectivityChecker.online, FUNC_25(VAR_1.get(VAR_14)), ] + sorted( "{}:{}".format(to_unicode(VAR_38, errors="replace"), to_unicode(v, errors="replace")) for VAR_38, v in VAR_3.items() ) def FUNC_27( VAR_8, VAR_60, VAR_10=None, VAR_11=None, VAR_7=None ): if (VAR_10 is None and VAR_11 is None) or g.locale is None: return VAR_60 VAR_37 = FUNC_1( VAR_8, VAR_10=data, VAR_11=additional_request_data ) def VAR_100(): return FUNC_0( VAR_6=request.url_root, VAR_7=additional_unless ) return util.flask.preemptively_cached( cache=preemptiveCache, VAR_10=VAR_37, VAR_100=FUNC_35 )(VAR_60) def FUNC_28( VAR_8, VAR_60, VAR_15=None, VAR_61=None, VAR_62=None, VAR_63=None, VAR_64=None, VAR_65=None, ): if VAR_62 is None: VAR_62 = [] def FUNC_36(): return FUNC_2(VAR_8, VAR_15=additional_key_data) def FUNC_37(): if callable(VAR_63): try: VAR_33 = VAR_63() if VAR_33: return VAR_33 except Exception: VAR_0.exception( "Error while trying to retrieve tracked VAR_33 for VAR_130 {}".format( VAR_8 ) ) VAR_33 = FUNC_21() VAR_33 += FUNC_22() VAR_33 += FUNC_23( g.locale.language if g.locale else "en", "messages" ) if callable(VAR_61): try: VAR_142 = VAR_61() if VAR_142: VAR_33 += VAR_142 except Exception: VAR_0.exception( "Error while trying to retrieve VAR_101 tracked VAR_33 for VAR_130 {}".format( VAR_8 ) ) return sorted(set(VAR_33)) def FUNC_38(VAR_33): if callable(VAR_65): try: VAR_34 = VAR_65() if VAR_34: return VAR_34 except Exception: VAR_0.exception( "Error while trying to retrieve custom LastModified VAR_87 for VAR_130 {}".format( VAR_8 ) ) return FUNC_19(VAR_33) def FUNC_39(VAR_33, VAR_34, VAR_101=None): if callable(VAR_64): try: VAR_143 = VAR_64() if VAR_143: return VAR_143 except Exception: VAR_0.exception( "Error while trying to retrieve custom ETag VAR_87 for VAR_130 {}".format( VAR_8 ) ) if VAR_34 and not isinstance(VAR_34, str): from werkzeug.http import http_date VAR_34 = http_date(VAR_34) if VAR_101 is None: VAR_101 = [] import .hashlib VAR_86 = hashlib.sha1() def FUNC_32(VAR_87): VAR_86.update(to_bytes(VAR_87, encoding="utf-8", errors="replace")) FUNC_32(octoprint.__version__) FUNC_32(get_python_version_string()) FUNC_32(",".join(sorted(VAR_33))) if VAR_34: FUNC_32(VAR_34) for add in VAR_101: FUNC_32(add) return VAR_86.hexdigest() VAR_102 = FUNC_37() VAR_103 = FUNC_38(VAR_102) VAR_104 = FUNC_39( VAR_33=VAR_102, VAR_34=VAR_103, VAR_101=[FUNC_36()] + VAR_62, ) def FUNC_40(): VAR_90 = util.flask.check_lastmodified(VAR_103) VAR_89 = util.flask.check_etag(VAR_104) return VAR_90 and VAR_89 def FUNC_41(VAR_105): return VAR_50 or (VAR_104 != VAR_105.get_etag()[0]) VAR_106 = VAR_60 VAR_106 = util.flask.lastmodified(lambda _: VAR_103)( VAR_106 ) VAR_106 = util.flask.etagged(lambda _: VAR_104)(VAR_106) VAR_106 = util.flask.cached( timeout=-1, refreshif=FUNC_41, VAR_8=FUNC_36, unless_response=lambda VAR_44: util.flask.cache_check_response_headers( VAR_44 ) or util.flask.cache_check_status_code(VAR_44, FUNC_3), )(VAR_106) VAR_106 = util.flask.with_client_revalidation(VAR_106) VAR_106 = util.flask.conditional( FUNC_40, NOT_MODIFIED )(VAR_106) return VAR_106 def FUNC_29(VAR_66): VAR_105 = FUNC_28( VAR_66._identifier, VAR_66.on_ui_render, VAR_15=VAR_66.get_ui_additional_key_data_for_cache, VAR_61=VAR_66.get_ui_additional_tracked_files, VAR_63=VAR_66.get_ui_custom_tracked_files, VAR_64=VAR_66.get_ui_custom_etag, VAR_65=VAR_66.get_ui_custom_lastmodified, VAR_62=VAR_66.get_ui_additional_etag(VAR_59), ) if VAR_46 and VAR_66.get_ui_preemptive_caching_enabled(): VAR_60 = FUNC_27( VAR_66._identifier, VAR_105, VAR_66.get_ui_data_for_preemptive_caching, VAR_66.get_ui_additional_request_data_for_preemptive_caching, VAR_66.get_ui_preemptive_caching_additional_unless, ) else: VAR_60 = VAR_105 VAR_30 = VAR_66.get_ui_custom_template_filter(FUNC_26) if VAR_30 is not None and callable(VAR_30): VAR_82 = FUNC_13(VAR_1[VAR_14], VAR_30) else: VAR_82 = VAR_1[VAR_14] VAR_43 = FUNC_9( VAR_82, VAR_2, VAR_3, VAR_21 ) return VAR_60(VAR_21, request, VAR_43) def FUNC_30(): VAR_82 = FUNC_13( VAR_1[VAR_14], FUNC_26 ) VAR_107 = FUNC_25(VAR_82) VAR_108 = userManager.has_been_customized() VAR_43 = FUNC_9( VAR_82, VAR_2, VAR_3, VAR_21 ) VAR_43.update( { "enableWebcam": VAR_54, "enableTemperatureGraph": VAR_55, "enableAccessControl": True, "accessControlActive": VAR_108, "enableLoadingAnimation": VAR_52, "enableSdSupport": VAR_53, "sockJsConnectTimeout": VAR_56 * 1000, "wizard": VAR_107, "online": connectivityChecker.online, "now": VAR_21, } ) def FUNC_42(): VAR_129 = make_response(render_template("index.jinja2", **VAR_43)) if VAR_107: VAR_129 = util.flask.add_non_caching_response_headers(VAR_129) return VAR_129 VAR_105 = FUNC_28( "_default", FUNC_42, VAR_62=VAR_59 ) VAR_109 = FUNC_27("_default", VAR_105, {}, {}) return VAR_109() VAR_67 = [Permissions.STATUS, Permissions.SETTINGS_READ] VAR_44 = None VAR_68 = request.headers.get("X-Force-View", None) if VAR_68: VAR_0.debug(f"Forcing rendering of VAR_60 {VAR_68}") if VAR_68 != "_default": VAR_130 = pluginManager.get_plugin_info(VAR_68, require_enabled=True) if VAR_130 is not None and isinstance( VAR_130.implementation, octoprint.plugin.UiPlugin ): VAR_41 = VAR_130.implementation.get_ui_permissions() VAR_44 = require_login_with(VAR_41=permissions) if not VAR_44: VAR_44 = FUNC_29(VAR_130.implementation) if VAR_0.isEnabledFor(logging.DEBUG) and isinstance( VAR_44, Response ): VAR_44.headers[ "X-Ui-Plugin" ] = VAR_130.implementation._identifier else: VAR_44 = require_login_with(VAR_41=VAR_67) if not VAR_44: VAR_44 = FUNC_30() if VAR_0.isEnabledFor(logging.DEBUG) and isinstance(VAR_44, Response): VAR_44.headers["X-Ui-Plugin"] = "_default" else: VAR_45 = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for VAR_130 in VAR_45: try: if VAR_130.will_handle_ui(request): VAR_41 = VAR_130.get_ui_permissions() VAR_44 = require_login_with(VAR_41=permissions) if not VAR_44: VAR_44 = FUNC_29(VAR_130) if VAR_44 is not None: if VAR_0.isEnabledFor(logging.DEBUG) and isinstance( VAR_44, Response ): VAR_44.headers["X-Ui-Plugin"] = VAR_130._identifier break else: VAR_0.warning( "UiPlugin {} returned an empty response".format( VAR_130._identifier ) ) except Exception: VAR_0.exception( "Error while calling VAR_130 {}, skipping it".format( VAR_130._identifier ), extra={"plugin": VAR_130._identifier}, ) else: VAR_44 = require_login_with(VAR_41=VAR_67) if not VAR_44: VAR_44 = FUNC_30() if VAR_0.isEnabledFor(logging.DEBUG) and isinstance(VAR_44, Response): VAR_44.headers["X-Ui-Plugin"] = "_default" if VAR_44 is None: return abort(404) return VAR_44 def FUNC_9(VAR_18, VAR_19, VAR_20, VAR_21): global VAR_0 VAR_69 = settings().getBoolean(["server", "firstRun"]) VAR_70 = {} for VAR_131 in LOCALES: try: VAR_70[VAR_131.language] = { "language": VAR_131.language, "display": VAR_131.display_name, "english": VAR_131.english_name, } except Exception: VAR_0.exception("Error while collecting available locales") VAR_41 = [permission.as_dict() for permission in Permissions.all()] VAR_71 = list(sorted(full_extension_tree().keys())) VAR_72 = list(map(lambda ext: f".{ext}", get_all_extensions())) VAR_43 = { "debug": debug, "firstRun": VAR_69, "version": {"number": VERSION, "display": DISPLAY_VERSION, "branch": BRANCH}, "python_version": get_python_version_string(), "templates": VAR_18, "pluginNames": VAR_19, "locales": VAR_70, "permissions": VAR_41, "supportedFiletypes": VAR_71, "supportedExtensions": VAR_72, } VAR_43.update(VAR_20) return VAR_43 def FUNC_10(VAR_22=False): global VAR_1, VAR_2, VAR_3 VAR_14 = g.locale.language if g.locale else "en" if ( not VAR_22 and VAR_1.get(VAR_14) is not None and VAR_2 is not None and VAR_3 is not None ): return VAR_1[VAR_14], VAR_2, VAR_3 VAR_69 = settings().getBoolean(["server", "firstRun"]) VAR_18 = defaultdict(lambda: {"order": [], "entries": {}}) VAR_73 = { "navbar": { "div": lambda VAR_136: "navbar_plugin_" + VAR_136, "template": lambda VAR_136: VAR_136 + "_navbar.jinja2", "to_entry": lambda VAR_10: data, }, "sidebar": { "div": lambda VAR_136: "sidebar_plugin_" + VAR_136, "template": lambda VAR_136: VAR_136 + "_sidebar.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "tab": { "div": lambda VAR_136: "tab_plugin_" + VAR_136, "template": lambda VAR_136: VAR_136 + "_tab.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "settings": { "div": lambda VAR_136: "settings_plugin_" + VAR_136, "template": lambda VAR_136: VAR_136 + "_settings.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "usersettings": { "div": lambda VAR_136: "usersettings_plugin_" + VAR_136, "template": lambda VAR_136: VAR_136 + "_usersettings.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "wizard": { "div": lambda VAR_136: "wizard_plugin_" + VAR_136, "template": lambda VAR_136: VAR_136 + "_wizard.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "about": { "div": lambda VAR_136: "about_plugin_" + VAR_136, "template": lambda VAR_136: VAR_136 + "_about.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "generic": {"template": lambda VAR_136: VAR_136 + ".jinja2", "to_entry": lambda VAR_10: data}, } def FUNC_31(VAR_37, VAR_38): if VAR_37[1].get("_key", None) == "plugin_corewizard_acl": return f"0:{to_unicode(VAR_37[0])}" elif VAR_37[1].get("mandatory", False): return f"1:{to_unicode(VAR_37[0])}" else: return f"2:{to_unicode(VAR_37[0])}" VAR_74 = { "navbar": {"add": "prepend", "key": None}, "sidebar": {"add": "append", "key": "name"}, "tab": {"add": "append", "key": "name"}, "settings": { "add": "custom_append", "key": "name", "custom_add_entries": lambda VAR_111: { "section_plugins": (gettext("Plugins"), None) }, "custom_add_order": lambda VAR_111: ["section_plugins"] + VAR_111, }, "usersettings": {"add": "append", "key": "name"}, "wizard": {"add": "append", "key": "name", "key_extractor": FUNC_31}, "about": {"add": "append", "key": "name"}, "generic": {"add": "append", "key": None}, } VAR_75 = pluginManager.get_hooks("octoprint.ui.web.templatetypes") for VAR_23, VAR_17 in VAR_75.items(): try: VAR_39 = VAR_17(dict(VAR_74), dict(VAR_73)) except Exception: VAR_0.exception( f"Error while retrieving custom VAR_145 type " f"definitions from VAR_130 {VAR_23}", extra={"plugin": VAR_23}, ) else: if not isinstance(VAR_39, list): continue for entry in VAR_39: if not isinstance(entry, tuple) or not len(entry) == 3: continue VAR_8, VAR_139, VAR_27 = entry if "add" not in VAR_139: order["add"] = "prepend" if "key" not in VAR_139: order["key"] = "name" if "div" not in VAR_27: VAR_144 = f"{VAR_23}_{VAR_8}_plugin_" VAR_27["div"] = lambda VAR_136: VAR_144 + VAR_136 if "template" not in VAR_27: VAR_145 = f"_plugin_{VAR_23}_{VAR_8}.jinja2" VAR_27["template"] = lambda VAR_136: VAR_136 + VAR_145 if "to_entry" not in VAR_27: VAR_27["to_entry"] = lambda VAR_10: (VAR_10["name"], VAR_10) VAR_73["plugin_" + VAR_23 + "_" + VAR_8] = VAR_27 VAR_74["plugin_" + VAR_23 + "_" + VAR_8] = VAR_139 VAR_76 = list(VAR_73.keys()) VAR_18["navbar"]["entries"] = { "offlineindicator": { "template": "navbar/offlineindicator.jinja2", "_div": "navbar_offlineindicator", "custom_bindings": False, }, "settings": { "template": "navbar/settings.jinja2", "_div": "navbar_settings", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SETTINGS)", }, "systemmenu": { "template": "navbar/systemmenu.jinja2", "_div": "navbar_systemmenu", "classes": ["dropdown"], "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", "custom_bindings": False, }, "login": { "template": "navbar/FUNC_5.jinja2", "_div": "navbar_login", "classes": ["dropdown"], "custom_bindings": False, }, } VAR_18["sidebar"]["entries"] = { "connection": ( gettext("Connection"), { "template": "sidebar/connection.jinja2", "_div": "connection", "icon": "signal", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.CONNECTION)", "template_header": "sidebar/connection_header.jinja2", }, ), "state": ( gettext("State"), { "template": "sidebar/state.jinja2", "_div": "state", "icon": "info-circle", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.STATUS)", }, ), "files": ( gettext("Files"), { "template": "sidebar/VAR_33.jinja2", "_div": "files", "icon": "list", "classes_content": ["overflow_visible"], "template_header": "sidebar/files_header.jinja2", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.FILES_LIST)", }, ), } VAR_18["tab"]["entries"] = { "temperature": ( gettext("Temperature"), { "template": "tabs/temperature.jinja2", "_div": "temp", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)() && visible()", }, ), "control": ( gettext("Control"), { "template": "tabs/control.jinja2", "_div": "control", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.WEBCAM, access.permissions.CONTROL)", }, ), "terminal": ( gettext("Terminal"), { "template": "tabs/terminal.jinja2", "_div": "term", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.MONITOR_TERMINAL)", }, ), "timelapse": ( gettext("Timelapse"), { "template": "tabs/timelapse.jinja2", "_div": "timelapse", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.TIMELAPSE_LIST)", }, ), } VAR_18["settings"]["entries"] = { "section_printer": (gettext("Printer"), None), "serial": ( gettext("Serial Connection"), { "template": "dialogs/settings/serialconnection.jinja2", "_div": "settings_serialConnection", "custom_bindings": False, }, ), "printerprofiles": ( gettext("Printer Profiles"), { "template": "dialogs/settings/printerprofiles.jinja2", "_div": "settings_printerProfiles", "custom_bindings": False, }, ), "temperatures": ( gettext("Temperatures"), { "template": "dialogs/settings/temperatures.jinja2", "_div": "settings_temperature", "custom_bindings": False, }, ), "terminalfilters": ( gettext("Terminal Filters"), { "template": "dialogs/settings/terminalfilters.jinja2", "_div": "settings_terminalFilters", "custom_bindings": False, }, ), "gcodescripts": ( gettext("GCODE Scripts"), { "template": "dialogs/settings/gcodescripts.jinja2", "_div": "settings_gcodeScripts", "custom_bindings": False, }, ), "section_features": (gettext("Features"), None), "features": ( gettext("Features"), { "template": "dialogs/settings/features.jinja2", "_div": "settings_features", "custom_bindings": False, }, ), "webcam": ( gettext("Webcam & Timelapse"), { "template": "dialogs/settings/webcam.jinja2", "_div": "settings_webcam", "custom_bindings": False, }, ), "api": ( gettext("API"), { "template": "dialogs/settings/api.jinja2", "_div": "settings_api", "custom_bindings": False, }, ), "section_octoprint": (gettext("OctoPrint"), None), "accesscontrol": ( gettext("Access Control"), { "template": "dialogs/settings/accesscontrol.jinja2", "_div": "settings_users", "custom_bindings": False, }, ), "folders": ( gettext("Folders"), { "template": "dialogs/settings/folders.jinja2", "_div": "settings_folders", "custom_bindings": False, }, ), "appearance": ( gettext("Appearance"), { "template": "dialogs/settings/appearance.jinja2", "_div": "settings_appearance", "custom_bindings": False, }, ), "server": ( gettext("Server"), { "template": "dialogs/settings/server.jinja2", "_div": "settings_server", "custom_bindings": False, }, ), } VAR_18["usersettings"]["entries"] = { "access": ( gettext("Access"), { "template": "dialogs/usersettings/access.jinja2", "_div": "usersettings_access", "custom_bindings": False, }, ), "interface": ( gettext("Interface"), { "template": "dialogs/usersettings/interface.jinja2", "_div": "usersettings_interface", "custom_bindings": False, }, ), } if VAR_69: def FUNC_43(VAR_110, VAR_111): if "firstrunstart" in VAR_111: missing.remove("firstrunstart") if "firstrunend" in VAR_111: missing.remove("firstrunend") return ["firstrunstart"] + VAR_110 + VAR_111 + ["firstrunend"] VAR_74["wizard"].update( { "add": "custom_insert", "custom_insert_entries": lambda VAR_111: {}, "custom_insert_order": FUNC_43, } ) VAR_18["wizard"]["entries"] = { "firstrunstart": ( gettext("Start"), { "template": "dialogs/VAR_107/firstrun_start.jinja2", "_div": "wizard_firstrun_start", }, ), "firstrunend": ( gettext("Finish"), { "template": "dialogs/VAR_107/firstrun_end.jinja2", "_div": "wizard_firstrun_end", }, ), } VAR_18["about"]["entries"] = { "about": ( "About OctoPrint", { "template": "dialogs/about/about.jinja2", "_div": "about_about", "custom_bindings": False, }, ), "license": ( "OctoPrint License", { "template": "dialogs/about/license.jinja2", "_div": "about_license", "custom_bindings": False, }, ), "thirdparty": ( "Third Party Licenses", { "template": "dialogs/about/thirdparty.jinja2", "_div": "about_thirdparty", "custom_bindings": False, }, ), "authors": ( "Authors", { "template": "dialogs/about/authors.jinja2", "_div": "about_authors", "custom_bindings": False, }, ), "supporters": ( "Supporters", { "template": "dialogs/about/supporters.jinja2", "_div": "about_sponsors", "custom_bindings": False, }, ), "systeminfo": ( "System Information", { "template": "dialogs/about/systeminfo.jinja2", "_div": "about_systeminfo", "custom_bindings": False, "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", }, ), } VAR_77 = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin) VAR_20 = {} VAR_19 = set() VAR_78 = {} VAR_79 = settings().get(["server", "seenWizards"]) if not VAR_69 else {} for VAR_24 in VAR_77: VAR_23 = VAR_24._identifier VAR_19.add(VAR_23) VAR_112 = False VAR_113 = False try: VAR_132 = VAR_24.get_template_vars() VAR_25 = VAR_24.get_template_configs() if isinstance(VAR_24, octoprint.plugin.WizardPlugin): VAR_112 = VAR_24.is_wizard_required() VAR_113 = octoprint.plugin.WizardPlugin.is_wizard_ignored( VAR_79, VAR_24 ) except Exception: VAR_0.exception( "Error while retrieving VAR_145 VAR_10 for VAR_130 {}, ignoring it".format( VAR_23 ), extra={"plugin": VAR_23}, ) continue if not isinstance(VAR_132, dict): VAR_132 = {} if not isinstance(VAR_25, (list, tuple)): VAR_25 = [] for VAR_133, var_value in VAR_132.items(): VAR_20["plugin_" + VAR_23 + "_" + VAR_133] = var_value try: VAR_81 = FUNC_11( VAR_23, VAR_24, VAR_25, VAR_73 ) except Exception: VAR_0.exception( "Error while processing VAR_145 VAR_25 for VAR_130 {}, ignoring it".format( VAR_23 ), extra={"plugin": VAR_23}, ) if not VAR_112 or VAR_113: VAR_81["wizard"] = list() for VAR_117 in VAR_76: VAR_78[VAR_117] = {} for include in VAR_81[VAR_117]: if VAR_117 == "navbar" or VAR_117 == "generic": VAR_10 = include else: VAR_10 = include[1] VAR_8 = VAR_10["_key"] if "replaces" in VAR_10: VAR_8 = VAR_10["replaces"] VAR_78[VAR_117][VAR_10["_key"]] = VAR_10["replaces"] VAR_18[VAR_117]["entries"][VAR_8] = include for VAR_117 in VAR_76: VAR_114 = ( settings().get( ["appearance", "components", "order", VAR_117], merged=True, VAR_28={} ) or [] ) VAR_115 = ( settings().get(["appearance", "components", "order", VAR_117], merged=True) or [] ) VAR_116 = ( settings().get(["appearance", "components", "disabled", VAR_117]) or [] ) VAR_39 = [] for VAR_136 in VAR_115: if VAR_136 in VAR_78[VAR_117]: VAR_136 = VAR_78[VAR_117][VAR_136] if ( VAR_136 in VAR_18[VAR_117]["entries"] and VAR_136 not in VAR_116 and VAR_136 not in VAR_39 ): result.append(VAR_136) VAR_18[VAR_117]["order"] = VAR_39 VAR_18[VAR_117]["order"] += [ VAR_136 for VAR_136 in VAR_114 if VAR_136 not in VAR_18[VAR_117]["order"] and VAR_136 in VAR_18[VAR_117]["entries"] and VAR_136 not in VAR_116 ] VAR_118 = set(VAR_18[VAR_117]["order"]) VAR_119 = set(VAR_116) VAR_120 = ( set(VAR_18[VAR_117]["entries"].keys()) .difference(VAR_118) .difference(VAR_119) ) if len(VAR_120) == 0: continue def FUNC_44(VAR_121, VAR_8, VAR_122=None): if isinstance(VAR_121, dict) and VAR_8 in VAR_121: return VAR_121[VAR_8] if VAR_8 in VAR_121 else VAR_122 elif ( isinstance(VAR_121, tuple) and len(VAR_121) > 1 and isinstance(VAR_121[1], dict) and VAR_8 in VAR_121[1] ): return VAR_121[1][VAR_8] if VAR_8 in VAR_121[1] else VAR_122 return VAR_122 if VAR_74[VAR_117]["key"] is not None: VAR_134 = FUNC_44 if "key_extractor" in VAR_74[VAR_117] and callable( VAR_74[VAR_117]["key_extractor"] ): def FUNC_46(VAR_134): def FUNC_47(VAR_136, VAR_38): try: return VAR_134(VAR_136, VAR_38) except Exception: VAR_0.exception( "Error while extracting sorting keys for VAR_145 {}".format( VAR_117 ) ) return None return FUNC_47 VAR_134 = FUNC_46(VAR_74[VAR_117]["key_extractor"]) VAR_135 = VAR_74[VAR_117]["key"] def FUNC_45(VAR_136): VAR_28 = VAR_18[VAR_117]["entries"][VAR_136] VAR_140 = FUNC_44(VAR_28, "order", VAR_122=None) return ( VAR_140 is None, sv(VAR_140), sv(VAR_134(VAR_28, VAR_135)), ) VAR_137 = sorted(VAR_120, VAR_8=FUNC_45) else: def FUNC_45(VAR_136): VAR_28 = VAR_18[VAR_117]["entries"][VAR_136] VAR_140 = FUNC_44(VAR_28, "order", VAR_122=None) return VAR_140 is None, sv(VAR_140) VAR_137 = sorted(VAR_120, VAR_8=FUNC_45) if VAR_74[VAR_117]["add"] == "prepend": VAR_18[VAR_117]["order"] = VAR_137 + VAR_18[VAR_117]["order"] elif VAR_74[VAR_117]["add"] == "append": VAR_18[VAR_117]["order"] += VAR_137 elif ( VAR_74[VAR_117]["add"] == "custom_prepend" and "custom_add_entries" in VAR_74[VAR_117] and "custom_add_order" in VAR_74[VAR_117] ): VAR_18[VAR_117]["entries"].update( VAR_74[VAR_117]["custom_add_entries"](VAR_137) ) VAR_18[VAR_117]["order"] = ( VAR_74[VAR_117]["custom_add_order"](VAR_137) + VAR_18[VAR_117]["order"] ) elif ( VAR_74[VAR_117]["add"] == "custom_append" and "custom_add_entries" in VAR_74[VAR_117] and "custom_add_order" in VAR_74[VAR_117] ): VAR_18[VAR_117]["entries"].update( VAR_74[VAR_117]["custom_add_entries"](VAR_137) ) VAR_18[VAR_117]["order"] += VAR_74[VAR_117]["custom_add_order"]( VAR_137 ) elif ( VAR_74[VAR_117]["add"] == "custom_insert" and "custom_insert_entries" in VAR_74[VAR_117] and "custom_insert_order" in VAR_74[VAR_117] ): VAR_18[VAR_117]["entries"].update( VAR_74[VAR_117]["custom_insert_entries"](VAR_137) ) VAR_18[VAR_117]["order"] = VAR_74[VAR_117]["custom_insert_order"]( VAR_18[VAR_117]["order"], VAR_137 ) VAR_1[VAR_14] = VAR_18 VAR_2 = VAR_19 VAR_3 = VAR_20 return VAR_18, VAR_19, VAR_20 def FUNC_11(VAR_23, VAR_24, VAR_25, VAR_26): from jinja2.exceptions import TemplateNotFound VAR_80 = defaultdict(lambda: 1) VAR_81 = defaultdict(list) for VAR_28 in VAR_25: if not isinstance(VAR_28, dict): continue if "type" not in VAR_28: continue VAR_57 = VAR_28["type"] del VAR_28["type"] if VAR_57 not in VAR_26: continue VAR_27 = VAR_26[VAR_57] VAR_10 = FUNC_12( VAR_23, VAR_24, VAR_27, VAR_28=config, VAR_29=VAR_80[VAR_57] ) if VAR_10 is None: continue VAR_81[VAR_57].append(VAR_27["to_entry"](VAR_10)) VAR_80[VAR_57] += 1 for VAR_57 in VAR_26: if len(VAR_81[VAR_57]) == 0: VAR_27 = VAR_26[VAR_57] VAR_10 = FUNC_12(VAR_23, VAR_24, VAR_27) if VAR_10 is not None: try: app.jinja_env.get_or_select_template(VAR_10["template"]) except TemplateNotFound: pass except Exception: VAR_0.exception( "Error in VAR_145 {}, not going to include it".format( VAR_10["template"] ) ) else: VAR_81[VAR_57].append(VAR_27["to_entry"](VAR_10)) return VAR_81 def FUNC_12(VAR_23, VAR_24, VAR_27, VAR_28=None, VAR_29=1): if "mandatory" in VAR_27: for mandatory in VAR_27["mandatory"]: if mandatory not in VAR_28: return None if VAR_28 is None: VAR_28 = {} VAR_10 = dict(VAR_28) if "suffix" not in VAR_10 and VAR_29 > 1: VAR_10["suffix"] = "_%d" % VAR_29 if "div" in VAR_10: VAR_10["_div"] = VAR_10["div"] elif "div" in VAR_27: VAR_10["_div"] = VAR_27["div"](VAR_23) if "suffix" in VAR_10: VAR_10["_div"] = VAR_10["_div"] + VAR_10["suffix"] if not VAR_5.match(VAR_10["_div"]): VAR_0.warning( "Template VAR_28 {} contains invalid VAR_144 identifier {}, skipping it".format( VAR_23, VAR_10["_div"] ) ) return None if VAR_10.get("template"): VAR_10["template"] = VAR_24.template_folder_key + "/" + VAR_10["template"] else: VAR_10["template"] = ( VAR_24.template_folder_key + "/" + VAR_27["template"](VAR_23) ) if VAR_10.get("template_header"): VAR_10["template_header"] = ( VAR_24.template_folder_key + "/" + VAR_10["template_header"] ) if "name" not in VAR_10: VAR_10["name"] = VAR_24._plugin_name if "custom_bindings" not in VAR_10 or VAR_10["custom_bindings"]: VAR_123 = "allowBindings: true" if "data_bind" in VAR_10: VAR_123 = data_bind + ", " + VAR_10["data_bind"] VAR_123 = data_bind.replace('"', '\\"') VAR_10["data_bind"] = VAR_123 VAR_10["_key"] = "plugin_" + VAR_23 if "suffix" in VAR_10: VAR_10["_key"] += VAR_10["suffix"] VAR_10["_plugin"] = VAR_23 return VAR_10 def FUNC_13(VAR_18, VAR_30): VAR_82 = {} for VAR_57, template_collection in VAR_18.items(): VAR_124 = {} for VAR_58, template_entry in template_collection["entries"].items(): if VAR_30(VAR_57, VAR_58): VAR_124[VAR_58] = template_entry VAR_82[VAR_57] = { "order": list( filter(lambda VAR_136: VAR_136 in VAR_124, template_collection["order"]) ), "entries": VAR_124, } return VAR_82 @app.route("/robots.txt") def FUNC_14(): return send_from_directory(app.static_folder, "robots.txt") @app.route("/i18n/<string:VAR_14>/<string:VAR_31>.js") @util.flask.conditional(lambda: FUNC_20(), NOT_MODIFIED) @util.flask.etagged( lambda _: FUNC_17( request.view_args["locale"], request.view_args["domain"] ) ) @util.flask.lastmodified( lambda _: FUNC_18( request.view_args["locale"], request.view_args["domain"] ) ) def FUNC_15(VAR_14, VAR_31): VAR_83 = {} VAR_84 = None if VAR_14 != "en": VAR_83, VAR_84 = FUNC_24(VAR_14, VAR_31) VAR_85 = { "messages": VAR_83, "plural_expr": VAR_84, "locale": VAR_14, "domain": VAR_31, } from flask import Response return Response( render_template("i18n.js.jinja2", VAR_85=catalog), content_type="application/VAR_136-javascript; charset=utf-8", ) @app.route("/FUNC_16/<string:VAR_23>/<VAR_9:VAR_32>") def FUNC_16(VAR_23, VAR_32): return redirect(url_for("plugin." + VAR_23 + ".static", VAR_32=filename)) def FUNC_17(VAR_14, VAR_31, VAR_33=None, VAR_34=None): if VAR_33 is None: VAR_33 = FUNC_23(VAR_14, VAR_31) if VAR_34 is None: VAR_34 = FUNC_19(VAR_33) if VAR_34 and not isinstance(VAR_34, str): from werkzeug.http import http_date VAR_34 = http_date(VAR_34) import .hashlib VAR_86 = hashlib.sha1() def FUNC_32(VAR_87): VAR_86.update(VAR_87.encode("utf-8")) FUNC_32(",".join(sorted(VAR_33))) if VAR_34: FUNC_32(VAR_34) return VAR_86.hexdigest() def FUNC_18(VAR_14, VAR_31): return FUNC_19(FUNC_23(VAR_14, VAR_31)) def FUNC_19(VAR_33): import .stat from datetime import .datetime from octoprint.util.tz import UTC_TZ VAR_88 = 0 for VAR_9 in VAR_33: try: VAR_138 = os.stat(VAR_9) if stat.S_ISREG(VAR_138.st_mode) and VAR_138.st_mtime > VAR_88: VAR_88 = VAR_138.st_mtime except Exception: continue if VAR_88: VAR_88 = ( datetime.fromtimestamp(VAR_88) .replace(microsecond=0) .replace(tzinfo=UTC_TZ) ) return VAR_88 def FUNC_20(): VAR_14 = request.view_args["locale"] VAR_31 = request.view_args["domain"] VAR_89 = util.flask.check_etag( FUNC_17(request.view_args["locale"], request.view_args["domain"]) ) VAR_34 = FUNC_18(VAR_14, VAR_31) VAR_90 = VAR_34 is None or util.flask.check_lastmodified(VAR_34) return VAR_89 and VAR_90 def FUNC_21(): from octoprint.util.jinja import get_all_template_paths return get_all_template_paths(app.jinja_loader) def FUNC_22(): from octoprint.util.jinja import get_all_asset_paths return get_all_asset_paths(app.jinja_env.assets_environment, verifyExist=False) def FUNC_23(VAR_14, VAR_31): from flask import _request_ctx_stack def FUNC_33(VAR_91, VAR_14, VAR_31): return os.path.join(VAR_91, VAR_14, "LC_MESSAGES", f"{VAR_31}.po") VAR_92 = [] VAR_93 = os.path.join( settings().getBaseFolder("translations", check_writable=False) ) VAR_94 = os.path.join(VAR_93, "_plugins") VAR_95 = octoprint.plugin.plugin_manager().enabled_plugins for VAR_23, VAR_130 in VAR_95.items(): VAR_98 = [ os.path.join(VAR_94, VAR_23), os.path.join(VAR_130.location, "translations"), ] for dirname in VAR_98: VAR_92.append(FUNC_33(dirname, VAR_14, VAR_31)) VAR_96 = _request_ctx_stack.top VAR_97 = os.path.join(VAR_96.app.root_path, "translations") VAR_98 = [VAR_93, VAR_97] for dirname in VAR_98: VAR_92.append(FUNC_33(dirname, VAR_14, VAR_31)) return VAR_92 def FUNC_24(VAR_14, VAR_31): from babel.messages.pofile import .read_po from octoprint.util import .dict_merge VAR_83 = {} VAR_84 = None def FUNC_34(VAR_9, VAR_14, VAR_31): VAR_83 = {} with open(VAR_9, encoding="utf-8") as FUNC_47: VAR_85 = read_po(FUNC_47, VAR_14=locale, VAR_31=domain) for message in VAR_85: VAR_141 = message.id if isinstance(VAR_141, (list, tuple)): VAR_141 = message_id[0] if message.string: VAR_83[VAR_141] = message.string return VAR_83, VAR_85.plural_expr VAR_92 = FUNC_23(VAR_14, VAR_31) for po_file in VAR_92: if not os.path.exists(po_file): continue VAR_125, VAR_84 = FUNC_34(po_file, VAR_14, VAR_31) if VAR_125 is not None: VAR_83 = dict_merge(VAR_83, VAR_125, in_place=True) return VAR_83, VAR_84
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import base64 import .datetime import logging import os import .re from collections import .defaultdict from urllib.parse import .urlparse from flask import ( Response, abort, g, make_response, redirect, render_template, request, send_from_directory, url_for, ) import octoprint.plugin from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.filemanager import .full_extension_tree, get_all_extensions from octoprint.server import ( # noqa: F401 BRANCH, DISPLAY_VERSION, LOCALES, NOT_MODIFIED, VERSION, app, debug, gettext, groupManager, pluginManager, preemptiveCache, userManager, ) from octoprint.server.util import has_permissions, require_login_with from octoprint.settings import .settings from octoprint.util import .sv, to_bytes, to_unicode from octoprint.util.version import get_python_version_string from . import util VAR_0 = logging.getLogger(__name__) VAR_1 = {} VAR_2 = None VAR_3 = None VAR_4 = re.compile("[a-z_]+") VAR_5 = re.compile("[a-zA-Z_-]+") def FUNC_0(VAR_6=None, VAR_7=None): if VAR_6 is None: VAR_6 = request.url_root VAR_35 = ( not settings().getBoolean(["devel", "cache", "preemptive"]) or VAR_6 in settings().get(["server", "preemptiveCache", "exceptions"]) or not (VAR_6.startswith("http://") or VAR_6.startswith("https://")) ) VAR_36 = request.headers.get("X-Preemptive-Recording", "no") == "yes" if callable(VAR_7): return VAR_36 or VAR_35 or VAR_7() else: return VAR_36 or VAR_35 def FUNC_1( VAR_8, VAR_9=None, VAR_6=None, VAR_10=None, VAR_11=None ): if VAR_9 is None: VAR_9 = request.path if VAR_6 is None: VAR_6 = request.url_root VAR_37 = { "path": VAR_9, "base_url": VAR_6, "query_string": "l10n={}".format(g.locale.language if g.locale else "en"), } if VAR_8 != "_default": VAR_37["plugin"] = VAR_8 if VAR_10 is not None: try: if callable(VAR_10): VAR_10 = VAR_10() if VAR_10: if "query_string" in VAR_10: VAR_10["query_string"] = "l10n={}&{}".format( g.locale.language, VAR_10["query_string"] ) VAR_37.update(VAR_10) except Exception: VAR_0.exception( f"Error collecting VAR_10 for preemptive cache from VAR_132 {VAR_8}" ) if callable(VAR_11): try: VAR_128 = VAR_11() if VAR_128: VAR_37.update({"_additional_request_data": VAR_128}) except Exception: VAR_0.exception( "Error retrieving VAR_103 VAR_10 for preemptive cache from VAR_132 {}".format( VAR_8 ) ) return VAR_37 def FUNC_2(VAR_12, VAR_13=None, VAR_14=None, VAR_15=None): if VAR_13 is None: VAR_13 = request.base_url if VAR_14 is None: VAR_14 = g.locale.language if g.locale else "en" VAR_38 = f"ui:{VAR_12}:{VAR_13}:{VAR_14}" if callable(VAR_15): try: VAR_129 = VAR_15() if VAR_129: if not isinstance(VAR_129, (list, tuple)): VAR_129 = [ak] VAR_38 = "{}:{}".format(VAR_38, ":".join(VAR_129)) except Exception: VAR_0.exception( "Error while trying to retrieve VAR_103 cache VAR_8 parts for VAR_12 {}".format( VAR_12 ) ) return VAR_38 def FUNC_3(VAR_16): return 200 <= VAR_16 < 400 def FUNC_4(VAR_17): VAR_39 = [] for VAR_23, VAR_17 in pluginManager.get_hooks(VAR_17).items(): try: VAR_130 = VAR_17() if isinstance(VAR_130, (tuple, list)): VAR_39 += VAR_130 except Exception: VAR_0.exception( f"Error fetching theming CSS to include from VAR_132 {VAR_23}", extra={"plugin": VAR_23}, ) return VAR_39 @app.route("/login") @app.route("/FUNC_5/") def FUNC_5(): from flask_login import current_user VAR_40 = request.script_root + url_for("index") VAR_41 = request.args.get("redirect", VAR_40) VAR_42 = urlparse(VAR_41) # check if redirect VAR_13 is valid if VAR_42.scheme != "" or VAR_42.netloc != "": VAR_0.warning( f"Got an invalid redirect URL with the FUNC_5 attempt, misconfiguration or attack attempt: {VAR_41}" ) VAR_41 = VAR_40 VAR_43 = sorted( filter( lambda VAR_138: VAR_138 is not None and isinstance(VAR_138, OctoPrintPermission), map( lambda VAR_138: getattr(Permissions, VAR_138.strip()), request.args.get("permissions", "").split(","), ), ), VAR_8=lambda VAR_138: x.get_name(), ) if not VAR_43: permissions = [Permissions.STATUS, Permissions.SETTINGS_READ] VAR_44 = request.args.get("user_id", "") if (not VAR_44 or current_user.get_id() == VAR_44) and has_permissions( *VAR_43 ): return redirect(VAR_41) VAR_45 = { "theming": [], "redirect_url": VAR_41, "permission_names": map(lambda VAR_138: x.get_name(), VAR_43), "user_id": VAR_44, "logged_in": not current_user.is_anonymous, } try: VAR_101 = FUNC_4("octoprint.theming.login") VAR_101 += FUNC_4("octoprint.plugin.forcelogin.theming") VAR_101 += FUNC_4("octoprint.plugin.loginui.theming") VAR_45.update({"theming": VAR_101}) except Exception: VAR_0.exception("Error processing theming CSS, ignoring") return render_template("login.jinja2", **VAR_45) @app.route("/recovery") @app.route("/FUNC_6/") def FUNC_6(): VAR_46 = require_login_with(VAR_43=[Permissions.ADMIN]) if VAR_46: return VAR_46 VAR_45 = {"theming": []} try: VAR_101 = FUNC_4("octoprint.theming.recovery") VAR_45.update({"theming": VAR_101}) except Exception: VAR_0.exception("Error processing theming CSS, ignoring") try: from octoprint.plugins.backup import MAX_UPLOAD_SIZE from octoprint.util import get_formatted_size VAR_45.update( { "plugin_backup_max_upload_size": MAX_UPLOAD_SIZE, "plugin_backup_max_upload_size_str": get_formatted_size(MAX_UPLOAD_SIZE), } ) except Exception: VAR_0.exception("Error adding backup upload size info, ignoring") return render_template("recovery.jinja2", **VAR_45) @app.route("/VAR_107.gif") def FUNC_7(): VAR_13 = request.base_url.replace("/VAR_107.gif", "/") VAR_9 = request.path.replace("/VAR_107.gif", "/") VAR_6 = request.url_root VAR_47 = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for VAR_132 in VAR_47: try: if VAR_132.will_handle_ui(request): VAR_12 = VAR_132._identifier VAR_8 = FUNC_2( VAR_132._identifier, VAR_13=url, VAR_15=VAR_132.get_ui_additional_key_data_for_cache, ) VAR_102 = FUNC_0( VAR_13, VAR_7=VAR_132.get_ui_preemptive_caching_additional_unless, ) VAR_10 = FUNC_1( VAR_132._identifier, VAR_9=path, VAR_6=base_url, VAR_10=VAR_132.get_ui_data_for_preemptive_caching, VAR_11=VAR_132.get_ui_additional_request_data_for_preemptive_caching, ) break except Exception: VAR_0.exception( f"Error while calling VAR_132 {plugin._identifier}, skipping it", extra={"plugin": VAR_132._identifier}, ) else: VAR_12 = "_default" VAR_8 = FUNC_2("_default", VAR_13=url) VAR_102 = FUNC_0(VAR_13) VAR_10 = FUNC_1("_default", VAR_9=path, VAR_6=base_url) VAR_46 = make_response( bytes( base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7") ) ) VAR_46.headers["Content-Type"] = "image/gif" if VAR_102 or not preemptiveCache.has_record(VAR_10, root=VAR_9): VAR_0.info( "Preemptive cache not active for VAR_9 {}, VAR_12 {} and VAR_10 {!VAR_131}, signaling as cached".format( VAR_9, VAR_12, VAR_10 ) ) return VAR_46 elif util.flask.is_in_cache(VAR_8): VAR_0.info(f"Found VAR_9 {VAR_9} in cache (VAR_8: {VAR_8}), signaling as cached") return VAR_46 elif util.flask.is_cache_bypassed(VAR_8): VAR_0.info( "Path {} was bypassed from cache (VAR_8: {}), signaling as cached".format( VAR_9, VAR_8 ) ) return VAR_46 else: VAR_0.debug(f"Path {VAR_9} not yet VAR_107 (VAR_8: {VAR_8}), signaling as missing") return abort(404) @app.route("/") def FUNC_8(): from octoprint.server import connectivityChecker, printer global VAR_1, VAR_2, VAR_3 VAR_48 = settings().getBoolean(["devel", "cache", "preemptive"]) VAR_14 = g.locale.language if g.locale else "en" def FUNC_25(VAR_18): return VAR_18 is not None and bool(VAR_18["wizard"]["order"]) VAR_49 = util.flask.cache_check_headers() VAR_50 = "_refresh" in request.values VAR_51 = printer.is_printing() if VAR_49 and VAR_51: logging.getLogger(__name__).warning( "Client requested cache VAR_22 via cache-control headers but we are VAR_51. " "Not invalidating caches due to resource limitation. Append ?_refresh=true to " "the URL if you absolutely require a VAR_22 now" ) VAR_49 = VAR_49 and not VAR_51 VAR_52 = ( VAR_49 or VAR_50 or FUNC_25(VAR_1.get(VAR_14)) ) FUNC_10(VAR_22=VAR_52) VAR_21 = datetime.datetime.utcnow() VAR_53 = settings().getBoolean(["webcam", "timelapseEnabled"]) VAR_54 = settings().getBoolean(["devel", "showLoadingAnimation"]) VAR_55 = settings().get(["feature", "sdSupport"]) VAR_56 = settings().getBoolean(["webcam", "webcamEnabled"]) and bool( settings().get(["webcam", "stream"]) ) VAR_57 = settings().get(["feature", "temperatureGraph"]) VAR_58 = settings().getInt(["devel", "sockJsConnectTimeout"]) def FUNC_26(VAR_59, VAR_60): if VAR_59 == "tab": return VAR_60 != "timelapse" or VAR_53 else: return True VAR_61 = [ VAR_53, VAR_54, VAR_55, VAR_56, VAR_57, VAR_58, connectivityChecker.online, FUNC_25(VAR_1.get(VAR_14)), ] + sorted( "{}:{}".format(to_unicode(VAR_38, errors="replace"), to_unicode(v, errors="replace")) for VAR_38, v in VAR_3.items() ) def FUNC_27( VAR_8, VAR_62, VAR_10=None, VAR_11=None, VAR_7=None ): if (VAR_10 is None and VAR_11 is None) or g.locale is None: return VAR_62 VAR_37 = FUNC_1( VAR_8, VAR_10=data, VAR_11=additional_request_data ) def VAR_102(): return FUNC_0( VAR_6=request.url_root, VAR_7=additional_unless ) return util.flask.preemptively_cached( cache=preemptiveCache, VAR_10=VAR_37, VAR_102=FUNC_35 )(VAR_62) def FUNC_28( VAR_8, VAR_62, VAR_15=None, VAR_63=None, VAR_64=None, VAR_65=None, VAR_66=None, VAR_67=None, ): if VAR_64 is None: VAR_64 = [] def FUNC_36(): return FUNC_2(VAR_8, VAR_15=additional_key_data) def FUNC_37(): if callable(VAR_65): try: VAR_33 = VAR_65() if VAR_33: return VAR_33 except Exception: VAR_0.exception( "Error while trying to retrieve tracked VAR_33 for VAR_132 {}".format( VAR_8 ) ) VAR_33 = FUNC_21() VAR_33 += FUNC_22() VAR_33 += FUNC_23( g.locale.language if g.locale else "en", "messages" ) if callable(VAR_63): try: VAR_144 = VAR_63() if VAR_144: VAR_33 += VAR_144 except Exception: VAR_0.exception( "Error while trying to retrieve VAR_103 tracked VAR_33 for VAR_132 {}".format( VAR_8 ) ) return sorted(set(VAR_33)) def FUNC_38(VAR_33): if callable(VAR_67): try: VAR_34 = VAR_67() if VAR_34: return VAR_34 except Exception: VAR_0.exception( "Error while trying to retrieve custom LastModified VAR_89 for VAR_132 {}".format( VAR_8 ) ) return FUNC_19(VAR_33) def FUNC_39(VAR_33, VAR_34, VAR_103=None): if callable(VAR_66): try: VAR_145 = VAR_66() if VAR_145: return VAR_145 except Exception: VAR_0.exception( "Error while trying to retrieve custom ETag VAR_89 for VAR_132 {}".format( VAR_8 ) ) if VAR_34 and not isinstance(VAR_34, str): from werkzeug.http import http_date VAR_34 = http_date(VAR_34) if VAR_103 is None: VAR_103 = [] import .hashlib VAR_88 = hashlib.sha1() def FUNC_32(VAR_89): VAR_88.update(to_bytes(VAR_89, encoding="utf-8", errors="replace")) FUNC_32(octoprint.__version__) FUNC_32(get_python_version_string()) FUNC_32(",".join(sorted(VAR_33))) if VAR_34: FUNC_32(VAR_34) for add in VAR_103: FUNC_32(add) return VAR_88.hexdigest() VAR_104 = FUNC_37() VAR_105 = FUNC_38(VAR_104) VAR_106 = FUNC_39( VAR_33=VAR_104, VAR_34=VAR_105, VAR_103=[FUNC_36()] + VAR_64, ) def FUNC_40(): VAR_92 = util.flask.check_lastmodified(VAR_105) VAR_91 = util.flask.check_etag(VAR_106) return VAR_92 and VAR_91 def FUNC_41(VAR_107): return VAR_52 or (VAR_106 != VAR_107.get_etag()[0]) VAR_108 = VAR_62 VAR_108 = util.flask.lastmodified(lambda _: VAR_105)( VAR_108 ) VAR_108 = util.flask.etagged(lambda _: VAR_106)(VAR_108) VAR_108 = util.flask.cached( timeout=-1, refreshif=FUNC_41, VAR_8=FUNC_36, unless_response=lambda VAR_46: util.flask.cache_check_response_headers( VAR_46 ) or util.flask.cache_check_status_code(VAR_46, FUNC_3), )(VAR_108) VAR_108 = util.flask.with_client_revalidation(VAR_108) VAR_108 = util.flask.conditional( FUNC_40, NOT_MODIFIED )(VAR_108) return VAR_108 def FUNC_29(VAR_68): VAR_107 = FUNC_28( VAR_68._identifier, VAR_68.on_ui_render, VAR_15=VAR_68.get_ui_additional_key_data_for_cache, VAR_63=VAR_68.get_ui_additional_tracked_files, VAR_65=VAR_68.get_ui_custom_tracked_files, VAR_66=VAR_68.get_ui_custom_etag, VAR_67=VAR_68.get_ui_custom_lastmodified, VAR_64=VAR_68.get_ui_additional_etag(VAR_61), ) if VAR_48 and VAR_68.get_ui_preemptive_caching_enabled(): VAR_62 = FUNC_27( VAR_68._identifier, VAR_107, VAR_68.get_ui_data_for_preemptive_caching, VAR_68.get_ui_additional_request_data_for_preemptive_caching, VAR_68.get_ui_preemptive_caching_additional_unless, ) else: VAR_62 = VAR_107 VAR_30 = VAR_68.get_ui_custom_template_filter(FUNC_26) if VAR_30 is not None and callable(VAR_30): VAR_84 = FUNC_13(VAR_1[VAR_14], VAR_30) else: VAR_84 = VAR_1[VAR_14] VAR_45 = FUNC_9( VAR_84, VAR_2, VAR_3, VAR_21 ) return VAR_62(VAR_21, request, VAR_45) def FUNC_30(): VAR_84 = FUNC_13( VAR_1[VAR_14], FUNC_26 ) VAR_109 = FUNC_25(VAR_84) VAR_110 = userManager.has_been_customized() VAR_45 = FUNC_9( VAR_84, VAR_2, VAR_3, VAR_21 ) VAR_45.update( { "enableWebcam": VAR_56, "enableTemperatureGraph": VAR_57, "enableAccessControl": True, "accessControlActive": VAR_110, "enableLoadingAnimation": VAR_54, "enableSdSupport": VAR_55, "sockJsConnectTimeout": VAR_58 * 1000, "wizard": VAR_109, "online": connectivityChecker.online, "now": VAR_21, } ) def FUNC_42(): VAR_131 = make_response(render_template("index.jinja2", **VAR_45)) if VAR_109: VAR_131 = util.flask.add_non_caching_response_headers(VAR_131) return VAR_131 VAR_107 = FUNC_28( "_default", FUNC_42, VAR_64=VAR_61 ) VAR_111 = FUNC_27("_default", VAR_107, {}, {}) return VAR_111() VAR_69 = [Permissions.STATUS, Permissions.SETTINGS_READ] VAR_46 = None VAR_70 = request.headers.get("X-Force-View", None) if VAR_70: VAR_0.debug(f"Forcing rendering of VAR_62 {VAR_70}") if VAR_70 != "_default": VAR_132 = pluginManager.get_plugin_info(VAR_70, require_enabled=True) if VAR_132 is not None and isinstance( VAR_132.implementation, octoprint.plugin.UiPlugin ): VAR_43 = VAR_132.implementation.get_ui_permissions() VAR_46 = require_login_with(VAR_43=permissions) if not VAR_46: VAR_46 = FUNC_29(VAR_132.implementation) if VAR_0.isEnabledFor(logging.DEBUG) and isinstance( VAR_46, Response ): VAR_46.headers[ "X-Ui-Plugin" ] = VAR_132.implementation._identifier else: VAR_46 = require_login_with(VAR_43=VAR_69) if not VAR_46: VAR_46 = FUNC_30() if VAR_0.isEnabledFor(logging.DEBUG) and isinstance(VAR_46, Response): VAR_46.headers["X-Ui-Plugin"] = "_default" else: VAR_47 = pluginManager.get_implementations( octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render" ) for VAR_132 in VAR_47: try: if VAR_132.will_handle_ui(request): VAR_43 = VAR_132.get_ui_permissions() VAR_46 = require_login_with(VAR_43=permissions) if not VAR_46: VAR_46 = FUNC_29(VAR_132) if VAR_46 is not None: if VAR_0.isEnabledFor(logging.DEBUG) and isinstance( VAR_46, Response ): VAR_46.headers["X-Ui-Plugin"] = VAR_132._identifier break else: VAR_0.warning( "UiPlugin {} returned an empty response".format( VAR_132._identifier ) ) except Exception: VAR_0.exception( "Error while calling VAR_132 {}, skipping it".format( VAR_132._identifier ), extra={"plugin": VAR_132._identifier}, ) else: VAR_46 = require_login_with(VAR_43=VAR_69) if not VAR_46: VAR_46 = FUNC_30() if VAR_0.isEnabledFor(logging.DEBUG) and isinstance(VAR_46, Response): VAR_46.headers["X-Ui-Plugin"] = "_default" if VAR_46 is None: return abort(404) return VAR_46 def FUNC_9(VAR_18, VAR_19, VAR_20, VAR_21): global VAR_0 VAR_71 = settings().getBoolean(["server", "firstRun"]) VAR_72 = {} for VAR_133 in LOCALES: try: VAR_72[VAR_133.language] = { "language": VAR_133.language, "display": VAR_133.display_name, "english": VAR_133.english_name, } except Exception: VAR_0.exception("Error while collecting available locales") VAR_43 = [permission.as_dict() for permission in Permissions.all()] VAR_73 = list(sorted(full_extension_tree().keys())) VAR_74 = list(map(lambda ext: f".{ext}", get_all_extensions())) VAR_45 = { "debug": debug, "firstRun": VAR_71, "version": {"number": VERSION, "display": DISPLAY_VERSION, "branch": BRANCH}, "python_version": get_python_version_string(), "templates": VAR_18, "pluginNames": VAR_19, "locales": VAR_72, "permissions": VAR_43, "supportedFiletypes": VAR_73, "supportedExtensions": VAR_74, } VAR_45.update(VAR_20) return VAR_45 def FUNC_10(VAR_22=False): global VAR_1, VAR_2, VAR_3 VAR_14 = g.locale.language if g.locale else "en" if ( not VAR_22 and VAR_1.get(VAR_14) is not None and VAR_2 is not None and VAR_3 is not None ): return VAR_1[VAR_14], VAR_2, VAR_3 VAR_71 = settings().getBoolean(["server", "firstRun"]) VAR_18 = defaultdict(lambda: {"order": [], "entries": {}}) VAR_75 = { "navbar": { "div": lambda VAR_138: "navbar_plugin_" + VAR_138, "template": lambda VAR_138: VAR_138 + "_navbar.jinja2", "to_entry": lambda VAR_10: data, }, "sidebar": { "div": lambda VAR_138: "sidebar_plugin_" + VAR_138, "template": lambda VAR_138: VAR_138 + "_sidebar.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "tab": { "div": lambda VAR_138: "tab_plugin_" + VAR_138, "template": lambda VAR_138: VAR_138 + "_tab.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "settings": { "div": lambda VAR_138: "settings_plugin_" + VAR_138, "template": lambda VAR_138: VAR_138 + "_settings.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "usersettings": { "div": lambda VAR_138: "usersettings_plugin_" + VAR_138, "template": lambda VAR_138: VAR_138 + "_usersettings.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "wizard": { "div": lambda VAR_138: "wizard_plugin_" + VAR_138, "template": lambda VAR_138: VAR_138 + "_wizard.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "about": { "div": lambda VAR_138: "about_plugin_" + VAR_138, "template": lambda VAR_138: VAR_138 + "_about.jinja2", "to_entry": lambda VAR_10: (VAR_10["name"], VAR_10), }, "generic": {"template": lambda VAR_138: VAR_138 + ".jinja2", "to_entry": lambda VAR_10: data}, } def FUNC_31(VAR_37, VAR_38): if VAR_37[1].get("_key", None) == "plugin_corewizard_acl": return f"0:{to_unicode(VAR_37[0])}" elif VAR_37[1].get("mandatory", False): return f"1:{to_unicode(VAR_37[0])}" else: return f"2:{to_unicode(VAR_37[0])}" VAR_76 = { "navbar": {"add": "prepend", "key": None}, "sidebar": {"add": "append", "key": "name"}, "tab": {"add": "append", "key": "name"}, "settings": { "add": "custom_append", "key": "name", "custom_add_entries": lambda VAR_113: { "section_plugins": (gettext("Plugins"), None) }, "custom_add_order": lambda VAR_113: ["section_plugins"] + VAR_113, }, "usersettings": {"add": "append", "key": "name"}, "wizard": {"add": "append", "key": "name", "key_extractor": FUNC_31}, "about": {"add": "append", "key": "name"}, "generic": {"add": "append", "key": None}, } VAR_77 = pluginManager.get_hooks("octoprint.ui.web.templatetypes") for VAR_23, VAR_17 in VAR_77.items(): try: VAR_39 = VAR_17(dict(VAR_76), dict(VAR_75)) except Exception: VAR_0.exception( f"Error while retrieving custom VAR_147 type " f"definitions from VAR_132 {VAR_23}", extra={"plugin": VAR_23}, ) else: if not isinstance(VAR_39, list): continue for entry in VAR_39: if not isinstance(entry, tuple) or not len(entry) == 3: continue VAR_8, VAR_141, VAR_27 = entry if "add" not in VAR_141: order["add"] = "prepend" if "key" not in VAR_141: order["key"] = "name" if "div" not in VAR_27: VAR_146 = f"{VAR_23}_{VAR_8}_plugin_" VAR_27["div"] = lambda VAR_138: VAR_146 + VAR_138 if "template" not in VAR_27: VAR_147 = f"_plugin_{VAR_23}_{VAR_8}.jinja2" VAR_27["template"] = lambda VAR_138: VAR_138 + VAR_147 if "to_entry" not in VAR_27: VAR_27["to_entry"] = lambda VAR_10: (VAR_10["name"], VAR_10) VAR_75["plugin_" + VAR_23 + "_" + VAR_8] = VAR_27 VAR_76["plugin_" + VAR_23 + "_" + VAR_8] = VAR_141 VAR_78 = list(VAR_75.keys()) VAR_18["navbar"]["entries"] = { "offlineindicator": { "template": "navbar/offlineindicator.jinja2", "_div": "navbar_offlineindicator", "custom_bindings": False, }, "settings": { "template": "navbar/settings.jinja2", "_div": "navbar_settings", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SETTINGS)", }, "systemmenu": { "template": "navbar/systemmenu.jinja2", "_div": "navbar_systemmenu", "classes": ["dropdown"], "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", "custom_bindings": False, }, "login": { "template": "navbar/FUNC_5.jinja2", "_div": "navbar_login", "classes": ["dropdown"], "custom_bindings": False, }, } VAR_18["sidebar"]["entries"] = { "connection": ( gettext("Connection"), { "template": "sidebar/connection.jinja2", "_div": "connection", "icon": "signal", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.CONNECTION)", "template_header": "sidebar/connection_header.jinja2", }, ), "state": ( gettext("State"), { "template": "sidebar/state.jinja2", "_div": "state", "icon": "info-circle", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.STATUS)", }, ), "files": ( gettext("Files"), { "template": "sidebar/VAR_33.jinja2", "_div": "files", "icon": "list", "classes_content": ["overflow_visible"], "template_header": "sidebar/files_header.jinja2", "styles_wrapper": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.FILES_LIST)", }, ), } VAR_18["tab"]["entries"] = { "temperature": ( gettext("Temperature"), { "template": "tabs/temperature.jinja2", "_div": "temp", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)() && visible()", }, ), "control": ( gettext("Control"), { "template": "tabs/control.jinja2", "_div": "control", "styles": ["display: none;"], "data_bind": "visible: loginState.hasAnyPermissionKo(access.permissions.WEBCAM, access.permissions.CONTROL)", }, ), "terminal": ( gettext("Terminal"), { "template": "tabs/terminal.jinja2", "_div": "term", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.MONITOR_TERMINAL)", }, ), "timelapse": ( gettext("Timelapse"), { "template": "tabs/timelapse.jinja2", "_div": "timelapse", "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.TIMELAPSE_LIST)", }, ), } VAR_18["settings"]["entries"] = { "section_printer": (gettext("Printer"), None), "serial": ( gettext("Serial Connection"), { "template": "dialogs/settings/serialconnection.jinja2", "_div": "settings_serialConnection", "custom_bindings": False, }, ), "printerprofiles": ( gettext("Printer Profiles"), { "template": "dialogs/settings/printerprofiles.jinja2", "_div": "settings_printerProfiles", "custom_bindings": False, }, ), "temperatures": ( gettext("Temperatures"), { "template": "dialogs/settings/temperatures.jinja2", "_div": "settings_temperature", "custom_bindings": False, }, ), "terminalfilters": ( gettext("Terminal Filters"), { "template": "dialogs/settings/terminalfilters.jinja2", "_div": "settings_terminalFilters", "custom_bindings": False, }, ), "gcodescripts": ( gettext("GCODE Scripts"), { "template": "dialogs/settings/gcodescripts.jinja2", "_div": "settings_gcodeScripts", "custom_bindings": False, }, ), "section_features": (gettext("Features"), None), "features": ( gettext("Features"), { "template": "dialogs/settings/features.jinja2", "_div": "settings_features", "custom_bindings": False, }, ), "webcam": ( gettext("Webcam & Timelapse"), { "template": "dialogs/settings/webcam.jinja2", "_div": "settings_webcam", "custom_bindings": False, }, ), "api": ( gettext("API"), { "template": "dialogs/settings/api.jinja2", "_div": "settings_api", "custom_bindings": False, }, ), "section_octoprint": (gettext("OctoPrint"), None), "accesscontrol": ( gettext("Access Control"), { "template": "dialogs/settings/accesscontrol.jinja2", "_div": "settings_users", "custom_bindings": False, }, ), "folders": ( gettext("Folders"), { "template": "dialogs/settings/folders.jinja2", "_div": "settings_folders", "custom_bindings": False, }, ), "appearance": ( gettext("Appearance"), { "template": "dialogs/settings/appearance.jinja2", "_div": "settings_appearance", "custom_bindings": False, }, ), "server": ( gettext("Server"), { "template": "dialogs/settings/server.jinja2", "_div": "settings_server", "custom_bindings": False, }, ), } VAR_18["usersettings"]["entries"] = { "access": ( gettext("Access"), { "template": "dialogs/usersettings/access.jinja2", "_div": "usersettings_access", "custom_bindings": False, }, ), "interface": ( gettext("Interface"), { "template": "dialogs/usersettings/interface.jinja2", "_div": "usersettings_interface", "custom_bindings": False, }, ), } if VAR_71: def FUNC_43(VAR_112, VAR_113): if "firstrunstart" in VAR_113: missing.remove("firstrunstart") if "firstrunend" in VAR_113: missing.remove("firstrunend") return ["firstrunstart"] + VAR_112 + VAR_113 + ["firstrunend"] VAR_76["wizard"].update( { "add": "custom_insert", "custom_insert_entries": lambda VAR_113: {}, "custom_insert_order": FUNC_43, } ) VAR_18["wizard"]["entries"] = { "firstrunstart": ( gettext("Start"), { "template": "dialogs/VAR_109/firstrun_start.jinja2", "_div": "wizard_firstrun_start", }, ), "firstrunend": ( gettext("Finish"), { "template": "dialogs/VAR_109/firstrun_end.jinja2", "_div": "wizard_firstrun_end", }, ), } VAR_18["about"]["entries"] = { "about": ( "About OctoPrint", { "template": "dialogs/about/about.jinja2", "_div": "about_about", "custom_bindings": False, }, ), "license": ( "OctoPrint License", { "template": "dialogs/about/license.jinja2", "_div": "about_license", "custom_bindings": False, }, ), "thirdparty": ( "Third Party Licenses", { "template": "dialogs/about/thirdparty.jinja2", "_div": "about_thirdparty", "custom_bindings": False, }, ), "authors": ( "Authors", { "template": "dialogs/about/authors.jinja2", "_div": "about_authors", "custom_bindings": False, }, ), "supporters": ( "Supporters", { "template": "dialogs/about/supporters.jinja2", "_div": "about_sponsors", "custom_bindings": False, }, ), "systeminfo": ( "System Information", { "template": "dialogs/about/systeminfo.jinja2", "_div": "about_systeminfo", "custom_bindings": False, "styles": ["display: none;"], "data_bind": "visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", }, ), } VAR_79 = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin) VAR_20 = {} VAR_19 = set() VAR_80 = {} VAR_81 = settings().get(["server", "seenWizards"]) if not VAR_71 else {} for VAR_24 in VAR_79: VAR_23 = VAR_24._identifier VAR_19.add(VAR_23) VAR_114 = False VAR_115 = False try: VAR_134 = VAR_24.get_template_vars() VAR_25 = VAR_24.get_template_configs() if isinstance(VAR_24, octoprint.plugin.WizardPlugin): VAR_114 = VAR_24.is_wizard_required() VAR_115 = octoprint.plugin.WizardPlugin.is_wizard_ignored( VAR_81, VAR_24 ) except Exception: VAR_0.exception( "Error while retrieving VAR_147 VAR_10 for VAR_132 {}, ignoring it".format( VAR_23 ), extra={"plugin": VAR_23}, ) continue if not isinstance(VAR_134, dict): VAR_134 = {} if not isinstance(VAR_25, (list, tuple)): VAR_25 = [] for VAR_135, var_value in VAR_134.items(): VAR_20["plugin_" + VAR_23 + "_" + VAR_135] = var_value try: VAR_83 = FUNC_11( VAR_23, VAR_24, VAR_25, VAR_75 ) except Exception: VAR_0.exception( "Error while processing VAR_147 VAR_25 for VAR_132 {}, ignoring it".format( VAR_23 ), extra={"plugin": VAR_23}, ) if not VAR_114 or VAR_115: VAR_83["wizard"] = list() for VAR_119 in VAR_78: VAR_80[VAR_119] = {} for include in VAR_83[VAR_119]: if VAR_119 == "navbar" or VAR_119 == "generic": VAR_10 = include else: VAR_10 = include[1] VAR_8 = VAR_10["_key"] if "replaces" in VAR_10: VAR_8 = VAR_10["replaces"] VAR_80[VAR_119][VAR_10["_key"]] = VAR_10["replaces"] VAR_18[VAR_119]["entries"][VAR_8] = include for VAR_119 in VAR_78: VAR_116 = ( settings().get( ["appearance", "components", "order", VAR_119], merged=True, VAR_28={} ) or [] ) VAR_117 = ( settings().get(["appearance", "components", "order", VAR_119], merged=True) or [] ) VAR_118 = ( settings().get(["appearance", "components", "disabled", VAR_119]) or [] ) VAR_39 = [] for VAR_138 in VAR_117: if VAR_138 in VAR_80[VAR_119]: VAR_138 = VAR_80[VAR_119][VAR_138] if ( VAR_138 in VAR_18[VAR_119]["entries"] and VAR_138 not in VAR_118 and VAR_138 not in VAR_39 ): result.append(VAR_138) VAR_18[VAR_119]["order"] = VAR_39 VAR_18[VAR_119]["order"] += [ VAR_138 for VAR_138 in VAR_116 if VAR_138 not in VAR_18[VAR_119]["order"] and VAR_138 in VAR_18[VAR_119]["entries"] and VAR_138 not in VAR_118 ] VAR_120 = set(VAR_18[VAR_119]["order"]) VAR_121 = set(VAR_118) VAR_122 = ( set(VAR_18[VAR_119]["entries"].keys()) .difference(VAR_120) .difference(VAR_121) ) if len(VAR_122) == 0: continue def FUNC_44(VAR_123, VAR_8, VAR_124=None): if isinstance(VAR_123, dict) and VAR_8 in VAR_123: return VAR_123[VAR_8] if VAR_8 in VAR_123 else VAR_124 elif ( isinstance(VAR_123, tuple) and len(VAR_123) > 1 and isinstance(VAR_123[1], dict) and VAR_8 in VAR_123[1] ): return VAR_123[1][VAR_8] if VAR_8 in VAR_123[1] else VAR_124 return VAR_124 if VAR_76[VAR_119]["key"] is not None: VAR_136 = FUNC_44 if "key_extractor" in VAR_76[VAR_119] and callable( VAR_76[VAR_119]["key_extractor"] ): def FUNC_46(VAR_136): def FUNC_47(VAR_138, VAR_38): try: return VAR_136(VAR_138, VAR_38) except Exception: VAR_0.exception( "Error while extracting sorting keys for VAR_147 {}".format( VAR_119 ) ) return None return FUNC_47 VAR_136 = FUNC_46(VAR_76[VAR_119]["key_extractor"]) VAR_137 = VAR_76[VAR_119]["key"] def FUNC_45(VAR_138): VAR_28 = VAR_18[VAR_119]["entries"][VAR_138] VAR_142 = FUNC_44(VAR_28, "order", VAR_124=None) return ( VAR_142 is None, sv(VAR_142), sv(VAR_136(VAR_28, VAR_137)), ) VAR_139 = sorted(VAR_122, VAR_8=FUNC_45) else: def FUNC_45(VAR_138): VAR_28 = VAR_18[VAR_119]["entries"][VAR_138] VAR_142 = FUNC_44(VAR_28, "order", VAR_124=None) return VAR_142 is None, sv(VAR_142) VAR_139 = sorted(VAR_122, VAR_8=FUNC_45) if VAR_76[VAR_119]["add"] == "prepend": VAR_18[VAR_119]["order"] = VAR_139 + VAR_18[VAR_119]["order"] elif VAR_76[VAR_119]["add"] == "append": VAR_18[VAR_119]["order"] += VAR_139 elif ( VAR_76[VAR_119]["add"] == "custom_prepend" and "custom_add_entries" in VAR_76[VAR_119] and "custom_add_order" in VAR_76[VAR_119] ): VAR_18[VAR_119]["entries"].update( VAR_76[VAR_119]["custom_add_entries"](VAR_139) ) VAR_18[VAR_119]["order"] = ( VAR_76[VAR_119]["custom_add_order"](VAR_139) + VAR_18[VAR_119]["order"] ) elif ( VAR_76[VAR_119]["add"] == "custom_append" and "custom_add_entries" in VAR_76[VAR_119] and "custom_add_order" in VAR_76[VAR_119] ): VAR_18[VAR_119]["entries"].update( VAR_76[VAR_119]["custom_add_entries"](VAR_139) ) VAR_18[VAR_119]["order"] += VAR_76[VAR_119]["custom_add_order"]( VAR_139 ) elif ( VAR_76[VAR_119]["add"] == "custom_insert" and "custom_insert_entries" in VAR_76[VAR_119] and "custom_insert_order" in VAR_76[VAR_119] ): VAR_18[VAR_119]["entries"].update( VAR_76[VAR_119]["custom_insert_entries"](VAR_139) ) VAR_18[VAR_119]["order"] = VAR_76[VAR_119]["custom_insert_order"]( VAR_18[VAR_119]["order"], VAR_139 ) VAR_1[VAR_14] = VAR_18 VAR_2 = VAR_19 VAR_3 = VAR_20 return VAR_18, VAR_19, VAR_20 def FUNC_11(VAR_23, VAR_24, VAR_25, VAR_26): from jinja2.exceptions import TemplateNotFound VAR_82 = defaultdict(lambda: 1) VAR_83 = defaultdict(list) for VAR_28 in VAR_25: if not isinstance(VAR_28, dict): continue if "type" not in VAR_28: continue VAR_59 = VAR_28["type"] del VAR_28["type"] if VAR_59 not in VAR_26: continue VAR_27 = VAR_26[VAR_59] VAR_10 = FUNC_12( VAR_23, VAR_24, VAR_27, VAR_28=config, VAR_29=VAR_82[VAR_59] ) if VAR_10 is None: continue VAR_83[VAR_59].append(VAR_27["to_entry"](VAR_10)) VAR_82[VAR_59] += 1 for VAR_59 in VAR_26: if len(VAR_83[VAR_59]) == 0: VAR_27 = VAR_26[VAR_59] VAR_10 = FUNC_12(VAR_23, VAR_24, VAR_27) if VAR_10 is not None: try: app.jinja_env.get_or_select_template(VAR_10["template"]) except TemplateNotFound: pass except Exception: VAR_0.exception( "Error in VAR_147 {}, not going to include it".format( VAR_10["template"] ) ) else: VAR_83[VAR_59].append(VAR_27["to_entry"](VAR_10)) return VAR_83 def FUNC_12(VAR_23, VAR_24, VAR_27, VAR_28=None, VAR_29=1): if "mandatory" in VAR_27: for mandatory in VAR_27["mandatory"]: if mandatory not in VAR_28: return None if VAR_28 is None: VAR_28 = {} VAR_10 = dict(VAR_28) if "suffix" not in VAR_10 and VAR_29 > 1: VAR_10["suffix"] = "_%d" % VAR_29 if "div" in VAR_10: VAR_10["_div"] = VAR_10["div"] elif "div" in VAR_27: VAR_10["_div"] = VAR_27["div"](VAR_23) if "suffix" in VAR_10: VAR_10["_div"] = VAR_10["_div"] + VAR_10["suffix"] if not VAR_5.match(VAR_10["_div"]): VAR_0.warning( "Template VAR_28 {} contains invalid VAR_146 identifier {}, skipping it".format( VAR_23, VAR_10["_div"] ) ) return None if VAR_10.get("template"): VAR_10["template"] = VAR_24.template_folder_key + "/" + VAR_10["template"] else: VAR_10["template"] = ( VAR_24.template_folder_key + "/" + VAR_27["template"](VAR_23) ) if VAR_10.get("template_header"): VAR_10["template_header"] = ( VAR_24.template_folder_key + "/" + VAR_10["template_header"] ) if "name" not in VAR_10: VAR_10["name"] = VAR_24._plugin_name if "custom_bindings" not in VAR_10 or VAR_10["custom_bindings"]: VAR_125 = "allowBindings: true" if "data_bind" in VAR_10: VAR_125 = data_bind + ", " + VAR_10["data_bind"] VAR_125 = data_bind.replace('"', '\\"') VAR_10["data_bind"] = VAR_125 VAR_10["_key"] = "plugin_" + VAR_23 if "suffix" in VAR_10: VAR_10["_key"] += VAR_10["suffix"] VAR_10["_plugin"] = VAR_23 return VAR_10 def FUNC_13(VAR_18, VAR_30): VAR_84 = {} for VAR_59, template_collection in VAR_18.items(): VAR_126 = {} for VAR_60, template_entry in template_collection["entries"].items(): if VAR_30(VAR_59, VAR_60): VAR_126[VAR_60] = template_entry VAR_84[VAR_59] = { "order": list( filter(lambda VAR_138: VAR_138 in VAR_126, template_collection["order"]) ), "entries": VAR_126, } return VAR_84 @app.route("/robots.txt") def FUNC_14(): return send_from_directory(app.static_folder, "robots.txt") @app.route("/i18n/<string:VAR_14>/<string:VAR_31>.js") @util.flask.conditional(lambda: FUNC_20(), NOT_MODIFIED) @util.flask.etagged( lambda _: FUNC_17( request.view_args["locale"], request.view_args["domain"] ) ) @util.flask.lastmodified( lambda _: FUNC_18( request.view_args["locale"], request.view_args["domain"] ) ) def FUNC_15(VAR_14, VAR_31): VAR_85 = {} VAR_86 = None if VAR_14 != "en": VAR_85, VAR_86 = FUNC_24(VAR_14, VAR_31) VAR_87 = { "messages": VAR_85, "plural_expr": VAR_86, "locale": VAR_14, "domain": VAR_31, } from flask import Response return Response( render_template("i18n.js.jinja2", VAR_87=catalog), content_type="application/VAR_138-javascript; charset=utf-8", ) @app.route("/FUNC_16/<string:VAR_23>/<VAR_9:VAR_32>") def FUNC_16(VAR_23, VAR_32): return redirect(url_for("plugin." + VAR_23 + ".static", VAR_32=filename)) def FUNC_17(VAR_14, VAR_31, VAR_33=None, VAR_34=None): if VAR_33 is None: VAR_33 = FUNC_23(VAR_14, VAR_31) if VAR_34 is None: VAR_34 = FUNC_19(VAR_33) if VAR_34 and not isinstance(VAR_34, str): from werkzeug.http import http_date VAR_34 = http_date(VAR_34) import .hashlib VAR_88 = hashlib.sha1() def FUNC_32(VAR_89): VAR_88.update(VAR_89.encode("utf-8")) FUNC_32(",".join(sorted(VAR_33))) if VAR_34: FUNC_32(VAR_34) return VAR_88.hexdigest() def FUNC_18(VAR_14, VAR_31): return FUNC_19(FUNC_23(VAR_14, VAR_31)) def FUNC_19(VAR_33): import .stat from datetime import .datetime from octoprint.util.tz import UTC_TZ VAR_90 = 0 for VAR_9 in VAR_33: try: VAR_140 = os.stat(VAR_9) if stat.S_ISREG(VAR_140.st_mode) and VAR_140.st_mtime > VAR_90: VAR_90 = VAR_140.st_mtime except Exception: continue if VAR_90: VAR_90 = ( datetime.fromtimestamp(VAR_90) .replace(microsecond=0) .replace(tzinfo=UTC_TZ) ) return VAR_90 def FUNC_20(): VAR_14 = request.view_args["locale"] VAR_31 = request.view_args["domain"] VAR_91 = util.flask.check_etag( FUNC_17(request.view_args["locale"], request.view_args["domain"]) ) VAR_34 = FUNC_18(VAR_14, VAR_31) VAR_92 = VAR_34 is None or util.flask.check_lastmodified(VAR_34) return VAR_91 and VAR_92 def FUNC_21(): from octoprint.util.jinja import get_all_template_paths return get_all_template_paths(app.jinja_loader) def FUNC_22(): from octoprint.util.jinja import get_all_asset_paths return get_all_asset_paths(app.jinja_env.assets_environment, verifyExist=False) def FUNC_23(VAR_14, VAR_31): from flask import _request_ctx_stack def FUNC_33(VAR_93, VAR_14, VAR_31): return os.path.join(VAR_93, VAR_14, "LC_MESSAGES", f"{VAR_31}.po") VAR_94 = [] VAR_95 = os.path.join( settings().getBaseFolder("translations", check_writable=False) ) VAR_96 = os.path.join(VAR_95, "_plugins") VAR_97 = octoprint.plugin.plugin_manager().enabled_plugins for VAR_23, VAR_132 in VAR_97.items(): VAR_100 = [ os.path.join(VAR_96, VAR_23), os.path.join(VAR_132.location, "translations"), ] for dirname in VAR_100: VAR_94.append(FUNC_33(dirname, VAR_14, VAR_31)) VAR_98 = _request_ctx_stack.top VAR_99 = os.path.join(VAR_98.app.root_path, "translations") VAR_100 = [VAR_95, VAR_99] for dirname in VAR_100: VAR_94.append(FUNC_33(dirname, VAR_14, VAR_31)) return VAR_94 def FUNC_24(VAR_14, VAR_31): from babel.messages.pofile import .read_po from octoprint.util import .dict_merge VAR_85 = {} VAR_86 = None def FUNC_34(VAR_9, VAR_14, VAR_31): VAR_85 = {} with open(VAR_9, encoding="utf-8") as FUNC_47: VAR_87 = read_po(FUNC_47, VAR_14=locale, VAR_31=domain) for message in VAR_87: VAR_143 = message.id if isinstance(VAR_143, (list, tuple)): VAR_143 = message_id[0] if message.string: VAR_85[VAR_143] = message.string return VAR_85, VAR_87.plural_expr VAR_94 = FUNC_23(VAR_14, VAR_31) for po_file in VAR_94: if not os.path.exists(po_file): continue VAR_127, VAR_86 = FUNC_34(po_file, VAR_14, VAR_31) if VAR_127 is not None: VAR_85 = dict_merge(VAR_85, VAR_127, in_place=True) return VAR_85, VAR_86
[ 4, 11, 23, 45, 47, 49, 53, 56, 57, 61, 67, 69, 74, 75, 83, 89, 92, 93, 108, 109, 121, 123, 124, 130, 136, 147, 148, 151, 152, 166, 167, 172, 186, 188, 193, 201, 204, 205, 208, 212, 214, 215, 222, 224, 230, 234, 243, 245, 246, 252, 253, 288, 295, 316, 317, 321, 323, 325, 327, 328, 331, 332, 346, 347, 349, 351, 360, 366, 380, 386, 390, 395, 396, 400, 413, 416, 429, 435, 447, 449, 462, 464, 477, 480, 484, 486, 488, 491, 500, 508, 513, 516, 536, 548, 559, 565, 569, 571, 576, 579, 597, 598, 602, 605, 611, 613, 615, 617, 619, 642, 644, 651, 681, 685, 686, 689, 690, 691, 693, 704, 708, 709, 710, 724, 726, 727, 730, 732, 740, 742, 743, 744, 746, 747, 786, 787, 790, 791, 792, 795, 798, 800, 818, 832, 836, 838, 839, 844, 845, 847, 851, 855, 857, 861, 862, 863, 891, 892, 893, 929, 930, 931, 970, 971, 972, 1074, 1075, 1076, 1095, 1096, 1097, 1099, 1105, 1107, 1131, 1132, 1133, 1186, 1187, 1188, 1190, 1200, 1217, 1222, 1225, 1237, 1240, 1248, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1274, 1275, 1287, 1288, 1296, 1299, 1300, 1308, 1309, 1310, 1321, 1323, 1324, 1326, 1328, 1329, 1333, 1345, 1347, 1349, 1351, 1360, 1363, 1368, 1370, 1409, 1413, 1415, 1416, 1419, 1422, 1428, 1431, 1435, 1441, 1444, 1447, 1463, 1465, 1466, 1472, 1476, 1479, 1493, 1500, 1505, 1508, 1515, 1519, 1521, 1523, 1524, 1539, 1540, 1544, 1545, 1561, 1564, 1571, 1573, 1578, 1579, 1583, 1584, 1592, 1594, 1596, 1598, 1601, 1606, 1607, 1610, 1611, 1613, 1616, 1618, 1622, 1625, 1628, 1630, 1632, 1639, 1640, 1644, 1648, 1651, 1653, 1654, 1657, 1659, 1660, 1663, 1665, 1666, 1669, 1672, 1674, 1679, 1680, 1689, 1690, 1693, 1697, 1699, 1700, 1703, 1705, 1708, 1713, 1720, 1722, 1730, 1732 ]
[ 4, 12, 24, 46, 48, 50, 54, 57, 58, 62, 68, 70, 75, 76, 84, 90, 93, 94, 109, 110, 122, 124, 125, 131, 137, 148, 149, 152, 153, 167, 168, 173, 176, 183, 196, 198, 203, 211, 214, 215, 218, 222, 224, 225, 232, 234, 240, 244, 253, 255, 256, 262, 263, 298, 305, 326, 327, 331, 333, 335, 337, 338, 341, 342, 356, 357, 359, 361, 370, 376, 390, 396, 400, 405, 406, 410, 423, 426, 439, 445, 457, 459, 472, 474, 487, 490, 494, 496, 498, 501, 510, 518, 523, 526, 546, 558, 569, 575, 579, 581, 586, 589, 607, 608, 612, 615, 621, 623, 625, 627, 629, 652, 654, 661, 691, 695, 696, 699, 700, 701, 703, 714, 718, 719, 720, 734, 736, 737, 740, 742, 750, 752, 753, 754, 756, 757, 796, 797, 800, 801, 802, 805, 808, 810, 828, 842, 846, 848, 849, 854, 855, 857, 861, 865, 867, 871, 872, 873, 901, 902, 903, 939, 940, 941, 980, 981, 982, 1084, 1085, 1086, 1105, 1106, 1107, 1109, 1115, 1117, 1141, 1142, 1143, 1196, 1197, 1198, 1200, 1210, 1227, 1232, 1235, 1247, 1250, 1258, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1284, 1285, 1297, 1298, 1306, 1309, 1310, 1318, 1319, 1320, 1331, 1333, 1334, 1336, 1338, 1339, 1343, 1355, 1357, 1359, 1361, 1370, 1373, 1378, 1380, 1419, 1423, 1425, 1426, 1429, 1432, 1438, 1441, 1445, 1451, 1454, 1457, 1473, 1475, 1476, 1482, 1486, 1489, 1503, 1510, 1515, 1518, 1525, 1529, 1531, 1533, 1534, 1549, 1550, 1554, 1555, 1571, 1574, 1581, 1583, 1588, 1589, 1593, 1594, 1602, 1604, 1606, 1608, 1611, 1616, 1617, 1620, 1621, 1623, 1626, 1628, 1632, 1635, 1638, 1640, 1642, 1649, 1650, 1654, 1658, 1661, 1663, 1664, 1667, 1669, 1670, 1673, 1675, 1676, 1679, 1682, 1684, 1689, 1690, 1699, 1700, 1703, 1707, 1709, 1710, 1713, 1715, 1718, 1723, 1730, 1732, 1740, 1742 ]
2CWE-89
import operator from functools import partial from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Tuple from pypika import Table from pypika.functions import Upper from pypika.terms import BasicCriterion, Criterion, Equality, Term, ValueWrapper from tortoise.fields import Field from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstance if TYPE_CHECKING: # pragma: nocoverage from tortoise.models import Model ############################################################################## # Encoders # Should be type: (Any, instance: "Model", field: Field) -> type: ############################################################################## def list_encoder(values: Iterable[Any], instance: "Model", field: Field) -> list: """Encodes an iterable of a given field into a database-compatible format.""" return [field.to_db_value(element, instance) for element in values] def related_list_encoder(values: Iterable[Any], instance: "Model", field: Field) -> list: return [ field.to_db_value(element.pk if hasattr(element, "pk") else element, instance) for element in values ] def bool_encoder(value: Any, instance: "Model", field: Field) -> bool: return bool(value) def string_encoder(value: Any, instance: "Model", field: Field) -> str: return str(value) ############################################################################## # Operators # Should be type: (field: Term, value: Any) -> Criterion: ############################################################################## def is_in(field: Term, value: Any) -> Criterion: if value: return field.isin(value) # SQL has no False, so we return 1=0 return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(0)) def not_in(field: Term, value: Any) -> Criterion: if value: return field.notin(value) | field.isnull() # SQL has no True, so we return 1=1 return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(1)) def between_and(field: Term, value: Tuple[Any, Any]) -> Criterion: return field.between(value[0], value[1]) def not_equal(field: Term, value: Any) -> Criterion: return field.ne(value) | field.isnull() def is_null(field: Term, value: Any) -> Criterion: if value: return field.isnull() return field.notnull() def not_null(field: Term, value: Any) -> Criterion: if value: return field.notnull() return field.isnull() def contains(field: Term, value: str) -> Criterion: return field.like(f"%{value}%") def starts_with(field: Term, value: str) -> Criterion: return field.like(f"{value}%") def ends_with(field: Term, value: str) -> Criterion: return field.like(f"%{value}") def insensitive_exact(field: Term, value: str) -> Criterion: return Upper(field).eq(Upper(f"{value}")) def insensitive_contains(field: Term, value: str) -> Criterion: return Upper(field).like(Upper(f"%{value}%")) def insensitive_starts_with(field: Term, value: str) -> Criterion: return Upper(field).like(Upper(f"{value}%")) def insensitive_ends_with(field: Term, value: str) -> Criterion: return Upper(field).like(Upper(f"%{value}")) ############################################################################## # Filter resolvers ############################################################################## def get_m2m_filters(field_name: str, field: ManyToManyFieldInstance) -> Dict[str, dict]: target_table_pk = field.related_model._meta.pk return { field_name: { "field": field.forward_key, "backward_key": field.backward_key, "operator": operator.eq, "table": Table(field.through), "value_encoder": target_table_pk.to_db_value, }, f"{field_name}__not": { "field": field.forward_key, "backward_key": field.backward_key, "operator": not_equal, "table": Table(field.through), "value_encoder": target_table_pk.to_db_value, }, f"{field_name}__in": { "field": field.forward_key, "backward_key": field.backward_key, "operator": is_in, "table": Table(field.through), "value_encoder": partial(related_list_encoder, field=target_table_pk), }, f"{field_name}__not_in": { "field": field.forward_key, "backward_key": field.backward_key, "operator": not_in, "table": Table(field.through), "value_encoder": partial(related_list_encoder, field=target_table_pk), }, } def get_backward_fk_filters(field_name: str, field: BackwardFKRelation) -> Dict[str, dict]: target_table_pk = field.related_model._meta.pk return { field_name: { "field": field.related_model._meta.pk_attr, "backward_key": field.relation_field, "operator": operator.eq, "table": Table(field.related_model._meta.db_table), "value_encoder": target_table_pk.to_db_value, }, f"{field_name}__not": { "field": field.related_model._meta.pk_attr, "backward_key": field.relation_field, "operator": not_equal, "table": Table(field.related_model._meta.db_table), "value_encoder": target_table_pk.to_db_value, }, f"{field_name}__in": { "field": field.related_model._meta.pk_attr, "backward_key": field.relation_field, "operator": is_in, "table": Table(field.related_model._meta.db_table), "value_encoder": partial(related_list_encoder, field=target_table_pk), }, f"{field_name}__not_in": { "field": field.related_model._meta.pk_attr, "backward_key": field.relation_field, "operator": not_in, "table": Table(field.related_model._meta.db_table), "value_encoder": partial(related_list_encoder, field=target_table_pk), }, } def get_filters_for_field( field_name: str, field: Optional[Field], source_field: str ) -> Dict[str, dict]: if isinstance(field, ManyToManyFieldInstance): return get_m2m_filters(field_name, field) if isinstance(field, BackwardFKRelation): return get_backward_fk_filters(field_name, field) actual_field_name = field_name if field_name == "pk" and field: actual_field_name = field.model_field_name return { field_name: { "field": actual_field_name, "source_field": source_field, "operator": operator.eq, }, f"{field_name}__not": { "field": actual_field_name, "source_field": source_field, "operator": not_equal, }, f"{field_name}__in": { "field": actual_field_name, "source_field": source_field, "operator": is_in, "value_encoder": list_encoder, }, f"{field_name}__not_in": { "field": actual_field_name, "source_field": source_field, "operator": not_in, "value_encoder": list_encoder, }, f"{field_name}__isnull": { "field": actual_field_name, "source_field": source_field, "operator": is_null, "value_encoder": bool_encoder, }, f"{field_name}__not_isnull": { "field": actual_field_name, "source_field": source_field, "operator": not_null, "value_encoder": bool_encoder, }, f"{field_name}__gte": { "field": actual_field_name, "source_field": source_field, "operator": operator.ge, }, f"{field_name}__lte": { "field": actual_field_name, "source_field": source_field, "operator": operator.le, }, f"{field_name}__gt": { "field": actual_field_name, "source_field": source_field, "operator": operator.gt, }, f"{field_name}__lt": { "field": actual_field_name, "source_field": source_field, "operator": operator.lt, }, f"{field_name}__range": { "field": actual_field_name, "source_field": source_field, "operator": between_and, "value_encoder": list_encoder, }, f"{field_name}__contains": { "field": actual_field_name, "source_field": source_field, "operator": contains, "value_encoder": string_encoder, }, f"{field_name}__startswith": { "field": actual_field_name, "source_field": source_field, "operator": starts_with, "value_encoder": string_encoder, }, f"{field_name}__endswith": { "field": actual_field_name, "source_field": source_field, "operator": ends_with, "value_encoder": string_encoder, }, f"{field_name}__iexact": { "field": actual_field_name, "source_field": source_field, "operator": insensitive_exact, "value_encoder": string_encoder, }, f"{field_name}__icontains": { "field": actual_field_name, "source_field": source_field, "operator": insensitive_contains, "value_encoder": string_encoder, }, f"{field_name}__istartswith": { "field": actual_field_name, "source_field": source_field, "operator": insensitive_starts_with, "value_encoder": string_encoder, }, f"{field_name}__iendswith": { "field": actual_field_name, "source_field": source_field, "operator": insensitive_ends_with, "value_encoder": string_encoder, }, }
import operator from functools import partial from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Tuple from pypika import Table from pypika.functions import Upper from pypika.terms import ( BasicCriterion, Criterion, Enum, Equality, Term, ValueWrapper, basestring, date, format_quotes, ) from tortoise.fields import Field from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstance if TYPE_CHECKING: # pragma: nocoverage from tortoise.models import Model ############################################################################## # Here we monkey-patch PyPika Valuewrapper to behave differently for MySQL ############################################################################## def get_value_sql(self, **kwargs): # pragma: nocoverage quote_char = kwargs.get("secondary_quote_char") or "" dialect = kwargs.get("dialect") if dialect: dialect = dialect.value if isinstance(self.value, Term): return self.value.get_sql(**kwargs) if isinstance(self.value, Enum): return self.value.value if isinstance(self.value, date): value = self.value.isoformat() return format_quotes(value, quote_char) if isinstance(self.value, basestring): value = self.value.replace(quote_char, quote_char * 2) if dialect == "mysql": value = value.replace("\\", "\\\\") return format_quotes(value, quote_char) if isinstance(self.value, bool): return str.lower(str(self.value)) if self.value is None: return "null" return str(self.value) ValueWrapper.get_value_sql = get_value_sql ############################################################################## class Like(BasicCriterion): # type: ignore def __init__(self, left, right, alias=None, escape=" ESCAPE '\\'") -> None: """ A Like that supports an ESCAPE clause """ super().__init__(" LIKE ", left, right, alias=alias) self.escape = escape def get_sql(self, quote_char='"', with_alias=False, **kwargs): sql = "{left}{comparator}{right}{escape}".format( comparator=self.comparator, left=self.left.get_sql(quote_char=quote_char, **kwargs), right=self.right.get_sql(quote_char=quote_char, **kwargs), escape=self.escape, ) if with_alias and self.alias: # pragma: nocoverage return '{sql} "{alias}"'.format(sql=sql, alias=self.alias) return sql def escape_val(val: Any) -> Any: if isinstance(val, str): print(val) return val.replace("\\", "\\\\") return val def escape_like(val: str) -> str: return val.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") ############################################################################## # Encoders # Should be type: (Any, instance: "Model", field: Field) -> type: ############################################################################## def list_encoder(values: Iterable[Any], instance: "Model", field: Field) -> list: """Encodes an iterable of a given field into a database-compatible format.""" return [field.to_db_value(element, instance) for element in values] def related_list_encoder(values: Iterable[Any], instance: "Model", field: Field) -> list: return [ field.to_db_value(element.pk if hasattr(element, "pk") else element, instance) for element in values ] def bool_encoder(value: Any, instance: "Model", field: Field) -> bool: return bool(value) def string_encoder(value: Any, instance: "Model", field: Field) -> str: return str(value) ############################################################################## # Operators # Should be type: (field: Term, value: Any) -> Criterion: ############################################################################## def is_in(field: Term, value: Any) -> Criterion: if value: return field.isin(value) # SQL has no False, so we return 1=0 return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(0)) def not_in(field: Term, value: Any) -> Criterion: if value: return field.notin(value) | field.isnull() # SQL has no True, so we return 1=1 return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(1)) def between_and(field: Term, value: Tuple[Any, Any]) -> Criterion: return field.between(value[0], value[1]) def not_equal(field: Term, value: Any) -> Criterion: return field.ne(value) | field.isnull() def is_null(field: Term, value: Any) -> Criterion: if value: return field.isnull() return field.notnull() def not_null(field: Term, value: Any) -> Criterion: if value: return field.notnull() return field.isnull() def contains(field: Term, value: str) -> Criterion: return Like(field, field.wrap_constant(f"%{escape_like(value)}%")) def starts_with(field: Term, value: str) -> Criterion: return Like(field, field.wrap_constant(f"{escape_like(value)}%")) def ends_with(field: Term, value: str) -> Criterion: return Like(field, field.wrap_constant(f"%{escape_like(value)}")) def insensitive_exact(field: Term, value: str) -> Criterion: return Upper(field).eq(Upper(str(value))) def insensitive_contains(field: Term, value: str) -> Criterion: return Like(Upper(field), field.wrap_constant(Upper(f"%{escape_like(value)}%"))) def insensitive_starts_with(field: Term, value: str) -> Criterion: return Like(Upper(field), field.wrap_constant(Upper(f"{escape_like(value)}%"))) def insensitive_ends_with(field: Term, value: str) -> Criterion: return Like(Upper(field), field.wrap_constant(Upper(f"%{escape_like(value)}"))) ############################################################################## # Filter resolvers ############################################################################## def get_m2m_filters(field_name: str, field: ManyToManyFieldInstance) -> Dict[str, dict]: target_table_pk = field.related_model._meta.pk return { field_name: { "field": field.forward_key, "backward_key": field.backward_key, "operator": operator.eq, "table": Table(field.through), "value_encoder": target_table_pk.to_db_value, }, f"{field_name}__not": { "field": field.forward_key, "backward_key": field.backward_key, "operator": not_equal, "table": Table(field.through), "value_encoder": target_table_pk.to_db_value, }, f"{field_name}__in": { "field": field.forward_key, "backward_key": field.backward_key, "operator": is_in, "table": Table(field.through), "value_encoder": partial(related_list_encoder, field=target_table_pk), }, f"{field_name}__not_in": { "field": field.forward_key, "backward_key": field.backward_key, "operator": not_in, "table": Table(field.through), "value_encoder": partial(related_list_encoder, field=target_table_pk), }, } def get_backward_fk_filters(field_name: str, field: BackwardFKRelation) -> Dict[str, dict]: target_table_pk = field.related_model._meta.pk return { field_name: { "field": field.related_model._meta.pk_attr, "backward_key": field.relation_field, "operator": operator.eq, "table": Table(field.related_model._meta.db_table), "value_encoder": target_table_pk.to_db_value, }, f"{field_name}__not": { "field": field.related_model._meta.pk_attr, "backward_key": field.relation_field, "operator": not_equal, "table": Table(field.related_model._meta.db_table), "value_encoder": target_table_pk.to_db_value, }, f"{field_name}__in": { "field": field.related_model._meta.pk_attr, "backward_key": field.relation_field, "operator": is_in, "table": Table(field.related_model._meta.db_table), "value_encoder": partial(related_list_encoder, field=target_table_pk), }, f"{field_name}__not_in": { "field": field.related_model._meta.pk_attr, "backward_key": field.relation_field, "operator": not_in, "table": Table(field.related_model._meta.db_table), "value_encoder": partial(related_list_encoder, field=target_table_pk), }, } def get_filters_for_field( field_name: str, field: Optional[Field], source_field: str ) -> Dict[str, dict]: if isinstance(field, ManyToManyFieldInstance): return get_m2m_filters(field_name, field) if isinstance(field, BackwardFKRelation): return get_backward_fk_filters(field_name, field) actual_field_name = field_name if field_name == "pk" and field: actual_field_name = field.model_field_name return { field_name: { "field": actual_field_name, "source_field": source_field, "operator": operator.eq, }, f"{field_name}__not": { "field": actual_field_name, "source_field": source_field, "operator": not_equal, }, f"{field_name}__in": { "field": actual_field_name, "source_field": source_field, "operator": is_in, "value_encoder": list_encoder, }, f"{field_name}__not_in": { "field": actual_field_name, "source_field": source_field, "operator": not_in, "value_encoder": list_encoder, }, f"{field_name}__isnull": { "field": actual_field_name, "source_field": source_field, "operator": is_null, "value_encoder": bool_encoder, }, f"{field_name}__not_isnull": { "field": actual_field_name, "source_field": source_field, "operator": not_null, "value_encoder": bool_encoder, }, f"{field_name}__gte": { "field": actual_field_name, "source_field": source_field, "operator": operator.ge, }, f"{field_name}__lte": { "field": actual_field_name, "source_field": source_field, "operator": operator.le, }, f"{field_name}__gt": { "field": actual_field_name, "source_field": source_field, "operator": operator.gt, }, f"{field_name}__lt": { "field": actual_field_name, "source_field": source_field, "operator": operator.lt, }, f"{field_name}__range": { "field": actual_field_name, "source_field": source_field, "operator": between_and, "value_encoder": list_encoder, }, f"{field_name}__contains": { "field": actual_field_name, "source_field": source_field, "operator": contains, "value_encoder": string_encoder, }, f"{field_name}__startswith": { "field": actual_field_name, "source_field": source_field, "operator": starts_with, "value_encoder": string_encoder, }, f"{field_name}__endswith": { "field": actual_field_name, "source_field": source_field, "operator": ends_with, "value_encoder": string_encoder, }, f"{field_name}__iexact": { "field": actual_field_name, "source_field": source_field, "operator": insensitive_exact, "value_encoder": string_encoder, }, f"{field_name}__icontains": { "field": actual_field_name, "source_field": source_field, "operator": insensitive_contains, "value_encoder": string_encoder, }, f"{field_name}__istartswith": { "field": actual_field_name, "source_field": source_field, "operator": insensitive_starts_with, "value_encoder": string_encoder, }, f"{field_name}__iendswith": { "field": actual_field_name, "source_field": source_field, "operator": insensitive_ends_with, "value_encoder": string_encoder, }, }
sql
{ "code": [ "from pypika.terms import BasicCriterion, Criterion, Equality, Term, ValueWrapper", " return field.like(f\"%{value}%\")", " return field.like(f\"{value}%\")", " return field.like(f\"%{value}\")", " return Upper(field).eq(Upper(f\"{value}\"))", " return Upper(field).like(Upper(f\"%{value}%\"))", " return Upper(field).like(Upper(f\"{value}%\"))", " return Upper(field).like(Upper(f\"%{value}\"))" ], "line_no": [ 7, 82, 86, 90, 94, 98, 102, 106 ] }
{ "code": [ "from pypika.terms import (", " Criterion,", " Enum,", " Term,", " ValueWrapper,", " date,", ")", " dialect = kwargs.get(\"dialect\")", " if dialect:", " dialect = dialect.value", " return self.value.get_sql(**kwargs)", " if isinstance(self.value, Enum):", " if isinstance(self.value, date):", " return format_quotes(value, quote_char)", " value = self.value.replace(quote_char, quote_char * 2)", " value = value.replace(\"\\\\\", \"\\\\\\\\\")", " return format_quotes(value, quote_char)", " if isinstance(self.value, bool):", " return str.lower(str(self.value))", " return \"null\"", "ValueWrapper.get_value_sql = get_value_sql", " \"\"\"", " A Like that supports an ESCAPE clause", " super().__init__(\" LIKE \", left, right, alias=alias)", " self.escape = escape", " sql = \"{left}{comparator}{right}{escape}\".format(", " comparator=self.comparator,", " left=self.left.get_sql(quote_char=quote_char, **kwargs),", " right=self.right.get_sql(quote_char=quote_char, **kwargs),", " escape=self.escape,", " return '{sql} \"{alias}\"'.format(sql=sql, alias=self.alias)", " return sql", " if isinstance(val, str):", " print(val)", " return val.replace(\"\\\\\", \"\\\\\\\\\")", "def escape_like(val: str) -> str:", " return Like(field, field.wrap_constant(f\"%{escape_like(value)}%\"))", " return Like(field, field.wrap_constant(f\"{escape_like(value)}%\"))", " return Like(field, field.wrap_constant(f\"%{escape_like(value)}\"))", " return Upper(field).eq(Upper(str(value)))", " return Like(Upper(field), field.wrap_constant(Upper(f\"%{escape_like(value)}%\")))", " return Like(Upper(field), field.wrap_constant(Upper(f\"{escape_like(value)}%\")))" ], "line_no": [ 7, 9, 10, 12, 13, 15, 17, 32, 33, 34, 37, 38, 40, 42, 44, 46, 47, 48, 49, 51, 55, 61, 62, 64, 65, 68, 69, 70, 71, 72, 75, 76, 80, 81, 82, 86, 157, 161, 165, 169, 173, 177 ] }
import operator from functools import partial from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Tuple from pypika import Table from pypika.functions import Upper from pypika.terms import BasicCriterion, Criterion, Equality, Term, ValueWrapper from tortoise.fields import Field from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstance if TYPE_CHECKING: # pragma: nocoverage from tortoise.models import Model def FUNC_0(VAR_0: Iterable[Any], VAR_1: "Model", VAR_2: Field) -> list: return [VAR_2.to_db_value(element, VAR_1) for element in VAR_0] def FUNC_1(VAR_0: Iterable[Any], VAR_1: "Model", VAR_2: Field) -> list: return [ VAR_2.to_db_value(element.pk if hasattr(element, "pk") else element, VAR_1) for element in VAR_0 ] def FUNC_2(VAR_3: Any, VAR_1: "Model", VAR_2: Field) -> bool: return bool(VAR_3) def FUNC_3(VAR_3: Any, VAR_1: "Model", VAR_2: Field) -> str: return str(VAR_3) def FUNC_4(VAR_2: Term, VAR_3: Any) -> Criterion: if VAR_3: return VAR_2.isin(VAR_3) return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(0)) def FUNC_5(VAR_2: Term, VAR_3: Any) -> Criterion: if VAR_3: return VAR_2.notin(VAR_3) | VAR_2.isnull() return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(1)) def FUNC_6(VAR_2: Term, VAR_3: Tuple[Any, Any]) -> Criterion: return VAR_2.between(VAR_3[0], VAR_3[1]) def FUNC_7(VAR_2: Term, VAR_3: Any) -> Criterion: return VAR_2.ne(VAR_3) | VAR_2.isnull() def FUNC_8(VAR_2: Term, VAR_3: Any) -> Criterion: if VAR_3: return VAR_2.isnull() return VAR_2.notnull() def FUNC_9(VAR_2: Term, VAR_3: Any) -> Criterion: if VAR_3: return VAR_2.notnull() return VAR_2.isnull() def FUNC_10(VAR_2: Term, VAR_3: str) -> Criterion: return VAR_2.like(f"%{VAR_3}%") def FUNC_11(VAR_2: Term, VAR_3: str) -> Criterion: return VAR_2.like(f"{VAR_3}%") def FUNC_12(VAR_2: Term, VAR_3: str) -> Criterion: return VAR_2.like(f"%{VAR_3}") def FUNC_13(VAR_2: Term, VAR_3: str) -> Criterion: return Upper(VAR_2).eq(Upper(f"{VAR_3}")) def FUNC_14(VAR_2: Term, VAR_3: str) -> Criterion: return Upper(VAR_2).like(Upper(f"%{VAR_3}%")) def FUNC_15(VAR_2: Term, VAR_3: str) -> Criterion: return Upper(VAR_2).like(Upper(f"{VAR_3}%")) def FUNC_16(VAR_2: Term, VAR_3: str) -> Criterion: return Upper(VAR_2).like(Upper(f"%{VAR_3}")) def FUNC_17(VAR_4: str, VAR_2: ManyToManyFieldInstance) -> Dict[str, dict]: VAR_6 = VAR_2.related_model._meta.pk return { VAR_4: { "field": VAR_2.forward_key, "backward_key": VAR_2.backward_key, "operator": operator.eq, "table": Table(VAR_2.through), "value_encoder": VAR_6.to_db_value, }, f"{VAR_4}__not": { "field": VAR_2.forward_key, "backward_key": VAR_2.backward_key, "operator": FUNC_7, "table": Table(VAR_2.through), "value_encoder": VAR_6.to_db_value, }, f"{VAR_4}__in": { "field": VAR_2.forward_key, "backward_key": VAR_2.backward_key, "operator": FUNC_4, "table": Table(VAR_2.through), "value_encoder": partial(FUNC_1, VAR_2=VAR_6), }, f"{VAR_4}__not_in": { "field": VAR_2.forward_key, "backward_key": VAR_2.backward_key, "operator": FUNC_5, "table": Table(VAR_2.through), "value_encoder": partial(FUNC_1, VAR_2=VAR_6), }, } def FUNC_18(VAR_4: str, VAR_2: BackwardFKRelation) -> Dict[str, dict]: VAR_6 = VAR_2.related_model._meta.pk return { VAR_4: { "field": VAR_2.related_model._meta.pk_attr, "backward_key": VAR_2.relation_field, "operator": operator.eq, "table": Table(VAR_2.related_model._meta.db_table), "value_encoder": VAR_6.to_db_value, }, f"{VAR_4}__not": { "field": VAR_2.related_model._meta.pk_attr, "backward_key": VAR_2.relation_field, "operator": FUNC_7, "table": Table(VAR_2.related_model._meta.db_table), "value_encoder": VAR_6.to_db_value, }, f"{VAR_4}__in": { "field": VAR_2.related_model._meta.pk_attr, "backward_key": VAR_2.relation_field, "operator": FUNC_4, "table": Table(VAR_2.related_model._meta.db_table), "value_encoder": partial(FUNC_1, VAR_2=VAR_6), }, f"{VAR_4}__not_in": { "field": VAR_2.related_model._meta.pk_attr, "backward_key": VAR_2.relation_field, "operator": FUNC_5, "table": Table(VAR_2.related_model._meta.db_table), "value_encoder": partial(FUNC_1, VAR_2=VAR_6), }, } def FUNC_19( VAR_4: str, VAR_2: Optional[Field], VAR_5: str ) -> Dict[str, dict]: if isinstance(VAR_2, ManyToManyFieldInstance): return FUNC_17(VAR_4, VAR_2) if isinstance(VAR_2, BackwardFKRelation): return FUNC_18(VAR_4, VAR_2) VAR_7 = VAR_4 if VAR_4 == "pk" and VAR_2: VAR_7 = VAR_2.model_field_name return { VAR_4: { "field": VAR_7, "source_field": VAR_5, "operator": operator.eq, }, f"{VAR_4}__not": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_7, }, f"{VAR_4}__in": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_4, "value_encoder": FUNC_0, }, f"{VAR_4}__not_in": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_5, "value_encoder": FUNC_0, }, f"{VAR_4}__isnull": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_8, "value_encoder": FUNC_2, }, f"{VAR_4}__not_isnull": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_9, "value_encoder": FUNC_2, }, f"{VAR_4}__gte": { "field": VAR_7, "source_field": VAR_5, "operator": operator.ge, }, f"{VAR_4}__lte": { "field": VAR_7, "source_field": VAR_5, "operator": operator.le, }, f"{VAR_4}__gt": { "field": VAR_7, "source_field": VAR_5, "operator": operator.gt, }, f"{VAR_4}__lt": { "field": VAR_7, "source_field": VAR_5, "operator": operator.lt, }, f"{VAR_4}__range": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_6, "value_encoder": FUNC_0, }, f"{VAR_4}__contains": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_10, "value_encoder": FUNC_3, }, f"{VAR_4}__startswith": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_11, "value_encoder": FUNC_3, }, f"{VAR_4}__endswith": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_12, "value_encoder": FUNC_3, }, f"{VAR_4}__iexact": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_13, "value_encoder": FUNC_3, }, f"{VAR_4}__icontains": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_14, "value_encoder": FUNC_3, }, f"{VAR_4}__istartswith": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_15, "value_encoder": FUNC_3, }, f"{VAR_4}__iendswith": { "field": VAR_7, "source_field": VAR_5, "operator": FUNC_16, "value_encoder": FUNC_3, }, }
import operator from functools import partial from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Tuple from pypika import Table from pypika.functions import Upper from pypika.terms import ( BasicCriterion, Criterion, Enum, Equality, Term, ValueWrapper, basestring, date, format_quotes, ) from tortoise.fields import Field from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstance if TYPE_CHECKING: # pragma: nocoverage from tortoise.models import Model def FUNC_0(self, **VAR_0): # pragma: nocoverage VAR_8 = VAR_0.get("secondary_quote_char") or "" VAR_9 = VAR_0.get("dialect") if VAR_9: dialect = VAR_9.value if isinstance(self.value, Term): return self.value.get_sql(**VAR_0) if isinstance(self.value, Enum): return self.value.value if isinstance(self.value, date): VAR_5 = self.value.isoformat() return format_quotes(VAR_5, VAR_8) if isinstance(self.value, basestring): VAR_5 = self.value.replace(VAR_8, quote_char * 2) if VAR_9 == "mysql": VAR_5 = value.replace("\\", "\\\\") return format_quotes(VAR_5, VAR_8) if isinstance(self.value, bool): return str.lower(str(self.value)) if self.value is None: return "null" return str(self.value) ValueWrapper.get_value_sql = FUNC_0 class CLASS_0(BasicCriterion): # type: ignore def __init__(self, VAR_10, VAR_11, VAR_12=None, VAR_13=" ESCAPE '\\'") -> None: super().__init__(" LIKE ", VAR_10, VAR_11, VAR_12=alias) self.escape = VAR_13 def FUNC_23(self, VAR_8='"', VAR_14=False, **VAR_0): VAR_17 = "{VAR_10}{comparator}{VAR_11}{VAR_13}".format( comparator=self.comparator, VAR_10=self.left.get_sql(VAR_8=quote_char, **VAR_0), VAR_11=self.right.get_sql(VAR_8=quote_char, **VAR_0), VAR_13=self.escape, ) if VAR_14 and self.alias: # pragma: nocoverage return '{VAR_17} "{VAR_12}"'.format(VAR_17=sql, VAR_12=self.alias) return VAR_17 def FUNC_1(VAR_1: Any) -> Any: if isinstance(VAR_1, str): print(VAR_1) return VAR_1.replace("\\", "\\\\") return VAR_1 def FUNC_2(VAR_1: str) -> str: return VAR_1.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") def FUNC_3(VAR_2: Iterable[Any], VAR_3: "Model", VAR_4: Field) -> list: return [VAR_4.to_db_value(element, VAR_3) for element in VAR_2] def FUNC_4(VAR_2: Iterable[Any], VAR_3: "Model", VAR_4: Field) -> list: return [ VAR_4.to_db_value(element.pk if hasattr(element, "pk") else element, VAR_3) for element in VAR_2 ] def FUNC_5(VAR_5: Any, VAR_3: "Model", VAR_4: Field) -> bool: return bool(VAR_5) def FUNC_6(VAR_5: Any, VAR_3: "Model", VAR_4: Field) -> str: return str(VAR_5) def FUNC_7(VAR_4: Term, VAR_5: Any) -> Criterion: if VAR_5: return VAR_4.isin(VAR_5) return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(0)) def FUNC_8(VAR_4: Term, VAR_5: Any) -> Criterion: if VAR_5: return VAR_4.notin(VAR_5) | VAR_4.isnull() return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(1)) def FUNC_9(VAR_4: Term, VAR_5: Tuple[Any, Any]) -> Criterion: return VAR_4.between(VAR_5[0], VAR_5[1]) def FUNC_10(VAR_4: Term, VAR_5: Any) -> Criterion: return VAR_4.ne(VAR_5) | VAR_4.isnull() def FUNC_11(VAR_4: Term, VAR_5: Any) -> Criterion: if VAR_5: return VAR_4.isnull() return VAR_4.notnull() def FUNC_12(VAR_4: Term, VAR_5: Any) -> Criterion: if VAR_5: return VAR_4.notnull() return VAR_4.isnull() def FUNC_13(VAR_4: Term, VAR_5: str) -> Criterion: return CLASS_0(VAR_4, VAR_4.wrap_constant(f"%{FUNC_2(VAR_5)}%")) def FUNC_14(VAR_4: Term, VAR_5: str) -> Criterion: return CLASS_0(VAR_4, VAR_4.wrap_constant(f"{FUNC_2(VAR_5)}%")) def FUNC_15(VAR_4: Term, VAR_5: str) -> Criterion: return CLASS_0(VAR_4, VAR_4.wrap_constant(f"%{FUNC_2(VAR_5)}")) def FUNC_16(VAR_4: Term, VAR_5: str) -> Criterion: return Upper(VAR_4).eq(Upper(str(VAR_5))) def FUNC_17(VAR_4: Term, VAR_5: str) -> Criterion: return CLASS_0(Upper(VAR_4), VAR_4.wrap_constant(Upper(f"%{FUNC_2(VAR_5)}%"))) def FUNC_18(VAR_4: Term, VAR_5: str) -> Criterion: return CLASS_0(Upper(VAR_4), VAR_4.wrap_constant(Upper(f"{FUNC_2(VAR_5)}%"))) def FUNC_19(VAR_4: Term, VAR_5: str) -> Criterion: return CLASS_0(Upper(VAR_4), VAR_4.wrap_constant(Upper(f"%{FUNC_2(VAR_5)}"))) def FUNC_20(VAR_6: str, VAR_4: ManyToManyFieldInstance) -> Dict[str, dict]: VAR_15 = VAR_4.related_model._meta.pk return { VAR_6: { "field": VAR_4.forward_key, "backward_key": VAR_4.backward_key, "operator": operator.eq, "table": Table(VAR_4.through), "value_encoder": VAR_15.to_db_value, }, f"{VAR_6}__not": { "field": VAR_4.forward_key, "backward_key": VAR_4.backward_key, "operator": FUNC_10, "table": Table(VAR_4.through), "value_encoder": VAR_15.to_db_value, }, f"{VAR_6}__in": { "field": VAR_4.forward_key, "backward_key": VAR_4.backward_key, "operator": FUNC_7, "table": Table(VAR_4.through), "value_encoder": partial(FUNC_4, VAR_4=VAR_15), }, f"{VAR_6}__not_in": { "field": VAR_4.forward_key, "backward_key": VAR_4.backward_key, "operator": FUNC_8, "table": Table(VAR_4.through), "value_encoder": partial(FUNC_4, VAR_4=VAR_15), }, } def FUNC_21(VAR_6: str, VAR_4: BackwardFKRelation) -> Dict[str, dict]: VAR_15 = VAR_4.related_model._meta.pk return { VAR_6: { "field": VAR_4.related_model._meta.pk_attr, "backward_key": VAR_4.relation_field, "operator": operator.eq, "table": Table(VAR_4.related_model._meta.db_table), "value_encoder": VAR_15.to_db_value, }, f"{VAR_6}__not": { "field": VAR_4.related_model._meta.pk_attr, "backward_key": VAR_4.relation_field, "operator": FUNC_10, "table": Table(VAR_4.related_model._meta.db_table), "value_encoder": VAR_15.to_db_value, }, f"{VAR_6}__in": { "field": VAR_4.related_model._meta.pk_attr, "backward_key": VAR_4.relation_field, "operator": FUNC_7, "table": Table(VAR_4.related_model._meta.db_table), "value_encoder": partial(FUNC_4, VAR_4=VAR_15), }, f"{VAR_6}__not_in": { "field": VAR_4.related_model._meta.pk_attr, "backward_key": VAR_4.relation_field, "operator": FUNC_8, "table": Table(VAR_4.related_model._meta.db_table), "value_encoder": partial(FUNC_4, VAR_4=VAR_15), }, } def FUNC_22( VAR_6: str, VAR_4: Optional[Field], VAR_7: str ) -> Dict[str, dict]: if isinstance(VAR_4, ManyToManyFieldInstance): return FUNC_20(VAR_6, VAR_4) if isinstance(VAR_4, BackwardFKRelation): return FUNC_21(VAR_6, VAR_4) VAR_16 = VAR_6 if VAR_6 == "pk" and VAR_4: VAR_16 = VAR_4.model_field_name return { VAR_6: { "field": VAR_16, "source_field": VAR_7, "operator": operator.eq, }, f"{VAR_6}__not": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_10, }, f"{VAR_6}__in": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_7, "value_encoder": FUNC_3, }, f"{VAR_6}__not_in": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_8, "value_encoder": FUNC_3, }, f"{VAR_6}__isnull": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_11, "value_encoder": FUNC_5, }, f"{VAR_6}__not_isnull": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_12, "value_encoder": FUNC_5, }, f"{VAR_6}__gte": { "field": VAR_16, "source_field": VAR_7, "operator": operator.ge, }, f"{VAR_6}__lte": { "field": VAR_16, "source_field": VAR_7, "operator": operator.le, }, f"{VAR_6}__gt": { "field": VAR_16, "source_field": VAR_7, "operator": operator.gt, }, f"{VAR_6}__lt": { "field": VAR_16, "source_field": VAR_7, "operator": operator.lt, }, f"{VAR_6}__range": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_9, "value_encoder": FUNC_3, }, f"{VAR_6}__contains": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_13, "value_encoder": FUNC_6, }, f"{VAR_6}__startswith": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_14, "value_encoder": FUNC_6, }, f"{VAR_6}__endswith": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_15, "value_encoder": FUNC_6, }, f"{VAR_6}__iexact": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_16, "value_encoder": FUNC_6, }, f"{VAR_6}__icontains": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_17, "value_encoder": FUNC_6, }, f"{VAR_6}__istartswith": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_18, "value_encoder": FUNC_6, }, f"{VAR_6}__iendswith": { "field": VAR_16, "source_field": VAR_7, "operator": FUNC_19, "value_encoder": FUNC_6, }, }
[ 4, 8, 11, 14, 15, 16, 17, 18, 19, 20, 24, 25, 31, 32, 35, 36, 39, 40, 41, 42, 43, 44, 45, 46, 50, 52, 53, 57, 59, 60, 63, 64, 67, 68, 73, 74, 79, 80, 83, 84, 87, 88, 91, 92, 95, 96, 99, 100, 103, 104, 107, 108, 109, 110, 111, 112, 113, 146, 147, 180, 181, 296, 22 ]
[ 4, 18, 21, 24, 25, 26, 27, 28, 29, 35, 53, 54, 56, 57, 58, 66, 77, 78, 84, 85, 88, 89, 90, 91, 92, 93, 94, 95, 99, 100, 106, 107, 110, 111, 114, 115, 116, 117, 118, 119, 120, 121, 125, 127, 128, 132, 134, 135, 138, 139, 142, 143, 148, 149, 154, 155, 158, 159, 162, 163, 166, 167, 170, 171, 174, 175, 178, 179, 182, 183, 184, 185, 186, 187, 188, 221, 222, 255, 256, 371, 97, 61, 62, 63 ]
0CWE-22
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Proxy AMI-related calls from cloud controller to objectstore service.""" import binascii import os import shutil import tarfile import tempfile from xml.etree import ElementTree import boto.s3.connection import eventlet from nova import crypto import nova.db.api from nova import exception from nova import flags from nova import image from nova import log as logging from nova import utils from nova.api.ec2 import ec2utils LOG = logging.getLogger("nova.image.s3") FLAGS = flags.FLAGS flags.DEFINE_string('image_decryption_dir', '/tmp', 'parent dir for tempdir used for image decryption') flags.DEFINE_string('s3_access_key', 'notchecked', 'access key to use for s3 server for images') flags.DEFINE_string('s3_secret_key', 'notchecked', 'secret key to use for s3 server for images') class S3ImageService(object): """Wraps an existing image service to support s3 based register.""" def __init__(self, service=None, *args, **kwargs): self.service = service or image.get_default_image_service() self.service.__init__(*args, **kwargs) def get_image_uuid(self, context, image_id): return nova.db.api.s3_image_get(context, image_id)['uuid'] def get_image_id(self, context, image_uuid): return nova.db.api.s3_image_get_by_uuid(context, image_uuid)['id'] def _create_image_id(self, context, image_uuid): return nova.db.api.s3_image_create(context, image_uuid)['id'] def _translate_uuids_to_ids(self, context, images): return [self._translate_uuid_to_id(context, img) for img in images] def _translate_uuid_to_id(self, context, image): def _find_or_create(image_uuid): if image_uuid is None: return try: return self.get_image_id(context, image_uuid) except exception.NotFound: return self._create_image_id(context, image_uuid) image_copy = image.copy() try: image_id = image_copy['id'] except KeyError: pass else: image_copy['id'] = _find_or_create(image_id) for prop in ['kernel_id', 'ramdisk_id']: try: image_uuid = image_copy['properties'][prop] except (KeyError, ValueError): pass else: image_copy['properties'][prop] = _find_or_create(image_uuid) return image_copy def create(self, context, metadata, data=None): """Create an image. metadata['properties'] should contain image_location. """ image = self._s3_create(context, metadata) return image def delete(self, context, image_id): image_uuid = self.get_image_uuid(context, image_id) self.service.delete(context, image_uuid) def update(self, context, image_id, metadata, data=None): image_uuid = self.get_image_uuid(context, image_id) image = self.service.update(context, image_uuid, metadata, data) return self._translate_uuid_to_id(context, image) def index(self, context): #NOTE(bcwaldon): sort asc to make sure we assign lower ids # to older images images = self.service.index(context, sort_dir='asc') return self._translate_uuids_to_ids(context, images) def detail(self, context): #NOTE(bcwaldon): sort asc to make sure we assign lower ids # to older images images = self.service.detail(context, sort_dir='asc') return self._translate_uuids_to_ids(context, images) def show(self, context, image_id): image_uuid = self.get_image_uuid(context, image_id) image = self.service.show(context, image_uuid) return self._translate_uuid_to_id(context, image) def show_by_name(self, context, name): image = self.service.show_by_name(context, name) return self._translate_uuid_to_id(context, image) def get(self, context, image_id): image_uuid = self.get_image_uuid(context, image_id) return self.get(self, context, image_uuid) @staticmethod def _conn(context): # NOTE(vish): access and secret keys for s3 server are not # checked in nova-objectstore access = FLAGS.s3_access_key secret = FLAGS.s3_secret_key calling = boto.s3.connection.OrdinaryCallingFormat() return boto.s3.connection.S3Connection(aws_access_key_id=access, aws_secret_access_key=secret, is_secure=False, calling_format=calling, port=FLAGS.s3_port, host=FLAGS.s3_host) @staticmethod def _download_file(bucket, filename, local_dir): key = bucket.get_key(filename) local_filename = os.path.join(local_dir, filename) key.get_contents_to_filename(local_filename) return local_filename def _s3_parse_manifest(self, context, metadata, manifest): manifest = ElementTree.fromstring(manifest) image_format = 'ami' image_type = 'machine' try: kernel_id = manifest.find('machine_configuration/kernel_id').text if kernel_id == 'true': image_format = 'aki' image_type = 'kernel' kernel_id = None except Exception: kernel_id = None try: ramdisk_id = manifest.find('machine_configuration/ramdisk_id').text if ramdisk_id == 'true': image_format = 'ari' image_type = 'ramdisk' ramdisk_id = None except Exception: ramdisk_id = None try: arch = manifest.find('machine_configuration/architecture').text except Exception: arch = 'x86_64' # NOTE(yamahata): # EC2 ec2-budlne-image --block-device-mapping accepts # <virtual name>=<device name> where # virtual name = {ami, root, swap, ephemeral<N>} # where N is no negative integer # device name = the device name seen by guest kernel. # They are converted into # block_device_mapping/mapping/{virtual, device} # # Do NOT confuse this with ec2-register's block device mapping # argument. mappings = [] try: block_device_mapping = manifest.findall('machine_configuration/' 'block_device_mapping/' 'mapping') for bdm in block_device_mapping: mappings.append({'virtual': bdm.find('virtual').text, 'device': bdm.find('device').text}) except Exception: mappings = [] properties = metadata['properties'] properties['project_id'] = context.project_id properties['architecture'] = arch def _translate_dependent_image_id(image_key, image_id): image_id = ec2utils.ec2_id_to_id(image_id) image_uuid = self.get_image_uuid(context, image_id) properties['image_id'] = image_uuid if kernel_id: _translate_dependent_image_id('kernel_id', kernel_id) if ramdisk_id: _translate_dependent_image_id('ramdisk_id', ramdisk_id) if mappings: properties['mappings'] = mappings metadata.update({'disk_format': image_format, 'container_format': image_format, 'status': 'queued', 'is_public': False, 'properties': properties}) metadata['properties']['image_state'] = 'pending' #TODO(bcwaldon): right now, this removes user-defined ids. # We need to re-enable this. image_id = metadata.pop('id', None) image = self.service.create(context, metadata) # extract the new uuid and generate an int id to present back to user image_uuid = image['id'] image['id'] = self._create_image_id(context, image_uuid) # return image_uuid so the caller can still make use of image_service return manifest, image, image_uuid def _s3_create(self, context, metadata): """Gets a manifext from s3 and makes an image.""" image_path = tempfile.mkdtemp(dir=FLAGS.image_decryption_dir) image_location = metadata['properties']['image_location'] bucket_name = image_location.split('/')[0] manifest_path = image_location[len(bucket_name) + 1:] bucket = self._conn(context).get_bucket(bucket_name) key = bucket.get_key(manifest_path) manifest = key.get_contents_as_string() manifest, image, image_uuid = self._s3_parse_manifest(context, metadata, manifest) def delayed_create(): """This handles the fetching and decrypting of the part files.""" log_vars = {'image_location': image_location, 'image_path': image_path} metadata['properties']['image_state'] = 'downloading' self.service.update(context, image_uuid, metadata) try: parts = [] elements = manifest.find('image').getiterator('filename') for fn_element in elements: part = self._download_file(bucket, fn_element.text, image_path) parts.append(part) # NOTE(vish): this may be suboptimal, should we use cat? enc_filename = os.path.join(image_path, 'image.encrypted') with open(enc_filename, 'w') as combined: for filename in parts: with open(filename) as part: shutil.copyfileobj(part, combined) except Exception: LOG.exception(_("Failed to download %(image_location)s " "to %(image_path)s"), log_vars) metadata['properties']['image_state'] = 'failed_download' self.service.update(context, image_uuid, metadata) return metadata['properties']['image_state'] = 'decrypting' self.service.update(context, image_uuid, metadata) try: hex_key = manifest.find('image/ec2_encrypted_key').text encrypted_key = binascii.a2b_hex(hex_key) hex_iv = manifest.find('image/ec2_encrypted_iv').text encrypted_iv = binascii.a2b_hex(hex_iv) # FIXME(vish): grab key from common service so this can run on # any host. cloud_pk = crypto.key_path(context.project_id) dec_filename = os.path.join(image_path, 'image.tar.gz') self._decrypt_image(enc_filename, encrypted_key, encrypted_iv, cloud_pk, dec_filename) except Exception: LOG.exception(_("Failed to decrypt %(image_location)s " "to %(image_path)s"), log_vars) metadata['properties']['image_state'] = 'failed_decrypt' self.service.update(context, image_uuid, metadata) return metadata['properties']['image_state'] = 'untarring' self.service.update(context, image_uuid, metadata) try: unz_filename = self._untarzip_image(image_path, dec_filename) except Exception: LOG.exception(_("Failed to untar %(image_location)s " "to %(image_path)s"), log_vars) metadata['properties']['image_state'] = 'failed_untar' self.service.update(context, image_uuid, metadata) return metadata['properties']['image_state'] = 'uploading' self.service.update(context, image_uuid, metadata) try: with open(unz_filename) as image_file: self.service.update(context, image_uuid, metadata, image_file) except Exception: LOG.exception(_("Failed to upload %(image_location)s " "to %(image_path)s"), log_vars) metadata['properties']['image_state'] = 'failed_upload' self.service.update(context, image_uuid, metadata) return metadata['properties']['image_state'] = 'available' metadata['status'] = 'active' self.service.update(context, image_uuid, metadata) shutil.rmtree(image_path) eventlet.spawn_n(delayed_create) return image @staticmethod def _decrypt_image(encrypted_filename, encrypted_key, encrypted_iv, cloud_private_key, decrypted_filename): key, err = utils.execute('openssl', 'rsautl', '-decrypt', '-inkey', '%s' % cloud_private_key, process_input=encrypted_key, check_exit_code=False) if err: raise exception.Error(_('Failed to decrypt private key: %s') % err) iv, err = utils.execute('openssl', 'rsautl', '-decrypt', '-inkey', '%s' % cloud_private_key, process_input=encrypted_iv, check_exit_code=False) if err: raise exception.Error(_('Failed to decrypt initialization ' 'vector: %s') % err) _out, err = utils.execute('openssl', 'enc', '-d', '-aes-128-cbc', '-in', '%s' % (encrypted_filename,), '-K', '%s' % (key,), '-iv', '%s' % (iv,), '-out', '%s' % (decrypted_filename,), check_exit_code=False) if err: raise exception.Error(_('Failed to decrypt image file ' '%(image_file)s: %(err)s') % {'image_file': encrypted_filename, 'err': err}) @staticmethod def _untarzip_image(path, filename): tar_file = tarfile.open(filename, 'r|gz') tar_file.extractall(path) image_file = tar_file.getnames()[0] tar_file.close() return os.path.join(path, image_file)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Proxy AMI-related calls from cloud controller to objectstore service.""" import binascii import os import shutil import tarfile import tempfile from xml.etree import ElementTree import boto.s3.connection import eventlet from nova import crypto import nova.db.api from nova import exception from nova import flags from nova import image from nova import log as logging from nova import utils from nova.api.ec2 import ec2utils LOG = logging.getLogger("nova.image.s3") FLAGS = flags.FLAGS flags.DEFINE_string('image_decryption_dir', '/tmp', 'parent dir for tempdir used for image decryption') flags.DEFINE_string('s3_access_key', 'notchecked', 'access key to use for s3 server for images') flags.DEFINE_string('s3_secret_key', 'notchecked', 'secret key to use for s3 server for images') class S3ImageService(object): """Wraps an existing image service to support s3 based register.""" def __init__(self, service=None, *args, **kwargs): self.service = service or image.get_default_image_service() self.service.__init__(*args, **kwargs) def get_image_uuid(self, context, image_id): return nova.db.api.s3_image_get(context, image_id)['uuid'] def get_image_id(self, context, image_uuid): return nova.db.api.s3_image_get_by_uuid(context, image_uuid)['id'] def _create_image_id(self, context, image_uuid): return nova.db.api.s3_image_create(context, image_uuid)['id'] def _translate_uuids_to_ids(self, context, images): return [self._translate_uuid_to_id(context, img) for img in images] def _translate_uuid_to_id(self, context, image): def _find_or_create(image_uuid): if image_uuid is None: return try: return self.get_image_id(context, image_uuid) except exception.NotFound: return self._create_image_id(context, image_uuid) image_copy = image.copy() try: image_id = image_copy['id'] except KeyError: pass else: image_copy['id'] = _find_or_create(image_id) for prop in ['kernel_id', 'ramdisk_id']: try: image_uuid = image_copy['properties'][prop] except (KeyError, ValueError): pass else: image_copy['properties'][prop] = _find_or_create(image_uuid) return image_copy def create(self, context, metadata, data=None): """Create an image. metadata['properties'] should contain image_location. """ image = self._s3_create(context, metadata) return image def delete(self, context, image_id): image_uuid = self.get_image_uuid(context, image_id) self.service.delete(context, image_uuid) def update(self, context, image_id, metadata, data=None): image_uuid = self.get_image_uuid(context, image_id) image = self.service.update(context, image_uuid, metadata, data) return self._translate_uuid_to_id(context, image) def index(self, context): #NOTE(bcwaldon): sort asc to make sure we assign lower ids # to older images images = self.service.index(context, sort_dir='asc') return self._translate_uuids_to_ids(context, images) def detail(self, context): #NOTE(bcwaldon): sort asc to make sure we assign lower ids # to older images images = self.service.detail(context, sort_dir='asc') return self._translate_uuids_to_ids(context, images) def show(self, context, image_id): image_uuid = self.get_image_uuid(context, image_id) image = self.service.show(context, image_uuid) return self._translate_uuid_to_id(context, image) def show_by_name(self, context, name): image = self.service.show_by_name(context, name) return self._translate_uuid_to_id(context, image) def get(self, context, image_id): image_uuid = self.get_image_uuid(context, image_id) return self.get(self, context, image_uuid) @staticmethod def _conn(context): # NOTE(vish): access and secret keys for s3 server are not # checked in nova-objectstore access = FLAGS.s3_access_key secret = FLAGS.s3_secret_key calling = boto.s3.connection.OrdinaryCallingFormat() return boto.s3.connection.S3Connection(aws_access_key_id=access, aws_secret_access_key=secret, is_secure=False, calling_format=calling, port=FLAGS.s3_port, host=FLAGS.s3_host) @staticmethod def _download_file(bucket, filename, local_dir): key = bucket.get_key(filename) local_filename = os.path.join(local_dir, os.path.basename(filename)) key.get_contents_to_filename(local_filename) return local_filename def _s3_parse_manifest(self, context, metadata, manifest): manifest = ElementTree.fromstring(manifest) image_format = 'ami' image_type = 'machine' try: kernel_id = manifest.find('machine_configuration/kernel_id').text if kernel_id == 'true': image_format = 'aki' image_type = 'kernel' kernel_id = None except Exception: kernel_id = None try: ramdisk_id = manifest.find('machine_configuration/ramdisk_id').text if ramdisk_id == 'true': image_format = 'ari' image_type = 'ramdisk' ramdisk_id = None except Exception: ramdisk_id = None try: arch = manifest.find('machine_configuration/architecture').text except Exception: arch = 'x86_64' # NOTE(yamahata): # EC2 ec2-budlne-image --block-device-mapping accepts # <virtual name>=<device name> where # virtual name = {ami, root, swap, ephemeral<N>} # where N is no negative integer # device name = the device name seen by guest kernel. # They are converted into # block_device_mapping/mapping/{virtual, device} # # Do NOT confuse this with ec2-register's block device mapping # argument. mappings = [] try: block_device_mapping = manifest.findall('machine_configuration/' 'block_device_mapping/' 'mapping') for bdm in block_device_mapping: mappings.append({'virtual': bdm.find('virtual').text, 'device': bdm.find('device').text}) except Exception: mappings = [] properties = metadata['properties'] properties['project_id'] = context.project_id properties['architecture'] = arch def _translate_dependent_image_id(image_key, image_id): image_id = ec2utils.ec2_id_to_id(image_id) image_uuid = self.get_image_uuid(context, image_id) properties['image_id'] = image_uuid if kernel_id: _translate_dependent_image_id('kernel_id', kernel_id) if ramdisk_id: _translate_dependent_image_id('ramdisk_id', ramdisk_id) if mappings: properties['mappings'] = mappings metadata.update({'disk_format': image_format, 'container_format': image_format, 'status': 'queued', 'is_public': False, 'properties': properties}) metadata['properties']['image_state'] = 'pending' #TODO(bcwaldon): right now, this removes user-defined ids. # We need to re-enable this. image_id = metadata.pop('id', None) image = self.service.create(context, metadata) # extract the new uuid and generate an int id to present back to user image_uuid = image['id'] image['id'] = self._create_image_id(context, image_uuid) # return image_uuid so the caller can still make use of image_service return manifest, image, image_uuid def _s3_create(self, context, metadata): """Gets a manifext from s3 and makes an image.""" image_path = tempfile.mkdtemp(dir=FLAGS.image_decryption_dir) image_location = metadata['properties']['image_location'] bucket_name = image_location.split('/')[0] manifest_path = image_location[len(bucket_name) + 1:] bucket = self._conn(context).get_bucket(bucket_name) key = bucket.get_key(manifest_path) manifest = key.get_contents_as_string() manifest, image, image_uuid = self._s3_parse_manifest(context, metadata, manifest) def delayed_create(): """This handles the fetching and decrypting of the part files.""" log_vars = {'image_location': image_location, 'image_path': image_path} metadata['properties']['image_state'] = 'downloading' self.service.update(context, image_uuid, metadata) try: parts = [] elements = manifest.find('image').getiterator('filename') for fn_element in elements: part = self._download_file(bucket, fn_element.text, image_path) parts.append(part) # NOTE(vish): this may be suboptimal, should we use cat? enc_filename = os.path.join(image_path, 'image.encrypted') with open(enc_filename, 'w') as combined: for filename in parts: with open(filename) as part: shutil.copyfileobj(part, combined) except Exception: LOG.exception(_("Failed to download %(image_location)s " "to %(image_path)s"), log_vars) metadata['properties']['image_state'] = 'failed_download' self.service.update(context, image_uuid, metadata) return metadata['properties']['image_state'] = 'decrypting' self.service.update(context, image_uuid, metadata) try: hex_key = manifest.find('image/ec2_encrypted_key').text encrypted_key = binascii.a2b_hex(hex_key) hex_iv = manifest.find('image/ec2_encrypted_iv').text encrypted_iv = binascii.a2b_hex(hex_iv) # FIXME(vish): grab key from common service so this can run on # any host. cloud_pk = crypto.key_path(context.project_id) dec_filename = os.path.join(image_path, 'image.tar.gz') self._decrypt_image(enc_filename, encrypted_key, encrypted_iv, cloud_pk, dec_filename) except Exception: LOG.exception(_("Failed to decrypt %(image_location)s " "to %(image_path)s"), log_vars) metadata['properties']['image_state'] = 'failed_decrypt' self.service.update(context, image_uuid, metadata) return metadata['properties']['image_state'] = 'untarring' self.service.update(context, image_uuid, metadata) try: unz_filename = self._untarzip_image(image_path, dec_filename) except Exception: LOG.exception(_("Failed to untar %(image_location)s " "to %(image_path)s"), log_vars) metadata['properties']['image_state'] = 'failed_untar' self.service.update(context, image_uuid, metadata) return metadata['properties']['image_state'] = 'uploading' self.service.update(context, image_uuid, metadata) try: with open(unz_filename) as image_file: self.service.update(context, image_uuid, metadata, image_file) except Exception: LOG.exception(_("Failed to upload %(image_location)s " "to %(image_path)s"), log_vars) metadata['properties']['image_state'] = 'failed_upload' self.service.update(context, image_uuid, metadata) return metadata['properties']['image_state'] = 'available' metadata['status'] = 'active' self.service.update(context, image_uuid, metadata) shutil.rmtree(image_path) eventlet.spawn_n(delayed_create) return image @staticmethod def _decrypt_image(encrypted_filename, encrypted_key, encrypted_iv, cloud_private_key, decrypted_filename): key, err = utils.execute('openssl', 'rsautl', '-decrypt', '-inkey', '%s' % cloud_private_key, process_input=encrypted_key, check_exit_code=False) if err: raise exception.Error(_('Failed to decrypt private key: %s') % err) iv, err = utils.execute('openssl', 'rsautl', '-decrypt', '-inkey', '%s' % cloud_private_key, process_input=encrypted_iv, check_exit_code=False) if err: raise exception.Error(_('Failed to decrypt initialization ' 'vector: %s') % err) _out, err = utils.execute('openssl', 'enc', '-d', '-aes-128-cbc', '-in', '%s' % (encrypted_filename,), '-K', '%s' % (key,), '-iv', '%s' % (iv,), '-out', '%s' % (decrypted_filename,), check_exit_code=False) if err: raise exception.Error(_('Failed to decrypt image file ' '%(image_file)s: %(err)s') % {'image_file': encrypted_filename, 'err': err}) @staticmethod def _test_for_malicious_tarball(path, filename): """Raises exception if extracting tarball would escape extract path""" tar_file = tarfile.open(filename, 'r|gz') for n in tar_file.getnames(): if not os.path.abspath(os.path.join(path, n)).startswith(path): tar_file.close() raise exception.Error(_('Unsafe filenames in image')) tar_file.close() @staticmethod def _untarzip_image(path, filename): S3ImageService._test_for_malicious_tarball(path, filename) tar_file = tarfile.open(filename, 'r|gz') tar_file.extractall(path) image_file = tar_file.getnames()[0] tar_file.close() return os.path.join(path, image_file)
path_disclosure
{ "code": [ " local_filename = os.path.join(local_dir, filename)" ], "line_no": [ 158 ] }
{ "code": [ " local_filename = os.path.join(local_dir, os.path.basename(filename))", " @staticmethod", " def _test_for_malicious_tarball(path, filename):", " \"\"\"Raises exception if extracting tarball would escape extract path\"\"\"", " tar_file = tarfile.open(filename, 'r|gz')", " for n in tar_file.getnames():", " if not os.path.abspath(os.path.join(path, n)).startswith(path):", " tar_file.close()", " tar_file.close()", " S3ImageService._test_for_malicious_tarball(path, filename)" ], "line_no": [ 158, 390, 391, 392, 393, 394, 395, 396, 398, 402 ] }
import binascii import os import shutil import tarfile import tempfile from xml.etree import ElementTree import boto.s3.connection import eventlet from nova import crypto import nova.db.api from nova import exception from nova import flags from nova import .image from nova import log as logging from nova import utils from nova.api.ec2 import ec2utils VAR_0 = logging.getLogger("nova.image.s3") VAR_1 = flags.FLAGS flags.DEFINE_string('image_decryption_dir', '/tmp', 'parent dir for tempdir used for VAR_9 decryption') flags.DEFINE_string('s3_access_key', 'notchecked', 'access VAR_27 to use for s3 server for images') flags.DEFINE_string('s3_secret_key', 'notchecked', 'secret VAR_27 to use for s3 server for images') class CLASS_0(object): def __init__(self, VAR_2=None, *VAR_3, **VAR_4): self.service = VAR_2 or VAR_9.get_default_image_service() self.service.__init__(*VAR_3, **VAR_4) def FUNC_0(self, VAR_5, VAR_6): return nova.db.api.s3_image_get(VAR_5, VAR_6)['uuid'] def FUNC_1(self, VAR_5, VAR_7): return nova.db.api.s3_image_get_by_uuid(VAR_5, VAR_7)['id'] def FUNC_2(self, VAR_5, VAR_7): return nova.db.api.s3_image_create(VAR_5, VAR_7)['id'] def FUNC_3(self, VAR_5, VAR_8): return [self._translate_uuid_to_id(VAR_5, img) for img in VAR_8] def FUNC_4(self, VAR_5, VAR_9): def FUNC_19(VAR_7): if VAR_7 is None: return try: return self.get_image_id(VAR_5, VAR_7) except exception.NotFound: return self._create_image_id(VAR_5, VAR_7) VAR_23 = VAR_9.copy() try: VAR_6 = VAR_23['id'] except KeyError: pass else: VAR_23['id'] = FUNC_19(VAR_6) for VAR_48 in ['kernel_id', 'ramdisk_id']: try: VAR_7 = VAR_23['properties'][VAR_48] except (KeyError, ValueError): pass else: VAR_23['properties'][VAR_48] = FUNC_19(VAR_7) return VAR_23 def FUNC_5(self, VAR_5, VAR_10, VAR_11=None): VAR_9 = self._s3_create(VAR_5, VAR_10) return VAR_9 def FUNC_6(self, VAR_5, VAR_6): VAR_7 = self.get_image_uuid(VAR_5, VAR_6) self.service.delete(VAR_5, VAR_7) def FUNC_7(self, VAR_5, VAR_6, VAR_10, VAR_11=None): VAR_7 = self.get_image_uuid(VAR_5, VAR_6) VAR_9 = self.service.update(VAR_5, VAR_7, VAR_10, VAR_11) return self._translate_uuid_to_id(VAR_5, VAR_9) def FUNC_8(self, VAR_5): images = self.service.index(VAR_5, sort_dir='asc') return self._translate_uuids_to_ids(VAR_5, VAR_8) def FUNC_9(self, VAR_5): images = self.service.detail(VAR_5, sort_dir='asc') return self._translate_uuids_to_ids(VAR_5, VAR_8) def FUNC_10(self, VAR_5, VAR_6): VAR_7 = self.get_image_uuid(VAR_5, VAR_6) VAR_9 = self.service.show(VAR_5, VAR_7) return self._translate_uuid_to_id(VAR_5, VAR_9) def FUNC_11(self, VAR_5, VAR_12): VAR_9 = self.service.show_by_name(VAR_5, VAR_12) return self._translate_uuid_to_id(VAR_5, VAR_9) def FUNC_12(self, VAR_5, VAR_6): VAR_7 = self.get_image_uuid(VAR_5, VAR_6) return self.get(self, VAR_5, VAR_7) @staticmethod def FUNC_13(VAR_5): VAR_24 = VAR_1.s3_access_key VAR_25 = VAR_1.s3_secret_key VAR_26 = boto.s3.connection.OrdinaryCallingFormat() return boto.s3.connection.S3Connection(aws_access_key_id=VAR_24, aws_secret_access_key=VAR_25, is_secure=False, calling_format=VAR_26, port=VAR_1.s3_port, host=VAR_1.s3_host) @staticmethod def FUNC_14(VAR_13, VAR_14, VAR_15): VAR_27 = VAR_13.get_key(VAR_14) VAR_28 = os.path.join(VAR_15, VAR_14) VAR_27.get_contents_to_filename(VAR_28) return VAR_28 def FUNC_15(self, VAR_5, VAR_10, VAR_16): manifest = ElementTree.fromstring(VAR_16) VAR_29 = 'ami' VAR_30 = 'machine' try: VAR_43 = VAR_16.find('machine_configuration/kernel_id').text if VAR_43 == 'true': VAR_29 = 'aki' VAR_30 = 'kernel' VAR_43 = None except Exception: VAR_43 = None try: VAR_44 = VAR_16.find('machine_configuration/ramdisk_id').text if VAR_44 == 'true': VAR_29 = 'ari' VAR_30 = 'ramdisk' VAR_44 = None except Exception: VAR_44 = None try: VAR_45 = VAR_16.find('machine_configuration/architecture').text except Exception: VAR_45 = 'x86_64' VAR_31 = [] try: VAR_46 = VAR_16.findall('machine_configuration/' 'block_device_mapping/' 'mapping') for bdm in VAR_46: VAR_31.append({'virtual': bdm.find('virtual').text, 'device': bdm.find('device').text}) except Exception: VAR_31 = [] VAR_32 = VAR_10['properties'] VAR_32['project_id'] = VAR_5.project_id VAR_32['architecture'] = VAR_45 def FUNC_20(VAR_33, VAR_6): VAR_6 = ec2utils.ec2_id_to_id(VAR_6) VAR_7 = self.get_image_uuid(VAR_5, VAR_6) VAR_32['image_id'] = VAR_7 if VAR_43: FUNC_20('kernel_id', VAR_43) if VAR_44: FUNC_20('ramdisk_id', VAR_44) if VAR_31: VAR_32['mappings'] = VAR_31 VAR_10.update({'disk_format': VAR_29, 'container_format': VAR_29, 'status': 'queued', 'is_public': False, 'properties': VAR_32}) VAR_10['properties']['image_state'] = 'pending' VAR_6 = VAR_10.pop('id', None) VAR_9 = self.service.create(VAR_5, VAR_10) VAR_7 = VAR_9['id'] VAR_9['id'] = self._create_image_id(VAR_5, VAR_7) return VAR_16, VAR_9, VAR_7 def FUNC_16(self, VAR_5, VAR_10): VAR_34 = tempfile.mkdtemp(dir=VAR_1.image_decryption_dir) VAR_35 = VAR_10['properties']['image_location'] VAR_36 = VAR_35.split('/')[0] VAR_37 = VAR_35[len(VAR_36) + 1:] VAR_13 = self._conn(VAR_5).get_bucket(VAR_36) VAR_27 = VAR_13.get_key(VAR_37) VAR_16 = VAR_27.get_contents_as_string() VAR_16, VAR_9, VAR_7 = self._s3_parse_manifest(VAR_5, VAR_10, VAR_16) def FUNC_21(): VAR_47 = {'image_location': VAR_35, 'image_path': VAR_34} VAR_10['properties']['image_state'] = 'downloading' self.service.update(VAR_5, VAR_7, VAR_10) try: VAR_49 = [] VAR_50 = VAR_16.find('image').getiterator('filename') for fn_element in VAR_50: VAR_57 = self._download_file(VAR_13, fn_element.text, VAR_34) VAR_49.append(VAR_57) VAR_51 = os.path.join(VAR_34, 'image.encrypted') with open(VAR_51, 'w') as combined: for VAR_14 in VAR_49: with open(VAR_14) as VAR_57: shutil.copyfileobj(VAR_57, combined) except Exception: VAR_0.exception(_("Failed to download %(VAR_35)s " "to %(VAR_34)s"), VAR_47) VAR_10['properties']['image_state'] = 'failed_download' self.service.update(VAR_5, VAR_7, VAR_10) return VAR_10['properties']['image_state'] = 'decrypting' self.service.update(VAR_5, VAR_7, VAR_10) try: VAR_52 = VAR_16.find('image/ec2_encrypted_key').text VAR_18 = binascii.a2b_hex(VAR_52) VAR_53 = VAR_16.find('image/ec2_encrypted_iv').text VAR_19 = binascii.a2b_hex(VAR_53) VAR_54 = crypto.key_path(VAR_5.project_id) VAR_55 = os.path.join(VAR_34, 'image.tar.gz') self._decrypt_image(VAR_51, VAR_18, VAR_19, VAR_54, VAR_55) except Exception: VAR_0.exception(_("Failed to decrypt %(VAR_35)s " "to %(VAR_34)s"), VAR_47) VAR_10['properties']['image_state'] = 'failed_decrypt' self.service.update(VAR_5, VAR_7, VAR_10) return VAR_10['properties']['image_state'] = 'untarring' self.service.update(VAR_5, VAR_7, VAR_10) try: VAR_56 = self._untarzip_image(VAR_34, VAR_55) except Exception: VAR_0.exception(_("Failed to untar %(VAR_35)s " "to %(VAR_34)s"), VAR_47) VAR_10['properties']['image_state'] = 'failed_untar' self.service.update(VAR_5, VAR_7, VAR_10) return VAR_10['properties']['image_state'] = 'uploading' self.service.update(VAR_5, VAR_7, VAR_10) try: with open(VAR_56) as VAR_42: self.service.update(VAR_5, VAR_7, VAR_10, VAR_42) except Exception: VAR_0.exception(_("Failed to upload %(VAR_35)s " "to %(VAR_34)s"), VAR_47) VAR_10['properties']['image_state'] = 'failed_upload' self.service.update(VAR_5, VAR_7, VAR_10) return VAR_10['properties']['image_state'] = 'available' VAR_10['status'] = 'active' self.service.update(VAR_5, VAR_7, VAR_10) shutil.rmtree(VAR_34) eventlet.spawn_n(FUNC_21) return VAR_9 @staticmethod def FUNC_17(VAR_17, VAR_18, VAR_19, VAR_20, VAR_21): VAR_27, VAR_38 = utils.execute('openssl', 'rsautl', '-decrypt', '-inkey', '%s' % VAR_20, process_input=VAR_18, check_exit_code=False) if VAR_38: raise exception.Error(_('Failed to decrypt private VAR_27: %s') % VAR_38) VAR_39, VAR_38 = utils.execute('openssl', 'rsautl', '-decrypt', '-inkey', '%s' % VAR_20, process_input=VAR_19, check_exit_code=False) if VAR_38: raise exception.Error(_('Failed to decrypt initialization ' 'vector: %s') % VAR_38) VAR_40, VAR_38 = utils.execute('openssl', 'enc', '-d', '-aes-128-cbc', '-in', '%s' % (VAR_17,), '-K', '%s' % (VAR_27,), '-iv', '%s' % (VAR_39,), '-out', '%s' % (VAR_21,), check_exit_code=False) if VAR_38: raise exception.Error(_('Failed to decrypt VAR_9 file ' '%(VAR_42)s: %(VAR_38)s') % {'image_file': VAR_17, 'err': VAR_38}) @staticmethod def FUNC_18(VAR_22, VAR_14): VAR_41 = tarfile.open(VAR_14, 'r|gz') VAR_41.extractall(VAR_22) VAR_42 = VAR_41.getnames()[0] VAR_41.close() return os.path.join(VAR_22, VAR_42)
import binascii import os import shutil import tarfile import tempfile from xml.etree import ElementTree import boto.s3.connection import eventlet from nova import crypto import nova.db.api from nova import exception from nova import flags from nova import .image from nova import log as logging from nova import utils from nova.api.ec2 import ec2utils VAR_0 = logging.getLogger("nova.image.s3") VAR_1 = flags.FLAGS flags.DEFINE_string('image_decryption_dir', '/tmp', 'parent dir for tempdir used for VAR_9 decryption') flags.DEFINE_string('s3_access_key', 'notchecked', 'access VAR_27 to use for s3 server for images') flags.DEFINE_string('s3_secret_key', 'notchecked', 'secret VAR_27 to use for s3 server for images') class CLASS_0(object): def __init__(self, VAR_2=None, *VAR_3, **VAR_4): self.service = VAR_2 or VAR_9.get_default_image_service() self.service.__init__(*VAR_3, **VAR_4) def FUNC_0(self, VAR_5, VAR_6): return nova.db.api.s3_image_get(VAR_5, VAR_6)['uuid'] def FUNC_1(self, VAR_5, VAR_7): return nova.db.api.s3_image_get_by_uuid(VAR_5, VAR_7)['id'] def FUNC_2(self, VAR_5, VAR_7): return nova.db.api.s3_image_create(VAR_5, VAR_7)['id'] def FUNC_3(self, VAR_5, VAR_8): return [self._translate_uuid_to_id(VAR_5, img) for img in VAR_8] def FUNC_4(self, VAR_5, VAR_9): def FUNC_20(VAR_7): if VAR_7 is None: return try: return self.get_image_id(VAR_5, VAR_7) except exception.NotFound: return self._create_image_id(VAR_5, VAR_7) VAR_23 = VAR_9.copy() try: VAR_6 = VAR_23['id'] except KeyError: pass else: VAR_23['id'] = FUNC_20(VAR_6) for VAR_48 in ['kernel_id', 'ramdisk_id']: try: VAR_7 = VAR_23['properties'][VAR_48] except (KeyError, ValueError): pass else: VAR_23['properties'][VAR_48] = FUNC_20(VAR_7) return VAR_23 def FUNC_5(self, VAR_5, VAR_10, VAR_11=None): VAR_9 = self._s3_create(VAR_5, VAR_10) return VAR_9 def FUNC_6(self, VAR_5, VAR_6): VAR_7 = self.get_image_uuid(VAR_5, VAR_6) self.service.delete(VAR_5, VAR_7) def FUNC_7(self, VAR_5, VAR_6, VAR_10, VAR_11=None): VAR_7 = self.get_image_uuid(VAR_5, VAR_6) VAR_9 = self.service.update(VAR_5, VAR_7, VAR_10, VAR_11) return self._translate_uuid_to_id(VAR_5, VAR_9) def FUNC_8(self, VAR_5): images = self.service.index(VAR_5, sort_dir='asc') return self._translate_uuids_to_ids(VAR_5, VAR_8) def FUNC_9(self, VAR_5): images = self.service.detail(VAR_5, sort_dir='asc') return self._translate_uuids_to_ids(VAR_5, VAR_8) def FUNC_10(self, VAR_5, VAR_6): VAR_7 = self.get_image_uuid(VAR_5, VAR_6) VAR_9 = self.service.show(VAR_5, VAR_7) return self._translate_uuid_to_id(VAR_5, VAR_9) def FUNC_11(self, VAR_5, VAR_12): VAR_9 = self.service.show_by_name(VAR_5, VAR_12) return self._translate_uuid_to_id(VAR_5, VAR_9) def FUNC_12(self, VAR_5, VAR_6): VAR_7 = self.get_image_uuid(VAR_5, VAR_6) return self.get(self, VAR_5, VAR_7) @staticmethod def FUNC_13(VAR_5): VAR_24 = VAR_1.s3_access_key VAR_25 = VAR_1.s3_secret_key VAR_26 = boto.s3.connection.OrdinaryCallingFormat() return boto.s3.connection.S3Connection(aws_access_key_id=VAR_24, aws_secret_access_key=VAR_25, is_secure=False, calling_format=VAR_26, port=VAR_1.s3_port, host=VAR_1.s3_host) @staticmethod def FUNC_14(VAR_13, VAR_14, VAR_15): VAR_27 = VAR_13.get_key(VAR_14) VAR_28 = os.path.join(VAR_15, os.path.basename(VAR_14)) VAR_27.get_contents_to_filename(VAR_28) return VAR_28 def FUNC_15(self, VAR_5, VAR_10, VAR_16): manifest = ElementTree.fromstring(VAR_16) VAR_29 = 'ami' VAR_30 = 'machine' try: VAR_43 = VAR_16.find('machine_configuration/kernel_id').text if VAR_43 == 'true': VAR_29 = 'aki' VAR_30 = 'kernel' VAR_43 = None except Exception: VAR_43 = None try: VAR_44 = VAR_16.find('machine_configuration/ramdisk_id').text if VAR_44 == 'true': VAR_29 = 'ari' VAR_30 = 'ramdisk' VAR_44 = None except Exception: VAR_44 = None try: VAR_45 = VAR_16.find('machine_configuration/architecture').text except Exception: VAR_45 = 'x86_64' VAR_31 = [] try: VAR_46 = VAR_16.findall('machine_configuration/' 'block_device_mapping/' 'mapping') for bdm in VAR_46: VAR_31.append({'virtual': bdm.find('virtual').text, 'device': bdm.find('device').text}) except Exception: VAR_31 = [] VAR_32 = VAR_10['properties'] VAR_32['project_id'] = VAR_5.project_id VAR_32['architecture'] = VAR_45 def FUNC_21(VAR_33, VAR_6): VAR_6 = ec2utils.ec2_id_to_id(VAR_6) VAR_7 = self.get_image_uuid(VAR_5, VAR_6) VAR_32['image_id'] = VAR_7 if VAR_43: FUNC_21('kernel_id', VAR_43) if VAR_44: FUNC_21('ramdisk_id', VAR_44) if VAR_31: VAR_32['mappings'] = VAR_31 VAR_10.update({'disk_format': VAR_29, 'container_format': VAR_29, 'status': 'queued', 'is_public': False, 'properties': VAR_32}) VAR_10['properties']['image_state'] = 'pending' VAR_6 = VAR_10.pop('id', None) VAR_9 = self.service.create(VAR_5, VAR_10) VAR_7 = VAR_9['id'] VAR_9['id'] = self._create_image_id(VAR_5, VAR_7) return VAR_16, VAR_9, VAR_7 def FUNC_16(self, VAR_5, VAR_10): VAR_34 = tempfile.mkdtemp(dir=VAR_1.image_decryption_dir) VAR_35 = VAR_10['properties']['image_location'] VAR_36 = VAR_35.split('/')[0] VAR_37 = VAR_35[len(VAR_36) + 1:] VAR_13 = self._conn(VAR_5).get_bucket(VAR_36) VAR_27 = VAR_13.get_key(VAR_37) VAR_16 = VAR_27.get_contents_as_string() VAR_16, VAR_9, VAR_7 = self._s3_parse_manifest(VAR_5, VAR_10, VAR_16) def FUNC_22(): VAR_47 = {'image_location': VAR_35, 'image_path': VAR_34} VAR_10['properties']['image_state'] = 'downloading' self.service.update(VAR_5, VAR_7, VAR_10) try: VAR_49 = [] VAR_50 = VAR_16.find('image').getiterator('filename') for fn_element in VAR_50: VAR_57 = self._download_file(VAR_13, fn_element.text, VAR_34) VAR_49.append(VAR_57) VAR_51 = os.path.join(VAR_34, 'image.encrypted') with open(VAR_51, 'w') as combined: for VAR_14 in VAR_49: with open(VAR_14) as VAR_57: shutil.copyfileobj(VAR_57, combined) except Exception: VAR_0.exception(_("Failed to download %(VAR_35)s " "to %(VAR_34)s"), VAR_47) VAR_10['properties']['image_state'] = 'failed_download' self.service.update(VAR_5, VAR_7, VAR_10) return VAR_10['properties']['image_state'] = 'decrypting' self.service.update(VAR_5, VAR_7, VAR_10) try: VAR_52 = VAR_16.find('image/ec2_encrypted_key').text VAR_18 = binascii.a2b_hex(VAR_52) VAR_53 = VAR_16.find('image/ec2_encrypted_iv').text VAR_19 = binascii.a2b_hex(VAR_53) VAR_54 = crypto.key_path(VAR_5.project_id) VAR_55 = os.path.join(VAR_34, 'image.tar.gz') self._decrypt_image(VAR_51, VAR_18, VAR_19, VAR_54, VAR_55) except Exception: VAR_0.exception(_("Failed to decrypt %(VAR_35)s " "to %(VAR_34)s"), VAR_47) VAR_10['properties']['image_state'] = 'failed_decrypt' self.service.update(VAR_5, VAR_7, VAR_10) return VAR_10['properties']['image_state'] = 'untarring' self.service.update(VAR_5, VAR_7, VAR_10) try: VAR_56 = self._untarzip_image(VAR_34, VAR_55) except Exception: VAR_0.exception(_("Failed to untar %(VAR_35)s " "to %(VAR_34)s"), VAR_47) VAR_10['properties']['image_state'] = 'failed_untar' self.service.update(VAR_5, VAR_7, VAR_10) return VAR_10['properties']['image_state'] = 'uploading' self.service.update(VAR_5, VAR_7, VAR_10) try: with open(VAR_56) as VAR_42: self.service.update(VAR_5, VAR_7, VAR_10, VAR_42) except Exception: VAR_0.exception(_("Failed to upload %(VAR_35)s " "to %(VAR_34)s"), VAR_47) VAR_10['properties']['image_state'] = 'failed_upload' self.service.update(VAR_5, VAR_7, VAR_10) return VAR_10['properties']['image_state'] = 'available' VAR_10['status'] = 'active' self.service.update(VAR_5, VAR_7, VAR_10) shutil.rmtree(VAR_34) eventlet.spawn_n(FUNC_22) return VAR_9 @staticmethod def FUNC_17(VAR_17, VAR_18, VAR_19, VAR_20, VAR_21): VAR_27, VAR_38 = utils.execute('openssl', 'rsautl', '-decrypt', '-inkey', '%s' % VAR_20, process_input=VAR_18, check_exit_code=False) if VAR_38: raise exception.Error(_('Failed to decrypt private VAR_27: %s') % VAR_38) VAR_39, VAR_38 = utils.execute('openssl', 'rsautl', '-decrypt', '-inkey', '%s' % VAR_20, process_input=VAR_19, check_exit_code=False) if VAR_38: raise exception.Error(_('Failed to decrypt initialization ' 'vector: %s') % VAR_38) VAR_40, VAR_38 = utils.execute('openssl', 'enc', '-d', '-aes-128-cbc', '-in', '%s' % (VAR_17,), '-K', '%s' % (VAR_27,), '-iv', '%s' % (VAR_39,), '-out', '%s' % (VAR_21,), check_exit_code=False) if VAR_38: raise exception.Error(_('Failed to decrypt VAR_9 file ' '%(VAR_42)s: %(VAR_38)s') % {'image_file': VAR_17, 'err': VAR_38}) @staticmethod def FUNC_18(VAR_22, VAR_14): VAR_41 = tarfile.open(VAR_14, 'r|gz') for n in VAR_41.getnames(): if not os.path.abspath(os.path.join(VAR_22, n)).startswith(VAR_22): VAR_41.close() raise exception.Error(_('Unsafe filenames in image')) VAR_41.close() @staticmethod def FUNC_19(VAR_22, VAR_14): CLASS_0._test_for_malicious_tarball(VAR_22, VAR_14) VAR_41 = tarfile.open(VAR_14, 'r|gz') VAR_41.extractall(VAR_22) VAR_42 = VAR_41.getnames()[0] VAR_41.close() return os.path.join(VAR_22, VAR_42)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 27, 30, 39, 40, 49, 50, 53, 57, 60, 63, 66, 69, 78, 80, 87, 95, 97, 100, 102, 106, 110, 115, 117, 118, 121, 123, 124, 127, 132, 136, 140, 143, 144, 154, 161, 166, 175, 184, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 211, 215, 220, 223, 226, 229, 236, 237, 238, 240, 242, 243, 246, 247, 249, 252, 254, 261, 265, 272, 281, 282, 288, 295, 298, 304, 305, 306, 308, 319, 322, 331, 344, 348, 350, 352, 354, 376, 389, 397, 19, 52, 99, 100, 101, 102, 103, 251, 267 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 27, 30, 39, 40, 49, 50, 53, 57, 60, 63, 66, 69, 78, 80, 87, 95, 97, 100, 102, 106, 110, 115, 117, 118, 121, 123, 124, 127, 132, 136, 140, 143, 144, 154, 161, 166, 175, 184, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 211, 215, 220, 223, 226, 229, 236, 237, 238, 240, 242, 243, 246, 247, 249, 252, 254, 261, 265, 272, 281, 282, 288, 295, 298, 304, 305, 306, 308, 319, 322, 331, 344, 348, 350, 352, 354, 376, 389, 399, 408, 19, 52, 99, 100, 101, 102, 103, 251, 392, 267 ]
1CWE-79
__version__ = '2.6.0b0' if __name__ == '__main__': print(__version__)
__version__ = '2.6.0b1' if __name__ == '__main__': print(__version__)
xss
{ "code": [ "__version__ = '2.6.0b0'" ], "line_no": [ 1 ] }
{ "code": [ "__version__ = '2.6.0b1'" ], "line_no": [ 1 ] }
__version__ = '2.6.0b0' if __name__ == '__main__': print(__version__)
__version__ = '2.6.0b1' if __name__ == '__main__': print(__version__)
[ 2, 5 ]
[ 2, 5 ]
4CWE-601
import hashlib import hmac import logging import time from datetime import timedelta from urllib.parse import urlsplit, urlunsplit from flask import jsonify, redirect, request, url_for, session from flask_login import LoginManager, login_user, logout_user, user_logged_in from redash import models, settings from redash.authentication import jwt_auth from redash.authentication.org_resolving import current_org from redash.settings.organization import settings as org_settings from redash.tasks import record_event from sqlalchemy.orm.exc import NoResultFound from werkzeug.exceptions import Unauthorized login_manager = LoginManager() logger = logging.getLogger("authentication") def get_login_url(external=False, next="/"): if settings.MULTI_ORG and current_org == None: login_url = "/" elif settings.MULTI_ORG: login_url = url_for( "redash.login", org_slug=current_org.slug, next=next, _external=external ) else: login_url = url_for("redash.login", next=next, _external=external) return login_url def sign(key, path, expires): if not key: return None h = hmac.new(key.encode(), msg=path.encode(), digestmod=hashlib.sha1) h.update(str(expires).encode()) return h.hexdigest() @login_manager.user_loader def load_user(user_id_with_identity): user = api_key_load_user_from_request(request) if user: return user org = current_org._get_current_object() try: user_id, _ = user_id_with_identity.split("-") user = models.User.get_by_id_and_org(user_id, org) if user.is_disabled or user.get_id() != user_id_with_identity: return None return user except (models.NoResultFound, ValueError, AttributeError): return None def request_loader(request): user = None if settings.AUTH_TYPE == "hmac": user = hmac_load_user_from_request(request) elif settings.AUTH_TYPE == "api_key": user = api_key_load_user_from_request(request) else: logger.warning( "Unknown authentication type ({}). Using default (HMAC).".format( settings.AUTH_TYPE ) ) user = hmac_load_user_from_request(request) if org_settings["auth_jwt_login_enabled"] and user is None: user = jwt_token_load_user_from_request(request) return user def hmac_load_user_from_request(request): signature = request.args.get("signature") expires = float(request.args.get("expires") or 0) query_id = request.view_args.get("query_id", None) user_id = request.args.get("user_id", None) # TODO: 3600 should be a setting if signature and time.time() < expires <= time.time() + 3600: if user_id: user = models.User.query.get(user_id) calculated_signature = sign(user.api_key, request.path, expires) if user.api_key and signature == calculated_signature: return user if query_id: query = models.Query.query.filter(models.Query.id == query_id).one() calculated_signature = sign(query.api_key, request.path, expires) if query.api_key and signature == calculated_signature: return models.ApiUser( query.api_key, query.org, list(query.groups.keys()), name="ApiKey: Query {}".format(query.id), ) return None def get_user_from_api_key(api_key, query_id): if not api_key: return None user = None # TODO: once we switch all api key storage into the ApiKey model, this code will be much simplified org = current_org._get_current_object() try: user = models.User.get_by_api_key_and_org(api_key, org) if user.is_disabled: user = None except models.NoResultFound: try: api_key = models.ApiKey.get_by_api_key(api_key) user = models.ApiUser(api_key, api_key.org, []) except models.NoResultFound: if query_id: query = models.Query.get_by_id_and_org(query_id, org) if query and query.api_key == api_key: user = models.ApiUser( api_key, query.org, list(query.groups.keys()), name="ApiKey: Query {}".format(query.id), ) return user def get_api_key_from_request(request): api_key = request.args.get("api_key", None) if api_key is not None: return api_key if request.headers.get("Authorization"): auth_header = request.headers.get("Authorization") api_key = auth_header.replace("Key ", "", 1) elif request.view_args is not None and request.view_args.get("token"): api_key = request.view_args["token"] return api_key def api_key_load_user_from_request(request): api_key = get_api_key_from_request(request) if request.view_args is not None: query_id = request.view_args.get("query_id", None) user = get_user_from_api_key(api_key, query_id) else: user = None return user def jwt_token_load_user_from_request(request): org = current_org._get_current_object() payload = None if org_settings["auth_jwt_auth_cookie_name"]: jwt_token = request.cookies.get(org_settings["auth_jwt_auth_cookie_name"], None) elif org_settings["auth_jwt_auth_header_name"]: jwt_token = request.headers.get(org_settings["auth_jwt_auth_header_name"], None) else: return None if jwt_token: payload, token_is_valid = jwt_auth.verify_jwt_token( jwt_token, expected_issuer=org_settings["auth_jwt_auth_issuer"], expected_audience=org_settings["auth_jwt_auth_audience"], algorithms=org_settings["auth_jwt_auth_algorithms"], public_certs_url=org_settings["auth_jwt_auth_public_certs_url"], ) if not token_is_valid: raise Unauthorized("Invalid JWT token") if not payload: return try: user = models.User.get_by_email_and_org(payload["email"], org) except models.NoResultFound: user = create_and_login_user(current_org, payload["email"], payload["email"]) return user def log_user_logged_in(app, user): event = { "org_id": user.org_id, "user_id": user.id, "action": "login", "object_type": "redash", "timestamp": int(time.time()), "user_agent": request.user_agent.string, "ip": request.remote_addr, } record_event.delay(event) @login_manager.unauthorized_handler def redirect_to_login(): if request.is_xhr or "/api/" in request.path: response = jsonify( {"message": "Couldn't find resource. Please login and try again."} ) response.status_code = 404 return response login_url = get_login_url(next=request.url, external=False) return redirect(login_url) def logout_and_redirect_to_index(): logout_user() if settings.MULTI_ORG and current_org == None: index_url = "/" elif settings.MULTI_ORG: index_url = url_for("redash.index", org_slug=current_org.slug, _external=False) else: index_url = url_for("redash.index", _external=False) return redirect(index_url) def init_app(app): from redash.authentication import ( google_oauth, saml_auth, remote_user_auth, ldap_auth, ) login_manager.init_app(app) login_manager.anonymous_user = models.AnonymousUser login_manager.REMEMBER_COOKIE_DURATION = settings.REMEMBER_COOKIE_DURATION @app.before_request def extend_session(): session.permanent = True app.permanent_session_lifetime = timedelta(seconds=settings.SESSION_EXPIRY_TIME) from redash.security import csrf for auth in [google_oauth, saml_auth, remote_user_auth, ldap_auth]: blueprint = auth.blueprint csrf.exempt(blueprint) app.register_blueprint(blueprint) user_logged_in.connect(log_user_logged_in) login_manager.request_loader(request_loader) def create_and_login_user(org, name, email, picture=None): try: user_object = models.User.get_by_email_and_org(email, org) if user_object.is_disabled: return None if user_object.is_invitation_pending: user_object.is_invitation_pending = False models.db.session.commit() if user_object.name != name: logger.debug("Updating user name (%r -> %r)", user_object.name, name) user_object.name = name models.db.session.commit() except NoResultFound: logger.debug("Creating user object (%r)", name) user_object = models.User( org=org, name=name, email=email, is_invitation_pending=False, _profile_image_url=picture, group_ids=[org.default_group.id], ) models.db.session.add(user_object) models.db.session.commit() login_user(user_object, remember=True) return user_object def get_next_path(unsafe_next_path): if not unsafe_next_path: return "" # Preventing open redirection attacks parts = list(urlsplit(unsafe_next_path)) parts[0] = "" # clear scheme parts[1] = "" # clear netloc safe_next_path = urlunsplit(parts) # If the original path was a URL, we might end up with an empty # safe url, which will redirect to the login page. Changing to # relative root to redirect to the app root after login. if not safe_next_path: safe_next_path = "./" return safe_next_path
import hashlib import hmac import logging import time from datetime import timedelta from urllib.parse import urlsplit, urlunsplit from flask import jsonify, redirect, request, url_for, session from flask_login import LoginManager, login_user, logout_user, user_logged_in from redash import models, settings from redash.authentication import jwt_auth from redash.authentication.org_resolving import current_org from redash.settings.organization import settings as org_settings from redash.tasks import record_event from sqlalchemy.orm.exc import NoResultFound from werkzeug.exceptions import Unauthorized login_manager = LoginManager() logger = logging.getLogger("authentication") def get_login_url(external=False, next="/"): if settings.MULTI_ORG and current_org == None: login_url = "/" elif settings.MULTI_ORG: login_url = url_for( "redash.login", org_slug=current_org.slug, next=next, _external=external ) else: login_url = url_for("redash.login", next=next, _external=external) return login_url def sign(key, path, expires): if not key: return None h = hmac.new(key.encode(), msg=path.encode(), digestmod=hashlib.sha1) h.update(str(expires).encode()) return h.hexdigest() @login_manager.user_loader def load_user(user_id_with_identity): user = api_key_load_user_from_request(request) if user: return user org = current_org._get_current_object() try: user_id, _ = user_id_with_identity.split("-") user = models.User.get_by_id_and_org(user_id, org) if user.is_disabled or user.get_id() != user_id_with_identity: return None return user except (models.NoResultFound, ValueError, AttributeError): return None def request_loader(request): user = None if settings.AUTH_TYPE == "hmac": user = hmac_load_user_from_request(request) elif settings.AUTH_TYPE == "api_key": user = api_key_load_user_from_request(request) else: logger.warning( "Unknown authentication type ({}). Using default (HMAC).".format( settings.AUTH_TYPE ) ) user = hmac_load_user_from_request(request) if org_settings["auth_jwt_login_enabled"] and user is None: user = jwt_token_load_user_from_request(request) return user def hmac_load_user_from_request(request): signature = request.args.get("signature") expires = float(request.args.get("expires") or 0) query_id = request.view_args.get("query_id", None) user_id = request.args.get("user_id", None) # TODO: 3600 should be a setting if signature and time.time() < expires <= time.time() + 3600: if user_id: user = models.User.query.get(user_id) calculated_signature = sign(user.api_key, request.path, expires) if user.api_key and signature == calculated_signature: return user if query_id: query = models.Query.query.filter(models.Query.id == query_id).one() calculated_signature = sign(query.api_key, request.path, expires) if query.api_key and signature == calculated_signature: return models.ApiUser( query.api_key, query.org, list(query.groups.keys()), name="ApiKey: Query {}".format(query.id), ) return None def get_user_from_api_key(api_key, query_id): if not api_key: return None user = None # TODO: once we switch all api key storage into the ApiKey model, this code will be much simplified org = current_org._get_current_object() try: user = models.User.get_by_api_key_and_org(api_key, org) if user.is_disabled: user = None except models.NoResultFound: try: api_key = models.ApiKey.get_by_api_key(api_key) user = models.ApiUser(api_key, api_key.org, []) except models.NoResultFound: if query_id: query = models.Query.get_by_id_and_org(query_id, org) if query and query.api_key == api_key: user = models.ApiUser( api_key, query.org, list(query.groups.keys()), name="ApiKey: Query {}".format(query.id), ) return user def get_api_key_from_request(request): api_key = request.args.get("api_key", None) if api_key is not None: return api_key if request.headers.get("Authorization"): auth_header = request.headers.get("Authorization") api_key = auth_header.replace("Key ", "", 1) elif request.view_args is not None and request.view_args.get("token"): api_key = request.view_args["token"] return api_key def api_key_load_user_from_request(request): api_key = get_api_key_from_request(request) if request.view_args is not None: query_id = request.view_args.get("query_id", None) user = get_user_from_api_key(api_key, query_id) else: user = None return user def jwt_token_load_user_from_request(request): org = current_org._get_current_object() payload = None if org_settings["auth_jwt_auth_cookie_name"]: jwt_token = request.cookies.get(org_settings["auth_jwt_auth_cookie_name"], None) elif org_settings["auth_jwt_auth_header_name"]: jwt_token = request.headers.get(org_settings["auth_jwt_auth_header_name"], None) else: return None if jwt_token: payload, token_is_valid = jwt_auth.verify_jwt_token( jwt_token, expected_issuer=org_settings["auth_jwt_auth_issuer"], expected_audience=org_settings["auth_jwt_auth_audience"], algorithms=org_settings["auth_jwt_auth_algorithms"], public_certs_url=org_settings["auth_jwt_auth_public_certs_url"], ) if not token_is_valid: raise Unauthorized("Invalid JWT token") if not payload: return try: user = models.User.get_by_email_and_org(payload["email"], org) except models.NoResultFound: user = create_and_login_user(current_org, payload["email"], payload["email"]) return user def log_user_logged_in(app, user): event = { "org_id": user.org_id, "user_id": user.id, "action": "login", "object_type": "redash", "timestamp": int(time.time()), "user_agent": request.user_agent.string, "ip": request.remote_addr, } record_event.delay(event) @login_manager.unauthorized_handler def redirect_to_login(): if request.is_xhr or "/api/" in request.path: response = jsonify( {"message": "Couldn't find resource. Please login and try again."} ) response.status_code = 404 return response login_url = get_login_url(next=request.url, external=False) return redirect(login_url) def logout_and_redirect_to_index(): logout_user() if settings.MULTI_ORG and current_org == None: index_url = "/" elif settings.MULTI_ORG: index_url = url_for("redash.index", org_slug=current_org.slug, _external=False) else: index_url = url_for("redash.index", _external=False) return redirect(index_url) def init_app(app): from redash.authentication import ( saml_auth, remote_user_auth, ldap_auth, ) from redash.authentication.google_oauth import create_google_oauth_blueprint login_manager.init_app(app) login_manager.anonymous_user = models.AnonymousUser login_manager.REMEMBER_COOKIE_DURATION = settings.REMEMBER_COOKIE_DURATION @app.before_request def extend_session(): session.permanent = True app.permanent_session_lifetime = timedelta(seconds=settings.SESSION_EXPIRY_TIME) from redash.security import csrf # Authlib's flask oauth client requires a Flask app to initialize for blueprint in [create_google_oauth_blueprint(app), saml_auth.blueprint, remote_user_auth.blueprint, ldap_auth.blueprint, ]: csrf.exempt(blueprint) app.register_blueprint(blueprint) user_logged_in.connect(log_user_logged_in) login_manager.request_loader(request_loader) def create_and_login_user(org, name, email, picture=None): try: user_object = models.User.get_by_email_and_org(email, org) if user_object.is_disabled: return None if user_object.is_invitation_pending: user_object.is_invitation_pending = False models.db.session.commit() if user_object.name != name: logger.debug("Updating user name (%r -> %r)", user_object.name, name) user_object.name = name models.db.session.commit() except NoResultFound: logger.debug("Creating user object (%r)", name) user_object = models.User( org=org, name=name, email=email, is_invitation_pending=False, _profile_image_url=picture, group_ids=[org.default_group.id], ) models.db.session.add(user_object) models.db.session.commit() login_user(user_object, remember=True) return user_object def get_next_path(unsafe_next_path): if not unsafe_next_path: return "" # Preventing open redirection attacks parts = list(urlsplit(unsafe_next_path)) parts[0] = "" # clear scheme parts[1] = "" # clear netloc safe_next_path = urlunsplit(parts) # If the original path was a URL, we might end up with an empty # safe url, which will redirect to the login page. Changing to # relative root to redirect to the app root after login. if not safe_next_path: safe_next_path = "./" return safe_next_path
open_redirect
{ "code": [ " google_oauth,", " for auth in [google_oauth, saml_auth, remote_user_auth, ldap_auth]:", " blueprint = auth.blueprint" ], "line_no": [ 246, 262, 263 ] }
{ "code": [ " for blueprint in [create_google_oauth_blueprint(app), saml_auth.blueprint, remote_user_auth.blueprint, ldap_auth.blueprint, ]:" ], "line_no": [ 265 ] }
import .hashlib import .hmac import logging import time from datetime import timedelta from urllib.parse import urlsplit, urlunsplit from flask import jsonify, redirect, VAR_8, url_for, session from flask_login import LoginManager, login_user, logout_user, user_logged_in from redash import models, settings from redash.authentication import jwt_auth from redash.authentication.org_resolving import current_org from redash.settings.organization import settings as org_settings from redash.tasks import record_event from sqlalchemy.orm.exc import NoResultFound from werkzeug.exceptions import Unauthorized VAR_0 = LoginManager() VAR_1 = logging.getLogger("authentication") def FUNC_0(VAR_2=False, VAR_3="/"): if settings.MULTI_ORG and current_org == None: VAR_23 = "/" elif settings.MULTI_ORG: VAR_23 = url_for( "redash.login", org_slug=current_org.slug, VAR_3=next, _external=VAR_2 ) else: VAR_23 = url_for("redash.login", VAR_3=next, _external=VAR_2) return VAR_23 def FUNC_1(VAR_4, VAR_5, VAR_6): if not VAR_4: return None VAR_18 = hmac.new(VAR_4.encode(), msg=VAR_5.encode(), digestmod=hashlib.sha1) VAR_18.update(str(VAR_6).encode()) return VAR_18.hexdigest() @VAR_0.user_loader def FUNC_2(VAR_7): VAR_12 = FUNC_7(VAR_8) if VAR_12: return VAR_12 VAR_13 = current_org._get_current_object() try: VAR_20, VAR_26 = VAR_7.split("-") VAR_12 = models.User.get_by_id_and_org(VAR_20, VAR_13) if VAR_12.is_disabled or VAR_12.get_id() != VAR_7: return None return VAR_12 except (models.NoResultFound, ValueError, AttributeError): return None def FUNC_3(VAR_8): VAR_12 = None if settings.AUTH_TYPE == "hmac": VAR_12 = FUNC_4(VAR_8) elif settings.AUTH_TYPE == "api_key": VAR_12 = FUNC_7(VAR_8) else: VAR_1.warning( "Unknown authentication type ({}). Using default (HMAC).".format( settings.AUTH_TYPE ) ) VAR_12 = FUNC_4(VAR_8) if org_settings["auth_jwt_login_enabled"] and VAR_12 is None: VAR_12 = FUNC_8(VAR_8) return VAR_12 def FUNC_4(VAR_8): VAR_19 = VAR_8.args.get("signature") VAR_6 = float(VAR_8.args.get("expires") or 0) VAR_10 = VAR_8.view_args.get("query_id", None) VAR_20 = VAR_8.args.get("user_id", None) if VAR_19 and time.time() < VAR_6 <= time.time() + 3600: if VAR_20: VAR_12 = models.User.query.get(VAR_20) VAR_34 = FUNC_1(VAR_12.api_key, VAR_8.path, VAR_6) if VAR_12.api_key and VAR_19 == VAR_34: return VAR_12 if VAR_10: VAR_35 = models.Query.query.filter(models.Query.id == VAR_10).one() VAR_34 = FUNC_1(VAR_35.api_key, VAR_8.path, VAR_6) if VAR_35.api_key and VAR_19 == VAR_34: return models.ApiUser( VAR_35.api_key, VAR_35.org, list(VAR_35.groups.keys()), VAR_14="ApiKey: Query {}".format(VAR_35.id), ) return None def FUNC_5(VAR_9, VAR_10): if not VAR_9: return None VAR_12 = None VAR_13 = current_org._get_current_object() try: VAR_12 = models.User.get_by_api_key_and_org(VAR_9, VAR_13) if VAR_12.is_disabled: VAR_12 = None except models.NoResultFound: try: VAR_9 = models.ApiKey.get_by_api_key(VAR_9) VAR_12 = models.ApiUser(VAR_9, api_key.org, []) except models.NoResultFound: if VAR_10: VAR_35 = models.Query.get_by_id_and_org(VAR_10, VAR_13) if VAR_35 and VAR_35.api_key == VAR_9: VAR_12 = models.ApiUser( VAR_9, VAR_35.org, list(VAR_35.groups.keys()), VAR_14="ApiKey: Query {}".format(VAR_35.id), ) return VAR_12 def FUNC_6(VAR_8): VAR_9 = VAR_8.args.get("api_key", None) if VAR_9 is not None: return VAR_9 if VAR_8.headers.get("Authorization"): VAR_27 = VAR_8.headers.get("Authorization") VAR_9 = VAR_27.replace("Key ", "", 1) elif VAR_8.view_args is not None and VAR_8.view_args.get("token"): VAR_9 = VAR_8.view_args["token"] return VAR_9 def FUNC_7(VAR_8): VAR_9 = FUNC_6(VAR_8) if VAR_8.view_args is not None: VAR_10 = VAR_8.view_args.get("query_id", None) VAR_12 = FUNC_5(VAR_9, VAR_10) else: VAR_12 = None return VAR_12 def FUNC_8(VAR_8): VAR_13 = current_org._get_current_object() VAR_21 = None if org_settings["auth_jwt_auth_cookie_name"]: VAR_28 = VAR_8.cookies.get(org_settings["auth_jwt_auth_cookie_name"], None) elif org_settings["auth_jwt_auth_header_name"]: VAR_28 = VAR_8.headers.get(org_settings["auth_jwt_auth_header_name"], None) else: return None if VAR_28: VAR_21, VAR_29 = jwt_auth.verify_jwt_token( VAR_28, expected_issuer=org_settings["auth_jwt_auth_issuer"], expected_audience=org_settings["auth_jwt_auth_audience"], algorithms=org_settings["auth_jwt_auth_algorithms"], public_certs_url=org_settings["auth_jwt_auth_public_certs_url"], ) if not VAR_29: raise Unauthorized("Invalid JWT token") if not VAR_21: return try: VAR_12 = models.User.get_by_email_and_org(VAR_21["email"], VAR_13) except models.NoResultFound: VAR_12 = FUNC_13(current_org, VAR_21["email"], VAR_21["email"]) return VAR_12 def FUNC_9(VAR_11, VAR_12): VAR_22 = { "org_id": VAR_12.org_id, "user_id": VAR_12.id, "action": "login", "object_type": "redash", "timestamp": int(time.time()), "user_agent": VAR_8.user_agent.string, "ip": VAR_8.remote_addr, } record_event.delay(VAR_22) @VAR_0.unauthorized_handler def FUNC_10(): if VAR_8.is_xhr or "/api/" in VAR_8.path: VAR_30 = jsonify( {"message": "Couldn't find resource. Please login and try again."} ) VAR_30.status_code = 404 return VAR_30 VAR_23 = FUNC_0(VAR_3=VAR_8.url, VAR_2=False) return redirect(VAR_23) def FUNC_11(): logout_user() if settings.MULTI_ORG and current_org == None: VAR_31 = "/" elif settings.MULTI_ORG: VAR_31 = url_for("redash.index", org_slug=current_org.slug, _external=False) else: VAR_31 = url_for("redash.index", _external=False) return redirect(VAR_31) def FUNC_12(VAR_11): from redash.authentication import ( google_oauth, saml_auth, remote_user_auth, ldap_auth, ) VAR_0.init_app(VAR_11) VAR_0.anonymous_user = models.AnonymousUser VAR_0.REMEMBER_COOKIE_DURATION = settings.REMEMBER_COOKIE_DURATION @VAR_11.before_request def FUNC_15(): session.permanent = True VAR_11.permanent_session_lifetime = timedelta(seconds=settings.SESSION_EXPIRY_TIME) from redash.security import csrf for auth in [google_oauth, saml_auth, remote_user_auth, ldap_auth]: VAR_32 = auth.blueprint csrf.exempt(VAR_32) VAR_11.register_blueprint(VAR_32) user_logged_in.connect(FUNC_9) VAR_0.request_loader(FUNC_3) def FUNC_13(VAR_13, VAR_14, VAR_15, VAR_16=None): try: VAR_33 = models.User.get_by_email_and_org(VAR_15, VAR_13) if VAR_33.is_disabled: return None if VAR_33.is_invitation_pending: VAR_33.is_invitation_pending = False models.db.session.commit() if VAR_33.name != VAR_14: VAR_1.debug("Updating VAR_12 VAR_14 (%r -> %r)", VAR_33.name, VAR_14) VAR_33.name = VAR_14 models.db.session.commit() except NoResultFound: VAR_1.debug("Creating VAR_12 object (%r)", VAR_14) VAR_33 = models.User( VAR_13=org, VAR_14=name, VAR_15=email, is_invitation_pending=False, _profile_image_url=VAR_16, group_ids=[VAR_13.default_group.id], ) models.db.session.add(VAR_33) models.db.session.commit() login_user(VAR_33, remember=True) return VAR_33 def FUNC_14(VAR_17): if not VAR_17: return "" VAR_24 = list(urlsplit(VAR_17)) VAR_24[0] = "" # clear scheme VAR_24[1] = "" # clear netloc VAR_25 = urlunsplit(VAR_24) if not VAR_25: safe_next_path = "./" return VAR_25
import .hashlib import .hmac import logging import time from datetime import timedelta from urllib.parse import urlsplit, urlunsplit from flask import jsonify, redirect, VAR_8, url_for, session from flask_login import LoginManager, login_user, logout_user, user_logged_in from redash import models, settings from redash.authentication import jwt_auth from redash.authentication.org_resolving import current_org from redash.settings.organization import settings as org_settings from redash.tasks import record_event from sqlalchemy.orm.exc import NoResultFound from werkzeug.exceptions import Unauthorized VAR_0 = LoginManager() VAR_1 = logging.getLogger("authentication") def FUNC_0(VAR_2=False, VAR_3="/"): if settings.MULTI_ORG and current_org == None: VAR_23 = "/" elif settings.MULTI_ORG: VAR_23 = url_for( "redash.login", org_slug=current_org.slug, VAR_3=next, _external=VAR_2 ) else: VAR_23 = url_for("redash.login", VAR_3=next, _external=VAR_2) return VAR_23 def FUNC_1(VAR_4, VAR_5, VAR_6): if not VAR_4: return None VAR_18 = hmac.new(VAR_4.encode(), msg=VAR_5.encode(), digestmod=hashlib.sha1) VAR_18.update(str(VAR_6).encode()) return VAR_18.hexdigest() @VAR_0.user_loader def FUNC_2(VAR_7): VAR_12 = FUNC_7(VAR_8) if VAR_12: return VAR_12 VAR_13 = current_org._get_current_object() try: VAR_20, VAR_26 = VAR_7.split("-") VAR_12 = models.User.get_by_id_and_org(VAR_20, VAR_13) if VAR_12.is_disabled or VAR_12.get_id() != VAR_7: return None return VAR_12 except (models.NoResultFound, ValueError, AttributeError): return None def FUNC_3(VAR_8): VAR_12 = None if settings.AUTH_TYPE == "hmac": VAR_12 = FUNC_4(VAR_8) elif settings.AUTH_TYPE == "api_key": VAR_12 = FUNC_7(VAR_8) else: VAR_1.warning( "Unknown authentication type ({}). Using default (HMAC).".format( settings.AUTH_TYPE ) ) VAR_12 = FUNC_4(VAR_8) if org_settings["auth_jwt_login_enabled"] and VAR_12 is None: VAR_12 = FUNC_8(VAR_8) return VAR_12 def FUNC_4(VAR_8): VAR_19 = VAR_8.args.get("signature") VAR_6 = float(VAR_8.args.get("expires") or 0) VAR_10 = VAR_8.view_args.get("query_id", None) VAR_20 = VAR_8.args.get("user_id", None) if VAR_19 and time.time() < VAR_6 <= time.time() + 3600: if VAR_20: VAR_12 = models.User.query.get(VAR_20) VAR_33 = FUNC_1(VAR_12.api_key, VAR_8.path, VAR_6) if VAR_12.api_key and VAR_19 == VAR_33: return VAR_12 if VAR_10: VAR_34 = models.Query.query.filter(models.Query.id == VAR_10).one() VAR_33 = FUNC_1(VAR_34.api_key, VAR_8.path, VAR_6) if VAR_34.api_key and VAR_19 == VAR_33: return models.ApiUser( VAR_34.api_key, VAR_34.org, list(VAR_34.groups.keys()), VAR_14="ApiKey: Query {}".format(VAR_34.id), ) return None def FUNC_5(VAR_9, VAR_10): if not VAR_9: return None VAR_12 = None VAR_13 = current_org._get_current_object() try: VAR_12 = models.User.get_by_api_key_and_org(VAR_9, VAR_13) if VAR_12.is_disabled: VAR_12 = None except models.NoResultFound: try: VAR_9 = models.ApiKey.get_by_api_key(VAR_9) VAR_12 = models.ApiUser(VAR_9, api_key.org, []) except models.NoResultFound: if VAR_10: VAR_34 = models.Query.get_by_id_and_org(VAR_10, VAR_13) if VAR_34 and VAR_34.api_key == VAR_9: VAR_12 = models.ApiUser( VAR_9, VAR_34.org, list(VAR_34.groups.keys()), VAR_14="ApiKey: Query {}".format(VAR_34.id), ) return VAR_12 def FUNC_6(VAR_8): VAR_9 = VAR_8.args.get("api_key", None) if VAR_9 is not None: return VAR_9 if VAR_8.headers.get("Authorization"): VAR_27 = VAR_8.headers.get("Authorization") VAR_9 = VAR_27.replace("Key ", "", 1) elif VAR_8.view_args is not None and VAR_8.view_args.get("token"): VAR_9 = VAR_8.view_args["token"] return VAR_9 def FUNC_7(VAR_8): VAR_9 = FUNC_6(VAR_8) if VAR_8.view_args is not None: VAR_10 = VAR_8.view_args.get("query_id", None) VAR_12 = FUNC_5(VAR_9, VAR_10) else: VAR_12 = None return VAR_12 def FUNC_8(VAR_8): VAR_13 = current_org._get_current_object() VAR_21 = None if org_settings["auth_jwt_auth_cookie_name"]: VAR_28 = VAR_8.cookies.get(org_settings["auth_jwt_auth_cookie_name"], None) elif org_settings["auth_jwt_auth_header_name"]: VAR_28 = VAR_8.headers.get(org_settings["auth_jwt_auth_header_name"], None) else: return None if VAR_28: VAR_21, VAR_29 = jwt_auth.verify_jwt_token( VAR_28, expected_issuer=org_settings["auth_jwt_auth_issuer"], expected_audience=org_settings["auth_jwt_auth_audience"], algorithms=org_settings["auth_jwt_auth_algorithms"], public_certs_url=org_settings["auth_jwt_auth_public_certs_url"], ) if not VAR_29: raise Unauthorized("Invalid JWT token") if not VAR_21: return try: VAR_12 = models.User.get_by_email_and_org(VAR_21["email"], VAR_13) except models.NoResultFound: VAR_12 = FUNC_13(current_org, VAR_21["email"], VAR_21["email"]) return VAR_12 def FUNC_9(VAR_11, VAR_12): VAR_22 = { "org_id": VAR_12.org_id, "user_id": VAR_12.id, "action": "login", "object_type": "redash", "timestamp": int(time.time()), "user_agent": VAR_8.user_agent.string, "ip": VAR_8.remote_addr, } record_event.delay(VAR_22) @VAR_0.unauthorized_handler def FUNC_10(): if VAR_8.is_xhr or "/api/" in VAR_8.path: VAR_30 = jsonify( {"message": "Couldn't find resource. Please login and try again."} ) VAR_30.status_code = 404 return VAR_30 VAR_23 = FUNC_0(VAR_3=VAR_8.url, VAR_2=False) return redirect(VAR_23) def FUNC_11(): logout_user() if settings.MULTI_ORG and current_org == None: VAR_31 = "/" elif settings.MULTI_ORG: VAR_31 = url_for("redash.index", org_slug=current_org.slug, _external=False) else: VAR_31 = url_for("redash.index", _external=False) return redirect(VAR_31) def FUNC_12(VAR_11): from redash.authentication import ( saml_auth, remote_user_auth, ldap_auth, ) from redash.authentication.google_oauth import create_google_oauth_blueprint VAR_0.init_app(VAR_11) VAR_0.anonymous_user = models.AnonymousUser VAR_0.REMEMBER_COOKIE_DURATION = settings.REMEMBER_COOKIE_DURATION @VAR_11.before_request def FUNC_15(): session.permanent = True VAR_11.permanent_session_lifetime = timedelta(seconds=settings.SESSION_EXPIRY_TIME) from redash.security import csrf for blueprint in [create_google_oauth_blueprint(VAR_11), saml_auth.blueprint, remote_user_auth.blueprint, ldap_auth.blueprint, ]: csrf.exempt(blueprint) VAR_11.register_blueprint(blueprint) user_logged_in.connect(FUNC_9) VAR_0.request_loader(FUNC_3) def FUNC_13(VAR_13, VAR_14, VAR_15, VAR_16=None): try: VAR_32 = models.User.get_by_email_and_org(VAR_15, VAR_13) if VAR_32.is_disabled: return None if VAR_32.is_invitation_pending: VAR_32.is_invitation_pending = False models.db.session.commit() if VAR_32.name != VAR_14: VAR_1.debug("Updating VAR_12 VAR_14 (%r -> %r)", VAR_32.name, VAR_14) VAR_32.name = VAR_14 models.db.session.commit() except NoResultFound: VAR_1.debug("Creating VAR_12 object (%r)", VAR_14) VAR_32 = models.User( VAR_13=org, VAR_14=name, VAR_15=email, is_invitation_pending=False, _profile_image_url=VAR_16, group_ids=[VAR_13.default_group.id], ) models.db.session.add(VAR_32) models.db.session.commit() login_user(VAR_32, remember=True) return VAR_32 def FUNC_14(VAR_17): if not VAR_17: return "" VAR_24 = list(urlsplit(VAR_17)) VAR_24[0] = "" # clear scheme VAR_24[1] = "" # clear netloc VAR_25 = urlunsplit(VAR_24) if not VAR_25: safe_next_path = "./" return VAR_25
[ 7, 17, 20, 21, 31, 33, 34, 38, 41, 43, 44, 50, 52, 58, 62, 63, 77, 81, 82, 88, 89, 94, 97, 101, 109, 111, 112, 116, 118, 119, 139, 141, 142, 145, 148, 154, 156, 157, 165, 167, 168, 171, 173, 180, 191, 194, 199, 201, 202, 213, 215, 216, 225, 227, 229, 230, 233, 240, 242, 243, 251, 255, 260, 266, 269, 270, 295, 297, 299, 300, 304, 305, 310, 311, 312, 313, 316, 318 ]
[ 7, 17, 20, 21, 31, 33, 34, 38, 41, 43, 44, 50, 52, 58, 62, 63, 77, 81, 82, 88, 89, 94, 97, 101, 109, 111, 112, 116, 118, 119, 139, 141, 142, 145, 148, 154, 156, 157, 165, 167, 168, 171, 173, 180, 191, 194, 199, 201, 202, 213, 215, 216, 225, 227, 229, 230, 233, 240, 242, 243, 250, 252, 256, 261, 263, 264, 268, 271, 272, 297, 299, 301, 302, 306, 307, 312, 313, 314, 315, 318, 320 ]
1CWE-79
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt # Search from __future__ import unicode_literals import frappe, json from frappe.utils import cstr, unique, cint from frappe.permissions import has_permission from frappe.handler import is_whitelisted from frappe import _ from six import string_types import re import wrapt UNTRANSLATED_DOCTYPES = ["DocType", "Role"] def sanitize_searchfield(searchfield): blacklisted_keywords = ['select', 'delete', 'drop', 'update', 'case', 'and', 'or', 'like'] def _raise_exception(searchfield): frappe.throw(_('Invalid Search Field {0}').format(searchfield), frappe.DataError) if len(searchfield) == 1: # do not allow special characters to pass as searchfields regex = re.compile(r'^.*[=;*,\'"$\-+%#@()_].*') if regex.match(searchfield): _raise_exception(searchfield) if len(searchfield) >= 3: # to avoid 1=1 if '=' in searchfield: _raise_exception(searchfield) # in mysql -- is used for commenting the query elif ' --' in searchfield: _raise_exception(searchfield) # to avoid and, or and like elif any(' {0} '.format(keyword) in searchfield.split() for keyword in blacklisted_keywords): _raise_exception(searchfield) # to avoid select, delete, drop, update and case elif any(keyword in searchfield.split() for keyword in blacklisted_keywords): _raise_exception(searchfield) else: regex = re.compile(r'^.*[=;*,\'"$\-+%#@()].*') if any(regex.match(f) for f in searchfield.split()): _raise_exception(searchfield) # this is called by the Link Field @frappe.whitelist() def search_link(doctype, txt, query=None, filters=None, page_length=20, searchfield=None, reference_doctype=None, ignore_user_permissions=False): search_widget(doctype, txt.strip(), query, searchfield=searchfield, page_length=page_length, filters=filters, reference_doctype=reference_doctype, ignore_user_permissions=ignore_user_permissions) frappe.response['results'] = build_for_autosuggest(frappe.response["values"]) del frappe.response["values"] # this is called by the search box @frappe.whitelist() def search_widget(doctype, txt, query=None, searchfield=None, start=0, page_length=20, filters=None, filter_fields=None, as_dict=False, reference_doctype=None, ignore_user_permissions=False): start = cint(start) if isinstance(filters, string_types): filters = json.loads(filters) if searchfield: sanitize_searchfield(searchfield) if not searchfield: searchfield = "name" standard_queries = frappe.get_hooks().standard_queries or {} if query and query.split()[0].lower()!="select": # by method try: is_whitelisted(frappe.get_attr(query)) frappe.response["values"] = frappe.call(query, doctype, txt, searchfield, start, page_length, filters, as_dict=as_dict) except frappe.exceptions.PermissionError as e: if frappe.local.conf.developer_mode: raise e else: frappe.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return except Exception as e: raise e elif not query and doctype in standard_queries: # from standard queries search_widget(doctype, txt, standard_queries[doctype][0], searchfield, start, page_length, filters) else: meta = frappe.get_meta(doctype) if query: frappe.throw(_("This query style is discontinued")) # custom query # frappe.response["values"] = frappe.db.sql(scrub_custom_query(query, searchfield, txt)) else: if isinstance(filters, dict): filters_items = filters.items() filters = [] for f in filters_items: if isinstance(f[1], (list, tuple)): filters.append([doctype, f[0], f[1][0], f[1][1]]) else: filters.append([doctype, f[0], "=", f[1]]) if filters==None: filters = [] or_filters = [] # build from doctype if txt: search_fields = ["name"] if meta.title_field: search_fields.append(meta.title_field) if meta.search_fields: search_fields.extend(meta.get_search_fields()) for f in search_fields: fmeta = meta.get_field(f.strip()) if (doctype not in UNTRANSLATED_DOCTYPES) and (f == "name" or (fmeta and fmeta.fieldtype in ["Data", "Text", "Small Text", "Long Text", "Link", "Select", "Read Only", "Text Editor"])): or_filters.append([doctype, f.strip(), "like", "%{0}%".format(txt)]) if meta.get("fields", {"fieldname":"enabled", "fieldtype":"Check"}): filters.append([doctype, "enabled", "=", 1]) if meta.get("fields", {"fieldname":"disabled", "fieldtype":"Check"}): filters.append([doctype, "disabled", "!=", 1]) # format a list of fields combining search fields and filter fields fields = get_std_fields_list(meta, searchfield or "name") if filter_fields: fields = list(set(fields + json.loads(filter_fields))) formatted_fields = ['`tab%s`.`%s`' % (meta.name, f.strip()) for f in fields] # find relevance as location of search term from the beginning of string `name`. used for sorting results. formatted_fields.append("""locate({_txt}, `tab{doctype}`.`name`) as `_relevance`""".format( _txt=frappe.db.escape((txt or "").replace("%", "").replace("@", "")), doctype=doctype)) # In order_by, `idx` gets second priority, because it stores link count from frappe.model.db_query import get_order_by order_by_based_on_meta = get_order_by(doctype, meta) # 2 is the index of _relevance column order_by = "_relevance, {0}, `tab{1}`.idx desc".format(order_by_based_on_meta, doctype) ptype = 'select' if frappe.only_has_select_perm(doctype) else 'read' ignore_permissions = True if doctype == "DocType" else (cint(ignore_user_permissions) and has_permission(doctype, ptype=ptype)) if doctype in UNTRANSLATED_DOCTYPES: page_length = None values = frappe.get_list(doctype, filters=filters, fields=formatted_fields, or_filters=or_filters, limit_start=start, limit_page_length=page_length, order_by=order_by, ignore_permissions=ignore_permissions, reference_doctype=reference_doctype, as_list=not as_dict, strict=False) if doctype in UNTRANSLATED_DOCTYPES: values = tuple([v for v in list(values) if re.search(re.escape(txt)+".*", (_(v.name) if as_dict else _(v[0])), re.IGNORECASE)]) # remove _relevance from results if as_dict: for r in values: r.pop("_relevance") frappe.response["values"] = values else: frappe.response["values"] = [r[:-1] for r in values] def get_std_fields_list(meta, key): # get additional search fields sflist = ["name"] if meta.search_fields: for d in meta.search_fields.split(","): if d.strip() not in sflist: sflist.append(d.strip()) if meta.title_field and meta.title_field not in sflist: sflist.append(meta.title_field) if key not in sflist: sflist.append(key) return sflist def build_for_autosuggest(res): results = [] for r in res: out = {"value": r[0], "description": ", ".join(unique(cstr(d) for d in r if d)[1:])} results.append(out) return results def scrub_custom_query(query, key, txt): if '%(key)s' in query: query = query.replace('%(key)s', key) if '%s' in query: query = query.replace('%s', ((txt or '') + '%')) return query @wrapt.decorator def validate_and_sanitize_search_inputs(fn, instance, args, kwargs): kwargs.update(dict(zip(fn.__code__.co_varnames, args))) sanitize_searchfield(kwargs['searchfield']) kwargs['start'] = cint(kwargs['start']) kwargs['page_len'] = cint(kwargs['page_len']) if kwargs['doctype'] and not frappe.db.exists('DocType', kwargs['doctype']): return [] return fn(**kwargs)
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt # Search from __future__ import unicode_literals import frappe, json from frappe.utils import cstr, unique, cint from frappe.permissions import has_permission from frappe import _, is_whitelisted from six import string_types import re import wrapt UNTRANSLATED_DOCTYPES = ["DocType", "Role"] def sanitize_searchfield(searchfield): blacklisted_keywords = ['select', 'delete', 'drop', 'update', 'case', 'and', 'or', 'like'] def _raise_exception(searchfield): frappe.throw(_('Invalid Search Field {0}').format(searchfield), frappe.DataError) if len(searchfield) == 1: # do not allow special characters to pass as searchfields regex = re.compile(r'^.*[=;*,\'"$\-+%#@()_].*') if regex.match(searchfield): _raise_exception(searchfield) if len(searchfield) >= 3: # to avoid 1=1 if '=' in searchfield: _raise_exception(searchfield) # in mysql -- is used for commenting the query elif ' --' in searchfield: _raise_exception(searchfield) # to avoid and, or and like elif any(' {0} '.format(keyword) in searchfield.split() for keyword in blacklisted_keywords): _raise_exception(searchfield) # to avoid select, delete, drop, update and case elif any(keyword in searchfield.split() for keyword in blacklisted_keywords): _raise_exception(searchfield) else: regex = re.compile(r'^.*[=;*,\'"$\-+%#@()].*') if any(regex.match(f) for f in searchfield.split()): _raise_exception(searchfield) # this is called by the Link Field @frappe.whitelist() def search_link(doctype, txt, query=None, filters=None, page_length=20, searchfield=None, reference_doctype=None, ignore_user_permissions=False): search_widget(doctype, txt.strip(), query, searchfield=searchfield, page_length=page_length, filters=filters, reference_doctype=reference_doctype, ignore_user_permissions=ignore_user_permissions) frappe.response['results'] = build_for_autosuggest(frappe.response["values"]) del frappe.response["values"] # this is called by the search box @frappe.whitelist() def search_widget(doctype, txt, query=None, searchfield=None, start=0, page_length=20, filters=None, filter_fields=None, as_dict=False, reference_doctype=None, ignore_user_permissions=False): start = cint(start) if isinstance(filters, string_types): filters = json.loads(filters) if searchfield: sanitize_searchfield(searchfield) if not searchfield: searchfield = "name" standard_queries = frappe.get_hooks().standard_queries or {} if query and query.split()[0].lower()!="select": # by method try: is_whitelisted(frappe.get_attr(query)) frappe.response["values"] = frappe.call(query, doctype, txt, searchfield, start, page_length, filters, as_dict=as_dict) except frappe.exceptions.PermissionError as e: if frappe.local.conf.developer_mode: raise e else: frappe.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return except Exception as e: raise e elif not query and doctype in standard_queries: # from standard queries search_widget(doctype, txt, standard_queries[doctype][0], searchfield, start, page_length, filters) else: meta = frappe.get_meta(doctype) if query: frappe.throw(_("This query style is discontinued")) # custom query # frappe.response["values"] = frappe.db.sql(scrub_custom_query(query, searchfield, txt)) else: if isinstance(filters, dict): filters_items = filters.items() filters = [] for f in filters_items: if isinstance(f[1], (list, tuple)): filters.append([doctype, f[0], f[1][0], f[1][1]]) else: filters.append([doctype, f[0], "=", f[1]]) if filters==None: filters = [] or_filters = [] # build from doctype if txt: search_fields = ["name"] if meta.title_field: search_fields.append(meta.title_field) if meta.search_fields: search_fields.extend(meta.get_search_fields()) for f in search_fields: fmeta = meta.get_field(f.strip()) if (doctype not in UNTRANSLATED_DOCTYPES) and (f == "name" or (fmeta and fmeta.fieldtype in ["Data", "Text", "Small Text", "Long Text", "Link", "Select", "Read Only", "Text Editor"])): or_filters.append([doctype, f.strip(), "like", "%{0}%".format(txt)]) if meta.get("fields", {"fieldname":"enabled", "fieldtype":"Check"}): filters.append([doctype, "enabled", "=", 1]) if meta.get("fields", {"fieldname":"disabled", "fieldtype":"Check"}): filters.append([doctype, "disabled", "!=", 1]) # format a list of fields combining search fields and filter fields fields = get_std_fields_list(meta, searchfield or "name") if filter_fields: fields = list(set(fields + json.loads(filter_fields))) formatted_fields = ['`tab%s`.`%s`' % (meta.name, f.strip()) for f in fields] # find relevance as location of search term from the beginning of string `name`. used for sorting results. formatted_fields.append("""locate({_txt}, `tab{doctype}`.`name`) as `_relevance`""".format( _txt=frappe.db.escape((txt or "").replace("%", "").replace("@", "")), doctype=doctype)) # In order_by, `idx` gets second priority, because it stores link count from frappe.model.db_query import get_order_by order_by_based_on_meta = get_order_by(doctype, meta) # 2 is the index of _relevance column order_by = "_relevance, {0}, `tab{1}`.idx desc".format(order_by_based_on_meta, doctype) ptype = 'select' if frappe.only_has_select_perm(doctype) else 'read' ignore_permissions = True if doctype == "DocType" else (cint(ignore_user_permissions) and has_permission(doctype, ptype=ptype)) if doctype in UNTRANSLATED_DOCTYPES: page_length = None values = frappe.get_list(doctype, filters=filters, fields=formatted_fields, or_filters=or_filters, limit_start=start, limit_page_length=page_length, order_by=order_by, ignore_permissions=ignore_permissions, reference_doctype=reference_doctype, as_list=not as_dict, strict=False) if doctype in UNTRANSLATED_DOCTYPES: values = tuple([v for v in list(values) if re.search(re.escape(txt)+".*", (_(v.name) if as_dict else _(v[0])), re.IGNORECASE)]) # remove _relevance from results if as_dict: for r in values: r.pop("_relevance") frappe.response["values"] = values else: frappe.response["values"] = [r[:-1] for r in values] def get_std_fields_list(meta, key): # get additional search fields sflist = ["name"] if meta.search_fields: for d in meta.search_fields.split(","): if d.strip() not in sflist: sflist.append(d.strip()) if meta.title_field and meta.title_field not in sflist: sflist.append(meta.title_field) if key not in sflist: sflist.append(key) return sflist def build_for_autosuggest(res): results = [] for r in res: out = {"value": r[0], "description": ", ".join(unique(cstr(d) for d in r if d)[1:])} results.append(out) return results def scrub_custom_query(query, key, txt): if '%(key)s' in query: query = query.replace('%(key)s', key) if '%s' in query: query = query.replace('%s', ((txt or '') + '%')) return query @wrapt.decorator def validate_and_sanitize_search_inputs(fn, instance, args, kwargs): kwargs.update(dict(zip(fn.__code__.co_varnames, args))) sanitize_searchfield(kwargs['searchfield']) kwargs['start'] = cint(kwargs['start']) kwargs['page_len'] = cint(kwargs['page_len']) if kwargs['doctype'] and not frappe.db.exists('DocType', kwargs['doctype']): return [] return fn(**kwargs)
xss
{ "code": [ "from frappe.handler import is_whitelisted", "from frappe import _", "\treturn fn(**kwargs)" ], "line_no": [ 9, 10, 224 ] }
{ "code": [ "from frappe import _, is_whitelisted" ], "line_no": [ 9 ] }
from __future__ import unicode_literals import .frappe, json from VAR_20.utils import cstr, unique, cint from VAR_20.permissions import has_permission from VAR_20.handler import is_whitelisted from VAR_20 import _ from six import string_types import re import wrapt VAR_0 = ["DocType", "Role"] def FUNC_0(VAR_1): VAR_19 = ['select', 'delete', 'drop', 'update', 'case', 'and', 'or', 'like'] def FUNC_7(VAR_1): VAR_20.throw(_('Invalid Search Field {0}').format(VAR_1), VAR_20.DataError) if len(VAR_1) == 1: VAR_24 = re.compile(r'^.*[=;*,\'"$\-+%#@()_].*') if VAR_24.match(VAR_1): FUNC_7(VAR_1) if len(VAR_1) >= 3: if '=' in VAR_1: FUNC_7(VAR_1) elif ' --' in VAR_1: FUNC_7(VAR_1) elif any(' {0} '.format(keyword) in VAR_1.split() for keyword in VAR_19): FUNC_7(VAR_1) elif any(keyword in VAR_1.split() for keyword in VAR_19): FUNC_7(VAR_1) else: VAR_24 = re.compile(r'^.*[=;*,\'"$\-+%#@()].*') if any(VAR_24.match(f) for f in VAR_1.split()): FUNC_7(VAR_1) @VAR_20.whitelist() def FUNC_1(VAR_2, VAR_3, VAR_4=None, VAR_5=None, VAR_6=20, VAR_1=None, VAR_7=None, VAR_8=False): FUNC_2(VAR_2, VAR_3.strip(), VAR_4, VAR_1=searchfield, VAR_6=page_length, VAR_5=filters, VAR_7=reference_doctype, VAR_8=ignore_user_permissions) VAR_20.response['results'] = FUNC_4(VAR_20.response["values"]) del VAR_20.response["values"] @VAR_20.whitelist() def FUNC_2(VAR_2, VAR_3, VAR_4=None, VAR_1=None, VAR_9=0, VAR_6=20, VAR_5=None, VAR_10=None, VAR_11=False, VAR_7=None, VAR_8=False): VAR_9 = cint(VAR_9) if isinstance(VAR_5, string_types): VAR_5 = json.loads(VAR_5) if VAR_1: FUNC_0(VAR_1) if not VAR_1: searchfield = "name" VAR_21 = VAR_20.get_hooks().standard_queries or {} if VAR_4 and VAR_4.split()[0].lower()!="select": try: is_whitelisted(VAR_20.get_attr(VAR_4)) VAR_20.response["values"] = VAR_20.call(VAR_4, VAR_2, VAR_3, VAR_1, VAR_9, VAR_6, VAR_5, VAR_11=as_dict) except VAR_20.exceptions.PermissionError as e: if VAR_20.local.conf.developer_mode: raise e else: VAR_20.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return except Exception as e: raise e elif not VAR_4 and VAR_2 in VAR_21: FUNC_2(VAR_2, VAR_3, VAR_21[VAR_2][0], VAR_1, VAR_9, VAR_6, VAR_5) else: VAR_12 = VAR_20.get_meta(VAR_2) if VAR_4: VAR_20.throw(_("This VAR_4 style is discontinued")) else: if isinstance(VAR_5, dict): VAR_34 = VAR_5.items() VAR_5 = [] for f in VAR_34: if isinstance(f[1], (list, tuple)): VAR_5.append([VAR_2, f[0], f[1][0], f[1][1]]) else: VAR_5.append([VAR_2, f[0], "=", f[1]]) if VAR_5==None: VAR_5 = [] VAR_26 = [] if VAR_3: VAR_35 = ["name"] if VAR_12.title_field: VAR_35.append(VAR_12.title_field) if VAR_12.search_fields: VAR_35.extend(VAR_12.get_search_fields()) for f in VAR_35: VAR_36 = VAR_12.get_field(f.strip()) if (VAR_2 not in VAR_0) and (f == "name" or (VAR_36 and VAR_36.fieldtype in ["Data", "Text", "Small Text", "Long Text", "Link", "Select", "Read Only", "Text Editor"])): VAR_26.append([VAR_2, f.strip(), "like", "%{0}%".format(VAR_3)]) if VAR_12.get("fields", {"fieldname":"enabled", "fieldtype":"Check"}): VAR_5.append([VAR_2, "enabled", "=", 1]) if VAR_12.get("fields", {"fieldname":"disabled", "fieldtype":"Check"}): VAR_5.append([VAR_2, "disabled", "!=", 1]) fields = FUNC_3(VAR_12, VAR_1 or "name") if VAR_10: VAR_27 = list(set(VAR_27 + json.loads(VAR_10))) VAR_28 = ['`tab%s`.`%s`' % (VAR_12.name, f.strip()) for f in VAR_27] VAR_28.append("""locate({_txt}, `tab{VAR_2}`.`name`) as `_relevance`""".format( _txt=VAR_20.db.escape((VAR_3 or "").replace("%", "").replace("@", "")), VAR_2=doctype)) from VAR_20.model.db_query import get_order_by VAR_29 = get_order_by(VAR_2, VAR_12) VAR_30 = "_relevance, {0}, `tab{1}`.idx desc".format(VAR_29, VAR_2) VAR_31 = 'select' if VAR_20.only_has_select_perm(VAR_2) else 'read' VAR_32 = True if VAR_2 == "DocType" else (cint(VAR_8) and has_permission(VAR_2, VAR_31=ptype)) if VAR_2 in VAR_0: VAR_6 = None VAR_33 = VAR_20.get_list(VAR_2, VAR_5=filters, VAR_27=VAR_28, VAR_26=or_filters, limit_start=VAR_9, limit_page_length=VAR_6, VAR_30=order_by, VAR_32=ignore_permissions, VAR_7=reference_doctype, as_list=not VAR_11, strict=False) if VAR_2 in VAR_0: VAR_33 = tuple([v for v in list(VAR_33) if re.search(re.escape(VAR_3)+".*", (_(v.name) if VAR_11 else _(v[0])), re.IGNORECASE)]) if VAR_11: for r in VAR_33: r.pop("_relevance") VAR_20.response["values"] = VAR_33 else: VAR_20.response["values"] = [r[:-1] for r in VAR_33] def FUNC_3(VAR_12, VAR_13): VAR_22 = ["name"] if VAR_12.search_fields: for d in VAR_12.search_fields.split(","): if d.strip() not in VAR_22: sflist.append(d.strip()) if VAR_12.title_field and VAR_12.title_field not in VAR_22: sflist.append(VAR_12.title_field) if VAR_13 not in VAR_22: sflist.append(VAR_13) return VAR_22 def FUNC_4(VAR_14): VAR_23 = [] for r in VAR_14: VAR_25 = {"value": r[0], "description": ", ".join(unique(cstr(d) for d in r if d)[1:])} VAR_23.append(VAR_25) return VAR_23 def FUNC_5(VAR_4, VAR_13, VAR_3): if '%(VAR_13)s' in VAR_4: query = VAR_4.replace('%(VAR_13)s', VAR_13) if '%s' in VAR_4: query = VAR_4.replace('%s', ((VAR_3 or '') + '%')) return VAR_4 @wrapt.decorator def FUNC_6(VAR_15, VAR_16, VAR_17, VAR_18): kwargs.update(dict(zip(VAR_15.__code__.co_varnames, VAR_17))) FUNC_0(VAR_18['searchfield']) VAR_18['start'] = cint(VAR_18['start']) VAR_18['page_len'] = cint(VAR_18['page_len']) if VAR_18['doctype'] and not VAR_20.db.exists('DocType', VAR_18['doctype']): return [] return VAR_15(**VAR_18)
from __future__ import unicode_literals import .frappe, json from VAR_20.utils import cstr, unique, cint from VAR_20.permissions import has_permission from VAR_20 import _, is_whitelisted from six import string_types import re import wrapt VAR_0 = ["DocType", "Role"] def FUNC_0(VAR_1): VAR_19 = ['select', 'delete', 'drop', 'update', 'case', 'and', 'or', 'like'] def FUNC_7(VAR_1): VAR_20.throw(_('Invalid Search Field {0}').format(VAR_1), VAR_20.DataError) if len(VAR_1) == 1: VAR_24 = re.compile(r'^.*[=;*,\'"$\-+%#@()_].*') if VAR_24.match(VAR_1): FUNC_7(VAR_1) if len(VAR_1) >= 3: if '=' in VAR_1: FUNC_7(VAR_1) elif ' --' in VAR_1: FUNC_7(VAR_1) elif any(' {0} '.format(keyword) in VAR_1.split() for keyword in VAR_19): FUNC_7(VAR_1) elif any(keyword in VAR_1.split() for keyword in VAR_19): FUNC_7(VAR_1) else: VAR_24 = re.compile(r'^.*[=;*,\'"$\-+%#@()].*') if any(VAR_24.match(f) for f in VAR_1.split()): FUNC_7(VAR_1) @VAR_20.whitelist() def FUNC_1(VAR_2, VAR_3, VAR_4=None, VAR_5=None, VAR_6=20, VAR_1=None, VAR_7=None, VAR_8=False): FUNC_2(VAR_2, VAR_3.strip(), VAR_4, VAR_1=searchfield, VAR_6=page_length, VAR_5=filters, VAR_7=reference_doctype, VAR_8=ignore_user_permissions) VAR_20.response['results'] = FUNC_4(VAR_20.response["values"]) del VAR_20.response["values"] @VAR_20.whitelist() def FUNC_2(VAR_2, VAR_3, VAR_4=None, VAR_1=None, VAR_9=0, VAR_6=20, VAR_5=None, VAR_10=None, VAR_11=False, VAR_7=None, VAR_8=False): VAR_9 = cint(VAR_9) if isinstance(VAR_5, string_types): VAR_5 = json.loads(VAR_5) if VAR_1: FUNC_0(VAR_1) if not VAR_1: searchfield = "name" VAR_21 = VAR_20.get_hooks().standard_queries or {} if VAR_4 and VAR_4.split()[0].lower()!="select": try: is_whitelisted(VAR_20.get_attr(VAR_4)) VAR_20.response["values"] = VAR_20.call(VAR_4, VAR_2, VAR_3, VAR_1, VAR_9, VAR_6, VAR_5, VAR_11=as_dict) except VAR_20.exceptions.PermissionError as e: if VAR_20.local.conf.developer_mode: raise e else: VAR_20.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return except Exception as e: raise e elif not VAR_4 and VAR_2 in VAR_21: FUNC_2(VAR_2, VAR_3, VAR_21[VAR_2][0], VAR_1, VAR_9, VAR_6, VAR_5) else: VAR_12 = VAR_20.get_meta(VAR_2) if VAR_4: VAR_20.throw(_("This VAR_4 style is discontinued")) else: if isinstance(VAR_5, dict): VAR_34 = VAR_5.items() VAR_5 = [] for f in VAR_34: if isinstance(f[1], (list, tuple)): VAR_5.append([VAR_2, f[0], f[1][0], f[1][1]]) else: VAR_5.append([VAR_2, f[0], "=", f[1]]) if VAR_5==None: VAR_5 = [] VAR_26 = [] if VAR_3: VAR_35 = ["name"] if VAR_12.title_field: VAR_35.append(VAR_12.title_field) if VAR_12.search_fields: VAR_35.extend(VAR_12.get_search_fields()) for f in VAR_35: VAR_36 = VAR_12.get_field(f.strip()) if (VAR_2 not in VAR_0) and (f == "name" or (VAR_36 and VAR_36.fieldtype in ["Data", "Text", "Small Text", "Long Text", "Link", "Select", "Read Only", "Text Editor"])): VAR_26.append([VAR_2, f.strip(), "like", "%{0}%".format(VAR_3)]) if VAR_12.get("fields", {"fieldname":"enabled", "fieldtype":"Check"}): VAR_5.append([VAR_2, "enabled", "=", 1]) if VAR_12.get("fields", {"fieldname":"disabled", "fieldtype":"Check"}): VAR_5.append([VAR_2, "disabled", "!=", 1]) fields = FUNC_3(VAR_12, VAR_1 or "name") if VAR_10: VAR_27 = list(set(VAR_27 + json.loads(VAR_10))) VAR_28 = ['`tab%s`.`%s`' % (VAR_12.name, f.strip()) for f in VAR_27] VAR_28.append("""locate({_txt}, `tab{VAR_2}`.`name`) as `_relevance`""".format( _txt=VAR_20.db.escape((VAR_3 or "").replace("%", "").replace("@", "")), VAR_2=doctype)) from VAR_20.model.db_query import get_order_by VAR_29 = get_order_by(VAR_2, VAR_12) VAR_30 = "_relevance, {0}, `tab{1}`.idx desc".format(VAR_29, VAR_2) VAR_31 = 'select' if VAR_20.only_has_select_perm(VAR_2) else 'read' VAR_32 = True if VAR_2 == "DocType" else (cint(VAR_8) and has_permission(VAR_2, VAR_31=ptype)) if VAR_2 in VAR_0: VAR_6 = None VAR_33 = VAR_20.get_list(VAR_2, VAR_5=filters, VAR_27=VAR_28, VAR_26=or_filters, limit_start=VAR_9, limit_page_length=VAR_6, VAR_30=order_by, VAR_32=ignore_permissions, VAR_7=reference_doctype, as_list=not VAR_11, strict=False) if VAR_2 in VAR_0: VAR_33 = tuple([v for v in list(VAR_33) if re.search(re.escape(VAR_3)+".*", (_(v.name) if VAR_11 else _(v[0])), re.IGNORECASE)]) if VAR_11: for r in VAR_33: r.pop("_relevance") VAR_20.response["values"] = VAR_33 else: VAR_20.response["values"] = [r[:-1] for r in VAR_33] def FUNC_3(VAR_12, VAR_13): VAR_22 = ["name"] if VAR_12.search_fields: for d in VAR_12.search_fields.split(","): if d.strip() not in VAR_22: sflist.append(d.strip()) if VAR_12.title_field and VAR_12.title_field not in VAR_22: sflist.append(VAR_12.title_field) if VAR_13 not in VAR_22: sflist.append(VAR_13) return VAR_22 def FUNC_4(VAR_14): VAR_23 = [] for r in VAR_14: VAR_25 = {"value": r[0], "description": ", ".join(unique(cstr(d) for d in r if d)[1:])} VAR_23.append(VAR_25) return VAR_23 def FUNC_5(VAR_4, VAR_13, VAR_3): if '%(VAR_13)s' in VAR_4: query = VAR_4.replace('%(VAR_13)s', VAR_13) if '%s' in VAR_4: query = VAR_4.replace('%s', ((VAR_3 or '') + '%')) return VAR_4 @wrapt.decorator def FUNC_6(VAR_15, VAR_16, VAR_17, VAR_18): kwargs.update(dict(zip(VAR_15.__code__.co_varnames, VAR_17))) FUNC_0(VAR_18['searchfield']) VAR_18['start'] = cint(VAR_18['start']) VAR_18['page_len'] = cint(VAR_18['page_len']) if VAR_18['doctype'] and not VAR_20.db.exists('DocType', VAR_18['doctype']): return [] return VAR_15(**VAR_18)
[ 1, 2, 3, 4, 14, 16, 19, 22, 24, 28, 30, 31, 34, 35, 38, 39, 42, 43, 46, 51, 52, 58, 59, 63, 65, 68, 71, 74, 76, 78, 93, 98, 101, 102, 112, 116, 117, 118, 123, 126, 132, 137, 138, 143, 144, 147, 148, 149, 152, 154, 157, 160, 172, 175, 176, 183, 185, 191, 194, 197, 199, 206, 213, 220, 223 ]
[ 1, 2, 3, 4, 13, 15, 18, 21, 23, 27, 29, 30, 33, 34, 37, 38, 41, 42, 45, 50, 51, 57, 58, 62, 64, 67, 70, 73, 75, 77, 92, 97, 100, 101, 111, 115, 116, 117, 122, 125, 131, 136, 137, 142, 143, 146, 147, 148, 151, 153, 156, 159, 171, 174, 175, 182, 184, 190, 193, 196, 198, 205, 212, 219, 222, 224 ]
1CWE-79
from django.core.exceptions import ValidationError from shuup.utils.django_compat import force_text # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. class Problem(Exception): """ User-visible exception. """ message = property(lambda self: self.args[0] if self.args else None) def __init__(self, message, title=None): super(Problem, self).__init__(message) self.title = title self.links = [] def with_link(self, url, title): """ Append a link to this Problem and return itself. This API is designed after `Exception.with_traceback()`, so you can fluently chain this in a `raise` statement:: raise Problem("Oops").with_link("...", "...") :param url: URL string. :type url: str :param title: Title text. :type title: str :return: This same Problem. :rtype: shuup.utils.excs.Problem """ self.links.append({"url": url, "title": title}) return self class ExceptionalResponse(Exception): def __init__(self, response): self.response = response super(ExceptionalResponse, self).__init__(force_text(response)) def extract_messages(obj_list): """ Extract "messages" from a list of exceptions or other objects. For ValidationErrors, `messages` are flattened into the output. For Exceptions, `args[0]` is added into the output. For other objects, `force_text` is called. :param obj_list: List of exceptions etc. :type obj_list: Iterable[object] :rtype: Iterable[str] """ for obj in obj_list: if isinstance(obj, ValidationError): for msg in obj.messages: yield force_text(msg) continue if isinstance(obj, Exception): if len(obj.args): yield force_text(obj.args[0]) continue yield force_text(obj)
from django.core.exceptions import ValidationError from django.utils.html import escape from shuup.utils.django_compat import force_text # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. class Problem(Exception): """ User-visible exception. """ message = property(lambda self: self.args[0] if self.args else None) def __init__(self, message, title=None): super(Problem, self).__init__(message) self.title = title self.links = [] def with_link(self, url, title): """ Append a link to this Problem and return itself. This API is designed after `Exception.with_traceback()`, so you can fluently chain this in a `raise` statement:: raise Problem("Oops").with_link("...", "...") :param url: URL string. :type url: str :param title: Title text. :type title: str :return: This same Problem. :rtype: shuup.utils.excs.Problem """ self.links.append({"url": url, "title": title}) return self class ExceptionalResponse(Exception): def __init__(self, response): self.response = response super(ExceptionalResponse, self).__init__(force_text(response)) def extract_messages(obj_list): """ Extract "messages" from a list of exceptions or other objects. For ValidationErrors, `messages` are flattened into the output. For Exceptions, `args[0]` is added into the output. For other objects, `force_text` is called. :param obj_list: List of exceptions etc. :type obj_list: Iterable[object] :rtype: Iterable[str] """ for obj in obj_list: if isinstance(obj, ValidationError): for msg in obj.messages: yield escape(force_text(msg)) continue if isinstance(obj, Exception): if len(obj.args): yield escape(force_text(obj.args[0])) continue yield escape(force_text(obj))
xss
{ "code": [ " yield force_text(msg)", " yield force_text(obj.args[0])", " yield force_text(obj)" ], "line_no": [ 64, 68, 70 ] }
{ "code": [ " yield escape(force_text(msg))", " yield escape(force_text(obj.args[0]))" ], "line_no": [ 65, 69 ] }
from django.core.exceptions import ValidationError from shuup.utils.django_compat import force_text class CLASS_0(Exception): VAR_1 = property(lambda self: self.args[0] if self.args else None) def __init__(self, VAR_1, VAR_2=None): super(CLASS_0, self).__init__(VAR_1) self.title = VAR_2 self.links = [] def FUNC_1(self, VAR_3, VAR_2): self.links.append({"url": VAR_3, "title": VAR_2}) return self class CLASS_1(Exception): def __init__(self, VAR_4): self.response = VAR_4 super(CLASS_1, self).__init__(force_text(VAR_4)) def FUNC_0(VAR_0): for obj in VAR_0: if isinstance(obj, ValidationError): for msg in obj.messages: yield force_text(msg) continue if isinstance(obj, Exception): if len(obj.args): yield force_text(obj.args[0]) continue yield force_text(obj)
from django.core.exceptions import ValidationError from django.utils.html import escape from shuup.utils.django_compat import force_text class CLASS_0(Exception): VAR_1 = property(lambda self: self.args[0] if self.args else None) def __init__(self, VAR_1, VAR_2=None): super(CLASS_0, self).__init__(VAR_1) self.title = VAR_2 self.links = [] def FUNC_1(self, VAR_3, VAR_2): self.links.append({"url": VAR_3, "title": VAR_2}) return self class CLASS_1(Exception): def __init__(self, VAR_4): self.response = VAR_4 super(CLASS_1, self).__init__(force_text(VAR_4)) def FUNC_0(VAR_0): for obj in VAR_0: if isinstance(obj, ValidationError): for msg in obj.messages: yield escape(force_text(msg)) continue if isinstance(obj, Exception): if len(obj.args): yield escape(force_text(obj.args[0])) continue yield escape(force_text(obj))
[ 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 17, 22, 26, 29, 31, 41, 42, 47, 48, 52, 56, 71, 14, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38 ]
[ 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 18, 23, 27, 30, 32, 42, 43, 48, 49, 53, 57, 72, 15, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 ]
1CWE-79
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import json, datetime from frappe import _, scrub import frappe.desk.query_report from frappe.utils import cint, cstr from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.modules import make_boilerplate from frappe.core.doctype.page.page import delete_custom_role from frappe.core.doctype.custom_role.custom_role import get_custom_allowed_roles from frappe.desk.reportview import append_totals_row from six import iteritems from frappe.utils.safe_exec import safe_exec class Report(Document): def validate(self): """only administrator can save standard report""" if not self.module: self.module = frappe.db.get_value("DocType", self.ref_doctype, "module") if not self.is_standard: self.is_standard = "No" if frappe.session.user=="Administrator" and getattr(frappe.local.conf, 'developer_mode',0)==1: self.is_standard = "Yes" if self.is_standard == "No": # allow only script manager to edit scripts if self.report_type != 'Report Builder': frappe.only_for('Script Manager', True) if frappe.db.get_value("Report", self.name, "is_standard") == "Yes": frappe.throw(_("Cannot edit a standard report. Please duplicate and create a new report")) if self.is_standard == "Yes" and frappe.session.user!="Administrator": frappe.throw(_("Only Administrator can save a standard report. Please rename and save.")) if self.report_type == "Report Builder": self.update_report_json() def before_insert(self): self.set_doctype_roles() def on_update(self): self.export_doc() def on_trash(self): if (self.is_standard == 'Yes' and not cint(getattr(frappe.local.conf, 'developer_mode', 0)) and not frappe.flags.in_patch): frappe.throw(_("You are not allowed to delete Standard Report")) delete_custom_role('report', self.name) def get_columns(self): return [d.as_dict(no_default_fields = True) for d in self.columns] def set_doctype_roles(self): if not self.get('roles') and self.is_standard == 'No': meta = frappe.get_meta(self.ref_doctype) if not meta.istable: roles = [{'role': d.role} for d in meta.permissions if d.permlevel==0] self.set('roles', roles) def is_permitted(self): """Returns true if Has Role is not set or the user is allowed.""" from frappe.utils import has_common allowed = [d.role for d in frappe.get_all("Has Role", fields=["role"], filters={"parent": self.name})] custom_roles = get_custom_allowed_roles('report', self.name) allowed.extend(custom_roles) if not allowed: return True if has_common(frappe.get_roles(), allowed): return True def update_report_json(self): if not self.json: self.json = '{}' def export_doc(self): if frappe.flags.in_import: return if self.is_standard == 'Yes' and (frappe.local.conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.name]], record_module=self.module, create_init=True) self.create_report_py() def create_report_py(self): if self.report_type == "Script Report": make_boilerplate("controller.py", self, {"name": self.name}) make_boilerplate("controller.js", self, {"name": self.name}) def execute_query_report(self, filters): if not self.query: frappe.throw(_("Must specify a Query to run"), title=_('Report Document Error')) if not self.query.lower().startswith("select"): frappe.throw(_("Query must be a SELECT"), title=_('Report Document Error')) result = [list(t) for t in frappe.db.sql(self.query, filters, debug=True)] columns = self.get_columns() or [cstr(c[0]) for c in frappe.db.get_description()] return [columns, result] def execute_script_report(self, filters): # save the timestamp to automatically set to prepared threshold = 30 res = [] start_time = datetime.datetime.now() # The JOB if self.is_standard == 'Yes': res = self.execute_module(filters) else: res = self.execute_script(filters) # automatically set as prepared execution_time = (datetime.datetime.now() - start_time).total_seconds() if execution_time > threshold and not self.prepared_report: self.db_set('prepared_report', 1) frappe.cache().hset('report_execution_time', self.name, execution_time) return res def execute_module(self, filters): # report in python module module = self.module or frappe.db.get_value("DocType", self.ref_doctype, "module") method_name = get_report_module_dotted_path(module, self.name) + ".execute" return frappe.get_attr(method_name)(frappe._dict(filters)) def execute_script(self, filters): # server script loc = {"filters": frappe._dict(filters), 'data':None, 'result':None} safe_exec(self.report_script, None, loc) if loc['data']: return loc['data'] else: return self.get_columns(), loc['result'] def get_data(self, filters=None, limit=None, user=None, as_dict=False, ignore_prepared_report=False): if self.report_type in ('Query Report', 'Script Report', 'Custom Report'): columns, result = self.run_query_report(filters, user, ignore_prepared_report) else: columns, result = self.run_standard_report(filters, limit, user) if as_dict: result = self.build_data_dict(result, columns) return columns, result def run_query_report(self, filters, user, ignore_prepared_report=False): columns, result = [], [] data = frappe.desk.query_report.run(self.name, filters=filters, user=user, ignore_prepared_report=ignore_prepared_report) for d in data.get('columns'): if isinstance(d, dict): col = frappe._dict(d) if not col.fieldname: col.fieldname = col.label columns.append(col) else: fieldtype, options = "Data", None parts = d.split(':') if len(parts) > 1: if parts[1]: fieldtype, options = parts[1], None if fieldtype and '/' in fieldtype: fieldtype, options = fieldtype.split('/') columns.append(frappe._dict(label=parts[0], fieldtype=fieldtype, fieldname=parts[0], options=options)) result += data.get('result') return columns, result def run_standard_report(self, filters, limit, user): params = json.loads(self.json) columns = self.get_standard_report_columns(params) result = [] order_by, group_by, group_by_args = self.get_standard_report_order_by(params) _result = frappe.get_list(self.ref_doctype, fields = [ get_group_by_field(group_by_args, c[1]) if c[0] == '_aggregate_column' and group_by_args else Report._format([c[1], c[0]]) for c in columns ], filters = self.get_standard_report_filters(params, filters), order_by = order_by, group_by = group_by, as_list = True, limit = limit, user = user) columns = self.build_standard_report_columns(columns, group_by_args) result = result + [list(d) for d in _result] if params.get('add_totals_row'): result = append_totals_row(result) return columns, result @staticmethod def _format(parts): # sort by is saved as DocType.fieldname, covert it to sql return '`tab{0}`.`{1}`'.format(*parts) def get_standard_report_columns(self, params): if params.get('fields'): columns = params.get('fields') elif params.get('columns'): columns = params.get('columns') elif params.get('fields'): columns = params.get('fields') else: columns = [['name', self.ref_doctype]] for df in frappe.get_meta(self.ref_doctype).fields: if df.in_list_view: columns.append([df.fieldname, self.ref_doctype]) return columns def get_standard_report_filters(self, params, filters): _filters = params.get('filters') or [] if filters: for key, value in iteritems(filters): condition, _value = '=', value if isinstance(value, (list, tuple)): condition, _value = value _filters.append([key, condition, _value]) return _filters def get_standard_report_order_by(self, params): group_by_args = None if params.get('sort_by'): order_by = Report._format(params.get('sort_by').split('.')) + ' ' + params.get('sort_order') elif params.get('order_by'): order_by = params.get('order_by') else: order_by = Report._format([self.ref_doctype, 'modified']) + ' desc' if params.get('sort_by_next'): order_by += ', ' + Report._format(params.get('sort_by_next').split('.')) + ' ' + params.get('sort_order_next') group_by = None if params.get('group_by'): group_by_args = frappe._dict(params['group_by']) group_by = group_by_args['group_by'] order_by = '_aggregate_column desc' return order_by, group_by, group_by_args def build_standard_report_columns(self, columns, group_by_args): _columns = [] for (fieldname, doctype) in columns: meta = frappe.get_meta(doctype) if meta.get_field(fieldname): field = meta.get_field(fieldname) else: if fieldname == '_aggregate_column': label = get_group_by_column_label(group_by_args, meta) else: label = meta.get_label(fieldname) field = frappe._dict(fieldname=fieldname, label=label) # since name is the primary key for a document, it will always be a Link datatype if fieldname == "name": field.fieldtype = "Link" field.options = doctype _columns.append(field) return _columns def build_data_dict(self, result, columns): data = [] for row in result: if isinstance(row, (list, tuple)): _row = frappe._dict() for i, val in enumerate(row): _row[columns[i].get('fieldname')] = val elif isinstance(row, dict): # no need to convert from dict to dict _row = frappe._dict(row) data.append(_row) return data @Document.whitelist def toggle_disable(self, disable): self.db_set("disabled", cint(disable)) @frappe.whitelist() def is_prepared_report_disabled(report): return frappe.db.get_value('Report', report, 'disable_prepared_report') or 0 def get_report_module_dotted_path(module, report_name): return frappe.local.module_app[scrub(module)] + "." + scrub(module) \ + ".report." + scrub(report_name) + "." + scrub(report_name) def get_group_by_field(args, doctype): if args['aggregate_function'] == 'count': group_by_field = 'count(*) as _aggregate_column' else: group_by_field = '{0}(`tab{1}`.{2}) as _aggregate_column'.format( args.aggregate_function, doctype, args.aggregate_on ) return group_by_field def get_group_by_column_label(args, meta): if args['aggregate_function'] == 'count': label = 'Count' else: sql_fn_map = { 'avg': 'Average', 'sum': 'Sum' } aggregate_on_label = meta.get_label(args.aggregate_on) label = _('{function} of {fieldlabel}').format( function=sql_fn_map[args.aggregate_function], fieldlabel = aggregate_on_label ) return label
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import json, datetime from frappe import _, scrub import frappe.desk.query_report from frappe.utils import cint, cstr from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.modules import make_boilerplate from frappe.core.doctype.page.page import delete_custom_role from frappe.core.doctype.custom_role.custom_role import get_custom_allowed_roles from frappe.desk.reportview import append_totals_row from six import iteritems from frappe.utils.safe_exec import safe_exec class Report(Document): def validate(self): """only administrator can save standard report""" if not self.module: self.module = frappe.db.get_value("DocType", self.ref_doctype, "module") if not self.is_standard: self.is_standard = "No" if frappe.session.user=="Administrator" and getattr(frappe.local.conf, 'developer_mode',0)==1: self.is_standard = "Yes" if self.is_standard == "No": # allow only script manager to edit scripts if self.report_type != 'Report Builder': frappe.only_for('Script Manager', True) if frappe.db.get_value("Report", self.name, "is_standard") == "Yes": frappe.throw(_("Cannot edit a standard report. Please duplicate and create a new report")) if self.is_standard == "Yes" and frappe.session.user!="Administrator": frappe.throw(_("Only Administrator can save a standard report. Please rename and save.")) if self.report_type == "Report Builder": self.update_report_json() def before_insert(self): self.set_doctype_roles() def on_update(self): self.export_doc() def on_trash(self): if (self.is_standard == 'Yes' and not cint(getattr(frappe.local.conf, 'developer_mode', 0)) and not frappe.flags.in_patch): frappe.throw(_("You are not allowed to delete Standard Report")) delete_custom_role('report', self.name) def get_columns(self): return [d.as_dict(no_default_fields = True) for d in self.columns] @frappe.whitelist() def set_doctype_roles(self): if not self.get('roles') and self.is_standard == 'No': meta = frappe.get_meta(self.ref_doctype) if not meta.istable: roles = [{'role': d.role} for d in meta.permissions if d.permlevel==0] self.set('roles', roles) def is_permitted(self): """Returns true if Has Role is not set or the user is allowed.""" from frappe.utils import has_common allowed = [d.role for d in frappe.get_all("Has Role", fields=["role"], filters={"parent": self.name})] custom_roles = get_custom_allowed_roles('report', self.name) allowed.extend(custom_roles) if not allowed: return True if has_common(frappe.get_roles(), allowed): return True def update_report_json(self): if not self.json: self.json = '{}' def export_doc(self): if frappe.flags.in_import: return if self.is_standard == 'Yes' and (frappe.local.conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.name]], record_module=self.module, create_init=True) self.create_report_py() def create_report_py(self): if self.report_type == "Script Report": make_boilerplate("controller.py", self, {"name": self.name}) make_boilerplate("controller.js", self, {"name": self.name}) def execute_query_report(self, filters): if not self.query: frappe.throw(_("Must specify a Query to run"), title=_('Report Document Error')) if not self.query.lower().startswith("select"): frappe.throw(_("Query must be a SELECT"), title=_('Report Document Error')) result = [list(t) for t in frappe.db.sql(self.query, filters, debug=True)] columns = self.get_columns() or [cstr(c[0]) for c in frappe.db.get_description()] return [columns, result] def execute_script_report(self, filters): # save the timestamp to automatically set to prepared threshold = 30 res = [] start_time = datetime.datetime.now() # The JOB if self.is_standard == 'Yes': res = self.execute_module(filters) else: res = self.execute_script(filters) # automatically set as prepared execution_time = (datetime.datetime.now() - start_time).total_seconds() if execution_time > threshold and not self.prepared_report: self.db_set('prepared_report', 1) frappe.cache().hset('report_execution_time', self.name, execution_time) return res def execute_module(self, filters): # report in python module module = self.module or frappe.db.get_value("DocType", self.ref_doctype, "module") method_name = get_report_module_dotted_path(module, self.name) + ".execute" return frappe.get_attr(method_name)(frappe._dict(filters)) def execute_script(self, filters): # server script loc = {"filters": frappe._dict(filters), 'data':None, 'result':None} safe_exec(self.report_script, None, loc) if loc['data']: return loc['data'] else: return self.get_columns(), loc['result'] def get_data(self, filters=None, limit=None, user=None, as_dict=False, ignore_prepared_report=False): if self.report_type in ('Query Report', 'Script Report', 'Custom Report'): columns, result = self.run_query_report(filters, user, ignore_prepared_report) else: columns, result = self.run_standard_report(filters, limit, user) if as_dict: result = self.build_data_dict(result, columns) return columns, result def run_query_report(self, filters, user, ignore_prepared_report=False): columns, result = [], [] data = frappe.desk.query_report.run(self.name, filters=filters, user=user, ignore_prepared_report=ignore_prepared_report) for d in data.get('columns'): if isinstance(d, dict): col = frappe._dict(d) if not col.fieldname: col.fieldname = col.label columns.append(col) else: fieldtype, options = "Data", None parts = d.split(':') if len(parts) > 1: if parts[1]: fieldtype, options = parts[1], None if fieldtype and '/' in fieldtype: fieldtype, options = fieldtype.split('/') columns.append(frappe._dict(label=parts[0], fieldtype=fieldtype, fieldname=parts[0], options=options)) result += data.get('result') return columns, result def run_standard_report(self, filters, limit, user): params = json.loads(self.json) columns = self.get_standard_report_columns(params) result = [] order_by, group_by, group_by_args = self.get_standard_report_order_by(params) _result = frappe.get_list(self.ref_doctype, fields = [ get_group_by_field(group_by_args, c[1]) if c[0] == '_aggregate_column' and group_by_args else Report._format([c[1], c[0]]) for c in columns ], filters = self.get_standard_report_filters(params, filters), order_by = order_by, group_by = group_by, as_list = True, limit = limit, user = user) columns = self.build_standard_report_columns(columns, group_by_args) result = result + [list(d) for d in _result] if params.get('add_totals_row'): result = append_totals_row(result) return columns, result @staticmethod def _format(parts): # sort by is saved as DocType.fieldname, covert it to sql return '`tab{0}`.`{1}`'.format(*parts) def get_standard_report_columns(self, params): if params.get('fields'): columns = params.get('fields') elif params.get('columns'): columns = params.get('columns') elif params.get('fields'): columns = params.get('fields') else: columns = [['name', self.ref_doctype]] for df in frappe.get_meta(self.ref_doctype).fields: if df.in_list_view: columns.append([df.fieldname, self.ref_doctype]) return columns def get_standard_report_filters(self, params, filters): _filters = params.get('filters') or [] if filters: for key, value in iteritems(filters): condition, _value = '=', value if isinstance(value, (list, tuple)): condition, _value = value _filters.append([key, condition, _value]) return _filters def get_standard_report_order_by(self, params): group_by_args = None if params.get('sort_by'): order_by = Report._format(params.get('sort_by').split('.')) + ' ' + params.get('sort_order') elif params.get('order_by'): order_by = params.get('order_by') else: order_by = Report._format([self.ref_doctype, 'modified']) + ' desc' if params.get('sort_by_next'): order_by += ', ' + Report._format(params.get('sort_by_next').split('.')) + ' ' + params.get('sort_order_next') group_by = None if params.get('group_by'): group_by_args = frappe._dict(params['group_by']) group_by = group_by_args['group_by'] order_by = '_aggregate_column desc' return order_by, group_by, group_by_args def build_standard_report_columns(self, columns, group_by_args): _columns = [] for (fieldname, doctype) in columns: meta = frappe.get_meta(doctype) if meta.get_field(fieldname): field = meta.get_field(fieldname) else: if fieldname == '_aggregate_column': label = get_group_by_column_label(group_by_args, meta) else: label = meta.get_label(fieldname) field = frappe._dict(fieldname=fieldname, label=label) # since name is the primary key for a document, it will always be a Link datatype if fieldname == "name": field.fieldtype = "Link" field.options = doctype _columns.append(field) return _columns def build_data_dict(self, result, columns): data = [] for row in result: if isinstance(row, (list, tuple)): _row = frappe._dict() for i, val in enumerate(row): _row[columns[i].get('fieldname')] = val elif isinstance(row, dict): # no need to convert from dict to dict _row = frappe._dict(row) data.append(_row) return data @frappe.whitelist() def toggle_disable(self, disable): self.db_set("disabled", cint(disable)) @frappe.whitelist() def is_prepared_report_disabled(report): return frappe.db.get_value('Report', report, 'disable_prepared_report') or 0 def get_report_module_dotted_path(module, report_name): return frappe.local.module_app[scrub(module)] + "." + scrub(module) \ + ".report." + scrub(report_name) + "." + scrub(report_name) def get_group_by_field(args, doctype): if args['aggregate_function'] == 'count': group_by_field = 'count(*) as _aggregate_column' else: group_by_field = '{0}(`tab{1}`.{2}) as _aggregate_column'.format( args.aggregate_function, doctype, args.aggregate_on ) return group_by_field def get_group_by_column_label(args, meta): if args['aggregate_function'] == 'count': label = 'Count' else: sql_fn_map = { 'avg': 'Average', 'sum': 'Sum' } aggregate_on_label = meta.get_label(args.aggregate_on) label = _('{function} of {fieldlabel}').format( function=sql_fn_map[args.aggregate_function], fieldlabel = aggregate_on_label ) return label
xss
{ "code": [ "\t@Document.whitelist" ], "line_no": [ 307 ] }
{ "code": [ "\t@frappe.whitelist()", "\t@frappe.whitelist()" ], "line_no": [ 61, 308 ] }
from __future__ import unicode_literals import frappe import json, datetime from frappe import _, scrub import frappe.desk.query_report from frappe.utils import cint, cstr from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.modules import make_boilerplate from frappe.core.doctype.page.page import delete_custom_role from frappe.core.doctype.custom_role.custom_role import get_custom_allowed_roles from frappe.desk.reportview import append_totals_row from six import .iteritems from frappe.utils.safe_exec import safe_exec class CLASS_0(Document): def FUNC_4(self): if not self.module: self.module = frappe.db.get_value("DocType", self.ref_doctype, "module") if not self.is_standard: self.is_standard = "No" if frappe.session.user=="Administrator" and getattr(frappe.local.conf, 'developer_mode',0)==1: self.is_standard = "Yes" if self.is_standard == "No": if self.report_type != 'Report Builder': frappe.only_for('Script Manager', True) if frappe.db.get_value("Report", self.name, "is_standard") == "Yes": frappe.throw(_("Cannot edit a standard VAR_0. Please duplicate and create a new report")) if self.is_standard == "Yes" and frappe.session.user!="Administrator": frappe.throw(_("Only Administrator can save a standard VAR_0. Please rename and save.")) if self.report_type == "Report Builder": self.update_report_json() def FUNC_5(self): self.set_doctype_roles() def FUNC_6(self): self.export_doc() def FUNC_7(self): if (self.is_standard == 'Yes' and not cint(getattr(frappe.local.conf, 'developer_mode', 0)) and not frappe.flags.in_patch): frappe.throw(_("You are not VAR_17 to delete Standard Report")) delete_custom_role('report', self.name) def FUNC_8(self): return [d.as_dict(no_default_fields = True) for d in self.columns] def FUNC_9(self): if not self.get('roles') and self.is_standard == 'No': VAR_5 = frappe.get_meta(self.ref_doctype) if not VAR_5.istable: VAR_35 = [{'role': d.role} for d in VAR_5.permissions if d.permlevel==0] self.set('roles', VAR_35) def FUNC_10(self): from frappe.utils import has_common VAR_17 = [d.role for d in frappe.get_all("Has Role", fields=["role"], VAR_6={"parent": self.name})] VAR_18 = get_custom_allowed_roles('report', self.name) VAR_17.extend(VAR_18) if not VAR_17: return True if has_common(frappe.get_roles(), VAR_17): return True def FUNC_11(self): if not self.json: self.json = '{}' def FUNC_12(self): if frappe.flags.in_import: return if self.is_standard == 'Yes' and (frappe.local.conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.name]], record_module=self.module, create_init=True) self.create_report_py() def FUNC_13(self): if self.report_type == "Script Report": make_boilerplate("controller.py", self, {"name": self.name}) make_boilerplate("controller.js", self, {"name": self.name}) def FUNC_14(self, VAR_6): if not self.query: frappe.throw(_("Must specify a Query to run"), title=_('Report Document Error')) if not self.query.lower().startswith("select"): frappe.throw(_("Query must be a SELECT"), title=_('Report Document Error')) VAR_15 = [list(t) for t in frappe.db.sql(self.query, VAR_6, debug=True)] VAR_13 = self.get_columns() or [cstr(c[0]) for c in frappe.db.get_description()] return [VAR_13, VAR_15] def FUNC_15(self, VAR_6): VAR_19 = 30 VAR_20 = [] VAR_21 = datetime.datetime.now() if self.is_standard == 'Yes': VAR_20 = self.execute_module(VAR_6) else: VAR_20 = self.execute_script(VAR_6) VAR_22 = (datetime.datetime.now() - VAR_21).total_seconds() if VAR_22 > VAR_19 and not self.prepared_report: self.db_set('prepared_report', 1) frappe.cache().hset('report_execution_time', self.name, VAR_22) return VAR_20 def FUNC_16(self, VAR_6): module = self.module or frappe.db.get_value("DocType", self.ref_doctype, "module") VAR_23 = FUNC_1(VAR_1, self.name) + ".execute" return frappe.get_attr(VAR_23)(frappe._dict(VAR_6)) def FUNC_17(self, VAR_6): VAR_24 = {"filters": frappe._dict(VAR_6), 'data':None, 'result':None} safe_exec(self.report_script, None, VAR_24) if VAR_24['data']: return VAR_24['data'] else: return self.get_columns(), VAR_24['result'] def FUNC_18(self, VAR_6=None, VAR_7=None, VAR_8=None, VAR_9=False, VAR_10=False): if self.report_type in ('Query Report', 'Script Report', 'Custom Report'): VAR_13, VAR_15 = self.run_query_report(VAR_6, VAR_8, VAR_10) else: VAR_13, VAR_15 = self.run_standard_report(VAR_6, VAR_7, VAR_8) if VAR_9: VAR_15 = self.build_data_dict(VAR_15, VAR_13) return VAR_13, VAR_15 def FUNC_19(self, VAR_6, VAR_8, VAR_10=False): VAR_13, VAR_15 = [], [] VAR_25 = frappe.desk.query_report.run(self.name, VAR_6=filters, VAR_8=user, VAR_10=ignore_prepared_report) for d in VAR_25.get('columns'): if isinstance(d, dict): VAR_36 = frappe._dict(d) if not VAR_36.fieldname: VAR_36.fieldname = VAR_36.label VAR_13.append(VAR_36) else: VAR_37, VAR_38 = "Data", None VAR_11 = d.split(':') if len(VAR_11) > 1: if VAR_11[1]: VAR_37, VAR_38 = VAR_11[1], None if VAR_37 and '/' in VAR_37: fieldtype, VAR_38 = VAR_37.split('/') VAR_13.append(frappe._dict(VAR_32=VAR_11[0], VAR_37=fieldtype, fieldname=VAR_11[0], VAR_38=options)) VAR_15 += VAR_25.get('result') return VAR_13, VAR_15 def FUNC_20(self, VAR_6, VAR_7, VAR_8): VAR_12 = json.loads(self.json) VAR_13 = self.get_standard_report_columns(VAR_12) VAR_15 = [] VAR_26, VAR_27, VAR_14 = self.get_standard_report_order_by(VAR_12) VAR_28 = frappe.get_list(self.ref_doctype, fields = [ FUNC_2(VAR_14, c[1]) if c[0] == '_aggregate_column' and VAR_14 else CLASS_0._format([c[1], c[0]]) for c in VAR_13 ], VAR_6 = self.get_standard_report_filters(VAR_12, VAR_6), VAR_26 = order_by, VAR_27 = group_by, as_list = True, VAR_7 = limit, VAR_8 = user) VAR_13 = self.build_standard_report_columns(VAR_13, VAR_14) VAR_15 = result + [list(d) for d in VAR_28] if VAR_12.get('add_totals_row'): VAR_15 = append_totals_row(VAR_15) return VAR_13, VAR_15 @staticmethod def FUNC_21(VAR_11): return '`tab{0}`.`{1}`'.format(*VAR_11) def FUNC_22(self, VAR_12): if VAR_12.get('fields'): VAR_13 = VAR_12.get('fields') elif VAR_12.get('columns'): VAR_13 = VAR_12.get('columns') elif VAR_12.get('fields'): VAR_13 = VAR_12.get('fields') else: VAR_13 = [['name', self.ref_doctype]] for df in frappe.get_meta(self.ref_doctype).fields: if df.in_list_view: VAR_13.append([df.fieldname, self.ref_doctype]) return VAR_13 def FUNC_23(self, VAR_12, VAR_6): VAR_29 = VAR_12.get('filters') or [] if VAR_6: for key, value in iteritems(VAR_6): VAR_39, VAR_40 = '=', value if isinstance(value, (list, tuple)): VAR_39, VAR_40 = value VAR_29.append([key, VAR_39, VAR_40]) return VAR_29 def FUNC_24(self, VAR_12): VAR_14 = None if VAR_12.get('sort_by'): VAR_26 = CLASS_0._format(VAR_12.get('sort_by').split('.')) + ' ' + VAR_12.get('sort_order') elif VAR_12.get('order_by'): VAR_26 = VAR_12.get('order_by') else: VAR_26 = CLASS_0._format([self.ref_doctype, 'modified']) + ' desc' if VAR_12.get('sort_by_next'): VAR_26 += ', ' + CLASS_0._format(VAR_12.get('sort_by_next').split('.')) + ' ' + VAR_12.get('sort_order_next') VAR_27 = None if VAR_12.get('group_by'): VAR_14 = frappe._dict(VAR_12['group_by']) VAR_27 = VAR_14['group_by'] VAR_26 = '_aggregate_column desc' return VAR_26, VAR_27, VAR_14 def FUNC_25(self, VAR_13, VAR_14): VAR_30 = [] for (fieldname, VAR_4) in VAR_13: VAR_5 = frappe.get_meta(VAR_4) if VAR_5.get_field(fieldname): VAR_41 = VAR_5.get_field(fieldname) else: if fieldname == '_aggregate_column': VAR_32 = FUNC_3(VAR_14, VAR_5) else: VAR_32 = VAR_5.get_label(fieldname) VAR_41 = frappe._dict(fieldname=fieldname, VAR_32=label) if fieldname == "name": VAR_41.fieldtype = "Link" VAR_41.options = VAR_4 VAR_30.append(VAR_41) return VAR_30 def FUNC_26(self, VAR_15, VAR_13): VAR_25 = [] for row in VAR_15: if isinstance(row, (list, tuple)): VAR_42 = frappe._dict() for VAR_43, val in enumerate(row): VAR_42[VAR_13[VAR_43].get('fieldname')] = val elif isinstance(row, dict): VAR_42 = frappe._dict(row) VAR_25.append(VAR_42) return VAR_25 @Document.whitelist def FUNC_27(self, VAR_16): self.db_set("disabled", cint(VAR_16)) @frappe.whitelist() def FUNC_0(VAR_0): return frappe.db.get_value('Report', VAR_0, 'disable_prepared_report') or 0 def FUNC_1(VAR_1, VAR_2): return frappe.local.module_app[scrub(VAR_1)] + "." + scrub(VAR_1) \ + ".report." + scrub(VAR_2) + "." + scrub(VAR_2) def FUNC_2(VAR_3, VAR_4): if VAR_3['aggregate_function'] == 'count': VAR_31 = 'count(*) as _aggregate_column' else: VAR_31 = '{0}(`tab{1}`.{2}) as _aggregate_column'.format( VAR_3.aggregate_function, VAR_4, VAR_3.aggregate_on ) return VAR_31 def FUNC_3(VAR_3, VAR_5): if VAR_3['aggregate_function'] == 'count': VAR_32 = 'Count' else: VAR_33 = { 'avg': 'Average', 'sum': 'Sum' } VAR_34 = VAR_5.get_label(VAR_3.aggregate_on) VAR_32 = _('{function} of {fieldlabel}').format( function=VAR_33[VAR_3.aggregate_function], fieldlabel = VAR_34 ) return VAR_32
from __future__ import unicode_literals import frappe import json, datetime from frappe import _, scrub import frappe.desk.query_report from frappe.utils import cint, cstr from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.modules import make_boilerplate from frappe.core.doctype.page.page import delete_custom_role from frappe.core.doctype.custom_role.custom_role import get_custom_allowed_roles from frappe.desk.reportview import append_totals_row from six import .iteritems from frappe.utils.safe_exec import safe_exec class CLASS_0(Document): def FUNC_4(self): if not self.module: self.module = frappe.db.get_value("DocType", self.ref_doctype, "module") if not self.is_standard: self.is_standard = "No" if frappe.session.user=="Administrator" and getattr(frappe.local.conf, 'developer_mode',0)==1: self.is_standard = "Yes" if self.is_standard == "No": if self.report_type != 'Report Builder': frappe.only_for('Script Manager', True) if frappe.db.get_value("Report", self.name, "is_standard") == "Yes": frappe.throw(_("Cannot edit a standard VAR_0. Please duplicate and create a new report")) if self.is_standard == "Yes" and frappe.session.user!="Administrator": frappe.throw(_("Only Administrator can save a standard VAR_0. Please rename and save.")) if self.report_type == "Report Builder": self.update_report_json() def FUNC_5(self): self.set_doctype_roles() def FUNC_6(self): self.export_doc() def FUNC_7(self): if (self.is_standard == 'Yes' and not cint(getattr(frappe.local.conf, 'developer_mode', 0)) and not frappe.flags.in_patch): frappe.throw(_("You are not VAR_17 to delete Standard Report")) delete_custom_role('report', self.name) def FUNC_8(self): return [d.as_dict(no_default_fields = True) for d in self.columns] @frappe.whitelist() def FUNC_9(self): if not self.get('roles') and self.is_standard == 'No': VAR_5 = frappe.get_meta(self.ref_doctype) if not VAR_5.istable: VAR_35 = [{'role': d.role} for d in VAR_5.permissions if d.permlevel==0] self.set('roles', VAR_35) def FUNC_10(self): from frappe.utils import has_common VAR_17 = [d.role for d in frappe.get_all("Has Role", fields=["role"], VAR_6={"parent": self.name})] VAR_18 = get_custom_allowed_roles('report', self.name) VAR_17.extend(VAR_18) if not VAR_17: return True if has_common(frappe.get_roles(), VAR_17): return True def FUNC_11(self): if not self.json: self.json = '{}' def FUNC_12(self): if frappe.flags.in_import: return if self.is_standard == 'Yes' and (frappe.local.conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.name]], record_module=self.module, create_init=True) self.create_report_py() def FUNC_13(self): if self.report_type == "Script Report": make_boilerplate("controller.py", self, {"name": self.name}) make_boilerplate("controller.js", self, {"name": self.name}) def FUNC_14(self, VAR_6): if not self.query: frappe.throw(_("Must specify a Query to run"), title=_('Report Document Error')) if not self.query.lower().startswith("select"): frappe.throw(_("Query must be a SELECT"), title=_('Report Document Error')) VAR_15 = [list(t) for t in frappe.db.sql(self.query, VAR_6, debug=True)] VAR_13 = self.get_columns() or [cstr(c[0]) for c in frappe.db.get_description()] return [VAR_13, VAR_15] def FUNC_15(self, VAR_6): VAR_19 = 30 VAR_20 = [] VAR_21 = datetime.datetime.now() if self.is_standard == 'Yes': VAR_20 = self.execute_module(VAR_6) else: VAR_20 = self.execute_script(VAR_6) VAR_22 = (datetime.datetime.now() - VAR_21).total_seconds() if VAR_22 > VAR_19 and not self.prepared_report: self.db_set('prepared_report', 1) frappe.cache().hset('report_execution_time', self.name, VAR_22) return VAR_20 def FUNC_16(self, VAR_6): module = self.module or frappe.db.get_value("DocType", self.ref_doctype, "module") VAR_23 = FUNC_1(VAR_1, self.name) + ".execute" return frappe.get_attr(VAR_23)(frappe._dict(VAR_6)) def FUNC_17(self, VAR_6): VAR_24 = {"filters": frappe._dict(VAR_6), 'data':None, 'result':None} safe_exec(self.report_script, None, VAR_24) if VAR_24['data']: return VAR_24['data'] else: return self.get_columns(), VAR_24['result'] def FUNC_18(self, VAR_6=None, VAR_7=None, VAR_8=None, VAR_9=False, VAR_10=False): if self.report_type in ('Query Report', 'Script Report', 'Custom Report'): VAR_13, VAR_15 = self.run_query_report(VAR_6, VAR_8, VAR_10) else: VAR_13, VAR_15 = self.run_standard_report(VAR_6, VAR_7, VAR_8) if VAR_9: VAR_15 = self.build_data_dict(VAR_15, VAR_13) return VAR_13, VAR_15 def FUNC_19(self, VAR_6, VAR_8, VAR_10=False): VAR_13, VAR_15 = [], [] VAR_25 = frappe.desk.query_report.run(self.name, VAR_6=filters, VAR_8=user, VAR_10=ignore_prepared_report) for d in VAR_25.get('columns'): if isinstance(d, dict): VAR_36 = frappe._dict(d) if not VAR_36.fieldname: VAR_36.fieldname = VAR_36.label VAR_13.append(VAR_36) else: VAR_37, VAR_38 = "Data", None VAR_11 = d.split(':') if len(VAR_11) > 1: if VAR_11[1]: VAR_37, VAR_38 = VAR_11[1], None if VAR_37 and '/' in VAR_37: fieldtype, VAR_38 = VAR_37.split('/') VAR_13.append(frappe._dict(VAR_32=VAR_11[0], VAR_37=fieldtype, fieldname=VAR_11[0], VAR_38=options)) VAR_15 += VAR_25.get('result') return VAR_13, VAR_15 def FUNC_20(self, VAR_6, VAR_7, VAR_8): VAR_12 = json.loads(self.json) VAR_13 = self.get_standard_report_columns(VAR_12) VAR_15 = [] VAR_26, VAR_27, VAR_14 = self.get_standard_report_order_by(VAR_12) VAR_28 = frappe.get_list(self.ref_doctype, fields = [ FUNC_2(VAR_14, c[1]) if c[0] == '_aggregate_column' and VAR_14 else CLASS_0._format([c[1], c[0]]) for c in VAR_13 ], VAR_6 = self.get_standard_report_filters(VAR_12, VAR_6), VAR_26 = order_by, VAR_27 = group_by, as_list = True, VAR_7 = limit, VAR_8 = user) VAR_13 = self.build_standard_report_columns(VAR_13, VAR_14) VAR_15 = result + [list(d) for d in VAR_28] if VAR_12.get('add_totals_row'): VAR_15 = append_totals_row(VAR_15) return VAR_13, VAR_15 @staticmethod def FUNC_21(VAR_11): return '`tab{0}`.`{1}`'.format(*VAR_11) def FUNC_22(self, VAR_12): if VAR_12.get('fields'): VAR_13 = VAR_12.get('fields') elif VAR_12.get('columns'): VAR_13 = VAR_12.get('columns') elif VAR_12.get('fields'): VAR_13 = VAR_12.get('fields') else: VAR_13 = [['name', self.ref_doctype]] for df in frappe.get_meta(self.ref_doctype).fields: if df.in_list_view: VAR_13.append([df.fieldname, self.ref_doctype]) return VAR_13 def FUNC_23(self, VAR_12, VAR_6): VAR_29 = VAR_12.get('filters') or [] if VAR_6: for key, value in iteritems(VAR_6): VAR_39, VAR_40 = '=', value if isinstance(value, (list, tuple)): VAR_39, VAR_40 = value VAR_29.append([key, VAR_39, VAR_40]) return VAR_29 def FUNC_24(self, VAR_12): VAR_14 = None if VAR_12.get('sort_by'): VAR_26 = CLASS_0._format(VAR_12.get('sort_by').split('.')) + ' ' + VAR_12.get('sort_order') elif VAR_12.get('order_by'): VAR_26 = VAR_12.get('order_by') else: VAR_26 = CLASS_0._format([self.ref_doctype, 'modified']) + ' desc' if VAR_12.get('sort_by_next'): VAR_26 += ', ' + CLASS_0._format(VAR_12.get('sort_by_next').split('.')) + ' ' + VAR_12.get('sort_order_next') VAR_27 = None if VAR_12.get('group_by'): VAR_14 = frappe._dict(VAR_12['group_by']) VAR_27 = VAR_14['group_by'] VAR_26 = '_aggregate_column desc' return VAR_26, VAR_27, VAR_14 def FUNC_25(self, VAR_13, VAR_14): VAR_30 = [] for (fieldname, VAR_4) in VAR_13: VAR_5 = frappe.get_meta(VAR_4) if VAR_5.get_field(fieldname): VAR_41 = VAR_5.get_field(fieldname) else: if fieldname == '_aggregate_column': VAR_32 = FUNC_3(VAR_14, VAR_5) else: VAR_32 = VAR_5.get_label(fieldname) VAR_41 = frappe._dict(fieldname=fieldname, VAR_32=label) if fieldname == "name": VAR_41.fieldtype = "Link" VAR_41.options = VAR_4 VAR_30.append(VAR_41) return VAR_30 def FUNC_26(self, VAR_15, VAR_13): VAR_25 = [] for row in VAR_15: if isinstance(row, (list, tuple)): VAR_42 = frappe._dict() for VAR_43, val in enumerate(row): VAR_42[VAR_13[VAR_43].get('fieldname')] = val elif isinstance(row, dict): VAR_42 = frappe._dict(row) VAR_25.append(VAR_42) return VAR_25 @frappe.whitelist() def FUNC_27(self, VAR_16): self.db_set("disabled", cint(VAR_16)) @frappe.whitelist() def FUNC_0(VAR_0): return frappe.db.get_value('Report', VAR_0, 'disable_prepared_report') or 0 def FUNC_1(VAR_1, VAR_2): return frappe.local.module_app[scrub(VAR_1)] + "." + scrub(VAR_1) \ + ".report." + scrub(VAR_2) + "." + scrub(VAR_2) def FUNC_2(VAR_3, VAR_4): if VAR_3['aggregate_function'] == 'count': VAR_31 = 'count(*) as _aggregate_column' else: VAR_31 = '{0}(`tab{1}`.{2}) as _aggregate_column'.format( VAR_3.aggregate_function, VAR_4, VAR_3.aggregate_on ) return VAR_31 def FUNC_3(VAR_3, VAR_5): if VAR_3['aggregate_function'] == 'count': VAR_32 = 'Count' else: VAR_33 = { 'avg': 'Average', 'sum': 'Sum' } VAR_34 = VAR_5.get_label(VAR_3.aggregate_on) VAR_32 = _('{function} of {fieldlabel}').format( function=VAR_33[VAR_3.aggregate_function], fieldlabel = VAR_34 ) return VAR_32
[ 1, 2, 3, 18, 19, 25, 30, 32, 35, 38, 41, 44, 47, 50, 57, 60, 67, 71, 74, 77, 80, 83, 87, 91, 95, 97, 102, 106, 109, 112, 114, 116, 119, 121, 122, 127, 128, 132, 134, 136, 138, 142, 144, 151, 157, 160, 162, 167, 182, 184, 186, 188, 194, 206, 208, 210, 213, 215, 218, 220, 233, 235, 238, 245, 247, 252, 257, 260, 266, 268, 271, 274, 282, 284, 285, 289, 292, 301, 304, 306, 310, 315, 319, 329, 331, 346, 22, 69 ]
[ 1, 2, 3, 18, 19, 25, 30, 32, 35, 38, 41, 44, 47, 50, 57, 60, 68, 72, 75, 78, 81, 84, 88, 92, 96, 98, 103, 107, 110, 113, 115, 117, 120, 122, 123, 128, 129, 133, 135, 137, 139, 143, 145, 152, 158, 161, 163, 168, 183, 185, 187, 189, 195, 207, 209, 211, 214, 216, 219, 221, 234, 236, 239, 246, 248, 253, 258, 261, 267, 269, 272, 275, 283, 285, 286, 290, 293, 302, 305, 307, 311, 316, 320, 330, 332, 347, 22, 70 ]
4CWE-601
import pytest from werkzeug.routing import BuildError from flask_unchained.bundles.controller import Controller, Resource from flask_unchained.bundles.controller.utils import ( controller_name, get_param_tuples, join, method_name_to_url, url_for, _validate_redirect_url) from py_meta_utils import deep_getattr def test_deep_getattr(): clsdict = {'a': 'clsdict'} class First: a = 'first' b = 'first' class Second: b = 'second' c = 'second' bases = (First, Second) assert deep_getattr(clsdict, bases, 'a') == 'clsdict' assert deep_getattr(clsdict, bases, 'b') == 'first' assert deep_getattr(clsdict, bases, 'c') == 'second' with pytest.raises(AttributeError): deep_getattr(clsdict, bases, 'd') assert deep_getattr(clsdict, bases, 'a', 'default') == 'clsdict' assert deep_getattr(clsdict, bases, 'b', 'default') == 'first' assert deep_getattr(clsdict, bases, 'c', 'default') == 'second' assert deep_getattr(clsdict, bases, 'd', 'default') == 'default' class TestControllerName: def test_it_strips_controller(self): class UserController(Controller): pass assert controller_name(UserController) == 'user' def test_it_handles_acronyms(self): class APIController(Controller): pass assert controller_name(APIController) == 'api' def test_it_strips_view(self): class SomeView(Controller): pass assert controller_name(SomeView) == 'some' def test_it_works_with_more_than_one_word(self): class MoreThanOneWordController(Controller): pass assert controller_name(MoreThanOneWordController) == 'more_than_one_word' def test_it_strips_resource(self): class UserResource(Resource): pass assert controller_name(UserResource) == 'user' def test_it_strips_method_view(self): class RoleMethodView(Resource): pass assert controller_name(RoleMethodView) == 'role' def test_it_only_strips_one_suffix(self): class RoleViewControllerResource(Resource): pass assert controller_name(RoleViewControllerResource) == 'role_view_controller' def test_it_works_without_stripping_any_suffixes(self): class SomeCtrl(Controller): pass assert controller_name(SomeCtrl) == 'some_ctrl' class TestGetParamTuples: def test_it_works(self): assert get_param_tuples('<int:id>') == [('int', 'id')] def test_it_works_on_garbage(self): assert get_param_tuples(None) == [] def test_multiple(self): path = '/users/<int:user_id>/roles/<string:slug>' assert get_param_tuples(path) == [('int', 'user_id'), ('string', 'slug')] class TestUrlFor: def test_it_works_with_already_formed_path(self): assert url_for('/foobar') == '/foobar' def test_it_works_with_garbage(self): assert url_for(None) is None def test_it_works_with_config_keys_returning_path(self, app): app.config.from_mapping({'MY_KEY': '/my-key'}) assert url_for('MY_KEY') == '/my-key' def test_it_works_with_config_keys_returning_endpoints(self, app): app.config.from_mapping({'MY_KEY': 'some.endpoint'}) with pytest.raises(BuildError): assert url_for('MY_KEY') with app.test_request_context(): app.add_url_rule('/some-endpoint', endpoint='some.endpoint') assert url_for('MY_KEY') == '/some-endpoint' def test_it_works_with_endpoints(self, app): with pytest.raises(BuildError): assert url_for('some.endpoint') with app.test_request_context(): app.add_url_rule('/some-endpoint', endpoint='some.endpoint') assert url_for('some.endpoint') == '/some-endpoint' def test_it_works_with_controller_method_names(self, app): class SiteController(Controller): def about_us(self): pass with app.test_request_context(): app.add_url_rule('/about-us', endpoint='site_controller.about_us') assert url_for('about_us', _cls=SiteController) == '/about-us' def test_it_works_with_url_for_kwargs(self, app): class SiteResource(Resource): def get(self, id): pass with app.test_request_context(): app.add_url_rule('/sites/<int:id>', endpoint='site_resource.get') assert url_for('get', id=1, _cls=SiteResource) == '/sites/1' app.add_url_rule('/foo/<string:slug>', endpoint='some.endpoint') assert url_for('some.endpoint', slug='hi') == '/foo/hi' def test_it_falls_through_if_class_endpoint_not_found(self, app): class SiteResource(Resource): def get(self, id): pass with app.test_request_context(): app.add_url_rule('/sites/<int:id>', endpoint='site_resource.get') with pytest.raises(BuildError): url_for('delete', id=1, _cls=SiteResource) class TestJoin: def test_it_works_with_garbage(self): assert join(None) == '/' assert join(None, None, '', 0) == '/' def test_it_works_with_partially_valid_input(self): assert join('/', 'foo', None, 'bar', '', 'baz') == '/foo/bar/baz' def test_it_strips_neighboring_slashes(self): assert join('/', '/foo', '/', '/bar') == '/foo/bar' def test_it_doesnt_eat_single_slash(self): assert join('/', '/') == '/' assert join(None, '/') == '/' assert join('/', None) == '/' def test_it_strips_trailing_slash(self): assert join('/foo/bar/') == '/foo/bar' assert join('/foo/bar/', None) == '/foo/bar' assert join('/foo/bar/', '/') == '/foo/bar' assert join('/foo', 'bar/') == '/foo/bar' def test_trailing_slash(self): assert join('/', trailing_slash=True) == '/' assert join('/foo', 'baz', None, trailing_slash=True) == '/foo/baz/' assert join('/foo', 'baz/', trailing_slash=True) == '/foo/baz/' class TestMethodNameToUrl: def test_it_works(self): assert method_name_to_url('fooBar') == '/foo-bar' assert method_name_to_url('foo_bar') == '/foo-bar' assert method_name_to_url('fooBar_baz') == '/foo-bar-baz' assert method_name_to_url('_FooBar_baz-booFoo_') == '/foo-bar-baz-boo-foo' class TestValidateRedirectUrl: def test_it_fails_on_garbage(self): assert _validate_redirect_url(None) is False assert _validate_redirect_url(' ') is False def test_it_fails_with_invalid_netloc(self, app, monkeypatch): with app.test_request_context(): monkeypatch.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://fail.com') is False monkeypatch.undo() @pytest.mark.options(EXTERNAL_SERVER_NAME='works.com') def test_it_works_with_external_server_name(self, app, monkeypatch): with app.test_request_context(): monkeypatch.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://works.com') is True monkeypatch.undo() def test_it_works_with_explicit_external_host(self, app, monkeypatch): with app.test_request_context(): monkeypatch.setattr('flask.request.host_url', 'http://example.com') result = _validate_redirect_url('http://works.com', _external_host='works.com') assert result is True monkeypatch.undo()
import pytest from werkzeug.routing import BuildError from flask_unchained.bundles.controller import Controller, Resource from flask_unchained.bundles.controller.utils import ( controller_name, get_param_tuples, join, method_name_to_url, url_for, _validate_redirect_url) from py_meta_utils import deep_getattr def test_deep_getattr(): clsdict = {'a': 'clsdict'} class First: a = 'first' b = 'first' class Second: b = 'second' c = 'second' bases = (First, Second) assert deep_getattr(clsdict, bases, 'a') == 'clsdict' assert deep_getattr(clsdict, bases, 'b') == 'first' assert deep_getattr(clsdict, bases, 'c') == 'second' with pytest.raises(AttributeError): deep_getattr(clsdict, bases, 'd') assert deep_getattr(clsdict, bases, 'a', 'default') == 'clsdict' assert deep_getattr(clsdict, bases, 'b', 'default') == 'first' assert deep_getattr(clsdict, bases, 'c', 'default') == 'second' assert deep_getattr(clsdict, bases, 'd', 'default') == 'default' class TestControllerName: def test_it_strips_controller(self): class UserController(Controller): pass assert controller_name(UserController) == 'user' def test_it_handles_acronyms(self): class APIController(Controller): pass assert controller_name(APIController) == 'api' def test_it_strips_view(self): class SomeView(Controller): pass assert controller_name(SomeView) == 'some' def test_it_works_with_more_than_one_word(self): class MoreThanOneWordController(Controller): pass assert controller_name(MoreThanOneWordController) == 'more_than_one_word' def test_it_strips_resource(self): class UserResource(Resource): pass assert controller_name(UserResource) == 'user' def test_it_strips_method_view(self): class RoleMethodView(Resource): pass assert controller_name(RoleMethodView) == 'role' def test_it_only_strips_one_suffix(self): class RoleViewControllerResource(Resource): pass assert controller_name(RoleViewControllerResource) == 'role_view_controller' def test_it_works_without_stripping_any_suffixes(self): class SomeCtrl(Controller): pass assert controller_name(SomeCtrl) == 'some_ctrl' class TestGetParamTuples: def test_it_works(self): assert get_param_tuples('<int:id>') == [('int', 'id')] def test_it_works_on_garbage(self): assert get_param_tuples(None) == [] def test_multiple(self): path = '/users/<int:user_id>/roles/<string:slug>' assert get_param_tuples(path) == [('int', 'user_id'), ('string', 'slug')] class TestUrlFor: def test_it_works_with_already_formed_path(self): assert url_for('/foobar') == '/foobar' def test_it_works_with_garbage(self): assert url_for(None) is None def test_it_works_with_config_keys_returning_path(self, app): app.config.from_mapping({'MY_KEY': '/my-key'}) assert url_for('MY_KEY') == '/my-key' def test_it_works_with_config_keys_returning_endpoints(self, app): app.config.from_mapping({'MY_KEY': 'some.endpoint'}) with pytest.raises(BuildError): assert url_for('MY_KEY') with app.test_request_context(): app.add_url_rule('/some-endpoint', endpoint='some.endpoint') assert url_for('MY_KEY') == '/some-endpoint' def test_it_works_with_endpoints(self, app): with pytest.raises(BuildError): assert url_for('some.endpoint') with app.test_request_context(): app.add_url_rule('/some-endpoint', endpoint='some.endpoint') assert url_for('some.endpoint') == '/some-endpoint' def test_it_works_with_controller_method_names(self, app): class SiteController(Controller): def about_us(self): pass with app.test_request_context(): app.add_url_rule('/about-us', endpoint='site_controller.about_us') assert url_for('about_us', _cls=SiteController) == '/about-us' def test_it_works_with_url_for_kwargs(self, app): class SiteResource(Resource): def get(self, id): pass with app.test_request_context(): app.add_url_rule('/sites/<int:id>', endpoint='site_resource.get') assert url_for('get', id=1, _cls=SiteResource) == '/sites/1' app.add_url_rule('/foo/<string:slug>', endpoint='some.endpoint') assert url_for('some.endpoint', slug='hi') == '/foo/hi' def test_it_falls_through_if_class_endpoint_not_found(self, app): class SiteResource(Resource): def get(self, id): pass with app.test_request_context(): app.add_url_rule('/sites/<int:id>', endpoint='site_resource.get') with pytest.raises(BuildError): url_for('delete', id=1, _cls=SiteResource) class TestJoin: def test_it_works_with_garbage(self): assert join(None) == '/' assert join(None, None, '', 0) == '/' def test_it_works_with_partially_valid_input(self): assert join('/', 'foo', None, 'bar', '', 'baz') == '/foo/bar/baz' def test_it_strips_neighboring_slashes(self): assert join('/', '/foo', '/', '/bar') == '/foo/bar' def test_it_doesnt_eat_single_slash(self): assert join('/', '/') == '/' assert join(None, '/') == '/' assert join('/', None) == '/' def test_it_strips_trailing_slash(self): assert join('/foo/bar/') == '/foo/bar' assert join('/foo/bar/', None) == '/foo/bar' assert join('/foo/bar/', '/') == '/foo/bar' assert join('/foo', 'bar/') == '/foo/bar' def test_trailing_slash(self): assert join('/', trailing_slash=True) == '/' assert join('/foo', 'baz', None, trailing_slash=True) == '/foo/baz/' assert join('/foo', 'baz/', trailing_slash=True) == '/foo/baz/' class TestMethodNameToUrl: def test_it_works(self): assert method_name_to_url('fooBar') == '/foo-bar' assert method_name_to_url('foo_bar') == '/foo-bar' assert method_name_to_url('fooBar_baz') == '/foo-bar-baz' assert method_name_to_url('_FooBar_baz-booFoo_') == '/foo-bar-baz-boo-foo' class TestValidateRedirectUrl: def test_it_fails_on_garbage(self): assert _validate_redirect_url(None) is False assert _validate_redirect_url(' ') is False assert _validate_redirect_url('///evil.com') is False assert _validate_redirect_url('\\\\\\evil.com') is False assert _validate_redirect_url('\x00evil.com') is False def test_it_fails_with_invalid_netloc(self, app, monkeypatch): with app.test_request_context(): monkeypatch.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://fail.com') is False monkeypatch.undo() def test_it_requires_same_scheme(self, app, monkeypatch): with app.test_request_context(): monkeypatch.setattr('flask.request.host_url', 'https://example.com') assert _validate_redirect_url('http://example.com/foo') is False monkeypatch.undo() @pytest.mark.options(EXTERNAL_SERVER_NAME='http://works.com') def test_it_works_with_external_server_name(self, app, monkeypatch): with app.test_request_context(): monkeypatch.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://works.com') is True monkeypatch.undo() @pytest.mark.options(EXTERNAL_SERVER_NAME='https://works.com') def test_it_requires_same_external_server_name_scheme(self, app, monkeypatch): with app.test_request_context(): monkeypatch.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://works.com') is False monkeypatch.undo() def test_it_works_with_explicit_external_host(self, app, monkeypatch): with app.test_request_context(): monkeypatch.setattr('flask.request.host_url', 'http://example.com') result = _validate_redirect_url('http://works.com', _external_host='http://works.com') assert result is True monkeypatch.undo()
open_redirect
{ "code": [ " @pytest.mark.options(EXTERNAL_SERVER_NAME='works.com')", " _external_host='works.com')" ], "line_no": [ 200, 211 ] }
{ "code": [ " assert _validate_redirect_url('\\\\\\\\\\\\evil.com') is False", " assert _validate_redirect_url('\\x00evil.com') is False", " def test_it_requires_same_scheme(self, app, monkeypatch):", " with app.test_request_context():", " monkeypatch.setattr('flask.request.host_url', 'https://example.com')", " monkeypatch.undo()", " @pytest.mark.options(EXTERNAL_SERVER_NAME='http://works.com')", " @pytest.mark.options(EXTERNAL_SERVER_NAME='https://works.com')", " def test_it_requires_same_external_server_name_scheme(self, app, monkeypatch):", " with app.test_request_context():", " monkeypatch.setattr('flask.request.host_url', 'http://example.com')", " assert _validate_redirect_url('http://works.com') is False", " monkeypatch.undo()", " _external_host='http://works.com')" ], "line_no": [ 194, 195, 203, 204, 205, 207, 209, 216, 217, 218, 219, 220, 221, 227 ] }
import pytest from werkzeug.routing import BuildError from flask_unchained.bundles.controller import Controller, Resource from flask_unchained.bundles.controller.utils import ( controller_name, get_param_tuples, join, method_name_to_url, url_for, _validate_redirect_url) from py_meta_utils import deep_getattr def FUNC_0(): VAR_0 = {'a': 'clsdict'} class CLASS_6: VAR_4 = 'first' VAR_5 = 'first' class CLASS_7: VAR_5 = 'second' VAR_6 = 'second' VAR_1 = (CLASS_6, CLASS_7) assert deep_getattr(VAR_0, VAR_1, 'a') == 'clsdict' assert deep_getattr(VAR_0, VAR_1, 'b') == 'first' assert deep_getattr(VAR_0, VAR_1, 'c') == 'second' with pytest.raises(AttributeError): deep_getattr(VAR_0, VAR_1, 'd') assert deep_getattr(VAR_0, VAR_1, 'a', 'default') == 'clsdict' assert deep_getattr(VAR_0, VAR_1, 'b', 'default') == 'first' assert deep_getattr(VAR_0, VAR_1, 'c', 'default') == 'second' assert deep_getattr(VAR_0, VAR_1, 'd', 'default') == 'default' class CLASS_0: def FUNC_1(self): class CLASS_8(Controller): pass assert controller_name(CLASS_8) == 'user' def FUNC_2(self): class CLASS_9(Controller): pass assert controller_name(CLASS_9) == 'api' def FUNC_3(self): class CLASS_10(Controller): pass assert controller_name(CLASS_10) == 'some' def FUNC_4(self): class CLASS_11(Controller): pass assert controller_name(CLASS_11) == 'more_than_one_word' def FUNC_5(self): class CLASS_12(Resource): pass assert controller_name(CLASS_12) == 'user' def FUNC_6(self): class CLASS_13(Resource): pass assert controller_name(CLASS_13) == 'role' def FUNC_7(self): class CLASS_14(Resource): pass assert controller_name(CLASS_14) == 'role_view_controller' def FUNC_8(self): class CLASS_15(Controller): pass assert controller_name(CLASS_15) == 'some_ctrl' class CLASS_1: def FUNC_9(self): assert get_param_tuples('<int:VAR_8>') == [('int', 'id')] def FUNC_10(self): assert get_param_tuples(None) == [] def FUNC_11(self): VAR_7 = '/users/<int:user_id>/roles/<string:slug>' assert get_param_tuples(VAR_7) == [('int', 'user_id'), ('string', 'slug')] class CLASS_2: def FUNC_12(self): assert url_for('/foobar') == '/foobar' def FUNC_13(self): assert url_for(None) is None def FUNC_14(self, VAR_2): VAR_2.config.from_mapping({'MY_KEY': '/my-key'}) assert url_for('MY_KEY') == '/my-key' def FUNC_15(self, VAR_2): VAR_2.config.from_mapping({'MY_KEY': 'some.endpoint'}) with pytest.raises(BuildError): assert url_for('MY_KEY') with VAR_2.test_request_context(): VAR_2.add_url_rule('/some-endpoint', endpoint='some.endpoint') assert url_for('MY_KEY') == '/some-endpoint' def FUNC_16(self, VAR_2): with pytest.raises(BuildError): assert url_for('some.endpoint') with VAR_2.test_request_context(): VAR_2.add_url_rule('/some-endpoint', endpoint='some.endpoint') assert url_for('some.endpoint') == '/some-endpoint' def FUNC_17(self, VAR_2): class CLASS_16(Controller): def FUNC_29(self): pass with VAR_2.test_request_context(): VAR_2.add_url_rule('/about-us', endpoint='site_controller.about_us') assert url_for('about_us', _cls=CLASS_16) == '/about-us' def FUNC_18(self, VAR_2): class CLASS_17(Resource): def FUNC_30(self, VAR_8): pass with VAR_2.test_request_context(): VAR_2.add_url_rule('/sites/<int:VAR_8>', endpoint='site_resource.get') assert url_for('get', VAR_8=1, _cls=CLASS_17) == '/sites/1' VAR_2.add_url_rule('/foo/<string:slug>', endpoint='some.endpoint') assert url_for('some.endpoint', slug='hi') == '/foo/hi' def FUNC_19(self, VAR_2): class CLASS_17(Resource): def FUNC_30(self, VAR_8): pass with VAR_2.test_request_context(): VAR_2.add_url_rule('/sites/<int:VAR_8>', endpoint='site_resource.get') with pytest.raises(BuildError): url_for('delete', VAR_8=1, _cls=CLASS_17) class CLASS_3: def FUNC_13(self): assert join(None) == '/' assert join(None, None, '', 0) == '/' def FUNC_20(self): assert join('/', 'foo', None, 'bar', '', 'baz') == '/foo/bar/baz' def FUNC_21(self): assert join('/', '/foo', '/', '/bar') == '/foo/bar' def FUNC_22(self): assert join('/', '/') == '/' assert join(None, '/') == '/' assert join('/', None) == '/' def FUNC_23(self): assert join('/foo/bar/') == '/foo/bar' assert join('/foo/bar/', None) == '/foo/bar' assert join('/foo/bar/', '/') == '/foo/bar' assert join('/foo', 'bar/') == '/foo/bar' def FUNC_24(self): assert join('/', trailing_slash=True) == '/' assert join('/foo', 'baz', None, trailing_slash=True) == '/foo/baz/' assert join('/foo', 'baz/', trailing_slash=True) == '/foo/baz/' class CLASS_4: def FUNC_9(self): assert method_name_to_url('fooBar') == '/foo-bar' assert method_name_to_url('foo_bar') == '/foo-bar' assert method_name_to_url('fooBar_baz') == '/foo-bar-baz' assert method_name_to_url('_FooBar_baz-booFoo_') == '/foo-bar-baz-boo-foo' class CLASS_5: def FUNC_25(self): assert _validate_redirect_url(None) is False assert _validate_redirect_url(' ') is False def FUNC_26(self, VAR_2, VAR_3): with VAR_2.test_request_context(): VAR_3.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://fail.com') is False VAR_3.undo() @pytest.mark.options(EXTERNAL_SERVER_NAME='works.com') def FUNC_27(self, VAR_2, VAR_3): with VAR_2.test_request_context(): VAR_3.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://works.com') is True VAR_3.undo() def FUNC_28(self, VAR_2, VAR_3): with VAR_2.test_request_context(): VAR_3.setattr('flask.request.host_url', 'http://example.com') VAR_9 = _validate_redirect_url('http://works.com', _external_host='works.com') assert VAR_9 is True VAR_3.undo()
import pytest from werkzeug.routing import BuildError from flask_unchained.bundles.controller import Controller, Resource from flask_unchained.bundles.controller.utils import ( controller_name, get_param_tuples, join, method_name_to_url, url_for, _validate_redirect_url) from py_meta_utils import deep_getattr def FUNC_0(): VAR_0 = {'a': 'clsdict'} class CLASS_6: VAR_4 = 'first' VAR_5 = 'first' class CLASS_7: VAR_5 = 'second' VAR_6 = 'second' VAR_1 = (CLASS_6, CLASS_7) assert deep_getattr(VAR_0, VAR_1, 'a') == 'clsdict' assert deep_getattr(VAR_0, VAR_1, 'b') == 'first' assert deep_getattr(VAR_0, VAR_1, 'c') == 'second' with pytest.raises(AttributeError): deep_getattr(VAR_0, VAR_1, 'd') assert deep_getattr(VAR_0, VAR_1, 'a', 'default') == 'clsdict' assert deep_getattr(VAR_0, VAR_1, 'b', 'default') == 'first' assert deep_getattr(VAR_0, VAR_1, 'c', 'default') == 'second' assert deep_getattr(VAR_0, VAR_1, 'd', 'default') == 'default' class CLASS_0: def FUNC_1(self): class CLASS_8(Controller): pass assert controller_name(CLASS_8) == 'user' def FUNC_2(self): class CLASS_9(Controller): pass assert controller_name(CLASS_9) == 'api' def FUNC_3(self): class CLASS_10(Controller): pass assert controller_name(CLASS_10) == 'some' def FUNC_4(self): class CLASS_11(Controller): pass assert controller_name(CLASS_11) == 'more_than_one_word' def FUNC_5(self): class CLASS_12(Resource): pass assert controller_name(CLASS_12) == 'user' def FUNC_6(self): class CLASS_13(Resource): pass assert controller_name(CLASS_13) == 'role' def FUNC_7(self): class CLASS_14(Resource): pass assert controller_name(CLASS_14) == 'role_view_controller' def FUNC_8(self): class CLASS_15(Controller): pass assert controller_name(CLASS_15) == 'some_ctrl' class CLASS_1: def FUNC_9(self): assert get_param_tuples('<int:VAR_8>') == [('int', 'id')] def FUNC_10(self): assert get_param_tuples(None) == [] def FUNC_11(self): VAR_7 = '/users/<int:user_id>/roles/<string:slug>' assert get_param_tuples(VAR_7) == [('int', 'user_id'), ('string', 'slug')] class CLASS_2: def FUNC_12(self): assert url_for('/foobar') == '/foobar' def FUNC_13(self): assert url_for(None) is None def FUNC_14(self, VAR_2): VAR_2.config.from_mapping({'MY_KEY': '/my-key'}) assert url_for('MY_KEY') == '/my-key' def FUNC_15(self, VAR_2): VAR_2.config.from_mapping({'MY_KEY': 'some.endpoint'}) with pytest.raises(BuildError): assert url_for('MY_KEY') with VAR_2.test_request_context(): VAR_2.add_url_rule('/some-endpoint', endpoint='some.endpoint') assert url_for('MY_KEY') == '/some-endpoint' def FUNC_16(self, VAR_2): with pytest.raises(BuildError): assert url_for('some.endpoint') with VAR_2.test_request_context(): VAR_2.add_url_rule('/some-endpoint', endpoint='some.endpoint') assert url_for('some.endpoint') == '/some-endpoint' def FUNC_17(self, VAR_2): class CLASS_16(Controller): def FUNC_31(self): pass with VAR_2.test_request_context(): VAR_2.add_url_rule('/about-us', endpoint='site_controller.about_us') assert url_for('about_us', _cls=CLASS_16) == '/about-us' def FUNC_18(self, VAR_2): class CLASS_17(Resource): def FUNC_32(self, VAR_8): pass with VAR_2.test_request_context(): VAR_2.add_url_rule('/sites/<int:VAR_8>', endpoint='site_resource.get') assert url_for('get', VAR_8=1, _cls=CLASS_17) == '/sites/1' VAR_2.add_url_rule('/foo/<string:slug>', endpoint='some.endpoint') assert url_for('some.endpoint', slug='hi') == '/foo/hi' def FUNC_19(self, VAR_2): class CLASS_17(Resource): def FUNC_32(self, VAR_8): pass with VAR_2.test_request_context(): VAR_2.add_url_rule('/sites/<int:VAR_8>', endpoint='site_resource.get') with pytest.raises(BuildError): url_for('delete', VAR_8=1, _cls=CLASS_17) class CLASS_3: def FUNC_13(self): assert join(None) == '/' assert join(None, None, '', 0) == '/' def FUNC_20(self): assert join('/', 'foo', None, 'bar', '', 'baz') == '/foo/bar/baz' def FUNC_21(self): assert join('/', '/foo', '/', '/bar') == '/foo/bar' def FUNC_22(self): assert join('/', '/') == '/' assert join(None, '/') == '/' assert join('/', None) == '/' def FUNC_23(self): assert join('/foo/bar/') == '/foo/bar' assert join('/foo/bar/', None) == '/foo/bar' assert join('/foo/bar/', '/') == '/foo/bar' assert join('/foo', 'bar/') == '/foo/bar' def FUNC_24(self): assert join('/', trailing_slash=True) == '/' assert join('/foo', 'baz', None, trailing_slash=True) == '/foo/baz/' assert join('/foo', 'baz/', trailing_slash=True) == '/foo/baz/' class CLASS_4: def FUNC_9(self): assert method_name_to_url('fooBar') == '/foo-bar' assert method_name_to_url('foo_bar') == '/foo-bar' assert method_name_to_url('fooBar_baz') == '/foo-bar-baz' assert method_name_to_url('_FooBar_baz-booFoo_') == '/foo-bar-baz-boo-foo' class CLASS_5: def FUNC_25(self): assert _validate_redirect_url(None) is False assert _validate_redirect_url(' ') is False assert _validate_redirect_url('///evil.com') is False assert _validate_redirect_url('\\\\\\evil.com') is False assert _validate_redirect_url('\x00evil.com') is False def FUNC_26(self, VAR_2, VAR_3): with VAR_2.test_request_context(): VAR_3.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://fail.com') is False VAR_3.undo() def FUNC_27(self, VAR_2, VAR_3): with VAR_2.test_request_context(): VAR_3.setattr('flask.request.host_url', 'https://example.com') assert _validate_redirect_url('http://example.com/foo') is False VAR_3.undo() @pytest.mark.options(EXTERNAL_SERVER_NAME='http://works.com') def FUNC_28(self, VAR_2, VAR_3): with VAR_2.test_request_context(): VAR_3.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://works.com') is True VAR_3.undo() @pytest.mark.options(EXTERNAL_SERVER_NAME='https://works.com') def FUNC_29(self, VAR_2, VAR_3): with VAR_2.test_request_context(): VAR_3.setattr('flask.request.host_url', 'http://example.com') assert _validate_redirect_url('http://works.com') is False VAR_3.undo() def FUNC_30(self, VAR_2, VAR_3): with VAR_2.test_request_context(): VAR_3.setattr('flask.request.host_url', 'http://example.com') VAR_9 = _validate_redirect_url('http://works.com', _external_host='http://works.com') assert VAR_9 is True VAR_3.undo()
[ 2, 4, 10, 11, 14, 18, 22, 24, 30, 35, 36, 42, 46, 48, 53, 58, 63, 68, 73, 78, 79, 83, 86, 90, 91, 95, 98, 102, 105, 108, 112, 116, 120, 125, 129, 134, 138, 141, 146, 151, 152, 157, 160, 163, 168, 174, 179, 180, 187, 188, 193, 199, 206, 214 ]
[ 2, 4, 10, 11, 14, 18, 22, 24, 30, 35, 36, 42, 46, 48, 53, 58, 63, 68, 73, 78, 79, 83, 86, 90, 91, 95, 98, 102, 105, 108, 112, 116, 120, 125, 129, 134, 138, 141, 146, 151, 152, 157, 160, 163, 168, 174, 179, 180, 187, 188, 196, 202, 208, 215, 222, 230 ]