ApiV1Controller.php 94 KB

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