def add_subscription_local(youtube_auth, channel_id, by_username=False):
    """
    Add a YouTube subscription (Local/DB).
    :param by_username:
    :param youtube_auth:
    :param channel_id:
    :return:
    """
    # FIXME: Somewhat duplicate code of get_remote_subscriptions, move to own function -- START
    # Get ID of uploads playlist
    # channel_uploads_playlist_id = get_channel_uploads_playlist_id(youtube_auth, channel_id)
    if by_username:
        channel_response = get_channel_by_username(youtube_auth, channel_id)
    else:
        channel_response = get_channel_by_id(youtube_auth, channel_id)
    channel_uploads_playlist_id = channel_response['contentDetails'][
        'relatedPlaylists']['uploads']
    channel = Channel(channel_response,
                      channel_uploads_playlist_id,
                      channel_list_response=True)
    db_channel = engine_execute_first(get_channel_by_id_stmt(channel))
    if db_channel:
        engine_execute(update_channel_from_remote(channel))
    else:
        # TODO: change to sqlalchemy core stmt
        create_logger(__name__ + ".subscriptions").info(
            "Added channel {} - {}".format(channel.title, channel.id))
        db_session.add(channel)

    db_session.commit()
    # FIXME: Somewhat duplicate code of get_remote_subscriptions, move to own function -- END

    logger.info("Added subscription (Local/DB): {} / {}".format(
        channel_id, channel.title))
def add_subscription_remote(channel_id):
    """
    Add a YouTube subscription (On YouTube).

    DEPRECATED: Google doesn't let you, see supported op table https://developers.google.com/youtube/v3/getting-started
    :param youtube_oauth:
    :param channel_id:
    :return: returns response or raises exception
    """
    youtube_oauth = load_youtube()
    response = youtube_oauth.subscriptions().insert(
        part='snippet',
        body=dict(snippet=dict(resourceId=dict(channelId=channel_id))))
    try:
        response.execute()
    except HttpError as exc_http:
        _msg = "Failed adding subscription to '{}', HTTP Error {}".format(
            channel_id, exc_http.resp.status)
        logger.error("{}: {}".format(_msg, exc_http.content),
                     exc_info=exc_http)
        raise exc_http

    except Exception as exc:
        _msg = "Unhandled exception occurred when adding subscription to '{}'".format(
            channel_id)
        logger.critical("{} | response={}".format(_msg, response.__dict__),
                        exc_info=exc)
        raise exc

    # FIXME: Somewhat duplicate code of get_remote_subscriptions, move to own function -- START
    # Get ID of uploads playlist
    channel_uploads_playlist_id = response['items'][0]['contentDetails'][
        'relatedPlaylists']['uploads']
    channel = Channel(channel_id, channel_uploads_playlist_id)
    db_channel = engine_execute_first(get_channel_by_id_stmt(channel))
    if db_channel:
        engine_execute(update_channel_from_remote(channel))
        # subs.append(channel)
    else:
        # TODO: change to sqlalchemy core stmt
        create_logger(__name__ + ".subscriptions").info(
            "Added channel {} - {}".format(channel.title, channel.id))
        db_session.add(channel)
        # subs.append(channel)

    db_session.commit()
    # FIXME: Somewhat duplicate code of get_remote_subscriptions, move to own function -- END

    logger.info("Added subscription: {} / {}".format(
        channel_id, response['snippet']['title']))
    return response
def get_remote_subscriptions(youtube_oauth):
    """
    Get a list of the authenticated user's subscriptions.
    :param youtube_oauth:
    :param stats:
    :param info: debug lite
    :param debug:
    :param traverse_pages:
    :return: [total, subs, statistics]
    """
    subscription_list_request = youtube_oauth.subscriptions().list(
        part='snippet', mine=True, maxResults=50)
    subs = []
    # Retrieve the list of subscribed channels for authenticated user's channel.
    update_stmts = []
    channel_ids = []
    while subscription_list_request:
        subscription_list_response = subscription_list_request.execute()

        # Grab information about each subscription page
        for page in tqdm(subscription_list_response['items'],
                         desc="Adding and updating channels by page",
                         disable=read_config('Debug', 'disable_tqdm')):
            # Get channel
            channel_response = channels_list(
                youtube_oauth,
                part='contentDetails',
                id=page['snippet']['resourceId']['channelId'])

            # Get ID of uploads playlist
            channel_uploads_playlist_id = channel_response['items'][0][
                'contentDetails']['relatedPlaylists']['uploads']
            channel = Channel(page['snippet'], channel_uploads_playlist_id)
            db_channel = engine_execute_first(get_channel_by_id_stmt(channel))
            if db_channel:
                engine_execute(update_channel_from_remote(channel))
                subs.append(channel)
            else:
                # TODO: change to sqlalchemy core stmt
                create_logger(__name__ + ".subscriptions").info(
                    "Added channel {} - {}".format(channel.title, channel.id))
                db_session.add(channel)
                subs.append(channel)
            channel_ids.append(channel.id)
        subscription_list_request = youtube_oauth.playlistItems().list_next(
            subscription_list_request, subscription_list_response)
    delete_sub_not_in_list(channel_ids)
    db_session.commit()
    return subs
Beispiel #4
0
def get_remote_subscriptions(youtube_oauth):
    """
    Get a list of the authenticated user's subscriptions.
    :param youtube_oauth:
    :return: [subs]
    """
    if youtube_oauth is None:
        logger.critical("YouTube API OAuth object was NoneType, aborting!")
        return None
    subscription_list_request = youtube_oauth.subscriptions().list(part='snippet', mine=True,
                                                                   maxResults=50)
    subs = []
    # Retrieve the list of subscribed channels for authenticated user's channel.
    channel_ids = []
    while subscription_list_request:
        subscription_list_response = subscription_list_request.execute()

        # Grab information about each subscription page
        for page in subscription_list_response['items']:
            # Get channel
            channel_response = channels_list(youtube_oauth, part='contentDetails',
                                             id=page['snippet']['resourceId']['channelId'])

            # Get ID of uploads playlist
            channel_uploads_playlist_id = channel_response['items'][0]['contentDetails']['relatedPlaylists']['uploads']
            channel = Channel(page['snippet'], channel_uploads_playlist_id)
            db_channel = engine_execute_first(get_channel_by_id_stmt(channel))
            if db_channel:
                engine_execute(update_channel_from_remote(channel))
                subs.append(channel)
            else:
                # TODO: change to sqlalchemy core stmt
                create_logger(__name__ + ".subscriptions").info(
                    "Added channel {} - {}".format(channel.title, channel.id))
                db_session.add(channel)
                subs.append(channel)
            channel_ids.append(channel.id)
        subscription_list_request = youtube_oauth.playlistItems().list_next(
            subscription_list_request, subscription_list_response)
    delete_sub_not_in_list(channel_ids)
    db_session.commit()
    return subs
Beispiel #5
0
def run():
    video_item = {
        'kind': 'youtube#searchResult',
        'etag': '"XI7nbFXulYBIpL0ayR_gDh3eu1k/rrGI6j0VT4vX91p6eQyuqFQjf8M"',
        'id': {
            'kind': 'youtube#video',
            'videoId': '8NG1PEFceG0'
        },
        'snippet': {
            'publishedAt': '2017-06-22T19:26:41.000Z',
            'channelId': 'UCzORJV8l3FWY4cFO8ot-F2w',
            'title':
            '[Vinesauce] Vinny - The Legend of Zelda: Clips of the Wild',
            'description':
            'A compilation of user-created Twitch clips from Breath of the Wild! Streamed live on Vinesauce. Check out my other youtube channel for full streams.',
            'thumbnails': {
                'default': {
                    'url': 'https://i.ytimg.com/vi/8NG1PEFceG0/default.jpg',
                    'width': 120,
                    'height': 90
                },
                'medium': {
                    'url': 'https://i.ytimg.com/vi/8NG1PEFceG0/mqdefault.jpg',
                    'width': 320,
                    'height': 180
                },
                'high': {
                    'url': 'https://i.ytimg.com/vi/8NG1PEFceG0/hqdefault.jpg',
                    'width': 480,
                    'height': 360
                }
            },
            'channelTitle': 'vinesauce',
            'liveBroadcastContent': 'none'
        }
    }

    channel_item = {
        "publishedAt": "2015-01-09T12:46:03.000Z",
        "title": "OfficialNerdCubed",
        "description":
        "Recommending good games every Monday and Wednesday. Going strange every Saturday.",
        "resourceId": {
            "kind": "youtube#channel",
            "channelId": "UCKab3hYnOoTZZbEUQBMx-ww"
        },
        "channelId": "UCv5TbAM7zHQOoDr0fw2Cy8w",
        "thumbnails": {
            "default": {
                "url":
                "https://yt3.ggpht.com/-2AuBRBi8yE8/AAAAAAAAAAI/AAAAAAAAAAA/PsaY8p1aJ2U/s88-c-k-no-mo-rj-c0xffffff/photo.jpg"
            },
            "medium": {
                "url":
                "https://yt3.ggpht.com/-2AuBRBi8yE8/AAAAAAAAAAI/AAAAAAAAAAA/PsaY8p1aJ2U/s240-c-k-no-mo-rj-c0xffffff/photo.jpg"
            },
            "high": {
                "url":
                "https://yt3.ggpht.com/-2AuBRBi8yE8/AAAAAAAAAAI/AAAAAAAAAAA/PsaY8p1aJ2U/s800-c-k-no-mo-rj-c0xffffff/photo.jpg"
            }
        }
    }

    channel = Channel(channel_item, 'UUv5TbAM7zHQOoDr0fw2Cy8w')
    video = Video(video_item)
    insrt_txt = {
        "video_id": video.video_id,
        "channel_title": video.channel_title,
        'title': video.title,
        "date_published": video.date_published,
        "description": video.description,
        "thumbnail_path": video.thumbnail_path,
        "playlist_pos": video.playlist_pos,
        "url_video": video.url_video,
        "url_playlist_video": video.url_playlist_video,
        "thumbnails": video.thumbnails,
        "downloaded": video.downloaded,
        "search_item": video.search_item
    }
    # stmt_1 = Video.__table__.insert(), [insrt_txt]
    # engine.execute(Video.__table__.insert(), [insrt_txt])
    # stmt = update_statement_full(video)
    # stmt = get_video_by_id_stmt(video)
    # # stmt = Video.__table__.select('video.video_id').where(text("video_id = '{}'".format(video.video_id)))
    # # print(db_session.execute(stmt).first())
    # print(engine.execute(stmt).first())
    # video2 = engine.execute(Video.__table__.select(Video.title).where('video_id' == video.video_id).limit(1))
    stmt = get_channel_by_id_stmt(channel)
    print(engine.execute(stmt).first())