Skip to content

Commit

Permalink
Initial code posted.
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewbauer committed Mar 7, 2015
1 parent 3d7882b commit da090d8
Show file tree
Hide file tree
Showing 10 changed files with 507 additions and 113 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -1,3 +1,5 @@
dist
build
*.pyc
*.egg
*.tar.gz
Binary file added alien.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file added detools/__init__.py
Empty file.
46 changes: 46 additions & 0 deletions detools/de.py
@@ -0,0 +1,46 @@
#!/usr/bin/env python

import os
import sys

def get_desktop_environment():
if sys.platform in ["win32", "cygwin"]:
return "windows"
elif sys.platform == "darwin":
return "mac"
else: #Most likely either a POSIX system or something not much common
desktop_session = os.environ.get("DESKTOP_SESSION")
if desktop_session is not None: #easier to match if we doesn't have to deal with caracter cases
desktop_session = desktop_session.lower()
if desktop_session in ["gnome","unity", "cinnamon", "mate", "xfce4", "lxde", "fluxbox",
"blackbox", "openbox", "icewm", "jwm", "afterstep","trinity", "kde"]:
return desktop_session
## Special cases ##
# Canonical sets $DESKTOP_SESSION to Lubuntu rather than LXDE if using LXDE.
# There is no guarantee that they will not do the same with the other desktop environments.
elif "xfce" in desktop_session or desktop_session.startswith("xubuntu"):
return "xfce4"
elif desktop_session.startswith("ubuntu"):
return "unity"
elif desktop_session.startswith("lubuntu"):
return "lxde"
elif desktop_session.startswith("kubuntu"):
return "kde"
elif desktop_session.startswith("razor"): # e.g. razorkwin
return "razor-qt"
elif desktop_session.startswith("wmaker"): # e.g. wmaker-common
return "windowmaker"
if os.environ.get('KDE_FULL_SESSION') == 'true':
return "kde"
elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
if not "deprecated" in os.environ.get('GNOME_DESKTOP_SESSION_ID'):
return "gnome2"
#From http://ubuntuforums.org/showthread.php?t=652320
elif self.is_running("xfce-mcs-manage"):
return "xfce4"
elif self.is_running("ksmserver"):
return "kde"
return "unknown"

if __name__ == "__main__":
print(get_desktop_environment())
57 changes: 57 additions & 0 deletions detools/imagefinder.py
@@ -0,0 +1,57 @@
#!/usr/bin/env python

import requests
from bs4 import BeautifulSoup
import urlparse

class NoImageFound(Exception):
def __init__(self, url):
self.url = url
def __str__(self):
return "Could not find an image for the url %s" % self.url

def get_image_links(soup):
links = []
links.extend(soup.select('.image a')) # imgur
links.extend(soup.select('a.js-download')) # pexels
links.extend(soup.select('#allsizes-photo img')) # flickr
links.extend(soup.select('a[imageanchor]')) # blogspot
links.extend(soup.select('.dev-view-deviation img')) # deviantart
links.extend(soup.select('img#wallpaper')) # wallhaven
links.extend(soup.select('.post a img')) # imgur
return links

def get_image_request(url, follow=True):
url = urlparse.urlparse(url, 'http')
r = requests.get(url.geturl())
content_type = r.headers['content-type'].split(';')[0]
if follow and 'location' in r.headers:
return get_image_request(r.headers['location'], False)
if follow and content_type == 'text/html':
soup = BeautifulSoup(r.text)
links = get_image_links(soup)
if len(links) == 0:
raise NoImageFound(url.geturl())
link = links[0]
link_url = None
if link.has_attr('href'):
link_url = link['href']
elif link.has_attr('src'):
link_url = link['src']
if link_url is None:
raise NoImageFound(url.geturl())
return get_image_request(link_url, False)
if not content_type.startswith('image/'):
raise NoImageFound(url.geturl())
return r

if __name__ == "__main__":
import praw

r = praw.Reddit(user_agent='reddwall:v1.0.1 (by /u/mjbauer95)')

for submission in r.get_subreddit('wallpaper').get_hot(limit=100):
try:
get_image_request(submission.url)
except NoImageFound:
print(submission.url)
71 changes: 25 additions & 46 deletions wallpaper.py → detools/wallpaper.py
@@ -1,10 +1,13 @@
#!/usr/bin/env python

import os
import sys
import subprocess
import tempfile
import de

class WallpaperSetter:
def __init__(self, environment):
self.environment = environment
def set_wallpaper(self, filename):
pass

Expand Down Expand Up @@ -90,60 +93,36 @@ def get_args(self, filename):
class MacWallpaperSetter(PopenWallpaperSetter):
def get_args(self, filename):
return 'osascript -e "tell application \\"Finder\\" to set desktop picture to POSIX file \\"%s\\""' % filename

wallpaper_setters["mac"] = MacWallpaperSetter

def get_desktop_environment():
if sys.platform in ["win32", "cygwin"]:
return "windows"
elif sys.platform == "darwin":
return "mac"
else: #Most likely either a POSIX system or something not much common
desktop_session = os.environ.get("DESKTOP_SESSION")
if desktop_session is not None: #easier to match if we doesn't have to deal with caracter cases
desktop_session = desktop_session.lower()
if desktop_session in ["gnome","unity", "cinnamon", "mate", "xfce4", "lxde", "fluxbox",
"blackbox", "openbox", "icewm", "jwm", "afterstep","trinity", "kde"]:
return desktop_session
## Special cases ##
# Canonical sets $DESKTOP_SESSION to Lubuntu rather than LXDE if using LXDE.
# There is no guarantee that they will not do the same with the other desktop environments.
elif "xfce" in desktop_session or desktop_session.startswith("xubuntu"):
return "xfce4"
elif desktop_session.startswith("ubuntu"):
return "unity"
elif desktop_session.startswith("lubuntu"):
return "lxde"
elif desktop_session.startswith("kubuntu"):
return "kde"
elif desktop_session.startswith("razor"): # e.g. razorkwin
return "razor-qt"
elif desktop_session.startswith("wmaker"): # e.g. wmaker-common
return "windowmaker"
if os.environ.get('KDE_FULL_SESSION') == 'true':
return "kde"
elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
if not "deprecated" in os.environ.get('GNOME_DESKTOP_SESSION_ID'):
return "gnome2"
#From http://ubuntuforums.org/showthread.php?t=652320
elif self.is_running("xfce-mcs-manage"):
return "xfce4"
elif self.is_running("ksmserver"):
return "kde"
return "unknown"

def get_wallpaper_setter():
environment = get_desktop_environment()
environment = de.get_desktop_environment()
if environment in wallpaper_setters:
return wallpaper_setters[environment]()
return None
return wallpaper_setters[environment](environment)
return WallpaperSetter(environment)

class WallpaperSetterError(Exception):
def __init__(self, environment):
self.environment = environment
def __str__(self):
return "Cannot set wallpaper for %s" % self.environment

def set_wallpaper(filename):
wallpaper_setter = get_wallpaper_setter()
if wallpaper_setter is not None:
wallpaper_setter.set_wallpaper(filename)
try:
wallpaper_setter.set_wallpaper(filename)
except:
raise WallpaperSetterError(wallpaper_setter.environment)
else:
raise Exception("Wallpaper could not be set because you're desktop is not recognized.")
raise WallpaperSetterError(wallpaper_setter.environment)

def set_wallpaper_request(request):
i, path = tempfile.mkstemp()
with open(path, 'wb') as fo:
for chunk in request.iter_content(4096):
fo.write(chunk)
set_wallpaper(path)

if __name__ == "__main__":
if len(sys.argv) > 1:
Expand Down
98 changes: 98 additions & 0 deletions praw.ini
@@ -0,0 +1,98 @@
[DEFAULT]
# Time, a float, in seconds, required between calls. See:
# http://code.reddit.com/wiki/API
api_request_delay: 2.0

# A boolean to indicate whether or not to check for package updates.
check_for_updates: True

# Time, a float, in seconds, to save the results of a get/post request.
cache_timeout: 30

# A boolean to indicate if html entities should be decoded
decode_html_entities: False

# Whether or not to use HTTPS for oauth connections. This should only be
# changed for development environments.
oauth_https: True

# The maximum length of unicode representations of Comment, Message and
# Submission objects. This is mainly used to fit them within a terminal window
# line. A negative value means no limit.
output_chars_limit: 80

# Maximum time, a float, in seconds, before a single HTTP request times
# out. urllib2.URLError is raised upon timeout.
timeout: 45

# Object to kind mappings
comment_kind: t1
message_kind: t4
redditor_kind: t2
submission_kind: t3
subreddit_kind: t5

# Log the API calls
# 0: no logging
# 1: log only the request URIs
# 2: log the request URIs as well as any POST data
log_requests: 0

# A boolean to indicate if json_dict, which contains the original API response,
# should be stored on every object in the json_dict attribute. Default is
# False as memory usage will double if enabled.
store_json_result: False

[reddit]
domain: www.reddit.com
oauth_domain: oauth.reddit.com
short_domain: redd.it
ssl_domain: ssl.reddit.com

[reddit_bypass_cdn]
domain: api.reddit.com
oauth_domain: oauth.reddit.com
short_domain: redd.it
ssl_domain: ssl.reddit.com

[reddit_bypass_cdn_oauth_test]
domain: www.reddit.com
short_domain: redd.it
ssl_domain: ssl.reddit.com
oauth_domain: oauth.reddit.com
oauth_client_id: stJlUSUbPQe5lQ
oauth_client_secret: iU-LsOzyJH7BDVoq-qOWNEq2zuI
oauth_redirect_uri: https://127.0.0.1:65010/authorize_callback

[reddit_oauth_test]
domain: www.reddit.com
short_domain: redd.it
ssl_domain: ssl.reddit.com
oauth_domain: oauth.reddit.com
oauth_client_id: stJlUSUbPQe5lQ
oauth_client_secret: iU-LsOzyJH7BDVoq-qOWNEq2zuI
oauth_redirect_uri: https://127.0.0.1:65010/authorize_callback

[local]
domain: reddit.local
api_request_delay: 0

message_kind: t7
submission_kind: t6
subreddit_kind: t5
log_requests: 0

[local_oauth_test]
domain: reddit.local
api_request_delay: 0

message_kind: t7
submission_kind: t6
subreddit_kind: t5
log_requests: 0

oauth_https: False
oauth_domain: reddit.local
oauth_client_id: gXMPrZscuuUgaw
oauth_client_secret: JfmLYwwsP9Dj2z513JdTEOeXEaQ
oauth_redirect_uri: http://127.0.0.1:65010/authorize_callback

0 comments on commit da090d8

Please sign in to comment.