Example #1
0
def download_all(count_of_eshops=30, req=None):
    """
    A function for downloading it all-at-once.

    :param RequestHelper req: a Request helper class to be passed
    :param int count_of_eshops: Number of eshops to include.
    :return pandas.DataFrame: Data frame with all the data
    """

    # we run the Heureka first
    h = Heureka(req=req)
    h.run(count_of_eshops)

    # then we find the instagram links on the eshop's webpages
    e = EshopWebsite(req=req)
    e.run([shop['link'] for shop in h.output])

    # then use the information from web pages to collect instagram accounts
    i = Instagram(req=req)
    i.run([shop['instagram'] for shop in e.output if shop['instagram']])

    # here we create DataFrames
    df_h = pd.DataFrame(h.output).set_index('link')
    df_e = pd.DataFrame(e.output).set_index('url')
    df_i = pd.DataFrame(i.output).set_index('account')
    df_all = df_h.join(pd.merge(df_e, df_i, left_on='instagram', right_index=True))

    # and return the merged DataFrame
    return df_all
Example #2
0
class Application:
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.instagram = Instagram(username, password)
        self.logged_in = False

    def exit_application(self):
        if self.logged_in:
            self.instagram.logout()

    def thread_list(self, sleep_time=2):
        next_page = ''
        while True:
            time.sleep(sleep_time)

            direct = self.instagram.direct_list(next_page=next_page)
            if direct:
                items = direct['inbox']['threads']
                for item in items:
                    yield item['thread_title']

                if not direct['inbox']['has_older']:
                    return

                next_page = direct['inbox']['oldest_cursor']

    def run(self):
        if not self.instagram.login():
            self.exit_application()
            return

        self.logged_in = True
        for thread_name in self.thread_list():
            print thread_name
Example #3
0
def unfollow(instagram: Instagram, utils: Utils,
             pending_unfollows: dict) -> None:
    """Takes a dict of users and gets the accounts to unfollow using selenium webdriver"""

    unfollow_left = pending_unfollows[instagram.username]
    for i in range(len(unfollow_left)):
        user = unfollow_left.pop()
        try:
            link = instagram.create_link(user)
            instagram.unfollow(link)
            seconds = random.randint(15, 30)
            time.sleep(seconds)
        except KeyboardInterrupt:
            pending_unfollows[instagram.username] = unfollow_left
            save_users_left(instagram, utils, pending_unfollows,
                            config.UNFOLLOW_LEFT_PATH)
            close(instagram)

        except Exception as e:
            print(f"Following error appear when visiting {user}:\n{e}")
            seconds = random.randint(5, 10)
            time.sleep(seconds)
            continue

        if (i + 1) % 10 == 0:
            print(f"You have unfollowed {i+1} accounts")
Example #4
0
def like_comment_photos(instagram: Instagram,
                        utils: Utils,
                        photos: list,
                        user: str,
                        comment: bool = True) -> None:
    liked = 0
    commented = 0
    if photos:
        for photo in photos:
            instagram.like_photo(photo)
            liked += 1
            utils.insert_photos(photo, instagram.username)
            time.sleep(3)
            comment_true = random.randint(1, 4)

            if comment and (comment_true == 1):
                instagram.comment(config.COMMENTS, photo)
                seconds = random.randint(3, 10)
                time.sleep(seconds)
                commented += 1

        utils.insert_followed_or_visited_account("Visited", user,
                                                 instagram.username, liked)
        conn.commit()
        print(f"You commented {commented} and liked {liked} photos on {user}")
    else:
        utils.insert_followed_or_visited_account("Visited", user,
                                                 instagram.username, 0)
Example #5
0
 def source_query(self):
   now = util.now_fn()
   since_sun = (now.weekday() * datetime.timedelta(days=1) +
                (now - now.replace(hour=0, minute=0, second=0)))
   batch = float(Instagram.query().count()) / self.BATCH
   offset = batch * float(since_sun.total_seconds()) / self.FREQUENCY.total_seconds()
   return Instagram.query().fetch(offset=int(math.floor(offset)),
                                  limit=int(math.ceil(batch)))
Example #6
0
 def source_query(self):
   now = util.now_fn()
   since_sun = (now.weekday() * datetime.timedelta(days=1) +
                (now - now.replace(hour=0, minute=0, second=0)))
   batch = float(Instagram.query().count()) / self.BATCH
   offset = batch * float(since_sun.total_seconds()) / self.FREQUENCY.total_seconds()
   return Instagram.query().fetch(offset=int(math.floor(offset)),
                                  limit=int(math.ceil(batch)))
Example #7
0
def unfollowPoster(ig: Instagram, shortcode: str):
    x = ig.getPostInfo(shortcode)
    sleep(5)

    user = x['username']
    ig.unfollowUser(user)
    print(
        f'āˆ˜ [{getTimeStamp()}] Unfollowed {user} | https://www.instagram.com/{user}'
    )
Example #8
0
def likePost(ig: Instagram, data: dict):
    ig.likePost(data['id'])
    mediaType = 'video' if data['is_video'] else 'image'
    shortcode = data['shortcode']
    print(
        f'āˆ˜ [{getTimeStamp()}] Liked {mediaType} | https://www.instagram.com/p/{shortcode}'
    )

    LIKE_STEP = random.randint(2, 4)
Example #9
0
 def get(self):
     instagram = Instagram()
     result = instagram.get_news()
     path = base.set_template('news')
     session = get_current_session()
     self.response.out.write(template.render(path, {
         'items'     : result['items'][0]['updates'],
         'user'      : instagram.get_user_info(session['ds_user_id']),
         'followings': instagram.get_following(session['ds_user_id'])['users'],
         'login'     : True }))
Example #10
0
def followPoster(ig: Instagram, shortcode: str):
    x = ig.getPostInfo(shortcode)
    sleep(5)

    user = x['username']
    ig.followUser(user)
    print(
        f'āˆ˜ [{getTimeStamp()}] Followed {user} | https://www.instagram.com/{user}'
    )

    FOLLOW_STEP = random.randint(14, 20)
Example #11
0
def commentPost(ig: Instagram, data: dict):
    if len(config.COMMENTS) <= 0:
        return

    c = random.choice(config.COMMENTS)
    ig.postComment(data['id'], c)
    shortcode = data['shortcode']
    print(
        f'āˆ˜ [{getTimeStamp()}] Posted comment | https://www.instagram.com/p/{shortcode}'
    )

    COMMENT_STEP = random.randint(13, 15)
Example #12
0
 def __init__(self, username):
     config = ConfigParser.ConfigParser()
     config.read('./config.properties')
     self.pinterest = Pinterest(username, config)
     self.googleplus = GooglePlus(username, config)
     self.youtube = YouTube(username, config)
     self.twitch = Twitch(username, config)
     self.vimeo = Vimeo(username, config)
     self.behance = Behance(username, config)
     self.instagram = Instagram(username, config)
     self.twitter = Twitter(username, config)
     self.github = Github(username, config)
     self.dict = dict()
Example #13
0
def main():

    if len(sys.argv) < 2:
        fname = "Instagram_THORNAPPLE_2020-02-05~2020-02-05.json"
    else:
        fname = sys.argv[1]

    with open(fname, "r", encoding="utf-8") as f:
        data = json.loads(f.read())

    i = Instagram()
    analysed = i.analyse(data)

    pprint.pprint(analysed)
def index(url=None, error=None, media=None):

    if request.method == 'POST':
        try:
            data = Instagram(request.form["url"])
            media = data.get_download_url()
        except Exception as e:
            error = e

    return render_template("index.html",
                           method=request.method,
                           url=url,
                           error=error,
                           media=media)
Example #15
0
    def __init__(self):
        self.bot = Instagram()

        self.window = tk.Tk()

        self.window.title("Instagram bot")
        self.window.geometry("900x100")
        #self.window.iconbitmap('instagram.png')
        self.window.resizable(0, 0)

        self.window.config(bg="#E6E6FA")

        self.create_widgets()

        self.window.mainloop()
Example #16
0
    def __init__(self, username, password, thread_name, output_dir,
                 debug_mode=False):
        self.username = username
        self.password = password
        self.selected_thread_name = thread_name
        self.logged_in = False
        self.debug_mode = debug_mode
        self.media_folder = output_dir
        self.instagram = Instagram(username, password, debug_mode=debug_mode)
        self.selected_thread_id = ''

        if not os.path.exists(output_dir):
            os.mkdir(output_dir, 0755)

        self.dump_file = open(os.path.join(output_dir, 'dump_file.csv'), 'wb')
        self.csv_handler = csv.writer(self.dump_file, delimiter=',', quotechar='|')
Example #17
0
class Interface:
    def __init__(self):
        self.bot = Instagram()

        self.window = tk.Tk()

        self.window.title("Instagram bot")
        self.window.geometry("900x100")
        #self.window.iconbitmap('instagram.png')
        self.window.resizable(0, 0)

        self.window.config(bg="#E6E6FA")

        self.create_widgets()

        self.window.mainloop()

    def create_widgets(self):
        self.linkentry = tk.Entry(self.window, font=("Courrier", 20))
        self.linkentry.place(relx=0.001, rely=0.1, relwidth=0.8, relheight=0.8)

        self.click = tk.Button(
            self.window,
            text="Click",
            font=("Courrier", 15),
            command=lambda: self.bot.FollowLiker(self.linkentry.get()))
        self.click.place(relx=0.81, rely=0.1, relwidth=0.18, relheight=0.8)
Example #18
0
 def test_get_activities_response(self):
   """Check that min_id is discarded."""
   inst = Instagram.new(self.handler, auth_entity=self.auth_entity)
   self.mox.StubOutWithMock(inst.as_source.api, 'user_recent_media')
   inst.as_source.api.user_recent_media('self').AndReturn(([], {}))
   self.mox.ReplayAll()
   assert inst.get_activities_response(min_id='123')
Example #19
0
  def test_update_instagram_pictures(self):
    for username in 'a', 'b':
      profile = copy.deepcopy(test_instagram.HTML_PROFILE)
      profile['entry_data']['ProfilePage'][0]['user'].update({
        'username': username,
        'profile_pic_url': 'http://new/pic',
        })
      super(HandlerTest, self).expect_requests_get(
        gr_instagram.HTML_BASE_URL + '%s/' % username,
        test_instagram.HTML_HEADER + json.dumps(profile) + test_instagram.HTML_FOOTER,
        allow_redirects=False)
    self.mox.ReplayAll()

    sources = []
    auth_entity = indieauth.IndieAuth(id='http://foo.com/', user_json='{}')
    for username in 'a', 'b', 'c', 'd':
      source = Instagram.new(
        None, auth_entity=auth_entity, features=['listen'],
        actor={'username': username, 'image': {'url': 'http://old/pic'}})
      # test that we skip disabled and deleted sources
      if username == 'c':
        source.status = 'disabled'
      elif username == 'd':
        source.features = []
      sources.append(source.put())

    resp = cron.application.get_response('/cron/update_instagram_pictures')
    self.assertEqual(200, resp.status_int)

    self.assertEquals('http://new/pic', sources[0].get().picture)
    self.assertEquals('http://new/pic', sources[1].get().picture)
    self.assertEquals('http://old/pic', sources[2].get().picture)
    self.assertEquals('http://old/pic', sources[3].get().picture)
Example #20
0
    def test_post_merge_comments(self):
        source = Instagram.create_new(self.handler, actor={'username': '******'})

        # existing activity with one of the two comments in HTML_VIDEO_COMPLETE
        existing_activity = copy.deepcopy(HTML_VIDEO_ACTIVITY)
        existing_activity['object']['replies'] = {
            'totalItems': 1,
            'items': [COMMENT_OBJS[0]],
        }
        activity_key = Activity(
            id='tag:instagram.com,2013:789_456',
            activity_json=json_dumps(existing_activity)).put()

        # send HTML_VIDEO_COMPLETE to /post, check that the response and stored
        # activity have both of its comments
        resp = app.application.get_response(
            '/instagram/browser/post?token=towkin',
            method='POST',
            text=HTML_VIDEO_COMPLETE)

        self.assertEqual(200, resp.status_int, resp.text)
        self.assert_equals(HTML_VIDEO_ACTIVITY_FULL, resp.json)

        activity = activity_key.get()
        self.assert_equals(HTML_VIDEO_ACTIVITY_FULL,
                           json_loads(activity.activity_json))
Example #21
0
async def on_message(message):
    if message.content.startswith('!insta'):
        names = message.content.split(' ')[1:]
        for name in names:
            try:
                bio = Instagram(name).bio
                cursor.execute(
                    '''INSERT INTO bios VALUES(
                                ?,
                                ?
               );''', (name, bio))
                connection.commit()
                await bot.send_message(
                    message.channel,
                    '%s was added to the monitoring ' % (name))

            except:
                await bot.send_message(
                    message.channel,
                    "Sorry I couldn't find a user by the name %s" % (name))

    elif message.content.startswith('!remove'):
        names = message.content.split(' ')[1:]
        for name in names:
            cursor.execute('''DELETE FROM bios WHERE name=?;''', (name, ))
            await bot.send_message(message.channel,
                                   '%s was removed successfully' % name)
Example #22
0
    def test_update_instagram_picture_profile_404s(self):
        self.setup_instagram(batch_size=1)

        auth_entity = indieauth.IndieAuth(id='http://foo.com/', user_json='{}')
        source = Instagram.new(None,
                               auth_entity=auth_entity,
                               features=['listen'],
                               actor={
                                   'username': '******',
                                   'image': {
                                       'url': 'http://old/pic'
                                   }
                               })
        source.put()

        super(HandlerTest,
              self).expect_requests_get(gr_instagram.HTML_BASE_URL + 'x/',
                                        status_code=404,
                                        allow_redirects=False)
        self.mox.ReplayAll()

        resp = tasks.application.get_response(
            '/cron/update_instagram_pictures')
        self.assertEqual(200, resp.status_int)
        self.assertEqual('http://old/pic', source.key.get().picture)
Example #23
0
  def test_update_instagram_pictures(self):
    for username in 'a', 'b':
      profile = copy.deepcopy(test_instagram.HTML_PROFILE)
      profile['entry_data']['ProfilePage'][0]['user'].update({
        'username': username,
        'profile_pic_url': 'http://new/pic',
        })
      super(HandlerTest, self).expect_requests_get(
        gr_instagram.HTML_BASE_URL + '%s/' % username,
        test_instagram.HTML_HEADER + json.dumps(profile) + test_instagram.HTML_FOOTER,
        allow_redirects=False)
    self.mox.ReplayAll()

    sources = []
    auth_entity = indieauth.IndieAuth(id='http://foo.com/', user_json='{}')
    for username in 'a', 'b', 'c', 'd':
      source = Instagram.new(
        None, auth_entity=auth_entity, features=['listen'],
        actor={'username': username, 'image': {'url': 'http://old/pic'}})
      # test that we skip disabled and deleted sources
      if username == 'c':
        source.status = 'disabled'
      elif username == 'd':
        source.features = []
      sources.append(source.put())

    resp = cron.application.get_response('/cron/update_instagram_pictures')
    self.assertEqual(200, resp.status_int)

    self.assertEquals('http://new/pic', sources[0].get().picture)
    self.assertEquals('http://new/pic', sources[1].get().picture)
    self.assertEquals('http://old/pic', sources[2].get().picture)
    self.assertEquals('http://old/pic', sources[3].get().picture)
Example #24
0
    def test_update_instagram_pictures(self):
        self.setup_instagram(batch_size=1)
        for username in 'a', 'b':
            self.expect_instagram_profile_fetch(username)
        self.mox.ReplayAll()

        sources = []
        auth_entity = indieauth.IndieAuth(id='http://foo.com/', user_json='{}')
        for username in 'a', 'b', 'c', 'd':
            source = Instagram.new(None,
                                   auth_entity=auth_entity,
                                   features=['listen'],
                                   actor={
                                       'username': username,
                                       'image': {
                                           'url': 'http://old/pic'
                                       }
                                   })
            # test that we skip disabled and deleted sources
            if username == 'c':
                source.status = 'disabled'
            elif username == 'd':
                source.features = []
            sources.append(source.put())

        resp = cron.application.get_response('/cron/update_instagram_pictures')
        self.assertEqual(200, resp.status_int)

        self.assertEquals('http://new/pic', sources[0].get().picture)
        self.assertEquals('http://new/pic', sources[1].get().picture)
        self.assertEquals('http://old/pic', sources[2].get().picture)
        self.assertEquals('http://old/pic', sources[3].get().picture)
Example #25
0
  def test_update_instagram_pictures(self):
    for username in 'a', 'b':
      self.expect_urlopen(
        'https://api.instagram.com/v1/users/self?access_token=token',
        json.dumps({'data': {'id': username,
                             'username': username,
                             'full_name': 'Ryan Barrett',
                             'profile_picture': 'http://new/pic',
                           }}))
    self.mox.ReplayAll()

    sources = []
    for username in 'a', 'b', 'c', 'd':
      auth_entity = oauth_instagram.InstagramAuth(
        id=username, auth_code='code', access_token_str='token',
        user_json=json.dumps({'username': username,
                              'full_name': 'Ryan Barrett',
                              'profile_picture': 'http://old/pic',
                            }))
      auth_entity.put()
      source = Instagram.new(None, auth_entity=auth_entity, features=['listen'])
      # test that we skip disabled and deleted sources
      if username == 'c':
        source.status = 'disabled'
      elif username == 'd':
        source.features = []
      sources.append(source.put())

    resp = cron.application.get_response('/cron/update_instagram_pictures')
    self.assertEqual(200, resp.status_int)

    self.assertEquals('http://new/pic', sources[0].get().picture)
    self.assertEquals('http://new/pic', sources[1].get().picture)
    self.assertEquals('http://old/pic', sources[2].get().picture)
    self.assertEquals('http://old/pic', sources[3].get().picture)
Example #26
0
    def test_update_instagram_pictures_batch(self):
        self.setup_instagram(weekday=3)
        self.expect_instagram_profile_fetch('d')
        self.mox.ReplayAll()

        sources = []
        auth_entity = indieauth.IndieAuth(id='http://foo.com/', user_json='{}')
        for username in 'a', 'b', 'c', 'd', 'e', 'f', 'g':
            source = Instagram.new(None,
                                   auth_entity=auth_entity,
                                   features=['listen'],
                                   actor={
                                       'username': username,
                                       'image': {
                                           'url': 'http://old/pic'
                                       }
                                   })
            sources.append(source.put())

        resp = cron.application.get_response('/cron/update_instagram_pictures')
        self.assertEqual(200, resp.status_int)

        for i, source in enumerate(sources):
            self.assertEqual('http://new/pic' if i == 3 else 'http://old/pic',
                             source.get().picture)
Example #27
0
def new_session(instagram: Instagram, utils: Utils) -> Dict[str, set]:
    """Asks for an instagram account and number of followers. Then, visits
    the account and return the amount of followers in a set.

    Note: It avoids accounts that we already follow"""

    new_user = input(
        "Write the username from where you want to get the followers: ")
    amount = input("Write the amount of followers to get: ")
    amount = int(amount)

    following = utils.select_followees("Following", instagram.username)
    visited = utils.select_followees("Visited", instagram.username)

    union = following.union(visited)

    print("Getting new accounts, please wait...")
    users_left = instagram.get_followers(new_user, amount)
    users_left = users_left.difference(union)

    print(f"{len(users_left)} to check")

    pending_users_left = dict()
    pending_users_left[instagram.username] = users_left

    return pending_users_left
Example #28
0
  def test_update_instagram_pictures(self):
    self.setup_instagram(batch_size=1)
    for username in 'a', 'b':
      self.expect_instagram_profile_fetch(username)
    self.mox.ReplayAll()

    sources = []
    auth_entity = indieauth.IndieAuth(id='http://foo.com/', user_json='{}')
    for username in 'a', 'b', 'c', 'd':
      source = Instagram.new(
        None, auth_entity=auth_entity, features=['listen'],
        actor={'username': username, 'image': {'url': 'http://old/pic'}})
      # test that we skip disabled and deleted sources
      if username == 'c':
        source.status = 'disabled'
      elif username == 'd':
        source.features = []
      sources.append(source.put())

    resp = cron.application.get_response('/cron/update_instagram_pictures')
    self.assertEqual(200, resp.status_int)

    self.assertEquals('http://new/pic', sources[0].get().picture)
    self.assertEquals('http://new/pic', sources[1].get().picture)
    self.assertEquals('http://old/pic', sources[2].get().picture)
    self.assertEquals('http://old/pic', sources[3].get().picture)
Example #29
0
 def test_get_activities_response(self):
   """Check that min_id is discarded."""
   inst = Instagram.new(self.handler, auth_entity=self.auth_entity)
   self.expect_urlopen(
     'https://api.instagram.com/v1/users/self/media/recent?access_token=my_token',
     '{"data":[]}')
   self.mox.ReplayAll()
   assert inst.get_activities_response(min_id='123')
Example #30
0
  def test_profile_new_user(self):
    self.assertIsNone(Instagram.get_by_id('snarfed'))

    self.expect_requests_get('https://snarfed.org/', '')
    self.mox.ReplayAll()

    resp = self.get_response('profile?token=towkin', data=HTML_PROFILE_COMPLETE)

    self.assertEqual(200, resp.status_code)
    self.assertEqual(self.source.key.urlsafe().decode(), resp.json)

    ig = Instagram.get_by_id('snarfed')
    self.assertEqual('Ryan B', ig.name)
    self.assertEqual('https://scontent-sjc2-1.cdninstagram.com/hphotos-xfa1/t51.2885-19/11373714_959073410822287_2004790583_a.jpg', ig.picture)
    self.assertEqual('https://www.instagram.com/snarfed/', ig.silo_url())
    self.assertEqual(['https://snarfed.org/'], ig.domain_urls)
    self.assertEqual(['snarfed.org'], ig.domains)
Example #31
0
def main():
    print('- -' * 14)
    print(f'|\tSession started {config.INSTAGRAM_USERNAME}\t |')
    print('- -' * 14, end='\n\n')

    ig = Instagram()

    # --------------------------------------

    print(f'\nāˆ˜ [{getTimeStamp()}] Getting timeline posts', end='\n\n')
    timeline = ig.getTimeline(count=200)
    for i, x in enumerate(timeline):
        if i % LIKE_STEP == 0:
            likePost(ig, x)
        if i % COMMENT_STEP == 0:
            commentPost(ig, x)
        if i % FOLLOW_STEP == 0:
            unfollowPoster(ig, x['shortcode'])

        randSleep()

    # --------------------------------------

    tagFeed = []
    for i in config.TAGS:
        print(f'āˆ˜ [{getTimeStamp()}] Getting posts for #{i}')
        tagFeed.extend(ig.searchTagFeed(i.replace('#', ''), count=200))
        randSleep()
    print()

    for i, x in enumerate(tagFeed):
        if i % LIKE_STEP == 0:
            likePost(ig, x)
        if i % COMMENT_STEP == 0:
            commentPost(ig, x)
        if i % FOLLOW_STEP == 0:
            followPoster(ig, x['shortcode'])

        randSleep()

    # --------------------------------------

    print('- -' * 14)
    print(f'|\t     Finished session!\t\t |')
    print('- -' * 14, end='\n\n')
Example #32
0
 def test_new(self):
   inst = Instagram.new(self.handler, auth_entity=self.auth_entity)
   self.assertEqual(self.auth_entity, inst.auth_entity.get())
   self.assertEqual('my_token', inst.as_source.access_token)
   self.assertEqual('snarfed', inst.key.string_id())
   self.assertEqual('http://pic.ture/url', inst.picture)
   self.assertEqual('http://instagram.com/snarfed', inst.url)
   self.assertEqual('http://instagram.com/snarfed', inst.silo_url())
   self.assertEqual('Ryan Barrett', inst.name)
Example #33
0
  def test_canonicalize_syndication_url(self):
    inst = Instagram.new(self.handler, auth_entity=self.auth_entity)

    for url in (
        'http://www.instagram.com/p/abcd',
        'https://www.instagram.com/p/abcd',
        'https://instagram.com/p/abcd',
    ):
      self.assertEqual(
        'http://instagram.com/p/abcd',
        inst.canonicalize_syndication_url(url))
Example #34
0
 def test_poll(self):
     source = Instagram.create_new(self.handler,
                                   actor={'username': '******'})
     self.expect_task('poll',
                      eta_seconds=0,
                      source_key=source.key,
                      last_polled='1970-01-01-00-00-00')
     self.mox.ReplayAll()
     resp = app.application.get_response(
         '/instagram/browser/poll?username=snarfed', method='POST')
     self.assertEqual(200, resp.status_int, resp.text)
     self.assertEqual('OK', resp.json)
Example #35
0
  def test_get_activities_response_no_activity_id(self):
    Activity(id='tag:instagram.com,2013:123', source=self.source.key,
             activity_json=json_dumps({'foo': 'bar'})).put()
    Activity(id='tag:instagram.com,2013:456', source=self.source.key,
             activity_json=json_dumps({'baz': 'biff'})).put()

    other = Instagram.new(actor={'username': '******'}).put()
    Activity(id='tag:instagram.com,2013:789', source=other,
             activity_json=json_dumps({'boo': 'bah'})).put()

    resp = self.source.get_activities_response()
    self.assert_equals([{'foo': 'bar'}, {'baz': 'biff'}], resp['items'])
Example #36
0
    def test_profile_new_user(self):
        self.assertIsNone(Instagram.get_by_id('snarfed'))

        self.expect_webmention_discovery()
        self.mox.ReplayAll()

        resp = app.application.get_response(
            '/instagram/browser/profile?token=towkin',
            method='POST',
            text=HTML_PROFILE_COMPLETE)

        self.assertEqual(200, resp.status_int)
        self.assertEqual([HTML_PHOTO_ACTIVITY, HTML_VIDEO_ACTIVITY], resp.json)

        ig = Instagram.get_by_id('snarfed')
        self.assertEqual('Ryan B', ig.name)
        self.assertEqual(
            'https://scontent-sjc2-1.cdninstagram.com/hphotos-xfa1/t51.2885-19/11373714_959073410822287_2004790583_a.jpg',
            ig.picture)
        self.assertEqual('https://www.instagram.com/snarfed/', ig.url)
        self.assertEqual(['https://snarfed.org/'], ig.domain_urls)
        self.assertEqual(['snarfed.org'], ig.domains)
Example #37
0
  def test_update_instagram_picture_profile_404s(self):
    auth_entity = indieauth.IndieAuth(id='http://foo.com/', user_json='{}')
    source = Instagram.new(
        None, auth_entity=auth_entity, features=['listen'],
        actor={'username': '******', 'image': {'url': 'http://old/pic'}})
    source.put()

    super(HandlerTest, self).expect_requests_get(
      gr_instagram.HTML_BASE_URL + 'x/', status_code=404, allow_redirects=False)
    self.mox.ReplayAll()

    resp = cron.application.get_response('/cron/update_instagram_pictures')
    self.assertEqual(200, resp.status_int)
    self.assertEquals('http://old/pic', source.key.get().picture)
Example #38
0
    def test_post(self):
        source = Instagram.create_new(self.handler, actor={'username': '******'})

        resp = app.application.get_response(
            '/instagram/browser/post?token=towkin',
            method='POST',
            text=HTML_VIDEO_COMPLETE)
        self.assertEqual(200, resp.status_int, resp.text)
        self.assertEqual(HTML_VIDEO_ACTIVITY_FULL, resp.json)

        activities = Activity.query().fetch()
        self.assertEqual(1, len(activities))
        self.assertEqual(source.key, activities[0].source)
        self.assertEqual(HTML_VIDEO_ACTIVITY_FULL,
                         json_loads(activities[0].activity_json))
Example #39
0
    def setUp(self):
        super(InstagramTest, self).setUp()
        self.handler.messages = []
        self.inst = Instagram.new(
            self.handler,
            actor={
                'objectType': 'person',
                'id': 'tag:instagram.com,2013:420973239',
                'username': '******',
                'displayName': 'Ryan Barrett',
                'url': 'https://snarfed.org/',
                'image': {
                    'url': 'http://pic.ture/url'
                },
                # ...
            })

        self.domain = Domain(id='snarfed.org', tokens=['towkin']).put()
Example #40
0
    def test_update_instagram_pictures(self):
        for username in "a", "b":
            self.expect_urlopen(
                "https://api.instagram.com/v1/users/self?access_token=token",
                json.dumps(
                    {
                        "data": {
                            "id": username,
                            "username": username,
                            "full_name": "Ryan Barrett",
                            "profile_picture": "http://new/pic",
                        }
                    }
                ),
            )
        self.mox.ReplayAll()

        sources = []
        for username in "a", "b", "c", "d":
            auth_entity = oauth_instagram.InstagramAuth(
                id=username,
                auth_code="code",
                access_token_str="token",
                user_json=json.dumps(
                    {"username": username, "full_name": "Ryan Barrett", "profile_picture": "http://old/pic"}
                ),
            )
            auth_entity.put()
            source = Instagram.new(None, auth_entity=auth_entity, features=["listen"])
            # test that we skip disabled and deleted sources
            if username == "c":
                source.status = "disabled"
            elif username == "d":
                source.features = []
            sources.append(source.put())

        resp = cron.application.get_response("/cron/update_instagram_pictures")
        self.assertEqual(200, resp.status_int)

        self.assertEquals("http://new/pic", sources[0].get().picture)
        self.assertEquals("http://new/pic", sources[1].get().picture)
        self.assertEquals("http://old/pic", sources[2].get().picture)
        self.assertEquals("http://old/pic", sources[3].get().picture)
Example #41
0
  def test_update_instagram_pictures_batch(self):
    self.setup_instagram(weekday=3)
    self.expect_instagram_profile_fetch('d')
    self.mox.ReplayAll()

    sources = []
    auth_entity = indieauth.IndieAuth(id='http://foo.com/', user_json='{}')
    for username in 'a', 'b', 'c', 'd', 'e', 'f', 'g':
      source = Instagram.new(
        None, auth_entity=auth_entity, features=['listen'],
        actor={'username': username, 'image': {'url': 'http://old/pic'}})
      sources.append(source.put())

    resp = cron.application.get_response('/cron/update_instagram_pictures')
    self.assertEqual(200, resp.status_int)

    for i, source in enumerate(sources):
      self.assertEqual('http://new/pic' if i == 3 else 'http://old/pic',
                       source.get().picture)
Example #42
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)
Example #43
0
from instagram import Instagram

test = Instagram ("2535574809.64e7c60.74b13064e52d438f9a72e82dfbf01c85")
result = test.self_info()
print result
Example #44
0
 def get(self):
   for source in Instagram.query():
     if source.features and source.status != 'disabled':
       maybe_update_picture(source, source.gr_source.get_actor(), self)