New stuff for version 0.4.1 detailed decription in Changelog
[diaspy.git] / diaspy / settings.py
CommitLineData
dea56a86
MM
1"""This module provides access to user's settings on Diaspora*.
2"""
3
4
fb680551 5import json
f61c14c1 6import os
fb680551
MM
7import re
8import urllib
f61c14c1 9import warnings
fb680551 10
f61c14c1 11from diaspy import errors, streams
0d5880af 12
fb680551 13
fb680551
MM
14class Settings():
15 """This object is used to get access to user's settings on
16 Diaspora* and provides interface for downloading user's stuff.
17 """
18 def __init__(self, connection):
19 self._connection = connection
20
21 def downloadxml(self):
f61c14c1
MM
22 """Returns downloaded XML.
23 """
fb680551
MM
24 request = self._connection.get('user/export')
25 return request.text
76745cf5 26
f61c14c1
MM
27 def downloadPhotos(self, size='large', path='.', _critical=False, _stream=None):
28 """Downloads photos into the current working directory.
29 Sizes are: large, medium, small.
30 Filename is: {photo_guid}.{extension}
31
32 Normally, this method will catch urllib-generated errors and
33 just issue warnings about photos that couldn't be downloaded.
34 However, with _critical param set to True errors will become
35 critical - the will be reraised in finally block.
36
37 :param size: size of the photos to download - large, medium or small
38 :type size: str
39 :param path: path to download (defaults to current working directory
40 :type path: str
41 :param _stream: diaspy.streams.Generic-like object (only for testing)
42 :param _critical: if True urllib errors will be reraised after generating a warning (may be removed)
43
44 :returns: integer, number of photos downloaded
45 """
46 photos = 0
47 if _stream is not None: stream = _stream
48 else: stream = streams.Activity
49 stream = stream(self._connection)
50 stream.full()
51 for i, post in enumerate(stream):
52 if post['photos']:
53 for n, photo in enumerate(post['photos']):
54 name = '{0}.{1}'.format(photo['guid'], photo['sizes'][size].split('.')[-1])
55 filename = os.path.join(path, name)
56 try:
57 urllib.request.urlretrieve(url=photo['sizes'][size], filename=filename)
58 except (urllib.error.HTTPError, urllib.error.URLError) as e:
59 warnings.warn('downloading image {0} from post {1}: {2}'.format(photo['guid'], post['guid'], e))
60 finally:
61 if _critical: raise
62 photos += 1
63 return photos
64
0d5880af 65 def setEmail(self, email):
76745cf5
MM
66 """Changes user's email.
67 """
68 data = {'_method': 'put', 'utf-8': '✓', 'user[email]': email, 'authenticity_token': repr(self._connection)}
69 request = self._connection.post('user')
70
0d5880af
MM
71 def getEmail(self):
72 """Returns currently used email.
73 """
74 data = self._connection.get('user/edit')
75 email = re.compile('<input id="user_email" name="user\[email\]" size="30" type="text" value=".+?"').search(data.text)
76 if email is None: raise errors.DiaspyError('cannot fetch email')
77 email = email.group(0)[:-1]
78 email = email[email.rfind('"')+1:]
79 return email
80
81 def setLanguage(self, lang):
76745cf5 82 """Changes user's email.
52c871a4
MM
83
84 :param lang: language identifier from getLanguages()
76745cf5
MM
85 """
86 data = {'_method': 'put', 'utf-8': '✓', 'user[language]': lang, 'authenticity_token': repr(self._connection)}
52c871a4 87 request = self._connection.post('user', data=data)
b7a15036
MM
88
89 def getLanguages(self):
90 """Returns a list of tuples containing ('Language name', 'identifier').
91 One of the Black Magic(tm) methods.
92 """
dea56a86 93 select_start = '<select id="user_language" name="user[language]">'
b7a15036
MM
94 select_end = '</select>'
95 languages = []
96 request = self._connection.get('user/edit')
dea56a86
MM
97 data = request.text[request.text.find(select_start)+len(select_start):]
98 data = data[:data.find(select_end)].split('\n')
99 for item in data:
100 name = item[item.find('>')+1:item.rfind('<')]
101 identifier = item[item.find('"')+1:]
102 identifier = identifier[:identifier.find('"')]
103 languages.append((name, identifier))
b7a15036 104 return languages