Пример #1
0
    def test_recipeRender(self):
        # arrage
        r = ghObjectRecipe.schematicRecipe()
        r.recipeID = 1
        r.schematicID = "armor_segment_composite_advanced"
        r.recipeName = "Test Recipe"

        i1 = ghObjectRecipe.recipeIngredient("steel_kiirium", "17895",
                                             "armor_layer_weld_tabs", 8, "0",
                                             "Kiirium Steel", 455,
                                             "stuff steel")
        i2 = ghObjectRecipe.recipeIngredient("copper_polysteel", "13455",
                                             "segment_mounting_tabs", 5, "0",
                                             "Polysteel Copper", 877,
                                             "This is great")

        r.recipeIngredients.append(i1)
        r.recipeIngredients.append(i2)

        # act
        slotHTML = r.getIngredientSlots()
        rowHTML = r.getRow()

        # assert
        self.assertIn("steel_kiirium", slotHTML,
                      "Resource id not in slot html.")
        self.assertIn("Test Recipe", rowHTML, "Title not in row html.")
        self.assertIn("yellow", slotHTML,
                      "Expected quality color not present in slot HTML.")
Пример #2
0
def main():
    # Get current url
    try:
        url = os.environ['SCRIPT_NAME']
    except KeyError:
        url = ''

    form = cgi.FieldStorage()
    uiTheme = ''
    # Get Cookies
    useCookies = 1
    cookies = Cookie.SimpleCookie()
    try:
        cookies.load(os.environ['HTTP_COOKIE'])
    except KeyError:
        useCookies = 0

    if useCookies:
        try:
            currentUser = cookies['userID'].value
        except KeyError:
            currentUser = ''
        try:
            loginResult = cookies['loginAttempt'].value
        except KeyError:
            loginResult = 'success'
        try:
            sid = cookies['gh_sid'].value
        except KeyError:
            sid = form.getfirst('gh_sid', '')
        try:
            uiTheme = cookies['uiTheme'].value
        except KeyError:
            uiTheme = ''
    else:
        currentUser = ''
        loginResult = form.getfirst('loginAttempt', '')
        sid = form.getfirst('gh_sid', '')

    # escape input to prevent sql injection
    sid = dbShared.dbInsertSafe(sid)

    # Get a session
    logged_state = 0
    linkappend = ''
    disableStr = ''
    if loginResult == None:
        loginResult = 'success'

    sess = dbSession.getSession(sid, 2592000)
    if (sess != ''):
        logged_state = 1
        currentUser = sess
        if (uiTheme == ''):
            uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
        if (useCookies == 0):
            linkappend = 'gh_sid=' + sid
    else:
        disableStr = ' disabled="disabled"'
        if (uiTheme == ''):
            uiTheme = 'crafter'

    # Get recipe id from path
    path = []
    if os.environ.has_key('PATH_INFO'):
        path = os.environ['PATH_INFO'].split('/')[1:]
        path = [p for p in path if p != '']
    recipeHTML = ''
    slotHTML = ''
    schemImageName = ''
    schematicDetailsHTML = ''
    ingTypes = ''
    ingGroups = ''
    pageType = 'recipe'
    if len(path) > 0:
        recipeID = dbShared.dbInsertSafe(path[0])
        url = url + '/' + recipeID
        r = ghObjectRecipe.schematicRecipe()
        if logged_state == 1:
            # Look up recipe info
            try:
                conn = dbShared.ghConn()
                cursor = conn.cursor()
            except Exception:
                recipeHTML = "Error: could not connect to database"

            if (cursor and recipeID.isdigit()):
                cursor.execute(
                    'SELECT recipeID, userID, tRecipe.schematicID, recipeName, (SELECT imageName FROM tSchematicImages si WHERE si.schematicID=tRecipe.schematicID AND si.imageType=1) AS schemImage, schematicName, complexity FROM tRecipe INNER JOIN tSchematic ON tRecipe.schematicID = tSchematic.schematicID WHERE recipeID='
                    + recipeID + ';')
                row = cursor.fetchone()

                if (row != None):
                    if row[1] == currentUser:
                        # main recipe data
                        if (row[4] != None):
                            schemImageName = row[4]
                        else:
                            schemImageName = 'none.jpg'

                        r.recipeID = row[0]
                        r.schematicID = row[2]
                        r.recipeName = row[3]
                        r.schematicImage = schemImageName

                        # schematic quality data
                        schematicDetailsHTML = '<div><a href="' + ghShared.BASE_SCRIPT_URL + 'schematics.py/' + row[
                            2] + '" title="Go to schematic page.">' + row[
                                5] + '</a></div>'
                        schematicDetailsHTML += '<div>Complexity: ' + str(
                            row[6]) + '</div>'
                        expGroup = ''
                        expProp = ''
                        schematicDetailsHTML += '<td valign="top"><h3>Qualities</h3><ul id="qualitiesList" style="margin-top:6px;">'
                        expCursor = conn.cursor()
                        expCursor.execute(
                            'SELECT tSchematicQualities.expQualityID, expProperty, expGroup, statName, statWeight, weightTotal FROM tSchematicQualities INNER JOIN tSchematicResWeights ON tSchematicQualities.expQualityID = tSchematicResWeights.expQualityID WHERE schematicID="'
                            + r.schematicID +
                            '" ORDER BY expGroup, expProperty, statName;')
                        expRow = expCursor.fetchone()
                        while (expRow != None):
                            if (expGroup != expRow[2]):
                                tmpName = expRow[2].replace('_', ' ')
                                schematicDetailsHTML = schematicDetailsHTML + '<li class="groupText">' + tmpName + '</li>'
                                expGroup = expRow[2]
                            if (expProp != expRow[1]):
                                tmpName = expRow[1].replace('_', ' ')
                                schematicDetailsHTML = schematicDetailsHTML + '<li class="schemQualityProperty altText">' + tmpName + '</li>'
                                expProp = expRow[1]

                            schematicDetailsHTML += '<li class="schemQualityItem" tag="' + expRow[
                                3] + ':' + str(
                                    (expRow[4] * 1.0 / expRow[5]) * 100
                                ) + '"><span class="inlineBlock" style="width:100px;">' + ghNames.getStatName(
                                    expRow[3]) + (': </span><span>%.0f' % (
                                        (expRow[4] * 1.0 / expRow[5]) * 100)
                                                  ) + '%</span></li>'

                            expRow = expCursor.fetchone()

                        expCursor.close()
                        # Look up ingredient data
                        ri = None
                        sqlStr = 'SELECT si.ingredientName, ingredientResource, ingredientObject, ingredientQuantity, ingredientContribution, rt.containerType tcontainer, rg.containerType gcontainer, rt.resourceTypeName, rg.groupName, ingredientQuality FROM tSchematicIngredients si LEFT JOIN (SELECT ingredientName, ingredientResource, ingredientQuality FROM tRecipeIngredients WHERE recipeID=' + str(
                            r.recipeID
                        ) + ') ri ON si.ingredientName = ri.ingredientName LEFT JOIN tResourceType rt ON si.ingredientObject = rt.resourceType LEFT JOIN tResourceGroup rg ON si.ingredientObject = rg.resourceGroup WHERE schematicID="' + r.schematicID + '" ORDER BY ingredientQuantity DESC, si.ingredientName'
                        ingCursor = conn.cursor()
                        ingCursor.execute(sqlStr)
                        ingRow = ingCursor.fetchone()
                        while (ingRow != None):
                            if ingRow[5] == None:
                                if ingRow[6] == None:
                                    container = 'default'
                                    objectName = ingRow[2].rpartition(
                                        '/')[2].replace('_', ' ')
                                    if objectName[-4:] == '.iff':
                                        objectName = objectName[:-4]
                                else:
                                    ingGroups += '"' + ingRow[2] + '",'
                                    container = ingRow[6]
                                    objectName = ingRow[8]
                            else:
                                ingTypes += '"' + ingRow[2] + '",'
                                container = ingRow[5]
                                objectName = ingRow[7]

                            # get details of ingredient resource for schematic
                            resDetails = ''
                            if ingRow[1] != None and (ingRow[5] != None
                                                      or ingRow[6] != None):
                                spawn = resource.getResource(
                                    conn, logged_state, currentUser, ingRow[1],
                                    None, None)
                                resDetails = 'Loaded with: ' + spawn.spawnName + ', ' + spawn.resourceTypeName + '<br />' + spawn.getStatList(
                                )
                            r.recipeIngredients.append(
                                ghObjectRecipe.recipeIngredient(
                                    ingRow[2], ingRow[1], ingRow[0], ingRow[3],
                                    container, objectName, ingRow[9],
                                    resDetails))
                            ingRow = ingCursor.fetchone()

                        ingCursor.close()
                        if ingTypes != '':
                            ingTypes = ingTypes[:-1]
                        if ingGroups != '':
                            ingGroups = ingGroups[:-1]
                        slotHTML = r.getIngredientSlots()
                    else:
                        recipeHTML = "That is not your recipe."
                else:
                    recipeHTML = "The recipe ID given could not be found."
                cursor.close()
            else:
                # Render recipe home if any non number in sub path
                pageType = 'home'

            conn.close()
        else:
            recipeHTML = "You must be logged in to manage recipes."
    else:
        recipeHTML = 'You have not specified a recipe to edit, would you like to create a new one?<div style="float:right;"><button type=button value="New Recipe" class="ghButton" onclick="addRecipe();">New Recipe</button></div>'

    pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
    print 'Content-type: text/html\n'
    env = Environment(loader=FileSystemLoader('templates'))
    env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
    env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(
        os.environ['HTTP_USER_AGENT'])
    template = env.get_template('recipe.html')
    print template.render(uiTheme=uiTheme,
                          loggedin=logged_state,
                          currentUser=currentUser,
                          loginResult=loginResult,
                          linkappend=linkappend,
                          url=url,
                          pictureName=pictureName,
                          imgNum=ghShared.imgNum,
                          galaxyList=ghLists.getGalaxyList(),
                          professionList=ghLists.getProfessionList(),
                          recipeHTML=recipeHTML,
                          slotHTML=slotHTML,
                          schematicDetailsHTML=schematicDetailsHTML,
                          ingTypes=ingTypes,
                          ingGroups=ingGroups,
                          pageType=pageType,
                          recipeID=r.recipeID,
                          recipeName=r.recipeName,
                          schemImageName=schemImageName)
Пример #3
0
def buildBestRecipe(conn, schem, inventory, user):
	#sys.stderr.write(str(schem) + '\n')
	r = ghObjectRecipe.schematicRecipe()
	r.schematicID = schem[0]
	r.recipeName = schem[4]
	if schem[5] != None:
		r.schematicImage = schem[5]
	# Look up the schematic ingredients
	oingSql = 'SELECT ingredientObject, Sum(ingredientContribution) FROM tSchematicIngredients WHERE schematicID="' + schem[0] + '" AND ingredientType = 0 GROUP BY ingredientObject;'
	oingCursor = conn.cursor()
	oingCursor.execute(oingSql)
	# Find other potential ingredients and their quality from inventory
	filledIng = True
	oingRow = oingCursor.fetchone()
	ingredients = []
	while oingRow != None and oingRow[0] != None:
		thisFilled = False
		# Iterate over the option for each ingredient and save top quality to new list
		for resType in inventory.iterkeys():
			if str(resType).find('\'' + oingRow[0] + '\'') > -1:
				thisFilled = True
				spawns = inventory[resType].split()
				for s in spawns:
					spawnQuality = recipe.calcIngredientQuality(conn, s.split('|')[0].strip(','), schem[0], user)
					ingredients.append((oingRow[0], s, spawnQuality))
		if thisFilled == False:
			filledIng = False
			break
		oingRow = oingCursor.fetchone()

	oingCursor.close()
	oingRow = None
	# If all ingredients can be found in inventory
	if filledIng:
		# Add the top quality scores found from sorted lists as new suggestion
		ingredients = sorted(ingredients, key=lambda ing: ing[2], reverse=True)
		cingSql = 'SELECT si.ingredientName, ingredientObject, ingredientQuantity, ingredientContribution, rt.containerType tcontainer, rg.containerType gcontainer, rt.resourceTypeName, rg.groupName FROM tSchematicIngredients si LEFT JOIN tResourceType rt ON si.ingredientObject = rt.resourceType LEFT JOIN tResourceGroup rg ON si.ingredientObject = rg.resourceGroup WHERE schematicID="' + r.schematicID + '" ORDER BY ingredientQuantity DESC, si.ingredientName'
		cingCursor = conn.cursor()
		cingCursor.execute(cingSql)
		cingRow = cingCursor.fetchone()
		while (cingRow != None):
			for ing in ingredients:
				if ing[0] == cingRow[1]:
					# get details of ingredient resource and add to recipe
					if cingRow[4] == None:
						if cingRow[5] == None:
							container = 'default'
							objectName = cingRow[1].rpartition('/')[2].replace('_',' ')
							if objectName[-4:] == '.iff':
								objectName = objectName[:-4]
						else:
							container = cingRow[5]
							objectName = cingRow[7]
					else:
						container = cingRow[4]
						objectName = cingRow[6]

					resDetails = ''
					spawn = resource.getResource(conn, 1, user, ing[1].split('|')[0].strip(','), None, None)
					resDetails = 'Loaded with: ' + spawn.spawnName + ', ' + spawn.resourceTypeName + '<br />' + spawn.getStatList()
					r.recipeIngredients.append(ghObjectRecipe.recipeIngredient(cingRow[1], ing[1].split('|')[0].strip(','), cingRow[0], cingRow[2], container, objectName, ing[2], resDetails))
					break

			cingRow = cingCursor.fetchone()
		cingCursor.close()
	return r
Пример #4
0
def main():
	form = cgi.FieldStorage()
	# Get Cookies
	useCookies = 1
	cookies = Cookie.SimpleCookie()
	try:
		cookies.load(os.environ['HTTP_COOKIE'])
	except KeyError:
		useCookies = 0

	if useCookies:
		try:
			currentUser = cookies['userID'].value
		except KeyError:
			currentUser = ''
		try:
			sid = cookies['gh_sid'].value
		except KeyError:
			sid = form.getfirst('gh_sid', '')
	else:
		currentUser = ''
		sid = form.getfirst('gh_sid', '')

	listFormat = form.getfirst('listFormat', '')
	listType = form.getfirst('listType', '')
	galaxy = form.getfirst('galaxy', '')
	profession = form.getfirst('profession', '')

	# Get a session
	logged_state = 0

	sess = dbSession.getSession(sid)
	if (sess != ''):
		logged_state = 1
		currentUser = sess

	# Main program
	errstr = ''
	tmpStr = ''
	profFilter = ''

	if not galaxy.isdigit():
		errstr = 'Error: You must provide a valid galaxy id.'
	if profession != '' and not profession.isdigit():
		errstr = 'Error: That is not a valid profession id.'
	if logged_state != 1:
		errstr = 'Error: You must be logged in to get your recipe list.'

	conn = dbShared.ghConn()
	cursor = conn.cursor()
	if (cursor and errstr == ''):
		headStr = '<table width="100%">'
		if listType == 'suggest':
			rl = getSuggestedRecipes(conn, currentUser, galaxy, profession)
			if len(rl) > 0:
				for r in rl:
					tmpStr += r.getRow(listType)
			else:
				tmpStr = '<tr><td>No suggestions at this time.  Try adding more to your inventory.</td></tr>'
		else:
			if profession.isdigit() and profession != '0':
				profFilter = ' AND profID={0}'.format(profession)
			sqlStr = 'SELECT recipeID, userID, tRecipe.schematicID, recipeName, (SELECT imageName FROM tSchematicImages img WHERE img.schematicID=tRecipe.schematicID AND img.imageType=1) AS schemImage FROM tRecipe INNER JOIN tSchematic ON tRecipe.schematicID = tSchematic.schematicID LEFT JOIN tSkillGroup ON tSchematic.skillGroup = tSkillGroup.skillGroup WHERE userID="' + currentUser + '" AND (tRecipe.galaxy=' + str(galaxy) + ' OR tRecipe.galaxy IS NULL)' + profFilter + ' ORDER BY recipeName;'
			cursor.execute(sqlStr)
			row = cursor.fetchone()

			while (row != None):
				if (row[4] != None):
					schemImageName = row[4]
				else:
					schemImageName = 'none.jpg'
				r = ghObjectRecipe.schematicRecipe()
				r.recipeID = row[0]
				r.schematicID = row[2]
				r.recipeName = row[3]
				r.schematicImage = schemImageName
				sqlStr = 'SELECT si.ingredientName, ingredientResource, ingredientObject, ingredientContribution, ingredientQuality FROM tSchematicIngredients si LEFT JOIN (SELECT ingredientName, ingredientResource, ingredientQuality FROM tRecipeIngredients WHERE recipeID=' + str(r.recipeID) + ') ri ON si.ingredientName = ri.ingredientName WHERE schematicID="' + r.schematicID + '" and ingredientType = 0 ORDER BY ingredientQuantity DESC, si.ingredientName;'
				ingCursor = conn.cursor()
				ingCursor.execute(sqlStr)
				ingRow = ingCursor.fetchone()
				while (ingRow != None):
					ri = ghObjectRecipe.recipeIngredient()
					ri.ingredientObject = ingRow[2]
					ri.ingredientResource = ingRow[1]
					ri.ingredientName = ingRow[0]
					ri.ingredientAmount = ingRow[3]
					ri.resourceQuality = ingRow[4]
					r.recipeIngredients.append(ri)
					ingRow = ingCursor.fetchone()

				ingCursor.close()
				tmpStr += r.getRow('normal',sid)

				row = cursor.fetchone()

		tmpStr = headStr + tmpStr + '</table>'

		cursor.close()
	conn.close()

	print 'Content-type: text/html\n'
	print tmpStr
Пример #5
0
def main():
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	uiTheme = ''
	# Get Cookies
	useCookies = 1
	cookies = Cookie.SimpleCookie()
	try:
		cookies.load(os.environ['HTTP_COOKIE'])
	except KeyError:
		useCookies = 0

	if useCookies:
		try:
			currentUser = cookies['userID'].value
		except KeyError:
			currentUser = ''
		try:
			loginResult = cookies['loginAttempt'].value
		except KeyError:
			loginResult = 'success'
		try:
			sid = cookies['gh_sid'].value
		except KeyError:
			sid = form.getfirst('gh_sid', '')
		try:
			uiTheme = cookies['uiTheme'].value
		except KeyError:
			uiTheme = ''
		try:
			galaxy = cookies['galaxy'].value
		except KeyError:
			galaxy = "8"
	else:
		currentUser = ''
		loginResult = form.getfirst('loginAttempt', '')
		sid = form.getfirst('gh_sid', '')

	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)

	# Get a session
	logged_state = 0
	linkappend = ''
	disableStr = ''
	if loginResult == None:
		loginResult = 'success'

	sess = dbSession.getSession(sid, 2592000)
	if (sess != ''):
		logged_state = 1
		currentUser = sess
		if (uiTheme == ''):
			uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
		if (useCookies == 0):
			linkappend = 'gh_sid=' + sid
	else:
		disableStr = ' disabled="disabled"'
		if (uiTheme == ''):
			uiTheme = 'crafter'

	# Get recipe id from path
	path = []
	if os.environ.has_key('PATH_INFO'):
		path = os.environ['PATH_INFO'].split('/')[1:]
		path = [p for p in path if p != '']
	recipeHTML = ''
	slotHTML = ''
	schematicSummaryHTML = ''
	schematicDetailsHTML = ''
	ingTypes = ''
	ingGroups = ''
	pageType = 'recipe'
	if len(path) > 0:
		recipeID = dbShared.dbInsertSafe(path[0])
		url = url + '/' + recipeID
		if logged_state == 1:
			# Look up recipe info
			try:
				conn = dbShared.ghConn()
				cursor = conn.cursor()
			except Exception:
				recipeHTML = "Error: could not connect to database"
			if (cursor and recipeID.isdigit()):
				cursor.execute('SELECT recipeID, userID, tRecipe.schematicID, recipeName, (SELECT imageName FROM tSchematicImages si WHERE si.schematicID=tRecipe.schematicID AND si.imageType=1) AS schemImage, schematicName, complexity FROM tRecipe INNER JOIN tSchematic ON tRecipe.schematicID = tSchematic.schematicID WHERE recipeID=' + recipeID + ';')
				row = cursor.fetchone()

				if (row != None):
					if row[1] == currentUser:
						# main recipe data
						if (row[4] != None):
							schemImageName = row[4]
						else:
							schemImageName = 'none.jpg'
						schematicSummaryHTML = '<img src="/images/schematics/' + schemImageName + '" class="schematics" />'
						r = ghObjectRecipe.schematicRecipe()
						r.recipeID = row[0]
						r.schematicID = row[2]
						r.recipeName = row[3]
						r.schematicImage = schemImageName
						recipeHTML = '<div><a href="" id="nameLink" onclick="$(this).hide();$(\'#nameEditor\').show();$(\'#recipeName\').focus();return false;" title="Click to edit name." class="nameLink">' + r.recipeName + '</a></div><div id="nameEditor" style="display:none;"><input type="text" id="recipeName" size="30" maxlength="255" value="' + r.recipeName + '" onblur="$(\'#nameLink\').html(this.value).show();$(\'#nameEditor\').hide();" onkeyup="if(event.keyCode == 13){$(\'#nameLink\').html(this.value).show();$(\'#nameEditor\').hide();}"/></div><div style="float:right;"><button type=button value="Save" class="ghButton" onclick="saveRecipe(' + recipeID + ',$(\'#recipeName\').val());">Save</button> <button type=button value="Delete" class="ghButton" onclick="deleteRecipe(\'recipe\',' + str(r.recipeID) + ');">Delete</button></div>'
						recipeHTML += '<div class="footer"/><div id="factoryCalc" style="text-align:left">Calculate Factory Run: <input type="text" id="factoryAmount" size="6" maxlength="4"/> units.  <button type="button" value="Calculate" class="ghButton" onclick="getFactoryList(parseInt($(\'#factoryAmount\').val()))">Calculate</button><div id="factoryResults"></div></div>'

						# schematic quality data
						schematicDetailsHTML = '<div><a href="' + ghShared.BASE_SCRIPT_URL + 'schematics.py/' + row[2] + '" title="Go to schematic page.">' + row[5] + '</a></div>'
						schematicDetailsHTML += '<div>Complexity: ' + str(row[6]) + '</div>'
						expGroup = ''
						expProp = ''
						schematicDetailsHTML += '<td valign="top"><h3>Qualities</h3><ul id="qualitiesList" style="margin-top:6px;">'
						expCursor = conn.cursor()
						expCursor.execute('SELECT tSchematicQualities.expQualityID, expProperty, expGroup, statName, statWeight, weightTotal FROM tSchematicQualities INNER JOIN tSchematicResWeights ON tSchematicQualities.expQualityID = tSchematicResWeights.expQualityID WHERE schematicID="' + r.schematicID + '" ORDER BY expGroup, expProperty, statName;')
						expRow = expCursor.fetchone()
						while (expRow != None):
							if (expGroup != expRow[2]):
								tmpName = expRow[2].replace('_',' ')
								schematicDetailsHTML = schematicDetailsHTML + '<li class="groupText">' + tmpName + '</li>'
								expGroup = expRow[2]
							if (expProp != expRow[1]):
								tmpName = expRow[1].replace('_',' ')
								schematicDetailsHTML = schematicDetailsHTML + '<li class="schemQualityProperty altText">' + tmpName + '</li>'
								expProp = expRow[1]
						
							schematicDetailsHTML += '<li class="schemQualityItem" tag="' + expRow[3] + ':' + str((expRow[4]*1.0/expRow[5])*100) + '"><span class="inlineBlock" style="width:100px;">' + ghNames.getStatName(expRow[3]) + (': </span><span>%.0f' % ((expRow[4]*1.0/expRow[5])*100)) + '%</span></li>'

							expRow = expCursor.fetchone()

						expCursor.close()
						# Look up ingredient data
						ri = None
						sqlStr = 'SELECT si.ingredientName, ingredientResource, ingredientObject, ingredientQuantity, ingredientContribution, rt.containerType tcontainer, rg.containerType gcontainer, rt.resourceTypeName, rg.groupName, ingredientQuality FROM tSchematicIngredients si LEFT JOIN (SELECT ingredientName, ingredientResource, ingredientQuality FROM tRecipeIngredients WHERE recipeID=' + str(r.recipeID) + ') ri ON si.ingredientName = ri.ingredientName LEFT JOIN tResourceType rt ON si.ingredientObject = rt.resourceType LEFT JOIN tResourceGroup rg ON si.ingredientObject = rg.resourceGroup WHERE schematicID="' + r.schematicID + '" ORDER BY ingredientQuantity DESC, si.ingredientName'
						ingCursor = conn.cursor()
						ingCursor.execute(sqlStr)
						ingRow = ingCursor.fetchone()
						while (ingRow != None):
							if ingRow[5] == None:
								if ingRow[6] == None:
									container = 'default'
									objectName = ingRow[2].rpartition('/')[2].replace('_',' ')
									if objectName[-4:] == '.iff':
										objectName = objectName[:-4]
								else:
									ingGroups += '"' + ingRow[2] + '",'
									container = ingRow[6]
									objectName = ingRow[8]
							else:
								ingTypes += '"' + ingRow[2] + '",'
								container = ingRow[5]
								objectName = ingRow[7]

							# get details of ingredient resource for schematic
							resDetails = ''
							if ingRow[1] != None and (ingRow[5] != None or ingRow[6] != None):
								spawn = resource.getResource(conn, logged_state, currentUser, ingRow[1], None, None)
								resDetails = 'Loaded with: ' + spawn.spawnName + ', ' + spawn.resourceTypeName + '<br />' + spawn.getStatList()
							r.recipeIngredients.append(ghObjectRecipe.recipeIngredient(ingRow[2], ingRow[1], ingRow[0], ingRow[3], container, objectName, ingRow[9], resDetails))
							ingRow = ingCursor.fetchone()

						ingCursor.close()
						if ingTypes != '':
							ingTypes = ingTypes[:-1]
						if ingGroups != '':
							ingGroups = ingGroups[:-1]
						slotHTML = r.getIngredientSlots()
					else:
						recipeHTML = "That is not your recipe."
				else:
					recipeHTML = "The recipe ID given could not be found."
				cursor.close()
			else:
				# Render recipe home if any non number in sub path
				pageType = 'home'
				recipeHTML = 'Home<div style="float:right;"><button type=button value="New Recipe" class="ghButton" onclick="addRecipe();">New Recipe</button></div>'

			conn.close()
		else:
			recipeHTML = "You must be logged in to manage recipes."
	else:
		recipeHTML = 'You have not specified a recipe to edit, would you like to create a new one?<div style="float:right;"><button type=button value="New Recipe" class="ghButton" onclick="addRecipe();">New Recipe</button></div>'

	pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
	print 'Content-type: text/html\n'
	env = Environment(loader=FileSystemLoader('templates'))
	env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
	template = env.get_template('recipe.html')
	print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=loginResult, linkappend=linkappend, url=url, pictureName=pictureName, imgNum=ghShared.imgNum, planetList=ghLists.getPlanetList(), galaxyList=ghLists.getGalaxyList(), professionList=ghLists.getProfessionList(), recipeHTML=recipeHTML, slotHTML=slotHTML, schematicSummaryHTML=schematicSummaryHTML, schematicDetailsHTML=schematicDetailsHTML, ingTypes=ingTypes, ingGroups=ingGroups, pageType=pageType)
Пример #6
0
def buildBestRecipe(conn, schem, inventory, user):
	#sys.stderr.write(str(schem) + '\n')
	r = ghObjectRecipe.schematicRecipe()
	r.schematicID = schem[0]
	r.recipeName = schem[4]
	if schem[5] != None:
		r.schematicImage = schem[5]
	# Look up the schematic ingredients
	oingSql = 'SELECT ingredientObject, Sum(ingredientContribution) FROM tSchematicIngredients WHERE schematicID="' + schem[0] + '" AND ingredientType = 0 GROUP BY ingredientObject;'
	oingCursor = conn.cursor()
	oingCursor.execute(oingSql)
	# Find other potential ingredients and their quality from inventory
	filledIng = True
	oingRow = oingCursor.fetchone()
	ingredients = []
	while oingRow != None and oingRow[0] != None:
		thisFilled = False
		# Iterate over the option for each ingredient and save top quality to new list
		for resType in inventory.iterkeys():
			if str(resType).find('\'' + oingRow[0] + '\'') > -1:
				thisFilled = True
				spawns = inventory[resType].split()
				for s in spawns:
					spawnQuality = recipe.calcIngredientQuality(conn, s.split('|')[0].strip(','), schem[0], user)
					ingredients.append((oingRow[0], s, spawnQuality))
		if thisFilled == False:
			filledIng = False
			break
		oingRow = oingCursor.fetchone()

	oingCursor.close()
	oingRow = None
	# If all ingredients can be found in inventory
	if filledIng:
		# Add the top quality scores found from sorted lists as new suggestion
		ingredients = sorted(ingredients, key=lambda ing: ing[2], reverse=True)
		cingSql = 'SELECT si.ingredientName, ingredientObject, ingredientQuantity, ingredientContribution, rt.containerType tcontainer, rg.containerType gcontainer, rt.resourceTypeName, rg.groupName FROM tSchematicIngredients si LEFT JOIN tResourceType rt ON si.ingredientObject = rt.resourceType LEFT JOIN tResourceGroup rg ON si.ingredientObject = rg.resourceGroup WHERE schematicID="' + r.schematicID + '" ORDER BY ingredientQuantity DESC, si.ingredientName'
		cingCursor = conn.cursor()
		cingCursor.execute(cingSql)
		cingRow = cingCursor.fetchone()
		while (cingRow != None):
			for ing in ingredients:
				if ing[0] == cingRow[1]:
					# get details of ingredient resource and add to recipe
					if cingRow[4] == None:
						if cingRow[5] == None:
							container = 'default'
							objectName = cingRow[1].rpartition('/')[2].replace('_',' ')
							if objectName[-4:] == '.iff':
								objectName = objectName[:-4]
						else:
							container = cingRow[5]
							objectName = cingRow[7]
					else:
						container = cingRow[4]
						objectName = cingRow[6]

					resDetails = ''
					spawn = resource.getResource(conn, 1, user, ing[1].split('|')[0].strip(','), None, None)
					resDetails = 'Loaded with: ' + spawn.spawnName + ', ' + spawn.resourceTypeName + '<br />' + spawn.getStatList()
					r.recipeIngredients.append(ghObjectRecipe.recipeIngredient(cingRow[1], ing[1].split('|')[0].strip(','), cingRow[0], cingRow[2], container, objectName, ing[2], resDetails))
					break

			cingRow = cingCursor.fetchone()
		cingCursor.close()
	return r
Пример #7
0
def main():
	form = cgi.FieldStorage()
	# Get Cookies
	useCookies = 1
	cookies = Cookie.SimpleCookie()
	try:
		cookies.load(os.environ['HTTP_COOKIE'])
	except KeyError:
		useCookies = 0

	if useCookies:
		try:
			currentUser = cookies['userID'].value
		except KeyError:
			currentUser = ''
		try:
			sid = cookies['gh_sid'].value
		except KeyError:
			sid = form.getfirst('gh_sid', '')
	else:
		currentUser = ''
		sid = form.getfirst('gh_sid', '')

	listFormat = form.getfirst('listFormat', '')
	listType = form.getfirst('listType', '')
	galaxy = form.getfirst('galaxy', '')
	profession = form.getfirst('profession', '')

	# Get a session
	logged_state = 0

	sess = dbSession.getSession(sid, 2592000)
	if (sess != ''):
		logged_state = 1
		currentUser = sess

	# Main program
	errstr = ''
	tmpStr = ''

	if not galaxy.isdigit():
		errstr = 'Error: You must provide a valid galaxy id.'
	if profession != '' and not profession.isdigit():
		errstr = 'Error: That is not a valid profession id.'
	if logged_state != 1:
		errstr = 'Error: You must be logged in to get your recipe list.'

	conn = dbShared.ghConn()
	cursor = conn.cursor()
	if (cursor and errstr == ''):
		headStr = '<table width="100%">'
		if listType == 'suggest':
			rl = getSuggestedRecipes(conn, currentUser, galaxy, profession)
			if len(rl) > 0:
				for r in rl:
					tmpStr += r.getRow(listType)
			else:
				tmpStr = '<tr><td>No suggestions at this time.  Try adding more to your inventory.</td></tr>'
		else:
			sqlStr = 'SELECT recipeID, userID, schematicID, recipeName, (SELECT imageName FROM tSchematicImages img WHERE img.schematicID=tRecipe.schematicID AND img.imageType=1) AS schemImage FROM tRecipe WHERE userID="' + currentUser + '" ORDER BY recipeName;'
			cursor.execute(sqlStr)
			row = cursor.fetchone()

			while (row != None):
				if (row[4] != None):
					schemImageName = row[4]
				else:
					schemImageName = 'none.jpg'
				r = ghObjectRecipe.schematicRecipe()
				r.recipeID = row[0]
				r.schematicID = row[2]
				r.recipeName = row[3]
				r.schematicImage = schemImageName
				sqlStr = 'SELECT si.ingredientName, ingredientResource, ingredientObject, ingredientContribution, ingredientQuality FROM tSchematicIngredients si LEFT JOIN (SELECT ingredientName, ingredientResource, ingredientQuality FROM tRecipeIngredients WHERE recipeID=' + str(r.recipeID) + ') ri ON si.ingredientName = ri.ingredientName WHERE schematicID="' + r.schematicID + '" and ingredientType = 0 ORDER BY ingredientQuantity DESC, si.ingredientName;'
				ingCursor = conn.cursor()
				ingCursor.execute(sqlStr)
				ingRow = ingCursor.fetchone()
				while (ingRow != None):
					ri = ghObjectRecipe.recipeIngredient()
					ri.ingredientObject = ingRow[2]
					ri.ingredientResource = ingRow[1]
					ri.ingredientName = ingRow[0]
					ri.ingredientAmount = ingRow[3]
					ri.resourceQuality = ingRow[4]
					r.recipeIngredients.append(ri)
					ingRow = ingCursor.fetchone()

				ingCursor.close()
				tmpStr += r.getRow('normal',sid)

				row = cursor.fetchone()

		tmpStr = headStr + tmpStr + '</table>'

		cursor.close()
	conn.close()

	print 'Content-type: text/html\n'
	print tmpStr