Beispiel #1
0
def spy_info(room):
    """
    Finds info for a given room name.

    The info shows many mods, broadcasters, total users and a users(list) with all the user names.

    :param room: str the room name to get spy info for.
    :return: dict{'mod_count', 'broadcaster_count', 'total_count', list('users')} or PW on password protected room.,
    or None on failure or empty room.
    """
    url = 'http://api.tinychat.com/%s.json' % room
    check = get_roomconfig_xml(room)
    if check == 'PW':
        return check
    else:
        try:
            response = web.http_get(url, json=True)
            mod_count = str(response['json']['mod_count'])
            broadcaster_count = str(response['json']['broadcaster_count'])
            total_count = str(response['json']['total_count'])
            if total_count > 0:
                users = response['json']['names']
                return {
                    'mod_count': mod_count,
                    'broadcaster_count': broadcaster_count,
                    'total_count': total_count,
                    'users': users
                }
        except KeyError:
            return None
def soundcloud_search(search):
    """
    Searches soundcloud's API for a given search term.

    :param search: str the search term to search for.
    :return: dict{'type=soundcloud', 'video_id', 'video_time', 'video_title'} or None on no match or error.
    """
    if search:
        search_url = 'http://api.soundcloud.com/tracks/?' \
                     'filter=streamable&q=%s&limit=25&client_id=%s' % (search, SOUNDCLOUD_API_KEY)

        response = web.http_get(search_url, json=True)
        if response['json'] is not None:
            try:
                track_id = response['json'][0]['id']
                track_time = response['json'][0]['duration']
                track_title = response['json'][0]['title'].encode(
                    'ascii', 'ignore')
                return {
                    'type': 'soundCloud',
                    'video_id': track_id,
                    'video_time': track_time,
                    'video_title': track_title
                }
            except (IndexError, KeyError):
                return None
        return None
Beispiel #3
0
def tinychat_user_info(tc_account):
    """
    Finds info for a given tinychat account name.
    :param tc_account: str the account name.
    :return: dict {'username', 'tinychat_id', 'last_active', 'name', 'location', 'biography'} or None on error.
    """
    url = 'http://tinychat.com/api/tcinfo?username=%s' % tc_account
    response = web.http_get(url=url, json=True)
    if response['json'] is not None:
        try:
            username = response['json']['username']
            user_id = response['json']['id']
            last_active = time.ctime(int(response['json']['last_active']))
            name = response['json']['name']
            location = response['json']['location']
            biography = response['json']['biography']

            return {
                'username': username,
                'tinychat_id': user_id,
                'last_active': last_active,
                'name': name,
                'location': location,
                'biography': biography
            }
        except KeyError:
            return None
Beispiel #4
0
def youtube_playlist_search(search, results=10):
    """
    Searches youtube for a playlist matching the search term.
    :param search: str the search term to search to search for.
    :param results: int the number of playlist matches we want returned.
    :return: list[dict{'playlist_title', 'playlist_id'}] or None on failure.
    """
    if search:
        youtube_search_url = 'https://www.googleapis.com/youtube/v3/search?' \
                             'type=playlist&key=%s&maxResults=50&q=%s&part=snippet' % (YOUTUBE_API_KEY, search)

        response = web.http_get(youtube_search_url, json=True)
        if response['json'] is not None:
            play_lists = []
            try:
                if 'items' in response['json']:
                    for item in response['json']['items']:
                        playlist_id = item['id']['playlistId']
                        playlist_title = item['snippet']['title'].encode(
                            'ascii', 'ignore')
                        play_list_info = {
                            'playlist_title': playlist_title,
                            'playlist_id': playlist_id
                        }
                        play_lists.append(play_list_info)
                        if len(play_lists) == results:
                            return play_lists
            except KeyError as ke:
                log.error(ke, exc_info=True)
                return None
    else:
        return None
Beispiel #5
0
def spy_info(room):
    """
    Finds info for a given room name.

    The info shows many mods, broadcasters, total users and a users(list) with all the user names.

    :param room: str the room name to get spy info for.
    :return: dict{'mod_count', 'broadcaster_count', 'total_count', list('users')} or PW on password protected room.,
    or None on failure or empty room.
    """
    url = 'https://api.tinychat.com/%s.json' % room
    check = get_roomconfig_xml(room)
    if check == 'PW':
        return check
    else:
        try:
            response = web.http_get(url, json=True)
            mod_count = str(response['json']['mod_count'])
            broadcaster_count = str(response['json']['broadcaster_count'])
            total_count = str(response['json']['total_count'])
            # membername = str(response['json']['membername'])
            if total_count > 0:
                users = response['json']['names']
                return {
                    'mod_count': mod_count,
                    'broadcaster_count': broadcaster_count,
                    'total_count': total_count,
                    # 'membername': membername,
                    'users': users
                }
        except KeyError:
            return None
Beispiel #6
0
def lastfm_listening_now(max_tunes, by_id=True):
    """
    Gets a list of tunes other people using last.fm are listening to, and turns them in to a youtube list of tracks.
    :param max_tunes: int the amount of tracks we want.
    :param by_id: bool if set to True, only tunes that have a youtube id will be added(recommended)
    :return: list[ dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'} ] or None on error.
    """
    url = 'http://lastfm-ajax-vip1.phx1.cbsig.net/kerve/listeningnow?limit=%s&format=json' % max_tunes
    lastfm = web.http_get(url, json=True)
    log.debug('lastfm response %s' % lastfm)
    if lastfm['json'] is not None:
        if len(lastfm['json']['Users']) is not 0:
            yt_tracks = []
            for user in lastfm['json']['Users']:
                if 'playlink' in user:
                    if 'data-youtube-id' in user['playlink']:
                        youtube_id = user['playlink']['data-youtube-id']
                        yt = youtube.youtube_time(youtube_id)
                        log.debug(yt)
                        if yt is not None:
                            yt_tracks.append(yt)
                else:
                    if 'Track' in user:
                        search_str = '%s - %s' % (user['Track']['Artist'],
                                                  user['Track']['Name'])
                        if not by_id:
                            yt = youtube.youtube_search(search_str)
                            log.debug(
                                'search by search string: %s result: %s' %
                                (search_str, yt))
                            if yt is not None:
                                yt_tracks.append(yt)
            return yt_tracks
        return None
Beispiel #7
0
def get_bauth_token(roomname, nick, uid, greenroom, proxy=None):
    """
    Find the bauth token needed before we can start a broadcast.
    NOTE: Might need some more work related to green room.
    :param roomname: str the room name.
    :param nick: str the nick we use in the room.
    :param uid: str our ID in the room.
    :param greenroom: bool should be True if greenroom is enabled.
    :param proxy: str use a proxy for this request.
    :return: str token or PW if a password is needed to broadcast.
    """
    if greenroom:
        xmlurl = 'https://tinychat.com/api/broadcast.pw?site=greenroom&name=%s&nick=%s&id=%s' % (
            roomname, nick, uid)
    else:
        xmlurl = 'https://tinychat.com/api/broadcast.pw?site=tinychat&name=%s&nick=%s&id=%s' % (
            roomname, nick, uid)

    response = web.http_get(xmlurl, proxy=proxy)
    if response['content'] is not None:
        xml = parseString(response['content'])
        root = xml.getElementsByTagName('response')[0]
        result = root.getAttribute('result')
        if result == 'PW':
            return result
        else:
            token = root.getAttribute('token')
            return token
Beispiel #8
0
def whois(ip):
    """
    Searches ip-api for information about a given IP.
    :param ip: The ip str to search for.
    :return: information str or None on error.
    """
    if str(ip).strip():
        url = 'http://ip-api.com/json/%s' % ip
        json_data = web.http_get(url, json=True)
        try:
            query = json_data['json']['query']
            city = json_data['json']['city']
            countrycode = json_data['json']['countryCode']
            country = json_data['json']['country']
            isp = json_data['json']['isp']
            org = json_data['json']['org']
            region = json_data['json']['regionName']
            zipcode = json_data['json']['zip']
            info = query + (' - ' + city + ', ' + region + ', ' + 'Country: ' +
                            country + ' (' + countrycode + '),' + ' Zip: ' +
                            zipcode + ', ' + 'Isp: ' + isp + ' (' + org + ') ')
            return info
        except KeyError:
            return None
    else:
        return None
Beispiel #9
0
def tinychat_user_info(tc_account):
    """
    Finds info for a given tinychat account name.
    :param tc_account: str the account name.
    :return: dict {'username', 'tinychat_id', 'last_active', 'name', 'location', 'biography'} or None on error.
    """
    url = 'https://tinychat.com/api/tcinfo?username=%s' % tc_account
    response = web.http_get(url=url, json=True)
    if response['json'] is not None:
        try:
            username = response['json']['username']
            # Enable the below for the ID, There is no need to know that tbh.
            # user_id = response['json']['id']
            last_active = time.ctime(int(response['json']['last_active']))
            name = response['json']['name']
            location = response['json']['location']
            biography = response['json']['biography']
            website = response['json']['website']

            return {
                'username': username,
                # 'tinychat_id': user_id,
                'last_active': last_active,
                'name': name,
                'location': location,
                'biography': biography,
                'website': website
            }
        except KeyError:
            return None
Beispiel #10
0
def youtube_playlist_videos(playlist_id):
    """
    Finds the video info for a given playlist ID.

    The list returned will contain a maximum of 50 videos.
    :param playlist_id: str the playlist ID
    :return: list[dict{'type=youTube', 'video_id', 'video_title', 'video_time'}] or None on failure.
    """
    playlist_details_url = 'https://www.googleapis.com/youtube/v3/playlistItems?' \
                           'key=%s&playlistId=%s&maxResults=50&part=snippet,id' % (YOUTUBE_API_KEY, playlist_id)

    response = web.http_get(playlist_details_url, json=True)
    if response['json'] is not None:
        video_list = []
        try:
            if 'items' in response['json']:
                for item in response['json']['items']:
                    video_id = item['snippet']['resourceId']['videoId']
                    video_title = item['snippet']['title'].encode(
                        'ascii', 'ignore')

                    video_time = youtube_time(video_id)
                    if video_time is not None:
                        info = {
                            'type': 'youTube',
                            'video_id': video_id,
                            'video_title': video_title,
                            'video_time': video_time['video_time']
                        }
                        video_list.append(info)
                return video_list
        except KeyError as ke:
            log.error(ke, exc_info=True)
            return None
Beispiel #11
0
def get_bauth_token(roomname, nick, uid, greenroom, proxy=None):
    """
    Find the bauth token needed before we can start a broadcast.
    NOTE: Might need some more work related to green room.
    :param roomname: str the room name.
    :param nick: str the nick we use in the room.
    :param uid: str our ID in the room.
    :param greenroom: bool should be True if greenroom is enabled.
    :param proxy: str use a proxy for this request.
    :return: str token or PW if a password is needed to broadcast.
    """
    if greenroom:
        xmlurl = 'http://tinychat.com/api/broadcast.pw?site=greenroom&name=%s&nick=%s&id=%s' % (roomname, nick, uid)
    else:
        xmlurl = 'http://tinychat.com/api/broadcast.pw?site=tinychat&name=%s&nick=%s&id=%s' % (roomname, nick, uid)

    response = web.http_get(xmlurl, proxy=proxy)
    if response['content'] is not None:
        xml = parseString(response['content'])
        root = xml.getElementsByTagName('response')[0]
        result = root.getAttribute('result')
        if result == 'PW':
            return result
        else:
            token = root.getAttribute('token')
            return token
Beispiel #12
0
def chuck_norris():
    """
    Finds a random Chuck Norris joke/quote.
    :return: joke str or None on failure.
    """
    url = 'https://api.icndb.com/jokes/random/?escape=javascript'
    response = web.http_get(url, json=True)
    if response['json'] is not None:
        if response['json']['type'] == 'success':
            joke = response['json']['value']['joke'].decode('string_escape')
            return joke
        return None
Beispiel #13
0
def advice():
    """
    Random sentences of advice.
    :return:
    """
    url = "http://api.adviceslip.com/advice"
    json_data = web.http_get(url, json=True)
    if json_data['json']:
        advised = json_data['json']['slip']['advice'].decode('string_escape')
        return advised
    else:
        return None
Beispiel #14
0
def get_roomconfig_xml(room, roompass=None, proxy=None):
    """
    Finds room configuration for a given room name.
    :param room: str the room name to find info for.
    :param roompass: str the password to the room. Defaults to None.
    :param proxy: str use a proxy for this request.
    :return: dict {'tcurl', 'ip', 'port', 'app', 'roomtype', 'greenroom=bool', 'bpassword'}
    """
    if roompass:
        xmlurl = 'https://apl.tinychat.com/api/find.room/%s?site=tinychat&password=%s&url=tinychat.com' % \
                 (room, roompass)
    else:
        xmlurl = 'https://apl.tinychat.com/api/find.room/%s?site=tinychat&url=tinychat.com' % room

    response = web.http_get(xmlurl, proxy=proxy)
    if response['content'] is not None:
        try:
            xml = parseString(response['content'])
        except ExpatError:
            xml = None
        if xml is not None:
            broadcast_pass = None
            root = xml.getElementsByTagName('response')[0]
            result = root.getAttribute('result')
            if result == 'PW':
                return result
            else:
                roomtype = root.getAttribute('roomtype')
                tc_url = root.getAttribute('rtmp')
                rtmp_parts = tc_url.split('/')
                app = rtmp_parts[3]
                ip_port_parts = rtmp_parts[2].split(':')
                ip = ip_port_parts[0]
                port = int(ip_port_parts[1])

                if 'bpassword' in response['content']:
                    broadcast_pass = root.getAttribute('bpassword')
                if root.getAttribute('greenroom'):
                    greenroom = True
                else:
                    greenroom = False

                return {
                    'tcurl': tc_url,
                    'ip': ip,
                    'port': port,
                    'app': app,
                    'roomtype': roomtype,
                    'greenroom': greenroom,
                    'bpassword': broadcast_pass
                }
        return None
Beispiel #15
0
def get_roomconfig_xml(room, roompass=None, proxy=None):
    """
    Finds room configuration for a given room name.
    :param room: str the room name to find info for.
    :param roompass: str the password to the room. Defaults to None.
    :param proxy: str use a proxy for this request.
    :return: dict {'tcurl', 'ip', 'port', 'app', 'roomtype', 'greenroom=bool', 'bpassword'}
    """
    if roompass:
        xmlurl = 'http://apl.tinychat.com/api/find.room/%s?site=tinychat&password=%s&url=tinychat.com' % \
                 (room, roompass)
    else:
        xmlurl = 'http://apl.tinychat.com/api/find.room/%s?site=tinychat&url=tinychat.com' % room

    response = web.http_get(xmlurl, proxy=proxy)
    if response['content'] is not None:
        try:
            xml = parseString(response['content'])
        except ExpatError:
            xml = None
        if xml is not None:
            broadcast_pass = None
            root = xml.getElementsByTagName('response')[0]
            result = root.getAttribute('result')
            if result == 'PW':
                return result
            else:
                roomtype = root.getAttribute('roomtype')
                tc_url = root.getAttribute('rtmp')
                rtmp_parts = tc_url.split('/')
                app = rtmp_parts[3]
                ip_port_parts = rtmp_parts[2].split(':')
                ip = ip_port_parts[0]
                port = int(ip_port_parts[1])

                if 'bpassword' in response['content']:
                    broadcast_pass = root.getAttribute('bpassword')
                if root.getAttribute('greenroom'):
                    greenroom = True
                else:
                    greenroom = False

                return {
                    'tcurl': tc_url,
                    'ip': ip,
                    'port': port,
                    'app': app,
                    'roomtype': roomtype,
                    'greenroom': greenroom,
                    'bpassword': broadcast_pass
                }
        return None
Beispiel #16
0
def get_captcha_key(roomname, uid, proxy=None):
    """
    Find the captcha key needed before we can send messages in a room.
    :param roomname: str the room name.
    :param uid: str the ID we have in the room.
    :param proxy: str use a proxy for this request.
    :return: str the captcha key or None on captcha enabled room.
    """
    url = 'http://tinychat.com/api/captcha/check.php?room=tinychat^%s&guest_id=%s' % (roomname, uid)
    response = web.http_get(url, json=True, proxy=proxy)
    if response['json'] is not None:
        if 'key' in response['json']:
            return response['json']['key']
        else:
            return None
Beispiel #17
0
def get_cauth_cookie(roomname, proxy=None):
    """
    Find the cauth 'cookie' needed to make a successful connection.

    NOTE: This is not really a cookie, but named so after its name in the json response.
    :param roomname: str the room name.
    :param proxy: str use a proxy for this request.
    :return: str the 'cookie'
    """
    ts = int(round(time.time() * 1000))
    url = 'https://tinychat.com/cauth?room=%s&t=%s' % (roomname, ts)
    response = web.http_get(url, json=True, proxy=proxy)
    if response['json'] is not None:
        if 'cookie' in response['json']:
            return response['json']['cookie']
        return None
Beispiel #18
0
def get_captcha_key(roomname, uid, proxy=None):
    """
    Find the captcha key needed before we can send messages in a room.
    :param roomname: str the room name.
    :param uid: str the ID we have in the room.
    :param proxy: str use a proxy for this request.
    :return: str the captcha key or None on captcha enabled room.
    """
    url = 'https://tinychat.com/api/captcha/check.php?room=tinychat^%s&guest_id=%s' % (
        roomname, uid)
    response = web.http_get(url, json=True, proxy=proxy)
    if response['json'] is not None:
        if 'key' in response['json']:
            return response['json']['key']
        else:
            return None
Beispiel #19
0
def get_cauth_cookie(roomname, proxy=None):
    """
    Find the cauth 'cookie' needed to make a successful connection.

    NOTE: This is not really a cookie, but named so after its name in the json response.
    :param roomname: str the room name.
    :param proxy: str use a proxy for this request.
    :return: str the 'cookie'
    """
    ts = int(round(time.time() * 1000))
    url = 'http://tinychat.com/cauth?room=%s&t=%s' % (roomname, ts)
    response = web.http_get(url, json=True, proxy=proxy)
    if response['json'] is not None:
        if 'cookie' in response['json']:
            return response['json']['cookie']
        return None
Beispiel #20
0
def urbandictionary_search(search):
    """
    Searches urbandictionary's API for a given search term.
    :param search: The search term str to search for.
    :return: definition str or None on no match or error.
    """
    if str(search).strip():
        urban_api_url = 'http://api.urbandictionary.com/v0/define?term=%s' % search
        response = web.http_get(urban_api_url, json=True)
        if response['json'] is not None:
            try:
                definition = response['json']['list'][0]['definition']
                return definition.encode('ascii', 'ignore')
            except (KeyError, IndexError):
                return None
    else:
        return None
Beispiel #21
0
def recaptcha(proxy=None):
    """
    Check if we have to solve a captcha before we can connect.
    If yes, then it will open in the default browser.
    :param proxy: str use a proxy for this request.
    :return: dict{'cookies'} this is NOT used in the code , but are left here for debugging purpose.
    """
    t = str(random.uniform(0.9, 0.10))
    url = 'http://tinychat.com/cauth/captcha?%s' % t
    response = web.http_get(url, json=True, proxy=proxy)
    if response['json'] is not None:
        if response['json']['need_to_solve_captcha'] == 1:
            link = 'http://tinychat.com/cauth/recaptcha?token=%s' % response['json']['token']
            webbrowser.open(link, new=1)
            print (link)
            raw_input('Solve the captcha and click enter to continue.')
        return response['cookies']
Beispiel #22
0
def weather_search(city):
    """
    Searches worldweatheronline's API for weather data for a given city.
    You must have a working API key to be able to use this function.
    :param city: The city str to search for.
    :return: weather data str or None on no match or error.
    """
    if str(city).strip():
        api_key = '500d22f9d3f17b1c01d7584d19741'
        if not api_key:
            return 'Missing api key.'
        else:
            weather_api_url = 'https://api.worldweatheronline.com/free/v2/weather.ashx?' \
                              'q=%s&format=json&key=%s' % (city, api_key)

            response = web.http_get(weather_api_url, json=True)

            if response['json'] is not None:
                try:
                    weatherdesc = response['json']['data'][
                        'current_condition'][0]['weatherDesc'][0]['value']
                    winddir16point = response['json']['data'][
                        'current_condition'][0]['winddir16Point']
                    windspeedmiles = response['json']['data'][
                        'current_condition'][0]['windspeedMiles']
                    windspeedkmph = response['json']['data'][
                        'current_condition'][0]['windspeedKmph']
                    feelslikec = response['json']['data']['current_condition'][
                        0]['FeelsLikeC']
                    feelslikef = response['json']['data']['current_condition'][
                        0]['FeelsLikeF']
                    temp_c = response['json']['data']['current_condition'][0][
                        'temp_C']
                    temp_f = response['json']['data']['current_condition'][0][
                        'temp_F']
                    query = response['json']['data']['request'][0][
                        'query'].encode('ascii', 'ignore')
                    result = query + ' - ' + weatherdesc + ', ' + temp_c + 'C (' + temp_f + 'F), ' \
                                     'Feels Like: ' + feelslikec + 'C (' + feelslikef + 'F) , ' \
                                     'Wind Speed: ' + windspeedmiles + ' mph (' + windspeedkmph + ' kph), ' \
                                     'Wind Direction: ' + winddir16point
                    return result
                except (IndexError, KeyError):
                    return None
    else:
        return None
Beispiel #23
0
def youtube_search_list(search, results=10):
    """
    Searches the API of youtube for videos matching the search term.

    Instead of returning only one video matching the search term, we return a list of candidates.

    :param search: The search term str to search for.
    :param results: int determines how many results we would like on our list
    :return: list[dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'}] or None on error.
    """
    if search:
        youtube_search_url = 'https://www.googleapis.com/youtube/v3/search?type=video' \
                             '&key=%s&maxResults=50&q=%s&part=snippet' % (YOUTUBE_API_KEY, search)

        response = web.http_get(youtube_search_url, json=True)
        if response['json'] is not None:
            media_list = []
            try:
                if 'items' in response['json']:
                    i = 0
                    for item in response['json']['items']:
                        if i == results:
                            return media_list
                        else:
                            video_id = item['id']['videoId']
                            video_title = item['snippet']['title'].encode(
                                'ascii', 'ignore')

                            video_time = youtube_time(video_id)
                            if video_time is not None:
                                media_info = {
                                    'type': 'youTube',
                                    'video_id': video_id,
                                    'video_time': video_time['video_time'],
                                    'video_title': video_title
                                }
                                log.debug('Youtube item %s %s' %
                                          (i, media_info))
                                media_list.append(media_info)
                                i += 1
            except KeyError as ke:
                log.error(ke, exc_info=True)
                return None
    else:
        return None
Beispiel #24
0
def recaptcha(proxy=None):
    """
    Check if we have to solve a captcha before we can connect.
    If yes, then it will open in the default browser.
    :param proxy: str use a proxy for this request.
    :return: dict{'cookies'} this is NOT used in the code , but are left here for debugging purpose.
    """
    t = str(random.uniform(0.9, 0.10))
    url = 'http://tinychat.com/cauth/captcha?%s' % t
    response = web.http_get(url, json=True, proxy=proxy)
    if response['json'] is not None:
        if response['json']['need_to_solve_captcha'] == 1:
            link = 'http://tinychat.com/cauth/recaptcha?token=%s' % response[
                'json']['token']
            webbrowser.open(link, new=1)
            print(link)
            raw_input('Solve the captcha and click enter to continue.')
        return response['cookies']
Beispiel #25
0
def search_lastfm_by_tag(search_str, by_id=True, max_tunes=40):
    """
    Search last.fm for tunes matching the search term and turns them in to a youtube list of tracks.
    :param search_str: str the search term to search for.
    :param by_id: bool if set to True, only tunes that have a youtube id will be added(recommended)
    :param max_tunes: int the max amount of tunes to return.
    :return: list[ dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'} ] or None on error.
    """
    url = 'http://lastfm-ajax-vip1.phx1.cbsig.net/kerve/charts?nr=%s&type=track&f=tag:%s&format=json' % \
          (max_tunes, search_str)
    lastfm = web.http_get(url, json=True)
    log.debug('lastfm response %s' % lastfm)
    if lastfm['json'] is not None:
        if 'track' in lastfm['json']['results']:
            if len(lastfm['json']['results']['track']) is not 0:
                yt_tracks = []
                for track in lastfm['json']['results']['track']:
                    search_str = '%s - %s' % (track['artist'], track['name'])
                    if 'playlink' in track:
                        if 'data-youtube-id' in track['playlink']:
                            youtube_id = track['playlink']['data-youtube-id']
                            yt = youtube.youtube_time(youtube_id)
                            log.debug(yt)
                            if yt is not None:
                                yt_tracks.append(yt)
                        else:
                            if not by_id:
                                yt = youtube.youtube_search(search_str)
                                log.debug(
                                    'search by search string: %s result: %s' %
                                    (search_str, yt))
                                if yt is not None:
                                    yt_tracks.append(yt)
                    else:
                        if not by_id:
                            yt = youtube.youtube_search(search_str)
                            log.debug(
                                'search by search string: %s result: %s' %
                                (search_str, yt))
                            if yt is not None:
                                yt_tracks.append(yt)
                return yt_tracks
            return None
Beispiel #26
0
def youtube_search(search):
    """
    Searches the youtube API for a youtube video matching the search term.

    A json response of ~50 possible items matching the search term will be presented.
    Each video_id will then be checked by youtube_time() until a candidate has been found
    and the resulting dict can be returned.

    :param search: The search term str to search for.
    :return: dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'} or None on error.
    """
    if search:
        if 'list' in search:
            search = search.split('?list')[0]
        youtube_search_url = 'https://www.googleapis.com/youtube/v3/search?' \
                             'type=video&key=%s&maxResults=50&q=%s&part=snippet' % (YOUTUBE_API_KEY, search)

        response = web.http_get(youtube_search_url, json=True)

        if response['json'] is not None:
            try:
                if 'items' in response['json']:
                    for item in response['json']['items']:
                        video_id = item['id']['videoId']
                        video_title = item['snippet']['title'].encode(
                            'ascii', 'ignore')

                        video_time = youtube_time(video_id)
                        if video_time is not None:
                            return {
                                'type': 'youTube',
                                'video_id': video_id,
                                'video_time': video_time['video_time'],
                                'video_title': video_title
                            }
            except KeyError as ke:
                log.error(ke, exc_info=True)
                return None
    else:
        return None
def soundcloud_track_info(track_id):
    if track_id:
        info_url = 'http://api.soundcloud.com/tracks/%s?client_id=%s' % (
            track_id, SOUNDCLOUD_API_KEY)
        response = web.http_get(info_url, json=True)

        if response['json'] is not None:
            try:
                user_id = response['json'][0]['user_id']
                track_time = response['json'][0]['duration']
                track_title = response['json'][0]['title'].encode(
                    'ascii', 'ignore')
                return {
                    'type': 'soundCloud',
                    'video_id': track_id,
                    'video_time': track_time,
                    'video_title': track_title,
                    'user_id': user_id
                }
            except (IndexError, KeyError):
                return None
        return None
Beispiel #28
0
def time_is(location):
    """
    Retrieves the time in a location by parsing the time element in the html from Time.is .
    :param location: str location of the place you want to find time (works for small towns as well).
    :return: time str or None on failure.
    """
    if BeautifulSoup:
        header = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/51.0.2704.106 Safari/537.36',
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language':
            'en-GB,en;q=0.5',
            'Accept-Encoding':
            'gzip, deflate',
            'Connection':
            'keep-alive',
            'Referrer':
            'http://time.is/',
        }

        post_url = 'http://time.is/' + str(location)
        time_data = web.http_get(post_url, header=header)
        time_html = time_data['content']
        soup = BeautifulSoup(time_html, "html.parser")

        time = ''
        try:
            for hit in soup.findAll(attrs={'id': 'twd'}):
                time = hit.contents[0].strip()
        except KeyError:
            pass

        return time
    else:
        return None
Beispiel #29
0
def get_lastfm_chart(chart_items=5):
    """
    Finds the currently most played tunes on last.fm and turns them in to a youtube list of tracks.
    :param chart_items: int the amount of tracks we want.
    :return: list[ dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'} ] or None on error.
    """
    url = 'http://lastfm-ajax-vip1.phx1.cbsig.net/kerve/charts?nr=%s&type=track&format=json' % chart_items
    lastfm = web.http_get(url, json=True)
    log.debug('lastfm response %s' % lastfm)
    if lastfm['json'] is not None:
        if 'results' in lastfm['json']:
            if 'track' in lastfm['json']['results']:
                if len(lastfm['json']['results']['track']) is not 0:
                    yt_tracks = []
                    for track in lastfm['json']['results']['track']:
                        search_str = '%s - %s' % (track['artist'],
                                                  track['name'])
                        yt = youtube.youtube_search(search_str)
                        log.info(yt)
                        if yt is not None:
                            yt_tracks.append(yt)
                    return yt_tracks
                return None
Beispiel #30
0
def youtube_time(video_id, check=True):
    """
    Youtube helper function to get the video time for a given video id.

    Checks a youtube video id to see if the video is blocked or allowed in the following countries:
    USA, DENMARK and POLAND. If a video is blocked in one of the countries, None is returned.
    If a video is NOT allowed in ONE of the countries, None is returned else the video time will be returned.

    :param check: bool True = checks region restriction. False = no check will be done
    :param video_id: The youtube video id str to check.
    :return: dict{'type=youTube', 'video_id', 'video_time', 'video_title'} or None
    """
    youtube_details_url = 'https://www.googleapis.com/youtube/v3/videos?' \
                          'id=%s&key=%s&part=contentDetails,snippet' % (video_id, YOUTUBE_API_KEY)

    response = web.http_get(youtube_details_url, json=True)

    if response['json'] is not None:
        try:
            if 'items' in response['json']:
                if len(response['json']['items']) is not 0:
                    contentdetails = response['json']['items'][0][
                        'contentDetails']
                    if check:
                        if 'regionRestriction' in contentdetails:
                            if 'blocked' in contentdetails[
                                    'regionRestriction']:
                                if ('US' or 'DK' or 'PL'
                                        or 'DE') in contentdetails[
                                            'regionRestriction']['blocked']:
                                    log.info(
                                        '%s is blocked in: %s' %
                                        (video_id,
                                         contentdetails['regionRestriction']
                                         ['blocked']))
                                    return None
                            if 'allowed' in contentdetails[
                                    'regionRestriction']:
                                if ('US' or 'DK' or 'PL'
                                        or 'DE') not in contentdetails[
                                            'regionRestriction']['allowed']:
                                    log.info(
                                        '%s is allowed in: %s' %
                                        (video_id,
                                         contentdetails['regionRestriction']
                                         ['allowed']))
                                    return None
                    video_time = string_utili.convert_to_millisecond(
                        contentdetails['duration'])
                    video_title = response['json']['items'][0]['snippet'][
                        'title'].encode('ascii', 'ignore')

                    return {
                        'type': 'youTube',
                        'video_id': video_id,
                        'video_time': video_time,
                        'video_title': video_title
                    }
                return None
        except KeyError as ke:
            log.error(ke, exc_info=True)
            return None