def get_next_episode(self, rating_key): plex_item = get_item(rating_key) if not plex_item: return if get_item_kind_from_item(plex_item) == "episode": # get season season = get_item(plex_item.season.rating_key) if not season: return # determine next episode # next episode is in the same season if plex_item.index < season.episode_count: # get next ep for ep in season.children(): if ep.index == plex_item.index + 1: return ep # it's not, try getting the first episode of the next season else: # get show show = get_item(plex_item.show.rating_key) # is there a next season? if season.index < show.season_count: for other_season in show.children(): if other_season.index == season.index + 1: next_season = other_season for ep in next_season.children(): if ep.index == 1: return ep
def init_items(self): weapon = items.get_item(0, 1) armour = items.get_item(8, 1) self.inventory.add_item(weapon) self.inventory.try_to_equip(0) self.inventory.add_item(armour) self.inventory.try_to_equip(1)
def flatten_media(media, kind="series"): """ iterates through media and returns the associated parts (videos) :param media: :param kind: :return: """ parts = [] def get_metadata_dict(item, part, add): data = { "section": item.section.title, "path": part.file, "folder": os.path.dirname(part.file), "filename": os.path.basename(part.file) } data.update(add) return data if kind == "series": for season in media.seasons: season_object = media.seasons[season] for episode in media.seasons[season].episodes: ep = media.seasons[season].episodes[episode] # get plex item via API for additional metadata plex_episode = get_item(ep.id) for item in media.seasons[season].episodes[episode].items: for part in item.parts: parts.append( get_metadata_dict(plex_episode, part, {"video": part, "type": "episode", "title": ep.title, "series": media.title, "id": ep.id, "series_id": media.id, "season_id": season_object.id, "season": plex_episode.season.index, }) ) else: plex_item = get_item(media.id) for item in media.items: for part in item.parts: parts.append( get_metadata_dict(plex_item, part, {"video": part, "type": "movie", "title": media.title, "id": media.id, "series_id": None, "season_id": None, "section": plex_item.section.title}) ) return parts
def media_to_videos(media, kind="series"): """ iterates through media and returns the associated parts (videos) :param media: :param kind: :return: """ videos = [] if kind == "series": for season in media.seasons: season_object = media.seasons[season] for episode in media.seasons[season].episodes: ep = media.seasons[season].episodes[episode] # get plex item via API for additional metadata plex_episode = get_item(ep.id) for item in media.seasons[season].episodes[episode].items: for part in item.parts: videos.append( get_metadata_dict( plex_episode, part, { "plex_part": part, "type": "episode", "title": ep.title, "series": media.title, "id": ep.id, "series_id": media.id, "season_id": season_object.id, "episode": plex_episode.index, "season": plex_episode.season.index, "section": plex_episode.section.title })) else: plex_item = get_item(media.id) for item in media.items: for part in item.parts: videos.append( get_metadata_dict( plex_item, part, { "plex_part": part, "type": "movie", "title": media.title, "id": media.id, "series_id": None, "season_id": None, "section": plex_item.section.title })) return videos
def add_other(): from items import get_item char.equipment.update( {'Cloak of Protection': get_item('Cloak of Protection', 1)}) char.update()
def display_items(self, items): for item in items: args = dict() args["name"] = item.get_name() price_in = item.recipe.get_fabrication_price() price_out = item.recipe.get_runes_result_price() args["price in"] = unicode(int(price_in)) args["price out"] = unicode(int(price_out)) args["profit"] = unicode(int(price_out - price_in)) if (int(price_out - price_in)) > 0: args["profit tag"] = u"positif" else: args["profit tag"] = u"negatif" args["ingredients"] = [] args["craft tag"] = u"complet" for ingredient, nb in item.recipe.ingredients.items(): obj = get_item(ingredient) name = obj.get_name() if name in prix.prix: price = unicode(prix.prix[name]) tag = u"price_ok" elif hasattr(obj, "recipe"): price = unicode(obj.recipe.get_fabrication_price()) tag = u"price_ok" else: price = u"?" tag = u"no_price" args["craft tag"] = u"incomplet" args["ingredients"].append((unicode(nb), name, price, tag)) args["runes"] = dict() args["brisage tag"] = u"complet" for (carac, (min, max)) in item.get_caracs().items(): if carac in carac_to_rune: args["runes"][carac] = [] rune = carac_to_rune[carac] powers = item.runes[rune] names = (u"Rune ", u"Rune Pa ", u"Rune Ra ") prix_ba = prix_pa = prix_ra = u"?" for q, name in zip(powers, names): if q != 0: qt = u"%0.2f"%(q,) rune_name = name + rune if rune_name in prix.prix: price = unicode(prix.prix[rune_name]) tag = u"price_ok" else: price = u"?" tag = u"no_price" args["brisage tag"] = u"incomplet" args["runes"][carac].append((qt, rune_name, price, tag)) display = web.display_item(args) self.write(display)
def __init__(self, result,job): self.result = result self.ingredients = dict() self.caracs = dict() self.job = job item = get_item(self.result) if item != None: string = item.get_name() for (carac, (min,max)) in item.get_caracs().items(): self.caracs[carac] = (min,max)
def test_get_item(self): w = items.get_item("W01") self.assertTrue(isinstance(w,items.Weapon)) self.assertEqual("W01", w.id) self.assertEqual("Empty Hands", w.name) self.assertEqual(10, w.value) self.assertEqual("1d4", w.damage) a = items.get_item("A01") self.assertTrue(isinstance(a,items.Armor)) self.assertEqual("A01", a.id) self.assertEqual("Iron Skin", a.name) self.assertEqual(39, a.value) self.assertEqual(3, a.rating) a2 = items.get_item("Headband") self.assertTrue(isinstance(a2,items.Armor)) self.assertEqual("A02", a2.id) self.assertEqual("Headband", a2.name) self.assertEqual(3, a2.value) self.assertEqual(0, a2.rating)
def execute(self, block_id, amount=1, *args, **kwargs): try: bid = BlockID(block_id) item_or_block = get_item(float("%s.%s" % (bid.main, bid.sub))) self.send_info("Giving %s of '%s'." % (amount, item_or_block.name)) self.user.inventory.add_item(bid, quantity=int(amount)) #self.controller.item_list.update_items() #self.controller.inventory_list.update_items() except KeyError: raise CommandException(self.command_text, message="ID %s unknown." % block_id) except ValueError: raise CommandException(self.command_text, message="ID should be a number. Amount must be an integer.")
def execute(self, block_id, amount=1, *args, **kwargs): try: bid = BlockID(block_id) item_or_block = get_item(float("%s.%s" % (bid.main, bid.sub))) self.send_info("Giving %s of '%s'." % (amount, item_or_block.name)) self.user.inventory.add_item(bid, quantity=int(amount)) self.controller.item_list.update_items() self.controller.inventory_list.update_items() except KeyError: raise CommandException(self.command_text, message="ID %s unknown." % block_id) except ValueError: raise CommandException(self.command_text, message="ID should be a number. Amount must be an integer.")
def get_runes_result_price(self): total = 0 for (type, (ba, pa, ra)) in get_item(self.result).runes.iteritems(): baname = "Rune " + type paname = "Rune Pa " + type raname = "Rune Ra " + type if baname in prix.prix: total += ba * prix.prix[baname] if paname in prix.prix: total += pa * prix.prix[paname] if raname in prix.prix: total += ra * prix.prix[raname] return total
def main(): cluster = Cluster() session = cluster.connect() keyspace = 'warehouse' warehouse.create_keyspace(keyspace, session) session.set_keyspace(keyspace) items.create_table(session) item = { 'id': 1234, 'title': 'Test Item', } item_id = get_item_id(item) # new item, insert items.upsert_item(item_id, item, session) # unchanged item, update check time items.upsert_item(item_id, item, session) # changed item, update timeseries.create_table(session) item['title'] = 'New title' items.upsert_item(item_id, item, session) # fetch item item_from_db = items.get_item(item_id, session) assert item_from_db == item event = { 'id': 1234, 'pageviews': 100, } event_type = get_event_type(event) # new event, insert timeseries.upsert_event(event_type, event, session) # unchanged event, update check time timeseries.upsert_event(event_type, event, session) # changed event, insert event['pageviews'] = 120 timeseries.upsert_event(event_type, event, session) # fetch latest event event_from_db, insert_time = timeseries.get_last_event(event_type, session) assert event_from_db == event warehouse.drop_keyspace(keyspace, session)
def on_playing(self, info): if not config.use_activities: return # ignore non-playing states and anything too far in if info["state"] != "playing" or info["viewOffset"] > 60000: return # don't trigger on the first hit ever if "last_played_items" not in Dict: Dict["last_played_items"] = [] Dict.Save() return rating_key = info["ratingKey"] if rating_key not in Dict["last_played_items"]: # new playing; store last 10 recently played items Dict["last_played_items"].insert(0, rating_key) Dict["last_played_items"] = Dict["last_played_items"][:10] Dict.Save() debug_msg = "Started playing %s. Refreshing it." % rating_key key_to_refresh = None if config.activity_mode in ["refresh", "next_episode", "hybrid"]: # next episode or next episode and current movie if config.activity_mode in ["next_episode", "hybrid"]: plex_item = get_item(rating_key) if not plex_item: Log.Warn("Can't determine media type of %s, skipping" % rating_key) return if get_item_kind_from_item(plex_item) == "episode": next_ep = self.get_next_episode(rating_key) if next_ep: key_to_refresh = next_ep.rating_key debug_msg = "Started playing %s. Refreshing next episode (%s, S%02iE%02i)." % \ (rating_key, next_ep.rating_key, int(next_ep.season.index), int(next_ep.index)) else: if config.activity_mode == "hybrid": key_to_refresh = rating_key elif config.activity_mode == "refresh": key_to_refresh = rating_key if key_to_refresh: Log.Debug(debug_msg) refresh_item(key_to_refresh)
def add_class_features(self, char): if not hasattr(char, 'classes'): char.classes = Dict() origin = 'origin: ' + self.class_name for trait in vars(self).keys(): if trait == 'saves': for save in self.saves: char.saving_throws[save].prof += [origin] elif trait == 'skills': for skill in self.skills: char.skills[skill].prof += [origin] elif trait == 'prof_weapons': char.proficiencies.weapons[origin] = self.prof_weapons elif trait == 'prof_armor': char.proficiencies.armor[origin] = self.prof_armor elif trait == 'prof_tools': char.proficiencies.tools[origin] = self.prof_tools elif trait == 'equipment': self.equipment = f.choose_weapons(self.equipment) for item in self.equipment: if item[0] in char.equipment: char.equipment[item[0]].add_number(item[1]) else: char.equipment.update( {item[0]: get_item(item[0], item[1])}) elif trait not in [ 'class_name', 'hit_dice', 'hit_points', 'levels' ]: raise Exception( f"{trait} included which haven't been added.") char.classes[self.class_name] = character_class( 1, self.hit_dice, self.hit_points, True) else: char.classes[self.class_name] = character_class( 1, self.hit_dice, self.hit_points, False) for feature in self.levels[1]: new_feature = get_feature(feature) char.features[f"Class: {self.class_name}"][feature] = new_feature new_feature.initial_effects(char)
def load_items(file = 'Recipes.json'): global items global all_recipes json_data=open(file) data = json.load(json_data) for node in data: item = get_item(node["resultId"]) if item: recette = recipe(node["resultId"], node["jobId"]) for (ingredient,quantity) in zip(node["ingredientIds"], node["quantities"]): recette.add_ingredient(ingredient,quantity) if recette.job not in recipes_by_job: recipes_by_job[recette.job] = dict() recipes_by_job[recette.job][recette.result] = recette all_recipes += [recette]
def make_human_race(self): var.player = people.human(player=True) var.player.name = ['Player','Derp'] var.player.male = False var.player.age = 25 var.player.strength = 4 var.player.dexterity = 5 var.player.intelligence = 3 var.player.charisma = 8 #var.player.warp_to(list(self.get_random_town().loc)) var.player.warp_to([1,1]) var.player.birthplace = var.player var.player.add_item(item.get_item('light')) var.camera[0] = var.player.loc[0]-40 var.camera[1] = var.player.loc[1]-12 if var.camera[0]<0: var.camera[0] = 0 if var.camera[1]<0: var.camera[1] = 0
def execute(self, x, y, z, block_id): bid = BlockID(block_id) try: item_or_block = get_item(float("%s.%s" % (bid.main, bid.sub))) except KeyError: raise CommandException(self.command_text, message="ID %s unknown." % block_id) except ValueError: raise CommandException(self.command_text, message="ID should be a number. Amount must be an integer.") if issubclass(type(item_or_block), Block): block = item_or_block try: self.world.add_block((int(x), int(y), int(z)), block) except ValueError: raise CommandException(self.command_text, message="Invalid coordinates must be integers") else: raise CommandException( self.command_text, message="Invalid value for block, expected Block not %s" % type(item_or_block).__name__)
def update(self, map_, graphics, consts, level, inventory): level_consts = consts['level'][level] items = consts['items'] num_items_const = level_consts['num_items'] num_items = int(random.gauss(num_items_const['avg'], num_items_const['std'])) allowed_items = level_consts['allowed_items'] population = [k for k, v in allowed_items.iteritems() for _ in range(v['weight'])] entities = {} for n in range(num_items): p = random.choice(population) item_cls = get_item(p) item = item_cls(p, items[p], inventory, self.turn, self.message) place_in_random_room(item, entities, map_.rooms) entity_key = "item_{}_{}".format(p, random.randint(0, 1e8)) log.debug("Added {}".format(entity_key)) entities[entity_key] = EntityPack(item, graphics) return entities
def store_subtitle_info(scanned_video_part_map, downloaded_subtitles, storage_type, mode="a"): """ stores information about downloaded subtitles in plex's Dict() """ existing_parts = [] for video, video_subtitles in downloaded_subtitles.items(): part = scanned_video_part_map[video] part_id = str(part.id) video_id = str(video.id) plex_item = get_item(video_id) metadata = video.plexapi_metadata title = get_title_for_video_metadata(metadata) subtitle_storage = get_subtitle_storage() stored_subs = subtitle_storage.load_or_new(plex_item) existing_parts.append(part_id) stored_any = False for subtitle in video_subtitles: lang = Locale.Language.Match(subtitle.language.alpha2) Log.Debug(u"Adding subtitle to storage: %s, %s, %s" % (video_id, part_id, title)) ret_val = stored_subs.add(part_id, lang, subtitle, storage_type, mode=mode) if ret_val: Log.Debug("Subtitle stored") stored_any = True else: Log.Debug("Subtitle already existing in storage") if stored_any: Log.Debug("Saving subtitle storage for %s" % video_id) subtitle_storage.save(stored_subs)
def add_item(self, item_id, quantity=1, durability=-1): if quantity < 1 or item_id == 0: return False item_stack = self.get_item(item_id) max_size = get_item(item_id).max_stack_size retval = False while quantity > 0: # can't find an unfilled slot if not item_stack: # find an empty slot to store these items index = self.find_empty_slot() if index == -1 and len(self.slots) == self.slot_count: return retval # overflow ? if quantity > max_size: quantity -= max_size item_stack = ItemStack(type=item_id, amount=max_size, durability=durability) else: item_stack = ItemStack(type=item_id, amount=quantity, durability=durability) quantity = 0 self.slots[index] = item_stack retval = True else: capacity = max_size - item_stack.amount if quantity < capacity: # there is a slot with enough space item_stack.change_amount(quantity) return True else: # overflow quantity -= capacity item_stack.change_amount(capacity) # find next unfilled slot item_stack = self.get_unfilled_item(item_id) return True
def write_item(file, item, recipe): f.write(item.get_name() + '\t') #recipe n = 0 for ingredient, nb in recipe.ingredients.items(): f.write(str(nb) + "\t") obj = get_item(ingredient) if obj != None: f.write(obj.get_name() + "\t") else: f.write(str(ingredient) + "\t") n += 1 for i in range(n, 8): f.write('\t\t') for (carac, (min, max)) in item.get_caracs().items(): if carac in carac_to_rune: rune = carac_to_rune[carac] (ba, pa, ra) = item.runes[rune] f.write(str(ba) + '\t' + str(pa) + '\t' + str(ra) + '\t' + rune + '\t') else: pass f.write('\n')
def add_item(self, item_id, quantity = 1, durability = -1): if quantity < 1 or item_id == 0: return False item_stack = self.get_item(item_id) max_size = get_item(item_id).max_stack_size retval = False while quantity > 0: # can't find an unfilled slot if not item_stack: # find an empty slot to store these items index = self.find_empty_slot() if index == -1 and len(self.slots) == self.slot_count: return retval # overflow ? if quantity > max_size: quantity -= max_size item_stack = ItemStack(type=item_id, amount=max_size, durability=durability) else: item_stack = ItemStack(type=item_id, amount=quantity, durability=durability) quantity = 0 self.slots[index] = item_stack retval = True else: capacity = max_size - item_stack.amount if quantity < capacity: # there is a slot with enough space item_stack.change_amount(quantity) return True else: # overflow quantity -= capacity item_stack.change_amount(capacity) # find next unfilled slot item_stack = self.get_unfilled_item(item_id) return True
def display_prices_list(self, lettre): self.display_metiers() self.write(u""" <table> <tr> <th>Nom</th> <th>Prix</th> <th></th> </tr>""") items = [] for id in get_items(): item = get_item(id) if item.get_name()[0] == lettre or (lettre in correspondances and item.get_name()[0] in correspondances[lettre]): items.append(item) items.sort(key = lambda item: item.get_name()) for item in items: self.write(u""" <tr> <form action="/prices" method="get"> <td> <input class="object_name" type="text" name="nom" disabled="disabled" value=\"""" + item.get_name() + u""""/> </td> <td> <input class="object_price" type="number" name="prix" value=\"""" + unicode(item.get_price()) + """"/> </td> <td> <input type="hidden" name="id" value=\"""" + unicode(id) + u""""/> <input type="submit" name="submit" value="Modifier"/> </td> </form> </tr>""") self.write(u"</table>")
def get_fabrication_price(self): return sum(nb*get_item(id).get_price() for (id,nb) in self.ingredients.iteritems())
def on_playing(self, info): # ignore non-playing states and anything too far in if info["state"] != "playing" or info["viewOffset"] > 60000: return # don't trigger on the first hit ever if "last_played_items" not in Dict: Dict["last_played_items"] = [] Dict.Save() return rating_key = info["ratingKey"] # only use integer based rating keys try: int(rating_key) except ValueError: return if rating_key in Dict["last_played_items"] and rating_key != Dict[ "last_played_items"][0]: # shift last played Dict["last_played_items"].insert( 0, Dict["last_played_items"].pop( Dict["last_played_items"].index(rating_key))) Dict.Save() elif rating_key not in Dict["last_played_items"]: # new playing; store last X recently played items Dict["last_played_items"].insert(0, rating_key) Dict["last_played_items"] = Dict[ "last_played_items"][:config.store_recently_played_amount] Dict.Save() if not config.react_to_activities: return debug_msg = "Started playing %s. Refreshing it." % rating_key # todo: cleanup debug messages for hybrid-plus keys_to_refresh = [] if config.activity_mode in [ "refresh", "next_episode", "hybrid", "hybrid-plus" ]: # next episode or next episode and current movie if config.activity_mode in [ "next_episode", "hybrid", "hybrid-plus" ]: plex_item = get_item(rating_key) if not plex_item: Log.Warn("Can't determine media type of %s, skipping" % rating_key) return if get_item_kind_from_item(plex_item) == "episode": next_ep = self.get_next_episode(rating_key) if config.activity_mode == "hybrid-plus": keys_to_refresh.append(rating_key) if next_ep: keys_to_refresh.append(next_ep.rating_key) debug_msg = "Started playing %s. Refreshing next episode (%s, S%02iE%02i)." % \ (rating_key, next_ep.rating_key, int(next_ep.season.index), int(next_ep.index)) else: if config.activity_mode in ("hybrid", "hybrid-plus"): keys_to_refresh.append(rating_key) elif config.activity_mode == "refresh": keys_to_refresh.append(rating_key) if keys_to_refresh: Log.Debug(debug_msg) Log.Debug("Refreshing %s", keys_to_refresh) for key in keys_to_refresh: refresh_item(key)
def test_weapon(self): i = items.get_item('W01') d = i.get_damage() self.assertNotEqual(0,d)
def get_result_price(self): return get_item(self.result).get_price()
def get_plex_metadata(rating_key, part_id, item_type, plex_item=None): """ uses the Plex 3rd party API accessor to get metadata information :param rating_key: movie or episode :param part_id: :param item_type: :return: """ if not plex_item: plex_item = get_item(rating_key) if not plex_item: return # find current part current_part = get_part(plex_item, part_id) if not current_part: raise helpers.PartUnknownException("Part unknown") stream_info = get_plexapi_stream_info(plex_item, part_id) # get normalized metadata # fixme: duplicated logic of media_to_videos if item_type == "episode": show = list(Plex["library"].metadata(plex_item.show.rating_key))[0] year = show.year tvdb_id = None series_tvdb_id = None original_title = show.title_original if tvdb_guid_identifier in plex_item.guid: tvdb_id = plex_item.guid[len(tvdb_guid_identifier):].split("?")[0] series_tvdb_id = tvdb_id.split("/")[0] metadata = get_metadata_dict( plex_item, current_part, dict( stream_info, **{ "plex_part": current_part, "type": "episode", "title": plex_item.title, "series": plex_item.show.title, "id": plex_item.rating_key, "series_id": plex_item.show.rating_key, "season_id": plex_item.season.rating_key, "imdb_id": None, "year": year, "tvdb_id": tvdb_id, "super_thumb": plex_item.show.thumb, "series_tvdb_id": series_tvdb_id, "original_title": original_title, "season": plex_item.season.index, "episode": plex_item.index })) else: imdb_id = None original_title = plex_item.title_original if imdb_guid_identifier in plex_item.guid: imdb_id = plex_item.guid[len(imdb_guid_identifier):].split("?")[0] metadata = get_metadata_dict( plex_item, current_part, dict( stream_info, **{ "plex_part": current_part, "type": "movie", "title": plex_item.title, "id": plex_item.rating_key, "series_id": None, "season_id": None, "imdb_id": imdb_id, "year": plex_item.year, "tvdb_id": None, "super_thumb": plex_item.thumb, "series_tvdb_id": None, "original_title": original_title, "season": None, "episode": None, "section": plex_item.section.title })) return metadata
# f = open('runes', 'w') # for n, recipe in enumerate(recipes): # if recipe["jobId"] not in remove_jobs: # if recipe["jobId"] not in allowed: # print items.get_job(recipe["jobId"]), recipe["jobId"] # item = items.get_item(recipe["resultId"]) # item.runes = brisage_objet(item) # write_item(f, item, recipe) # if n % 1000 == 0: # print n f = open('runes', 'w') for n, recipe in enumerate(recipes.all_recipes): if recipe.job not in remove_jobs: if recipe.job not in allowed: print items.get_job(recipe.job), recipe.job item = items.get_item(recipe.result) item.runes = brisage_objet(item) write_item(f, item, recipe) if n % 1000 == 0: print n f.close() else: allowed = [11,13,14,15,16,17,18,19,20,27,31] # remove_jobs = [0,1,2,24,25,26,28,36,41,56,58,60,65] for n, recipe in enumerate(recipes.all_recipes): if recipe.job in allowed: item = items.get_item(recipe.result) item.runes = brisage_objet(item) item.recipe = recipe if recipe.job not in all_items:
def media_to_videos(media, kind="series"): """ iterates through media and returns the associated parts (videos) :param media: :param kind: :return: """ videos = [] # this is a Show or a Movie object plex_item = get_item(media.id) year = plex_item.year original_title = plex_item.title_original if kind == "series": for season in media.seasons: season_object = media.seasons[season] for episode in media.seasons[season].episodes: ep = media.seasons[season].episodes[episode] tvdb_id = None series_tvdb_id = None if tvdb_guid_identifier in ep.guid: tvdb_id = ep.guid[len(tvdb_guid_identifier):].split("?")[0] series_tvdb_id = tvdb_id.split("/")[0] # get plex item via API for additional metadata plex_episode = get_item(ep.id) stream_info = get_plexapi_stream_info(plex_episode) for item in media.seasons[season].episodes[episode].items: for part in item.parts: videos.append( get_metadata_dict(plex_episode, part, dict(stream_info, **{"plex_part": part, "type": "episode", "title": ep.title, "series": media.title, "id": ep.id, "year": year, "series_id": media.id, "super_thumb": plex_item.thumb, "season_id": season_object.id, "imdb_id": None, "series_tvdb_id": series_tvdb_id, "tvdb_id": tvdb_id, "original_title": original_title, "episode": plex_episode.index, "season": plex_episode.season.index, "section": plex_episode.section.title }) ) ) else: stream_info = get_plexapi_stream_info(plex_item) imdb_id = None if imdb_guid_identifier in media.guid: imdb_id = media.guid[len(imdb_guid_identifier):].split("?")[0] for item in media.items: for part in item.parts: videos.append( get_metadata_dict(plex_item, part, dict(stream_info, **{"plex_part": part, "type": "movie", "title": media.title, "id": media.id, "super_thumb": plex_item.thumb, "series_id": None, "year": year, "season_id": None, "imdb_id": imdb_id, "original_title": original_title, "series_tvdb_id": None, "tvdb_id": None, "section": plex_item.section.title}) ) ) return videos
def get_plex_metadata(rating_key, part_id, item_type, plex_item=None): """ uses the Plex 3rd party API accessor to get metadata information :param rating_key: movie or episode :param part_id: :param item_type: :return: """ if not plex_item: plex_item = get_item(rating_key) if not plex_item: return # find current part current_part = get_part(plex_item, part_id) if not current_part: raise helpers.PartUnknownException("Part unknown") stream_info = get_plexapi_stream_info(plex_item, part_id) # get normalized metadata # fixme: duplicated logic of media_to_videos if item_type == "episode": show = list(Plex["library"].metadata(plex_item.show.rating_key))[0] year = show.year tvdb_id = None series_tvdb_id = None original_title = show.title_original if tvdb_guid_identifier in plex_item.guid: tvdb_id = plex_item.guid[len(tvdb_guid_identifier):].split("?")[0] series_tvdb_id = tvdb_id.split("/")[0] metadata = get_metadata_dict(plex_item, current_part, dict(stream_info, **{"plex_part": current_part, "type": "episode", "title": plex_item.title, "series": plex_item.show.title, "id": plex_item.rating_key, "series_id": plex_item.show.rating_key, "season_id": plex_item.season.rating_key, "imdb_id": None, "year": year, "tvdb_id": tvdb_id, "super_thumb": plex_item.show.thumb, "series_tvdb_id": series_tvdb_id, "original_title": original_title, "season": plex_item.season.index, "episode": plex_item.index }) ) else: imdb_id = None original_title = plex_item.title_original if imdb_guid_identifier in plex_item.guid: imdb_id = plex_item.guid[len(imdb_guid_identifier):].split("?")[0] metadata = get_metadata_dict(plex_item, current_part, dict(stream_info, **{"plex_part": current_part, "type": "movie", "title": plex_item.title, "id": plex_item.rating_key, "series_id": None, "season_id": None, "imdb_id": imdb_id, "year": plex_item.year, "tvdb_id": None, "super_thumb": plex_item.thumb, "series_tvdb_id": None, "original_title": original_title, "season": None, "episode": None, "section": plex_item.section.title}) ) return metadata
def do_GET(self): address = dottedQuadToNum(self.client_address[0]) ens = networkMask("138.231.0.0",16) #if not addressInNetwork(address,ens): # self.send_response(403) # self.end_headers() # return params = parse_qs(urlparse(self.path).query) if self.path.endswith('.js') or self.path.endswith('.css'): try: filename = os.path.dirname(os.path.realpath(__file__)) + os.sep + "res" + urllib2.url2pathname(self.path) f = open(filename, 'rb') #open requested file #send code 200 response self.send_response(200) #send header first if self.path.endswith('.js'): self.send_header('Content-type','text/javascript') elif self.path.endswith('.css'): self.send_header('Content-type','text/css') self.end_headers() #send file content to client self.wfile.write(f.read()) f.close() except IOError: self.send_error(404, 'File Not Found') elif self.path.startswith("/jobs"): if "job_id" in params: if hasattr(self, "invalidate") and self.invalidate: for job in brisage.all_items: brisage.all_items[job].sort(key = lambda item: item.recipe.get_fabrication_price() - item.recipe.get_runes_result_price()) self.invalidate = False self.begin(u"runes") self.item_list(int(params["job_id"][0])) self.end() else: self.begin(u"zendikar") self.display_metiers() self.end() elif self.path.startswith("/prices"): id = None price = None if "id" in params: id = int(params[u"id"][0]) if "prix" in params: price = int(params[u"prix"][0]) if id is not None and price is not None: prix.set_price(get_item(id).get_name(), price) self.invalidate = True self.send_response(304) self.end_headers() else: if "l" in params: lettre = params[u"l"][0].decode("utf8") if lettre not in lettres: lettre = u'A' else: lettre = u'A' self.begin(u"prix") self.display_prices_list(lettre) self.end() elif self.path.startswith("/search"): flags = self.get_search_params(params) self.begin(u"search") self.display_metiers() self.afficher_search_menu(flags) self.display_prices_search(flags) self.end() else: self.begin(u"zendikar") self.display_metiers() self.end()
def media_to_videos(media, kind="series"): """ iterates through media and returns the associated parts (videos) :param media: :param kind: :return: """ videos = [] # this is a Show or a Movie object plex_item = get_item(media.id) year = plex_item.year original_title = plex_item.title_original if kind == "series": for season in media.seasons: season_object = media.seasons[season] for episode in media.seasons[season].episodes: ep = media.seasons[season].episodes[episode] tvdb_id = None series_tvdb_id = None if tvdb_guid_identifier in ep.guid: tvdb_id = ep.guid[len(tvdb_guid_identifier):].split("?")[0] series_tvdb_id = tvdb_id.split("/")[0] # get plex item via API for additional metadata plex_episode = get_item(ep.id) stream_info = get_plexapi_stream_info(plex_episode) for item in media.seasons[season].episodes[episode].items: for part in item.parts: videos.append( get_metadata_dict( plex_episode, part, dict( stream_info, **{ "plex_part": part, "type": "episode", "title": ep.title, "series": media.title, "id": ep.id, "year": year, "series_id": media.id, "super_thumb": plex_item.thumb, "season_id": season_object.id, "imdb_id": None, "series_tvdb_id": series_tvdb_id, "tvdb_id": tvdb_id, "original_title": original_title, "episode": plex_episode.index, "season": plex_episode.season.index, "section": plex_episode.section.title }))) else: stream_info = get_plexapi_stream_info(plex_item) imdb_id = None if imdb_guid_identifier in media.guid: imdb_id = media.guid[len(imdb_guid_identifier):].split("?")[0] for item in media.items: for part in item.parts: videos.append( get_metadata_dict( plex_item, part, dict( stream_info, **{ "plex_part": part, "type": "movie", "title": media.title, "id": media.id, "super_thumb": plex_item.thumb, "series_id": None, "year": year, "season_id": None, "imdb_id": imdb_id, "original_title": original_title, "series_tvdb_id": None, "tvdb_id": None, "section": plex_item.section.title }))) return videos
def randomize(self): if self.type == 'clearing': for n in range(0,random.randint(0,1)): _i = item.get_item('foliage') _i.loc = self.loc self.add_object(_i) elif self.type == 'house': _d = item.get_item_name('iron dagger') _d.room_loc = [1,2] self.add_object(_d) _d = item.get_item_name('health potion') _d.room_loc = [1,3] self.add_object(_d) #Decorate~~!! #Windows - Corner check. _windows = 0 while _windows < self.house['windows']: for wall in self.walls: if _windows >= self.house['windows']: break if random.randint(1,8) <= 1: _h = 0 _v = 0 for pos in [[-1,0],[1,0]]: if [wall[0]+pos[0],wall[1]+pos[1]] in self.walls: _h += 1 for pos in [[0,-1],[0,1]]: if [wall[0]+pos[0],wall[1]+pos[1]] in self.walls: _v += 1 if _h == 2 and not _v or _v == 2 and not _h: self.map[wall[0]][wall[1]] = 'grass' _i = item.get_item('window') _i.room_loc = [wall[0],wall[1]] self.add_object(_i) _windows += 1 _doors = 0 while _doors < self.house['doors']: for wall in self.walls: if _doors >= self.house['doors']: break if random.randint(1,8) <= 1: _h = 0 _v = 0 for pos in [[-1,0],[1,0]]: if [wall[0]+pos[0],wall[1]+pos[1]] in self.walls: _h += 1 for pos in [[0,-1],[0,1]]: if [wall[0]+pos[0],wall[1]+pos[1]] in self.walls: _v += 1 if _h == 2 and not _v or _v == 2 and not _h: self.map[wall[0]][wall[1]] = 'clear' _doors += 1 _t = item.get_item_name('table') _rpos = self.walkingspace[random.randint(0,len(self.walkingspace)-1)] _t.room_loc=[_rpos[0],_rpos[1]] _t.blocking = True self.add_object(_t) for _pos in [[-1,0],[0,-1],[1,0],[0,1]]: if [_rpos[0]+_pos[0],_rpos[1]+_pos[1]] in self.walkingspace: _i = item.get_item_name('chair') _i.room_loc = [_rpos[0]+_pos[0],_rpos[1]+_pos[1]] self.add_object(_i) elif self.type == 'forest': _ws = [] for w in range(self.green/10): _w = ai.RandomWalker(self.loc) _w.walk() _ws.append(_w) for w in _ws: for _pos in w.path: if _pos[0]>0 and _pos[0]<var.world_size[0]-2 and _pos[1]>0 and _pos[1]<var.world_size[1]-2 and not var._c.map[_pos[0]][_pos[1]]: r = room(_pos,var._c) r.type = 'forest' r.flags['sunlit'] = True r.green = self.green - 10 r.randomize() var._c.map[_pos[0]][_pos[1]] = r elif self.type == 'lake': _ws = [] for w in range(self.green/10): _w = ai.RandomWalker(self.loc,bold=True) _w.walk() _ws.append(_w) for w in _ws: for _pos in w.path: if _pos[0]>0 and _pos[0]<var.world_size[0]-2 and _pos[1]>0 and _pos[1]<var.world_size[1]-2 and not var._c.map[_pos[0]][_pos[1]]: r = room(_pos,var._c) r.type = 'lake' r.flags['sunlit'] = True r.green = self.green - 10 r.randomize() var._c.map[_pos[0]][_pos[1]] = r elif self.type == 'river': _ws = [] for w in range(self.green/10): if self.walk_dir == 'south': _xchange = 5 _ychange = 0 elif self.walk_dir == 'east': _xchange = 0 _ychange = 15 _w = ai.DirectionalWalker(self.loc,self.walk_dir,xchange=_xchange,ychange=_ychange) _w.walk() _ws.append(_w) for w in _ws: for _pos in w.path: if _pos[0]>0 and _pos[0]<var.world_size[0]-2 and _pos[1]>0 and _pos[1]<var.world_size[1]-2 and (not var._c.map[_pos[0]][_pos[1]] or var._c.map[_pos[0]][_pos[1]].type == 'forest'): r = room(_pos,var._c) r.type = 'river' r.flags['sunlit'] = True r.green = self.green - 10 r.walk_dir = self.walk_dir r.randomize() var._c.map[_pos[0]][_pos[1]] = r