#!/usr/bin/env python2.5
from channelguide import manage, init # set up environment
import math
init.init_external_libraries()

from channelguide import db
from channelguide.guide.tables import channel
from channelguide.guide.models.channel import Channel
from sqlhelper.orm.query import Query
from sqlhelper.sql.statement import Select
database = db.connect()

def getAllSimilar(channel):
    sql = """SELECT DISTINCT channel_id FROM cg_channel_subscription WHERE
(channel_id<>%s AND ip_address IN (
SELECT ip_address FROM cg_channel_subscription WHERE ip_address!=%s AND
    channel_id=%s AND (NOW()-timestamp) < %s))"""
    results = database.execute(sql, (channel, "0.0.0.0", channel, 16070400))
    return [e[0] for e in results]

def getSimilarity(channel1, channel2):
    c = Channel()
    c.id = channel1
    return c.get_similarity(database, channel2)

def main():
    hit = set()
    database.execute("DELETE FROM cg_channel_recommendations");
    channels = [e[0] for e in channel.select('id').execute(database)]
    for c1 in channels:
        gas = getAllSimilar(c1)
        if gas:
            for c2 in gas:
                if c1 > c2:
                    c1, c2 = c2, c1
                k = (c1, c2)
                if k not in hit:
                    hit.add(k)
                    gs = getSimilarity(c1, c2)
                    if gs:
                        database.execute("INSERT LOW_PRIORITY INTO cg_channel_recommendations VALUES (%s, %s, %s)", (c1, c2, gs))
            database.commit()
if __name__ == "__main__":
    main()

@@ -88,17 +88,22 @@
 ort math
+, sys
 %0A
-
 init.ini
@@ -734,16 +734,254 @@
 sults%5D%0A%0A
+def getRecent(seconds):%0A    sql = %22%22%22SELECT DISTINCT channel_id FROM cg_channel_subscription WHERE (NOW()-timestamp) %3C %25s AND ip_address!=%25s%22%22%22%0A    results = database.execute(sql, (seconds, %220.0.0.0%22))%0A    return %5Be%5B0%5D for e in results%5D%0A%0A
 def getS
@@ -1106,31 +1106,23 @@
 def 
-main():%0A    hit = set
+calculateAll
 ()
+:
 %0A   
@@ -1252,16 +1252,432 @@
 abase)%5D%0A
+    calculateRecommendations(channels)%0A%0Adef calculateTwoDays():%0A    channels = map(int, getRecent(60*60*24*2))%0A    print channels%0A    container = ','.join(%5Bstr(x) for x in channels%5D)%0A    database.execute(%22DELETE FROM cg_channel_recommendations WHERE channel1_id IN (%25s) OR channel2_id IN (%25s)%22 %25 (container, container))%0A    calculateRecommendations(channels)%0A%0Adef calculateRecommendations(channels):%0A    hit = set()%0A
     for 
@@ -2158,16 +2158,17 @@
 ommit()%0A
+%0A
 if __nam
@@ -2190,15 +2190,115 @@
 _%22:%0A    
-main
+if len(sys.argv) %3E 1 and sys.argv%5B1%5D == 'all':%0A        calculateAll()%0A    else:%0A        calculateTwoDays
 ()%0A

add support for calculating last two days of recommendations