Example #1
0
    def test_invalid_json(self):
        data = {
            "requestContext": {
                "authorizer": {
                    "foo": "bar",
                    "baz": 1
                },
                "identity": {
                    "sourceIp": "127.0.0.1"
                },
            },
            "pathParameters": {
                "one": 1,
                "two": 2
            },
            "queryStringParameters": {
                "limit": 10,
                "page": 2
            },
            "headers": {
                "Accept": "*/*"
            },
        }

        result = api.Request(data)

        self.assertEqual(result.body, "")
Example #2
0
def MusicCollections(offset=0):
    res = API.Request('music.collections', {
        'arg_limit': Common.MAILRU_LIMIT,
        'arg_offset': offset,
    })

    if not res or not res['Total']:
        return Common.NoContents()

    oc = ObjectContainer(title2=u'%s' % L('Collections'),
                         replace_parent=(offset > 0))

    for item in res['Data']:
        title = u'%s' % item['Name']
        summary = ', '.join(item['tags'])
        if item['Description']:
            summary = u"%s\n%s" % (summary, item['Description'])

        oc.add(
            DirectoryObject(key=Callback(
                MusicCollection,
                uid='',
                title=title,
            ),
                            title=title,
                            thumb=item['CoverCroped'],
                            summary=u'%s' % summary))

    offset = int(offset) + Common.MAILRU_LIMIT
    if offset < res['Total']:
        oc.add(
            NextPageObject(key=Callback(MusicCollections, offset=offset),
                           title=u'%s' % L('Next page')))
    return oc
Example #3
0
def resolve_request(provider,
                    method,
                    url_path,
                    status_code=200,
                    format="json"):

    return get_desired_response(provider, api.Request(method, url_path),
                                status_code, format)
Example #4
0
 def __init__(self, origins, destinations, key):
     param_map = self._map(origins, destinations, key)
     replace = {" ": "+"}
     url = "https://maps.googleapis.com/maps/api/distancematrix/json?"
     req = api.Request(url, param_map, replace)
     self.data = api.send(req)
     self.origins = origins
     self.destinations = destinations
Example #5
0
def MusicCollection(uid, title, offset=0):
    return Common.GetMusicList(init_object=GetTrackObject,
                               callback_page=MusicCollection,
                               title=title,
                               uid=uid,
                               offset=0,
                               res=API.Request(
                                   'music.collection', {
                                       'arg_limit': Prefs['audio_per_page'],
                                       'arg_offset': offset,
                                       'arg_name': title,
                                   }))
Example #6
0
def MusicSearch(query, title=u'%s' % L('Search'), offset=0):
    return Common.GetMusicList(init_object=GetTrackObject,
                               callback_page=MusicList,
                               title=title,
                               uid=Prefs['username'],
                               offset=offset,
                               res=API.Request(
                                   'music.search', {
                                       'arg_limit': Prefs['audio_per_page'],
                                       'arg_offset': offset,
                                       'arg_query': query,
                                   }))
Example #7
0
def MusicList(uid, title, offset=0, path='/my/'):
    return Common.GetMusicList(init_object=GetTrackObject,
                               callback_page=MusicList,
                               title=title,
                               uid=uid,
                               offset=offset,
                               res=API.Request(
                                   'audio.get', {
                                       'user': uid,
                                       'arg_limit': Prefs['audio_per_page'],
                                       'arg_offset': offset
                                   }))
Example #8
0
def AddVideoAlbums(oc, uid, offset=0):
    albums = API.Request('video.get_albums', {
        'user': uid,
        'arg_limit': Common.MAILRU_LIMIT,
        'arg_offset': offset
    })

    # First album is default
    has_albums = albums and albums['total'] > 1
    offset = int(offset)

    if not offset:
        if not has_albums and not len(oc.objects):
            return VideoList(uid=uid, title=u'%s' % L('All videos'))
        else:
            oc.add(
                DirectoryObject(
                    key=Callback(
                        VideoList,
                        uid=uid,
                        title=u'%s' % L('All videos'),
                    ),
                    title=u'%s' % L('All videos'),
                ))

    if has_albums:
        for item in albums['items']:
            # display playlist title and number of videos
            title = u'%s: %s (%d)' % (L('Album'), item['Name'], item['Count'])

            oc.add(
                DirectoryObject(key=Callback(VideoList,
                                             uid=uid,
                                             title=u'%s' % item['Name'],
                                             ltype='album_items',
                                             album_id=item['ID']),
                                title=title,
                                thumb=item['CoverImgPath']))

        offset = offset + Common.MAILRU_LIMIT
        if offset < albums['total']:
            oc.add(
                NextPageObject(key=Callback(VideoAlbums,
                                            uid=uid,
                                            title=oc.title2,
                                            offset=offset),
                               title=u'%s' % L('More albums')))

    return oc
Example #9
0
def GetChannels(callback_action, callback_page, uid, offset):
    '''Get groups container with custom callback'''
    if uid:
        method = 'video_channel.get_channels'
        title = u'%s' % L('My channels')
    else:
        method = 'video_channel.get_channels_catalogue'
        title = u'%s' % L('All channels')

    items = API.Request(method, {
        'user': uid,
        'arg_offset': offset,
        'arg_limit': MAILRU_LIMIT,
    })

    if items:
        items = HTML.ElementFromString(items)

    if not items:
        return NoContents()

    oc = ObjectContainer(title2=title, replace_parent=(offset > 0))

    for item in items.xpath('//div[@data-type="item"]'):
        info = item.xpath(
            './/a[contains(@class, "b-catalog__channel-item__name")]')[0]

        title = u'%s' % info.text_content()

        try:
            thumb = API.ImageFromElement(
                item.xpath(
                    './/a[contains(@class, "b-catalog__channel-item__avatar")]'
                )[0])
        except:
            thumb = None
            pass

        oc.add(
            DirectoryObject(key=Callback(
                callback_action,
                uid=API.GroupFromElement(info),
                title=title,
            ),
                            title=title,
                            thumb=thumb))

    return oc
Example #10
0
    def test_instance(self):
        data = {
            "requestContext": {
                "authorizer": {
                    "foo": "bar",
                    "baz": 1
                },
                "identity": {
                    "sourceIp": "127.0.0.1"
                },
            },
            "body": '{"ping": "pong"}',
            "pathParameters": {
                "one": 1,
                "two": 2
            },
            "queryStringParameters": {
                "limit": 10,
                "page": 2
            },
            "headers": {
                "Accept": "*/*"
            },
        }
        instance = api.Request(data)

        self.assertIsInstance(instance, api.Request)
        self.assertTrue(hasattr(instance, "authorizer"))
        self.assertTrue(hasattr(instance, "body"))
        self.assertTrue(hasattr(instance, "path"))
        self.assertTrue(hasattr(instance, "query"))
        self.assertTrue(hasattr(instance, "headers"))
        self.assertTrue(hasattr(instance, "identity"))
        self.assertEqual(instance.authorizer.foo, "bar")
        self.assertEqual(instance.authorizer.baz, 1)
        self.assertEqual(instance.body, {"ping": "pong"})
        self.assertEqual(instance.path.one, 1)
        self.assertEqual(instance.path.two, 2)
        self.assertEqual(instance.query.limit, 10)
        self.assertEqual(instance.query.page, 2)
        self.assertEqual(instance.headers.Accept, "*/*")
        self.assertEqual(instance.identity.sourceIp, "127.0.0.1")
Example #11
0
def PhotoList(uid, title, album_id, offset=0):
    photos = API.Request(
        'photo.photostream', {
            'user': uid,
            'arg_album_id': album_id,
            'arg_limit': Prefs['photos_per_page'],
            'arg_offset': offset
        }, True)

    if not photos or len(photos) < 5 or not photos[4]:
        return Common.NoContents()

    oc = ObjectContainer(title2=(u'%s' % title),
                         content='photo',
                         replace_parent=(offset > 0))

    total = int(photos[4])
    items = HTML.ElementFromString(
        photos[3]).xpath('//div[contains(@class, "b-catalog__photo-item")]')

    for item in items:
        try:
            link = item.find('a[@class="b-catalog__photo-item-img"]')
            oc.add(
                PhotoObject(key=link.get('data-filedimageurl'),
                            rating_key='%s%s' %
                            (Common.MAILRU_URL, link.get('href')),
                            thumb=API.ImageFromElement(item)))
        except:
            pass

    offset = int(offset) + int(Prefs['photos_per_page'])
    if offset < total:
        oc.add(
            NextPageObject(key=Callback(PhotoList,
                                        uid=uid,
                                        title=title,
                                        album_id=album_id,
                                        offset=offset),
                           title=u'%s' % L('Next page')))

    return oc
Example #12
0
def GetGroups(callback_action, callback_page, uid, offset):
    '''Get groups container with custom callback'''
    oc = ObjectContainer(title2=u'%s' % L('My groups'),
                         replace_parent=(offset > 0))
    groups = API.Request('groups.get_groups', {
        'user': uid,
        'arg_offset': offset
    })

    if groups and groups['total']:
        items = HTML.ElementFromString(groups['html'])

        for item in items.xpath('//div[@data-group="item"]'):
            info = item.xpath('.//a[contains(@class, "groups__name")]')[0]

            title = u'%s' % info.text_content()

            try:
                thumb = API.ImageFromElement(
                    item.xpath('.//a[contains(@class, "groups__avatar")]')[0])
            except:
                thumb = None
                pass

            oc.add(
                DirectoryObject(key=Callback(callback_action,
                                             uid=API.GroupFromElement(info),
                                             title=title,
                                             path=info.get('href').replace(
                                                 '/?ref=', '/')),
                                title=title,
                                thumb=thumb))

        if groups['next_page_size'] > 0:
            oc.add(
                NextPageObject(key=Callback(callback_page,
                                            uid=uid,
                                            offset=groups['new_offset']),
                               title=u'%s' % L('Next page')))

    return oc
Example #13
0
def GetFriends(callback_action, callback_page, uid, offset):
    '''Get friends container with custom callback'''
    oc = ObjectContainer(title2=u'%s' % L('My friends'),
                         replace_parent=(offset > 0))

    friends = API.Request('video.friends', {
        'user': uid,
        'arg_limit': MAILRU_LIMIT,
        'arg_offset': offset
    })

    if friends and friends['Total'] and len(friends['Data']):
        '''
        Avatar32URL, FirstName, Avatar180URL, AvatarChangeTime,
        SmallAvatarURL, Dir, AuID, LastName, VideoCount,
        Email, Name, IsFemale
        '''
        for item in friends['Data']:
            title = u'%s' % item['Name']

            oc.add(
                DirectoryObject(key=Callback(
                    callback_action,
                    uid=item['Email'],
                    title=title,
                    path=item['Dir'],
                ),
                                title=title,
                                thumb=item['Avatar180URL']))

        if 'NewOffset' in friends and friends['NewOffset'] < friends['Total']:
            oc.add(
                NextPageObject(key=Callback(callback_page,
                                            uid=uid,
                                            offset=friends['NewOffset']),
                               title=u'%s' % L('Next page')))

    return oc
Example #14
0
 def result(self, scriptName=""):
     with api.Request("GET", False) as (authorized, status):
         if authorized:
             result = scriptManager.getResult(scriptName)
             status(result)
             return result
Example #15
0
 def result(self, scriptName="", scriptResults={}):
     with api.Request("GET", False) as (authorized, status):
         if authorized:
             scriptManager.setResult(scriptName, scriptResults)
             return {"Result":"Completed"}
Example #16
0
 def update(self):
     with api.Request("GET", False) as (authorized, status):
         if authorized:
             scriptManager.refresh()
             api.refresh()
             return {"Result":"Completed"}
Example #17
0
            return ""

    def _fault(self, error):
        return xmlrpclib.Fault(*error)

    def _dump(self, data):
        return xmlrpclib.dumps((data, ), methodresponse=True)


class UpstreamServerProvider(rpc.UpstreamServerProvider):
    pass


if __name__ == "__main__":

    import api

    provider = FilesMockProvider("/Users/tomashanacek/Downloads/api")

    print provider(
        api.Request(
            body="<?xml version='1.0'?><methodCall><methodName>user.list"
            "</methodName><params></params></methodCall>"))
    print provider.error

    print provider(
        api.Request(
            body="<?xml version='1.0'?><methodCall><methodName>user.get"
            "</methodName><params></params></methodCall>"))
    print provider.error
Example #18
0
    def _dump(self, data, rpcid=1):
        return jsonrpclib.dumps(data, methodresponse=True, rpcid=rpcid)

    @staticmethod
    def get_method_name(request_body):
        try:
            data = jsonrpclib.loads(request_body)
            if not data or "method" not in data:
                return ""
            return data["method"]
        except ValueError:
            return ""


class UpstreamServerProvider(rpc.UpstreamServerProvider):
    pass


if __name__ == "__main__":

    import api

    provider = FilesMockProvider("/Users/tomashanacek/Downloads/api")

    print provider(api.Request(body='{"method": "user.list", "id": 1}'))
    print provider.error

    print provider(method_name=FilesMockProvider.get_method_name(
        '{"method": "user.get", "id": 1}'))
    print provider.error
Example #19
0
 def run(self, scriptName="", args = ""):
     with api.Request("POST", True) as (authorized, status):
         if authorized:
             scriptManager.add(scriptName)
             return {"Result":"Completed"}