class AppiumSession(object):

    def __init__(self, capabilities):
        # Find free port for Appium server
        port = self.free_port()

        # Ensure we have driver if we test mobile web or hybrid apps
        if "chromeDriverVersion" in capabilities:
            driver_version = capabilities.get('chromeDriverVersion')
            path = ChromeDriverManager(version=driver_version).install()
            sys.path.append(path)

        # Start Appium server and attach client
        self.appium_service = AppiumService()
        self.appium_service.start(args=['--address', '127.0.0.1', '-p', str(port)])
        self.driver = webdriver.Remote("http://127.0.0.1:{0}/wd/hub".format(port), capabilities)

    def stop(self):
        if self.driver is not None:
            self.driver.quit()
        if self.appium_service is not None:
            self.appium_service.stop()

    @staticmethod
    def free_port():
        """
        Determines a free port using sockets.
        """
        free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        free_socket.bind(('0.0.0.0', 0))
        free_socket.listen(5)
        port = free_socket.getsockname()[1]
        free_socket.close()
        return port
예제 #2
0
 def stop_appium_server():
     if Utils.check_appium_is_already_running():
         appium_service = AppiumService()
         appium_service.stop()
         os.system('pkill adb')
         print("Appium is stop")
     else:
         print("Appium is already stop")
class AppiumDriver(object):
    def __init__(self, capabilities):
        self.appium_service = AppiumService()
        self.appium_service.start()
        self.capabilities = capabilities
        self.executor = 'http://0.0.0.0:4723/wd/hub'
        self.driver = webdriver.Remote(self.executor, capabilities)

    def quit(self):
        self.appium_service.stop()
예제 #4
0
class Appium(Logger):
    def __init__(self, appium_args: List[str] = None, **kwargs: Any):
        """ Initialize Appium wrapper """
        super().__init__()
        self.port = find_free_port()
        self.service = AppiumService()
        self._extra_args = kwargs
        self._appium_args = appium_args or []

        @atexit.register
        def _exit():
            nonlocal self
            if self.service.is_running:
                self.logger.warn("exit:stop appium")
                self.stop()

    def get_wd_hub_uri(self) -> str:
        """ Get local appium uri """
        assert self.service.is_running, 'Appium is not running'
        return f'http://127.0.0.1:{self.port}/wd/hub'

    def start(self):
        assert not self.service.is_running, 'Appium already running'
        # https://appium.io/docs/en/writing-running-appium/server-args/
        args = ['-a', '127.0.0.1', '-p', f"{self.port}"]
        args.extend(self._appium_args)
        self.logger.info(
            f'Start Appium with args: {" ".join(args)} {self._extra_args}')
        self.service.start(args=args, **self._extra_args)
        assert self.service.is_running, 'Appium did not started :o'
        uri = self.get_wd_hub_uri()
        self.logger.info(
            f'Appium started: {uri} (pid: {self.service._process.pid})')
        return uri

    def stop(self):
        assert self.service.is_running, 'Appium is not running'
        self.logger.info(
            f"Close appium server (port: {self.port}, pid: {self.service._process.pid})"
        )
        self.service.stop()

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop()
예제 #5
0
def start(**kwargs):
    port = str(free_port())
    devices = Command().devices_and_version()[0]
    caps = get_caps()["devices"]["samsung-10"]
    caps.update(getattr(Context, "CAPS"))
    if kwargs:
        for key, value in kwargs.items():
            caps[key] = value
    caps["deviceName"] = devices[0]
    caps["platformVersion"] = devices[1]
    service = AppiumService()
    service.start(args=["-a", "127.0.0.1", "-p", port, "--session-override"],
                  timeout_ms=2000)
    driver = webdriver.Remote(
        command_executor=f'http://127.0.0.1:{port}/wd/hub',
        desired_capabilities=caps)
    yield driver
    driver.close()
    driver.quit()
    service.stop()
예제 #6
0
def base_args(*port, **kwargs):
    if not port:  # 寻找空闲端口
        port = free_port()
    caps = get_caps()
    caps.update(getattr(Context, "ENV")["caps"])
    devices = Command().devices_and_version()
    n = 0
    if kwargs:
        for key, value in kwargs.items():
            caps[key] = value
    for res in devices:
        caps["deviceName"] = res[0]
        caps["platformVersion"] = res[1]
        service = AppiumService()
        service.start(
            args=["-a", "127.0.0.1", "-p", port[n], "--session-override"],
            timeout_ms=2000)
        driver = webdriver.Remote(
            command_executor='http://127.0.0.1:{}/wd/hub'.format(port[n]),
            desired_capabilities=caps)
        yield driver
        service.stop()
예제 #7
0
from appium.webdriver.appium_service import AppiumService

appium_server = AppiumService()
appium_server.start()
appium_server.stop()
예제 #8
0
class AppiumDriver(object):
    service = None
    driver = None

    def __init__(self,
                 platform,
                 device,
                 bundle_id,
                 activity='com.tns.NativeScriptActivity',
                 wait_timeout=30):
        """
        Init appium session.
        :param platform: Platform enum value.
        :param device: device instance.
        :param bundle_id: bundle id of application under test (must be already deployed on device).
        :param activity: default app activity (needed in Android only).
        :param wait_timeout: timeout for finding elements (in seconds).
        """
        capabilities = self.__get_capabilities(platform=platform,
                                               device=device,
                                               bundle_id=bundle_id,
                                               activity=activity)
        self.__start_server()
        self.__start_client(capabilities, wait_timeout)

    def stop(self):
        """
        Stop appium session.
        """
        self.__stop_client()
        self.__stop_server()

    @staticmethod
    def kill():
        """
        Kill all instance of appium server.
        """
        Process.kill(proc_name='node', proc_cmdline='appium')

    def __start_server(self):
        Log.info("Starting appium server...")
        self.service = AppiumService()
        self.service.start(args=['-p', str(DEFAULT_PORT)])
        assert self.service.is_running, "Failed to start appium server."
        Log.info("Appium server started.")

    def __stop_server(self):
        if self.service is not None and self.service.is_running:
            self.service.stop()
            Log.info("Stop appium server.")

    @staticmethod
    def __get_capabilities(platform,
                           device,
                           bundle_id,
                           activity='com.tns.NativeScriptActivity'):
        capabilities = {}
        capabilities['platformName'] = str(platform)
        capabilities['platformVersion'] = device.version
        capabilities['deviceName'] = device.name
        capabilities['udid'] = device.id
        capabilities['noReset'] = 'true'
        capabilities['fullReset'] = 'false'
        if platform == Platform.ANDROID:
            capabilities['automationName'] = 'uiautomator2'
            capabilities['appPackage'] = bundle_id
            capabilities['appActivity'] = activity
        if platform == Platform.IOS:
            capabilities['automationName'] = 'XCUITest'
            capabilities['bundleId'] = bundle_id
        # In case debug session is found increase 'newCommandTimeout' to allow debugging longer period of time.
        capabilities['newCommandTimeout'] = 3600 if Settings.IS_DEBUG else 60
        return capabilities

    def __start_client(self, capabilities, wait_timeout):
        Log.info("Starting appium client...")
        self.driver = webdriver.Remote('http://0.0.0.0:4723/wd/hub',
                                       capabilities)
        self.driver.implicitly_wait(wait_timeout)
        Log.info("Appium client started.")

    def __stop_client(self):
        if self.driver is not None:
            self.driver.quit()
            Log.info("Stop appium client.")
예제 #9
0
class tc_android_calculator(aetest.Testcase):
    @aetest.setup
    def prepare_testcase(self, section):
        """ Testcase Setup section """
        log.info("Preparing the test")
        # Make sure python client is installed "pip install Appium-Python-Client"
        # Make sure appium is installed 'npm install -g appium'
        self.appium_service = AppiumService()
        # By default appium starts server at port 4723.
        # You can pass port as argument in AppiumService to change it.
        self.appium_service.start()
        log.info(self.appium_service.is_running)

        # Following is desired capabilities for Android app
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '6.0'
        desired_caps['automationName'] = 'androidautomator'
        desired_caps['deviceName'] = 'Android Emulator'
        desired_caps['appPackage'] = 'com.android.calculator2'
        desired_caps['appActivity'] = 'com.android.calculator2.Calculator'
        self.driver = webdriver.Remote('http://localhost:4723/wd/hub',
                                       desired_caps)

        # Following is example of testing iOS app
        # desired_caps['platformName'] = 'iOS'
        # desired_caps['platformVersion'] = '11.0'
        # desired_caps['automationName'] = 'iosautomator'
        # desired_caps['deviceName'] = 'iPhone 7'
        # desired_caps['app'] = '/path/to/my.app'

    # First test section
    @aetest.test
    def pass_check(self):
        no_7 = self.driver.find_element(value="digit_7", by=By.ID)
        no_7.click()
        plus = self.driver.find_element(value="op_add", by=By.ID)
        plus.click()
        no_4 = self.driver.find_element(value="digit_4", by=By.ID)
        no_4.click()
        equalTo = self.driver.find_element(value="eq", by=By.ID)
        equalTo.click()
        results = self.driver.find_element(value="formula", by=By.ID)
        result_value = results.get_attribute('text')
        if result_value == '11':
            self.passed('Value is 11')
        else:
            self.failed('Value is not 11')

    # Second test section
    @aetest.test
    def failure_check(self):
        no_7 = self.driver.find_element(value="digit_7", by=By.ID)
        no_7.click()
        plus = self.driver.find_element(value="op_add", by=By.ID)
        plus.click()
        no_4 = self.driver.find_element(value="digit_4", by=By.ID)
        no_4.click()
        equalTo = self.driver.find_element(value="eq", by=By.ID)
        equalTo.click()

        results = self.driver.find_element(value="formula", by=By.ID)
        result_value = results.get_attribute('text')
        if result_value == '12':
            self.passed('Value is 12')
        else:
            self.failed('Value is not 12')

    @aetest.cleanup
    def clean_testcase(self):
        log.info("Pass testcase cleanup")
        # Close app
        self.driver.quit()
        # Stop Appium Service
        self.appium_service.stop()
def stop_appium_server():
    appium_service = AppiumService()
    appium_service.stop()
    print("Server Stoped")
예제 #11
0
class AddMoney:
    def __init__(self, startServer=False, phone="RN8P"):
        self.start_server = startServer  # Flag to start inline server

        # ============ START SERVER ============
        if self.start_server:
            self.appium_service = AppiumService()
            self.appium_service.start()

        # ============ LAUNCH APP ============
        self.driver = webdriver.Remote("http://localhost:4723/wd/hub",
                                       DESIRED_CAPS)
        time.sleep(5)  # Wait for App

        self.dev_window_size = WIN_SIZE_RN8P if phone == "RN8P" else self.driver.get_window_size(
        )
        #print(dev_window_size) # debug

    def tap_at(self, _x=0, _y=0, t=1):
        TouchAction(self.driver).tap(x=_x * self.dev_window_size['width'] /
                                     WIN_SIZE_RN8P['width'],
                                     y=_y).perform()
        time.sleep(t)

    def _handle_fb_login(self):
        CONTINUE_BTN_XPATH = "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.webkit.WebView/android.view.View/android.view.View[2]/android.view.View[2]/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[2]/android.view.View/android.view.View/android.widget.Button"

        # Login to FB Account
        self.tap_at(1656, 354)
        time.sleep(5)
        try:
            print("Tap Continue")
            fb_login_continue_elem = self.driver.find_element_by_xpath(
                CONTINUE_BTN_XPATH)  # Login to FB Account
            TouchAction(self.driver).tap(fb_login_continue_elem).perform()
            time.sleep(5)  # Wait for Login
        except Exception as e:
            print(e)
            pass

    def _handle_set_DOB(self):
        # Set DOB
        self.tap_at(890, 500)  # ^ (Mon)
        self.tap_at(700, 250)  # Jan
        self.tap_at(1694, 504)  # ^ (yr)
        self.tap_at(1528, 460)  #1961
        self.tap_at(1100, 800)  # Continue

    def add_money(self, count=50):
        for i in range(count):
            #Start Ad
            self.tap_at(409, 489)  # free coins
            time.sleep(35)
            self.driver.back()
            time.sleep(1)
            self.tap_at(1115, 777)  # Continue
            if i == 0:
                self.tap_at(1130, 883)  # 1 Friend has used your code (Collect)

    def teardown(self):
        # ============ STOP SESSION ============
        self.driver.quit()  # End client
        # ============ STOP SERVER ============
        if self.start_server:
            self.appium_service.stop()  # End Server

    def main(self, count=200):
        # self.setup()
        self._handle_fb_login()
        self._handle_set_DOB()
        self.add_money(count)
        self.teardown()
예제 #12
0
class BurbnBot:
    actions = []
    amount_followed: int = 0
    amount_liked: int = 0
    appiumservice = None
    driver = ""
    follow_percentage: int = 0
    instabot = None
    logPath: str = "log/"
    logger = ""
    posts_to_follow = ""
    predict = ""
    settings = {}
    touchaction = None

    def __init__(self, configfile: str = None):
        self.configfile = configfile
        parser = argparse.ArgumentParser(add_help=True)
        parser.add_argument('-settings', type=str, help="json settings file")
        args = parser.parse_args()
        self.settings = json.load(open(args.settings))

        self.logger = logger
        self.logger.add("log/{}.log".format(
            self.settings['instagram']['username']),
                        backtrace=True,
                        diagnose=True,
                        level="WARNING")

        try:
            self.logger.info("Lets do it!.")

            self.predict = Predict(
                api_key=self.settings['clarifai']['api_key'],
                logger=self.logger)

            self.instabot = instabot.Bot(base_path="InstaBot/")
            self.instabot.logger = self.logger
            self.instabot.api.logger = self.logger

            self.instabot.login(
                username=self.settings['instagram']['username'],
                password=self.settings['instagram']['password'],
                proxy=None)

        except Exception as err:
            self.treat_exception(err)
            self.end()
            pass

    def start_driver(self):
        try:
            sys.stdout.flush()
            self.logger.info("Starting Appium service.")
            os.environ.setdefault(
                key="ANDROID_HOME",
                value=self.settings['android']['android_home'])
            self.appiumservice = AppiumService()
            self.appiumservice.stop()
            self.appiumservice.start()

            if self.appiumservice.is_running:
                self.logger.info("Appium Server is running.")
                self.driver = webdriver.Remote(
                    command_executor="http://*****:*****@{} again."
                .format(user))
        try:
            self.driver.find_element_by_xpath(ElementXpath.btn_follow)
        except NoSuchElementException:
            return False
        return True

    def unfollow_non_followers(self, avoid_saved=True, amount=None):
        self.logger.info("Unfollowing non-followers.")
        following = []
        for a in self.instabot.api.get_total_followings(
                user_id=self.instabot.user_id):
            following.append(a["username"])

        followers = []
        for b in self.instabot.api.get_total_followers(
                user_id=self.instabot.user_id):
            followers.append(b["username"])

        if avoid_saved:
            users_saved = self.get_owner_saved_post()
            followers = followers + users_saved

        non_followers = [x for x in following if x not in followers]
        self.logger.info("Setting command to unfollow users.")
        for username in tqdm(non_followers[:amount],
                             desc="Selecting user to unfollow.",
                             unit=" users"):
            self.actions.append({"function": "unfollow", "argument": username})

    def get_owner_saved_post(self):
        self.instabot.api.get_saved_medias()
        saveds = self.instabot.last_json['items']
        r = []
        self.logger.info("Getting owner of saved posts")
        for p in saveds:
            r.append(str(p['media']['user']['username']))
        return r

    def treat_exception(self, err):
        self.logger.exception(err)
        if isdebugging:
            breakpoint()

    def end(self):
        self.appiumservice.stop()
        self.logger.info("That's all folks! Bye bye!")
        quit()

    def check_element_exist(self, xpath):
        try:
            self.driver.find_element_by_xpath(xpath)
        except NoSuchElementException:
            return False
        return True

    def chimping_timeline(self):
        try:
            self.refreshing()
            amount = random.randint(5, 15)
            count = 0
            self.logger.info("Let's chimping the timeline a bit.")
            el1 = self.driver.find_element_by_id(
                "com.instagram.android:id/action_bar_root")
            start_x = el1.rect["width"] - 50
            start_y = el1.rect["height"] - 50
            end_x = el1.rect["x"] + 50
            end_y = el1.rect["y"] + 50
            while count < amount:
                self.driver.swipe(start_x,
                                  start_y,
                                  end_x,
                                  end_y,
                                  duration=random.randint(2500, 4000))
                count += 1
        except Exception as err:
            self.treat_exception(err)
            pass

    def refreshing(self):
        try:
            self.driver.get(url="https://www.instagram.com/")
            self.driver.find_element_by_xpath(
                ElementXpath.tab_bar_home).click()
            self.driver.find_element_by_xpath(
                ElementXpath.tab_bar_home).click()
            self.driver.find_element_by_xpath(ElementXpath.top_title).click()

            el1 = self.driver.find_element_by_xpath(
                ElementXpath.row_feed_photo_profile_name)
            el2 = self.driver.find_element_by_xpath(
                ElementXpath.tab_bar_camera)

            start_x = el1.rect["x"]
            start_y = el1.rect["y"]
            end_x = el2.rect["x"]
            end_y = el2.rect["y"] - 100
            self.driver.swipe(start_x,
                              start_y,
                              end_x,
                              end_y,
                              duration=random.randint(350, 400))
        except Exception as err:
            self.treat_exception(err)
            pass

    def chimping_stories(self):
        self.refreshing()
        count = 0
        amount = random.randint(2, 5)
        try:
            stories_thumbnails = self.driver.find_elements_by_xpath(
                ElementXpath.stories_thumbnails)
            stories_thumbnails[1].click()
            self.logger.info("Watching {} stories.".format(amount))
            while count < amount:
                t = random.randint(5, 10)
                sleep(t)
                if self.check_element_exist(
                        xpath=ElementXpath.reel_viewer_texture_view):
                    x1 = random.randint(750, 850)
                    y1 = random.randint(550, 650)
                    x2 = random.randint(200, 300)
                    y2 = random.randint(550, 650)
                    self.driver.swipe(x1, y1, x2, y2,
                                      random.randint(500, 1000))
                count += 1
        except Exception as err:
            self.logger.warning(
                "Ops, something wrong while waching stories, sorry.")
            self.treat_exception(err)
            pass

        self.driver.get(url="https://www.instagram.com/{}/".format(
            self.settings['instagram']['username']))
        self.driver.get(url="https://www.instagram.com/")

    def interact_by_location(self, amount: int = 15, location_id: int = ""):
        self.instabot.api.get_location_feed(location_id=213819997, max_id=9999)
        last_json = self.instabot.last_json
        if amount > len(last_json['items']):
            amount = len(last_json['items'])
        counter = 0
        while counter < amount:
            self.interact(last_json['items'][counter]['id'])
            counter += 1

    def check_item(self,
                   item,
                   concepts=[],
                   concepts_skip=[],
                   max_likes=1000,
                   min_likes=0):
        if not item['like_count'] in range(min_likes, max_likes):
            return False
        if item['has_liked']:
            return False

        if isinstance(concepts, list) and isinstance(concepts_skip, list):
            if item['media_type'] == MediaType.PHOTO:
                url_image = item['image_versions2']['candidates'][0]['url']
            elif item['media_type'] == MediaType.CAROUSEL:
                url_image = item['carousel_media'][0]['image_versions2'][
                    'candidates'][0]['url']
            else:
                url_image = item['video_versions'][0]['url']
            predict = self.predict.check(url=url_image,
                                         tags=concepts,
                                         tags_skip=concepts_skip,
                                         is_video=item['media_type'] == 2)
        else:
            predict = True

        return predict

    def interact_by_hashtag(self,
                            amount: int = 15,
                            hashtag: str = "",
                            ranked_items: bool = True,
                            concepts=[],
                            concepts_skip=[],
                            max_likes=100,
                            min_likes=0):
        try:
            items = []
            next_max_id = ""
            while self.instabot.api.get_hashtag_feed(hashtag,
                                                     max_id=next_max_id):
                last_json = self.instabot.api.last_json
                next_max_id = last_json['next_max_id']
                if ranked_items:
                    if "ranked_items" in last_json:
                        items = items + last_json['ranked_items']
                items = items + last_json['items']
                items = [
                    i for i in items[0:amount]
                    if self.check_item(item=i,
                                       concepts=concepts,
                                       concepts_skip=concepts_skip,
                                       max_likes=max_likes,
                                       min_likes=min_likes)
                ]
                if amount == len(items[0:amount]):
                    items = items[0:amount]
                    break

            return [item for item in items if self.add_action(item, "like")]
        except Exception as err:
            self.logger.warning(
                "Ops, something wrong while working with hashtag #{}, sorry.".
                format(hashtag))
            self.treat_exception(err)
            pass

    def interact_by_location(self,
                             amount: int = 15,
                             location_id: int = "",
                             ranked_items: bool = True,
                             concepts=[],
                             concepts_skip=[],
                             max_likes=100,
                             min_likes=0):
        try:
            items = []
            next_max_id = ""
            while self.instabot.api.get_location_feed(location_id,
                                                      max_id=next_max_id):
                last_json = self.instabot.api.last_json
                next_max_id = last_json['next_max_id']
                if ranked_items:
                    if "ranked_items" in last_json:
                        items = items + last_json['ranked_items']
                items = items + last_json['items']
                items = [
                    i for i in items
                    if self.check_item(item=i,
                                       concepts=concepts,
                                       concepts_skip=concepts_skip,
                                       max_likes=max_likes,
                                       min_likes=min_likes)
                ]
                if amount == len(items[0:amount]):
                    items = items[0:amount]
                    break

            return [item for item in items if self.add_action(item, "like")]
        except Exception as err:
            self.logger.warning(
                "Ops, something wrong while working with location {}, sorry.".
                format(location_id))
            self.treat_exception(err)
            pass

    def add_action(self, item, function):
        try:
            self.actions.append({
                "function": function,
                "argument": {
                    "url":
                    "https://www.instagram.com/p/{}/".format(item["code"]),
                    "media_type": item['media_type']
                }
            })
            return True
        except:
            return False

    def set_do_follow(self, follow_percentage: int = 0):
        self.follow_percentage = follow_percentage

    def do_actions(self):
        likes_actions = [i for i in self.actions if i["function"] == "like"]
        self.posts_to_follow = []
        if self.follow_percentage > 0:
            self.posts_to_follow = random.sample(
                range(0, len(likes_actions)),
                int(len(likes_actions) * (self.follow_percentage / 100)))

        amount_actions = int(len(self.actions) / 2)
        if not isdebugging():
            for i in tqdm(range(1, amount_actions),
                          desc="Let's include some (not so real) actions.",
                          unit=" actions"):
                self.actions.append({"function": "chimping_timeline"})
                self.actions.append({"function": "chimping_stories"})

        random.shuffle(self.actions)
        self.actions = [i[0] for i in groupby(self.actions)]

        self.start_android()

        for action in tqdm(self.actions,
                           desc="Execution actions on the phone/emulator",
                           unit=" actions"):
            try:
                method_to_call = getattr(self, action['function'])
                if "argument" in action:
                    method_to_call(action['argument'])
                    sleep(random.randint(3, 10))
                else:
                    method_to_call()
            except Exception as err:
                self.logger.warning(
                    "Ops, something with the action {} ({}), sorry.".format(
                        action['function'], action['argument']))
                self.treat_exception(err)
                pass
        self.stop_driver()

    def start_android(self):
        starting_appium = threading.Thread(name='process',
                                           target=self.start_driver)
        starting_appium.start()
        while starting_appium.isAlive():
            self.animated_loading()

    def follow(self):
        if self.save_in_collection():
            try:
                self.driver.find_element_by_xpath(
                    ElementXpath.btn_follow).click()
                user = self.driver.find_element_by_xpath(
                    ElementXpath.action_bar_textview_title).text
                self.logger.info("Following user {}.".format(user))
                self.amount_followed += 1
                print(self.amount_followed)
                return True
            except Exception as err:
                self.treat_exception(err)
                return False
                pass
        else:
            return False

    def save_in_collection(self):
        try:
            button_save = self.driver.find_element_by_xpath(
                ElementXpath.row_feed_button_save)
            self.touchaction.long_press(button_save)
            self.touchaction.perform()

            strdate = datetime.now().strftime("%Y%m%d")

            if self.check_element_exist(
                    ElementXpath.create_collection_edit_text):
                self.logger.info(
                    "Zero collection, let's create the first one.")
                collection_today = []
            else:
                collection_names = self.driver.find_elements_by_xpath(
                    ElementXpath.collection_name)
                collection_today = [
                    i for i in collection_names if i.text == strdate
                ]

            if len(collection_today) > 0:
                collection_today[0].click()
            else:
                if self.check_element_exist(
                        ElementXpath.save_to_collection_new_collection_button):
                    self.driver.find_element_by_xpath(
                        ElementXpath.save_to_collection_new_collection_button
                    ).click()
                self.driver.find_element_by_xpath(
                    ElementXpath.create_collection_edit_text).send_keys(
                        strdate)
                self.driver.find_element_by_xpath(
                    ElementXpath.save_to_collection_action_button).click()

            self.driver.find_element_by_xpath(
                ElementXpath.row_feed_photo_profile_name).click()
            return True
        except Exception as e:
            self.logger.warning("Post not saved!")
            self.treat_exception(e)
            return False

    def like(self, param):
        url = param["url"]
        media_type = param["media_type"]
        self.driver.get(url=url)
        try:
            e = self.driver.find_element_by_xpath(
                ElementXpath.row_feed_button_like)
            if e.tag_name == "Liked":
                self.logger.info("Ops, you already like this one, sorry.")
                return False
            else:

                if media_type == MediaType.VIDEO:
                    self.wait_random()
                elif media_type == MediaType.CAROUSEL:
                    self.swipe_carousel()

                e.click()
                # sleep(random.randint(1, 3))
                self.logger.info("Image {} Liked.".format(url))
                if self.amount_liked in self.posts_to_follow:
                    self.follow()
                return True
        except Exception as err:
            self.logger.warning(
                "Ops, something wrong on try to like {}, sorry.".format(url))
            self.logger.error(err)
            self.treat_exception(err)
            return False
            pass

    def watch_stories(self):
        try:
            while self.check_element_exist(
                    xpath=ElementXpath.reel_viewer_texture_view):
                t = random.randint(2, 10)
                self.logger.info("Sleeping for {} seconds.".format(t))
                sleep(t)
                if self.check_element_exist(
                        xpath=ElementXpath.reel_viewer_texture_view):
                    self.logger.info("Tap")
                    self.driver.tap([(800, 600)], random.randint(3, 10))
        except Exception as err:
            self.logger.warning(
                "Ops, something wrong while waching stories, sorry.")
            self.treat_exception(err)
            pass

    def get_info(self):
        row_feed_photo_profile_name = self.driver.find_element_by_xpath(
            ElementXpath.row_feed_photo_profile_name)
        owner_username = row_feed_photo_profile_name.text.replace(" •", "")
        has_liked = self.driver.find_element_by_id(
            "com.instagram.android:id/row_feed_button_like"
        ).tag_name == "Liked"
        self.get_type_post()

    def swipe_carousel(self):
        try:
            carousel_image = self.driver.find_element_by_xpath(
                ElementXpath.carousel_image)
            match = re.search(r"(\d+).*?(\d+)", carousel_image.tag_name)
            n = int(match.group(2))
        except NoSuchElementException as err:
            n = 2  # if don't find the number of pictures work with only 2
            pass
        self.logger.warning("Let's check all the {} images here.".format(n))
        for x in range(n - 1):
            self.driver.swipe(800, 600, 250, 600, random.randint(500, 1000))
        for x in range(n - 1):
            self.driver.swipe(300, 650, 800, 600, random.randint(500, 1000))

    @staticmethod
    def wait_random():
        t = random.randint(5, 15)
        sleep(t)

    def get_collections(self):
        self.instabot.api.send_request("collections/list/")
        return self.instabot.last_json

    def get_collection(self, collection_id):
        self.instabot.api.send_request(
            "feed/collection/{}/".format(collection_id))
        return self.instabot.last_json

    def unfollow_by_collection(self, name):
        collections = self.get_collections()
        for c in collections["items"]:
            if c['collection_name'] == name:
                collection = self.get_collection(
                    collection_id=c['collection_id'])
                for i in tqdm(
                        collection["items"],
                        desc="Getting users from colletion {} to unfollow.".
                        format(name)):
                    self.actions.append({
                        "function":
                        "unfollow",
                        "argument":
                        i['media']['user']['username']
                    })
                    self.actions.append({
                        "function": "unsave",
                        "argument": i['media']['code']
                    })

    @staticmethod
    def animated_loading():
        chars = "/—\|"
        for char in chars:
            sys.stdout.write('\r' + 'loading service...' + char)
            time.sleep(.1)
            sys.stdout.flush()