File: tig.rb

package info (click to toggle)
ruby-net-irc 0.0.9-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 408 kB
  • sloc: ruby: 7,268; makefile: 3
file content (2320 lines) | stat: -rwxr-xr-x 59,493 bytes parent folder | download | duplicates (4)
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
#!/usr/bin/env ruby
# vim:encoding=UTF-8:
$KCODE = "u" unless defined? ::Encoding # json use this
=begin

# tig.rb

Ruby version of TwitterIrcGateway
<http://www.misuzilla.org/dist/net/twitterircgateway/>

## Launch

	$ ruby tig.rb

If you want to help:

	$ ruby tig.rb --help

## Configuration

Options specified by after IRC realname.

Configuration example for Tiarra <http://coderepos.org/share/wiki/Tiarra>.

	general {
		server-in-encoding: utf8
		server-out-encoding: utf8
		client-in-encoding: utf8
		client-out-encoding: utf8
	}

	networks {
		name: tig
	}

	tig {
		server: localhost 16668
		password: password on Twitter
		# Recommended
		name: username mentions tid

		# Same as TwitterIrcGateway.exe.config.sample
		#   (90, 360 and 300 seconds)
		#name: username dm ratio=4:1 maxlimit=50
		#name: username dm ratio=20:5:6 maxlimit=62 mentions
		#
		# <http://cheebow.info/chemt/archives/2009/04/posttwit.html>
		#   (60, 360 and 150 seconds)
		#name: username dm ratio=30:5:12 maxlimit=94 mentions
		#
		# <http://cheebow.info/chemt/archives/2009/07/api150rhtwit.html>
		#   (36, 360 and 150 seconds)
		#name: username dm ratio=50:5:12 maxlimit=134 mentions
		#
		# for Jabber
		#name: username jabber=username@example.com:jabberpasswd
	}

### athack

If `athack` client option specified,
all nick in join message is leading with @.

So if you complemente nicks (e.g. Irssi),
it's good for Twitter like reply command (@nick).

In this case, you will see torrent of join messages after connected,
because NAMES list can't send @ leading nick (it interpreted op.)

### tid[=<color:10>[,<bgcolor>]]

Apply ID to each message for make favorites by CTCP ACTION.

	/me fav [ID...]

<color> and <bgcolor> can be

	0  => white
	1  => black
	2  => blue         navy
	3  => green
	4  => red
	5  => brown        maroon
	6  => purple
	7  => orange       olive
	8  => yellow
	9  => lightgreen   lime
	10 => teal
	11 => lightcyan    cyan aqua
	12 => lightblue    royal
	13 => pink         lightpurple fuchsia
	14 => grey
	15 => lightgrey    silver

### jabber=<jid>:<pass>

If `jabber=<jid>:<pass>` option specified,
use Jabber to get friends timeline.

You must setup im notifing settings in the site and
install "xmpp4r-simple" gem.

	$ sudo gem install xmpp4r-simple

Be careful for managing password.

### alwaysim

Use IM instead of any APIs (e.g. post)

### ratio=<timeline>:<dm>[:<mentions>]

"121:6:20" by default.

	/me ratios

	   Ratio | Timeline |   DM  | Mentions |
	---------+----------+-------+----------|
	       1 |      24s |   N/A |      N/A |
	   141:6 |      26s |   10m OR N/A     |
	  135:12 |      27s |    5m OR N/A     |
	 135:6:6 |      27s |   10m |      10m |
	---------+----------+-------+----------|
	121:6:20 |      30s |   10m |       3m |
	---------+----------+-------+----------|
	     4:1 |      31s |  2m1s |      N/A |
	 50:5:12 |      49s | 8m12s |    3m25s |
	  20:5:6 |      57s | 3m48s |    3m10s |
	 30:5:12 |      58s | 5m45s |    2m24s |
	   1:1:1 |    1m13s | 1m13s |    1m13s |
	---------------------------------------+
	                    (Hourly limit: 150)

### dm[=<ratio>]

### mentions[=<ratio>]

### maxlimit=<hourly_limit>

### clientspoofing

### httpproxy=[<user>[:<password>]@]<address>[:<port>]

### main_channel=<channel:#twitter>

### api_source=<source>

### check_friends_interval=<seconds:3600>

### check_updates_interval=<seconds:86400>

Set 0 to disable checking.

### old_style_reply

### tmap_size=<number:10404>

### strftime=<format:%m-%d %H:%M>

### untiny_whole_urls

### bitlify=<username>:<apikey>:<minlength:20>

### unuify

### shuffled_tmap

### ll=<lat>,<long>

### with_retweets

## Extended commands through the CTCP ACTION

### list (ls)

	/me list NICK [NUMBER]

### fav (favorite, favourite, unfav, unfavorite, unfavourite)

	/me fav [ID...]
	/me unfav [ID...]
	/me fav! [ID...]
	/me fav NICK

### link (ln, url, u)

	/me link ID [ID...]

### destroy (del, delete, miss, oops, remove, rm)

	/me destroy [ID...]

### in (location)

	/me in Sugamo, Tokyo, Japan

### reply (re, mention)

	/me reply ID blah, blah...

### retweet (rt)

	/me retweet ID (blah, blah...)

### utf7 (utf-7)

	/me utf7

### name

	/me name My Name

### description (desc)

	/me description blah, blah...

### spoof

	/me spoof
	/me spoo[o...]f
	/me spoof tigrb twitterircgateway twitt web mobileweb

### bot (drone)

	/me bot NICK [NICK...]

## Feed

<http://coderepos.org/share/log/lang/ruby/net-irc/trunk/examples/tig.rb?limit=100&mode=stop_on_copy&format=rss>

## License

Ruby's by cho45

=end

case
when File.directory?("lib")
	$LOAD_PATH << "lib"
when File.directory?(File.expand_path("lib", ".."))
	$LOAD_PATH << File.expand_path("lib", "..")
end

require "rubygems"
require "net/irc"
require "net/https"
require "uri"
require "time"
require "logger"
require "yaml"
require "pathname"
require "ostruct"
require "json"

begin
	require "iconv"
	require "punycode"
rescue LoadError
end

module Net::IRC::Constants; RPL_WHOISBOT = "335"; RPL_CREATEONTIME = "329"; end

class TwitterIrcGateway < Net::IRC::Server::Session
	@@ctcp_action_commands = []

	class << self
		def ctcp_action(*commands, &block)
			name = "+ctcp_action_#{commands.inspect}"
			define_method(name, block)
			commands.each do |command|
				@@ctcp_action_commands << [command, name]
			end
		end
	end

	def server_name
		"twittergw"
	end

	def server_version
		head = `git rev-parse HEAD 2>/dev/null`
		head.empty?? "unknown" : head
	end

	def available_user_modes
		"o"
	end

	def available_channel_modes
		"mnti"
	end

	def main_channel
		@opts.main_channel || "#twitter"
	end

	def api_base(secure = true)
		URI("http#{"s" if secure}://twitter.com/")
	end

	def api_source
		"#{@opts.api_source || "tigrb"}"
	end

	def jabber_bot_id
		"twitter@twitter.com"
	end

	def hourly_limit
		150
	end

	class APIFailed < StandardError; end

	MAX_MODE_PARAMS = 3
	WSP_REGEX       = Regexp.new("\\r\\n|[\\r\\n\\t#{"\\u00A0\\u1680\\u180E\\u2002-\\u200D\\u202F\\u205F\\u2060\\uFEFF" if "\u0000" == "\000"}]")

	def initialize(*args)
		super
		@groups        = {}
		@channels      = [] # joined channels (groups)
		@nicknames     = {}
		@drones        = []
		@config        = Pathname.new(ENV["HOME"]) + ".tig" ### TODO マルチユーザに対応してない
		@etags         = {}
		@consums       = []
		@limit         = hourly_limit
		@friends       =
		@sources       =
		@rsuffix_regex =
		@im            =
		@im_thread     =
		@utf7          =
		@httpproxy     = nil
		load_config
	end

	def on_user(m)
		super

		@real, *@opts = (@opts.name || @real).split(" ")
		@opts = @opts.inject({}) do |r, i|
			key, value = i.split("=", 2)
			key = "mentions" if key == "replies" # backcompat
			r.update key => case value
				when nil                      then true
				when /\A\d+\z/                then value.to_i
				when /\A(?:\d+\.\d*|\.\d+)\z/ then value.to_f
				else                               value
			end
		end
		@opts = OpenStruct.new(@opts)
		@opts.httpproxy.sub!(/\A(?:([^:@]+)(?::([^@]+))?@)?([^:]+)(?::(\d+))?\z/) do
			@httpproxy = OpenStruct.new({
				:user => $1, :password => $2, :address => $3, :port => $4.to_i,
			})
			$&.sub(/[^:@]+(?=@)/, "********")
		end if @opts.httpproxy

		retry_count = 0
		begin
			@me = api("account/update_profile") #api("account/verify_credentials")
		rescue APIFailed => e
			@log.error e.inspect
			sleep 1
			retry_count += 1
			retry if retry_count < 3
			log "Failed to access API 3 times." <<
			    " Please check your username/email and password combination, " <<
			    " Twitter Status <http://status.twitter.com/> and try again later."
			finish
		end

		@prefix = prefix(@me)
		@user   = @prefix.user
		@host   = @prefix.host

		#post NICK, @me.screen_name if @nick != @me.screen_name
		post server_name, MODE, @nick, "+o"
		post @prefix, JOIN, main_channel
		post server_name, MODE, main_channel, "+mto", @nick
		post server_name, MODE, main_channel, "+q", @nick
		if @me.status
			@me.status.user = @me
			post @prefix, TOPIC, main_channel, generate_status_message(@me.status.text)
		end

		if @opts.jabber
			jid, pass = @opts.jabber.split(":", 2)
			@opts.jabber.replace("jabber=#{jid}:********")
			if jabber_bot_id
				begin
					require "xmpp4r-simple"
					start_jabber(jid, pass)
				rescue LoadError
					log "Failed to start Jabber."
					log 'Installl "xmpp4r-simple" gem or check your ID/pass.'
					finish
				end
			else
				@opts.delete_field :jabber
				log "This gateway does not support Jabber bot."
			end
		end

		log "Client options: #{@opts.marshal_dump.inspect}"
		@log.info "Client options: #{@opts.inspect}"

		@opts.tid = begin
			c = @opts.tid # expect: 0..15, true, "0,1"
			b = nil
			c, b = c.split(",", 2).map {|i| i.to_i } if c.respond_to? :split
			c = 10 unless (0 .. 15).include? c # 10: teal
			if (0 .. 15).include?(b)
				"\003%.2d,%.2d[%%s]\017" % [c, b]
			else
				"\003%.2d[%%s]\017"      % c
			end
		end if @opts.tid

		@ratio = (@opts.ratio || "121").split(":")
		@ratio = Struct.new(:timeline, :dm, :mentions).new(*@ratio)
		@ratio.dm       ||= @opts.dm == true ? @opts.mentions ?  6 : 26 : @opts.dm
		@ratio.mentions ||= @opts.mentions == true ? @opts.dm ? 20 : 26 : @opts.mentions

		@check_friends_thread = Thread.start do
			loop do
				begin
					check_friends
				rescue APIFailed => e
					@log.error e.inspect
				rescue Exception => e
					@log.error e.inspect
					e.backtrace.each do |l|
						@log.error "\t#{l}"
					end
				end
				sleep @opts.check_friends_interval || 3600
			end
		end

		return if @opts.jabber

		@timeline = TypableMap.new(@opts.tmap_size     || 10_404,
		                           @opts.shuffled_tmap || false)

		if @opts.clientspoofing
			update_sources
		else
			@sources = [api_source]
		end

		update_redundant_suffix
		@check_updates_thread = Thread.start do
			sleep 30

			loop do
				begin
					@log.info "check_updates"
					check_updates
				rescue Exception => e
					@log.error e.inspect
					e.backtrace.each do |l|
						@log.error "\t#{l}"
					end
				end
				sleep 0.01 * (90 + rand(21)) *
				      (@opts.check_updates_interval || 86400) # 0.9 ... 1.1 day
			end

			sleep @opts.check_updates_interval || 86400
		end

		@check_timeline_thread = Thread.start do
			sleep 2 * (@me.friends_count / 100.0).ceil

			loop do
				begin
					check_timeline
				rescue APIFailed => e
					@log.error e.inspect
				rescue Exception => e
					@log.error e.inspect
					e.backtrace.each do |l|
						@log.error "\t#{l}"
					end
				end
				sleep interval(@ratio.timeline)
			end
		end

		@check_dms_thread = Thread.start do
			loop do
				begin
					check_direct_messages
				rescue APIFailed => e
					@log.error e.inspect
				rescue Exception => e
					@log.error e.inspect
					e.backtrace.each do |l|
						@log.error "\t#{l}"
					end
				end
				sleep interval(@ratio.dm)
			end
		end if @opts.dm

		@check_mentions_thread = Thread.start do
			sleep interval(@ratio.timeline) / 2

			loop do
				begin
					check_mentions
				rescue APIFailed => e
					@log.error e.inspect
				rescue Exception => e
					@log.error e.inspect
					e.backtrace.each do |l|
						@log.error "\t#{l}"
					end
				end
				sleep interval(@ratio.mentions)
			end
		end if @opts.mentions
	end

	def on_disconnected
		@check_friends_thread.kill  rescue nil
		@check_timeline_thread.kill rescue nil
		@check_mentions_thread.kill rescue nil
		@check_dms_thread.kill      rescue nil
		@check_updates_thread.kill  rescue nil
		@im_thread.kill             rescue nil
		@im.disconnect              rescue nil
	end

	def on_privmsg(m)
		target, mesg = *m.params

		m.ctcps.each {|ctcp| on_ctcp(target, ctcp) } if m.ctcp?

		return if mesg.empty?
		return on_ctcp_action(target, mesg) if mesg.sub!(/\A +/, "") #and @opts.direct_action

		command, params = mesg.split(" ", 2)
		case command.downcase # TODO: escape recursive
		when "d", "dm"
			screen_name, mesg = params.split(" ", 2)
			unless screen_name or mesg
				log 'Send "d NICK message" to send a direct (private) message.' <<
				    " You may reply to a direct message the same way."
				return
			end
			m.params[0] = screen_name.sub(/\A@/, "")
			m.params[1] = mesg #.rstrip
			return on_privmsg(m)
		# TODO
		#when "f", "follow"
		#when "on"
		#when "off" # BUG if no args
		#when "g", "get"
		#when "w", "whois"
		#when "n", "nudge" # BUG if no args
		#when "*", "fav"
		#when "delete"
		#when "stats" # no args
		#when "leave"
		#when "invite"
		end unless command.nil?

		mesg = escape_http_urls(mesg)
		mesg = @opts.unuify ? unuify(mesg) : bitlify(mesg)
		mesg = Iconv.iconv("UTF-7", "UTF-8", mesg).join.encoding!("ASCII-8BIT") if @utf7

		ret         = nil
		retry_count = 3
		begin
			case
			when target.ch?
				if @opts.alwaysim and @im and @im.connected? # in Jabber mode, using Jabber post
					ret = @im.deliver(jabber_bot_id, mesg)
					post @prefix, TOPIC, main_channel, mesg
				else
					previous = @me.status
					if previous and
					   ((Time.now - Time.parse(previous.created_at)).to_i < 60 rescue true) and
					   mesg.strip == previous.text
						log "You can't submit the same status twice in a row."
						return
					end

					q = { :status => mesg, :source => source }

					if @opts.old_style_reply and mesg[/\A@(?>([A-Za-z0-9_]{1,15}))[^A-Za-z0-9_]/]
						if user = friend($1) || api("users/show/#{$1}")
							unless user.status
								user = api("users/show/#{user.id}", {},
								           { :authenticate => user.protected })
							end
							if user.status
								q.update :in_reply_to_status_id => user.status.id
							end
						end
					end
					if @opts.ll
						lat, long = @opts.ll.split(",", 2)
						q.update :lat  => lat.to_f
						q.update :long => long.to_f
					end

					ret = api("statuses/update", q)
					log oops(ret) if ret.truncated
					ret.user.status = ret
					@me = ret.user
					log "Status updated"
				end
			when target.screen_name? # Direct message
				ret = api("direct_messages/new", { :screen_name => target, :text => mesg })
				post server_name, NOTICE, @nick, "Your direct message has been sent to #{target}."
			else
				post server_name, ERR_NOSUCHNICK, target, "No such nick/channel"
			end
		rescue => e
			@log.error [retry_count, e.inspect].inspect
			if retry_count > 0
				retry_count -= 1
				@log.debug "Retry to setting status..."
				retry
			end
			log "Some Error Happened on Sending #{mesg}. #{e}"
		end
	end

	def on_whois(m)
		nick = m.params[0]
		unless nick.screen_name?
			post server_name, ERR_NOSUCHNICK, nick, "No such nick/channel"
			return
		end

		unless user = user(nick)
			if api("users/username_available", { :username => nick }).valid
			# TODO: 404 suspended
				post server_name, ERR_NOSUCHNICK, nick, "No such nick/channel"
				return
			end
			user = api("users/show/#{nick}", {}, { :authenticate => false })
		end

		prefix    = prefix(user)
		desc      = user.name
		desc      = "#{desc} / #{user.description}".gsub(/\s+/, " ") if user.description and not user.description.empty?
		signon_at = Time.parse(user.created_at).to_i rescue 0
		idle_sec  = (Time.now - (user.status ? Time.parse(user.status.created_at) : signon_at)).to_i rescue 0
		location  = user.location
		location  = "SoMa neighborhood of San Francisco, CA" if location.nil? or location.empty?
		post server_name, RPL_WHOISUSER,   @nick, nick, prefix.user, prefix.host, "*", desc
		post server_name, RPL_WHOISSERVER, @nick, nick, api_base.host, location
		post server_name, RPL_WHOISIDLE,   @nick, nick, "#{idle_sec}", "#{signon_at}", "seconds idle, signon time"
		post server_name, RPL_ENDOFWHOIS,  @nick, nick, "End of WHOIS list"
		if @drones.include?(user.id)
			post server_name, RPL_WHOISBOT, @nick, nick, "is a \002Bot\002 on #{server_name}"
		end
	end

	def on_who(m)
		channel  = m.params[0]
		whoreply = Proc.new do |ch, user|
			#     "<channel> <user> <host> <server> <nick>
			#         ( "H" / "G" > ["*"] [ ( "@" / "+" ) ]
			#             :<hopcount> <real name>"
			prefix = prefix(user)
			server = api_base.host
			mode   = case prefix.nick
				when @nick                     then "~"
				#when @drones.include?(user.id) then "%" # FIXME
				else                                "+"
			end
			hop  = prefix.host.count("/")
			real = user.name
			post server_name, RPL_WHOREPLY, @nick,
			     ch, prefix.user, prefix.host, server, prefix.nick, "H*#{mode}", "#{hop} #{real}"
		end

		case
		when channel.casecmp(main_channel).zero?
			users = [@me]
			users.concat @friends.reverse if @friends
			users.each {|friend| whoreply.call channel, friend }
			post server_name, RPL_ENDOFWHO, @nick, channel
		when (@groups.key?(channel) and @friends)
			@groups[channel].each do |nick|
				whoreply.call channel, friend(nick)
			end
			post server_name, RPL_ENDOFWHO, @nick, channel
		else
			post server_name, ERR_NOSUCHNICK, @nick, "No such nick/channel"
		end
	end

	def on_join(m)
		channels = m.params[0].split(/ *, */)
		channels.each do |channel|
			channel = channel.split(" ", 2).first
			next if channel.casecmp(main_channel).zero?

			@channels << channel
			@channels.uniq!
			post @prefix, JOIN, channel
			post server_name, MODE, channel, "+mtio", @nick
			post server_name, MODE, channel, "+q", @nick
			save_config
		end
	end

	def on_part(m)
		channel = m.params[0]
		return if channel.casecmp(main_channel).zero?

		@channels.delete(channel)
		post @prefix, PART, channel, "Ignore group #{channel}, but setting is alive yet."
	end

	def on_invite(m)
		nick, channel = *m.params
		if not nick.screen_name? or @nick.casecmp(nick).zero?
			post server_name, ERR_NOSUCHNICK, nick, "No such nick/channel" # or yourself
			return
		end

		friend = friend(nick)

		case
		when channel.casecmp(main_channel).zero?
			case
			when friend #TODO
			when api("users/username_available", { :username => nick }).valid
				post server_name, ERR_NOSUCHNICK, nick, "No such nick/channel"
			else
				user = api("friendships/create/#{nick}")
				join main_channel, [user]
				@friends << user if @friends
				@me.friends_count += 1
			end
		when friend
			((@groups[channel] ||= []) << friend.screen_name).uniq!
			join channel, [friend]
			save_config
		else
			post server_name, ERR_NOSUCHNICK, nick, "No such nick/channel"
		end
	end

	def on_kick(m)
		channel, nick, msg = *m.params

		if channel.casecmp(main_channel).zero?
			@friends.delete_if do |friend|
				if friend.screen_name.casecmp(nick).zero?
					user = api("friendships/destroy/#{friend.id}")
					if user.is_a? User
						post prefix(user), PART, main_channel, "Removed: #{msg}"
						@me.friends_count -= 1
					end
				end
			end if @friends
		else
			friend = friend(nick)
			if friend
				(@groups[channel] ||= []).delete(friend.screen_name)
				post prefix(friend), PART, channel, "Removed: #{msg}"
				save_config
			else
				post server_name, ERR_NOSUCHNICK, nick, "No such nick/channel"
			end
		end
	end

	#def on_nick(m)
	#	@nicknames[@nick] = m.params[0]
	#end

	def on_topic(m)
		channel = m.params[0]
		return if not channel.casecmp(main_channel).zero? or @me.status.nil?

		return if not @opts.mesautofix
		begin
			require "levenshtein"
			topic    = m.params[1]
			previous = @me.status
			return unless previous

			distance = Levenshtein.normalized_distance(previous.text, topic)
			return if distance.zero?

			status = api("statuses/update", { :status => topic, :source => source })
			log oops(ret) if status.truncated
			status.user.status = status
			@me = status.user

			if distance < 0.5
				deleted = api("statuses/destroy/#{previous.id}")
				@timeline.delete_if {|tid, s| s.id == deleted.id }
				log "Similar update in previous. Conclude that it has error."
				log "And overwrite previous as new status: #{status.text}"
			else
				log "Status updated"
			end
		rescue LoadError
		end
	end

	def on_mode(m)
		channel = m.params[0]

		unless m.params[1]
			case
			when channel.ch?
				mode = "+mt"
				mode += "i" unless channel.casecmp(main_channel).zero?
				post server_name, RPL_CHANNELMODEIS, @nick, channel, mode
				#post server_name, RPL_CREATEONTIME, @nick, channel, 0
			when channel.casecmp(@nick).zero?
				post server_name, RPL_UMODEIS, @nick, @nick, "+o"
			end
		end
	end

	private
	def on_ctcp(target, mesg)
		type, mesg = mesg.split(" ", 2)
		method = "on_ctcp_#{type.downcase}".to_sym
		send(method, target, mesg) if respond_to? method, true
	end

	def on_ctcp_action(target, mesg)
		#return unless main_channel.casecmp(target).zero?
		command, *args = mesg.split(" ")
		if command
			command.downcase!

			@@ctcp_action_commands.each do |define, name|
				if define === command
					send(name, target, mesg, Regexp.last_match || command, args)
					break
				end
			end
		else
			commands = @@ctcp_action_commands.map {|define, name|
				define
			}.select {|define|
				define.is_a? String
			}

			log "[tig.rb] CTCP ACTION COMMANDS:"
			commands.each_slice(5) do |c|
				log c.join(" ")
			end
		end

	rescue APIFailed => e
		log e.inspect
	rescue Exception => e
		log e.inspect
		e.backtrace.each do |l|
			@log.error "\t#{l}"
		end
	end

	ctcp_action "call" do |target, mesg, command, args|
		if args.size < 2
			log "/me call <Twitter_screen_name> as <IRC_nickname>"
			return
		end
		screen_name = args[0]
		nickname    = args[2] || args[1] # allow omitting "as"
		if nickname == "is" and
		   deleted_nick = @nicknames.delete(screen_name)
			log %Q{Removed the nickname "#{deleted_nick}" for #{screen_name}}
		else
			@nicknames[screen_name] = nickname
			log "Call #{screen_name} as #{nickname}"
		end
		#save_config
	end

	ctcp_action "debug" do |target, mesg, command, args|
		code = args.join(" ")
		begin
			log instance_eval(code).inspect
		rescue Exception => e
			log e.inspect
		end
	end

	ctcp_action "utf-7", "utf7" do |target, mesg, command, args|
		unless defined? ::Iconv
			log "Can't load iconv."
			return
		end
		@utf7 = !@utf7
		log "UTF-7 mode: #{@utf7 ? 'on' : 'off'}"
	end

	ctcp_action "list", "ls" do |target, mesg, command, args|
		if args.empty?
			log "/me list <NICK> [<NUM>]"
			return
		end
		nick = args.first
		if not nick.screen_name? or
		   api("users/username_available", { :username => nick }).valid
			post server_name, ERR_NOSUCHNICK, nick, "No such nick/channel"
			return
		end
		id           = nick
		authenticate = false
		if user = friend(nick)
			id           = user.id
			nick         = user.screen_name
			authenticate = user.protected
		end
		unless (1..200).include?(count = args[1].to_i)
			count = 20
		end
		begin
			res = api("statuses/user_timeline/#{id}",
					  { :count => count }, { :authenticate => authenticate })
		rescue APIFailed
			#log "#{nick} has protected their updates."
			return
		end
		res.reverse_each do |s|
			message(s, target, nil, nil, NOTICE)
		end
	end

	ctcp_action %r/\A(un)?fav(?:ou?rite)?(!)?\z/ do |target, mesg, command, args|
		# fav, unfav, favorite, unfavorite, favourite, unfavourite
		method   = command[1].nil? ? "create" : "destroy"
		force    = !!command[2]
		entered  = command[0].capitalize
		statuses = []
		if args.empty?
			if method == "create"
				if status = @timeline.last
					statuses << status
				else
					#log ""
					return
				end
			else
				@favorites ||= api("favorites").reverse
				if @favorites.empty?
					log "You've never favorite yet. No favorites to unfavorite."
					return
				end
				statuses.push @favorites.last
			end
		else
			args.each do |tid_or_nick|
				case
				when status = @timeline[tid = tid_or_nick]
					statuses.push status
				when friend = friend(nick = tid_or_nick)
					if friend.status
						statuses.push friend.status
					else
						log "#{tid_or_nick} has no status."
					end
				else
					# PRIVMSG: fav nick
					log "No such ID/NICK #{@opts.tid % tid_or_nick}"
				end
			end
		end
		@favorites ||= []
		statuses.each do |s|
			if not force and method == "create" and
			   @favorites.find {|i| i.id == s.id }
				log "The status is already favorited! <#{permalink(s)}>"
				next
			end
			res = api("favorites/#{method}/#{s.id}")
			log "#{entered}: #{res.user.screen_name}: #{generate_status_message(res.text)}"
			if method == "create"
				@favorites.push res
			else
				@favorites.delete_if {|i| i.id == res.id }
			end
		end
	end

	ctcp_action "link", "ln", /\Au(?:rl)?\z/ do |target, mesg, command, args|
		args.each do |tid|
			if status = @timeline[tid]
				log "#{@opts.tid % tid}: #{permalink(status)}"
			else
				log "No such ID #{@opts.tid % tid}"
			end
		end
	end

	ctcp_action "ratio", "ratios" do |target, mesg, command, args|
		unless args.empty?
			args = args.first.split(":") if args.size == 1
			case
			when @opts.dm && @opts.mentions && args.size < 3
				log "/me ratios <timeline> <dm> <mentions>"
				return
			when @opts.dm && args.size < 2
				log "/me ratios <timeline> <dm>"
				return
			when @opts.mentions && args.size < 2
				log "/me ratios <timeline> <mentions>"
				return
			end
			ratios = args.map {|ratio| ratio.to_f }
			if ratios.any? {|ratio| ratio <= 0.0 }
				log "Ratios must be greater than 0.0 and fractional values are permitted."
				return
			end
			@ratio.timeline = ratios[0]

			case
			when @opts.dm
				@ratio.dm       = ratios[1]
				@ratio.mentions = ratios[2] if @opts.mentions
			when @opts.mentions
				@ratio.mentions = ratios[1]
			end
		end
		log "Intervals: " + @ratio.zip([:timeline, :dm, :mentions]).map {|ratio, name| [name,  "#{interval(ratio).round}sec"] }.inspect
	end

	ctcp_action "rm", %r/\A(?:de(?:stroy|l(?:ete)?)|miss|oops|r(?:emove|m))\z/ do |target, mesg, command, args|
	# destroy, delete, del, remove, rm, miss, oops
		statuses = []
		if args.empty? and @me.status
			statuses.push @me.status
		else
			args.each do |tid|
				if status = @timeline[tid]
					if status.user.id == @me.id
						statuses.push status
					else
						log "The status you specified by the ID #{@opts.tid % tid} is not yours."
					end
				else
					log "No such ID #{@opts.tid % tid}"
				end
			end
		end
		b = false
		statuses.each do |st|
			res = api("statuses/destroy/#{st.id}")
			@timeline.delete_if {|tid, s| s.id == res.id }
			b = @me.status && @me.status.id == res.id
			log "Destroyed: #{res.text}"
		end
		Thread.start do
			sleep 2
			@me = api("account/update_profile") #api("account/verify_credentials")
			if @me.status
				@me.status.user = @me
				msg = generate_status_message(@me.status.text)
				@timeline.any? do |tid, s|
					if s.id == @me.status.id
						msg << " " << @opts.tid % tid
					end
				end
				post @prefix, TOPIC, main_channel, msg
			end
		end if b
	end

	ctcp_action "name" do |target, mesg, command, args|
		name = mesg.split(" ", 2)[1]
		unless name.nil?
			@me = api("account/update_profile", { :name => name })
			@me.status.user = @me if @me.status
			log "You are named #{@me.name}."
		end
	end

	ctcp_action "email" do |target, mesg, command, args|
		# FIXME
		email = args.first
		unless email.nil?
			@me = api("account/update_profile", { :email => email })
			@me.status.user = @me if @me.status
		end
	end

	ctcp_action "url" do |target, mesg, command, args|
		# FIXME
		url = args.first || ""
		@me = api("account/update_profile", { :url => url })
		@me.status.user = @me if @me.status
	end

	ctcp_action "in", "location" do |target, mesg, command, args|
		location = mesg.split(" ", 2)[1] || ""
		@me = api("account/update_profile", { :location => location })
		@me.status.user = @me if @me.status
		location = (@me.location and @me.location.empty?) ? "nowhere" : "in #{@me.location}"
		log "You are #{location} now."
	end

	ctcp_action %r/\Adesc(?:ription)?\z/ do |target, mesg, command, args|
		# FIXME
		description = mesg.split(" ", 2)[1] || ""
		@me = api("account/update_profile", { :description => description })
		@me.status.user = @me if @me.status
	end

	ctcp_action %r/\A(?:mention|re(?:ply)?)\z/ do |target, mesg, command, args|
		# reply, re, mention
		tid = args.first
		if status = @timeline[tid]
			text = mesg.split(" ", 3)[2]
			screen_name = "@#{status.user.screen_name}"
			if text.nil? or not text.include?(screen_name)
				text = "#{screen_name} #{text}"
			end
			ret = api("statuses/update", { :status => text, :source => source,
										   :in_reply_to_status_id => status.id })
			log oops(ret) if ret.truncated
			msg = generate_status_message(status.text)
			url = permalink(status)
			log "Status updated (In reply to #{@opts.tid % tid}: #{msg} <#{url}>)"
			ret.user.status = ret
			@me = ret.user
		end
	end

	ctcp_action %r/\Aspoo(o+)?f\z/ do |target, mesg, command, args|
		if args.empty?
			Thread.start do
				update_sources(command[1].nil?? 0 : command[1].size)
			end
			return
		end
		names = []
		@sources = args.map do |arg|
			names << "=#{arg}"
			case arg.upcase
			when "WEB" then ""
			when "API" then nil
			else            arg
			end
		end
		log(names.inject([]) do |r, name|
			s = r.join(", ")
			if s.size < 400
				r << name
			else
				log s
				[name]
			end
		end.join(", "))
	end

	ctcp_action "bot", "drone" do |target, mesg, command, args|
		if args.empty?
			log "/me bot <NICK> [<NICK>...]"
			return
		end
		args.each do |bot|
			user = friend(bot)
			unless user
				post server_name, ERR_NOSUCHNICK, bot, "No such nick/channel"
				next
			end
			if @drones.delete(user.id)
				mode = "-#{mode}"
				log "#{bot} is no longer a bot."
			else
				@drones << user.id
				mode = "+#{mode}"
				log "Marks #{bot} as a bot."
			end
		end
		save_config

	end

	ctcp_action "home", "h" do |target, mesg, command, args|
		if args.empty?
			log "/me home <NICK>"
			return
		end
		nick = args.first
		if not nick.screen_name? or
		   api("users/username_available", { :username => nick }).valid
			post server_name, ERR_NOSUCHNICK, nick, "No such nick/channel"
			return
		end
		log "http://twitter.com/#{nick}"
	end

	ctcp_action "retweet", "rt" do |target, mesg, command, args|
		if args.empty?
			log "/me #{command} <ID> blah blah"
			return
		end
		tid = args.first
		if status = @timeline[tid]
			if args.size >= 2
				comment = mesg.split(" ", 3)[2] + " "
			else
				comment = ""
			end
			screen_name = "@#{status.user.screen_name}"
			rt_message = generate_status_message(status.text)
			text = "#{comment}RT #{screen_name}: #{rt_message}"
			ret = api("statuses/update", { :status => text, :source => source })
			log oops(ret) if ret.truncated
			log "Status updated (RT to #{@opts.tid % tid}: #{text})"
			ret.user.status = ret
			@me = ret.user
		end
	end

	def on_ctcp_clientinfo(target, msg)
		if user = user(target)
			post prefix(user), NOTICE, @nick, ctcp_encode("CLIENTINFO :CLIENTINFO USERINFO VERSION TIME")
		end
	end

	def on_ctcp_userinfo(target, msg)
		user = user(target)
		if user and not user.description.empty?
			post prefix(user), NOTICE, @nick, ctcp_encode("USERINFO :#{user.description}")
		end
	end

	def on_ctcp_version(target, msg)
		user = user(target)
		if user and user.status
			source = user.status.source
			version = source.gsub(/<[^>]*>/, "").strip
			version << " <#{$1}>" if / href="([^"]+)/ === source
			post prefix(user), NOTICE, @nick, ctcp_encode("VERSION :#{version}")
		end
	end

	def on_ctcp_time(target, msg)
		if user = user(target)
			offset = user.utc_offset
			post prefix(user), NOTICE, @nick, ctcp_encode("TIME :%s%s (%s)" % [
				(Time.now + offset).utc.iso8601[0, 19],
				"%+.2d:%.2d" % (offset/60).divmod(60),
				user.time_zone,
			])
		end
	end

	def check_friends
		if @friends.nil?
			@friends = page("statuses/friends/#{@me.id}", @me.friends_count)
			if @opts.athack
				join main_channel, @friends
			else
				rest = @friends.map do |i|
					prefix = "+" #@drones.include?(i.id) ? "%" : "+" # FIXME ~&%
					"#{prefix}#{i.screen_name}"
				end.reverse.inject("~#{@nick}") do |r, nick|
					if r.size < 400
						r << " " << nick
					else
						post server_name, RPL_NAMREPLY, @nick, "=", main_channel, r
						nick
					end
				end
				post server_name, RPL_NAMREPLY, @nick, "=", main_channel, rest
				post server_name, RPL_ENDOFNAMES, @nick, main_channel, "End of NAMES list"
			end
		else
			new_ids    = page("friends/ids/#{@me.id}", @me.friends_count)
			friend_ids = @friends.reverse.map {|friend| friend.id }

			(friend_ids - new_ids).each do |id|
				@friends.delete_if do |friend|
					if friend.id == id
						post prefix(friend), PART, main_channel, ""
						@me.friends_count -= 1
					end
				end
			end

			new_ids -= friend_ids
			unless new_ids.empty?
				new_friends = page("statuses/friends/#{@me.id}", new_ids.size)
				join main_channel, new_friends.delete_if {|friend|
					@friends.any? {|i| i.id == friend.id }
				}.reverse
				@friends.concat new_friends
				@me.friends_count += new_friends.size
			end
		end
	end

	def check_timeline
		cmd  = PRIVMSG
		path = "statuses/#{@opts.with_retweets ? "home" : "friends"}_timeline"
		q    = { :count => 200 }
		@latest_id ||= nil

		case 
		when @latest_id
			q.update(:since_id => @latest_id)
		when is_first_retrieve = !@me.statuses_count.zero? && !@me.friends_count.zero?
		#	cmd = NOTICE # デバッグするときめんどくさいので
			q.update(:count => 20)
		end

		api(path, q).reverse_each do |status|
			id = @latest_id = status.id
			next if @timeline.any? {|tid, s| s.id == id }

			status.user.status = status
			user = status.user
			tid  = @timeline.push(status)
			tid  = nil unless @opts.tid

			@log.debug [id, user.screen_name, status.text].inspect

			if user.id == @me.id
				mesg = generate_status_message(status.text)
				mesg << " " << @opts.tid % tid if tid
				post @prefix, TOPIC, main_channel, mesg

				@me = user
			else
				if @friends
					b = false
					@friends.each_with_index do |friend, i|
						if b = friend.id == user.id
							if friend.screen_name != user.screen_name
								post prefix(friend), NICK, user.screen_name
							end
							@friends[i] = user
							break
						end
					end
					unless b
						join main_channel, [user]
						@friends << user
						@me.friends_count += 1
					end
				end

				message(status, main_channel, tid, nil, cmd)
			end
			@groups.each do |channel, members|
				next unless members.include?(user.screen_name)
				message(status, channel, tid, nil, cmd)
			end
		end
	end

	def check_direct_messages
		@prev_dm_id ||= nil
		q = @prev_dm_id ? { :count => 200, :since_id => @prev_dm_id } \
		                : { :count => 1 }
		api("direct_messages", q).reverse_each do |mesg|
			unless @prev_dm_id &&= mesg.id
				@prev_dm_id = mesg.id
				next
			end

			id   = mesg.id
			user = mesg.sender
			tid  = nil
			text = mesg.text
			@log.debug [id, user.screen_name, text].inspect
			message(user, @nick, tid, text)
		end
	end

	def check_mentions
		return if @timeline.empty?
		@prev_mention_id ||= @timeline.last.id
		api("statuses/mentions", {
			:count    => 200,
			:since_id => @prev_mention_id
		}).reverse_each do |mention|
			id = @prev_mention_id = mention.id
			next if @timeline.any? {|tid, s| s.id == id }

			mention.user.status = mention
			user = mention.user
			tid  = @timeline.push(mention)
			tid  = nil unless @opts.tid

			@log.debug [id, user.screen_name, mention.text].inspect
			message(mention, main_channel, tid)

			@friends.each_with_index do |friend, i|
				if friend.id == user.id
					@friends[i] = user
					break
				end
			end if @friends
		end
	end

	def check_updates
		update_redundant_suffix

		uri = URI("http://github.com/api/v1/json/cho45/net-irc/commits/master")
		@log.debug uri.inspect
		res = http(uri).request(http_req(:get, uri))

		latest = JSON.parse(res.body)['commits'][0]['id']
		unless server_version == latest
			log "\002New version is available.\017 run 'git pull'."
		end
	rescue Errno::ECONNREFUSED, Timeout::Error => e
		@log.error "Failed to get the latest revision of tig.rb from #{uri.host}: #{e.inspect}"
	end

	def interval(ratio)
		now   = Time.now
		max   = @opts.maxlimit || 0
		limit = 0.98 * @limit # 98% of the rate limit
		i     = 3600.0        # an hour in seconds
		i *= @ratio.inject {|sum, r| sum.to_f + r.to_f } +
		     @consums.delete_if {|t| t < now }.size
		i /= ratio.to_f
		i /= (0 < max && max < limit) ? max : limit
		i = 60 * 30 if i > 60 * 30 # 30分以上止まらないように。
		i
	rescue => e
		@log.error e.inspect
		100
	end

	def join(channel, users)
		params = []
		users.each do |user|
			prefix = prefix(user)
			post prefix, JOIN, channel
			params << prefix.nick if user.protected
			next if params.size < MAX_MODE_PARAMS

			post server_name, MODE, channel, "+#{"v" * params.size}", *params
			params = []
		end
		post server_name, MODE, channel, "+#{"v" * params.size}", *params unless params.empty?
		users
	end

	def start_jabber(jid, pass)
		@log.info "Logging-in with #{jid} -> jabber_bot_id: #{jabber_bot_id}"
		@im = Jabber::Simple.new(jid, pass)
		@im.add(jabber_bot_id)
		@im_thread = Thread.start do
			require "cgi"

			loop do
				begin
					@im.received_messages.each do |msg|
						@log.debug [msg.from, msg.body].inspect
						if msg.from.strip == jabber_bot_id
							# Twitter -> 'id: msg'
							body = msg.body.sub(/\A(.+?)(?:\(([^()]+)\))?: /, "")
							body = decode_utf7(body)

							if Regexp.last_match
								nick, id = Regexp.last_match.captures
								body = untinyurl(CGI.unescapeHTML(body))
								user = nick
								nick = id || nick
								nick = @nicknames[nick] || nick
								post "#{nick}!#{user}@#{api_base.host}", PRIVMSG, main_channel, body
							end
						end
					end
				rescue Exception => e
					@log.error "Error on Jabber loop: #{e.inspect}"
					e.backtrace.each do |l|
						@log.error "\t#{l}"
					end
				end
				sleep 1
			end
		end
	end

	def save_config
		config = {
			:groups    => @groups,
			:channels  => @channels,
			#:nicknames => @nicknames,
			:drones    => @drones,
		}
		@config.open("w") {|f| YAML.dump(config, f) }
	end

	def load_config
		@config.open do |f|
			config     = YAML.load(f)
			@groups    = config[:groups]    || {}
			@channels  = config[:channels]  || []
			#@nicknames = config[:nicknames] || {}
			@drones    = config[:drones]    || []
		end
	rescue Errno::ENOENT
	end

	def require_post?(path)
		%r{
			\A
			(?: status(?:es)?/update \z
			  | direct_messages/new \z
			  | friendships/create/
			  | account/(?: end_session \z | update_ )
			  | favou?ri(?: ing | tes )/create/
			  | notifications/
			  | blocks/create/ )
		}x === path
	end

	#def require_put?(path)
	#	%r{ \A status(?:es)?/retweet (?:/|\z) }x === path
	#end

	def api(path, query = {}, opts = {})
		path.sub!(%r{\A/+}, "")
		query = query.to_query_str

		authenticate = opts.fetch(:authenticate, true)

		uri = api_base(authenticate)
		uri.path += path
		uri.path += ".json" if path != "users/username_available"
		uri.query = query unless query.empty?

		header      = {}
		credentials = authenticate ? [@real, @pass] : nil
		req         = case
			when path.include?("/destroy/")
				http_req :delete, uri, header, credentials
			when require_post?(path)
				http_req :post,   uri, header, credentials
			#when require_put?(path)
			#	http_req :put,    uri, header, credentials
			else
				http_req :get,    uri, header, credentials
		end

		@log.debug [req.method, uri.to_s]
		ret = http(uri, 30, 30).request req

		#@etags[uri.to_s] = ret["ETag"]

		case
		when authenticate
			hourly_limit = ret["X-RateLimit-Limit"].to_i
			unless hourly_limit.zero?
				if @limit != hourly_limit
					msg = "The rate limit per hour was changed: #{@limit} to #{hourly_limit}"
					log msg
					@log.info msg
					@limit = hourly_limit
				end

				#if req.is_a?(Net::HTTP::Get) and not %w{
				if not %w{
					statuses/friends_timeline
					direct_messages
					statuses/mentions
				}.include?(path) and not ret.is_a?(Net::HTTPServerError)
					expired_on = Time.parse(ret["Date"]) rescue Time.now
					expired_on += 3636 # 1.01 hours in seconds later
					@consums << expired_on
				end
			end
		when ret["X-RateLimit-Remaining"]
			@limit_remaining_for_ip = ret["X-RateLimit-Remaining"].to_i
			@log.debug "IP based limit: #{@limit_remaining_for_ip}"
		end

		case ret
		when Net::HTTPOK # 200
			# Avoid Twitter's invalid JSON
			json = ret.body.strip.sub(/\A(?:false|true)\z/, "[\\&]")

			res = JSON.parse json
			if res.is_a?(Hash) and res["error"] # and not res["response"]
				if @error != res["error"]
					@error = res["error"]
					log @error
				end
				raise APIFailed, res["error"]
			end
			res.to_tig_struct
		when Net::HTTPNoContent,  # 204
		     Net::HTTPNotModified # 304
			[]
		when Net::HTTPBadRequest # 400: exceeded the rate limitation
			if ret.key?("X-RateLimit-Reset")
				s = ret["X-RateLimit-Reset"].to_i - Time.now.to_i
				if s > 0
					log "RateLimit: #{(s / 60.0).ceil} min remaining to get timeline"
					sleep (s > 60 * 10) ? 60 * 10 : s # 10 分に一回はとってくるように
				end
			end
			raise APIFailed, "#{ret.code}: #{ret.message}"
		when Net::HTTPUnauthorized # 401
			raise APIFailed, "#{ret.code}: #{ret.message}"
		else
			raise APIFailed, "Server Returned #{ret.code} #{ret.message}"
		end
	rescue Errno::ETIMEDOUT, JSON::ParserError, IOError, Timeout::Error, Errno::ECONNRESET => e
		raise APIFailed, e.inspect
	end

	def page(path, max_count, authenticate = false)
		@limit_remaining_for_ip ||= 52
		limit = 0.98 * @limit_remaining_for_ip # 98% of IP based rate limit
		r     = []
		cpp   = nil # counts per page
		1.upto(limit) do |num|
			ret = api(path, { :page => num }, { :authenticate => authenticate })
			cpp ||= ret.size
			r.concat ret
			break if ret.empty? or num >= max_count / cpp.to_f or
			         ret.size != cpp or r.size >= max_count
		end
		r
	end

	def generate_status_message(mesg)
		mesg = decode_utf7(mesg)
		mesg.delete!("\000\001")
		mesg.gsub!("&gt;", ">")
		mesg.gsub!("&lt;", "<")
		mesg.gsub!(WSP_REGEX, " ")
		mesg = untinyurl(mesg)
		mesg.sub!(@rsuffix_regex, "") if @rsuffix_regex
		mesg.strip
	end

	def friend(id)
		return nil unless @friends
		if id.is_a? String
			@friends.find {|i| i.screen_name.casecmp(id).zero? }
		else
			@friends.find {|i| i.id == id }
		end
	end

	def user(id)
		if id.is_a? String
			@nick.casecmp(id).zero? ? @me : friend(id)
		else
			@me.id == id ? @me : friend(id)
		end
	end

	def prefix(u)
		nick = u.screen_name
		nick = "@#{nick}" if @opts.athack
		user = "id=%.9d" % u.id
		host = api_base.host
		host += "/protected" if u.protected
		host += "/bot"       if @drones.include?(u.id)

		Prefix.new("#{nick}!#{user}@#{host}")
	end

	def message(struct, target, tid = nil, str = nil, command = PRIVMSG)
		unless str
			status = struct.is_a?(Status) ? struct : struct.status
			str = status.text
			if command != PRIVMSG
				time = Time.parse(status.created_at) rescue Time.now
				str  = "#{time.strftime(@opts.strftime || "%m-%d %H:%M")} #{str}" # TODO: color
			end
		end
		user        = (struct.is_a?(User) ? struct : struct.user).dup
		screen_name = user.screen_name

		user.screen_name = @nicknames[screen_name] || screen_name
		prefix = prefix(user)
		str    = generate_status_message(str)
		str    = "#{str} #{@opts.tid % tid}" if tid

		post prefix, command, target, str
	end

	def log(str)
		post server_name, NOTICE, main_channel, str.gsub(/\r\n|[\r\n]/, " ")
	end

	def decode_utf7(str)
		return str unless defined? ::Iconv and str.include?("+")

		str.sub!(/\A(?:.+ > |.+\z)/) { Iconv.iconv("UTF-8", "UTF-7", $&).join }
		#FIXME str = "[utf7]: #{str}" if str =~ /[^a-z0-9\s]/i
		str
	rescue Iconv::IllegalSequence
		str
	rescue => e
		@log.error e
		str
	end

	def untinyurl(text)
		text.gsub(@opts.untiny_whole_urls ? URI.regexp(%w[http https]) : %r{
			http:// (?:
				(?: bit\.ly | (?: tin | rub) yurl\.com
				  | is\.gd | cli\.gs | tr\.im | u\.nu | airme\.us
				  | ff\.im | twurl.nl | bkite\.com | tumblr\.com
				  | pic\.gd | sn\.im | digg\.com )
				/ [0-9a-z=-]+ |
				blip\.fm/~ (?> [0-9a-z]+) (?! /) |
				flic\.kr/[a-z0-9/]+
			)
		}ix) {|url| "#{resolve_http_redirect(URI(url)) || url}" }
	end

	def bitlify(text)
		login, key, len = @opts.bitlify.split(":", 3) if @opts.bitlify
		len      = (len || 20).to_i
		longurls = URI.extract(text, %w[http https]).uniq.map do |url|
			URI.rstrip url
		end.reject do |url|
			url.size < len
		end
		return text if longurls.empty?

		bitly = URI("http://api.bit.ly/shorten")
		if login and key
			bitly.path  = "/shorten"
			bitly.query = {
				:version => "2.0.1", :format => "json", :longUrl => longurls,
			}.to_query_str(";")
			@log.debug bitly
			req = http_req(:get, bitly, {}, [login, key])
			res = http(bitly, 5, 10).request(req)
			res = JSON.parse(res.body)
			res = res["results"]

			longurls.each do |longurl|
				text.gsub!(longurl) do
					res[$&] && res[$&]["shortUrl"] || $&
				end
			end
		else
			bitly.path = "/api"
			longurls.each do |longurl|
				bitly.query = { :url => longurl }.to_query_str
				@log.debug bitly
				req = http_req(:get, bitly)
				res = http(bitly, 5, 5).request(req)
				text.gsub!(longurl, res.body)
			end
		end

		text
	rescue => e
		@log.error e
		text
	end

	def unuify(text)
		unu_url = "http://u.nu/"
		unu     = URI("#{unu_url}unu-api-simple")
		size    = unu_url.size

		text.gsub(URI.regexp(%w[http https])) do |url|
			url = URI.rstrip url
			if url.size < size + 5 or url[0, size] == unu_url
				return url
			end

			unu.query = { :url => url }.to_query_str
			@log.debug unu

			res = http(unu, 5, 5).request(http_req(:get, unu)).body

			if res[0, 12] == unu_url
				res
			else
				raise res.split("|")
			end
		end
	rescue => e
		@log.error e
		text
	end

	def escape_http_urls(text)
		original_text = text.encoding!("UTF-8").dup

		if defined? ::Punycode
			# TODO: Nameprep
			text.gsub!(%r{(https?://)([^\x00-\x2C\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+)}) do
				domain = $2
				# Dots:
				#   * U+002E (full stop)           * U+3002 (ideographic full stop)
				#   * U+FF0E (fullwidth full stop) * U+FF61 (halfwidth ideographic full stop)
				# => /[.\u3002\uFF0E\uFF61] # Ruby 1.9 /x
				$1 + domain.split(/\.|\343\200\202|\357\274\216|\357\275\241/).map do |label|
					break [domain] if /\A-|[\x00-\x2C\x2E\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]|-\z/ === label
					next label unless /[^-A-Za-z0-9]/ === label
					punycode = Punycode.encode(label)
					break [domain] if punycode.size > 59
					"xn--#{punycode}"
				end.join(".")
			end
			if text != original_text
				log "Punycode encoded: #{text}"
				original_text = text.dup
			end
		end

		urls = []
		text.split(/[\s<>]+/).each do |str|
			next if /%[0-9A-Fa-f]{2}/ === str
			# URI::UNSAFE + "#"
			escaped_str = URI.escape(str, %r{[^-_.!~*'()a-zA-Z0-9;/?:@&=+$,\[\]#]})
			URI.extract(escaped_str, %w[http https]).each do |url|
				uri = URI(URI.rstrip(url))
				if not urls.include?(uri.to_s) and exist_uri?(uri)
					urls << uri.to_s
				end
			end if escaped_str != str
		end
		urls.each do |url|
			unescaped_url = URI.unescape(url).encoding!("UTF-8")
			text.gsub!(unescaped_url, url)
		end
		log "Percent encoded: #{text}" if text != original_text

		text.encoding!("ASCII-8BIT")
	rescue => e
		@log.error e
		text
	end

	def exist_uri?(uri, limit = 1)
		ret = nil
		#raise "Not supported." unless uri.is_a?(URI::HTTP)
		return ret if limit.zero? or uri.nil? or not uri.is_a?(URI::HTTP)
		@log.debug uri.inspect

		req = http_req :head, uri
		http(uri, 3, 2).request(req) do |res|
			ret = case res
				when Net::HTTPSuccess
					true
				when Net::HTTPRedirection
					uri = resolve_http_redirect(uri)
					exist_uri?(uri, limit - 1)
				when Net::HTTPClientError
					false
				#when Net::HTTPServerError
				#	nil
				else
					nil
			end
		end

		ret
	rescue => e
		@log.error e.inspect
		ret
	end

	def resolve_http_redirect(uri, limit = 3)
		return uri if limit.zero? or uri.nil?
		@log.debug uri.inspect

		req = http_req :head, uri
		http(uri, 3, 2).request(req) do |res|
			break if not res.is_a?(Net::HTTPRedirection) or
			         not res.key?("Location")
			begin
				location = URI(res["Location"])
			rescue URI::InvalidURIError
			end
			unless location.is_a? URI::HTTP
				begin
					location = URI.join(uri.to_s, res["Location"])
				rescue URI::InvalidURIError, URI::BadURIError
					# FIXME
				end
			end
			uri = resolve_http_redirect(location, limit - 1)
		end

		uri
	rescue => e
		@log.error e.inspect
		uri
	end

	def update_sources(n = 0)
		if @sources and @sources.size > 1 and n.zero?
			log "tig.rb"
			@sources = [api_source]
			return @sources
		end

		uri = URI("http://wedata.net/databases/TwitterSources/items.json")
		@log.debug uri.inspect
		json    = http(uri).request(http_req(:get, uri)).body
		sources = JSON.parse json
		sources.map! {|item| [item["data"]["source"], item["name"]] }
		sources.push ["", "web"]
		sources.push [nil, "API"]

		sources = Array.new(n) do
			sources.delete_at(rand(sources.size))
		end if (1 ... sources.size).include?(n)

		log(sources.inject([]) do |r, src|
			s = r.join(", ")
			if s.size < 400
				r << src[1]
			else
				log s
				[src[1]]
			end
		end.join(", ")) if @sources

		@sources = sources.map {|src| src[0] }
	rescue => e
		@log.error e.inspect
		log "An error occured while loading #{uri.host}."
		@sources ||= [api_source]
	end

	def update_redundant_suffix
		uri = URI("http://svn.coderepos.org/share/platform/twitterircgateway/suffixesblacklist.txt")
		@log.debug uri.inspect
		res = http(uri).request(http_req(:get, uri))
		@etags[uri.to_s] = res["ETag"]
		return if res.is_a? Net::HTTPNotModified
		source = res.body
		source.encoding!("UTF-8") if source.respond_to?(:encoding) and source.encoding == Encoding::BINARY
		@rsuffix_regex = /#{Regexp.union(*source.split)}\z/
	rescue Errno::ECONNREFUSED, Timeout::Error => e
		@log.error "Failed to get the redundant suffix blacklist from #{uri.host}: #{e.inspect}"
	end

	def http(uri, open_timeout = nil, read_timeout = 60)
		http = case
			when @httpproxy
				Net::HTTP.new(uri.host, uri.port, @httpproxy.address, @httpproxy.port,
				                                  @httpproxy.user, @httpproxy.password)
			when ENV["HTTP_PROXY"], ENV["http_proxy"]
				proxy = URI(ENV["HTTP_PROXY"] || ENV["http_proxy"])
				Net::HTTP.new(uri.host, uri.port, proxy.host, proxy.port,
				                                  proxy.user, proxy.password)
			else
				Net::HTTP.new(uri.host, uri.port)
		end
		http.open_timeout = open_timeout if open_timeout # nil by default
		http.read_timeout = read_timeout if read_timeout # 60 by default
		if uri.is_a? URI::HTTPS
			http.use_ssl     = true
			http.verify_mode = OpenSSL::SSL::VERIFY_NONE
		end
		http
	rescue => e
		@log.error e
	end

	def http_req(method, uri, header = {}, credentials = nil)
		accepts = ["*/*;q=0.1"]
		#require "mime/types"; accepts.unshift MIME::Types.of(uri.path).first.simplified
		types   = { "json" => "application/json", "txt" => "text/plain" }
		ext     = uri.path[/[^.]+\z/]
		accepts.unshift types[ext] if types.key?(ext)
		user_agent = "#{self.class}/#{server_version} (#{File.basename(__FILE__)}; net-irc) Ruby/#{RUBY_VERSION} (#{RUBY_PLATFORM})"

		header["User-Agent"]      ||= user_agent
		header["Accept"]          ||= accepts.join(",")
		header["Accept-Charset"]  ||= "UTF-8,*;q=0.0" if ext != "json"
		#header["Accept-Language"] ||= @opts.lang # "en-us,en;q=0.9,ja;q=0.5"
		header["If-None-Match"]   ||= @etags[uri.to_s] if @etags[uri.to_s]

		req = case method.to_s.downcase.to_sym
		when :get
			Net::HTTP::Get.new    uri.request_uri, header
		when :head
			Net::HTTP::Head.new   uri.request_uri, header
		when :post
			Net::HTTP::Post.new   uri.path,        header
		when :put
			Net::HTTP::Put.new    uri.path,        header
		when :delete
			Net::HTTP::Delete.new uri.request_uri, header
		else # raise ""
		end
		if req.request_body_permitted?
			req["Content-Type"] ||= "application/x-www-form-urlencoded"
			req.body = uri.query
		end
		req.basic_auth(*credentials) if credentials
		req
	rescue => e
		@log.error e
	end

	def oops(status)
		"Oops! Your update was over 140 characters. We sent the short version" <<
		" to your friends (they can view the entire update on the Web <" <<
		permalink(status) << ">)."
	end

	def permalink(struct)
		path = struct.is_a?(Status) ? "#{struct.user.screen_name}/statuses/#{struct.id}" \
		                            : struct.screen_name
		"http://twitter.com/#{path}"
	end

	def source
		@sources[rand(@sources.size)]
	end

	def initial_message
		super
		post server_name, RPL_ISUPPORT, @nick,
		     "PREFIX=(qov)~@%+", "CHANTYPES=#", "CHANMODES=#{available_channel_modes}",
		     "MODES=#{MAX_MODE_PARAMS}", "NICKLEN=15", "TOPICLEN=420", "CHANNELLEN=50",
		     "NETWORK=Twitter",
		     "are supported by this server"
	end

	User   = Struct.new(:id, :name, :screen_name, :location, :description, :url,
	                    :following, :notifications, :protected, :time_zone,
	                    :utc_offset, :created_at, :friends_count, :followers_count,
	                    :statuses_count, :favourites_count, :verified, :geo_enabled,
	                    :profile_image_url, :profile_background_color, :profile_text_color,
	                    :profile_link_color, :profile_sidebar_fill_color,
	                    :profile_sidebar_border_color, :profile_background_image_url,
	                    :profile_background_tile, :status)
	Status = Struct.new(:id, :text, :source, :created_at, :truncated, :favorited, :geo,
	                    :in_reply_to_status_id, :in_reply_to_user_id,
	                    :in_reply_to_screen_name, :user)
	DM     = Struct.new(:id, :text, :created_at,
	                    :sender_id, :sender_screen_name, :sender,
	                    :recipient_id, :recipient_screen_name, :recipient)
	Geo    = Struct.new(:type, :coordinates, :geometries, :geometry, :properties, :id,
	                    :crs, :name, :href, :bbox, :features)

	class TypableMap < Hash
		#Roman = %w[
		#	k g ky gy s z sh j t d ch n ny h b p hy by py m my y r ry w v q
		#].unshift("").map do |consonant|
		#	case consonant
		#	when "h", "q"  then %w|a i   e o|
		#	when /[hy]$/   then %w|a   u   o|
		#	else                %w|a i u e o|
		#	end.map {|vowel| "#{consonant}#{vowel}" }
		#end.flatten
		Roman = %w[
			  a   i   u   e   o  ka  ki  ku  ke  ko  sa shi  su  se  so
			 ta chi tsu  te  to  na  ni  nu  ne  no  ha  hi  fu  he  ho
			 ma  mi  mu  me  mo  ya      yu      yo  ra  ri  ru  re  ro
			 wa              wo   n
			 ga  gi  gu  ge  go  za  ji  zu  ze  zo  da          de  do
			 ba  bi  bu  be  bo  pa  pi  pu  pe  po
			kya     kyu     kyo sha     shu     sho cha     chu     cho
			nya     nyu     nyo hya     hyu     hyo mya     myu     myo
			rya     ryu     ryo
			gya     gyu     gyo  ja      ju      jo bya     byu     byo
			pya     pyu     pyo
		].freeze

		def initialize(size = nil, shuffle = false)
			if shuffle
				@seq = Roman.dup
				if @seq.respond_to?(:shuffle!)
					@seq.shuffle!
				else
					@seq = Array.new(@seq.size) { @seq.delete_at(rand(@seq.size)) }
				end
				@seq.freeze
			else
				@seq = Roman
			end
			@n    = 0
			@size = size || @seq.size
		end

		def generate(n)
			ret = []
			begin
				n, r = n.divmod(@seq.size)
				ret << @seq[r]
			end while n > 0
			ret.reverse.join #.gsub(/n(?=[bmp])/, "m")
		end

		def push(obj)
			id = generate(@n)
			self[id] = obj
			@n += 1
			@n %= @size
			id
		end
		alias :<< :push

		def clear
			@n = 0
			super
		end

		def first
			@size.times do |i|
				id = generate((@n + i) % @size)
				return self[id] if key? id
			end unless empty?
			nil
		end

		def last
			@size.times do |i|
				id = generate((@n - 1 - i) % @size)
				return self[id] if key? id
			end unless empty?
			nil
		end

		private :[]=
		undef update, merge, merge!, replace
	end


end

class Array
	def to_tig_struct
		map do |v|
			v.respond_to?(:to_tig_struct) ? v.to_tig_struct : v
		end
	end
end

class Hash
	def to_tig_struct
		if empty?
			#warn "" if $VERBOSE
			#raise Error
			return nil
		end

		struct = case
			when struct_of?(TwitterIrcGateway::User)
				TwitterIrcGateway::User.new
			when struct_of?(TwitterIrcGateway::Status)
				TwitterIrcGateway::Status.new
			when struct_of?(TwitterIrcGateway::DM)
				TwitterIrcGateway::DM.new
			when struct_of?(TwitterIrcGateway::Geo)
				TwitterIrcGateway::Geo.new
			else
				members = keys
				members.concat TwitterIrcGateway::User.members
				members.concat TwitterIrcGateway::Status.members
				members.concat TwitterIrcGateway::DM.members
				members.concat TwitterIrcGateway::Geo.members
				members.map! {|m| m.to_sym }
				members.uniq!
				Struct.new(*members).new
		end
		each do |k, v|
			struct[k.to_sym] = v.respond_to?(:to_tig_struct) ? v.to_tig_struct : v
		end
		struct
	end

	# { :f  => "v" }    #=> "f=v"
	# { "f" => [1, 2] } #=> "f=1&f=2"
	# { "f" => "" }     #=> "f="
	# { "f" => nil }    #=> "f"
	def to_query_str separator = "&"
		inject([]) do |r, (k, v)|
			k = URI.encode_component k.to_s
			(v.is_a?(Array) ? v : [v]).each do |i|
				if i.nil?
					r << k
				else
					r << "#{k}=#{URI.encode_component i.to_s}"
				end
			end
			r
		end.join separator
	end

	private
	def struct_of? struct
		(keys - struct.members.map {|m| m.to_s }).size.zero?
	end
end

class String
	def ch?
		/\A[&#+!][^ \007,]{1,50}\z/ === self
	end

	def screen_name?
		/\A[A-Za-z0-9_]{1,15}\z/ === self
	end

	def encoding! enc
		return self unless respond_to? :force_encoding
		force_encoding enc
	end
end

module URI::Escape
	alias :_orig_escape :escape

	if defined? ::RUBY_REVISION and RUBY_REVISION < 24544
		# URI.escape("あ1") #=> "%E3%81%82\xEF\xBC\x91"
		# URI("file:///4")  #=> #<URI::Generic:0x9d09db0 URL:file:/4>
		#   "\\d" -> "[0-9]" for Ruby 1.9
		def escape str, unsafe = %r{[^-_.!~*'()a-zA-Z0-9;/?:@&=+$,\[\]]}
			_orig_escape(str, unsafe)
		end
		alias :encode :escape
	end

	def encode_component str, unsafe = /[^-_.!~*'()a-zA-Z0-9 ]/
		_orig_escape(str, unsafe).tr(" ", "+")
	end

	def rstrip str
		str.sub(%r{
			(?: ( / [^/?#()]* (?: \( [^/?#()]* \) [^/?#()]* )* ) \) [^/?#()]*
			  | \.
			) \z
		}x, "\\1")
	end
end

if __FILE__ == $0
	require "optparse"

	opts = {
		:port  => 16668,
		:host  => "localhost",
		:log   => nil,
		:debug => false,
		:foreground => false,
	}

	OptionParser.new do |parser|
		parser.instance_eval do
			self.banner = <<-EOB.gsub(/^\t+/, "")
				Usage: #{$0} [opts]

			EOB

			separator ""

			separator "Options:"
			on("-p", "--port [PORT=#{opts[:port]}]", "port number to listen") do |port|
				opts[:port] = port
			end

			on("-h", "--host [HOST=#{opts[:host]}]", "host name or IP address to listen") do |host|
				opts[:host] = host
			end

			on("-l", "--log LOG", "log file") do |log|
				opts[:log] = log
			end

			on("--debug", "Enable debug mode") do |debug|
				opts[:log]   = $stdout
				opts[:debug] = true
			end

			on("-f", "--foreground", "run foreground") do |foreground|
				opts[:log]        = $stdout
				opts[:foreground] = true
			end

			on("-n", "--name [user name or email address]") do |name|
				opts[:name] = name
			end

			parse!(ARGV)
		end
	end

	opts[:logger] = Logger.new(opts[:log], "daily")
	opts[:logger].level = opts[:debug] ? Logger::DEBUG : Logger::INFO

	#def daemonize(foreground = false)
	#	[:INT, :TERM, :HUP].each do |sig|
	#		Signal.trap sig, "EXIT"
	#	end
	#	return yield if $DEBUG or foreground
	#	Process.fork do
	#		Process.setsid
	#		Dir.chdir "/"
	#		STDIN.reopen  "/dev/null"
	#		STDOUT.reopen "/dev/null", "a"
	#		STDERR.reopen STDOUT
	#		yield
	#	end
	#	exit! 0
	#end

	#daemonize(opts[:debug] || opts[:foreground]) do
		Net::IRC::Server.new(opts[:host], opts[:port], TwitterIrcGateway, opts).start
	#end
end