def __init__(self): BaseExtension.__init__(self) self.utils = Utils() self.count = 0 self.tag = Tag() self.convert_url_args = '' #'?start=' #'?start=0&tag=' self.convert_page_step = 1 self.convert_page_start = 1 self.convert_page_max = 10 self.convert_page_to_end = False self.convert_tag = '' #"div#title" # tag#class or tag self.convert_min_num = 0 self.convert_max_num = 1000 self.convert_filter = "" self.convert_contain = "" self.convert_start = 0 self.convert_split_column_number = 0 self.convert_output_data_to_new_tab = False self.convert_output_data_format = '' self.convert_cut_start = '' self.convert_cut_start_offset = 0 self.convert_cut_end = '' self.convert_cut_end_offset = 0 self.convert_remove = [] self.convert_cut_max_len = 1000 self.convert_script = '' self.convert_script_custom_ui = False self.convert_smart_engine = '' self.url_prefix = ''
custom_cell_len = 0 custom_cell_row = 5 cell_len = 89 # cell_len >= course_num_len + 1 + course_name_len + 3 course_name_len = 70 course_num_len = 10 color_index = 0 output_with_color = False output_with_describe = False top_row = 0 utils = Utils() line_max_len_list = [0, 0, 0] line_id_max_len_list = [0, 0, 0] tag = Tag() keyword_list = tag.tag_list def usage(): print 'usage:' print '\t-h,--help: print help message.' print '\t-k,--keyword: print suggest keyword in file.' print '\t-i,--input: filename or dirname' print '\t-c,--column: from 1 to 3' print '\t-f,--filter: keyword for filter course' print '\t-s,--style: print text with color' print '\t-d,--describe: output the describe of the item' print '\t-w,--width: the width of cell' print '\t-r,--row: the rows of the describe' print '\t-t,--top: the top number rows for display'
class History(BaseExtension): raw_data = '' jobj_list = [] tag = Tag() """docstring for History""" def __init__(self): BaseExtension.__init__(self) self.utils = Utils() #self.loadHistory() self.form_dict = None self.divID = '' def loadHistory(self): self.updateHistory() if os.path.exists('extensions/history/data/chrome_history.json'): f = open('extensions/history/data/chrome_history.json', 'rU') self.raw_data = f.read() self.jobj_list = json.loads(self.raw_data) f.close() def updateHistory(self): if os.path.exists(Config.history_file_path): subprocess.check_output( "mv " + Config.history_file_path + " extensions/history/data/chrome_history.json", shell=True) self.loadHistory() def getAlias(self, rID, file, nocache): alias = '' use_cache = nocache == False record = self.utils.getRecord(rID.strip(), path=file, log=True, use_cache=use_cache) if record != None and record.get_id().strip() != '': ret = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag': 'alias'}) if ret != None: alias = ret.strip() #print 'alias:' + alias if alias.find(',') != -1: return record, alias.split(',') elif alias != '': return record, [alias] else: return record, [] def needBR(self): return self.form_dict['column'] != '1' and self.form_dict.has_key( 'extension_count') and int(self.form_dict['extension_count']) > 12 def getDeleteButton(self, divID, historyFile, url): deleteScript = "$.post('/exec', {command : 'deleteRow', fileName : '" + historyFile + "', key : '" + url + "'}, function(data){" + "var target=document.getElementById('" + divID.replace( '-history', '' ) + '-nav-history' + "');hidendiv_2('" + divID + "');navTopic(target,'" + divID.replace( '-history', '') + "','" + divID.replace( '-history', '') + '-nav-' + "',9);" + "});" deleteButton = ' <a target="_blank" href="javascript:void(0);" onclick="' + deleteScript + '" style="color:#999966; font-size: 10pt;"><image src="' + Config.website_icons[ 'delete'] + '" width="14" height="12"></image></a>' return deleteButton def getClickCount(self, record): if record.line.find('clickcount:') != -1: return self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, { 'tag': 'clickcount' }).strip() else: return '1' def genQuickAccessSyncButton(self, rid, quickAccessHistoryFile, divID, objID): script = "$.post('/syncQuickAccess', {rid : '" + rid + "', fileName : '" + quickAccessHistoryFile + "'},function(data) { " script += "refreshTab2('" + divID + "', '" + objID + "', 'history');" script += "});" html = '<a target="_blank" href="javascript:void(0);" onclick="' + script + '">' + self.utils.getIconHtml( '', 'sync') + '</a>' return html def getRefreshID(self, divID, text): if text == Config.history_quick_access_name: return 'td-' + divID.replace('history', 'a-qa-') else: return 'td-' + divID.replace('history', 'a-') def excute(self, form_dict): self.form_dict = form_dict if form_dict.has_key('command'): return self.excuteCommand(form_dict) else: #print '---excute---' print form_dict if form_dict.has_key('nocache'): nocache = form_dict['nocache'].encode('utf8') rTitle = form_dict['rTitle'].encode('utf8').replace('%20', ' ').strip() rID = form_dict['rID'].encode('utf8') divID = form_dict['divID'].encode('utf8') self.divID = divID objID = form_dict['objID'].encode('utf8') libraryRecord, alias = self.getAlias(rID.strip(), form_dict['fileName'], nocache) html = '' quickAccessHistoryFile = '' if self.existHistoryFile(form_dict['fileName'].strip()): historyFile = self.getHistoryFileName(form_dict['fileName']) quickAccessHistoryFile = self.utils.getQuickAccessHistoryFileName( ) print historyFile f = open(historyFile, 'r+') rDict = {} all_lines = f.readlines() if Config.history_enable_quick_access: quickAccess = self.utils.queryQuickAccess(rID) if quickAccess != None: print 'quickAccess:' + quickAccess.line all_lines.append(quickAccess.line) #print all_lines for line in all_lines: r = Record(line) if r.valid(line) == False: #print r.line continue if r.get_url().strip() != '': #key = r.get_url().strip() key = r.get_id().strip() + '-' + r.get_title().strip() if key.find(' - ') != -1: key = key[0:key.find(' - ')].strip() if rDict.has_key(key): cacheRecord = rDict[key] desc = self.getClickCount(cacheRecord) cacheLine = cacheRecord.line #desc = str(int(newLine[newLine.rfind(':')+1 :].replace('\n', '').strip())) if line.find('clickcount:') != -1: desc2 = str(int(self.getClickCount(r))) #if int(desc2) > int(desc): # desc = desc2 desc = str(int(desc2) + int(desc)) else: desc = str(int(desc) + 1) preStr = cacheLine[0:cacheLine.rfind('clickcount:' )].strip() preStr2 = r.line[0:r.line.rfind('clickcount:' )].strip() newRecord = Record(preStr2) if newRecord.get_describe().strip() != '': preStr = preStr2 #print newLine #print desc rDict[key] = Record(preStr + ' clickcount:' + desc + '\n') else: if line.find('clickcount:') != -1: rDict[key] = Record(line) else: preStr = line[0:line.rfind('clickcount:' )].strip() rDict[key] = Record(preStr + ' clickcount:1' + '\n') rList = [] #print rDict if len(rDict) != len(all_lines): f.truncate() f.close() else: f.close() f = None for k, v in rDict.items(): #print '---' + v.line #if k.lower().endswith(Config.history_quick_access_name.lower()): # print ')))))))((((' + v if v.line.strip() != '' and v.valid(v.line): if len(rDict) != len(all_lines): if f == None: #print historyFile f = open(historyFile, 'w') #print v.line if k.lower().endswith( Config.history_quick_access_name.lower() ) == False and v.get_title().lower().strip( ) != Config.history_quick_access_name.lower(): f.write(v.line) if v.get_id().strip() == form_dict['rID'].strip() or ( v.get_id().strip().startswith('loop') and v.get_id().strip().find( form_dict['rID'].strip()) != -1): rList.append(v) else: print v.line if f != None: f.close() #print rList #f = open('extensions/history/data/' + historyFilename, 'r') if len(rList) > 0: if Config.hidtory_sort_type == 0: rList = sorted( rList, key=lambda d: int(self.getClickCount(d)), reverse=False) allSubList = [] clickCount = self.getClickCount(rList[0]) subList = [] for item in rList: clickCount2 = self.getClickCount(item) if clickCount != clickCount2: clickCount = clickCount2 allSubList.append(subList) subList = [] subList.append(item) if len(subList) > 0: allSubList.append(subList) rList = [] for subList in allSubList: rList += sorted( subList, key=lambda d: d.get_url().strip()[0:20], reverse=True) elif Config.hidtory_sort_type == 1: rList = sorted(rList, key=lambda d: d.get_url().strip()[0:20], reverse=True) elif Config.hidtory_sort_type == 2: rList = sorted( rList, key=lambda d: d.get_title().strip()[0:20], reverse=True) else: rList = sorted(rList, key=lambda d: d.get_id().strip(), reverse=True) if self.needBR(): html += '<br>' # count = 0 rList.reverse() parentDesc = '' if libraryRecord != None: parentDesc = libraryRecord.get_describe() if form_dict['column'] == '1': titleList = [] urlList = [] htmlList = [] descHtmlList = [] aidList = [] refreshIDList = [] count = 0 for item in rList: title = item.get_title().strip().replace( '%20', ' ') titleList.append(title) #print titleList urlList.append(item.get_url().strip()) appendFrontHtml = '' if title.lower( ) != Config.history_quick_access_name.lower(): appendFrontHtml = self.utils.genQuickAcessButton( item, 'history', iconType='remark') else: appendFrontHtml = self.utils.genQuickAcessButton( item, 'history') if title.lower( ) != Config.history_quick_access_name.lower(): htmlList.append(appendFrontHtml + self.getDeleteButton( divID, historyFile, item.get_url().strip())) else: #html = self.utils.getIconHtml('', 'quickaccess') html += appendFrontHtml + self.genQuickAccessSyncButton( rID, quickAccessHistoryFile, divID, objID) + ' ' htmlList.append(html) count += 1 refreshID = self.getRefreshID(self.divID, title) aid = self.getAID(self.divID, count) aidList.append(aid) refreshIDList.append(refreshID) descHtmlList.append( self.utils.genDescHtml( item.get_describe().strip(), Config.course_name_len, self.tag.tag_list, iconKeyword=True, fontScala=1, aid=aid, refreshID=refreshID)) #splitNumber = len(rList) / 3 splitNumber = len(rList) return self.utils.toListHtml( titleList, urlList, htmlList, descHtmlList=descHtmlList, splitNumber=splitNumber, moreHtml=True, aidList=aidList, refreshIDList=refreshIDList, orginFilename=form_dict['originFileName']) else: html += '<div class="ref"><ol>' for item in rList: title = item.get_title().strip().replace( '%20', ' ') count += 1 jobj_record = {} jobj_record['id'] = rID + '-' + str(count) jobj_record['title'] = title jobj_record['url'] = item.get_url().strip() jobj_record['count'] = self.getClickCount(item) jobj_record['desc'] = item.get_describe() jobj_record['parentDesc'] = parentDesc print jobj_record['desc'] appendHtml = '' appendFrontHtml = '' if title.lower( ) != Config.history_quick_access_name.lower(): appendFrontHtml = self.utils.genQuickAcessButton( item, 'history', iconType='remark') appendHtml += self.getDeleteButton( divID, historyFile, item.get_url().strip()) + ' ' else: #appendHtml = self.utils.getIconHtml('', 'quickaccess') appendFrontHtml = self.utils.genQuickAcessButton( item, 'history') appendHtml += self.genQuickAccessSyncButton( rID, quickAccessHistoryFile, divID, objID) + ' ' #print jobj_record html += self.gen_item( rID, divID, count, jobj_record, Config.more_button_for_history_module, form_dict['fileName'], form_dict['originFileName'], appendFrontHtml='', appendAfterHtml=appendFrontHtml + appendHtml) ''' html += '<li><span>' + str(count) + '.</span>' html += '<p>' + self.utils.enhancedLink(item.get_url().strip(), self.utils.formatTitle(title, Config.smart_link_br_len, []), module='history', library=form_dict['originFileName'], rid=rID) + self.utils.getIconHtml(item.get_url().strip()) ''' html += "</ol></div>" return html else: self.updateHistory() if self.needBR(): html += '<br>' html += '<div class="ref"><ol>' count = 0 item_dict = {} for jobj in self.jobj_list: if self.match_item(jobj, [rTitle]) or self.match_item( jobj, alias): if item_dict.has_key(jobj['title'].strip()): continue item_dict[jobj['title'].strip()] = '' count += 1 html += self.gen_item( rID, divID, count, jobj, Config.more_button_for_history_module, form_dict['fileName'], form_dict['originFileName']) html += "</ol></div>" if count == 0: html = '' return html def gen_item(self, rID, ref_divID, count, jobj, moreOption, fileName, orginFilename, keywords=[], appendFrontHtml='', appendAfterHtml='', parentDesc=''): html = '' html += '<li><span>' + str(count) + '.</span>' url = '' resType = '' if jobj.has_key('url'): url = jobj['url'] title = self.utils.getValueOrText(jobj['title'].strip(), returnType='text') if title.find(' - ') != -1: resType = title[title.rfind('-') + 1:].strip() if Config.website_icons.has_key(resType): title = title[0:title.find(' - ')] if title.find('/') != -1: title = title[title.rfind('/') + 1:] ftitle = self.utils.formatTitle(title, Config.smart_link_br_len, keywords) urlIcon = '' if url != '': if title.lower() != Config.history_quick_access_name.lower(): urlIcon = self.utils.getIconHtml(url, title=jobj['title']) #print url + jobj['title'] showText = ftitle #if Config.history_show_click_count and jobj.has_key('count'): # clickCount = jobj['count'] # if int(clickCount) > 1: # showText = ftitle + ' (' + clickCount + ')' aid = self.getAID(ref_divID, count) refreshID = self.getRefreshID(self.divID, text=title) desc = jobj['desc'].strip() if desc.find('clickcount') != -1: desc = desc[0:desc.find('clickcount')].strip() haveDesc = True if len(desc) == 0 and url.find( Config.ip_adress ) == -1: #and url.startswith('/') == False: haveDesc = False pid = aid.replace('a-', 'p-') pscript = "switchLinkBGColor('" + pid + "', 'rgb(248, 248, 255)', 'rgb(255, 255, 255)');" html += '<p id="' + pid + '" onmouseover="' + pscript + '" style="border-radius: 5px 5px 5px 5px;">' html += self.utils.enhancedLink(url, ftitle, module='history', library=fileName, rid=rID, haveDesc=haveDesc, aid=aid, refreshID=refreshID, showText=showText) if appendFrontHtml != '': html += appendFrontHtml html += urlIcon #if jobj['desc'].strip().startswith('clickcount') == False and title.lower() != Config.history_quick_access_name.lower(): # html += self.utils.getIconHtml('', title='remark') else: html += '<p>' + title if appendFrontHtml != '': html += appendFrontHtml html += ' > ' #if self.existChild(str(jobj['id'])): # html += ' > ' if urlIcon == '' and resType != '' and Config.website_icons.has_key( resType): html += self.utils.getIconHtml('', title=resType) if appendAfterHtml != '': html += appendAfterHtml if moreOption: linkID = self.getAID(ref_divID, count) + '-more' ref_divID += '-' + str(count) appendID = str(count) originTitle = title #if title.find(' - ') != -1: # title = title[0 : title.find('-')].strip() script = self.utils.genMoreEnginScript( linkID, ref_divID, "loop-h-" + rID.replace(' ', '-') + '-' + str(appendID) + '-' + str(jobj['id']), title, url, originTitle, hidenEnginSection=Config.history_hiden_engin_section) descHtml = '' if jobj.has_key('desc') and jobj['desc'].strip() != '': #print jobj['desc'] #refreshID = self.getRefreshID(self.divID, text=title) refreshID = '' aid = self.getAID(self.divID, count) #print 'parentDesc--->' + jobj['parentDesc'] if Config.history_enable_subitem_log: descHtml = self.utils.genDescHtml( jobj['desc'], Config.course_name_len, self.tag.tag_list, library=fileName, rid=rID, aid=aid, refreshID=refreshID, iconKeyword=True, fontScala=1, parentDesc=jobj['parentDesc']) else: descHtml = self.utils.genDescHtml( jobj['desc'], Config.course_name_len, self.tag.tag_list, iconKeyword=True, fontScala=1, rid=rID, aid=aid, refreshID=refreshID, parentDesc=jobj['parentDesc']) #if url != '': # descHtml = self.utils.genDescHtml('url:' + url, Config.course_name_len, self.tag.tag_list) #print 'descHtml:' + descHtml html += self.utils.genMoreEnginHtml(linkID, script.replace("'", '"'), '...', ref_divID, '', False, descHtml=descHtml).strip() html += '</p></li>' return html def getAID(self, ref_divID, count): ref_divID += '-' + str(count) linkID = 'a-' + ref_divID[ref_divID.find('-') + 1:] return linkID def match_item(self, jobj, rTitleList): if len(rTitleList) == 0: return False for rTitle in rTitleList: if rTitle.strip() == '': continue if self.containIgoncase(jobj['title'].strip(), rTitle.strip()): #print jobj['title'].strip() + ' ' + rTitle.strip() return True return False def containIgoncase(self, leftData, rightData): return leftData.lower().find(rightData.lower()) != -1 def existHistoryFile(self, filename): return os.path.exists(self.getHistoryFileName(filename)) def getHistoryFileName(self, filename): if filename.find('/') != -1: filename = filename[filename.rfind('/') + 1:] return 'extensions/history/data/' + filename + '-history' def excuteCommand(self, form): if form['command'] == 'sync': print 'sync' self.syncHistory(form) return '' def syncHistory(self, form): print '--syncHistory--' oldLine = form['oldLine'] newLine = form['newLine'] originFileName = form['fileName'] category = form['resourceType'] utils = self.utils if oldLine != newLine: oldRecord = Record(oldLine) newRecord = Record(newLine) oldID = oldRecord.get_id().strip() newID = newRecord.get_id().strip() oldDesc = oldRecord.get_describe() newDesc = newRecord.get_describe() historyFileName = self.getHistoryFileName(originFileName) print historyFileName all_lines = [] historyRecord = None count = 0 if oldID != newID and os.path.exists(historyFileName): print 'id chanage' f = open(historyFileName, 'rU') for line in f.readlines(): count += 1 historyRecord = Record(line) if historyRecord.get_id().strip() == oldID: print 'match line:' + line newline = newID + ' | ' + historyRecord.get_title( ).strip() + ' | ' + historyRecord.get_url().strip( ) + ' | ' + historyRecord.get_describe().strip() + '\n' print 'newline:' + newline all_lines.append(newline) else: all_lines.append(line) f.close() print 'hislines before:' + str(count) + ' after:' + str( len(all_lines)) utils.write2File(historyFileName, all_lines) elif oldDesc != newDesc: print 'desc chanage' oldDescDict = utils.toDescDict(oldDesc, originFileName) newDescDict = utils.toDescDict(newDesc, originFileName) print oldDescDict print newDescDict notMatchDict = {} for k, v in newDescDict.items(): if oldDescDict.has_key(k) == False: print 'add new tag:' + k elif oldDescDict[k] != newDescDict[k]: print 'desc not match:' + k #print oldDescDict[k] #print newDescDict[k] notMatchDict = self.whatNotMacth( oldDescDict[k], newDescDict[k]) for k, v in oldDescDict.items(): if newDescDict.has_key(k) == False: print 'delete tag:' + k if os.path.exists(historyFileName): print 'foud history file:' + historyFileName f = open(historyFileName, 'rU') for line in f.readlines(): #print line[0 : line.find('|')].strip() #print newID count += 1 historyRecord = Record(line) if newID != historyRecord.get_id().strip(): all_lines.append(line) else: found = False for k, v in notMatchDict.items(): #print historyRecord.get_title() #print k if historyRecord.get_title().find(k) != -1: print 'matched line:' print line found = True desc = utils.valueText2Desc( v, prefix=False).strip() print 'new desc:' print desc if category != None and category != '' and desc.find( 'category:') == -1: desc += ' category:' + category if line.find('clickcount:') != -1: clickcount = utils.reflection_call( 'record', 'WrapRecord', 'get_tag_content', line, { 'tag': 'clickcount' }).strip() desc += ' clickcount:' + str( clickcount) newline = historyRecord.get_id().strip( ) + ' | ' + historyRecord.get_title( ).strip() + ' | ' + historyRecord.get_url( ).strip() + ' | ' + desc.strip() + '\n' print 'new line:' print newline all_lines.append(newline) break if found == False: all_lines.append(line) f.close() print 'hislines before:' + str(count) + ' after:' + str( len(all_lines)) utils.write2File(historyFileName, all_lines) print '---syncHistory finish----' def whatNotMacth(self, oldValue, newValue): result = {} oldValueDict = self.toNotMatchDict(oldValue) newValueDict = self.toNotMatchDict(newValue) #print oldValueDict #print newValueDict for k, v in newValueDict.items(): if oldValueDict.has_key(k) and oldValueDict[k] != newValueDict[k]: print 'whatChanage:' + k result[k] = newValueDict[k] return result def toNotMatchDict(self, value): valueDict = {} if value.find(',') != -1: values = value.split(',') else: values = [value] for item in values: item = item.strip().encode('utf-8') #print '===' + item if self.utils.getValueOrTextCheck(item): #print item[0 : item.find('(')] valueDict[self.utils.getValueOrText(item, 'text')] = item else: valueDict[item] = item return valueDict def check(self, form_dict): self.updateHistory() rID = form_dict['rID'].encode('utf8') rTitle = form_dict['rTitle'].encode('utf8').replace('%20', ' ') return self.existHistoryFile( form_dict['fileName']) and self.utils.find_file_by_pattern_path( re.compile(rID, re.I), self.getHistoryFileName(form_dict['fileName']))
class History(BaseExtension): raw_data = '' jobj_list = [] tag = Tag() """docstring for History""" def __init__(self): BaseExtension.__init__(self) self.utils = Utils() #self.loadHistory() self.form_dict = None def loadHistory(self): self.updateHistory() if os.path.exists('extensions/history/data/chrome_history.json'): f = open('extensions/history/data/chrome_history.json', 'rU') self.raw_data = f.read() self.jobj_list = json.loads(self.raw_data) f.close() def updateHistory(self): if os.path.exists(Config.history_file_path): subprocess.check_output( "mv " + Config.history_file_path + " extensions/history/data/chrome_history.json", shell=True) self.loadHistory() def getAlias(self, rID, file, nocache): alias = '' use_cache = nocache == False record = self.utils.getRecord(rID.strip(), path=file, log=True, use_cache=use_cache) if record != None and record.get_id().strip() != '': ret = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag': 'alias'}) if ret != None: alias = ret.strip() print 'alias:' + alias if alias.find(',') != -1: return alias.split(',') elif alias != '': return [alias] else: return [] def needBR(self): return self.form_dict['column'] != '1' and self.form_dict.has_key( 'extension_count') and int(self.form_dict['extension_count']) > 12 def getDeleteButton(self, divID, historyFile, url): deleteScript = "$.post('/exec', {command : 'deleteRow', fileName : '" + historyFile + "', key : '" + url + "'}, function(data){" + "var target=document.getElementById('" + divID.replace( '-history', '' ) + '-nav-history' + "');hidendiv_2('" + divID + "');navTopic(target,'" + divID.replace( '-history', '') + "','" + divID.replace( '-history', '') + '-nav-' + "',9);" + "});" deleteButton = ' <a target="_blank" href="javascript:void(0);" onclick="' + deleteScript + '" style="color:#999966; font-size: 10pt;"><image src="http://findicons.com/files/icons/766/base_software/128/deletered.png" width="14" height="12"></image></a>' return deleteButton def excute(self, form_dict): self.form_dict = form_dict #print form_dict if form_dict.has_key('nocache'): nocache = form_dict['nocache'].encode('utf8') rTitle = form_dict['rTitle'].encode('utf8').replace('%20', ' ') rID = form_dict['rID'].encode('utf8') divID = form_dict['divID'].encode('utf8') alias = self.getAlias(rID.strip(), form_dict['originFileName'], nocache) html = '' if self.existHistoryFile(form_dict['originFileName'].strip()): historyFilename = form_dict['originFileName'][ form_dict['originFileName'].rfind('/') + 1:].strip() historyFile = 'extensions/history/data/' + historyFilename + '-history' #print historyFile f = open(historyFile, 'r+') rDict = {} all_lines = f.readlines() for line in all_lines: r = Record(line) if r.valid(r.line) == False: #print r.line continue if r.get_url().strip() != '': rDict[r.get_url().strip()] = r rList = [] #print rDict if len(rDict) != len(all_lines): f.truncate() f.close() else: f.close() f = open(historyFile, 'r+') for k, v in rDict.items(): #print v.line if v.line.strip() != '' and v.valid(r.line): if len(rDict) != len(all_lines): f.write(v.line) if v.get_id().strip() == form_dict['rID'].strip() or ( v.get_id().strip().startswith('loop') and v.get_id().strip().find( form_dict['rID'].strip()) != -1): rList.append(v) f.close() #print rList #f = open('extensions/history/data/' + historyFilename, 'r') if len(rList) > 0: rList = sorted(rList, key=lambda d: d.get_url().strip()[0:20], reverse=True) if self.needBR(): html += '<br>' # count = 0 rList.reverse() if form_dict['column'] == '1': titleList = [] urlList = [] htmlList = [] for item in rList: title = item.get_title().strip().replace('%20', ' ') titleList.append(title) #print titleList urlList.append(item.get_url().strip()) htmlList.append( self.getDeleteButton(divID, historyFile, item.get_url().strip())) return self.utils.toListHtml(titleList, urlList, htmlList, 10, False) else: html += '<div class="ref"><ol>' for item in rList: title = item.get_title().strip().replace('%20', ' ') count += 1 jobj_record = {} jobj_record['id'] = rID + '-' + str(count) jobj_record['title'] = title jobj_record['url'] = item.get_url().strip() appendHtml = self.getDeleteButton( divID, historyFile, item.get_url().strip()) + ' ' html += self.gen_item( rID, divID, count, jobj_record, Config.more_button_for_history_module, form_dict['originFileName'], appendHtml=appendHtml) ''' html += '<li><span>' + str(count) + '.</span>' html += '<p>' + self.utils.enhancedLink(item.get_url().strip(), self.utils.formatTitle(title, Config.smart_link_br_len, []), module='history', library=form_dict['originFileName'], rid=rID) + self.utils.getIconHtml(item.get_url().strip()) ''' html += "</ol></div>" return html else: self.updateHistory() if self.needBR(): html += '<br>' html += '<div class="ref"><ol>' count = 0 item_dict = {} for jobj in self.jobj_list: if self.match_item(jobj, [rTitle]) or self.match_item( jobj, alias): if item_dict.has_key(jobj['title'].strip()): continue item_dict[jobj['title'].strip()] = '' count += 1 html += self.gen_item( rID, divID, count, jobj, Config.more_button_for_history_module, form_dict['originFileName']) html += "</ol></div>" if count == 0: html = '' return html def gen_item(self, rID, ref_divID, count, jobj, moreOption, orginFilename, keywords=[], appendHtml=''): html = '' html += '<li><span>' + str(count) + '.</span>' url = '' if jobj.has_key('url'): url = jobj['url'] #if self.tag.account_tag_alias.has_key(jobj['title'].strip()): # title = self.tag.account_tag_alias[jobj['title'].strip()] title = self.utils.getValueOrText(jobj['title'].strip(), returnType='text') ftitle = self.utils.formatTitle(title, Config.smart_link_br_len, keywords) if url != '': #print url + jobj['title'] html += '<p>' + self.utils.enhancedLink( url, ftitle, module='history', library=orginFilename, rid=rID) + self.utils.getIconHtml(url, title=jobj['title']) else: html += '<p>' + title + ' > ' #if self.existChild(str(jobj['id'])): # html += ' > ' if appendHtml != '': html += appendHtml if moreOption: ref_divID += '-' + str(count) linkID = 'a-' + ref_divID[ref_divID.find('-') + 1:] appendID = str(count) if title.find(' - ') != -1: title = title[0:title.find('-')].strip() script = self.utils.genMoreEnginScript( linkID, ref_divID, "loop-h-" + rID.replace(' ', '-') + '-' + str(appendID) + '-' + str(jobj['id']), title, url, '-', hidenEnginSection=Config.history_hiden_engin_section) descHtml = '' #if url != '': # descHtml = self.utils.genDescHtml('url:' + url, Config.course_name_len, self.tag.tag_list) #print 'descHtml:' + descHtml html += self.utils.genMoreEnginHtml(linkID, script.replace("'", '"'), '...', ref_divID, '', False, descHtml=descHtml) html += '</p></li>' return html def match_item(self, jobj, rTitleList): if len(rTitleList) == 0: return False for rTitle in rTitleList: if rTitle.strip() == '': continue if self.containIgoncase(jobj['title'].strip(), rTitle.strip()): #print jobj['title'].strip() + ' ' + rTitle.strip() return True return False def containIgoncase(self, leftData, rightData): return leftData.lower().find(rightData.lower()) != -1 def existHistoryFile(self, filename): return os.path.exists(self.getHistoryFileName(filename)) def getHistoryFileName(self, filename): if filename.find('/') != -1: filename = filename[filename.rfind('/') + 1:] return 'extensions/history/data/' + filename + '-history' def check(self, form_dict): self.updateHistory() rID = form_dict['rID'].encode('utf8') rTitle = form_dict['rTitle'].encode('utf8').replace('%20', ' ') return self.existHistoryFile( form_dict['originFileName'] ) and self.utils.find_file_by_pattern_path( re.compile(rID, re.I), self.getHistoryFileName(form_dict['originFileName']))
def __init__(self): BaseExtension.__init__(self) self.utils = Utils() self.tag = Tag()
class Edit(BaseExtension): def __init__(self): BaseExtension.__init__(self) self.utils = Utils() self.tag = Tag() def textFormatConvert(self, textContent): newTextContent = textContent.strip() textContentList = newTextContent.split('\n') if textContentList[0].endswith(':'): print textContentList group = '' convertText = '' accountTag = False accountType = '' accountValue = '' for item in textContentList: if item == '': continue if item.strip().endswith(':'): if self.utils.isAccountTag(item, self.tag.tag_list_account): accountTag = True if accountValue != '' and item != accountType + ':': convertText += accountType + '(' + accountValue[ 0:len(accountValue) - 1] + '),\n' accountValue = '' accountType = '' accountType = item.replace(':', '') else: accountTag = False if accountValue != '': convertText += accountType + '(' + accountValue[ 0:len(accountValue) - 1] + '),\n' accountValue = '' accountType = '' group = item[0:item.find(':')] elif accountTag: accountValue += item + '*' else: key = '' if item.find(' - ') != -1: parts = item.split(' - ') key = parts[0] item = parts[1] else: key = item.replace('https', 'http').replace( 'http', '').replace('://', '').replace('www.', '') if key.find('.') != -1: key = key[0:key.find('.')] convertText += key + '<' + group + '>' + '(' + item + '),\n' if accountValue != '': convertText += accountType + '(' + accountValue[ 0:len(accountValue) - 1] + '),\n' convertText = convertText[0:len(convertText) - 2].strip() + '\n' print convertText return convertText else: return textContent def excute(self, form_dict): print form_dict rID = form_dict['rID'].strip() rTitle = form_dict['rTitle'].replace('%20', ' ').strip() fileName = form_dict['fileName'].strip() originFileName = form_dict['originFileName'].strip() divID = form_dict['divID'] if divID.find('-history-') != -1 and divID.find('-content-') != -1: fileName = fileName[fileName.rfind('/') + 1:] fileName = os.getcwd( ) + '/extensions/content/data/' + fileName + '-history-content' elif divID.find('-content-') != -1 and divID.find('-edit') != -1: originFileName = originFileName[originFileName.rfind('/') + 1:] fileName = os.getcwd( ) + '/extensions/content/data/' + originFileName + '-content' library = form_dict['fileName'] if form_dict.has_key('textContent'): textContent = form_dict['textContent'] if rID.startswith('loop-h-') or rID.find('plugin') != -1: editedData = '' textContent = self.textFormatConvert(textContent) textContent = textContent.replace(',\n', '+') textContent = self.utils.removeDoubleSpace(textContent) textContent = textContent.replace(', ', '+') textContent = textContent.replace(',', '+') textContent = textContent.replace('\n', '') editedData = rTitle + '(' + textContent + ')' print 'editedData--->' + editedData #return historyRecord = None r = None print rID r, historyRecord = self.getRecordByHistory( rID, rTitle, fileName) if rID.find('plugin') != -1 and historyRecord == None: pid = rID.replace('custom-plugin-', '') if pid.find('-pg') != -1: pid = pid[0:pid.find('-pg')] r = self.utils.getRecord(pid, path=fileName, use_cache=False) #print historyRecord.line #return 'error' if r != None: editRID = r.get_id().strip() resourceType = '' if historyRecord != None and editedData.find( 'category(') == -1: resourceType = self.utils.reflection_call( 'record', 'WrapRecord', 'get_tag_content', historyRecord.line, {'tag': 'category'}) if resourceType != None: resourceType = resourceType.strip() print 'editRID-->' + editRID if rID.find(editRID) != -1: newData = r.edit_desc_field2( self.utils, r, resourceType, rTitle, editedData, self.tag.get_tag_list(library), library=library) if newData != '': #print '--->' + newData result = self.editRecord( editRID, self.utils.removeDoubleSpace(newData), originFileName, library=library, resourceType=resourceType, divID=divID) return result return 'error' else: textContent = self.utils.removeDoubleSpace( textContent.replace(',\n ', ', ').replace('\n', ' ')) print textContent return self.editRecord(rID, textContent, originFileName, library=library, divID=divID) return 'error' column = str(form_dict['column']) print fileName r = None if rTitle.startswith('library/') and rID.find('custom-plugin') != -1: rTitle = rTitle.replace('==', '->') r = self.utils.crossref2Record(rTitle, rID='custom-plugin') print r.line fileName = 'db/' + rTitle[0:rTitle.find('#')] originFileName = fileName rTitle = r.get_title().strip() else: if rTitle.startswith('library/'): fileName = 'db/' + rTitle[0:rTitle.find('#')] if rTitle.find('==') != -1: rTitle = rTitle[rTitle.find('==') + 2:] r = self.utils.getRecord(rID, path=fileName, use_cache=False) print fileName html = 'not found' areaID = rID.replace(' ', '-').replace('.', '-') + '-area' if rID.startswith('loop-h-') or rID.find('plugin') != -1: if rID.find('plugin') == -1: r, historyRecord = self.getRecordByHistory( rID, rTitle, fileName) if r != None: #print r.line item = '' if rID.find('plugin') == -1: item = r.get_desc_field2(self.utils, rTitle, self.tag.get_tag_list(library), library=library) else: item = rTitle + '(' + self.utils.desc2ValueText( r.get_describe(), self.tag.get_tag_list(library)) + ')' #rID = rID.replace('custom-plugin-', '') #print 'item:' + item rID = rID.replace( '-' + rTitle.lower().strip().replace(' ', '-'), '') if item != '': print '---->' + rID + '----' + item text = value = self.utils.getValueOrText(item, returnType='text') value = self.utils.getValueOrText(item, returnType='value') rows, cols = self.getRowsCols(column) html = '<div class="ref">' html += self.genTextareaHtml(rows, cols, areaID, value.replace('+', ',\n')) html += '<br>' html += self.genEditButton(areaID, rID, text, fileName, divID, originFileName) html += '</div>' return html return r.line if r != None and r.get_id().strip() != '': desc = r.get_describe().strip() html = '' print form_dict['extension_count'] print desc if int(form_dict['extension_count']) > 12: html += '<br>' start = 0 text = '' rows, cols = self.getRowsCols(column) if rID.startswith('custom-'): text += 'id:' + r.get_id().strip() + '\n' text += '\ntitle:' + r.get_title().strip() + '\n' else: text += 'title:' + r.get_title().strip() + '\n' text += '\nurl:' + r.get_url().strip() + '\n' #print 'library:----' + library while start < len(desc): end = self.utils.next_pos(desc, start, int(cols), self.tag.get_tag_list(library), library=library, shortPos=True) #print end line = desc[start:end].strip() print line if line.find(':') != -1 and line.find( ':') < 15 and line[0:1].islower(): line = '\n' + line line = line.replace(', ', ',\n ') text += line + '\n' if end < 0 or line.strip() == '': break start = end if form_dict.has_key( 'appendText') and form_dict['appendText'] != '': text += '\n' + form_dict['appendText'] + '\n' html += self.genTextareaHtml(rows, cols, areaID, text) html += '<br>' html += self.genEditButton(areaID, rID, rTitle, fileName, divID, originFileName) return html def getRecordByHistory(self, rid, title, fileName): path = fileName[0:fileName. find('db/')] + 'extensions/history/data/' + fileName[ fileName.rfind('/') + 1:] + '-history' if os.path.exists(path): print path print title rList = self.utils.getRecord(title, path=path, use_cache=False, accurate=False, matchType=2, return_all=True, log=True) if rList != None: record = None hRecord = None for historyRecord in rList: historyRID = historyRecord.get_id().strip() historyTitle = historyRecord.get_title().strip() print 'historyRID:' + historyRID + ' rid:' + rid print 'historyTitle:' + historyTitle + ' title:' + title if historyRID != '': if rid.find(historyRID) != -1: record = self.utils.getRecord(historyRID, path=fileName, use_cache=False) if title == historyTitle: return record, historyRecord else: hRecord = historyRecord return record, hRecord return None, None def genEditButton(self, areaID, rID, rTitle, fileName, divID, originFileName): script = "var text = $('#" + areaID + "'); console.log('', text[0].value);" script += "var postArgs = {name : 'edit', rID : '" + rID + "', rTitle : '" + rTitle + "', check: 'false', fileName : '" + fileName + "', divID : '" + divID + "', originFileName : '" + originFileName + "', textContent: text[0].value};" linkid = divID.replace('-edit', '').replace('div', 'a') if rID.find('plugin') != -1: script += "$.post('/extensions', postArgs, function(data) { \ a = document.getElementById('searchbox-a');\ if (a.text == 'less'){\ if (popupMode == false) {\ a.onclick();\ a.onclick();\ } else {\ showPopupContent(0, 20, 1444, 900, '>" + rTitle + "');\ }\ }\ });" else: script += "$.post('/extensions', postArgs, function(data) { \ console.log('refresh:' + data);\ if (data.indexOf('#') != -1) {\ dataList = data.split('#');\ if (dataList.length == 3) {\ refreshTab(dataList[2], dataList[1]);\ return;\ }\ }\ search_txt = document.getElementById('search_txt');\ if (search_txt != null && search_txt.value != '') {\ typeKeyword(search_txt.value, '');\ } else {\ window.location.href = window.location.href.replace('#', '');\ }\ });" # var a = document.getElementById('" + linkid + "'); var evnt = a['onclick']; evnt.call(a); script += 'isEditing = false;' html = '<button type="submit" id="edit_btn" hidefocus="true" onclick="' + script + '">submit</button>' return html def getRowsCols(self, column): rows = '25' cols = '75' if column == '1': rows = '40' cols = '199' elif column == '2': rows = '35' cols = '88' return rows, cols def genTextareaHtml(self, rows, cols, areaID, text): html = '' html += '<textarea rows="' + rows + '" cols="' + cols + '" id="' + areaID + '" style="font-size: 13px; border-radius:5px 5px 5px 5px; font-family:San Francisco;color:#003399;white-space:pre-wrap" ' html += 'onfocus="setbg(' + "'" + areaID + "'," + "'#e5fff3');" + '" ' html += 'onblur="setbg(' + "'" + areaID + "'," + "'white');" + '">' html += text html += '</textarea>' return html def editRecord(self, rID, data, originFileName, library='', resourceType='', divID=''): print 'editRecord->' + data record = Record(' | | | ' + data) newid = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag': 'id'}) if newid != None: newid = newid.strip() else: newid = rID title = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, { 'tag': 'title', 'library': library }).strip() url = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, { 'tag': 'url', 'library': library }).strip() desc = data.replace('id:' + newid, '').replace('title:' + title, '').replace('url:' + url, '').strip() if url == None: url = '' newRecord = Record(newid + ' | ' + title + ' | ' + url + ' | ' + desc) result = newRecord.editRecord(self.utils, rID, newRecord, originFileName, library, resourceType=resourceType) if result: print divID if divID.find('-history-') != -1: aid = divID[0:divID.find('-history-')].strip() + '-a-' result = 'refresh#history#' + aid elif divID.find('-content-') != -1: aid = divID[0:divID.find('-content-')].strip() + '-a-' result = 'refresh#content#' + aid else: result = 'refresh' else: result = 'error' print 'result--->' + result return result def check(self, form_dict): rID = form_dict['rID'].strip() return rID.startswith('loop') == False or rID.startswith('loop-h')
class Bookmark(BaseExtension): rounter = {'' : '',\ '' : ''} raw_data = '' jobj_list = [] tag = Tag() def __init__(self): BaseExtension.__init__(self) self.utils = Utils() self.loadBookmark() self.form_dict = None def existChild(self, pid): return self.raw_data.lower().find('"parentId":"' + pid + '"') != -1 def loadBookmark(self): if os.path.exists('extensions/bookmark/data/chrome_bookmarks.json'): f = open('extensions/bookmark/data/chrome_bookmarks.json', 'rU') self.raw_data = f.read() self.jobj_list = json.loads(self.raw_data) f.close() def updateBookmark(self): if os.path.exists(Config.bookmark_file_path): subprocess.check_output("mv " + Config.bookmark_file_path + " extensions/bookmark/data/chrome_bookmarks.json", shell=True) self.loadBookmark() def getAlias(self, rID, rTitle, file, nocache): alias = '' use_cache = not nocache record = None if rID.startswith('loop-h-'): file = file[0 : file.find('db/')] + 'extensions/history/data/' + file[file.rfind('/') + 1 :] + '-history' print file record = self.utils.getRecord(rTitle, path=file, matchType=2, use_cache=use_cache, accurate=False) #print record.line elif rID.startswith('loop-hc-'): file = file[0 : file.find('db/')] + 'extensions/content/data/' + file[file.rfind('/') + 1 :] + '-history-content' print file record = self.utils.getRecord(rTitle, path=file, matchType=2, use_cache=use_cache) elif rTitle.startswith('library/'): record = self.utils.crossref2Record(rTitle.replace('==', '->')) else: record = self.utils.getRecord(rID.strip(), path=file, log=True, use_cache=use_cache) if record != None and record.get_id().strip() != '': ret = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag' : 'alias'}) if ret != None: alias = ret.strip() print 'alias:' + alias if alias.find(',') != -1: return alias.split(',') elif alias != '': return [alias] else: return [] def needBR(self): if self.form_dict['column'] != '1' and self.form_dict.has_key('extension_count') and int(self.form_dict['extension_count']) > 12: return True if self.form_dict['column'] == '3' and int(self.form_dict['extension_count']) > 10: return True return False def excute(self, form_dict): self.form_dict = form_dict divID = form_dict['divID'].encode('utf8') nocache = True if form_dict.has_key('nocache'): nocache = form_dict['nocache'].encode('utf8') rID = form_dict['rID'].encode('utf8') fileName = form_dict['fileName'].encode('utf8') originFileName = form_dict['originFileName'] rTitle = form_dict['rTitle'].encode('utf8').replace('%20', ' ') alias = self.getAlias(rID.strip(), rTitle, originFileName, nocache) if rTitle.startswith('library/'): rTitle = rTitle.replace('==', '->') if rTitle.find('->') != -1: rTitle = rTitle[rTitle.find('->') + 2 :] else: rTitle = rTitle[rTitle.find('#') + 1 :] print divID ''' if divID.find('-cloud-') != -1: html = '' cloud_bookmark = self.genWebsiteHtml(rTitle, form_dict['originFileName']) if cloud_bookmark.find('<li>') != -1: html += 'cloud bookmark(' + rTitle + '):<br>' + cloud_bookmark else: html = '' return html ''' html = '' if self.needBR(): html += '<br>' html += '<div class="ref"><ol>' print alias #if form_dict.has_key('selection') and form_dict['selection'].strip() != '': # selection = form_dict['selection'].encode('utf8').strip() #if rTitle.find(selection) != -1: # rTitle = selection self.updateBookmark() count = 0 pid = '' records = [] currentPage = form_dict['page'] if self.rounter.has_key(rID): pid = self.rounter[rID] elif rID.startswith('loop-b'): pid = rID[rID.rfind('-') + 1 :] print 'rID ' + rID + ' pid: ' + pid + ' rTitle:' + rTitle notList = [] aliasList = [] for item in alias: item = item.strip() if item.startswith('!') == True: notList.append(item.replace('!', '').strip()) else: aliasList.append(item) print notList print aliasList page_item_count = Config.bookmark_page_item_count[int(form_dict['column']) - 1] if form_dict.has_key('nopage'): page_item_count = 1000 for jobj in self.jobj_list: if pid == '': matched1, matchedText1 = self.match_item(jobj, [rTitle]) matched2, matchedText2 = self.match_item(jobj, aliasList, notList) if matched1 or matched2: count += 1 higtLightText = '' if matchedText1 != '': higtLightText = matchedText1.lower() elif matchedText2 != '': higtLightText = matchedText2.lower() if rID.startswith('loop-b'): html += self.gen_item(rID, divID, count, jobj, True, form_dict['originFileName'], higtLightText=higtLightText) else: if count <= int(form_dict['page']) * page_item_count and count > (int(form_dict['page']) - 1) * page_item_count: currentPage = form_dict['page'] html += self.gen_item(rID, divID, count, jobj, True, form_dict['originFileName'], higtLightText=higtLightText) url = '' if jobj.has_key('url'): url = jobj['url'] records.append(Record('bookmark-' + str(count) + ' | ' + jobj['title'] + ' | ' + url + ' | ')) else : if jobj['parentId'] == pid: count += 1 html += self.gen_item(rID, divID, count, jobj, True, form_dict['originFileName'], higtLightText=jobj['title']) url = '' if jobj.has_key('url'): url = jobj['url'] records.append(Record('bookmark-' + str(count) + ' | ' + jobj['title'] + ' | ' + url + ' | ')) html += "</ol></div>" if count == 0: html = '' total_page = 0; if Config.bookmark_output_data_to_new_tab: return self.utils.output2Disk(records, 'bookmark', rTitle, Config.bookmark_output_data_format) else: if len(records) < page_item_count: total_page = 1 elif len(records) % page_item_count == 0: total_page = len(records) / page_item_count else: total_page = len(records) / page_item_count + 1 print 'currentPage ' + str(currentPage) if total_page > 1 and rID.startswith('loop-b') == False: if int(currentPage) == 1: html += '<div style="margin-left:auto; text-align:right;margin-top:2px; margin-right:55px;">' html += self.utils.enhancedLink('', '<font size="1">expand</font>', module='bookmark', library=form_dict['originFileName'], rid=form_dict['rID'], script=self.getPageScript(form_dict, 1, nopage=True), ignoreUrl=True) html += '</div>' html += '<div style="margin-left:auto; text-align:center;margin-top:2px; margin-right:auto;">' for page in range(0, total_page): print (page + 1) if page == 0 and int(currentPage) > 1: html += self.utils.enhancedLink('', '<font size="5">< </font>', module='bookmark', library=form_dict['originFileName'], rid=form_dict['rID'], script=self.getPageScript(form_dict, int(currentPage) - 1), ignoreUrl=True) html += ' ' if ((page + 1) == int(currentPage)): html += '<font size="5">' + self.utils.enhancedLink('', str(page + 1), module='bookmark', library=form_dict['originFileName'], rid=form_dict['rID'], script=self.getPageScript(form_dict, page + 1), style="color:#00BFFF;", ignoreUrl=True) + '</font> ' else: html += self.utils.enhancedLink('', str(page + 1), module='bookmark', library=form_dict['originFileName'], rid=form_dict['rID'], script=self.getPageScript(form_dict, page + 1), ignoreUrl=True) + ' ' if page == total_page - 1 and int(currentPage) < total_page: html += ' ' html += self.utils.enhancedLink('', '<font size="5"> ></font>', module='bookmark', library=form_dict['originFileName'], rid=form_dict['rID'], script=self.getPageScript(form_dict, int(currentPage) + 1), ignoreUrl=True) html += '</div>' if rID.startswith('loop') == False: cloudDivID = divID + '-cloud-' + str(random.randint(0, 1000)) cloudLinkID = divID + '-cloud-a-' + str(random.randint(0, 1000)) if total_page > 1 and form_dict['column'] != '1': html += '<br>' html += '<div id="' + cloudDivID + '" class="ref">' aCount = 0 alias = [rTitle] + alias html += 'Load Cloud Bookmark' for a in alias: aCount += 1 if aCount == 1: html += '<br>' script = "var postArgs = {name : 'bookmark', rID : '" + rID + "', rTitle : '" + a +"', check: 'false', fileName : '" + fileName + "', divID : '" + cloudDivID + "', originFileName : '" + form_dict['originFileName'] + "'};"; script += "$('#' + '" + cloudDivID +"').load('/extensions', postArgs, function(data) { });$('#' + '" + cloudDivID +"').html('Loading...');" html += '<a id="' + cloudLinkID+ '-' + str(aCount) + '" href="javascript:void(0);" onclick="' + script + '" style="font-size:10pt;">' + str(a) + '</a> ' html += '</div>' return html def getBookmarkItemCount(self, column): return Config.bookmark_page_item_count[int(column) - 1] def getPageScript(self, form_dict, page, nopage=False): script = 'var postArgs = {};'; #print form_dict for k, v in form_dict.items(): if k == 'defaultLinks' or k == 'screenWidth' or k =='screenHeight': script += 'postArgs["' + k + '"] = ' + str(form_dict[k]) + ';' else: script += 'postArgs["' + k + '"] = "' + form_dict[k] + '";' script += 'postArgs["page"] = ' + str(page) + ';' if nopage: script += 'postArgs["nopage"] = true;' script += 'requestExtension(postArgs, false);'; return script def match_item(self, jobj, rTitleList, notList=[]): if len(rTitleList) == 0: return False, '' if len(notList) > 0 and self.do_match_item(jobj, notList): return False, '' return self.do_match_item(jobj, rTitleList) def do_match_item(self, jobj, items): for rTitle in items: if rTitle.strip() == '': continue if self.containIgoncase(jobj['title'].strip(), rTitle.strip()): #print jobj['title'].strip() + ' ' + rTitle.strip() return True, rTitle.strip() if jobj.has_key('url') and len(rTitle) > 8: if self.containIgoncase(jobj['url'].strip(), rTitle.replace(' ', '').strip()): return True, '' if self.containIgoncase(jobj['url'].strip(), rTitle.replace(' ', '%20').strip()): return True, '' if self.containIgoncase(jobj['url'].strip(), rTitle.strip().replace(' ', '-')): return True, '' if self.containIgoncase(jobj['title'].strip(), rTitle.strip().replace(' ', '-')): return True, rTitle.strip().replace(' ', '-') return False, '' def gen_item(self, rID, ref_divID, count, jobj, moreOption, orginFilename, keywords=[], higtLightText=''): html = '' html += '<li><span>' + str(count) + '.</span>' url = '' if jobj.has_key('url'): url = jobj['url'] showText = self.utils.formatTitle(jobj['title'], Config.smart_link_br_len, keywords) if higtLightText != '': showText = self.utils.doHighLight(showText, higtLightText, appendValue=False) if url != '': html += '<p>' + self.utils.enhancedLink(url, self.utils.formatTitle(jobj['title'], Config.smart_link_br_len, keywords), module='bookmark', library=orginFilename, rid=rID, aid=rID, showText=showText) + self.utils.getIconHtml(url) else: html += '<p>' + showText + self.utils.getIconHtml(".dir", radius=False) #' > ' #if self.existChild(str(jobj['id'])): # html += ' > ' if moreOption: ref_divID += '-' + str(count) linkID = 'a-' + ref_divID[ref_divID.find('-') + 1 :] appendID = str(count) script = self.utils.genMoreEnginScript(linkID, ref_divID, "loop-b-" + rID.replace(' ', '-') + '-' + str(appendID) + '-' + str(jobj['id']), jobj['title'], url, '-', hidenEnginSection=Config.bookmark_hiden_engin_section) descHtml = '' if url != '': descHtml = self.utils.genDescHtml('url:' + url, Config.course_name_len, self.tag.tag_list) #print 'descHtml:' + descHtml html += self.utils.genMoreEnginHtml(linkID, script.replace("'", '"'), '...', ref_divID, '', False, descHtml=descHtml); html += '</p></li>' return html def genWebsiteHtml(self, key, orginFilename): html = '<ol>' count = 0 cookies = dict(unsafe='True') page = '' page_num = 6 page = 'http://www.xmarks.com/topic/' + key nextpage = '' page_count = 0 for i in range(0, page_num): page_count += 1 if nextpage != '': page = nextpage.replace('2', str(page_count)) print 'request ' + page r = requests.get(page, cookies=cookies) if r.status_code != 200: break soup = BeautifulSoup(r.text) #print r.text for div in soup.find_all('div', class_='content'): count += 1 title = self.colorkeyword(div.a.text, key) html += '<li><span>' + str(count) + '.</span><p>' + self.utils.enhancedLink(div.a['href'], title, module='xmarks', library=orginFilename) + self.utils.getIconHtml(div.a['href']) html += "</p></li>" nextDiv = soup.find('div', class_='site-pagination') if nextDiv != None and nextpage == '': nextpage = 'http://www.xmarks.com' + nextDiv.a['href'] if nextDiv == None: break html += "</ol>" return html def colorkeyword(self, text, keyword): text = text.replace(keyword.replace('%20', ' '), '<font style="color:red;">' + keyword + '</font>') text = text.replace(keyword.replace('%20', ' ').lower(), '<font style="color:red;">' + keyword.lower() + '</font>') return text def containIgoncase(self, leftData, rightData): if leftData.lower().find(rightData.lower()) != -1: return True elif rightData.endswith('s') and leftData.lower().find(rightData[0 : len(rightData) - 1].lower()) != -1: return True else: #if leftData.find('2017') != -1: # print leftData + ' - ' + rightData return False def containIgoncase2(self, leftData, rightDataList): for rightData in rightDataList: if leftData.lower().find(rightData.lower()) != -1: return True return False def check(self, form_dict): return True if os.path.exists('extensions/bookmark/data/chrome_bookmarks.json') == False: return False fileName = form_dict['fileName'].encode('utf8') rID = form_dict['rID'].encode('utf8') rTitle = form_dict['rTitle'].encode('utf8').replace('%20', ' ') nocache = False if form_dict.has_key('nocache'): nocache = form_dict['nocache'].encode('utf8') print 'rTitle:' + rTitle return fileName.find('exclusive') != -1 or self.rounter.has_key(rID) or rID.startswith('loop-h') or rID.startswith('loop-b') or self.containIgoncase(self.raw_data, rTitle) or self.containIgoncase2(self.raw_data, self.getAlias(rID, rTitle, form_dict['originFileName'], nocache)) or rTitle.find('.') != -1
class History(BaseExtension): raw_data = '' jobj_list = [] tag = Tag() """docstring for History""" def __init__(self): BaseExtension.__init__(self) self.utils = Utils() self.loadHistory() self.form_dict = None def loadHistory(self): self.updateHistory() if os.path.exists('extensions/history/data/chrome_history.json'): f = open('extensions/history/data/chrome_history.json', 'rU') self.raw_data = f.read() self.jobj_list = json.loads(self.raw_data) f.close() def updateHistory(self): if os.path.exists(Config.history_file_path): subprocess.check_output( "mv " + Config.history_file_path + " extensions/history/data/chrome_history.json", shell=True) self.loadHistory() def getAlias(self, rID, file, nocache): alias = '' use_cache = nocache == False record = self.utils.getRecord(rID.strip(), path=file, log=True, use_cache=use_cache) if record != None and record.get_id().strip() != '': ret = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag': 'alias'}) if ret != None: alias = ret.strip() print 'alias:' + alias if alias.find(',') != -1: return alias.split(',') elif alias != '': return [alias] else: return [] def excute(self, form_dict): self.form_dict = form_dict if form_dict.has_key('nocache'): nocache = form_dict['nocache'].encode('utf8') rTitle = form_dict['rTitle'].encode('utf8').replace('%20', ' ') rID = form_dict['rID'].encode('utf8') divID = form_dict['divID'].encode('utf8') alias = self.getAlias(rID.strip(), form_dict['originFileName'], nocache) self.updateHistory() html = '' if form_dict['column'] != '1' and form_dict.has_key( 'extension_count') and int(form_dict['extension_count']) > 12: html += '<br>' html += '<div class="ref"><ol>' count = 0 item_dict = {} for jobj in self.jobj_list: if self.match_item(jobj, [rTitle]) or self.match_item(jobj, alias): if item_dict.has_key(jobj['title'].strip()): continue item_dict[jobj['title'].strip()] = '' count += 1 html += self.gen_item(rID, divID, count, jobj, True, form_dict['originFileName']) html += "</ol></div>" if count == 0: html = '' return html def gen_item(self, rID, ref_divID, count, jobj, moreOption, orginFilename, keywords=[]): html = '' html += '<li><span>' + str(count) + '.</span>' url = '' if jobj.has_key('url'): url = jobj['url'] if url != '': html += '<p>' + self.utils.enhancedLink( url, self.utils.formatTitle(jobj['title'], Config.smart_link_br_len, keywords), module='history', library=orginFilename, rid=rID) + self.utils.getIconHtml(url) else: html += '<p>' + jobj['title'] + ' > ' #if self.existChild(str(jobj['id'])): # html += ' > ' if moreOption: ref_divID += '-' + str(count) linkID = 'a-' + ref_divID[ref_divID.find('-') + 1:] appendID = str(count) script = self.utils.genMoreEnginScript( linkID, ref_divID, "loop-h-" + rID.replace(' ', '-') + '-' + str(appendID) + '-' + str(jobj['id']), jobj['title'], url, '-', hidenEnginSection=Config.history_hiden_engin_section) descHtml = '' #if url != '': # descHtml = self.utils.genDescHtml('url:' + url, Config.course_name_len, self.tag.tag_list) #print 'descHtml:' + descHtml html += self.utils.genMoreEnginHtml(linkID, script.replace("'", '"'), '...', ref_divID, '', False, descHtml=descHtml) html += '</p></li>' return html def match_item(self, jobj, rTitleList): if len(rTitleList) == 0: return False for rTitle in rTitleList: if rTitle.strip() == '': continue if self.containIgoncase(jobj['title'].strip(), rTitle.strip()): #print jobj['title'].strip() + ' ' + rTitle.strip() return True return False def containIgoncase(self, leftData, rightData): return leftData.lower().find(rightData.lower()) != -1 def check(self, form_dict): self.updateHistory() rTitle = form_dict['rTitle'].encode('utf8').replace('%20', ' ') return os.path.exists('extensions/history/data/chrome_history.json' ) and self.containIgoncase( self.raw_data, rTitle)
class Edit(BaseExtension): def __init__(self): BaseExtension.__init__(self) self.utils = Utils() self.tag = Tag() def excute(self, form_dict): rID = form_dict['rID'].strip() rTitle = form_dict['rTitle'].strip() fileName = form_dict['originFileName'].strip() originFileName = form_dict['originFileName'].strip() divID = form_dict['divID'] if form_dict.has_key('textContent'): textContent = form_dict['textContent'] library = '' if form_dict['fileName'].strip().endswith('-library'): library = form_dict['fileName'][form_dict['fileName']. rfind('/') + 1:].strip() return self.editRecord(rID, self.utils.removeDoubleSpace( textContent.replace('\n', ' ')), originFileName, library=library) print fileName r = self.utils.getRecord(rID, path=fileName, use_cache=False) html = 'not found' areaID = rID.replace(' ', '-').replace('.', '-') + '-area' if r != None and r.get_id().strip() != '': column = str(form_dict['column']) rows = '25' cols = '75' if column == '1': rows = '45' cols = '99' elif column == '2': rows = '35' cols = '88' desc = r.get_describe().strip() html = '' print form_dict['extension_count'] print desc if int(form_dict['extension_count']) > 12: html += '<br>' html += '<textarea rows="' + rows + '" cols="' + cols + '" id="' + areaID + '" style="font-size: 13px; border-radius:5px 5px 5px 5px;" ' html += 'onfocus="setbg(' + "'" + areaID + "'," + "'#e5fff3');" + '" ' html += 'onblur="setbg(' + "'" + areaID + "'," + "'white');" + '">' start = 0 if rID.startswith('custom-'): html += 'id:' + r.get_id().strip() + '\n' html += '\ntitle:' + r.get_title().strip() + '\n' else: html += 'title:' + r.get_title().strip() + '\n' html += '\nurl:' + r.get_url().strip() + '\n' library = '' if form_dict['fileName'].strip().endswith('-library'): library = form_dict['fileName'][form_dict['fileName']. rfind('/') + 1:].strip() #print 'library:----' + library while start < len(desc): end = self.utils.next_pos(desc, start, int(cols), self.tag.get_tag_list(library), library=library) #print end line = desc[start:end].strip() print line if line.find(':') != -1 and line.find( ':') < 15 and line[0:1].islower(): line = '\n' + line html += line + '\n' if end < 0 or line.strip() == '': break start = end html += '</textarea>' script = "var text = $('#" + areaID + "'); console.log('', text[0].value);" script += "var postArgs = {name : 'edit', rID : '" + rID + "', rTitle : '" + rTitle + "', check: 'false', fileName : '" + fileName + "', divID : '" + divID + "', originFileName : '" + originFileName + "', textContent: text[0].value};" linkid = divID.replace('-edit', '').replace('div', 'a') script += "$.post('/extensions', postArgs, function(data) { window.location.href = window.location.href.replace('#', ''); });" # var a = document.getElementById('" + linkid + "'); var evnt = a['onclick']; evnt.call(a); html += '<br><button type="submit" id="edit_btn" hidefocus="true" onclick="' + script + '">submit</button>' return html def editRecord(self, rID, data, originFileName, library=''): print data record = Record(' | | | ' + data) newid = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag': 'id'}) if newid != None: newid = newid.strip() title = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, { 'tag': 'title', 'library': library }).strip() url = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, { 'tag': 'url', 'library': library }).strip() desc = data.replace('title:' + title, '').replace('url:' + url, '').strip() print rID print title print url print desc newline = '' if rID.startswith('custom-'): desc = desc.replace('id:' + newid, '').strip() newline = newid + ' | ' + title + ' | ' + url + ' | ' + desc + '\n' else: newline = rID + ' | ' + title + ' | ' + url + ' | ' + desc + '\n' print 'newline:' print newline if os.path.exists(originFileName): f = open(originFileName, 'rU') all_lines = [] for line in f.readlines(): if rID != line[0:line.find('|')].strip(): all_lines.append(line) else: print 'old line:' print line all_lines.append(newline) f.close() f = open(originFileName, 'w') if len(all_lines) > 0: for line in all_lines: f.write(line) else: f.write('') f.close() return 'refresh' return 'error' def check(self, form_dict): rID = form_dict['rID'].strip() return rID.startswith('loop') == False
class Edit(BaseExtension): def __init__(self): BaseExtension.__init__(self) self.utils = Utils() self.tag = Tag() def textFormatConvert(self, textContent): newTextContent = textContent.strip() textContentList = newTextContent.split('\n') if textContentList[0].endswith(':'): print textContentList group = '' convertText = '' accountTag = False accountType = '' accountValue = '' for item in textContentList: if item == '': continue if item.strip().endswith(':'): if self.utils.isAccountTag(item, self.tag.tag_list_account): accountTag = True if accountValue != '' and item != accountType + ':': convertText += accountType + '(' + accountValue[0 : len(accountValue) - 1] + '),\n' accountValue = '' accountType = '' accountType = item.replace(':', '') else: accountTag = False if accountValue != '': convertText += accountType + '(' + accountValue[0 : len(accountValue) - 1] + '),\n' accountValue = '' accountType = '' group = item[0 : item.find(':')] elif accountTag: accountValue += item + '*' else: key = '' if item.find(' - ') != -1: parts = item.split(' - ') key = parts[0] item = parts[1] else: key = item.replace('https', 'http').replace('http','').replace('://','').replace('www.', '') if key.find('.') != -1: key = key[0 : key.find('.')] convertText += key + '<' + group + '>' + '(' + item + '),\n' if accountValue != '': convertText += accountType + '(' + accountValue[0 : len(accountValue) - 1] + '),\n' convertText = convertText[0 : len(convertText) - 2].strip() + '\n' print convertText return convertText else: return textContent def excute(self, form_dict): print form_dict rID = form_dict['rID'].strip() rTitle = form_dict['rTitle'].replace('%20', ' ').strip() fileName = form_dict['fileName'].strip() originFileName = form_dict['originFileName'].strip() divID = form_dict['divID'] if divID.find('-history-') != -1 and divID.find('-content-') != -1: fileName = fileName[fileName.rfind('/') + 1 :] fileName = os.getcwd() + '/extensions/content/data/' + fileName + '-history-content' elif divID.find('-content-') != -1 and divID.find('-edit') != -1: originFileName = originFileName[originFileName.rfind('/') + 1 :] fileName = os.getcwd() + '/extensions/content/data/' + originFileName + '-content' library = form_dict['fileName'] if form_dict.has_key('textContent'): textContent = form_dict['textContent'] if rID.startswith('loop-h-') or rID.find('plugin') != -1: editedData = '' textContent = self.textFormatConvert(textContent) textContent = textContent.replace(',\n', '+') textContent = self.utils.removeDoubleSpace(textContent) textContent = textContent.replace(', ', '+') textContent = textContent.replace(',', '+') textContent = textContent.replace('\n', '') editedData = rTitle + '(' + textContent + ')' print 'editedData--->' + editedData #return historyRecord = None r = None print rID r, historyRecord = self.getRecordByHistory(rID, rTitle, fileName) if rID.find('plugin') != -1 and historyRecord == None: pid = rID.replace('custom-plugin-', '') if pid.find('-pg') != -1: pid = pid[0 : pid.find('-pg')] r = self.utils.getRecord(pid, path=fileName, use_cache=False) #print historyRecord.line #return 'error' if r != None: editRID = r.get_id().strip() resourceType = '' if historyRecord != None and editedData.find('category(') == -1: resourceType = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', historyRecord.line, {'tag' : 'category'}) if resourceType != None: resourceType = resourceType.strip() print 'editRID-->' + editRID if rID.find(editRID) != -1: newData = r.edit_desc_field2(self.utils, r, resourceType, rTitle, editedData, self.tag.get_tag_list(library), library=library) if newData != '': #print '--->' + newData result = self.editRecord(editRID, self.utils.removeDoubleSpace(newData), originFileName, library=library, resourceType=resourceType, divID=divID) return result return 'error' else: textContent = self.utils.removeDoubleSpace(textContent.replace(',\n ', ', ').replace('\n', ' ')) print textContent return self.editRecord(rID, textContent, originFileName, library=library, divID=divID) return 'error' column = str(form_dict['column']) print fileName r = None if rTitle.startswith('library/'): rTitle = rTitle.replace('==', '->') r = self.utils.crossref2Record(rTitle, rID='custom-plugin') print r.line fileName = 'db/' + rTitle[0 : rTitle.find('#')] originFileName = fileName rTitle = r.get_title().strip() else: r = self.utils.getRecord(rID, path=fileName, use_cache=False) html = 'not found' areaID = rID.replace(' ', '-').replace('.', '-') + '-area' if rID.startswith('loop-h-') or rID.find('plugin') != -1: if rID.find('plugin') == -1: r, historyRecord = self.getRecordByHistory(rID, rTitle, fileName) if r != None: #print r.line item = '' if rID.find('plugin') == -1: item = r.get_desc_field2(self.utils, rTitle, self.tag.get_tag_list(library), library=library) else: item = rTitle + '(' + self.utils.desc2ValueText(r.get_describe(), self.tag.get_tag_list(library)) + ')' #rID = rID.replace('custom-plugin-', '') #print 'item:' + item rID = rID.replace('-' + rTitle.lower().strip().replace(' ', '-'), '') if item != '': print '---->' + rID + '----' + item text = value = self.utils.getValueOrText(item, returnType='text') value = self.utils.getValueOrText(item, returnType='value') rows, cols = self.getRowsCols(column) html = '<div class="ref">' html += self.genTextareaHtml(rows, cols, areaID, value.replace('+', ',\n')) html += '<br>' html += self.genEditButton(areaID, rID, text, fileName, divID, originFileName) html += '</div>' return html return r.line if r != None and r.get_id().strip() != '': desc = r.get_describe().strip() html = '' print form_dict['extension_count'] print desc if int(form_dict['extension_count']) > 12: html += '<br>' start = 0 text = '' rows, cols = self.getRowsCols(column) if rID.startswith('custom-'): text += 'id:' + r.get_id().strip() + '\n' text += '\ntitle:' + r.get_title().strip() + '\n' else: text += 'title:' + r.get_title().strip() + '\n' text += '\nurl:' + r.get_url().strip() + '\n' #print 'library:----' + library while start < len(desc): end = self.utils.next_pos(desc, start, int(cols), self.tag.get_tag_list(library), library=library) #print end line = desc[start : end].strip() print line if line.find(':') != -1 and line.find(':') < 15 and line[0 : 1].islower(): line = '\n' + line line = line.replace(', ', ',\n ') text += line + '\n' if end < 0 or line.strip() == '': break start = end if form_dict.has_key('appendText') and form_dict['appendText'] != '': text += '\n' + form_dict['appendText'] + '\n' html += self.genTextareaHtml(rows, cols, areaID, text) html += '<br>' html += self.genEditButton(areaID, rID, rTitle, fileName, divID, originFileName) return html def getRecordByHistory(self, rid, title, fileName): path = fileName[0 : fileName.find('db/')] + 'extensions/history/data/' + fileName[fileName.rfind('/') + 1:] + '-history' if os.path.exists(path): print path print title rList = self.utils.getRecord(title, path=path, use_cache=False, accurate=False, matchType=2, return_all=True, log=True) if rList != None: record = None hRecord = None for historyRecord in rList: historyRID = historyRecord.get_id().strip() historyTitle = historyRecord.get_title().strip() print 'historyRID:' + historyRID + ' rid:' + rid print 'historyTitle:' + historyTitle + ' title:' + title if historyRID != '': if rid.find(historyRID) != -1: record = self.utils.getRecord(historyRID, path=fileName, use_cache=False) if title == historyTitle: return record, historyRecord else: hRecord = historyRecord return record, hRecord return None, None def genEditButton(self, areaID, rID, rTitle, fileName, divID, originFileName): script = "var text = $('#" + areaID + "'); console.log('', text[0].value);" script += "var postArgs = {name : 'edit', rID : '" + rID + "', rTitle : '" + rTitle +"', check: 'false', fileName : '" + fileName + "', divID : '" + divID + "', originFileName : '" + originFileName+ "', textContent: text[0].value};"; linkid = divID.replace('-edit', '').replace('div', 'a') if rID.find('plugin') != -1: script += "$.post('/extensions', postArgs, function(data) { \ a = document.getElementById('searchbox-a');\ if (a.text == 'less'){\ a.onclick();\ a.onclick();\ }\ });" else: script += "$.post('/extensions', postArgs, function(data) { \ console.log('refresh:' + data);\ if (data.indexOf('#') != -1) {\ dataList = data.split('#');\ if (dataList.length == 3) {\ refreshTab(dataList[2], dataList[1]);\ return;\ }\ window.location.href = window.location.href.replace('#', '');\ } else {\ window.location.href = window.location.href.replace('#', ''); \ }});" # var a = document.getElementById('" + linkid + "'); var evnt = a['onclick']; evnt.call(a); script += 'isEditing = false;' html = '<button type="submit" id="edit_btn" hidefocus="true" onclick="' + script + '">submit</button>' return html def getRowsCols(self, column): rows = '25' cols = '75' if column == '1': rows = '40' cols = '199' elif column == '2': rows = '35' cols = '88' return rows, cols def genTextareaHtml(self, rows, cols, areaID, text): html = '' html += '<textarea rows="' + rows + '" cols="' + cols + '" id="' + areaID + '" style="font-size: 13px; border-radius:5px 5px 5px 5px; font-family:San Francisco;color:#003399;white-space:pre-wrap" ' html += 'onfocus="setbg(' + "'" + areaID + "'," + "'#e5fff3');" + '" ' html += 'onblur="setbg(' + "'" + areaID + "'," + "'white');" + '">' html += text html += '</textarea>' return html def editRecord(self, rID, data, originFileName, library='', resourceType='', divID=''): print 'editRecord->' + data record = Record(' | | | ' + data) newid = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag' : 'id'}) if newid != None: newid = newid.strip() else: newid = rID title = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag' : 'title', 'library' : library}).strip() url = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag' : 'url', 'library' : library}).strip() desc = data.replace('id:' + newid, '').replace('title:' + title, '').replace('url:' + url, '').strip() if url == None: url = '' newRecord = Record(newid + ' | ' + title + ' | ' + url + ' | ' + desc) result = newRecord.editRecord(self.utils, rID, newRecord, originFileName, library, resourceType=resourceType) if result: print divID if divID.find('-history-') != -1: aid = divID[0 : divID.find('-history-')].strip() + '-a-' result = 'refresh#history#' + aid elif divID.find('-content-') != -1: aid = divID[0 : divID.find('-content-')].strip() + '-a-' result = 'refresh#content#' + aid else: result = 'refresh' else: result = 'error' print 'result--->' + result return result def check(self, form_dict): rID = form_dict['rID'].strip() return rID.startswith('loop') == False or rID.startswith('loop-h')
class Edit(BaseExtension): def __init__(self): BaseExtension.__init__(self) self.utils = Utils() self.tag = Tag() def excute(self, form_dict): print form_dict rID = form_dict['rID'].strip() rTitle = form_dict['rTitle'].replace('%20', ' ').strip() fileName = form_dict['fileName'].strip() originFileName = form_dict['originFileName'].strip() divID = form_dict['divID'] library = form_dict['fileName'] if form_dict.has_key('textContent'): textContent = form_dict['textContent'] if rID.startswith('loop-h'): editedData = '' textContent = textContent.replace(',\n', '+') textContent = self.utils.removeDoubleSpace(textContent) textContent = textContent.replace(', ', '+') textContent = textContent.replace(',', '+') textContent = textContent.replace('\n', '') editedData = rTitle + '(' + textContent + ')' print 'editedData--->' + editedData r, historyRecord = self.getRecordByHistory( rID, rTitle, fileName) if r != None: editRID = r.get_id().strip() resourceType = '' if historyRecord != None and editedData.find( 'category(') == -1: resourceType = self.utils.reflection_call( 'record', 'WrapRecord', 'get_tag_content', historyRecord.line, {'tag': 'category'}) if resourceType != None: resourceType = resourceType.strip() print 'editRID-->' + editRID if rID.find(editRID) != -1: newData = r.edit_desc_field2( self.utils, r, resourceType, rTitle, editedData, self.tag.get_tag_list(library), library=library) if newData != '': #print '--->' + newData result = self.editRecord( editRID, self.utils.removeDoubleSpace(newData), originFileName, library=library, resourceType=resourceType) if divID.find('-history-') != -1: aid = divID[0:divID.find('-history-')].strip( ) + '-a-' result = result + '#history#' + aid print 'result--->' + result return result return 'error' else: textContent = textContent.replace(',\n ', ', ') print textContent return self.editRecord(rID, self.utils.removeDoubleSpace( textContent.replace('\n', ' ')), originFileName, library=library) return 'error' column = str(form_dict['column']) print fileName r = self.utils.getRecord(rID, path=fileName, use_cache=False) html = 'not found' areaID = rID.replace(' ', '-').replace('.', '-') + '-area' if rID.startswith('loop-h'): r, historyRecord = self.getRecordByHistory(rID, rTitle, fileName) if r != None: #print r.line item = r.get_desc_field2(self.utils, rTitle, self.tag.get_tag_list(library), library=library) if item != '': print '---->' + item text = value = self.utils.getValueOrText(item, returnType='text') value = self.utils.getValueOrText(item, returnType='value') rows, cols = self.getRowsCols(column) html = self.genTextareaHtml(rows, cols, areaID, value.replace('+', ',\n')) html += '<br>' html += self.genEditButton(areaID, rID, text, fileName, divID, originFileName) return html return r.line if r != None and r.get_id().strip() != '': desc = r.get_describe().strip() html = '' print form_dict['extension_count'] print desc if int(form_dict['extension_count']) > 12: html += '<br>' start = 0 text = '' rows, cols = self.getRowsCols(column) if rID.startswith('custom-'): text += 'id:' + r.get_id().strip() + '\n' text += '\ntitle:' + r.get_title().strip() + '\n' else: text += 'title:' + r.get_title().strip() + '\n' text += '\nurl:' + r.get_url().strip() + '\n' #print 'library:----' + library while start < len(desc): end = self.utils.next_pos(desc, start, int(cols), self.tag.get_tag_list(library), library=library) #print end line = desc[start:end].strip() print line if line.find(':') != -1 and line.find( ':') < 15 and line[0:1].islower(): line = '\n' + line line = line.replace(', ', ',\n ') text += line + '\n' if end < 0 or line.strip() == '': break start = end html += self.genTextareaHtml(rows, cols, areaID, text) html += '<br>' html += self.genEditButton(areaID, rID, rTitle, fileName, divID, originFileName) return html def getRecordByHistory(self, rid, title, fileName): path = fileName[0:fileName. find('db/')] + 'extensions/history/data/' + fileName[ fileName.rfind('/') + 1:] + '-history' print path print title rList = self.utils.getRecord(title, path=path, use_cache=False, accurate=False, matchType=2, return_all=True, log=True) for historyRecord in rList: historyRID = historyRecord.get_id().strip() print 'historyRID:' + historyRID + ' rid:' + rid if historyRID != '' and rid.find(historyRID) != -1: record = self.utils.getRecord(historyRID, path=fileName, use_cache=False) return record, historyRecord return None def genEditButton(self, areaID, rID, rTitle, fileName, divID, originFileName): script = "var text = $('#" + areaID + "'); console.log('', text[0].value);" script += "var postArgs = {name : 'edit', rID : '" + rID + "', rTitle : '" + rTitle + "', check: 'false', fileName : '" + fileName + "', divID : '" + divID + "', originFileName : '" + originFileName + "', textContent: text[0].value};" linkid = divID.replace('-edit', '').replace('div', 'a') script += "$.post('/extensions', postArgs, function(data) { \ console.log('refresh:' + data);\ if (data.indexOf('#') != -1) {\ dataList = data.split('#');\ if (dataList.length == 3) {\ if (dataList[1] == 'history') {\ refreshTab(dataList[2], 'history');\ return;\ }\ }\ window.location.href = window.location.href.replace('#', '');\ } else {\ window.location.href = window.location.href.replace('#', ''); \ }});" # var a = document.getElementById('" + linkid + "'); var evnt = a['onclick']; evnt.call(a); html = '<button type="submit" id="edit_btn" hidefocus="true" onclick="' + script + '">submit</button>' return html def getRowsCols(self, column): rows = '25' cols = '75' if column == '1': rows = '45' cols = '199' elif column == '2': rows = '35' cols = '88' return rows, cols def genTextareaHtml(self, rows, cols, areaID, text): html = '' html += '<textarea rows="' + rows + '" cols="' + cols + '" id="' + areaID + '" style="font-size: 13px; border-radius:5px 5px 5px 5px; font-family:San Francisco;color:#003399;white-space:pre-wrap" ' html += 'onfocus="setbg(' + "'" + areaID + "'," + "'#e5fff3');" + '" ' html += 'onblur="setbg(' + "'" + areaID + "'," + "'white');" + '">' html += text html += '</textarea>' return html def editRecord(self, rID, data, originFileName, library='', resourceType=''): print data record = Record(' | | | ' + data) newid = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, {'tag': 'id'}) if newid != None: newid = newid.strip() else: newid = rID title = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, { 'tag': 'title', 'library': library }).strip() url = self.utils.reflection_call('record', 'WrapRecord', 'get_tag_content', record.line, { 'tag': 'url', 'library': library }).strip() desc = data.replace('id:' + newid, '').replace('title:' + title, '').replace('url:' + url, '').strip() if url == None: url = '' newRecord = Record(newid + ' | ' + title + ' | ' + url + ' | ' + desc) result = newRecord.editRecord(self.utils, rID, newRecord, originFileName, library, resourceType=resourceType) if result: return 'refresh' return 'error' def check(self, form_dict): rID = form_dict['rID'].strip() return rID.startswith('loop') == False or rID.startswith('loop-h')