aboutsummaryrefslogtreecommitdiff
path: root/Silicium/Forum.py
blob: 12f2e3a8b58d7c6ed4303961294e223bfe1d3460 (plain)
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#******************************************************************************
# Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
#
# 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 2
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA  02110-1301, USA.
#******************************************************************************
""" Forum object.
	The homepage is considered as a forum with only subforums.
	A forum shall contain a title, subforums, announcements, and topics.
"""

import requests    as _requests
import urllib      as _urllib
import datetime    as _datetime
import collections as _collections

from bs4 import BeautifulSoup as _BeautifulSoup
from bs4.element import NavigableString as _NavigableString

from .User  import *
from .Topic import *
from .utils import *

class Forum:
	def __init__(self, forum_id, base = sili_base):
		self.id   = forum_id
		self.__base = base
		self.title  = None
		self.forums = None
		self.announcements = None
		self.updated = None
		self.updater = None

	def load(self, title, updater, updated):
		self.title = title
		self.updater = updater
		self.updated = updated

	def __loadlist(self, element):
		""" Load a list of rows. """

		ul = element.find(True, {'class': ['topiclist topics',
			'topiclist forums']}, recursive=True)

		for li in ul.find_all('li', {'class': 'row'}, recursive=False):
			ans = {}

			# Get the title.
			title = li.find('a', {'class': ['topictitle', 'forumtitle']},
				recursive=True)
			ans['title'] = title.text

			# Load the link.
			url = _urllib.parse.urlparse(title['href'])
			arg = _urllib.parse.parse_qs(url.query)
			if 't' in arg:
				ans['topic_id'] = int(arg['t'][0])
			if 'f' in arg:
				ans['forum_id'] = int(arg['f'][0])

			if 'topics' in ul['class']:
				# Get the poster ID and date.
				tab = list(li.find('div', {'class': 'topic-poster'}, \
					recursive=True).children)
				if tab[1].name == 'a':
					url = _urllib.parse.urlparse(tab[1]['href'])
					arg = _urllib.parse.parse_qs(url.query)
					uid = int(arg['u'][0])
				else:
					uid = -1
				poster = User(uid, base = self.__base)
				poster.name = tab[1].text

				while type(tab[-1]) != _NavigableString \
				or tab[-1].find('»') < 0:
					tab = tab[:-1]
				p_date = decode_date(tab[-1].split('»')[1])
				ans['poster'] = poster
				ans['posted'] = p_date

			# Get the updater ID and date.
			tab = list(li.find(True, {'class': 'lastpost'}, \
				recursive=True).find('span').children)
			if len(tab) < 6:
				ans['updater'] = None
				ans['updated'] = None
			else:
				if tab[-6].name == 'a':
					url = _urllib.parse.urlparse(tab[-6]['href'])
					arg = _urllib.parse.parse_qs(url.query)
					uid = int(arg['u'][0])
				else:
					uid = -1
				updater = User(uid, base = self.__base)
				updater.name = tab[-6].text
				u_date = decode_date(tab[-1].strip())
				ans['updater'] = updater
				ans['updated'] = u_date

			yield ans

	def __loadpage(self, start=0, auth = DefaultAuth):
		print("[p] Loading entries starting from {}".format(start))

		url = self.__base
		if self.id == 0:
			url += '/index.php'
		else:
			url += '/viewforum.php?f={}&start={}'.format(self.id, start)

		text = _requests.get(url, cookies=auth.cookies()).text
		tree = _BeautifulSoup(text, "html5lib")
		body = tree.body.find(id='page-body', recursive=True)

		# Check if authentication is required.
		if body.find('strong', recursive=False):
			raise NotEnoughPermissionsError
		if body.find('form', {'id': 'login'}, recursive=True):
			raise NotEnoughPermissionsError

		# Prepare the answer, find the name.
		ans = {'topics': []}
		if self.id == 0:
			ans['title'] = "My Silicium"
		else:
			ans['title'] = next(tree.body.find(True, {'class': 'forum-title'},
				recursive=True).children).text

		# Find the forums.
		forums = []
		for raw in body.find_all(True, {'class': 'forabg'}):
			for el in self.__loadlist(raw):
				forum = Forum(el['forum_id'], base = self.__base)
				forum.load(el['title'], el['updater'], el['updated'])
				forums.append(forum)
		ans['forums'] = forums

		# Find the announcements.
		announcements = []
		for raw in body.find_all(True, {'class': 'forumbg announcement'}):
			for el in self.__loadlist(raw):
				topic = Topic(el['topic_id'], base = self.__base)
				topic.load(el['title'], el['poster'], el['posted'],
					el['updater'], el['updated'])
				announcements.append(topic)
			break
		ans['announcements'] = announcements

		# Find the last page.
		buttons = body.find('div', {'class': 'pagination'}, recursive=True)
		if buttons and buttons.find('ul'):
			buttons = buttons.find('ul').find_all('li')
			buttons = _collections.deque(buttons, 2)
			if len(buttons) == 1 or 'arrow' in buttons[1]['class']:
				button = buttons[0]
			else:
				button = buttons[1]
			if button.find('a'):
				button = button.find('a')
				url = _urllib.parse.urlparse(button['href'])
				arg = _urllib.parse.parse_qs(url.query)
				lastpage = int(arg["start"][0]) if "start" in arg else 0
			else:
				lastpage = int(button.find('span').text) * 50 - 50
		else:
			lastpage = 0

		# Supplementary checks:
		# If `start` is above the maximum possible start value for the
		# topic, it will display the last page as if nothing happened.
		# So we need to check a little more, as PHPBB3 won't do it
		# for us :(
		if start >= lastpage + 50:
			return ans
		if start > lastpage:
			sub_ans = self.__loadpage(lastpage, auth)
			if start >= lastpage + len(ans):
				return ans
			ans['topics'] = sub_ans['topics'][start - lastpage:]
			return ans

		# Find the topics.
		topics = []
		for raw in body.find_all(True, {'class': 'forumbg'}):
			if 'announcement' in raw['class']: continue
			for el in self.__loadlist(raw):
				topic = Topic(el['topic_id'], base = self.__base)
				topic.load(el['title'], el['poster'], el['posted'],
					el['updater'], el['updated'])
				topics.append(topic)
			break
		ans['topics'] = topics

		return ans

	def __getmain(self, auth = DefaultAuth):
		if self.forums != None:
			return

		ans = self.__loadpage(auth = auth)
		self.title = ans['title']
		self.forums = ans['forums']
		self.announcements = ans['announcements']

	def get_title(self, auth = DefaultAuth):
		self.__getmain(auth)
		return self.title

	def get_forums(self, auth = DefaultAuth):
		self.__getmain(auth)
		return self.forums

	def get_topics(self, start=0, count=50, auth = DefaultAuth):
		topics = []
		while count:
			ans = self.__loadpage(start, auth)
			if not ans['topics']: break
			topics += ans['topics']
			start += len(ans['topics'])
			count -= len(ans['topics'])

		return topics

	def get_latest_topics(self, since, auth = DefaultAuth):
		topics = []
		done = False
		start = 0
		while True:
			ans = self.__loadpage(start, auth)
			if not ans['topics']: break

			for topic in ans['topics']:
				if topic.updated <= since:
					done = True
					break
				topics.append(topic)

			if done:
				break
			start += len(ans['topics'])

		return topics

	def __repr__(self):
		rep  = '<Silicium Forum {}'.format(self.id)
		if self.updated:
			rep += ' updated on {}'.format(self.updated.isoformat())
			if self.updater:
				rep += ' by {}'.format(self.updater.name)
		else:
			rep += ' never updated'
		if self.title:
			rep += ' entitled "{}"'.format(self.title)
		rep += '>'
		return rep

# End of file.