aboutsummaryrefslogtreecommitdiffstats
path: root/piccast/feeds/management/commands/scrape_feeds.py
blob: 2371f9725440e162dd109cef6dcfb654e47f2f1a (plain)
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
import re
import feedparser
import urllib
import sys
from datetime import *

from django.core.management.base import BaseCommand, CommandError
from feeds.models import *

# see Command definition at the end

# this mechanism isn't robust yet b/c any small sets get parsed repeatedly
MIN_SET_SIZE = 1   # Need to find at least this many images for each set

###############################################################################
def scrape_pics_from_html(pset, html):
    
    if(type(pset) != PicSet):
        raise("Type error, expected PicSet")

    # assumptions: one <img> per line, ordering, etc
    mset = re.finditer('<img src="(http://\S+)" \S* width="(\d+)" height="(\d+)"', html)

    pics = list()
    index = 0
    for m in mset:
        index += 1
        p = Pic()
        #print m.group(1)
        #print m.group(2)
        # This one line strips any paren content; disabled because it's just the
        # set title repeated
        #p.title = m.group(2).split(" (")[0]
        p.title = "#" + str(index)
        p.set = pset
        # empty string isn't the same as leaving this null
        #p.caption = ""
        p.original_url = m.group(1)
        p.source_url = pset.source_url
        p.width = m.group(2)
        p.height = m.group(3)
        pics.append(p)

    if(len(pics) < MIN_SET_SIZE):
        print "Didn't find enough pictures to save this set (found " + \
            str(len(pics)) + ", MIN_SET_SIZE=" + str(MIN_SET_SIZE) + ")"
        pset.delete()
        return

    # TODO: oh boy, serial, this is a horrible way to do it! 
    for p in pics:
        p.save()

    # add a thumbnail image for the picset (TODO: resize thumbnail?)
    if not pset.image:
        pset.image = pics[0]
        pset.save()

    print "Found and saved " + str(len(pics)) + " new Pics"

###############################################################################
def scrape_pics_acidcow(pset):
    
    if(type(pset) != PicSet):
        raise("Type error, expected PicSet")

    #print "DEBUG"
    #html = open("./19340-evolution-16-pics.html")
    print "Scraping from " + pset.source_url + "..."
    html = urllib.urlopen(pset.source_url)

    mset = re.finditer('src="(http://acidcow.com/pics/\d+/\S+)" alt=\'([^\.]+)\' title', html.read())

    pics = list()
    index = 0
    for m in mset:
        index += 1
        p = Pic()
        #print m.group(1)
        #print m.group(2)
        # This oneline strips any paren content; disabled because it's just the
        # set title repeated
        #p.title = m.group(2).split(" (")[0]
        p.title = "#" + str(index)
        p.set = pset
        p.caption = ""
        p.original_url = m.group(1)
        p.source_url = pset.source_url
        pics.append(p)

    # close the connection
    html.close()

    if(len(pics) < MIN_SET_SIZE):
        print "Didn't find enough pictures to save this set (found " + \
            str(len(pics)) + ", MIN_SET_SIZE=" + str(MIN_SET_SIZE) + ")"
        pset.delete()
        return

    # TODO: oh boy, serial, this is a horrible way to do it! 
    for p in pics:
        p.save()

    # add a thumbnail image for the picset (TODO: resize thumbnail?)
    if not pset.image:
        pset.image = pics[0]
        pset.save()

    print "Found and saved " + str(len(pics)) + " new Pics"


###############################################################################
def scrape_feed(feed_shortname):

    try:
        feed = PicFeed.objects.get(shortname=feed_shortname)
    except Exception as e:
        sys.stderr.write("Error finding feed by shortname: " + \
            feed_shortname + "\n")
        raise e

    print "Fetching feed for " + feed_shortname + ": " + feed.rssfeed_url
    f = feedparser.parse(feed.rssfeed_url)
    #print "DEBUG"
    #f = feedparser.parse("./acidcow_com?format=xml")
    #f = feedparser.parse("./ButDoesItFloat?format=xml")

    psets = list()
    for e in f['entries']:
        pset = dict()
        if(feed_shortname == "acidcow"):
            pset['source_url'] = e.guid
        elif(feed_shortname == "butdoesitfloat"):
            pset['source_url'] = e.comments
        else:
            pset['source_url'] = e.link
        pset['created'] = e.date
        pset['title'] = e.title
        pset['category'] = e.category
        pset['description'] = e.description
        psets.append(pset)

    # clean up parser
    del f
    
    if(feed_shortname == u"acidcow"):
        psets = filter(lambda s: s['category'] in (u'Pics', u'Picdump',u'Celebs',u'Girls',u'Cars'), psets)

    new_psets = filter(lambda s: \
        0 == len(PicSet.objects.filter(source_url=s['source_url'])), \
        psets)

    for pset in new_psets:
        print "Parsing PicSet: " + pset['title'] + " (" + pset['category'] + ")"
        p = PicSet()
        p.feed = feed
        p.source_url = pset['source_url']
        p.created = datetime.strptime(pset['created'][:-6], \
            "%a, %d %b %Y %H:%M:%S")
        # This oneline strips any paren content
        p.title = pset['title'].split(" (")[0]
        if(feed_shortname == u"butdoesitfloat"):
            # Category is a list for this site
            p.category = Category.objects.get_or_create(name="Art")[0]
        else:
            p.category = Category.objects.get_or_create(name=pset['category'])[0]

        # Ok, this is where we split out and do custom, per-site processing
        if(feed_shortname == u"acidcow"):
            p.save()
            print "Great, saved: " + p.title + " (id=" + str(p.id) + ")"
            scrape_pics_acidcow(p)
        elif(feed_shortname == u"butdoesitfloat"):
            # the descriptions here are usually important
            # TODO: should comment URL instead of link url (which bounces)?
            p.description = pset['description'].split("<img")[0]
            p.save()
            print "Great, saved: " + p.title + " (id=" + str(p.id) + ")"
            scrape_pics_from_html(p, pset['description'])
        else:
            print "ERROR: unknown PicFeed: " + pset['feed']
        #parse_page(s['source_url'], httplib.HTTPConnection)
        #break # DEBUG


###############################################################################

class Command(BaseCommand):
    args = '<feed_shortname feed_shortname ...>'
    help = 'Fetches RSS, parses, and possibly scrapes HTML for the given feeds/sources'

    def handle(self, *args, **options):
        if len(args) < 1:
            sys.stderr.write("Need to specify at least one <feed_shortname>...\n")
            return

        for shortname in args:
            try:
                scrape_feed(shortname)
            except Exception:
                sys.stderr.write("Error scraping " + shortname + "\n")

        sys.stdout.flush()
        sys.stdout.write('Done scraping feeds.\n')