chiark / gitweb /
Do only a quick referential integrity check on market data updates
[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 the YARRG website.  YARRG is a tool and website
6 # for assisting 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 Affero General Public License as
12 # published by the Free Software Foundation, either version 3 of the
13 # License, or (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 Affero General Public License for more details.
19 #
20 # You should have received a copy of the GNU Affero 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 re as regexp
41 import subprocess
42 from optparse import OptionParser
43 from BeautifulSoup import BeautifulSoup
44
45
46 # For fuck's sake!
47 import codecs
48 import locale
49 def fix_stdout():
50     sys.stdout = codecs.EncodedFile(sys.stdout, locale.getpreferredencoding())
51     def null_decode(input, errors='strict'):
52         return input, len(input)
53     sys.stdout.decode = null_decode
54 # From
55 #  http://ewx.livejournal.com/457086.html?thread=3016574
56 #  http://ewx.livejournal.com/457086.html?thread=3016574
57 # lightly modified.
58 # See also Debian #415968.
59 fix_stdout()
60
61
62 # User agent:
63 class YarrgURLopener(urllib.FancyURLopener):
64         base_version= urllib.URLopener().version
65         proc= subprocess.Popen(
66                 ["./database-info-fetch", "useragentstringmap",
67                  base_version, "manual islands/topology fetch"],
68                 shell=False,
69                 stderr=None,
70                 stdout=subprocess.PIPE,
71                 )
72         version = proc.communicate()[0].rstrip('\n');
73         assert(proc.returncode is not None and proc.returncode == 0)
74 urllib._urlopener = YarrgURLopener()
75
76 ocean = None
77 soup = None
78 opts = None
79 arches = {}
80
81 def debug(k,v):
82         if opts.debug:
83                 print >>sys.stderr, k,`v`
84
85 def fetch():
86         global soup
87         if opts.chart:
88                 url_base = 'index.php?title=Template:Map:%s_Ocean&action=edit'
89         else:
90                 url_base = '%s_Ocean'
91         url = ('http://yppedia.puzzlepirates.com/' +
92                         (url_base % urllib.quote(ocean,'')))
93         debug('fetching',url)
94         dataf = urllib.urlopen(url)
95         debug('fetched',dataf)
96         soup = BeautifulSoup(dataf)
97
98
99 title_arch_re = regexp.compile('(\\S.*\\S) Archipelago \\((\\S+)\\)$')
100 title_any_re = regexp.compile('(\\S.*\\S) \((\\S+)\\)$')
101 href_img_re = regexp.compile('\\.png$')
102
103 def title_arch_info(t):
104         # returns (arch,ocean)
105         debug('checking',t)
106         if t is None: return (None,None)
107         m = title_arch_re.match(t)
108         if not m: return (None,None)
109         return m.groups()
110
111 def title_arch_ok(t):
112         (a,o) = title_arch_info(t)
113         if o is None: return False
114         return o == ocean
115
116 def parse_chart():
117         ta = soup.find('textarea')
118         debug('ta',ta)
119         s = ta.string
120         debug('s',s)
121         s = regexp.sub(r'\&lt\;', '<', s)
122         s = regexp.sub(r'\&gt\;', '>', s)
123         s = regexp.sub(r'\&quot\;', '"', s)
124         s = regexp.sub(r'\&amp\;', '&', s)
125         debug('s',s)
126         return s
127
128 def parse_ocean():
129         content = soup.find('div', attrs = {'id': 'content'})
130
131         def findall_title_arch_ok(t):
132                 return t.findAll('a', attrs = {'title': title_arch_ok})
133
134         def is_archestable(u):
135                 if u.name != 'table': return False
136                 return len(findall_title_arch_ok(u)) > 1
137
138         archestable = content.findChild('table', attrs={'border':'1'})
139         debug('at',archestable)
140
141         archsoups = []
142         for row in archestable.findAll('tr',recursive=False):
143                 archsoups += row.findAll('td',recursive=False)
144         debug('ac',archsoups)
145
146         def is_island(v):
147                 return len(v.findAll(text = regexp.compile('.*Large'))) > 0
148         def arch_up_map(u):
149                 return u.findParent(is_island)
150
151         for arch in archsoups:
152                 links = arch.findAll('a', href=True)
153                 debug('links',links)
154                 if not links: continue
155                 (a,o) = title_arch_info(links[0]['title'])
156                 debug('arch-ocean', (a,o))
157                 assert(o == ocean)
158                 assert(a not in arches)
159                 isles = []
160                 for link in links[1:]:
161                         debug('link',link)
162                         if href_img_re.search(link['href']): continue
163                         m = title_any_re.match(link['title'])
164                         assert(m.group(2) == ocean)
165                         island = m.group(1)
166                         debug('island', island)
167                         isles.append(island)
168                 isles.sort()
169                 arches[a] = isles
170
171 def output():
172         print 'ocean',ocean
173         al = arches.keys()
174         al.sort()
175         for a in al:
176                 print '',a
177                 for island in arches[a]:
178                         print ' ',island
179
180 def main():
181         global ocean
182         global opts
183
184         pa = OptionParser(
185 '''usage: .../yppedia-ocean-scraper [--debug] [--chart] OCEAN''')
186         ao = pa.add_option
187
188         ao('--chart', action='store_true', dest='chart',
189                 help='print chart source rather than arch/island info')
190         ao('--debug', action='count', dest='debug', default=0,
191                 help='enable debugging output')
192
193         (opts,args) = pa.parse_args()
194         if len(args) != 1:
195                 print >>sys.stderr, copyright_info
196                 pa.error('need an ocean argument')
197         ocean = args[0]
198
199         fetch()
200         if opts.chart:
201                 print parse_chart()
202         else:
203                 parse_ocean()
204                 output()
205
206 main()