/app/Http/Controllers/AnnotationsController.php
PHP | 416 lines | 302 code | 99 blank | 15 comment | 15 complexity | 69c5a34027e3c7f31b9812e0dcb8adfa MD5 | raw file
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Jobs\ProcessAnnotations;
- use App\Http\Requests;
- use Carbon\Carbon;
- use Illuminate\Support\Collection;
- class AnnotationsController extends Controller
- {
- private $jsons = [];
- private function collapseJSONs(){
- $decoded = new Collection();
- $jsons = $this->jsons;
- foreach($jsons as $json){
- $decodedSet = json_decode($json);
- $decoded->push($decodedSet->rows);
- }
- return $decoded->collapse();
- }
- public function callAPI($apiKey, $groupID, $offset=0){
- $context = stream_context_create(array (
- 'http' => array (
- 'header' => 'Authorization: Bearer '.$apiKey
- )
- ));
- $url = "https://hypothes.is/api/search?group=".$groupID."&limit=200&offset=".$offset;
- $json = file_get_contents($url, false, $context);
- $decoded = json_decode($json);
-
- $this->jsons[] = $json; //$json;
- $total = $decoded->total;
- if($total > $offset){
- \Log::info("TOTAL: ".$total.", OFFSET: ".$offset);
- $this->callAPI($apiKey, $groupID, $offset + 200); //recursive call
- }else{
- return $this->jsons;
- }
-
- }
- public function getFeed(){
- $groups = \App\Group::all();
- $jsons = [];
- foreach($groups as $group){
- $this->callAPI($group->api_key, $group->hypothesis_id);
- $jsons[$group->id] = $this->collapseJSONs();
- }
- $report = [];
- foreach($jsons as $groupID => $annotations){
- $saved = 0;
- $skipped = 0;
- foreach($annotations as $annotation){
- $existingUser = $this->findByHypothesisUsername($annotation->user);
- $existingLocalAnnotation = \App\Annotation::where("hypothesis_id", $annotation->id)->count();
- if($existingUser && $existingLocalAnnotation == 0){
- $publishedAt = \Carbon\Carbon::parse($annotation->created);
- $title = $annotation->document;
- $title = $title->title[0];
- $localAnnotation = new \App\Annotation();
- $localAnnotation->hypothesis_id = $annotation->id;
- $localAnnotation->group_id = $groupID;
- $localAnnotation->user_id = $existingUser->id;
- $localAnnotation->content = $annotation->text;
- $localAnnotation->document = $annotation->uri;
- $localAnnotation->doc_title = $title;
- $localAnnotation->source = json_encode($annotation);
- $localAnnotation->published_at = $publishedAt;
- $localAnnotation->save();
- $saved++;
- }else{
- !$existingUser ? \Log::warning("There is no registered user with this username: ".$this->cutUsernameString($annotation->user)) : "";
- $existingLocalAnnotation > 0 ? \Log::warning("Annotation: ".$annotation->id." already persisted.") : "";
- $skipped++;
- }
- }
- $ind = 0;
- $group = \App\Group::findOrFail($groupID);
- $report[$ind]['Group'] = $group->name;
- $report[$ind]['Annotations Recorded'] = $saved;
- $report[$ind]['Annotations Skipped'] = $skipped;
- $ind++;
- }
- dispatch(new ProcessAnnotations());
- return $report;
- }
- public function testRelations(){
- //$annotation = \App\Annotation::findOrFail(2);
- //dd($annotation->user->name);
- //dd($annotation->group->name);
- //return $annotation;
- //$group = \App\Group::findOrFail(1);
- //return $group->annotations;
- //$user = \App\User::findOrFail(1);
- //return ($user->annotations);
- //$annotation = \App\Annotation::findOrFail(49);
- //dd($annotation->likes->count());
- }
- public function annotationsByDocuments(){
- $module_id = "DOCUMENTS";
- $documents = \App\Annotation::distinct('document')->select('document')->get();
- $documentsArray = [];
- $index = 0;
- //check documents and prepare the collection
- foreach($documents as $document){
- $annotations = \App\Annotation::where("document", $document->document)->get();
- $documentsArray[$index]['url'] = $document->document;
- $documentsArray[$index]['title'] = $annotations[0]->doc_title;
- $documentsArray[$index]['count'] = $annotations->count();
- $documentsArray[$index]['annotations'] = $annotations;
- $documentsArray[$index]['shouldNotify'] = $annotations->count() >= 2 ? true : false;
- $index++;
- }
- foreach($documentsArray as $doc){
- if($doc['shouldNotify']){
- foreach($doc['annotations'] as $annotation){
- $data['annotation'] = $annotation;
- $data['count'] = $doc['count'];
- $data['title'] = $doc['title'];
- $userEmail = $annotation->user->email;
- $userName = $annotation->user->name;
- $link = new \App\Link();
- $link->endpoint = $doc['url'];
- $link->entity_id = $annotation->hypothesis_id;
- $link->user_id = $annotation->user->id;
- $link->clicked = 0;
- $link->module_name = $module_id;
- $link->save();
- $data['emailLink'] = $link->getApplicationLink();
- $alreadyNotified = $this->alreadyNotified($module_id, $annotation->user->id, $annotation->hypothesis_id);
- if(!$alreadyNotified){
- \Mail::send('emails.documentReached', $data, function ($m) use ($userEmail, $userName, $data) {
- $m->from('noreply@HypothesisApp.com', 'Hypothesis App');
- $m->to($userEmail, $userName)->subject($data['title'].' reached ' .$data['count']. ' annotations!');
- });
- $log = new \App\MailLog();
- $log->module_id = $module_id;
- $log->user_id = $annotation->user->id;
- $log->entity_id = $annotation->hypothesis_id;
- $log->save();
- }else{
- \Log::info("User ".$annotation->user->name. " is already notified about module ".$module_id. " and entity (annotation) ".$annotation->hypothesis_id);
- }
- }
- }
- }
- }
- public function testEmail(){
- $groups = \App\Group::all();
- foreach($groups as $group){
- $count = $group->annotations->count();
- if($count > 3){
- \Log::info("Group ".$group->name. " has ".$count . " annotations, we should notify our users...");
- $usersToNotify = [];
- foreach($group->annotations as $annotation){
- $data = [ "count" => $count,
- "group" => $group,
- "user" => $annotation->user,
- "link" => "https://hypothes.is/stream?q=group:".$group->hypothesis_id
- ];
- $usersToNotify[$annotation->user->id] = $annotation->user; //to avoid many emails to the same user
- }
- foreach($usersToNotify as $user){
- //return $data;
- $userEmail = $user->email;
- $userName = $user->name;
- \Mail::send('emails.annotationsReached', $data, function ($m) use ($userEmail, $userName, $data) {
- $m->from('noreply@HypothesisApp.com', 'Hypothesis App');
- $m->to($userEmail, $userName)->subject('Group '.$data['group']->name.' has '.$data['count'].' annotations!');
- });
- }
- }else{
- \Log::info("Group ".$group->name. " does not have enough annotations, no further action needed.");
- }
- }
- }
- public function cutUsernameString($string){
- $cutPrefix = substr($string, 5);
- $cutSufix = str_replace("@hypothes.is", "", $cutPrefix);
- return $cutSufix;
- }
- public function findByHypothesisUsername($username){
- $username = $this->cutUsernameString($username);
- return \App\User::findByHypothesisUsername($username);
- }
- public function testMentions(){
- $annotations = \App\Annotation::all();
- $mentions = [];
- foreach($annotations as $annot){
- $hasMention = $this->checkMentions($annot->content);
- if($hasMention){
- $mentions[$annot->id] = $hasMention;
- }
- }
- foreach($mentions as $annotID => $userArray){
- $annotation = \App\Annotation::findOrFail($annotID);
- foreach($userArray as $mention){
- $mention = substr($mention, 1); //to cut @
- $mentionedUser = \App\User::findByHypothesisUsername($mention);
- if($mentionedUser){
- $data['link'] = "https://hypothes.is/stream?q=user:".$mention;
- $data['user'] = $mentionedUser;
- $data['author'] = $annotation->user->name . " (@" .$annotation->user->hypothesis_username.")";
- $data['annotation'] = $annotation;
- $userEmail = $mentionedUser->email;
- $userName = $mentionedUser->name;
- \Mail::send('emails.mentionNotification', $data, function ($m) use ($userEmail, $userName, $data) {
- $m->from('noreply@HypothesisApp.com', 'Hypothesis App');
- $m->to($userEmail, $userName)->subject('New mention by '.$data['author'].'!');
- });
- }else{
- \Log::warning("User @".$mention. " was mentioned in annotation #".$annotID." but that user profile is missing");
- }
- }
- }
- }
- private function checkMentions($string){
- $matches = null;
- $returnValue = preg_match_all('/\\B@[a-z0-9_-]+/', $string, $matches);
- return $returnValue > 0 ? $matches[0] : false;
- }
- public function getLikes(){
- return \App\Like::all();
- }
- public function getLikesForAnnotation($id){
- return \App\Like::where("annotation_id", $id)->get();
- }
- public function postLike(){
- $input = \Request::all();
- $like = new \App\Like();
- $like->annotation_id = $input['annotation_id'];
- $like->user_id = $input['user_id'];
- $like->save();
- return $like;
- }
- public function deleteLikeForAnnotation(){
- $input = \Request::all();
- if(isset($input['annotation_id']) && isset($input['user_id'])){
- $like = \App\Like::where("annotation_id", $input['annotation_id'])
- ->where("user_id", $input['user_id'])->delete();
- return "DELETED";
- }
- return "OK";
- }
- public function linkRedirect($id){
- $link = \App\Link::findOrFail($id);
- $link->clicked = 1;
- $link->save();
- return redirect()->away($link->endpoint);
- }
- public function groupEmails(){
- $mailItems = \App\MailItem::all()->groupBy('user_id');
- //dd($mailItems);
- $users = []; //list of the users that should be emailed
- foreach($mailItems as $userItems){
- $userId = $userItems[0]->user_id;
- $users[$userId] = false; //assumption: no new items to send
- foreach($userItems as $emailItem){
- is_null($emailItem->mail_id) ? $users[$userId] = true : ""; //if mail_id is null then it should be sent
- }
- if($users[$userId]){
- //there is something to send, create a new Email Instance;
- $mail = new \App\Mail();
- $mail->user_id = $userId;
- $mail->subject = "Hypothesis: New notifications for you";
- $mail->sent_at = null;
- $mail->save();
- //update mail_items table with our new mail_id;
- \App\MailItem::where('user_id', $userId)
- ->where('mail_id', null)
- ->update(['mail_id' => $mail->id]);
- }
- }
- }
- public function sendEmails(){
- \Log::info('sendEmails cron-job started at (EU) '.Carbon::now(new \DateTimeZone('Europe/Belgrade')));
- \Log::info('sendEmails cron-job started at (Surrey) '.Carbon::now(new \DateTimeZone('America/Vancouver')));
- $emails = \App\Mail::where('sent_at', null)->get();
- if($emails->count() == 0){
- \Log::info("No emails to send");
- }else{
- $sent = 0;
- foreach($emails as $email){
- $userEmail = $email->user->email;
- $userName = $email->user->name;
- $subject = $email->subject;
- $data['email'] = $email;
- \Mail::send('emails.groupEmail', $data, function ($m) use ($userEmail, $userName, $subject) {
- $m->from('noreply@hypo.dusandevic.com', 'Hypothesis App');
- $m->to($userEmail, $userName)->subject($subject);
- });
- $email->touch();
- $email->save();
- $email->sent_at = $email->updated_at;
- $email->save();
- $sent++;
- }
- \Log::info($sent." emails are sent");
- }
- }
- public function showHomepage(){
- return view("welcome");
- }
- public function getGroups(){
- $data['groups'] = \App\Group::all();
- return view("groups", $data);
- }
- public function postGroup(){
- $g = new \App\Group;
- $g->name = \Request::get('name');
- $g->hypothesis_id = \Request::get('hypothesis_id');
- $g->api_key = \Request::get('api_key');
- $g->save();
- return redirect()->action('AnnotationsController@getGroups');
- }
- public function deleteGroup($id){
- $g = \App\Group::findOrFail($id);
- $g->delete();
- return redirect()->action('AnnotationsController@getGroups');
- }
- }