ApiV1Controller.php 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869
  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. HashtagFollow,
  21. Instance,
  22. Like,
  23. Media,
  24. Notification,
  25. Profile,
  26. Status,
  27. StatusHashtag,
  28. User,
  29. UserSetting,
  30. UserFilter,
  31. };
  32. use League\Fractal;
  33. use App\Transformer\Api\Mastodon\v1\{
  34. AccountTransformer,
  35. MediaTransformer,
  36. NotificationTransformer,
  37. StatusTransformer,
  38. };
  39. use App\Transformer\Api\{
  40. RelationshipTransformer,
  41. };
  42. use App\Http\Controllers\FollowerController;
  43. use League\Fractal\Serializer\ArraySerializer;
  44. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  45. use App\Http\Controllers\AccountController;
  46. use App\Http\Controllers\StatusController;
  47. use App\Jobs\AvatarPipeline\AvatarOptimize;
  48. use App\Jobs\CommentPipeline\CommentPipeline;
  49. use App\Jobs\LikePipeline\LikePipeline;
  50. use App\Jobs\MediaPipeline\MediaDeletePipeline;
  51. use App\Jobs\SharePipeline\SharePipeline;
  52. use App\Jobs\SharePipeline\UndoSharePipeline;
  53. use App\Jobs\StatusPipeline\NewStatusPipeline;
  54. use App\Jobs\StatusPipeline\StatusDelete;
  55. use App\Jobs\FollowPipeline\FollowPipeline;
  56. use App\Jobs\FollowPipeline\UnfollowPipeline;
  57. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  58. use App\Jobs\VideoPipeline\{
  59. VideoOptimize,
  60. VideoPostProcess,
  61. VideoThumbnail
  62. };
  63. use App\Services\{
  64. AccountService,
  65. BookmarkService,
  66. BouncerService,
  67. CollectionService,
  68. FollowerService,
  69. HashtagService,
  70. HomeTimelineService,
  71. InstanceService,
  72. LikeService,
  73. NetworkTimelineService,
  74. NotificationService,
  75. MediaService,
  76. MediaPathService,
  77. ProfileStatusService,
  78. PublicTimelineService,
  79. ReblogService,
  80. RelationshipService,
  81. SearchApiV2Service,
  82. StatusService,
  83. MediaBlocklistService,
  84. SnowflakeService,
  85. UserFilterService
  86. };
  87. use App\Util\Lexer\Autolink;
  88. use App\Util\Lexer\PrettyNumber;
  89. use App\Util\Localization\Localization;
  90. use App\Util\Media\License;
  91. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  92. use App\Services\DiscoverService;
  93. use App\Services\CustomEmojiService;
  94. use App\Services\MarkerService;
  95. use App\Models\Conversation;
  96. use App\Jobs\FollowPipeline\FollowAcceptPipeline;
  97. use App\Jobs\FollowPipeline\FollowRejectPipeline;
  98. use Illuminate\Support\Facades\RateLimiter;
  99. use Purify;
  100. use Carbon\Carbon;
  101. use App\Http\Resources\MastoApi\FollowedTagResource;
  102. use App\Jobs\HomeFeedPipeline\FeedWarmCachePipeline;
  103. class ApiV1Controller extends Controller
  104. {
  105. protected $fractal;
  106. const PF_API_ENTITY_KEY = "_pe";
  107. public function __construct()
  108. {
  109. $this->fractal = new Fractal\Manager();
  110. $this->fractal->setSerializer(new ArraySerializer());
  111. }
  112. public function json($res, $code = 200, $headers = [])
  113. {
  114. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  115. }
  116. public function getApp(Request $request)
  117. {
  118. if(!$request->user()) {
  119. return response('', 403);
  120. }
  121. $client = $request->user()->token()->client;
  122. $res = [
  123. 'name' => $client->name,
  124. 'website' => null,
  125. 'vapid_key' => null
  126. ];
  127. return $this->json($res);
  128. }
  129. public function apps(Request $request)
  130. {
  131. abort_if(!config_cache('pixelfed.oauth_enabled'), 404);
  132. $this->validate($request, [
  133. 'client_name' => 'required',
  134. 'redirect_uris' => 'required'
  135. ]);
  136. $uris = implode(',', explode('\n', $request->redirect_uris));
  137. $client = Passport::client()->forceFill([
  138. 'user_id' => null,
  139. 'name' => e($request->client_name),
  140. 'secret' => Str::random(40),
  141. 'redirect' => $uris,
  142. 'personal_access_client' => false,
  143. 'password_client' => false,
  144. 'revoked' => false,
  145. ]);
  146. $client->save();
  147. $res = [
  148. 'id' => (string) $client->id,
  149. 'name' => $client->name,
  150. 'website' => null,
  151. 'redirect_uri' => $client->redirect,
  152. 'client_id' => (string) $client->id,
  153. 'client_secret' => $client->secret,
  154. 'vapid_key' => null
  155. ];
  156. return $this->json($res, 200, [
  157. 'Access-Control-Allow-Origin' => '*'
  158. ]);
  159. }
  160. /**
  161. * GET /api/v1/accounts/verify_credentials
  162. *
  163. *
  164. * @return \App\Transformer\Api\AccountTransformer
  165. */
  166. public function verifyCredentials(Request $request)
  167. {
  168. $user = $request->user();
  169. abort_if(!$user, 403);
  170. abort_if($user->status != null, 403);
  171. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($user->profile_id) : AccountService::getMastodon($user->profile_id);
  172. $res['source'] = [
  173. 'privacy' => $res['locked'] ? 'private' : 'public',
  174. 'sensitive' => false,
  175. 'language' => $user->language ?? 'en',
  176. 'note' => strip_tags($res['note']),
  177. 'fields' => []
  178. ];
  179. return $this->json($res);
  180. }
  181. /**
  182. * GET /api/v1/accounts/{id}
  183. *
  184. * @param integer $id
  185. *
  186. * @return \App\Transformer\Api\AccountTransformer
  187. */
  188. public function accountById(Request $request, $id)
  189. {
  190. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  191. if(!$res) {
  192. return response()->json(['error' => 'Record not found'], 404);
  193. }
  194. return $this->json($res);
  195. }
  196. /**
  197. * PATCH /api/v1/accounts/update_credentials
  198. *
  199. * @return \App\Transformer\Api\AccountTransformer
  200. */
  201. public function accountUpdateCredentials(Request $request)
  202. {
  203. abort_if(!$request->user(), 403);
  204. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  205. abort_if(BouncerService::checkIp($request->ip()), 404);
  206. }
  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')->storePubliclyAs($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. $napi = $request->has(self::PF_API_ENTITY_KEY);
  794. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  795. $res = collect($request->input('id'))
  796. ->filter(function($id) use($pid) {
  797. return intval($id) !== intval($pid);
  798. })
  799. ->map(function($id) use($pid, $napi) {
  800. return $napi ?
  801. RelationshipService::getWithDate($pid, $id) :
  802. RelationshipService::get($pid, $id);
  803. });
  804. return $this->json($res);
  805. }
  806. /**
  807. * GET /api/v1/accounts/search
  808. *
  809. *
  810. *
  811. * @return \App\Transformer\Api\AccountTransformer
  812. */
  813. public function accountSearch(Request $request)
  814. {
  815. abort_if(!$request->user(), 403);
  816. $this->validate($request, [
  817. 'q' => 'required|string|min:1|max:255',
  818. 'limit' => 'nullable|integer|min:1|max:40',
  819. 'resolve' => 'nullable'
  820. ]);
  821. $user = $request->user();
  822. $query = $request->input('q');
  823. $limit = $request->input('limit') ?? 20;
  824. $resolve = (bool) $request->input('resolve', false);
  825. $q = '%' . $query . '%';
  826. $profiles = Cache::remember('api:v1:accounts:search:' . sha1($query) . ':limit:' . $limit, 86400, function() use($q, $limit) {
  827. return Profile::whereNull('status')
  828. ->where('username', 'like', $q)
  829. ->orWhere('name', 'like', $q)
  830. ->limit($limit)
  831. ->pluck('id')
  832. ->map(function($id) {
  833. return AccountService::getMastodon($id);
  834. })
  835. ->filter(function($account) {
  836. return $account && isset($account['id']);
  837. });
  838. });
  839. return $this->json($profiles);
  840. }
  841. /**
  842. * GET /api/v1/blocks
  843. *
  844. *
  845. *
  846. * @return \App\Transformer\Api\AccountTransformer
  847. */
  848. public function accountBlocks(Request $request)
  849. {
  850. abort_if(!$request->user(), 403);
  851. $this->validate($request, [
  852. 'limit' => 'nullable|integer|min:1|max:40',
  853. 'page' => 'nullable|integer|min:1|max:10'
  854. ]);
  855. $user = $request->user();
  856. $limit = $request->input('limit') ?? 40;
  857. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  858. ->whereUserId($user->profile_id)
  859. ->whereFilterableType('App\Profile')
  860. ->whereFilterType('block')
  861. ->orderByDesc('id')
  862. ->simplePaginate($limit)
  863. ->pluck('filterable_id')
  864. ->map(function($id) {
  865. return AccountService::get($id, true);
  866. })
  867. ->filter(function($account) {
  868. return $account && isset($account['id']);
  869. })
  870. ->values();
  871. return $this->json($blocked);
  872. }
  873. /**
  874. * POST /api/v1/accounts/{id}/block
  875. *
  876. * @param integer $id
  877. *
  878. * @return \App\Transformer\Api\RelationshipTransformer
  879. */
  880. public function accountBlockById(Request $request, $id)
  881. {
  882. abort_if(!$request->user(), 403);
  883. $user = $request->user();
  884. $pid = $user->profile_id ?? $user->profile->id;
  885. if(intval($id) === intval($pid)) {
  886. abort(400, 'You cannot block yourself');
  887. }
  888. $profile = Profile::findOrFail($id);
  889. if($profile->user && $profile->user->is_admin == true) {
  890. abort(400, 'You cannot block an admin');
  891. }
  892. $count = UserFilterService::blockCount($pid);
  893. $maxLimit = intval(config('instance.user_filters.max_user_blocks'));
  894. if($count == 0) {
  895. $filterCount = UserFilter::whereUserId($pid)
  896. ->whereFilterType('block')
  897. ->get()
  898. ->map(function($rec) {
  899. return AccountService::get($rec->filterable_id, true);
  900. })
  901. ->filter(function($account) {
  902. return $account && isset($account['id']);
  903. })
  904. ->values()
  905. ->count();
  906. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT . $maxLimit . ' accounts');
  907. } else {
  908. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT . $maxLimit . ' accounts');
  909. }
  910. $followed = Follower::whereProfileId($profile->id)->whereFollowingId($pid)->first();
  911. if($followed) {
  912. $followed->delete();
  913. $profile->following_count = Follower::whereProfileId($profile->id)->count();
  914. $profile->save();
  915. $selfProfile = $user->profile;
  916. $selfProfile->followers_count = Follower::whereFollowingId($pid)->count();
  917. $selfProfile->save();
  918. FollowerService::remove($profile->id, $pid);
  919. AccountService::del($pid);
  920. AccountService::del($profile->id);
  921. }
  922. $following = Follower::whereProfileId($pid)->whereFollowingId($profile->id)->first();
  923. if($following) {
  924. $following->delete();
  925. $profile->followers_count = Follower::whereFollowingId($profile->id)->count();
  926. $profile->save();
  927. $selfProfile = $user->profile;
  928. $selfProfile->following_count = Follower::whereProfileId($pid)->count();
  929. $selfProfile->save();
  930. FollowerService::remove($pid, $profile->pid);
  931. AccountService::del($pid);
  932. AccountService::del($profile->id);
  933. }
  934. Notification::whereProfileId($pid)
  935. ->whereActorId($profile->id)
  936. ->get()
  937. ->map(function($n) use($pid) {
  938. NotificationService::del($pid, $n['id']);
  939. $n->forceDelete();
  940. });
  941. $filter = UserFilter::firstOrCreate([
  942. 'user_id' => $pid,
  943. 'filterable_id' => $profile->id,
  944. 'filterable_type' => 'App\Profile',
  945. 'filter_type' => 'block',
  946. ]);
  947. UserFilterService::block($pid, $id);
  948. RelationshipService::refresh($pid, $id);
  949. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  950. $res = $this->fractal->createData($resource)->toArray();
  951. return $this->json($res);
  952. }
  953. /**
  954. * POST /api/v1/accounts/{id}/unblock
  955. *
  956. * @param integer $id
  957. *
  958. * @return \App\Transformer\Api\RelationshipTransformer
  959. */
  960. public function accountUnblockById(Request $request, $id)
  961. {
  962. abort_if(!$request->user(), 403);
  963. $user = $request->user();
  964. $pid = $user->profile_id ?? $user->profile->id;
  965. if(intval($id) === intval($pid)) {
  966. abort(400, 'You cannot unblock yourself');
  967. }
  968. $profile = Profile::findOrFail($id);
  969. $filter = UserFilter::whereUserId($pid)
  970. ->whereFilterableId($profile->id)
  971. ->whereFilterableType('App\Profile')
  972. ->whereFilterType('block')
  973. ->first();
  974. if($filter) {
  975. $filter->delete();
  976. UserFilterService::unblock($pid, $profile->id);
  977. RelationshipService::refresh($pid, $id);
  978. }
  979. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  980. $res = $this->fractal->createData($resource)->toArray();
  981. return $this->json($res);
  982. }
  983. /**
  984. * GET /api/v1/custom_emojis
  985. *
  986. * Return custom emoji
  987. *
  988. * @return array
  989. */
  990. public function customEmojis()
  991. {
  992. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  993. }
  994. /**
  995. * GET /api/v1/domain_blocks
  996. *
  997. * Return empty array
  998. *
  999. * @return array
  1000. */
  1001. public function accountDomainBlocks(Request $request)
  1002. {
  1003. abort_if(!$request->user(), 403);
  1004. return response()->json([]);
  1005. }
  1006. /**
  1007. * GET /api/v1/endorsements
  1008. *
  1009. * Return empty array
  1010. *
  1011. * @return array
  1012. */
  1013. public function accountEndorsements(Request $request)
  1014. {
  1015. abort_if(!$request->user(), 403);
  1016. return response()->json([]);
  1017. }
  1018. /**
  1019. * GET /api/v1/favourites
  1020. *
  1021. * Returns collection of liked statuses
  1022. *
  1023. * @return \App\Transformer\Api\StatusTransformer
  1024. */
  1025. public function accountFavourites(Request $request)
  1026. {
  1027. abort_if(!$request->user(), 403);
  1028. $this->validate($request, [
  1029. 'limit' => 'sometimes|integer|min:1|max:20'
  1030. ]);
  1031. $user = $request->user();
  1032. $maxId = $request->input('max_id');
  1033. $minId = $request->input('min_id');
  1034. $limit = $request->input('limit') ?? 10;
  1035. $res = Like::whereProfileId($user->profile_id)
  1036. ->when($maxId, function($q, $maxId) {
  1037. return $q->where('id', '<', $maxId);
  1038. })
  1039. ->when($minId, function($q, $minId) {
  1040. return $q->where('id', '>', $minId);
  1041. })
  1042. ->orderByDesc('id')
  1043. ->limit($limit)
  1044. ->get()
  1045. ->map(function($like) {
  1046. $status = StatusService::getMastodon($like['status_id'], false);
  1047. $status['favourited'] = true;
  1048. $status['like_id'] = $like->id;
  1049. $status['liked_at'] = str_replace('+00:00', 'Z', $like->created_at->format(DATE_RFC3339_EXTENDED));
  1050. return $status;
  1051. })
  1052. ->filter(function($status) {
  1053. return $status && isset($status['id'], $status['like_id']);
  1054. })
  1055. ->values();
  1056. if($res->count()) {
  1057. $ids = $res->map(function($status) {
  1058. return $status['like_id'];
  1059. });
  1060. $max = $ids->max();
  1061. $min = $ids->min();
  1062. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  1063. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  1064. return $this->json($res, 200, ['Link' => $link]);
  1065. } else {
  1066. return $this->json($res);
  1067. }
  1068. }
  1069. /**
  1070. * POST /api/v1/statuses/{id}/favourite
  1071. *
  1072. * @param integer $id
  1073. *
  1074. * @return \App\Transformer\Api\StatusTransformer
  1075. */
  1076. public function statusFavouriteById(Request $request, $id)
  1077. {
  1078. abort_if(!$request->user(), 403);
  1079. $user = $request->user();
  1080. $status = StatusService::getMastodon($id, false);
  1081. abort_unless($status, 400);
  1082. $spid = $status['account']['id'];
  1083. if(intval($spid) !== intval($user->profile_id)) {
  1084. if($status['visibility'] == 'private') {
  1085. abort_if(!FollowerService::follows($user->profile_id, $spid), 403);
  1086. } else {
  1087. abort_if(!in_array($status['visibility'], ['public','unlisted']), 403);
  1088. }
  1089. }
  1090. abort_if(
  1091. Like::whereProfileId($user->profile_id)
  1092. ->where('created_at', '>', now()->subDay())
  1093. ->count() >= Like::MAX_PER_DAY,
  1094. 429
  1095. );
  1096. $blocks = UserFilterService::blocks($spid);
  1097. if($blocks && in_array($user->profile_id, $blocks)) {
  1098. abort(422);
  1099. }
  1100. $like = Like::firstOrCreate([
  1101. 'profile_id' => $user->profile_id,
  1102. 'status_id' => $status['id']
  1103. ]);
  1104. if($like->wasRecentlyCreated == true) {
  1105. $like->status_profile_id = $spid;
  1106. $like->is_comment = !empty($status['in_reply_to_id']);
  1107. $like->save();
  1108. Status::findOrFail($status['id'])->update([
  1109. 'likes_count' => ($status['favourites_count'] ?? 0) + 1
  1110. ]);
  1111. LikePipeline::dispatch($like)->onQueue('feed');
  1112. }
  1113. $status['favourited'] = true;
  1114. $status['favourites_count'] = $status['favourites_count'] + 1;
  1115. return $this->json($status);
  1116. }
  1117. /**
  1118. * POST /api/v1/statuses/{id}/unfavourite
  1119. *
  1120. * @param integer $id
  1121. *
  1122. * @return \App\Transformer\Api\StatusTransformer
  1123. */
  1124. public function statusUnfavouriteById(Request $request, $id)
  1125. {
  1126. abort_if(!$request->user(), 403);
  1127. $user = $request->user();
  1128. $status = Status::findOrFail($id);
  1129. if(intval($status->profile_id) !== intval($user->profile_id)) {
  1130. if($status->scope == 'private') {
  1131. abort_if(!$status->profile->followedBy($user->profile), 403);
  1132. } else {
  1133. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1134. }
  1135. }
  1136. $like = Like::whereProfileId($user->profile_id)
  1137. ->whereStatusId($status->id)
  1138. ->first();
  1139. if($like) {
  1140. $like->forceDelete();
  1141. $status->likes_count = $status->likes_count > 1 ? $status->likes_count - 1 : 0;
  1142. $status->save();
  1143. }
  1144. StatusService::del($status->id);
  1145. $res = StatusService::getMastodon($status->id, false);
  1146. $res['favourited'] = false;
  1147. return $this->json($res);
  1148. }
  1149. /**
  1150. * GET /api/v1/filters
  1151. *
  1152. * Return empty response since we filter server side
  1153. *
  1154. * @return array
  1155. */
  1156. public function accountFilters(Request $request)
  1157. {
  1158. abort_if(!$request->user(), 403);
  1159. return response()->json([]);
  1160. }
  1161. /**
  1162. * GET /api/v1/follow_requests
  1163. *
  1164. * Return array of Accounts that have sent follow requests
  1165. *
  1166. * @return \App\Transformer\Api\AccountTransformer
  1167. */
  1168. public function accountFollowRequests(Request $request)
  1169. {
  1170. abort_if(!$request->user(), 403);
  1171. $this->validate($request, [
  1172. 'limit' => 'sometimes|integer|min:1|max:100'
  1173. ]);
  1174. $user = $request->user();
  1175. $res = FollowRequest::whereFollowingId($user->profile->id)
  1176. ->limit($request->input('limit', 40))
  1177. ->pluck('follower_id')
  1178. ->map(function($id) {
  1179. return AccountService::getMastodon($id, true);
  1180. })
  1181. ->filter(function($acct) {
  1182. return $acct && isset($acct['id']);
  1183. })
  1184. ->values();
  1185. return $this->json($res);
  1186. }
  1187. /**
  1188. * POST /api/v1/follow_requests/{id}/authorize
  1189. *
  1190. * @param integer $id
  1191. *
  1192. * @return null
  1193. */
  1194. public function accountFollowRequestAccept(Request $request, $id)
  1195. {
  1196. abort_if(!$request->user(), 403);
  1197. $pid = $request->user()->profile_id;
  1198. $target = AccountService::getMastodon($id);
  1199. if(!$target) {
  1200. return response()->json(['error' => 'Record not found'], 404);
  1201. }
  1202. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1203. if(!$followRequest) {
  1204. return response()->json(['error' => 'Record not found'], 404);
  1205. }
  1206. $follower = $followRequest->follower;
  1207. $follow = new Follower();
  1208. $follow->profile_id = $follower->id;
  1209. $follow->following_id = $pid;
  1210. $follow->save();
  1211. $profile = Profile::findOrFail($pid);
  1212. $profile->followers_count++;
  1213. $profile->save();
  1214. AccountService::del($profile->id);
  1215. $profile = Profile::findOrFail($follower->id);
  1216. $profile->following_count++;
  1217. $profile->save();
  1218. AccountService::del($profile->id);
  1219. if($follower->domain != null && $follower->private_key === null) {
  1220. FollowAcceptPipeline::dispatch($followRequest)->onQueue('follow');
  1221. } else {
  1222. FollowPipeline::dispatch($follow);
  1223. $followRequest->delete();
  1224. }
  1225. RelationshipService::refresh($pid, $id);
  1226. $res = RelationshipService::get($pid, $id);
  1227. $res['followed_by'] = true;
  1228. return $this->json($res);
  1229. }
  1230. /**
  1231. * POST /api/v1/follow_requests/{id}/reject
  1232. *
  1233. * @param integer $id
  1234. *
  1235. * @return null
  1236. */
  1237. public function accountFollowRequestReject(Request $request, $id)
  1238. {
  1239. abort_if(!$request->user(), 403);
  1240. $pid = $request->user()->profile_id;
  1241. $target = AccountService::getMastodon($id);
  1242. if(!$target) {
  1243. return response()->json(['error' => 'Record not found'], 404);
  1244. }
  1245. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1246. if(!$followRequest) {
  1247. return response()->json(['error' => 'Record not found'], 404);
  1248. }
  1249. $follower = $followRequest->follower;
  1250. if($follower->domain != null && $follower->private_key === null) {
  1251. FollowRejectPipeline::dispatch($followRequest)->onQueue('follow');
  1252. } else {
  1253. $followRequest->delete();
  1254. }
  1255. RelationshipService::refresh($pid, $id);
  1256. $res = RelationshipService::get($pid, $id);
  1257. return $this->json($res);
  1258. }
  1259. /**
  1260. * GET /api/v1/suggestions
  1261. *
  1262. * Return empty array as we don't support suggestions
  1263. *
  1264. * @return null
  1265. */
  1266. public function accountSuggestions(Request $request)
  1267. {
  1268. abort_if(!$request->user(), 403);
  1269. // todo
  1270. return response()->json([]);
  1271. }
  1272. /**
  1273. * GET /api/v1/instance
  1274. *
  1275. * Information about the server.
  1276. *
  1277. * @return Instance
  1278. */
  1279. public function instance(Request $request)
  1280. {
  1281. $res = Cache::remember('api:v1:instance-data-response-v1', 1800, function () {
  1282. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1283. if(config_cache('instance.admin.pid')) {
  1284. return AccountService::getMastodon(config_cache('instance.admin.pid'), true);
  1285. }
  1286. $admin = User::whereIsAdmin(true)->first();
  1287. return $admin && isset($admin->profile_id) ?
  1288. AccountService::getMastodon($admin->profile_id, true) :
  1289. null;
  1290. });
  1291. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1292. return [
  1293. 'user_count' => User::count(),
  1294. 'status_count' => Status::whereNull('uri')->count(),
  1295. 'domain_count' => Instance::count(),
  1296. ];
  1297. });
  1298. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1299. return config_cache('app.rules') ?
  1300. collect(json_decode(config_cache('app.rules'), true))
  1301. ->map(function($rule, $key) {
  1302. $id = $key + 1;
  1303. return [
  1304. 'id' => "{$id}",
  1305. 'text' => $rule
  1306. ];
  1307. })
  1308. ->toArray() : [];
  1309. });
  1310. return [
  1311. 'uri' => config('pixelfed.domain.app'),
  1312. 'title' => config('app.name'),
  1313. 'short_description' => config_cache('app.short_description'),
  1314. 'description' => config_cache('app.description'),
  1315. 'email' => config('instance.email'),
  1316. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1317. 'urls' => [
  1318. 'streaming_api' => 'wss://' . config('pixelfed.domain.app')
  1319. ],
  1320. 'stats' => $stats,
  1321. 'thumbnail' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  1322. 'languages' => [config('app.locale')],
  1323. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1324. 'approval_required' => false,
  1325. 'contact_account' => $contact,
  1326. 'rules' => $rules,
  1327. 'configuration' => [
  1328. 'media_attachments' => [
  1329. 'image_matrix_limit' => 16777216,
  1330. 'image_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1331. 'supported_mime_types' => explode(',', config('pixelfed.media_types')),
  1332. 'video_frame_rate_limit' => 120,
  1333. 'video_matrix_limit' => 2304000,
  1334. 'video_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1335. ],
  1336. 'polls' => [
  1337. 'max_characters_per_option' => 50,
  1338. 'max_expiration' => 2629746,
  1339. 'max_options' => 4,
  1340. 'min_expiration' => 300
  1341. ],
  1342. 'statuses' => [
  1343. 'characters_reserved_per_url' => 23,
  1344. 'max_characters' => (int) config('pixelfed.max_caption_length'),
  1345. 'max_media_attachments' => (int) config('pixelfed.max_album_length')
  1346. ]
  1347. ]
  1348. ];
  1349. });
  1350. return $this->json($res);
  1351. }
  1352. /**
  1353. * GET /api/v1/lists
  1354. *
  1355. * Return empty array as we don't support lists
  1356. *
  1357. * @return null
  1358. */
  1359. public function accountLists(Request $request)
  1360. {
  1361. abort_if(!$request->user(), 403);
  1362. return response()->json([]);
  1363. }
  1364. /**
  1365. * GET /api/v1/accounts/{id}/lists
  1366. *
  1367. * @param integer $id
  1368. *
  1369. * @return null
  1370. */
  1371. public function accountListsById(Request $request, $id)
  1372. {
  1373. abort_if(!$request->user(), 403);
  1374. return response()->json([]);
  1375. }
  1376. /**
  1377. * POST /api/v1/media
  1378. *
  1379. *
  1380. * @return MediaTransformer
  1381. */
  1382. public function mediaUpload(Request $request)
  1383. {
  1384. abort_if(!$request->user(), 403);
  1385. $this->validate($request, [
  1386. 'file.*' => [
  1387. 'required_without:file',
  1388. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1389. 'max:' . config_cache('pixelfed.max_photo_size'),
  1390. ],
  1391. 'file' => [
  1392. 'required_without:file.*',
  1393. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1394. 'max:' . config_cache('pixelfed.max_photo_size'),
  1395. ],
  1396. 'filter_name' => 'nullable|string|max:24',
  1397. 'filter_class' => 'nullable|alpha_dash|max:24',
  1398. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1399. ]);
  1400. $user = $request->user();
  1401. if($user->last_active_at == null) {
  1402. return [];
  1403. }
  1404. if(empty($request->file('file'))) {
  1405. return response('', 422);
  1406. }
  1407. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1408. $limitTtl = now()->addMinutes(15);
  1409. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1410. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1411. return $dailyLimit >= 1250;
  1412. });
  1413. abort_if($limitReached == true, 429);
  1414. $profile = $user->profile;
  1415. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1416. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1417. return Media::whereUserId($user->id)->sum('size') / 1000;
  1418. });
  1419. $limit = (int) config_cache('pixelfed.max_account_size');
  1420. if ($size >= $limit) {
  1421. abort(403, 'Account size limit reached.');
  1422. }
  1423. }
  1424. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1425. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1426. $photo = $request->file('file');
  1427. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1428. if(in_array($photo->getMimeType(), $mimes) == false) {
  1429. abort(403, 'Invalid or unsupported mime type.');
  1430. }
  1431. $storagePath = MediaPathService::get($user, 2);
  1432. $path = $photo->storePublicly($storagePath);
  1433. $hash = \hash_file('sha256', $photo);
  1434. $license = null;
  1435. $mime = $photo->getMimeType();
  1436. // if($photo->getMimeType() == 'image/heic') {
  1437. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1438. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1439. // $oldPath = $path;
  1440. // $path = str_replace('.heic', '.jpg', $path);
  1441. // $mime = 'image/jpeg';
  1442. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1443. // @unlink(storage_path("app/{$oldPath}"));
  1444. // }
  1445. $settings = UserSetting::whereUserId($user->id)->first();
  1446. if($settings && !empty($settings->compose_settings)) {
  1447. $compose = $settings->compose_settings;
  1448. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1449. $license = $compose['default_license'];
  1450. }
  1451. }
  1452. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1453. $media = new Media();
  1454. $media->status_id = null;
  1455. $media->profile_id = $profile->id;
  1456. $media->user_id = $user->id;
  1457. $media->media_path = $path;
  1458. $media->original_sha256 = $hash;
  1459. $media->size = $photo->getSize();
  1460. $media->mime = $mime;
  1461. $media->caption = $request->input('description');
  1462. $media->filter_class = $filterClass;
  1463. $media->filter_name = $filterName;
  1464. if($license) {
  1465. $media->license = $license;
  1466. }
  1467. $media->save();
  1468. switch ($media->mime) {
  1469. case 'image/jpeg':
  1470. case 'image/png':
  1471. ImageOptimize::dispatch($media)->onQueue('mmo');
  1472. break;
  1473. case 'video/mp4':
  1474. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1475. $preview_url = '/storage/no-preview.png';
  1476. $url = '/storage/no-preview.png';
  1477. break;
  1478. }
  1479. Cache::forget($limitKey);
  1480. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1481. $res = $this->fractal->createData($resource)->toArray();
  1482. $res['preview_url'] = $media->url(). '?v=' . time();
  1483. $res['url'] = $media->url(). '?v=' . time();
  1484. return $this->json($res);
  1485. }
  1486. /**
  1487. * PUT /api/v1/media/{id}
  1488. *
  1489. * @param integer $id
  1490. *
  1491. * @return MediaTransformer
  1492. */
  1493. public function mediaUpdate(Request $request, $id)
  1494. {
  1495. abort_if(!$request->user(), 403);
  1496. $this->validate($request, [
  1497. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1498. ]);
  1499. $user = $request->user();
  1500. $media = Media::whereUserId($user->id)
  1501. ->whereProfileId($user->profile_id)
  1502. ->findOrFail($id);
  1503. $executed = RateLimiter::attempt(
  1504. 'media:update:'.$user->id,
  1505. 10,
  1506. function() use($media, $request) {
  1507. $caption = Purify::clean($request->input('description'));
  1508. if($caption != $media->caption) {
  1509. $media->caption = $caption;
  1510. $media->save();
  1511. if($media->status_id) {
  1512. MediaService::del($media->status_id);
  1513. StatusService::del($media->status_id);
  1514. }
  1515. }
  1516. });
  1517. if(!$executed) {
  1518. return response()->json([
  1519. 'error' => 'Too many attempts. Try again in a few minutes.'
  1520. ], 429);
  1521. };
  1522. $fractal = new Fractal\Manager();
  1523. $fractal->setSerializer(new ArraySerializer());
  1524. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1525. return $this->json($fractal->createData($resource)->toArray());
  1526. }
  1527. /**
  1528. * GET /api/v1/media/{id}
  1529. *
  1530. * @param integer $id
  1531. *
  1532. * @return MediaTransformer
  1533. */
  1534. public function mediaGet(Request $request, $id)
  1535. {
  1536. abort_if(!$request->user(), 403);
  1537. $user = $request->user();
  1538. $media = Media::whereUserId($user->id)
  1539. ->whereNull('status_id')
  1540. ->findOrFail($id);
  1541. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1542. $res = $this->fractal->createData($resource)->toArray();
  1543. return $this->json($res);
  1544. }
  1545. /**
  1546. * POST /api/v2/media
  1547. *
  1548. *
  1549. * @return MediaTransformer
  1550. */
  1551. public function mediaUploadV2(Request $request)
  1552. {
  1553. abort_if(!$request->user(), 403);
  1554. $this->validate($request, [
  1555. 'file.*' => [
  1556. 'required_without:file',
  1557. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1558. 'max:' . config_cache('pixelfed.max_photo_size'),
  1559. ],
  1560. 'file' => [
  1561. 'required_without:file.*',
  1562. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1563. 'max:' . config_cache('pixelfed.max_photo_size'),
  1564. ],
  1565. 'filter_name' => 'nullable|string|max:24',
  1566. 'filter_class' => 'nullable|alpha_dash|max:24',
  1567. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length'),
  1568. 'replace_id' => 'sometimes'
  1569. ]);
  1570. $user = $request->user();
  1571. if($user->last_active_at == null) {
  1572. return [];
  1573. }
  1574. if(empty($request->file('file'))) {
  1575. return response('', 422);
  1576. }
  1577. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1578. $limitTtl = now()->addMinutes(15);
  1579. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1580. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1581. return $dailyLimit >= 1250;
  1582. });
  1583. abort_if($limitReached == true, 429);
  1584. $profile = $user->profile;
  1585. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1586. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1587. return Media::whereUserId($user->id)->sum('size') / 1000;
  1588. });
  1589. $limit = (int) config_cache('pixelfed.max_account_size');
  1590. if ($size >= $limit) {
  1591. abort(403, 'Account size limit reached.');
  1592. }
  1593. }
  1594. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1595. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1596. $photo = $request->file('file');
  1597. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1598. if(in_array($photo->getMimeType(), $mimes) == false) {
  1599. abort(403, 'Invalid or unsupported mime type.');
  1600. }
  1601. $storagePath = MediaPathService::get($user, 2);
  1602. $path = $photo->storePublicly($storagePath);
  1603. $hash = \hash_file('sha256', $photo);
  1604. $license = null;
  1605. $mime = $photo->getMimeType();
  1606. $settings = UserSetting::whereUserId($user->id)->first();
  1607. if($settings && !empty($settings->compose_settings)) {
  1608. $compose = $settings->compose_settings;
  1609. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1610. $license = $compose['default_license'];
  1611. }
  1612. }
  1613. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1614. if($request->has('replace_id')) {
  1615. $rpid = $request->input('replace_id');
  1616. $removeMedia = Media::whereNull('status_id')
  1617. ->whereUserId($user->id)
  1618. ->whereProfileId($profile->id)
  1619. ->where('created_at', '>', now()->subHours(2))
  1620. ->find($rpid);
  1621. if($removeMedia) {
  1622. $dateTime = Carbon::now();
  1623. MediaDeletePipeline::dispatch($removeMedia)
  1624. ->onQueue('mmo')
  1625. ->delay($dateTime->addMinutes(15));
  1626. }
  1627. }
  1628. $media = new Media();
  1629. $media->status_id = null;
  1630. $media->profile_id = $profile->id;
  1631. $media->user_id = $user->id;
  1632. $media->media_path = $path;
  1633. $media->original_sha256 = $hash;
  1634. $media->size = $photo->getSize();
  1635. $media->mime = $mime;
  1636. $media->caption = $request->input('description');
  1637. $media->filter_class = $filterClass;
  1638. $media->filter_name = $filterName;
  1639. if($license) {
  1640. $media->license = $license;
  1641. }
  1642. $media->save();
  1643. switch ($media->mime) {
  1644. case 'image/jpeg':
  1645. case 'image/png':
  1646. ImageOptimize::dispatch($media)->onQueue('mmo');
  1647. break;
  1648. case 'video/mp4':
  1649. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1650. $preview_url = '/storage/no-preview.png';
  1651. $url = '/storage/no-preview.png';
  1652. break;
  1653. }
  1654. Cache::forget($limitKey);
  1655. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1656. $res = $this->fractal->createData($resource)->toArray();
  1657. $res['preview_url'] = $media->url(). '?v=' . time();
  1658. $res['url'] = null;
  1659. return $this->json($res, 202);
  1660. }
  1661. /**
  1662. * GET /api/v1/mutes
  1663. *
  1664. *
  1665. * @return AccountTransformer
  1666. */
  1667. public function accountMutes(Request $request)
  1668. {
  1669. abort_if(!$request->user(), 403);
  1670. $this->validate($request, [
  1671. 'limit' => 'nullable|integer|min:1|max:40'
  1672. ]);
  1673. $user = $request->user();
  1674. $limit = $request->input('limit', 40);
  1675. $mutes = UserFilter::whereUserId($user->profile_id)
  1676. ->whereFilterableType('App\Profile')
  1677. ->whereFilterType('mute')
  1678. ->orderByDesc('id')
  1679. ->simplePaginate($limit)
  1680. ->pluck('filterable_id')
  1681. ->map(function($id) {
  1682. return AccountService::get($id, true);
  1683. })
  1684. ->filter(function($account) {
  1685. return $account && isset($account['id']);
  1686. })
  1687. ->values();
  1688. return $this->json($mutes);
  1689. }
  1690. /**
  1691. * POST /api/v1/accounts/{id}/mute
  1692. *
  1693. * @param integer $id
  1694. *
  1695. * @return RelationshipTransformer
  1696. */
  1697. public function accountMuteById(Request $request, $id)
  1698. {
  1699. abort_if(!$request->user(), 403);
  1700. $user = $request->user();
  1701. $pid = $user->profile_id;
  1702. if(intval($pid) === intval($id)) {
  1703. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1704. }
  1705. $account = Profile::findOrFail($id);
  1706. $count = UserFilterService::muteCount($pid);
  1707. $maxLimit = intval(config('instance.user_filters.max_user_mutes'));
  1708. if($count == 0) {
  1709. $filterCount = UserFilter::whereUserId($pid)
  1710. ->whereFilterType('mute')
  1711. ->get()
  1712. ->map(function($rec) {
  1713. return AccountService::get($rec->filterable_id, true);
  1714. })
  1715. ->filter(function($account) {
  1716. return $account && isset($account['id']);
  1717. })
  1718. ->values()
  1719. ->count();
  1720. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1721. } else {
  1722. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1723. }
  1724. $filter = UserFilter::firstOrCreate([
  1725. 'user_id' => $pid,
  1726. 'filterable_id' => $account->id,
  1727. 'filterable_type' => 'App\Profile',
  1728. 'filter_type' => 'mute',
  1729. ]);
  1730. RelationshipService::refresh($pid, $id);
  1731. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1732. $res = $this->fractal->createData($resource)->toArray();
  1733. return $this->json($res);
  1734. }
  1735. /**
  1736. * POST /api/v1/accounts/{id}/unmute
  1737. *
  1738. * @param integer $id
  1739. *
  1740. * @return RelationshipTransformer
  1741. */
  1742. public function accountUnmuteById(Request $request, $id)
  1743. {
  1744. abort_if(!$request->user(), 403);
  1745. $user = $request->user();
  1746. $pid = $user->profile_id;
  1747. if(intval($pid) === intval($id)) {
  1748. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1749. }
  1750. $profile = Profile::findOrFail($id);
  1751. $filter = UserFilter::whereUserId($pid)
  1752. ->whereFilterableId($profile->id)
  1753. ->whereFilterableType('App\Profile')
  1754. ->whereFilterType('mute')
  1755. ->first();
  1756. if($filter) {
  1757. $filter->delete();
  1758. UserFilterService::unmute($pid, $profile->id);
  1759. RelationshipService::refresh($pid, $id);
  1760. }
  1761. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  1762. $res = $this->fractal->createData($resource)->toArray();
  1763. return $this->json($res);
  1764. }
  1765. /**
  1766. * GET /api/v1/notifications
  1767. *
  1768. *
  1769. * @return NotificationTransformer
  1770. */
  1771. public function accountNotifications(Request $request)
  1772. {
  1773. abort_if(!$request->user(), 403);
  1774. $this->validate($request, [
  1775. 'limit' => 'nullable|integer|min:1|max:100',
  1776. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1777. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1778. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1779. ]);
  1780. $pid = $request->user()->profile_id;
  1781. $limit = $request->input('limit', 20);
  1782. $since = $request->input('since_id');
  1783. $min = $request->input('min_id');
  1784. $max = $request->input('max_id');
  1785. if(!$since && !$min && !$max) {
  1786. $min = 1;
  1787. }
  1788. $maxId = null;
  1789. $minId = null;
  1790. if($max) {
  1791. $res = NotificationService::getMaxMastodon($pid, $max, $limit);
  1792. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1793. if(!empty($ids)) {
  1794. $maxId = max($ids);
  1795. $minId = min($ids);
  1796. }
  1797. } else {
  1798. $res = NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  1799. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1800. if(!empty($ids)) {
  1801. $maxId = max($ids);
  1802. $minId = min($ids);
  1803. }
  1804. }
  1805. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1806. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1807. NotificationService::warmCache($pid, 400, true);
  1808. }
  1809. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1810. if($minId == $maxId) {
  1811. $minId = null;
  1812. }
  1813. if($maxId) {
  1814. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1815. }
  1816. if($minId) {
  1817. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1818. }
  1819. if($maxId && $minId) {
  1820. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1821. }
  1822. $headers = isset($link) ? ['Link' => $link] : [];
  1823. return $this->json($res, 200, $headers);
  1824. }
  1825. /**
  1826. * GET /api/v1/timelines/home
  1827. *
  1828. *
  1829. * @return StatusTransformer
  1830. */
  1831. public function timelineHome(Request $request)
  1832. {
  1833. $this->validate($request,[
  1834. 'page' => 'sometimes|integer|max:40',
  1835. 'min_id' => 'sometimes|integer|min:0|max:' . PHP_INT_MAX,
  1836. 'max_id' => 'sometimes|integer|min:0|max:' . PHP_INT_MAX,
  1837. 'limit' => 'sometimes|integer|min:1|max:40',
  1838. 'include_reblogs' => 'sometimes',
  1839. ]);
  1840. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1841. $page = $request->input('page');
  1842. $min = $request->input('min_id');
  1843. $max = $request->input('max_id');
  1844. $limit = $request->input('limit') ?? 20;
  1845. $pid = $request->user()->profile_id;
  1846. $includeReblogs = $request->filled('include_reblogs');
  1847. $nullFields = $includeReblogs ?
  1848. ['in_reply_to_id'] :
  1849. ['in_reply_to_id', 'reblog_of_id'];
  1850. $inTypes = $includeReblogs ?
  1851. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album', 'share'] :
  1852. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'];
  1853. if(config('exp.cached_home_timeline')) {
  1854. if($min || $max) {
  1855. if($request->has('min_id')) {
  1856. $res = HomeTimelineService::getRankedMinId($pid, $min ?? 0, $limit + 10);
  1857. } else {
  1858. $res = HomeTimelineService::getRankedMaxId($pid, $max ?? 0, $limit + 10);
  1859. }
  1860. } else {
  1861. $res = HomeTimelineService::get($pid, 0, $limit + 10);
  1862. }
  1863. if(!$res) {
  1864. $res = Cache::has('pf:services:apiv1:home:cached:coldbootcheck:' . $pid);
  1865. if(!$res) {
  1866. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:' . $pid, 1, 86400);
  1867. FeedWarmCachePipeline::dispatchSync($pid);
  1868. return response()->json([], 206);
  1869. } else {
  1870. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:' . $pid, 1, 86400);
  1871. return response()->json([], 206);
  1872. }
  1873. }
  1874. $res = collect($res)->take($limit)->map(function($id) use($napi) {
  1875. return $napi ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  1876. })->filter(function($res) {
  1877. return $res && isset($res['account']);
  1878. })->map(function($status) use($pid) {
  1879. if($pid) {
  1880. $status['favourited'] = (bool) LikeService::liked($pid, $status['id']);
  1881. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1882. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  1883. }
  1884. return $status;
  1885. });
  1886. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  1887. $minId = $res->map(function($s) {
  1888. return ['id' => $s['id']];
  1889. })->min('id');
  1890. $maxId = $res->map(function($s) {
  1891. return ['id' => $s['id']];
  1892. })->max('id');
  1893. if($minId == $maxId) {
  1894. $minId = null;
  1895. }
  1896. if($maxId) {
  1897. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1898. }
  1899. if($minId) {
  1900. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1901. }
  1902. if($maxId && $minId) {
  1903. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1904. }
  1905. $headers = isset($link) ? ['Link' => $link] : [];
  1906. return $this->json($res->toArray(), 200, $headers);
  1907. }
  1908. $following = Cache::remember('profile:following:'.$pid, 1209600, function() use($pid) {
  1909. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1910. return $following->push($pid)->toArray();
  1911. });
  1912. $muted = UserFilterService::mutes($pid);
  1913. if($muted && count($muted)) {
  1914. $following = array_diff($following, $muted);
  1915. }
  1916. if($min || $max) {
  1917. $dir = $min ? '>' : '<';
  1918. $id = $min ?? $max;
  1919. $res = Status::select(
  1920. 'id',
  1921. 'profile_id',
  1922. 'type',
  1923. 'visibility',
  1924. 'in_reply_to_id',
  1925. 'reblog_of_id'
  1926. )
  1927. ->where('id', $dir, $id)
  1928. ->whereNull($nullFields)
  1929. ->whereIntegerInRaw('profile_id', $following)
  1930. ->whereIn('type', $inTypes)
  1931. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1932. ->orderByDesc('id')
  1933. ->take(($limit * 2))
  1934. ->get()
  1935. ->map(function($s) use($pid, $napi) {
  1936. try {
  1937. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  1938. if(!$account) {
  1939. return false;
  1940. }
  1941. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1942. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1943. return false;
  1944. }
  1945. } catch(\Exception $e) {
  1946. return false;
  1947. }
  1948. $status['account'] = $account;
  1949. if($pid) {
  1950. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1951. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1952. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  1953. }
  1954. return $status;
  1955. })
  1956. ->filter(function($status) {
  1957. return $status && isset($status['account']);
  1958. })
  1959. ->map(function($status) use($pid) {
  1960. if(!empty($status['reblog'])) {
  1961. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  1962. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  1963. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  1964. }
  1965. return $status;
  1966. })
  1967. ->take($limit)
  1968. ->values();
  1969. } else {
  1970. $res = Status::select(
  1971. 'id',
  1972. 'profile_id',
  1973. 'type',
  1974. 'visibility',
  1975. 'in_reply_to_id',
  1976. 'reblog_of_id',
  1977. )
  1978. ->whereNull($nullFields)
  1979. ->whereIntegerInRaw('profile_id', $following)
  1980. ->whereIn('type', $inTypes)
  1981. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1982. ->orderByDesc('id')
  1983. ->take(($limit * 2))
  1984. ->get()
  1985. ->map(function($s) use($pid, $napi) {
  1986. try {
  1987. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  1988. if(!$account) {
  1989. return false;
  1990. }
  1991. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1992. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1993. return false;
  1994. }
  1995. } catch(\Exception $e) {
  1996. return false;
  1997. }
  1998. $status['account'] = $account;
  1999. if($pid) {
  2000. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2001. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2002. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2003. }
  2004. return $status;
  2005. })
  2006. ->filter(function($status) {
  2007. return $status && isset($status['account']);
  2008. })
  2009. ->map(function($status) use($pid) {
  2010. if(!empty($status['reblog'])) {
  2011. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  2012. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  2013. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2014. }
  2015. return $status;
  2016. })
  2017. ->take($limit)
  2018. ->values();
  2019. }
  2020. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  2021. $minId = $res->map(function($s) {
  2022. return ['id' => $s['id']];
  2023. })->min('id');
  2024. $maxId = $res->map(function($s) {
  2025. return ['id' => $s['id']];
  2026. })->max('id');
  2027. if($minId == $maxId) {
  2028. $minId = null;
  2029. }
  2030. if($maxId) {
  2031. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2032. }
  2033. if($minId) {
  2034. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2035. }
  2036. if($maxId && $minId) {
  2037. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2038. }
  2039. $headers = isset($link) ? ['Link' => $link] : [];
  2040. return $this->json($res->toArray(), 200, $headers);
  2041. }
  2042. /**
  2043. * GET /api/v1/timelines/public
  2044. *
  2045. *
  2046. * @return StatusTransformer
  2047. */
  2048. public function timelinePublic(Request $request)
  2049. {
  2050. $this->validate($request,[
  2051. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2052. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2053. 'limit' => 'nullable|integer|max:100',
  2054. 'remote' => 'sometimes',
  2055. 'local' => 'sometimes'
  2056. ]);
  2057. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2058. $min = $request->input('min_id');
  2059. $max = $request->input('max_id');
  2060. $limit = $request->input('limit') ?? 20;
  2061. $user = $request->user();
  2062. $remote = $request->has('remote');
  2063. $local = $request->has('local');
  2064. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  2065. if($remote && config('instance.timeline.network.cached')) {
  2066. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function() {
  2067. if(NetworkTimelineService::count() == 0) {
  2068. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  2069. }
  2070. });
  2071. if ($max) {
  2072. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  2073. } else if ($min) {
  2074. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  2075. } else {
  2076. $feed = NetworkTimelineService::get(0, $limit + 5);
  2077. }
  2078. }
  2079. if($local || !$remote && !$local) {
  2080. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  2081. if(PublicTimelineService::count() == 0) {
  2082. PublicTimelineService::warmCache(true, 400);
  2083. }
  2084. });
  2085. if ($max) {
  2086. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  2087. } else if ($min) {
  2088. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  2089. } else {
  2090. $feed = PublicTimelineService::get(0, $limit + 5);
  2091. }
  2092. }
  2093. $res = collect($feed)
  2094. ->filter(function($k) use($min, $max) {
  2095. if(!$min && !$max) {
  2096. return true;
  2097. }
  2098. if($min) {
  2099. return $min != $k;
  2100. }
  2101. if($max) {
  2102. return $max != $k;
  2103. }
  2104. })
  2105. ->map(function($k) use($user, $napi) {
  2106. try {
  2107. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  2108. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  2109. return false;
  2110. }
  2111. } catch(\Exception $e) {
  2112. return false;
  2113. }
  2114. $account = $napi ? AccountService::get($status['account']['id'], true) : AccountService::getMastodon($status['account']['id'], true);
  2115. if(!$account) {
  2116. return false;
  2117. }
  2118. $status['account'] = $account;
  2119. if($user) {
  2120. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  2121. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  2122. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $status['id']);
  2123. }
  2124. return $status;
  2125. })
  2126. ->filter(function($s) use($filtered) {
  2127. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  2128. })
  2129. ->take($limit)
  2130. ->values();
  2131. $baseUrl = config('app.url') . '/api/v1/timelines/public?limit=' . $limit . '&';
  2132. if($remote) {
  2133. $baseUrl .= 'remote=1&';
  2134. }
  2135. $minId = $res->map(function($s) {
  2136. return ['id' => $s['id']];
  2137. })->min('id');
  2138. $maxId = $res->map(function($s) {
  2139. return ['id' => $s['id']];
  2140. })->max('id');
  2141. if($minId == $maxId) {
  2142. $minId = null;
  2143. }
  2144. if($maxId) {
  2145. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2146. }
  2147. if($minId) {
  2148. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2149. }
  2150. if($maxId && $minId) {
  2151. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2152. }
  2153. $headers = isset($link) ? ['Link' => $link] : [];
  2154. return $this->json($res->toArray(), 200, $headers);
  2155. }
  2156. /**
  2157. * GET /api/v1/conversations
  2158. *
  2159. * Not implemented
  2160. *
  2161. * @return array
  2162. */
  2163. public function conversations(Request $request)
  2164. {
  2165. abort_if(!$request->user(), 403);
  2166. $this->validate($request, [
  2167. 'limit' => 'min:1|max:40',
  2168. 'scope' => 'nullable|in:inbox,sent,requests'
  2169. ]);
  2170. $limit = $request->input('limit', 20);
  2171. $scope = $request->input('scope', 'inbox');
  2172. $pid = $request->user()->profile_id;
  2173. if(config('database.default') == 'pgsql') {
  2174. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  2175. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  2176. })
  2177. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2178. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  2179. })
  2180. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2181. return $q->whereToId($pid)->whereIsHidden(true);
  2182. });
  2183. } else {
  2184. $dms = Conversation::when($scope === 'inbox', function($q, $scope) use($pid) {
  2185. return $q->whereIsHidden(false)
  2186. ->where('to_id', $pid)
  2187. ->orWhere('from_id', $pid)
  2188. ->orderByDesc('status_id')
  2189. ->groupBy(['to_id', 'from_id']);
  2190. })
  2191. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2192. return $q->whereFromId($pid)->groupBy('to_id');
  2193. })
  2194. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2195. return $q->whereToId($pid)->whereIsHidden(true);
  2196. });
  2197. }
  2198. $dms = $dms->orderByDesc('status_id')
  2199. ->simplePaginate($limit)
  2200. ->map(function($dm) use($pid) {
  2201. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2202. $res = [
  2203. 'id' => $dm->id,
  2204. 'unread' => false,
  2205. 'accounts' => [
  2206. AccountService::getMastodon($from, true)
  2207. ],
  2208. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  2209. ];
  2210. return $res;
  2211. })
  2212. ->filter(function($dm) {
  2213. if(!$dm || empty($dm['last_status']) || !isset($dm['accounts']) || !count($dm['accounts']) || !isset($dm['accounts'][0]) || !isset($dm['accounts'][0]['id'])) {
  2214. return false;
  2215. }
  2216. return true;
  2217. })
  2218. ->unique(function($item, $key) {
  2219. return $item['accounts'][0]['id'];
  2220. })
  2221. ->values();
  2222. return $this->json($dms);
  2223. }
  2224. /**
  2225. * GET /api/v1/statuses/{id}
  2226. *
  2227. * @param integer $id
  2228. *
  2229. * @return StatusTransformer
  2230. */
  2231. public function statusById(Request $request, $id)
  2232. {
  2233. abort_if(!$request->user(), 403);
  2234. $pid = $request->user()->profile_id;
  2235. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2236. if(!$res || !isset($res['visibility'])) {
  2237. abort(404);
  2238. }
  2239. $scope = $res['visibility'];
  2240. if(!in_array($scope, ['public', 'unlisted'])) {
  2241. if($scope === 'private') {
  2242. if(intval($res['account']['id']) !== intval($pid)) {
  2243. abort_unless(FollowerService::follows($pid, $res['account']['id']), 403);
  2244. }
  2245. } else {
  2246. abort(400, 'Invalid request');
  2247. }
  2248. }
  2249. if(!empty($res['reblog']) && isset($res['reblog']['id'])) {
  2250. $res['reblog']['favourited'] = (bool) LikeService::liked($pid, $res['reblog']['id']);
  2251. $res['reblog']['reblogged'] = (bool) ReblogService::get($pid, $res['reblog']['id']);
  2252. $res['reblog']['bookmarked'] = BookmarkService::get($pid, $res['reblog']['id']);
  2253. }
  2254. $res['favourited'] = LikeService::liked($pid, $res['id']);
  2255. $res['reblogged'] = ReblogService::get($pid, $res['id']);
  2256. $res['bookmarked'] = BookmarkService::get($pid, $res['id']);
  2257. return $this->json($res);
  2258. }
  2259. /**
  2260. * GET /api/v1/statuses/{id}/context
  2261. *
  2262. * @param integer $id
  2263. *
  2264. * @return StatusTransformer
  2265. */
  2266. public function statusContext(Request $request, $id)
  2267. {
  2268. abort_if(!$request->user(), 403);
  2269. $user = $request->user();
  2270. $pid = $user->profile_id;
  2271. $status = StatusService::getMastodon($id, false);
  2272. if(!$status || !isset($status['account'])) {
  2273. return response('', 404);
  2274. }
  2275. if(intval($status['account']['id']) !== intval($user->profile_id)) {
  2276. if($status['visibility'] == 'private') {
  2277. if(!FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2278. return response('', 404);
  2279. }
  2280. } else {
  2281. if(!in_array($status['visibility'], ['public','unlisted'])) {
  2282. return response('', 404);
  2283. }
  2284. }
  2285. }
  2286. $ancestors = [];
  2287. $descendants = [];
  2288. if($status['in_reply_to_id']) {
  2289. $ancestors[] = StatusService::getMastodon($status['in_reply_to_id'], false);
  2290. }
  2291. if($status['replies_count']) {
  2292. $filters = UserFilterService::filters($pid);
  2293. $descendants = DB::table('statuses')
  2294. ->where('in_reply_to_id', $id)
  2295. ->limit(20)
  2296. ->pluck('id')
  2297. ->map(function($sid) {
  2298. return StatusService::getMastodon($sid, false);
  2299. })
  2300. ->filter(function($post) use($filters) {
  2301. return $post && isset($post['account'], $post['account']['id']) && !in_array($post['account']['id'], $filters);
  2302. })
  2303. ->map(function($status) use($pid) {
  2304. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2305. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2306. return $status;
  2307. })
  2308. ->values();
  2309. }
  2310. $res = [
  2311. 'ancestors' => $ancestors,
  2312. 'descendants' => $descendants
  2313. ];
  2314. return $this->json($res);
  2315. }
  2316. /**
  2317. * GET /api/v1/statuses/{id}/card
  2318. *
  2319. * @param integer $id
  2320. *
  2321. * @return StatusTransformer
  2322. */
  2323. public function statusCard(Request $request, $id)
  2324. {
  2325. abort_if(!$request->user(), 403);
  2326. $res = [];
  2327. return response()->json($res);
  2328. }
  2329. /**
  2330. * GET /api/v1/statuses/{id}/reblogged_by
  2331. *
  2332. * @param integer $id
  2333. *
  2334. * @return AccountTransformer
  2335. */
  2336. public function statusRebloggedBy(Request $request, $id)
  2337. {
  2338. abort_if(!$request->user(), 403);
  2339. $this->validate($request, [
  2340. 'limit' => 'sometimes|integer|min:1|max:80'
  2341. ]);
  2342. $limit = $request->input('limit', 10);
  2343. $user = $request->user();
  2344. $pid = $user->profile_id;
  2345. $status = Status::findOrFail($id);
  2346. $account = AccountService::get($status->profile_id, true);
  2347. abort_if(!$account, 404);
  2348. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2349. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2350. abort_if(
  2351. !$status->type ||
  2352. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2353. 404,
  2354. );
  2355. if(!$author) {
  2356. if($status->scope == 'private') {
  2357. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2358. } else {
  2359. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2360. }
  2361. if($request->has('cursor')) {
  2362. return $this->json([]);
  2363. }
  2364. }
  2365. $res = Status::where('reblog_of_id', $status->id)
  2366. ->orderByDesc('id')
  2367. ->cursorPaginate($limit)
  2368. ->withQueryString();
  2369. if(!$res) {
  2370. return $this->json([]);
  2371. }
  2372. $headers = [];
  2373. if($author && $res->hasPages()) {
  2374. $links = '';
  2375. if($res->onFirstPage()) {
  2376. if($res->nextPageUrl()) {
  2377. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2378. }
  2379. } else {
  2380. if($res->previousPageUrl()) {
  2381. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2382. }
  2383. if($res->nextPageUrl()) {
  2384. if(!empty($links)) {
  2385. $links .= ', ';
  2386. }
  2387. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2388. }
  2389. }
  2390. $headers = ['Link' => $links];
  2391. }
  2392. $res = $res->map(function($status) use($pid, $napi) {
  2393. $account = $napi ? AccountService::get($status->profile_id, true) : AccountService::getMastodon($status->profile_id, true);
  2394. if(!$account) {
  2395. return false;
  2396. }
  2397. if($napi) {
  2398. $account['follows'] = $status->profile_id == $pid ? null : FollowerService::follows($pid, $status->profile_id);
  2399. }
  2400. return $account;
  2401. })
  2402. ->filter(function($account) {
  2403. return $account && isset($account['id']);
  2404. })
  2405. ->values();
  2406. return $this->json($res, 200, $headers);
  2407. }
  2408. /**
  2409. * GET /api/v1/statuses/{id}/favourited_by
  2410. *
  2411. * @param integer $id
  2412. *
  2413. * @return AccountTransformer
  2414. */
  2415. public function statusFavouritedBy(Request $request, $id)
  2416. {
  2417. abort_if(!$request->user(), 403);
  2418. $this->validate($request, [
  2419. 'limit' => 'nullable|integer|min:1|max:80'
  2420. ]);
  2421. $limit = $request->input('limit', 10);
  2422. $user = $request->user();
  2423. $pid = $user->profile_id;
  2424. $status = Status::findOrFail($id);
  2425. $account = AccountService::get($status->profile_id, true);
  2426. abort_if(!$account, 404);
  2427. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2428. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2429. abort_if(
  2430. !$status->type ||
  2431. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2432. 404,
  2433. );
  2434. if(!$author) {
  2435. if($status->scope == 'private') {
  2436. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2437. } else {
  2438. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2439. }
  2440. if($request->has('cursor')) {
  2441. return $this->json([]);
  2442. }
  2443. }
  2444. $res = Like::where('status_id', $status->id)
  2445. ->orderByDesc('id')
  2446. ->cursorPaginate($limit)
  2447. ->withQueryString();
  2448. if(!$res) {
  2449. return $this->json([]);
  2450. }
  2451. $headers = [];
  2452. if($author && $res->hasPages()) {
  2453. $links = '';
  2454. if($res->onFirstPage()) {
  2455. if($res->nextPageUrl()) {
  2456. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2457. }
  2458. } else {
  2459. if($res->previousPageUrl()) {
  2460. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2461. }
  2462. if($res->nextPageUrl()) {
  2463. if(!empty($links)) {
  2464. $links .= ', ';
  2465. }
  2466. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2467. }
  2468. }
  2469. $headers = ['Link' => $links];
  2470. }
  2471. $res = $res->map(function($like) use($pid, $napi) {
  2472. $account = $napi ? AccountService::get($like->profile_id, true) : AccountService::getMastodon($like->profile_id, true);
  2473. if(!$account) {
  2474. return false;
  2475. }
  2476. if($napi) {
  2477. $account['follows'] = $like->profile_id == $pid ? null : FollowerService::follows($pid, $like->profile_id);
  2478. }
  2479. return $account;
  2480. })
  2481. ->filter(function($account) {
  2482. return $account && isset($account['id']);
  2483. })
  2484. ->values();
  2485. return $this->json($res, 200, $headers);
  2486. }
  2487. /**
  2488. * POST /api/v1/statuses
  2489. *
  2490. *
  2491. * @return StatusTransformer
  2492. */
  2493. public function statusCreate(Request $request)
  2494. {
  2495. abort_if(!$request->user(), 403);
  2496. $this->validate($request, [
  2497. 'status' => 'nullable|string',
  2498. 'in_reply_to_id' => 'nullable',
  2499. 'media_ids' => 'sometimes|array|max:' . config_cache('pixelfed.max_album_length'),
  2500. 'sensitive' => 'nullable',
  2501. 'visibility' => 'string|in:private,unlisted,public',
  2502. 'spoiler_text' => 'sometimes|max:140',
  2503. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2504. 'collection_ids' => 'sometimes|array|max:3',
  2505. 'comments_disabled' => 'sometimes|boolean',
  2506. ]);
  2507. if($request->hasHeader('idempotency-key')) {
  2508. $key = 'pf:api:v1:status:idempotency-key:' . $request->user()->id . ':' . hash('sha1', $request->header('idempotency-key'));
  2509. $exists = Cache::has($key);
  2510. abort_if($exists, 400, 'Duplicate idempotency key.');
  2511. Cache::put($key, 1, 3600);
  2512. }
  2513. if(config('costar.enabled') == true) {
  2514. $blockedKeywords = config('costar.keyword.block');
  2515. if($blockedKeywords !== null && $request->status) {
  2516. $keywords = config('costar.keyword.block');
  2517. foreach($keywords as $kw) {
  2518. if(Str::contains($request->status, $kw) == true) {
  2519. abort(400, 'Invalid object. Contains banned keyword.');
  2520. }
  2521. }
  2522. }
  2523. }
  2524. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  2525. abort(403, 'Empty statuses are not allowed');
  2526. }
  2527. $ids = $request->input('media_ids');
  2528. $in_reply_to_id = $request->input('in_reply_to_id');
  2529. $user = $request->user();
  2530. $profile = $user->profile;
  2531. $limitKey = 'compose:rate-limit:store:' . $user->id;
  2532. $limitTtl = now()->addMinutes(15);
  2533. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  2534. $dailyLimit = Status::whereProfileId($user->profile_id)
  2535. ->whereNull('in_reply_to_id')
  2536. ->whereNull('reblog_of_id')
  2537. ->where('created_at', '>', now()->subDays(1))
  2538. ->count();
  2539. return $dailyLimit >= 1000;
  2540. });
  2541. abort_if($limitReached == true, 429);
  2542. $visibility = $profile->is_private ? 'private' : (
  2543. $profile->unlisted == true &&
  2544. $request->input('visibility', 'public') == 'public' ?
  2545. 'unlisted' :
  2546. $request->input('visibility', 'public'));
  2547. if($user->last_active_at == null) {
  2548. return [];
  2549. }
  2550. $content = strip_tags($request->input('status'));
  2551. $rendered = Autolink::create()->autolink($content);
  2552. $cw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  2553. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2554. if($in_reply_to_id) {
  2555. $parent = Status::findOrFail($in_reply_to_id);
  2556. if($parent->comments_disabled) {
  2557. return $this->json("Comments have been disabled on this post", 422);
  2558. }
  2559. $blocks = UserFilterService::blocks($parent->profile_id);
  2560. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  2561. $status = new Status;
  2562. $status->caption = $content;
  2563. $status->rendered = $rendered;
  2564. $status->scope = $visibility;
  2565. $status->visibility = $visibility;
  2566. $status->profile_id = $user->profile_id;
  2567. $status->is_nsfw = $cw;
  2568. $status->cw_summary = $spoilerText;
  2569. $status->in_reply_to_id = $parent->id;
  2570. $status->in_reply_to_profile_id = $parent->profile_id;
  2571. $status->save();
  2572. StatusService::del($parent->id);
  2573. Cache::forget('status:replies:all:' . $parent->id);
  2574. }
  2575. if($ids) {
  2576. if(Media::whereUserId($user->id)
  2577. ->whereNull('status_id')
  2578. ->find($ids)
  2579. ->count() == 0
  2580. ) {
  2581. abort(400, 'Invalid media_ids');
  2582. }
  2583. if(!$in_reply_to_id) {
  2584. $status = new Status;
  2585. $status->caption = $content;
  2586. $status->rendered = $rendered;
  2587. $status->profile_id = $user->profile_id;
  2588. $status->is_nsfw = $cw;
  2589. $status->cw_summary = $spoilerText;
  2590. $status->scope = 'draft';
  2591. $status->visibility = 'draft';
  2592. if($request->has('place_id')) {
  2593. $status->place_id = $request->input('place_id');
  2594. }
  2595. $status->save();
  2596. }
  2597. $mimes = [];
  2598. foreach($ids as $k => $v) {
  2599. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  2600. continue;
  2601. }
  2602. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  2603. if($m->profile_id !== $user->profile_id || $m->status_id) {
  2604. abort(403, 'Invalid media id');
  2605. }
  2606. $m->order = $k + 1;
  2607. $m->status_id = $status->id;
  2608. $m->save();
  2609. array_push($mimes, $m->mime);
  2610. }
  2611. if(empty($mimes)) {
  2612. $status->delete();
  2613. abort(400, 'Invalid media ids');
  2614. }
  2615. if($request->has('comments_disabled') && $request->input('comments_disabled')) {
  2616. $status->comments_disabled = true;
  2617. }
  2618. $status->scope = $visibility;
  2619. $status->visibility = $visibility;
  2620. $status->type = StatusController::mimeTypeCheck($mimes);
  2621. $status->save();
  2622. }
  2623. if(!$status) {
  2624. abort(500, 'An error occured.');
  2625. }
  2626. NewStatusPipeline::dispatch($status);
  2627. if($status->in_reply_to_id) {
  2628. CommentPipeline::dispatch($parent, $status);
  2629. }
  2630. Cache::forget('user:account:id:'.$user->id);
  2631. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  2632. Cache::forget('profile:status_count:'.$user->profile_id);
  2633. Cache::forget($user->storageUsedKey());
  2634. Cache::forget('profile:embed:' . $status->profile_id);
  2635. Cache::forget($limitKey);
  2636. if($request->has('collection_ids') && $ids) {
  2637. $collections = Collection::whereProfileId($user->profile_id)
  2638. ->find($request->input('collection_ids'))
  2639. ->each(function($collection) use($status) {
  2640. $count = $collection->items()->count();
  2641. $item = CollectionItem::firstOrCreate([
  2642. 'collection_id' => $collection->id,
  2643. 'object_type' => 'App\Status',
  2644. 'object_id' => $status->id
  2645. ],[
  2646. 'order' => $count,
  2647. ]);
  2648. CollectionService::addItem(
  2649. $collection->id,
  2650. $status->id,
  2651. $count
  2652. );
  2653. $collection->updated_at = now();
  2654. $collection->save();
  2655. CollectionService::setCollection($collection->id, $collection);
  2656. });
  2657. }
  2658. $res = StatusService::getMastodon($status->id, false);
  2659. $res['favourited'] = false;
  2660. $res['language'] = 'en';
  2661. $res['bookmarked'] = false;
  2662. $res['card'] = null;
  2663. return $this->json($res);
  2664. }
  2665. /**
  2666. * DELETE /api/v1/statuses
  2667. *
  2668. * @param integer $id
  2669. *
  2670. * @return null
  2671. */
  2672. public function statusDelete(Request $request, $id)
  2673. {
  2674. abort_if(!$request->user(), 403);
  2675. $status = Status::whereProfileId($request->user()->profile->id)
  2676. ->findOrFail($id);
  2677. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2678. Cache::forget('profile:status_count:'.$status->profile_id);
  2679. StatusDelete::dispatch($status);
  2680. $res = $this->fractal->createData($resource)->toArray();
  2681. $res['text'] = $res['content'];
  2682. unset($res['content']);
  2683. return $this->json($res);
  2684. }
  2685. /**
  2686. * POST /api/v1/statuses/{id}/reblog
  2687. *
  2688. * @param integer $id
  2689. *
  2690. * @return StatusTransformer
  2691. */
  2692. public function statusShare(Request $request, $id)
  2693. {
  2694. abort_if(!$request->user(), 403);
  2695. $user = $request->user();
  2696. $status = Status::whereScope('public')->findOrFail($id);
  2697. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2698. if($status->scope == 'private') {
  2699. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2700. } else {
  2701. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2702. }
  2703. $blocks = UserFilterService::blocks($status->profile_id);
  2704. if($blocks && in_array($user->profile_id, $blocks)) {
  2705. abort(422);
  2706. }
  2707. }
  2708. $share = Status::firstOrCreate([
  2709. 'profile_id' => $user->profile_id,
  2710. 'reblog_of_id' => $status->id,
  2711. 'type' => 'share',
  2712. 'in_reply_to_profile_id' => $status->profile_id,
  2713. 'scope' => 'public',
  2714. 'visibility' => 'public'
  2715. ]);
  2716. SharePipeline::dispatch($share)->onQueue('low');
  2717. StatusService::del($status->id);
  2718. ReblogService::add($user->profile_id, $status->id);
  2719. $res = StatusService::getMastodon($status->id);
  2720. $res['reblogged'] = true;
  2721. return $this->json($res);
  2722. }
  2723. /**
  2724. * POST /api/v1/statuses/{id}/unreblog
  2725. *
  2726. * @param integer $id
  2727. *
  2728. * @return StatusTransformer
  2729. */
  2730. public function statusUnshare(Request $request, $id)
  2731. {
  2732. abort_if(!$request->user(), 403);
  2733. $user = $request->user();
  2734. $status = Status::whereScope('public')->findOrFail($id);
  2735. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2736. if($status->scope == 'private') {
  2737. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2738. } else {
  2739. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2740. }
  2741. }
  2742. $reblog = Status::whereProfileId($user->profile_id)
  2743. ->whereReblogOfId($status->id)
  2744. ->first();
  2745. if(!$reblog) {
  2746. $res = StatusService::getMastodon($status->id);
  2747. $res['reblogged'] = false;
  2748. return $this->json($res);
  2749. }
  2750. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  2751. ReblogService::del($user->profile_id, $status->id);
  2752. $res = StatusService::getMastodon($status->id);
  2753. $res['reblogged'] = false;
  2754. return $this->json($res);
  2755. }
  2756. /**
  2757. * GET /api/v1/timelines/tag/{hashtag}
  2758. *
  2759. * @param string $hashtag
  2760. *
  2761. * @return StatusTransformer
  2762. */
  2763. public function timelineHashtag(Request $request, $hashtag)
  2764. {
  2765. abort_if(!$request->user(), 403);
  2766. $this->validate($request,[
  2767. 'page' => 'nullable|integer|max:40',
  2768. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2769. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2770. 'limit' => 'nullable|integer|max:100',
  2771. 'only_media' => 'sometimes|boolean',
  2772. '_pe' => 'sometimes'
  2773. ]);
  2774. if(config('database.default') === 'pgsql') {
  2775. $tag = Hashtag::where('name', 'ilike', $hashtag)
  2776. ->orWhere('slug', 'ilike', $hashtag)
  2777. ->first();
  2778. } else {
  2779. $tag = Hashtag::whereName($hashtag)
  2780. ->orWhere('slug', $hashtag)
  2781. ->first();
  2782. }
  2783. if(!$tag) {
  2784. return response()->json([]);
  2785. }
  2786. if($tag->is_banned == true) {
  2787. return $this->json([]);
  2788. }
  2789. $min = $request->input('min_id');
  2790. $max = $request->input('max_id');
  2791. $limit = $request->input('limit', 20);
  2792. $onlyMedia = $request->input('only_media', true);
  2793. $pe = $request->has(self::PF_API_ENTITY_KEY);
  2794. if($min || $max) {
  2795. $minMax = SnowflakeService::byDate(now()->subMonths(6));
  2796. if($min && intval($min) < $minMax) {
  2797. return [];
  2798. }
  2799. if($max && intval($max) < $minMax) {
  2800. return [];
  2801. }
  2802. }
  2803. $filters = UserFilterService::filters($request->user()->profile_id);
  2804. if(!$min && !$max) {
  2805. $id = 1;
  2806. $dir = '>';
  2807. } else {
  2808. $dir = $min ? '>' : '<';
  2809. $id = $min ?? $max;
  2810. }
  2811. $res = StatusHashtag::whereHashtagId($tag->id)
  2812. ->whereStatusVisibility('public')
  2813. ->where('status_id', $dir, $id)
  2814. ->orderBy('status_id', 'desc')
  2815. ->limit($limit)
  2816. ->pluck('status_id')
  2817. ->map(function ($i) use($pe) {
  2818. return $pe ? StatusService::get($i) : StatusService::getMastodon($i);
  2819. })
  2820. ->filter(function($i) use($onlyMedia) {
  2821. if(!$i) {
  2822. return false;
  2823. }
  2824. if($onlyMedia && !isset($i['media_attachments']) || !count($i['media_attachments'])) {
  2825. return false;
  2826. }
  2827. return $i && isset($i['account']);
  2828. })
  2829. ->filter(function($i) use($filters) {
  2830. return !in_array($i['account']['id'], $filters);
  2831. })
  2832. ->values()
  2833. ->toArray();
  2834. return $this->json($res);
  2835. }
  2836. /**
  2837. * GET /api/v1/bookmarks
  2838. *
  2839. *
  2840. *
  2841. * @return StatusTransformer
  2842. */
  2843. public function bookmarks(Request $request)
  2844. {
  2845. abort_if(!$request->user(), 403);
  2846. $this->validate($request, [
  2847. 'limit' => 'nullable|integer|min:1|max:40',
  2848. 'max_id' => 'nullable|integer|min:0',
  2849. 'since_id' => 'nullable|integer|min:0',
  2850. 'min_id' => 'nullable|integer|min:0'
  2851. ]);
  2852. $pe = $request->has('_pe');
  2853. $pid = $request->user()->profile_id;
  2854. $limit = $request->input('limit') ?? 20;
  2855. $max_id = $request->input('max_id');
  2856. $since_id = $request->input('since_id');
  2857. $min_id = $request->input('min_id');
  2858. $dir = $min_id ? '>' : '<';
  2859. $id = $min_id ?? $max_id;
  2860. $bookmarkQuery = Bookmark::whereProfileId($pid)
  2861. ->orderByDesc('id')
  2862. ->cursorPaginate($limit);
  2863. $bookmarks = $bookmarkQuery->map(function($bookmark) use($pid, $pe) {
  2864. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  2865. if($status) {
  2866. $status['bookmarked'] = true;
  2867. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2868. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2869. }
  2870. return $status;
  2871. })
  2872. ->filter()
  2873. ->values()
  2874. ->toArray();
  2875. $links = null;
  2876. $headers = [];
  2877. if($bookmarkQuery->nextCursor()) {
  2878. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  2879. }
  2880. if($bookmarkQuery->previousCursor()) {
  2881. if($links != null) {
  2882. $links .= ', ';
  2883. }
  2884. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  2885. }
  2886. if($links) {
  2887. $headers = ['Link' => $links];
  2888. }
  2889. return $this->json($bookmarks, 200, $headers);
  2890. }
  2891. /**
  2892. * POST /api/v1/statuses/{id}/bookmark
  2893. *
  2894. *
  2895. *
  2896. * @return StatusTransformer
  2897. */
  2898. public function bookmarkStatus(Request $request, $id)
  2899. {
  2900. abort_if(!$request->user(), 403);
  2901. $status = Status::findOrFail($id);
  2902. $pid = $request->user()->profile_id;
  2903. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2904. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2905. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2906. if($status->scope == 'private') {
  2907. abort_if(
  2908. $pid !== $status->profile_id && !FollowerService::follows($pid, $status->profile_id),
  2909. 404,
  2910. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  2911. );
  2912. }
  2913. Bookmark::firstOrCreate([
  2914. 'status_id' => $status->id,
  2915. 'profile_id' => $pid
  2916. ]);
  2917. BookmarkService::add($pid, $status->id);
  2918. $res = StatusService::getMastodon($status->id, false);
  2919. $res['bookmarked'] = true;
  2920. return $this->json($res);
  2921. }
  2922. /**
  2923. * POST /api/v1/statuses/{id}/unbookmark
  2924. *
  2925. *
  2926. *
  2927. * @return StatusTransformer
  2928. */
  2929. public function unbookmarkStatus(Request $request, $id)
  2930. {
  2931. abort_if(!$request->user(), 403);
  2932. $status = Status::findOrFail($id);
  2933. $pid = $request->user()->profile_id;
  2934. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2935. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2936. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2937. $bookmark = Bookmark::whereStatusId($status->id)
  2938. ->whereProfileId($pid)
  2939. ->first();
  2940. if($bookmark) {
  2941. BookmarkService::del($pid, $status->id);
  2942. $bookmark->delete();
  2943. }
  2944. $res = StatusService::getMastodon($status->id, false);
  2945. $res['bookmarked'] = false;
  2946. return $this->json($res);
  2947. }
  2948. /**
  2949. * GET /api/v1/discover/posts
  2950. *
  2951. *
  2952. * @return array
  2953. */
  2954. public function discoverPosts(Request $request)
  2955. {
  2956. abort_if(!$request->user(), 403);
  2957. $this->validate($request, [
  2958. 'limit' => 'integer|min:1|max:40'
  2959. ]);
  2960. $limit = $request->input('limit', 40);
  2961. $pid = $request->user()->profile_id;
  2962. $filters = UserFilterService::filters($pid);
  2963. $forYou = DiscoverService::getForYou();
  2964. $posts = $forYou->take(50)->map(function($post) {
  2965. return StatusService::getMastodon($post);
  2966. })
  2967. ->filter(function($post) use($filters) {
  2968. return $post &&
  2969. isset($post['account']) &&
  2970. isset($post['account']['id']) &&
  2971. !in_array($post['account']['id'], $filters);
  2972. })
  2973. ->take(12)
  2974. ->values();
  2975. return $this->json(compact('posts'));
  2976. }
  2977. /**
  2978. * GET /api/v2/statuses/{id}/replies
  2979. *
  2980. *
  2981. * @return array
  2982. */
  2983. public function statusReplies(Request $request, $id)
  2984. {
  2985. abort_if(!$request->user(), 403);
  2986. $this->validate($request, [
  2987. 'limit' => 'int|min:1|max:10',
  2988. 'sort' => 'in:all,newest,popular'
  2989. ]);
  2990. $limit = $request->input('limit', 3);
  2991. $pid = $request->user()->profile_id;
  2992. $status = StatusService::getMastodon($id, false);
  2993. abort_if(!$status, 404);
  2994. if($status['visibility'] == 'private') {
  2995. if($pid != $status['account']['id']) {
  2996. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2997. }
  2998. }
  2999. $sortBy = $request->input('sort', 'all');
  3000. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  3001. if(!Cache::has('status:replies:all-rc:' . $id)) {
  3002. Cache::forget('status:replies:all:' . $id);
  3003. Cache::put('status:replies:all-rc:' . $id, true, 300);
  3004. }
  3005. }
  3006. if($sortBy == 'all' && !$request->has('cursor')) {
  3007. $ids = Cache::remember('status:replies:all:' . $id, 3600, function() use($id) {
  3008. return DB::table('statuses')
  3009. ->where('in_reply_to_id', $id)
  3010. ->orderBy('id')
  3011. ->cursorPaginate(3);
  3012. });
  3013. } else {
  3014. $ids = DB::table('statuses')
  3015. ->where('in_reply_to_id', $id)
  3016. ->when($sortBy, function($q, $sortBy) {
  3017. if($sortBy === 'all') {
  3018. return $q->orderBy('id');
  3019. }
  3020. if($sortBy === 'newest') {
  3021. return $q->orderByDesc('created_at');
  3022. }
  3023. if($sortBy === 'popular') {
  3024. return $q->orderByDesc('likes_count');
  3025. }
  3026. })
  3027. ->cursorPaginate($limit);
  3028. }
  3029. $filters = UserFilterService::filters($pid);
  3030. $data = $ids->filter(function($post) use($filters) {
  3031. return !in_array($post->profile_id, $filters);
  3032. })
  3033. ->map(function($post) use($pid) {
  3034. $status = StatusService::get($post->id, false);
  3035. if(!$status || !isset($status['id'])) {
  3036. return false;
  3037. }
  3038. $status['favourited'] = LikeService::liked($pid, $post->id);
  3039. return $status;
  3040. })
  3041. ->map(function($post) {
  3042. if(isset($post['account']) && isset($post['account']['id'])) {
  3043. $account = AccountService::get($post['account']['id'], true);
  3044. $post['account'] = $account;
  3045. }
  3046. return $post;
  3047. })
  3048. ->filter(function($post) {
  3049. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  3050. })
  3051. ->values();
  3052. $res = [
  3053. 'data' => $data,
  3054. 'next' => $ids->nextPageUrl()
  3055. ];
  3056. return $this->json($res);
  3057. }
  3058. /**
  3059. * GET /api/v2/statuses/{id}/state
  3060. *
  3061. *
  3062. * @return array
  3063. */
  3064. public function statusState(Request $request, $id)
  3065. {
  3066. abort_if(!$request->user(), 403);
  3067. $status = Status::findOrFail($id);
  3068. $pid = $request->user()->profile_id;
  3069. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3070. return $this->json(StatusService::getState($status->id, $pid));
  3071. }
  3072. /**
  3073. * GET /api/v1.1/discover/accounts/popular
  3074. *
  3075. *
  3076. * @return array
  3077. */
  3078. public function discoverAccountsPopular(Request $request)
  3079. {
  3080. abort_if(!$request->user(), 403);
  3081. $pid = $request->user()->profile_id;
  3082. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 86400, function() {
  3083. return DB::table('profiles')
  3084. ->where('is_private', false)
  3085. ->whereNull('status')
  3086. ->orderByDesc('profiles.followers_count')
  3087. ->limit(20)
  3088. ->get();
  3089. });
  3090. $ids = $ids->map(function($profile) {
  3091. return AccountService::get($profile->id, true);
  3092. })
  3093. ->filter(function($profile) use($pid) {
  3094. return $profile && isset($profile['id']);
  3095. })
  3096. ->filter(function($profile) use($pid) {
  3097. return $profile['id'] != $pid;
  3098. })
  3099. ->take(6)
  3100. ->values();
  3101. return $this->json($ids);
  3102. }
  3103. /**
  3104. * GET /api/v1/preferences
  3105. *
  3106. *
  3107. * @return array
  3108. */
  3109. public function getPreferences(Request $request)
  3110. {
  3111. abort_if(!$request->user(), 403);
  3112. $pid = $request->user()->profile_id;
  3113. $account = AccountService::get($pid);
  3114. return $this->json([
  3115. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  3116. 'posting:default:sensitive' => false,
  3117. 'posting:default:language' => null,
  3118. 'reading:expand:media' => 'default',
  3119. 'reading:expand:spoilers' => false
  3120. ]);
  3121. }
  3122. /**
  3123. * GET /api/v1/trends
  3124. *
  3125. *
  3126. * @return array
  3127. */
  3128. public function getTrends(Request $request)
  3129. {
  3130. abort_if(!$request->user(), 403);
  3131. return $this->json([]);
  3132. }
  3133. /**
  3134. * GET /api/v1/announcements
  3135. *
  3136. *
  3137. * @return array
  3138. */
  3139. public function getAnnouncements(Request $request)
  3140. {
  3141. abort_if(!$request->user(), 403);
  3142. return $this->json([]);
  3143. }
  3144. /**
  3145. * GET /api/v1/markers
  3146. *
  3147. *
  3148. * @return array
  3149. */
  3150. public function getMarkers(Request $request)
  3151. {
  3152. abort_if(!$request->user(), 403);
  3153. $type = $request->input('timeline');
  3154. if(is_array($type)) {
  3155. $type = $type[0];
  3156. }
  3157. if(!$type || !in_array($type, ['home', 'notifications'])) {
  3158. return $this->json([]);
  3159. }
  3160. $pid = $request->user()->profile_id;
  3161. return $this->json(MarkerService::get($pid, $type));
  3162. }
  3163. /**
  3164. * POST /api/v1/markers
  3165. *
  3166. *
  3167. * @return array
  3168. */
  3169. public function setMarkers(Request $request)
  3170. {
  3171. abort_if(!$request->user(), 403);
  3172. $pid = $request->user()->profile_id;
  3173. $home = $request->input('home[last_read_id]');
  3174. $notifications = $request->input('notifications[last_read_id]');
  3175. if($home) {
  3176. return $this->json(MarkerService::set($pid, 'home', $home));
  3177. }
  3178. if($notifications) {
  3179. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  3180. }
  3181. return $this->json([]);
  3182. }
  3183. /**
  3184. * GET /api/v1/followed_tags
  3185. *
  3186. *
  3187. * @return array
  3188. */
  3189. public function getFollowedTags(Request $request)
  3190. {
  3191. abort_if(!$request->user(), 403);
  3192. $account = AccountService::get($request->user()->profile_id);
  3193. $this->validate($request, [
  3194. 'cursor' => 'sometimes',
  3195. 'limit' => 'sometimes|integer|min:1|max:200'
  3196. ]);
  3197. $limit = $request->input('limit', 100);
  3198. $res = HashtagFollow::whereProfileId($account['id'])
  3199. ->orderByDesc('id')
  3200. ->cursorPaginate($limit)->withQueryString();
  3201. $pagination = false;
  3202. $prevPage = $res->nextPageUrl();
  3203. $nextPage = $res->previousPageUrl();
  3204. if($nextPage && $prevPage) {
  3205. $pagination = '<' . $nextPage . '>; rel="next", <' . $prevPage . '>; rel="prev"';
  3206. } else if($nextPage && !$prevPage) {
  3207. $pagination = '<' . $nextPage . '>; rel="next"';
  3208. } else if(!$nextPage && $prevPage) {
  3209. $pagination = '<' . $prevPage . '>; rel="prev"';
  3210. }
  3211. if($pagination) {
  3212. return response()->json(FollowedTagResource::collection($res)->collection)
  3213. ->header('Link', $pagination);
  3214. }
  3215. return response()->json(FollowedTagResource::collection($res)->collection);
  3216. }
  3217. /**
  3218. * POST /api/v1/tags/:id/follow
  3219. *
  3220. *
  3221. * @return object
  3222. */
  3223. public function followHashtag(Request $request, $id)
  3224. {
  3225. abort_if(!$request->user(), 403);
  3226. $pid = $request->user()->profile_id;
  3227. $account = AccountService::get($pid);
  3228. $operator = config('database.default') == 'pgsql' ? 'ilike' : 'like';
  3229. $tag = Hashtag::where('name', $operator, $id)
  3230. ->orWhere('slug', $operator, $id)
  3231. ->first();
  3232. abort_if(!$tag, 422, 'Unknown hashtag');
  3233. abort_if(
  3234. HashtagFollow::whereProfileId($pid)->count() >= HashtagFollow::MAX_LIMIT,
  3235. 422,
  3236. 'You cannot follow more than ' . HashtagFollow::MAX_LIMIT . ' hashtags.'
  3237. );
  3238. $follows = HashtagFollow::updateOrCreate(
  3239. [
  3240. 'profile_id' => $account['id'],
  3241. 'hashtag_id' => $tag->id
  3242. ],
  3243. [
  3244. 'user_id' => $request->user()->id
  3245. ]
  3246. );
  3247. HashtagService::follow($pid, $tag->id);
  3248. return response()->json(FollowedTagResource::make($follows)->toArray($request));
  3249. }
  3250. /**
  3251. * POST /api/v1/tags/:id/unfollow
  3252. *
  3253. *
  3254. * @return object
  3255. */
  3256. public function unfollowHashtag(Request $request, $id)
  3257. {
  3258. abort_if(!$request->user(), 403);
  3259. $pid = $request->user()->profile_id;
  3260. $account = AccountService::get($pid);
  3261. $operator = config('database.default') == 'pgsql' ? 'ilike' : 'like';
  3262. $tag = Hashtag::where('name', $operator, $id)
  3263. ->orWhere('slug', $operator, $id)
  3264. ->first();
  3265. abort_if(!$tag, 422, 'Unknown hashtag');
  3266. $follows = HashtagFollow::whereProfileId($pid)
  3267. ->whereHashtagId($tag->id)
  3268. ->first();
  3269. if(!$follows) {
  3270. return [
  3271. 'name' => $tag->name,
  3272. 'url' => config('app.url') . '/i/web/hashtag/' . $tag->slug,
  3273. 'history' => [],
  3274. 'following' => false
  3275. ];
  3276. }
  3277. if($follows) {
  3278. HashtagService::unfollow($pid, $tag->id);
  3279. $follows->delete();
  3280. }
  3281. $res = FollowedTagResource::make($follows)->toArray($request);
  3282. $res['following'] = false;
  3283. return response()->json($res);
  3284. }
  3285. /**
  3286. * GET /api/v1/tags/:id
  3287. *
  3288. *
  3289. * @return object
  3290. */
  3291. public function getHashtag(Request $request, $id)
  3292. {
  3293. abort_if(!$request->user(), 403);
  3294. $pid = $request->user()->profile_id;
  3295. $account = AccountService::get($pid);
  3296. $operator = config('database.default') == 'pgsql' ? 'ilike' : 'like';
  3297. $tag = Hashtag::where('name', $operator, $id)
  3298. ->orWhere('slug', $operator, $id)
  3299. ->first();
  3300. if(!$tag) {
  3301. return [
  3302. 'name' => $id,
  3303. 'url' => config('app.url') . '/i/web/hashtag/' . $id,
  3304. 'history' => [],
  3305. 'following' => false
  3306. ];
  3307. }
  3308. $res = [
  3309. 'name' => $tag->name,
  3310. 'url' => config('app.url') . '/i/web/hashtag/' . $tag->slug,
  3311. 'history' => [],
  3312. 'following' => HashtagService::isFollowing($pid, $tag->id)
  3313. ];
  3314. if($request->has(self::PF_API_ENTITY_KEY)) {
  3315. $res['count'] = HashtagService::count($tag->id);
  3316. }
  3317. return $this->json($res);
  3318. }
  3319. }