Exemplo n.º 1
0
def hello_world():
    json = util.getJson(request)
    user = database.get_user_object_from_token((json["token"]))
    if user:
        return "Hello " + user.username
    else:
        return 'Hello World!'
Exemplo n.º 2
0
def add_note():
    json = util.getJson(request)

    user = database.get_user_object_from_token(json["token"])

    if user:
        #What type of note is it?
        if json["type"] <= 6:
            #Pure note
            id = database.add_note(json["type"], user.ID, json["note"])

            if json["type"] in [0, 1, 2, 3]:
                #Bluetooth / Wifi based
                database.add_notefilter(id, json["filtertype"], json["filter"])

            elif json["type"] in [4, 5]:
                # Locationsbased
                database.add_noteloc(id, json["radius"], json["lat"],
                                     json["lng"])

            return JSON.dumps(
                util.makeResponseDict(200, "Note created", data={"noteid":
                                                                 id}))
        else:
            return JSON.dumps(util.makeResponseDict(400, "Bad notetype"))
    else:
        return JSON.dumps(util.makeResponseDict(403, "Bad credentials!"))
Exemplo n.º 3
0
def update_display_name():
    json = util.getJson(request)
    user = database.get_user_object_from_token(json["token"])
    if user:
        database.update_user_displayname(user.ID, json["displayname"])
        return JSON.dumps(util.makeResponseDict(200, "Display name updated"))
    else:
        return JSON.dumps(util.makeResponseDict(403, "Bad credentials"))
Exemplo n.º 4
0
def updatepos():
    json = util.getJson(request)
    user = database.get_user_object_from_token(json["token"])
    if user:
        database.update_user_loc(user.ID, json["lat"], json["lng"])
        return JSON.dumps(util.makeResponseDict(200, "Position updated"))
    else:
        return JSON.dumps(util.makeResponseDict(403, "Bad credentials"))
Exemplo n.º 5
0
def remove_friend():
    json = util.getJson(request)

    user = database.get_user_object_from_token(json["token"])

    if user:
        q = database.delete_friend(user.ID, json["friendid"])
        return JSON.dumps(util.makeResponseDict(200, q))
    else:
        return JSON.dumps(util.makeResponseDict(403, "Bad credentials!"))
Exemplo n.º 6
0
def getSubreddit(subredditName):
    auth = util.getJson('src/config.json')

    reddit = praw.Reddit(client_id=auth['clientId'],
                         client_secret=auth['clientSecret'],
                         user_agent=auth['userAgent'],
                         username=auth['user'],
                         password=auth['pw'])
    reddit.validate_on_submit = True
    return reddit.subreddit(subredditName)
Exemplo n.º 7
0
def get_friends():
    json = util.getJson(request)

    user = database.get_user_object_from_token(json["token"])

    if user:
        return JSON.dumps(
            util.makeResponseDict(200, data=database.get_friends(user.ID)))
    else:
        return JSON.dumps(util.makeResponseDict(403, "Bad credentials!"))
Exemplo n.º 8
0
def claim_device():
    json = util.getJson(request)

    device = database.get_device_object(json["mac"])
    user = database.get_user_object_from_token(json["token"])

    if device and user:
        database.update_device_owner(json["mac"], user.username)

    # TODO make real response
    return JSON.dumps(util.makeResponseDict())
Exemplo n.º 9
0
def delete_note():
    json = util.getJson(request)

    user = database.get_user_object_from_token(json["token"])

    if user:
        if database.delete_note(json["noteid"], user.ID):
            return JSON.dumps(util.makeResponseDict(200, "Note deleted"))
        else:
            return JSON.dumps(util.makeResponseDict(403, "Not your note!"))
    else:
        return JSON.dumps(util.makeResponseDict(403, "Bad credentials!"))
Exemplo n.º 10
0
def get_notes():
    if request.method == "POST":
        json = util.getJson(request)
        user = database.get_user_object_from_token(json["token"])

        if user:
            return JSON.dumps(
                util.makeResponseDict(data=database.get_notes(user.ID)))
        else:
            return JSON.dumps(util.makeResponseDict(403, "Bad credentials!"))
    else:
        return JSON.dumps(database.get_all_notes())
Exemplo n.º 11
0
def signup():
    json = util.getJson(request)
    if database.get_user(json["username"]):
        resp = util.makeResponseDict(403, "Username taken")
    else:
        database.add_user(json["username"], json["password"])
        user = database.login_user_object(json["username"], json["password"])
        resp = util.makeResponseDict(data={
            "token": user.token,
            "username": user.username
        })
        SESSIONS[user.token] = user

    return JSON.dumps(resp)
Exemplo n.º 12
0
def add_friend():
    json = util.getJson(request)

    user = database.get_user_object_from_token(json["token"])

    if user:
        #if user.ID == json["friendid"]:
        #return JSON.dumps(300, "Cannot friend yourself")
        if database.add_friend(user.ID, json["friendid"]):
            return JSON.dumps(util.makeResponseDict(200, "Friend added!"))
        else:
            return JSON.dumps(
                util.makeResponseDict(400, "ID of other user not existing"))
    else:
        return JSON.dumps(util.makeResponseDict(403, "Bad credentials!"))
Exemplo n.º 13
0
def login():
    json = util.getJson(request)
    user = database.login_user_object(json["username"], json["password"])
    if user:
        resp = util.makeResponseDict(
            data={
                "token": user.token,
                "username": user.username,
                "displayname": user.displayname
            })
        SESSIONS[user.token] = user
    else:
        resp = util.makeResponseDict(403, "Bad credentials")

    return JSON.dumps(resp)
Exemplo n.º 14
0
def add_device():
    json = util.getJson(request)
    device = database.add_device(json["mac"])

    #Check if there's more in the request to add
    if json.has_key("owner"):
        user = database.get_user_object(json["owner"])
        if user:
            database.update_device_owner(json["mac"], user.ID)

    if json.has_key("name"):
        database.update_device_name(json["mac"], json["name"])

    if json.has_key("lat") and json.has_key("lng"):
        database.update_device_info(json["mac"], json["lat"], json["lng"])

    #TODO make real response
    return JSON.dumps(util.makeResponseDict())
Exemplo n.º 15
0
def sendResultToReportServer(reportServerUrl, data, resultType="testRun"):
    if type(data).__name__ != "str":
        data = util.getJson(data)

    postdata = urllib.urlencode({resultType: data})
    req = urllib2.Request(reportServerUrl, postdata)

    try:
        response = urllib2.urlopen(req)
    except urllib2.URLError, e:
        try:
            fileName = "reportservererror_%s.html" % util.getTimestamp()
            errorFile = open(fileName, "w")
            errorFile.write(e.read())
            errorFile.close()
        except Exception:
            pass
        raise RuntimeError, e
Exemplo n.º 16
0
def sendResultToReportServer(reportServerUrl, data, resultType = "testRun" ):
    if type(data).__name__ != "str":
        data = util.getJson(data)
    
    postdata = urllib.urlencode({resultType : data})
    req = urllib2.Request(reportServerUrl, postdata)
    
    try:
        response = urllib2.urlopen(req)    
    except urllib2.URLError, e:
        try:
            fileName = "reportservererror_%s.html" %util.getTimestamp()
            errorFile = open(fileName, "w")
            errorFile.write(e.read())
            errorFile.close()
        except Exception:
            pass
        raise RuntimeError, e
Exemplo n.º 17
0
def update_device():
    json = util.getJson(request)
    user = database.get_user_object_from_token(json["token"])

    if user:
        device = database.get_device_object(json["mac"])
        if device:
            if device.owner == user.username:
                if json.has_key("name") and json["name"] != device.name:
                    database.update_device_name(json["mac"], json["name"])

            if json.has_key("lat") and json.has_key("lng") and (
                    json["lat"] != device.lat or json["lng"] != device.lng):
                database.update_device_info(json["mac"], json["lat"],
                                            json["lng"])
        else:
            device = database.add_device(json["mac"])

    #TODO make real response
    return JSON.dumps(util.makeResponseDict())
Exemplo n.º 18
0
def device_info():
    json = util.getJson(request)

    device = database.get_device_object(json["mac"])

    if device:
        if device.owner == None:
            dOwner = "unknown"
        else:
            dOwner = device.owner.username

        data = {
            "name": device.name,
            "owner": dOwner,
            "lastseen": device.last_activity,
            "lat": device.lat,
            "lng": device.lng
        }
        return JSON.dumps(util.makeResponseDict(data=data))
    else:
        return JSON.dumps(util.makeResponseDict(404, "Device not known"))
Exemplo n.º 19
0
def postImage(subredditName, title, imgPath, comment):
    subreddit = getSubreddit(subredditName)

    try:
        submission = subreddit.submit_image(title,
                                            imgPath,
                                            resubmit=True,
                                            send_replies=False,
                                            nsfw=False,
                                            spoiler=False,
                                            timeout=20,
                                            without_websockets=False,
                                            discussion_type=None)
        submission.reply(comment)
        return f'Submitted post with comment at {datetime.now()}'
    except praw.exceptions.WebSocketException:
        posted = datetime.now()
        time.sleep(60)

        counter = 0
        interval = 15
        author = util.getJson('src/config.json')['user']

        # poll for our submitted post
        while interval * counter < 300:  # retry for up to 5 minutes
            submission = getPost(subreddit,
                                 f'title:"{title}" AND author:{author}')
            if submission != None:
                break
            time.sleep(interval)
            counter += 1

        if submission != None:
            submission.reply(comment)
            return f'Submitted post at {posted}, submitted comment at {datetime.now()}'
        else:
            return f'Error submitting post or comment. {datetime.now()}'
Exemplo n.º 20
0
 def get(self):
   key_word = self.request.get("key")
   page = self.request.get("page")
   json_response = util.getJson(key_word, page)
   self.response.out.write(json_response)
Exemplo n.º 21
0
def userspos():
    if request.method == "POST":
        json = util.getJson(request)
        return JSON.dumps(database.get_other_users_pos(json["token"]))
    else:
        return JSON.dumps(database.get_all_users())
Exemplo n.º 22
0
    if '"' in v['-title-']: # not a reddit restriction, but it messes up our search
        return 'ERROR: Title cannot contain double quotes'
    if util.isNullOrWhitespace(v['-comment-']):
        return 'ERROR: Missing comment'
    return f'Post scheduled for {parseDatetime(v)}'

def setStatus(window, status):
    # status = f'{status} ({datetime.now()})'
    window['-status-'].update(status)
    print(status)


try:
    sg.theme('DarkGreen2')

    subredditValues = util.getJson('src/config.json')['subreddits']
    dateValues = list(map(util.daysFromNow, range(7)))
    hourValues = list(range(1, 13))
    minuteValues = list(map(util.pad, range(60)))
    periodValues = ['AM', 'PM']

    layout = [
        [sg.Text('Subreddit:', size=(10, 1)),
            sg.InputCombo(subredditValues, size=(50, 1), key='-subredditName-')],
        [sg.Text('Image:', size=(10, 1)),
            sg.Input(disabled=True, size=(43, 1)),
            sg.FileBrowse(key='-imagePath-')],
        [sg.Text('Title:', size=(10, 1)),
            sg.InputText(key='-title-', size=(52, 1))],
        [sg.Text('Comment:', size=(10, 1)),
            sg.Multiline(size=(50, 3), key='-comment-')],
Exemplo n.º 23
0
Arquivo: asklogin.py Projeto: jq/zhong
 def get(self):
     key_word = self.request.get("key")
     page = self.request.get("page")
     json_response = util.getJson(key_word, page)
     self.response.out.write(json_response)
Exemplo n.º 24
0
def logout():
    json = util.getJson(request)
    if SESSIONS.has_key(json["token"]):
        del SESSIONS[json["token"]]
    return JSON.dumps(util.makeResponseDict(200, "Logged out"))