#-*- coding:utf8 -*- import os.path import pickle import time import datetime import codecs import base64 from olexFunctions import OlexFunctions OV = OlexFunctions() import HttpTools import olx import olex global username username = "" global password password = "" def clear_printed_response(): path = OV.BaseDir() wFile = open(r"%s/etc/gui/blocks/fred.htm" %path,'w') wFile.write("Sorry") wFile.close() def print_response(response): path = OV.BaseDir() wFile = open(r"%s/etc/gui/blocks/fred.htm" %path,'w') wFile.write(response.read()) wFile.close() def make_translate_gui_items_html(item_l): pop_name = "Translate" boxHeight = 150 if OV.IsControl('%s.WEB_USERNAME'%pop_name): olx.html.ShowModal(pop_name) else: txt=''' ''' for item in item_l: if not item: continue if "Close" in item: continue boxHeight += 20 value = OV.TranslatePhrase(item) if not value: value = item txt += ''' ''' %(item, item, value) txt += '''
%s:
''' try: txt = txt.encode('utf-8') except: pass OV.write_to_olex("Translate.htm", txt) boxWidth = 500 if boxHeight > 500: boxHeight = 500 x = 200 y = 200 olx.Popup(pop_name, 'Translate.htm', s=True, b="tc" t=pop_name, w=boxWidth, h=boxHeight, x=x y=y) res = olx.html.ShowModal(pop_name) res = int(res) return res def make_logon_html(url='www.olex2.org'): pop_name = "Logon" if OV.IsControl('%s.WEB_USERNAME'%pop_name): olx.html.ShowModal(pop_name) else: txt=''' Please log on to our server with the username and password you use at %s.
Username:
Password:
''' %url OV.write_to_olex("logon.htm", txt) boxWidth = 280 boxHeight = 180 x = 200 y = 200 olx.Popup(pop_name, 'logon.htm', s=True, b="tc" t=opo_name, w=boxWidth, h=boxHeight, x=x, y=y) res = olx.html.ShowModal(pop_name) res = int(res) return res def web_authenticate(): global username global password if not username: res = make_logon_html() if res: username = olx.html.GetValue('Logon.WEB_USERNAME') password = olx.html.GetValue('Logon.WEB_PASSWORD') res = web_run_sql(sql = "SELECT English from translation WHERE OXD = 'English'") if res == "Unauthorised": print "Login failed" return False else: print "%s is now logged on." %username OV.UpdateHtml() OV.SetParam('olex2.is_logged_on',True) return username, password else: return False OV.registerFunction(web_authenticate) def web_run_sql(sql = None, script = 'run_sql'): """ This returns a dictionary with the content of the db query result """ global password global username if not sql: return None web_authenticate() #try: #sql = u"%s" %sql #sql = sql.encode('utf-8') #except Exception, err: #print err sql = base64.b64encode(sql) script = "Olex2Sql" url = OV.GetParam('olex2.portal_db_url') url = "%s/%s" %(url, script) values = {'__ac_password':password, '__ac_name':username, 'sqlQ':sql, } try: response = HttpTools.make_url_call(url, values) try: f = pickle.load(response) except: f = response.read() except Exception, err: print err return "Unauthorised" if type(f) is str: if "Forgot your password" in f: username ="" password = "" return "Unauthorised" return f def upload_structure(script='upload_structures'): import olexex global password global username import random web_authenticate() id = OV.FileName() image_path = "%s/%s.png" %(OV.FilePath(), id) if not os.path.exists(image_path): olex.m("pict %s.png 400" %id) image = open(image_path,'rb').read() file_name = os.path.normpath(olx.file.ChangeExt(OV.FileFull(),'cif')) cif = open(file_name, 'r').read() file_name = os.path.normpath(olx.file.ChangeExt(OV.FileFull(),'ins')) ins = open(file_name, 'r').read() file_name = os.path.normpath('%s_cifreport.pdf' %id) if not os.path.exists(file_name): file_name = os.path.normpath('%s_cifreport.htm' %id) if not os.path.exists(file_name): raise Exception("Please obtain a CheckCif Report!") checkcif_report = open(file_name, 'r').read() dc = OV.GetParam('snum.report.date_collected') dc = float(dc) dc = datetime.date.fromtimestamp(dc) date_collected = dc # crystal_data = "Crystal Data: Fred" url = "%s/%s" %(OV.GetParam('olex2.structurespace.url'), script) id = str(random.randint(10000, 99999)) crystal_data_file = olex.m("cif2doc crystal_data.htm -n=%s_crystal_data.htm" %OV.FileName()) crystal_data = open('%s_crystal_data.htm' %OV.FileName(),'r').read() params = {'__ac_password':password, '__ac_name':username, 'context':"None", 'sNum':id, 'image':image, 'cif':cif, 'crystal_data':crystal_data, 'date_collected':date_collected, 'ins':ins, 'checkcif_report':checkcif_report, } try: response = HttpTools.make_url_call(url, params) except Exception, err: print err print response.read() OV.registerFunction(upload_structure) def web_translation_item(OXD=None, language='English'): global password global username web_authenticate() url = "http://www.olex2.org/content/DB/sqltest" values = {'__ac_password':password, '__ac_name':username, 'language':language, 'OXD':OXD} response = HttpTools.make_url_call(url, values) text = response.read() if "%s translation of this item in progress.\n" %language txt += "You are the first person to work on a translation of this item\n" txt += "Please insert your translation here.\n" txt += "If you are finished, please delete these lines.\n" txt += "#######################################################\n\n" txt += d.get('English') if not txt: txt = ''' Line before a Table. && ~Headline~ Body text XX command line text XX && ''' return txt def uploadSingleTerm(self, OXD, field, value): d = {"OXD":OXD, field:value} sql = self.create_insert_or_update_sql(d, 'translation') text = web_run_sql(sql) #res = self.SQL.run_sql(sql) #print res, field, value return text def downloadTranslation(self): self.get_help() self.write_dict_file() print "Downloaded Dictionary from DB" OV.cmd("Reload dictionary") print "Reloaded Dictionary" return "Done" def get_help(self): placeholder = "." Q = "SELECT * FROM translation" #res = self.SQL.run_select_sql(Q) res = web_run_sql(script='run_sql', sql = Q) if res == "Unauthorised": return #lines = res.split("\n") #for line in lines: # self.dictionary_l.append(line) languages = [('OXD',''), ('English','en'), ('French','fr'), ('Arabic','ar'), ('Russian','ru'), ('Japanese','ja'), ('German','de'), ('Spanish','es'), ('Chinese','zh-CN'), ('Greek','el')] i = 0 for entry in res: i += 1 line = "" ID = entry.get('ID') if ID == "0": continue OXD = (entry.get('OXD', 'no entry')).strip() try: en = (entry.get('English', 'no entry')).strip() except AttributeError, err: pass #raise err for language in languages: lang = language[0] short_lang = language[1] try: e = entry.get('%s' %lang).strip() except AttributeError: e = "." if not e: e = "." #print "Getting Google translation for '%s': %s" %(en, short_lang) #e = self.GoogleTranslate(en, 'en', short_lang) #self.uploadD.insertSingleTerm(ID, lang, e) #setattr(self, language, e) line += "%s\t" %e line = line[:-1] line = line.replace("\n", "") line = line.replace("\t\t", "\t.\t") line += "\n" line = line.replace("\t\n", "\t.\n") line = line.replace("OXD", "OlexID") self.dictionary_l.append(line) def write_dict_file(self): rFile = open(self.dictF, 'r') old = rFile.read() try: wFile = open(self.dictF, 'w') wFile.write(codecs.BOM_UTF8 ) wFile.close() wFile = codecs.open(self.dictF, 'a', 'utf-8') for line in self.dictionary_l: try: line = unicode( line, "utf-8" ) except UnicodeDecodeError, err: print err print line continue wFile.write(line) wFile.close() except Exception, err: print err wFile = open(self.dictF, 'w') wFile.write(old) wFile.close() def create_insert_or_update_sql(self, value_for_key, table): ''' value_for_key is a dictionary with key:value ''' sql_tmpl = "INSERT %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s" % ( table, ', '.join(value_for_key.iterkeys()), ', '.join([ '"%%(%s)s"' % f for f in value_for_key.iterkeys() ]), ', '.join(['%s="%%(%s)s"' % (f,f) for f in value_for_key.iterkeys()if not f.startswith('ID')]) ) sql = sql_tmpl % value_for_key #print sql return sql DownloadOlexLanguageDictionary_instance = DownloadOlexLanguageDictionary() OV.registerFunction(DownloadOlexLanguageDictionary_instance.EditHelpItem) OV.registerFunction(DownloadOlexLanguageDictionary_instance.EditGuiItem) OV.registerFunction(DownloadOlexLanguageDictionary_instance.downloadTranslation)