Ejemplo n.º 1
0
def getConfig(configFileName):
    """Read credentials from config.json file"""

    keys = [
        'reddit_username', 'reddit_password', 'reddit_client_id',
        'reddit_client_secret', 'imgur_client_id', 'imgur_client_secret'
    ]

    if os.path.exists(configFileName):
        FILE = jsonFile(configFileName)
        content = FILE.read()
        for key in keys:
            try:
                if content[key] == "":
                    raise KeyError
            except KeyError:
                print(key, ": ")
                FILE.add({key: input()})
        return jsonFile(configFileName).read()

    else:
        FILE = jsonFile(configFileName)
        configDictionary = {}
        for key in keys:
            configDictionary[key] = input(key + ": ")
        FILE.add(configDictionary)
        return FILE.read()
Ejemplo n.º 2
0
def getConfig(configFileName):
    """Read credentials from config.json file"""

    keys = ['imgur_client_id', 'imgur_client_secret']

    if os.path.exists(configFileName):
        FILE = jsonFile(configFileName)
        content = FILE.read()
        if "reddit_refresh_token" in content:
            if content["reddit_refresh_token"] == "":
                FILE.delete("reddit_refresh_token")
        for key in keys:
            try:
                if content[key] == "":
                    raise KeyError
            except KeyError:
                print(key, ": ")
                FILE.add({key: input()})
        return jsonFile(configFileName).read()

    else:
        FILE = jsonFile(configFileName)
        configDictionary = {}
        for key in keys:
            configDictionary[key] = input(key + ": ")
        FILE.add(configDictionary)
        return FILE.read()
Ejemplo n.º 3
0
def beginPraw(config, user_agent=str(socket.gethostname())):
    """Start reddit instance"""

    scopes = ['identity', 'history', 'read']
    port = "8080"
    arguments = {
        "client_id": GLOBAL.reddit_client_id,
        "client_secret": GLOBAL.reddit_client_secret,
        "user_agent": user_agent
    }

    if "reddit_refresh_token" in GLOBAL.config:
        arguments["refresh_token"] = GLOBAL.config["reddit_refresh_token"]
        reddit = praw.Reddit(**arguments)
        try:
            reddit.auth.scopes()
        except ResponseException:
            arguments["redirect_uri"] = "http://localhost:8080"
            reddit = praw.Reddit(**arguments)
            authorizedInstance = GetAuth(reddit,
                                         port=port).getRefreshToken(*scopes)
            reddit = authorizedInstance[0]
            refresh_token = authorizedInstance[1]
            jsonFile("config.json").add(
                {"reddit_refresh_token": refresh_token})
    else:
        arguments["redirect_uri"] = "http://localhost:8080"
        reddit = praw.Reddit(**arguments)
        authorizedInstance = GetAuth(reddit,
                                     port=port).getRefreshToken(*scopes)
        reddit = authorizedInstance[0]
        refresh_token = authorizedInstance[1]
        jsonFile("config.json").add({"reddit_refresh_token": refresh_token})
    return reddit
Ejemplo n.º 4
0
def getConfig(configFileName):
    """Read credentials from config.json file"""

    keys = ['imgur_client_id', 'imgur_client_secret']

    if os.path.exists(configFileName):
        FILE = jsonFile(configFileName)
        content = FILE.read()
        if "reddit_refresh_token" in content:
            if content["reddit_refresh_token"] == "":
                FILE.delete("reddit_refresh_token")

        if not all(False if content.get(key, "") == "" else True
                   for key in keys):
            print(
                "Go to this URL and fill the form: " \
                "https://api.imgur.com/oauth2/addclient\n" \
                "Enter the client id and client secret here:"
            )
            webbrowser.open("https://api.imgur.com/oauth2/addclient", new=2)

        for key in keys:
            try:
                if content[key] == "":
                    raise KeyError
            except KeyError:
                FILE.add({key: input("  " + key + ": ")})
        return jsonFile(configFileName).read()

    else:
        FILE = jsonFile(configFileName)
        configDictionary = {}
        print(
            "Go to this URL and fill the form: " \
            "https://api.imgur.com/oauth2/addclient\n" \
            "Enter the client id and client secret here:"
            )
        webbrowser.open("https://api.imgur.com/oauth2/addclient", new=2)
        for key in keys:
            configDictionary[key] = input("  " + key + ": ")
        FILE.add(configDictionary)
        return FILE.read()
Ejemplo n.º 5
0
def postFromLog(fileName):
    """Analyze a log file and return a list of dictionaries containing
    submissions
    """

    content = jsonFile(fileName).read()

    try:
        del content["HEADER"]
    except KeyError:
        pass

    posts = []

    for post in content:
        if not content[post][-1]['postType'] == None:
            posts.append(content[post][-1])

    return posts
Ejemplo n.º 6
0
def postFromLog(fileName):
    """Analyze a log file and return a list of dictionaries containing
    submissions
    """
    if Path.is_file(Path(fileName)):
        content = jsonFile(fileName).read()
    else:
        print("File not found")
        sys.exit()

    try:
        del content["HEADER"]
    except KeyError:
        pass

    posts = []

    for post in content:
        if not content[post][-1]['postType'] == None:
            posts.append(content[post][-1])

    return posts
Ejemplo n.º 7
0
def beginPraw(config, user_agent=str(socket.gethostname())):
    class GetAuth:
        def __init__(self, redditInstance, port):
            self.redditInstance = redditInstance
            self.PORT = int(port)

        def recieve_connection(self):
            """Wait for and then return a connected socket..
            Opens a TCP connection on port 8080, and waits for a single client.
            """
            server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server.bind(('localhost', self.PORT))
            server.listen(1)
            client = server.accept()[0]
            server.close()
            return client

        def send_message(self, message):
            """Send message to client and close the connection."""
            self.client.send(
                'HTTP/1.1 200 OK\r\n\r\n{}'.format(message).encode('utf-8'))
            self.client.close()

        def getRefreshToken(self, *scopes):
            state = str(random.randint(0, 65000))
            url = self.redditInstance.auth.url(scopes, state, 'permanent')
            print("Go to this URL and login to reddit:\n\n", url)
            webbrowser.open(url, new=2)

            self.client = self.recieve_connection()
            data = self.client.recv(1024).decode('utf-8')
            str(data)
            param_tokens = data.split(' ', 2)[1].split('?', 1)[1].split('&')
            params = {
                key: value for (key, value) in [token.split('=') \
                for token in param_tokens]
            }
            if state != params['state']:
                self.send_message(
                    client, 'State mismatch. Expected: {} Received: {}'.format(
                        state, params['state']))
                raise RedditLoginFailed
            elif 'error' in params:
                self.send_message(client, params['error'])
                raise RedditLoginFailed

            refresh_token = self.redditInstance.auth.authorize(params['code'])
            self.send_message(
                "<script>" \
                "alert(\"You can go back to terminal window now.\");" \
                "</script>"
            )
            return (self.redditInstance, refresh_token)

    """Start reddit instance"""

    scopes = ['identity', 'history', 'read']
    port = "1337"
    arguments = {
        "client_id": GLOBAL.reddit_client_id,
        "client_secret": GLOBAL.reddit_client_secret,
        "user_agent": user_agent
    }

    if "reddit_refresh_token" in GLOBAL.config:
        arguments["refresh_token"] = GLOBAL.config["reddit_refresh_token"]
        reddit = praw.Reddit(**arguments)
        try:
            reddit.auth.scopes()
        except ResponseException:
            arguments["redirect_uri"] = "http://localhost:" + str(port)
            reddit = praw.Reddit(**arguments)
            authorizedInstance = GetAuth(reddit, port).getRefreshToken(*scopes)
            reddit = authorizedInstance[0]
            refresh_token = authorizedInstance[1]
            jsonFile(GLOBAL.configDirectory / "config.json").add({
                "reddit_username":
                str(reddit.user.me()),
                "reddit_refresh_token":
                refresh_token
            })
    else:
        arguments["redirect_uri"] = "http://localhost:" + str(port)
        reddit = praw.Reddit(**arguments)
        authorizedInstance = GetAuth(reddit, port).getRefreshToken(*scopes)
        reddit = authorizedInstance[0]
        refresh_token = authorizedInstance[1]
        jsonFile(GLOBAL.configDirectory / "config.json").add({
            "reddit_username":
            str(reddit.user.me()),
            "reddit_refresh_token":
            refresh_token
        })
    return reddit