raw
logotron_genesis.kv     1 #!/usr/bin/python
logotron_genesis.kv 2
logotron_genesis.kv 3 ##############################################################################
logotron_genesis.kv 4 import ConfigParser, sys
logotron_genesis.kv 5 import psycopg2, psycopg2.extras
logotron_genesis.kv 6 import psycopg2.extensions
logotron_genesis.kv 7 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
logotron_genesis.kv 8 psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
logotron_genesis.kv 9 import time
logotron_genesis.kv 10 import datetime
logotron_genesis.kv 11 from datetime import timedelta
logotron_genesis.kv 12 import sys
logotron_genesis.kv 13 reload(sys)
logotron_genesis.kv 14 sys.setdefaultencoding('utf8')
logotron_genesis.kv 15 import os
logotron_genesis.kv 16 import threading
logotron_genesis.kv 17 import re
logotron_genesis.kv 18 from datetime import datetime
logotron_genesis.kv 19 from urlparse import urljoin
raw_line_export.kv 20 from flask import Flask, request, session, url_for, redirect, Response, \
logotron_genesis.kv 21 render_template, abort, g, flash, _app_ctx_stack, make_response, \
logotron_genesis.kv 22 jsonify
logotron_genesis.kv 23 from flask import Flask
logotron_genesis.kv 24 ##############################################################################
logotron_genesis.kv 25
logotron_genesis.kv 26 ##############################################################################
logotron_genesis.kv 27 # Single mandatory arg: config file path
hide_inactive.kv 28
logotron_genesis.kv 29 if len(sys.argv[1:]) != 1:
hide_inactive.kv 30 # Default path for WSGI use (change to yours) :
hide_inactive.kv 31 config_path = "/home/nsabot/logger/nsabot.conf"
hide_inactive.kv 32 else:
hide_inactive.kv 33 # Read Config from given conf file
hide_inactive.kv 34 config_path = sys.argv[1]
logotron_genesis.kv 35
hide_inactive.kv 36 #config_path = os.path.abspath(config_path)
logotron_genesis.kv 37 cfg = ConfigParser.ConfigParser()
logotron_genesis.kv 38 cfg.readfp(open(config_path))
logotron_genesis.kv 39
logotron_genesis.kv 40 try:
logotron_genesis.kv 41 # IRCism:
logotron_genesis.kv 42 Nick = cfg.get("irc", "nick")
logotron_genesis.kv 43 Channels = [x.strip() for x in cfg.get("irc", "chans").split(',')]
logotron_genesis.kv 44 Bots = [x.strip() for x in cfg.get("logotron", "bots").split(',')]
logotron_genesis.kv 45 Bots.append(Nick) # Add our own bot to the bot list
logotron_genesis.kv 46 # DBism:
logotron_genesis.kv 47 DB_Name = cfg.get("db", "db_name")
logotron_genesis.kv 48 DB_User = cfg.get("db", "db_user")
raw_line_export.kv 49 DB_DEBUG = int(cfg.get("db", "db_debug"))
logotron_genesis.kv 50 # Logism:
logotron_genesis.kv 51 Base_URL = cfg.get("logotron", "base_url")
logotron_genesis.kv 52 Era = int(cfg.get("logotron", "era"))
raw_line_export.kv 53 DEBUG = int(cfg.get("logotron", "www_dbg"))
raw_line_export.kv 54 Max_Raw_Ln = int(cfg.get("logotron", "max_raw"))
hide_inactive.kv 55 Days_Hide = int(cfg.get("logotron", "days_hide"))
logotron_genesis.kv 56 # WWW:
logotron_genesis.kv 57 WWW_Port = int(cfg.get("logotron", "www_port"))
logotron_genesis.kv 58
logotron_genesis.kv 59 except Exception as e:
logotron_genesis.kv 60 print "Invalid config: ", e
logotron_genesis.kv 61 exit(1)
logotron_genesis.kv 62
logotron_genesis.kv 63 ##############################################################################
logotron_genesis.kv 64
logotron_genesis.kv 65 ##############################################################################
logotron_genesis.kv 66 ### Knobs not made into config yet ###
logotron_genesis.kv 67 Default_Chan = Channels[0]
logotron_genesis.kv 68 Min_Query_Length = 3
logotron_genesis.kv 69 Max_Search_Results = 1000
logotron_genesis.kv 70
logotron_genesis.kv 71 ## Format for Date in Log Lines
logotron_genesis.kv 72 Date_Short_Format = "%Y-%m-%d"
logotron_genesis.kv 73 ##############################################################################
logotron_genesis.kv 74
logotron_genesis.kv 75 app = Flask(__name__)
logotron_genesis.kv 76 app.config.from_object(__name__)
logotron_genesis.kv 77
logotron_genesis.kv 78 def get_db():
logotron_genesis.kv 79 db = getattr(g, 'db', None)
logotron_genesis.kv 80 if db is None:
logotron_genesis.kv 81 db = g.db = psycopg2.connect("dbname=%s user=%s" % (DB_Name, DB_User))
logotron_genesis.kv 82 return db
logotron_genesis.kv 83
logotron_genesis.kv 84 def close_db():
logotron_genesis.kv 85 if hasattr(g, 'db'):
logotron_genesis.kv 86 g.db.close()
logotron_genesis.kv 87
logotron_genesis.kv 88 @app.before_request
logotron_genesis.kv 89 def before_request():
logotron_genesis.kv 90 g.db = get_db()
logotron_genesis.kv 91
logotron_genesis.kv 92 @app.teardown_request
logotron_genesis.kv 93 def teardown_request(exception):
logotron_genesis.kv 94 close_db()
logotron_genesis.kv 95
logotron_genesis.kv 96 def query_db(query, args=(), one=False):
logotron_genesis.kv 97 cur = get_db().cursor(cursor_factory=psycopg2.extras.RealDictCursor)
logotron_genesis.kv 98 if (DB_DEBUG): print "query: '{0}'".format(query)
logotron_genesis.kv 99 cur.execute(query, args)
logotron_genesis.kv 100 rv = cur.fetchone() if one else cur.fetchall()
logotron_genesis.kv 101 if (DB_DEBUG): print "query res: '{0}'".format(rv)
logotron_genesis.kv 102 return rv
logotron_genesis.kv 103
logotron_genesis.kv 104 ##############################################################################
logotron_genesis.kv 105
logotron_genesis.kv 106 ## All eggogs redirect to main page
logotron_genesis.kv 107 @app.errorhandler(404)
logotron_genesis.kv 108 def page_not_found(error):
logotron_genesis.kv 109 return redirect(url_for('log'))
logotron_genesis.kv 110
logotron_genesis.kv 111 ##############################################################################
logotron_genesis.kv 112
logotron_genesis.kv 113 html_escape_table = {
logotron_genesis.kv 114 "&": "&",
logotron_genesis.kv 115 '"': """,
logotron_genesis.kv 116 "'": "'",
logotron_genesis.kv 117 ">": ">",
logotron_genesis.kv 118 "<": "&lt;",
logotron_genesis.kv 119 }
logotron_genesis.kv 120
logotron_genesis.kv 121 def html_escape(text):
logotron_genesis.kv 122 return "".join(html_escape_table.get(c,c) for c in text)
logotron_genesis.kv 123
logotron_genesis.kv 124 ##############################################################################
logotron_genesis.kv 125
logotron_genesis.kv 126 ## Get base URL
logotron_genesis.kv 127 def get_base():
logotron_genesis.kv 128 if DEBUG:
logotron_genesis.kv 129 return request.host_url
logotron_genesis.kv 130 return Base_URL
logotron_genesis.kv 131
logotron_genesis.kv 132
logotron_genesis.kv 133 # Get perma-URL corresponding to given log line
logotron_genesis.kv 134 def line_url(l):
logotron_genesis.kv 135 return "{0}log/{1}/{2}#{3}".format(get_base(),
logotron_genesis.kv 136 l['chan'],
logotron_genesis.kv 137 l['t'].strftime(Date_Short_Format),
logotron_genesis.kv 138 l['idx'])
logotron_genesis.kv 139
hide_inactive.kv 140 def gen_chanlist(selected_chan, show_all_chans=False):
logotron_genesis.kv 141 # Get current time
logotron_genesis.kv 142 now = datetime.now()
hide_inactive.kv 143 # Data for channel display :
hide_inactive.kv 144 chan_tbl = {}
logotron_genesis.kv 145 for chan in Channels:
hide_inactive.kv 146 chan_tbl[chan] = {}
hide_inactive.kv 147 chan_tbl[chan]['show'] = False
hide_inactive.kv 148
logotron_genesis.kv 149 chan_formed = chan
logotron_genesis.kv 150 if chan == selected_chan:
logotron_genesis.kv 151 chan_formed = "<span class='highlight'>" + chan + "</span>"
hide_inactive.kv 152
hide_inactive.kv 153 chan_tbl[chan]['link'] = """<a href="{0}log/{1}"><b>{2}</b></a>""".format(
logotron_genesis.kv 154 get_base(), chan, chan_formed)
hide_inactive.kv 155
logotron_genesis.kv 156 last_time = query_db(
logotron_genesis.kv 157 '''select t, idx from loglines where chan=%s
logotron_genesis.kv 158 and idx = (select max(idx) from loglines where chan=%s) ;''',
logotron_genesis.kv 159 [chan, chan], one=True)
logotron_genesis.kv 160
logotron_genesis.kv 161 last_time_txt = ""
hide_inactive.kv 162 time_field = ""
logotron_genesis.kv 163 if last_time != None:
logotron_genesis.kv 164 span = (now - last_time['t'])
logotron_genesis.kv 165 days = span.days
logotron_genesis.kv 166 hours = span.seconds/3600
logotron_genesis.kv 167 minutes = (span.seconds%3600)/60
logotron_genesis.kv 168
logotron_genesis.kv 169 if days != 0:
logotron_genesis.kv 170 last_time_txt += '%dd ' % days
logotron_genesis.kv 171 if hours != 0:
logotron_genesis.kv 172 last_time_txt += '%dh ' % hours
logotron_genesis.kv 173 if minutes != 0:
logotron_genesis.kv 174 last_time_txt += '%dm' % minutes
hide_inactive.kv 175
hide_inactive.kv 176 time_field = """<i><a href="{0}log/{1}/{2}#{3}">{4}</a></i>""".format(
logotron_genesis.kv 177 get_base(),
logotron_genesis.kv 178 chan,
logotron_genesis.kv 179 last_time['t'].strftime(Date_Short_Format),
logotron_genesis.kv 180 last_time['idx'],
logotron_genesis.kv 181 last_time_txt)
logotron_genesis.kv 182
hide_inactive.kv 183 if (days <= Days_Hide) or (chan == selected_chan) or show_all_chans:
hide_inactive.kv 184 chan_tbl[chan]['show'] = True
logotron_genesis.kv 185
hide_inactive.kv 186 chan_tbl[chan]['time'] = time_field
hide_inactive.kv 187
hide_inactive.kv 188 ## Generate channel selector bar :
hide_inactive.kv 189 s = """<table align="center" class="chantable"><tr>"""
hide_inactive.kv 190 for chan in Channels:
hide_inactive.kv 191 if chan_tbl[chan]['show']:
hide_inactive.kv 192 s += """<th>{0}</th>""".format(chan_tbl[chan]['link'])
hide_inactive.kv 193 s += "</tr><tr>"
hide_inactive.kv 194 ## Generate last-activ. links for above :
hide_inactive.kv 195 for chan in Channels:
hide_inactive.kv 196 if chan_tbl[chan]['show']:
hide_inactive.kv 197 s += """<td>{0}</td>""".format(chan_tbl[chan]['time'])
hide_inactive.kv 198 # wrap up:
search_all_chans.kv 199 s += "</tr></table>"
logotron_genesis.kv 200 return s
logotron_genesis.kv 201
logotron_genesis.kv 202
logotron_genesis.kv 203 # Make above callable from inside htm templater:
logotron_genesis.kv 204 app.jinja_env.globals.update(gen_chanlist=gen_chanlist)
logotron_genesis.kv 205
logotron_genesis.kv 206
logotron_genesis.kv 207 # HTML Tag Regex
logotron_genesis.kv 208 tag_regex = re.compile("(<[^>]+>)")
logotron_genesis.kv 209
logotron_genesis.kv 210
logotron_genesis.kv 211 # Find the segments of a block of text which constitute HTML tags
logotron_genesis.kv 212 def get_link_intervals(str):
logotron_genesis.kv 213 links = []
logotron_genesis.kv 214 span = []
logotron_genesis.kv 215 for match in tag_regex.finditer(str):
logotron_genesis.kv 216 span = match.span()
logotron_genesis.kv 217 links += [span]
logotron_genesis.kv 218 return links
logotron_genesis.kv 219
logotron_genesis.kv 220
logotron_genesis.kv 221 # Highlight all matched tokens in given text
logotron_genesis.kv 222 def highlight_matches(strings, text):
logotron_genesis.kv 223 e = '(' + ('|'.join(strings)) + ')'
logotron_genesis.kv 224 return re.sub(e,
logotron_genesis.kv 225 r"""<span class='highlight'>\1</span>""",
logotron_genesis.kv 226 text,
logotron_genesis.kv 227 flags=re.I)
logotron_genesis.kv 228
logotron_genesis.kv 229
logotron_genesis.kv 230 # Highlight matched tokens in the display of a search result logline,
logotron_genesis.kv 231 # but leave HTML tags alone
logotron_genesis.kv 232 def highlight_text(strings, text):
logotron_genesis.kv 233 result = ""
logotron_genesis.kv 234 last = 0
logotron_genesis.kv 235 for i in get_link_intervals(text):
logotron_genesis.kv 236 i_start, i_end = i
logotron_genesis.kv 237 result += highlight_matches(strings, text[last:i_start])
logotron_genesis.kv 238 result += text[i_start:i_end] # the HTML tag, leave it alone
logotron_genesis.kv 239 last = i_end
logotron_genesis.kv 240 result += highlight_matches(strings, text[last:]) # last block
logotron_genesis.kv 241 return result
logotron_genesis.kv 242
logotron_genesis.kv 243
logotron_genesis.kv 244 # Regexps used in format_logline:
uniturds_etc.kv 245 boxlinks_re = re.compile(
uniturds_etc.kv 246 '\[\s*<a href="(http[^ \[\]]+)"[^>]*>[^ <]+</a>\s*\]\[([^\[\]]+)\]')
uniturds_etc.kv 247
logotron_genesis.kv 248 stdlinks_re = re.compile('(http[^ \[\]]+)')
logotron_genesis.kv 249
logotron_genesis.kv 250
logotron_genesis.kv 251 ## Format given log line for display
search_all_chans.kv 252 def format_logline(l, highlights = [], select=[], showchan=False):
logotron_genesis.kv 253 payload = html_escape(l['payload'])
logotron_genesis.kv 254
logotron_genesis.kv 255 # Format ordinary links:
uniturds_etc.kv 256 payload = re.sub(stdlinks_re,
uniturds_etc.kv 257 r'<a href="\1" target=\'_blank\'>\1</a>', payload)
logotron_genesis.kv 258
logotron_genesis.kv 259 # Now also format [link][text] links :
uniturds_etc.kv 260 payload = re.sub(boxlinks_re,
uniturds_etc.kv 261 r'<a href="\1" target=\'_blank\'>\2</a>', payload)
logotron_genesis.kv 262
logotron_genesis.kv 263 # If this is a search result, illuminate the matched strings:
logotron_genesis.kv 264 if highlights != []:
logotron_genesis.kv 265 payload = highlight_text(highlights, payload)
logotron_genesis.kv 266
logotron_genesis.kv 267 bot = ""
logotron_genesis.kv 268 if l['speaker'] in Bots:
logotron_genesis.kv 269 bot = " bot"
logotron_genesis.kv 270
multsel_and_datef... 271 # default -- no selection
multsel_and_datef... 272 dclass = l['speaker']
multsel_and_datef... 273
multsel_and_datef... 274 # If selection is given:
multsel_and_datef... 275 if select != []:
multsel_and_datef... 276 ss, se = select
multsel_and_datef... 277 if ss <= l['idx'] <= se:
multsel_and_datef... 278 dclass = "highlight"
multsel_and_datef... 279
sept_fixes.kv 280 speaker = l['speaker']
sept_fixes.kv 281 separator = ":"
sept_fixes.kv 282
search_all_chans.kv 283 if showchan:
search_all_chans.kv 284 speaker = '<small>(' + l['chan'] + ')</small> ' + speaker
search_all_chans.kv 285
sept_fixes.kv 286 # If 'action', annotate:
sept_fixes.kv 287 if l['self']:
sept_fixes.kv 288 separator = ""
sept_fixes.kv 289 payload = "<i>" + payload + "</i>"
sept_fixes.kv 290 speaker = "<i>" + speaker + "</i>"
sept_fixes.kv 291
logotron_genesis.kv 292 # HTMLize the given line :
multsel_and_datef... 293 s = ("<div id='{0}' class='{6}{5}'>"
logotron_genesis.kv 294 "<a class='nick' title='{2}'"
sept_errata.kv 295 " href=\"{3}\">{1}</a>{7} {4}</div>").format(l['idx'],
sept_fixes.kv 296 speaker,
sept_fixes.kv 297 l['t'],
sept_fixes.kv 298 line_url(l),
sept_fixes.kv 299 payload,
sept_fixes.kv 300 bot,
sept_fixes.kv 301 dclass,
sept_fixes.kv 302 separator)
logotron_genesis.kv 303 return s
logotron_genesis.kv 304
logotron_genesis.kv 305 # Make above callable from inside htm templater:
logotron_genesis.kv 306 app.jinja_env.globals.update(format_logline=format_logline)
logotron_genesis.kv 307
logotron_genesis.kv 308
uniturds_etc.kv 309 @app.route('/rnd/<chan>')
uniturds_etc.kv 310 def rnd(chan):
uniturds_etc.kv 311 # Handle rubbish chan:
uniturds_etc.kv 312 if chan not in Channels:
uniturds_etc.kv 313 return redirect(url_for('log'))
uniturds_etc.kv 314
uniturds_etc.kv 315 rnd_line = query_db(
uniturds_etc.kv 316 '''select * from loglines where chan=%s
uniturds_etc.kv 317 order by random() limit 1 ;''',
uniturds_etc.kv 318 [chan], one=True)
uniturds_etc.kv 319
uniturds_etc.kv 320 return redirect(line_url(rnd_line))
uniturds_etc.kv 321
uniturds_etc.kv 322
logotron_genesis.kv 323 @app.route('/log/<chan>/<date>')
logotron_genesis.kv 324 @app.route('/log/<chan>', defaults={'date': None})
logotron_genesis.kv 325 @app.route('/log/', defaults={'chan': Default_Chan, 'date': None})
logotron_genesis.kv 326 @app.route('/log', defaults={'chan': Default_Chan, 'date': None})
logotron_genesis.kv 327 def log(chan, date):
logotron_genesis.kv 328 # Handle rubbish chan:
logotron_genesis.kv 329 if chan not in Channels:
logotron_genesis.kv 330 return redirect(url_for('log'))
logotron_genesis.kv 331
multsel_and_datef... 332 # Get possible selection start and end
multsel_and_datef... 333 sel_start = request.args.get('ss', default = 0, type = int)
multsel_and_datef... 334 sel_end = request.args.get('se', default = 0, type = int)
uniturds_etc.kv 335
uniturds_etc.kv 336 # Get possible 'reverse gear'
uniturds_etc.kv 337 rev = request.args.get('rev', default = 0, type = int)
hide_inactive.kv 338
hide_inactive.kv 339 # Get possible 'show all'
hide_inactive.kv 340 show_all = request.args.get('all', default = 0, type = int)
multsel_and_datef... 341
logotron_genesis.kv 342 # Get current time
logotron_genesis.kv 343 now = datetime.now()
logotron_genesis.kv 344
logotron_genesis.kv 345 # Whether we are viewing 'current' tail
logotron_genesis.kv 346 tail = False
logotron_genesis.kv 347
logotron_genesis.kv 348 # If viewing 'current' log:
logotron_genesis.kv 349 if date == None:
logotron_genesis.kv 350 date = now.strftime(Date_Short_Format)
logotron_genesis.kv 351 tail = True
logotron_genesis.kv 352
logotron_genesis.kv 353 # Parse given date, and redirect to default log if rubbish:
logotron_genesis.kv 354 try:
logotron_genesis.kv 355 day_start = datetime.strptime(date, Date_Short_Format)
logotron_genesis.kv 356 except Exception, e:
logotron_genesis.kv 357 return redirect(url_for('log'))
logotron_genesis.kv 358
logotron_genesis.kv 359 # Determine the end of the interval being shown
logotron_genesis.kv 360 day_end = day_start + timedelta(days=1)
logotron_genesis.kv 361
multsel_and_datef... 362 # Enable 'tail' is day_end is after end of current day
rle_errata.kv 363 if day_end > now:
multsel_and_datef... 364 tail = True
navbar_date_auto.kv 365
logotron_genesis.kv 366 # Get the loglines from DB
logotron_genesis.kv 367 lines = query_db(
logotron_genesis.kv 368 '''select * from loglines where chan=%s
logotron_genesis.kv 369 and t between %s and %s order by idx asc;''',
logotron_genesis.kv 370 [chan, day_start, day_end], one=False)
logotron_genesis.kv 371
uniturds_etc.kv 372 # Optional 'reverse gear' knob:
uniturds_etc.kv 373 if rev == 1:
uniturds_etc.kv 374 lines.reverse()
navbar_date_auto.kv 375
navbar_date_auto.kv 376 # Generate navbar for the given date:
navbar_date_auto.kv 377 prev_day = ""
navbar_date_auto.kv 378 next_day = ""
navbar_date_auto.kv 379
navbar_date_auto.kv 380 prev_t = query_db(
navbar_date_auto.kv 381 '''select t from loglines where chan=%s
navbar_date_auto.kv 382 and t < %s order by idx desc limit 1;''',
navbar_date_auto.kv 383 [chan, day_start], one=True)
navbar_date_auto.kv 384
navbar_date_auto.kv 385 if prev_t != None:
navbar_date_auto.kv 386 prev_day = prev_t['t'].strftime(Date_Short_Format)
navbar_date_auto.kv 387
navbar_date_auto.kv 388 if not tail:
navbar_date_auto.kv 389 next_t = query_db(
navbar_date_auto.kv 390 '''select t from loglines where chan=%s
navbar_date_auto.kv 391 and t > %s order by idx asc limit 1;''',
navbar_date_auto.kv 392 [chan, day_end], one=True)
navbar_date_auto.kv 393
navbar_date_auto.kv 394 if next_t != None:
navbar_date_auto.kv 395 next_day = next_t['t'].strftime(Date_Short_Format)
navbar_date_auto.kv 396
logotron_genesis.kv 397 # Return the HTMLized text
logotron_genesis.kv 398 return render_template('log.html',
logotron_genesis.kv 399 chan = chan,
logotron_genesis.kv 400 loglines = lines,
multsel_and_datef... 401 sel = (sel_start, sel_end),
logotron_genesis.kv 402 date = date,
navbar_date_auto.kv 403 prev_day = prev_day,
navbar_date_auto.kv 404 next_day = next_day,
hide_inactive.kv 405 rev = not rev,
hide_inactive.kv 406 show_all = show_all,
hide_inactive.kv 407 idle_day = Days_Hide)
logotron_genesis.kv 408
logotron_genesis.kv 409
raw_line_export.kv 410 @app.route('/log-raw/<chan>')
raw_line_export.kv 411 def rawlog(chan):
raw_line_export.kv 412 res = ""
raw_line_export.kv 413
raw_line_export.kv 414 # Handle rubbish chan:
raw_line_export.kv 415 if chan not in Channels:
raw_line_export.kv 416 return Response("EGGOG: No such Channel!", mimetype='text/plain')
raw_line_export.kv 417
raw_line_export.kv 418 # Get start and end indices:
raw_line_export.kv 419 idx_start = request.args.get('istart', default = 0, type = int)
raw_line_export.kv 420 idx_end = request.args.get('iend', default = 0, type = int)
raw_line_export.kv 421
raw_line_export.kv 422 # Malformed bounds?
raw_line_export.kv 423 if idx_start > idx_end:
raw_line_export.kv 424 return Response("EGGOG: Start must precede End!",
raw_line_export.kv 425 mimetype='text/plain')
raw_line_export.kv 426
raw_line_export.kv 427 # Demanded too many in one burst ?
raw_line_export.kv 428 if (idx_end - idx_start) > Max_Raw_Ln :
raw_line_export.kv 429 return Response("EGGOG: May request Max. of %s Lines !" % Max_Raw_Ln,
raw_line_export.kv 430 mimetype='text/plain')
raw_line_export.kv 431
raw_line_export.kv 432 # Get the loglines from DB
raw_line_export.kv 433 lines = query_db(
raw_line_export.kv 434 '''select * from loglines where chan=%s
raw_line_export.kv 435 and idx between %s and %s order by idx asc;''',
raw_line_export.kv 436 [chan, idx_start, idx_end], one=False)
raw_line_export.kv 437
raw_line_export.kv 438 # Retrieve raw lines in classical Phf format:
raw_line_export.kv 439 for l in lines:
raw_line_export.kv 440 action = ""
raw_line_fix.kv 441 speaker = "%s;" % l['speaker']
raw_line_export.kv 442 if l['self']:
raw_line_export.kv 443 action = "*;"
raw_line_fix.kv 444 speaker = "%s " % l['speaker']
raw_line_fix.kv 445 res += "%s;%s;%s%s%s\n" % (l['idx'],
raw_line_export.kv 446 l['t'].strftime('%s'),
raw_line_export.kv 447 action,
raw_line_fix.kv 448 speaker,
raw_line_export.kv 449 l['payload'])
raw_line_export.kv 450
raw_line_export.kv 451 # Return plain text:
raw_line_export.kv 452 return Response(res, mimetype='text/plain')
raw_line_export.kv 453
logotron_genesis.kv 454
logotron_genesis.kv 455 Name_Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
logotron_genesis.kv 456
logotron_genesis.kv 457 def sanitize_speaker(s):
logotron_genesis.kv 458 return "".join([ch for ch in s if ch in Name_Chars])
logotron_genesis.kv 459
logotron_genesis.kv 460
logotron_genesis.kv 461 def re_escape(s):
logotron_genesis.kv 462 return re.sub(r"[(){}\[\].*?|^$\\+-]", r"\\\g<0>", s)
logotron_genesis.kv 463
logotron_genesis.kv 464 # Search knob. Supports 'chan' parameter.
logotron_genesis.kv 465 @app.route('/log-search')
logotron_genesis.kv 466 def logsearch():
logotron_genesis.kv 467 # The query params:
logotron_genesis.kv 468 chan = request.args.get('chan', default = Default_Chan, type = str)
logotron_genesis.kv 469 query = request.args.get('q', default = '', type = str)
logotron_genesis.kv 470 # page_num = request.args.get('page', default = 0, type = int)
logotron_genesis.kv 471
search_all_chans.kv 472 # channels to search in
search_all_chans.kv 473 chans = []
logotron_genesis.kv 474
search_all_chans.kv 475 # whether to indicate chan per log line
search_all_chans.kv 476 showchan = False
search_all_chans.kv 477
search_all_chans.kv 478 if chan == 'all':
search_all_chans.kv 479 # search in all logged channels
search_all_chans.kv 480 chans = Channels
search_all_chans.kv 481 legend = "<i>all logged channels</i>"
search_all_chans.kv 482 showchan = True
search_all_chans.kv 483 else:
search_all_chans.kv 484 # Handle possible rubbish chan:
search_all_chans.kv 485 if chan not in Channels:
search_all_chans.kv 486 return redirect(url_for('log'))
search_all_chans.kv 487 else:
search_all_chans.kv 488 # search in selected channel only
search_all_chans.kv 489 chans = [chan]
search_all_chans.kv 490 legend = chan
search_all_chans.kv 491
logotron_genesis.kv 492 nres = 0
logotron_genesis.kv 493 searchres = []
logotron_genesis.kv 494 tokens_orig = []
logotron_genesis.kv 495 search_head = "Query is too short!"
logotron_genesis.kv 496 # Forbid query that is too short:
logotron_genesis.kv 497 if len(query) >= Min_Query_Length:
logotron_genesis.kv 498 # Get the search tokens to use:
shlex_removal.kv 499 tokens = query.split()
logotron_genesis.kv 500 tokens_standard = []
logotron_genesis.kv 501 from_users = []
logotron_genesis.kv 502
logotron_genesis.kv 503 # separate out "from:foo" tokens and ordinary:
logotron_genesis.kv 504 for t in tokens:
logotron_genesis.kv 505 if t.startswith("from:") or t.startswith("f:"):
logotron_genesis.kv 506 from_users.append(t.split(':')[1]) # Record user for 'from' query
logotron_genesis.kv 507 else:
logotron_genesis.kv 508 tokens_standard.append(t)
logotron_genesis.kv 509
logotron_genesis.kv 510 from_users = ['%' + sanitize_speaker(t) + '%' for t in from_users]
logotron_genesis.kv 511 tokens_orig = [re_escape(t) for t in tokens_standard]
logotron_genesis.kv 512 tokens_formed = ['%' + t + '%' for t in tokens_orig]
logotron_genesis.kv 513
logotron_genesis.kv 514 # Query is usable; perform the search on DB and get the finds
logotron_genesis.kv 515 if from_users == []:
logotron_genesis.kv 516 searchres = query_db(
search_all_chans.kv 517 '''select * from loglines where chan = any(%s)
search_all_chans.kv 518 and payload ilike all(%s) order by t desc limit %s;''',
search_all_chans.kv 519 [(chans,),
logotron_genesis.kv 520 tokens_formed,
logotron_genesis.kv 521 Max_Search_Results], one=False)
logotron_genesis.kv 522 else:
logotron_genesis.kv 523 searchres = query_db(
search_all_chans.kv 524 '''select * from loglines where chan = any(%s)
logotron_genesis.kv 525 and speaker ilike any(%s)
search_all_chans.kv 526 and payload ilike all(%s) order by t desc limit %s;''',
search_all_chans.kv 527 [(chans,),
logotron_genesis.kv 528 from_users,
logotron_genesis.kv 529 tokens_formed,
logotron_genesis.kv 530 Max_Search_Results], one=False)
logotron_genesis.kv 531
logotron_genesis.kv 532
logotron_genesis.kv 533 # Number of entries found
logotron_genesis.kv 534 nres = len(searchres)
logotron_genesis.kv 535 search_head = "<b>{0}</b> entries found in {1} for <b>'{2}'</b> :".format(
search_all_chans.kv 536 nres, legend, html_escape(query))
logotron_genesis.kv 537
logotron_genesis.kv 538 # No paging support just yet:
logotron_genesis.kv 539 return render_template('searchres.html',
logotron_genesis.kv 540 query = query,
logotron_genesis.kv 541 nres = nres,
logotron_genesis.kv 542 chan = chan,
logotron_genesis.kv 543 search_head = search_head,
logotron_genesis.kv 544 tokens = tokens_orig,
search_all_chans.kv 545 loglines = searchres,
search_all_chans.kv 546 showchan = showchan)
logotron_genesis.kv 547
logotron_genesis.kv 548 # Comment this out if you don't have one
logotron_genesis.kv 549 @app.route('/favicon.ico')
logotron_genesis.kv 550 def favicon():
logotron_genesis.kv 551 return redirect(url_for('static', filename='favicon.ico'))
logotron_genesis.kv 552
logotron_genesis.kv 553
logotron_genesis.kv 554 ## App Mode
logotron_genesis.kv 555 if __name__ == '__main__':
logotron_genesis.kv 556 app.run(threaded=True, port=WWW_Port)