コード例 #1
0
def deletePhoto(photo_info):
	result = {}
	graph = facebook.GraphAPI(access_token=__facebook_page_token, version='2.5')
	facebook_response = graph.update_photo(
		facebook_post_id=photo_info['facebook_post_id'],
		message= getFacebookPostContent(None, isValid=False, photo_info=photo_info)
	)

	flickr_api.set_keys(api_key = __flickr_api_key, api_secret = __flickr_api_secret)
	flickr_api.set_auth_handler('oauth_verifier.txt')
	uni_title = u'[無效] '+ photo_info['title']
	uni_title = uni_title.encode('utf-8')
	uni_description = u'[這張照片已經被投稿者移除,它的票數不會列入計分]\n\n'+ photo_info['content']
	uni_description = uni_description.encode('utf-8')

	flick_response = flickr_api.objects.Photo(
        id=photo_info['flickr_photo_id'],
        editurl='https://www.flickr.com/photos/upload/edit/?ids=' + photo_info['flickr_photo_id']
    ).setMeta(
    	title=uni_title,
		description=uni_description,
	)

	result['facebook_response'] = facebook_response
	result['flick_response'] = flick_response
	#photo.image.delete()
	print 'deletePhoto result:'+str(result)
	return result
コード例 #2
0
    def _authenticate(self):
        if self._is_authenticated:
            return

        try:
            flickr_api.set_keys(api_key=self._config.flickr_api_key, api_secret=self._config.flickr_api_secret)
            tokens = self._config.load_tokens(self._config.PATH_FLICKR)
            if tokens:
                auth_handler = flickr_api.auth.AuthHandler.fromdict(tokens)

            else:
                print("logging in...")
                auth_handler = flickr_api.auth.AuthHandler()
                can_delete = choice("request permission to delete files?", "no")
                permissions_requested = OAUTH_PERMISSIONS_DELETE if can_delete else OAUTH_PERMISSIONS_WRITE
                url = auth_handler.get_authorization_url(permissions_requested)
                webbrowser.open(url)
                print("Please enter the OAuth verifier tag once logged in:")
                verifier_code = input("> ")
                auth_handler.set_verifier(verifier_code)
                self._config.save_tokens(self._config.PATH_FLICKR, auth_handler.todict())

            flickr_api.set_auth_handler(auth_handler)
            self._user = flickr_api.test.login()
            self._is_authenticated = True

        except Exception as err:    #pylint: disable=broad-except
            logger.error(
                "Unable to authenticate with Flickr\n"
                f"{err}\n"
                "Use -v / --verbose to list the ensure the correct settings are being used\n"
                "Go to http://www.flickr.com/services/apps/create/apply to apply for a Flickr API key")
            exit(1)
コード例 #3
0
def HandleOauthRequestResponse(cookie):
    oauth_verifier = parsed['oauth_verifier'][0]

    import flickr_api as f
    f.disable_cache()
    a = f.auth.AuthHandler.fromdict({
        'api_key':
        keys.kAPI_KEY,
        'api_secret':
        keys.kAPI_SECRET,
        'request_token_key':
        cookie["request_token_key"].value,
        'request_token_secret':
        cookie["request_token_secret"].value,
    })
    try:
        a.set_verifier(oauth_verifier)
        f.set_auth_handler(a)
    except urllib2.HTTPError as e:
        return HandleNotLoggedIn(cookie)

    # Should be able to login now.
    user = utils.AutoRetry(f.test.login)

    # Add details to MySQL.
    token_id = database.AddToDatabase(user.id, a.access_token.key,
                                      a.access_token.secret)

    # Store userId in a cookie so we can attempt to avoid logging in next time.
    cookie["user_id"] = user.id
    cookie["token_id"] = token_id
    print cookie.output()

    # Can just display page now.
    HandlePage(user, token_id)
コード例 #4
0
def deletePhoto(photo_info):
    result = {}
    graph = facebook.GraphAPI(access_token=__facebook_page_token,
                              version='2.5')
    facebook_response = graph.update_photo(
        facebook_post_id=photo_info['facebook_post_id'],
        message=getFacebookPostContent(None,
                                       isValid=False,
                                       photo_info=photo_info))

    flickr_api.set_keys(api_key=__flickr_api_key,
                        api_secret=__flickr_api_secret)
    flickr_api.set_auth_handler('oauth_verifier.txt')
    uni_title = u'[無效] ' + photo_info['title']
    uni_title = uni_title.encode('utf-8')
    uni_description = u'[這張照片已經被投稿者移除,它的票數不會列入計分]\n\n' + photo_info['content']
    uni_description = uni_description.encode('utf-8')

    flick_response = flickr_api.objects.Photo(
        id=photo_info['flickr_photo_id'],
        editurl='https://www.flickr.com/photos/upload/edit/?ids=' +
        photo_info['flickr_photo_id']).setMeta(
            title=uni_title,
            description=uni_description,
        )

    result['facebook_response'] = facebook_response
    result['flick_response'] = flick_response
    #photo.image.delete()
    print 'deletePhoto result:' + str(result)
    return result
コード例 #5
0
def flickr_authenticate():

	## Load authentication handler

	AUTH_HANDLER_FILENAME = 'auth_handler'

	flickr_api.set_auth_handler(AUTH_HANDLER_FILENAME)
コード例 #6
0
def _init(key, secret, oauth):
    """
    Initialize API.

    @see: http://www.flickr.com/services/api/

    @param key: str, API key
    @param secret: str, API secret
    """
    Flickr.set_keys(key, secret)
    if not oauth:
        return True

    if os.path.exists(os.path.expanduser(OAUTH_TOKEN_FILE)):
        Flickr.set_auth_handler(os.path.expanduser(OAUTH_TOKEN_FILE))
        return True

    # Get new OAuth credentials
    auth = Flickr.auth.AuthHandler()  # creates the AuthHandler object
    perms = "read"  # set the required permissions
    url = auth.get_authorization_url(perms)
    print
    print("\nEnter the following url in a browser to authorize the application:")
    print(url)
    print("Copy and paste the <oauth_verifier> value from XML here and press return:")
    Flickr.set_auth_handler(auth)
    token = raw_input()
    auth.set_verifier(token)
    auth.save(os.path.expanduser(OAUTH_TOKEN_FILE))
    print("OAuth token was saved, re-run script to use it.")
    return False
コード例 #7
0
def _init(key, secret, oauth):
    """
    Initialize API.

    @see: http://www.flickr.com/services/api/

    @param key: str, API key
    @param secret: str, API secret
    """
    Flickr.set_keys(key, secret)
    
    if oauth:
    	if os.path.exists(os.path.expanduser(TOKEN_FILE)):
            Flickr.set_auth_handler(os.path.expanduser(TOKEN_FILE))
        else:
            a = Flickr.auth.AuthHandler() #creates the AuthHandler object
            perms = "read" # set the required permissions
            url = a.get_authorization_url(perms)
            print
            print "Enter following url to the browser to authorize application"
            print url
            print "Copy paste <oauth_verifier> value from xml and press return"
            Flickr.set_auth_handler(a)
            token = raw_input()
            a.set_verifier(token)
            a.save(os.path.expanduser(TOKEN_FILE))
コード例 #8
0
    def _authenticate(self):
        if self._is_authenticated:
            return

        flickr_api.set_keys(api_key=self._config.api_key,
                            api_secret=self._config.api_secret)

        token_path = self._config.locate_datafile(TOKEN_FILENAME)
        if token_path:
            auth_handler = flickr_api.auth.AuthHandler.load(token_path)

        else:
            token_path = self._config.default_datafile(TOKEN_FILENAME)
            auth_handler = flickr_api.auth.AuthHandler()
            permissions_requested = OAUTH_PERMISSIONS
            url = auth_handler.get_authorization_url(permissions_requested)
            webbrowser.open(url)
            print("Please enter the OAuth verifier tag once logged in:")
            verifier_code = raw_input("> ")
            auth_handler.set_verifier(verifier_code)
            auth_handler.save(token_path)

        try:
            flickr_api.set_auth_handler(auth_handler)
            self._user = flickr_api.test.login()
            self._is_authenticated = True

        except flickr_api.flickrerrors.FlickrError as e:
            print(e.message)
            if e.message == 'The Flickr API keys have not been set':
                print(
                    "Go to http://www.flickr.com/services/apps/create/apply and apply for an API key"
                )
            sys.exit(1)
コード例 #9
0
ファイル: socialApplication.py プロジェクト: EelaiWind/NTHUFC
def getPhotoDetails(photo, user_access_token):
	'''
		取得某張照片的facebook讚數、評論跟內容,和flickr的收藏數
		如果使用者有登入的話,確認使用者是否有按過讚了
	'''
	__facebook_query_field = 'likes.summary(true), comments{from{name, picture{url}}, message}'
	response = fb_fanpage_graph.get_object(id=photo.facebook_post_id, fields=__facebook_query_field)
	comment_list = []

	if 'comments' in response:
		for item in response['comments']['data']:
			comment_list.append(
				Comment(
					user_name=item['from']['name'],
					user_photo_url=item['from']['picture']['data']['url'],
					comment_text=item['message'],
					comment_facebook_id=item['id'],
				)
			)
	facebook_likes = response['likes']['summary']['total_count']

	flickr_api.set_keys(api_key = __flickr_api_key, api_secret = __flickr_api_secret)
	flickr_api.set_auth_handler('oauth_verifier.txt')
	favorites = flickr_api.Photo(id = photo.flickr_photo_id).getFavorites()

	return {
		'facebook_likes': facebook_likes,
		'facebook_post_id': photo.facebook_post_id,
		'comment_list': [ x.toDict() for x in comment_list],
		'flickr_favorites': len(favorites),
		'photo_url': photo.flickr_photo_url,
		'photo_content': getFacebookPostContent(photo),
		'user_has_like': getHasLiked(photo.facebook_post_id,user_access_token),
	}
コード例 #10
0
ファイル: views.py プロジェクト: anujacharya1/HashVoice
def callback2(request):
    oauth_verifier = request.GET['oauth_verifier']
    a = request.session.get('a', False)
    a.set_verifier(oauth_verifier)
    fi.set_auth_handler(a)
    a.save(Const.cFILENAME)
    to_json = {Const.cANUJSVIC : '200'}
    return HttpResponse(json.dumps(to_json), mimetype='application/json')
コード例 #11
0
ファイル: socialApplication.py プロジェクト: EelaiWind/NTHUFC
def changeFlickrFavorite(access_token_key, access_token_secret,flickr_photo_id , method = 'ADD'):
	flickr_api.set_keys(api_key = __flickr_api_key, api_secret = __flickr_api_secret)
	a = flickr_api.auth.AuthHandler(access_token_key=access_token_key , access_token_secret=access_token_secret)
	flickr_api.set_auth_handler(a)
	photo = flickr_api.Photo(id=flickr_photo_id)
	if method == 'DELETE':
		return photo.removeFromFavorites()
	else:
		return photo.addToFavorites()
コード例 #12
0
def authflickr():
    a = flickr.auth.AuthHandler()
    perms = "delete"
    url = a.get_authorization_url(perms)
    print("Open this Link in a web browser -->", url)
    oauth_verifier = input("Copy & Past tag &oauth_verifier : ")
    a.set_verifier(oauth_verifier)
    flickr.set_auth_handler(a)
    a.save('.auth')
コード例 #13
0
ファイル: main.py プロジェクト: rschiang/flickr-agent
def load_settings():
    with open('settings.json', 'r') as f:
        settings = json.load(f)
    if 'api_key' in settings:
        flickr.set_keys(api_key=str(settings['api_key']), api_secret=str(settings['api_secret']))
    if 'token_key' in settings:
        handler = flickr.auth.AuthHandler.create(str(settings['token_key']), str(settings['token_secret']))
        flickr.set_auth_handler(handler)
    return settings
コード例 #14
0
ファイル: views.py プロジェクト: anujacharya1/HashVoice
def user(request):
    
    fi.set_auth_handler(Const.cFILENAME)
    user = fi.test.login()
    result = User.objects.get_or_create_user(user.id, user.username)
    user_obj_db = result[Const.cMODEL]
    to_json = {Const.cSTATUS : '200',
               Const.cUSERNAME : user_obj_db.username}
    return HttpResponse(json.dumps(to_json), mimetype='application/json')  
コード例 #15
0
ファイル: main.py プロジェクト: rschiang/flickr-agent
def load_settings():
    with open('settings.json', 'r') as f:
        settings = json.load(f)
    if 'api_key' in settings:
        flickr.set_keys(api_key=str(settings['api_key']),
                        api_secret=str(settings['api_secret']))
    if 'token_key' in settings:
        handler = flickr.auth.AuthHandler.create(str(settings['token_key']),
                                                 str(settings['token_secret']))
        flickr.set_auth_handler(handler)
    return settings
コード例 #16
0
ファイル: eyefiserver.py プロジェクト: optiz0r/eyefi-drive
def runEyeFi():
    configfile = 'eyefiserver.conf'
    eyeFiLogger.info("Reading config " + configfile)

    config = ConfigParser.SafeConfigParser(defaults=DEFAULTS)
    config.read(configfile)

    # check whether flickr needs to be set up
    if config.getint('EyeFiServer', 'flickr_enable') > 0:
        if len(config.get('EyeFiServer', 'flickr_key')) and len(
                config.get('EyeFiServer', 'flickr_secret')):
            eyeFiLogger.info('Flickr uploading enabled')
            import flickr_api
            flickr_api.set_keys(config.get('EyeFiServer', 'flickr_key'),
                                config.get('EyeFiServer', 'flickr_secret'))
            flickr_api.is_public = int(
                config.get('EyeFiServer', 'flickr_public'))
            flickr_api.is_family = int(
                config.get('EyeFiServer', 'flickr_family'))
            flickr_api.is_friend = int(
                config.get('EyeFiServer', 'flickr_friend'))

            try:
                a = flickr_api.auth.AuthHandler.load('./flickr.verifier')
                flickr_api.set_auth_handler(a)
                eyeFiLogger.info('loaded Flickr credentials')
            except:
                a = flickr_api.auth.AuthHandler()
                url = a.get_authorization_url('write')
                print 'Please visit this URL and grant access:'
                print url
                a.set_verifier(
                    raw_input('Enter the value of <oauth_verifier>: '))
                a.save('/tmp/src/flickr.verifier')
                print 'Thanks! This process will now exit. You should then rebuild the Docker image according to the README instructions.'
                sys.exit(0)
        else:
            eyeFiLogger.error(
                'Flickr upload enabled, but flickr_key/flickr_secret not set. Exiting...'
            )
            sys.exit(1)
    else:
        flickr_api = None

    server_address = (config.get('EyeFiServer', 'host_name'),
                      config.getint('EyeFiServer', 'host_port'))

    # Create an instance of an HTTP server. Requests will be handled
    # by the class EyeFiRequestHandler
    eyeFiServer = EyeFiServer(config, server_address,
                              EyeFiRequestHandlerFactory(config, flickr_api))
    eyeFiLogger.info("Eye-Fi server started listening on port " +
                     str(server_address[1]))
    eyeFiServer.serve_forever()
コード例 #17
0
ファイル: auth.py プロジェクト: shadowfax-chc/pycsync
def setup_auth_handler(rootdir):
    '''
    Set up the auth handler using the authfile in ``rootdir``

    rootdir
        The root directory to sync.
    '''
    set_api_keys()
    authfile = pjoin(rootdir, '.pycsync')
    fapi.set_auth_handler(authfile)
    return True
コード例 #18
0
ファイル: flickr.py プロジェクト: jessiemtnbear/commons
def authenticate():
    a = flickr_api.auth.AuthHandler()
    perms = 'write'
    url = a.get_authorization_url(perms)
    print url
    verification_code = raw_input("Enter verification code: ")
    a.set_verifier(verification_code)
    flickr_api.set_auth_handler(a)
    a.save('auth_file')
    print "Authenticated!"
    return True
コード例 #19
0
 def __init__(self):
     if not os.path.exists(self.filename):
         a = flickr_api.auth.AuthHandler()
         perms = "read"
         url = a.get_authorization_url(perms)
         print(f"Go to {url}")
         verifier_code = input("Please input the verifier code : ")
         a.set_verifier(verifier_code)
         a.save(self.filename)
         flickr_api.set_auth_handler(a)
     else:
         flickr_api.set_auth_handler(self.filename)
コード例 #20
0
def flickr_auth():
    if os.path.exists('./.auth'):
        flickr.set_auth_handler(".auth")
    else:
        a = flickr.auth.AuthHandler()
        perms = "write"
        url = a.get_authorization_url(perms)
        print("Open this in a web browser -> ", url)
        oauth_verifier = input("Copy the oauth_verifier tag > ")
        a.set_verifier(oauth_verifier)
        flickr.set_auth_handler(a)
        a.save('.auth')
コード例 #21
0
ファイル: socialApplication.py プロジェクト: EelaiWind/NTHUFC
def getVotes(photo):
	flickr_api.set_keys(api_key = __flickr_api_key, api_secret = __flickr_api_secret)
	flickr_api.set_auth_handler('oauth_verifier.txt')
	favorites = flickr_api.Photo(id = photo.flickr_photo_id).getFavorites()

	response = fb_fanpage_graph.get_object(id=photo.facebook_post_id, fields='likes.summary(true)')
	likes =  response['likes']['summary']['total_count']
	photo.favorites = len(favorites)
	photo.likes = likes
	photo.votes = photo.likes + photo.favorites
	photo.last_modified_time = timezone.now()
	photo.save(update_fields=['favorites','likes','votes','last_modified_time'])
	return photo.favorites+photo.likes
コード例 #22
0
ファイル: qclickr.py プロジェクト: qcl/QCLickr
def initAPI(auth_filename):
    a = flickr_api.auth.AuthHandler.load(auth_filename)
    flickr_api.set_auth_handler(a)
    user = flickr_api.test.login()
    print 'Hi,',user.username
    print 'Building photo sets...'
    w = flickr_api.Walker(user.getPhotosets)
    #photosets = user.getPhotosets()
    #print photosets.info
    for photoset in w:
        #print photoset.title
        photosetDict[photoset.title] = photoset
    return user
コード例 #23
0
ファイル: api_helper.py プロジェクト: azzaxp/yahoo_face
def Oauth(key_file = '', verifier_file = 'flickr.verifier') :   
    API_KEY = '0b9ca8fca8041e791d684c0b88fe5708'
    API_SECRET = '4WlmUalSo3_SLScJyBaaJvgMCWjK3-WR'

    flickr_key = '31573003eefcabb832334323de5027a0'
    flickr_secret = 'f66472f76f1992ee'

    flickr_api.set_keys(api_key = flickr_key, api_secret = flickr_secret)

    a = flickr_api.auth.AuthHandler.load(verifier_file)
    flickr_api.set_auth_handler(a)
    face_api = API(API_KEY, API_SECRET)
    return face_api
コード例 #24
0
ファイル: handlers.py プロジェクト: tsinin/FlickrBot
def handle_upload(message):
    if USERS.get(hash(message.chat.id)) is None:
        try:
            flickr_api.set_auth_handler(
                "./users_data/{}/auth_token.dat".format(hash(message.chat.id)))
            USERS[hash(message.chat.id)] = flickr_api.test.login()
        except Exception:
            BOT.send_message(
                message.chat.id,
                "You're not authorized! Do it through /auth command")
            return
    BOT.send_message(message.chat.id, "Send me your photo.")
    BOT.register_next_step_handler(message, handle_upload_photo)
コード例 #25
0
 def add_flickr(self):
     today_string = date.today().strftime("%m/%d/%Y")
     today = int(
         time.mktime(
             datetime.datetime.strptime(today_string,
                                        "%m/%d/%Y").timetuple()))
     flickr_api.set_keys(api_key=FLICKR_API_KEY,
                         api_secret=FLICKR_API_SECRET)
     a = flickr_api.auth.AuthHandler.load('flickr_auth')
     flickr_api.set_auth_handler(a)
     user = flickr_api.test.login()
     meals = user.getPhotos(min_taken_date=today)
     return {"meals": meals}
コード例 #26
0
def photos(user):
    try:
        flickr_api.set_auth_handler(session['oauth_token'])
        flickr_api.set_keys(**secrets)
        if re.match("^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", user):
            person = flickr_api.Person.findByEmail(user)
        else:
            person = flickr_api.Person.findByUserName(user)
        photos, resp = person.getPhotos()
    except FlickrError, e:
        raise
        flash("You need to be logged in, redirecting", "error")
        return redirect(url_for('login'))
コード例 #27
0
ファイル: dupes.py プロジェクト: guyburton/FlickrDeduplicator
def initFlickrApi():
    config = configparser.ConfigParser()
    config.read('config.ini')

    print("Authenticating with Flickr")
    if 'FLICKR' not in config or 'API_KEY' not in config['FLICKR']:
        raise Exception(
            'You need to set your API key in config.ini (see config.ini.example)'
        )

    flickr_api.set_keys(api_key=config['FLICKR']['API_KEY'],
                        api_secret=config['FLICKR']['API_SECRET'])
    flickr_api.set_auth_handler('auth.txt')
コード例 #28
0
def Oauth(key_file='', verifier_file='flickr.verifier'):
    API_KEY = '0b9ca8fca8041e791d684c0b88fe5708'
    API_SECRET = '4WlmUalSo3_SLScJyBaaJvgMCWjK3-WR'

    flickr_key = '31573003eefcabb832334323de5027a0'
    flickr_secret = 'f66472f76f1992ee'

    flickr_api.set_keys(api_key=flickr_key, api_secret=flickr_secret)

    a = flickr_api.auth.AuthHandler.load(verifier_file)
    flickr_api.set_auth_handler(a)
    face_api = API(API_KEY, API_SECRET)
    return face_api
コード例 #29
0
ファイル: test_upload.py プロジェクト: ronost/py_flickr_sync
def main():
    parser = argparse.ArgumentParser(description='''Upload one file to a user.''')
    parser.add_argument('-f', '--filepath', help='Path to file.', required=True)

    args = parser.parse_args()

    if args.filepath:
        file_path = args.filepath
        auth_file_name = '.flickr_auth'
        home_dir = os.path.expanduser('~')
        auth_file = os.path.join(home_dir, auth_file_name)
        f.set_auth_handler(auth_file)
        f.upload(photo_file = file_path, title='Cake!!')
コード例 #30
0
def uploadUsingThread(photo):
    photo_file_path = photo.image.path
    result = {}

    if photo.flickr_photo_id == '':
        try_count = 3
        flickr_api.set_keys(api_key=__flickr_api_key,
                            api_secret=__flickr_api_secret)
        flickr_api.set_auth_handler('oauth_verifier.txt')

        while try_count > 0:
            try:
                flickr_response = flickr_api.upload(
                    photo_file=photo_file_path,
                    title=photo.title,
                    description=u'地點: ' + photo.location_marker.title +
                    u'\n拍攝者: ' + photo.owner.nickname + '\n\n' + photo.content,
                    tags=photo.tags,
                    is_public=1,
                    is_family=1,
                    is_friend=1,
                    safety_level=1,
                    content_type=1,
                    hidden=1,
                )
                photo.flickr_photo_id = flickr_response.id
                photo_info = flickr_response.getInfo()
                photo.flickr_photo_url = 'https://farm{}.staticflickr.com/{}/{}_{}_b.jpg'.format(
                    photo_info['farm'], photo_info['server'],
                    flickr_response.id, photo_info['secret'])
                photo.save()
                result['flickr_response'] = flickr_response
                break
            except Exception as e:
                print str(e)
                try_count -= 1
            time.sleep(10)
    else:
        result['flickr_response'] = 'already upload to flickr'

    if photo.facebook_post_id == '':
        result['facebook_response'] = uploadToFacebook(photo)
    else:
        result['facebook_response'] = updateFlickrPhotoURL(photo)

    print 'uploadPhotoresult' + str(result)

    photo.isReady = True
    photo.image.delete()
    photo.save()
    return result
コード例 #31
0
def HandleNotLoggedIn(cookie):
    import flickr_api as f
    f.disable_cache()

    authHandler = f.auth.AuthHandler(keys.kAPI_KEY,
                                     keys.kAPI_SECRET,
                                     callback=keys.kCALLBACK_URL)
    f.set_auth_handler(authHandler)
    url = authHandler.get_authorization_url("write")
    cookie["request_token_key"] = authHandler.request_token.key
    cookie["request_token_secret"] = authHandler.request_token.secret

    print cookie.output()
    print 'Location: %s\n' % (url)
コード例 #32
0
ファイル: handlers.py プロジェクト: tsinin/FlickrBot
def handle_set_title(message):
    try:
        flickr_api.set_auth_handler("./users_data/{}/auth_token.dat".format(
            hash(message.chat.id)))
        USERS[hash(message.chat.id)] = flickr_api.test.login()
        flickr_api.upload(photo_file="Photo",
                          title=message.text,
                          photo_file_data=urllib.request.urlopen(URLS[hash(
                              message.chat.id)]))
    except Exception:
        BOT.send_message(message.chat.id,
                         "Oops! Error! Try later or try another photo.")
        return

    BOT.send_message(message.chat.id, "Photo is uploaded!")
コード例 #33
0
ファイル: shell.py プロジェクト: EelaiWind/python-flickr-api
def main():
    """Start shell with `user` object
    """
    ACCESS_TOKEN = sys.argv[1]
    flickr_api.set_auth_handler(ACCESS_TOKEN)

    user_namespace = {
        'flickr_api': flickr_api,
        'user': flickr_api.test.login()}

    # iPython uses `sys.argv`
    # so we're resetting it
    sys.argv = sys.argv[:1]

    IPython.start_ipython(user_ns=user_namespace)
コード例 #34
0
def flickr_albums(id):
    account = FlickrAccount.query.get(id)
    print account
    # Set the api keys
    flickr_api.set_keys(api_key=account.key, api_secret=str(account.secret))
    auth_handler = flickr_api.auth.AuthHandler(
        access_token_key=account.oauth_token,
        access_token_secret=str(account.oauth_secret))

    # Set the authentication handler
    flickr_api.set_auth_handler(auth_handler)
    user = flickr_api.test.login()
    photosets = user.getPhotosets()
    print photosets
    return render_template('flickr/flickr_albums.html', photosets=photosets)
コード例 #35
0
def generate_handler():
    """Generates flickr api handler if it does not exist. Saves handler to file with inputed filename"""

    print(
        'To use this script, you must grant read and modify permissions to it by generating special access handler.\nLet\'s do it'
    )
    print(
        'Fisrt step is to go to your flickr\'s profile and open AppGarden.\nIf you are logged in, you can use this url -> http://www.flickr.com/services/apps/'
    )
    print(
        'You need to get an api key. When you get api key and secret, tell it to the application '
    )
    my_api_key = raw_input('My api key: ')
    my_secret = raw_input('My secret: ')
    perms = raw_input(
        'Permissions: read, write (includes read), delete (includes write): ')

    try:
        flickr_api.set_keys(api_key=my_api_key, api_secret=my_secret)
    except:
        print('Somth goes wrong with your keys. Try again')

    def check_perms(perms):
        """Checks permissions for correct input"""

        if (perms == 'read' or perms == 'write' or perms == 'delete'):
            pass
        else:
            print(
                'please, re-enter permissions. you can choose "read" or "write" or "delete" option'
            )
            perms = raw_input('Enter permissions: ')
            perms = check_perms(perms)
        return perms

    perms = check_perms(perms)
    #generate handler
    access_handler = flickr_api.auth.AuthHandler()
    url = access_handler.get_authorization_url(perms)
    print('Please, open url: %s and get auth code' % url)
    auth_code = raw_input(
        'Pleas, enter auth code. It is in <oauth_verifier> tag:')
    access_handler.set_verifier(auth_code)
    flickr_api.set_auth_handler(access_handler)
    filename = raw_input(
        'Enter filename to store your access handler. it is needed by scrypt to get access to your account:'
    )
    access_handler.save(filename)
コード例 #36
0
    def auth():
        """
        Authorises a user with the app. Exectutes steps and prompts user for auth details
        """
        if os.path.exists('./.flickr_auth'):
            flickr.set_auth_handler(".flickr_auth")
            return

        a = flickr.auth.AuthHandler()
        perms = "delete"
        url = a.get_authorization_url(perms)
        print("Open this in a web browser -> ", url)
        oauth_verifier = input("Copy the oauth_verifier tag > ")
        a.set_verifier(oauth_verifier)
        flickr.set_auth_handler(a)
        a.save('.flickr_auth')
コード例 #37
0
def main():
    """Start shell with `user` object
    """
    ACCESS_TOKEN = sys.argv[1]
    flickr_api.set_auth_handler(ACCESS_TOKEN)

    user_namespace = {
        'flickr_api': flickr_api,
        'user': flickr_api.test.login()
    }

    # iPython uses `sys.argv`
    # so we're resetting it
    sys.argv = sys.argv[:1]

    IPython.start_ipython(user_ns=user_namespace)
コード例 #38
0
ファイル: socialApplication.py プロジェクト: EelaiWind/NTHUFC
def uploadUsingThread(photo):
	photo_file_path = photo.image.path
	result = {}

	if photo.flickr_photo_id=='':
		try_count = 3
		flickr_api.set_keys(api_key = __flickr_api_key, api_secret = __flickr_api_secret)
		flickr_api.set_auth_handler('oauth_verifier.txt')

		while try_count > 0 :
			try :
				flickr_response = flickr_api.upload(
					photo_file = photo_file_path,
					title =photo.title,
					description = u'地點: '+photo.location_marker.title+u'\n拍攝者: '+photo.owner.nickname+'\n\n'+photo.content,
					tags = photo.tags,
					is_public = 1,
					is_family = 1,
					is_friend = 1,
					safety_level =1,
					content_type  =1,
					hidden = 1,
				)
				photo.flickr_photo_id = flickr_response.id
				photo_info = flickr_response.getInfo()
				photo.flickr_photo_url = 'https://farm{}.staticflickr.com/{}/{}_{}_b.jpg'.format(photo_info['farm'], photo_info['server'], flickr_response.id, photo_info['secret'])
				photo.save()
				result['flickr_response'] = flickr_response
				break;
			except Exception as e:
				print str(e)
				try_count -= 1
			time.sleep(10)
	else:
		result['flickr_response'] = 'already upload to flickr'

	if photo.facebook_post_id =='':
		result['facebook_response'] = uploadToFacebook(photo)
	else:
		result['facebook_response'] = updateFlickrPhotoURL(photo)

	print 'uploadPhotoresult' + str(result)

	photo.isReady = True
	photo.image.delete()
	photo.save()
	return result
コード例 #39
0
def import_photoset(id):
    # Do some stuff
    account = models.FlickrAccount.query.get(1)
    print account
    #Set the api keys
    flickr_api.set_keys(api_key=account.key, api_secret=str(account.secret))
    auth_handler = flickr_api.auth.AuthHandler(
        access_token_key=account.oauth_token,
        access_token_secret=str(account.oauth_secret))

    # Set the authentication handler
    flickr_api.set_auth_handler(auth_handler)
    user = flickr_api.test.login()
    photosets = user.getPhotosets(id=id)
    print photosets
    photoset = [i for i in user.getPhotosets() if i.id == id][0]

    # Create category
    category = models.PhotoCategory()
    category.name = "Trips"
    category.slug = "Vacations and Trips"
    db.session.add(category)

    # Add the photoset to the db
    photoset_db = models.PhotoAlbum(category)
    photoset_db.name = photoset.title
    photoset_db.description = "First visit to San Francisco"
    category.albums.append(photoset_db)
    #db.session.add(photoset_db)

    photos = photoset.getPhotos()
    print photoset
    for photo in photos:
        print photo
        photo_db = models.Photo(photoset_db)
        sizes = photo.getSizes()
        photo_db.thumbnail_path = sizes['Medium 640']['source']
        photo_db.path = sizes['Large 1600']['source']
        photo_db.height = sizes['Large 1600']['height']
        photo_db.width = sizes['Large 1600']['width']
        print sizes['Medium 640']['source']
        photoset_db.photos.append(photo_db)
        #db.session.add(photo_db)
        #print flickr_api.Photo.getInfo(photo=photo)
        #db.session
    db.session.add(category)
    db.session.commit()
コード例 #40
0
    def test_bytes_response(self):
        from flickr_api import set_auth_handler
        auth_handler = AuthHandler(key='test',
                                   secret='test',
                                   access_token_key='test',
                                   access_token_secret='test')
        set_auth_handler(auth_handler)
        args = dict(photo_file='/tmp/test_file',
                    photo_file_data=StringIO('000000'))

        module = inspect.getmodule(method_call)
        resp = Response()
        resp.status_code = 200
        resp.raw = BytesIO(b'[0,1]')
        module.requests.post = MagicMock(return_value=resp)
        payload = module.requests.post.return_value.json()
        self.assertEqual(type(payload), list)
コード例 #41
0
ファイル: views.py プロジェクト: PhoeniXkrypT/flickr_oauth
def base(request):
	state="HOMEPAGE"
	
	oauth_verifier = request.GET.get('oauth_verifier')
	print ">>>>", oauth_verifier
	authorize_url=settings.authorize_url
	authorize_url.set_verifier(oauth_verifier)
	flickr_api.set_auth_handler(authorize_url)
	
	print
	user = flickr_api.test.login()
	print "User Info : ", user
	photos = user.getPhotos()
	print photos
	print "Photo No: ",photos.info.total
	
	return render(request,'base.html')
コード例 #42
0
def getVotes(photo):
    flickr_api.set_keys(api_key=__flickr_api_key,
                        api_secret=__flickr_api_secret)
    flickr_api.set_auth_handler('oauth_verifier.txt')
    favorites = flickr_api.Photo(id=photo.flickr_photo_id).getFavorites()

    graph = facebook.GraphAPI(access_token=__facebook_page_token,
                              version='2.5')
    response = graph.get_object(id=photo.facebook_post_id,
                                fields='likes.summary(true)')
    likes = response['likes']['summary']['total_count']
    photo.favorites = len(favorites)
    photo.likes = likes
    photo.votes = photo.likes + photo.favorites
    photo.last_modified_time = timezone.now()
    photo.save(
        update_fields=['favorites', 'likes', 'votes', 'last_modified_time'])
    return photo.favorites + photo.likes
コード例 #43
0
ファイル: main.py プロジェクト: pro2s/fyTunnel
 def get(self):	        
     flickr_auth = flikr_token
     if flickr_auth is not None:
         a = flickr_api.auth.AuthHandler.fromdict(flickr_auth)
         flickr_api.set_auth_handler(a)
         u = flickr_api.test.login()
         id = self.request.get('id','')
         for item in u.getPhotosets():
             if item.id == id:
                 a = Album.get_by_id(item.id)
                 if a is not None and not a.sync:
                     pages = (item.photos + 250) // 500
                     if pages == 0: pages = 1 
                     for page in range(pages):
                         for p in item.getPhotos(page = page + 1):
                             # p.id, p.title, album.id, album.yaf_id
                             taskqueue.add(url='/sync/', params = {'id': p.id, 'title': p.title, 'album_id': item.id, 'album_yaf':a.yaf_id})
                     self.response.write(a.title + '<br>')
コード例 #44
0
ファイル: handlers.py プロジェクト: tsinin/FlickrBot
def handle_verifier(message):
    text = message.text
    begin, end = text.find("<oauth_verifier>"), text.find("</oauth_verifier>")
    if begin != -1 and end != -1:
        AUTH_TOKENS[hash(message.chat.id)].set_verifier(
            text[begin + OAUTH_VERIFIER_LENGTH:end])
        flickr_api.set_auth_handler(AUTH_TOKENS[hash(message.chat.id)])
        USERS[hash(message.chat.id)] = flickr_api.test.login()
        os.system("mkdir ./users_data/{}".format(hash(message.chat.id)))
        AUTH_TOKENS[hash(message.chat.id)].save(
            "./users_data/{}/auth_token.dat".format(hash(message.chat.id)))

        BOT.send_message(
            message.chat.id, "You're authorised, let's start using me!"
            "\n(/help and /info are still available.)")
    else:
        BOT.send_message(
            message.chat.id,
            "Wrong input, are you sure you're following my instructions?"
            "Let's try from the beginning")
コード例 #45
0
    def test_upload_not_200(self):
        from flickr_api import set_auth_handler
        auth_handler = AuthHandler(key="test",
                                   secret="test",
                                   access_token_key="test",
                                   access_token_secret="test")
        set_auth_handler(auth_handler)
        args = dict(photo_file='/tmp/test_file',
                    photo_file_data=StringIO("000000"))

        module = inspect.getmodule(upload)
        resp = Response()
        resp.status_code = 404
        resp.raw = BytesIO("Not Found".encode("utf-8"))
        module.requests.post = MagicMock(return_value=resp)

        with self.assertRaises(FlickrError) as context:
            upload(**args)

        print(context.exception)
        self.assertEquals("HTTP Error 404: Not Found", str(context.exception))
コード例 #46
0
    def test_call_5XX(self):
        from flickr_api import set_auth_handler
        auth_handler = AuthHandler(key="test",
                                   secret="test",
                                   access_token_key="test",
                                   access_token_secret="test")
        set_auth_handler(auth_handler)
        args = dict(photo_file='/tmp/test_file',
                    photo_file_data=StringIO("000000"))

        module = inspect.getmodule(method_call)
        resp = Response()
        resp.status_code = 502
        resp.raw = BytesIO("Bad Gateway".encode("utf-8"))
        module.requests.post = MagicMock(return_value=resp)

        with self.assertRaises(FlickrServerError) as context:
            f.Person.findByUserName("tomquirkphoto")

        print(context.exception)
        self.assertEquals("HTTP Server Error 502: Bad Gateway",
                          str(context.exception))
コード例 #47
0
    def test_upload_not_200(self):
        from flickr_api import set_auth_handler
        auth_handler = AuthHandler(
            key="test",
            secret="test",
            access_token_key="test",
            access_token_secret="test")
        set_auth_handler(auth_handler)
        args = dict(
            photo_file='/tmp/test_file', photo_file_data=StringIO("000000"))

        module = inspect.getmodule(upload)
        resp = Response()
        resp.status_code = 404
        resp.raw = BytesIO("Not Found".encode("utf-8"))
        module.requests.post = MagicMock(return_value=resp)

        with self.assertRaises(FlickrError) as context:
            upload(**args)

        print(context.exception)
        self.assertEquals("HTTP Error 404: Not Found", str(context.exception))
コード例 #48
0
    def _get_user_info(self, session_id ):
        logging.debug( "Session ID: {0}".format(session_id) )

        # Do we know anything about this session ID?
        access_token_file =  "access_token_{0}.json".format( session_id )

        if os.path.isfile( access_token_file ) is True:
            logging.info( "Session ID {0} is known and has an access token".format(session_id) )
            with open( access_token_file, "r" ) as access_token_file_handle:
                access_token_info = json.load( access_token_file_handle )

            #logging.debug( "Access token info:\n{0}".format( json.dumps(access_token_info, indent=4, sort_keys=True)))
        else:
            self.set_status( 400, "Unknown session ID {0}".format(session_id) )
            return

        auth_handler = flickr_api.auth.AuthHandler.fromdict( access_token_info )

        flickr_api.set_auth_handler( auth_handler )

        # Now fully authorized

        # Get currently logged-in user
        flickr_user = self._get_flickr_user()

        # Get all relevant info for the page
        user_info = {
            'id'        : flickr_user.id,
            'username'  : flickr_user.username 
        }
        #flickr_photo_ids    = self._get_flickr_photo_ids( flickr_user )
        flickr_groups = self._get_groups()

        self.write( 
            {
                "user_info"         : user_info,
                "public_groups"     : flickr_groups,
            }
        )
コード例 #49
0
def HandleResumeSession(cookie):
    token, secret = database.GetOAuthTokenAndSecret(cookie["user_id"].value,
                                                    cookie["token_id"].value)
    if token == None or secret == None:
        return False

    import flickr_api as f
    f.disable_cache()
    a = f.auth.AuthHandler.fromdict({
        'api_key': keys.kAPI_KEY,
        'api_secret': keys.kAPI_SECRET,
        'access_token_key': token,
        'access_token_secret': secret,
    })
    try:
        f.set_auth_handler(a)
        HandlePage(f.test.login(), cookie["token_id"].value)
        return True
    except urllib2.HTTPError as e:
        pass

    return False
コード例 #50
0
    def test_call_5XX(self):
        from flickr_api import set_auth_handler
        auth_handler = AuthHandler(
            key="test",
            secret="test",
            access_token_key="test",
            access_token_secret="test")
        set_auth_handler(auth_handler)
        args = dict(
            photo_file='/tmp/test_file', photo_file_data=StringIO("000000"))

        module = inspect.getmodule(method_call)
        resp = Response()
        resp.status_code = 502
        resp.raw = BytesIO("Bad Gateway".encode("utf-8"))
        module.requests.post = MagicMock(return_value=resp)

        with self.assertRaises(FlickrServerError) as context:
            f.Person.findByUserName("tomquirkphoto")

        print(context.exception)
        self.assertEquals("HTTP Server Error 502: Bad Gateway",
                          str(context.exception))
コード例 #51
0
ファイル: views.py プロジェクト: anujacharya1/HashVoice
def photoSearch(request, tag=None):
    
    fi.set_auth_handler(Const.cFILENAME)
    user = fi.test.login()    
    imagesList = list()    
    result = Photo.objects.get_photo(tag,user.username)
    
    if result[Const.cRESPONSE]:
        imagesList = result[Const.cMODEL]
        print imagesList
    
    mainImageList = list()
    for i in imagesList:
        iTemp  =i.split('/')
        iTempLen = len(iTemp)
        print imagesList
        
        mainImageList.append(iTemp[iTempLen-1])
  
    to_json = {Const.cPHOTO : str(mainImageList) }
    print to_json

    return HttpResponse(json.dumps(to_json), mimetype='application/json')
コード例 #52
0
ファイル: uploadr.py プロジェクト: Lafcadio/uploadr
 def authorize(self, path):
     root = path
     while not os.path.exists(os.path.join(root, TOKEN)) and root is not "/":
         root = os.path.dirname(root)
     token_path = os.path.join(root, TOKEN)
     if os.path.exists(token_path):
         flickr.set_auth_handler(token_path)
     else:
         token_path = os.path.join(path, TOKEN)
         a = flickr.auth.AuthHandler()
         print "Please go to the following URL, and enter the oauth_verifier:"
         print "                                              --------------"
         print a.get_authorization_url("delete")
         print ""
         print "oauth_verifier:",
         code = raw_input()
         try:
             a.set_verifier(code)
         except:
             print "ERROR! Code was not accepted. Please try again."
             sys.exit(0)
         a.save(token_path)
         flickr.set_auth_handler(a)
コード例 #53
0
ファイル: lib.py プロジェクト: beaufour/flickr-upload
def init(key, secret):
    """
    Initialize API.

    @see: http://www.flickr.com/services/api/

    @param key: str, API key
    @param secret: str, API secret
    """
    # TODO: save keys in file too, and share with download tool
    logging.debug('Initializing Flickr API ({0}/{1})'.format(key, secret))
    Flickr.set_keys(key, secret)

    auth_file = os.path.expanduser(AUTH_FILE)
    logging.debug('Loading credentials from: {0}'.format(auth_file))
    try:
        handler = AuthHandler.load(auth_file)
        set_auth_handler(handler)
        return
    except IOError:
        logging.warning('Could not load credentials from: {0}'.format(auth_file))
        # fall through and create the file
        pass

    # Get new crendentials
    logging.debug('Retrieving new credentials from Flickr')
    handler = AuthHandler(key=key, secret=secret)
    print('Please authorize: {0}'.format(handler.get_authorization_url('write')))
    # TODO: make landing page that extracts the verifier
    verifier = raw_input('Verifier: ')
    handler.set_verifier(verifier)
    try:
        handler.save(auth_file)
    except IOError:
        logging.warning('Could not save credentials to: {0}'.format(auth_file))
    set_auth_handler(handler)
コード例 #54
0
ファイル: views.py プロジェクト: anujacharya1/HashVoice
def photos(request):
    try:
        val = request.POST.get(Const.cUID)
        fi.set_auth_handler(Const.cFILENAME)
        user = fi.test.login()
        photo = request.FILES.get('image')
        photoName = val+photo.name
        handle_uploaded_file(photo,photoName)
        tags = request.POST.get(Const.cTAGS)
        tag = tags.split('%2C')
        tagWithSpaces = ''
        for i in tag:
            tagWithSpaces+=i+' '
                        
        response = fi.upload(photo_file = Const.cMEDIA+photoName, title = photoName, tags=tagWithSpaces)

        for t in tag:
            photo = Photo.objects.create_photo(user.username,Const.cMEDIA+photoName,t)
        
        to_json = {Const.cSTATUS : '203'}
    
        return HttpResponse(json.dumps(to_json), mimetype='application/json')
    except Exception as e:
        print ('Exception: %s (%s)' % (e.message, type(e)))
コード例 #55
0
def generate_handler():
    """Generates flickr api handler if it does not exist. Saves handler to file with inputed filename"""
    
    print ('To use this script, you must grant read and modify permissions to it by generating special access handler.\nLet\'s do it')
    print ('Fisrt step is to go to your flickr\'s profile and open AppGarden.\nIf you are logged in, you can use this url -> http://www.flickr.com/services/apps/')
    print ('You need to get an api key. When you get api key and secret, tell it to the application ')
    my_api_key=raw_input('My api key: ')
    my_secret=raw_input('My secret: ')
    perms=raw_input('Permissions: read, write (includes read), delete (includes write): ')
    
    try:
        flickr_api.set_keys(api_key = my_api_key, api_secret = my_secret)
    except:
        print ('Somth goes wrong with your keys. Try again')
    
    def check_perms(perms):
        """Checks permissions for correct input"""
        
        if (perms=='read' or perms=='write' or perms=='delete'):
            pass        
        else:
            print ('please, re-enter permissions. you can choose "read" or "write" or "delete" option')
            perms=raw_input('Enter permissions: ')
            perms=check_perms(perms)
        return perms

    perms=check_perms(perms)
    #generate handler
    access_handler = flickr_api.auth.AuthHandler()
    url = access_handler.get_authorization_url(perms)
    print ('Please, open url: %s and get auth code'%url)
    auth_code=raw_input('Pleas, enter auth code. It is in <oauth_verifier> tag:')
    access_handler.set_verifier(auth_code)
    flickr_api.set_auth_handler(access_handler)
    filename=raw_input('Enter filename to store your access handler. it is needed by scrypt to get access to your account:')
    access_handler.save(filename)
コード例 #56
0
ファイル: sync_flickr.py プロジェクト: ybrodskiy/flickr
        
    except IndexError : pass
    return


##############################################
# Main code starts here
##############################################
try :
    #username = sys.argv[1]
    #try :
    #    access_token = sys.argv[2]
    #    f.set_auth_handler(access_token)
    #except IndexError : pass
    
    #u = f.Person.findByUserName(username)
    f.set_auth_handler("filename")
    u = f.test.login() 

    ps = u.getPhotosets()
    
    for i,p in enumerate(ps) :
        logging.info("Checking set # %s, named: %s", i,p.title)
        if 13  == i : download_set( u, i )
        #download_set( u,i )
except IndexError :
    print "usage: python show_albums.py username [access_token_file]"
    print "Displays the list of photosets belonging to a user"


コード例 #57
0
ファイル: upload_thread.py プロジェクト: jzbora/myFlickrSync
                pass
            else :
                raise FlickrError("Unexpected tag: %s"%t.tag)
        if photo and self.photoset:
            if photoset_exist:
                self.photoset.addPhoto(photo = photo)
            else:
                self.photoset = Photoset.create(title = self.photoset.encode("utf-8"), primary_photo = photo)

        Utils.insertDB(self.filepath, self.photoset_txt, 1, upload_date)
        #logger.info(photoset)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    filepath = "test//bb.jpg"
    photoset = ""

    FLICKR_APP_KEY = getattr(settings, 'FLICKR_APP_KEY')
    FLICKR_APP_SECRET = getattr(settings, 'FLICKR_APP_SECRET')

    flickr_api.set_keys(api_key = FLICKR_APP_KEY, api_secret = FLICKR_APP_SECRET)

    auth_path = getattr(settings, 'AUTH_PATH')

    auth = flickr_api.auth.AuthHandler.load(auth_path)
    flickr_api.set_auth_handler(auth)
    logger.info(flickr_api.auth.AUTH_HANDLER)
    upload_thread = UploadThread(None, flickr_api, filepath, photoset)
    upload_thread.check()
    sys.exit(app.exec_())
コード例 #58
0
ファイル: testAuthorization.py プロジェクト: EelaiWind/NTHUFC
# -*- coding:utf-8 -*-

from authorization_token import __flickr_api_key, __flickr_api_secret, fb_fanpage_graph
import flickr_api
import facebook

print 'Testing Flickr API ...'
flickr_api.set_keys(api_key = __flickr_api_key, api_secret = __flickr_api_secret)
a = flickr_api.auth.AuthHandler()
url = a.get_authorization_url('delete')
print url
verifier_code = raw_input('verifier code = ')
a.set_verifier(verifier_code)
a.save('oauth_verifier.txt')
flickr_api.set_auth_handler('oauth_verifier.txt')

user = flickr_api.test.login()
print user

print 'Testing Facebook API...'
page = fb_fanpage_graph.get_object(id='1528712347441804')
print '{} (id = {})'.format(page['name'].encode('utf-8'), page['id'])