예제 #1
0
 def __init__(self, path=None, id=None, original_path=None):
     if path is not None and id is not None and original_path is not None:
         self.create(path, id, original_path)
     elif path is not None and id is None and original_path is None:
         self.open(path)
     self.flickr_capable = False
     Flickr.__init__(self)
예제 #2
0
 def __init__(self, path=None, id=None, original_path=None):
     if path is not None and id is not None and original_path is not None:
         self.create(path, id, original_path)
     elif path is not None and id is None and original_path is None:
         self.open(path)
     self.flickr_capable = False
     Flickr.__init__(self)
예제 #3
0
파일: airframe.py 프로젝트: puwkin/airframe
 def flickr_mode(self):
     # Connect to Flickr
     logging.debug("list of tags: %s" % self.photo_tags)
     self.flickr = Flickr()
     if len(self.photo_tags) > 0:
         photo_filenames = self.flickr.get_tagged(self.photo_tags, self.photo_count, download_dir=self.download_dir)
     else:
         photo_filenames = self.flickr.get_recent(self.photo_count,download_dir=self.download_dir)
     return photo_filenames
예제 #4
0
파일: auth.py 프로젝트: mikeboers/PyFlickr
 def do_auth_return(self, environ, start):
     verifier = self.args['oauth_verifier']
     self.token, self.userdata = self.flickr.get_access_token(self.request_token, verifier)
     print 'ACCESS TOKEN:', self.token
     print 'USERDATA:',
     pprint(self.userdata)
     self.flickr = Flickr(key, secret, self.token, format='json')
     start('303 See Other', [('Location', '/recent')])
     return ['']
예제 #5
0
def generateJSON(year, month, metric):
    data = Flickr.parse_interface_flickr(year, month, metric)
    n = ('"'+"Popular Flickr pictures for " + months[month-1]+" "+str(year)+'"')
    s = data["status"]
    pos_data_name = data["data"]["name"]
    pos_data = data["data"]["data"]
    result = '    "name": '+n+',\n'
    result = result + '    "status": ' + str(s)+',\n'
    result = result + '    "pos_data": {\n'
    result = result + '        "name":' + pos_data_name +',\n'
    result = result + '        "data":' + str(pos_data) +',\n'
    result = result + '    }\n'
    return result
예제 #6
0
  def setUp(self):
    super(CronTest, self).setUp()
    oauth_dropins.appengine_config.FLICKR_APP_KEY = 'my_app_key'
    oauth_dropins.appengine_config.FLICKR_APP_SECRET = 'my_app_secret'

    flickr_auth = oauth_flickr.FlickrAuth(
      id='123@N00', user_json=json.dumps(test_flickr.PERSON_INFO),
      token_key='my_key', token_secret='my_secret')
    flickr_auth.put()
    self.flickr = Flickr.new(None, auth_entity=flickr_auth, features=['listen'])
    self.assertEquals(
      'https://farm5.staticflickr.com/4068/buddyicons/[email protected]',
      self.flickr.picture)
예제 #7
0
  def setUp(self):
    super(CronTest, self).setUp()
    oauth_dropins.appengine_config.FLICKR_APP_KEY = 'my_app_key'
    oauth_dropins.appengine_config.FLICKR_APP_SECRET = 'my_app_secret'
    oauth_dropins.appengine_config.TWITTER_APP_KEY = 'my_app_key'
    oauth_dropins.appengine_config.TWITTER_APP_SECRET = 'my_app_secret'

    flickr_auth = oauth_flickr.FlickrAuth(
      id='123@N00', user_json=json.dumps(test_flickr.PERSON_INFO),
      token_key='my_key', token_secret='my_secret')
    flickr_auth.put()
    self.flickr = Flickr.new(None, auth_entity=flickr_auth, features=['listen'])
    self.assertEquals(
      'https://farm5.staticflickr.com/4068/buddyicons/[email protected]',
      self.flickr.picture)
예제 #8
0
파일: test_cron.py 프로젝트: snarfed/bridgy
  def _setup_flickr(self):
    """Creates and test :class:`Flickr` entities."""
    flickrs = []

    for id, features in (('123@N00', ['listen']), ('456@N11', [])):
      info = copy.deepcopy(test_flickr.PERSON_INFO)
      info['person']['nsid'] = id
      flickr_auth = oauth_dropins.flickr.FlickrAuth(
        id=id, user_json=json_dumps(info),
        token_key='my_key', token_secret='my_secret')
      flickr_auth.put()
      flickr = Flickr.new(auth_entity=flickr_auth, features=features)
      flickr.put()
      flickrs.append(flickr)

    return flickrs
예제 #9
0
def home():
    templates = {'home': 'home.html', 'serp': 'serp.html'}
    template = templates.get('home')
    context = {
        'data': {
            'title': '',
            'link': '',
            'description': '',
            'modified': '',
            'generator': '',
            'items': [],
        }
    }
    query = request.args.get('q', '')
    params = {'format': 'json', 'tagmode': 'all'}

    if query:
        template = templates.get('serp')
        context['query'] = query
        params['tags'] = query
        params['tagmode'] = 'any'

    context['data'] = Flickr().public_feed(params)
    return render_template(template, **context)
예제 #10
0
def getImage(location, service='flickr'):

    returnJson = {}

    print(" 1. my token is " + request.get_cookie("insta_auth_token"))

    if service == 'flickr':
        ps = Flickr()
    elif service == 'insta':
        ps = Instagram()
    print("2. my token is " + request.get_cookie("insta_auth_token"))

    print("GETTING SHIT")
    ps.photo_lookup(location)
    print(" 3. my token is " + request.get_cookie("insta_auth_token"))
    photo = ps.get_next_photo()
    print(" 4. my token is " + request.get_cookie("insta_auth_token"))
    print(photo)

    return json.dumps(photo)
예제 #11
0
파일: auth.py 프로젝트: mikeboers/PyFlickr
 def __init__(self):
     self.token = None
     self.flickr = Flickr(key, secret, format='json')
     self.request_token = self.flickr.get_request_token('http://%s/auth_return' % hostname)
     print 'REQUEST TOKEN:', self.request_token
예제 #12
0
파일: auth.py 프로젝트: mikeboers/PyFlickr
class WSGIApp(object):
    
    def __init__(self):
        self.token = None
        self.flickr = Flickr(key, secret, format='json')
        self.request_token = self.flickr.get_request_token('http://%s/auth_return' % hostname)
        print 'REQUEST TOKEN:', self.request_token
    
    def __call__(self, environ, start):
        func_name = 'do_' + (
            environ.get('PATH_INFO', '').strip('/').replace('/', '__') or
            'index'
        )
        func = getattr(self, func_name, None)
        if not func:
            start('404 Not Found', [])
            return ['Not found.']
        fs = cgi.FieldStorage(environ=environ)
        self.args = args = {}
        for key in fs:
            args[key] = fs.getvalue(key)
        return func(environ, start)
        
    
    def do_index(self, environ, start):
        start('200 OK', [('Content-Type', 'text/html')])
        if not self.token:
            return [
                '''<html><body><a href="%s">Authorize with flickr.</a><br/>''' %
                self.flickr.get_auth_url(self.request_token)
            ]

        return ['''hi''']
    
    def do_interesting(self, environ, start):
        start('200 OK', [('Content-Type', 'text/html')])
        yield '<html><body>'
            
        one_day = datetime.timedelta(days=1)
        date = datetime.date.today()
        limit = int(self.args.get('n', 100))

        found = 0
        while found < limit:
            date -= one_day
            for photo in flickr.interestingness.getList.iter(date=str(date), extras='license', per_page=limit):
                if photo['license'] == '0':
                    continue
                found += 1

                src = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s_s.jpg' % photo
                url = short_url(photo['id'])
                yield str('<a href="%s"><img src="%s" /></a>' % (url, src))
                
                if found == limit:
                    break
                    
    def do_auth_return(self, environ, start):
        verifier = self.args['oauth_verifier']
        self.token, self.userdata = self.flickr.get_access_token(self.request_token, verifier)
        print 'ACCESS TOKEN:', self.token
        print 'USERDATA:',
        pprint(self.userdata)
        self.flickr = Flickr(key, secret, self.token, format='json')
        start('303 See Other', [('Location', '/recent')])
        return ['']
    
    def do_recent(self, environ, start):
        start('200 OK', [('Content-Type', 'text/html')])
        yield '<html><body>'
        for photo in self.flickr.people.getPhotos.iter(user_id=self.userdata['user_nsid'], per_page=25):
            src = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s_s.jpg' % photo
            url = short_url(photo['id'])
            yield str('<a href="%s"><img src="%s" /></a>' % (url, src))
예제 #13
0
파일: airframe.py 프로젝트: puwkin/airframe
class AirFrame(object):

    def __init__(self):
        pass

    def _parse_csv_list(self, s):
        try:
            assert isinstance(s,str)
            s = s.strip()
            value_list = s.split(',')
        except:
            raise argparse.ArgumentTypeError("Could not parse tag list")
        return value_list

    def get_options(self, argv):
        """
            Parse the command-line options and set the following object properties:

            I really need to convert this to use docopt!

            :param argv: usually just sys.argv[1:]
            :returns: Nothing

            :ivar debug: Enable logging debug statements
            :ivar verbose: Enable verbose logging
        """
        p = argparse.ArgumentParser(
                description = "Push pictures from Flickr, Facebook or local files to a Toshiba FlashAir automatically",
                epilog = "AirFrame version %s (Copyright 2014 Virantha Ekanayake)" % __version__,
                )

        p.add_argument('-b', '--facebook', action='store_true',
            default=False, help='Upload pictures from Flickr to Flashair')

        p.add_argument('-r', '--flickr', action='store_true',
            default=True, help='Upload pictures from Facebook to Flashair (default)')

        p.add_argument('-l', '--local-dir', type=str,
            help='Upload all .jpg files from this directory instead of Flickr or Facebook')
        
        p.add_argument('-s', '--resize', type=str,
            help='Resize all images to fit in this box (e.g. 1024x768) before uploading them to Flashair')

        p.add_argument('-d', '--debug', action='store_true',
            default=False, dest='debug', help='Turn on debugging')

        p.add_argument('-v', '--verbose', action='store_true',
            default=False, dest='verbose', help='Turn on verbose mode')

        p.add_argument('-f', '--force', action='store_true',
            default=False, help='Force upload of all pictures to Flashair (instead of only new pictures)')

        p.add_argument('-n', '--number', type=int,
            default=100, dest='number', help='Max number of photos to sync')

        p.add_argument('-t', '--tags', type=self._parse_csv_list,
                default=[], dest='tags', help='List of Flickr tags to match')

        p.add_argument('flashair_ip', type=str,
                        help='The ip/hostname of your FlashAir card')


        args = p.parse_args(argv)

        self.debug = args.debug
        self.verbose = args.verbose
        self.photo_count = args.number
        self.photo_tags = args.tags
        self.force_upload = args.force
        self.flashair_ip = args.flashair_ip
        self.local_dir = args.local_dir
        self.resize = args.resize
        self.facebook = args.facebook
        self.flickr = args.flickr

        if self.debug:
            logging.basicConfig(level=logging.DEBUG, format='%(message)s')

        if self.verbose:
            logging.basicConfig(level=logging.INFO, format='%(message)s')

    def flickr_mode(self):
        # Connect to Flickr
        logging.debug("list of tags: %s" % self.photo_tags)
        self.flickr = Flickr()
        if len(self.photo_tags) > 0:
            photo_filenames = self.flickr.get_tagged(self.photo_tags, self.photo_count, download_dir=self.download_dir)
        else:
            photo_filenames = self.flickr.get_recent(self.photo_count,download_dir=self.download_dir)
        return photo_filenames

    def facebook_mode(self):
        # Connect to Facebook
        logging.debug("list of tags: %s" % self.photo_tags)
        self.facebookphotos = FacebookPhotos()
#        if len(self.photo_tags) > 0:
#            photo_filenames = self.flickr.get_tagged(self.photo_tags, self.photo_count, download_dir=self.download_dir)
#        else:
#            photo_filenames = self.flickr.get_recent(self.photo_count,download_dir=self.download_dir)
        photo_filenames = self.facebookphotos.get_recent(self.photo_count,download_dir=self.download_dir)
        return photo_filenames

    def local_dir_mode(self):
        # Copy all the files in the named directory to the cache (download_dir).
        # completely replaces both the local cached files and the ones on the 
        # wifi sd card
        pattern = '/*.[jJ][pP][gG]'
        match = self.local_dir + pattern
        
        if os.path.isdir(self.download_dir):
            logging.debug("removing existing cache dir: %s", self.download_dir)
            shutil.rmtree(self.download_dir)
        
        os.mkdir(self.download_dir)
        logging.debug("caching files from: %s" % match)
        photo_filenames = glob.glob(match)
        for filename in photo_filenames:
            logging.debug("copy %s to %s" % (filename, self.download_dir))
            shutil.copy(filename, self.download_dir)
        return photo_filenames    

    def resize_pictures(self, photo_filenames):
        print 'Resizing images...'
        size = self.resize.split('x')
        size = [int(x) for x in tuple(size)]
        for infile in photo_filenames:
            im = Image.open(infile)
            if im.size[0] > size[0] or im.size[1] > size[1]:
                im.thumbnail(size, Image.ANTIALIAS)
                im.save(infile)
            im.close()


    def go(self, argv):
        self.download_dir = ".airframe"
        self.get_options(argv)

        if self.local_dir:
            photo_filenames = self.local_dir_mode()
        elif self.facebook:
            photo_filenames = self.facebook_mode()
        else:
            photo_filenames = self.flickr_mode()

        if self.resize:
            self.resize_pictures(photo_filenames)

        self.flashair = FlashAir(self.flashair_ip)
        self.flashair.sync_files_on_card_to_list(photo_filenames, self.force_upload)
예제 #14
0
    {'start': '2015-08-1', 'end': '2015-09-1'},
    {'start': '2015-11-1', 'end': '2016-12-1'}
]

places = [
    {'name': "NewYork", 'id': ".skCPTpTVr.Q3WKW"},
    {'name': "Boston", 'id': "5MvaTZJTUbx1uPnP"},
    {'name': "Beijing", 'id': "vQ6vOjpTU7_QE6S8"},
    {'name': "Hongkong", 'id': "JAJiM7JTU78IjzqC"}
]

results = {}
for place in places:
    place_results = results[place.get('name')] = {}
    for time in times:
        query = Flickr({
            'place_id': place.get('id'),
            'sort': 'interestingness-desc',
            'per_page': 100,
            # 'text': 'landscape',
            'min_taken_date': parseTime(time.get('start')),
            'max_taken_date': parseTime(time.get('end'))
        })
        # place_results[time.get('start')] = query.results
        # The above yields a lot of unused json. Below just the title, and image url.
        place_results[time.get('start')] = [{'title': r.get('title'),'url': r.get('url')} for r in query.results]



with open("kini.json", 'w') as outfile:
    json.dump(results, outfile, indent=4, sort_keys=True)
예제 #15
0
import os
from flickr import Flickr
from lxml.etree import tostring
from pprint import pprint
from subprocess import call

key = os.environ.get('FLICKR_KEY')
secret = os.environ.get('FLICKR_SECRET')
if not (key and secret):
    print 'please set FLICKR_KEY and FLICKR_SECRET'
    exit(1)

flickr = Flickr(key, secret, format='json')

if False:
    
    pprint(flickr.test.echo())
    
if True:
    token = flickr.get_request_token('http://localhost')
    print token

    auth_url = flickr.get_auth_url(token)
    print auth_url

    call(['open', auth_url])
    exit()

if False:
    
    oauth_token='oauth_callback_confirmed=true&oauth_token=72157627056318817-bb00258df35ad251&oauth_token_secret=da781ef84d3c5727'