Example #1
0
 def translate_view(self, cr, node, state, lang):
     if node.get('string'):
         trans = translate(cr, self.wiz_name+','+state, 'wizard_view', lang, node.get('string').encode('utf8'))
         if trans:
             node.set('string', trans)
     for n in node:
         self.translate_view(cr, n, state, lang)
Example #2
0
            def tr(src, ttype):
                # We try to do the same as the _(), but without the frame
                # inspection, since we aready are wrapping an osv function
                # trans_obj = self.get('ir.translation') cannot work yet :(
                ctx = {}
                if not kwargs:
                    if args and isinstance(args[-1], dict):
                        ctx = args[-1]
                elif isinstance(kwargs, dict):
                    ctx = kwargs.get('context', {})

                uid = 1
                if args and isinstance(args[0], (long, int)):
                    uid = args[0]

                lang = ctx and ctx.get('lang')
                if not (lang or hasattr(src, '__call__')):
                    return src

                # We open a *new* cursor here, one reason is that failed SQL
                # queries (as in IntegrityError) will invalidate the current one.
                cr = False

                if hasattr(src, '__call__'):
                    # callable. We need to find the right parameters to call
                    # the  orm._sql_message(self, cr, uid, ids, context) function,
                    # or we skip..
                    # our signature is f(osv_pool, dbname [,uid, obj, method, args])
                    try:
                        if args and len(args) > 1:
                            obj = self.get(args[1])
                            if len(args) > 3 and isinstance(
                                    args[3], (long, int, list)):
                                ids = args[3]
                            else:
                                ids = []
                        cr = pooler.get_db_only(dbname).cursor()
                        return src(obj, cr, uid, ids, context=(ctx or {}))
                    except Exception:
                        pass
                    finally:
                        if cr: cr.close()

                    return False  # so that the original SQL error will
                    # be returned, it is the best we have.

                try:
                    cr = pooler.get_db_only(dbname).cursor()
                    res = translate(cr,
                                    name=False,
                                    source_type=ttype,
                                    lang=lang,
                                    source=src)
                    if res:
                        return res
                    else:
                        return src
                finally:
                    if cr: cr.close()
Example #3
0
 def translate_view(self, cr, node, state, lang):
     if node.get('string'):
         trans = translate(cr, self.wiz_name + ',' + state, 'wizard_view',
                           lang,
                           node.get('string').encode('utf8'))
         if trans:
             node.set('string', trans)
     for n in node:
         self.translate_view(cr, n, state, lang)
            def tr(src, ttype):
                # We try to do the same as the _(), but without the frame
                # inspection, since we aready are wrapping an osv function
                # trans_obj = self.get('ir.translation') cannot work yet :(
                ctx = {}
                if not kwargs:
                    if args and isinstance(args[-1], dict):
                        ctx = args[-1]
                elif isinstance(kwargs, dict):
                    ctx = kwargs.get('context', {})

                uid = 1
                if args and isinstance(args[0], (long, int)):
                    uid = args[0]

                lang = ctx and ctx.get('lang')
                if not (lang or hasattr(src, '__call__')):
                    return src

                # We open a *new* cursor here, one reason is that failed SQL
                # queries (as in IntegrityError) will invalidate the current one.
                cr = False
                
                if hasattr(src, '__call__'):
                    # callable. We need to find the right parameters to call
                    # the  orm._sql_message(self, cr, uid, ids, context) function,
                    # or we skip..
                    # our signature is f(osv_pool, dbname [,uid, obj, method, args])
                    try:
                        if args and len(args) > 1:
                            obj = self.get(args[1])
                            if len(args) > 3 and isinstance(args[3], (long, int, list)):
                                ids = args[3]
                            else:
                                ids = []
                        cr = pooler.get_db_only(dbname).cursor()
                        return src(obj, cr, uid, ids, context=(ctx or {}))
                    except Exception:
                        pass
                    finally:
                        if cr: cr.close()
                   
                    return False # so that the original SQL error will
                                 # be returned, it is the best we have.

                try:
                    cr = pooler.get_db_only(dbname).cursor()
                    res = translate(cr, name=False, source_type=ttype,
                                    lang=lang, source=src)
                    if res:
                        return res
                    else:
                        return src
                finally:
                    if cr: cr.close()
Example #5
0
    def execute_cr(self, cr, uid, data, state='init', context=None):
        if not context:
            context={}
        res = {}
        try:
            state_def = self.states[state]

            result_def = state_def.get('result', {})
            
            actions_res = {}
            # iterate through the list of actions defined for this state
            for action in state_def.get('actions', []):
                # execute them
                action_res = action(self, cr, uid, data, context)
                assert isinstance(action_res, dict), 'The return value of wizard actions should be a dictionary'
                actions_res.update(action_res)
                
            res = copy.copy(result_def)
            res['datas'] = actions_res
            
            lang = context.get('lang', False)
            if result_def['type'] == 'action':
                res['action'] = result_def['action'](self, cr, uid, data, context)
            elif result_def['type'] == 'form':
                fields = copy.deepcopy(result_def['fields'])
                arch = copy.copy(result_def['arch'])
                button_list = copy.copy(result_def['state'])

                if isinstance(fields, UpdateableDict):
                    fields = fields.dict
                if isinstance(arch, UpdateableStr):
                    arch = arch.string

                # fetch user-set defaut values for the field... shouldn't we pass it the uid?
                defaults = ir.ir_get(cr, uid, 'default', False, [('wizard.'+self.wiz_name, False)])
                default_values = dict([(x[1], x[2]) for x in defaults])
                for val in fields.keys():
                    if 'default' in fields[val]:
                        # execute default method for this field
                        if callable(fields[val]['default']):
                            fields[val]['value'] = fields[val]['default'](uid, data, state)
                        else:
                            fields[val]['value'] = fields[val]['default']
                        del fields[val]['default']
                    else:
                        # if user has set a default value for the field, use it
                        if val in default_values:
                            fields[val]['value'] = default_values[val]
                    if 'selection' in fields[val]:
                        if not isinstance(fields[val]['selection'], (tuple, list)):
                            fields[val] = copy.copy(fields[val])
                            fields[val]['selection'] = fields[val]['selection'](self, cr, uid, context)
                        elif lang:
                            res_name = "%s,%s,%s" % (self.wiz_name, state, val)
                            trans = lambda x: translate(cr, res_name, 'selection', lang, x) or x
                            for idx, (key, val2) in enumerate(fields[val]['selection']):
                                fields[val]['selection'][idx] = (key, trans(val2))

                if lang:
                    # translate fields
                    for field in fields:
                        res_name = "%s,%s,%s" % (self.wiz_name, state, field)

                        trans = translate(cr, res_name, 'wizard_field', lang)
                        if trans:
                            fields[field]['string'] = trans

                        if 'help' in fields[field]:
                            t = translate(cr, res_name, 'help', lang, fields[field]['help']) 
                            if t:
                                fields[field]['help'] = t

                    # translate arch
                    if not isinstance(arch, UpdateableStr):
                        doc = etree.XML(arch)
                        self.translate_view(cr, doc, state, lang)
                        arch = etree.tostring(doc)

                    # translate buttons
                    button_list = list(button_list)
                    for i, aa  in enumerate(button_list):
                        button_name = aa[0]
                        trans = translate(cr, self.wiz_name+','+state+','+button_name, 'wizard_button', lang)
                        if trans:
                            aa = list(aa)
                            aa[1] = trans
                            button_list[i] = aa
                    
                res['fields'] = fields
                res['arch'] = arch
                res['state'] = button_list

            elif result_def['type'] == 'choice':
                next_state = result_def['next_state'](self, cr, uid, data, context)
                return self.execute_cr(cr, uid, data, next_state, context)
        
        except Exception, e:
            if isinstance(e, except_wizard) \
                or isinstance(e, except_osv) \
                or isinstance(e, except_orm):
                self.abortResponse(2, e.name, 'warning', e.value)
            else:
                import traceback
                tb_s = reduce(lambda x, y: x+y, traceback.format_exception(
                    sys.exc_type, sys.exc_value, sys.exc_traceback))
                logger = Logger()
                logger.notifyChannel("web-services", LOG_ERROR,
                        'Exception in call: ' + tb_s)
                raise
Example #6
0
 def translate_view(source):
     """Return a translation of type view of source."""
     return translate(
         cr, None, 'view', context.get('lang'), source
     ) or source
Example #7
0
def main():
    global LAST_UPDATE_ID
    
    HAIL_SATAN = 0
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # Telegram Bot Authorization Token
    bot = telegram.Bot(config.get('telegram', 'token'))

    # This will be our global variable to keep the latest update_id when requesting
    # for updates. It starts with the latest update_id if available.
    try:
        LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
    except IndexError as TypeError:
        LAST_UPDATE_ID = None

    while True:
        for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=20):
            try:
                if update.message:
                    if update.message.text:

                        def post(msg):
                            """Posts a message to Telegram."""
                            bot.sendChatAction(
                                update.message.chat_id,
                                action=telegram.ChatAction.TYPING)
                            bot.sendMessage(update.message.chat_id, msg)

                        def post_random(odds, text):
                            """Has a one in x chance of posting a message to telegram."""
                            if random.randint(1, odds) == odds:
                                post(text)

                        text = update.message.text.encode("utf-8")
                        first_name = update.message.from_user.first_name.encode(
                            "utf-8")

                        # logging for quotable data
                        if update.message.chat.title.encode(
                                "utf-8") == "May Be A Little Late" and text[0] != '/':
                            with open("data/mball.txt", "a") as quote_file:
                                quote_file.write("%s: %s\n" % (first_name, text))
                            quote_file.close()
                        else:
                            with open("data/cmds.txt", "a") as quote_file:
                                quote_file.write("%s: %s\n" % (first_name, text))
                            quote_file.close()

                        if text.startswith("/"):
                            text = text.replace("@originalstatic_bot", "")

                            if text == "/help":
                                post("type '/' into chat, or press the '[/]' button to view all available commands")

                            elif text.lower().startswith("/char"):
                                char_args = text.title().split()
                                if len(char_args) == 4:
                                    post(
                                        ffxiv_char(
                                            char_args[1],
                                            char_args[2],
                                            char_args[3]))
                                else:
                                    post(
                                        "needs 3 arguments. usage: /char [first name] [last name] [server]")

                            elif text.lower() == "/quote" or text.lower() == "/quote ":
                                quote_file = open("data/mball.txt").read().splitlines()
                                post(random.choice(quote_file))
                                
                            elif text.lower().startswith("/quote") and len(text) > 7:
                                names = static_config.get('static', 'names').splitlines()
                                # Pull aliases for names from static_config.ini
                                name_elem = next(name for name in names if text[7:].lower() + ',' in name.lower())
                                name = name_elem[:name_elem.index(':')+1]

                                quote_file = open("data/mball.txt").read().splitlines()
                                random.shuffle(quote_file)
                                post(next(line for line in quote_file if line.startswith(name)))

                            elif text.lower().startswith("/calc"):
                                post(calculate(text, first_name))

                            elif text.lower().startswith("/tweet"):
                                if len(text) < 7:
                                    post("usage: /tweet (some garbage)")
                                elif len(text) >= 140:
                                    post("maybe make your tweet just a teensy bit shorter?")
                                else:
                                    post_tweet(text[7:])
                                    post(random.choice([
                                        "tweet posted. fuccckkkk", "tweet posted. this is a terrible, terrible idea",
                                        "tweet posted. why though? why?", "garbage posted.", "tweet posted.",
                                        "tweet posted. it's a shitty tweet and this is coming from a toilet"
                                    ]) + " (http://twitter.com/raidbot)")

                            elif text.lower().startswith("/youtube") or text.lower().startswith("/yt"):
                                post(youtube(text))

                            elif text.lower() == "/vgm":
                                post(vgm())

                            elif text.lower() == "/alias":
                                post(static_config.get('static', 'alias'))

                            elif text.lower() == "/raid":
                                post(static_config.get('static', 'raid'))

                            elif text.lower().startswith("/weather"):
                                post(get_weather(text))

                            elif text.lower().startswith("/translate"):
                                post(translate(text))

                            elif text.lower() == "/news":
                                results = latest_tweets("ff_xiv_en")
                                if isinstance(results, str):
                                     post(results)
                                else:
                                    for tweet in results:
                                        post("https://twitter.com/ff_xiv_en/status/%s" % (tweet.id_str))

                            elif text.lower() == "/status":
                                post(status("excalibur"))

                            elif text.lower() == "/timers":
                                post(timers())

                            elif text == "/flush":
                                post("aaaah. why thank you, %s. ;)" % (first_name.lower()))

                            elif text.lower() == "/goons":
                                post(random_tweet("Goons_TXT"))
                            elif text.lower() == "/yahoo":
                                post(random_tweet("YahooAnswersTXT"))
                            elif text.lower() == "/meirl":
                                post(random_tweet("itmeirl"))
                            elif text.lower() == "/wikihow":
                                post(random_tweet("WikiHowTXT"))
                            elif text.lower() == "/tumblr":
                                post(random_tweet("TumblrTXT"))
                            elif text.lower() == "/fanfiction":
                                post(random_tweet("fanfiction_txt"))
                            elif text.lower() == "/reddit":
                                post(random_tweet("Reddit_txt"))
                            elif text.lower() == "/catgirl":
                                post(random_tweet("catgirls_bot"))
                            elif text.lower() == "/catboy":
                                post(random_tweet("catboys_bot"))
                            elif text.lower() == "/catperson":
                                post(random_tweet(random.choice(
                                    ["catboys_bot", "catgirls_bot"])))
                            elif text.lower() == "/ff14":
                                account = [
                                    "ff14forums_txt",
                                    "FFXIV_Memes",
                                    "FFXIV_Names",
                                    "FFXIV_PTFinders"]
                                post(random_tweet(random.choice(account)))
                            elif text.lower() == "/oocanime":
                                post(random_tweet("oocanime"))
                            elif text.lower() == "/damothafuckinsharez0ne":
                                post(random_tweet("dasharez0ne"))
                            elif text.lower() == "/dog" or text.lower() == "/doggo":
                                post(random_tweet("dog_rates"))
                            elif text.lower() == "/twitter":
                                account = [
                                    "ff14forums_txt", "FFXIV_Memes", "FFXIV_Names",
                                    "Goons_TXT", "YahooAnswersTXT", "TumblrTXT",
                                    "Reddit_txt", "fanfiction_txt", "WikiHowTXT",
                                    "itmeirl", "oocanime", "damothafuckinsharez0ne",
                                    "dog_rates", "FFXIV_PTFinders"]
                                post(random_tweet(random.choice(account)))

                            elif text.lower() == "/rt":
                                post(retweet())

                            elif text.lower().startswith("/wiki"):
                                post(wiki(text))

                            elif text.lower() == "/heart":
                                post("<3<3<3 hi %s <3<3<3" % (first_name.lower()))
                                
                            elif text.lower() == "/ping" or text.lower() == "ping":
                                post("pong")
                                
                            elif text.lower() == "/bing" or text.lower() == "bing":
                                post("bong")

                            elif text.lower() == "/quoth the raven":
                                post("nevermore")

                            elif text.lower() == "/sleep":
                                post("brb 5 mins")
                                time.sleep(300)
                                
                            elif text.lower() == "/brum":
                                post(random.choice(["https://s-media-cache-ak0.pinimg.com/736x/0c/c1/9a/0cc19aa7d2184fbeb5f4ff57442f7846.jpg",
                                                "http://i3.birminghammail.co.uk/incoming/article4289373.ece/ALTERNATES/s615/Brum1.jpg",
                                                "https://i.ytimg.com/vi/pmBX3461TdU/hqdefault.jpg",
                                                "https://i.ytimg.com/vi/bvnhLdFqo1k/hqdefault.jpg",
                                                "https://abitofculturedotnet.files.wordpress.com/2014/10/img_1133.jpg"]))
                                
                            elif text.lower().startswith("/sleep ") and len(text[7:]) >= 1:
                                try:
                                    sleep_timer = int(text[7:])

                                    if sleep_timer > 300:
                                        post("i can only go to sleep for up to 5 minutes.")
                                    else:
                                        post("brb")
                                        time.sleep(sleep_timer)
                                except ValueError as e:
                                    post("that's not a number, %s." % first_name.lower())

                            else:
                                post(
                                    "that's not a command i recognise, but we can't all be perfect i guess")

                        elif (text.lower().startswith("hey ") or text.lower() == "hey"
                                or text.lower().startswith("hi ") or text.lower() == "hi"
                                or text.lower().startswith("sup ") or text.lower().startswith("hello")
                                or text.lower().startswith("good morning")):
                            post(random.choice(["hi", "hi!", "hey", "yo", "eyyyy", "*flush*", "sup",
                                                "hey %s... *flush* ;)" % (
                                                    first_name.lower()),
                                                "hello %s! *FLUSH*" % (
                                                    first_name.lower()),
                                                "hello %s" % (first_name.lower())]))

                        elif "robot" in text.lower():
                            post_random(2, "robutt")

                        elif "same" == text.lower():
                            post_random(4, "same")

                        elif text.lower().startswith("i "):
                            post_random(20, "same")

                        elif "rip" == text.lower() or "RIP" in text or text.lower().startswith("rip"):
                            post("ded") if random.randint(1, 2) == 1 else post("yeah, rip.")

                        elif "lol" in text.lower():
                            post_random(10, "lol")

                        elif "lmao" in text.lower():
                            post_random(5, "lmbo")

                        elif "f**k" in text.lower() or "shit" in text.lower() or "piss" in text.lower():
                            post_random(20, random.choice(
                                ["RUDE", "rude", "... rude", "rude... but i'll allow it.", ":O"]))

                        elif "hail satan" in text.lower() or "hail santa" in text.lower() or "hail stan" in text.lower():
                            HAIL_SATAN = 3
                            post("hail satan")

                        elif (text.lower() == "thanks" or text.lower() == "ty" or text.lower() == "thank you"):
                            post_random(2, random.choice(
                                ["np", "anytime", "my... *flush* pleasure.", "no problem, now sit on my face"]))

                        elif "k" == text.lower() or "ok" == text.lower():
                            post(random.choice(["... k", "k"]))
                            
                        elif "nice" == text.lower() or "noice" == text.lower():
                            post_random(4, "noice")
                            
                        elif "69" in text.lower() or "420" in text.lower():
                            post("nice")

                        elif "raidbot" in text.lower():
                            post_random(6, random.choice(["WHAT?? i wasn't sleeping i swear",
                                                          "i can hear you fine, %s. you don't need to shout" % (
                                                              first_name.lower()),
                                                          "please redirect all your questions and comments to yoship. thank you",
                                                          "careful now",
                                                          "my /timeplayed is a time so long it cannot be comprehended by a mortal mind",
                                                          "look i'm trying to be a toilet here, stop bothering me",
                                                          "beep boop. *FLUSH*",
                                                          "yoship pls nerf my toilet handle",
                                                          "/unsubscribe",
                                                          "plumber job when?????",
                                                          "switch on that toaster and throw it in me",
                                                          "...",
                                                          "what, you want me to say something witty?"
                                                          "/flush"]))

                        elif "yoship" in text.lower():
                            post_random(2, random.choice(["yoship pls nerf this static group (down my toilet bowl)",
                                                          "spoilers: i'm yoship",
                                                          "yoship is MY waifu and nobody will ever take my darling away from me~",
                                                          "i can't wait for yoship to introduce stat boosting microtransactions",
                                                          "1.0 was better it had more polygons",
                                                          "lvl 60 toilet lfg exdr",
                                                          "they nerfed the catgirl butts i want all my sub money back",
                                                          "imo the relic quests aren't long enough",
                                                          "plumber job when?????",
                                                          "i know a place you can put your live letter"]))

                        elif "civ" in text.lower():
                            post_random(2, "my flushes are backed by NUCLEAR WEAPONS!!!")
                                                          
                        elif random.randint(1, 500) == 1:
                            post("%s: i am a brony, and %s" % (first_name.lower(), text.lower()))
                        
                        if HAIL_SATAN == 3:
                            HAIL_SATAN = 2
                        elif HAIL_SATAN == 2:
                            post("HAIL SATAN")
                            HAIL_SATAN = 1
                        elif HAIL_SATAN == 1:
                            post("hail satan.")
                            HAIL_SATAN = 0

            except Exception as e:
                with open("data/debug.txt", "a") as err_file:
                    err_file.write(
                        "%s - Error %s\n%s\nJSON: \n%s\n" %
                        (str(datetime.now()), str(e), traceback.format_exc(), str(update)))
                err_file.close()
            finally:
                # Updates global offset to get the new updates
                LAST_UPDATE_ID = update.update_id + 1
Example #8
0
 def translate_view(source):
     """Return a translation of type view of source."""
     return translate(cr, None, 'view', context.get('lang'),
                      source) or source
 def get_ddl_module(self,cr,uid,context=None):
     """
     Web Service que sirve para enviar la definición de datos (DDL) en formato JSON, esto sirve para crear una geodatabase a partir de los datos
     y luego realizar una exportación masiva de los mismos
     
     Estructura de los datos en JSON que se va a retornar:
     {
         objeto o feature class:{campo1:{nombre:"nombre(español)", nom_pres:"Nombre de Presentación del Objeto",tipo_dato:"Tipo Dato",}, campo2:{}.....
     }
     ejemplo:
     {
         puente:{id:{"nombre":"id","nom_pres":identificador,"tipo_dato":"integer"},
                 width:{"nombre":"ancho","nom_pres":"Ancho","tipo_dato":"float"}
         ...
         }
         riostra:{id:{"nombre":"id","nom_pres":identificador,"tipo_dato":"integer"},
         }
     }
     
     """
     res={}
     #1. Se envian la lista de los campos que estan involucrados en el objeto puentes
     puente={}
     fields = self.fields_get(cr,uid,context)
     for field in fields:
         campo = translate(cr,"addons/urban_bridge/urban_bridge.py","code","es_CO",field)
         nombre_presentacion = translate(cr,"urban_bridge.bridge,"+field,"field","es_CO",fields[field]["string"])
         if (nombre_presentacion==False):
             nombre_presentacion = fields[field]["string"]
         tipo_dato = fields[field]["type"]
         if (campo == False):
             raise Exception("Campo :'"+field+"' no se encuentra definido en fichero de traduccion es_CO.po, verifique que se encuentre el campo en el fichero\
             y actualice el módulo")
         if (tipo_dato=="selection"):
             puente[field] = {'nom_pres':nombre_presentacion,"tipo_dato":tipo_dato,"nombre":campo,"selection":str(fields[field]["selection"])}
         #Convertir los elementos many 2 one en un dominio tipo selection
         elif (tipo_dato == "many2one"):
             objeto_rel = self.pool.get(fields[field]["relation"])
             try:
                 objetos_rel_ids = objeto_rel.search(cr,uid,[('id','>','0')])
                 campos_seleccion = []
                 for code_value_obj in objeto_rel.browse(cr,uid,objetos_rel_ids):
                     campos_seleccion.append((str(code_value_obj.code),str(code_value_obj.name)))
                 puente[field] = {'nom_pres':nombre_presentacion,"tipo_dato":"selection","nombre":campo,"selection":str(campos_seleccion)}
             except Exception as e:
                 print str(e)
         else:
             puente[field] = {'nom_pres':nombre_presentacion,"tipo_dato":tipo_dato,"nombre":campo}
     res["puente"] = puente
     #2, Definición de datos de cada uno de los elementos de infraestructura
     #2.1 Campos comunes que se encuentran definidos de manera general en el elemento de infraestructura
     struct_elem = self.pool.get('urban_bridge.structure_element')
     elem_fields = struct_elem.fields_get(cr,uid,context)
     common_fields={}
     for elem_field in elem_fields:
         campo = translate(cr,"addons/urban_bridge/urban_bridge.py","code","es_CO",elem_field)
         #Nombre con el cual se ve el campo en la pantalla
         nombre_presentacion = translate(cr,"urban_bridge.structure_element,"+elem_field,"field","es_CO",elem_fields[elem_field]["string"])
         if (nombre_presentacion==False):
             nombre_presentacion = elem_fields[elem_field]["string"]
         
         if (campo == False):
             raise Exception("Campo :'"+elem_field+"' no se encuentra definido en fichero de traduccion es_CO.po, verifique que se encuentre el campo en el fichero\
             y actualice el módulo")
         
         tipo_dato = elem_fields[elem_field]["type"]
         if (tipo_dato=="selection"):
             common_fields[elem_field] = {'nom_pres':nombre_presentacion,"tipo_dato":tipo_dato,"nombre":campo,"selection":str(fields[field]["selection"])}
         elif (tipo_dato=="many2one"):
             common_fields[elem_field] = {'nom_pres':nombre_presentacion,"tipo_dato":"integer","nombre":campo}
         else:
             common_fields[elem_field] = {'nom_pres':nombre_presentacion,"tipo_dato":tipo_dato,"nombre":campo}
     #2.2 Campos definidos de manera particular para cada campo
     struct_elem_type_obj = self.pool.get('urban_bridge.structure_element_type')
     struct_elem_type_ids = struct_elem_type_obj.search(cr,uid,[('id','>','0')])
         #Estructura de datos para los elementos de infraestructura que se definen dinamicamente
     for struct_elem_type in struct_elem_type_obj.browse(cr,uid,struct_elem_type_ids):
         objeto = struct_elem_type.alias
         objeto_dict = {}
         for comfield in common_fields:
             objeto_dict[comfield]=common_fields[comfield]
         for attribute in struct_elem_type.attributes:
             if (attribute.data_type=="selection"):
                 objeto_dict[attribute.alias]={"nombre":str(attribute.alias),'nom_pres':str(attribute.name),"tipo_dato":str(attribute.data_type), "selection":str(attribute.selection_text)}
             else:
                 objeto_dict[attribute.alias]={"nombre":str(attribute.alias),'nom_pres':str(attribute.name),"tipo_dato":str(attribute.data_type)}
         #Agregar campo al diccionario
         res[objeto]=objeto_dict
     return res
    def get_data_module(self,cr,uid,bridge_id = None, context=None):
        """
        Web Service que devuelve todos los datos de los puentes junto con los elementos de infraestructura
        Modo de trabajo:
        
        Consulta cada puente y llena un diccionario con cada uno de los elementos de acuerdo a los nombres 
        que se implementaron en el método anterior
        ejemplo:
        {
        puente:[{id:1,galibo:2,ancho:2.5 .....},],
        riostra:[{id:5,id_puente:1,ancho:2.5 .....},{id:7,id_puente_1,ancho:2.8... (depende de los datos de la base de datos)
        }
        """
        res = {}
        if (bridge_id == None):
            return res
        bridge_obj = self.pool.get('urban_bridge.bridge')
        bridge_dict = bridge_obj.read(cr,uid,bridge_id)
        spatial_reference = self.pool.get('ir.config_parameter').get_param(cr, uid, 'urban_bridge.local_spatial_reference', default='', context=context)
        #bridge_fields = bridge_obj.fields_get (cr,uid,context)
        puente = {}
        #1. Mandar el diccionario de valores para el objeto puente con los campos traducidos al español        
        for attribute in bridge_dict:
            att_name = translate(cr,"addons/urban_bridge/urban_bridge.py","code","es_CO",attribute)
            if (att_name == False):
                att_name=attribute
            att_value = bridge_dict[attribute]
            #Si es una geometría entonces se debe hacer la transformación de coordenadas.
            if (attribute == "shape"):
                query = """
                select st_asgeojson(st_transform(shape,%s),15,0) 
                from urban_bridge_bridge where id = %s
                """
                cr.execute(query,(spatial_reference,bridge_dict["id"]))
                for row in cr.fetchall():
                    att_value=row[0]
            if (type(att_value) is tuple):
                puente[att_name] = att_value[0]
            elif (type(att_value) is list):
                
                pass
#             elif (type(att_value) is dict):
#                 if att_value.has_key("coordinates"):
#                     
            else:
                puente[att_name] = att_value
        res["puente"]=[puente]
        #2. Mandar un diccionario por cada objeto de infraestructura
        structure_element_obj = self.pool.get("urban_bridge.structure_element")
        bridge = bridge_obj.browse(cr,uid,bridge_id)
        for element in bridge.elements:
            element_dict = {}
            #2.1 Primero los atributos generales correspondientes al elemento de infraestructura. 
            elem_type = element.element_type_id.alias
            #Inicializa diccionario para tipo de elemento
            if not (res.has_key(elem_type)):
                res[elem_type]=[]
            elem_base = structure_element_obj.read(cr,uid,element.id)
            for elem_base_att in elem_base:
                base_att = translate(cr,"addons/urban_bridge/urban_bridge.py","code","es_CO",elem_base_att)
                if (base_att == False):
                    base_att = elem_base_att
                att_value = elem_base[elem_base_att]
                if (type(att_value) is tuple):
                    element_dict[base_att]=att_value[0]
                elif (type(att_value) is list):
                    pass
                else:
                    element_dict[base_att]=att_value
                #element_dict[base_att]=elem_base[elem_base_att]
            for values in element.values:
                attribute = values.element_attribute_id.alias
                data_type = values.element_attribute_id.data_type
                value=None
                if (data_type=="integer"):
                    value = values.value_integer
                elif (data_type=="text"):
                    value = values.value_text
                elif (data_type=="datetime"):
                    value = values.value_datetime
                elif (data_type== "date"):
                    value = values.value_datetime
                elif (data_type == "float"):
                    value = values.value_float
                elif (data_type=="boolean"):
                    value = values.value_bool
                elif (data_type == "char"):
                    value = values.value_char
                elif (data_type == "selection"):
                    value = values.value_selection
                elif (data_type == "binary"):
                    value = values.value_photo
                #En los tipos de datos geométricos se devuelve la geometría de acuerdo con 
                #con el sistema de referencia establecido en los parametros de configuracion
                elif (data_type == "geo_point"):
                    query = """
                    select st_asgeojson(st_transform(value_point,%s),15,0) 
                    from urban_bridge_structure_element_value where id = %s;
                    """
                    cr.execute(query,(spatial_reference,value.id))
                    for row in cr.fetchall():
                        value = eval(row[0])
                    value = values.value_point
                elif (data_type == "geo_polygon"):
                    query = """
                    select st_asgeojson(st_transform(value_polygon,%s),15,0) 
                    from urban_bridge_structure_element_value where id = %s;
                    """
                    cr.execute(query,(spatial_reference,values.id))
                    for row in cr.fetchall():
                        value = eval(row[0])
                elif (data_type == "geo_line"):
                    query = """
                    select st_asgeojson(st_transform(value_line,%s),15,0) 
                    from urban_bridge_structure_element_value where id = %s;
                    """
                    cr.execute(query,(spatial_reference,values.id))
                    for row in cr.fetchall():
                        value = eval(row[0])
                element_dict[attribute]=value
            res[elem_type].append(element_dict)
        return res
Example #11
0
def main():
    global LAST_UPDATE_ID
    global TRY_AGAIN_MARKOV

    # Telegram Bot Authorization Token
    bot = telegram.Bot(config.get('telegram', 'token'))

    # This will be our global variable to keep the latest update_id when requesting
    # for updates. It starts with the latest update_id if available.
    try:
        LAST_UPDATE_ID = bot.get_updates()[-1].update_id
    except IndexError:
        LAST_UPDATE_ID = None

    TRY_AGAIN_MARKOV = False

    while True:
        for update in bot.get_updates(offset=LAST_UPDATE_ID, timeout=60):
            try:
                if update.message:
                    if update.message.text:

                        def post(msg):
                            """Posts a message to Telegram."""
                            bot.send_chat_action(
                                update.message.chat_id,
                                action=telegram.ChatAction.TYPING)
                            bot.send_message(update.message.chat_id, msg)

                        def post_random(odds, msg):
                            """Has a one in x chance of posting a message to telegram."""
                            if random.randint(1, odds) == odds:
                                post(msg)

                        def append_to_file(filename, msg):
                            """Logs a line of text to a given file"""
                            with open("data/{}".format(filename),
                                      "a") as log_file:
                                log_file.write(msg)
                            log_file.close()

                        text = update.message.text.encode("utf-8")
                        first_name = update.message.from_user.first_name.encode(
                            "utf-8")

                        # logging for quotable data
                        if "group" in update.message.chat.type:
                            if update.message.chat.title.encode(
                                    "utf-8"
                            ) == "May Be A Little Late" and text[0] != '/':
                                append_to_file(
                                    "mball.txt",
                                    "{}: {}\n".format(first_name, text))

                        if text.startswith("/"):
                            text = text.replace("@originalstatic_bot", "")

                            if text.lower() == "/dev":
                                dev_url = "http://xivdb.com/assets/devtracker.json"
                                dev_response = http.request('GET', dev_url)
                                dev_json = json.loads(
                                    dev_response.read().decode())
                                print(str(dev_json))
                                try:
                                    for x in range(0, 5):
                                        username = dev_json[x]['thread'][
                                            'user']['username']
                                        dev_title = dev_json[x]['thread'][
                                            'user']['title']
                                        post_url = dev_json[x]['thread']['url']
                                        post_title = dev_json[x]['thread'][
                                            'title']

                                        post("{} ({}) posted:\n{}\n{}".format(
                                            username, dev_title, post_title,
                                            post_url))

                                except Exception as e:
                                    print(e)

                            if text.lower().startswith(
                                    "/lore") and len(text) > 6:
                                lore_search = text[6:].title()
                                post('placeholder lol')

                            if text.lower().startswith(
                                    "/map") and len(text) > 5:
                                map_search = text[5:].title()
                                try:
                                    map_found = False
                                    maps_url = 'https://api.xivdb.com/maps'
                                    maps_response = http.request(
                                        'GET', maps_url)
                                    maps_json = json.loads(
                                        maps_response.read().decode())

                                    for x in range(len(maps_json)):
                                        for y in range(
                                                len(maps_json[x]
                                                    ['placenames'])):
                                            if map_search == maps_json[x][
                                                    'placenames'][y]['name']:
                                                map_url_list = [
                                                    map_urls for map_urls in
                                                    maps_json[x]['placenames']
                                                    [y]['layers']
                                                ]
                                                map_found = True

                                    if not map_found:
                                        for x in range(len(maps_json)):
                                            for y in range(
                                                    len(maps_json[x]
                                                        ['placenames'])):
                                                map_name = maps_json[x][
                                                    'placenames'][y]['name']
                                                if map_search in map_name:
                                                    map_url_list = [
                                                        map_urls for map_urls
                                                        in maps_json[x]
                                                        ['placenames'][y]
                                                        ['layers']
                                                    ]
                                                    found_map_name = maps_json[
                                                        x]['placenames'][y][
                                                            'name']
                                                    map_found = True

                                except Exception as e:
                                    print(e)

                                if not map_found:
                                    post("couldn't find that map")
                                else:
                                    for map_url in map_url_list:
                                        post("https://api.xivdb.com{0}".format(
                                            map_url))
                                    post("found {0} in a fuzzy search".format(
                                        found_map_name))

                            if text.lower().startswith("/char"):

                                if len(text.title().split()) == 4:
                                    char_args = text.title()
                                    first = char_args.split(' ')[1]
                                    last = char_args.split(' ')[2]
                                    server = char_args.split(' ')[3]
                                    bot.send_chat_action(
                                        update.message.chat_id,
                                        action=telegram.ChatAction.TYPING)
                                    post(ffxiv_char(first, last, server))

                                elif len(text.title().split()) == 1:
                                    try:
                                        bot.send_chat_action(
                                            update.message.chat_id,
                                            action=telegram.ChatAction.TYPING)

                                        char_details = static_config.get(
                                            'static', first_name).split(' ')
                                        first = char_details[0]
                                        last = char_details[1]
                                        server = char_details[2]
                                        post(ffxiv_char(first, last, server))

                                    except Exception as e:
                                        append_to_file(
                                            "debug.txt",
                                            "{} - Error {}\n{}\n{}\n\n\n".
                                            format(str(datetime.now()), str(e),
                                                   traceback.format_exc(),
                                                   str(update)))
                                        post(
                                            "i don't know your character name. "
                                            +
                                            "tell erika or use /char [first name] [last name] [server]"
                                        )
                                else:
                                    post(
                                        "usage: /char; /char [first name] [last name] [server]"
                                    )

                            elif text.lower().startswith("/achievements"):
                                if len(text.title().split()) == 5:
                                    char_args = text.title()
                                    first = char_args.split(' ')[1]
                                    last = char_args.split(' ')[2]
                                    server = char_args.split(' ')[3]
                                    count = char_args.split(' ')[4]
                                    bot.send_chat_action(
                                        update.message.chat_id,
                                        action=telegram.ChatAction.TYPING)
                                    post(
                                        ffxiv_achievements(
                                            first, last, server, count))
                                elif len(text.title().split()) == 2:
                                    try:
                                        bot.send_chat_action(
                                            update.message.chat_id,
                                            action=telegram.ChatAction.TYPING)

                                        char_details = static_config.get(
                                            'static', first_name).split(' ')
                                        first = char_details[0]
                                        last = char_details[1]
                                        server = char_details[2]
                                        count = text.split(' ')[1]

                                        if int(count) > 40 or int(count) < 1:
                                            post("really " + first_name +
                                                 "? i mean... really?")
                                        else:
                                            post(
                                                ffxiv_achievements(
                                                    first, last, server,
                                                    count))
                                    except ValueError:
                                        post(
                                            "you failed at writing a regular number, well done"
                                        )
                                else:
                                    post(
                                        "usage: /achievements [#]; /achievements [firstname] [lastname] [server] [#]"
                                    )

                            elif text.lower().startswith(
                                    "/item ") and len(text) > 6:
                                bot.send_chat_action(
                                    update.message.chat_id,
                                    action=telegram.ChatAction.TYPING)
                                item = ffxiv_item(text[6:])
                                if str(type(item)) == "<type 'str'>":
                                    post(item)
                                else:
                                    post(item[0])
                                    if item[1] != "":
                                        post(item[1])

                            elif text.lower() == "/quote":
                                quote_file = open(
                                    "data/mball.txt").read().splitlines()
                                post(random.choice(quote_file))

                            elif text.lower().startswith(
                                    "/quote") and len(text) > 7:
                                names = static_config.get(
                                    'static', 'names').splitlines()

                                # Pull aliases for names from static_config.ini
                                name_elem = next(name for name in names
                                                 if text[7:].lower() +
                                                 ',' in name.lower())
                                name = name_elem[:name_elem.index(':') + 1]

                                quote_file = open(
                                    "data/mball.txt").read().splitlines()
                                random.shuffle(quote_file)
                                post(
                                    next(line for line in quote_file
                                         if line.startswith(name)))

                            elif text.lower().startswith("/calc"):
                                post(calculate(text, first_name))

                            elif text.lower().startswith("/tweet"):
                                if len(text) < 7:
                                    post("usage: /tweet (some garbage)")
                                elif len(text) >= 140:
                                    post(
                                        "maybe make your tweet just a teensy bit shorter?"
                                    )
                                else:
                                    post_tweet(text[7:])
                                    post(
                                        random.choice([
                                            "tweet posted. fuccckkkk",
                                            "tweet posted. this is a terrible, terrible idea",
                                            "tweet posted. why though? why?",
                                            "garbage posted.", "tweet posted.",
                                            "tweet posted. it's a shitty tweet and this is coming from a toilet"
                                        ]) + " (http://twitter.com/raidbot)")

                            elif text.lower() == "/vgm":
                                post(vgm())

                            elif text.lower().startswith("/guide"):
                                if len(text) > 7:
                                    result = guide(text[7:])
                                    if result:
                                        post(guide(text[7:]))
                                    else:
                                        post("what")
                                else:
                                    post(
                                        "usage: /guide a8 savage; /guide antitower, etc."
                                    )

                            elif text.lower().startswith("/addtwitter"):
                                # /addtwitter bird_twitter bird
                                add_twitter_cmd = text.lower().split()
                                if len(add_twitter_cmd) == 3:
                                    append_to_file(
                                        "twitters.txt", '/{},{}\n'.format(
                                            str(add_twitter_cmd[1]),
                                            str(add_twitter_cmd[2])))

                                    post("done.")
                                else:
                                    post(
                                        "usage: /addtwitter [desired command] [twitter username]"
                                    )

                            elif text.lower().startswith("/deletetwitter"):
                                del_twitter_cmd = text.lower().split()
                                full_list = []
                                found = False

                                if len(del_twitter_cmd) == 2:
                                    cmd = del_twitter_cmd[1]

                                    with open("data/twitters.txt",
                                              "r") as twitter_file:
                                        i = 0
                                        j = 0
                                        for line in twitter_file:
                                            if line.startswith(cmd) or line[
                                                    1:].startswith(cmd):
                                                j = i
                                                found = True
                                            full_list.append(line[:-1] + "\n")
                                            i += 1
                                    twitter_file.close()

                                    if found:
                                        full_list.remove(full_list[j])

                                        with open("data/twitters.txt",
                                                  "w") as twitter_file:
                                            for line in full_list:
                                                twitter_file.write(str(line))
                                        twitter_file.close()
                                        post("done.")
                                    else:
                                        post(
                                            "ummm, that account's not in the list."
                                        )
                                else:
                                    post("usage: /deletetwitter [command]")

                            elif text.lower() == "/usertwitters":
                                twitter_list = "list of saved twitters:\n"
                                with open("data/twitters.txt",
                                          "r") as twitter_file:
                                    for line in twitter_file:
                                        twitter_list += "- {}, @{}\n".format(
                                            line.split(',')[0],
                                            line.split(',')[1][:-1])
                                twitter_file.close()
                                post(twitter_list)

                            elif text.lower() == "/alias":
                                post(static_config.get('static', 'alias'))

                            elif text.lower() == "/raid":
                                post(static_config.get('static', 'raid'))

                            elif text.lower().startswith("/weather"):
                                weather, latitude, longitude = get_weather(
                                    text)
                                bot.send_location(update.message.chat_id,
                                                  latitude, longitude)
                                post(weather)

                            elif text.lower().startswith("/place"):
                                if len(text) <= 7:
                                    post("usage: /place [place name]")
                                else:
                                    place = text.title()[7:]
                                    geolocator = Nominatim()
                                    location = geolocator.geocode(place)
                                    if location:
                                        bot.send_venue(
                                            update.message.chat_id,
                                            title=place,
                                            address=location.address,
                                            latitude=location.latitude,
                                            longitude=location.longitude)
                                    else:
                                        post("couldn't find that place")

                            elif text.lower().startswith("/translate"):
                                post(translate(text))

                            elif text.lower() == "/news":
                                results = latest_tweets("ff_xiv_en")
                                if isinstance(results, str):
                                    post(results)
                                else:
                                    for tweet in results:
                                        post(
                                            "https://twitter.com/ff_xiv_en/status/{}"
                                            .format(tweet.id_str))

                            elif text.lower().startswith("/status"):
                                statuses = arrstatus()

                                if len(text) <= 8:
                                    status_text = "{} status: {}\n".format(
                                        "Excalibur",
                                        str(statuses["Excalibur"]))
                                    status_text += "{} status: {}".format(
                                        "Omega", str(statuses["Omega"]))
                                    status_text += "{} status: {}".format(
                                        "Shiva", str(statuses["Shiva"]))
                                    '''if all(value == "Online" for value in statuses.values()):
                                        status_text = "\nAll servers online"
                                    elif all(value != "Online" for value in statuses.values()):
                                        status_text = "\nall servers down. *flush*"'''
                                else:
                                    server = text.title()[8:]
                                    if server in statuses.keys():
                                        status_text = "{} status: {}".format(
                                            server, str(statuses[server]))
                                    else:
                                        status_text = "that's not a server."

                                post(status_text)

                            elif text.lower() == "/timers":
                                post(timers())

                            elif text == "/flush":
                                post("aaaah. why thank you, {}. ;)".format(
                                    first_name.lower()))

                            elif text.lower() == "/catperson":
                                post(
                                    random_tweet(
                                        random.choice(
                                            ["catboys_bot", "catgirls_bot"])))
                            elif text.lower() == "/ff14":
                                account = [
                                    "ff14forums_txt", "FFXIV_Memes",
                                    "FFXIV_Names", "FFXIV_PTFinders"
                                ]
                                post(random_tweet(random.choice(account)))
                            elif text.lower() == "/twitter":
                                account = [
                                    "ff14forums_txt", "FFXIV_Memes",
                                    "FFXIV_Names", "Goons_TXT",
                                    "YahooAnswersTXT", "TumblrTXT",
                                    "Reddit_txt", "fanfiction_txt",
                                    "WikiHowTXT", "itmeirl", "oocanime",
                                    "damothafuckinsharez0ne", "dog_rates",
                                    "FFXIV_PTFinders"
                                ]
                                post(random_tweet(random.choice(account)))

                            elif text.lower() == "/rt":
                                post(retweet())

                            elif text.lower() == "/heart":
                                post("<3<3<3 hi {} <3<3<3".format(
                                    first_name.lower()))

                            elif text.lower() == "/quoth the raven":
                                post(
                                    "http://data0.eklablog.com/live-your-life-in-books/mod_article46415481_4fb61cb0e0c79.jpg?3835"
                                )

                            elif text.lower() == "/brum":
                                post(
                                    random.choice([
                                        "https://s-media-cache-ak0.pinimg.com/736x/0c/c1/9a/0cc19aa7d2184fbeb5f4ff57442f7846.jpg",
                                        "http://i3.birminghammail.co.uk/incoming/article4289373.ece/ALTERNATES/s615/Brum1.jpg",
                                        "https://i.ytimg.com/vi/pmBX3461TdU/hqdefault.jpg",
                                        "https://i.ytimg.com/vi/bvnhLdFqo1k/hqdefault.jpg",
                                        "https://abitofculturedotnet.files.wordpress.com/2014/10/img_1133.jpg"
                                    ]))

                            else:
                                with open("data/twitters.txt",
                                          "r") as twitter_file:
                                    for line in twitter_file:
                                        cmd = line.split(',')[0]
                                        if text.lower() == cmd:
                                            post(
                                                random_tweet(
                                                    line.split(',')[1][:-1]))
                                twitter_file.close()

                        elif text.lower() == "hey":
                            post(
                                random.choice([
                                    "hi", "hi!", "hey", "yo", "eyyyy",
                                    "*flush*", "sup",
                                    "hey {}... *flush* ;)".format(
                                        first_name.lower()),
                                    "hello {}! *FLUSH*".format(
                                        first_name.lower()),
                                    "hello {}".format(first_name.lower())
                                ]))

                        elif "same" == text.lower():
                            post_random(100, "same")

                        elif text.lower().startswith("i "):
                            post_random(100, "same")

                        elif "rip" == text.lower(
                        ) or "RIP" in text or text.lower().startswith("rip"):
                            roll = random.randint(1, 100)
                            if roll == 1:
                                post("ded")
                            elif roll == 2:
                                post("yeah, rip.")
                            elif roll == 3:
                                post("rip")

                        elif text.lower() == "ping":
                            post("pong")

                        elif text.lower() == "bing":
                            post("bong")

                        elif "lol" in text.lower():
                            post_random(100, "lol")

                        elif "hail satan" in text.lower(
                        ) or "hail santa" in text.lower(
                        ) or "hail stan" in text.lower():
                            post("hail satan")

                        elif ("69" in text.lower() or "420" in text.lower()
                              ) and not text.lower().startswith("http"):
                            post_random(4, "nice")

                        elif "raidbot" in text.lower():
                            post_random(
                                100,
                                random.choice([
                                    "WHAT?? i wasn't sleeping i swear",
                                    "i can hear you fine, {}. you don't need to shout"
                                    .format(first_name.lower()),
                                    "please redirect all your questions and comments to yoship. thank you",
                                    "careful now",
                                    "my /timeplayed is a time so long it cannot be comprehended by a mortal mind",
                                    "look i'm trying to be a toilet here, stop bothering me",
                                    "beep boop. *FLUSH*",
                                    "yoship pls nerf my toilet handle",
                                    "/unsubscribe", "plumber job when?????",
                                    "switch on that toaster and throw it in me",
                                    "...", "go flush yourself",
                                    "what, you want me to say something witty?",
                                    "toilet ex farm no bonus 2 mistakes = kick",
                                    "/flush"
                                ]))

                        elif "yoship" in text.lower():
                            post_random(
                                2,
                                random.choice([
                                    "yoship pls nerf this static group (down my toilet bowl)",
                                    "i can't wait for yoship to introduce stat boosting microtransactions",
                                    "1.0 was better it had more polygons",
                                    "lvl 60 TLT lfg exdr",
                                    "they nerfed the catgirl butts i want all my sub money back",
                                    "plumber job when?????",
                                    "i know a place you can put your live letter"
                                ]))

                        elif random.randint(1, 50) == 1 or TRY_AGAIN_MARKOV:
                            if " " in text:
                                line = text.lower().strip()
                                phrase = line.split(
                                    ' ')[-2] + " " + line.split(' ')[-1]
                                result = markov(phrase)[:-1]

                                if result[:-1].lower() == phrase.lower(
                                ) or result == "" or len(result.split()) < 3:
                                    TRY_AGAIN_MARKOV = True
                                else:
                                    TRY_AGAIN_MARKOV = False
                                    post(result)
                                    update_markov_source()

                                    if len(result) > 277:
                                        result = result[:277]
                                        result = result[:result.rfind(' ')]

                                        post_tweet(result + "...")
                                    else:
                                        post_tweet(result)
                            else:
                                TRY_AGAIN_MARKOV = True

                        # elif random.randint(1, 1000) == 1: your wildest dreams

            except Exception as e:
                append_to_file(
                    "debug.txt", "{} - Error {}\n{}\n{}\n\n\n".format(
                        str(datetime.now()), str(e), traceback.format_exc(),
                        str(update)))
            finally:
                # Updates global offset to get the new updates
                LAST_UPDATE_ID = update.update_id + 1
    def get_ddl_module(self, cr, uid, context=None):
        """
        Web Service que sirve para enviar la definición de datos (DDL) en formato JSON, esto sirve para crear una geodatabase a partir de los datos
        y luego realizar una exportación masiva de los mismos
        
        Estructura de los datos en JSON que se va a retornar:
        {
            objeto o feature class:{campo1:{nombre:"nombre(español)", nom_pres:"Nombre de Presentación del Objeto",tipo_dato:"Tipo Dato",}, campo2:{}.....
        }
        ejemplo:
        {
            puente:{id:{"nombre":"id","nom_pres":identificador,"tipo_dato":"integer"},
                    width:{"nombre":"ancho","nom_pres":"Ancho","tipo_dato":"float"}
            ...
            }
            riostra:{id:{"nombre":"id","nom_pres":identificador,"tipo_dato":"integer"},
            }
        }
        
        """
        res = {}
        #1. Se envian la lista de los campos que estan involucrados en el objeto puentes
        puente = {}
        fields = self.fields_get(cr, uid, context)
        for field in fields:
            campo = translate(cr, "addons/urban_bridge/urban_bridge.py",
                              "code", "es_CO", field)
            nombre_presentacion = translate(cr, "urban_bridge.bridge," + field,
                                            "field", "es_CO",
                                            fields[field]["string"])
            if (nombre_presentacion == False):
                nombre_presentacion = fields[field]["string"]
            tipo_dato = fields[field]["type"]
            if (campo == False):
                raise Exception(
                    "Campo :'" + field +
                    "' no se encuentra definido en fichero de traduccion es_CO.po, verifique que se encuentre el campo en el fichero\
                y actualice el módulo")
            if (tipo_dato == "selection"):
                puente[field] = {
                    'nom_pres': nombre_presentacion,
                    "tipo_dato": tipo_dato,
                    "nombre": campo,
                    "selection": str(fields[field]["selection"])
                }
            #Convertir los elementos many 2 one en un dominio tipo selection
            elif (tipo_dato == "many2one"):
                objeto_rel = self.pool.get(fields[field]["relation"])
                try:
                    objetos_rel_ids = objeto_rel.search(
                        cr, uid, [('id', '>', '0')])
                    campos_seleccion = []
                    for code_value_obj in objeto_rel.browse(
                            cr, uid, objetos_rel_ids):
                        campos_seleccion.append((str(code_value_obj.code),
                                                 str(code_value_obj.name)))
                    puente[field] = {
                        'nom_pres': nombre_presentacion,
                        "tipo_dato": "selection",
                        "nombre": campo,
                        "selection": str(campos_seleccion)
                    }
                except Exception as e:
                    print str(e)
            else:
                puente[field] = {
                    'nom_pres': nombre_presentacion,
                    "tipo_dato": tipo_dato,
                    "nombre": campo
                }
        res["puente"] = puente
        #2, Definición de datos de cada uno de los elementos de infraestructura
        #2.1 Campos comunes que se encuentran definidos de manera general en el elemento de infraestructura
        struct_elem = self.pool.get('urban_bridge.structure_element')
        elem_fields = struct_elem.fields_get(cr, uid, context)
        common_fields = {}
        for elem_field in elem_fields:
            campo = translate(cr, "addons/urban_bridge/urban_bridge.py",
                              "code", "es_CO", elem_field)
            #Nombre con el cual se ve el campo en la pantalla
            nombre_presentacion = translate(
                cr, "urban_bridge.structure_element," + elem_field, "field",
                "es_CO", elem_fields[elem_field]["string"])
            if (nombre_presentacion == False):
                nombre_presentacion = elem_fields[elem_field]["string"]

            if (campo == False):
                raise Exception(
                    "Campo :'" + elem_field +
                    "' no se encuentra definido en fichero de traduccion es_CO.po, verifique que se encuentre el campo en el fichero\
                y actualice el módulo")

            tipo_dato = elem_fields[elem_field]["type"]
            if (tipo_dato == "selection"):
                common_fields[elem_field] = {
                    'nom_pres': nombre_presentacion,
                    "tipo_dato": tipo_dato,
                    "nombre": campo,
                    "selection": str(fields[field]["selection"])
                }
            elif (tipo_dato == "many2one"):
                common_fields[elem_field] = {
                    'nom_pres': nombre_presentacion,
                    "tipo_dato": "integer",
                    "nombre": campo
                }
            else:
                common_fields[elem_field] = {
                    'nom_pres': nombre_presentacion,
                    "tipo_dato": tipo_dato,
                    "nombre": campo
                }
        #2.2 Campos definidos de manera particular para cada campo
        struct_elem_type_obj = self.pool.get(
            'urban_bridge.structure_element_type')
        struct_elem_type_ids = struct_elem_type_obj.search(
            cr, uid, [('id', '>', '0')])
        #Estructura de datos para los elementos de infraestructura que se definen dinamicamente
        for struct_elem_type in struct_elem_type_obj.browse(
                cr, uid, struct_elem_type_ids):
            objeto = struct_elem_type.alias
            objeto_dict = {}
            for comfield in common_fields:
                objeto_dict[comfield] = common_fields[comfield]
            for attribute in struct_elem_type.attributes:
                if (attribute.data_type == "selection"):
                    objeto_dict[attribute.alias] = {
                        "nombre": str(attribute.alias),
                        'nom_pres': str(attribute.name),
                        "tipo_dato": str(attribute.data_type),
                        "selection": str(attribute.selection_text)
                    }
                else:
                    objeto_dict[attribute.alias] = {
                        "nombre": str(attribute.alias),
                        'nom_pres': str(attribute.name),
                        "tipo_dato": str(attribute.data_type)
                    }
            #Agregar campo al diccionario
            res[objeto] = objeto_dict
        return res
    def get_data_module(self, cr, uid, bridge_id=None, context=None):
        """
        Web Service que devuelve todos los datos de los puentes junto con los elementos de infraestructura
        Modo de trabajo:
        
        Consulta cada puente y llena un diccionario con cada uno de los elementos de acuerdo a los nombres 
        que se implementaron en el método anterior
        ejemplo:
        {
        puente:[{id:1,galibo:2,ancho:2.5 .....},],
        riostra:[{id:5,id_puente:1,ancho:2.5 .....},{id:7,id_puente_1,ancho:2.8... (depende de los datos de la base de datos)
        }
        """
        res = {}
        if (bridge_id == None):
            return res
        bridge_obj = self.pool.get('urban_bridge.bridge')
        bridge_dict = bridge_obj.read(cr, uid, bridge_id)
        spatial_reference = self.pool.get('ir.config_parameter').get_param(
            cr,
            uid,
            'urban_bridge.local_spatial_reference',
            default='',
            context=context)
        #bridge_fields = bridge_obj.fields_get (cr,uid,context)
        puente = {}
        #1. Mandar el diccionario de valores para el objeto puente con los campos traducidos al español
        for attribute in bridge_dict:
            att_name = translate(cr, "addons/urban_bridge/urban_bridge.py",
                                 "code", "es_CO", attribute)
            if (att_name == False):
                att_name = attribute
            att_value = bridge_dict[attribute]
            #Si es una geometría entonces se debe hacer la transformación de coordenadas.
            if (attribute == "shape"):
                query = """
                select st_asgeojson(st_transform(shape,%s),15,0) 
                from urban_bridge_bridge where id = %s
                """
                cr.execute(query, (spatial_reference, bridge_dict["id"]))
                for row in cr.fetchall():
                    att_value = row[0]
            if (type(att_value) is tuple):
                puente[att_name] = att_value[0]
            elif (type(att_value) is list):

                pass
#             elif (type(att_value) is dict):
#                 if att_value.has_key("coordinates"):
#
            else:
                puente[att_name] = att_value
        res["puente"] = [puente]
        #2. Mandar un diccionario por cada objeto de infraestructura
        structure_element_obj = self.pool.get("urban_bridge.structure_element")
        bridge = bridge_obj.browse(cr, uid, bridge_id)
        for element in bridge.elements:
            element_dict = {}
            #2.1 Primero los atributos generales correspondientes al elemento de infraestructura.
            elem_type = element.element_type_id.alias
            #Inicializa diccionario para tipo de elemento
            if not (res.has_key(elem_type)):
                res[elem_type] = []
            elem_base = structure_element_obj.read(cr, uid, element.id)
            for elem_base_att in elem_base:
                base_att = translate(cr, "addons/urban_bridge/urban_bridge.py",
                                     "code", "es_CO", elem_base_att)
                if (base_att == False):
                    base_att = elem_base_att
                att_value = elem_base[elem_base_att]
                if (type(att_value) is tuple):
                    element_dict[base_att] = att_value[0]
                elif (type(att_value) is list):
                    pass
                else:
                    element_dict[base_att] = att_value
                #element_dict[base_att]=elem_base[elem_base_att]
            for values in element.values:
                attribute = values.element_attribute_id.alias
                data_type = values.element_attribute_id.data_type
                value = None
                if (data_type == "integer"):
                    value = values.value_integer
                elif (data_type == "text"):
                    value = values.value_text
                elif (data_type == "datetime"):
                    value = values.value_datetime
                elif (data_type == "date"):
                    value = values.value_datetime
                elif (data_type == "float"):
                    value = values.value_float
                elif (data_type == "boolean"):
                    value = values.value_bool
                elif (data_type == "char"):
                    value = values.value_char
                elif (data_type == "selection"):
                    value = values.value_selection
                elif (data_type == "binary"):
                    value = values.value_photo
                #En los tipos de datos geométricos se devuelve la geometría de acuerdo con
                #con el sistema de referencia establecido en los parametros de configuracion
                elif (data_type == "geo_point"):
                    query = """
                    select st_asgeojson(st_transform(value_point,%s),15,0) 
                    from urban_bridge_structure_element_value where id = %s;
                    """
                    cr.execute(query, (spatial_reference, value.id))
                    for row in cr.fetchall():
                        value = eval(row[0])
                    value = values.value_point
                elif (data_type == "geo_polygon"):
                    query = """
                    select st_asgeojson(st_transform(value_polygon,%s),15,0) 
                    from urban_bridge_structure_element_value where id = %s;
                    """
                    cr.execute(query, (spatial_reference, values.id))
                    for row in cr.fetchall():
                        value = eval(row[0])
                elif (data_type == "geo_line"):
                    query = """
                    select st_asgeojson(st_transform(value_line,%s),15,0) 
                    from urban_bridge_structure_element_value where id = %s;
                    """
                    cr.execute(query, (spatial_reference, values.id))
                    for row in cr.fetchall():
                        value = eval(row[0])
                element_dict[attribute] = value
            res[elem_type].append(element_dict)
        return res
Example #14
0
    def execute_cr(self, cr, uid, data, state='init', context=None):
        if not context:
            context = {}
        res = {}
        try:
            state_def = self.states[state]

            result_def = state_def.get('result', {})

            actions_res = {}
            # iterate through the list of actions defined for this state
            for action in state_def.get('actions', []):
                # execute them
                action_res = action(self, cr, uid, data, context)
                assert isinstance(
                    action_res, dict
                ), 'The return value of wizard actions should be a dictionary'
                actions_res.update(action_res)

            res = copy.copy(result_def)
            res['datas'] = actions_res

            lang = context.get('lang', False)
            if result_def['type'] == 'action':
                res['action'] = result_def['action'](self, cr, uid, data,
                                                     context)
            elif result_def['type'] == 'form':
                fields = copy.deepcopy(result_def['fields'])
                arch = copy.copy(result_def['arch'])
                button_list = copy.copy(result_def['state'])

                if isinstance(fields, UpdateableDict):
                    fields = fields.dict
                if isinstance(arch, UpdateableStr):
                    arch = arch.string

                # fetch user-set defaut values for the field... shouldn't we pass it the uid?
                defaults = ir.ir_get(cr, uid, 'default', False,
                                     [('wizard.' + self.wiz_name, False)])
                default_values = dict([(x[1], x[2]) for x in defaults])
                for val in fields.keys():
                    if 'default' in fields[val]:
                        # execute default method for this field
                        if callable(fields[val]['default']):
                            fields[val]['value'] = fields[val]['default'](
                                uid, data, state)
                        else:
                            fields[val]['value'] = fields[val]['default']
                        del fields[val]['default']
                    else:
                        # if user has set a default value for the field, use it
                        if val in default_values:
                            fields[val]['value'] = default_values[val]
                    if 'selection' in fields[val]:
                        if not isinstance(fields[val]['selection'],
                                          (tuple, list)):
                            fields[val] = copy.copy(fields[val])
                            fields[val]['selection'] = fields[val][
                                'selection'](self, cr, uid, context)
                        elif lang:
                            res_name = "%s,%s,%s" % (self.wiz_name, state, val)
                            trans = lambda x: translate(
                                cr, res_name, 'selection', lang, x) or x
                            for idx, (key, val2) in enumerate(
                                    fields[val]['selection']):
                                fields[val]['selection'][idx] = (key,
                                                                 trans(val2))

                if lang:
                    # translate fields
                    for field in fields:
                        res_name = "%s,%s,%s" % (self.wiz_name, state, field)

                        trans = translate(cr, res_name, 'wizard_field', lang)
                        if trans:
                            fields[field]['string'] = trans

                        if 'help' in fields[field]:
                            t = translate(cr, res_name, 'help', lang,
                                          fields[field]['help'])
                            if t:
                                fields[field]['help'] = t

                    # translate arch
                    if not isinstance(arch, UpdateableStr):
                        doc = etree.XML(arch)
                        self.translate_view(cr, doc, state, lang)
                        arch = etree.tostring(doc)

                    # translate buttons
                    button_list = list(button_list)
                    for i, aa in enumerate(button_list):
                        button_name = aa[0]
                        trans = translate(
                            cr,
                            self.wiz_name + ',' + state + ',' + button_name,
                            'wizard_button', lang)
                        if trans:
                            aa = list(aa)
                            aa[1] = trans
                            button_list[i] = aa

                res['fields'] = fields
                res['arch'] = arch
                res['state'] = button_list

            elif result_def['type'] == 'choice':
                next_state = result_def['next_state'](self, cr, uid, data,
                                                      context)
                return self.execute_cr(cr, uid, data, next_state, context)

        except Exception, e:
            if isinstance(e, except_wizard) \
                or isinstance(e, except_osv) \
                or isinstance(e, except_orm):
                self.abortResponse(2, e.name, 'warning', e.value)
            else:
                import traceback
                tb_s = reduce(
                    lambda x, y: x + y,
                    traceback.format_exception(sys.exc_type, sys.exc_value,
                                               sys.exc_traceback))
                logger = Logger()
                logger.notifyChannel("web-services", LOG_ERROR,
                                     'Exception in call: ' + tb_s)
                raise