~davidc3/onehundredscopes/youporn-precise

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
#! /usr/bin/python
# -*- coding: latin-1 -*-

#    Copyright (c) 2011 David Calle <davidc@framli.eu>

#    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 3 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, see <http://www.gnu.org/licenses/>.
import sys
from gi.repository import GLib, GObject, Gio
from gi.repository import Dee
from gi.repository import Unity
import socket
from lxml.html import fromstring
import urllib2

socket.setdefaulttimeout(5)
BUS_NAME = "net.launchpad.scope.video.youporn"

class Daemon:
    def __init__ (self):
        self.scope = Unity.Scope.new ("/net/launchpad/scope/video/youporn")
        self.scope.search_in_global = False
        self.scope.connect ("search-changed", self.on_search_changed)
        self.scope.connect ("filters-changed", lambda scope : self.scope.queue_search_changed(Unity.SearchType.DEFAULT))
        self.scope.connect ("activate-uri", self.on_activate_uri)
        self.scope.export()
        self.opener = urllib2.build_opener()
        self.opener.addheaders.append(('Cookie', 'age_verified=1'))
        urllib2.install_opener(self.opener)

    def on_activate_uri (self, scope, uri):
        print uri
        if uri.split('__')[0] == "page":
            results = self.scope.props.results_model
            results.remove(results.get_iter_at_row(results.get_n_rows()-1))
            self.update_results_model (uri.split('__')[2], results, int(uri.split('__')[1])+1)
            return Unity.ActivationResponse(handled=Unity.HandledType.SHOW_DASH, goto_uri='')
        else:
            GLib.spawn_command_line_async(uri)
            return Unity.ActivationResponse(handled=Unity.HandledType.HIDE_DASH, goto_uri='')


    def on_search_changed (self, scope, search=None, search_type=0, cancellable=None):
        if search:
            search_string = search.props.search_string
            print 'Search changed to %s' % search_string
        else:
            search_string = None
        if search_type == Unity.SearchType.DEFAULT:
            results = self.scope.props.results_model
            results.clear()
            self.update_results_model (search_string, results, 1)
            results.flush_revision_queue ()
        else:
            print "Hide on Global search"
        
        if search:
            search.finished()

    def update_results_model(self, search, model, page):
        counter = 0
        try:
            active_filter = self.scope.get_filter('porn_categories').get_active_option().props.id
            cat_list = ['amateur', 'anal', 'blowjob', 'cunnilingus', 'gay', 'group-sex', 'lesbian', 'masturbate', 'dildo-toys', 'webcam']
            cat_id_list = [1, 2, 9, 15, 20, 21, 26, 55, 44, 35]
            if active_filter in cat_list:
                cat_id = cat_id_list[cat_list.index(active_filter)]
            else:
                cat_id = ''
        except:
            cat_id = ''
            active_filter = ''
        pages = [page]
        for page in pages:
            if search == "None":
                search = ''
            for i in self.youporn(search, active_filter, cat_id, page):
                counter = counter + 1
                title = i[0]
                comment = i[1]
                uri = i[4]
                icon_hint = i[3]
                dnd_uri = i[2]
                model.append (uri, icon_hint, 0,"text/html", title, comment, dnd_uri)
            model.flush_revision_queue ()
        print counter
        if counter > 0:
            model.append ("page__"+str(page)+"__"+str(search), "add", 0,"text/html", "More results", "", "")

    def youporn(self, search, cat_name, cat_id, page):
        if not search or search == '':
            if cat_name != '':
                url = "http://www.youporn.com/category/%s/%s/?page=%s" % (cat_id, cat_name, page)
                print url
            else:
                url = "http://www.youporn.com/?page=%s" % (page)
        else:
            search = search.replace(" ", "+")
            url = "http://www.youporn.com/search/time?query=%s&page=%s&category_id=%s" % (search, page, cat_id)
        print url
        try:
            results = urllib2.urlopen(url).read()
            tree = fromstring(results)
            href = []
            youporn_href = []
            title = []
            icons = []
            duration = []

    # Parse for thumbnails
            for img in tree.cssselect('a img'):
                try:
                    if '/thumbnail/' in img.get('src') or '/screenshot/' in img.get('src') or '.image.' in img.get('src'):
                        icons.append(img.get('src'))
                except:
                    pass

    # Parse for uris and titles
            for a in tree.cssselect('h1 a'):
                if a.get('href').startswith("/watch/"):
                    youporn_href.append(a.get('href'))
                    title.append(a.text_content())
                    href.append(a.get('href'))
                    
    # Parse for duration
            for div in tree.cssselect('div div div'):
                if div.get('class') == "duration fontSize2":
                    if ':' in div.text_content():
                        duration.append(div.text_content())
            for h2 in tree.cssselect('div div h2'):
                if h2.get('class') == "duration fontSize2":
                    if ':' in h2.text_content():
                        duration.append(h2.text_content())

    # Parse results 
            i = -1
            result_list = []
            for uri in href:
                i = i+1
        # Add to the list
                item = []
                item.append(title[i])
                try:
                    item.append(duration[i])
                except:
                    item.append('')
                item.append("")
                try:
                    item.append(icons[i])
                except:
                    item.append('video')
                item.append("/usr/lib/unity-scope-youporn/tiny-video-parser 'http://youporn.com%s'" % uri)
                result_list.append(item)
            return result_list
        except (urllib2.URLError):
            print "Connection to http://www.youporn.com is impossible"
            return []

if __name__ == "__main__":
    session_bus_connection = Gio.bus_get_sync (Gio.BusType.SESSION, None)
    session_bus = Gio.DBusProxy.new_sync (session_bus_connection, 0, None,
                                          'org.freedesktop.DBus',
                                          '/org/freedesktop/DBus',
                                          'org.freedesktop.DBus', None)
    result = session_bus.call_sync('RequestName',
                                   GLib.Variant ("(su)", (BUS_NAME, 0x4)),
                                   0, -1, None)
                                   
    # Unpack variant response with signature "(u)". 1 means we got it.
    result = result.unpack()[0]
    
    if result != 1 :
        print >> sys.stderr, "Failed to own name %s. Bailing out." % BUS_NAME
        raise SystemExit (1)
    
    daemon = Daemon()
    GObject.MainLoop().run()