예제 #1
0
파일: serv.py 프로젝트: qxZap/Coliw
def client_thread(conn,addr):
    loggedIn = False
    loggedInIG = False
    userInstagram= None
    username=None
    while True:
        try:
            data = conn.recv(1024)
        except Exception as disconnected:
            print("[-] Disconnected "+addr[0]+":"+str(addr[1]))
            q=disconnected
            break
        if not data:
            break
        arguments = data.split(" ")
        
        if arguments[0]=='--help' or arguments[0]=='-h':
            to_send="CoLiW\n\nCommands:\n\tlogin\n\tlogout\n\tregister\n\tweb module\n\thistory"
        
        elif arguments[0] == "login":
            if loggedIn==True:
                to_send="You are already logged in"
                
            else:
                if len(arguments)<3:
                    to_send="Too few arguments!\nSyntax: login <username> <password>"
                elif len(arguments)>3:
                    to_send="Too many arguments!\nSyntax: login <username> <password>"
                else:
                    db = MySQLdb.connect(host="localhost", user="******", passwd="", db="aplicatiebd")
                    cur = db.cursor()
                    stringalau="SELECT password FROM USERS WHERE username ='******'"
                    cur.execute(stringalau)
                    if arguments[2]==cur.fetchall()[0][0]:
                        loggedIn=True
                        username=arguments[1]
                        to_send="Login sucessfull"
                    else:
                        to_send="Wrong creditals"
                
        
        
            #flag = subprocess.check_output([sys.executable, "login.py", arguments[1], arguments[2]])
            
            #if flag == '1\n':
            #    to_send = "Login sucessfull"
            #    loggedIn = True
            #else:
            #    to_send = "Error with login creditals. Check again your user/password"
        elif arguments[0]=='history':
            if loggedIn:
                if len(arguments)==2:
                    if arguments[1]=='-h':
                        to_send="Hystory\nBasicly, it prints command history of the user\n\n\t-h prints this message\n\t-o prints output also (rather not)\n\t-c clears the history"
                    elif arguments[1]=='-o':
                        db = MySQLdb.connect(host="localhost", user="******", passwd="", db="aplicatiebd")
                        cur=db.cursor()
                        stringalau="SELECT command,output from history where username='******'"
                        cur.execute(stringalau)
                        output=cur.fetchall()
                        sortedOutput=list(set(output))
                        to_send=""
                        for i in sortedOutput:
                            to_send=to_send+i[0]+"\t\t"+i[1]+"\n"
                    elif arguments[1]=='-c':
                        flag=subprocess.check_output( [sys.executable, "clearHistory.py", username])
                        to_send="History cleared"
                    else:
                        to_send="Expected -o -h or -c and recieved"+arguments[1]
                        
                elif len(arguments)==1:
                    db = MySQLdb.connect(host="localhost", user="******", passwd="", db="aplicatiebd")
                    cur=db.cursor()
                    stringalau="SELECT command from history where username='******'"
                    cur.execute(stringalau)
                    output=cur.fetchall()
                    sortedOutput=list(set(output))
                    to_send=""
                    for i in sortedOutput:
                        to_send=to_send+i[0]+"\n"
                else:
                    to_send="Wrong syntax\nType in 'history -h' for more info"
            else:
                to_send="You cannot use this command if you`re not logged in"
            
        elif arguments[0] == "register":
            if loggedIn==True:
                to_send="You cannot register while you are logged in already"
            else:
                if len(arguments)<4:
                    to_send="Too few arguments!\nSyntax: register <username> <password> <email>"
                elif len(arguments)>4:
                    to_send="Too many arguments!\nSyntax: register <username> <password> <email>"
                else:
                    db = MySQLdb.connect(host="localhost", user="******", passwd="", db="aplicatiebd")
                    cur = db.cursor()
                    stringalau="SELECT id FROM USERS WHERE username ='******'"
                    cur.execute(stringalau)
                    if len(cur.fetchall())>0:
                        to_send="There is already someone called "+arguments[1]
                    else:
                        stringalau="INSERT INTO users(username,password,email) VALUES('"+arguments[1]+"','"+arguments[2]+"','"+arguments[3]+"');"
                        cur.execute(stringalau)
                        db.commit()
                        to_send="You`ve been registred and now you`re logged in"
                        loggedIn=True
                        username=arguments[1]
        elif arguments[0]=='logout':
            to_send="Logged out"
            loggedIn=False
                    
        
        
        
            #flag = subprocess.check_output([sys.executable, "register.py", arguments[1], arguments[2], arguments[3]])
            #if flag == "True\n":
            #    to_send = "You have been registered!"
            #else:
            #    to_send = "There is someone called " + arguments[1]
                
        elif arguments[0]=="web":
            if loggedIn==False:
                to_send="You have to be logged in to use web module."
            else:
                if len(arguments)>1:
                    if arguments[1]=='-h':
                        to_send="CoLiW Web Module\n\tinstagram API\n\tflickr API"
                    elif arguments[1]=="instagram":
                        if len(arguments)==2:
                            to_send="Invalid syntax.\nType in web instagram -h"
                        else:
                        #web instagram login username passwd
                            if arguments[2]=="login":
                                if len(arguments)>5:
                                    to_send="Too many arguments\nSyntax: web instagram login <username> <password>"
                                elif len(arguments)<5:
                                    to_send="Too few arguments\nSyntax: web instagram login <username> <password>"
                                else:
                                    userInstagram=InstagramAPI(arguments[3],arguments[4])
                                    if(userInstagram.login()):
                                        to_send="You`ve logged in through Instagram. Now you can use it as you desire"
                                        loggedInIG = True
                                    else:
                                        to_send="Wrong username/password. try again after you check them again"
                            elif arguments[2]=='logout':
                                if loggedInIG:
                                    loggedInIG=False
                                    userInstagram=None
                                    to_send="Logged out"
                                else:
                                    to_send="You cannot log out if you`re not logged in"
                                
                                

                            elif arguments[2]=="follow":
                                if loggedInIG == True :
                                    #returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]])
                                    returnID=getIDbyUsername(arguments[3])
                                    if returnID[len(returnID)-1]=='"':
                                        returnID=returnID[:-1]
                                    userInstagram.follow(returnID)
                                    to_send="Now following "+arguments[3]
                                else:
                                    to_send="You have to be logged in with instagram\nUse web instagram -h for more info"
                                    
                            elif arguments[2] == "unfollow":
                                if loggedInIG==True:
                                    #returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]])
                                    returnID=getIDbyUsername(arguments[3])
                                    if returnID[len(returnID)-1]=='"':
                                        returnID=returnID[:-1]
                                    userInstagram.unfollow(returnID)
                                    to_send="Now not following "+arguments[3]+" anymore"
                                else:
                                    to_send="You have to be logged in with instagram\nUse web instagram -h for more info"
                            elif arguments[2] == 'block':
                                if loggedInIG==True:
                                    returnID=getIDbyUsername(arguments[3])
                                    if returnID[len(returnID)-1]=='"':
                                        returnID=returnID[:-1]
                                    userInstagram.block(returnID)
                                    to_send=+arguments[3]+" been blocked"
                                else:
                                    to_send="You have to be logged in with instagram\nUse web instagram -h for more info"
                            elif arguments[2] == 'unblock':
                                if loggedInIG==True:
                                    returnID=getIDbyUsername(arguments[3])
                                    if returnID[len(returnID)-1]=='"':
                                        returnID=returnID[:-1]
                                    userInstagram.unblock(returnID)
                                    to_send=+arguments[3]+" been unblocked"
                                else:
                                    to_send="You have to be logged in with instagram\nUse web instagram -h for more info"
                                    
                            elif arguments[2]=="upload":
                                if loggedInIG == True:
                                    if arguments[3]=="photo":
                                        caption=""
                                        for i in arguments[4:]:
                                            caption+=str(i)+" "
                                        uploadPhoto(arguments[4], caption)
                            elif arguments[2]=='-h':
                                to_send="Instagram API in Coliw\n\n\tsyntax: web instagram <follow/unfollow/login/block/unblock> <username>"
                    elif arguments[1] == "flickr":
                        continueT=True
                        index_to_start=0
                        number_of_photos=0
                        #web flickr
                        if len(arguments)==2:
                            to_send="no arguments given!"
                        #web flickr <tag>
                        elif len(arguments)==3:
                            if arguments[2]=='-h':
                                to_send="\nFlickr api\nSyntax: web flickr <keyword> <options>\n\n\t-i start index ( 0 as default )\n\t-n number of photos ( 1 as default )"
                                continueT=False
                            else:
                                index_to_start=1
                                number_of_photos=1
                            
                        elif len(arguments)==5:
                            if arguments[3]=='-i':
                                if arguments[4].isdigit():
                                    index_to_start=int(arguments[4])
                                else:
                                    continueT=False
                                    to_send=argument[4]+" is not a number"
                        
                            elif arguments[3]=='-n':
                                if arguments[4].isdigit():
                                    number_of_photos=int(arguments[4])
                                else:
                                    continueT=False
                                    to_send=argument[4]+" is not a number"
                        
                        
                            
                        elif len(arguments)==6:
                            if arguments[3]=='-in':
                                
                                if arguments[4].isdigit():
                                    index_to_start=int(arguments[4])
                                else:
                                    continueT=False
                                    to_send=arguments[4]+" is not a number"
                                     
                                if arguments[5].isdigit():
                                    number_of_photos=int(arguments[5])
                                else:
                                    continueT=False
                                    to_send=arguments[5]+" is not a number"
                                    
                            elif arguments[3]=='-ni':
                                    
                                if arguments[4].isdigit():
                                    number_of_photos=int(arguments[4])
                                else:
                                    continueT=False
                                    to_send=arguments[4]+" is not a number"
                                        
                                if arguments[5].isdigit():
                                    index_to_start=int(arguments[5])
                                else:
                                    continueT=False
                                    to_send=arguments[5]+" is not a number"                                    
                        elif len(arguments)==7:
                            if arguments[3]=='-i' and arguments[5]=='-n':
                                if arguments[4].isdigit():
                                    if arguments[6].isdigit():
                                        index_to_start=int(arguments[4])
                                        number_of_photos=int(arguments[6])
                                    else:
                                        continueT=False
                                        to_send=arguments[6]+" is not a number"
                                else:
                                    continueT=False
                                    to_send=arguments[4]+" is not a number"
                            
                            elif arguments[3]=='-n' and arguments[5]=='-i':
                                if arguments[4].isdigit():
                                    if arguments[6].isdigit():
                                        number_of_photos=int(arguments[4])
                                        index_to_start=int(arguments[6])
                                    else:
                                        continueT=False
                                        to_send=arguments[6]+" is not a number"
                                else:
                                    continueT=False
                                    to_send=arguments[4]+" is not a number"
                            elif arguments[3]==arguments[5]:
                                continueT=False
                                to_send="3rd and 5th argument cannot be even"
                            else:
                                continueT=False
                                to_send="Wrong syntax, expected -i or -n on the 3rd or 5th"
                        
                        
                        else:
                            to_send="Too many arguments given/wrong syntax"
                            continueT=False
                        if continueT:
                            #to_send="Right syntax/ you wanna search "+arguments[2]+" index="+str(index_to_start)+" no="+str(number_of_photos)
                            startUP=0
                            startDOWN=0
                            if number_of_photos==0:
                                number_of_photos=1
                            if number_of_photos==1 and index_to_start==1:
                                startUP=0
                                startDOWN=1
                            elif index_to_start==0 and number_of_photos>1:
                                startUP=0
                                startDOWN=number_of_photos
                            elif index_to_start>1 and number_of_photos==1:
                                startUP=index_to_start
                                startDOWN=index_to_start+1
                            elif index_to_start>1 and number_of_photos>1:
                                startUP=index_to_start
                                startDOWN=startUP+number_of_photos
                            elif index_to_start==1 and number_of_photos>1:
                                startUP=index_to_start
                                startDOWN=number_of_photos+1
                            elif index_to_start==0 and number_of_photos==1:
                                startUP=0
                                startDOWN=1
                                
                            
                                
                            
                            
                                
                            flickr = flickrapi.FlickrAPI('e57cfa37f00d7a9a5d7fac7e37ebcbb5', '00751b0c7b65ba7a',format='parsed-json')
                            extras = 'url_sq,url_t,url_s,url_q,url_m,url_n,url_z,url_c,url_l,url_o'
                            links = ""
                            cats = flickr.photos.search(text=arguments[2], per_page=startDOWN+startUP, extras=extras)
                                
                            for i in range(startUP, startDOWN):
                                photos = cats['photos']['photo'][i]['url_m']
                                links =links+photos + '\n'
                            links=links[:-1] 
                            to_send=links
                            
                    else:
                        to_send="unknown web command"
                else:
                    to_send="too few arguments known"
                 
        else:
            to_send=arguments[0]+" is not recognized"
        if loggedIn:
            print subprocess.check_output( [sys.executable, "addCMD.py", username,data, to_send])
        reply = to_send
        conn.send(reply.encode('ascii'))
    conn.close()
예제 #2
0
파일: serv.py 프로젝트: qxZap/Coliw
def client_thread(conn, addr):
    loggedIn = False
    loggedInIG = False
    userInstagram = None
    username = None
    while True:
        try:
            data = conn.recv(1024)
        except Exception as disconnected:
            print("[-] Disconnected " + addr[0] + ":" + str(addr[1]))
            q = disconnected
            break
        if not data:
            break
        arguments = data.split(" ")

        if arguments[0] == '--help' or arguments[0] == '-h':
            to_send = "CoLiW\n\nCommands:\n\tlogin\n\tlogout\n\tregister\n\tweb module\n\thistory"

        elif arguments[0] == "login":
            if loggedIn == True:
                to_send = "You are already logged in"

            else:
                if len(arguments) < 3:
                    to_send = "Too few arguments!\nSyntax: login <username> <password>"
                elif len(arguments) > 3:
                    to_send = "Too many arguments!\nSyntax: login <username> <password>"
                else:
                    db = MySQLdb.connect(host="localhost",
                                         user="******",
                                         passwd="",
                                         db="aplicatiebd")
                    cur = db.cursor()
                    stringalau = "SELECT password FROM USERS WHERE username ='******'"
                    cur.execute(stringalau)
                    if arguments[2] == cur.fetchall()[0][0]:
                        loggedIn = True
                        username = arguments[1]
                        to_send = "Login sucessfull"
                    else:
                        to_send = "Wrong creditals"

            #flag = subprocess.check_output([sys.executable, "login.py", arguments[1], arguments[2]])

            #if flag == '1\n':
            #    to_send = "Login sucessfull"
            #    loggedIn = True
            #else:
            #    to_send = "Error with login creditals. Check again your user/password"
        elif arguments[0] == 'history':
            if loggedIn:
                if len(arguments) == 2:
                    if arguments[1] == '-h':
                        to_send = "Hystory\nBasicly, it prints command history of the user\n\n\t-h prints this message\n\t-o prints output also (rather not)\n\t-c clears the history"
                    elif arguments[1] == '-o':
                        db = MySQLdb.connect(host="localhost",
                                             user="******",
                                             passwd="",
                                             db="aplicatiebd")
                        cur = db.cursor()
                        stringalau = "SELECT command,output from history where username='******'"
                        cur.execute(stringalau)
                        output = cur.fetchall()
                        sortedOutput = list(set(output))
                        to_send = ""
                        for i in sortedOutput:
                            to_send = to_send + i[0] + "\t\t" + i[1] + "\n"
                    elif arguments[1] == '-c':
                        flag = subprocess.check_output(
                            [sys.executable, "clearHistory.py", username])
                        to_send = "History cleared"
                    else:
                        to_send = "Expected -o -h or -c and recieved" + arguments[
                            1]

                elif len(arguments) == 1:
                    db = MySQLdb.connect(host="localhost",
                                         user="******",
                                         passwd="",
                                         db="aplicatiebd")
                    cur = db.cursor()
                    stringalau = "SELECT command from history where username='******'"
                    cur.execute(stringalau)
                    output = cur.fetchall()
                    sortedOutput = list(set(output))
                    to_send = ""
                    for i in sortedOutput:
                        to_send = to_send + i[0] + "\n"
                else:
                    to_send = "Wrong syntax\nType in 'history -h' for more info"
            else:
                to_send = "You cannot use this command if you`re not logged in"

        elif arguments[0] == "register":
            if loggedIn == True:
                to_send = "You cannot register while you are logged in already"
            else:
                if len(arguments) < 4:
                    to_send = "Too few arguments!\nSyntax: register <username> <password> <email>"
                elif len(arguments) > 4:
                    to_send = "Too many arguments!\nSyntax: register <username> <password> <email>"
                else:
                    db = MySQLdb.connect(host="localhost",
                                         user="******",
                                         passwd="",
                                         db="aplicatiebd")
                    cur = db.cursor()
                    stringalau = "SELECT id FROM USERS WHERE username ='******'"
                    cur.execute(stringalau)
                    if len(cur.fetchall()) > 0:
                        to_send = "There is already someone called " + arguments[
                            1]
                    else:
                        stringalau = "INSERT INTO users(username,password,email) VALUES('" + arguments[
                            1] + "','" + arguments[2] + "','" + arguments[
                                3] + "');"
                        cur.execute(stringalau)
                        db.commit()
                        to_send = "You`ve been registred and now you`re logged in"
                        loggedIn = True
                        username = arguments[1]
        elif arguments[0] == 'logout':
            to_send = "Logged out"
            loggedIn = False

            #flag = subprocess.check_output([sys.executable, "register.py", arguments[1], arguments[2], arguments[3]])
            #if flag == "True\n":
            #    to_send = "You have been registered!"
            #else:
            #    to_send = "There is someone called " + arguments[1]

        elif arguments[0] == "web":
            if loggedIn == False:
                to_send = "You have to be logged in to use web module."
            else:
                if len(arguments) > 1:
                    if arguments[1] == '-h':
                        to_send = "CoLiW Web Module\n\tinstagram API\n\tflickr API"
                    elif arguments[1] == "instagram":
                        if len(arguments) == 2:
                            to_send = "Invalid syntax.\nType in web instagram -h"
                        else:
                            #web instagram login username passwd
                            if arguments[2] == "login":
                                if len(arguments) > 5:
                                    to_send = "Too many arguments\nSyntax: web instagram login <username> <password>"
                                elif len(arguments) < 5:
                                    to_send = "Too few arguments\nSyntax: web instagram login <username> <password>"
                                else:
                                    userInstagram = InstagramAPI(
                                        arguments[3], arguments[4])
                                    if (userInstagram.login()):
                                        to_send = "You`ve logged in through Instagram. Now you can use it as you desire"
                                        loggedInIG = True
                                    else:
                                        to_send = "Wrong username/password. try again after you check them again"
                            elif arguments[2] == 'logout':
                                if loggedInIG:
                                    loggedInIG = False
                                    userInstagram = None
                                    to_send = "Logged out"
                                else:
                                    to_send = "You cannot log out if you`re not logged in"

                            elif arguments[2] == "follow":
                                if loggedInIG == True:
                                    #returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]])
                                    returnID = getIDbyUsername(arguments[3])
                                    if returnID[len(returnID) - 1] == '"':
                                        returnID = returnID[:-1]
                                    userInstagram.follow(returnID)
                                    to_send = "Now following " + arguments[3]
                                else:
                                    to_send = "You have to be logged in with instagram\nUse web instagram -h for more info"

                            elif arguments[2] == "unfollow":
                                if loggedInIG == True:
                                    #returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]])
                                    returnID = getIDbyUsername(arguments[3])
                                    if returnID[len(returnID) - 1] == '"':
                                        returnID = returnID[:-1]
                                    userInstagram.unfollow(returnID)
                                    to_send = "Now not following " + arguments[
                                        3] + " anymore"
                                else:
                                    to_send = "You have to be logged in with instagram\nUse web instagram -h for more info"
                            elif arguments[2] == 'block':
                                if loggedInIG == True:
                                    returnID = getIDbyUsername(arguments[3])
                                    if returnID[len(returnID) - 1] == '"':
                                        returnID = returnID[:-1]
                                    userInstagram.block(returnID)
                                    to_send = +arguments[3] + " been blocked"
                                else:
                                    to_send = "You have to be logged in with instagram\nUse web instagram -h for more info"
                            elif arguments[2] == 'unblock':
                                if loggedInIG == True:
                                    returnID = getIDbyUsername(arguments[3])
                                    if returnID[len(returnID) - 1] == '"':
                                        returnID = returnID[:-1]
                                    userInstagram.unblock(returnID)
                                    to_send = +arguments[3] + " been unblocked"
                                else:
                                    to_send = "You have to be logged in with instagram\nUse web instagram -h for more info"

                            elif arguments[2] == "upload":
                                if loggedInIG == True:
                                    if arguments[3] == "photo":
                                        caption = ""
                                        for i in arguments[4:]:
                                            caption += str(i) + " "
                                        uploadPhoto(arguments[4], caption)
                            elif arguments[2] == '-h':
                                to_send = "Instagram API in Coliw\n\n\tsyntax: web instagram <follow/unfollow/login/block/unblock> <username>"
                    elif arguments[1] == "flickr":
                        continueT = True
                        index_to_start = 0
                        number_of_photos = 0
                        #web flickr
                        if len(arguments) == 2:
                            to_send = "no arguments given!"
                        #web flickr <tag>
                        elif len(arguments) == 3:
                            if arguments[2] == '-h':
                                to_send = "\nFlickr api\nSyntax: web flickr <keyword> <options>\n\n\t-i start index ( 0 as default )\n\t-n number of photos ( 1 as default )"
                                continueT = False
                            else:
                                index_to_start = 1
                                number_of_photos = 1

                        elif len(arguments) == 5:
                            if arguments[3] == '-i':
                                if arguments[4].isdigit():
                                    index_to_start = int(arguments[4])
                                else:
                                    continueT = False
                                    to_send = argument[4] + " is not a number"

                            elif arguments[3] == '-n':
                                if arguments[4].isdigit():
                                    number_of_photos = int(arguments[4])
                                else:
                                    continueT = False
                                    to_send = argument[4] + " is not a number"

                        elif len(arguments) == 6:
                            if arguments[3] == '-in':

                                if arguments[4].isdigit():
                                    index_to_start = int(arguments[4])
                                else:
                                    continueT = False
                                    to_send = arguments[4] + " is not a number"

                                if arguments[5].isdigit():
                                    number_of_photos = int(arguments[5])
                                else:
                                    continueT = False
                                    to_send = arguments[5] + " is not a number"

                            elif arguments[3] == '-ni':

                                if arguments[4].isdigit():
                                    number_of_photos = int(arguments[4])
                                else:
                                    continueT = False
                                    to_send = arguments[4] + " is not a number"

                                if arguments[5].isdigit():
                                    index_to_start = int(arguments[5])
                                else:
                                    continueT = False
                                    to_send = arguments[5] + " is not a number"
                        elif len(arguments) == 7:
                            if arguments[3] == '-i' and arguments[5] == '-n':
                                if arguments[4].isdigit():
                                    if arguments[6].isdigit():
                                        index_to_start = int(arguments[4])
                                        number_of_photos = int(arguments[6])
                                    else:
                                        continueT = False
                                        to_send = arguments[
                                            6] + " is not a number"
                                else:
                                    continueT = False
                                    to_send = arguments[4] + " is not a number"

                            elif arguments[3] == '-n' and arguments[5] == '-i':
                                if arguments[4].isdigit():
                                    if arguments[6].isdigit():
                                        number_of_photos = int(arguments[4])
                                        index_to_start = int(arguments[6])
                                    else:
                                        continueT = False
                                        to_send = arguments[
                                            6] + " is not a number"
                                else:
                                    continueT = False
                                    to_send = arguments[4] + " is not a number"
                            elif arguments[3] == arguments[5]:
                                continueT = False
                                to_send = "3rd and 5th argument cannot be even"
                            else:
                                continueT = False
                                to_send = "Wrong syntax, expected -i or -n on the 3rd or 5th"

                        else:
                            to_send = "Too many arguments given/wrong syntax"
                            continueT = False
                        if continueT:
                            #to_send="Right syntax/ you wanna search "+arguments[2]+" index="+str(index_to_start)+" no="+str(number_of_photos)
                            startUP = 0
                            startDOWN = 0
                            if number_of_photos == 0:
                                number_of_photos = 1
                            if number_of_photos == 1 and index_to_start == 1:
                                startUP = 0
                                startDOWN = 1
                            elif index_to_start == 0 and number_of_photos > 1:
                                startUP = 0
                                startDOWN = number_of_photos
                            elif index_to_start > 1 and number_of_photos == 1:
                                startUP = index_to_start
                                startDOWN = index_to_start + 1
                            elif index_to_start > 1 and number_of_photos > 1:
                                startUP = index_to_start
                                startDOWN = startUP + number_of_photos
                            elif index_to_start == 1 and number_of_photos > 1:
                                startUP = index_to_start
                                startDOWN = number_of_photos + 1
                            elif index_to_start == 0 and number_of_photos == 1:
                                startUP = 0
                                startDOWN = 1

                            flickr = flickrapi.FlickrAPI(
                                'e57cfa37f00d7a9a5d7fac7e37ebcbb5',
                                '00751b0c7b65ba7a',
                                format='parsed-json')
                            extras = 'url_sq,url_t,url_s,url_q,url_m,url_n,url_z,url_c,url_l,url_o'
                            links = ""
                            cats = flickr.photos.search(text=arguments[2],
                                                        per_page=startDOWN +
                                                        startUP,
                                                        extras=extras)

                            for i in range(startUP, startDOWN):
                                photos = cats['photos']['photo'][i]['url_m']
                                links = links + photos + '\n'
                            links = links[:-1]
                            to_send = links

                    else:
                        to_send = "unknown web command"
                else:
                    to_send = "too few arguments known"

        else:
            to_send = arguments[0] + " is not recognized"
        if loggedIn:
            print subprocess.check_output(
                [sys.executable, "addCMD.py", username, data, to_send])
        reply = to_send
        conn.send(reply.encode('ascii'))
    conn.close()
from InstagramAPI import InstagramAPI
from Application.get_blacklist import get_blacklist
import configuration
import time
from random import randint
from Application.remove_from_blacklist import remove_from_blacklist

if __name__ == "__main__":
    api = InstagramAPI(configuration.username, configuration.password)
    api.login()

    blacklist = get_blacklist()

    for pk in blacklist:
        api.block(int(pk))
        print("Blocked:", pk)

        remove_from_blacklist(pk)
        time.sleep(randint(5, 15))
예제 #4
0
class Instagram(ApiInterface):
    """ Wrapper for accessing the instagram API  """
    def __init__(self) -> None:
        # Store keys and api info
        self.keys = InstagramKey()
        self.api = InstagramAPI(self.keys.username, self.keys.password)
        self.api.login()

        # Store the authenticated user's Instagram UID
        self.uid = self.api.username_id

        # Memoize follower and following information for the authenticated user
        self.followers: List[_InstagramUser] = self._user_follower_info()
        self.followings: List[_InstagramUser] = self._user_following_info()

        # Specify the output graphfile for follower/time graphing
        self.graphfile = os.path.join('postr', 'instagram',
                                      'instagram_graphing.csv')

        if not os.path.isfile(self.graphfile):
            self.setup_csv()

    def post_text(self, text: str) -> bool:
        """ Not an operation that this platform has. """
        return False

    def post_video(self, url: str, text: str) -> bool:
        """ Not an operations that the Instagram API allows. """
        return False

    def post_photo(self, url: str, text: str) -> bool:
        self.api.uploadPhoto(photo=url, caption=text)
        return False

    def get_user_likes(self) -> int:
        """ Not supported by the API """
        return -1

    def get_user_followers(self, text: str) -> List[str]:
        """ Gets the names of all users followers """
        # Get all follower information
        followers: List[_InstagramUser] = self._user_follower_info()
        # Convert each folllower to just their name
        names: List[str] = list([x.username for x in followers])
        return names

    def remove_post(self, post_id: str) -> bool:
        """ Removes a post, prints an exception if the post doesn't exist """
        try:
            self.api.deleteMedia(mediaId=post_id)
            return True
        except BaseException as e:
            print('Error on data %s' % str(e))
            return False

    def refresh(self) -> None:
        """ Updates the stored contents for a user's followers and followings """
        self.followers = self._user_follower_info()
        self.followings = self._user_following_info()

    @staticmethod
    def direct_share(media_id: str,
                     recipients: List[int],
                     message: str = '') -> None:
        """
        Shares media to a list of recipients via a direct message
        mediaID: The id of the media to share
        recipients: A list of the user ids to share media with
        mesage: The message to go along with the media share
        """
        InstagramAPI.direct_share(media_id, recipients, message)

    def spam_follower_ratio(self, uid: int = 0) -> float:
        """ Determines the ratio of spam followers on a given user.
            Assumption: A spam account is an account with a default profile
            picture, as well as a 10x or greater following/follower ratio """
        # If no uid was specified, use the authenticated user's uid
        if uid == 0:
            uid = self.uid

        # Get the followers for the given uid
        followers: List[_InstagramUser] = self._user_follower_info(uid)

        # Filter the followers based on default profile picture
        default_profile_followers = list(
            [x for x in followers if not x.is_anon])

        # Filter the followers again based on if the remaining are likely to be spam accounts
        spam_default_profiles = list([
            x for x in default_profile_followers
            if self._has_following_ratio_of(x, 10)
        ])

        return len(spam_default_profiles) / len(followers)

    def username_to_id(self, username: str) -> int:
        """
        Converts a username to its associated id

        Unfortunately this isn't built in from the InstagramAPI (they wanted to decrease bot usage)
        so I had to build this myself.

        This function has a small chance of error, as documented in the _username_to_profile() function
        """
        profile_json = self._username_to_profile(username)
        user = Instagram._profile_to_InstagramUser(profile_json)
        return user.uid

    def follow_by_id(self, uid: int) -> None:
        """ Follows a user based off of their uid """
        self.api.follow(uid)

    def unsafe_follow_by_username(self, username: str) -> None:
        """
        Follows a user based off their username
        See the _username_to_profile() function for correctness concerns
        """
        uid = self.username_to_id(username)
        self.api.follow(uid)

    def block_by_id(self, uid: int) -> None:
        """ Blocks a user based off their uid """
        self.api.block(uid)

    def unsafe_block_by_username(self, username: str) -> None:
        """
        Blocks a user based off their username
        Seee the _username_to_profile() function for correctness concerns
        """
        uid = InstagramAPI.username_to_id(username)
        self.api.block(uid)

    def setup_csv(self) -> None:
        """ Initializes a csv file for the time series graphing """
        csvData = ['Followers', 'Time']

        # Create our CSV file header
        with open(self.graphfile, 'w') as csvFile:
            writer = csv.writer(csvFile)
            writer.writerow(csvData)
            csvFile.close()

    def log_followers(self) -> None:
        """ Logs follower information to the graph file """
        with open(self.graphfile, 'a') as gf:
            writer = csv.writer(gf)
            follower_count = len(self.get_user_followers(''))
            date = datetime.datetime.now()

            # Append the current date and follower count to the file
            writer.writerow([date, follower_count])
            gf.close()

    @staticmethod
    def _read_csv_col(colNum: int, filename: str) -> List[str]:
        """ Reads a specific column by index in the graph csv"""
        col = []
        with open(filename, 'r') as rf:
            reader = csv.reader(rf, delimiter=',')
            for row in reader:
                col.append(str(row[colNum]))

        return col[1::]  # Ignore the csv header

    def graph_followers(self) -> None:
        """ Graphs a blob file for twitter sentiment """
        dates = Instagram._read_csv_col(0, self.graphfile)
        # Truncate the datetime object to the minute precision
        dates = [d[:DATETIME_MINUTE_PRECISION] for d in dates]

        followers = [
            int(f) for f in Instagram._read_csv_col(1, self.graphfile)
        ]

        # Get the global maximum follower value and its index
        max_val = max(followers)
        max_index = followers.index(max_val)

        # Plot followers vs. time
        plt.plot(
            dates,
            followers,
        )

        plt.ylabel('Follower count')
        plt.xlabel('Time')

        # Annotate the plot with the global max
        plt.annotate(
            'Absolute max',
            xy=(max_index, max_val),
            xytext=(max_index, max_val + 1),
            arrowprops=dict(facecolor='black', shrink=0.05),
        )

        # beautify the x-labels
        plt.gcf().autofmt_xdate()

        # Set our y-range to be the max value plus a few more, to show the annotation
        plt.ylim(-1, max_val + 3)
        plt.show()

    @staticmethod
    def _profile_to_InstagramUser(profile: Dict[str, Any]) -> _InstagramUser:
        """ Given a user profile JSON, builds an InstagramUser """
        # Navigate to the user JSON that is coincidentally used by the provided API methods
        user = profile['users'][0]['user']

        # Simply build our InstagramUser, as the user JSON is the same
        return _InstagramUser(user)

    def _username_to_profile(self, username: str) -> Dict[str, Any]:
        """
        Creates a json out of a user's profile info given their username

        If the username contains any special characters, or just by random chance, Instagram
        will not return the correct user. Instead, it seems to return any user whose name is
        relatively similar to the given username. Is this a fuzzy matching error?

        I'm not the first to discover this flaw.
        https://stackoverflow.com/a/13586797

        Hopefully Instagram fixes this flaw.
        """

        base_url = self.keys.pre_profile + username + self.keys.rank_token + self.keys.post_profile

        # Build the page source url for the given user's account
        con = urllib.request.urlopen(base_url)
        user_profile = con.read().decode('utf-8')

        # Convert the webpage to a profile JSON
        profile: dict = json.loads(str(user_profile))
        return profile

    def _has_following_ratio_of(self, user: _InstagramUser,
                                ratio: float) -> bool:
        """ Determines if a user has a following/follower ratio greater than a threshold """
        follower_count = len(self._user_follower_info(uid=user.uid))
        following_count = len(self._user_following_info(uid=user.uid))

        if follower_count == 0:
            return True

        return (following_count / follower_count) > ratio

    def _user_follower_info(self, uid: int = 0) -> List[_InstagramUser]:
        """
        Gets info about followers
        rtype: List of JSON representing users
        """
        # If no uid was specified, use the authenticated user's uid
        if uid == 0:
            uid = self.uid

        followers: List[Dict[str, Any]] = self.api.getTotalFollowers(uid)
        user_followers = list([_InstagramUser(x) for x in followers])
        return user_followers

    def _user_following_info(self, uid: int = 0) -> List[_InstagramUser]:
        """
        Gets info about followings
        rtype: List of JSON representing users
        """
        # If no uid was specified, use the authenticated user's uid
        if uid == 0:
            uid = self.uid

        followings: List[Dict[str, Any]] = self.api.getTotalFollowings(uid)
        user_followings = list([_InstagramUser(x) for x in followings])
        return user_followings

    def example_graphing(self) -> None:
        """ Example method demonstrating graphing """
        # Log the current amount of followers to our history of followers
        self.log_followers()

        # Graphs all followers / time
        self.graph_followers()
예제 #5
0
    print(upload_url)
print("Hit Ctrl+C to stop broadcast")
try:
    if TYPE=="2":
        os.system(ffmpeg_cmd)
        print(ffmpeg_cmd)
    while True:
        act = input("1.send comment\n2.block user\n3.get comments\n4.mute comments\n5.unmute comments\n")

        if act=="1":
            postCommentBroadcast(api,broadcast_id,input("Comment: "))
            comment_id = api.LastResponse.json()['comment']['pk']
            pinComment(api,broadcast_id,comment_id)
        elif act=="2":
            user_id = getUserId(input("Username: "******"3":
            try:
                num = int(input("how many? "))
            except:
                print("thats not a valid number\ntry again")
                continue
            getComments(api,broadcast_id,commentsRequested=num)
            if api.LastResponse.status_code >= 400:
                print("Error while retrieving comments")
                continue
            raw_comments = api.LastResponse.json()['comments']
            comments = list()
            for comment in raw_comments:
                comments.append((comment['text'] , comment['user']['username'], comment['pk']))
            for comment in comments: