-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFeed.php
97 lines (75 loc) · 2.14 KB
/
Feed.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php namespace App;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Collection;
use PicoFeed\Reader\Reader;
class Feed extends \Eloquent {
const TYPE_RSS = 1;
const TYPE_TWITTER = 2;
protected $fillable = ['name', 'url', 'type'];
public function articles()
{
return $this->hasMany('App\Article');
}
public function scopeRss($query)
{
return $query->where('type', self::TYPE_RSS);
}
public function scopeTwitter($query)
{
return $query->where('type', self::TYPE_TWITTER);
}
/**
* @return BelongsToMany
*/
public function users()
{
return $this->belongsToMany('App\User');
}
/**
* @param $q
* @return Collection
*/
public static function search($q)
{
$feeds = new Collection();
// Looks like a URL or domain name, discover
if (preg_match("#^(https?://)?[\w./]+\.\w{2,}(/.+)?$#", $q)) {
try {
$feeds = $feeds->merge(self::getFeedsFromUrl($q));
} catch (\Exception $e) {
// TODO: log the error.
}
};
if ($q) {
$res = Feed::where('name', 'like', "%$q%")->get();
} else {
$res = Feed::all();
}
$feeds = $feeds->merge($res);
return $feeds;
}
protected static function getFeedsFromUrl($url)
{
$return = new Collection();
$reader = new Reader;
$resource = $reader->download($url);
$feeds = $reader->find(
$resource->getUrl(),
$resource->getContent()
);
foreach ($feeds as $feed) {
$resource = $reader->download($feed);
$feed = $reader->getParser(
$resource->getUrl(),
$resource->getContent(),
$resource->getEncoding()
)->setHashAlgo('sha1')->execute();
$return->push(new Feed([
'name' => $feed->title,
'url' => $feed->getFeedUrl(),
'type' => self::TYPE_RSS
]));
}
return $return;
}
}