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