Campustream 1.0
A social network MQP for WPI
|
00001 <? 00002 00006 class stream { 00007 00008 // Define the different stream types 00009 const STREAM_PUBLIC = 1; 00010 const STREAM_FRIENDS = 2; 00011 const STREAM_USER = 3; 00012 00013 // Define the different data types 00014 const TYPE_STATUS = 'text'; 00015 const TYPE_QUESTION = 'question'; 00016 const TYPE_RESPONSE = 'response'; 00017 const TYPE_NEWSEVENT = 'newsevent'; 00018 00019 // Max length for the stream 00020 const STREAM_LENGTH = 200; 00021 00029 public static function publish($stream, $type, $id) { 00030 $stream_data = array( 00031 'type' => $type, 00032 'id' => $id 00033 ); 00034 00035 $stream_data = serialize($stream_data); 00036 00037 $stream_key = null; 00038 switch ($stream) { 00039 case self::STREAM_PUBLIC: 00040 $stream_key = 'statuses:public_timeline'; 00041 break; 00042 case self::STREAM_FRIENDS: 00043 $user = sess::getUser(); 00044 $followers = $user->followers(); 00045 $followers[] = $user->id; 00046 00047 $stream_key = array(); 00048 foreach ($followers as $follower) { 00049 $stream_key[] = "statuses:friend_timeline:$follower"; 00050 } 00051 00052 break; 00053 case self::STREAM_USER: 00054 $user = sess::getUser(); 00055 $stream_key = "statuses:user_timeline:{$user->id}"; 00056 break; 00057 } 00058 00059 if (!$stream_key) { 00060 return false; 00061 } 00062 00063 if (is_array($stream_key)) { 00064 foreach ($stream_key as $key) { 00065 self::broadcast($key, $stream_data); 00066 } 00067 } else { 00068 self::broadcast($stream_key, $stream_data); 00069 } 00070 } 00071 00072 private static function broadcast($stream_key, $data) { 00073 $r = RedisManager::connection(); 00074 00075 $id = self::id($data); 00076 Logger::debug("publishing to stream $stream_key, id $id"); 00077 $num = $r->lpush($stream_key, $data); 00078 if ($num > self::STREAM_LENGTH) { 00079 $r->ltrim($stream_key, 0, self::STREAM_LENGTH); 00080 } 00081 } 00082 00086 public static function id($data) { 00087 $data = unserialize($data); 00088 return $data['id']; 00089 } 00090 00094 public static function type($data) { 00095 $data = unserialize($data); 00096 return $data['type']; 00097 } 00098 00099 }