~khurshid-alam/gwibber/gwibber-hack

« back to all changes in this revision

Viewing changes to gwibber/microblog/util/resources.py

  • Committer: Khurshid Alam
  • Date: 2012-04-06 14:38:38 UTC
  • Revision ID: khurshid.alam@linuxmail.org-20120406143838-nz7hjg8vtzi2wl7i
initial revision

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
"""
 
3
Paths to various Gwibber files and resources
 
4
SegPhault (Ryan Paul) - 11/22/2008
 
5
"""
 
6
 
 
7
import os, sys
 
8
from os.path import join, isdir, realpath, exists
 
9
from os import makedirs, remove
 
10
from os import environ
 
11
import Image
 
12
import log
 
13
import mx.DateTime
 
14
from gwibber.microblog import network
 
15
from const import *
 
16
import inspect
 
17
 
 
18
# Try to import * from custom, install custom.py to include packaging 
 
19
# customizations like distro API keys, etc
 
20
try:
 
21
  from custom import *
 
22
except:
 
23
  pass
 
24
 
 
25
log.logger.name = "Gwibber Dispatcher Resources"
 
26
 
 
27
PROGRAM_NAME = "gwibber"
 
28
UI_DIR_NAME = "ui"
 
29
THEME_DIR_NAME = os.path.join(UI_DIR_NAME, "themes")
 
30
LAUNCH_DIR = os.path.abspath(sys.path[0])
 
31
DATA_DIRS = [LAUNCH_DIR]
 
32
THEME_NAME = "default"
 
33
 
 
34
# Minimum theme version, this is a serial to ensure themes are compatible
 
35
# with current version of the client.  This serial is set in the theme 
 
36
# dir in a file named theme.version 
 
37
THEME_MIN_VERSION = 2
 
38
 
 
39
try:
 
40
  import xdg
 
41
  DATA_BASE_DIRS = xdg.BaseDirectory.xdg_data_dirs
 
42
  CACHE_BASE_DIR = xdg.BaseDirectory.xdg_cache_home
 
43
except:
 
44
  DATA_BASE_DIRS = [
 
45
    os.path.join(os.path.expanduser("~"), ".local", "share"),
 
46
    "/usr/local/share", "/usr/share"]
 
47
  CACHE_BASE_DIR = os.path.join(os.path.expanduser("~"), ".cache")
 
48
 
 
49
DATA_DIRS += [os.path.join(d, PROGRAM_NAME) for d in DATA_BASE_DIRS]
 
50
 
 
51
def get_plugin_dirs():
 
52
  PLUGINS = []
 
53
  PLUGINS_DIRS = []
 
54
  PLUGINS_DIRS += [os.path.join(d, "gwibber", "plugins") for d in DATA_BASE_DIRS]
 
55
 
 
56
  if exists(os.path.join("gwibber", "microblog", "plugins")):
 
57
    PLUGINS_DIRS.insert(0, os.path.realpath(os.path.join("gwibber", "microblog", "plugins")))
 
58
 
 
59
  if exists(os.path.join("gwibber", "plugins")):
 
60
    PLUGINS_DIRS.insert(0, os.path.realpath(os.path.join("gwibber", "plugins")))
 
61
 
 
62
  if environ.has_key("GWIBBER_PLUGIN_DIR"):
 
63
    GWIBBER_PLUGIN_DIR = environ["GWIBBER_PLUGIN_DIR"]
 
64
    if exists(os.path.realpath(GWIBBER_PLUGIN_DIR)):
 
65
      PLUGINS_DIRS.insert(0, os.path.realpath(GWIBBER_PLUGIN_DIR))
 
66
 
 
67
  PLUGINS_DIRS.reverse()
 
68
 
 
69
  for p in PLUGINS_DIRS:
 
70
    if exists(p):
 
71
      sys.path.insert(0, p)
 
72
      for d in os.listdir(p):
 
73
        if os.path.isdir(os.path.join(p, d)):
 
74
          if d not in PLUGINS:
 
75
            PLUGINS.append(d)
 
76
  return [PLUGINS,PLUGINS_DIRS] 
 
77
 
 
78
def get_twitter_keys():
 
79
  # Distros should register their own keys and not rely on the defaults
 
80
  return TWITTER_OAUTH_KEY, TWITTER_OAUTH_SECRET
 
81
 
 
82
def get_avatar_path(url):
 
83
  avatar_cache_dir = realpath(join(CACHE_BASE_DIR, "gwibber", "avatars"))
 
84
  if not isdir(avatar_cache_dir):
 
85
    makedirs(avatar_cache_dir)
 
86
  avatar_cache_image = join(avatar_cache_dir, url.replace("/",""))
 
87
 
 
88
  if not exists(avatar_cache_image) or len(open(avatar_cache_image, "r").read()) < 1:
 
89
    log.logger.debug("Downloading avatar %s", url)
 
90
    f = file(avatar_cache_image, "w")
 
91
    data = network.Download(url)
 
92
    f.write(data.get_string())
 
93
    f.close()
 
94
    img_resize(avatar_cache_image, 48)
 
95
 
 
96
  if len(open(avatar_cache_image, "r").read()) > 0:
 
97
    return avatar_cache_image
 
98
  return None
 
99
 
 
100
def del_avatar(avatar):
 
101
  if exists(avatar):
 
102
    try:
 
103
      remove(avatar)
 
104
    except:
 
105
      log.logger.error("Failed to remove avatar from cache: %s", avatar)
 
106
 
 
107
def img_resize(img_path, size):
 
108
  try:
 
109
    image = Image.open(img_path)
 
110
    x, y = image.size
 
111
    if x != size or y != size:
 
112
      # need to upsample limited palette images before resizing
 
113
      if image.mode == 'P': image = image.convert('RGBA')
 
114
      image.resize((size, size), Image.ANTIALIAS).save(img_path, format="jpeg")
 
115
  except Exception, e:
 
116
    from traceback import format_exc
 
117
    log.logger.error("Image resizing failed:\n%s", format_exc())
 
118
 
 
119
def get_desktop_file():
 
120
  p = os.path.join(LAUNCH_DIR, "gwibber.desktop")
 
121
  if os.path.exists(p): return p
 
122
  
 
123
  for base in DATA_BASE_DIRS:
 
124
    p = os.path.join(base, "applications", "gwibber.desktop")
 
125
    if os.path.exists(p): return p
 
126
 
 
127
def get_theme_paths():
 
128
  for base in DATA_DIRS:
 
129
    theme_root = os.path.join(base, THEME_DIR_NAME)
 
130
    if os.path.exists(theme_root):
 
131
      for f in sorted(os.listdir(theme_root)):
 
132
        if not f.startswith('.'):
 
133
          theme_dir = os.path.join(theme_root, f)
 
134
          if os.path.isdir(theme_dir) and \
 
135
            os.path.exists(os.path.join(theme_dir, "theme.version")):
 
136
            with open(os.path.join(theme_dir, "theme.version")) as f:
 
137
              for line in f:
 
138
                if "theme_version" in line:
 
139
                  theme_version = int(line.split("=")[1])
 
140
                  if theme_version >= THEME_MIN_VERSION:
 
141
                    yield theme_dir
 
142
 
 
143
def get_theme_path(name):
 
144
  for path in get_theme_paths():
 
145
    if name == os.path.basename(path):
 
146
      return path
 
147
 
 
148
def theme_exists(theme):
 
149
  return bool(get_theme_path(theme))
 
150
 
 
151
def get_themes():
 
152
  themes = {}
 
153
  for path in get_theme_paths():
 
154
    if not os.path.basename(path) in themes:
 
155
      themes[os.path.basename(path)] = path
 
156
  return themes
 
157
 
 
158
def get_ui_asset(asset_name):
 
159
  # Look for UI assets in PLUGINS_DIRS first, then fallback to DATA_DIRS
 
160
  PLUGINS_DIRS = get_plugin_dirs()[1]
 
161
  PLUGINS_DIRS.reverse()
 
162
  for p in PLUGINS_DIRS:
 
163
    if exists(p):
 
164
      for d in os.listdir(p):
 
165
        if os.path.isdir(os.path.join(p, d, UI_DIR_NAME)):
 
166
          asset_path = os.path.join(p, d, UI_DIR_NAME, asset_name)
 
167
          if os.path.exists(asset_path):
 
168
            return asset_path
 
169
 
 
170
  for base in DATA_DIRS:
 
171
    asset_path = os.path.join(base, UI_DIR_NAME, asset_name)
 
172
    if os.path.exists(asset_path):
 
173
      return asset_path
 
174
  return None
 
175
 
 
176
def get_template_dirs():
 
177
  for base in DATA_DIRS:
 
178
    p = os.path.join(base, UI_DIR_NAME, "templates")
 
179
    if os.path.exists(p):
 
180
      yield p
 
181
 
 
182
def get_theme_asset(asset_name, theme="default"):
 
183
  theme_path = get_theme_path(theme)
 
184
  if theme_path:
 
185
    fname = os.path.join(theme_path, asset_name)
 
186
    if os.path.exists(fname):
 
187
      return fname
 
188
 
 
189
def get_template_path(template, theme="default"):
 
190
  theme_template = get_theme_asset(template, theme)
 
191
  if theme_template: return theme_template
 
192
  for d in get_template_dirs():
 
193
    template_path = os.path.join(d, template)
 
194
    if template_path: return template_path
 
195
 
 
196
def dump(service, aid, data):
 
197
  if GWIBBER_TEST_DUMP and len(data) > 0:
 
198
    operation = inspect.stack()[2][3]
 
199
    dump_cache_dir = realpath(join(CACHE_BASE_DIR, "gwibber", "dump", service))
 
200
    if not isdir(dump_cache_dir):
 
201
      makedirs(dump_cache_dir)
 
202
    dump_cache_file = join(dump_cache_dir, (aid + "." + str(mx.DateTime.now()) + "." + operation))
 
203
 
 
204
    if not exists(dump_cache_file) or len(open(dump_cache_file, "r").read()) < 1:
 
205
      log.logger.debug("Dumping test data %s - %s - %s", service, aid, operation)
 
206
      f = file(dump_cache_file, "w")
 
207
      f.write(str(data))
 
208
      f.close()