Example #1
0
 def __init__(self):
     ''' Initiate the connector '''
     flickr_api.set_keys(api_key=API_KEY, api_secret=API_SECRET)
     a = flickr_api.auth.AuthHandler()  #creates the AuthHandler object
     perms = "read, write"  # set the required permissions
     url = a.get_authorization_url(perms)
     self.connector = flickr_api
Example #2
0
 def __init__(self,
              url,
              key='e780392c82204d601eaaf715db9d2e4e',
              secret='c8aeddf10d814962'):
     flickr_api.set_keys(api_key=key, api_secret=secret)
     self.page = urlopen(url).read()
     self.user = flickr_api.Person.findByUrl(url)
Example #3
0
def gatherImages():
	import flickr_api as flickr
	import Image
	flickr.set_keys(settings.FLICKR_API,settings.FLICKR_SECRET)
	try:
		latest = Photo.objects.latest('id').date_posted 
	except:
		latest = 00000000
	w = flickr.Walker(flickr.Photo.search, tags=settings.FLICKR_TAGS, min_upload_date =latest, sort="date-posted-asc")
	for photo in w:
		face_pic = recognizeFace(photo.getPhotoFile())
		dbPhoto = Photo()
		dbPhoto.p_id = photo.id
		dbPhoto.date_posted = photo.dateuploaded
		if not face_pic == False:
			dbPhoto.has_face = True
			pic_filename = settings.MEDIA_ROOT+'raw_photos/'+photo.id+'.jpg'
			photo.save(pic_filename)
			local_image = Image.open(pic_filename)
			face_file = local_image.crop(face_pic)
			face_file.save(settings.MEDIA_ROOT+'faces/'+photo.id+'.jpg','jpeg')
			dbPhoto.pic = 'faces/'+photo.id+'.jpg'
		else:
			dbPhoto.has_face = False
		dbPhoto.save()
Example #4
0
def flickr_to_go(dest, savecreds, key, secret, output=sys.stdout):
    start_time = time.time()
    timestamp_path = os.path.join(dest, 'timestamp')
    flickr_api.set_keys(api_key=key, api_secret=secret)
    file_store = FileStore(dest)
    user = authenticate(savecreds, flickr_api, auth.AuthHandler, file_store)
    if not user:
        return False

    err_path = os.path.join(dest, "errors.txt")
    with open(err_path, 'w') as errfile:
        errors = ErrorHandler(errfile)
        downloader = FlickrApiDownloader(file_store, errors)
        photos = photolist.download(downloader, flickr)
        if photos is None:
            output.write("Photo list download failed. Can't continue.\n")
            return False
        containers.download(downloader, flickr)
        last_time = read_timestamp(timestamp_path)
        if last_time is None:
            recently_updated = []
        else:
            recently_updated = photolist.fetch_recently_updated(last_time,
                downloader, flickr) or []
        photo.download(photos, recently_updated, downloader, flickr)

        if errors.has_errors():
            print("Some requests failed.")
            print("Errors are logged to %s" % err_path)
            return False

    with open(timestamp_path, 'w') as f:
        f.write(str(int(round(start_time))))
    return True
Example #5
0
 def __init__(self):
     ''' Initiate the connector '''
     flickr_api.set_keys(api_key = API_KEY, api_secret = API_SECRET)
     a = flickr_api.auth.AuthHandler() #creates the AuthHandler object
     perms = "read, write" # set the required permissions
     url = a.get_authorization_url(perms)
     self.connector = flickr_api
Example #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
Example #7
0
def init_bot(token, flickr_keys):
    global BOT, BOT_TOKEN
    BOT_TOKEN = token
    BOT = telebot.TeleBot(token)
    flickr_api.set_keys(api_key=flickr_keys[0], api_secret=flickr_keys[1])

    from app import handlers
Example #8
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)
Example #9
0
def get_carousel_images_by_location(location):
    flickr_api.set_keys(api_key=flickr_keys.api_key,
                        api_secret=flickr_keys.api_secret)
    url = "http://api.flickr.com/services/rest/?%s"
    query_params = urllib.urlencode({
        "method": "flickr.photos.search",
        "api_key": flickr_keys.api_key,
        "tags": location,
        "per_page": 20
    })
    print url % query_params
    #url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=%s&tags=joshua+tree&safe_search=1&per_page=20"%flickr_keys.api_key;
    result = urlopen(url % query_params)
    tree = ET.parse(result).getroot()
    imageURL = []
    carouselList = []
    photoTags = tree.findall("photos")[0].getchildren()
    #print photoTags[0].attrib['title']
    for x in photoTags:
        imageURL.append("http://farm" + x.attrib['farm'] +
                        ".staticflickr.com/" + x.attrib['server'] + "/" +
                        x.attrib['id'] + "_" + x.attrib['secret'] + ".jpg")
    for imgurl in imageURL:
        carouselList.append(
            '<div class="item"><img width="900" height="500" data-src="holder.js/900x500/auto/#777:#555/text:First slide" src="'
            + imgurl + '"></div>')
    return carouselList
Example #10
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))
Example #11
0
def load_image(username='******', load_file=False):
    save_to = os.path.join( os.getcwd(), 'res', 'photos')

    photo_lst = []
    if not os.path.exists(save_to):
        os.makedirs(save_to)

    flickr_api.set_keys(api_key='de55944b9ca453372730df42309acf63', api_secret='04a10434fbfc8315')
    u = flickr_api.Person.findByUserName(username)

    photos = u.getPublicPhotos()

    for p in photos:
        p_info = p.getInfo()
        photo_lst.append({
            'id': p_info['id'],
            'location': p_info.get('location', None),
            'title': p_info['title'],
            'taken': p_info.get('taken', None)
        })

        if load_file:
            path_thumb = os.path.join(save_to, p.id + '_thumb.jpg')
            path_orig = os.path.join(save_to, p.id + '.jpg')
            p.save(path_thumb, 'Medium')
            p.save(path_orig, 'Original')

    with open(os.path.join(save_to, 'photo_lst.json'), 'wb') as f:
        f.write(json.dumps(photo_lst, indent=4))

    return photo_lst
Example #12
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
Example #13
0
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),
	}
Example #14
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
Example #15
0
    def run(
        self,
        query,
        page_id=0,
        urls_per_page=500,
        api_key="a1c5cc6b3d6c7bad6ceff207e2d901b2",
        api_secret="7ee7e077ffb72800",
    ):
        # 1. Call Flickr

        flickr_api.set_keys(api_key=api_key, api_secret=api_secret)
        json_reply = flickr.photos.search(
            text=query, page=page_id, per_page=urls_per_page, format="json", extras="url_m,geo,tags,views,date_taken"
        )

        m = re.search(r"jsonFlickrApi\((.+)\)", json_reply)
        reply = json.loads(m.group(1))

        # print reply
        urls = []
        print "TRC: pages = %d" % reply["photos"]["pages"]
        for photo in reply["photos"]["photo"]:
            # print "Submitted " + photo['url_m']
            urls.append(photo["url_m"])
            # FIXME deal correctly with date_taken GetURL().delay( photo['url_m'], tags= photo['tags'], taken_time=photo['date_taken'], coords=photo['geo'] )

            GetURL().delay(photo["url_m"], tags=photo["tags"].split())

        pagination_struct = {"urls": urls, "pages": reply["photos"]["pages"]}
        return pagination_struct
Example #16
0
def import_photos(username, photoset_title, api_key, api_secret):

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

    user = flickr_api.Person.findByUserName(username)
    photosets = user.getPhotosets()

    for photoset in iter(photosets):
        if photoset.title == photoset_title:
            photos = photoset.getPhotos()
            for photo in iter(photos):
                photo_id = int(photo.id)
                point = Point.query(Point.pointid == photo_id).get()
                if point is None:
                    latitude = None
                    longitude = None
                    timestamp = None
                    title = photo.title
                    thumb_url = None
                    photo_url = None
                    photopage = None
                    info = photo.getInfo()
                    taken = info[u"taken"]
                    timestamp = datetime.strptime(taken, "%Y-%m-%d %H:%M:%S")
                    urls = info[u"urls"][u"url"]
                    for url in urls:
                        if url[u"type"] == "photopage":
                            photopage = url[u"text"]
                            break
                    if u"location" in info:
                        location = info[u"location"]
                        # locality = location[u'locality']
                        # region = location[u'region']
                        # country = location[u'country']
                        latitude = float(location[u"latitude"])
                        longitude = float(location[u"longitude"])
                        # title =  "%s, %s, %s" % (locality, region, country)
                    sizes = photo.getSizes()
                    thumb_url = sizes[u"Square"][u"source"]
                    photo_url = sizes[u"Medium"][u"source"]

                    try:
                        point = Point(
                            title=title,
                            latitude=latitude,
                            longitude=longitude,
                            type="photo",
                            timestamp=timestamp,
                            pointid=photo_id,
                            thumb=thumb_url,
                            photo=photo_url,
                            resource=photopage,
                        )
                        point.put()
                    except AttributeError:
                        pass
                    except Exception as e:
                        logging.error(e.args[0])

    return Response(json.dumps({"status": "ok"}), status=200, mimetype="application/json")
Example #17
0
def add_flickr_account():
    if request.method == 'POST':

        print request.form
        flickr_api.set_keys(api_key=request.form.get('api_key'),
                            api_secret=str(request.form.get('api_secret')))
        auth_handler = flickr_api.auth.AuthHandler(
            request_token_key=session['request_token_key'],
            request_token_secret=session['request_token_secret'])

        auth_handler.set_verifier(request.form.get('oauth_verifier'))

        the_stuff = auth_handler.todict(include_api_keys=True)
        print the_stuff
        account = FlickrAccount()
        account.authenticated = True
        account.key = the_stuff['api_key']
        account.secret = the_stuff['api_secret']
        account.oauth_token = the_stuff['access_token_key']
        account.oauth_secret = the_stuff['access_token_secret']

        db.session.add(account)
        db.session.commit()
        redirect(url_for('flickr_accounts'))
    else:
        return render_template('flickr/add_flickr_account.html')
def main():
    parser = argparse.ArgumentParser(description='''Takes flickr API key and secret in order to create an access token file. \n
                                                See: http://www.flickr.com/services/api/keys/ for more information. \n
                                                Once key and secret are passed through arguments a URL will be printed where you \n
                                                need to authenticate with your flickr credentials to authorize permissions for \n
                                                py_flickr_backup_tool. When this is done a XML is generated where you need to \n
                                                extract the value of the <oath_verifier> tag and provide it to this script when \n
                                                prompted.''')
    parser.add_argument('-k', '--api_key', help='API key provided by flickr.', required=True)
    parser.add_argument('-s', '--api_secret', help='API secret provided by flickr.', required=True)

    args = parser.parse_args()

    if args.api_key and args.api_secret:
        f.set_keys(api_key = args.api_key, api_secret = args.api_secret) 
        auth_handler = f.auth.AuthHandler()
        url = auth_handler.get_authorization_url('write')
        print '\nPaste this url into your browser and authorize the app. Once that is done, copy and paste the value of <oath_verifier>.\n'
        print url
        #Hack for python 2 and 3 compability
        try: 
            input = raw_input
        except NameError: 
            pass
        oauth_verifier = input('\nOauth_verifier: ')
        auth_handler.set_verifier(oauth_verifier)
        auth_handler.save('access_token')
        print 'Access token file saved as file: access_token'
Example #19
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)
def _set_keys(keyfile=None):
    if keyfile is None:
        keyfile = str(path(__file__).abspath().dirname()) + "/default.key"
    f = open(keyfile, 'r')
    lines = f.read().split("\n")
    flickr_api.set_keys(api_key=lines[0], api_secret=lines[1])
    f.close()
    return flickr_api
Example #21
0
def search_max(term, maximum):
    try:
        maximum=int(maximum)
    except:
        flash("maximum must be integer, 10 results will be rendered", "error")
    flickr_api.set_keys(**secrets)
    photos = flickr_api.Photo.search(tags=term, sort='date-posted-desc', per_page=maximum)
    return render_template('photos.html', photos=photos, maximum=maximum, term=term)
Example #22
0
def initialise():
    from ConfigParser import SafeConfigParser
    parser = SafeConfigParser()
    parser.read('config.ini')
    API_KEY = parser.get('credential', 'API_KEY')
    API_SECRET = parser.get('credential', 'API_SECRET')
    flickr_api.set_keys(api_key=API_KEY, api_secret=API_SECRET)
    return
Example #23
0
    def __init__(self, bot):
        self.bot = bot
        self.session = requests.Session()
        self.cache = TTLCache(maxsize=500, ttl=300)

        public_key = config.flickrPublic
        secret_key = config.flickrSecret
        flickr_api.set_keys(public_key, secret_key)
Example #24
0
def index(request):
    fi.set_keys(api_key = settings.FLICKR_API_KEY, api_secret = settings.FLICKR_API_SECRET)
    # This need to change after we deploy it on the external server
    a = fi.auth.AuthHandler(callback=Const.cPORT_LOCAL+'flickr/callback')
    perms = "delete"
    url = a.get_authorization_url(perms)
    request.session['a'] = a
    return HttpResponseRedirect(url)
Example #25
0
def checkIds(akv, skv, print_M=0):
    flickr_api.set_keys(api_key=akv, api_secret=skv)
    try:
        flickr_api.Person.findByUserName('vicro_bot').id
    except flickr_api.flickrerrors.FlickrAPIError:
        if print_M: print("Wrong Keys!!", "Try again")
        return 0
    return 1
Example #26
0
def search(term):
    flickr_api.set_keys(**secrets)
    write_to_sqs(term, "web")
    photos = flickr_api.Photo.search(tags=term,
                                     sort='date-posted-desc',
                                     per_page=10)
    #raise
    return render_template('photos.html', photos=photos, maximum=10, term=term)
Example #27
0
 def __init__(self):
     ''' Initiate the connector '''
     flickr_api.set_keys(api_key=API_KEY, api_secret=API_SECRET)
     a = flickr_api.auth.AuthHandler()  #creates the AuthHandler object
     perms = "read"  # set the required permissions
     url = a.get_authorization_url(perms)
     username = '******'
     user = flickr_api.Person.findByUserName(username)
     print user
Example #28
0
 def __init__(self):
     ''' Initiate the connector '''
     flickr_api.set_keys(api_key = API_KEY, api_secret = API_SECRET)
     a = flickr_api.auth.AuthHandler() #creates the AuthHandler object
     perms = "read" # set the required permissions
     url = a.get_authorization_url(perms)
     username = '******'
     user = flickr_api.Person.findByUserName(username)
     print user
Example #29
0
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()
Example #30
0
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
Example #31
0
 def test_httpexception_retry_success(self, mock_urlopen):
     handler = FailsTwice(StringIO('{"x": 42}'))
     mock_urlopen.side_effect = lambda *args: handler.urlopen(args[0])
     flickr_api.set_keys(api_key='test', api_secret='test')
     error_handler = ErrorHandler(StringIO())
     downloader = FlickrApiDownloader(Mock(), error_handler)
     result = downloader.download(flickr.people.getPublicPhotos, {},
             lambda doc: doc,
             'ignored')
     self.assertEqual(result, {'x': 42})
Example #32
0
    def initialize(self):
        self.flickr_auth = {
            "api_key"   : "80aa90492203094f9fad6b8032f5948b",
            "secret"    : "69003acec0548150"
        }

        flickr_api.set_keys( 
            api_key     = self.flickr_auth['api_key'], 
            api_secret  = self.flickr_auth['secret']
        )
    def __init__(self, user_name, export_to, api_key, api_secret):

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

        self.user = flickr_api.Person.findByUserName(user_name)
        self.export_directory = export_to

        logging.info('User has been loaded')

        csv_file = open(os.path.join(self.export_directory, 'exif.csv'), 'wb')
        self.csv = csv.DictWriter(csv_file, ('#', 'ID', 'FileName', 'EXIF'))
Example #34
0
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
Example #35
0
def home(request):

	flickr_api.set_keys(api_key = settings.API_KEY, api_secret = settings.API_SECRET)
	authorize_url = flickr_api.auth.AuthHandler(callback = "http://127.0.0.1:8000/base/") 
	settings.authorize_url=authorize_url
	perms = "read"
	url = authorize_url.get_authorization_url(perms)
	print url
	return HttpResponseRedirect(url)
	
	return render (request,'home.html')
Example #36
0
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()
Example #37
0
def api(term):
    flickr_api.set_keys(**secrets)
    write_to_sqs(term, "api")
    photos = flickr_api.Photo.search(tags=term, sort='date-posted-desc', per_page=10)
    j = []
    for photo in photos:
        j.append({
            'title': photo.title,
            'description': photo.title,
            'url': photo.getPhotoUrl()})
    response = Response(json.dumps({'photos': j}), status=200, mimetype='application/json')
    return response
Example #38
0
def login(request):

    # Add the CSRF Token to the template context
    #c = {}
    #c.update(csrf(request))

    form = LoginForm()
    # Set the Flickr keys only once
    flickr_api.set_keys(api_key = FLICKR_API_KEY, api_secret = FLICKR_SECRET)
    return render_to_response('login.html',
                                 {'form': form,
                                    })
Example #39
0
def get_photos():
    #reach out to flickr and get photos
    try:
        flickr.set_keys(api_key='#', api_secret='#')
        photos = flickr.Person.findByUserName("warejc").getPublicPhotos()
        photo_urls = [
            photo.getPhotoFile(size_label="Medium") for photo in photos
        ]
    except Exception as e:
        return jsonify({'Exception': str(e)})

    return render_template('pages/photos.html', photo_urls=photo_urls)
Example #40
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}
Example #41
0
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')
Example #42
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
Example #43
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
Example #44
0
def checkIds(akv, skv, print_M=0):
    """
    Checks whether the provided keys are correct or not.
    akv is access key, akv is secret key.
    print_M is used for showing a message if keys were wrong.
    """
    flickr_api.set_keys(api_key=akv, api_secret=skv)
    try:
        flickr_api.Person.findByUserName('vicro_bot').id
    except flickr_api.flickrerrors.FlickrAPIError:
        if print_M: anim_write("Wrong Keys!!", "Try again")
        return 0
    return 1
Example #45
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()

	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
Example #46
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'))
Example #47
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
    def __init__(self, search_key='', image_dl_number=10, store_size=256):
        self.g_search_key=search_key
        
        self.api_key='2ec4736acee10664b81d64d5ae17a7a2'
        self.api_secret='cd8c4dd6946d5064'
        
        self.image_dl_number=image_dl_number
        
        self.folder='./image'
        self.gs_raw_dirpath=''

        self.store_size=store_size
        
        flickr_api.set_keys(api_key=self.api_key, api_secret=self.api_secret)
Example #49
0
def get_Photos(tag,num,sort):
    flickr_api.set_keys(**secrets)
    photos = flickr_api.Photo.search(tags=tag, sort=sort, per_page=num,extras='url_o')
    j = []
    for photo in photos:
        j.append(
            {
                'title': photo.title,
                'id':photo.id,
                'url': "https://www.flickr.com/photos/" + str(photo.owner.id) + "/" + str(photo.id),
                'd_url': "https://farm" + str(photo.farm) + ".staticflickr.com/" + str(photo.server) + "/" + str(photo.id) + "_" + str(photo.secret) + ".jpg"
            }
        )
    return j
Example #50
0
def search_max(term, maximum):
    try:
        maximum = int(maximum)
    except:
        flash("maximum must be integer, 10 results will be rendered", "error")
    flickr_api.set_keys(**secrets)
    write_to_sqs(term, "web")
    photos = flickr_api.Photo.search(tags=term,
                                     sort='date-posted-desc',
                                     per_page=maximum)
    return render_template('photos.html',
                           photos=photos,
                           maximum=maximum,
                           term=term)
Example #51
0
def main(username: str, local_dir: str, key: str, secret: str,
         number: int) -> None:
    """Downloads flickr images, optimizes them and creates markdown code"""
    print("YYYYYEAH")
    try:
        # pylint: disable=import-error
        import pelicanconf

        if not username and hasattr(pelicanconf, "FLICKR_USERNAME"):
            logger.debug(f"uses username: {pelicanconf.FLICKR_USERNAME}")
            username = pelicanconf.FLICKR_USERNAME

        if not local_dir and hasattr(pelicanconf, "FLICKR_IMAGE_PATH"):
            logger.debug(f"uses local_dir: {pelicanconf.FLICKR_IMAGE_PATH}")
            local_dir = pelicanconf.FLICKR_IMAGE_PATH

        if not key and hasattr(pelicanconf, "FLICKR_API_KEY"):
            logger.debug(f"uses key: {pelicanconf.FLICKR_API_KEY}")
            key = pelicanconf.FLICKR_API_KEY

        if not secret and hasattr(pelicanconf, "FLICKR_API_SECRET"):
            logger.debug(f"uses secret: {pelicanconf.FLICKR_API_SECRET}")
            secret = pelicanconf.FLICKR_API_SECRET

    except ModuleNotFoundError:
        pass

    if not username:
        username = click.prompt("flickr username")

    if not local_dir:
        local_dir = click.prompt("local dir")

    if not key:
        key = click.prompt("flickr api key")

    if not secret:
        secret = click.prompt("flickr api secret")

    flickr_api.set_keys(api_key=key, api_secret=secret)

    flickr_user = core.get_user(username, flickr_api)
    photos = core.get_latest_photos(flickr_user, number, Path(local_dir),
                                    flickr_api)
    core.download_n_optimize(photos)
    markdowns = [i.markdown for i in photos]

    click.secho("---BEGIN MARKDOWN---\n", bold=True)
    click.echo("\n\n".join(markdowns))
    click.secho("\n---END MARKDOWN---", bold=True)
Example #52
0
 def test_httpexception_fails(self, mock_urlopen):
     error = mock_urlopen.side_effect = BadStatusLine('nope')
     flickr_api.set_keys(api_key='test', api_secret='test')
     file_store = Mock()
     error_handler = ErrorHandler(StringIO())
     downloader = FlickrApiDownloader(file_store, error_handler)
     result = downloader.download(flickr.people.getPublicPhotos, {},
             lambda doc: doc,
             'ignored')
     self.assertIs(result, None)
     file_store.save_json.assert_not_called()
     params = {'nojsoncallback': 1, 'format': 'json'}
     self.assertIn((flickr.people.getPublicPhotos, params, error),
             error_handler.errors)
Example #53
0
def check_flickr(self):
    flickr.set_keys(api_key=settings.FLICKR_API_KEY, api_secret=settings.FLICKR_API_SECRET)

    # photos from photoset
    photoset = flickr.Photoset(id=settings.FLICKR_PHOTOSET_ID)
    photos_from_photoset = photoset.getPhotos(extras=['url_m', 'url_o'], media='photos')
    photos_from_photoset_to_save = [
        Photo(
            title=photo.title,
            flickr_id=photo.id,
            url_m=photo.url_m,
            url_o=photo.url_o,
        ) for photo in photos_from_photoset
    ]
    # photos by tag #int20h
    photos_by_tag = flickr.Photo.search(
        tags=settings.FLICKR_PARSE_TAG,
        extras=['url_m', 'url_o'],
        media='photos',
        per_page=500,
    )
    photos_by_tag_to_save = [
        Photo(
            title=photo.title,
            flickr_id=photo.id,
            url_m=photo.url_m,
            url_o=photo.url_o,
        ) for photo in photos_by_tag
    ]
    # merge two unsaved lists into one
    all_photos_to_save = photos_by_tag_to_save + photos_from_photoset_to_save

    # save to db preventing duplicates
    # we will need to wait for Django 2.2 to use bulk_create ignore_conflicts
    all_photos_to_save_flickr_ids = {photo.flickr_id for photo in all_photos_to_save}
    photos_already_exists_flickr_ids = set(
        Photo.objects.filter(
            flickr_id__in=list(all_photos_to_save_flickr_ids)
        ).values_list(
            'flickr_id', flat=True,
        )
    )
    # Note: we save flickr_id as integer in db
    new_photos_to_save = [
        photo for photo in all_photos_to_save if int(photo.flickr_id) not in photos_already_exists_flickr_ids
    ]
    Photo.objects.bulk_create(new_photos_to_save)

    return f'added: {len(new_photos_to_save)} Photos'
Example #54
0
def initialize_flickr_api(generator):
    if has_flickr_settings(generator):
        flickr_api.set_keys(generator.settings['FLICKR_KEY'],
                            generator.settings['FLICKR_SECRET'])
        if not 'FLICKR_EXTRA_PARAMS' in generator.settings:
            generator.settings['FLICKR_EXTRA_PARAMS'] = \
                {'extras': 'url_l, url_m'}
        if not 'FLICKR_MAX_HEIGHT' in generator.settings:
            generator.settings['FLICKR_MAX_HEIGHT'] = 768
        if not 'FLICKR_MAX_WIDTH' in generator.settings:
            generator.settings['FLICKR_MAX_WIDTH'] = 1024
        if not 'FLICKR_THUMBNAIL_MAX_HEIGHT' in generator.settings:
            generator.settings['FLICKR_THUMBNAIL_MAX_HEIGHT'] = 480
        if not 'FLICKR_THUMBNAIL_MAX_WIDTH' in generator.settings:
            generator.settings['FLICKR_THUMBNAIL_MAX_WIDTH'] = 640
Example #55
0
def get_verifier_url():
    if request.method == 'GET':
        key = request.args.get('api_key')
        secret = request.args.get('api_secret')
        flickr_api.set_keys(api_key=str(key), api_secret=str(secret))
        a = flickr_api.auth.AuthHandler()
        perms = "read"
        url = a.get_authorization_url(perms)
        print url
        the_stuff = a.todict()
        print the_stuff
        session['request_token_key'] = the_stuff['request_token_key']
        session['request_token_secret'] = the_stuff['request_token_secret']

        return jsonify({'url': url})
Example #56
0
    def test_httpexception(self, mock_do_open):
        import flickr_api
        from flickr_api.api import flickr

        sets = [{'id': '1', 'secret': '2'}]
        error = mock_do_open.side_effect = BadStatusLine('nope')
        flickr_api.set_keys(api_key='test', api_secret='test')
        file_store = Mock()
        error_handler = ErrorHandler(StringIO())
        downloader = FlickrApiDownloader(file_store, error_handler)
        download_set_photolists(sets, downloader, flickr, 2)
        file_store.save_json.assert_not_called()
        params = {'nojsoncallback': 1, 'format': 'json', 'page': 1,
                'per_page': 2, 'photoset_id': '1'}
        self.assertIn((flickr.photosets.getPhotos, params, error),
                error_handler.errors)
Example #57
0
def search_flickr_for_images(text):
    flickr_api.set_keys(api_key=api_key, api_secret=api_secret)
    photos = []
    try:
        photo_search = Walker(Photo.search, text=text)
    except Exception as e:
        dpr(e)
        abort(503)
    for photo in photo_search[:16]:
        url = photo.getSizes()["Medium"]["source"]
        photos.append({
            "url": url,
            "title": photo.title.encode('ascii', 'replace'),
            "id": photo.id,
            })
    return photos
Example #58
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