from celery.task import task
from django.db import transaction
from datetime import datetime
from time import mktime
import feedparser

from .models import ResourceRSS, RawItem

@task
def update_rss():
    for resource in ResourceRSS.objects.filter(status=True):
        try:
            data = feedparser.parse(resource.link)
            if 'updated_parsed' not in data.feed.keys():
                updated_date = datetime.fromtimestamp(mktime(data.entries[0].published_parsed))
            else:
                updated_date = datetime.fromtimestamp(mktime(data.entries[0].updated_parsed))
            if not resource.sync_date or resource.sync_date < updated_date:
                with transaction.commit_on_success():
                    for item in data.entries:
                        #NOTE need exist published in item like
                        # if not 'published_parsed':
                        #     related_to_date=datetime.now()
                        entry = RawItem(
                                title=item.title,
                                resource_rss=resource,
                                description=item.title,
                                link=item.link,
                                language=resource.language,
                                related_to_date=datetime.fromtimestamp(\
                                                mktime(item.published_parsed)),
                        )
                        if entry and (not resource.sync_date or \
                                     entry.related_to_date > resource.sync_date):
                            entry.save()
                resource.sync_date = updated_date
                resource.save()
                print ('sync rss "%s" done!' % data.feed.title)
        except Exception as e:
            print ('sync failes: %s' % e)

@@ -90,32 +90,8 @@
 ime%0A
-from time import mktime%0A
 impo
@@ -296,16 +296,83 @@
 e.link)%0A
+            print resource.link%0A            print data.feed.keys()%0A
         
@@ -447,32 +447,35 @@
 ated_date = 
+to_
 datetime
 .fromtimesta
@@ -462,37 +462,16 @@
 datetime
-.fromtimestamp(mktime
 (data.en
@@ -488,33 +488,32 @@
 ublished_parsed)
-)
 %0A            els
@@ -546,24 +546,27 @@
 _date = 
+to_
 datetime
 .fromtim
@@ -561,29 +561,8 @@
 time
-.fromtimestamp(mktime
 (dat
@@ -589,17 +589,16 @@
 _parsed)
-)
 %0A       
@@ -1302,24 +1302,27 @@
 to_date=
+to_
 datetime
 .fromtim
@@ -1317,79 +1317,8 @@
 time
-.fromtimestamp(%5C%0A                                                mktime
 (ite
@@ -1336,17 +1336,16 @@
 _parsed)
-)
 ,%0A      
@@ -1772,8 +1772,164 @@
 s' %25 e)%0A
+%0A%0A%0Adef to_datetime(feed_date):%0A    return datetime(feed_date%5B0%5D, feed_date%5B1%5D, feed_date%5B2%5D,%5C%0A                    feed_date%5B3%5D, feed_date%5B4%5D, feed_date%5B5%5D)%0A

add def to_datatime