summaryrefslogtreecommitdiff
path: root/bak/unused_apps/syndication
diff options
context:
space:
mode:
Diffstat (limited to 'bak/unused_apps/syndication')
-rw-r--r--bak/unused_apps/syndication/__init__.py0
-rw-r--r--bak/unused_apps/syndication/admin.py20
-rw-r--r--bak/unused_apps/syndication/migrations/0001_initial.py37
-rw-r--r--bak/unused_apps/syndication/migrations/0002_auto_20160628_2149.py31
-rw-r--r--bak/unused_apps/syndication/migrations/0003_auto_20161023_2014.py19
-rw-r--r--bak/unused_apps/syndication/migrations/__init__.py0
-rw-r--r--bak/unused_apps/syndication/models.py86
-rw-r--r--bak/unused_apps/syndication/syndicators.py123
-rw-r--r--bak/unused_apps/syndication/templatetags/__init__.py0
-rw-r--r--bak/unused_apps/syndication/templatetags/facebook_processor.py23
-rw-r--r--bak/unused_apps/syndication/views.py17
11 files changed, 356 insertions, 0 deletions
diff --git a/bak/unused_apps/syndication/__init__.py b/bak/unused_apps/syndication/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/bak/unused_apps/syndication/__init__.py
diff --git a/bak/unused_apps/syndication/admin.py b/bak/unused_apps/syndication/admin.py
new file mode 100644
index 0000000..b873eb7
--- /dev/null
+++ b/bak/unused_apps/syndication/admin.py
@@ -0,0 +1,20 @@
+from django.contrib import admin
+
+from .models import Syndicate, SyndicatedItem, FBOAuthToken
+
+
+@admin.register(FBOAuthToken)
+class FBOAuthTokenAdmin(admin.ModelAdmin):
+ list_display = ('__str__', 'expires',)
+ pass
+
+
+@admin.register(Syndicate)
+class SyndicateAdmin(admin.ModelAdmin):
+ pass
+
+
+@admin.register(SyndicatedItem)
+class SyndicatedItemAdmin(admin.ModelAdmin):
+ list_display = ('__str__', 'syndicated_to',)
+ pass
diff --git a/bak/unused_apps/syndication/migrations/0001_initial.py b/bak/unused_apps/syndication/migrations/0001_initial.py
new file mode 100644
index 0000000..9643d51
--- /dev/null
+++ b/bak/unused_apps/syndication/migrations/0001_initial.py
@@ -0,0 +1,37 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9 on 2016-03-29 10:07
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ('contenttypes', '0002_remove_content_type_name'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Syndicate',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('name', models.CharField(max_length=200)),
+ ],
+ ),
+ migrations.CreateModel(
+ name='SyndicatedItem',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('object_id', models.PositiveIntegerField()),
+ ('publish_date', models.DateTimeField()),
+ ('status', models.CharField(blank=True, choices=[('1', 'Unsent'), ('2', 'Sent')], max_length=1, null=True)),
+ ('rel_link', models.CharField(blank=True, max_length=300, null=True)),
+ ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
+ ('syndicate', models.ManyToManyField(to='syndication.Syndicate')),
+ ],
+ ),
+ ]
diff --git a/bak/unused_apps/syndication/migrations/0002_auto_20160628_2149.py b/bak/unused_apps/syndication/migrations/0002_auto_20160628_2149.py
new file mode 100644
index 0000000..51812bf
--- /dev/null
+++ b/bak/unused_apps/syndication/migrations/0002_auto_20160628_2149.py
@@ -0,0 +1,31 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9 on 2016-06-28 21:49
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('syndication', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='FBOAuthToken',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('short_token', models.TextField()),
+ ('long_token', models.TextField(blank=True, null=True)),
+ ('expires', models.DateTimeField(blank=True)),
+ ('created', models.DateTimeField(default=django.utils.timezone.now)),
+ ],
+ ),
+ migrations.AlterField(
+ model_name='syndicateditem',
+ name='status',
+ field=models.CharField(choices=[('1', 'Unsent'), ('2', 'Sent')], max_length=1, null=True),
+ ),
+ ]
diff --git a/bak/unused_apps/syndication/migrations/0003_auto_20161023_2014.py b/bak/unused_apps/syndication/migrations/0003_auto_20161023_2014.py
new file mode 100644
index 0000000..2b311fb
--- /dev/null
+++ b/bak/unused_apps/syndication/migrations/0003_auto_20161023_2014.py
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9 on 2016-10-23 20:14
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('syndication', '0002_auto_20160628_2149'),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name='fboauthtoken',
+ options={'get_latest_by': 'expires', 'ordering': ('-expires',)},
+ ),
+ ]
diff --git a/bak/unused_apps/syndication/migrations/__init__.py b/bak/unused_apps/syndication/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/bak/unused_apps/syndication/migrations/__init__.py
diff --git a/bak/unused_apps/syndication/models.py b/bak/unused_apps/syndication/models.py
new file mode 100644
index 0000000..c348c1b
--- /dev/null
+++ b/bak/unused_apps/syndication/models.py
@@ -0,0 +1,86 @@
+from django.db import models
+from django.utils import timezone
+from django.conf import settings
+import datetime
+from django.contrib.contenttypes.models import ContentType
+from django.contrib.contenttypes.fields import GenericForeignKey
+from django.db.models.signals import post_save
+from django.dispatch import receiver
+
+from .syndicators import post_to_medium, build_facebook_feed, post_to_twitter, post_photo_to_flickr, post_to_facebook
+
+
+class FBOAuthToken(models.Model):
+ short_token = models.TextField()
+ long_token = models.TextField(null=True, blank=True)
+ expires = models.DateTimeField(blank=True)
+ created = models.DateTimeField(default=timezone.now)
+
+ def __str__(self):
+ return str(self.expires)
+
+ def long_token_link(self):
+ token_url = "https://graph.facebook.com/oauth/access_token?client_id=%s&client_secret=%s&grant_type=fb_exchange_token&fb_exchange_token=%s" % (settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET, self.short_token)
+ return token_url
+
+ class Meta:
+ ordering = ('-expires',)
+ get_latest_by = 'expires'
+
+ def save(self, *args, **kwargs):
+ self.expires = self.created + datetime.timedelta(60)
+ super(FBOAuthToken, self).save()
+
+
+class Syndicate(models.Model):
+ name = models.CharField(max_length=200)
+
+ def __str__(self):
+ return self.name
+
+
+class SyndicatedItem(models.Model):
+ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
+ object_id = models.PositiveIntegerField()
+ content_object = GenericForeignKey('content_type', 'object_id')
+ syndicate = models.ManyToManyField(Syndicate)
+ publish_date = models.DateTimeField()
+ STATUS = (
+ ('1', "Unsent"),
+ ('2', "Sent"),
+ )
+ status = models.CharField(max_length=1, choices=STATUS, null=True)
+ rel_link = models.CharField(max_length=300, null=True, blank=True)
+
+ def __str__(self):
+ return str(self.content_object)
+
+ def syndicated_to(self):
+ return ','.join(str(synd) for synd in self.syndicate.all())
+
+
+@receiver(post_save, sender=SyndicatedItem)
+def post_save_events(sender, update_fields, created, instance, **kwargs):
+ print(instance.status)
+ if instance.status == "1":
+ print("---------calling-----------")
+ for item in instance.syndicate.all():
+ print(item.name)
+ if item.name == "Medium":
+ instance.rel_link = post_to_medium(instance.content_object)
+ instance.status = 2
+ if item.name == "Facebook Instant Articles":
+ build_facebook_feed()
+ instance.status = 2
+ if item.name == "Twitter":
+ print("calling function")
+ post_to_twitter(instance.content_object, instance.content_type.name)
+ if item.name == "Flickr":
+ if instance.content_type.name == "lux image":
+ post_photo_to_flickr(instance.content_object)
+ if item.name == "Facebook":
+ post_to_facebook(instance.content_object, instance.content_type.name)
+ post_save.disconnect(post_save_events, sender=SyndicatedItem)
+ instance.status = "2"
+ instance.save()
+ post_save.connect(post_save_events, sender=SyndicatedItem)
diff --git a/bak/unused_apps/syndication/syndicators.py b/bak/unused_apps/syndication/syndicators.py
new file mode 100644
index 0000000..5f8762c
--- /dev/null
+++ b/bak/unused_apps/syndication/syndicators.py
@@ -0,0 +1,123 @@
+import os
+from django.conf import settings
+from django.test.client import Client
+
+from twython import Twython
+from bs4 import BeautifulSoup
+from medium import Client as MediumClient
+import flickrapi
+import facebook
+
+from photos.models import LuxImage
+
+
+def absolute_urls_for_syndication(s):
+ soup = BeautifulSoup(s, "lxml")
+ for a in soup.find_all('a'):
+ if a['href'][:1] == "/":
+ a['href'] = "https://luxagraf.net%s" % a['href']
+ return soup
+
+
+def post_to_medium(item):
+ client = MediumClient(application_id=settings.MEDIUM_CLIENT_ID, application_secret=settings.MEDIUM_CLIENT_SECRET)
+ client.access_token = settings.MEDIUM_INT_TOKEN
+ user = client.get_current_user()
+ head = '<p><i>This was originally posted <a href="https://luxagraf.net%s" rel="canonical">on my own site</a>.</i></p>' % item.get_absolute_url()
+ body = "%s %s" % (head, absolute_urls_for_syndication(item.body_html))
+ # Create a post.
+ post = client.create_post(
+ user_id=user["id"],
+ title=item.title,
+ content=body,
+ content_format="html",
+ publish_status="public",
+ canonical_url="https://luxagraf.net%s" % item.get_absolute_url(),
+ license="all-rights-reserved"
+ )
+ return post["url"]
+
+
+def build_facebook_feed():
+ print("+++++++++++++building+++++++++++")
+ c = Client()
+ response = c.get('/iafeed.xml', HTTP_HOST='127.0.0.1')
+ f = open("%siafeed.xml" % settings.FLATFILES_ROOT, 'wb')
+ f.write(response.content)
+ f.close()
+
+
+def post_to_twitter(obj, ctype):
+ print("content type is" + ctype)
+ t = Twython(settings.TWITTER_API_KEY, settings.TWITTER_API_SECRET, settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_SECRET)
+ imgs = []
+ if ctype == "lux image":
+ p = open(obj.get_largest_image(), 'rb')
+ if obj.caption:
+ status = obj.caption
+ else:
+ status = obj.title
+ response = t.upload_media(media=p)
+ imgs.append(response)
+ elif ctype == "lux note":
+ status = obj.body_markdown
+ # parse out images and send seperately
+ soup = BeautifulSoup(status, "lxml")
+ loop = 0
+ for img in soup.find_all('img'):
+ src = img['src'].split("images/")[1]
+ i = LuxImage.objects.get(image__icontains=src)
+ p = open(i.get_largest_image(), 'rb')
+ response = t.upload_media(media=p)
+ imgs.append(response)
+ loop = loop+1
+ if loop == 3:
+ break
+ for t in soup.find_all('img'):
+ t.replaceWith("")
+ # truncate message
+ if len(status) > 140:
+ try:
+ status = status.split("|")[0] + obj.get_absolute_url()
+ except:
+ status = status[:140] + obj.get_absolute_url()
+ print(status)
+ try:
+ geo = t.reverse_geocode(lat=obj.latitude, lon=obj.longitude, accuracy=1500, granularity="city")
+ geo_id = geo['result']['places'][0]['id']
+ tweet = t.update_status(status=status, media_ids=[img['media_id'] for img in imgs], place_id=geo_id)
+ except:
+ try:
+ tweet = t.update_status(status=status, media_ids=[img['media_id'] for img in imgs])
+ except:
+ tweet = t.update_status(status=status)
+
+
+def post_photo_to_flickr(photo):
+ TOKEN_FILE = os.path.join(settings.PROJ_ROOT, "config/flickrToken")
+ token = open(TOKEN_FILE).read()
+ flickr = flickrapi.FlickrAPI(settings.FLICKR_API_KEY, settings.FLICKR_API_SECRET, token=token)
+ sent = flickr.upload(filename=photo.get_image_path_by_size("original"), title=photo.title, description=photo.caption)
+ photo_id = sent.find('photoid').text
+ photo.flickr_id = photo_id
+ try:
+ flickr.photos.geo.setLocation(photo_id=photo_id, lat=photo.latitude, lon=photo.longitude, accuracy=12)
+ except:
+ pass
+
+
+def post_to_facebook(obj, ctype):
+ from syndication.models import FBOAuthToken
+ token = FBOAuthToken.objects.latest()
+ graph = facebook.GraphAPI(access_token=token.long_token, version='2.2')
+ if ctype == "lux image":
+ p = open(obj.get_largest_image(), 'rb')
+ if obj.caption:
+ message = obj.caption
+ else:
+ message = obj.title
+ try:
+ fb_response = graph.put_photo(p, message=message)
+ print(fb_response)
+ except facebook.GraphAPIError as e:
+ print('Something went wrong:', e.type, e.message)
diff --git a/bak/unused_apps/syndication/templatetags/__init__.py b/bak/unused_apps/syndication/templatetags/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/bak/unused_apps/syndication/templatetags/__init__.py
diff --git a/bak/unused_apps/syndication/templatetags/facebook_processor.py b/bak/unused_apps/syndication/templatetags/facebook_processor.py
new file mode 100644
index 0000000..973f863
--- /dev/null
+++ b/bak/unused_apps/syndication/templatetags/facebook_processor.py
@@ -0,0 +1,23 @@
+from django import template
+from bs4 import BeautifulSoup
+
+from syndication.syndicators import absolute_urls_for_syndication
+
+register = template.Library()
+
+
+def wrap_image_tags(text):
+ soup = BeautifulSoup(text, 'lxml')
+ for img in soup.find_all('img'):
+ if img.parent.name != "figure":
+ new_tag = soup.new_tag('figure')
+ img.wrap(new_tag)
+ return soup
+
+
+def facebook_processor(text):
+ ia = absolute_urls_for_syndication(text)
+ ia = wrap_image_tags(str(ia)[12:-14])
+ return str(ia)[12:-14]
+
+register.filter('facebook_processor', facebook_processor)
diff --git a/bak/unused_apps/syndication/views.py b/bak/unused_apps/syndication/views.py
new file mode 100644
index 0000000..e489846
--- /dev/null
+++ b/bak/unused_apps/syndication/views.py
@@ -0,0 +1,17 @@
+from django.views.generic import ListView
+
+from .models import SyndicatedItem
+
+
+class FacebookFeedView(ListView):
+ """
+ Return a main entry and list of Entries in reverse chronological order
+ """
+ queryset = SyndicatedItem.objects.filter(syndicate__name__exact="Facebook")[:16]
+
+ def get_template_names(self):
+ return "fb-feed.xml"
+
+ def render_to_response(self, context, **response_kwargs):
+ response_kwargs.update({'content_type': 'text/xml'})
+ return super(FacebookFeedView, self).render_to_response(context, **response_kwargs)