/usr/share/weechat/python/urlserver.py is in weechat-scripts 20111030-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Sebastien Helleu <flashcode@flashtux.org>
# Copyright (C) 2011 xt <xt@bash.no>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# Shorten URLs with own HTTP server.
# (this script requires Python >= 2.6)
#
# How does it work?
#
# 1. The URLs displayed in buffers are shortened and stored in memory (saved in
# a file when script is unloaded).
# 2. URLs shortened can be displayed below messages, in a dedicated buffer, or
# as HTML page in your browser.
# 3. This script embeds an HTTP server, which will redirect shortened URLs
# to real URL and display list of all URLs if you browse address without URL key.
# 4. It is recommended to customize/protect the HTTP server using script options
# (see /help urlserver)
#
# Example:
#
# FlashCode | look at this: http://test.server.com/this-is-a-very-looooong-url
# | http://myhost.org:1234/8aK
#
# List of URLs:
# - in WeeChat: /urlserver
# - in browser: http://myhost.org:1234/
#
# History:
#
# 2011-10-30, Sebastien Helleu <flashcode@flashtux.org>:
# version 0.2: fix error on loading of file "urlserver_list.txt" when it is empty
# 2011-10-30, Sebastien Helleu <flashcode@flashtux.org>:
# version 0.1: initial release
#
SCRIPT_NAME = 'urlserver'
SCRIPT_AUTHOR = 'Sebastien Helleu <flashcode@flashtux.org>'
SCRIPT_VERSION = '0.2'
SCRIPT_LICENSE = 'GPL3'
SCRIPT_DESC = 'Shorten URLs with own HTTP server'
SCRIPT_COMMAND = 'urlserver'
SCRIPT_BUFFER = 'urlserver'
import_ok = True
try:
import weechat
except ImportError:
print('This script must be run under WeeChat.')
print('Get WeeChat now at: http://www.weechat.org/')
import_ok = False
try:
import os, string, ast, datetime, socket, re, base64
except ImportError, message:
print('Missing package(s) for %s: %s' % (SCRIPT_NAME, message))
import_ok = False
# regex are from urlbar.py, written by xt
url_octet = r'(?:2(?:[0-4]\d|5[0-5])|1\d\d|\d{1,2})'
url_ipaddr = r'%s(?:\.%s){3}' % (url_octet, url_octet)
url_label = r'[0-9a-z][-0-9a-z]*[0-9a-z]?'
url_domain = r'%s(?:\.%s)*\.[a-z][-0-9a-z]*[a-z]?' % (url_label, url_label)
urlserver = {
'socket' : None,
'hook_fd' : None,
'regex' : re.compile(r'(\w+://(?:%s|%s)(?::\d+)?(?:/[^\])>\s]*)?)' % (url_domain, url_ipaddr), re.IGNORECASE),
'urls' : {},
'number' : 0,
'buffer' : '',
}
# script options
urlserver_settings_default = {
# HTTP server settings
'http_hostname' : ('', 'force hostname (or IP) for URLs (empty value = auto-detect current hostname)'),
'http_port' : ('', 'force port for listening (empty value = find a random free port)'),
'http_allowed_ips' : ('', 'regex for IPs allowed to use server (example: "^(123.45.67.89|192.160.*)$")'),
'http_auth' : ('', 'login and password (format: "login:password") required to access to page with list of URLs'),
'http_url_prefix' : ('', 'prefix to add in URLs to prevent external people to scan your URLs (for example: prefix "xx" will give URL: http://host.com:1234/xx/8)'),
'http_embed_image' : ('off', 'embed images in HTML page (BE CAREFUL: the HTTP referer will be sent to site hosting image!)'),
'http_embed_youtube': ('off', 'embed youtube videos in HTML page (BE CAREFUL: the HTTP referer will be sent to youtube!)'),
# message filter settings
'msg_ignore_buffers': ('core.weechat,python.grep', 'comma-separated list (without spaces) of buffers to ignore (full name like "irc.freenode.#weechat")'),
'msg_ignore_tags' : ('irc_quit,irc_part,notify_none', 'comma-separated list (without spaces) of tags (or beginning of tags) to ignore (for example, use "notify_none" to ignore self messages or "nick_weebot" to ignore messages from nick "weebot")'),
'msg_require_tags' : ('nick_', 'comma-separated list (without spaces) of tags (or beginning of tags) required to shorten URLs (for example "nick_" to shorten URLs only in messages from other users)'),
'msg_ignore_regex' : ('', 'ignore messages matching this regex'),
'msg_ignore_dup_urls': ('off', 'ignore duplicated URLs (do not add an URL in list if it is already)'),
# display settings
'color' : ('darkgray', 'color for urls displayed'),
'display_urls' : ('on', 'display URLs below messages'),
'url_min_length' : ('0', 'minimum length for an URL to be shortened (0 = shorten all URLs)'),
'urls_amount' : ('100', 'number of URLs to keep in memory (and in file when script is not loaded)'),
'buffer_short_name' : ('off', 'use buffer short name on dedicated buffer'),
'debug' : ('off', 'print some debug messages'),
}
urlserver_settings = {}
def base62_encode(number):
"""Encode a number in base62 (all digits + a-z + A-Z)."""
base62chars = string.digits + string.letters
l = []
while number > 0:
remainder = number % 62
number = number // 62
l.insert(0, base62chars[remainder])
return ''.join(l) or '0'
def base62_decode(str_value):
"""Decode a base62 string (all digits + a-z + A-Z) to a number."""
base62chars = string.digits + string.letters
return sum([base62chars.index(char) * (62 ** (len(str_value) - index - 1)) for index, char in enumerate(str_value)])
def urlserver_short_url(number):
"""Return short URL with number."""
global urlserver_settings
prefix = ''
if urlserver_settings['http_url_prefix']:
prefix = '%s/' % urlserver_settings['http_url_prefix']
return 'http://%s:%s/%s%s' % (urlserver_settings['http_hostname'] or socket.getfqdn(),
urlserver['socket'].getsockname()[1],
prefix, base62_encode(number))
def urlserver_server_reply(conn, code, extra_header, message, mimetype='text/html'):
"""Send a HTTP reply to client."""
if extra_header:
extra_header += '\r\n'
conn.send('HTTP/1.1 %s\r\n'
'%s'
'Content-Type: %s\r\n'
'Content-Length: %d\r\n'
'\r\n'
'%s' % (code, extra_header, mimetype, len(message), message))
def urlserver_server_favicon():
"""Return favicon for HTML page."""
return base64.b64decode(
'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1wgcDwo4MOEy+AAAAB10'
'RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJTVDvZCVuAAADp0lEQVQ4y12TXUxbBRTH/733ttx+XFq+Ci2Ur8AEYSBIosnS+YJhauJY9mQyXfTBh8UEnclm1Gxq'
'YoJGfZkzqAkmQ2IicVOcwY1YyMZwWcfXVq2Ulpax3raX2y9ob29v7+31QViIJzkPJyfn//D7/48G+2r+6jzaO9oHFCjPCTkBM7MzF06eOhng/uHMFE2dUopKExthb3cf'
'6h4DUAAAar+A3WB/b21l7a3pW9NLPW099Vk+axn9aPRDkROvX3FdiRtpo9LX0XeMJMm/FUW5DQDE3vHSN0t9vhXfy+eGz00hjgk6TZfcWXajlq79ePLyZGLog6Gvm7XN'
'nPumO+50HnYAIB8J+P3cMzmL+oVAy1ZdRhdykA4bp6YT5z/79PjaVtDJ+ThxeHCYSOUzWn17eebs2fMvAWgBoCEAIBTiS1cDG81b8azZz/rrT4+f/qWm92D2wUY6H91O'
'VfFhvnFkZiQRKRWnNzfj4fn5RSOA0kcM4nwhHRckQRLFwoBx4Ljd3pD3eoKNNkeDoaDTSzIvM2cqz7zLJKsVylphG//ynd8B8ABUCgC8Xn+oxt5W7V2aS99JuANP9th6'
'9RtsUlbNjNZkk+5tTwRjmXisK1t5gJR1qsfjDu4K/Mdg7PtPuFSKzEWS6Xi6QTdlau9ZD4Y22EgkI7KxVEZqrVgwveC8nJX08vLKQhSAB4CAPZLJZLjY2fnqYCLBV6ga'
'ISuROdP9xRthhnkMeVGtIQijXGo+0JTZEYzXrg8vdB0u8/Yeakj57sWEPRvVCLuzIgg0XdW3fSySdHX4A7N3+a3sH2LOQlNka1ssmmwKP2T1BJkKOJ5ST/hXN50ACAIA'
'Pv+2W0+UT2WFrNFkLsmVRP0PxaefNehl5b5nZ8di0OjUGp3d5eCE0fX+18nauh7u+a4jhVcAmKnvrtnrWTY6bKwcrxILUtHe5CVaWtPKE/3ki8s3Lk1aLIiq8NrrD/os'
'ZfZIvdVBqWSKkoNzSgYAQ5gZ4bXNQNw0cZF/P8r6fq4zJ9ORkDTXXCdrkNZo+49eon8d41apbYGjZTVlJSmfSdKE3a7cVwBYqopWDEecupYTg+TQny53uK6qkPL8Jcw+'
'3sh0LjbL1jZbkbwwEtgmCW2C47X5GhOhXw9oWABhADL12w/qxSIpEz/9mI9JucIsw6hzxaK6tBMyVE9dTWbKrMqb01OoUyXdrQfhAvP2G3S5y1W4CyC5/xF1u63Zy0Z1'
'mZ7ejSv5v50OQMnujH8BbzDFpcdRAIIAAAAASUVORK5CYII=')
def urlserver_server_reply_list(conn, sort='-time'):
"""Send list of URLs as HTML page to client."""
global urlserver, urlserver_settings
content = '<div class="urls">\n<table>\n'
if not sort.startswith('-'):
sort = '+%s' % sort
if sort[1:] == 'time':
urls = sorted(urlserver['urls'].iteritems())
else:
idx = ['time', 'nick', 'buffer'].index(sort[1:])
urls = sorted(urlserver['urls'].iteritems(), key=lambda(k,v):v[idx].lower())
if sort.startswith('-'):
urls.reverse()
sortkey = { '-': ('', '↑'), '+': ('-', '↓') }
prefix = ''
if urlserver_settings['http_url_prefix']:
prefix = '%s/' % urlserver_settings['http_url_prefix']
content += ' <tr>'
for column, defaultsort in (('time', '-'), ('nick', ''), ('buffer', '')):
if sort[1:] == column:
content += '<th><a href="/%ssort=%s%s">%s</a> %s</th>' % (prefix, sortkey[sort[0]][0], column, column.capitalize(), sortkey[sort[0]][1])
else:
content += '<th><a href="/%ssort=%s%s">%s</a></th>' % (prefix, defaultsort, column, column.capitalize())
content += '<th>URLs</th>'
content += '</tr>\n'
for key, item in urls:
content += ' <tr>'
url = item[3]
obj = ''
message = item[4].split('\t', 1)
message = ' | '.join(message).replace(url, '<a href="%s" title="%s">%s</a>' % (urlserver_short_url(key), url, url))
if urlserver_settings['http_embed_image'] == 'on' and url.lower()[-4:] in ('.jpg', '.png', '.gif'):
obj = '<div class="obj"><img src="%s" title="%s" alt="%s"></div>' % (url, url, url)
elif urlserver_settings['http_embed_youtube'] == 'on' and 'youtube.com/' in url:
m = re.search('v=([\w\d]+)', url)
if m:
yid = m.group(1)
obj = '<div class="obj"><iframe id="%s" type="text/html" width="640" height="390" ' \
'src="http://www.youtube.com/embed/%s?enablejsapi=1"></iframe></div>' %(yid, yid)
content += '<td class="nowrap">%s</td><td class="nowrap">%s</td><td class="nowrap">%s</td><td>' % (item[0], item[1], item[2])
content += '%s%s</td></tr>\n' % (message, obj)
content += '</table>'
html = '<html>\n' \
'<head>\n' \
'<title>Weechat URLs</title>\n' \
'<meta http-equiv="content-type" content="text/html; charset=utf-8" />\n' \
'<style type="text/css" media="screen">' \
'<!--\n' \
' html { font-family: Verdana, Arial, Helvetica; font-size: 12px }\n' \
' .urls table { border-collapse: collapse }\n' \
' .urls table td,th { border: solid 1px #DDDDDD; padding: 4px; font-size: 12px }\n' \
' .nowrap { white-space: nowrap }\n' \
' .obj { text-align: center; margin-top: 1em }\n' \
'-->' \
'</style>\n' \
'</head>\n' \
'<body>\n%s\n</body>\n' \
'</html>' %content
urlserver_server_reply(conn, '200 OK', '', html)
def urlserver_server_fd_cb(data, fd):
"""Callback for server socket."""
global urlserver, urlserver_settings
if not urlserver['socket']:
return weechat.WEECHAT_RC_OK
conn, addr = urlserver['socket'].accept()
if urlserver_settings['debug'] == 'on':
weechat.prnt('', 'urlserver: connection from %s' % str(addr))
if urlserver_settings['http_allowed_ips'] and not re.match(urlserver_settings['http_allowed_ips'], addr[0]):
if urlserver_settings['debug'] == 'on':
weechat.prnt('', 'urlserver: IP not allowed')
conn.close()
return weechat.WEECHAT_RC_OK
data = None
try:
conn.settimeout(0.3)
data = conn.recv(4096)
data = data.replace('\r\n', '\n')
except:
return weechat.WEECHAT_RC_OK
replysent = False
sort = '-time'
m = re.search('^GET /(.*) HTTP/.*$', data, re.MULTILINE)
if m:
url = m.group(1)
if urlserver_settings['debug'] == 'on':
weechat.prnt('', 'urlserver: %s' % m.group(0))
if 'favicon.' in url:
urlserver_server_reply(conn, '200 OK', '',
urlserver_server_favicon(), mimetype='image/x-icon')
replysent = True
else:
# check if prefix is ok (if prefix defined in settings)
prefixok = True
if urlserver_settings['http_url_prefix']:
if url.startswith(urlserver_settings['http_url_prefix']):
url = url[len(urlserver_settings['http_url_prefix']):]
if url.startswith('/'):
url = url[1:]
else:
prefixok = False
# prefix ok, go on with url
if prefixok:
if url.startswith('sort='):
# sort asked for list of urls
sort = url[5:]
url = ''
if url:
# short url, read base62 key and redirect to page
number = -1
try:
number = base62_decode(url)
except:
pass
if number >= 0 and number in urlserver['urls']:
# no redirection with "Location:" because it sends HTTP referer
#conn.send('HTTP/1.1 302 Found\nLocation: %s\n' % urlserver['urls'][number][2])
urlserver_server_reply(conn, '200 OK', '',
'<meta http-equiv="refresh" content="0; url=%s">' % urlserver['urls'][number][3])
replysent = True
else:
# page with list of urls
authok = True
if urlserver_settings['http_auth']:
auth = re.search('^Authorization: Basic (\S+)$', data, re.MULTILINE)
if not auth or base64.b64decode(auth.group(1)) != urlserver_settings['http_auth']:
authok = False
if authok:
urlserver_server_reply_list(conn, sort)
else:
urlserver_server_reply(conn, '401 Authorization required',
'WWW-Authenticate: Basic realm="%s"' % SCRIPT_NAME, '')
replysent = True
else:
if urlserver_settings['debug'] == 'on':
weechat.prnt('', 'urlserver: prefix missing')
if not replysent:
urlserver_server_reply(conn,
'404 Not found', '',
'<html>\n'
'<head><title>Page not found</title></head>\n'
'<body><h1>Page not found</h1></body>\n'
'</html>')
conn.close()
return weechat.WEECHAT_RC_OK
def urlserver_server_status():
"""Display status of server."""
global urlserver
if urlserver['socket']:
weechat.prnt('', 'URL server listening on %s' % str(urlserver['socket'].getsockname()))
else:
weechat.prnt('', 'URL server not running')
def urlserver_server_start():
"""Start mini HTTP server."""
global urlserver, urlserver_settings
if urlserver['socket']:
weechat.prnt('', 'URL server already running')
return
port = 0
try:
port = int(urlserver_settings['http_port'])
except:
port = 0
urlserver['socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
urlserver['socket'].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
urlserver['socket'].bind((urlserver_settings['http_hostname'] or socket.getfqdn(), port))
except Exception as e:
weechat.prnt('', '%sBind error: %s' % (weechat.prefix('error'), e))
urlserver['socket'] = None
urlserver_server_status()
return
urlserver['socket'].listen(5)
urlserver['hook_fd'] = weechat.hook_fd(urlserver['socket'].fileno(), 1, 0, 0, 'urlserver_server_fd_cb', '')
urlserver_server_status()
def urlserver_server_stop():
"""Stop mini HTTP server."""
global urlserver
if urlserver['socket'] or urlserver['hook_fd']:
if urlserver['socket']:
urlserver['socket'].close()
urlserver['socket'] = None
if urlserver['hook_fd']:
weechat.unhook(urlserver['hook_fd'])
urlserver['hook_fd'] = None
weechat.prnt('', 'URL server stopped')
def urlserver_server_restart():
"""Restart mini HTTP server."""
urlserver_server_stop()
urlserver_server_start()
def urlserver_display_url_detail(key):
global urlserver
url = urlserver['urls'][key]
nick = url[1]
if nick:
nick += ' @ '
weechat.prnt(urlserver['buffer'], '%s, %s%s%s%s: %s%s%s -> %s' % (url[0],
nick,
weechat.color('chat_buffer'),
url[2],
weechat.color('reset'),
weechat.color(urlserver_settings['color']),
urlserver_short_url(key),
weechat.color('reset'),
url[3]))
def urlserver_buffer_input_cb(data, buffer, input_data):
if input_data in ('q', 'Q'):
weechat.buffer_close(buffer)
return weechat.WEECHAT_RC_OK
def urlserver_buffer_close_cb(data, buffer):
global urlserver
urlserver['buffer'] = ''
return weechat.WEECHAT_RC_OK
def urlserver_open_buffer():
global urlserver, urlserver_settings
if not urlserver['buffer']:
urlserver['buffer'] = weechat.buffer_new(SCRIPT_BUFFER,
'urlserver_buffer_input_cb', '',
'urlserver_buffer_close_cb', '')
if urlserver['buffer']:
weechat.buffer_set(urlserver['buffer'], 'title', 'urlserver')
weechat.buffer_set(urlserver['buffer'], 'localvar_set_no_log', '1')
weechat.buffer_set(urlserver['buffer'], 'time_for_each_line', '0')
weechat.buffer_set(urlserver['buffer'], 'print_hooks_enabled', '0')
weechat.buffer_clear(urlserver['buffer'])
keys = urlserver['urls'].keys()
keys.sort()
for key in keys:
urlserver_display_url_detail(key)
weechat.buffer_set(urlserver['buffer'], 'display', '1')
def urlserver_cmd_cb(data, buffer, args):
"""The /urlserver command."""
global urlserver
if args == 'start':
urlserver_server_start()
elif args == 'restart':
urlserver_server_restart()
elif args == 'stop':
urlserver_server_stop()
elif args == 'status':
urlserver_server_status()
elif args == 'clear':
urlserver['urls'] = {}
urlserver['number'] = 0
weechat.prnt('', 'urlserver: list cleared')
else:
urlserver_open_buffer()
return weechat.WEECHAT_RC_OK
def urlserver_print_cb(data, buffer, time, tags, displayed, highlight, prefix, message):
"""Callback for messages printed in buffers."""
global urlserver, urlserver_settings
buffer_full_name = '%s.%s' % (weechat.buffer_get_string(buffer, 'plugin'), weechat.buffer_get_string(buffer, 'name'))
if urlserver_settings['buffer_short_name'] == 'on':
buffer_name = weechat.buffer_get_string(buffer, 'short_name')
else:
buffer_name = buffer_full_name
listtags = tags.split(',')
# skip ignored buffers
if urlserver_settings['msg_ignore_buffers']:
if buffer_full_name in urlserver_settings['msg_ignore_buffers'].split(','):
return weechat.WEECHAT_RC_OK
# skip ignored tags
if urlserver_settings['msg_ignore_tags']:
for itag in urlserver_settings['msg_ignore_tags'].split(','):
for tag in listtags:
if tag.startswith(itag):
return weechat.WEECHAT_RC_OK
# exit if a required tag is missing
if urlserver_settings['msg_require_tags']:
for rtag in urlserver_settings['msg_require_tags'].split(','):
tagfound = False
for tag in listtags:
if tag.startswith(rtag):
tagfound = True
break
if not tagfound:
return weechat.WEECHAT_RC_OK
# ignore message is matching the "msg_ignore_regex"
if urlserver_settings['msg_ignore_regex']:
if re.search(urlserver_settings['msg_ignore_regex'], prefix + '\t' + message):
return weechat.WEECHAT_RC_OK
# extract nick from tags
nick = ''
for tag in listtags:
if tag.startswith('nick_'):
nick = tag[5:]
break
# get URL min length
min_length = 0
try:
min_length = int(urlserver_settings['url_min_length'])
except:
min_length = 0
# shorten URL(s) in message
for url in urlserver['regex'].findall(message):
if len(url) >= min_length:
if urlserver_settings['msg_ignore_dup_urls'] == 'on':
if [key for key, value in urlserver['urls'].iteritems() if value[3] == url]:
continue
number = urlserver['number']
urlserver['urls'][number] = (datetime.datetime.now().strftime('%d/%m/%y %H:%M'), nick, buffer_name, url, '%s\t%s' % (prefix, message))
if urlserver_settings['display_urls'] == 'on':
weechat.prnt_date_tags(buffer, 0, 'no_log,notify_none', '%s%s' % (weechat.color(urlserver_settings['color']), urlserver_short_url(number)))
if urlserver['buffer']:
urlserver_display_url_detail(number)
urlserver['number'] += 1
# remove old URLs if we have reach max list size
urls_amount = 50
try:
urls_amount = int(urlserver_settings['urls_amount'])
if urls_amount <= 0:
urls_amount = 50
except:
urls_amount = 50
while len(urlserver['urls']) > urls_amount:
keys = urlserver['urls'].keys()
keys.sort()
del urlserver['urls'][keys[0]]
return weechat.WEECHAT_RC_OK
def urlserver_config_cb(data, option, value):
"""Called when a script option is changed."""
global urlserver_settings
pos = option.rfind('.')
if pos > 0:
name = option[pos+1:]
if name in urlserver_settings:
if name == 'http_allowed_ips':
urlserver_settings[name] = re.compile(value)
else:
urlserver_settings[name] = value
if name in ('http_hostname', 'http_port'):
urlserver_server_restart()
return weechat.WEECHAT_RC_OK
def urlserver_filename():
"""Return name of file used to store list of urls."""
return os.path.join(weechat.info_get('weechat_dir', ''), 'urlserver_list.txt')
def urlserver_read_urls():
"""Read file with URLs."""
global urlserver
filename = urlserver_filename()
if os.path.isfile(filename):
urlserver['number'] = 0
try:
urlserver['urls'] = ast.literal_eval(open(filename, 'r').read())
keys = urlserver['urls'].keys()
if keys:
keys.sort()
urlserver['number'] = keys[-1] + 1
else:
urlserver['number'] = 0
except:
weechat.prnt('', '%surlserver: error reading file "%s"' % (weechat.prefix('error'), filename))
def urlserver_write_urls():
"""Write file with URLs."""
global urlserver
keys = urlserver['urls'].keys()
keys.sort()
content = '{\n%s\n}\n' % '\n'.join([' %d: %s,' % (key, str(urlserver['urls'][key])) for key in keys])
open(urlserver_filename(), 'w').write(content)
def urlserver_end():
"""Script unloaded (oh no, why?)"""
urlserver_server_stop()
urlserver_write_urls()
return weechat.WEECHAT_RC_OK
if __name__ == '__main__' and import_ok:
if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
SCRIPT_DESC, 'urlserver_end', ''):
# set default settings
version = weechat.info_get('version_number', '') or 0
for option, value in urlserver_settings_default.iteritems():
if weechat.config_is_set_plugin(option):
urlserver_settings[option] = weechat.config_get_plugin(option)
else:
weechat.config_set_plugin(option, value[0])
urlserver_settings[option] = value[0]
if int(version) >= 0x00030500:
weechat.config_set_desc_plugin(option, '%s (default: "%s")' % (value[1], value[0]))
# detect config changes
weechat.hook_config('plugins.var.python.%s.*' % SCRIPT_NAME, 'urlserver_config_cb', '')
# add command
weechat.hook_command(SCRIPT_COMMAND, SCRIPT_DESC, 'start|restart|stop|status || clear',
' start: start server\n'
'restart: restart server\n'
' stop: stop server\n'
' status: display status of server\n'
' clear: remove all URLs from list\n\n'
'Without argument, this command opens new buffer with list of URLs.\n\n'
'Initial setup:\n'
' - by default, script will listen on a random free port, you can force a port with:\n'
' /set plugins.var.python.urlserver.http_port "1234"\n'
' - you can force an IP or custom hostname with:\n'
' /set plugins.var.python.urlserver.http_hostname "111.22.33.44"\n'
' - it is strongly recommended to restrict IPs allowed and/or use auth, for example:\n'
' /set plugins.var.python.urlserver.http_allowed_ips "^(123.45.67.89|192.160.*)$"\n'
' /set plugins.var.python.urlserver.http_auth "user:password"\n\n'
'Tip: use URL without key at the end to display list of all URLs in your browser.',
'start|restart|stop|status|clear', 'urlserver_cmd_cb', '')
# start mini HTTP server
urlserver_server_start()
# load urls from file
urlserver_read_urls()
# catch URLs in buffers
weechat.hook_print("", "", "://", 1, "urlserver_print_cb", "")
# search buffer
urlserver['buffer'] = weechat.buffer_search('python', SCRIPT_BUFFER)
|