This file is indexed.

/usr/lib/python2.7/dist-packages/libturpial/config.py is in python-libturpial 1.7.0-4.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
# -*- coding: utf-8 -*-

"""Module to handle basic configuration of Turpial"""

import os
import base64
import shutil
import logging
import ConfigParser

from libturpial.api.models.proxy import Proxy
from libturpial.common import get_username_from, get_protocol_from
from libturpial.exceptions import EmptyOAuthCredentials, \
    ExpressionAlreadyFiltered

try:
    from xdg import BaseDirectory
    XDG_CACHE = True
except:
    XDG_CACHE = False

APP_CFG = {
    'General': {
        'update-interval': '5',
        'queue-interval': '30',
        'minimize-on-close': 'on', # TODO: Deprecate in next mayor version
        'statuses': '60',
    },
    'Columns':{
    },
    'Services':{
        'shorten-url': 'is.gd',
        'upload-pic': 'pic.twitter.com',
    },
    'Proxy':{
        'username': '',
        'password': '',
        'server': '',
        'port': '',
        'protocol': 'http',
    },
    'Advanced': {
        'socket-timeout': '20',
        'show-user-avatars': 'on',
    },
    # TODO: Deprecate all of this config options in next mayor version
    'Window': {
        'size': '320,480',
    },
    'Notifications': {
        'on-updates': 'on',
        'on-actions': 'on',
    },
    'Sounds': {
        'on-login': 'on',
        'on-updates': 'on',
    },
    'Browser': {
        'cmd': '',
    },
}

ACCOUNT_CFG = {
    'OAuth':{
        'key': '',
        'secret': '',
    },
    'Login': {
        'username': '',
        'protocol': '',
    }
}

USERDIR = os.path.expanduser('~')
BASEDIR = os.path.join(USERDIR, '.config', 'turpial')


class ConfigBase:
    """Base configuration"""
    def __init__(self, default=None):
        self.__config = {}
        if default is None:
            self.default = APP_CFG
        else:
            self.default = default
        self.cfg = ConfigParser.ConfigParser()
        self.filepath = ''
        self.extra_sections = {}

    def register_extra_option(self, section, option, default_value):
        if section in self.__config:
            if option in self.__config[section]:
                return

        if not self.extra_sections.has_key(section):
            self.extra_sections[section] = {}
        self.extra_sections[section][option] = default_value
        self.write(section, option, default_value)

    def create(self):
        for section, v in self.default.iteritems():
            for option, value in self.default[section].iteritems():
                self.write(section, option, value)

    # TODO: Return True on success?
    def load(self):
        self.__config = dict(self.default)
        self.__config.update(self.extra_sections)

        on_disk = {}

        self.cfg.read(self.configpath)

        for section in self.cfg.sections():
            if not on_disk.has_key(section):
                on_disk[section] = {}

            for option in self.cfg.options(section):
                on_disk[section][option] = self.cfg.get(section, option)

        self.__config.update(on_disk)

        # ConfigParser doesn't store on disk empty sections, so we need to remove them
        # just to compare against saved on disk
        on_memory = dict(self.__config)
        for key in on_memory.keys():
            if on_memory[key] == {}:
                del on_memory[key]

        if on_disk != on_memory:
            self.save()

    def load_failsafe(self):
        self.__config = self.default

    def save(self, config=None):
        if config is None:
            config = dict(self.__config)

        self.__config = {}
        for section, _v in config.iteritems():
            for option, value in config[section].iteritems():
                self.write(section, option, value)

    def write(self, section, option, value):
        if not self.__config.has_key(section):
            self.__config[section] = {}

        self.__config[section][option] = value

        _fd = open(self.configpath, 'w')
        if not self.cfg.has_section(section):
            self.cfg.add_section(section)
        self.cfg.set(section, option, value)
        self.cfg.write(_fd)
        _fd.close()

    def write_section(self, section, items):
        if self.cfg.has_section(section):
            self.cfg.remove_section(section)
            self.cfg.add_section(section)
        else:
            self.cfg.add_section(section)
        self.__config[section] = {}

        for option, value in items.iteritems():
            self.__config[section][option] = value
            self.cfg.set(section, option, value)

        _fd = open(self.configpath, 'w')
        self.cfg.write(_fd)
        _fd.close()

    # WARN: Next version boolean will be the default answer
    def read(self, section, option, boolean=False):
        try:
            value = self.__config[section][option]
            if boolean:
                if value == 'on':
                    return True
                elif value == 'off':
                    return False
                else:
                    return value
            else:
                return value
        except Exception:
            return None

    def read_section(self, section):
        try:
            return self.__config[section]
        except Exception:
            return None

    def read_all(self):
        try:
            return self.__config
        except Exception:
            return None


class AppConfig(ConfigBase):
    """ Handle app configuration """
    def __init__(self, basedir=BASEDIR, default=None):
        ConfigBase.__init__(self, default)
        self.log = logging.getLogger('AppConfig')
        self.log.debug('Started')
        self.basedir = basedir

        self.configpath = os.path.join(self.basedir, 'config')
        self.filterpath = os.path.join(self.basedir, 'filtered')
        self.friendspath = os.path.join(self.basedir, 'friends')

        if not os.path.isdir(self.basedir):
            os.makedirs(self.basedir)
        if not os.path.isfile(self.configpath):
            self.create()
        if not os.path.isfile(self.filterpath):
            open(self.filterpath, 'w').close()
        if not os.path.isfile(self.friendspath):
            open(self.friendspath, 'w').close()

        self.log.debug('CONFIG_FILE: %s' % self.configpath)
        self.log.debug('FILTERS_FILE: %s' % self.filterpath)
        self.log.debug('FRIENDS_FILE: %s' % self.friendspath)

        self.load()

    def load_filters(self):
        muted = []
        _fd = open(self.filterpath, 'r')
        for line in _fd:
            if line == '\n':
                continue
            muted.append(line.strip('\n'))
        _fd.close()
        return muted

    # TODO: Return saved filters?
    def save_filters(self, filter_list):
        _fd = open(self.filterpath, 'w')
        for expression in filter_list:
            _fd.write(expression + '\n')
        _fd.close()

    # TODO: Return added expresion?
    def append_filter(self, expression):
        for term in self.load_filters():
            if term == expression:
                raise ExpressionAlreadyFiltered
        _fd = open(self.filterpath, 'a')
        _fd.write(expression + '\n')
        _fd.close()

    # TODO: Return removed expression?
    def remove_filter(self, expression):
        new_list = []
        for term in self.load_filters():
            if term == expression:
                continue
            new_list.append(term)
        self.save_filters(new_list)

    def load_friends(self):
        friends = []
        _fd = open(self.friendspath, 'r')
        for line in _fd:
            if line == '\n':
                continue
            friends.append(line.strip('\n'))
        _fd.close()
        return friends

    # TODO: Return saved friends?
    def save_friends(self, lst):
        _fd = open(self.friendspath, 'w')
        for friend in lst:
            _fd.write(friend + '\n')
        _fd.close()

    def get_stored_accounts(self):
        accounts = []
        acc_dir = os.path.join(BASEDIR, 'accounts')
        for root, dirs, files in os.walk(acc_dir):
            for acc_dir in dirs:
                filepath = os.path.join(root, acc_dir, 'config')
                if os.path.isfile(filepath):
                    accounts.append(acc_dir)
        return accounts

    def get_stored_columns(self):
        columns = []
        stored_cols = self.read_section('Columns')
        if not stored_cols or len(stored_cols) == 0:
            return columns

        indexes = stored_cols.keys()
        indexes.sort()

        for i in indexes:
            value = stored_cols[i]
            if value != '':
                columns.append(value)
        return columns

    def get_proxy(self):
        temp = self.read_section('Proxy')
        secure = True if temp['protocol'].lower() == 'https' else False
        return Proxy(temp['server'], temp['port'], temp['username'], temp['password'], secure)

    def get_socket_timeout(self):
        return int(self.read('Advanced', 'socket-timeout'))

    # TODO: Return True when success?
    def delete(self):
        os.remove(self.configpath)
        self.log.debug('Deleted current config. Please restart Turpial')


class AccountConfig(ConfigBase):

    def __init__(self, account_id):
        ConfigBase.__init__(self, default=ACCOUNT_CFG)
        self.log = logging.getLogger('AccountConfig')
        self.basedir = os.path.join(BASEDIR, 'accounts', account_id)

        if XDG_CACHE:
            cachedir = BaseDirectory.xdg_cache_home
            self.imgdir = os.path.join(cachedir, 'turpial',
                                       account_id, 'images')
        else:
            self.imgdir = os.path.join(self.basedir, 'images')

        self.configpath = os.path.join(self.basedir, 'config')

        self.log.debug('CACHEDIR: %s' % self.imgdir)
        self.log.debug('CONFIGFILE: %s' % self.configpath)

        if not os.path.isdir(self.basedir):
            os.makedirs(self.basedir)
        if not os.path.isdir(self.imgdir):
            os.makedirs(self.imgdir)
        if not self.exists(account_id):
            self.create()

        try:
            self.load()
        except Exception, exc:
            self.load_failsafe()

        if not self.exists(account_id):
            self.write('Login', 'username', get_username_from(account_id))
            self.write('Login', 'protocol', get_protocol_from(account_id))

    @staticmethod
    def exists(account_id):
        basedir = os.path.join(BASEDIR, 'accounts', account_id)
        configpath = os.path.join(basedir, 'config')

        if not os.path.isfile(configpath):
            return False
        return True

    # DEPRECATE: Remove verifier in the next stable version
    def save_oauth_credentials(self, key, secret, verifier=None):
        self.write('OAuth', 'key', key)
        self.write('OAuth', 'secret', secret)

    # DEPRECATE: Remove verifier in the next stable version
    def load_oauth_credentials(self):
        key = self.read('OAuth', 'key')
        secret = self.read('OAuth', 'secret')
        if key and secret:
            return key, secret
        else:
            raise EmptyOAuthCredentials

    def forget_oauth_credentials(self):
        self.write('OAuth', 'key', '')
        self.write('OAuth', 'secret', '')

    def transform(self, pw, us):
        a = base64.b16encode(pw)
        b = us[0] + a + ('%s' % us[-1])
        c = base64.b32encode(b)
        d = ('%s' % us[-1]) + c + us[0]
        e = base64.b64encode(d)
        f = [e[i] for i in range(len(e))]
        f.reverse()
        return ''.join(f)

    def revert(self, pw, us):
        if pw == '':
            return None
        z = [pw[i] for i in range(len(pw))]
        z.reverse()
        y = ''.join(z)
        x = base64.b64decode(y)
        w = ('%s' % x[1:len(x)])[:-1]
        v = base64.b32decode(w)
        u = ('%s' % v[:len(v) - 1])[1:]
        return base64.b16decode(u)

    # TODO: Return True on success?
    def dismiss(self):
        if os.path.isdir(self.imgdir):
            shutil.rmtree(self.imgdir)
            self.log.debug('Removed cache directory')
        if os.path.isfile(self.configpath):
            os.remove(self.configpath)
            self.log.debug('Removed configuration file')
        if os.path.isdir(self.basedir):
            shutil.rmtree(self.basedir)
            self.log.debug('Removed base directory')

    # TODO: Return True on success?
    def delete_cache(self):
        for root, dirs, files in os.walk(self.imgdir):
            for f in files:
                path = os.path.join(root, f)
                self.log.debug("Deleting %s" % path)
                os.remove(path)

    def calculate_cache_size(self):
        size = 0
        for root, dirs, files in os.walk(self.imgdir):
            for f in files:
                path = os.path.join(root, f)
                size += os.path.getsize(path)
        return size