chiark / gitweb /
ad35c4d708a432566941542156e10339d5ed421f
[ypp-sc-tools.main.git] / yarrg / yppedia-ocean-scraper
1 #!/usr/bin/python
2
3 # helper program for getting information from yppedia
4
5 # This is part of ypp-sc-tools, a set of third-party tools for assisting
6 # players of Yohoho Puzzle Pirates.
7 #
8 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 #
23 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24 # are used without permission.  This program is not endorsed or
25 # sponsored by Three Rings.
26
27 copyright_info = '''
28 yppedia-ocean-scraper is part of ypp-sc-tools Copyright (C) 2009 Ian Jackson
29 This program comes with ABSOLUTELY NO WARRANTY; this is free software,
30 and you are welcome to redistribute it under certain conditions.  For
31 details, read the top of the yppedia-ocean-scraper file.
32 '''
33
34 import signal
35 signal.signal(signal.SIGINT, signal.SIG_DFL)
36
37 import sys
38 import os
39 import urllib
40 import urllib2
41 import re as regexp
42 from optparse import OptionParser
43 from BeautifulSoup import BeautifulSoup
44
45 ocean = None
46 soup = None
47 opts = None
48 arches = {}
49
50 def debug(k,v):
51         if opts.debug:
52                 print >>sys.stderr, k,`v`
53
54 def fetch():
55         global soup
56         if opts.chart:
57                 url_base = 'index.php?title=Template:Map:%s_Ocean&action=edit'
58         else:
59                 url_base = '%s_Ocean'
60         url = ('http://yppedia.puzzlepirates.com/' +
61                         (url_base % urllib.quote(ocean,'')))
62         debug('fetching',url)
63         dataf = urllib2.urlopen(url)
64         debug('fetched',dataf)
65         soup = BeautifulSoup(dataf)
66
67
68 title_arch_re = regexp.compile('(\\S.*\\S) Archipelago \\((\\S+)\\)$')
69 title_any_re = regexp.compile('(\\S.*\\S) \((\\S+)\\)$')
70 href_img_re = regexp.compile('\\.png$')
71
72 def title_arch_info(t):
73         # returns (arch,ocean)
74         debug('checking',t)
75         if t is None: return (None,None)
76         m = title_arch_re.match(t)
77         if not m: return (None,None)
78         return m.groups()
79
80 def title_arch_ok(t):
81         (a,o) = title_arch_info(t)
82         if o is None: return False
83         return o == ocean
84
85 def parse_chart():
86         ta = soup.find('textarea')
87         debug('ta',ta)
88         s = ta.string
89         debug('s',s)
90         s = regexp.sub(r'\&lt\;', '<', s)
91         s = regexp.sub(r'\&gt\;', '>', s)
92         s = regexp.sub(r'\&quot\;', '"', s)
93         s = regexp.sub(r'\&amp\;', '&', s)
94         debug('s',s)
95         return s
96
97 def parse_ocean():
98         firstarch = soup.find('a', attrs = {'title': title_arch_ok})
99         debug('fa',firstarch)
100
101         def findall_title_arch_ok(t):
102                 return t.findAll('a', attrs = {'title': title_arch_ok})
103
104         def is_archestable(u):
105                 if u.name != 'table': return False
106                 return len(findall_title_arch_ok(u)) > 1
107
108         archestable = firstarch.findParent('table', attrs={'border':'1'})
109         debug('at',archestable)
110
111         archsoups = []
112         for row in archestable.findAll('tr',recursive=False):
113                 archsoups += row.findAll('td',recursive=False)
114         debug('ac',archsoups)
115
116         def is_island(v):
117                 return len(v.findAll(text = regexp.compile('.*Large'))) > 0
118         def arch_up_map(u):
119                 return u.findParent(is_island)
120
121         for arch in archsoups:
122                 links = arch.findAll('a', href=True)
123                 debug('links',links)
124                 if not links: continue
125                 (a,o) = title_arch_info(links[0]['title'])
126                 debug('arch-ocean', (a,o))
127                 assert(o == ocean)
128                 assert(a not in arches)
129                 isles = []
130                 for link in links[1:]:
131                         debug('link',link)
132                         if href_img_re.search(link['href']): continue
133                         m = title_any_re.match(link['title'])
134                         assert(m.group(2) == ocean)
135                         island = m.group(1)
136                         debug('island', island)
137                         isles.append(island)
138                 isles.sort()
139                 arches[a] = isles
140
141 def output():
142         print 'ocean',ocean
143         al = arches.keys()
144         al.sort()
145         for a in al:
146                 print '',a
147                 for island in arches[a]:
148                         print ' ',island
149
150 def main():
151         global ocean
152         global opts
153
154         pa = OptionParser(
155 '''usage: .../yppedia-ocean-scraper [--debug] [--chart] OCEAN''')
156         ao = pa.add_option
157
158         ao('--chart', action='store_true', dest='chart',
159                 help='print chart source rather than arch/island info')
160         ao('--debug', action='count', dest='debug', default=0,
161                 help='enable debugging output')
162
163         (opts,args) = pa.parse_args()
164         if len(args) != 1:
165                 print >>sys.stderr, copyright_info
166                 pa.error('need an ocean argument')
167         ocean = args[0]
168
169         fetch()
170         if opts.chart:
171                 print parse_chart()
172         else:
173                 parse_ocean()
174                 output()
175
176 main()