ApiV1Controller.php 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. use Illuminate\Support\Str;
  6. use App\Util\ActivityPub\Helpers;
  7. use App\Util\Media\Filter;
  8. use Laravel\Passport\Passport;
  9. use Auth, Cache, DB, Storage, URL;
  10. use Illuminate\Support\Facades\Redis;
  11. use App\{
  12. Avatar,
  13. Bookmark,
  14. Collection,
  15. CollectionItem,
  16. DirectMessage,
  17. Follower,
  18. FollowRequest,
  19. Hashtag,
  20. Instance,
  21. Like,
  22. Media,
  23. Notification,
  24. Profile,
  25. Status,
  26. StatusHashtag,
  27. User,
  28. UserSetting,
  29. UserFilter,
  30. };
  31. use League\Fractal;
  32. use App\Transformer\Api\Mastodon\v1\{
  33. AccountTransformer,
  34. MediaTransformer,
  35. NotificationTransformer,
  36. StatusTransformer,
  37. };
  38. use App\Transformer\Api\{
  39. RelationshipTransformer,
  40. };
  41. use App\Http\Controllers\FollowerController;
  42. use League\Fractal\Serializer\ArraySerializer;
  43. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  44. use App\Http\Controllers\AccountController;
  45. use App\Http\Controllers\StatusController;
  46. use App\Jobs\AvatarPipeline\AvatarOptimize;
  47. use App\Jobs\CommentPipeline\CommentPipeline;
  48. use App\Jobs\LikePipeline\LikePipeline;
  49. use App\Jobs\SharePipeline\SharePipeline;
  50. use App\Jobs\SharePipeline\UndoSharePipeline;
  51. use App\Jobs\StatusPipeline\NewStatusPipeline;
  52. use App\Jobs\StatusPipeline\StatusDelete;
  53. use App\Jobs\FollowPipeline\FollowPipeline;
  54. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  55. use App\Jobs\VideoPipeline\{
  56. VideoOptimize,
  57. VideoPostProcess,
  58. VideoThumbnail
  59. };
  60. use App\Services\{
  61. AccountService,
  62. BookmarkService,
  63. CollectionService,
  64. FollowerService,
  65. InstanceService,
  66. LikeService,
  67. NetworkTimelineService,
  68. NotificationService,
  69. MediaService,
  70. MediaPathService,
  71. ProfileStatusService,
  72. PublicTimelineService,
  73. ReblogService,
  74. RelationshipService,
  75. SearchApiV2Service,
  76. StatusService,
  77. MediaBlocklistService,
  78. SnowflakeService,
  79. UserFilterService
  80. };
  81. use App\Util\Lexer\Autolink;
  82. use App\Util\Lexer\PrettyNumber;
  83. use App\Util\Localization\Localization;
  84. use App\Util\Media\License;
  85. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  86. use App\Services\DiscoverService;
  87. use App\Services\CustomEmojiService;
  88. use App\Services\MarkerService;
  89. use App\Models\Conversation;
  90. use App\Jobs\FollowPipeline\FollowAcceptPipeline;
  91. use App\Jobs\FollowPipeline\FollowRejectPipeline;
  92. use Illuminate\Support\Facades\RateLimiter;
  93. use Purify;
  94. class ApiV1Controller extends Controller
  95. {
  96. protected $fractal;
  97. const PF_API_ENTITY_KEY = "_pe";
  98. public function __construct()
  99. {
  100. $this->fractal = new Fractal\Manager();
  101. $this->fractal->setSerializer(new ArraySerializer());
  102. }
  103. public function json($res, $code = 200, $headers = [])
  104. {
  105. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  106. }
  107. public function getWebsocketConfig()
  108. {
  109. return config('broadcasting.default') === 'pusher' ? [
  110. 'host' => config('broadcasting.connections.pusher.options.host'),
  111. 'port' => config('broadcasting.connections.pusher.options.port'),
  112. 'key' => config('broadcasting.connections.pusher.key'),
  113. 'cluster' => config('broadcasting.connections.pusher.options.cluster')
  114. ] : [];
  115. }
  116. public function getApp(Request $request)
  117. {
  118. if(!$request->user()) {
  119. return response('', 403);
  120. }
  121. $client = $request->user()->token()->client;
  122. $res = [
  123. 'name' => $client->name,
  124. 'website' => null,
  125. 'vapid_key' => null
  126. ];
  127. return $this->json($res);
  128. }
  129. public function apps(Request $request)
  130. {
  131. abort_if(!config_cache('pixelfed.oauth_enabled'), 404);
  132. $this->validate($request, [
  133. 'client_name' => 'required',
  134. 'redirect_uris' => 'required'
  135. ]);
  136. $uris = implode(',', explode('\n', $request->redirect_uris));
  137. $client = Passport::client()->forceFill([
  138. 'user_id' => null,
  139. 'name' => e($request->client_name),
  140. 'secret' => Str::random(40),
  141. 'redirect' => $uris,
  142. 'personal_access_client' => false,
  143. 'password_client' => false,
  144. 'revoked' => false,
  145. ]);
  146. $client->save();
  147. $res = [
  148. 'id' => (string) $client->id,
  149. 'name' => $client->name,
  150. 'website' => null,
  151. 'redirect_uri' => $client->redirect,
  152. 'client_id' => (string) $client->id,
  153. 'client_secret' => $client->secret,
  154. 'vapid_key' => null
  155. ];
  156. return $this->json($res, 200, [
  157. 'Access-Control-Allow-Origin' => '*'
  158. ]);
  159. }
  160. /**
  161. * GET /api/v1/accounts/verify_credentials
  162. *
  163. *
  164. * @return \App\Transformer\Api\AccountTransformer
  165. */
  166. public function verifyCredentials(Request $request)
  167. {
  168. $user = $request->user();
  169. abort_if(!$user, 403);
  170. abort_if($user->status != null, 403);
  171. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($user->profile_id) : AccountService::getMastodon($user->profile_id);
  172. $res['source'] = [
  173. 'privacy' => $res['locked'] ? 'private' : 'public',
  174. 'sensitive' => false,
  175. 'language' => $user->language ?? 'en',
  176. 'note' => strip_tags($res['note']),
  177. 'fields' => []
  178. ];
  179. return $this->json($res);
  180. }
  181. /**
  182. * GET /api/v1/accounts/{id}
  183. *
  184. * @param integer $id
  185. *
  186. * @return \App\Transformer\Api\AccountTransformer
  187. */
  188. public function accountById(Request $request, $id)
  189. {
  190. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  191. if(!$res) {
  192. return response()->json(['error' => 'Record not found'], 404);
  193. }
  194. return $this->json($res);
  195. }
  196. /**
  197. * PATCH /api/v1/accounts/update_credentials
  198. *
  199. * @return \App\Transformer\Api\AccountTransformer
  200. */
  201. public function accountUpdateCredentials(Request $request)
  202. {
  203. abort_if(!$request->user(), 403);
  204. $this->validate($request, [
  205. 'avatar' => 'sometimes|mimetypes:image/jpeg,image/png|max:' . config('pixelfed.max_avatar_size'),
  206. 'display_name' => 'nullable|string|max:30',
  207. 'note' => 'nullable|string|max:200',
  208. 'locked' => 'nullable',
  209. 'website' => 'nullable|string|max:120',
  210. // 'source.privacy' => 'nullable|in:unlisted,public,private',
  211. // 'source.sensitive' => 'nullable|boolean'
  212. ], [
  213. 'required' => 'The :attribute field is required.',
  214. 'avatar.mimetypes' => 'The file must be in jpeg or png format',
  215. 'avatar.max' => 'The :attribute exceeds the file size limit of ' . PrettyNumber::size(config('pixelfed.max_avatar_size'), true, false),
  216. ]);
  217. $user = $request->user();
  218. $profile = $user->profile;
  219. $settings = $user->settings;
  220. $changes = false;
  221. $other = array_merge(AccountService::defaultSettings()['other'], $settings->other ?? []);
  222. $syncLicenses = false;
  223. $licenseChanged = false;
  224. $composeSettings = array_merge(AccountService::defaultSettings()['compose_settings'], $settings->compose_settings ?? []);
  225. if($request->has('avatar')) {
  226. $av = Avatar::whereProfileId($profile->id)->first();
  227. if($av) {
  228. $currentAvatar = storage_path('app/'.$av->media_path);
  229. $file = $request->file('avatar');
  230. $path = "public/avatars/{$profile->id}";
  231. $name = strtolower(str_random(6)). '.' . $file->guessExtension();
  232. $request->file('avatar')->storeAs($path, $name);
  233. $av->media_path = "{$path}/{$name}";
  234. $av->save();
  235. Cache::forget("avatar:{$profile->id}");
  236. Cache::forget('user:account:id:'.$user->id);
  237. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  238. }
  239. $changes = true;
  240. }
  241. if($request->has('source[language]')) {
  242. $lang = $request->input('source[language]');
  243. if(in_array($lang, Localization::languages())) {
  244. $user->language = $lang;
  245. $changes = true;
  246. $other['language'] = $lang;
  247. }
  248. }
  249. if($request->has('website')) {
  250. $website = $request->input('website');
  251. if($website != $profile->website) {
  252. if($website) {
  253. if(!strpos($website, '.')) {
  254. $website = null;
  255. }
  256. if($website && !strpos($website, '://')) {
  257. $website = 'https://' . $website;
  258. }
  259. $host = parse_url($website, PHP_URL_HOST);
  260. $bannedInstances = InstanceService::getBannedDomains();
  261. if(in_array($host, $bannedInstances)) {
  262. $website = null;
  263. }
  264. }
  265. $profile->website = $website ? $website : null;
  266. $changes = true;
  267. }
  268. }
  269. if($request->has('display_name')) {
  270. $displayName = $request->input('display_name');
  271. if($displayName !== $user->name) {
  272. $user->name = $displayName;
  273. $profile->name = $displayName;
  274. $changes = true;
  275. }
  276. }
  277. if($request->has('note')) {
  278. $note = $request->input('note');
  279. if($note !== strip_tags($profile->bio)) {
  280. $profile->bio = Autolink::create()->autolink(strip_tags($note));
  281. $changes = true;
  282. }
  283. }
  284. if($request->has('locked')) {
  285. $locked = $request->input('locked') == 'true';
  286. if($profile->is_private != $locked) {
  287. $profile->is_private = $locked;
  288. $changes = true;
  289. }
  290. }
  291. if($request->has('reduce_motion')) {
  292. $reduced = $request->input('reduce_motion');
  293. if($settings->reduce_motion != $reduced) {
  294. $settings->reduce_motion = $reduced;
  295. $changes = true;
  296. }
  297. }
  298. if($request->has('high_contrast_mode')) {
  299. $contrast = $request->input('high_contrast_mode');
  300. if($settings->high_contrast_mode != $contrast) {
  301. $settings->high_contrast_mode = $contrast;
  302. $changes = true;
  303. }
  304. }
  305. if($request->has('video_autoplay')) {
  306. $autoplay = $request->input('video_autoplay');
  307. if($settings->video_autoplay != $autoplay) {
  308. $settings->video_autoplay = $autoplay;
  309. $changes = true;
  310. }
  311. }
  312. if($request->has('license')) {
  313. $license = $request->input('license');
  314. abort_if(!in_array($license, License::keys()), 422, 'Invalid media license id');
  315. $syncLicenses = $request->input('sync_licenses') == true;
  316. abort_if($syncLicenses && Cache::get('pf:settings:mls_recently:'.$user->id) == 2, 422, 'You can only sync licenses twice per 24 hours');
  317. if($composeSettings['default_license'] != $license) {
  318. $composeSettings['default_license'] = $license;
  319. $licenseChanged = true;
  320. $changes = true;
  321. }
  322. }
  323. if($request->has('media_descriptions')) {
  324. $md = $request->input('media_descriptions') == true;
  325. if($composeSettings['media_descriptions'] != $md) {
  326. $composeSettings['media_descriptions'] = $md;
  327. $changes = true;
  328. }
  329. }
  330. if($request->has('crawlable')) {
  331. $crawlable = $request->input('crawlable');
  332. if($settings->crawlable != $crawlable) {
  333. $settings->crawlable = $crawlable;
  334. $changes = true;
  335. }
  336. }
  337. if($request->has('show_profile_follower_count')) {
  338. $show_profile_follower_count = $request->input('show_profile_follower_count');
  339. if($settings->show_profile_follower_count != $show_profile_follower_count) {
  340. $settings->show_profile_follower_count = $show_profile_follower_count;
  341. $changes = true;
  342. }
  343. }
  344. if($request->has('show_profile_following_count')) {
  345. $show_profile_following_count = $request->input('show_profile_following_count');
  346. if($settings->show_profile_following_count != $show_profile_following_count) {
  347. $settings->show_profile_following_count = $show_profile_following_count;
  348. $changes = true;
  349. }
  350. }
  351. if($request->has('public_dm')) {
  352. $public_dm = $request->input('public_dm');
  353. if($settings->public_dm != $public_dm) {
  354. $settings->public_dm = $public_dm;
  355. $changes = true;
  356. }
  357. }
  358. if($request->has('source[privacy]')) {
  359. $scope = $request->input('source[privacy]');
  360. if(in_array($scope, ['public', 'private', 'unlisted'])) {
  361. if($composeSettings['default_scope'] != $scope) {
  362. $composeSettings['default_scope'] = $profile->is_private ? 'private' : $scope;
  363. $changes = true;
  364. }
  365. }
  366. }
  367. if($request->has('disable_embeds')) {
  368. $disabledEmbeds = $request->input('disable_embeds');
  369. if($other['disable_embeds'] != $disabledEmbeds) {
  370. $other['disable_embeds'] = $disabledEmbeds;
  371. $changes = true;
  372. }
  373. }
  374. if($changes) {
  375. $settings->other = $other;
  376. $settings->compose_settings = $composeSettings;
  377. $settings->save();
  378. $user->save();
  379. $profile->save();
  380. Cache::forget('profile:settings:' . $profile->id);
  381. Cache::forget('user:account:id:' . $profile->user_id);
  382. Cache::forget('profile:follower_count:' . $profile->id);
  383. Cache::forget('profile:following_count:' . $profile->id);
  384. Cache::forget('profile:embed:' . $profile->id);
  385. Cache::forget('profile:compose:settings:' . $user->id);
  386. Cache::forget('profile:view:'.$user->username);
  387. AccountService::del($user->profile_id);
  388. }
  389. if($syncLicenses && $licenseChanged) {
  390. $key = 'pf:settings:mls_recently:'.$user->id;
  391. $val = Cache::has($key) ? 2 : 1;
  392. Cache::put($key, $val, 86400);
  393. MediaSyncLicensePipeline::dispatch($user->id, $request->input('license'));
  394. }
  395. if($request->has(self::PF_API_ENTITY_KEY)) {
  396. $res = AccountService::get($user->profile_id, true);
  397. } else {
  398. $res = AccountService::getMastodon($user->profile_id, true);
  399. $res['bio'] = strip_tags($res['note']);
  400. $res = array_merge($res, $other);
  401. }
  402. return $this->json($res);
  403. }
  404. /**
  405. * GET /api/v1/accounts/{id}/followers
  406. *
  407. * @param integer $id
  408. *
  409. * @return \App\Transformer\Api\AccountTransformer
  410. */
  411. public function accountFollowersById(Request $request, $id)
  412. {
  413. abort_if(!$request->user(), 403);
  414. $account = AccountService::get($id);
  415. abort_if(!$account, 404);
  416. $pid = $request->user()->profile_id;
  417. if(intval($pid) !== intval($account['id'])) {
  418. if($account['locked']) {
  419. if(!FollowerService::follows($pid, $account['id'])) {
  420. return [];
  421. }
  422. }
  423. if(AccountService::hiddenFollowers($id)) {
  424. return [];
  425. }
  426. if($request->has('page') && $request->page >= 5) {
  427. return [];
  428. }
  429. }
  430. $res = DB::table('followers')
  431. ->select('id', 'profile_id', 'following_id')
  432. ->whereFollowingId($account['id'])
  433. ->orderByDesc('id')
  434. ->simplePaginate(10)
  435. ->map(function($follower) {
  436. return AccountService::getMastodon($follower->profile_id);
  437. })
  438. ->filter(function($account) {
  439. return $account && isset($account['id']);
  440. })
  441. ->values()
  442. ->toArray();
  443. return $this->json($res);
  444. }
  445. /**
  446. * GET /api/v1/accounts/{id}/following
  447. *
  448. * @param integer $id
  449. *
  450. * @return \App\Transformer\Api\AccountTransformer
  451. */
  452. public function accountFollowingById(Request $request, $id)
  453. {
  454. abort_if(!$request->user(), 403);
  455. $account = AccountService::get($id);
  456. abort_if(!$account, 404);
  457. $pid = $request->user()->profile_id;
  458. if(intval($pid) !== intval($account['id'])) {
  459. if($account['locked']) {
  460. if(!FollowerService::follows($pid, $account['id'])) {
  461. return [];
  462. }
  463. }
  464. if(AccountService::hiddenFollowing($id)) {
  465. return [];
  466. }
  467. if($request->has('page') && $request->page >= 5) {
  468. return [];
  469. }
  470. }
  471. $res = DB::table('followers')
  472. ->select('id', 'profile_id', 'following_id')
  473. ->whereProfileId($account['id'])
  474. ->orderByDesc('id')
  475. ->simplePaginate(10)
  476. ->map(function($follower) {
  477. return AccountService::get($follower->following_id);
  478. })
  479. ->filter(function($account) {
  480. return $account && isset($account['id']);
  481. })
  482. ->values()
  483. ->toArray();
  484. return $this->json($res);
  485. }
  486. /**
  487. * GET /api/v1/accounts/{id}/statuses
  488. *
  489. * @param integer $id
  490. *
  491. * @return \App\Transformer\Api\StatusTransformer
  492. */
  493. public function accountStatusesById(Request $request, $id)
  494. {
  495. $user = $request->user();
  496. $this->validate($request, [
  497. 'only_media' => 'nullable',
  498. 'media_type' => 'sometimes|string|in:photo,video',
  499. 'pinned' => 'nullable',
  500. 'exclude_replies' => 'nullable',
  501. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  502. 'since_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  503. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  504. 'limit' => 'nullable|integer|min:1|max:100'
  505. ]);
  506. $napi = $request->has(self::PF_API_ENTITY_KEY);
  507. $profile = $napi ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  508. if(!$profile || !isset($profile['id']) || !$user) {
  509. return $this->json(['error' => 'Account not found'], 404);
  510. }
  511. $limit = $request->limit ?? 20;
  512. $max_id = $request->max_id;
  513. $min_id = $request->min_id;
  514. if(!$max_id && !$min_id) {
  515. $min_id = 1;
  516. }
  517. $pid = $request->user()->profile_id;
  518. $scope = $request->only_media == true ?
  519. ['photo', 'photo:album', 'video', 'video:album'] :
  520. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  521. if($request->only_media && $request->has('media_type')) {
  522. $mt = $request->input('media_type');
  523. if($mt == 'video') {
  524. $scope = ['video', 'video:album'];
  525. }
  526. }
  527. if(intval($pid) === intval($profile['id'])) {
  528. $visibility = ['public', 'unlisted', 'private'];
  529. } else if($profile['locked']) {
  530. $following = FollowerService::follows($pid, $profile['id']);
  531. if(!$following) {
  532. return response('', 403);
  533. }
  534. $visibility = ['public', 'unlisted', 'private'];
  535. } else {
  536. $following = FollowerService::follows($pid, $profile['id']);
  537. $visibility = $following ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  538. }
  539. $dir = $min_id ? '>' : '<';
  540. $id = $min_id ?? $max_id;
  541. $res = Status::whereProfileId($profile['id'])
  542. ->whereNull('in_reply_to_id')
  543. ->whereNull('reblog_of_id')
  544. ->whereIn('type', $scope)
  545. ->where('id', $dir, $id)
  546. ->whereIn('scope', $visibility)
  547. ->limit($limit)
  548. ->orderByDesc('id')
  549. ->get()
  550. ->map(function($s) use($user, $napi, $profile) {
  551. try {
  552. $status = $napi ? StatusService::get($s->id, false) : StatusService::getMastodon($s->id, false);
  553. } catch (\Exception $e) {
  554. return false;
  555. }
  556. if($profile) {
  557. $status['account'] = $profile;
  558. }
  559. if($user && $status) {
  560. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
  561. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $s->id);
  562. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $s->id);
  563. }
  564. return $status;
  565. })
  566. ->filter(function($s) {
  567. return $s;
  568. })
  569. ->values();
  570. return $this->json($res);
  571. }
  572. /**
  573. * POST /api/v1/accounts/{id}/follow
  574. *
  575. * @param integer $id
  576. *
  577. * @return \App\Transformer\Api\RelationshipTransformer
  578. */
  579. public function accountFollowById(Request $request, $id)
  580. {
  581. abort_if(!$request->user(), 403);
  582. $user = $request->user();
  583. $target = Profile::where('id', '!=', $user->profile_id)
  584. ->whereNull('status')
  585. ->findOrFail($id);
  586. $private = (bool) $target->is_private;
  587. $remote = (bool) $target->domain;
  588. $blocked = UserFilter::whereUserId($target->id)
  589. ->whereFilterType('block')
  590. ->whereFilterableId($user->profile_id)
  591. ->whereFilterableType('App\Profile')
  592. ->exists();
  593. if($blocked == true) {
  594. abort(400, 'You cannot follow this user.');
  595. }
  596. $isFollowing = Follower::whereProfileId($user->profile_id)
  597. ->whereFollowingId($target->id)
  598. ->exists();
  599. // Following already, return empty relationship
  600. if($isFollowing == true) {
  601. $res = RelationshipService::get($user->profile_id, $target->id) ?? [];
  602. return $this->json($res);
  603. }
  604. // Rate limits, max 7500 followers per account
  605. if($user->profile->following_count && $user->profile->following_count >= Follower::MAX_FOLLOWING) {
  606. abort(400, 'You cannot follow more than ' . Follower::MAX_FOLLOWING . ' accounts');
  607. }
  608. if($private == true) {
  609. $follow = FollowRequest::firstOrCreate([
  610. 'follower_id' => $user->profile_id,
  611. 'following_id' => $target->id
  612. ]);
  613. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  614. (new FollowerController())->sendFollow($user->profile, $target);
  615. }
  616. } else {
  617. $follower = Follower::firstOrCreate([
  618. 'profile_id' => $user->profile_id,
  619. 'following_id' => $target->id
  620. ]);
  621. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  622. (new FollowerController())->sendFollow($user->profile, $target);
  623. }
  624. FollowPipeline::dispatch($follower);
  625. $target->increment('followers_count');
  626. }
  627. RelationshipService::refresh($user->profile_id, $target->id);
  628. Cache::forget('profile:following:'.$target->id);
  629. Cache::forget('profile:followers:'.$target->id);
  630. Cache::forget('profile:following:'.$user->profile_id);
  631. Cache::forget('profile:followers:'.$user->profile_id);
  632. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  633. Cache::forget('user:account:id:'.$target->user_id);
  634. Cache::forget('user:account:id:'.$user->id);
  635. Cache::forget('profile:follower_count:'.$target->id);
  636. Cache::forget('profile:follower_count:'.$user->profile_id);
  637. Cache::forget('profile:following_count:'.$target->id);
  638. Cache::forget('profile:following_count:'.$user->profile_id);
  639. AccountService::del($user->profile_id);
  640. AccountService::del($target->id);
  641. $res = RelationshipService::get($user->profile_id, $target->id);
  642. return $this->json($res);
  643. }
  644. /**
  645. * POST /api/v1/accounts/{id}/unfollow
  646. *
  647. * @param integer $id
  648. *
  649. * @return \App\Transformer\Api\RelationshipTransformer
  650. */
  651. public function accountUnfollowById(Request $request, $id)
  652. {
  653. abort_if(!$request->user(), 403);
  654. $user = $request->user();
  655. $target = Profile::where('id', '!=', $user->profile_id)
  656. ->whereNull('status')
  657. ->findOrFail($id);
  658. $private = (bool) $target->is_private;
  659. $remote = (bool) $target->domain;
  660. $isFollowing = Follower::whereProfileId($user->profile_id)
  661. ->whereFollowingId($target->id)
  662. ->exists();
  663. if($isFollowing == false) {
  664. $followRequest = FollowRequest::whereFollowerId($user->profile_id)
  665. ->whereFollowingId($target->id)
  666. ->first();
  667. if($followRequest) {
  668. $followRequest->delete();
  669. RelationshipService::refresh($target->id, $user->profile_id);
  670. }
  671. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer());
  672. $res = $this->fractal->createData($resource)->toArray();
  673. return $this->json($res);
  674. }
  675. if($user->profile->following_count) {
  676. $user->profile->decrement('following_count');
  677. }
  678. FollowRequest::whereFollowerId($user->profile_id)
  679. ->whereFollowingId($target->id)
  680. ->delete();
  681. Follower::whereProfileId($user->profile_id)
  682. ->whereFollowingId($target->id)
  683. ->delete();
  684. if(config('instance.timeline.home.cached')) {
  685. Cache::forget('pf:timelines:home:' . $user->profile_id);
  686. }
  687. FollowerService::remove($user->profile_id, $target->id);
  688. $target->decrement('followers_count');
  689. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  690. (new FollowerController())->sendUndoFollow($user->profile, $target);
  691. }
  692. RelationshipService::refresh($user->profile_id, $target->id);
  693. Cache::forget('profile:following:'.$target->id);
  694. Cache::forget('profile:followers:'.$target->id);
  695. Cache::forget('profile:following:'.$user->profile_id);
  696. Cache::forget('profile:followers:'.$user->profile_id);
  697. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  698. Cache::forget('user:account:id:'.$target->user_id);
  699. Cache::forget('user:account:id:'.$user->id);
  700. Cache::forget('profile:follower_count:'.$target->id);
  701. Cache::forget('profile:follower_count:'.$user->profile_id);
  702. Cache::forget('profile:following_count:'.$target->id);
  703. Cache::forget('profile:following_count:'.$user->profile_id);
  704. AccountService::del($user->profile_id);
  705. AccountService::del($target->id);
  706. $res = RelationshipService::get($user->profile_id, $target->id);
  707. return $this->json($res);
  708. }
  709. /**
  710. * GET /api/v1/accounts/relationships
  711. *
  712. * @param array|integer $id
  713. *
  714. * @return \App\Services\RelationshipService
  715. */
  716. public function accountRelationshipsById(Request $request)
  717. {
  718. abort_if(!$request->user(), 403);
  719. $this->validate($request, [
  720. 'id' => 'required|array|min:1|max:20',
  721. 'id.*' => 'required|integer|min:1|max:' . PHP_INT_MAX
  722. ]);
  723. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  724. $res = collect($request->input('id'))
  725. ->filter(function($id) use($pid) {
  726. return intval($id) !== intval($pid);
  727. })
  728. ->map(function($id) use($pid) {
  729. return RelationshipService::get($pid, $id);
  730. });
  731. return $this->json($res);
  732. }
  733. /**
  734. * GET /api/v1/accounts/search
  735. *
  736. *
  737. *
  738. * @return \App\Transformer\Api\AccountTransformer
  739. */
  740. public function accountSearch(Request $request)
  741. {
  742. abort_if(!$request->user(), 403);
  743. $this->validate($request, [
  744. 'q' => 'required|string|min:1|max:255',
  745. 'limit' => 'nullable|integer|min:1|max:40',
  746. 'resolve' => 'nullable'
  747. ]);
  748. $user = $request->user();
  749. $query = $request->input('q');
  750. $limit = $request->input('limit') ?? 20;
  751. $resolve = (bool) $request->input('resolve', false);
  752. $q = '%' . $query . '%';
  753. $profiles = Cache::remember('api:v1:accounts:search:' . sha1($query) . ':limit:' . $limit, 86400, function() use($q, $limit) {
  754. return Profile::whereNull('status')
  755. ->where('username', 'like', $q)
  756. ->orWhere('name', 'like', $q)
  757. ->limit($limit)
  758. ->pluck('id')
  759. ->map(function($id) {
  760. return AccountService::getMastodon($id);
  761. })
  762. ->filter(function($account) {
  763. return $account && isset($account['id']);
  764. });
  765. });
  766. return $this->json($profiles);
  767. }
  768. /**
  769. * GET /api/v1/blocks
  770. *
  771. *
  772. *
  773. * @return \App\Transformer\Api\AccountTransformer
  774. */
  775. public function accountBlocks(Request $request)
  776. {
  777. abort_if(!$request->user(), 403);
  778. $this->validate($request, [
  779. 'limit' => 'nullable|integer|min:1|max:40',
  780. 'page' => 'nullable|integer|min:1|max:10'
  781. ]);
  782. $user = $request->user();
  783. $limit = $request->input('limit') ?? 40;
  784. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  785. ->whereUserId($user->profile_id)
  786. ->whereFilterableType('App\Profile')
  787. ->whereFilterType('block')
  788. ->orderByDesc('id')
  789. ->simplePaginate($limit)
  790. ->pluck('filterable_id')
  791. ->map(function($id) {
  792. return AccountService::get($id, true);
  793. })
  794. ->filter(function($account) {
  795. return $account && isset($account['id']);
  796. })
  797. ->values();
  798. return $this->json($blocked);
  799. }
  800. /**
  801. * POST /api/v1/accounts/{id}/block
  802. *
  803. * @param integer $id
  804. *
  805. * @return \App\Transformer\Api\RelationshipTransformer
  806. */
  807. public function accountBlockById(Request $request, $id)
  808. {
  809. abort_if(!$request->user(), 403);
  810. $user = $request->user();
  811. $pid = $user->profile_id ?? $user->profile->id;
  812. if(intval($id) === intval($pid)) {
  813. abort(400, 'You cannot block yourself');
  814. }
  815. $profile = Profile::findOrFail($id);
  816. if($profile->user->is_admin == true) {
  817. abort(400, 'You cannot block an admin');
  818. }
  819. $count = UserFilterService::blockCount($pid);
  820. $maxLimit = intval(config('instance.user_filters.max_user_blocks'));
  821. if($count == 0) {
  822. $filterCount = UserFilter::whereUserId($pid)
  823. ->whereFilterType('block')
  824. ->get()
  825. ->map(function($rec) {
  826. return AccountService::get($rec->filterable_id, true);
  827. })
  828. ->filter(function($account) {
  829. return $account && isset($account['id']);
  830. })
  831. ->values()
  832. ->count();
  833. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT . $maxLimit . ' accounts');
  834. } else {
  835. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT . $maxLimit . ' accounts');
  836. }
  837. Follower::whereProfileId($profile->id)->whereFollowingId($pid)->delete();
  838. Follower::whereProfileId($pid)->whereFollowingId($profile->id)->delete();
  839. Notification::whereProfileId($pid)->whereActorId($profile->id)->delete();
  840. $filter = UserFilter::firstOrCreate([
  841. 'user_id' => $pid,
  842. 'filterable_id' => $profile->id,
  843. 'filterable_type' => 'App\Profile',
  844. 'filter_type' => 'block',
  845. ]);
  846. RelationshipService::refresh($pid, $id);
  847. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  848. $res = $this->fractal->createData($resource)->toArray();
  849. return $this->json($res);
  850. }
  851. /**
  852. * POST /api/v1/accounts/{id}/unblock
  853. *
  854. * @param integer $id
  855. *
  856. * @return \App\Transformer\Api\RelationshipTransformer
  857. */
  858. public function accountUnblockById(Request $request, $id)
  859. {
  860. abort_if(!$request->user(), 403);
  861. $user = $request->user();
  862. $pid = $user->profile_id ?? $user->profile->id;
  863. if(intval($id) === intval($pid)) {
  864. abort(400, 'You cannot unblock yourself');
  865. }
  866. $profile = Profile::findOrFail($id);
  867. $filter = UserFilter::whereUserId($pid)
  868. ->whereFilterableId($profile->id)
  869. ->whereFilterableType('App\Profile')
  870. ->whereFilterType('block')
  871. ->first();
  872. if($filter) {
  873. $filter->delete();
  874. UserFilterService::unblock($pid, $profile->id);
  875. RelationshipService::refresh($pid, $id);
  876. }
  877. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  878. $res = $this->fractal->createData($resource)->toArray();
  879. return $this->json($res);
  880. }
  881. /**
  882. * GET /api/v1/custom_emojis
  883. *
  884. * Return custom emoji
  885. *
  886. * @return array
  887. */
  888. public function customEmojis()
  889. {
  890. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  891. }
  892. /**
  893. * GET /api/v1/domain_blocks
  894. *
  895. * Return empty array
  896. *
  897. * @return array
  898. */
  899. public function accountDomainBlocks(Request $request)
  900. {
  901. abort_if(!$request->user(), 403);
  902. return response()->json([]);
  903. }
  904. /**
  905. * GET /api/v1/endorsements
  906. *
  907. * Return empty array
  908. *
  909. * @return array
  910. */
  911. public function accountEndorsements(Request $request)
  912. {
  913. abort_if(!$request->user(), 403);
  914. return response()->json([]);
  915. }
  916. /**
  917. * GET /api/v1/favourites
  918. *
  919. * Returns collection of liked statuses
  920. *
  921. * @return \App\Transformer\Api\StatusTransformer
  922. */
  923. public function accountFavourites(Request $request)
  924. {
  925. abort_if(!$request->user(), 403);
  926. $this->validate($request, [
  927. 'limit' => 'sometimes|integer|min:1|max:20'
  928. ]);
  929. $user = $request->user();
  930. $maxId = $request->input('max_id');
  931. $minId = $request->input('min_id');
  932. $limit = $request->input('limit') ?? 10;
  933. $res = Like::whereProfileId($user->profile_id)
  934. ->when($maxId, function($q, $maxId) {
  935. return $q->where('id', '<', $maxId);
  936. })
  937. ->when($minId, function($q, $minId) {
  938. return $q->where('id', '>', $minId);
  939. })
  940. ->orderByDesc('id')
  941. ->limit($limit)
  942. ->get()
  943. ->map(function($like) {
  944. $status = StatusService::getMastodon($like['status_id'], false);
  945. $status['favourited'] = true;
  946. $status['like_id'] = $like->id;
  947. $status['liked_at'] = str_replace('+00:00', 'Z', $like->created_at->format(DATE_RFC3339_EXTENDED));
  948. return $status;
  949. })
  950. ->filter(function($status) {
  951. return $status && isset($status['id'], $status['like_id']);
  952. })
  953. ->values();
  954. if($res->count()) {
  955. $ids = $res->map(function($status) {
  956. return $status['like_id'];
  957. });
  958. $max = $ids->max();
  959. $min = $ids->min();
  960. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  961. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  962. return $this->json($res, 200, ['Link' => $link]);
  963. } else {
  964. return $this->json($res);
  965. }
  966. }
  967. /**
  968. * POST /api/v1/statuses/{id}/favourite
  969. *
  970. * @param integer $id
  971. *
  972. * @return \App\Transformer\Api\StatusTransformer
  973. */
  974. public function statusFavouriteById(Request $request, $id)
  975. {
  976. abort_if(!$request->user(), 403);
  977. $user = $request->user();
  978. $status = StatusService::getMastodon($id, false);
  979. abort_unless($status, 400);
  980. $spid = $status['account']['id'];
  981. if(intval($spid) !== intval($user->profile_id)) {
  982. if($status['visibility'] == 'private') {
  983. abort_if(!FollowerService::follows($user->profile_id, $spid), 403);
  984. } else {
  985. abort_if(!in_array($status['visibility'], ['public','unlisted']), 403);
  986. }
  987. }
  988. abort_if(
  989. Like::whereProfileId($user->profile_id)
  990. ->where('created_at', '>', now()->subDay())
  991. ->count() >= Like::MAX_PER_DAY,
  992. 429
  993. );
  994. $blocks = UserFilterService::blocks($spid);
  995. if($blocks && in_array($user->profile_id, $blocks)) {
  996. abort(422);
  997. }
  998. $like = Like::firstOrCreate([
  999. 'profile_id' => $user->profile_id,
  1000. 'status_id' => $status['id']
  1001. ]);
  1002. if($like->wasRecentlyCreated == true) {
  1003. $like->status_profile_id = $spid;
  1004. $like->is_comment = !empty($status['in_reply_to_id']);
  1005. $like->save();
  1006. Status::findOrFail($status['id'])->update([
  1007. 'likes_count' => ($status['favourites_count'] ?? 0) + 1
  1008. ]);
  1009. LikePipeline::dispatch($like);
  1010. }
  1011. $status['favourited'] = true;
  1012. $status['favourites_count'] = $status['favourites_count'] + 1;
  1013. return $this->json($status);
  1014. }
  1015. /**
  1016. * POST /api/v1/statuses/{id}/unfavourite
  1017. *
  1018. * @param integer $id
  1019. *
  1020. * @return \App\Transformer\Api\StatusTransformer
  1021. */
  1022. public function statusUnfavouriteById(Request $request, $id)
  1023. {
  1024. abort_if(!$request->user(), 403);
  1025. $user = $request->user();
  1026. $status = Status::findOrFail($id);
  1027. if(intval($status->profile_id) !== intval($user->profile_id)) {
  1028. if($status->scope == 'private') {
  1029. abort_if(!$status->profile->followedBy($user->profile), 403);
  1030. } else {
  1031. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1032. }
  1033. }
  1034. $like = Like::whereProfileId($user->profile_id)
  1035. ->whereStatusId($status->id)
  1036. ->first();
  1037. if($like) {
  1038. $like->forceDelete();
  1039. $status->likes_count = $status->likes()->count();
  1040. $status->save();
  1041. }
  1042. StatusService::del($status->id);
  1043. $res = StatusService::getMastodon($status->id, false);
  1044. $res['favourited'] = false;
  1045. return $this->json($res);
  1046. }
  1047. /**
  1048. * GET /api/v1/filters
  1049. *
  1050. * Return empty response since we filter server side
  1051. *
  1052. * @return array
  1053. */
  1054. public function accountFilters(Request $request)
  1055. {
  1056. abort_if(!$request->user(), 403);
  1057. return response()->json([]);
  1058. }
  1059. /**
  1060. * GET /api/v1/follow_requests
  1061. *
  1062. * Return array of Accounts that have sent follow requests
  1063. *
  1064. * @return \App\Transformer\Api\AccountTransformer
  1065. */
  1066. public function accountFollowRequests(Request $request)
  1067. {
  1068. abort_if(!$request->user(), 403);
  1069. $this->validate($request, [
  1070. 'limit' => 'sometimes|integer|min:1|max:100'
  1071. ]);
  1072. $user = $request->user();
  1073. $res = FollowRequest::whereFollowingId($user->profile->id)
  1074. ->limit($request->input('limit', 40))
  1075. ->pluck('follower_id')
  1076. ->map(function($id) {
  1077. return AccountService::getMastodon($id, true);
  1078. })
  1079. ->filter(function($acct) {
  1080. return $acct && isset($acct['id']);
  1081. })
  1082. ->values();
  1083. return $this->json($res);
  1084. }
  1085. /**
  1086. * POST /api/v1/follow_requests/{id}/authorize
  1087. *
  1088. * @param integer $id
  1089. *
  1090. * @return null
  1091. */
  1092. public function accountFollowRequestAccept(Request $request, $id)
  1093. {
  1094. abort_if(!$request->user(), 403);
  1095. $pid = $request->user()->profile_id;
  1096. $target = AccountService::getMastodon($id);
  1097. if(!$target) {
  1098. return response()->json(['error' => 'Record not found'], 404);
  1099. }
  1100. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1101. if(!$followRequest) {
  1102. return response()->json(['error' => 'Record not found'], 404);
  1103. }
  1104. $follower = $followRequest->follower;
  1105. $follow = new Follower();
  1106. $follow->profile_id = $follower->id;
  1107. $follow->following_id = $pid;
  1108. $follow->save();
  1109. $profile = Profile::findOrFail($pid);
  1110. $profile->followers_count++;
  1111. $profile->save();
  1112. AccountService::del($profile->id);
  1113. $profile = Profile::findOrFail($follower->id);
  1114. $profile->following_count++;
  1115. $profile->save();
  1116. AccountService::del($profile->id);
  1117. if($follower->domain != null && $follower->private_key === null) {
  1118. FollowAcceptPipeline::dispatch($followRequest)->onQueue('follow');
  1119. } else {
  1120. FollowPipeline::dispatch($follow);
  1121. $followRequest->delete();
  1122. }
  1123. RelationshipService::refresh($pid, $id);
  1124. $res = RelationshipService::get($pid, $id);
  1125. $res['followed_by'] = true;
  1126. return $this->json($res);
  1127. }
  1128. /**
  1129. * POST /api/v1/follow_requests/{id}/reject
  1130. *
  1131. * @param integer $id
  1132. *
  1133. * @return null
  1134. */
  1135. public function accountFollowRequestReject(Request $request, $id)
  1136. {
  1137. abort_if(!$request->user(), 403);
  1138. $pid = $request->user()->profile_id;
  1139. $target = AccountService::getMastodon($id);
  1140. if(!$target) {
  1141. return response()->json(['error' => 'Record not found'], 404);
  1142. }
  1143. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1144. if(!$followRequest) {
  1145. return response()->json(['error' => 'Record not found'], 404);
  1146. }
  1147. $follower = $followRequest->follower;
  1148. if($follower->domain != null && $follower->private_key === null) {
  1149. FollowRejectPipeline::dispatch($followRequest)->onQueue('follow');
  1150. } else {
  1151. $followRequest->delete();
  1152. }
  1153. RelationshipService::refresh($pid, $id);
  1154. $res = RelationshipService::get($pid, $id);
  1155. return $this->json($res);
  1156. }
  1157. /**
  1158. * GET /api/v1/suggestions
  1159. *
  1160. * Return empty array as we don't support suggestions
  1161. *
  1162. * @return null
  1163. */
  1164. public function accountSuggestions(Request $request)
  1165. {
  1166. abort_if(!$request->user(), 403);
  1167. // todo
  1168. return response()->json([]);
  1169. }
  1170. /**
  1171. * GET /api/v1/instance
  1172. *
  1173. * Information about the server.
  1174. *
  1175. * @return Instance
  1176. */
  1177. public function instance(Request $request)
  1178. {
  1179. $res = Cache::remember('api:v1:instance-data-response-v1', 1800, function () {
  1180. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1181. $admin = User::whereIsAdmin(true)->first();
  1182. return $admin && isset($admin->profile_id) ?
  1183. AccountService::getMastodon($admin->profile_id, true) :
  1184. null;
  1185. });
  1186. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1187. return [
  1188. 'user_count' => User::count(),
  1189. 'status_count' => Status::whereNull('uri')->count(),
  1190. 'domain_count' => Instance::count(),
  1191. ];
  1192. });
  1193. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1194. return config_cache('app.rules') ?
  1195. collect(json_decode(config_cache('app.rules'), true))
  1196. ->map(function($rule, $key) {
  1197. $id = $key + 1;
  1198. return [
  1199. 'id' => "{$id}",
  1200. 'text' => $rule
  1201. ];
  1202. })
  1203. ->toArray() : [];
  1204. });
  1205. return [
  1206. 'uri' => config('pixelfed.domain.app'),
  1207. 'title' => config('app.name'),
  1208. 'short_description' => config_cache('app.short_description'),
  1209. 'description' => config_cache('app.description'),
  1210. 'email' => config('instance.email'),
  1211. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1212. 'urls' => [
  1213. 'streaming_api' => 'wss://' . config('pixelfed.domain.app')
  1214. ],
  1215. 'stats' => $stats,
  1216. 'thumbnail' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  1217. 'languages' => [config('app.locale')],
  1218. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1219. 'approval_required' => false,
  1220. 'contact_account' => $contact,
  1221. 'rules' => $rules,
  1222. 'configuration' => [
  1223. 'media_attachments' => [
  1224. 'image_matrix_limit' => 16777216,
  1225. 'image_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1226. 'supported_mime_types' => explode(',', config('pixelfed.media_types')),
  1227. 'video_frame_rate_limit' => 120,
  1228. 'video_matrix_limit' => 2304000,
  1229. 'video_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1230. ],
  1231. 'polls' => [
  1232. 'max_characters_per_option' => 50,
  1233. 'max_expiration' => 2629746,
  1234. 'max_options' => 4,
  1235. 'min_expiration' => 300
  1236. ],
  1237. 'statuses' => [
  1238. 'characters_reserved_per_url' => 23,
  1239. 'max_characters' => (int) config('pixelfed.max_caption_length'),
  1240. 'max_media_attachments' => (int) config('pixelfed.max_album_length')
  1241. ]
  1242. ]
  1243. ];
  1244. });
  1245. return $this->json($res);
  1246. }
  1247. /**
  1248. * GET /api/v1/lists
  1249. *
  1250. * Return empty array as we don't support lists
  1251. *
  1252. * @return null
  1253. */
  1254. public function accountLists(Request $request)
  1255. {
  1256. abort_if(!$request->user(), 403);
  1257. return response()->json([]);
  1258. }
  1259. /**
  1260. * GET /api/v1/accounts/{id}/lists
  1261. *
  1262. * @param integer $id
  1263. *
  1264. * @return null
  1265. */
  1266. public function accountListsById(Request $request, $id)
  1267. {
  1268. abort_if(!$request->user(), 403);
  1269. return response()->json([]);
  1270. }
  1271. /**
  1272. * POST /api/v1/media
  1273. *
  1274. *
  1275. * @return MediaTransformer
  1276. */
  1277. public function mediaUpload(Request $request)
  1278. {
  1279. abort_if(!$request->user(), 403);
  1280. $this->validate($request, [
  1281. 'file.*' => [
  1282. 'required_without:file',
  1283. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1284. 'max:' . config_cache('pixelfed.max_photo_size'),
  1285. ],
  1286. 'file' => [
  1287. 'required_without:file.*',
  1288. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1289. 'max:' . config_cache('pixelfed.max_photo_size'),
  1290. ],
  1291. 'filter_name' => 'nullable|string|max:24',
  1292. 'filter_class' => 'nullable|alpha_dash|max:24',
  1293. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1294. ]);
  1295. $user = $request->user();
  1296. if($user->last_active_at == null) {
  1297. return [];
  1298. }
  1299. if(empty($request->file('file'))) {
  1300. return response('', 422);
  1301. }
  1302. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1303. $limitTtl = now()->addMinutes(15);
  1304. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1305. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1306. return $dailyLimit >= 250;
  1307. });
  1308. abort_if($limitReached == true, 429);
  1309. $profile = $user->profile;
  1310. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1311. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1312. return Media::whereUserId($user->id)->sum('size') / 1000;
  1313. });
  1314. $limit = (int) config_cache('pixelfed.max_account_size');
  1315. if ($size >= $limit) {
  1316. abort(403, 'Account size limit reached.');
  1317. }
  1318. }
  1319. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1320. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1321. $photo = $request->file('file');
  1322. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1323. if(in_array($photo->getMimeType(), $mimes) == false) {
  1324. abort(403, 'Invalid or unsupported mime type.');
  1325. }
  1326. $storagePath = MediaPathService::get($user, 2);
  1327. $path = $photo->store($storagePath);
  1328. $hash = \hash_file('sha256', $photo);
  1329. $license = null;
  1330. $mime = $photo->getMimeType();
  1331. // if($photo->getMimeType() == 'image/heic') {
  1332. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1333. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1334. // $oldPath = $path;
  1335. // $path = str_replace('.heic', '.jpg', $path);
  1336. // $mime = 'image/jpeg';
  1337. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1338. // @unlink(storage_path("app/{$oldPath}"));
  1339. // }
  1340. $settings = UserSetting::whereUserId($user->id)->first();
  1341. if($settings && !empty($settings->compose_settings)) {
  1342. $compose = $settings->compose_settings;
  1343. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1344. $license = $compose['default_license'];
  1345. }
  1346. }
  1347. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1348. $media = new Media();
  1349. $media->status_id = null;
  1350. $media->profile_id = $profile->id;
  1351. $media->user_id = $user->id;
  1352. $media->media_path = $path;
  1353. $media->original_sha256 = $hash;
  1354. $media->size = $photo->getSize();
  1355. $media->mime = $mime;
  1356. $media->caption = $request->input('description');
  1357. $media->filter_class = $filterClass;
  1358. $media->filter_name = $filterName;
  1359. if($license) {
  1360. $media->license = $license;
  1361. }
  1362. $media->save();
  1363. switch ($media->mime) {
  1364. case 'image/jpeg':
  1365. case 'image/png':
  1366. ImageOptimize::dispatch($media);
  1367. break;
  1368. case 'video/mp4':
  1369. VideoThumbnail::dispatch($media);
  1370. $preview_url = '/storage/no-preview.png';
  1371. $url = '/storage/no-preview.png';
  1372. break;
  1373. }
  1374. Cache::forget($limitKey);
  1375. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1376. $res = $this->fractal->createData($resource)->toArray();
  1377. $res['preview_url'] = $media->url(). '?v=' . time();
  1378. $res['url'] = $media->url(). '?v=' . time();
  1379. return $this->json($res);
  1380. }
  1381. /**
  1382. * PUT /api/v1/media/{id}
  1383. *
  1384. * @param integer $id
  1385. *
  1386. * @return MediaTransformer
  1387. */
  1388. public function mediaUpdate(Request $request, $id)
  1389. {
  1390. abort_if(!$request->user(), 403);
  1391. $this->validate($request, [
  1392. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1393. ]);
  1394. $user = $request->user();
  1395. $media = Media::whereUserId($user->id)
  1396. ->whereProfileId($user->profile_id)
  1397. ->findOrFail($id);
  1398. $executed = RateLimiter::attempt(
  1399. 'media:update:'.$user->id,
  1400. 10,
  1401. function() use($media, $request) {
  1402. $caption = Purify::clean($request->input('description'));
  1403. if($caption != $media->caption) {
  1404. $media->caption = $caption;
  1405. $media->save();
  1406. if($media->status_id) {
  1407. MediaService::del($media->status_id);
  1408. StatusService::del($media->status_id);
  1409. }
  1410. }
  1411. });
  1412. if(!$executed) {
  1413. return response()->json([
  1414. 'error' => 'Too many attempts. Try again in a few minutes.'
  1415. ], 429);
  1416. };
  1417. return $this->json(MediaService::get($media->status_id));
  1418. }
  1419. /**
  1420. * GET /api/v1/media/{id}
  1421. *
  1422. * @param integer $id
  1423. *
  1424. * @return MediaTransformer
  1425. */
  1426. public function mediaGet(Request $request, $id)
  1427. {
  1428. abort_if(!$request->user(), 403);
  1429. $user = $request->user();
  1430. $media = Media::whereUserId($user->id)
  1431. ->whereNull('status_id')
  1432. ->findOrFail($id);
  1433. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1434. $res = $this->fractal->createData($resource)->toArray();
  1435. return $this->json($res);
  1436. }
  1437. /**
  1438. * POST /api/v2/media
  1439. *
  1440. *
  1441. * @return MediaTransformer
  1442. */
  1443. public function mediaUploadV2(Request $request)
  1444. {
  1445. abort_if(!$request->user(), 403);
  1446. $this->validate($request, [
  1447. 'file.*' => [
  1448. 'required_without:file',
  1449. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1450. 'max:' . config_cache('pixelfed.max_photo_size'),
  1451. ],
  1452. 'file' => [
  1453. 'required_without:file.*',
  1454. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1455. 'max:' . config_cache('pixelfed.max_photo_size'),
  1456. ],
  1457. 'filter_name' => 'nullable|string|max:24',
  1458. 'filter_class' => 'nullable|alpha_dash|max:24',
  1459. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1460. ]);
  1461. $user = $request->user();
  1462. if($user->last_active_at == null) {
  1463. return [];
  1464. }
  1465. if(empty($request->file('file'))) {
  1466. return response('', 422);
  1467. }
  1468. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1469. $limitTtl = now()->addMinutes(15);
  1470. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1471. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1472. return $dailyLimit >= 250;
  1473. });
  1474. abort_if($limitReached == true, 429);
  1475. $profile = $user->profile;
  1476. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1477. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1478. return Media::whereUserId($user->id)->sum('size') / 1000;
  1479. });
  1480. $limit = (int) config_cache('pixelfed.max_account_size');
  1481. if ($size >= $limit) {
  1482. abort(403, 'Account size limit reached.');
  1483. }
  1484. }
  1485. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1486. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1487. $photo = $request->file('file');
  1488. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1489. if(in_array($photo->getMimeType(), $mimes) == false) {
  1490. abort(403, 'Invalid or unsupported mime type.');
  1491. }
  1492. $storagePath = MediaPathService::get($user, 2);
  1493. $path = $photo->store($storagePath);
  1494. $hash = \hash_file('sha256', $photo);
  1495. $license = null;
  1496. $mime = $photo->getMimeType();
  1497. $settings = UserSetting::whereUserId($user->id)->first();
  1498. if($settings && !empty($settings->compose_settings)) {
  1499. $compose = $settings->compose_settings;
  1500. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1501. $license = $compose['default_license'];
  1502. }
  1503. }
  1504. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1505. $media = new Media();
  1506. $media->status_id = null;
  1507. $media->profile_id = $profile->id;
  1508. $media->user_id = $user->id;
  1509. $media->media_path = $path;
  1510. $media->original_sha256 = $hash;
  1511. $media->size = $photo->getSize();
  1512. $media->mime = $mime;
  1513. $media->caption = $request->input('description');
  1514. $media->filter_class = $filterClass;
  1515. $media->filter_name = $filterName;
  1516. if($license) {
  1517. $media->license = $license;
  1518. }
  1519. $media->save();
  1520. switch ($media->mime) {
  1521. case 'image/jpeg':
  1522. case 'image/png':
  1523. ImageOptimize::dispatch($media);
  1524. break;
  1525. case 'video/mp4':
  1526. VideoThumbnail::dispatch($media);
  1527. $preview_url = '/storage/no-preview.png';
  1528. $url = '/storage/no-preview.png';
  1529. break;
  1530. }
  1531. Cache::forget($limitKey);
  1532. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1533. $res = $this->fractal->createData($resource)->toArray();
  1534. $res['preview_url'] = $media->url(). '?v=' . time();
  1535. $res['url'] = null;
  1536. return $this->json($res, 202);
  1537. }
  1538. /**
  1539. * GET /api/v1/mutes
  1540. *
  1541. *
  1542. * @return AccountTransformer
  1543. */
  1544. public function accountMutes(Request $request)
  1545. {
  1546. abort_if(!$request->user(), 403);
  1547. $this->validate($request, [
  1548. 'limit' => 'nullable|integer|min:1|max:40'
  1549. ]);
  1550. $user = $request->user();
  1551. $limit = $request->input('limit', 40);
  1552. $mutes = UserFilter::whereUserId($user->profile_id)
  1553. ->whereFilterableType('App\Profile')
  1554. ->whereFilterType('mute')
  1555. ->orderByDesc('id')
  1556. ->simplePaginate($limit)
  1557. ->pluck('filterable_id')
  1558. ->map(function($id) {
  1559. return AccountService::get($id, true);
  1560. })
  1561. ->filter(function($account) {
  1562. return $account && isset($account['id']);
  1563. })
  1564. ->values();
  1565. return $this->json($mutes);
  1566. }
  1567. /**
  1568. * POST /api/v1/accounts/{id}/mute
  1569. *
  1570. * @param integer $id
  1571. *
  1572. * @return RelationshipTransformer
  1573. */
  1574. public function accountMuteById(Request $request, $id)
  1575. {
  1576. abort_if(!$request->user(), 403);
  1577. $user = $request->user();
  1578. $pid = $user->profile_id;
  1579. if(intval($pid) === intval($id)) {
  1580. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1581. }
  1582. $account = Profile::findOrFail($id);
  1583. $count = UserFilterService::muteCount($pid);
  1584. $maxLimit = intval(config('instance.user_filters.max_user_mutes'));
  1585. if($count == 0) {
  1586. $filterCount = UserFilter::whereUserId($pid)
  1587. ->whereFilterType('mute')
  1588. ->get()
  1589. ->map(function($rec) {
  1590. return AccountService::get($rec->filterable_id, true);
  1591. })
  1592. ->filter(function($account) {
  1593. return $account && isset($account['id']);
  1594. })
  1595. ->values()
  1596. ->count();
  1597. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1598. } else {
  1599. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1600. }
  1601. $filter = UserFilter::firstOrCreate([
  1602. 'user_id' => $pid,
  1603. 'filterable_id' => $account->id,
  1604. 'filterable_type' => 'App\Profile',
  1605. 'filter_type' => 'mute',
  1606. ]);
  1607. RelationshipService::refresh($pid, $id);
  1608. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1609. $res = $this->fractal->createData($resource)->toArray();
  1610. return $this->json($res);
  1611. }
  1612. /**
  1613. * POST /api/v1/accounts/{id}/unmute
  1614. *
  1615. * @param integer $id
  1616. *
  1617. * @return RelationshipTransformer
  1618. */
  1619. public function accountUnmuteById(Request $request, $id)
  1620. {
  1621. abort_if(!$request->user(), 403);
  1622. $user = $request->user();
  1623. $pid = $user->profile_id;
  1624. if(intval($pid) === intval($id)) {
  1625. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1626. }
  1627. $profile = Profile::findOrFail($id);
  1628. $filter = UserFilter::whereUserId($pid)
  1629. ->whereFilterableId($profile->id)
  1630. ->whereFilterableType('App\Profile')
  1631. ->whereFilterType('mute')
  1632. ->first();
  1633. if($filter) {
  1634. $filter->delete();
  1635. UserFilterService::unmute($pid, $profile->id);
  1636. RelationshipService::refresh($pid, $id);
  1637. }
  1638. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  1639. $res = $this->fractal->createData($resource)->toArray();
  1640. return $this->json($res);
  1641. }
  1642. /**
  1643. * GET /api/v1/notifications
  1644. *
  1645. *
  1646. * @return NotificationTransformer
  1647. */
  1648. public function accountNotifications(Request $request)
  1649. {
  1650. abort_if(!$request->user(), 403);
  1651. $this->validate($request, [
  1652. 'limit' => 'nullable|integer|min:1|max:100',
  1653. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1654. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1655. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1656. ]);
  1657. $pid = $request->user()->profile_id;
  1658. $limit = $request->input('limit', 20);
  1659. $since = $request->input('since_id');
  1660. $min = $request->input('min_id');
  1661. $max = $request->input('max_id');
  1662. if(!$since && !$min && !$max) {
  1663. $min = 1;
  1664. }
  1665. $maxId = null;
  1666. $minId = null;
  1667. if($max) {
  1668. $res = NotificationService::getMaxMastodon($pid, $max, $limit);
  1669. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1670. if(!empty($ids)) {
  1671. $maxId = max($ids);
  1672. $minId = min($ids);
  1673. }
  1674. } else {
  1675. $res = NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  1676. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1677. if(!empty($ids)) {
  1678. $maxId = max($ids);
  1679. $minId = min($ids);
  1680. }
  1681. }
  1682. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1683. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1684. NotificationService::warmCache($pid, 400, true);
  1685. }
  1686. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1687. if($minId == $maxId) {
  1688. $minId = null;
  1689. }
  1690. if($maxId) {
  1691. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1692. }
  1693. if($minId) {
  1694. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1695. }
  1696. if($maxId && $minId) {
  1697. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1698. }
  1699. $headers = isset($link) ? ['Link' => $link] : [];
  1700. return $this->json($res, 200, $headers);
  1701. }
  1702. /**
  1703. * GET /api/v1/timelines/home
  1704. *
  1705. *
  1706. * @return StatusTransformer
  1707. */
  1708. public function timelineHome(Request $request)
  1709. {
  1710. $this->validate($request,[
  1711. 'page' => 'nullable|integer|max:40',
  1712. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1713. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1714. 'limit' => 'nullable|integer|max:100'
  1715. ]);
  1716. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1717. $page = $request->input('page');
  1718. $min = $request->input('min_id');
  1719. $max = $request->input('max_id');
  1720. $limit = $request->input('limit') ?? 20;
  1721. $pid = $request->user()->profile_id;
  1722. $following = Cache::remember('profile:following:'.$pid, 1209600, function() use($pid) {
  1723. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1724. return $following->push($pid)->toArray();
  1725. });
  1726. $includeReplies = false;
  1727. if(config('exp.top')) {
  1728. $includeReplies = (bool) Redis::zscore('pf:tl:replies', $pid);
  1729. }
  1730. if(config('instance.timeline.home.cached') && (!$min && !$max)) {
  1731. $ttl = config('instance.timeline.home.cache_ttl');
  1732. $res = Cache::remember(
  1733. 'pf:timelines:home:' . $pid,
  1734. $ttl,
  1735. function() use(
  1736. $following,
  1737. $limit,
  1738. $pid,
  1739. $includeReplies
  1740. ) {
  1741. return Status::select(
  1742. 'id',
  1743. 'uri',
  1744. 'caption',
  1745. 'rendered',
  1746. 'profile_id',
  1747. 'type',
  1748. 'in_reply_to_id',
  1749. 'reblog_of_id',
  1750. 'is_nsfw',
  1751. 'scope',
  1752. 'local',
  1753. 'reply_count',
  1754. 'comments_disabled',
  1755. 'place_id',
  1756. 'likes_count',
  1757. 'reblogs_count',
  1758. 'created_at',
  1759. 'updated_at'
  1760. )
  1761. ->when(!$includeReplies, function($q, $includeReplies) {
  1762. return $q->whereNull('in_reply_to_id');
  1763. })
  1764. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1765. ->whereIn('profile_id', $following)
  1766. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1767. ->orderBy('created_at', 'desc')
  1768. ->limit($limit)
  1769. ->get()
  1770. ->map(function($s) {
  1771. $status = StatusService::get($s->id, false);
  1772. if(!$status) {
  1773. return false;
  1774. }
  1775. return $status;
  1776. })
  1777. ->filter(function($s) {
  1778. return $s && isset($s['account']['id']);
  1779. })
  1780. ->values()
  1781. ->toArray();
  1782. });
  1783. $res = collect($res)
  1784. ->map(function($s) use ($pid) {
  1785. $status = StatusService::get($s['id'], false);
  1786. if(!$status) {
  1787. return false;
  1788. }
  1789. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1790. $status['bookmarked'] = (bool) BookmarkService::get($pid, $s['id']);
  1791. $status['reblogged'] = (bool) ReblogService::get($pid, $s['id']);
  1792. return $status;
  1793. })
  1794. ->filter(function($s) {
  1795. return $s && isset($s['account']['id']);
  1796. })
  1797. ->values()
  1798. ->take($limit)
  1799. ->toArray();
  1800. }
  1801. if($min || $max) {
  1802. $dir = $min ? '>' : '<';
  1803. $id = $min ?? $max;
  1804. $res = Status::select(
  1805. 'id',
  1806. 'profile_id',
  1807. 'type',
  1808. 'visibility',
  1809. 'created_at'
  1810. )
  1811. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1812. ->where('id', $dir, $id)
  1813. ->when(!$includeReplies, function($q, $includeReplies) {
  1814. return $q->whereNull('in_reply_to_id');
  1815. })
  1816. ->whereIn('profile_id', $following)
  1817. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1818. ->latest()
  1819. ->take(($limit * 2))
  1820. ->get()
  1821. ->map(function($s) use($pid, $napi) {
  1822. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1823. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1824. return false;
  1825. }
  1826. if($pid) {
  1827. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1828. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1829. }
  1830. return $status;
  1831. })
  1832. ->filter(function($status) {
  1833. return $status && isset($status['account']);
  1834. })
  1835. ->take($limit)
  1836. ->values();
  1837. } else {
  1838. $res = Status::select(
  1839. 'id',
  1840. 'profile_id',
  1841. 'type',
  1842. 'visibility',
  1843. 'created_at'
  1844. )
  1845. ->when(!$includeReplies, function($q, $includeReplies) {
  1846. return $q->whereNull('in_reply_to_id');
  1847. })
  1848. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1849. ->whereIn('profile_id', $following)
  1850. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1851. ->latest()
  1852. ->take(($limit * 2))
  1853. ->get()
  1854. ->map(function($s) use($pid, $napi) {
  1855. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1856. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1857. return false;
  1858. }
  1859. if($pid) {
  1860. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1861. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1862. }
  1863. return $status;
  1864. })
  1865. ->filter(function($status) {
  1866. return $status && isset($status['account']);
  1867. })
  1868. ->take($limit)
  1869. ->values();
  1870. }
  1871. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  1872. $minId = $res->map(function($s) {
  1873. return ['id' => $s['id']];
  1874. })->min('id');
  1875. $maxId = $res->map(function($s) {
  1876. return ['id' => $s['id']];
  1877. })->max('id');
  1878. if($minId == $maxId) {
  1879. $minId = null;
  1880. }
  1881. if($maxId) {
  1882. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1883. }
  1884. if($minId) {
  1885. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1886. }
  1887. if($maxId && $minId) {
  1888. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1889. }
  1890. $headers = isset($link) ? ['Link' => $link] : [];
  1891. return $this->json($res->toArray(), 200, $headers);
  1892. }
  1893. /**
  1894. * GET /api/v1/timelines/public
  1895. *
  1896. *
  1897. * @return StatusTransformer
  1898. */
  1899. public function timelinePublic(Request $request)
  1900. {
  1901. $this->validate($request,[
  1902. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1903. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1904. 'limit' => 'nullable|integer|max:100',
  1905. 'remote' => 'sometimes',
  1906. 'local' => 'sometimes'
  1907. ]);
  1908. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1909. $min = $request->input('min_id');
  1910. $max = $request->input('max_id');
  1911. $limit = $request->input('limit') ?? 20;
  1912. $user = $request->user();
  1913. $remote = ($request->has('remote') && $request->input('remote') == true) || ($request->filled('local') && $request->input('local') != true);
  1914. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1915. if((!$request->has('local') || $remote) && config('instance.timeline.network.cached')) {
  1916. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function() {
  1917. if(NetworkTimelineService::count() == 0) {
  1918. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  1919. }
  1920. });
  1921. if ($max) {
  1922. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  1923. } else if ($min) {
  1924. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  1925. } else {
  1926. $feed = NetworkTimelineService::get(0, $limit + 5);
  1927. }
  1928. } else {
  1929. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1930. if(PublicTimelineService::count() == 0) {
  1931. PublicTimelineService::warmCache(true, 400);
  1932. }
  1933. });
  1934. if ($max) {
  1935. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  1936. } else if ($min) {
  1937. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  1938. } else {
  1939. $feed = PublicTimelineService::get(0, $limit + 5);
  1940. }
  1941. }
  1942. $res = collect($feed)
  1943. ->filter(function($k) use($min, $max) {
  1944. if(!$min && !$max) {
  1945. return true;
  1946. }
  1947. if($min) {
  1948. return $min != $k;
  1949. }
  1950. if($max) {
  1951. return $max != $k;
  1952. }
  1953. })
  1954. ->map(function($k) use($user, $napi) {
  1955. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  1956. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1957. return false;
  1958. }
  1959. if($user) {
  1960. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1961. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  1962. }
  1963. return $status;
  1964. })
  1965. ->filter(function($s) use($filtered) {
  1966. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  1967. })
  1968. ->take($limit)
  1969. ->values();
  1970. $baseUrl = config('app.url') . '/api/v1/timelines/public?limit=' . $limit . '&';
  1971. if($remote) {
  1972. $baseUrl .= 'remote=1&';
  1973. }
  1974. $minId = $res->map(function($s) {
  1975. return ['id' => $s['id']];
  1976. })->min('id');
  1977. $maxId = $res->map(function($s) {
  1978. return ['id' => $s['id']];
  1979. })->max('id');
  1980. if($minId == $maxId) {
  1981. $minId = null;
  1982. }
  1983. if($maxId) {
  1984. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1985. }
  1986. if($minId) {
  1987. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1988. }
  1989. if($maxId && $minId) {
  1990. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1991. }
  1992. $headers = isset($link) ? ['Link' => $link] : [];
  1993. return $this->json($res->toArray(), 200, $headers);
  1994. }
  1995. /**
  1996. * GET /api/v1/conversations
  1997. *
  1998. * Not implemented
  1999. *
  2000. * @return array
  2001. */
  2002. public function conversations(Request $request)
  2003. {
  2004. abort_if(!$request->user(), 403);
  2005. $this->validate($request, [
  2006. 'limit' => 'min:1|max:40',
  2007. 'scope' => 'nullable|in:inbox,sent,requests'
  2008. ]);
  2009. $limit = $request->input('limit', 20);
  2010. $scope = $request->input('scope', 'inbox');
  2011. $pid = $request->user()->profile_id;
  2012. if(config('database.default') == 'pgsql') {
  2013. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  2014. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  2015. })
  2016. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2017. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  2018. })
  2019. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2020. return $q->whereToId($pid)->whereIsHidden(true);
  2021. });
  2022. } else {
  2023. $dms = Conversation::when($scope === 'inbox', function($q, $scope) use($pid) {
  2024. return $q->whereIsHidden(false)
  2025. ->where('to_id', $pid)
  2026. ->orWhere('from_id', $pid)
  2027. ->orderByDesc('status_id')
  2028. ->groupBy(['to_id', 'from_id']);
  2029. })
  2030. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2031. return $q->whereFromId($pid)->groupBy('to_id');
  2032. })
  2033. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2034. return $q->whereToId($pid)->whereIsHidden(true);
  2035. });
  2036. }
  2037. $dms = $dms->orderByDesc('status_id')
  2038. ->simplePaginate($limit)
  2039. ->map(function($dm) use($pid) {
  2040. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2041. $res = [
  2042. 'id' => $dm->id,
  2043. 'unread' => false,
  2044. 'accounts' => [
  2045. AccountService::getMastodon($from)
  2046. ],
  2047. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  2048. ];
  2049. return $res;
  2050. })
  2051. ->filter(function($dm) {
  2052. return isset($dm['accounts']) && count($dm['accounts']) && !empty($dm['last_status']);
  2053. })
  2054. ->unique(function($item, $key) {
  2055. return $item['accounts'][0]['id'];
  2056. })
  2057. ->values();
  2058. return $this->json($dms);
  2059. }
  2060. /**
  2061. * GET /api/v1/statuses/{id}
  2062. *
  2063. * @param integer $id
  2064. *
  2065. * @return StatusTransformer
  2066. */
  2067. public function statusById(Request $request, $id)
  2068. {
  2069. abort_if(!$request->user(), 403);
  2070. $user = $request->user();
  2071. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2072. if(!$res || !isset($res['visibility'])) {
  2073. abort(404);
  2074. }
  2075. $scope = $res['visibility'];
  2076. if(!in_array($scope, ['public', 'unlisted'])) {
  2077. if($scope === 'private') {
  2078. if(intval($res['account']['id']) !== intval($user->profile_id)) {
  2079. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  2080. }
  2081. } else {
  2082. abort(400, 'Invalid request');
  2083. }
  2084. }
  2085. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  2086. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  2087. $res['bookmarked'] = BookmarkService::get($user->profile_id, $res['id']);
  2088. return $this->json($res);
  2089. }
  2090. /**
  2091. * GET /api/v1/statuses/{id}/context
  2092. *
  2093. * @param integer $id
  2094. *
  2095. * @return StatusTransformer
  2096. */
  2097. public function statusContext(Request $request, $id)
  2098. {
  2099. abort_if(!$request->user(), 403);
  2100. $user = $request->user();
  2101. $pid = $user->profile_id;
  2102. $status = StatusService::getMastodon($id, false);
  2103. if(!$status || !isset($status['account'])) {
  2104. return response('', 404);
  2105. }
  2106. if(intval($status['account']['id']) !== intval($user->profile_id)) {
  2107. if($status['visibility'] == 'private') {
  2108. if(!FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2109. return response('', 404);
  2110. }
  2111. } else {
  2112. if(!in_array($status['visibility'], ['public','unlisted'])) {
  2113. return response('', 404);
  2114. }
  2115. }
  2116. }
  2117. $ancestors = [];
  2118. $descendants = [];
  2119. if($status['in_reply_to_id']) {
  2120. $ancestors[] = StatusService::getMastodon($status['in_reply_to_id'], false);
  2121. }
  2122. if($status['replies_count']) {
  2123. $descendants = DB::table('statuses')
  2124. ->where('in_reply_to_id', $id)
  2125. ->limit(20)
  2126. ->pluck('id')
  2127. ->map(function($sid) {
  2128. return StatusService::getMastodon($sid, false);
  2129. })
  2130. ->filter(function($post) {
  2131. return $post && isset($post['account']);
  2132. })
  2133. ->map(function($status) use($pid) {
  2134. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2135. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2136. return $status;
  2137. })
  2138. ->values();
  2139. }
  2140. $res = [
  2141. 'ancestors' => $ancestors,
  2142. 'descendants' => $descendants
  2143. ];
  2144. return $this->json($res);
  2145. }
  2146. /**
  2147. * GET /api/v1/statuses/{id}/card
  2148. *
  2149. * @param integer $id
  2150. *
  2151. * @return StatusTransformer
  2152. */
  2153. public function statusCard(Request $request, $id)
  2154. {
  2155. abort_if(!$request->user(), 403);
  2156. $res = [];
  2157. return response()->json($res);
  2158. }
  2159. /**
  2160. * GET /api/v1/statuses/{id}/reblogged_by
  2161. *
  2162. * @param integer $id
  2163. *
  2164. * @return AccountTransformer
  2165. */
  2166. public function statusRebloggedBy(Request $request, $id)
  2167. {
  2168. abort_if(!$request->user(), 403);
  2169. $this->validate($request, [
  2170. 'limit' => 'nullable|integer|min:1|max:100'
  2171. ]);
  2172. $limit = $request->input('limit') ?? 10;
  2173. $user = $request->user();
  2174. $status = Status::findOrFail($id);
  2175. $author = intval($status->profile_id) === intval($user->profile_id) || $user->is_admin;
  2176. abort_if(
  2177. !$status->type ||
  2178. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2179. 404,
  2180. );
  2181. if(!$author) {
  2182. if($status->scope == 'private') {
  2183. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2184. } else {
  2185. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2186. }
  2187. }
  2188. $res = Status::where('reblog_of_id', $status->id)
  2189. ->orderByDesc('id')
  2190. ->cursorPaginate($limit)
  2191. ->withQueryString();
  2192. if(!$res) {
  2193. return $this->json([]);
  2194. }
  2195. $headers = [];
  2196. if($author && $res->hasPages()) {
  2197. $links = '';
  2198. if($res->previousPageUrl()) {
  2199. $links = '<' . $res->previousPageUrl() .'>; rel="prev"';
  2200. }
  2201. if($res->nextPageUrl()) {
  2202. if(!empty($links)) {
  2203. $links .= ', ';
  2204. }
  2205. $links .= '<' . $res->nextPageUrl() .'>; rel="next"';
  2206. }
  2207. $headers = ['Link' => $links];
  2208. }
  2209. $res = $res->map(function($status) use($user) {
  2210. $account = AccountService::getMastodon($status->profile_id, true);
  2211. if(!$account) {
  2212. return false;
  2213. }
  2214. $account['follows'] = $status->profile_id == $user->profile_id ? null : FollowerService::follows($user->profile_id, $status->profile_id);
  2215. return $account;
  2216. })
  2217. ->filter(function($account) {
  2218. return $account && isset($account['id']);
  2219. })
  2220. ->values();
  2221. return $this->json($res, 200, $headers);
  2222. }
  2223. /**
  2224. * GET /api/v1/statuses/{id}/favourited_by
  2225. *
  2226. * @param integer $id
  2227. *
  2228. * @return AccountTransformer
  2229. */
  2230. public function statusFavouritedBy(Request $request, $id)
  2231. {
  2232. abort_if(!$request->user(), 403);
  2233. $this->validate($request, [
  2234. 'limit' => 'nullable|integer|min:1|max:100'
  2235. ]);
  2236. $limit = $request->input('limit') ?? 10;
  2237. $user = $request->user();
  2238. $status = Status::findOrFail($id);
  2239. $author = intval($status->profile_id) === intval($user->profile_id) || $user->is_admin;
  2240. abort_if(
  2241. !$status->type ||
  2242. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2243. 404,
  2244. );
  2245. if(!$author) {
  2246. if($status->scope == 'private') {
  2247. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2248. } else {
  2249. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2250. }
  2251. if($request->has('cursor')) {
  2252. return $this->json([]);
  2253. }
  2254. }
  2255. $res = Like::where('status_id', $status->id)
  2256. ->orderByDesc('id')
  2257. ->cursorPaginate($limit)
  2258. ->withQueryString();
  2259. if(!$res) {
  2260. return $this->json([]);
  2261. }
  2262. $headers = [];
  2263. if($author && $res->hasPages()) {
  2264. $links = '';
  2265. if($res->previousPageUrl()) {
  2266. $links = '<' . $res->previousPageUrl() .'>; rel="prev"';
  2267. }
  2268. if($res->nextPageUrl()) {
  2269. if(!empty($links)) {
  2270. $links .= ', ';
  2271. }
  2272. $links .= '<' . $res->nextPageUrl() .'>; rel="next"';
  2273. }
  2274. $headers = ['Link' => $links];
  2275. }
  2276. $res = $res->map(function($like) use($user) {
  2277. $account = AccountService::getMastodon($like->profile_id, true);
  2278. if(!$account) {
  2279. return false;
  2280. }
  2281. $account['follows'] = $like->profile_id == $user->profile_id ? null : FollowerService::follows($user->profile_id, $like->profile_id);
  2282. return $account;
  2283. })
  2284. ->filter(function($account) use($user) {
  2285. return $account && isset($account['id']);
  2286. })
  2287. ->values();
  2288. return $this->json($res, 200, $headers);
  2289. }
  2290. /**
  2291. * POST /api/v1/statuses
  2292. *
  2293. *
  2294. * @return StatusTransformer
  2295. */
  2296. public function statusCreate(Request $request)
  2297. {
  2298. abort_if(!$request->user(), 403);
  2299. $this->validate($request, [
  2300. 'status' => 'nullable|string',
  2301. 'in_reply_to_id' => 'nullable',
  2302. 'media_ids' => 'sometimes|array|max:' . config_cache('pixelfed.max_album_length'),
  2303. 'sensitive' => 'nullable',
  2304. 'visibility' => 'string|in:private,unlisted,public',
  2305. 'spoiler_text' => 'sometimes|max:140',
  2306. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2307. 'collection_ids' => 'sometimes|array|max:3',
  2308. 'comments_disabled' => 'sometimes|boolean',
  2309. ]);
  2310. if(config('costar.enabled') == true) {
  2311. $blockedKeywords = config('costar.keyword.block');
  2312. if($blockedKeywords !== null && $request->status) {
  2313. $keywords = config('costar.keyword.block');
  2314. foreach($keywords as $kw) {
  2315. if(Str::contains($request->status, $kw) == true) {
  2316. abort(400, 'Invalid object. Contains banned keyword.');
  2317. }
  2318. }
  2319. }
  2320. }
  2321. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  2322. abort(403, 'Empty statuses are not allowed');
  2323. }
  2324. $ids = $request->input('media_ids');
  2325. $in_reply_to_id = $request->input('in_reply_to_id');
  2326. $user = $request->user();
  2327. $profile = $user->profile;
  2328. $limitKey = 'compose:rate-limit:store:' . $user->id;
  2329. $limitTtl = now()->addMinutes(15);
  2330. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  2331. $dailyLimit = Status::whereProfileId($user->profile_id)
  2332. ->whereNull('in_reply_to_id')
  2333. ->whereNull('reblog_of_id')
  2334. ->where('created_at', '>', now()->subDays(1))
  2335. ->count();
  2336. return $dailyLimit >= 100;
  2337. });
  2338. abort_if($limitReached == true, 429);
  2339. $visibility = $profile->is_private ? 'private' : (
  2340. $profile->unlisted == true &&
  2341. $request->input('visibility', 'public') == 'public' ?
  2342. 'unlisted' :
  2343. $request->input('visibility', 'public'));
  2344. if($user->last_active_at == null) {
  2345. return [];
  2346. }
  2347. $content = strip_tags($request->input('status'));
  2348. $rendered = Autolink::create()->autolink($content);
  2349. $cw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  2350. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2351. if($in_reply_to_id) {
  2352. $parent = Status::findOrFail($in_reply_to_id);
  2353. if($parent->comments_disabled) {
  2354. return $this->json("Comments have been disabled on this post", 422);
  2355. }
  2356. $blocks = UserFilterService::blocks($parent->profile_id);
  2357. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  2358. $status = new Status;
  2359. $status->caption = $content;
  2360. $status->rendered = $rendered;
  2361. $status->scope = $visibility;
  2362. $status->visibility = $visibility;
  2363. $status->profile_id = $user->profile_id;
  2364. $status->is_nsfw = $cw;
  2365. $status->cw_summary = $spoilerText;
  2366. $status->in_reply_to_id = $parent->id;
  2367. $status->in_reply_to_profile_id = $parent->profile_id;
  2368. $status->save();
  2369. StatusService::del($parent->id);
  2370. Cache::forget('status:replies:all:' . $parent->id);
  2371. }
  2372. if($ids) {
  2373. if(Media::whereUserId($user->id)
  2374. ->whereNull('status_id')
  2375. ->find($ids)
  2376. ->count() == 0
  2377. ) {
  2378. abort(400, 'Invalid media_ids');
  2379. }
  2380. if(!$in_reply_to_id) {
  2381. $status = new Status;
  2382. $status->caption = $content;
  2383. $status->rendered = $rendered;
  2384. $status->profile_id = $user->profile_id;
  2385. $status->scope = 'draft';
  2386. $status->is_nsfw = $cw;
  2387. $status->cw_summary = $spoilerText;
  2388. if($request->has('place_id')) {
  2389. $status->place_id = $request->input('place_id');
  2390. }
  2391. $status->save();
  2392. }
  2393. $mimes = [];
  2394. foreach($ids as $k => $v) {
  2395. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  2396. continue;
  2397. }
  2398. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  2399. if($m->profile_id !== $user->profile_id || $m->status_id) {
  2400. abort(403, 'Invalid media id');
  2401. }
  2402. $m->status_id = $status->id;
  2403. $m->save();
  2404. array_push($mimes, $m->mime);
  2405. }
  2406. if(empty($mimes)) {
  2407. $status->delete();
  2408. abort(400, 'Invalid media ids');
  2409. }
  2410. if($request->has('comments_disabled') && $request->input('comments_disabled')) {
  2411. $status->comments_disabled = true;
  2412. }
  2413. $status->scope = $visibility;
  2414. $status->visibility = $visibility;
  2415. $status->type = StatusController::mimeTypeCheck($mimes);
  2416. $status->save();
  2417. }
  2418. if(!$status) {
  2419. abort(500, 'An error occured.');
  2420. }
  2421. NewStatusPipeline::dispatch($status);
  2422. if($status->in_reply_to_id) {
  2423. CommentPipeline::dispatch($parent, $status);
  2424. }
  2425. Cache::forget('user:account:id:'.$user->id);
  2426. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  2427. Cache::forget('profile:status_count:'.$user->profile_id);
  2428. Cache::forget($user->storageUsedKey());
  2429. Cache::forget('profile:embed:' . $status->profile_id);
  2430. Cache::forget($limitKey);
  2431. if($request->has('collection_ids') && $ids) {
  2432. $collections = Collection::whereProfileId($user->profile_id)
  2433. ->find($request->input('collection_ids'))
  2434. ->each(function($collection) use($status) {
  2435. $count = $collection->items()->count();
  2436. $item = CollectionItem::firstOrCreate([
  2437. 'collection_id' => $collection->id,
  2438. 'object_type' => 'App\Status',
  2439. 'object_id' => $status->id
  2440. ],[
  2441. 'order' => $count,
  2442. ]);
  2443. CollectionService::addItem(
  2444. $collection->id,
  2445. $status->id,
  2446. $count
  2447. );
  2448. $collection->updated_at = now();
  2449. $collection->save();
  2450. CollectionService::setCollection($collection->id, $collection);
  2451. });
  2452. }
  2453. $res = StatusService::getMastodon($status->id, false);
  2454. $res['favourited'] = false;
  2455. $res['language'] = 'en';
  2456. $res['bookmarked'] = false;
  2457. $res['card'] = null;
  2458. return $this->json($res);
  2459. }
  2460. /**
  2461. * DELETE /api/v1/statuses
  2462. *
  2463. * @param integer $id
  2464. *
  2465. * @return null
  2466. */
  2467. public function statusDelete(Request $request, $id)
  2468. {
  2469. abort_if(!$request->user(), 403);
  2470. $status = Status::whereProfileId($request->user()->profile->id)
  2471. ->findOrFail($id);
  2472. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2473. Cache::forget('profile:status_count:'.$status->profile_id);
  2474. StatusDelete::dispatch($status);
  2475. $res = $this->fractal->createData($resource)->toArray();
  2476. $res['text'] = $res['content'];
  2477. unset($res['content']);
  2478. return $this->json($res);
  2479. }
  2480. /**
  2481. * POST /api/v1/statuses/{id}/reblog
  2482. *
  2483. * @param integer $id
  2484. *
  2485. * @return StatusTransformer
  2486. */
  2487. public function statusShare(Request $request, $id)
  2488. {
  2489. abort_if(!$request->user(), 403);
  2490. $user = $request->user();
  2491. $status = Status::whereScope('public')->findOrFail($id);
  2492. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2493. if($status->scope == 'private') {
  2494. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2495. } else {
  2496. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2497. }
  2498. $blocks = UserFilterService::blocks($status->profile_id);
  2499. if($blocks && in_array($user->profile_id, $blocks)) {
  2500. abort(422);
  2501. }
  2502. }
  2503. $share = Status::firstOrCreate([
  2504. 'profile_id' => $user->profile_id,
  2505. 'reblog_of_id' => $status->id,
  2506. 'type' => 'share',
  2507. 'in_reply_to_profile_id' => $status->profile_id,
  2508. 'scope' => 'public',
  2509. 'visibility' => 'public'
  2510. ]);
  2511. SharePipeline::dispatch($share)->onQueue('low');
  2512. StatusService::del($status->id);
  2513. ReblogService::add($user->profile_id, $status->id);
  2514. $res = StatusService::getMastodon($status->id);
  2515. $res['reblogged'] = true;
  2516. return $this->json($res);
  2517. }
  2518. /**
  2519. * POST /api/v1/statuses/{id}/unreblog
  2520. *
  2521. * @param integer $id
  2522. *
  2523. * @return StatusTransformer
  2524. */
  2525. public function statusUnshare(Request $request, $id)
  2526. {
  2527. abort_if(!$request->user(), 403);
  2528. $user = $request->user();
  2529. $status = Status::whereScope('public')->findOrFail($id);
  2530. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2531. if($status->scope == 'private') {
  2532. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2533. } else {
  2534. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2535. }
  2536. }
  2537. $reblog = Status::whereProfileId($user->profile_id)
  2538. ->whereReblogOfId($status->id)
  2539. ->first();
  2540. if(!$reblog) {
  2541. $res = StatusService::getMastodon($status->id);
  2542. $res['reblogged'] = false;
  2543. return $this->json($res);
  2544. }
  2545. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  2546. ReblogService::del($user->profile_id, $status->id);
  2547. $res = StatusService::getMastodon($status->id);
  2548. $res['reblogged'] = false;
  2549. return $this->json($res);
  2550. }
  2551. /**
  2552. * GET /api/v1/timelines/tag/{hashtag}
  2553. *
  2554. * @param string $hashtag
  2555. *
  2556. * @return StatusTransformer
  2557. */
  2558. public function timelineHashtag(Request $request, $hashtag)
  2559. {
  2560. abort_if(!$request->user(), 403);
  2561. $this->validate($request,[
  2562. 'page' => 'nullable|integer|max:40',
  2563. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2564. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2565. 'limit' => 'nullable|integer|max:100'
  2566. ]);
  2567. $tag = Hashtag::whereName($hashtag)
  2568. ->orWhere('slug', $hashtag)
  2569. ->first();
  2570. if(!$tag) {
  2571. return response()->json([]);
  2572. }
  2573. if($tag->is_banned == true) {
  2574. return $this->json([]);
  2575. }
  2576. $min = $request->input('min_id');
  2577. $max = $request->input('max_id');
  2578. $limit = $request->input('limit', 20);
  2579. if(!$min && !$max) {
  2580. $id = 1;
  2581. $dir = '>';
  2582. } else {
  2583. $dir = $min ? '>' : '<';
  2584. $id = $min ?? $max;
  2585. }
  2586. $res = StatusHashtag::whereHashtagId($tag->id)
  2587. ->whereStatusVisibility('public')
  2588. ->where('status_id', $dir, $id)
  2589. ->latest()
  2590. ->limit($limit)
  2591. ->pluck('status_id')
  2592. ->map(function ($i) {
  2593. if($i) {
  2594. return StatusService::getMastodon($i);
  2595. }
  2596. })
  2597. ->filter(function($i) {
  2598. return $i && isset($i['account']);
  2599. })
  2600. ->values()
  2601. ->toArray();
  2602. return $this->json($res);
  2603. }
  2604. /**
  2605. * GET /api/v1/bookmarks
  2606. *
  2607. *
  2608. *
  2609. * @return StatusTransformer
  2610. */
  2611. public function bookmarks(Request $request)
  2612. {
  2613. abort_if(!$request->user(), 403);
  2614. $this->validate($request, [
  2615. 'limit' => 'nullable|integer|min:1|max:40',
  2616. 'max_id' => 'nullable|integer|min:0',
  2617. 'since_id' => 'nullable|integer|min:0',
  2618. 'min_id' => 'nullable|integer|min:0'
  2619. ]);
  2620. $pe = $request->has('_pe');
  2621. $pid = $request->user()->profile_id;
  2622. $limit = $request->input('limit') ?? 20;
  2623. $max_id = $request->input('max_id');
  2624. $since_id = $request->input('since_id');
  2625. $min_id = $request->input('min_id');
  2626. $dir = $min_id ? '>' : '<';
  2627. $id = $min_id ?? $max_id;
  2628. $bookmarkQuery = Bookmark::whereProfileId($pid)
  2629. ->orderByDesc('id')
  2630. ->cursorPaginate($limit);
  2631. $bookmarks = $bookmarkQuery->map(function($bookmark) use($pid, $pe) {
  2632. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  2633. if($status) {
  2634. $status['bookmarked'] = true;
  2635. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2636. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2637. }
  2638. return $status;
  2639. })
  2640. ->filter()
  2641. ->values()
  2642. ->toArray();
  2643. $links = null;
  2644. $headers = [];
  2645. if($bookmarkQuery->nextCursor()) {
  2646. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  2647. }
  2648. if($bookmarkQuery->previousCursor()) {
  2649. if($links != null) {
  2650. $links .= ', ';
  2651. }
  2652. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  2653. }
  2654. if($links) {
  2655. $headers = ['Link' => $links];
  2656. }
  2657. return $this->json($bookmarks, 200, $headers);
  2658. }
  2659. /**
  2660. * POST /api/v1/statuses/{id}/bookmark
  2661. *
  2662. *
  2663. *
  2664. * @return StatusTransformer
  2665. */
  2666. public function bookmarkStatus(Request $request, $id)
  2667. {
  2668. abort_if(!$request->user(), 403);
  2669. $status = Status::findOrFail($id);
  2670. $pid = $request->user()->profile_id;
  2671. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2672. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2673. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2674. if($status->scope == 'private') {
  2675. abort_if(
  2676. $pid !== $status->profile_id && !FollowerService::follows($pid, $status->profile_id),
  2677. 404,
  2678. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  2679. );
  2680. }
  2681. Bookmark::firstOrCreate([
  2682. 'status_id' => $status->id,
  2683. 'profile_id' => $pid
  2684. ]);
  2685. BookmarkService::add($pid, $status->id);
  2686. $res = StatusService::getMastodon($status->id, false);
  2687. $res['bookmarked'] = true;
  2688. return $this->json($res);
  2689. }
  2690. /**
  2691. * POST /api/v1/statuses/{id}/unbookmark
  2692. *
  2693. *
  2694. *
  2695. * @return StatusTransformer
  2696. */
  2697. public function unbookmarkStatus(Request $request, $id)
  2698. {
  2699. abort_if(!$request->user(), 403);
  2700. $status = Status::findOrFail($id);
  2701. $pid = $request->user()->profile_id;
  2702. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2703. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2704. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2705. $bookmark = Bookmark::whereStatusId($status->id)
  2706. ->whereProfileId($pid)
  2707. ->first();
  2708. if($bookmark) {
  2709. BookmarkService::del($pid, $status->id);
  2710. $bookmark->delete();
  2711. }
  2712. $res = StatusService::getMastodon($status->id, false);
  2713. $res['bookmarked'] = false;
  2714. return $this->json($res);
  2715. }
  2716. /**
  2717. * GET /api/v2/search
  2718. *
  2719. *
  2720. * @return array
  2721. */
  2722. public function searchV2(Request $request)
  2723. {
  2724. abort_if(!$request->user(), 403);
  2725. $this->validate($request, [
  2726. 'q' => 'required|string|min:1|max:100',
  2727. 'account_id' => 'nullable|string',
  2728. 'max_id' => 'nullable|string',
  2729. 'min_id' => 'nullable|string',
  2730. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2731. 'exclude_unreviewed' => 'nullable',
  2732. 'resolve' => 'nullable',
  2733. 'limit' => 'nullable|integer|max:40',
  2734. 'offset' => 'nullable|integer',
  2735. 'following' => 'nullable'
  2736. ]);
  2737. return $this->json(SearchApiV2Service::query($request, true));
  2738. }
  2739. /**
  2740. * GET /api/v1/discover/posts
  2741. *
  2742. *
  2743. * @return array
  2744. */
  2745. public function discoverPosts(Request $request)
  2746. {
  2747. abort_if(!$request->user(), 403);
  2748. $this->validate($request, [
  2749. 'limit' => 'integer|min:1|max:40'
  2750. ]);
  2751. $limit = $request->input('limit', 40);
  2752. $pid = $request->user()->profile_id;
  2753. $filters = UserFilterService::filters($pid);
  2754. $forYou = DiscoverService::getForYou();
  2755. $posts = $forYou->take(50)->map(function($post) {
  2756. return StatusService::getMastodon($post);
  2757. })
  2758. ->filter(function($post) use($filters) {
  2759. return $post &&
  2760. isset($post['account']) &&
  2761. isset($post['account']['id']) &&
  2762. !in_array($post['account']['id'], $filters);
  2763. })
  2764. ->take(12)
  2765. ->values();
  2766. return $this->json(compact('posts'));
  2767. }
  2768. /**
  2769. * GET /api/v2/statuses/{id}/replies
  2770. *
  2771. *
  2772. * @return array
  2773. */
  2774. public function statusReplies(Request $request, $id)
  2775. {
  2776. abort_if(!$request->user(), 403);
  2777. $this->validate($request, [
  2778. 'limit' => 'int|min:1|max:10',
  2779. 'sort' => 'in:all,newest,popular'
  2780. ]);
  2781. $limit = $request->input('limit', 3);
  2782. $pid = $request->user()->profile_id;
  2783. $status = StatusService::getMastodon($id, false);
  2784. abort_if(!$status, 404);
  2785. if($status['visibility'] == 'private') {
  2786. if($pid != $status['account']['id']) {
  2787. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2788. }
  2789. }
  2790. $sortBy = $request->input('sort', 'all');
  2791. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  2792. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2793. Cache::forget('status:replies:all:' . $id);
  2794. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2795. }
  2796. }
  2797. if($sortBy == 'all' && !$request->has('cursor')) {
  2798. $ids = Cache::remember('status:replies:all:' . $id, 3600, function() use($id) {
  2799. return DB::table('statuses')
  2800. ->where('in_reply_to_id', $id)
  2801. ->orderBy('id')
  2802. ->cursorPaginate(3);
  2803. });
  2804. } else {
  2805. $ids = DB::table('statuses')
  2806. ->where('in_reply_to_id', $id)
  2807. ->when($sortBy, function($q, $sortBy) {
  2808. if($sortBy === 'all') {
  2809. return $q->orderBy('id');
  2810. }
  2811. if($sortBy === 'newest') {
  2812. return $q->orderByDesc('created_at');
  2813. }
  2814. if($sortBy === 'popular') {
  2815. return $q->orderByDesc('likes_count');
  2816. }
  2817. })
  2818. ->cursorPaginate($limit);
  2819. }
  2820. $data = $ids->map(function($post) use($pid) {
  2821. $status = StatusService::get($post->id, false);
  2822. if(!$status || !isset($status['id'])) {
  2823. return false;
  2824. }
  2825. $status['favourited'] = LikeService::liked($pid, $post->id);
  2826. return $status;
  2827. })
  2828. ->map(function($post) {
  2829. if(isset($post['account']) && isset($post['account']['id'])) {
  2830. $account = AccountService::get($post['account']['id'], true);
  2831. $post['account'] = $account;
  2832. }
  2833. return $post;
  2834. })
  2835. ->filter(function($post) {
  2836. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  2837. })
  2838. ->values();
  2839. $res = [
  2840. 'data' => $data,
  2841. 'next' => $ids->nextPageUrl()
  2842. ];
  2843. return $this->json($res);
  2844. }
  2845. /**
  2846. * GET /api/v2/statuses/{id}/state
  2847. *
  2848. *
  2849. * @return array
  2850. */
  2851. public function statusState(Request $request, $id)
  2852. {
  2853. abort_if(!$request->user(), 403);
  2854. $status = Status::findOrFail($id);
  2855. $pid = $request->user()->profile_id;
  2856. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2857. return $this->json(StatusService::getState($status->id, $pid));
  2858. }
  2859. /**
  2860. * GET /api/v1.1/discover/accounts/popular
  2861. *
  2862. *
  2863. * @return array
  2864. */
  2865. public function discoverAccountsPopular(Request $request)
  2866. {
  2867. abort_if(!$request->user(), 403);
  2868. $pid = $request->user()->profile_id;
  2869. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 86400, function() {
  2870. return DB::table('profiles')
  2871. ->where('is_private', false)
  2872. ->whereNull('status')
  2873. ->orderByDesc('profiles.followers_count')
  2874. ->limit(20)
  2875. ->get();
  2876. });
  2877. $ids = $ids->map(function($profile) {
  2878. return AccountService::get($profile->id, true);
  2879. })
  2880. ->filter(function($profile) use($pid) {
  2881. return $profile && isset($profile['id']);
  2882. })
  2883. ->filter(function($profile) use($pid) {
  2884. return $profile['id'] != $pid;
  2885. })
  2886. ->map(function($profile) {
  2887. $ids = collect(ProfileStatusService::get($profile['id'], 0, 9))
  2888. ->map(function($id) {
  2889. return StatusService::get($id, true);
  2890. })
  2891. ->filter(function($post) {
  2892. return $post && isset($post['id']);
  2893. })
  2894. ->take(3);
  2895. $profile['recent_posts'] = $ids;
  2896. return $profile;
  2897. })
  2898. ->take(6)
  2899. ->values();
  2900. return $this->json($ids);
  2901. }
  2902. /**
  2903. * GET /api/v1/preferences
  2904. *
  2905. *
  2906. * @return array
  2907. */
  2908. public function getPreferences(Request $request)
  2909. {
  2910. abort_if(!$request->user(), 403);
  2911. $pid = $request->user()->profile_id;
  2912. $account = AccountService::get($pid);
  2913. return $this->json([
  2914. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  2915. 'posting:default:sensitive' => false,
  2916. 'posting:default:language' => null,
  2917. 'reading:expand:media' => 'default',
  2918. 'reading:expand:spoilers' => false
  2919. ]);
  2920. }
  2921. /**
  2922. * GET /api/v1/trends
  2923. *
  2924. *
  2925. * @return array
  2926. */
  2927. public function getTrends(Request $request)
  2928. {
  2929. abort_if(!$request->user(), 403);
  2930. return $this->json([]);
  2931. }
  2932. /**
  2933. * GET /api/v1/announcements
  2934. *
  2935. *
  2936. * @return array
  2937. */
  2938. public function getAnnouncements(Request $request)
  2939. {
  2940. abort_if(!$request->user(), 403);
  2941. return $this->json([]);
  2942. }
  2943. /**
  2944. * GET /api/v1/markers
  2945. *
  2946. *
  2947. * @return array
  2948. */
  2949. public function getMarkers(Request $request)
  2950. {
  2951. abort_if(!$request->user(), 403);
  2952. $type = $request->input('timeline');
  2953. if(is_array($type)) {
  2954. $type = $type[0];
  2955. }
  2956. if(!$type || !in_array($type, ['home', 'notifications'])) {
  2957. return $this->json([]);
  2958. }
  2959. $pid = $request->user()->profile_id;
  2960. return $this->json(MarkerService::get($pid, $type));
  2961. }
  2962. /**
  2963. * POST /api/v1/markers
  2964. *
  2965. *
  2966. * @return array
  2967. */
  2968. public function setMarkers(Request $request)
  2969. {
  2970. abort_if(!$request->user(), 403);
  2971. $pid = $request->user()->profile_id;
  2972. $home = $request->input('home.last_read_id');
  2973. $notifications = $request->input('notifications.last_read_id');
  2974. if($home) {
  2975. return $this->json(MarkerService::set($pid, 'home', $home));
  2976. }
  2977. if($notifications) {
  2978. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  2979. }
  2980. return $this->json([]);
  2981. }
  2982. }