Пример #1
0
def test_set_use_clarifai_raises_on_windows(load_follow_restriction):
    """windows not supported"""
    instapy = InstaPy(selenium_local_session=False)
    with patch('instapy.instapy.os') as os:
        type(os).name = PropertyMock(return_value='nt')
        with pytest.raises(InstaPyError):
            instapy.set_use_clarifai()
Пример #2
0
def test_interact_by_users_with_no_usernames():
    """ensure no usernames input is handled"""
    instapy = InstaPy(selenium_local_session=False)
    res = instapy.interact_by_users(None)
    assert isinstance(res, InstaPy)
    assert instapy.liked_img == 0
    assert instapy.already_liked == 0
    assert instapy.inap_img == 0
    assert instapy.commented == 0
Пример #3
0
def test_set_selenium_local_session_supports_chromedriver_version(webdriver):
    """Ensure chromedriver version is supported"""
    webdriver.Chrome.return_value.capabilities = {
        'chrome': {
            'chromedriverVersion':
            '2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91)'
        }
    }
    InstaPy()
Пример #4
0
def test_set_selenium_local_session_raises_missing_chromedriver(webdriver):
    """Ensure chromedriver is installed"""
    webdriver.Chrome.side_effect = WebDriverException()
    with pytest.raises(InstaPyError):
        InstaPy()
Пример #5
0
def test_like_by_users_with_no_usernames():
    """test no inputs returns instance without errors"""
    instapy = InstaPy(selenium_local_session=False)
    res = instapy.like_by_users([])
    assert isinstance(res, InstaPy)
Пример #6
0
def test_set_use_clarifai_raises_on_windows(load_follow_restriction):
    """windows not supported"""
    instapy = InstaPy(selenium_local_session=False)
    with patch('instapy.instapy.os'):
        with pytest.raises(InstaPyError):
            instapy.set_use_clarifai()
Пример #7
0
def addAccount(id_user, id_check):
    #STATUT retour statu en BDD
    #successconnection : connexion reussie
    #falseloginpass: login ou mot de passe faux
    #finishlimit: session fermé en raison d'inactivité
    #pushcode: besoin d'un code authentification
    #repushcode: erreur apres utilisation code authentification

    print("SELENIUM : CREATION SESSION + LACEMENT JUSQU'A ECRAN LOGIN")
    session = InstaPy(username="******",
                      password="******",
                      id_user=id_user,
                      headless_browser=True)

    session.login_create_home()
    login_temp=""
    pass_temp=""
    pid = ""


    currentDT = time.time()
    print("==============>000.1")
    print(str(currentDT))

    #timer pour ne pas depasser 300sec
    t0 = time.time()
    print("ON ATTEND ENSUITE QUE L'UTILISATEUR ENVOI SON LOGIN/PASS")
    while not login_temp:

        #on check les infos en base
        cur = cursor()
        sql = """SELECT login_temp,pass_temp,id_processpython  FROM processlogin WHERE id_user=%s and id_check=%s order by start_date desc  limit 1 """
        #print(sql)
        val = (id_user, id_check)
        cur.execute(sql, val)
        myresult = cur.fetchall()

        for row in myresult:
            login_temp = row[0]
            pass_temp = row[1]
            pid= row[2]

        #print(login_temp)
        #print(pass_temp)
        #print(pid)



        #si le temps depasse 5min, on kill le process
        t1 = time.time()
        if (t1 - t0) >300 :

            # UPDATE : TIMELIMIT
            cur = cursor()
            sql = """update processlogin set statut=%s WHERE id_user=%s and id_check=%s order by start_date desc  limit 1 """
            print("================>")
            val = ("finishlimit", id_user, id_check)
            cur.execute(sql, val)
            ############################
            print("On Kill d'abord la session selenium, puis le process python pour inactivité")
            session.end()
            os.kill(pid, signal.SIGTERM)

        time.sleep(1)


    currentDT = time.time()
    print("==============>000.2")
    print(str(currentDT))


    #on ajoute le login/mot de passe a la session
    session.username = login_temp.replace(" ", "")
    session.password = pass_temp.replace(" ", "")


    #dossier pour les cookies
    session.logfolder = '{0}{1}{2}{1}'.format(
        session.logfolderlocation, session.logfolderpath, session.username)
    if not os.path.exists(session.logfolder):
        os.makedirs(session.logfolder)



    currentDT =  time.time()
    print("==============>000.3")
    print(str(currentDT))
    #ON CREE LA SESSION
    result = session.login_create()

    #UPDATE DU MOT DE PASSE SI BON
    cur = cursor()
    sql = """update processlogin set pass_temp="" WHERE id_user=%s and id_check=%s order by start_date desc  limit 1 """
    print("================>")
    val = ( id_user, id_check)
    cur.execute(sql, val)
    #############################################################################


    print(result[0])
    #SI BESOIN AUTHENTIFICATION
    if result[0] == "False:suspicious":

        # UPDATE : ON UPDATE AVEC LE MESSAGE D'AUTHENTIFICATION
        cur = cursor()
        sql = """update processlogin set statut=%s, auth_message=%s WHERE id_user=%s and id_check=%s order by start_date desc  limit 1 """
        val = ("pushcode", result[1], id_user, id_check)
        cur.execute(sql, val)
        ############################
        
        
        # timer pour ne pas depasser 300sec
        t2 = time.time()
        print("ON ATTEND ENSUITE QUE L'UTILISATEUR ENVOI SON CODE D'AUTH")
        while 1:

            #APPEL A LA FONCTION POUR LE CODE
            auth_code = suspiciousCode(id_user, id_check)
            if auth_code!="0":

                print("Le code est bon")
                #ON ATTEND UN RESULTAT EN RETOUR POUR SAVOIR SI LE CODE A FONCTIONNE, ET DONC LE COMPTE EST LOGGÉ
                session.code=auth_code
                result = session.suspiciouscodeinsta()
                #si c'est bon

                #SI LE CODE EST BON : ON CLOS LA SESSION, SINAN ON ATTEND DE NOUVEAU UN CODE
                if result :
                    # UPDATE : FINISH
                    cur = cursor()
                    sql = """update processlogin set statut=%s WHERE id_user=%s and id_check=%s order by start_date desc  limit 1 """
                    val = ("successconnection", id_user, id_check)
                    cur.execute(sql, val)
                    ############################
                    print("On Kill d'abord la session selenium, puis le process python pour inactivité")
                    session.end()
                    os.kill(pid, signal.SIGTERM)
                else :
                    # UPDATE : statut + on remet le code a 0 e
                    cur = cursor()
                    sql = """update processlogin set statut=%s, auth_code=0 WHERE id_user=%s and id_check=%s order by start_date desc  limit 1 """
                    val = ("repushcode", id_user, id_check)
                    cur.execute(sql, val)

                    ##############################
                    print("CODE AUTH NE MARCHE PAS, A RETESTER")

            t3 = time.time()
            if (t2 - t3) > 300:
                # si le temps depasse 5min, on kill le process
                # UPDATE : TIMELIMIT
                cur = cursor()
                sql = """update processlogin set statut=%s WHERE id_user=%s and id_check=%s order by start_date desc  limit 1 """
                val = ("finishlimit", id_user, id_check)
                cur.execute(sql, val)
                ############################
                print("On Kill d'abord la session selenium, puis le process python pour inactivité")
                session.end()
                os.kill(pid, signal.SIGTERM)
            time.sleep(1)


    # UPDATE FINISH:message
    if result[0] == "True:success":
        cur = cursor()
        sql = """update processlogin set statut=%s WHERE id_user=%s and id_check=%s order by start_date desc  limit 1 """
        val = ("successconnection", id_user, id_check)
        cur.execute(sql, val)

    if result[0] == "False:loginpass":
        cur = cursor()
        sql = """update processlogin set statut=%s WHERE id_user=%s and id_check=%s order by start_date desc  limit 1 """
        val = ("falseloginpass", id_user, id_check)
        cur.execute(sql, val)

    #ON CLOS LA SESSION ET LE PROCESS
    ############################
    session.end()
    os.kill(pid, signal.SIGTERM)
Пример #8
0
def run_app1(id_insta):

    #childprocess.append(multiprocessing.current_process().pid)
    #print("list de child", childprocess)

    #print("le processur pour l'utilisateur", insta_username , "est : ", os.getpid())

    #print("pass", insta_username,insta_password )
    # get an InstaPy session!
    # set headless_browser=True to run InstaPy in the background

    print("MULTI - Started at", datetime.datetime.now().strftime("%H:%M:%S"))


    #on recupere toutes les données de l'user
    insta_username=instausername(id_insta)
    insta_password=instapassword(id_insta)


    session = InstaPy(username=insta_username,
                      password=insta_password,
                      headless_browser=True)

    with smart_run(session):
        """ Activity flow """
        # general settings

        ###############################################################################
        ################# BOUCLE -- BOUCLE -- BOUCLE -- BOUCLE -- BOUCLE ##############
        ###############################################################################
        while True:


            print("NOMBRE CONFIG==============>")
            #POUR N CONFIG : on parcoure
            n_config = nb_configuser(id_insta)
            print(n_config)


            #si aucune config (par precaution)
            if n_config==0:
                create_config(id_insta)

            # on recupere les infos a chaque fois pour updater le profil / en compélement du process stats
            session.getinfos(id_insta, insta_username)


            for x in range(0, n_config):

                #pour avoir le bon numero de config, on rajoute 1
                numConfig=x+1
                # ON CHERCHE LA CONFIG DE L'UTILISATEUR
                configuserinsta = configuser(id_insta, numConfig)

                #Boost a 0 de base
                boost = 0


                # ON REGARDE S'IL A UN BOOST (null : n'existe pas, 0 : deja utilisé dans la journée , 1: a utiliser
                if (getBoostUser(id_insta)>=1):
                    nbactions = random.randrange(80, 90)
                    nbactionsFollow = random.randrange(30, 40)
                    #on enleve donc un boost
                    boost=getBoostUser(id_insta)
                else:
                    nbactions = random.randrange(12, 16)
                    nbactionsFollow = random.randrange(5, 8)


                for row in configuserinsta:
                    id_instaconfig = row[0]
                    n_config = row[1]
                    actionL = row[2]
                    actionC = row[3]
                    actionF = row[4]
                    actionU = row[5]
                    minfollowing = row[6]
                    maxfollowing = row[7]
                    minfollowers = row[8]
                    maxfollowers = row[9]


                session.set_relationship_bounds(enabled=True,
                                                delimit_by_numbers=True,
                                                max_followers=maxfollowers,
                                                min_followers=minfollowers,
                                                max_following=maxfollowing,
                                                min_following=minfollowing)


                #session.set_dont_include(["friend1", "friend2", "friend3"])
                #session.set_dont_like(["pizza", "#store"])



                #NOT INCLUDE IN SESSION
               # notLike= getNotLikeUser(id_insta)
               # session.set_dont_like(notLike)
               # print('Not Likes like like sont [%s]' % ', '.join(map(str, notLike)))

               # notInclude=getNotIncludeBio(id_insta)
               # session.set_dont_include(notInclude)
               # print('Not include sont [%s]' % ', '.join(map(str, notInclude)))

                likesTags = getLikesTags(id_insta, numConfig)
                print('les tags de like sont [%s]' % ', '.join(map(str, likesTags)))

                commentTags = getCommentsTags(id_insta, numConfig)
                print('les tags de commentaires sont [%s]' % ', '.join(map(str, commentTags)))

                actionL = 0
                actionC = 0
                actionF = 0
                actionU = 0

                # pour le comment : implique que le like soit activé
                if actionC == 1:
                    print("COMMENT --------->")
                    session.set_do_comment(enabled=True, percentage=25)
                    session.set_comments(commentTags)

                #pour le like
                if actionL == 1:
                    print("LIKE --------->")
                    nblikes=nbactions
                    print('le nombre de likes sera de : ',nbactions )
                    session.like_by_tags(likesTags,id_insta, amount=nbactions)



                # pour le follow
                if actionF == 1:
                    print("FOLLOW --------->")
                    nbfollows=nbactionsFollow
                    print('le nombre de follow sera de : ', nbfollows)
                    session.follow_by_tags(likesTags, id_insta,amount=nbfollows)

                # pour le unfollow
                if actionU == 1:
                    print("UNFOLLOW --------->")
                    #pour ne pas enlever les followers actifs  des 15derniers posts
                    session.set_dont_unfollow_active_users(enabled=True, posts=15)
                    print("action Unfollow")


                    session.unfollow_users(id_insta,amount=2, InstapyFollowed=(True, "nonfollowers"), style="FIFO", unfollow_after=60*60, sleep_delay=501)


                # for unfollow, verify date of first follow
                # session.unfollow_users(amount=random.randint(7, 10), sleep_delay=(random.randint(44, 111)))
                # session.set_dont_unfollow_active_users(enabled=True, posts=7)
                # session.follow_by_list(followlist=['portraitographers'], times=2, sleep_delay=600, interact=True)


                #ON UPDATE LE BOOST A 0 POUR DIRE QU'IL A ETE VALDIDE
                if (boost >= 1):
                    updateBoostUser(id_insta, boost)

                ######################################################

                #pause et insertion de la pause dans les logs
                timeDelay = random.randrange(1000, 1300)
                print("-------> sleep while:", timeDelay/60, "minutes")
                cur=cursor()
                sql_insert_query = """ INSERT INTO `logs`(`type`,`user` ) VALUES (%s, %s)"""
                val = ("pause", timeDelay)
                result = cur.execute(sql_insert_query, val)
                time.sleep(timeDelay)


        ###############################################################################
        ################# FIN BOUCLE -- FIN BOUCLE -- FIN BOUCLE  #####################
        ###############################################################################


        #session.end()
        print("ERROR -finished with error at",datetime.datetime.now().strftime("%H:%M:%S"))