Ejemplo n.º 1
0
def handleApiProjectsCount(conn, method, addr, data):
    if method == "GET":
        _getProjectsCountJson(conn)
    elif method == "POST":
        _postProjectsCountJson(conn)
    else:
        core.sendAnswer(conn, "400 Bad Request")
    return True
Ejemplo n.º 2
0
def handleApiGetDreamCard(conn, method, addr, data):
    dreamId = addr[19:]
    dreamId = bytes(dreamId,
                    "utf-8").decode("unicode_escape").strip().replace('"', '')
    answer = '<div class="s-dream-div"><h3>' + dreamId + '</h3><p>Dream1</p></div>'
    core.sendAnswer(conn,
                    typ="application/json; charset=utf-8",
                    data=answer.encode('utf-8'))
    return True
Ejemplo n.º 3
0
def handleApiGetProjectCard(conn, method, addr, data):
    projId = addr[19:]
    projId = bytes(projId,
                   "utf-8").decode("unicode_escape").strip().replace('"', '')
    answer = '<div class="divBlock divProjectBlockOk"><h3>' + projId + '</h3>Описание проекта<br/><font color="green">Сделано</font><br/><b>2 000 / 2 000</b></div>'
    core.sendAnswer(conn,
                    typ="application/json; charset=utf-8",
                    data=answer.encode('utf-8'))
    return True
Ejemplo n.º 4
0
def handle(conn, method, addr, data):
	if method != "GET":
		core.sendAnswer(conn, typ="400 Bad Request: Static files must GET")
		return False
	for ext in mime.STATIC_MIME:
		if addr.endswith("."+ext):
			return core.sendAnswerFile(conn, STATIC_DIR + addr, mime.STATIC_MIME[ext])
	if core.fs.isFileDoctypeHtml(STATIC_DIR + addr):
		core.sendAnswerFile(conn, STATIC_DIR + addr, "text/html")
	else:
		core.sendAnswerFile(conn, STATIC_DIR + addr, "text/plain");
Ejemplo n.º 5
0
def handleApiGetProject(conn, method, addr, data):
    if method != "GET":
        core.sendAnswer(conn, "400 Bad Request")
        return True
    if addr.startswith("/api/getProject?"):
        if not addr.startswith("/api/getProject?id="):
            log("400 Bad Request: Must id")
            core.sendAnswer(conn, "400 Bad Request: must id")
            return True
        _apiGetProject(conn, addr[19:])
        return True
    _apiGetProject(conn, addr[15:])
    return True
Ejemplo n.º 6
0
def handleApiNeeds(conn, method, addr, data):
	if (method == "GET") or (method == "POST"):
		items = core.db.needs.find().limit(1000)
		answer = "["
		for item in items:
			answer += _needItemToStr(item)
		if answer.endswith(','):
			answer = answer[:-1]
		answer += ']'
		core.sendAnswer(conn, typ="application/json; charset=utf-8", data=answer.encode('utf-8'))
	else:
		core.sendAnswer(conn, "400 Bad Request: /api/needs must GET or POST")
	return True
Ejemplo n.º 7
0
def _apiGetProject(conn, projId):
    projId = bytes(projId,
                   "utf-8").decode("unicode_escape").strip().replace('"', '')
    try:
        item = core.db.projects.find_one({"_id": core.ObjectId(projId)})
    except Exception as e:
        log("500 Internal Server Error: " + str(e))
        core.sendAnswer(conn, "500 Internal Server Error: " + str(e))
        return True
    if item == None:
        answer = '{}'
    else:
        answer = str(item)
    core.sendAnswer(conn,
                    typ="application/json; charset=utf-8",
                    data=answer.encode('utf-8'))
    return True
Ejemplo n.º 8
0
def handle(conn, method, addr, data):
    if method != "GET":
        return False
    if addr != "/test/needs":
        return False
    answer = '<!DOCTYPE html>'
    answer += '<html><head><meta charset="utf-8"><title>Needs Test</title></head><body><h1>Needs</h1>'
    answer += '<div>Test</div>'
    answer += '<p><a href="/api/needsCount">GET /api/needsCount</a></p>'
    answer += '<p><a href="/api/getNeedsCount">GET /api/getNeedsCount</a></p>'
    answer += '<p><a href="/api/needs">GET /api/needs</a></p>'
    answer += '<p><a href="/api/need/5bf072b91a89170676a4b5bc">GET /api/need/5bf072b91a89170676a4b5bc</a></p>'
    answer += '<form action="/api/getNeed" method="GET"><input name="id" value="1"><input type="submit" value="GET /api/getNeed"></form>'
    answer += '<form action="/api/need" method="POST"><input type="submit" value="POST /api/need"></form>'
    answer += '<form action="/api/need" method="POST"><input name="title" value="Test1"><input type="submit" value="POST /api/need"></form>'
    answer += '<form action="/api/need" method="POST"><input name="title" value="Test1"><input name="description" value="Description"><input type="submit" value="POST /api/need"></form>'
    answer += '<form action="/api/needs" method="POST"><input type="submit" value="POST /api/needs"></form>'
    answer += '</body></html>'
    core.sendAnswer(conn,
                    typ="text/html; charset=utf-8",
                    data=answer.encode('utf-8'))
    return True
Ejemplo n.º 9
0
def handle(conn, method, addr, data):
    """ API Request handler (/api)
	method - GET/POST/PUT/DELETE
	data - utf-8 string
	"""
    if (addr == "/api/dream") or addr.startswith("/api/dream/"):
        return handleApiDream(conn, method, addr, data)
    if addr.startswith("/api/getDream?"):
        return handleApiGetDream(conn, method, addr, data)
    if addr == "/api/dreams":
        return handleApiGetDreams(conn, method, addr, data)
    if addr == "/api/getDreams":
        return handleApiGetDreams(conn, method, addr, data)
    if (addr == "/api/dreamsCount") or addr == "/api/getDreamsCount":
        return handleApiGetDreamsCount(conn, method, addr, data)
    if addr.startswith("/api/getDreamCard/") or addr.startswith(
            "/api/getDreamCard?"):
        return handleApiGetDreamCard(conn, method, addr, data)
    if addr == "/api/getDream":
        core.sendAnswer(conn, "400 Bad Request in Dreams addon")
        return True
    return False
Ejemplo n.º 10
0
def handle(conn, method, addr, data):
    if method != "GET":
        return False
    if addr != "/test/projects":
        return False
    answer = '<!DOCTYPE html>'
    answer += '<html><head><meta charset="utf-8"><title>Projects</title></head><body><h1>Projects</h1>'
    answer += '<div>Test</div>'
    answer += '<p><a href="/api/project/5bf03f611a89174156a2e6d5">/api/project/5bf03f611a89174156a2e6d5</a></p>'
    answer += '<p><a href="/api/getProject?id=5beb05c71a89173c9ee18bc6">/api/project?id=5beb05c71a89173c9ee18bc6</a></p>'
    answer += '<p><a href="/api/projectsCount">/api/projectsCount</a></p>'
    answer += '<p><a href="/api/getProjectsCount">/api/getProjectsCount</a></p>'
    answer += '<p><a href="/api/getProjects">/api/getProjects</a></p>'
    answer += '<form action="/api/project" method="POST"><input type="submit" value="POST /api/project"></form>'
    answer += '<form action="/api/project" method="POST"><input name="title" value="Test1"><input type="submit" value="POST"></form>'
    answer += '<form action="/api/project" method="POST"><input name="title" value="Test1"><input name="description" value="Description"><input name="status" value="100"><input name="img" value="/favicon.ico"><input type="submit" value="POST"></form>'
    answer += '<form action="/api/getProjects" method="POST"><input name="testParam1" value="Test1"><input name="testParam2" value="Test2"><input type="submit" value="POST GetProjects"></form>'
    answer += '</body></html>'
    core.sendAnswer(conn,
                    typ="text/html; charset=utf-8",
                    data=answer.encode('utf-8'))
    return True
Ejemplo n.º 11
0
def handle(conn, method, addr, data):
    """ API Request handler (/api)
	method - GET/POST/PUT/DELETE
	data - utf-8 string
	"""
    if (addr == "/api/project") or addr.startswith("/api/project/"):
        return handleApiProject(conn, method, addr, data)
    if addr == "/api/projectsCount":
        return handleApiProjectsCount(conn, method, addr, data)
    if (addr == "/api/getProject") or addr.startswith("/api/getProject?"):
        return handleApiGetProject(conn, method, addr, data)
    if (addr == "/api/getProjects") or addr.startswith("/api/getProjects?"):
        return handleApiGetProjects(conn, method, addr, data)
    if addr == "/api/getProjectsCount":
        return handleApiGetProjectsCount(conn, method, addr, data)
    if (addr == "/api/getProjectCard"
        ) or addr.startswith("/api/getProjectCard?"):
        return handleApiGetProjectCard(conn, method, addr, data)
    if addr == "/api/getProject":
        core.sendAnswer(conn, "400 Bad Request")
        return True
    return False
Ejemplo n.º 12
0
def handle(conn, method, addr, data):
	""" API Request handler (/api)
	method - GET/POST/PUT/DELETE
	data - utf-8 string
	"""
	if (addr == "/api/need") or addr.startswith("/api/need/"):
		return handleApiNeed(conn, method, addr, data)
	if addr == "/api/needs":
		return handleApiNeeds(conn, method, addr, data)
	if addr == "/api/needsCount":
		return handleApiNeedsCount(conn, method, addr, data)
	if (addr == "/api/getNeed") or addr.startswith("/api/getNeed?"):
		return handleApiGetNeed(conn, method, addr, data)
	if addr == "/api/getNeeds" or addr.startswith("/api/getNeeds?"):
		return handleApiGetNeeds(conn, method, addr, data)
	if addr == "/api/getNeedsCount":
		return handleApiGetNeedsCount(conn, method, addr, data)
	if addr.startswith("/api/getNeedCard/"):
		return handleApiGetNeedCard(conn, method, addr, data)
	if addr == "/api/getNeed":
		core.sendAnswer(conn, "400 Bad Request in Needs addon")
		return True
	return False
Ejemplo n.º 13
0
def _apiGetNeed(conn, needId):
	needId = bytes(needId, "utf-8").decode("unicode_escape").strip().replace('"','')
	if needId == "":
		core.sendAnswer(conn, "400 Bad Request: needId is empty")
		return True
	try:
		item = core.db.needs.find_one({"_id": core.ObjectId(needId)})
	except Exception as e:
		log("500 Internal Server Error: "+str(e))
		core.sendAnswer(conn, "500 Internal Server Error: "+str(e))
		return True
	if item == None:
		answer = '{}'
	else:
		answer = str(item)
	core.sendAnswer(conn, typ="application/json; charset=utf-8", data=answer.encode('utf-8'))
	return True
Ejemplo n.º 14
0
def handleApiProject(conn, method, addr, data):
    if method == "GET":
        # Возвращает информацию о проекте в формате JSON
        _apiGetProject(conn, addr[13:])
    elif method == "POST":
        log("handleApiProject POST " + addr)
        # Добавляет новый проект. Если указан id то возвращает ошибку 400.
        params = _getPostData(data)
        pId = addr[13:]
        if pId != "":
            core.sendAnswer(conn, "400 Bad Request")
            return True
        pTitle = ""
        pDescription = ""
        pInvestments = ""
        pGoal = ""
        pStatus = ""
        pImg = ""
        par = {}
        for p in params:
            if p == "":
                continue
            p = p.split("=")
            if len(p) < 2:
                continue
            if p[0] == 'id':
                core.sendAnswer(conn, "400 Bad Request")
                return True
            if p[0] == 'title':
                pTitle = p[1]
            if p[0] == 'description':
                pDescription = p[1]
            if p[0] == 'investments':
                pInvestments = p[1]
            if p[0] == 'goal':
                pGoal = p[1]
            if p[0] == 'status':
                pStatus = p[1]
            if p[0] == 'img':
                pImg = p[1]
            par[p[0]] = p[1]
        pId = _insertProject(pTitle, pDescription, pInvestments, pGoal,
                             pStatus, pImg)
        item = core.db.projects.find_one({"_id": core.ObjectId(pId)})
        if item == None:
            answer = '{}'
        else:
            answer = str(item)
        core.sendAnswer(conn,
                        typ="application/json; charset=utf-8",
                        data=answer.encode('utf-8'))
        return True
    elif method == "PUT":
        # Если указан id то обновляет информацию о проекте в формате JSON иначе возвращает ошибку 400
        params = _getPostData(data)
        pId = 0
        pTitle = ""
        pDescription = ""
        pInvestments = ""
        pGoal = ""
        pStatus = ""
        pImg = ""
        par = {}
        for p in params:
            if p == "":
                continue
            p = p.split("=")
            if len(p) < 2:
                continue
            if p[0] == 'id':
                pId = core.ObjectId(p[1])
            if p[0] == 'title':
                pTitle = p[1]
            if p[0] == 'description':
                pDescription = p[1]
            if p[0] == 'investments':
                pInvestments = p[1]
            if p[0] == 'goal':
                pGoal = p[1]
            if p[0] == 'status':
                pStatus = p[1]
            if p[0] == 'img':
                pImg = p[1]
            par[p[0]] = p[1]
        log(par)
        if pId == 0:
            core.sendAnswer(conn, "400 Bad Request")
            return True
        #item = core.db.projects.find_one({"_id": core.ObjectId(projId)})
        #...
        #_apiGetProject()
        #core.sendAnswer(conn, typ="application/json; charset=utf-8", data=answer.encode('utf-8'))
        core.sendAnswer(conn, "400 Bad Request")
    else:
        core.sendAnswer(conn, "400 Bad Request")
    return True
Ejemplo n.º 15
0
def Parse(conn, addr):
    data = b""
    while not b"\r\n" in data:  # waiting for the first line
        tmp = conn.recv(1024)
        if not tmp:  # socket closed, empty object
            break
        else:
            data += tmp
    if not data:  # data did not come
        return  # do not process
    core.handleRecv(conn, addr, data)


# ==== main ====

sock = socket.socket()
sock.bind((conf.HOST, conf.PORT))
sock.listen(5)
try:
    while 1:
        conn, addr = sock.accept()
        try:
            Parse(conn, addr)
        except Exception as e:
            core.sendAnswer(conn, "500 Internal Server Error")
            print(e)
        finally:
            conn.close()
finally:
    sock.close()
Ejemplo n.º 16
0
def handleApiNeedsCount(conn, method, addr, data):
	if method == "GET":
		_getNeedsCountJson(conn)
	else:
		core.sendAnswer(conn, "400 Bad Request: /api/needsCount must GET")
	return True
Ejemplo n.º 17
0
def _getNeedsCountJson(conn):
	count = core.db.needs.find().count()
	answer = '{"needsCount": '+str(count)+'}'
	core.sendAnswer(conn, typ="application/json; charset=utf-8", data=answer.encode('utf-8'))
Ejemplo n.º 18
0
def handleApiGetNeedCard(conn, method, addr, data):
	needId = addr[19:]
	needId = bytes(needId, "utf-8").decode("unicode_escape").strip().replace('"','')
	answer = '<div class="divBlock divNeedBlockOk"><h3>'+needId+'</h3><p>Need1</p></div>'
	core.sendAnswer(conn, typ="application/json; charset=utf-8", data=answer.encode('utf-8'))
	return True
Ejemplo n.º 19
0
def _postProjectsCountJson(conn):
    count = core.db.projects.find().count()
    answer = '{"projectsCount": ' + str(count) + '}'
    core.sendAnswer(conn,
                    typ="application/json; charset=utf-8",
                    data=answer.encode('utf-8'))
Ejemplo n.º 20
0
def handleApiGetNeed(conn, method, addr, data):
	if method != "GET":
		core.sendAnswer(conn, "400 Bad Request: /api/getNeed must is GET")
		return True
	_apiGetNeed(conn, addr[16:])
	return True